小编epi*_*ian的帖子

子类化本机对象:instanceof无法正常工作

我试图Error在CoffeeScript中继承本机JS 对象以获取专门的错误类型,但是instanceof如果我没有在子类中定义构造函数,我发现它无法正常工作:

class SimpleError extends Error
class EmptyConstructorError extends Error
  constructor: ->
class SuperConstructorError extends Error
  constructor: -> 
    super

new SimpleError instanceof SimpleError                     # -> false
new EmptyConstructorError instanceof EmptyConstructorError # -> true
new SuperConstructorError instanceof SuperConstructorError # -> true
Run Code Online (Sandbox Code Playgroud)

问题似乎是由如何定义生成的JS构造函数引起的.当我没有在CoffeeScript中定义构造函数时:

SimpleError = (function(_super) {

  __extends(SimpleError, _super);

  function SimpleError() {
    return SimpleError.__super__.constructor.apply(this, arguments);
  }

  return SimpleError;

})(Error);
Run Code Online (Sandbox Code Playgroud)

当我定义CoffeeScript的构造函数:

SuperConstructorError = (function(_super) {

  __extends(SuperConstructorError, _super);

  function SuperConstructorError() {
    SuperConstructorError.__super__.constructor.apply(this, arguments);
  } …
Run Code Online (Sandbox Code Playgroud)

coffeescript

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

Rails:在每个请求上切换连接但保留连接池

在我们的Rails应用程序中,我们需要使用不同的数据库,具体取决于请求的子域(每个国家/地区的DB不同).

现在我们正在做类似于这个问题的建议.也就是说,呼叫ActiveRecord::Base.establish_connection每个请求.

它似乎 ActiveRecord::Base.establish_connection丢弃了当前的连接池,并在每次调用时建立新的连接.

我做了这个快速基准测试,看看establish_connection每次调用和建立连接之间是否有任何显着差异:

require 'benchmark/ips'

$config = Rails.configuration.database_configuration[Rails.env]
$db1_config = $config.dup.update('database' => 'db1')
$db2_config = $config.dup.update('database' => 'db2')

# Method 1: call establish_connection on each "request".
Benchmark.ips do |r|
  r.report('establish_connection:') do
    # Simulate two requests, one for each DB.
    ActiveRecord::Base.establish_connection($db1_config)
    MyModel.count # A little query to force the DB connection to establish.
    ActiveRecord::Base.establish_connection($db2_config)
    MyModel.count
  end
end

# Method 2: Have different subclasses of my models, one for each DB, and …
Run Code Online (Sandbox Code Playgroud)

ruby activerecord ruby-on-rails

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

如何从JavaScript中的字符串中获取第n个(Unicode)字符

假设我们有一个包含一些(星体)Unicode字符的字符串:

const s = 'Hi  Unicode!'
Run Code Online (Sandbox Code Playgroud)

[]运营商和.charAt()方法不为获得第四字符,这应该是""工作:

> s[3]
'?'
> s.charAt(3)
'?'
Run Code Online (Sandbox Code Playgroud)

.codePointAt() 确实获得第四届字符正确的值,但不幸的是它是一个数字,并且必须转换回使用字符串String.fromCodePoint():

> String.fromCodePoint(s.codePointAt(3))
''
Run Code Online (Sandbox Code Playgroud)

类似地,使用splats将字符串转换为数组会产生有效的Unicode字符,因此这是获得第4个字符的另一种方法:

> [...s][3]
''
Run Code Online (Sandbox Code Playgroud)

但我无法相信从字符串到数字返回字符串,或者必须将字符串拆分为数组是执行这个看似微不足道的事情的唯一方法.这样做有没有简单的方法?

> s.simpleMethod(3)
''
Run Code Online (Sandbox Code Playgroud)

注意:我知道"字符"的定义有点模糊,但出于这个问题的目的,字符只是与Unicode代码点相对应的符号(没有组合字符,没有字形集群等).

更新:该String.fromCodePoint(str.codePointAt(n))方法不可行,因为n那里的位置没有考虑以前的星体符号:String.fromCodePoint(''.codePointAt(1)) // => '?'


(我觉得有点愚蠢地问这个;就像我可能错过了一些明显的东西.但是这些问题的先前答案不适用于在星体平面上使用Unicode simbols的字符串.)

javascript unicode

9
推荐指数
2
解决办法
910
查看次数

JSON到Groovy与JsonSlurper和未知的"字符串"

我正在编写一个Grails/Groovy应用程序,我有一个JSON对象,其中包含可以更改的params成员中的"字符串"名称(索引小部件).也就是说,下次它可能是极致缩放.这是JSON:

def jx = """{ 
    "job": "42",
    "params": {
        "grommet": {"name": "x", "data": "y"},
        "widget": { "name": "a", "data": "b"}
    } 
}"""
Run Code Online (Sandbox Code Playgroud)

我试图找出如何获得字符串索环.代码到目前为止:

def dalist = new JsonSlurper().parseText(jx)
println dalist.job     // Gives: 42
println dalist.params  // Gives: [grommet:[name:x, data:y], widget:[name:a, data:b]]
println dalist.params[0]  // Gives: null
Run Code Online (Sandbox Code Playgroud)

知道如何获得字符串索环吗?Iama不停地撞在墙上.

grails groovy json

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

Groovy - 将列表扩展为闭包参数

是否有可能有一个列表并将其用作闭包签名的参数,而不是几个变量?原因是我必须从java代码调用一个闭包,而java代码不知道groovy闭包需要什么变量.

用一个例子可以更好地服务.

假设我有一个'闭包存储库',每个闭包可能有不同的签名.例如:

closures = [
    closureA: { int a, String b ->
        a.times {
            System.err.println(b);
        }
    },
    closureB: { int a, int b, String c ->
        (a+b).times {
            System.err.println(c);
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

然后我有一个方法,我正在暴露于我的java代码来调用这些闭包:

def tryClosureExpansion(String whichClosure, Object ... args) {
    def c = closures[whichClosure]
    c.call(args)     // DOESNT COMPILE !
}
Run Code Online (Sandbox Code Playgroud)

而Java我会像这样调用这个方法:

// these calls will happen from Java, not from Groovy
tryClosureExpansion("closureA", 1, "Hello");
tryClosureExpansion("closureB", 1, 5, "Hello more");
Run Code Online (Sandbox Code Playgroud)

请参见上面未编译的行.我觉得groovy是'groovy'足以处理这样的事情.任何可能会飞的替代品?

groovy closures dynamic-programming

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

在异步回调上设置状态时,防止“对卸载的组件做出反应状态更新”警告

我想从组件上的事件处理程序触发异步操作,并在该操作完成后,更新该组件中的一些 UI 状态。但是由于用户导航到另一个页面,该组件可能随时从 DOM 中删除。如果在操作尚未完成时发生这种情况,React 会记录此警告:

警告:无法对卸载的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消 useEffect 清理函数中的所有订阅和异步任务。

这是一个可重现的示例:

import { useState } from "react";
import ReactDOM from "react-dom";
// The router lib is a detail; just to simulate navigating away.
import { Link, Route, BrowserRouter } from "react-router-dom";

function ExampleButton() {
  const [submitting, setSubmitting] = useState(false);

  const handleClick = async () => {
    setSubmitting(true);
    await doStuff();
    setSubmitting(false);
  };

  return (
    <button onClick={handleClick} disabled={submitting}>
      {submitting ? "Submitting" : "Submit"}
    </button>
  );
}

function doStuff() {
  // Suppose …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

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

避免在collect() 上使用turbofish 类型注释到Result&lt;Vec&lt;_&gt;, _&gt;

我想使用s 到 acollect()的迭代器并提前返回,以防迭代器中的任何元素出错。所以,像这样:Result<T, E>Vec<T>

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let input = ""; // Snip real input
    let games: Vec<Game> = input.lines().map(parse_game).collect()?;
    println!("parsed {} games", games.len());
    Ok(())
}

struct Game;

fn parse_game(_s: &str) -> Result<Game, Box<dyn Error>> {
    Ok(Game)
}
Run Code Online (Sandbox Code Playgroud)

Playground 链接,是的,该代码的灵感来自于 Advent of Code 2023 day 2)

但这不起作用,它无法编译并出现错误:

error[E0282]: type annotations needed
 --> src/main.rs:5:58
  |
5 |     let games: Vec<Game> = input.lines().map(parse_game).collect()?;
  |                                                          ^^^^^^^ cannot infer type of the …
Run Code Online (Sandbox Code Playgroud)

rust

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