问:
What is @dynamicCallable in Swift?
From Apple's documentation:

The @dynamicCallable attribute lets you call named types like you call
  functions using a simple syntactic sugar. The primary use case is
  dynamic language interoperability.

Why would you want to use an @dynamicCallable instead of direct approch?

答:
Introduce user-defined dynamically "callable" types

Proposal: SE-0216

Authors: Chris Lattner, Dan Zheng

Review Manager: John McCall

Implementation: apple/swift#20305

Decision Notes: Rationale

Status: Implemented (Swift 5)

Introduction

This proposal is a follow-up to SE-0195 - Introduce User-defined "Dynamic Member
Lookup" Types,
which shipped in Swift 4.2. It introduces a new @dynamicCallable attribute, which marks
a type as being "callable" with normal syntax. It is simple syntactic sugar
which allows the user to write:

a = someValue(keyword1: 42, "foo", keyword2: 19)
```

<p>and have it be rewritten by the compiler as:</p>

<pre class="lang-swift prettyprint-override"><code>a = someValue.dynamicallyCall(withKeywordArguments: [
    "keyword1": 42, "": "foo", "keyword2": 19
])
</code>```

Many other languages have analogous features (e.g. Python "callables", C++ operator(), and
functors in many other languages), but the
primary motivation of this proposal is to allow elegant and natural interoperation with
dynamic languages in Swift.

Swift-evolution threads:
 - Pitch: Introduce user-defined dynamically "callable"
    types.
 - Pitch #2: Introduce user-defined dynamically “callable”
    types.
 - Current pitch thread: Pitch #3: Introduce user-defined dynamically “callable”
   types

Motivation and context

Swift is exceptional at interworking with existing C and Objective-C APIs and
we would like to extend this interoperability to dynamic languages like Python,
JavaScript, Perl, and Ruby. We explored this overall goal in a long design
process wherein the Swift evolution community evaluated multiple different
implementation approaches. The conclusion was that the best approach was to put
most of the complexity into dynamic language specific bindings written as
pure-Swift libraries, but add small hooks in Swift to allow these bindings to
provide a natural experience to their clients.
SE-0195
was the first step in this process, which introduced a binding to naturally
express member lookup rules in dynamic languages.

What does interoperability with Python mean? Let's explain this by looking at
an example. Here's some simple Python code:

```<code>class Dog:
    def __init__(self, name):
        self.name = name
        self.tricks = []  # creates a new empty list for each `Dog`

    def add_trick(self, trick):
        self.tricks.append(trick)
</code>```

With the SE-0195 @dynamicMemberLookup feature
introduced in Swift 4.2, it is possible to implement a Python interoperability
layer
written in Swift. It interoperates with the Python runtime, and project all
Python values into a single PythonObject type. It allows us to call into the
Dog class like this:

// import DogModule.Dog as Dog
let Dog = Python.import.call(with: "DogModule.Dog")

// dog = Dog("Brianna")
let dog = Dog.call(with: "Brianna")

// dog.add_trick("Roll over")
dog.add_trick.call(with: "Roll over")

// dog2 = Dog("Kaylee").add_trick("snore")
let dog2 = Dog.call(with: "Kaylee").add_trick.call(with: "snore")
```

<p>This also works with arbitrary other APIs as well. Here is an example working
with the Python <code>pickle</code> API and the builtin Python function <code>open</code>. Note that
we choose to put builtin Python functions like <code>import</code> and <code>open</code> into a
<code>Python</code> namespace to avoid polluting the global namespace, but other designs
are possible:</p>

<pre class="lang-swift prettyprint-override"><code>// import pickle
let pickle = Python.import.call(with: "pickle")

// file = open(filename)
let file = Python.open.call(with: filename)

// blob = file.read()
let blob = file.read.call()

// result = pickle.loads(blob)
let result = pickle.loads.call(with: blob)
</code>```

This capability works well, but the syntactic burden of having to use
foo.call(with: bar, baz) instead of foo(bar, baz) is significant. Beyond
the syntactic weight, it directly harms code clarity by making code hard to
read and understand, cutting against a core value of Swift.

The proposed @dynamicCallable attribute directly solves this problem.
With it, these examples become more natural and clear, effectively matching the
original Python code in expressiveness:

// import DogModule.Dog as Dog
let Dog = Python.import("DogModule.Dog")

// dog = Dog("Brianna")
let dog = Dog("Brianna")

// dog.add_trick("Roll over")
dog.add_trick("Roll over")

// dog2 = Dog("Kaylee").add_trick("snore")
let dog2 = Dog("Kaylee").add_trick("snore")
```

<p>Python builtins:</p>

<pre class="lang-swift prettyprint-override"><code>// import pickle
let pickle = Python.import("pickle")

// file = open(filename)
let file = Python.open(filename)

// blob = file.read()
let blob = file.read()

// result = pickle.loads(blob)
let result = pickle.loads(blob)
</code>```

This proposal merely introduces a syntactic sugar - it does not add any new
semantic model to Swift. We believe that interoperability with scripting
languages is an important and rising need in the Swift community, particularly
as Swift makes inroads into the server development and machine learning
communities. This feature is also precedented in other languages (e.g. Scala's
Dynamic trait), and
can be used for other purposes besides language interoperability (e.g.
implementing dynamic proxy objects).

Proposed solution

We propose introducing a new @dynamicCallable attribute to the Swift language
which may be applied to structs, classes, enums, and protocols. This follows
the precedent of
SE-0195.

Before this proposal, values of these types are not valid in a call expression:
the only existing callable values in Swift are those with function types
(functions, methods, closures, etc) and metatypes (which are initializer
expressions like String(42)). Thus, it is always an error to "call" an
instance of a nominal type (like a struct, for instance).

With this proposal, types with the @dynamicCallable attribute on their
primary type declaration become "callable". They are required to implement at
least one of the following two methods for handling the call behavior:

func dynamicallyCall(withArguments: <#Arguments#>) -> <#R1#>
// `<#Arguments#>` can be any type that conforms to `ExpressibleByArrayLiteral`.
// `<#Arguments#>.ArrayLiteralElement` and the result type `<#R1#>` can be arbitrary.

func dynamicallyCall(withKeywordArguments: <#KeywordArguments#>) -> <#R2#>
// `<#KeywordArguments#>` can be any type that conforms to `ExpressibleByDictionaryLiteral`.
// `<#KeywordArguments#>.Key` must be a type that conforms to `ExpressibleByStringLiteral`.
// `<#KeywordArguments#>.Value` and the result type `<#R2#>` can be arbitrary.

// Note: in these type signatures, bracketed types like <#Arguments#> and <#KeywordArguments#>
// are not actual types, but rather any actual type that meets the specified conditions.
```

<p>As stated above, <code><#Arguments#></code> and <code><#KeywordArguments#></code> can be any types
that conform to the
<code>ExpressibleByArrayLiteral</code>
and
<code>ExpressibleByDictionaryLiteral</code>
protocols, respectively. The latter is inclusive of
<code>KeyValuePairs</code>,
which supports duplicate keys, unlike <code>Dictionary</code>.
Thus, using <code>KeyValuePairs</code> is recommended to support duplicate keywords and
positional arguments (because positional arguments are desugared as keyword
arguments with the empty string <code>""</code> as the key).</p>

<p>If a type implements the <code>withKeywordArguments:</code> method, it may be dynamically
called with both positional and keyword arguments: positional arguments have
the empty string <code>""</code> as the key. If a type only implements the
<code>withArguments:</code> method but is called with keyword arguments, a compile-time
error is emitted.</p>

<p>Since dynamic calls are syntactic sugar for direct calls to <code>dynamicallyCall</code>
methods, additional behavior of the <code>dynamicallyCall</code> methods is directly
forwarded.  For example, if a <code>dynamicallyCall</code> method is marked with <code>throws</code>
or <code>@discardableResult</code>, then the corresponding sugared dynamic call will
forward that behavior.</p>

<h3>Ambiguity resolution: most specific match</h3>

<p>Since there are two <code>@dynamicCallable</code> methods, there may be multiple ways to
handle some dynamic calls. What happens if a type specifies both the
<code>withArguments:</code> and <code>withKeywordArguments:</code> methods?</p>

<p>We propose that the type checker resolve this ambiguity towards the tightest
match based on syntactic form of the expression. The exact rules are:</p>

<ul>
<li>If a <code>@dynamicCallable</code> type implements the <code>withArguments:</code> method and it is
called with no keyword arguments, use the <code>withArguments:</code> method.</li>
<li>In all other cases, attempt to use the <code>withKeywordArguments:</code> method.

<ul>
<li>This includes the case where a <code>@dynamicCallable</code> type implements the
<code>withKeywordArguments:</code> method and it is called with at least one keyword
argument.</li>
<li>This also includes the case where a <code>@dynamicCallable</code> type implements only
the <code>withKeywordArguments:</code> method (not the <code>withArguments:</code> method) and
it is called with no keyword arguments.</li>
<li>If <code>@dynamicCallable</code> type does not implement the <code>withKeywordArguments:</code>
method but the call site has keyword arguments, an error is emitted.</li>
</ul></li>
</ul>

<p>Here are some toy illustrative examples:</p>

<pre class="lang-swift prettyprint-override"><code>@dynamicCallable
struct Callable {
  func dynamicallyCall(withArguments args: [Int]) -> Int { return args.count }
}
let c1 = Callable()
c1() // desugars to `c1.dynamicallyCall(withArguments: [])`
c1(1, 2) // desugars to `c1.dynamicallyCall(withArguments: [1, 2])`
c1(a: 1, 2) // error: `Callable` does not define the 'withKeywordArguments:' method

@dynamicCallable
struct KeywordCallable {
  func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Int>) -> Int {
    return args.count
  }
}
let c2 = KeywordCallable()
c2() // desugars to `c2.dynamicallyCall(withKeywordArguments: [:])`
c2(1, 2) // desugars to `c2.dynamicallyCall(withKeywordArguments: ["": 1, "": 2])`
c2(a: 1, 2) // desugars to `c2.dynamicallyCall(withKeywordArguments: ["a": 1, "": 2])`

@dynamicCallable
struct BothCallable {
  func dynamicallyCall(withArguments args: [Int]) -> Int { return args.count }
  func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Int>) -> Int {
    return args.count
  }
}
let c3 = BothCallable()
c3() // desugars to `c3.dynamicallyCall(withArguments: [])`
c3(1, 2) // desugars to `c3.dynamicallyCall(withArguments: [1, 2])`
c3(a: 1, 2) // desugars to `c3.dynamicallyCall(withKeywordArguments: ["a": 1, "": 2])`
</code>```

This ambiguity resolution rule works out naturally given the behavior of the
Swift type checker, because it only resolves call expressions when the type
of the base expression is known. At that point, it knows whether the base is a
function type, metatype, or a valid @dynamicCallable type, and it knows the
syntactic form of the call.

This proposal does not require massive or invasive changes to the constraint
solver. Please look at the implementation for more details.

Example usage

Here, we sketch some example bindings to show how this could be used in
practice. Note that there are lots of design decisions that are orthogonal to
this proposal (e.g. how to handle exceptions) that we aren't going into here.
This is just to show how this feature provides an underlying facility that
language bindings authors can use to achieve their desired result. These
examples also show @dynamicMemberLookup to illustrate how they work together,
but elides other implementation details.

JavaScript supports callable objects but does not have keyword arguments.

Here is a sample JavaScript binding:

@dynamicCallable @dynamicMemberLookup
struct JSValue {
  // JavaScript doesn't have keyword arguments.
  @discardableResult
  func dynamicallyCall(withArguments: [JSValue]) -> JSValue { ... }

  // This is a `@dynamicMemberLookup` requirement.
  subscript(dynamicMember member: JSValue) -> JSValue {...}

  // ... other stuff ...
}
```

<p>On the other hand, a common JavaScript pattern is to take a dictionary of
values as a stand-in for argument labels (called like
<code>example({first: 1, second: 2, third: 3})</code> in JavaScript). A JavaScript bridge
in Swift could choose to implement keyword argument support to allow this to be
called as <code>example(first: 1, second: 2, third: 3)</code> from Swift code (kudos to
Ben Rimmington for this
observation).</p>

<p>Python does support keyword arguments. While a Python binding could implement
only the <code>withKeywordArguments:</code> method, it is be better to implement both the
non-keyword and keyword forms to make the non-keyword case slightly more
efficient (avoid allocating temporary storage) and to make direct calls with
positional arguments nicer (<code>x.dynamicallyCall(withArguments: 1, 2)</code> instead of
<code>x.dynamicallyCall(withKeywordArguments: ["": 1, "": 2])</code>).</p>

<p>Here is a sample Python binding:</p>

<pre class="lang-swift prettyprint-override"><code>@dynamicCallable @dynamicMemberLookup
struct PythonObject {
  // Python supports arbitrary mixes of keyword arguments and non-keyword
  // arguments.
  @discardableResult
  func dynamicallyCall(
    withKeywordArguments: KeyValuePairs<String, PythonObject>
  ) -> PythonObject { ... }

  // An implementation of a Python binding could choose to implement this
  // method as well, avoiding allocation of a temporary array.
  @discardableResult
  func dynamicallyCall(withArguments: [PythonObject]) -> PythonObject { ... }

  // This is a `@dynamicMemberLookup` requirement.
  subscript(dynamicMember member: String) -> PythonObject {...}

  // ... other stuff ...
}
</code>```

Limitations

Following the precedent of SE-0195, this attribute must be placed on the
primary definition of a type, not on an extension.

This proposal does not introduce the ability to provide dynamically callable
static/class members. We don't believe this is important given the goal of
supporting dynamic languages like Python, but it could be explored if a use
case is discovered in the future. Such future work should keep in mind that
call syntax on metatypes is already meaningful, and that ambiguity would have
to be resolved somehow (e.g. through the most specific rule).

This proposal supports direct calls of values and methods, but subsets out
support for currying methods in Smalltalk family languages. This is just an
implementation limitation given the current state of currying in the Swift
compiler. Support can be added in the future if there is a specific need.

Source compatibility

This is a strictly additive proposal with no source breaking changes.

Effect on ABI stability

This is a strictly additive proposal with no ABI breaking changes.

Effect on API resilience

This has no impact on API resilience which is not already captured by other
language features.

Future directions

Dynamic member calling (for Smalltalk family languages)

In addition to supporting languages like Python and JavaScript, we would also
like to grow to support Smalltalk derived languages like Ruby and Squeak. These
languages resolve method calls using both the base name as well as the
keyword arguments at the same time. For example, consider this Ruby code:

```<code>time = Time.zone.parse(user_time)
</code>```

The Time.zone reference is a member lookup, but zone.parse(user_time) is a
method call, and needs to be handled differently than a lookup of zone.parse
followed by a direct function call.

This can be handled by adding a new @dynamicMemberCallable attribute, which
acts similarly to @dynamicCallable but enables dynamic member calls (instead
of dynamic calls of self).

@dynamicMemberCallable would have the following requirements:

func dynamicallyCallMethod(named: S1, withArguments: [T5]) -> T6
func dynamicallyCallMethod(named: S2, withKeywordArguments: [S3 : T7]) -> T8
```

<p>Here is a sample Ruby binding:</p>

<pre class="lang-swift prettyprint-override"><code>@dynamicMemberCallable @dynamicMemberLookup
struct RubyObject {
  @discardableResult
  func dynamicallyCallMethod(
    named: String, withKeywordArguments: KeyValuePairs<String, RubyObject>
  ) -> RubyObject { ... }

  // This is a `@dynamicMemberLookup` requirement.
  subscript(dynamicMember member: String) -> RubyObject {...}

  // ... other stuff ...
}
</code>```

General callable behavior

This proposal is mainly directed at dynamic language interoperability. For this
use case, it makes sense for the dynamicallyCall method to take a
variable-sized list of arguments where each argument has the same type.
However, it may be useful to support general callable behavior (akin to
operator() in C++) where the desugared "callable" method can have a fixed
number of arguments and arguments of different types.

For example, consider something like:

struct BinaryFunction<T1, T2, U> {
  func call(_ argument1: T1, _ argument1: T2) -> U { ... }
}
```

It is not unreasonable to look ahead to a day where sugaring such things is
supported, particularly when/if Swift gets variadic
generics.
This could allow typesafe n-ary smart function pointer types.

We feel that the approach outlined in this proposal supports this direction.
When/if a motivating use case for general callable behavior comes up, we can
simply add a new form to represent it and enhance the type checker to prefer
that during ambiguity resolution. If this is a likely direction, then it may be
better to name the attribute @callable instead of @dynamicCallable in
anticipation of that future growth.

We believe that general callable behavior and @dynamicCallable are orthogonal
features and should be evaluated separately.

Alternatives considered

Many alternatives were considered and discussed. Most of them are captured in
the "Alternatives Considered" section of
SE-0195.

Here are a few points raised in the discussion:

It was suggested that we use subscripts to represent the call
implementations instead of a function call, aligning with
@dynamicMemberLookup. We think that functions are a better fit here: the
reason @dynamicMemberLookup uses subscripts is to allow the members to be
l-values, but call results are not l-values.

It was requested that we design and implement the 'static callable' version
of this proposal in conjunction with the dynamic version proposed here. In
the author's opinion, it is important to consider static callable support as
a likely future direction to make sure that the two features sit well next
to each other and have a consistent design (something we believe this
proposal has done) but it doesn't make sense to join the two proposals. So
far, there have been no strong motivating use case presented for the static
callable version, and Swift lacks certain generics features (e.g. variadics)
that would be necessary to make static callables general. We feel that static
callable should stand alone on its own merits.

Title: What is @dynamicCallable in Swift?

Body:
Introduce user-defined dynamically "callable" types

Proposal: SE-0216

Authors: Chris Lattner, Dan Zheng

Review Manager: John McCall

Implementation: apple/swift#20305

Decision Notes: Rationale

Status: Implemented (Swift 5)

Introduction

This proposal is a follow-up to SE-0195 - Introduce User-defined "Dynamic Member
Lookup" Types,
which shipped in Swift 4.2. It introduces a new @dynamicCallable attribute, which marks
a type as being "callable" with normal syntax. It is simple syntactic sugar
which allows the user to write:

a = someValue(keyword1: 42, "foo", keyword2: 19)

and have it be rewritten by the compiler as:

a = someValue.dynamicallyCall(withKeywordArguments: [
    "keyword1": 42, "": "foo", "keyword2": 19
])

Many other languages have analogous features (e.g. Python "callables", C++ operator(), and
functors in many other languages), but the
primary motivation of this proposal is to allow elegant and natural interoperation with
dynamic languages in Swift.

Swift-evolution threads:
 - Pitch: Introduce user-defined dynamically "callable"
    types.
 - Pitch #2: Introduce user-defined dynamically “callable”
    types.
 - Current pitch thread: Pitch #3: Introduce user-defined dynamically “callable”
   types

Motivation and context

Swift is exceptional at interworking with existing C and Objective-C APIs and
we would like to extend this interoperability to dynamic languages like Python,
JavaScript, Perl, and Ruby. We explored this overall goal in a long design
process wherein the Swift evolution community evaluated multiple different
implementation approaches. The conclusion was that the best approach was to put
most of the complexity into dynamic language specific bindings written as
pure-Swift libraries, but add small hooks in Swift to allow these bindings to
provide a natural experience to their clients.
SE-0195
was the first step in this process, which introduced a binding to naturally
express member lookup rules in dynamic languages.

What does interoperability with Python mean? Let's explain this by looking at
an example. Here's some simple Python code:

class Dog:
    def __init__(self, name):
        self.name = name
        self.tricks = []  # creates a new empty list for each `Dog`

    def add_trick(self, trick):
        self.tricks.append(trick)

With the SE-0195 @dynamicMemberLookup feature
introduced in Swift 4.2, it is possible to implement a Python interoperability
layer
written in Swift. It interoperates with the Python runtime, and project all
Python values into a single PythonObject type. It allows us to call into the
Dog class like this:

// import DogModule.Dog as Dog
let Dog = Python.import.call(with: "DogModule.Dog")

// dog = Dog("Brianna")
let dog = Dog.call(with: "Brianna")

// dog.add_trick("Roll over")
dog.add_trick.call(with: "Roll over")

// dog2 = Dog("Kaylee").add_trick("snore")
let dog2 = Dog.call(with: "Kaylee").add_trick.call(with: "snore")

This also works with arbitrary other APIs as well. Here is an example working
with the Python pickle API and the builtin Python function open. Note that
we choose to put builtin Python functions like import and open into a
Python namespace to avoid polluting the global namespace, but other designs
are possible:

// import pickle
let pickle = Python.import.call(with: "pickle")

// file = open(filename)
let file = Python.open.call(with: filename)

// blob = file.read()
let blob = file.read.call()

// result = pickle.loads(blob)
let result = pickle.loads.call(with: blob)

This capability works well, but the syntactic burden of having to use
foo.call(with: bar, baz) instead of foo(bar, baz) is significant. Beyond
the syntactic weight, it directly harms code clarity by making code hard to
read and understand, cutting against a core value of Swift.

The proposed @dynamicCallable attribute directly solves this problem.
With it, these examples become more natural and clear, effectively matching the
original Python code in expressiveness:

// import DogModule.Dog as Dog
let Dog = Python.import("DogModule.Dog")

// dog = Dog("Brianna")
let dog = Dog("Brianna")

// dog.add_trick("Roll over")
dog.add_trick("Roll over")

// dog2 = Dog("Kaylee").add_trick("snore")
let dog2 = Dog("Kaylee").add_trick("snore")

Python builtins:

// import pickle
let pickle = Python.import("pickle")

// file = open(filename)
let file = Python.open(filename)

// blob = file.read()
let blob = file.read()

// result = pickle.loads(blob)
let result = pickle.loads(blob)

This proposal merely introduces a syntactic sugar - it does not add any new
semantic model to Swift. We believe that interoperability with scripting
languages is an important and rising need in the Swift community, particularly
as Swift makes inroads into the server development and machine learning
communities. This feature is also precedented in other languages (e.g. Scala's
Dynamic trait), and
can be used for other purposes besides language interoperability (e.g.
implementing dynamic proxy objects).

Proposed solution

We propose introducing a new @dynamicCallable attribute to the Swift language
which may be applied to structs, classes, enums, and protocols. This follows
the precedent of
SE-0195.

Before this proposal, values of these types are not valid in a call expression:
the only existing callable values in Swift are those with function types
(functions, methods, closures, etc) and metatypes (which are initializer
expressions like String(42)). Thus, it is always an error to "call" an
instance of a nominal type (like a struct, for instance).

With this proposal, types with the @dynamicCallable attribute on their
primary type declaration become "callable". They are required to implement at
least one of the following two methods for handling the call behavior:

func dynamicallyCall(withArguments: <#Arguments#>) -> <#R1#>
// `<#Arguments#>` can be any type that conforms to `ExpressibleByArrayLiteral`.
// `<#Arguments#>.ArrayLiteralElement` and the result type `<#R1#>` can be arbitrary.

func dynamicallyCall(withKeywordArguments: <#KeywordArguments#>) -> <#R2#>
// `<#KeywordArguments#>` can be any type that conforms to `ExpressibleByDictionaryLiteral`.
// `<#KeywordArguments#>.Key` must be a type that conforms to `ExpressibleByStringLiteral`.
// `<#KeywordArguments#>.Value` and the result type `<#R2#>` can be arbitrary.

// Note: in these type signatures, bracketed types like <#Arguments#> and <#KeywordArguments#>
// are not actual types, but rather any actual type that meets the specified conditions.

As stated above, <#Arguments#> and <#KeywordArguments#> can be any types
that conform to the
ExpressibleByArrayLiteral
and
ExpressibleByDictionaryLiteral
protocols, respectively. The latter is inclusive of
KeyValuePairs,
which supports duplicate keys, unlike Dictionary.
Thus, using KeyValuePairs is recommended to support duplicate keywords and
positional arguments (because positional arguments are desugared as keyword
arguments with the empty string "" as the key).

If a type implements the withKeywordArguments: method, it may be dynamically
called with both positional and keyword arguments: positional arguments have
the empty string "" as the key. If a type only implements the
withArguments: method but is called with keyword arguments, a compile-time
error is emitted.

Since dynamic calls are syntactic sugar for direct calls to dynamicallyCall
methods, additional behavior of the dynamicallyCall methods is directly
forwarded.  For example, if a dynamicallyCall method is marked with throws
or @discardableResult, then the corresponding sugared dynamic call will
forward that behavior.

Ambiguity resolution: most specific match

Since there are two @dynamicCallable methods, there may be multiple ways to
handle some dynamic calls. What happens if a type specifies both the
withArguments: and withKeywordArguments: methods?

We propose that the type checker resolve this ambiguity towards the tightest
match based on syntactic form of the expression. The exact rules are:

If a @dynamicCallable type implements the withArguments: method and it is
called with no keyword arguments, use the withArguments: method.

In all other cases, attempt to use the withKeywordArguments: method.

This includes the case where a @dynamicCallable type implements the
withKeywordArguments: method and it is called with at least one keyword
argument.

This also includes the case where a @dynamicCallable type implements only
the withKeywordArguments: method (not the withArguments: method) and
it is called with no keyword arguments.

If @dynamicCallable type does not implement the withKeywordArguments:
method but the call site has keyword arguments, an error is emitted.

Here are some toy illustrative examples:

@dynamicCallable
struct Callable {
  func dynamicallyCall(withArguments args: [Int]) -> Int { return args.count }
}
let c1 = Callable()
c1() // desugars to `c1.dynamicallyCall(withArguments: [])`
c1(1, 2) // desugars to `c1.dynamicallyCall(withArguments: [1, 2])`
c1(a: 1, 2) // error: `Callable` does not define the 'withKeywordArguments:' method

@dynamicCallable
struct KeywordCallable {
  func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Int>) -> Int {
    return args.count
  }
}
let c2 = KeywordCallable()
c2() // desugars to `c2.dynamicallyCall(withKeywordArguments: [:])`
c2(1, 2) // desugars to `c2.dynamicallyCall(withKeywordArguments: ["": 1, "": 2])`
c2(a: 1, 2) // desugars to `c2.dynamicallyCall(withKeywordArguments: ["a": 1, "": 2])`

@dynamicCallable
struct BothCallable {
  func dynamicallyCall(withArguments args: [Int]) -> Int { return args.count }
  func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Int>) -> Int {
    return args.count
  }
}
let c3 = BothCallable()
c3() // desugars to `c3.dynamicallyCall(withArguments: [])`
c3(1, 2) // desugars to `c3.dynamicallyCall(withArguments: [1, 2])`
c3(a: 1, 2) // desugars to `c3.dynamicallyCall(withKeywordArguments: ["a": 1, "": 2])`

This ambiguity resolution rule works out naturally given the behavior of the
Swift type checker, because it only resolves call expressions when the type
of the base expression is known. At that point, it knows whether the base is a
function type, metatype, or a valid @dynamicCallable type, and it knows the
syntactic form of the call.

This proposal does not require massive or invasive changes to the constraint
solver. Please look at the implementation for more details.

Example usage

Here, we sketch some example bindings to show how this could be used in
practice. Note that there are lots of design decisions that are orthogonal to
this proposal (e.g. how to handle exceptions) that we aren't going into here.
This is just to show how this feature provides an underlying facility that
language bindings authors can use to achieve their desired result. These
examples also show @dynamicMemberLookup to illustrate how they work together,
but elides other implementation details.

JavaScript supports callable objects but does not have keyword arguments.

Here is a sample JavaScript binding:

@dynamicCallable @dynamicMemberLookup
struct JSValue {
  // JavaScript doesn't have keyword arguments.
  @discardableResult
  func dynamicallyCall(withArguments: [JSValue]) -> JSValue { ... }

  // This is a `@dynamicMemberLookup` requirement.
  subscript(dynamicMember member: JSValue) -> JSValue {...}

  // ... other stuff ...
}

On the other hand, a common JavaScript pattern is to take a dictionary of
values as a stand-in for argument labels (called like
example({first: 1, second: 2, third: 3}) in JavaScript). A JavaScript bridge
in Swift could choose to implement keyword argument support to allow this to be
called as example(first: 1, second: 2, third: 3) from Swift code (kudos to
Ben Rimmington for this
observation).

Python does support keyword arguments. While a Python binding could implement
only the withKeywordArguments: method, it is be better to implement both the
non-keyword and keyword forms to make the non-keyword case slightly more
efficient (avoid allocating temporary storage) and to make direct calls with
positional arguments nicer (x.dynamicallyCall(withArguments: 1, 2) instead of
x.dynamicallyCall(withKeywordArguments: ["": 1, "": 2])).

Here is a sample Python binding:

@dynamicCallable @dynamicMemberLookup
struct PythonObject {
  // Python supports arbitrary mixes of keyword arguments and non-keyword
  // arguments.
  @discardableResult
  func dynamicallyCall(
    withKeywordArguments: KeyValuePairs<String, PythonObject>
  ) -> PythonObject { ... }

  // An implementation of a Python binding could choose to implement this
  // method as well, avoiding allocation of a temporary array.
  @discardableResult
  func dynamicallyCall(withArguments: [PythonObject]) -> PythonObject { ... }

  // This is a `@dynamicMemberLookup` requirement.
  subscript(dynamicMember member: String) -> PythonObject {...}

  // ... other stuff ...
}

Limitations

Following the precedent of SE-0195, this attribute must be placed on the
primary definition of a type, not on an extension.

This proposal does not introduce the ability to provide dynamically callable
static/class members. We don't believe this is important given the goal of
supporting dynamic languages like Python, but it could be explored if a use
case is discovered in the future. Such future work should keep in mind that
call syntax on metatypes is already meaningful, and that ambiguity would have
to be resolved somehow (e.g. through the most specific rule).

This proposal supports direct calls of values and methods, but subsets out
support for currying methods in Smalltalk family languages. This is just an
implementation limitation given the current state of currying in the Swift
compiler. Support can be added in the future if there is a specific need.

Source compatibility

This is a strictly additive proposal with no source breaking changes.

Effect on ABI stability

This is a strictly additive proposal with no ABI breaking changes.

Effect on API resilience

This has no impact on API resilience which is not already captured by other
language features.

Future directions

Dynamic member calling (for Smalltalk family languages)

In addition to supporting languages like Python and JavaScript, we would also
like to grow to support Smalltalk derived languages like Ruby and Squeak. These
languages resolve method calls using both the base name as well as the
keyword arguments at the same time. For example, consider this Ruby code:

time = Time.zone.parse(user_time)

The Time.zone reference is a member lookup, but zone.parse(user_time) is a
method call, and needs to be handled differently than a lookup of zone.parse
followed by a direct function call.

This can be handled by adding a new @dynamicMemberCallable attribute, which
acts similarly to @dynamicCallable but enables dynamic member calls (instead
of dynamic calls of self).

@dynamicMemberCallable would have the following requirements:

func dynamicallyCallMethod(named: S1, withArguments: [T5]) -> T6
func dynamicallyCallMethod(named: S2, withKeywordArguments: [S3 : T7]) -> T8

Here is a sample Ruby binding:

@dynamicMemberCallable @dynamicMemberLookup
struct RubyObject {
  @discardableResult
  func dynamicallyCallMethod(
    named: String, withKeywordArguments: KeyValuePairs<String, RubyObject>
  ) -> RubyObject { ... }

  // This is a `@dynamicMemberLookup` requirement.
  subscript(dynamicMember member: String) -> RubyObject {...}

  // ... other stuff ...
}

General callable behavior

This proposal is mainly directed at dynamic language interoperability. For this
use case, it makes sense for the dynamicallyCall method to take a
variable-sized list of arguments where each argument has the same type.
However, it may be useful to support general callable behavior (akin to
operator() in C++) where the desugared "callable" method can have a fixed
number of arguments and arguments of different types.

For example, consider something like:

struct BinaryFunction<T1, T2, U> {
  func call(_ argument1: T1, _ argument1: T2) -> U { ... }
}

It is not unreasonable to look ahead to a day where sugaring such things is
supported, particularly when/if Swift gets variadic
generics.
This could allow typesafe n-ary smart function pointer types.

We feel that the approach outlined in this proposal supports this direction.
When/if a motivating use case for general callable behavior comes up, we can
simply add a new form to represent it and enhance the type checker to prefer
that during ambiguity resolution. If this is a likely direction, then it may be
better to name the attribute @callable instead of @dynamicCallable in
anticipation of that future growth.

We believe that general callable behavior and @dynamicCallable are orthogonal
features and should be evaluated separately.

Alternatives considered

Many alternatives were considered and discussed. Most of them are captured in
the "Alternatives Considered" section of
SE-0195.

Here are a few points raised in the discussion:

It was suggested that we use subscripts to represent the call
implementations instead of a function call, aligning with
@dynamicMemberLookup. We think that functions are a better fit here: the
reason @dynamicMemberLookup uses subscripts is to allow the members to be
l-values, but call results are not l-values.

It was requested that we design and implement the 'static callable' version
of this proposal in conjunction with the dynamic version proposed here. In
the author's opinion, it is important to consider static callable support as
a likely future direction to make sure that the two features sit well next
to each other and have a consistent design (something we believe this
proposal has done) but it doesn't make sense to join the two proposals. So
far, there have been no strong motivating use case presented for the static
callable version, and Swift lacks certain generics features (e.g. variadics)
that would be necessary to make static callables general. We feel that static
callable should stand alone on its own merits.


来源: stackexchange

问:
How to return LocalDateTime from REST controller endpoint?
I'm writing a REST controller in Spring- java, and one of my endpoints should return a LocalDateTime variable.

```<code>@GetMapping(path = "/lastDateTimeOfReset")
LocalDateTime fetchLastDateTimeOfReset() {
   return mongoManagerService.fetchLastDateTimeOfReset();
}
</code>```

This is the client request:

```<code>ResponseEntity<LocalDateTime> lastDateEntity = restTemplate.getForEntity(url, LocalDateTime.class);
</code>```

I get the following excepation on my client side:

```<code>org.springframework.web.client.RestClientException:
Error while extracting response for type [class java.time.LocalDateTime] and content type [application/json;charset=UTF-8];
nested exception is org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Expected array or string.;
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
at [Source: (PushbackInputStream); line: 1, column: 1]
</code>```

I checked the return value on debug mode and it is a valid LocalDateTime.
Why is this exception thrown and how to overcome it?

答:
You can use String to overcome this issue.

```<code>@GetMapping(path = "/lastDateTimeOfReset")
String fetchLastDateTimeOfReset() {
   return (mongoManagerService.fetchLastDateTimeOfReset()).toString();
}
</code>```

Client Request:

```<code>ResponseEntity<String> lastDateEntity = restTemplate.getForEntity(url, String.class);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm writing a REST controller in Spring- java, and one of my endpoints should return a LocalDateTime variable.

@GetMapping(path = "/lastDateTimeOfReset")
LocalDateTime fetchLastDateTimeOfReset() {
   return mongoManagerService.fetchLastDateTimeOfReset();
}

This is the client request:

ResponseEntity<LocalDateTime> lastDateEntity = restTemplate.getForEntity(url, LocalDateTime.class);

I get the following excepation on my client side:

org.springframework.web.client.RestClientException:
Error while extracting response for type [class java.time.LocalDateTime] and content type [application/json;charset=UTF-8];
nested exception is org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Expected array or string.;
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
at [Source: (PushbackInputStream); line: 1, column: 1]

I checked the return value on debug mode and it is a valid LocalDateTime.
Why is this exception thrown and how to overcome it?

Body:
You can use String to overcome this issue.

@GetMapping(path = "/lastDateTimeOfReset")
String fetchLastDateTimeOfReset() {
   return (mongoManagerService.fetchLastDateTimeOfReset()).toString();
}

Client Request:

ResponseEntity<String> lastDateEntity = restTemplate.getForEntity(url, String.class);


问:
skipping shippingmethod step in magento onepage checkout
Busy on a project and I need to skip the shipping method step. Shop contains simple and grouped products. There is no need for shipping so I tried:
- disabling the shipping methods results in not able to checkout
- only turning on the free shipping results in the step still visible

changing template code and deleting the shipping_methods section from progress.phtml or setting is_show to false results in no able to checkout

changing the template as above and and the opcheckout.js so it skips the shipping_methods step and goes to payment results in shipping_address not pointing to payment (skipping shipping_methods).

What am I missing? Can anyone help me out?

Thanks in advance!

答:
You can use virtual products instead of simple.
Or you can make some code changes like in this article.</p>

ContentLicense: CC BY-SA 3.0


问:
React Navigation 5 - Native Stack Navigator with custom header which has a searchbar
I'm currently in a project for which we are using React Navigation 5 with the native stack navigator due to its increased performance. We are needing to add a searchbar to the header cause the client isn't gonna like it to be somewhere else. Is there any way to make a custom header?
using options={{ headerShown: false }} is not an option cause inside the native stack navigator we have a bottom stack navigator and inside this bottom tab navigator we have a top stack navigator with the screens inside it. So using headerShown: false and a custom header inside the screens would only render it below the top tabs and that would not be acceptable.
Any ideas on how to make this? is using the common stack navigator with a custom react element as the header prop the only solution?

Greatly appreciate any ideas on how to solve this.

答:
have a look at https://reactnavigation.org/docs/en/stack-navigator.html
You can pass in header to the options prop and use a custom header.


问:
Remove rows which nothing in more than one columns
```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where",""), stringsAsFactors = FALSE)
</code>```

How is it possible to check for text1, text2, text3 column if all of them have cells with nothing written how to remove it?

Example of expected output

```<code>data.frame(id = c(1,2,3), text1 = c("sth","","another"), text2 = c("more","another","add"), text3 = c("final","and","where"), stringsAsFactors = FALSE)
</code>```

答:
Suggestion solution using dplyr:

```<code>df <- data.frame(id = c(1,2,3,4),
           text1 = c("sth","","another",""),
           text2 = c("more","another","add",""),
           text3 = c("final","and","where",""),
           stringsAsFactors = FALSE)

library(dplyr)
df %>%
  filter_at(vars(starts_with("text")), any_vars(!. %in% c("")))
</code>```

Returns:

```<code>  id   text1   text2 text3
1  1     sth    more final
2  2         another   and
3  3 another     add where
</code>```

Body:
data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where",""), stringsAsFactors = FALSE)

How is it possible to check for text1, text2, text3 column if all of them have cells with nothing written how to remove it?

Example of expected output

data.frame(id = c(1,2,3), text1 = c("sth","","another"), text2 = c("more","another","add"), text3 = c("final","and","where"), stringsAsFactors = FALSE)

Body:
Suggestion solution using dplyr:

df <- data.frame(id = c(1,2,3,4),
           text1 = c("sth","","another",""),
           text2 = c("more","another","add",""),
           text3 = c("final","and","where",""),
           stringsAsFactors = FALSE)

library(dplyr)
df %>%
  filter_at(vars(starts_with("text")), any_vars(!. %in% c("")))

Returns:

  id   text1   text2 text3
1  1     sth    more final
2  2         another   and
3  3 another     add where


问:
R's paste function equivalent in BASH?
I'm trying to translate this piece of R code into bash:

```<code>year <- 2010
emmissions <- paste("Emmision table from ",year, sep="")
em_table <- read.table(emmissions, head=F, as.is=T)

for (i in 1:nrow(em_table)) {
        print(em_table[i,1])
}
</code>```

But can't figure out how to translate paste function to concatenate string with variable. Expected outcome would be this script translated into bash code.

答:
There already is an accepted answer but here is a awk solution.

Tested with just one file, named "test2020".

```<code>for var in 2020;
do
  awk '{print $1}' "test${var}"
done
</code>```

Output:

```<code>1
2
3
</code>```

To read both columns the awk code line would be

```<code>awk '{print $1 $2}' "test${var}"
</code>```

or, since the OP says the files only have two columns,

```<code>awk '{print $0}' "test${var}"
</code>```

The file contents are:

```<code>1 a
2 b
3 c
</code>```

Title: R's paste function equivalent in BASH?

Body:
I'm trying to translate this piece of R code into bash:

year <- 2010
emmissions <- paste("Emmision table from ",year, sep="")
em_table <- read.table(emmissions, head=F, as.is=T)

for (i in 1:nrow(em_table)) {
        print(em_table[i,1])
}

But can't figure out how to translate paste function to concatenate string with variable. Expected outcome would be this script translated into bash code.

Body:
There already is an accepted answer but here is a awk solution.

Tested with just one file, named "test2020".

for var in 2020;
do
  awk '{print $1}' "test${var}"
done

Output:

1
2
3

To read both columns the awk code line would be

awk '{print $1 $2}' "test${var}"

or, since the OP says the files only have two columns,

awk '{print $0}' "test${var}"

The file contents are:

1 a
2 b
3 c


问:
Find file name from full file path
Is there a way to extract the file name from the file full path (part of a file path) without the hassle of manipulating string?

The equivalent in Java would be:

```<code>File f = new File ("C:/some_dir/a")
f.getName() //output a
f.getFullAbsolutePath() //output c:/some_dir/a
</code>```

答:
The tidyverse equivalent lives in the fs package. {fs} makes use of libuv under the hood.

library("fs")

path_file("/some/path/to/file.xyz")
#> [1] "file.xyz"

path_dir("/some/path/to/file.xyz")
#> [1] "/some/path/to"
```

Created on 2020-02-19 by the reprex package (v0.3.0)

Title: Find file name from full file path

Body:
Is there a way to extract the file name from the file full path (part of a file path) without the hassle of manipulating string?

The equivalent in Java would be:

File f = new File ("C:/some_dir/a")
f.getName() //output a
f.getFullAbsolutePath() //output c:/some_dir/a

Body:
The tidyverse equivalent lives in the fs package. {fs} makes use of libuv under the hood.

library("fs")

path_file("/some/path/to/file.xyz")
#> [1] "file.xyz"

path_dir("/some/path/to/file.xyz")
#> [1] "/some/path/to"

Created on 2020-02-19 by the reprex package (v0.3.0)


问:
create authentication web service with token
I'm working with express in order to create web services I'm a beginner and now I need to make an authentication service for my application with mysql and express with tokens someone could help me</p>

答: try using jwt package or you can use passport.</p>


问:
Creating & using libraries in both Clojure and ClojureScript
I've just written some ClojureScript code, only to find out that I couldn't access one of the libraries listed in my project.clj's dependencies. Is this correct, i.e. that you can't use Clojure libraries from CLJS unless they're specifically designed to allow it?

If so, how much extra work is required to take a Clojure library that doesn't use any Java interop, and would itself be valid ClojureScript code, and make it useable from ClojureScript? From looking around GitHub, many libs appear to have separate source directories for clj and cljs code. Can such a library be added to my project.clj and be used immediately from either platform?

答:
I see that the answers were given in 2013, but as of 2020, this is still the case with CLJS version 1.10. Its still not possible to use just any Clojure library, unless the library has been made CLJS compatible.Building with shadow-cljs will give build error like:

```<code>The required namespace "clojure.data.json" is not available, it was required by "bharati/binita/frontend/demo3/main.cljs".
"clojure/data/json.clj" was found on the classpath. Should this be a .cljs file?
</code>```

I could not see any solution to that,other than using any other alternative library that is CLJS compatible.

Body:
I see that the answers were given in 2013, but as of 2020, this is still the case with CLJS version 1.10. Its still not possible to use just any Clojure library, unless the library has been made CLJS compatible.Building with shadow-cljs will give build error like:

The required namespace "clojure.data.json" is not available, it was required by "bharati/binita/frontend/demo3/main.cljs".
"clojure/data/json.clj" was found on the classpath. Should this be a .cljs file?

I could not see any solution to that,other than using any other alternative library that is CLJS compatible.


问:
Creating a Master excel file from dynamic CSV output using Python
I am trying to create a repository "Master" excel file from a CSV which will be generated and overwritten every couple of hours. The code below creates a new excel file and writes the content from "combo1.csv" to "master.xlsx". However, whenever the combo1 file is updated, the code basically overwrites the contents in the "master.xlsx" file. I need to append the contents from "combo1" to "Master" without the headers being inserted every time. Can someone help me with this?   </p>

```<code>import pandas as pd

writer = pd.ExcelWriter('master.xlsx', engine='xlsxwriter')
df = pd.read_csv('combo1.csv')
df.to_excel(writer, sheet_name='sheetname')
writer.save()
</code>```

答:
```<code>import pandas as pd
from openpyxl import load_workbook

# new dataframe with same columns
df = pd.read_csv('combo.csv')
writer = pd.ExcelWriter('master.xlsx', engine='openpyxl')
# try to open an existing workbook
writer.book = load_workbook('master.xlsx')
# copy existing sheets
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
# read existing file
reader = pd.read_excel(r'master.xlsx')
# write out the new sheet
df.to_excel(writer, index=False, header=False, startrow=len(reader) + 1)

writer.close()
</code>```

Note that a Master has to be created before running the script

Body:
I am trying to create a repository "Master" excel file from a CSV which will be generated and overwritten every couple of hours. The code below creates a new excel file and writes the content from "combo1.csv" to "master.xlsx". However, whenever the combo1 file is updated, the code basically overwrites the contents in the "master.xlsx" file. I need to append the contents from "combo1" to "Master" without the headers being inserted every time. Can someone help me with this?

import pandas as pd

writer = pd.ExcelWriter('master.xlsx', engine='xlsxwriter')
df = pd.read_csv('combo1.csv')
df.to_excel(writer, sheet_name='sheetname')
writer.save()

Body:
import pandas as pd
from openpyxl import load_workbook

# new dataframe with same columns
df = pd.read_csv('combo.csv')
writer = pd.ExcelWriter('master.xlsx', engine='openpyxl')
# try to open an existing workbook
writer.book = load_workbook('master.xlsx')
# copy existing sheets
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
# read existing file
reader = pd.read_excel(r'master.xlsx')
# write out the new sheet
df.to_excel(writer, index=False, header=False, startrow=len(reader) + 1)

writer.close()

Note that a Master has to be created before running the script


问:
nodes; user download via remote fileserver

I have a webserver and a fileserver. The webserver is allowed to access the fileserver (ip filter). I would like to share a file/make it downloadable from the fileserver, but without having to make a public access on the fileserver.
I'm thinking about making a api on the fileserver (small webserver)

```<code>router.get('/download', async (req, res) => {
    res.header("Access-Control-Allow-Origin", "https://testserver");
    res.header("Access-Control-Allow-Headers", "X-requested-With");
    res.download(__dirname + '/../download/'+req.query.file, req.query.file)
})
</code>```

And then download the file via the webserver and then send it to the browser/user

```<code>router('/downloadOnTheWebserver', (req,res) => {
...
res.download(request('testserver' + someFileToDownload').pipe(make a downloadstream somehow))
</code>```

Is that the way to do this, and how...?

答:
Well I did this:

Fileserver:

```<code>router.get('/download', async (req, res) => {
res.download(__dirname + '/folder/filename')
</code>```

})

Webserver:

```<code>var pdfstream = request.get("https://downloadlinkonfileserver)
res.attachment('filename');
pdfstream.pipe(res)
res.on('finish',function (err,data){
  if(err){
    throw err
  } else {
    console.log('It went well');
}
</code>```

Body:
I have a webserver and a fileserver. The webserver is allowed to access the fileserver (ip filter). I would like to share a file/make it downloadable from the fileserver, but without having to make a public access on the fileserver.
I'm thinking about making a api on the fileserver (small webserver)

router.get('/download', async (req, res) => {
    res.header("Access-Control-Allow-Origin", "https://testserver");
    res.header("Access-Control-Allow-Headers", "X-requested-With");
    res.download(__dirname + '/../download/'+req.query.file, req.query.file)
})

And then download the file via the webserver and then send it to the browser/user

router('/downloadOnTheWebserver', (req,res) => {
...
res.download(request('testserver' + someFileToDownload').pipe(make a downloadstream somehow))

Is that the way to do this, and how...?

Body:
Well I did this:

Fileserver:

router.get('/download', async (req, res) => {
res.download(__dirname + '/folder/filename')

})

Webserver:

var pdfstream = request.get("https://downloadlinkonfileserver)
res.attachment('filename');
pdfstream.pipe(res)
res.on('finish',function (err,data){
  if(err){
    throw err
  } else {
    console.log('It went well');
}


问:
How to copy one tablerow to another table using listrow?
I'm trying to copy data rows from different tables and usually i would setup a conveluted setup
counting rows and columns and a couple of level deep for loops.

However, it appears the modern way to go is using listrows.
I tried going over the guide always referenced at https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables

However i seem to miss this  "sometable.listobject(1).rows = differentable.listrow(1).rows"  roughly...

My code

```<code>Sub GenerateOverview()
Dim MainWs As Worksheet
Set MainWs = Worksheets("Overview")
Dim mainTbl As ListObject
Set mainTbl = MainWs.ListObjects(1)

' Later add for each sheet ----

Dim ws As Worksheet
Set ws = Worksheets("ABD")   ' ABD to be replaced with activesheet.name LATER
Dim tbl As ListObject
Set tbl = ws.ListObjects(1)

Dim TopXRange As Integer
TopXRange = 10  ' to be changed to user defined range

Dim i As Integer
i = 0

For i = 1 To TopXRange
    mainTbl.DataBodyRange.Rows(i) = tbl.DataBodyRange.Rows(i)
      ' THIS only produces empty cells on maintbl and not the content from tbl.
Next i

' end for each sheet ----

End Sub
</code>```

Any advice?

Working solution for my task..

```<code>Sub GenerateOverview()
Dim MainWs As Worksheet
Set MainWs = Worksheets("Overview")
Dim mainTbl As ListObject
Set mainTbl = MainWs.ListObjects(1)

Dim ws As Worksheet
Dim TopXRange As Integer
TopXRange = 10
Dim i As Integer
i = 1
Dim tbl As ListObject
Dim newI
Dim mainRows As Integer

For Each ws In ThisWorkbook.Worksheets

    If ws.Name = MainWs.Name Then GoTo skip

    Set ws = Worksheets(ws.Name)
    Set tbl = ws.ListObjects(1)

    mainRows = mainTbl.ListRows.Count
    If mainRows = 0 Then mainRows = 1

    For i = newI To TopXRange

        mainTbl.ListRows.Add (mainRows)
        mainTbl.ListRows(mainRows).Range.Value = tbl.ListRows(i + 1).Range.Value

    Next i

skip:
Next
End sub
</code>```

答:
Still not sure I follow. You probably need to insert a row into your second table before transferring. Something like this works:</p>

```<code>Sub x()

Dim t1 As ListObject, t2 As ListObject

Set t1 = Sheet1.ListObjects("Table1")
Set t2 = Sheet1.ListObjects("Table2")

t2.ListRows.Add (3) 'insert new row 3 into second table
t2.ListRows(3).Range.Value = t1.ListRows(4).Range.Value 'transfer to new row from first table

End Sub
</code>```

Body:
I'm trying to copy data rows from different tables and usually i would setup a conveluted setup
counting rows and columns and a couple of level deep for loops.

However, it appears the modern way to go is using listrows.
I tried going over the guide always referenced at https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables

However i seem to miss this  "sometable.listobject(1).rows = differentable.listrow(1).rows"  roughly...

My code

Sub GenerateOverview()
Dim MainWs As Worksheet
Set MainWs = Worksheets("Overview")
Dim mainTbl As ListObject
Set mainTbl = MainWs.ListObjects(1)

' Later add for each sheet ----

Dim ws As Worksheet
Set ws = Worksheets("ABD")   ' ABD to be replaced with activesheet.name LATER
Dim tbl As ListObject
Set tbl = ws.ListObjects(1)

Dim TopXRange As Integer
TopXRange = 10  ' to be changed to user defined range

Dim i As Integer
i = 0

For i = 1 To TopXRange
    mainTbl.DataBodyRange.Rows(i) = tbl.DataBodyRange.Rows(i)
      ' THIS only produces empty cells on maintbl and not the content from tbl.
Next i

' end for each sheet ----

End Sub

Any advice?

Working solution for my task..

Sub GenerateOverview()
Dim MainWs As Worksheet
Set MainWs = Worksheets("Overview")
Dim mainTbl As ListObject
Set mainTbl = MainWs.ListObjects(1)

Dim ws As Worksheet
Dim TopXRange As Integer
TopXRange = 10
Dim i As Integer
i = 1
Dim tbl As ListObject
Dim newI
Dim mainRows As Integer

For Each ws In ThisWorkbook.Worksheets

    If ws.Name = MainWs.Name Then GoTo skip

    Set ws = Worksheets(ws.Name)
    Set tbl = ws.ListObjects(1)

    mainRows = mainTbl.ListRows.Count
    If mainRows = 0 Then mainRows = 1

    For i = newI To TopXRange

        mainTbl.ListRows.Add (mainRows)
        mainTbl.ListRows(mainRows).Range.Value = tbl.ListRows(i + 1).Range.Value

    Next i

skip:
Next
End sub

Body:
Still not sure I follow. You probably need to insert a row into your second table before transferring. Something like this works:

Sub x()

Dim t1 As ListObject, t2 As ListObject

Set t1 = Sheet1.ListObjects("Table1")
Set t2 = Sheet1.ListObjects("Table2")

t2.ListRows.Add (3) 'insert new row 3 into second table
t2.ListRows(3).Range.Value = t1.ListRows(4).Range.Value 'transfer to new row from first table

End Sub


问:
Form validation for a specific numeric input (numeric range + number 0)
I have to validate an input where the numeric input value could
 range from 110 to 150
 OR
 could be zero.

Is there any chance I can do it with HTML5 validation I'm currently using for the other inputs? If not, what's the best way to achieve that?

答:
```<code>  <input type="text" pattern="(0|1[1-4][0-9]|150)" />
</code>```

This was the answer I was looking for :)

Body:
  <input type="text" pattern="(0|1[1-4][0-9]|150)" />

This was the answer I was looking for :)


问:
Edabit task doesn't show correct result
I'm doing a simple task which requires to sort a list by expression result and running this code:

```<code>   def sort_by_answer(lst):
        ans = []
        dict = {}
        for i in lst:
            if 'x' in i:
                i = i.replace('x', '*')
            dict.update({i: eval(i)})
        dict = {k: v for k, v in sorted(dict.items(), key=lambda item: item[1])}
        res = list(dict.keys())
        for i in res:
            if '*' in i:
                i = i.replace('*', 'x')
                ans.append(i)
            else:
                ans.append(i)
        return ans
</code>```

It checks out but the site for which i'm doing this test(here's a link to the task(https://edabit.com/challenge/9zf6scCreprSaQAPq) tells my that my list is not correctly sorted, which it is, can someone help me improve this code or smth so it works in every case-scenario?

P.S.

```<code>if 'x' in i:
      i = i.replace('x', '*')
</code>```

This is made so i can use the eval function but the site input has 'x' instead of '*' in their lists..

Title: Edabit task doesn't show correct result

Body:
I'm doing a simple task which requires to sort a list by expression result and running this code:

   def sort_by_answer(lst):
        ans = []
        dict = {}
        for i in lst:
            if 'x' in i:
                i = i.replace('x', '*')
            dict.update({i: eval(i)})
        dict = {k: v for k, v in sorted(dict.items(), key=lambda item: item[1])}
        res = list(dict.keys())
        for i in res:
            if '*' in i:
                i = i.replace('*', 'x')
                ans.append(i)
            else:
                ans.append(i)
        return ans

It checks out but the site for which i'm doing this test(here's a link to the task(https://edabit.com/challenge/9zf6scCreprSaQAPq) tells my that my list is not correctly sorted, which it is, can someone help me improve this code or smth so it works in every case-scenario?

P.S.

if 'x' in i:
      i = i.replace('x', '*')

This is made so i can use the eval function but the site input has 'x' instead of '*' in their lists..

Body:
You can try this. But using eval is dangerous on untrusted strings.

In [63]: a=['1 + 1', '1 + 7', '1 + 5', '1 + 4']

In [69]: def evaluate(_str):
    ...:     return eval(_str.replace('x','*'))

output

In [70]: sorted(a,key=evaluate)
Out[70]: ['1 + 1', '1 + 4', '1 + 5', '1 + 7']

In [71]: sorted(['4 - 4', '2 - 2', '5 - 5', '10 - 10'],key=evaluate)
Out[71]: ['4 - 4', '2 - 2', '5 - 5', '10 - 10']

In [72]: sorted(['2 + 2', '2 - 2', '2 x 1'],key=evaluate)
Out[72]: ['2 - 2', '2 x 1', '2 + 2']


问:
How to provide filter tab in timelion charts?
I am trying out some timelion visualizations in Kibana. In it I am not sure how to provide filter tab for the data.
For example, yearly country population data and filter tab to filter it based on zone and state.
Usually a timelion expression is just like ".es()" and some functions which can be appended to it like

```<code>.es(*).bars().label("Population")
</code>```

I don't want to specify filter under ".es(q=???)" as this will make the filter static and the user won't be able to use filtering directly. ( In this case, every time user has to go to edit timelion window and edit filter there.)

答:
you can specify a lucene query string as the q argument to .es() as in
.es(q=field:value)
That query string would only affect this time series and not interfere with the rest of your dashboard.</p>

Body:
I am trying out some timelion visualizations in Kibana. In it I am not sure how to provide filter tab for the data.
For example, yearly country population data and filter tab to filter it based on zone and state.
Usually a timelion expression is just like ".es()" and some functions which can be appended to it like

.es(*).bars().label("Population")

I don't want to specify filter under ".es(q=???)" as this will make the filter static and the user won't be able to use filtering directly. ( In this case, every time user has to go to edit timelion window and edit filter there.)


问:
How to add a drawer navigator React-Navigation v4
I have this code for creating a drawer navigator. But I can't open my drawer through left to right slide. Can anyone please help me to solve my problem. I am new to react-native. I am using react-navigation v4 and react-navigation-drawer for the drawer navigator.</p>

```<code>const EMBotomTabScreen = createDrawerNavigator ({
  SUMMARY: {
    screen : EMNavigator,
    navigationOptions :{
      animationEnabled : 'true',
      // headerLeft : <HamburgerIcon navigationProps={ navigation }/>,
      swipeEnabled: true,
      tabBarOptions: {
        activeTintColor: '#369841',
        //activeBackgroundColor : '#f2f2f2',
        inactiveTintColor : 'gray',
        inactiveBackgroundColor : '#adc1b8',
        borderRightWidth:2,
        borderRightColor:'blue',
        labelStyle: {
          fontSize: 13,
        },
        style: {
          backgroundColor: '#f2f2f2',
          // borderRightWidth:2,
          // borderRightColor:'blue'
        },
        indicatorStyle: {
            backgroundColor: 'red',
        },
      },

      tabStyle: {
        backgroundColor: 'green',
        borderRightWidth:2,
        borderRightColor:'blue'
      },
      indicatorStyle : {
        backgroundColor : 'red'
      },
      tabBarIcon: ({ focused, tintColor }) => {
        const iconName = `ios-desktop`;
        return <Image source={require('../assets/aaaaa.png')} size={27} color={tintColor} />;
    },
    }
  },
  DEMAND: {
    screen : EMDemandNavigator,
    navigationOptions : {
      tabBarOptions: {
        activeTintColor: '#369841',
       // activeBackgroundColor : '#f2f2f2',
        inactiveTintColor : 'gray',
        inactiveBackgroundColor : '#adc1b8',
        labelStyle: {
          fontSize: 13,
        },
        style: {
          backgroundColor: '#f2f2f2',
        },
      },
      tabBarIcon: ({ focused, tintColor }) => {
        const iconName = `ios-cloud`;
        return <Image source={require('../assets/aaaaaaa.png')} size={27} color={tintColor} />;
    },
    }
  },
  ALARM: {
    screen : EMAlarmNavigator,
    navigationOptions : {
      animationEnabled : 'true',
      swipeEnabled: true,
      tabBarOptions: {
        activeTintColor: '#369841',
        //activeBackgroundColor : '#f2f2f2',
        inactiveTintColor : 'gray',
        inactiveBackgroundColor : '#adc1b8',
        borderRightWidth:2,
        borderRightColor:'blue',
        labelStyle: {
          fontSize: 13,
        },
        style: {
          backgroundColor: '#f2f2f2',
          // borderRightWidth:2,
          // borderRightColor:'blue'
        },
        indicatorStyle: {
            backgroundColor: 'red',
        },
      },

      tabStyle: {
        backgroundColor: 'green',
        borderRightWidth:2,
        borderRightColor:'blue'
      },
      indicatorStyle : {
        backgroundColor : 'red'
      },
      tabBarIcon: ({ focused, tintColor }) => {
        const iconName = `bell-o`;
        return <Icons name={iconName} size={27} color={tintColor} />;
    },
    }
  }
</code>```

答:
You can get an idea from the below given code.

```<code>import Splash from '../Splash/Splash';
import Home from '../screens/Home';
import DrawerScreen from '../screens/DrawerScreen'
//And many more
import {createStackNavigator,
    createSwitchNavigator,
    createAppContainer,
    createDrawerNavigator} from 'react-navigation';

const AppStack = createDrawerNavigator({
        Home:Home,
    },{
    contentComponent: DrawerScreen,
        defaultNavigationOptions: {
            drawerWidth: Dimensions.get('window').width - 120,
          },
 });

const AppNavigator = createStackNavigator({
    Splash:Splash,
     Login:Login,
     SignUp:SignUp },,{
        defaultNavigationOptions: {
            header: null,
            gesturesEnabled: false
          },
          initialRouteName: "Splash");
const AppContainer = createAppContainer(AppNavigator);
</code>```

Whenever you want to open the drawer like on click of the drawer icon. then add these line in the onPress definition.

```<code>this.props.navigation.openDrawer();
</code>```

Body:
I have this code for creating a drawer navigator. But I can't open my drawer through left to right slide. Can anyone please help me to solve my problem. I am new to react-native. I am using react-navigation v4 and react-navigation-drawer for the drawer navigator.

const EMBotomTabScreen = createDrawerNavigator ({
  SUMMARY: {
    screen : EMNavigator,
    navigationOptions :{
      animationEnabled : 'true',
      // headerLeft : <HamburgerIcon navigationProps={ navigation }/>,
      swipeEnabled: true,
      tabBarOptions: {
        activeTintColor: '#369841',
        //activeBackgroundColor : '#f2f2f2',
        inactiveTintColor : 'gray',
        inactiveBackgroundColor : '#adc1b8',
        borderRightWidth:2,
        borderRightColor:'blue',
        labelStyle: {
          fontSize: 13,
        },
        style: {
          backgroundColor: '#f2f2f2',
          // borderRightWidth:2,
          // borderRightColor:'blue'
        },
        indicatorStyle: {
            backgroundColor: 'red',
        },
      },

      tabStyle: {
        backgroundColor: 'green',
        borderRightWidth:2,
        borderRightColor:'blue'
      },
      indicatorStyle : {
        backgroundColor : 'red'
      },
      tabBarIcon: ({ focused, tintColor }) => {
        const iconName = `ios-desktop`;
        return <Image source={require('../assets/aaaaa.png')} size={27} color={tintColor} />;
    },
    }
  },
  DEMAND: {
    screen : EMDemandNavigator,
    navigationOptions : {
      tabBarOptions: {
        activeTintColor: '#369841',
       // activeBackgroundColor : '#f2f2f2',
        inactiveTintColor : 'gray',
        inactiveBackgroundColor : '#adc1b8',
        labelStyle: {
          fontSize: 13,
        },
        style: {
          backgroundColor: '#f2f2f2',
        },
      },
      tabBarIcon: ({ focused, tintColor }) => {
        const iconName = `ios-cloud`;
        return <Image source={require('../assets/aaaaaaa.png')} size={27} color={tintColor} />;
    },
    }
  },
  ALARM: {
    screen : EMAlarmNavigator,
    navigationOptions : {
      animationEnabled : 'true',
      swipeEnabled: true,
      tabBarOptions: {
        activeTintColor: '#369841',
        //activeBackgroundColor : '#f2f2f2',
        inactiveTintColor : 'gray',
        inactiveBackgroundColor : '#adc1b8',
        borderRightWidth:2,
        borderRightColor:'blue',
        labelStyle: {
          fontSize: 13,
        },
        style: {
          backgroundColor: '#f2f2f2',
          // borderRightWidth:2,
          // borderRightColor:'blue'
        },
        indicatorStyle: {
            backgroundColor: 'red',
        },
      },

      tabStyle: {
        backgroundColor: 'green',
        borderRightWidth:2,
        borderRightColor:'blue'
      },
      indicatorStyle : {
        backgroundColor : 'red'
      },
      tabBarIcon: ({ focused, tintColor }) => {
        const iconName = `bell-o`;
        return <Icons name={iconName} size={27} color={tintColor} />;
    },
    }
  }

Body:
You can get an idea from the below given code.

import Splash from '../Splash/Splash';
import Home from '../screens/Home';
import DrawerScreen from '../screens/DrawerScreen'
//And many more
import {createStackNavigator,
    createSwitchNavigator,
    createAppContainer,
    createDrawerNavigator} from 'react-navigation';

const AppStack = createDrawerNavigator({
        Home:Home,
    },{
    contentComponent: DrawerScreen,
        defaultNavigationOptions: {
            drawerWidth: Dimensions.get('window').width - 120,
          },
 });

const AppNavigator = createStackNavigator({
    Splash:Splash,
     Login:Login,
     SignUp:SignUp },,{
        defaultNavigationOptions: {
            header: null,
            gesturesEnabled: false
          },
          initialRouteName: "Splash");
const AppContainer = createAppContainer(AppNavigator);

Whenever you want to open the drawer like on click of the drawer icon. then add these line in the onPress definition.

this.props.navigation.openDrawer();


问:
Run flutter code when android application class starts
I'm making a plugin for Flutter to handle fcm messages using an android native library.

As we know when a message is received by FCM, it starts the app (It's application class) and runs the codes within Application#onCreate block, so we can run native code when app starts by fcm in the background.

My question is, is it possible to run flutter code at that time when application starts?

For instance if the message was received:

Application class:

public class Application extends FlutterApplication {

  @Override
  public void onCreate() {
    super.onCreate();
    // Start flutter engine
    // Invoke a dart code in the Plugin using methodChannel or etc.
  }
}
```

答:
Short answer, Yes

You can call a Dart method in background using it's handle key.

1. Register your plugin in the background

Implement a custom application class (override FlutterApplication)

public class MyApp extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {

    @Override
    public void registerWith(io.flutter.plugin.common.PluginRegistry registry) {
        // For apps using FlutterEmbedding v1
        GeneratedPluginRegistrant.registerWith(registry);
       // App with V2 will initialize plugins automatically, you might need to register your own however
    }
}
```

<p>Remember to register the class in the <code>AndroidManifest</code> by adding <code>android:name=".MyApp"</code> to <code><application></code> attributes.</p>

<p>What is embedding v2?</p>

<h3>2. Create a setup function as top level function in your flutter code</h3>

<pre class="lang-dart prettyprint-override"><code>/// Define this TopLevel or static
void _setup() async {
  MethodChannel backgroundChannel = const MethodChannel('flutter_background');
  // Setup Flutter state needed for MethodChannels.
  WidgetsFlutterBinding.ensureInitialized();

  // This is where the magic happens and we handle background events from the
  // native portion of the plugin.
  backgroundChannel.setMethodCallHandler((MethodCall call) async {
    if (call.method == 'handleBackgroundMessage') {
      final CallbackHandle handle =
          CallbackHandle.fromRawHandle(call.arguments['handle']);
      final Function handlerFunction =
          PluginUtilities.getCallbackFromHandle(handle);
      try {
        var dataArg = call.arguments['message'];
        if (dataArg == null) {
          print('Data received from callback is null');
          return;
        }
        await handlerFunction(dataArg);
      } catch (e) {
        print('Unable to handle incoming background message.\n$e');
      }
    }
    return Future.value();
  });
</code>```

3. Create a top level callback that will get the background message and calls it

_bgFunction(dynamic message) {
    // Message received in background
    // Remember, this will be a different isolate. So, no widgets
}
```

<h3>4. Get the handle key of the background function and setup and send it to native via MethodChannel</h3>

<pre class="lang-dart prettyprint-override"><code>// dart:ui needed
CallbackHandle setup PluginUtilities.getCallbackHandle(_setup);
CallbackHandle handle PluginUtilities.getCallbackHandle(_bgFunction);

_channel.invokeMethod<bool>(
  'handleFunction',
  <String, dynamic>{
    'handle': handle.toRawHandle(),
    'setup': setup.toRawHandle()
  },
);
</code>```

5. Save them into SharedPref in the native side

public void onMethodCall(MethodCall call, MethodChannel.Result result) {
  String methodName = call.method
  if (methodName == "handleFunction") {
     long handle = call.argument("handle");
     long setup = call.argument("setup");
     // save them
  }
}

```

<h3>6. When background is awaken, start a background isolate</h3>

```FlutterMain.ensureInitializationComplete(context, null)
val appBundlePath = FlutterMain.findAppBundlePath()
val flutterCallback = FlutterCallbackInformation.lookupCallbackInformation(setupHandleYouHadSaved)

FlutterNativeView backgroundFlutterView = FlutterNativeView(context, true)

val args = FlutterRunArguments()
args.bundlePath = appBundlePath
args.entrypoint = flutterCallback.callbackName
args.libraryPath = flutterCallback.callbackLibraryPath

backgroundFlutterView?.runFromBundle(args)

// Initialize your registrant in the app class
pluginRegistrantCallback?.registerWith(backgroundFlutterView?.pluginRegistry)
```

<h3>7. When your plugin is registered, create a background channel and pass it to</h3>

```val backgroundChannel = MethodChannel(messenger, "pushe_flutter_background")
```

<h3>8. Call the setup method that would call and give the message to you callback</h3>

```private fun sendBackgroundMessageToExecute(context: Context, message: String) {
    if (backgroundChannel == null) {
        return
    }

    val args: MutableMap<String, Any?> = HashMap()
    if (backgroundMessageHandle == null) {
        backgroundMessageHandle = getMessageHandle(context)
    }
    args["handle"] = backgroundMessageHandle
    args["message"] = message
    // The created background channel at step 7
    backgroundChannel?.invokeMethod("handleBackgroundMessage", args, null)
}
```

The sendBackgroundMessageToExecute will execute the dart _setup function and pass the message and callback handle. In the step 2, callback will be called.

Note: There are still certain corner cases you may want to consider (for instance thread waiting and ...). Checkout the samples and see the source code.

There are several projects which support background execution when app is started in the background.

FirebaseMessaging

Pushe

WorkManager

Body:
Short answer, Yes

You can call a Dart method in background using it's handle key.

1. Register your plugin in the background

Implement a custom application class (override FlutterApplication)

public class MyApp extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {

    @Override
    public void registerWith(io.flutter.plugin.common.PluginRegistry registry) {
        // For apps using FlutterEmbedding v1
        GeneratedPluginRegistrant.registerWith(registry);
       // App with V2 will initialize plugins automatically, you might need to register your own however
    }
}

Remember to register the class in the AndroidManifest by adding android:name=".MyApp" to <application> attributes.

What is embedding v2?

2. Create a setup function as top level function in your flutter code

/// Define this TopLevel or static
void _setup() async {
  MethodChannel backgroundChannel = const MethodChannel('flutter_background');
  // Setup Flutter state needed for MethodChannels.
  WidgetsFlutterBinding.ensureInitialized();

  // This is where the magic happens and we handle background events from the
  // native portion of the plugin.
  backgroundChannel.setMethodCallHandler((MethodCall call) async {
    if (call.method == 'handleBackgroundMessage') {
      final CallbackHandle handle =
          CallbackHandle.fromRawHandle(call.arguments['handle']);
      final Function handlerFunction =
          PluginUtilities.getCallbackFromHandle(handle);
      try {
        var dataArg = call.arguments['message'];
        if (dataArg == null) {
          print('Data received from callback is null');
          return;
        }
        await handlerFunction(dataArg);
      } catch (e) {
        print('Unable to handle incoming background message.\n$e');
      }
    }
    return Future.value();
  });

3. Create a top level callback that will get the background message and calls it

_bgFunction(dynamic message) {
    // Message received in background
    // Remember, this will be a different isolate. So, no widgets
}

4. Get the handle key of the background function and setup and send it to native via MethodChannel

// dart:ui needed
CallbackHandle setup PluginUtilities.getCallbackHandle(_setup);
CallbackHandle handle PluginUtilities.getCallbackHandle(_bgFunction);

_channel.invokeMethod<bool>(
  'handleFunction',
  <String, dynamic>{
    'handle': handle.toRawHandle(),
    'setup': setup.toRawHandle()
  },
);

5. Save them into SharedPref in the native side

public void onMethodCall(MethodCall call, MethodChannel.Result result) {
  String methodName = call.method
  if (methodName == "handleFunction") {
     long handle = call.argument("handle");
     long setup = call.argument("setup");
     // save them
  }
}

6. When background is awaken, start a background isolate

FlutterMain.ensureInitializationComplete(context, null)
val appBundlePath = FlutterMain.findAppBundlePath()
val flutterCallback = FlutterCallbackInformation.lookupCallbackInformation(setupHandleYouHadSaved)

FlutterNativeView backgroundFlutterView = FlutterNativeView(context, true)

val args = FlutterRunArguments()
args.bundlePath = appBundlePath
args.entrypoint = flutterCallback.callbackName
args.libraryPath = flutterCallback.callbackLibraryPath

backgroundFlutterView?.runFromBundle(args)

// Initialize your registrant in the app class
pluginRegistrantCallback?.registerWith(backgroundFlutterView?.pluginRegistry)

7. When your plugin is registered, create a background channel and pass it to

val backgroundChannel = MethodChannel(messenger, "pushe_flutter_background")

8. Call the setup method that would call and give the message to you callback

private fun sendBackgroundMessageToExecute(context: Context, message: String) {
    if (backgroundChannel == null) {
        return
    }

    val args: MutableMap<String, Any?> = HashMap()
    if (backgroundMessageHandle == null) {
        backgroundMessageHandle = getMessageHandle(context)
    }
    args["handle"] = backgroundMessageHandle
    args["message"] = message
    // The created background channel at step 7
    backgroundChannel?.invokeMethod("handleBackgroundMessage", args, null)
}

The sendBackgroundMessageToExecute will execute the dart _setup function and pass the message and callback handle. In the step 2, callback will be called.

Note: There are still certain corner cases you may want to consider (for instance thread waiting and ...). Checkout the samples and see the source code.

There are several projects which support background execution when app is started in the background.

FirebaseMessaging

Pushe

WorkManager


问:
How can I access the current executing module or class name in Python?
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module.  Here is some code:

foo.py:

```<code>def f():
    print __name__
</code>```

bar.py:

```<code>from foo import f

def b(): f()
</code>```

This obviously does not work as __name__ is the name of the module that contains the function.  What I would like to be access inside the foo module is the name of the current executing module that is using foo.  So in the case above it would be bar but if any other module imported foo I would like foo to dynamically have access to the name of that module.

Edit: The inspect module looks quite promising but it is not exactly what I was looking for.  What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module.  Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.

Edit: Here is how I am trying to use this.  I have two different Django applications that both need to log errors to file.  Lets say that they are called "AppOne" and "AppTwo".  I also have a place to which I would like to log these files: "/home/hare/app_logs".  In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file.  However what I would like to do is create a directory under app_logs that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.

In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.

答: It's been a while since I've done python, but I believe that you can get access to the globals and locals of a caller through its traceback.</p>

OwnerDisplayName: Andrew Hare

ContentLicense: CC BY-SA 2.5

Body:
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module.  Here is some code:

foo.py:

def f():
    print __name__

bar.py:

from foo import f

def b(): f()

This obviously does not work as __name__ is the name of the module that contains the function.  What I would like to be access inside the foo module is the name of the current executing module that is using foo.  So in the case above it would be bar but if any other module imported foo I would like foo to dynamically have access to the name of that module.

Edit: The inspect module looks quite promising but it is not exactly what I was looking for.  What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module.  Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.

Edit: Here is how I am trying to use this.  I have two different Django applications that both need to log errors to file.  Lets say that they are called "AppOne" and "AppTwo".  I also have a place to which I would like to log these files: "/home/hare/app_logs".  In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file.  However what I would like to do is create a directory under app_logs that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.

In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.

LastEditorDisplayName: Andrew Hare

OwnerDisplayName: Mr Fooz


问:
Large database 500 milion records
A solution of one of our business problems would be to store about 500 milion records into a database.
Each record would have about 40 to 50 columns.

I have a text file containing all of this data and it is about 150 GB.
(a 3rd of my harddisk)

If I were to load (somehow) all of this data into a db (ORACLE ?) how well would it perform ?

A colleague of mine insists that it would be absolutely fine.
And I could even index all of the 40 to 50 columns and then it is a matter of writing some sql to get  data out.

is he right ?
or is 500 milion records too much for a db ?

p.s.
Just adding more information following some very good answers:
The 40 to 50 columns will hold small strings and/or numbers.
For small strings I intend something smaller than 64 characters.

答:
Your colleague is kind of correct - 500M records in DB is fine, I've used DB's with 2G rows and that was 10 years back. Indexing every column is a problem - the indexes will slow every new record insert, and building the indexes will take a looonng time. You need to identify what kind of queries you'll run and then index appropriately. With so many records you may get benefits by normalising the data - a flat structure is often faster, but if you have repetitive long text fields, then replacing them with lookups may give storage and indexing benefits. Without seeing the data it's hard to give more precise advice.

BTW If you do hit performance probs you can also partition the data into physically separate tables, maybe by year?

My next step (after you've chosen your DB platform and found a server) is to get the data loaded and see how it performs. I'd take a look at Bulk Loading your data - I'm a Sql Server bloke so Integration Services is the way to go. I'd make sure you have a single unique key and if it's not in the data add an identity column. Then you're ready to test some of this out. SqlExpress is free, comes with SSIS but it can only handle 10G DBs - but that's enough to get familiar with the issues.

I regularly bulk load a 4M row table with 50+ columns and it takes around 2 minutes. I'm happy to take this offline if you want further one on one advice.

Title: Large database 500 milion records