问题列表 - 第318128页

如何在 Parallel.ForEachAsync 中使用 CancellationTokenSource

拥有这个处理程序:

public async Task<Result> Handle(MyQuery request, CancellationToken cancellationToken)
{
     var cancellationTokenSource = new CancellationTokenSource();

     await Parallel.ForEachAsync(myList, async (objectId, _) =>
     {
         var result = await _service.GetObject(objectId);

         if (result.Any())
         {
             cancellationTokenSource.Cancel();
         }
     });

     if (cancellationTokenSource.IsCancellationRequested) return Result.Fail("Error message.");

     return Result.Ok();
}
Run Code Online (Sandbox Code Playgroud)

这可行,但想知道我CancellationTokenSource在这里使用是否正确?

.net c# async-await cancellationtokensource parallel.foreachasync

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

查找奇数长度子串的总数

我正在尝试编写一个函数来计算给定字符串中奇数长度子字符串的总数。例如,对于字符串“abcde”,仅考虑奇数长度的子字符串([a, abc, abcde, b, bcd, c, cde, d, e]),输出应为 9。同样,对于字符串“aaa”,输出应为 4 ([a, aaa, a, a])。我很感激任何关于如何在 java 中有效实现这一点的见解。

我无法想出有效的解决方案。

public static int countOddLengthSubstrings(String s) {
        int count = 0;
        int n = s.length();
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                if ((j - i + 1) % 2 != 0) { // Checking if length is odd
                    count++;
                }
            }
        }
        return count;
    }
Run Code Online (Sandbox Code Playgroud)

java algorithm

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

C++ 代码在不同的优化标志下表现不同

有四个文件,header.hA.cppB.cppmain.cpp

// header.h
struct test {
  static inline int get();
};
Run Code Online (Sandbox Code Playgroud)
// a.cpp
#include "header.h"
int testA() { return test::get(); }
int test::get() { return 0; }
Run Code Online (Sandbox Code Playgroud)
// b.cpp
#include "header.h"
int testB() { return test::get(); }
int test::get() { return 1; }
Run Code Online (Sandbox Code Playgroud)
// main.cpp
#include <cstdio>
int testA();
int testB();

int main() {
  printf("%d %d\n", testA(), testB());
}
Run Code Online (Sandbox Code Playgroud)

编译时g++ -o main A.cpp B.cpp main.cpp -O0二进制输出两个相同的数字,而-O3始终输出0 1 …

c++ language-lawyer

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

我可以让 MSVC 对“C4127:条件表达式为常量”不那么严格吗

我正在使用 MSVC 16 2019,并打开了许多警告,包括 C4127:条件表达式是常量。但是,我的代码如下所示:

template <bool B>
void foo(int x) {
    if (B && x == 0) { do_stuff(); }
    do_other_stuff();
}
Run Code Online (Sandbox Code Playgroud)

...当 B 为 false 时会触发警告。

我想一般保留此错误,但我不希望它在条件表达式的常量性仅由于模板实例化时无缘无故地发出警告。

注意:这个问题是相关的,但是 - 代码不会(显着)改变,所以这不是我要问的。C++17 中也没有。

c++ compiler-warnings c++11 c4127 visual-studio-2019

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

为什么内置函数中是“None”.__dict__

以下是正确的:

  • 'None' in keyword.kwlist
  • 'None' in builtins.__dict__ # import builtins

我的理解:

  • xPython通过获取对象来评估标识符builtins.__dict__[x]
  • Python evals 关键字x以一种特殊的方式取决于是x什么

这意味着 Python 将关键字 evals为类型(被保留)None的值,而不使用. 那么为什么包含?NoneTypebuiltins.__dict__builtins.__dict__'None'

(同样的问题适用于TrueFalse

python keyword python-builtins

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

如何使用 chrono::parse 向流写入/读取 std::chrono::zoned_seconds ?

我正在尝试将一个chrono::zoned_seconds对象作为文本写入文件,然后检索它并chrono::zoned_seconds稍后构造另一个对象。如何才能以相当有效的方式完成此任务?

我认为下面的代码片段没有显示正确的结果:

#include <fstream>
#include <print>
#include <chrono>
#include <format>
#include <string>
#include <sstream>


int main()
{
    {
        std::ofstream file("data.txt");
        if (!file) {
            std::println( "Unable to open file.\n" );
            return 1;
        }

        auto now = std::chrono::system_clock::now();
        const std::chrono::zoned_seconds zs { "America/New_York", std::chrono::time_point_cast<std::chrono::seconds>( now ) };

        std::format_to(std::ostreambuf_iterator<char>(file), "{:%F %T %Z}", zs);
        std::println( "{:%F %T %Z}", zs ); // correct time
    }

    {
        std::ifstream file("data.txt");
        if (!file) {
            std::println( "Unable to open file.\n" );
            return 1;
        }

        std::string …
Run Code Online (Sandbox Code Playgroud)

c++ fstream datetime-format c++-chrono c++23

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

Why does an instance of Test&lt;?&gt; accept non-null objects in the constructor?

The wildcard ? in generics represents an unknown type and accepts only null. However, in the following example, the constructor accepts (for example) a String object, even though I have declared an instance of Test<?>.

public class Test<T> {
    private T object;
    public Test(T object) {
        this.object = object;
    }
    public void set(T object) {
        this.object = object;
    }
    public static void main(String[] args) {
        Test<?> test = new Test<>("Test");    // compiles fine
        //test.set("Test");    // compiler error
    } …
Run Code Online (Sandbox Code Playgroud)

java generics wildcard

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