标签: callable

PHP可调用对象作为对象成员

我有一个课程Logger,其中包括一个方法Log.
作为实例Log的最常见用途Logger,我已__invoke拨打电话Log

另一个类"Site"包含一个成员"Log",一个Logger实例.

为什么这样做:

$Log = $this->Log;  
$Log("Message");  
Run Code Online (Sandbox Code Playgroud)

但不是这个:

$this->Log("Message");
Run Code Online (Sandbox Code Playgroud)

前者失败了"PHP致命错误:调用未定义的方法Site :: Log()"
这是可调用对象实现的限制,还是我误解了什么?

php callable invoke

5
推荐指数
2
解决办法
2550
查看次数

Java并发:如何在处理过程中告诉哪个Future属于哪个Callable?

我有一组Callables和一个ExecutorService.当我调用所有时,我得到一个Future对象列表.如何在Future完成之前判断哪个Future对象映射到哪个Callable?我事后可以告诉因为

码:

 ExecutorService es = .....;

 Collection<Callables> uniqueCallables = .....;  // each Callable is unique!

 List<Future> futures = es.invokeAll(uniqueCallables);

 // TODO--find unique Future A which is the future for Callable A!
Run Code Online (Sandbox Code Playgroud)

java concurrency future callable executorservice

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

动态地将可调用的类添加为类的“方法”

我实现了一个元类,该元类拆解使用它创建的类的类属性,并根据这些参数中的数据构建方法,然后将这些动态创建的方法直接附加到类对象上(所涉及的类可轻松定义Web表单对象,在网络测试框架中使用)。它一直工作得很好,但是现在我需要添加一个更复杂的方法类型,为了保持环境整洁,我将其实现为可调用类。不幸的是,当我尝试在实例上调用可调用类时,将其视为类属性而不是实例方法,并且在调用时仅接收其自己的self。我知道为什么会发生这种情况,但我希望有人能提供比我提出的解决方案更好的解决方案。问题的简化图示:

class Foo(object):
    def __init__(self, name, val):
        self.name = name
        self.val = val
        self.__name__ = name + '_foo'
        self.name = name
    # This doesn't work as I'd wish
    def __call__(self, instance):
        return self.name + str(self.val + instance.val)

def get_methods(name, foo_val):
    foo = Foo(name, foo_val)
    def bar(self):
        return name + str(self.val + 2)
    bar.__name__ = name + '_bar'
    return foo, bar

class Baz(object):
    def __init__(self, val):
        self.val = val

for method in get_methods('biff', 1):
    setattr(Baz, method.__name__, method)
baz = …
Run Code Online (Sandbox Code Playgroud)

python methods class callable

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

在继续之前如何等待所有callables完成执行?

我有以下代码哈希:

public class MyCallable implements Callable<Long> {
    @Override
    public Long call() throws Exception {
        // Do stuff...
    }
}

public class MyController {
    private ExecutorService executor = Executos.newCachedTreadPool();

    public Long concurrentDoStuff() {
        List<MyCallable> workers = makeWorkers();

        List<Long> allResults = new ArrayList<Long>();
        for(MyCallable worker : workers) {
            Future<Long> workerResults = executor.submit(worker);

            try {
                allResults.add(workerResults.get());
            } catch(InterruptedException ie) {
                // Handle...
            } catch(ExecutionException ee) {
                // Handle...
            }
        }

        // Question: how do I pause here and wait for all workers to …
Run Code Online (Sandbox Code Playgroud)

java concurrency future callable executorservice

5
推荐指数
2
解决办法
2567
查看次数

java.util.concurrent.ExecutionException:java.lang.NullPointerException错误

在独立模式下执行时,以下代码段不会引发任何错误。当我将其部署到Web服务器中时(实现服务器接口并作为JAR添加到类路径中),我得到

 java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at com.nbis.process.JSON_2_File_Split_V004.fn_1_parserEntity(JSON_2_File_Split_V004.java:256)
at com.nbis.process.JSON_2_File_Split_V004.fn_0_primaryCaller(JSON_2_File_Split_V004.java:177)
at com.nbis.process.JSON_2_File_Split_V004.execute(JSON_2_File_Split_V004.java:151)
Run Code Online (Sandbox Code Playgroud)

代码段:

this.callable = new JSON_3_File_Process_V005(this.originalFileName, this.inProgressDirLoc, this.processedDirLoc, "[" + jSONRecord.toString() + "]", this.dataMDHolder, this.dataAccIDValueMap, this.dataCountryNameValueMap);
String[] fullContent = null;    
try {
    fullContent = executor.submit(this.callable).get();
} catch (ExecutionException e) {
    StringWriter errors = new StringWriter();
    e.printStackTrace(new PrintWriter(errors));
    log.info("Srii: " + errors.toString());
    executor.shutdown();
    return 7;
    } 
Run Code Online (Sandbox Code Playgroud)

将get的返回值添加到ExecutorCompletionService将是一个选项,但这不会杀死异步处理的概念吗?换句话说,我在StringBuilder中收集可调用get的输出字符串,并在get计数达到特定数字时存储到磁盘。数据发送到磁盘后,我将刷新StringBuilder。这样,我可以定期将数据推送到磁盘,而不必将其保留在内存中。

关于我在这里做错什么的任何建议?感谢任何输入。谢谢。

java callable nullpointerexception

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

如何在PHP中调用可调用函数?

我有一个标题为的数组$post_data。我想将此数组作为参数传递给某些函数。连同该数组一起,我还必须将另一个可调用的“函数名称”作为第二个参数传递给函数调用。

我不了解如何实现这一目标。

以下是需要调用的函数体:

//Following is the function to be called
function walk_recursive_remove(array $array, callable $callback) {
  foreach ($array as $k => $v) {
    if (is_array($v)) {
      $array[$k] = walk_recursive_remove($v, $callback);
    } else {
      if ($callback($v, $k)) {
        unset($array[$k]);
      }
    }
  }
  return $array;
}

//Following is the callback function to be called

function unset_null_children($value, $key){
  return $value == NULL ? true : false;
}

The function call that I tried is as follows :
//Call to the function …
Run Code Online (Sandbox Code Playgroud)

php recursion function callback callable

5
推荐指数
2
解决办法
2833
查看次数

如何使用CompletableFuture返回值

我创建了一个示例,我想知道如何使用CompletableFuture?返回值?我也改变了CompletableFuture<Void> exeFutureList,CompletableFuture<Integer> exeFutureList但是eclipse总是建议把它设置回Void.

请告诉我如何使用CompletableFuture返回值.

代码:

    public class MainClass {

    static ExecutorService exe = null;
    static CompletableFuture<Void> exeFutureList = null;

    public static void main(String[] args) {
        exe = Executors.newFixedThreadPool(1);
        exeFutureList = CompletableFuture.runAsync(new RunClass(8), exe);
    }

    static class RunClass implements Runnable {

        private int num;

        public RunClass(int num) {
            // TODO Auto-generated constructor stub
            this.num = num;
        }

        public void run() {
            // TODO Auto-generated method stub
            this.num = this.num + 10;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

java multithreading callable countdownlatch completable-future

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

CompletableFuture:异步调用void函数

我试图在某些数据库异常上使用重试策略实现数据库查询.重试策略的代码不是很相关,所以我没有包含它.正如您在下面的代码中看到的那样 - 我编写了一个retryCallable,它采用了重试策略和Callable populateData().

getDataFromDB,我从DB获取数据并将数据放在全局散列图中,该散列图在应用程序级别充当缓存.

此代码按预期工作.我想populateData从另一个班级调用.但是,这将是一个阻止呼叫.由于这是数据库并且具有重试策略,因此这可能很慢.我想populateData异步调用.

我如何使用CompletableFuture或FutureTask来实现这一目标? CompletableFuture.runAsync期待一个可运行的.CompletableFuture.supplyAsync期待供应商.我以前没有实现过这些东西.所以关于最佳实践的任何建议都会有所帮助.

Class TestCallableRetry {

public void populateData() {
        final Callable<Set<String>> retryCallable = new RetryingCallable<>(retryStrategyToRetryOnDBException(), getDataFromDB());
        Set<String> data = new HashSet<>();

        data = retryCallable.call();

        if (data != null && !data.isEmpty()) {
            // store data in a global hash map
        }
    }

    private Callable<Set<Building>> getDataFromDB() {
        return new Callable<Set<String>>() {
            @Override
            public Set<String> call() {
                // returns data from database
            }
        };
    }
}

Class …
Run Code Online (Sandbox Code Playgroud)

java callable runnable completable-future

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

timeit ValueError:stmt既不是字符串也不是可调用的

timeit在Python中玩过,遇到了一个奇怪的问题。

我定义一个简单的函数addtimeit当我传递add两个字符串参数时,可以工作。但是ValueError: stmt is neither a string nor callable当我传递add两个int参数时,它会增加。

>>> import timeit
>>> def add(x,y):
...     return x + y
... 


>>> a = '1'
>>> b = '2'
>>> timeit.timeit(add(a,b))
0.01355926995165646


>>> a = 1
>>> b = 2
>>> timeit.timeit(add(a,b))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/anaconda/lib/python3.6/timeit.py", line 233, in timeit
    return Timer(stmt, setup, timer, globals).timeit(number)
  File "/anaconda/lib/python3.6/timeit.py", …
Run Code Online (Sandbox Code Playgroud)

python callable timeit

5
推荐指数
3
解决办法
3067
查看次数

mypy error: Callable has no attribute "__get__"

I have something like the following:

from typing import TypeVar, Callable, Generic, Type, Union, Optional

T = TypeVar("T")
V = TypeVar("V")

class DescClass(Generic[T, V]):
    """A descriptor."""
    def __init__(self, func: Callable[[T], V]) -> None:
        self.func = func

    def __get__(self, instance: Optional[T], owner: Type[T]) -> Callable[[], V]:
        return self.func.__get__(instance, owner)

class C:
    @DescClass
    def f(self): ...
Run Code Online (Sandbox Code Playgroud)

...for which Mypy will return this error:

test.py:12: error: "Callable[[T], Any]" has no attribute "__get__"
Run Code Online (Sandbox Code Playgroud)

What is the canonical way to specify the type for func …

python callable mypy

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