问:
Make folded border with clip-path property CSS
Making this card project with css and react, where the card will look like this:

But what I have achieved with using the clip-path is the following:

as you can see, the bottom left corner is getting clipped out. So, it is a problem.
What I have written in CSS so far,

```<code>.card {
    position: relative;
    border-radius: 10px;
    background: rgba(255, 255, 255, 0.05);
    clip-path: polygon(100% 0, 100% 81%, 70% 100%, 0 100%, 0 0);
}

.card::before {
    border: 0.76px solid;
    content: "";
    position: absolute;
    inset: 0;
    border-radius: 10px;
    padding: 1px;
    background: linear-gradient(331.82deg, rgba(132, 247, 41, 0.7) -5.31%, rgba(21, 191, 253, 0.7) 91.15%) !important;
    mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    -webkit-mask-composite: xor;
    mask-composite: exclude;
}
</code>```

How to not exclude the border using clip-path or any other property?

Body:
Making this card project with css and react, where the card will look like this:

But what I have achieved with using the clip-path is the following:

as you can see, the bottom left corner is getting clipped out. So, it is a problem.
What I have written in CSS so far,

.card {
    position: relative;
    border-radius: 10px;
    background: rgba(255, 255, 255, 0.05);
    clip-path: polygon(100% 0, 100% 81%, 70% 100%, 0 100%, 0 0);
}

.card::before {
    border: 0.76px solid;
    content: "";
    position: absolute;
    inset: 0;
    border-radius: 10px;
    padding: 1px;
    background: linear-gradient(331.82deg, rgba(132, 247, 41, 0.7) -5.31%, rgba(21, 191, 253, 0.7) 91.15%) !important;
    mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    -webkit-mask-composite: xor;
    mask-composite: exclude;
}

How to not exclude the border using clip-path or any other property?


来源: stackexchange

问:
import nltk nltk.download('vader_lexicon')
Error loading vader_lexicon: <urlopen error [WinError
A connection attempt failed because the
Connected party did not properly respond after a
period of time, or established connection failed
because connected host has failed to respond>
False

Why it is giving false every time. How to remove it?

ContentLicense: CC BY-SA 4.0


问:
Responsive gallery component with auto adjusting images
I am working on a gallery layout which would have 4 columns. I would want all the images to fit inside the component automatically without their aspect ratio being changed. All images are to be populated from a DB and can have varying dimensions. Some specific images shall be occupying 2 columns and that is where my problem lies. Since all the images are dynamically put onto the front-end, how do I have those specific images to occupy 2 columns?
I am working on next JS with typescript.

I tried using the Masonry layout but in that I did not have control over the rows.


问:
How to use useLockBodyScroll to avoid interference with popup?
Using like this:

    const [isBodyLocked, setIsBodyLocked] = useState(false)
    useLockBodyScroll(isBodyLocked, useRef(document.body))
    useEffect(() => {
        setIsBodyLocked(true)

        return () => {
            setIsBodyLocked(false)
        }
    }, [])
```
<p>I have cusom inputs on the popup login component:</p>
<pre class="lang-js prettyprint-override"><code><InputNonClosing
                        className={'input-text'}
                        value={password1 ?? ''}
                        type="password"
                        placeholder="Jelszó"
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                            setPassword1(e.target.value)
                        }
                        autoComplete={isRegistration ? 'new-password' : 'current-password'}
                        style={{ margin: 0 }}
                    />
</code>```

This is the implementation for it:

import React, { useRef, useState } from 'react'

const InputNonClosing = (props: any) => {
    const inputRef = useRef<HTMLInputElement>(null)
    const [hasLostFocus, setHasLostFocus] = useState(false)

    const handleBlur = (event: React.FocusEvent<HTMLInputElement>) => {
        setHasLostFocus(true)
    }

    const handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
        if (hasLostFocus) {
            setHasLostFocus(false)
            return
        }
        inputRef.current && inputRef.current.focus()
    }

    return (
        <input
            ref={inputRef}
            onBlur={handleBlur}
            onFocus={handleFocus}
            {...props}
        />
    )
}

export default InputNonClosing
```
<p>When keyboard in on on a mobil device the popup is a bit too long, so I would provide to be able to scroll it, and only it not the body behind. This is why body is locked.</p>
<p>And I assigned a fixed height 660px to the popup:</p>
<pre class="lang-js prettyprint-override"><code><div
            className={'popup'}
            style={{
                zIndex: 100,
                height: '660px',
            }}
            ref={popupRef}
        >
</code>```

and set also overflow-y: scroll;

Be in the save side, using createPortal and pushing popup to document.documentElement.

I  wrap the contents of the popup in a separate container element.

What else I can do? How can I react, freez body, bit make popup scrollable? It is embedded in Wordpress site, here you can look into: https://borespiac.hu/2022/11/24/kostoljon-pezsgoket-aszukat-es-egyeb-dessszertborokat-a-bor-es-piaccal/

popup is position: fixed

I tried set the body's overflow to hidden when the popup is open, and then set it back to auto when the popup is closed. Did not work.

Body:
Using like this:

    const [isBodyLocked, setIsBodyLocked] = useState(false)
    useLockBodyScroll(isBodyLocked, useRef(document.body))
    useEffect(() => {
        setIsBodyLocked(true)

        return () => {
            setIsBodyLocked(false)
        }
    }, [])

I have cusom inputs on the popup login component:

<InputNonClosing
                        className={'input-text'}
                        value={password1 ?? ''}
                        type="password"
                        placeholder="Jelszó"
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                            setPassword1(e.target.value)
                        }
                        autoComplete={isRegistration ? 'new-password' : 'current-password'}
                        style={{ margin: 0 }}
                    />

This is the implementation for it:

import React, { useRef, useState } from 'react'

const InputNonClosing = (props: any) => {
    const inputRef = useRef<HTMLInputElement>(null)
    const [hasLostFocus, setHasLostFocus] = useState(false)

    const handleBlur = (event: React.FocusEvent<HTMLInputElement>) => {
        setHasLostFocus(true)
    }

    const handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
        if (hasLostFocus) {
            setHasLostFocus(false)
            return
        }
        inputRef.current && inputRef.current.focus()
    }

    return (
        <input
            ref={inputRef}
            onBlur={handleBlur}
            onFocus={handleFocus}
            {...props}
        />
    )
}

export default InputNonClosing

When keyboard in on on a mobil device the popup is a bit too long, so I would provide to be able to scroll it, and only it not the body behind. This is why body is locked.

And I assigned a fixed height 660px to the popup:

and set also overflow-y: scroll;

Be in the save side, using createPortal and pushing popup to document.documentElement.

I  wrap the contents of the popup in a separate container element.

What else I can do? How can I react, freez body, bit make popup scrollable? It is embedded in Wordpress site, here you can look into: https://borespiac.hu/2022/11/24/kostoljon-pezsgoket-aszukat-es-egyeb-dessszertborokat-a-bor-es-piaccal/

popup is position: fixed

I tried set the body's overflow to hidden when the popup is open, and then set it back to auto when the popup is closed. Did not work.


问:
PySide2 Print Converting
How could I convert the printed statement into normal?
<PySide2.QtWidgets.QFileSystemModel(0x1f00bde4c60) at 0x000001F012D3F488></p>
```<code>proxy = self.tree_view.model()
print(proxy)
</code>```

Title: PySide2 Print Converting

Body:
How could I convert the printed statement into normal?
<PySide2.QtWidgets.QFileSystemModel(0x1f00bde4c60) at 0x000001F012D3F488>

proxy = self.tree_view.model()
print(proxy)


问:
value from property file is null in spring
I try to get value from property file in class path in spring,but returns null:
first,I have a property file named person.properties under the package of v4.c3.property with content:

```<code>name=tom
</code>```

Then I have a config class:

```<code>package v4.c3.property;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan
public class Config {
    @Bean
    public
    static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}
</code>```

And a test class:

```<code>package v4.c3.property;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=Config.class)
@PropertySource("classpath:/v4/c3/property/person.properties")
public class Test {

    @Autowired
    Environment env;

    @org.junit.Test
    public void test() {
        System.out.println("The name is:"+env.getProperty("name"));
    }
}
</code>```

and the pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>sia</groupId>
  <artifactId>sia</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <version>2.1.8.RELEASE</version>
    </dependency>
  </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
</code>```

When I run the test method, I got a result null:

```<code>The name is:null
</code>```

Why it is null? How to get value from property file?

Body:
I try to get value from property file in class path in spring,but returns null:
first,I have a property file named person.properties under the package of v4.c3.property with content:

name=tom

Then I have a config class:

package v4.c3.property;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan
public class Config {
    @Bean
    public
    static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

And a test class:

package v4.c3.property;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=Config.class)
@PropertySource("classpath:/v4/c3/property/person.properties")
public class Test {

    @Autowired
    Environment env;

    @org.junit.Test
    public void test() {
        System.out.println("The name is:"+env.getProperty("name"));
    }
}

and the pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>sia</groupId>
  <artifactId>sia</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <version>2.1.8.RELEASE</version>
    </dependency>
  </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

When I run the test method, I got a result null:

The name is:null

Why it is null? How to get value from property file?


问:
EXPO-AV, Unhandled Rejection (NotAllowedError)
I'm trying to make a page with videos that run by themselves
but I have a problem with safari :

Unhandled Rejection (NotAllowedError): The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

```<code> <Video
    ref={video}
    style={styles.container}
    useNativeControls
    source={{ uri: mediaURL || "" }}
    onError={(e) => console.log("error", e)}
    onPlaybackStatusUpdate={(status) => setStatus(() => status)}
    onLoad={() => {
      video.current.playAsync(); // It's this line which bug on Safari
    }}
  />
</code>```

It works for Chrome but doesn't work for Safari

Do you have any idea ?

Thanks in advance !

Body:
I'm trying to make a page with videos that run by themselves
but I have a problem with safari :

Unhandled Rejection (NotAllowedError): The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

 <Video
    ref={video}
    style={styles.container}
    useNativeControls
    source={{ uri: mediaURL || "" }}
    onError={(e) => console.log("error", e)}
    onPlaybackStatusUpdate={(status) => setStatus(() => status)}
    onLoad={() => {
      video.current.playAsync(); // It's this line which bug on Safari
    }}
  />

It works for Chrome but doesn't work for Safari

Do you have any idea ?

Thanks in advance !


问:
How to use selenium with imap in nodejs
I used imap to get the raw HTML data of email body according to below code, now how can i use selenium to request a link in href attribute of 'a' tag in html that imap just returned?
`

```<code>    var imap = new Imap({
      user: '*****@outlook.com',
      password: '*****',
      host: 'outlook.office365.com',
      port: 993,
      tls: true
    });

    function openInbox(cb) {
      imap.openBox('INBOX', true, cb);
    }

    imap.once('ready', function() {
        openInbox(function(err, box) {
        if (err) throw err;
        var f = imap.seq.fetch(box.messages.total + ':*', { bodies: ['HEADER.FIELDS (FROM)','TEXT'] });
        f.on('message', function(msg, seqno) {
          console.log('Message #%d', seqno);
          var prefix = '(#' + seqno + ') ';
          msg.on('body', function(stream, info) {
            if (info.which === 'TEXT')
              console.log(prefix + 'Body [%s] found, %d total bytes', inspect(info.which), info.size);
            var buffer = '', count = 0;
            stream.on('data', function(chunk) {
              count += chunk.length;
              buffer += chunk.toString('utf8');
              if (info.which === 'TEXT')
                console.log(prefix + 'Body [%s] (%d/%d)', inspect(info.which), count, info.size);
            });
            stream.once('end', function() {
              if (info.which !== 'TEXT')
                console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
              else
                console.log(prefix + 'Body [%s] Finished', inspect(info.which));
            });
          });
          msg.once('attributes', function(attrs) {
            console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));
          });
          msg.once('end', function() {
            console.log(prefix + 'Finished');
          });
        });
        f.once('error', function(err) {
          console.log('Fetch error: ' + err);
        });
        f.once('end', function() {
          console.log('Done fetching all messages!');
          imap.end();
        });
      });
    });

    imap.once('error', function(err) {
      console.log(err);
    });

    imap.once('end', function() {
      console.log('Connection ended');
    });

    imap.connect();
</code>```

`

I tried to search about how to combine selenium and imap in nodejs but the results didn't come up as I expected. Hope anyone can help me. Thank you very much.

Title: How to use selenium with imap in nodejs

Body:
I used imap to get the raw HTML data of email body according to below code, now how can i use selenium to request a link in href attribute of 'a' tag in html that imap just returned?
`

    var imap = new Imap({
      user: '*****@outlook.com',
      password: '*****',
      host: 'outlook.office365.com',
      port: 993,
      tls: true
    });

    function openInbox(cb) {
      imap.openBox('INBOX', true, cb);
    }

    imap.once('ready', function() {
        openInbox(function(err, box) {
        if (err) throw err;
        var f = imap.seq.fetch(box.messages.total + ':*', { bodies: ['HEADER.FIELDS (FROM)','TEXT'] });
        f.on('message', function(msg, seqno) {
          console.log('Message #%d', seqno);
          var prefix = '(#' + seqno + ') ';
          msg.on('body', function(stream, info) {
            if (info.which === 'TEXT')
              console.log(prefix + 'Body [%s] found, %d total bytes', inspect(info.which), info.size);
            var buffer = '', count = 0;
            stream.on('data', function(chunk) {
              count += chunk.length;
              buffer += chunk.toString('utf8');
              if (info.which === 'TEXT')
                console.log(prefix + 'Body [%s] (%d/%d)', inspect(info.which), count, info.size);
            });
            stream.once('end', function() {
              if (info.which !== 'TEXT')
                console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
              else
                console.log(prefix + 'Body [%s] Finished', inspect(info.which));
            });
          });
          msg.once('attributes', function(attrs) {
            console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));
          });
          msg.once('end', function() {
            console.log(prefix + 'Finished');
          });
        });
        f.once('error', function(err) {
          console.log('Fetch error: ' + err);
        });
        f.once('end', function() {
          console.log('Done fetching all messages!');
          imap.end();
        });
      });
    });

    imap.once('error', function(err) {
      console.log(err);
    });

    imap.once('end', function() {
      console.log('Connection ended');
    });

    imap.connect();

`

I tried to search about how to combine selenium and imap in nodejs but the results didn't come up as I expected. Hope anyone can help me. Thank you very much.


问:
How to restrict PHP mail from sending email to spam folder
I tried the code below but it is still sending to SPAM folder. Kindly help me to figure this out such that emails goes to INBOX only.</p>
```<code>function sendEmail($content,$email,$phone){
  $headers = "Reply-To: Danuel <".$email.">\r\n";
  $headers .= "Return-Path:Danuel <".$email.">\r\n";
  $headers .= "From:Danuel <".$email.">\r\n";
  $headers .= "Organization:Danuel international\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
  $headers .= "X-Priority: 3\r\n";
  $headers .= "X-Mailer: PHP". phpversion() ."\r\n";
  $to ="xxxxxxxxx@gmail.com";
  $subject ="Number ".$phone." Banned";
  return mail($to, $subject, $content, $headers);
}

if(isset($_POST['send'])){
    $content='Hey';

    if(sendEmail($content,$_POST['email'],$_POST['phone'])==1){
       echo"<small><font color=green>Sent</font></small>";
    }else{
       echo"<small><font color=red>Failed</font></small>";
    }
}
</code>```

Body:
I tried the code below but it is still sending to SPAM folder. Kindly help me to figure this out such that emails goes to INBOX only.

function sendEmail($content,$email,$phone){
  $headers = "Reply-To: Danuel <".$email.">\r\n";
  $headers .= "Return-Path:Danuel <".$email.">\r\n";
  $headers .= "From:Danuel <".$email.">\r\n";
  $headers .= "Organization:Danuel international\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
  $headers .= "X-Priority: 3\r\n";
  $headers .= "X-Mailer: PHP". phpversion() ."\r\n";
  $to ="xxxxxxxxx@gmail.com";
  $subject ="Number ".$phone." Banned";
  return mail($to, $subject, $content, $headers);
}

if(isset($_POST['send'])){
    $content='Hey';

    if(sendEmail($content,$_POST['email'],$_POST['phone'])==1){
       echo"Sent";
    }else{
       echo"Failed";
    }
}


问:
Button press not registered in [UnityTest] but is registered in [Test]
I have several tests (~50) for my game and finally got to the point to start testing classes that require input from the player. When I wrote my tests for the Gamepad and Keyboard + Mouse inputs every test passed properly but they were using the [Test] attribute and not [UnityTest] attribute.

Now that I'm trying to test button press with [UnityTest] it refuses to register it, neither with Set(_gamepad.rightShoulder, 1); neither with Press(_gamepad.rightShoulder); For curiosity, I tried the same test with the regular [Test] attribute and there it registered the button press.

Is this a known limitation for the [InputTestFixture] attribute or am I doing something wrong?

I'm using InputSystem v1.4.4 and the code that I was trying to test was the following:

```<code>[UnityTest]
public IEnumerator Shoot() {
    var bullets = GameObject.FindGameObjectsWithTag("Bullet");
    Assert.IsEmpty(bullets);
    Set(_gamepad.rightShoulder, 1);
    yield return new WaitForFixedUpdate();
    bullets = GameObject.FindGameObjectsWithTag("Bullet");
    Assert.IsNotEmpty(bullets);
}
</code>```

The Shooting controller is setup before, so it should run its Update() after yielding a  new WaitForFixedUpdate(). This was checked while debugging but the problem is the _gamepad.rightShoulder not being pressed.

Body:
I have several tests (~50) for my game and finally got to the point to start testing classes that require input from the player. When I wrote my tests for the Gamepad and Keyboard + Mouse inputs every test passed properly but they were using the [Test] attribute and not [UnityTest] attribute.

Now that I'm trying to test button press with [UnityTest] it refuses to register it, neither with Set(_gamepad.rightShoulder, 1); neither with Press(_gamepad.rightShoulder); For curiosity, I tried the same test with the regular [Test] attribute and there it registered the button press.

Is this a known limitation for the [InputTestFixture] attribute or am I doing something wrong?

I'm using InputSystem v1.4.4 and the code that I was trying to test was the following:

[UnityTest]
public IEnumerator Shoot() {
    var bullets = GameObject.FindGameObjectsWithTag("Bullet");
    Assert.IsEmpty(bullets);
    Set(_gamepad.rightShoulder, 1);
    yield return new WaitForFixedUpdate();
    bullets = GameObject.FindGameObjectsWithTag("Bullet");
    Assert.IsNotEmpty(bullets);
}

The Shooting controller is setup before, so it should run its Update() after yielding a  new WaitForFixedUpdate(). This was checked while debugging but the problem is the _gamepad.rightShoulder not being pressed.


问:
Getting "TypeError: Cannot read properties of null (reading 'items')" error but the code works after reloading
so I was working on making this Todo list website but I am facing a problem.

NODE.JS CODE:

```<code>//jshint esversion:6

// _______________________________Database Code_________________________________
const mongoose = require("mongoose")

none = []

main().catch(err => console.log(err));

async function main() {
  mongoose.set('strictQuery', false);
  await mongoose.connect('mongodb://0.0.0.0:27017/todolistDB');
}

// For the main list
const itemSchema = {
  itemName: {
    type: String,
    required: true
  }
}

const Item = mongoose.model("Item", itemSchema)

const buyFood = new Item({
  itemName: "Buy Food"
})

const cookFood = new Item({
  itemName: "Cook Food"
})

const eatFood = new Item({
  itemName: "Eat Food"
})

const defaultItems = [buyFood, cookFood, eatFood]

// New list schema
const listSchema = {
  listName: String,
  items: [itemSchema]
}

const List = mongoose.model("list", listSchema)

// Function that creates new lists
function makeNewList(name) {
  const list = new List({
    listName: name,
    items: defaultItems
  })
  list.save()
}

// Function that creates new list items
function createNewItem(newItem) {
  const item = new Item ({
    itemName: newItem
  })
}

// Function to find a list
function findList(listName) {
  List.findOne({listName: listName}, function(err, list) {
    if (!err) {
      return list
    }
  })
}
// _______________________________Server Code___________________________________
const express = require("express");
const bodyParser = require("body-parser");
const date = require(__dirname + "/date.js");
const _ = require("lodash")
const popup = require("node-popup")

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

const workItems = [];

// Default Home List
app.get("/", function(req, res) {

  const day = date.getDate();

  Item.find(function(err, item) {

    if (item.length === 0) {
      Item.insertMany(defaultItems, function(err) {
        if (err) {
          console.log(err);
        } else {
          console.log("Items added successfully.");
        }
      })
    }

    else if (err) {
      console.log(err);
    }

    else {
      List.find({}, function(err, list) {
        if (err) {
          console.log(err);
        }
        else if (list.length === 0) {
          res.render("list", {listTitle: day, newListItems: item, array: none});
        }
        else {
          list.forEach(function(listName) {
            console.log(listName);
          })
          res.render("list", {array: list, newListItems: defaultItems, listTitle: day})
        }
      })
    }
  })
});

// Creating new list items
app.post("/", function(req, res){

  const item = req.body.newItem;
  const listName = req.body.list;

  if (listName === "day") {
    createNewItem(item)
    res.redirect("/")
  }
  // else {
  //   List.findOne({listName: listName}, function(err, foundList) {
  //     foundList.items.push(item)
  //     foundList.save()
  //     res.redirect("/" + listName)
  //   })
  // }
  });

// Deleting list items
app.post("/delete", function(req, res) {
  deletedItem = String(req.body.box)

  Item.deleteOne({_id: deletedItem}, function(err) {
    if (err) {
      console.log(err);
    } else {
      console.log("Item deleted successfully");
    }
  })

  res.redirect("/")
})

// Making new lists
app.post("/list", function(req, res) {
  newList = req.body.newListName.toLowerCase()

  List.findOne({listName: newList}, function(err, listInSearch) {
    if (!listInSearch) {
      console.log("Does not exist");
      makeNewList(newList)
      res.redirect("/" + newList)
    }
    else {
      console.log("Exist");
    }
  })
})

// Loading existing list
app.get("/:extension", function(req, res) {
  extension = req.params.extension.toLowerCase()
  console.log("Site ends with " + extension);

  if (extension !== "list") {
    List.find({}, function(err, list) {
      if (err) {
        console.log(err);
      }
      else {
        List.findOne({listName: extension}, function(err, foundList) {
          if (!err) {
            items = foundList.items
            console.log(items);
            res.render("list", {array: list, newListItems: foundList.items, listTitle: _.startCase(extension)})
          }
        })
      }
    })
  }
})

// app.post("/:extension", function(req, res) {
//   extension = req.params.extension.toLowerCase()
//   item = req.body.newItem.toString()
//
//   console.log(item);
//   console.log(extension);
//
//   List.findOne({listName: extension}, function(err, foundList) {
//     if (!err) {
//       createNewItem(item)
//       foundList.items.push(item)
//       foundList.save()
//       res.redirect("/" + extension)
//     }
//   })
// })

// About page
app.get("/about", function(req, res){
  res.render("about");
});

// Server port
app.listen(2000, function() {
  console.log("Server started on port 2000");
});
</code>```

HTML CODE:

```<code><%- include("header") -%>

<!-- Showing list title -->
  <div class="content">
    <div class="box" id="heading">
      <h1> <%= listTitle %> </h1>
    </div>

<!-- Showing all lists -->
    <div class="form">
      <div class="btn-group">
        <button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
          Lists
        </button>
        <ul class="dropdown-menu">
          <% array.forEach(function(item) {%>
              <li><a class="dropdown-item" href="/<%= item.listName %>"> <%= item.listName %> </a></li>
          <% }) %>

          <li><hr class="dropdown-divider"></li>
          <li><a class="dropdown-item" href="/">Default List</a></li>
        </ul>
      </div>

<!-- Making new lists -->
      <div class="list drop">
        <form action="/list" method="post">
          <input type="text" name="newListName" placeholder="New List Name" autocomplete="off">
          <button class="btn btn-primary btn-md" type="submit" name="newList">Create</button>
        </form>
      </div>
    </div>

<!-- Showing each list item -->
    <div class="box">
      <% newListItems.forEach(function(item) {%>
          <form class="form-group" action="/delete" method="post">
            <div class="item">
              <input type="checkbox" onChange="this.form.submit()" name="box" value="<%=  item._id  %>">
              <p><%=  item.itemName  %></p>
            </div>
          </form>
      <% }) %>

<!-- Adding new list items -->
      <form class="item" action="/" method="post">
        <input type="text" name="newItem" placeholder="New Item" autocomplete="off">
        <button class="button" type="submit" name="list" value="<%= listTitle %>">+</button>
      </form>
    </div>
  </div>

<%- include("footer") -%>
</code>```

Now, the website works well for the home page but I have added the functionality to make custom lists with custom names and that's where the issue arises. Whenever I make a new list, I want to add some items to it that are then stored in mongodb database. But if you look at the "Loading existing list" section of the .js code, there's the "newListItems" parameter which is supposed to take a list of items which are later displayed on the screen using a forEach() loop in the html document using EJS. Now, I have checked it multiple times, the items always get added to the database and exist there but when it's time to render them, the "foundList.items" gives that "TypeError: Cannot read properties of null (reading 'items')" error. I don't know what to do... And one more thing, when I try to create a new list after already creating one before, the second one doesn't gets any issues whatsoever. No idea what that is but it only happens the first time.

I hope someone can help...

Body:
so I was working on making this Todo list website but I am facing a problem.

NODE.JS CODE:

//jshint esversion:6

// _______________________________Database Code_________________________________
const mongoose = require("mongoose")

none = []

main().catch(err => console.log(err));

async function main() {
  mongoose.set('strictQuery', false);
  await mongoose.connect('mongodb://0.0.0.0:27017/todolistDB');
}

// For the main list
const itemSchema = {
  itemName: {
    type: String,
    required: true
  }
}

const Item = mongoose.model("Item", itemSchema)

const buyFood = new Item({
  itemName: "Buy Food"
})

const cookFood = new Item({
  itemName: "Cook Food"
})

const eatFood = new Item({
  itemName: "Eat Food"
})

const defaultItems = [buyFood, cookFood, eatFood]

// New list schema
const listSchema = {
  listName: String,
  items: [itemSchema]
}

const List = mongoose.model("list", listSchema)

// Function that creates new lists
function makeNewList(name) {
  const list = new List({
    listName: name,
    items: defaultItems
  })
  list.save()
}

// Function that creates new list items
function createNewItem(newItem) {
  const item = new Item ({
    itemName: newItem
  })
}

// Function to find a list
function findList(listName) {
  List.findOne({listName: listName}, function(err, list) {
    if (!err) {
      return list
    }
  })
}
// _______________________________Server Code___________________________________
const express = require("express");
const bodyParser = require("body-parser");
const date = require(__dirname + "/date.js");
const _ = require("lodash")
const popup = require("node-popup")

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

const workItems = [];

// Default Home List
app.get("/", function(req, res) {

  const day = date.getDate();

  Item.find(function(err, item) {

    if (item.length === 0) {
      Item.insertMany(defaultItems, function(err) {
        if (err) {
          console.log(err);
        } else {
          console.log("Items added successfully.");
        }
      })
    }

    else if (err) {
      console.log(err);
    }

    else {
      List.find({}, function(err, list) {
        if (err) {
          console.log(err);
        }
        else if (list.length === 0) {
          res.render("list", {listTitle: day, newListItems: item, array: none});
        }
        else {
          list.forEach(function(listName) {
            console.log(listName);
          })
          res.render("list", {array: list, newListItems: defaultItems, listTitle: day})
        }
      })
    }
  })
});

// Creating new list items
app.post("/", function(req, res){

  const item = req.body.newItem;
  const listName = req.body.list;

  if (listName === "day") {
    createNewItem(item)
    res.redirect("/")
  }
  // else {
  //   List.findOne({listName: listName}, function(err, foundList) {
  //     foundList.items.push(item)
  //     foundList.save()
  //     res.redirect("/" + listName)
  //   })
  // }
  });

// Deleting list items
app.post("/delete", function(req, res) {
  deletedItem = String(req.body.box)

  Item.deleteOne({_id: deletedItem}, function(err) {
    if (err) {
      console.log(err);
    } else {
      console.log("Item deleted successfully");
    }
  })

  res.redirect("/")
})

// Making new lists
app.post("/list", function(req, res) {
  newList = req.body.newListName.toLowerCase()

  List.findOne({listName: newList}, function(err, listInSearch) {
    if (!listInSearch) {
      console.log("Does not exist");
      makeNewList(newList)
      res.redirect("/" + newList)
    }
    else {
      console.log("Exist");
    }
  })
})

// Loading existing list
app.get("/:extension", function(req, res) {
  extension = req.params.extension.toLowerCase()
  console.log("Site ends with " + extension);

  if (extension !== "list") {
    List.find({}, function(err, list) {
      if (err) {
        console.log(err);
      }
      else {
        List.findOne({listName: extension}, function(err, foundList) {
          if (!err) {
            items = foundList.items
            console.log(items);
            res.render("list", {array: list, newListItems: foundList.items, listTitle: _.startCase(extension)})
          }
        })
      }
    })
  }
})

// app.post("/:extension", function(req, res) {
//   extension = req.params.extension.toLowerCase()
//   item = req.body.newItem.toString()
//
//   console.log(item);
//   console.log(extension);
//
//   List.findOne({listName: extension}, function(err, foundList) {
//     if (!err) {
//       createNewItem(item)
//       foundList.items.push(item)
//       foundList.save()
//       res.redirect("/" + extension)
//     }
//   })
// })

// About page
app.get("/about", function(req, res){
  res.render("about");
});

// Server port
app.listen(2000, function() {
  console.log("Server started on port 2000");
});

HTML CODE:

<%- include("header") -%>

 <%= listTitle %>

        <button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
          Lists
        </button>

          <% array.forEach(function(item) {%>

<a class="dropdown-item" href="/<%= item.listName %>"> <%= item.listName %>

          <% }) %>

Default List

        <form action="/list" method="post">
          <input type="text" name="newListName" placeholder="New List Name" autocomplete="off">
          <button class="btn btn-primary btn-md" type="submit" name="newList">Create</button>
        </form>

      <% newListItems.forEach(function(item) {%>
          <form class="form-group" action="/delete" method="post">

              <input type="checkbox" onChange="this.form.submit()" name="box" value="<%=  item._id  %>">

<%=  item.itemName  %>

          </form>
      <% }) %>

      <form class="item" action="/" method="post">
        <input type="text" name="newItem" placeholder="New Item" autocomplete="off">
        <button class="button" type="submit" name="list" value="<%= listTitle %>">+</button>
      </form>

<%- include("footer") -%>

Now, the website works well for the home page but I have added the functionality to make custom lists with custom names and that's where the issue arises. Whenever I make a new list, I want to add some items to it that are then stored in mongodb database. But if you look at the "Loading existing list" section of the .js code, there's the "newListItems" parameter which is supposed to take a list of items which are later displayed on the screen using a forEach() loop in the html document using EJS. Now, I have checked it multiple times, the items always get added to the database and exist there but when it's time to render them, the "foundList.items" gives that "TypeError: Cannot read properties of null (reading 'items')" error. I don't know what to do... And one more thing, when I try to create a new list after already creating one before, the second one doesn't gets any issues whatsoever. No idea what that is but it only happens the first time.

I hope someone can help...


问:
AVD virtual device Pixel3a API 32 process gets terminted repeatedly and if somehow the device open, it stay frozen idle
I am having problem with Android Studio where my Andrdoid virtual device gets terminated for no clear reason!

I tried searching all over internet and Stackoverflow but nothing seemed to work for me.
Tried everything from installing just SDK, Buildtools, Envoirnment-variables, to completely deleting and reinstalling android studio but issue persists. Ps it's not space issue as i have plently available

Solution
it's temporary fix but works!

open Android Virtual Device manager.

click 3dots(located right after the pencil)

click show on device

delete the cache file. (there will be file named cache)

There will be file named config.ini, (open it and change  hw.ramSize=3068  hw.cpu.ncore=1 ) cores and ram
you can also change ram and cores from that pencil and going to advanced.
after that do a cold start and wait patiently!! it will load up after a while! it works ....

i just did it.. but i have to do it everytime...


问:
iOS simulator stopped listening by Charles/Proxyman
Today any of my iOS simulators stopped being listened by proxy app (Charles or Proxyman, any) after few minutes after fresh adding to Xcode. (Mac OS Ventura)

I do all needed preparations with the certificates, and everything works.

I can see all decoded traffic in proxy app just perfectly.

After few minutes traffic just stop appearing in proxy app. And nothing helps (simulators restart, Mac reboot etc.)

I have to remove app from simulator and reinstall from XCode, or reinstall simulator to have another few minutes of working proxy.

Any ideas how to solve this trouble and what is causing it?


问:
why scope variable with no variable when consoled gives error whereas global variable gives default value?
```<code>public class ll {
//    static int x; this doesn't give error
    public static void main(String[] args) {
        int x;
      System.out.println(x); //this gives error "variable x might not have been initialized"
    }
}
</code>```

Read that the int has default value 0 but when tried consoling got an error whereas the global variable consoled the default value

Body:
public class ll {
//    static int x; this doesn't give error
    public static void main(String[] args) {
        int x;
      System.out.println(x); //this gives error "variable x might not have been initialized"
    }
}

Read that the int has default value 0 but when tried consoling got an error whereas the global variable consoled the default value


问:
Call external JS files in Angular 12
How to Call external JS files in Angular, try to add Datepicker JS in angular https://github.com/balbarak/bootstrap-hijri-datepicker

```<code>import $ from "jquery";
import  "../../../../../../assets/js/bootstrap-hijri-datetimepicker.js";

  DatePicker() {
    $(document).ready(function () {
      $("#hijri-picker").hijriDatePicker({
        hijri: true,
        showSwitcher: false,
      });
    });
  }
 <input id="hijri-picker" (click)="DatePicker()" type="text" class="form-control" />
</code>```

I  am getting fn.hijriDatePicker is not a function, how to call date picker on click https://stackblitz.com/edit/angular-ivy-1pqfr5?file=src/app/app.component.ts

Title: Call external JS files in Angular 12

Body:
How to Call external JS files in Angular, try to add Datepicker JS in angular https://github.com/balbarak/bootstrap-hijri-datepicker

import $ from "jquery";
import  "../../../../../../assets/js/bootstrap-hijri-datetimepicker.js";

  DatePicker() {
    $(document).ready(function () {
      $("#hijri-picker").hijriDatePicker({
        hijri: true,
        showSwitcher: false,
      });
    });
  }
 <input id="hijri-picker" (click)="DatePicker()" type="text" class="form-control" />

I  am getting fn.hijriDatePicker is not a function, how to call date picker on click https://stackblitz.com/edit/angular-ivy-1pqfr5?file=src/app/app.component.ts


问:
How to download or save SQL Server database full backup and restore it using ASP.NET Core with a LINQ query?
I have developed an ASP.NET Core web application, I need to write a C# method to allow the end user to download or save the SQL Server database full backup on his local computer. Moreover, I need to upload that database backup to restore a database.

Here is an example C# method that I wrote to download and save only one table of data in Excel format. Now I want to write another method to allow the user to download and save the all table full-backup as a .bak file on his local computer.

Please guide how to achieve this, thank you.

```<code>[DisplayName("Export Data To Excel")]
[Authorize(policy: "HasAccess")]
public class ExportDataToExcelController : BaseController
{
    public ExportDataToExcelController(HoshmandDBContext context) : base(context)
    {
    }

    // ----Export Patient Data -----------------------------
    public IActionResult ExportPatientDataToExcel()
    {
        DataTable patientTable = new DataTable("Patients_Data");
        patientTable.Columns.AddRange(new DataColumn[9]
        {
              new DataColumn("Patient ID"),
              new DataColumn("First Name"),
        });

        var patientsList = _context.PatientTbs.Include(a => a.Doctor).ToList();

        foreach (var patient in patientsList)
        {
            patientTable.Rows.Add(patient.PatientId, patient.FirstName);
        }

        using (XLWorkbook wb = new XLWorkbook())
        {
            wb.Worksheets.Add(patientTable);

            using (MemoryStream stream = new MemoryStream())
            {
                wb.SaveAs(stream);
                return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Patients Data " + GetLocalDateTime().Date.ToShortDateString() + "_" + ".xlsx");
            }
        }
    }
}
</code>```

Here is the user interface screenshot that I can download only one table of data in Excel format:

Here is an example user interface for restoring the database backup:

Body:
I have developed an ASP.NET Core web application, I need to write a C# method to allow the end user to download or save the SQL Server database full backup on his local computer. Moreover, I need to upload that database backup to restore a database.

Here is an example C# method that I wrote to download and save only one table of data in Excel format. Now I want to write another method to allow the user to download and save the all table full-backup as a .bak file on his local computer.

Please guide how to achieve this, thank you.

[DisplayName("Export Data To Excel")]
[Authorize(policy: "HasAccess")]
public class ExportDataToExcelController : BaseController
{
    public ExportDataToExcelController(HoshmandDBContext context) : base(context)
    {
    }

    // ----Export Patient Data -----------------------------
    public IActionResult ExportPatientDataToExcel()
    {
        DataTable patientTable = new DataTable("Patients_Data");
        patientTable.Columns.AddRange(new DataColumn[9]
        {
              new DataColumn("Patient ID"),
              new DataColumn("First Name"),
        });

        var patientsList = _context.PatientTbs.Include(a => a.Doctor).ToList();

        foreach (var patient in patientsList)
        {
            patientTable.Rows.Add(patient.PatientId, patient.FirstName);
        }

        using (XLWorkbook wb = new XLWorkbook())
        {
            wb.Worksheets.Add(patientTable);

            using (MemoryStream stream = new MemoryStream())
            {
                wb.SaveAs(stream);
                return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Patients Data " + GetLocalDateTime().Date.ToShortDateString() + "_" + ".xlsx");
            }
        }
    }
}

Here is the user interface screenshot that I can download only one table of data in Excel format:

Here is an example user interface for restoring the database backup:


问:
I want to use a custom button to increment a input number field but it is re-rendering the parent component and losing a state value
I have an input element for a number that increments, I want to create my own increment buttons because I don't like the default buttons, they don't work well on mobile.
So I created a button element that onClick handles the change in the number value and does other things with an onchange function that is fired from its parent, the main thing is that I need change a boolean state from false to true here, it worked fine when using the onChange from the input but when using the onClick from the button the parent component seems to re-render again thus losing the boolean state from false to true and then back to false again as its declared at the top.

Child component:

```<code>const PredictField = (props: any) => {
    const { fixture, onchange, index, innerIndex } = props;
    const [away, setAway] = useState(0);

const handleOnChangeAway = (matchId: string) => {
        setAway((away) => away + 1);
        onchange(matchId);
    };

<input
className="score"
name={`awayTeam-${fixture.id}`}
type="number"
value={away}
onChange={(e) => handleOnChangeAway(e.target)}
min="0"
max="20"
/>

<button onClick={() => handleOnChangeAway(`awayTeam-${fixture.id}`)}>
<FontAwesomeIcon icon={faPlus} />
</button>
}
</code>```

Parent component:

```<code>export default function Predict() {
    const [showSave, setShowSave] = useState(false);

    const onchange = (matchIdString: string) => {
        setShowSave(true);
    }
}
</code>```

So basically the problem is that showSave should change to true and it does but then it re-renders again to false ONLY with the button onClick, using the onChange in the input form it keeps being true, as I want it to.

How can I stop the Predict component re-rendering and thus changing the showSave back to false?

I've tried memo and useCallback and they didn't for me.

Body:
I have an input element for a number that increments, I want to create my own increment buttons because I don't like the default buttons, they don't work well on mobile.
So I created a button element that onClick handles the change in the number value and does other things with an onchange function that is fired from its parent, the main thing is that I need change a boolean state from false to true here, it worked fine when using the onChange from the input but when using the onClick from the button the parent component seems to re-render again thus losing the boolean state from false to true and then back to false again as its declared at the top.

Child component:

const PredictField = (props: any) => {
    const { fixture, onchange, index, innerIndex } = props;
    const [away, setAway] = useState(0);

const handleOnChangeAway = (matchId: string) => {
        setAway((away) => away + 1);
        onchange(matchId);
    };

<input
className="score"
name={`awayTeam-${fixture.id}`}
type="number"
value={away}
onChange={(e) => handleOnChangeAway(e.target)}
min="0"
max="20"
/>

<button onClick={() => handleOnChangeAway(`awayTeam-${fixture.id}`)}>
<FontAwesomeIcon icon={faPlus} />
</button>
}

Parent component:

export default function Predict() {
    const [showSave, setShowSave] = useState(false);

    const onchange = (matchIdString: string) => {
        setShowSave(true);
    }
}

So basically the problem is that showSave should change to true and it does but then it re-renders again to false ONLY with the button onClick, using the onChange in the input form it keeps being true, as I want it to.

How can I stop the Predict component re-rendering and thus changing the showSave back to false?

I've tried memo and useCallback and they didn't for me.


问:
Uncaught exception: Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string
I'm trying to run some tests on some methods which handle some operation on a postgres database,  using jasmine testing framework, but I'm getting the following output in the console:

write-logging-middleware@1.0.0 test
set ENV=test && npx tsc && db-migrate --env test up && jasmine && db-migrate db:drop test

[INFO] No migrations to run [INFO] Done Started .FFFFF

Failures: 1) Realistic weapon model index method should return a list
of weapons   Message:
Uncaught exception: Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string   Stack:
at Object.continueSession (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\sasl.js:24:11)
at Client._handleAuthSASLContinue (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\client.js:257:10)
at Connection.emit (node:events:513:28)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\connection.js:114:12
at Parser.parse (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\parser.js:40:17)
at Socket. (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)   Message:
Uncaught exception: Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string   Stack:
at Object.continueSession (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\sasl.js:24:11)
at Client._handleAuthSASLContinue (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\client.js:257:10)
at Connection.emit (node:events:513:28)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\connection.js:114:12
at Parser.parse (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\parser.js:40:17)
at Socket. (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)   Message:
Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)   Stack:
at
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)

Realistic weapon model show method should return a specific weapon
Message:
Uncaught exception: Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string   Stack:
at Object.continueSession (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\sasl.js:24:11)
at Client._handleAuthSASLContinue (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\client.js:257:10)
at Connection.emit (node:events:513:28)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\connection.js:114:12
at Parser.parse (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\parser.js:40:17)
at Socket. (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)   Message:
Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)   Stack:
at
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)

Realistic weapon model create method should return the last created
object   Message:
Uncaught exception: Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string   Stack:
at Object.continueSession (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\sasl.js:24:11)
at Client._handleAuthSASLContinue (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\client.js:257:10)
at Connection.emit (node:events:513:28)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\connection.js:114:12
at Parser.parse (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\parser.js:40:17)
at Socket. (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)   Message:
Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)   Stack:
at
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)

Realistic weapon model update method should edit an existing object
Message:
Uncaught exception: Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string   Stack:
at Object.continueSession (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\sasl.js:24:11)
at Client._handleAuthSASLContinue (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\client.js:257:10)
at Connection.emit (node:events:513:28)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\connection.js:114:12
at Parser.parse (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\parser.js:40:17)
at Socket. (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)   Message:
Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)   Stack:
at
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)

Realistic weapon model delete method should delete an existing
object   Message:
Expected Function to equal null.
at
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\dist\model\test\realistic_weapon_spec.js:121:20

```<code> at step (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\dist\model\test\realistic_weapon_spec.js:33:23)
</code>```

at Object.next
(D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\dist\model\test\realistic_weapon_spec.js:14:53)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\dist\model\test\realistic_weapon_spec.js:8:71

6 specs, 5 failures Finished in 20.079 seconds PS

here is my files codes:

database.js

```<code>import dotenv from 'dotenv'
import {Pool} from 'pg'

dotenv.config()
let client:Pool = new Pool();

const{
    POSTGRES_HOST,
    POSTGRES_DB,
    POSTGRES_USER,
    POSTGRES_PASSWORD,
    ENV,
    POSTGRES_TEST_DB
} = process.env

if(ENV==='test'){
    client = new Pool({
        host: POSTGRES_HOST,
        database: POSTGRES_TEST_DB,
        user: POSTGRES_USER,
        password: POSTGRES_PASSWORD
    })
}

if(ENV==='dev'){
    client = new Pool({
        host: POSTGRES_HOST,
        database: POSTGRES_DB,
        user: POSTGRES_USER,
        password: POSTGRES_PASSWORD
    })
}

export default client
</code>```

Model class (called Realistic_weapon.ts) and its methodes:

```<code>import client from "../database";

export type Weapon = {
    id:Number,
    name:string,
    weight: Number,
    type:string
}

type RowWeapon = {
    name:string,
    weight: Number,
    type:string
}

export class RealisticWeaponsStore{
    async index(): Promise<Weapon[]>{
        try {
            // @ts-ignore
            const conn = await client.connect();
            const sql = 'select * from realistic_weapon'
            const result = conn.query(sql)
            conn.release()
            return (await result).rows
        } catch (err) {
            throw new Error(`Could not find weapons. Error: ${err}`)
        }

    }
    async show(id: number): Promise<Weapon> {
        try {
        const sql = 'SELECT * FROM weapon WHERE id=($1)'
        // @ts-ignore
        const conn = await client.connect()

        const result = await conn.query(sql, [id])

        conn.release()

        return result.rows[0]
        } catch (err) {
            throw new Error(`Could not find weapon ${id}. Error: ${err}`)
        }
    }
    async create(b:RowWeapon):Promise<Weapon>{
        try {
            // @ts-ignore
            const conn = await client.connect()
            const sql = 'insert into book (title, author, totalPages, summary) values($1, $2, $3, $4) returning'
            const result = conn.query(sql, [b.name, b.type, b.weight])
            const book = (await result).rows[0]
            conn.release()
            return book
        } catch (err) {
            throw new Error(`Could not create weapon. Error: ${err}`)

        }
    }

    async update(b:Weapon):Promise<Weapon>{
        try {
            // @ts-ignore
            const conn = await client.connect()
            const sql = 'update book set title=$1, author=$2, totalPages=$3, summary=$4 where id=($5)'
            const result = conn.query(sql, [b.name, b.type, b.weight, b.id])
            const book = (await result).rows[0]
            conn.release()
            return book;
        } catch (err) {
            throw new Error(`Could not update weapon. Error: ${err}`)
        }
    }

    async delete(id:Number):Promise<void>{
        try {
            const conn = await client.connect()
            const sql = 'delete from book where id=($1)'
            const result = conn.query(sql,[id])
        } catch (err) {
            throw new Error(`Could not delete weapon ${id}. Error: ${err}`)

        }
    }
}
</code>```

the spec file (Realistic_weapon_spec.ts):

```<code>import { Weapon, RealisticWeaponsStore} from './../Realistic_weapon';

const store = new RealisticWeaponsStore()

describe('Realistic weapon model', ()=>{
    it('should have an index method', ()=>{
        expect(store.index()).toBeDefined()
    })
    it('index method should return a list of weapons',async ()=>{
        const weapon1:Weapon = {id:1, name: 'first weapon', weight: 2, type: 'first weapon type'}
        const weapon2:Weapon = {id:2, name: 'second weapon', weight: 3, type: 'second weapon type'}
        const weapon3:Weapon = {id:3, name: 'third weapon', weight: 3.5, type: 'third weapon type'}
        expect(await store.index()).toEqual([weapon1, weapon2, weapon3])
    })
    it('show method should return a specific weapon',async ()=>{
        const weapon1:Weapon = {id:1, name: 'first weapon', weight: 2, type: 'first weapon type'}
        expect(await store.show(1)).toEqual(weapon1)
    })
    it('create method should return the last created object',async ()=>{
        const weapon1 = {name : 'new weapon', weight : 3, type : 'new weapon type'}
        const weapon2:Weapon = {id : 4, name : 'new weapon', weight : 3, type : 'new weapon type'}
        expect(await store.create(weapon1)).toEqual(weapon2)
    })
    it('update method should edit an existing object',async ()=>{
        const weapon1:Weapon = {id : 4, name : 'new weapon', weight : 3, type : 'new weapon type'}
        const weapon2:Weapon = {id : 4, name : 'updated weapon', weight : 5, type : 'updated weapon type'}
        expect(await store.update(weapon2)).toEqual(weapon2)
    })
    it('delete method should delete an existing object',async ()=>{
        const id = 4;
        expect(async ()=>{
            await store.delete(id)
            await store.show(id)
            }
        ).toEqual(null)
    })
})
</code>```

and here is the script which is executed to run the test:

```<code>"test": "set ENV=test && npx tsc && db-migrate --env test up && jasmine && db-migrate db:drop test"
</code>```

can any one help me please.

Body:
I'm trying to run some tests on some methods which handle some operation on a postgres database,  using jasmine testing framework, but I'm getting the following output in the console:

write-logging-middleware@1.0.0 test
set ENV=test && npx tsc && db-migrate --env test up && jasmine && db-migrate db:drop test

[INFO] No migrations to run [INFO] Done Started .FFFFF

Failures: 1) Realistic weapon model index method should return a list
of weapons   Message:
Uncaught exception: Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string   Stack:
at Object.continueSession (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\sasl.js:24:11)
at Client._handleAuthSASLContinue (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\client.js:257:10)
at Connection.emit (node:events:513:28)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\connection.js:114:12
at Parser.parse (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\parser.js:40:17)
at Socket. (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)   Message:
Uncaught exception: Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string   Stack:
at Object.continueSession (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\sasl.js:24:11)
at Client._handleAuthSASLContinue (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\client.js:257:10)
at Connection.emit (node:events:513:28)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\connection.js:114:12
at Parser.parse (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\parser.js:40:17)
at Socket. (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)   Message:
Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)   Stack:
at
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)

Realistic weapon model show method should return a specific weapon
Message:
Uncaught exception: Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string   Stack:
at Object.continueSession (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\sasl.js:24:11)
at Client._handleAuthSASLContinue (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\client.js:257:10)
at Connection.emit (node:events:513:28)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\connection.js:114:12
at Parser.parse (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\parser.js:40:17)
at Socket. (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)   Message:
Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)   Stack:
at
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)

Realistic weapon model create method should return the last created
object   Message:
Uncaught exception: Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string   Stack:
at Object.continueSession (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\sasl.js:24:11)
at Client._handleAuthSASLContinue (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\client.js:257:10)
at Connection.emit (node:events:513:28)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\connection.js:114:12
at Parser.parse (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\parser.js:40:17)
at Socket. (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)   Message:
Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)   Stack:
at
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)

Realistic weapon model update method should edit an existing object
Message:
Uncaught exception: Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string   Stack:
at Object.continueSession (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\sasl.js:24:11)
at Client._handleAuthSASLContinue (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\client.js:257:10)
at Connection.emit (node:events:513:28)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg\lib\connection.js:114:12
at Parser.parse (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\parser.js:40:17)
at Socket. (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)   Message:
Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)   Stack:
at
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)

Realistic weapon model delete method should delete an existing
object   Message:
Expected Function to equal null.
at
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\dist\model\test\realistic_weapon_spec.js:121:20

 at step (D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\dist\model\test\realistic_weapon_spec.js:33:23)

at Object.next
(D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\dist\model\test\realistic_weapon_spec.js:14:53)
at D:\Projets\Udacity-exercices-projects\node-postgres-api-starter\dist\model\test\realistic_weapon_spec.js:8:71

6 specs, 5 failures Finished in 20.079 seconds PS

here is my files codes:

database.js

import dotenv from 'dotenv'
import {Pool} from 'pg'

dotenv.config()
let client:Pool = new Pool();

const{
    POSTGRES_HOST,
    POSTGRES_DB,
    POSTGRES_USER,
    POSTGRES_PASSWORD,
    ENV,
    POSTGRES_TEST_DB
} = process.env

if(ENV==='test'){
    client = new Pool({
        host: POSTGRES_HOST,
        database: POSTGRES_TEST_DB,
        user: POSTGRES_USER,
        password: POSTGRES_PASSWORD
    })
}

if(ENV==='dev'){
    client = new Pool({
        host: POSTGRES_HOST,
        database: POSTGRES_DB,
        user: POSTGRES_USER,
        password: POSTGRES_PASSWORD
    })
}

export default client

Model class (called Realistic_weapon.ts) and its methodes:

import client from "../database";

export type Weapon = {
    id:Number,
    name:string,
    weight: Number,
    type:string
}

type RowWeapon = {
    name:string,
    weight: Number,
    type:string
}

export class RealisticWeaponsStore{
    async index(): Promise<Weapon[]>{
        try {
            // @ts-ignore
            const conn = await client.connect();
            const sql = 'select * from realistic_weapon'
            const result = conn.query(sql)
            conn.release()
            return (await result).rows
        } catch (err) {
            throw new Error(`Could not find weapons. Error: ${err}`)
        }

    }
    async show(id: number): Promise<Weapon> {
        try {
        const sql = 'SELECT * FROM weapon WHERE id=($1)'
        // @ts-ignore
        const conn = await client.connect()

        const result = await conn.query(sql, [id])

        conn.release()

        return result.rows[0]
        } catch (err) {
            throw new Error(`Could not find weapon ${id}. Error: ${err}`)
        }
    }
    async create(b:RowWeapon):Promise<Weapon>{
        try {
            // @ts-ignore
            const conn = await client.connect()
            const sql = 'insert into book (title, author, totalPages, summary) values($1, $2, $3, $4) returning'
            const result = conn.query(sql, [b.name, b.type, b.weight])
            const book = (await result).rows[0]
            conn.release()
            return book
        } catch (err) {
            throw new Error(`Could not create weapon. Error: ${err}`)

        }
    }

    async update(b:Weapon):Promise<Weapon>{
        try {
            // @ts-ignore
            const conn = await client.connect()
            const sql = 'update book set title=$1, author=$2, totalPages=$3, summary=$4 where id=($5)'
            const result = conn.query(sql, [b.name, b.type, b.weight, b.id])
            const book = (await result).rows[0]
            conn.release()
            return book;
        } catch (err) {
            throw new Error(`Could not update weapon. Error: ${err}`)
        }
    }

    async delete(id:Number):Promise<void>{
        try {
            const conn = await client.connect()
            const sql = 'delete from book where id=($1)'
            const result = conn.query(sql,[id])
        } catch (err) {
            throw new Error(`Could not delete weapon ${id}. Error: ${err}`)

        }
    }
}

the spec file (Realistic_weapon_spec.ts):

import { Weapon, RealisticWeaponsStore} from './../Realistic_weapon';

const store = new RealisticWeaponsStore()

describe('Realistic weapon model', ()=>{
    it('should have an index method', ()=>{
        expect(store.index()).toBeDefined()
    })
    it('index method should return a list of weapons',async ()=>{
        const weapon1:Weapon = {id:1, name: 'first weapon', weight: 2, type: 'first weapon type'}
        const weapon2:Weapon = {id:2, name: 'second weapon', weight: 3, type: 'second weapon type'}
        const weapon3:Weapon = {id:3, name: 'third weapon', weight: 3.5, type: 'third weapon type'}
        expect(await store.index()).toEqual([weapon1, weapon2, weapon3])
    })
    it('show method should return a specific weapon',async ()=>{
        const weapon1:Weapon = {id:1, name: 'first weapon', weight: 2, type: 'first weapon type'}
        expect(await store.show(1)).toEqual(weapon1)
    })
    it('create method should return the last created object',async ()=>{
        const weapon1 = {name : 'new weapon', weight : 3, type : 'new weapon type'}
        const weapon2:Weapon = {id : 4, name : 'new weapon', weight : 3, type : 'new weapon type'}
        expect(await store.create(weapon1)).toEqual(weapon2)
    })
    it('update method should edit an existing object',async ()=>{
        const weapon1:Weapon = {id : 4, name : 'new weapon', weight : 3, type : 'new weapon type'}
        const weapon2:Weapon = {id : 4, name : 'updated weapon', weight : 5, type : 'updated weapon type'}
        expect(await store.update(weapon2)).toEqual(weapon2)
    })
    it('delete method should delete an existing object',async ()=>{
        const id = 4;
        expect(async ()=>{
            await store.delete(id)
            await store.show(id)
            }
        ).toEqual(null)
    })
})

and here is the script which is executed to run the test:

"test": "set ENV=test && npx tsc && db-migrate --env test up && jasmine && db-migrate db:drop test"

can any one help me please.


问:
Error: connect ETIMEDOUT, how to solve it? using Node.js and MySQL2
I used Node.js and MySQL2. Working on MySQL workbench. Created virtual DB using Railway workbench. Schemas and tables are created. But showing `ETIMEDOUT error in the VS code's terminal when i try to run node index.js. What can i do?

db.js:

import mysql2 from 'mysql2';

export const db = mysql2.createConnection({
    host: 'containers-us-west-174.railway.app',
    user: 'user',
    password: 'password',
    database: 'railway'
})
```
<p><strong>index.js</strong>:</p>
<pre class="lang-js prettyprint-override"><code>import express from 'express';
import authRoutes from './routes/auth.js';
import userRoutes from './routes/users.js';
import postRoutes from './routes/posts.js';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import multer from 'multer';

dotenv.config();

const app = express();

app.use(express.json());
app.use(cookieParser());

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '../client/public/upload');
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname);
    }
})

const upload = multer({ storage: storage })

app.post('/api/upload', upload.single('file'), function (req, res) {
    const file = req.file;
    res.status(200).json(file?.filename)
});

app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/posts', postRoutes);

app.listen(8800, () => {
    console.log('Connected wih backend!');
})
</code>```

In my VS Code Terminal it is showing this error:

```<code>Connected wih backend!
node:events:505
      throw er; // Unhandled 'error' event
      ^

Error: connect ETIMEDOUT
    at Connection._handleTimeoutError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:189:17)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)
Emitted 'error' event on Connection instance at:
    at Connection._notifyError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:236:12)
    at Connection._handleFatalError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:167:10)
    at Connection._handleNetworkError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:180:10)
    at Connection._handleTimeoutError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:193:10)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7) {
  errorno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  syscall: 'connect',
  fatal: true
}
</code>```

I was trying to deploting in railway. I'm using MySQL workbench.

In Railway deployment logs this error shows:

```<code>> api@1.0.0 start
> node index.js
node:internal/modules/cjs/loader:1239
return process.dlopen(module, path.toNamespacedPath(filename));
^
Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
at Object.Module._extensions..node (node:internal/modules/cjs/loader:1239:18)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12)
at Module.require (node:internal/modules/cjs/loader:1057:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
at Module._compile (node:internal/modules/cjs/loader:1155:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12) {
code: 'ERR_DLOPEN_FAILED'
}
npm WARN config production Use `--omit=dev` instead.
</code>```

And deployment crashed!

Any solution?

Body:
I used Node.js and MySQL2. Working on MySQL workbench. Created virtual DB using Railway workbench. Schemas and tables are created. But showing `ETIMEDOUT error in the VS code's terminal when i try to run node index.js. What can i do?

db.js:

import mysql2 from 'mysql2';

export const db = mysql2.createConnection({
    host: 'containers-us-west-174.railway.app',
    user: 'user',
    password: 'password',
    database: 'railway'
})

index.js:

import express from 'express';
import authRoutes from './routes/auth.js';
import userRoutes from './routes/users.js';
import postRoutes from './routes/posts.js';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import multer from 'multer';

dotenv.config();

const app = express();

app.use(express.json());
app.use(cookieParser());

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '../client/public/upload');
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname);
    }
})

const upload = multer({ storage: storage })

app.post('/api/upload', upload.single('file'), function (req, res) {
    const file = req.file;
    res.status(200).json(file?.filename)
});

app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/posts', postRoutes);

app.listen(8800, () => {
    console.log('Connected wih backend!');
})

In my VS Code Terminal it is showing this error:

Connected wih backend!
node:events:505
      throw er; // Unhandled 'error' event
      ^

Error: connect ETIMEDOUT
    at Connection._handleTimeoutError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:189:17)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)
Emitted 'error' event on Connection instance at:
    at Connection._notifyError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:236:12)
    at Connection._handleFatalError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:167:10)
    at Connection._handleNetworkError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:180:10)
    at Connection._handleTimeoutError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:193:10)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7) {
  errorno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  syscall: 'connect',
  fatal: true
}

I was trying to deploting in railway. I'm using MySQL workbench.

In Railway deployment logs this error shows:

> api@1.0.0 start
> node index.js
node:internal/modules/cjs/loader:1239
return process.dlopen(module, path.toNamespacedPath(filename));
^
Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
at Object.Module._extensions..node (node:internal/modules/cjs/loader:1239:18)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12)
at Module.require (node:internal/modules/cjs/loader:1057:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
at Module._compile (node:internal/modules/cjs/loader:1155:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12) {
code: 'ERR_DLOPEN_FAILED'
}
npm WARN config production Use `--omit=dev` instead.

And deployment crashed!

Any solution?


问:
riot js version > 4 testing
Does anyone know how to test the riot files from riot 4 version or higher?

example file: test-page.riot

```<code><test-page>
  <h4>{ state.heading }</h4>
  <script>
    export default {
      state: {
        heading: ''
      },
      onMounted() {
        this.change_heading()
      }
      change_heading() {
        this.state.heading = 'Test page'
        this.update()
      }
    }
  </script>
</test-page>
</code>```

I tried Jest but it works with javascript files and not with riot.

Title: riot js version > 4 testing

Body:
Does anyone know how to test the riot files from riot 4 version or higher?

example file: test-page.riot

<test-page>

{ state.heading }

</test-page>

I tried Jest but it works with javascript files and not with riot.


问:
Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {user, notification, _persist})
Im receiving this error. and I don't even know why (ignore the user's one in the below blocks of code they are just added mistakenly):(
this is the code of my slice:

```<code>import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  notification: 0,
};

const setNotificationSlice = createSlice({
  name: "notification",

  initialState,
  reducers: {
    setNotification: (state, { payload }) => {
      state.notification = payload;
    },
  },
});

export const { setNotification } = setNotificationSlice.actions;

export const notification = setNotificationSlice.reducer;

</code>```

My actions

```<code>
export { setNotification } from "./Slices/Notification";

</code>```

Reducers

```<code>import { combineReducers } from "redux";
import { notification } from "redux/Slices/Notification";

const rootReducer = combineReducers({
  notification,
});

export { rootReducer };

</code>```

and my store

```<code>import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { rootReducer } from "./reducers";
import storage from "./presistStorage";
import { persistStore, persistReducer } from "redux-persist";
import { composeWithDevTools } from "redux-devtools-extension";

const initialState = {};

// presist the state of user after refreshing the app.
const persistConfig = {
  key: "PresistStorage", // variable name in storage
  storage,
  whitelist: ["user", "notification"], // which reducer want to store
};

const persistReducerState = persistReducer(persistConfig, rootReducer);
const middleware = [thunk];
const store = createStore(
  persistReducerState,
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
);

const persistor = persistStore(store);
export { store, persistor };

</code>```

my navbar where I want to show the notifications

```<code>  const notification = useSelector((state) => state.notification);
-----------------------------------------------------------------------------------
          <span className={classes.notifications}>
            {notification ? notification : 0}
            {/* {JSON.stringify(notification)} */}
          </span>
</code>```

and the last component where im dispatching the setNotification

```<code>  const handleNotification = () => {
    dispatch(setNotification(2));
  };
-------------------------------------------------------------------------------------
/// surrounded by API when the API will have 200 status code then this will run ///
handleNotification();
</code>```

what my console prints out

Thanks in advance :)

Body:
Im receiving this error. and I don't even know why (ignore the user's one in the below blocks of code they are just added mistakenly):(
this is the code of my slice:

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  notification: 0,
};

const setNotificationSlice = createSlice({
  name: "notification",

  initialState,
  reducers: {
    setNotification: (state, { payload }) => {
      state.notification = payload;
    },
  },
});

export const { setNotification } = setNotificationSlice.actions;

export const notification = setNotificationSlice.reducer;

My actions

export { setNotification } from "./Slices/Notification";

Reducers

import { combineReducers } from "redux";
import { notification } from "redux/Slices/Notification";

const rootReducer = combineReducers({
  notification,
});

export { rootReducer };

and my store

import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { rootReducer } from "./reducers";
import storage from "./presistStorage";
import { persistStore, persistReducer } from "redux-persist";
import { composeWithDevTools } from "redux-devtools-extension";

const initialState = {};

// presist the state of user after refreshing the app.
const persistConfig = {
  key: "PresistStorage", // variable name in storage
  storage,
  whitelist: ["user", "notification"], // which reducer want to store
};

const persistReducerState = persistReducer(persistConfig, rootReducer);
const middleware = [thunk];
const store = createStore(
  persistReducerState,
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
);

const persistor = persistStore(store);
export { store, persistor };

my navbar where I want to show the notifications

  const notification = useSelector((state) => state.notification);
-----------------------------------------------------------------------------------

            {notification ? notification : 0}
            {/* {JSON.stringify(notification)} */}

and the last component where im dispatching the setNotification

  const handleNotification = () => {
    dispatch(setNotification(2));
  };
-------------------------------------------------------------------------------------
/// surrounded by API when the API will have 200 status code then this will run ///
handleNotification();

what my console prints out

Thanks in advance :)


问:
error (string literal contains an unescaped line break app.js:5:33)
products are not showing

```<code>function renderProducts() {
    products.forEach( (product) => {
        productSec.innerHTML += '
        <div class="item">
            <div class="item-container">
                <div class="item-img">
                    <img src="${product.imgSrc}" alt="t-shirt ${product.name}" />
                </div>
                <div class="desc">
                    <h2>${product.name}</h2>
                    <h2><small>$</small>${product.price}</h2>
                    <p>${product.description}</p>
                </div>
                <div class="add-to-wishlist">
                    <img src="./icons/heart.png" alt="add to wish list" />
                </div>
                <div class="add-to-cart">
                    <img src="./icons/bag-plus.png" alt="add to cart" />
                </div>
            </div>
        </div>
        '
    });
}

renderProducts();
</code>```

i am trying to display in html but products are not showing.
error (string literal contains an unescaped line break app.js:5:33)

Body:
products are not showing

function renderProducts() {
    products.forEach( (product) => {
        productSec.innerHTML += '

${product.name}

$${product.price}

${product.description}

        '
    });
}

renderProducts();

i am trying to display in html but products are not showing.
error (string literal contains an unescaped line break app.js:5:33)


问:
Use exceptions rather than return codes: unused value
In the clean code book is an example about using exceptions rather than return codes:

You either set an error flag or returned an error code.

public class DeviceController {
    ...
    public void sendShutDown() {
        DeviceHandle handle = getHandle(DEV1);
        // Check the state of the device
        if (handle != DeviceHandle.INVALID) {
            // Save the device status to the record field
            retrieveDeviceRecord(handle);
            // If not suspended, shut down
            if (record.getStatus() != DEVICE_SUSPENDED) {
                pauseDevice(handle);
                clearDeviceWorkQueue(handle);
                closeDevice(handle);
            } else {
                logger.log("Device suspended. Unable to shut down");
            }
        } else {
            logger.log("Invalid handle for: " + DEV1.toString());
        }
    }
...
}
```
<p>Unfortunately, it's easy to forget. For this reason, it is better to throw an exception when you encounter an error. The calling code is cleaner. Its logic is not obscured by error handling.</p>
<pre class="lang-java prettyprint-override"><code>public class DeviceController {
    ...
    public void sendShutDown() {
        try {
            tryToShutDown();
        } catch (DeviceShutDownError e) {
            logger.log(e);
        }
    }

    private void tryToShutDown() throws DeviceShutDownError {
        DeviceHandle handle = getHandle(DEV1);
        DeviceRecord record = retrieveDeviceRecord(handle);

        pauseDevice(handle);
        clearDeviceWorkQueue(handle);
        closeDevice(handle);
    }

    private DeviceHandle getHandle(DeviceID id) {
        ...
        throw new DeviceShutDownError("Invalid handle for: " + id.toString());
        ...
    }
...
}
</code>```

The code is better because two concerns that were tangled, the algorithm for device shutdown and error handling, are now separated. You can look at each of those concerns and understand them independently.

Now my question is not so much about the whether to use exceptions or return codes but I am wondering about the unused DeviceRecord in the second "good example", which uses exceptions.

Wouldn't it be enough to just call retrieveDeviceRecord(handle); to save the device status to the record field as in the "bad example code" but change the method to also throw an exception in case anything goes wrong during retrieveDeviceRecord(handle);? Or is there a purpose of returning DeviceRecord but not using it?

Body:
In the clean code book is an example about using exceptions rather than return codes:

You either set an error flag or returned an error code.

public class DeviceController {
    ...
    public void sendShutDown() {
        DeviceHandle handle = getHandle(DEV1);
        // Check the state of the device
        if (handle != DeviceHandle.INVALID) {
            // Save the device status to the record field
            retrieveDeviceRecord(handle);
            // If not suspended, shut down
            if (record.getStatus() != DEVICE_SUSPENDED) {
                pauseDevice(handle);
                clearDeviceWorkQueue(handle);
                closeDevice(handle);
            } else {
                logger.log("Device suspended. Unable to shut down");
            }
        } else {
            logger.log("Invalid handle for: " + DEV1.toString());
        }
    }
...
}

Unfortunately, it's easy to forget. For this reason, it is better to throw an exception when you encounter an error. The calling code is cleaner. Its logic is not obscured by error handling.

public class DeviceController {
    ...
    public void sendShutDown() {
        try {
            tryToShutDown();
        } catch (DeviceShutDownError e) {
            logger.log(e);
        }
    }

    private void tryToShutDown() throws DeviceShutDownError {
        DeviceHandle handle = getHandle(DEV1);
        DeviceRecord record = retrieveDeviceRecord(handle);

        pauseDevice(handle);
        clearDeviceWorkQueue(handle);
        closeDevice(handle);
    }

    private DeviceHandle getHandle(DeviceID id) {
        ...
        throw new DeviceShutDownError("Invalid handle for: " + id.toString());
        ...
    }
...
}

The code is better because two concerns that were tangled, the algorithm for device shutdown and error handling, are now separated. You can look at each of those concerns and understand them independently.

Now my question is not so much about the whether to use exceptions or return codes but I am wondering about the unused DeviceRecord in the second "good example", which uses exceptions.

Wouldn't it be enough to just call retrieveDeviceRecord(handle); to save the device status to the record field as in the "bad example code" but change the method to also throw an exception in case anything goes wrong during retrieveDeviceRecord(handle);? Or is there a purpose of returning DeviceRecord but not using it?


问:
require error in react app when authentication complete
i have a react app and this app has an authentication with google. when i authenticed with google anfter that i got error. i done npm run build and upload dist file on netlify

and my login component is :

```<code>  const Login = () => {
  const provider = new GoogleAuthProvider();

  const signIn = async () => {
    await signInWithPopup(auth, provider)
      .then((result) => {
        console.log(result)
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <>
      <div className={style.login}>
        <div className={style.login__card}>
          <img src={twitterImage} alt="Twitter Image" className={style.login__image} />
          <Button variant="outlined" color="error" onClick={signIn} >
            Login with Google
          </Button>
        </div>
      </div>
    </>
  );
};

export default Login;
</code>```

i use react-firebase-hooks library to achive user data:

```<code>const App = () => {
  const [user, loading, error] = useAuthState(auth);

  if (loading) return

  return (
    <div className={`${user && style.app}`}>
      {user ? (
        <>
          {/* Sidebar */}
          <Sidebar />

          {/* Feed */}
          <Feed />

          {/* Widgets */}
          <Widgets />
        </>
      ) : (
        <Login />
      )}
    </div>
  );
};

export default App;
</code>```

Body:
i have a react app and this app has an authentication with google. when i authenticed with google anfter that i got error. i done npm run build and upload dist file on netlify

and my login component is :

  const Login = () => {
  const provider = new GoogleAuthProvider();

  const signIn = async () => {
    await signInWithPopup(auth, provider)
      .then((result) => {
        console.log(result)
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <>

          <Button variant="outlined" color="error" onClick={signIn} >
            Login with Google
          </Button>

    </>
  );
};

export default Login;

i use react-firebase-hooks library to achive user data:

const App = () => {
  const [user, loading, error] = useAuthState(auth);

  if (loading) return

  return (
    <div className={`${user && style.app}`}>
      {user ? (
        <>
          {/* Sidebar */}
          <Sidebar />

          {/* Feed */}
          <Feed />

          {/* Widgets */}
          <Widgets />
        </>
      ) : (
        <Login />
      )}

  );
};

export default App;