小编Abh*_*kar的帖子

在外部修改并发集合时,流式传输是否安全?

我有一个ConcurrentLinkedQueue由多个线程访问的; 其中的对象是不可变的.在一个线程中,我需要一个数据快照,我正在通过调用stream它来完成.安全吗?我知道无干扰要求,但它似乎是在讨论从其中一个流操作(" 源流可能不是并发的流管道永远不应修改流的数据源 ")的修改,而不一定是外部的.此外,它ConcurrentLinkedQueue是专为并发访问而设计的,所以就是这样.

java concurrency multithreading java-8 java-stream

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

以编程方式解析 Thymeleaf 模板

我正在尝试使用 Thymeleaf 模板呈现 XML/JSON。我不想使用模板名称渲染视图,只想解析模板,如下所示。麻烦的是我得到的只是模板名称,而不是它的内容。

设置:

@Bean
SpringResourceTemplateResolver xmlTemplateResolver(ApplicationContext appCtx) {
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();

    templateResolver.setApplicationContext(appCtx);
    templateResolver.setPrefix("classpath:/templates/");
    templateResolver.setSuffix(".xml");
    templateResolver.setTemplateMode(XML);
    templateResolver.setCharacterEncoding(UTF_8.name());
    templateResolver.setCacheable(false);

    return templateResolver;
}

@Bean
SpringTemplateEngine templateEngine(ApplicationContext appCtx) {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.addTemplateResolver(xmlTemplateResolver(appCtx));

    return templateEngine;
}
Run Code Online (Sandbox Code Playgroud)

模板(src/main/resources/templates/breakfast-menu.xml):

<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
    <food>
        <name>${item['name']}</name>
        <price>${item['price']}</price>
        <description>${item['description']}</description>
        <calories>${item['calories']}</calories>
    </food>
</breakfast_menu>
Run Code Online (Sandbox Code Playgroud)

用法:

@Autowired
SpringTemplateEngine templateEngine;

someMethod() {
    Context context = new Context();
    context.setVariable("item", item);
    item.put("name", "Waffle");
    String content = templateEngine.process("breakfast-menu", context);

    // content == "breakfast-menu". WTH?
}
Run Code Online (Sandbox Code Playgroud)

使用 Thymeleaf 3.0.0.BETA01。

spring templates thymeleaf spring-boot

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

“从blah安装”对于docker push命令意味着什么?

我在构建日志中注意到一个奇怪的日志语句,该语句似乎只在第一次构建特定映像时才会显示。我在Docker文献中找不到对此的任何引用。我有兴趣知道这意味着什么。

The push refers to a repository [mycompany.com:5000/blah]
a35c50f48e25: Preparing
// more preparing
0c3170905795: Waiting
// more waiting
47a9d8491623: Mounted from foo
e856ece746ae: Mounted from foo
f2ec1bba02a6: Mounted from bar
6407c62d4add: Mounted from foo
0c3170905795: Mounted from bar
df64d3292fd6: Mounted from bar
5ed59af669b0: Pushed
a35c50f48e25: Pushed
Run Code Online (Sandbox Code Playgroud)

在上面的日志中,“从foo安装”是什么意思,为什么它仅在第一次出现?

docker

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

Python 类型弃用

最新的打字文档有很多弃用通知,如下所示:

class typing.Deque(deque, MutableSequence[T])
A generic version of collections.deque.

New in version 3.5.4.

New in version 3.6.1.

Deprecated since version 3.9: collections.deque now supports []. See PEP 585 and Generic Alias Type.
Run Code Online (Sandbox Code Playgroud)

这意味着什么?我们是否应该不再使用泛型类型Deque(以及其他几种类型)?我查看了参考资料,但没有将这些点联系起来(可能是因为我是中级 Python 用户)。

python python-3.x python-typing

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

生成除特定值之外的随机数

我想生成随机数,但不希望它们来自exclude数组.这是我的代码.

public int generateRandom(int start, int end, ArrayList<Integer> exclude) {
    Random rand = new Random();
    int range = end - start +1 - exclude.size();
    int random = rand.nextInt(range) + 1;

    for(int i = 0; i < exclude.size(); i++) {
        if(exclude.get(i) > random) {
            return random;
        }
      random++;
    }

    return random;
}
Run Code Online (Sandbox Code Playgroud)

我在while循环中使用此函数,并在每次迭代期间添加一个新值exclude.有时会返回属于的数字exclude.有什么问题?

java random arraylist

6
推荐指数
2
解决办法
2万
查看次数

你能解释一下这个Spring环境变量分辨率吗?

春季启动文档具有下面的示例记录文件:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>
Run Code Online (Sandbox Code Playgroud)

你能帮我理解一下${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}吗?有什么-用?

spring spring-mvc environment-variables logback spring-boot

6
推荐指数
2
解决办法
1673
查看次数

Groovy:替换捕获组的惯用方法

我有一个这样的字符串:docker login -u username -p password docker-registry-url.

我用Groovy脚本执行命令execute.出于调试目的,我在执行前打印命令,但由于它包含敏感数据,因此我对用户名和密码进行了模糊处理.

def printableCmd = cmd.toString()

def m = printableCmd =~ /(?:.+) -u (.+) -p (.+) (?:.+)/

if (m.matches() && m[0].size() >= 3) {
  printableCmd = m[0][-1..-2].inject(m[0][0]) { acc, val -> acc.replaceAll(val, "***") }
}
Run Code Online (Sandbox Code Playgroud)

上面的工作正如预期和打印docker login -u *** -p *** docker-registry-url,但我想知道是否有更惯用的方式来做到这一点.请注意,我不想删除捕获的组,只需用星号替换它们,因此非常清楚命令没有错误,但出于安全目的进行模糊处理.

java regex groovy regex-group

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

如何从类变量引用静态方法

鉴于班级

from __future__ import annotations
from typing import ClassVar, Dict, Final
import abc

class Cipher(abc.ABC):
    @abc.abstractmethod
    def encrypt(self, plaintext: str) -> str:
        pass

    @abc.abstractmethod
    def decrypt(self, ciphertext: str) -> str:
        pass

class VigenereCipher(Cipher):
    @staticmethod
    def rotate(n: int) -> str:
        return string.ascii_uppercase[n:] + string.ascii_uppercase[:n]

    _TABLE: Final[ClassVar[Dict[str, str]]] = dict({(chr(i + ord("A")), rotate(i)) for i in range(26)})
Run Code Online (Sandbox Code Playgroud)

编译失败(使用 3.8.0

../cipher.py:19: in <module>
    class VigenereCipher(Cipher):
../cipher.py:24: in VigenereCipher
    _TABLE: Final[ClassVar[Dict[str, str]]] = dict({(chr(i + ord("A")), rotate(i)) for i in range(26)})
../cipher.py:24: …
Run Code Online (Sandbox Code Playgroud)

python static-methods decorator class-variables python-typing

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

gRPC 调用、通道、连接和​​ HTTP/2 生命周期

我阅读了 gRPC核心概念、架构和生命周期,但没有深入到我喜欢看到的深度。有RPC 调用gRPC 通道、gRPC 连接(文章中未描述)和 HTTP/2 连接(文章中未描述)。

我很想知道这些是如何结合在一起的。例如,当 RPC 抛出异常时,通道会发生什么?当通道关闭时,gRPC 连接会发生什么?通道什么时候关闭?gRPC 连接何时关闭?心脏跳动?逾期了怎么办?

任何人都可以回答这些问题,或者向我指出可以的资源吗?

grpc grpc-java

6
推荐指数
2
解决办法
3352
查看次数

Java 8流与迭代器性能

我正在比较两种方法来过滤列表,使用和不使用流.事实证明,对于10,000个项目的列表,不使用流的方法更快.我有兴趣理解为什么会这样.有人能解释一下结果吗?

public static int countLongWordsWithoutUsingStreams(
        final List<String> words, final int longWordMinLength) {
    words.removeIf(word -> word.length() <= longWordMinLength);

    return words.size();
}

public static int countLongWordsUsingStreams(final List<String> words, final int longWordMinLength) {
    return (int) words.stream().filter(w -> w.length() > longWordMinLength).count();
}
Run Code Online (Sandbox Code Playgroud)

使用JMH的Microbenchmark:

@Benchmark
@BenchmarkMode(Throughput)
@OutputTimeUnit(MILLISECONDS)
public void benchmarkCountLongWordsWithoutUsingStreams() {
    countLongWordsWithoutUsingStreams(nCopies(10000, "IAmALongWord"), 3);
}

@Benchmark
@BenchmarkMode(Throughput)
@OutputTimeUnit(MILLISECONDS)
public void benchmarkCountLongWordsUsingStreams() {
    countLongWordsUsingStreams(nCopies(10000, "IAmALongWord"), 3);
}

public static void main(String[] args) throws RunnerException {
    final Options opts = new OptionsBuilder()
        .include(PracticeQuestionsCh8Benchmark.class.getSimpleName())
        .warmupIterations(5).measurementIterations(5).forks(1).build();

    new Runner(opts).run();
} …
Run Code Online (Sandbox Code Playgroud)

list microbenchmark java-8 java-stream jmh

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