不语却知心

文章 评论 浏览 30

不语却知心 2025-02-20 19:27:24

没有错误,我只是没有正确阅读文档。我假设 faker.date.date.birthdate({max:70,min:1})会理解 70 1 年龄很高,但是方法默认情况下认为它们实际上是数年的时间,因此可以想象我想要一年 0001 和年份 0070 之间的任何东西。

我需要将模式:'age'添加到选项:

let date = faker.date.birthdate({ max: 70, min: 1, mode: 'age' });
// 1965-02-05T20:58:06.207Z
date.getFullYear()
// 1965

默认情况下, mode 设置为

There's no bug, I just wasn't reading the docs correctly. I assumed faker.date.birthdate({ max: 70, min: 1 }) would understand 70 and 1 to be ages, but the method by default thinks they're actually years, so it's imagining that I want anything between the year 0001 and the year 0070.

I needed to add mode: 'age' to the options:

let date = faker.date.birthdate({ max: 70, min: 1, mode: 'age' });
// 1965-02-05T20:58:06.207Z
date.getFullYear()
// 1965

By default, mode is set to year.

在设置“ max”和“ min”时,我如何从fakerjs date.birthdate()获得四位数的年份

不语却知心 2025-02-20 11:30:31

正如您尝试过的那样,可以用pandas和滚动 ,尽管它有点涉及。有可能有一些简单的解决方案,但以下至少应起作用。

首先,从数据创建数据框。我们将2个零(比群集之间的最小零数少1个)到数据框的开始和结尾,以确保末端没有群集。这简化了以后的逻辑。

data = [0,0,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,0,0,0,1,1,1]
df = pd.DataFrame({'val': [0,0] + data + [0,0]})

现在,我们在数据框架上计算窗口大小3和min_periods 3的滚动总和。这将在开始时给出2个NAN(对于我们的填充零值)。我们考虑到任何地方的总和高于1,并根据这些值分组为组,根据这些值,使用 diff cumsum cumsum

df['sum'] = df.rolling(window=3, min_periods=3).sum()
df['group'] = (df['sum'] > 0).diff().cumsum().bfill()

一个奇数将是一个集群。但是每个行都标记了2行。我们将其删除并使用 groupby 应用 apply

def adjust_group_value(x):
    group = x['group'].iloc[0]
    if group % 2 == 0:
        x['new_val'] = 0
    else:
        x['new_val'] = group // 2 + 1
        x['new_val'].iloc[-2:] = 0
    return x
     
df = df.groupby('group').apply(adjust_group_value)
df = df.iloc[2:-2]  # remove the padded 0s at the start and end

结果(保留所有中间列以说明过程):

    val  sum  group  new_val
2     0  0.0    0.0      0.0
3     0  0.0    0.0      0.0
4     0  0.0    0.0      0.0
5     1  1.0    1.0      1.0
6     1  2.0    1.0      1.0
7     1  3.0    1.0      1.0
8     1  3.0    1.0      1.0
9     0  2.0    1.0      0.0
10    0  1.0    1.0      0.0
11    0  0.0    2.0      0.0
12    1  1.0    3.0      2.0
13    1  2.0    3.0      2.0
14    0  2.0    3.0      2.0
15    1  2.0    3.0      2.0
16    0  1.0    3.0      2.0
17    1  2.0    3.0      2.0
18    0  1.0    3.0      0.0
19    0  1.0    3.0      0.0
20    0  0.0    4.0      0.0
21    0  0.0    4.0      0.0
22    1  1.0    5.0      3.0
23    1  2.0    5.0      3.0
24    1  3.0    5.0      3.0

可以使用最终的群集ID来获得 df ['new_val']。astype(int).values

[0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 3, 3, 3]

As you have tried, this can be done with pandas and rolling, although its a bit involved. It's possible that there is some simpler solution but the below should work at least.

First, create the dataframe from the data. We append 2 zeros (1 less than the minimum number of zeros between clusters) to the start and end of the dataframe to make sure that there is no cluster at the ends. This simplifies the later logic.

data = [0,0,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,0,0,0,1,1,1]
df = pd.DataFrame({'val': [0,0] + data + [0,0]})

Now, we compute the rolling sum on the dataframe with window size 3 and min_periods 3. This will give 2 nans at the start (for our padded zero values). We consider anywhere the sum is above 1 and divide the dataframe into groups depending on these values using diff and cumsum:

df['sum'] = df.rolling(window=3, min_periods=3).sum()
df['group'] = (df['sum'] > 0).diff().cumsum().bfill()

Any group with an odd number will be a cluster. But there are 2 extra rows marked for each. We remove these and assign the correct cluster id using a custom function with groupby and apply:

def adjust_group_value(x):
    group = x['group'].iloc[0]
    if group % 2 == 0:
        x['new_val'] = 0
    else:
        x['new_val'] = group // 2 + 1
        x['new_val'].iloc[-2:] = 0
    return x
     
df = df.groupby('group').apply(adjust_group_value)
df = df.iloc[2:-2]  # remove the padded 0s at the start and end

Result (all intermediate columns are kept to illustrate the process):

    val  sum  group  new_val
2     0  0.0    0.0      0.0
3     0  0.0    0.0      0.0
4     0  0.0    0.0      0.0
5     1  1.0    1.0      1.0
6     1  2.0    1.0      1.0
7     1  3.0    1.0      1.0
8     1  3.0    1.0      1.0
9     0  2.0    1.0      0.0
10    0  1.0    1.0      0.0
11    0  0.0    2.0      0.0
12    1  1.0    3.0      2.0
13    1  2.0    3.0      2.0
14    0  2.0    3.0      2.0
15    1  2.0    3.0      2.0
16    0  1.0    3.0      2.0
17    1  2.0    3.0      2.0
18    0  1.0    3.0      0.0
19    0  1.0    3.0      0.0
20    0  0.0    4.0      0.0
21    0  0.0    4.0      0.0
22    1  1.0    5.0      3.0
23    1  2.0    5.0      3.0
24    1  3.0    5.0      3.0

The final cluster ids can be obtained with df['new_val'].astype(int).values:

[0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 3, 3, 3]

与窗口聚类的1D向量

不语却知心 2025-02-20 00:53:41

在任何Posix Awk中,都不更改其余字段之前或之后的任何间距:

awk 'NR>775{sub(/([[:space:]]+[^[:space:]]+){4}[[:space:]]*$/,"")} 1' file

In any POSIX awk, without changing any of the spacing before/after or between the remaining fields:

awk 'NR>775{sub(/([[:space:]]+[^[:space:]]+){4}[[:space:]]*$/,"")} 1' file

从特定行Linux开始删除最后四列

不语却知心 2025-02-19 21:10:03

我通过使用SVG和内部的附加方法解决了它。

I solved it by using append for svg and inner.

d3.js选择不起作用。不确定为什么不

不语却知心 2025-02-19 07:47:46

#< void> display> display 函数的返回值,因此'(#< void>#< void> void> void< void< void&##< void&## #< void>) map content> content ( map 对于都产生结果列表,因此返回相同的结果)。

如果要对列表中的每个元素运行某些副作用,则应该使用

另外,请勿使用 define 内部 define ,使用

#lang racket
(require racket/string)
(require racket/file)

(define (print-file filename) 
  (for-each displayln
            (file->lines filename)))

(displayln "Now line by line with for-each and displayln:")
(print-file "../file-to-be-read.short")

#<void> is return value for display function, so '(#<void> #<void> #<void> #<void> #<void> #<void> #<void>) is result of map display over content (map and for both produce list of results, so for returns the same result).

If you want to run some side effect for each element in the list, you should rather use for-each.

Also, don't use define inside define, use let for introducing local variables, and consider using displayln:

#lang racket
(require racket/string)
(require racket/file)

(define (print-file filename) 
  (for-each displayln
            (file->lines filename)))

(displayln "Now line by line with for-each and displayln:")
(print-file "../file-to-be-read.short")

读取文件 - (#&lt; void&gt; ...#&lt; void&gt;)来自哪里?

不语却知心 2025-02-18 21:43:31

您的评论

#libsomething取决于dlopen/dlsym ...所以我必须在此处添加dl

揭示了问题的 core :它是 libsomething 需要链接使用 dl ,因此其 find_package(某物)应该关心这一点。缺乏这种联系是库本身中的缺陷(即一个错误)。

如果您是库的作者,请修复它。
如果图书馆的作者接受Bugreports,请填写有关给定问题的一个。

如果修复库不是您的选项,那么您可以在项目中“修复” find_package 的结果:

find_package(something)
# Created imported target misses linkage with 'dl' library.
# Add it here.
target_link_libraries(something::something INTERFACE ${CMAKE_DL_LIBS})

add_executable(exe main.cc)
# Now we can use the library in a simple way
target_link_libraries(exe PRIVATE something::something)

上面的代码依赖于事实, sometsing ::某种:: sometsing stays find_package(sometsing)提供,是导入的目标,表示库文件。因此,我们可以向其添加所需的链接。

Your comment

# libsomething depends on dlopen/dlsym... so I have to add dl here

reveals the core of the problem: It is libsomething needs linkage with dl, so its find_package(something) should care about that. The absence of that linkage is a deficiency (that is, a bug) in the library itself.

If you are the author of the library, then fix it.
If the author of the library accepts bugreports, then fill the one about given problem.

If fixing the library is not an option for you, then you could "fix" result of find_package in your project:

find_package(something)
# Created imported target misses linkage with 'dl' library.
# Add it here.
target_link_libraries(something::something INTERFACE ${CMAKE_DL_LIBS})

add_executable(exe main.cc)
# Now we can use the library in a simple way
target_link_libraries(exe PRIVATE something::something)

The above code relies on the fact, that something::something, provided by find_package(something), is an IMPORTED target, denoting the library file. So we can add required linkage to it.

find_package的cmake链接库,系统lib以错误的顺序

不语却知心 2025-02-18 19:41:22

这是一个没有异步/等待的解决方案:在第一个成功的呼叫中进行第二个Axios呼叫。您需要使用保留在VUE实例上:

this.$axios.get('http://first-url.call').then((response) => {
    console.log(response.request.res.responseUrl)
    let postUrl = response.request.res.responseUrl

    this.$axios.post(postUrl).then((response) => {
        console.log(response);
    }).catch(function(error){
        console.log(error)
    });
}).catch((error) =>{
    console.log(error)
});

Here is a solution without async/await: Make the second axios call within the first successful call. You need to use arrow functions for this so you keep the correct this on your Vue instance:

this.$axios.get('http://first-url.call').then((response) => {
    console.log(response.request.res.responseUrl)
    let postUrl = response.request.res.responseUrl

    this.$axios.post(postUrl).then((response) => {
        console.log(response);
    }).catch(function(error){
        console.log(error)
    });
}).catch((error) =>{
    console.log(error)
});

在第二Axios呼叫中使用第一Axios的响应

不语却知心 2025-02-18 02:05:32

这里的大多数答案是关于如何根据其先前的值更新状态的,但我不明白这与问题有关

USESTATE SET方法没有立即反映更改


反应18

USESTATE是异步的:

当触发某个代码,发生某个代码,发生的事件发生时,代码开始运行,当它finshes finshes时,React会检查是否有状态更新,以及它是否存在 usestate 挂钩的值已更新,这导致了一个新渲染,其中新值可用。

const [example,setExemple] = useState("")
//...
<button
  onClick={() => {
    const newValue = "new";
    setExample(newValue);
    console.log(example); // output "" and this is normal, because the component didn't rerenderd yet so the new value is not availabe yet
  }}
>
  Update state
</button>

假设我们有一个方案如果我们的状态取决于另一个状态,例如,我们要根据示例的新值每次更新时进行API调用,然后将响应中的数据存储在另一个状态<代码> anotherexample 。
为了实现,我们有两种方法:

1。使用 newValue 的值:

<button
  onClick={async () => {
    const newValue = "new";
    const response = await axios.get(`http://127.0.0.1:5000/${newValue}`);
    setExample(newValue);
    setAnotherExample(response.data);
  }}
>
  test
</button>

因为您知道示例将接收此值,因此可以直接基于它创建逻辑。

2。触发a useffect 每次运行 示例在其依赖项数组中:

<button
  onClick={() => {
    const newValue = "new";
    setExample(newValue);
  }}
>
  test
</button>
useEffect(() => {
 async function test(){
  const response = await axios.get(`http://127.0.0.1:5000/${example}`);
  setAnotherExample(response.data);
 } 
 test();
}, [example])

因此,当示例使用事件函数更新时渲染一旦完成, useffect 将运行,因为示例的值与上次渲染和由于它是一种新的不同渲染,因此在此处可用示例 USESTATE HONK的新值。

注意: 使用效果挂钩在第一个安装座期间都会运行。

哪种方法更好?

  • 虽然第一种方法将使所有工作都在一个渲染中(一种更好的方法)“ react组多个状态更新到单个重新渲染中以获得更好的性能”,第二种方法将做到这一点在两个渲染中,第一个是示例更新时,第二个是 anotherexample 从内部更新 useffeft useeffect

  • 更新的,因为组件仅在新的时重新读取器 usestate 挂钩的值与旧的值不同,因此,当 newValue 等于示例>示例时,组件将不会启用,因此 usausefect 将不会运行, anotherexample 将不会更新

Most of the answers here are about how to update a state based on its previous value, but I don't understand how that relates to the question

The useState set method is not reflecting a change immediately


React 18

useState is asynchronous:

When an event that triggers a certain code, occurs, the code starts running, and when it finshes, react will check if there was a state update and if it is the case, only then the value of the useState hook is updated and this leads to a new render in which the new value is availabe.

const [example,setExemple] = useState("")
//...
<button
  onClick={() => {
    const newValue = "new";
    setExample(newValue);
    console.log(example); // output "" and this is normal, because the component didn't rerenderd yet so the new value is not availabe yet
  }}
>
  Update state
</button>

Supposing we have a scenario where we have a state which depends on another state, for example we want to make an API call based on the new value of example every time it is updated and then store the data from response in another state anotherExample.
to achieve so we have two ways:

1. use the value of newValue:

<button
  onClick={async () => {
    const newValue = "new";
    const response = await axios.get(`http://127.0.0.1:5000/${newValue}`);
    setExample(newValue);
    setAnotherExample(response.data);
  }}
>
  test
</button>

since you know that example will receive this value, you can create your logic based on it directly.

2. trigger a useEffect to run each time example is updated by including example in its dependency array:

<button
  onClick={() => {
    const newValue = "new";
    setExample(newValue);
  }}
>
  test
</button>
useEffect(() => {
 async function test(){
  const response = await axios.get(`http://127.0.0.1:5000/${example}`);
  setAnotherExample(response.data);
 } 
 test();
}, [example])

so when example is updated with the event function the component rerenders, we are now in a new different render that once finished, useEffect will run because the value of example is different from what is was during the last render, and since it is a new different render, the new value of example useState hook is available here.

Note: the useEffect hook will run anyway during the first mount.

Which approach better?

  • while the first method will make all the work in one render ???? (a better approach) "React groups multiple state updates into a single re-render for better performance" the second method will do it in two renders, the first when example is updated and the second when anotherExample is updated from inside useEffect ????

  • since the component only rerenders when the new value of a useState hook is different from the old one, so when newValue is equal to example the component will not rerender so the useEffect will not run and anotherExample will not be updated ???? (a better approach), however in the first method the API is called anyway and we don't want to do that if there is no need also if this happens anotherExample will be updated (anotherExample will receive the same data it already contains because it is the same REQUEST since newValue is equal to example) but if the response in an object or an array then, Object.is method (that the useState hook utilizezs), cannot detect if the new value is equal to the previous one, therefore, the component will rerender ????

Conclusion:

As it is mentioned above, each one has its advantage, so it depends on the use case.

the second method is more recommended, however the first can be more performant in some cases, for example when you are sure the code will only run when newValue gets a new value using onChange, or maybe when you want to use some other local variables that you will no longer have access to from inside useEffect

USESTATE SET方法不是立即反映更改

不语却知心 2025-02-17 17:56:35

看来您当前在BigQuery沙箱中,您能确认是否有横幅 sandbox 文本上方的横幅?

如果是这种情况,那么BigQuery Sandbox就像资源的预览状态,而无需设置计费帐户。它受到

  • 限制,
  • 不支持流媒体数据,
  • 不支持数据传输服务等等(上面的超链接上列出)。

要充分利用BigQuery并访问您必须启用项目帐单的表Explorer选项卡。请访问此链接以获取有关升级的更多信息,从 bigquery sandbox

It appears you are currently in the BigQuery Sandbox, Can you confirm if there is a banner with highlighted SANDBOX text above your Explorer tab?

If that is the case, BigQuery Sandbox is like a preview state of the resource without setting up a billing account. It is subjected to limitations such as:

  • All datasets have the default table expiration time,
  • Streaming data is not supported
  • Data Transfer Service is not supported and etc(Listed on the hyperlink above.)

To fully utilize BigQuery and access the Table Explorer tab you must enable billing for your project. Please visit this link for more information about upgrading from BigQuery Sandbox

GCP- BQ Table Explorer在哪里?

不语却知心 2025-02-17 12:51:41

usestate 在每个渲染上都触发。但是在第一个渲染之后,该价值被忽略了。

来自 docs

您可能想知道:为什么USESTATE不命名Createstate? “创建”不是很准确,因为状态仅在我们的组件渲染第一次时创建。在接下来的渲染过程中,Usestate为我们提供了当前状态。

useState is triggered on every render yes. But the value is disregarded after the very first render.

From the docs:

You might be wondering: why is useState not named createState instead? “Create” wouldn’t be quite accurate because the state is only created the first time our component renders. During the next renders, useState gives us the current state.

setstate之后的反应会重新执行我们的usestate吗?

不语却知心 2025-02-17 11:58:56

解决此问题的最简单方法就是简单地忽略它。它不会以任何方式影响您的代码,但是它会忽略错误。忽略 node_modules 文件夹

// tsconfig.json
{
  // ...
  "exclude": ["node_modules"] // any other ignored folders/files can be provided here
  // ...
}

The easiest way to fix this, is by simply ignoring it. It will not affect your code in any way, it will however ignore the error. Ignore the node_modules folder

// tsconfig.json
{
  // ...
  "exclude": ["node_modules"] // any other ignored folders/files can be provided here
  // ...
}

Discord.js有错误的库。我该如何解决这个问题

不语却知心 2025-02-17 08:31:09

我做了叉子petitevue

        var vz = {
            count: 0,
            a1: "foo",
            inc: function () {
                this.count++
            }
        }

        var state = ppvue.createApp(vz).mount();
        
        
        setTimeout(() => { vz.inc() }, 3000);

I did fork petitevue to ppvue..but apparently not as simple as returning ctx.scope

This did the trick for me though.

        var vz = {
            count: 0,
            a1: "foo",
            inc: function () {
                this.count++
            }
        }

        var state = ppvue.createApp(vz).mount();
        
        
        setTimeout(() => { vz.inc() }, 3000);

访问或修改Petite-vue数据外应用程序

不语却知心 2025-02-17 07:59:03
onTap: () {
                  controller.selectedIndex.value = index;
                },);

设置索引元素而不是1
控制器是初始化的?

onTap: () {
                  controller.selectedIndex.value = index;
                },);

setup index element not 1
the controller is initialized how?

为什么我使用getX在Flutter ListView中不起作用?

不语却知心 2025-02-17 02:07:40

在打开CodeBlocks时,在任务栏中闪烁图标并不是损害IDE操作的问题。
是由于加载CodeBlocks使用的wxwidgets库。
该问题已在开发版本(夜间构建)中解决。

Flashing the icon in the task bar, while opening CodeBlocks, is not a problem that compromises the operation of the IDE.
Is due to loading the wxWidgets libraries used by CodeBlocks.
The issue has been fixed in the developing version (Nightly builds).

打开时,代码:: Block将继续在任务栏中闪烁

不语却知心 2025-02-16 22:40:36

我找到了在Palantir Foundry文件夹中保存文件的解决方案:

def upload_file(token: str, target_filename: str, parent_folder_rid: str, content_type: str, raw_data) -> None:

header = {'content-type': "application/json",
          'authorization': f"Bearer {token}"}

target = urllib.parse.quote(tgt_filename, safe='')
response = requests.post(f"{blobster}salt?filename={target}&parent={parent_folder_rid}",
                         headers=header,
                         verify=True,
                         data=raw_data)
return response.json()

I found a solution for saving files in a Palantir Foundry folder:

def upload_file(token: str, target_filename: str, parent_folder_rid: str, content_type: str, raw_data) -> None:

header = {'content-type': "application/json",
          'authorization': f"Bearer {token}"}

target = urllib.parse.quote(tgt_filename, safe='')
response = requests.post(f"{blobster}salt?filename={target}&parent={parent_folder_rid}",
                         headers=header,
                         verify=True,
                         data=raw_data)
return response.json()

在Slate应用程序中显示在Palantir铸造厂的数据集中存储的PDF文件

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文