我按照文档(http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/validation.html)中的内容配置了一个JSR-303自定义验证器,类路径上的LocalValidatorFactoryBean和Hibernate验证器.但是,我的验证器只是拒绝启动.我在这里提出了一个简单的测试项目(https://github.com/abhijitsarkar/java/tree/master/spring-jsr-303),以及一个故障单元测试.如果你决定看看,只需克隆它并gradlew clean test从根目录运行
.我正在使用Spring framework 4.0.2.RELEASE和Hibernate验证器5.0.3.Final.
验证方法:
public Coffee serve(@ValidOrder(Coffee.Blend.class) final String blend) {
Run Code Online (Sandbox Code Playgroud)
ValidOrder注释:
@Documented
@Constraint(validatedBy = {OrderValidator.class})
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,
ElementType.FIELD,
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.PARAMETER})
@NotNull
public @interface ValidOrder {
Run Code Online (Sandbox Code Playgroud)
OrderValidator验证器:
public class OrderValidator implements ConstraintValidator<ValidOrder, String> {
Run Code Online (Sandbox Code Playgroud)
Spring配置:
@Configuration
@ComponentScan(basePackages = "name.abhijitsarkar.coffeehouse")
@EnableAspectJAutoProxy
public abstract class AppConfig {
@Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
}
Run Code Online (Sandbox Code Playgroud)
依赖关系:
dependencies {
compile(
[group: 'javax.inject', name: 'javax.inject', version: injectApiVersion],
[group: 'javax.validation', name: 'validation-api', version: …Run Code Online (Sandbox Code Playgroud) 我正在比较两种方法来过滤列表,使用和不使用流.事实证明,对于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) 我正在使用Java 8 Spliterator并创建一个将Fibonacci数字流式传输到给定的n.所以对于Fibonacci系列0, 1, 1, 2, 3, 5, 8, ...
n fib(n)
-----------
-1 0
1 0
2 1
3 1
4 2
Run Code Online (Sandbox Code Playgroud)
以下是我的实现,它在耗尽堆栈内存之前打印出一堆1.你能帮我找到这个bug吗?(我认为它没有推进,currentIndex但我不确定设置它的价值).
编辑1:如果您决定回答,请保持与问题相关.这个问题不是关于有效的斐波那契数生成; 这是关于学习分裂者的.
FibonacciSpliterator:
@RequiredArgsConstructor
public class FibonacciSpliterator implements Spliterator<FibonacciPair> {
private int currentIndex = 3;
private FibonacciPair pair = new FibonacciPair(0, 1);
private final int n;
@Override
public boolean tryAdvance(Consumer<? super FibonacciPair> action) {
// System.out.println("tryAdvance called.");
// System.out.printf("tryAdvance: currentIndex = %d, n = %d, pair = %s.\n", currentIndex, n, pair); …Run Code Online (Sandbox Code Playgroud) 我需要在没有中间存储的情况下读写压缩(GZIP)流。当前,我正在使用Spring RestTemplate进行编写,而使用Apache HTTP客户端来进行阅读(请参阅此处的答案,以解释为何RestTemplate不能用于读取大数据流)。实现是相当简单的,我GZIPInputStream在响应上打了一下InputStream然后继续。
现在,我想切换到使用Spring 5 WebClient(只是因为我不喜欢现状)。但是,WebClient本质上是反应性的,并且要处理Flux<Stuff>;我相信有可能获得Flux<DataBuffer>,其中DataBuffer是的抽象ByteBuffer。问题是,如何在不将整个流存储到内存(OutOfMemoryError,我在看着你)或写入本地磁盘的情况下即时对其进行解压缩?值得一提的是WebClient在后台使用Netty。
我承认我不太了解(减压),但是我做了研究,但是网上提供的资料似乎都没有什么帮助。
SI 5+ 支持WebFlux,这意味着我们现在可以构建一个反应式消息系统。然而,这也意味着设计已经经过深思熟虑,通常的错误处理方法不起作用。在反应式流中,消息是Publisher( Flux),它不会抛出异常,但会发出错误通知。因此,消息上设置的错误通道标头是无用的,因为 SI 不知道导致Flux了错误。考虑以下代码:
.handle(WebFlux.outboundGateway(m -> m.getPayload().toString(), webClient)
.expectedResponseType(YelpRecord.class)
.httpMethod(GET)
.mappedRequestHeaders(ACCEPT)
.replyPayloadToFlux(true))
.handle((GenericHandler<Flux<YelpRecord>>) (flux, headers) ->
flux
.doOnError(t -> log.error(t.getMessage(), t))
.doAfterTerminate(() ->
log.info("Completed streaming from: {}.", headers.get(DOWNLOAD_URI_HEADER))
)
.onBackpressureBuffer(
yelpArtifactoryProperties.getOnBackpressureBufferSize(),
BufferOverflowStrategy.ERROR)
)
Run Code Online (Sandbox Code Playgroud)
上面的代码片段中缺少的是将异常发送到来自 的消息上配置的错误通道doOnError。我们怎样才能做到这一点?
spring spring-integration reactive-programming spring-webflux
我正在Coursera 上学习算法,第一部分课程,其中一个面试问题(未评分)如下:
十进制占优。给定一个包含 n 个键的数组,设计一个算法来查找出现次数超过 n/10 次的所有值。算法的预期运行时间应该是线性的。
它有一个提示:
使用 quickselect 确定第 (n/10) 个最大的键并检查它是否出现超过 n/10 次。
我不明白 n/10 最大的键与 n/10 重复值有什么关系。它不会告诉我哪些值出现次数超过 n/10 次。
有一篇论文为 n/k 找到了更通用的解决方案,但我很难理解论文中的代码。
解决这个问题的一种方法是对输入数组进行排序,然后再计算每个不同值的出现次数。这将花费 O(nlogn) + O(n) 时间,这比问题要求的要多。
想法?
我参加了Coursera上的算法第二部分课程,其中一项作业是解决Boggle游戏的方法:http : //coursera.cs.princeton.edu/algs4/assignments/boggle.html
荣誉代码要求我不要公开发布解决方案,因此这里是基本算法的伪代码。
visit:
word <- board[i][j]
start <- dictionary.match(word, start)
if start is not null
visited[i][j] <- true
word <- prefix + word
if word is longer than min required length
words <- words + word
for (x, y) ? adj(i, j)
if not visited(x, y)
visit (x, y)
visited[i][j] <- false
Run Code Online (Sandbox Code Playgroud)
该字典是使用Trie实现的。
上面的代码有效,我通过了分配,但是随后我遇到了这篇博客文章,该文章声称使用动态编程可以实现更快的解决方案:
事实证明,我们可以使用一种巧妙的动态编程技术来快速检查一个单词(在这种情况下是从词典中)是否可以从黑板上构造出来!
这是动态编程思想的核心:
要在板的第[i,j]个位置找到长度为k的单词(结束位置),该单词的第k-1个字母必须位于[i, j]。
基本情况是k = 1。
在板的第[i,j]个单元格的第[i,j]个单元格中会找到一个长度为1的字母(结束位置),该单词中唯一的字母与板的第[i,j]个位置的字母匹配。
一旦用基本情况填充了动态编程表,就可以在长度为k,k> 1的任何单词的基础上进行构建。
不幸的是,作者在解释方面做得很差,我无法遵循他的解决方案。我想不过,希望这里有人可以向我解释。
PS:
这个问题不是重复的,因为那个人不使用DP。请检查那些重复快乐的手指。
我已表现出足够的努力,没有要求任何人做我的作业。我已经有了自己的解决方案。我感兴趣的是学习一种更好的解决问题的方法(如果存在)。
谢谢!
我正在尝试做一本英语词典,这是我的代码
import json
file = open("data.json", "r", encoding= "utf-8")
#data.json contains some words and meanings in English as a dict.
dictionary = json.loads(file.read())
word = input("Enter Word: ")
print(dictionary[word])
Run Code Online (Sandbox Code Playgroud)
而且,如果用户无法正确输入,我想在字典中显示近键。(例如,如果用户输入 runn,我的代码将能够显示您的意思是“运行”)是否有任何函数可以做到这一点
考虑以下 Flux
Flux.range(1, 5)
.parallel(10)
.runOn(Schedulers.parallel())
.map(i -> "https://www.google.com")
.flatMap(uri -> Mono.fromCallable(new HttpGetTask(httpClient, uri)))
Run Code Online (Sandbox Code Playgroud)
HttpGetTask 是一个Callable,在这种情况下其实际实现是无关紧要的,它对给定的URI进行HTTP GET调用,如果成功,则返回内容。
现在,我想通过引入人为延迟来减慢发射速度,这样就可以同时启动多达10个线程,但是每个线程都不会立即HttpGetTask完成。例如,说没有线程必须在3秒之前完成。我该如何实现?
PEP 622引入了match声明作为if-elif-else. 然而,我在提案或任何在线材料中找不到的一件事是该match声明是否可以用作表达式而不仅仅是作为声明。
举几个例子可以清楚地说明这一点:
示例1:
def make_point_2d(pt):
match pt:
case (x, y):
return Point2d(x, y)
case _:
raise TypeError("not a point we support")
Run Code Online (Sandbox Code Playgroud)
示例2:
match response.status:
case 200:
do_something(response.data)
case 301 | 302:
retry(response.location)
Run Code Online (Sandbox Code Playgroud)
在第一个示例中,函数从子句内部返回case,而在第二个示例中,不返回任何内容。但我希望能够做类似以下假设示例的事情:
spouse = match name:
case "John":
"Jane"
case "David":
"Alice"
print(spouse)
Run Code Online (Sandbox Code Playgroud)
但它无法编译。
java ×4
spring ×3
algorithm ×2
java-8 ×2
python ×2
arrays ×1
boggle ×1
concurrency ×1
isinstance ×1
java-stream ×1
jmh ×1
list ×1
netty ×1
python-3.10 ×1
spliterator ×1
structural-pattern-matching ×1
trie ×1