小编Tax*_*xel的帖子

使用nodemon和express优雅关闭

当 nodemon 重新启动我的 Express 服务器时,我正在努力拦截信号。我需要这个来关闭数据库,否则当我下次尝试使用它时会抛出错误。编辑:它起初看起来并不像它,但当我通过 Ctrl+C 终止它时,它确实调用了一些函数。我已经评论了哪些。

显然,nodemon 在重新启动时会发送 SIGUSR2 信号,但我尝试向该事件以及无数其他事件添加一个事件;这是文件 nodemon 被告知启动的摘录(应用程序的主入口点位于名为 的文件中/bin/www,这是我创建 Express 应用程序时的默认设置);正如你所看到的,我尝试了很多事情:

var app = require("../app");
var debug = require("debug")("server:server");
var http = require("http");
// terminus was built to handle this, right?
const { createTerminus } = require("@godaddy/terminus");


app.set("port", "3001");

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

// the terminus handler for SIGUSR2
function onSignal() {
    console.log("server is starting cleanup");
    // start cleanup of resource, like databases or file …
Run Code Online (Sandbox Code Playgroud)

node.js express nodemon

7
推荐指数
1
解决办法
5498
查看次数

ValueError: 找不到匹配的函数来调用从 SavedModel 加载

我正在尝试加载tf-agents我通过以下方式保存的策略

try:
    PolicySaver(collect_policy).save(model_dir + 'collect_policy')
except TypeError:
    tf.saved_model.save(collect_policy, model_dir + 'collect_policy')
Run Code Online (Sandbox Code Playgroud)

try/except 块的快速解释:最初创建策略时,我可以通过 保存它PolicySaver,但是当我再次加载它以进行另一次训练运行时,它是一个SavedModel,因此无法通过 保存PolicySaver

这似乎工作正常,但现在我想使用此策略进行自我播放,因此我self.policy = tf.saved_model.load(policy_path)在我的 AIPlayer 类中加载了该策略。但是,当我尝试将其用于预测时,它不起作用。这是(测试)代码:

def decide(self, table):
    state = table.getState()
    timestep = ts.restart(np.array([table.getState()], dtype=np.float))
    prediction = self.policy.action(timestep)
    print(prediction)
Run Code Online (Sandbox Code Playgroud)

table传递给函数包含了游戏的状态和ts.restart()功能是从我的自定义pyEnvironment拷贝,因此时间步长的构造完全相同的方式,因为它会在环境中。但是,我收到该行的以下错误消息prediction=self.policy.action(timestep)

ValueError: Could not find matching function to call loaded from the SavedModel. Got:
  Positional arguments (2 total):
    * TimeStep(step_type=<tf.Tensor 'time_step:0' shape=() dtype=int32>, reward=<tf.Tensor 'time_step_1:0' shape=() dtype=float32>, discount=<tf.Tensor 'time_step_2:0' shape=() …
Run Code Online (Sandbox Code Playgroud)

python tensorflow tensorflow-agents

6
推荐指数
1
解决办法
3037
查看次数

Android:URL.createObjectURL 无法正常工作(无法加载,因为未找到支持的源。)

我正在尝试播放存储在 Meteor Android 应用程序的 LocalForage 中的音频文件。

LocalForage.getItem(track_id, (err, value)=>{
    if(err)
        throw err;
    //the loaded value is an arraybuffer of an m4a file
    let blob = new Blob([value]);
    let url = (window.URL || window.webkitURL || window || {}).createObjectURL(blob);
    let testAudio = new Audio(url);
    testAudio.play().then(()=>{console.log("play successful")}).catch((err)=>{console.error(err)});
});
Run Code Online (Sandbox Code Playgroud)

之前,我将 url 传递给 Howler.js 的实例,但为了更容易理解发生的情况,我添加了 testAudio。

在浏览器 (Chrome) 中测试时,代码可以正常工作。URL 已创建并且音频正在播放。

然而,Android(使用 Chromium 作为所有 Meteor Android 应用程序)似乎不喜欢我的方法:创建对象 URL 时,Chromium 返回如下 URL:

blob:http%3A//localhost%3A12128/4de4516a-2989-4e99-9269-0beff4517fc4
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,这不是一个可用的 URL,即使我这样做

url = url.replace(/%3A/g, ':');
Run Code Online (Sandbox Code Playgroud)

控制台输出结果是

DOMException: Failed to load because no supported …
Run Code Online (Sandbox Code Playgroud)

javascript android blob chromium meteor-react

5
推荐指数
1
解决办法
5295
查看次数

节点错误在远程服务器上产生 /bin/sh ENOENT

好的,我知道关于这个主题有多个问题,我阅读了其中的大部分内容,但没有任何帮助。

我正在尝试让节点服务器定期运行 python 脚本。为此,我有以下代码:

const
    { exec } = require('child_process');
const fs = require('fs');


let config = [
{
    "title": "My Python Script",
    "description": "A script that can scrape website data",
    "command": "python3 collect_data.py",
    "dir": "../file_folder",
    "minutesBetweenExecution": 60
}
];



const intervals = [];


function startCronjobs() {
    while (intervals.length > 0) {
        clearInterval(intervals.pop());
    }

    console.log("Starting cronjobs...")

    for (let i = 0; i < config.length; i++) {
        const cron = config[i];
        const func = () => {
            exec(cron.command, { cwd: cron.dir, …
Run Code Online (Sandbox Code Playgroud)

python node.js

5
推荐指数
1
解决办法
4434
查看次数

如何通过 Chakra UI 使用 Nextjs 13 中的服务器组件

我正在尝试在 Chakra UI 中使用 React Server 组件(使用 NextJS 13),但我认为这还不可能。

\n

来自 Chakra UI 文档 ( https://chakra-ui.com/getting-started/nextjs-guide ):\n在此输入图像描述

\n

在我的示例中,我想获取服务器组件中的数据,然后渲染它

\n

\r\n
\r\n
import { Text } from "@chakra-ui/react";\n\nasync function getData() {\n  const res = await fetch("http://localhost:3000/api/products");\n  if (!res.ok) {\n    throw new Error("Failed to fetch data");\n  }\n\n  return res.json();\n}\n\nexport default async function Page() {\n  const data = await getData();\n  return <Text>{data.length}</Text>;\n}
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

正如预期的那样,我收到一个错误:

\n
\n

./node_modules/@chakra-ui/accordion/dist/chunk\xe2\x80\x94JDQBKIKM.mjs\nReactServerComponentsError:\n您正在导入需要 useState 的组件。它仅在客户端组件中工作,但其父组件都没有标记为“使用客户端”,因此默认情况下它们是服务器组件。

\n
\n

因为我试图在服务器端组件中仅导入客户端兼容组件(文本)。

\n

有什么解决办法吗?

\n

node.js reactjs chakra-ui next.js13

5
推荐指数
1
解决办法
5220
查看次数

Next-auth:虽然从 getServerSideProps 传递,但页面的属性未定义

我试图将我从getSession(使用next-auth)获得的会话作为道具传递给页面。我知道我可以useSession()在组件中使用,但根据我的理解,这应该也可以工作,但我不明白为什么它不能。

这似乎是与这个问题类似的问题,但没有答案。

这是我的非常基本的pages/settings.tsx

import { Card, CardContent, Typography } from "@mui/material";
import { User } from "@prisma/client";
import { GetServerSideProps, NextPage } from "next";
import { getSession } from "next-auth/react";

interface SettingsProps {
  user: User,
}

const Settings : NextPage<SettingsProps> = ({user})=>{
  // in here, user is always undefined...
  return (
    <Card>
      <CardContent>      
        <Typography variant="h3">Settings</Typography>
        <Typography>UserId: {user.id}</Typography>
        <Typography>Created: {(new Date(user.createdAt)).toLocaleDateString()}</Typography>
      </CardContent>
      
    </Card>
  );
};

export const getServerSideProps: GetServerSideProps<SettingsProps> =  async …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs next.js next-auth

3
推荐指数
1
解决办法
2692
查看次数

为什么接口扩展 Record&lt;string, ...&gt; 允许数字键?

我正在尝试找到一种相对通用的方法来输入 POST 正文以及结合其 API 路由(在 nextjs 应用程序中)返回的响应。

为此,我希望编译器强制我向所有 API 路由添加一个body类型和一个return类型,这是我通过以下接口实现的:

export interface PostTypeMapping extends Record<string, {body: unknown, return: unknown}> {
  "/api/taskCompletions": {body: PostCompletionBody, return: void},
  "/api/task": {body: PostTaskBody, return: void},
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很好。我可以在我的 API 路由中使用这种类型,如下所示:

 async (req, res: NextApiResponse<PostTypeMapping["api/task"]["return"]>) => {
  //...
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试编写一个自动从 URL 推断 POST 正文和返回类型的包装器时,我在以下行中收到错误await fetch(url,

“keyof PostTypeMapping”类型的参数不可分配给“RequestInfo”类型的参数。类型“number”不可分配给类型“RequestInfo”

export async function fetchPost<T extends keyof PostTypeMapping>(url: T, body: PostTypeMapping[T]["body"]): Promise<PostTypeMapping[T]["return"]> {
  try {
    const res = await fetch(url, { // <- The error …
Run Code Online (Sandbox Code Playgroud)

generics typescript

1
推荐指数
1
解决办法
647
查看次数

无法将`[Int]'与`Integer - > Int'匹配,但在GHCI中有效

我是Haskell的新手,所以这个问题对于大多数Haskell程序员来说应该是相当简单的:我有一个函数digits :: Integer -> [Int]可以将整数转换为其数字列表(123到[1,2,3]).现在得到我sum $ digits 123在ghci中输入的那些数字的总和,一切正常,它输出6.然而,一旦我在文件中创建函数如下,我得到一个错误.这可能与ghci推断123的类型这一事实有关,但这还不够,所以我可以解决问题.

文本文件中的函数:

digitalSum :: Integer -> Int
digitalSum = sum $ digits
Run Code Online (Sandbox Code Playgroud)

和错误:

* Couldn't match type `[Int]' with `Integer -> Int'
  Expected type: Integer -> Integer -> Int
    Actual type: Integer -> [Int]
* In the second argument of `($)', namely `digits'
  In the expression: sum $ digits
  In an equation for `digitalSum': digitalSum = sum $ digits
Run Code Online (Sandbox Code Playgroud)

haskell

0
推荐指数
1
解决办法
297
查看次数