小编Tam*_*dus的帖子

结合像Promise.all这样的等待

在异步JavaScript中,很容易并行运行任务并等待所有这些任务完成Promise.all:

async function bar(i) {
  console.log('started', i);
  await delay(1000);
  console.log('finished', i);
}

async function foo() {
    await Promise.all([bar(1), bar(2)]);
}

// This works too:
async function my_all(promises) {
    for (let p of promises) await p;
}

async function foo() {
    await my_all([bar(1), bar(2), bar(3)]);
}
Run Code Online (Sandbox Code Playgroud)

我试图在python中重写后者:

import asyncio

async def bar(i):
  print('started', i)
  await asyncio.sleep(1)
  print('finished', i)

async def aio_all(seq):
  for f in seq:
    await f

async def main():
  await aio_all([bar(i) for i in range(10)])

loop = asyncio.get_event_loop() …
Run Code Online (Sandbox Code Playgroud)

python future python-3.x async-await python-asyncio

42
推荐指数
3
解决办法
1万
查看次数

获取插入Set的最后一个值

SetMDN文档说JavaScript Set对象保留元素的插入顺序:

Set对象是值的集合,您可以按插入顺序迭代其元素.

有没有办法将最后一项插入Set对象?

var s = new Set();
s.add("Alpha");
s.add("Zeta");
s.add("Beta");

console.log(getLastItem(s)); // prints "Beta"
Run Code Online (Sandbox Code Playgroud)

编辑

可以实现具有相同接口Set并具有所需功能的链接集数据结构容器类.请参阅下面的答案.

javascript ecmascript-6

31
推荐指数
3
解决办法
7520
查看次数

DOMException:无法加载,因为找不到支持的源

我收到DOMException:无法加载,因为在video.play()中找不到支持的源 ; 线.我只是在添加了video.setAttribute('crossorigin','anonymous')之后才遇到这个问题; 我正在开发移动应用程序,所以对于交叉起源我需要添加这一行.更新chrome 50版本后,我在此之前遇到此问题,它可以正常工作.

<!DOCTYPE html>
    <html>
    <head> 
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    </head> 
    <body>  
    <script>     
     var video = document.createElement( 'video' ); 

     video.id = 'video';    
     video.type = ' video/mp4; codecs="theora, vorbis" ';   
     video.src = "http://abcde.com/img/videos/what_is_design_thinking.mp4"; 
     video.volume = .1; 
     video.setAttribute('crossorigin', 'anonymous');    
     video.load(); // must call after setting/changing source   

     $('body').html(video);
     video.play();  

     var canvas = document.createElement('canvas');
     var ctx = canvas.getContext('2d');

     $('body').append(canvas);

     video.addEventListener('play', function() {
       var $this = this; //cache
       (function loop() {
       if (!$this.paused && !$this.ended) {
       ctx.drawImage($this, 0, 0);
       setTimeout(loop, 1000 …
Run Code Online (Sandbox Code Playgroud)

html javascript html5

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

何时是类型擦除后输入的函数的泛型返回值?

这个问题是由StackOverflow关于不安全转换的问题引起的:Java Casting方法,不知道要转换为什么.在回答我遇到此问题的问题时,我无法根据纯粹的规范进行解释

我在Oracle文档的Java教程中找到了以下语句:

没有解释"如果有必要"究竟意味着什么,而且我根本没有Java语言规范中找到这些演员,所以我开始尝试.

让我们看看下面这段代码:

// Java source
public static <T> T identity(T x) {
    return x;
}
public static void main(String args[]) {
    String a = identity("foo");
    System.out.println(a.getClass().getName());
    // Prints 'java.lang.String'

    Object b = identity("foo");
    System.out.println(b.getClass().getName());
    // Prints 'java.lang.String'
}
Run Code Online (Sandbox Code Playgroud)

使用Java Decompiler编译javac和反编译:

// Decompiled code
public static void main(String[] paramArrayOfString)
{
    // The compiler inserted a cast to String to ensure …
Run Code Online (Sandbox Code Playgroud)

java generics type-erasure

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

从Executor等待Future:Future不能用于'await'表达式

我想用的ThreadPoolExecutor蟒蛇协程,委托一些阻塞网络调用到一个单独的线程.但是,运行以下代码:

from concurrent.futures import ThreadPoolExecutor
import asyncio

def work():
  # do some blocking io
  pass

async def main():
  executor = ThreadPoolExecutor()
  await executor.submit(work)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
Run Code Online (Sandbox Code Playgroud)

导致错误:

TypeError: object Future can't be used in 'await' expression
Run Code Online (Sandbox Code Playgroud)

是不是Future对象等待?为什么说它们不是?

我怎样才能返回await一个Future对象executor.submit

Python 3.5.0

编辑

使用executor.submit不是我的决定.这在几个库内部使用,比如requests-futures.我正在寻找一种方法来与协同程序中的那些模块互操作.

python future python-3.x async-await python-asyncio

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

禁用npm缓存

前段时间我在构建机器上遇到了npm缓存问题.我们不时需要npm cache clean手工完成,这解决了我们仍然不确定导致它们的原因的各种问题.所以经过一段时间我们包含npm cache clean在我们所有的构建脚本中,从那以后我们没有遇到神秘的问题npm i,但是现在并行构建显然会相互影响.

对我来说,最好的解决方案似乎完全关闭了npm缓存机制,但我无法找到如何做到这一点.

node.js npm

12
推荐指数
3
解决办法
7123
查看次数

默认导出后的分号

在这里读到默认导出后我不需要加分号.所以这个程序有一个不必要的分号:

export default function() {};
Run Code Online (Sandbox Code Playgroud)

但如果我的模块继续这样:

export default function() {};

(() => {
  // creating a new function scope
})();
Run Code Online (Sandbox Code Playgroud)

然后我不能留下分号.

那么这里发生了什么?语法说我不需要分号,但如果我离开它,代码意味着别的什么?

更新:

如果我留下分号:

export default function() {}

(() => {
  // creating a new function scope
})();
Run Code Online (Sandbox Code Playgroud)

然后调用导出的函数而不是导出函数.babeljs.io将后者编译成:

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

exports["default"] = (function () {})(function () {
  // creating a new function scope
})();

;
module.exports = exports["default"];
Run Code Online (Sandbox Code Playgroud)

更准确地说,在调用它之后会抛出一个错误,因为第一个函数的返回值也会被调用(但这不是函数).我在chrome中遇到的错误是这样的:

Uncaught TypeError: (intermediate value)(...) is not a function(…)
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 babeljs

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

编译打字稿而不编译异步功能

有没有一种方法可以使用TypeScript编译器仅删除类型注释,而不使用转译异步函数?有点像{ target: 'esInfinite' }选项吗?原因是:有些浏览器已经支持异步功能,因此我希望有一个不影响这些功能的构建目标。

输入示例:

async function foo(a : number) : Promise<void> {}
Run Code Online (Sandbox Code Playgroud)

示例输出:

async function foo(a) {}
Run Code Online (Sandbox Code Playgroud)

javascript async-await typescript ecmascript-2017

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

angularjs中`<input>`元素的ng-type/show-password指令

我们可以在输入元素上使用数据绑定,如下所示:

<input type="{{ showPassword ? 'text' : 'password' }}" name="password">
Run Code Online (Sandbox Code Playgroud)

但是这与在href属性上使用数据绑定有类似的问题(参见ngHref).这样,dom中的输入元素具有{{ showPassword ? 'text' : 'password' }}直到角度载荷的类型.有一个ngType指令很方便ngHref,可以这样使用:

<input type="password" ng-type="{{ showPassword ? 'text' : 'password' }}" name="password">
Run Code Online (Sandbox Code Playgroud)

还有其他办法吗?我必须实现这个ngType东西吗?

angularjs angularjs-directive

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

位向量与布尔值性能列表

我试图在Python中重现我在一本书中找到的两个例子(最初是用Java编写的).

这两个函数检查字符串是否包含重复的字符.第一个函数使用integer(checker)作为位向量,而第二个函数只使用一个布尔列表.我期望使用带有位的功能有更好的性能,但实际上它表现更差.

这是为什么?从Java翻译到Python时,我写错了吗?

注意:为简单起见,我们只使用小写字母(az),尤其是位向量函数.

import sys
import timeit

def is_unique_chars_bit(my_str):
    checker = 0
    for char in my_str:
        val = ord(char) - ord('a')
        if ((checker & (1 << val)) > 0):
            return False
        checker |= (1 << val)
    return True

def is_unique_chars_list(my_str):
    if len(my_str) > 128:
        # Supposing we use ASCII, which only has 128 chars
        return False
    char_list = [False] * 128
    for char in my_str:
        val = ord(char)
        if char_list[val]:
            return False …
Run Code Online (Sandbox Code Playgroud)

python performance bit-manipulation arraylist

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