- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
尝试使用 .csv
文件中的值构建请求正文,但我的点数组未更新。我已经为 on()
函数内部和末尾的点数组完成了 console.log()
,并且值按预期存在。但我在 on()
之外console.log,它说数组是空的。
我知道这是一个范围问题,但对 Node.js 不太熟悉,所以无法弄清楚。谢谢。
// Detect anomalies in your spreadsheet
var points = []
var dict = {}
// Read the .csv file, convert date to Date object and number to float.
readline.createInterface({
input: fs.createReadStream(CSV_FILE),
terminal: false
}).on('line', function(line) {
var row = line.split(",")
dict[new Date(row[0])] = parseFloat(row[1])
points.push(dict)
});
// Create request body for API call
let body = { series: points, granularity: 'hourly' }
// Make the call
anomalyDetectorClient.entireDetect(body)
.then((response) => {
for (item in response.isAnomaly) {
if (item) {
console.log("An anomaly was detected from the series.")
console.log("Value: " + response.expectedValues[response.indexOf(item)])
}
}
}).catch((error) => {
console.log(error)
})
更新:
我正在尝试将异步函数移至 on()
中,因此 points[]
中包含值...但请求中存在错误的正文,我的点数组每次推送时都会采用累积字典而不是新字典。因此,在我可以再次查看最后一个 on() 之外未更新的 points[]
之前,需要先解决这个问题。
当前代码,我将 API 调用移至最后一个 on()
函数中(之前它位于函数外部,前面有一个 await
):
async function main() {
let CSV_FILE = './request-data.csv'
// Detect anomalies in your spreadsheet
var points = []
// Read the .csv file
await readline.createInterface({
input: fs.createReadStream(CSV_FILE),
terminal: false
}).on('line', function(line) {
var row = line.split(",")
// Convert date to Date object and number to float.
var date = new Date(row[0])
var dict = {}
dict[date] = parseFloat(row[1])
points.push(dict)
console.log(points)
}).on('close', function() {
// Create request body for API call
let body = { series: points, granularity: 'hourly' }
console.log("Body series: " + body.series.timestamp + "Body granularity: " + body.granularity)
// Make the call
anomalyDetectorClient.entireDetect(body)
.then((response) => {
for (item in response.isAnomaly) {
if (item) {
console.log("An anomaly was detected from the series.")
console.log("Value: " + response.expectedValues[response.indexOf(item)])
}
}
}).catch((error) => {
console.log(error)
})
})
更新2:
在答案中使用新代码,出现新错误:正文系列:未定义正文粒度:每小时
这是什么意思?
{ 错误:时间点应按小时粒度均匀分布,间隔为 1 gr,缺失点比例应小于 10%,2018-03-01 00:00:00 至 2018-04-16 00:00:00 之间至少应有 994 个点,但得到了 47 个点。
因为主体对象看起来不错而感到困惑,但打印出错误:
{ Error: Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points.
at new RestError (C:\Users\v-wiazur\Desktop\Anomaly Detector\node_modules\@azure\ms-rest-js\dist\msRest.node.js:1399:28)
at C:\Users\v-wiazur\Desktop\Anomaly Detector\node_modules\@azure\ms-rest-js\dist\msRest.node.js:2494:37
at process._tickCallback (internal/process/next_tick.js:68:7)
code: 'InvalidSeries',
statusCode: 400,
request:
WebResource {
streamResponseBody: false,
url:
'https://winonaanomalydetector.cognitiveservices.azure.com/anomalydetector/v1.0/timeseries/entire/detect',
method: 'POST',
headers: HttpHeaders { _headersMap: [Object] },
body:
'{"series":[{"timestamp":"2018-03-01T00:00:00.000Z","value":32858923},{"timestamp":"2018-03-02T00:00:00.000Z","value":29615278},{"timestamp":"2018-03-03T00:00:00.000Z","value":22839355},{"timestamp":"2018-03-04T00:00:00.000Z","value":25948736},{"timestamp":"2018-03-05T00:00:00.000Z","value":34139159},{"timestamp":"2018-03-06T00:00:00.000Z","value":33843985},{"timestamp":"2018-03-07T00:00:00.000Z","value":33637661},{"timestamp":"2018-03-08T00:00:00.000Z","value":32627350},{"timestamp":"2018-03-09T00:00:00.000Z","value":29881076},{"timestamp":"2018-03-10T00:00:00.000Z","value":22681575},{"timestamp":"2018-03-11T00:00:00.000Z","value":24629393},{"timestamp":"2018-03-12T00:00:00.000Z","value":34010679},{"timestamp":"2018-03-13T00:00:00.000Z","value":33893888},{"timestamp":"2018-03-14T00:00:00.000Z","value":33760076},{"timestamp":"2018-03-15T00:00:00.000Z","value":33093515},{"timestamp":"2018-03-16T00:00:00.000Z","value":29945555},{"timestamp":"2018-03-17T00:00:00.000Z","value":22676212},{"timestamp":"2018-03-18T00:00:00.000Z","value":25262514},{"timestamp":"2018-03-19T00:00:00.000Z","value":33631649},{"timestamp":"2018-03-20T00:00:00.000Z","value":34468310},{"timestamp":"2018-03-21T00:00:00.000Z","value":34212281},{"timestamp":"2018-03-22T00:00:00.000Z","value":38144434},{"timestamp":"2018-03-23T00:00:00.000Z","value":34662949},{"timestamp":"2018-03-24T00:00:00.000Z","value":24623684},{"timestamp":"2018-03-25T00:00:00.000Z","value":26530491},{"timestamp":"2018-03-26T00:00:00.000Z","value":35445003},{"timestamp":"2018-03-27T00:00:00.000Z","value":34250789},{"timestamp":"2018-03-28T00:00:00.000Z","value":33423012},{"timestamp":"2018-03-29T00:00:00.000Z","value":30744783},{"timestamp":"2018-03-30T00:00:00.000Z","value":25825128},{"timestamp":"2018-03-31T00:00:00.000Z","value":21244209},{"timestamp":"2018-04-01T00:00:00.000Z","value":22576956},{"timestamp":"2018-04-02T00:00:00.000Z","value":31957221},{"timestamp":"2018-04-03T00:00:00.000Z","value":33841228},{"timestamp":"2018-04-04T00:00:00.000Z","value":33554483},{"timestamp":"2018-04-05T00:00:00.000Z","value":32383350},{"timestamp":"2018-04-06T00:00:00.000Z","value":29494850},{"timestamp":"2018-04-07T00:00:00.000Z","value":22815534},{"timestamp":"2018-04-08T00:00:00.000Z","value":25557267},{"timestamp":"2018-04-09T00:00:00.000Z","value":34858252},{"timestamp":"2018-04-10T00:00:00.000Z","value":34750597},{"timestamp":"2018-04-11T00:00:00.000Z","value":34717956},{"timestamp":"2018-04-12T00:00:00.000Z","value":34132534},{"timestamp":"2018-04-13T00:00:00.000Z","value":30762236},{"timestamp":"2018-04-14T00:00:00.000Z","value":22504059},{"timestamp":"2018-04-15T00:00:00.000Z","value":26149060},{"timestamp":"2018-04-16T00:00:00.000Z","value":35250105}],"granularity":"hourly"}',
query: undefined,
formData: undefined,
withCredentials: false,
abortSignal: undefined,
timeout: 0,
onUploadProgress: undefined,
onDownloadProgress: undefined,
proxySettings: undefined,
operationSpec:
{ httpMethod: 'POST',
path: 'timeseries/entire/detect',
urlParameters: [Array],
requestBody: [Object],
responses: [Object],
serializer: [Serializer] } },
response:
{ body:
'{"code":"InvalidSeries","message":"Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points."}\n',
headers: HttpHeaders { _headersMap: [Object] },
status: 400 },
body:
{ code: 'InvalidSeries',
message:
'Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points.' } }
最佳答案
您的阵列正在更新。如果您在 line
事件处理程序中执行 console.log(points)
,您将看到它每次都会累积日期。
问题在于您在填充数组之前在错误的位置查看数组。 readline 接口(interface)是异步的。因此,您调用 readline.createInterface() 并为 line 事件设置事件处理程序,然后您的代码就会继续运行。在 readline 操作完成其工作之前,您将立即调用 anomalyDetectorClient.entireDetect()
。
解决方案是等到 readline 接口(interface)完成读取整个文件并完全填充您的 points
数组,然后再尝试使用 points
数组。
这是一种方法,您可以在 readline 接口(interface)的 close
事件处理程序中处理 points
数组:
// Detect anomalies in your spreadsheet
var points = [];
var dict = {};
// Read the .csv file, convert date to Date object and number to float.
readline.createInterface({
input: fs.createReadStream(CSV_FILE),
terminal: false
}).on('line', function(line) {
var row = line.split(",");
let point = {
timestamp: new Date(row[0]),
value: parseFloat(row[1])
};
dict[point.date] = point.value;
points.push(point);
console.log(points);
}).on('close', function() {
// now we're done reading the file
console.log(points); // all the points are here
// now process the points
// Create request body for API call
let body = { series: points, granularity: 'hourly' };
// Make the call
anomalyDetectorClient.entireDetect(body).then((response) => {
for (let item in response.isAnomaly) {
if (item) {
console.log("An anomaly was detected from the series.")
console.log("Value: " + response.expectedValues[response.indexOf(item)])
}
}
}).catch((error) => {
console.log(error)
});
}).on('error', function(err) {
// handle errors here
console.log(err);
});
仅供引用,您真的确定应该在 response.isAnomaly 中使用 item
吗? in
不适用于数组,它适用于对象的属性。它对数组有点,有点适用,但它也不能工作很多次。 for/of
是专门为数组构建的,如 for (let item of response.isAnomaly) {...}
中所示。另外,对于数组,in
获取的是值的索引,而不是数组值。 of
获取通常是您想要的数组值。
关于node.js - readline.createInterface({}).on({}) 内的变量未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57504586/
这个问题在这里已经有了答案: What could be the reason that `require` doesn't work in some places? (3 个回答) 6 个月前关闭。
我正在使用读取行从维基百科获取一些文本。但读取行仅返回列表,而不是我想要的文本。有什么方法可以使用替代方案或解决我的问题吗? public class mediawiki { public s
我正在编写一小段代码,其中涉及使用子进程运行一个脚本来监听一些实时数据 这是我的代码: def subscriber(): try: sub = subprocess.Pope
我已包括: #include "stdio.h" #include #include 我的编译器包含标志 -lreadline 但我仍然收到错误消息: fatal error: 'readl
使用 Term::Readline::readline 停止无限循环的正确方法是什么? ? 这样我一个都看不懂 0 #!/usr/bin/env perl use warnings; use stri
标题比我的实际目标更具体: 我有一个使用 GNU Readline 的命令行程序,主要用于命令历史记录(即使用向上箭头检索以前的命令)和其他一些细节。现在,程序的输出似乎散布在用户的输入中,有时是可以
在 ipython 中,如果我按“esc”,然后按“enter”(可能还有其他字符?),读行会中断。我无法再使用“向上”键搜索命令历史记录,并且某些命令(例如 control-K)失败。 有没有办法在
我在使用 readlines() 和 readline() 返回值时遇到问题,但在使用 read() 时却没有。任何人都知道这是怎么发生的?欣赏一下 with open('seatninger.txt
标题比我的实际目标更具体: 我有一个使用 GNU Readline 的命令行程序,主要用于命令历史记录(即使用向上箭头检索以前的命令)和其他一些细节。现在,程序的输出似乎散布在用户的输入中,有时是可以
我正在编写一个聊天客户端,它必须在接收用户输入的同时输出接收到的消息。 到目前为止,我已经 fork 成两个独立的进程,其中一个继续监听套接字连接并用 printf 写出接收到的字符串。另一个使用 r
我在 NetworkStream 上使用 StreamReader,我只想读取一行或多行,而另一个数据是 byte array(如文件数据)我不想在 StreamReader 中读取该文件数据,例如我
我遇到了这两个 API,用于在 C# 的简单控制台应用程序中读取用户的输入: System.Console.ReadLine() System.Console.In.ReadLine() 这是一个我试
yum 我的系统显示已安装 readline rlwrap-0.41]$ sudo yum install readline Loaded plugins: fastestmirror, presto
我尝试做 this tutorial在 Rust 中,到目前为止,我在将 C 库连接到 Rust 时遇到了很多问题。 C 等效代码: #include #include #include #in
我正在寻找 web Python的标题中提到的命令及其区别;但是,我并不满足于对这些命令有完整的基本理解。 假设我的文件只有以下内容。 This is the first time I am posi
你如何在 F# 中使用 Console.Readline?与 Console.Writeline 不同,当我调用它时,它并没有受到尊重。 最佳答案 如果你使用 let s = Console.Read
在一次面试中,面试官问我为什么 readline() 比 Python 中的 readlines() 慢很多? 我回答的是readlines()需要多次读取,需要更多的开销。 不知道我的回答对不对。
要在 OSX Lion 上完全运行 ipython 需要什么?我试图让 ipython 与 readline 一起工作,但没有成功。 我的做法: (在虚拟环境中) pip install ipytho
在 Nodejs 文档中,我看到: import EventEmitter from 'events'; import { readFile } from 'fs'; import fs, { rea
我写了一个简单的应用程序: #include #include #include #include int main() { char *user_input; while(u
我是一名优秀的程序员,十分优秀!