答:
In PHP, foreach actually have two syntaxes:

foreach($array as $element) this might means $element ends up being an array

foreach($array as $key => $value) this means that key will never be an array, it is what the key, so what you have before the => in your array, while $value can be an array.

Here is the way to follow the first syntax, mind that you don't even have to nest foreach here, as pointed out by @Nathanael's comment what you have in your array is mostly scalar, not really nested arrays.

foreach($documents as $document){
  echo $document['name']."
".
    $document['lastname']."
".
    $document['country']."
".
    $document['nationality']."
".
    $document['job']."
".
    $document['job']."
".
    $document['hobbies']['sports']."
".
    $document['hobbies']['others']['freetime'];
}
```

<p>If you want to go in the second syntax, then it would be even better to make a recursion:</p>

<pre class="lang-php prettyprint-override"><code>function display_multi_level_array($array) {
  foreach($array as $key => $value){
    if(is_array($value)) {
       display_multi_level_array($value);
       continue;
    }

    echo $key." ".$value."<br>";
  }
}

display_multi_level_array($documents);
</code>```

Title: Manage a 4 dimensional array or a 5 dimensional with foreach statement in php

Body:
In PHP, foreach actually have two syntaxes:

foreach($array as $element) this might means $element ends up being an array

foreach($array as $key => $value) this means that key will never be an array, it is what the key, so what you have before the => in your array, while $value can be an array.

Here is the way to follow the first syntax, mind that you don't even have to nest foreach here, as pointed out by @Nathanael's comment what you have in your array is mostly scalar, not really nested arrays.

foreach($documents as $document){
  echo $document['name']."<br>".
    $document['lastname']."<br>".
    $document['country']."<br>".
    $document['nationality']."<br>".
    $document['job']."<br>".
    $document['job']."<br>".
    $document['hobbies']['sports']."<br>".
    $document['hobbies']['others']['freetime'];
}

If you want to go in the second syntax, then it would be even better to make a recursion:

function display_multi_level_array($array) {
  foreach($array as $key => $value){
    if(is_array($value)) {
       display_multi_level_array($value);
       continue;
    }

    echo $key." ".$value."<br>";
  }
}

display_multi_level_array($documents);


来源: stackexchange

问:
Is there a way to track an URL traffics if the page doesn't exist but was directed to a working page?

A user enters https://example.com/mypage on the browser

.httaccess redirects to https://example.com/myfinallandingpage

I would like to track the traffics of /mypage.
/mypage is not an actual page, but /myfinallandingpage is a working page.

Does anybody know a way to do this?

答:
Out of the box you can't measure server-side redirects such as 301 or 302 since the browser JavaScript, and thus Google Analytics won't be executed on the redirect source pages.

However you can by doing a little customization:

Insert a URL parameter on the redirect destination page eg https://example.org/destination-page?ref=https://example.org/source-page and track whatever you want on that destination apge

Perform server-side tracking: you could handle your redirects at PHP level, allowing you to use a GA server-side tracking library with GA Client ID retrieved via the cookies in HTTP headers

ContentLicense: CC BY-SA 4.0


问:
Testing argument using Python Click
I have a command-line script with Python-click with an argument and option:

# console.py
import click

@click.command()
@click.version_option()
@click.argument("filepath", type=click.Path(exists=True), default=".")
@click.option(
    "-m",
    "--max-size",
    type=int,
    help="Max size in megabytes.",
    default=20,
    show_default=True,
)
def main(filepath: str, max_size: int) -> None:
    max_size_bytes = max_size * 1024 * 1024  # convert to MB
    if filepath.endswith(".pdf"):
        print("success")
    else:
        print(max_size_bytes)
```

<p>Both the argument and option have default values and work on the command-line and using the CLI it behaves as expected. But when I try testing it following Click documentation and debug it, it does not enter the first line:</p>

<pre class="lang-py prettyprint-override"><code># test_console.py
from unittest.mock import Mock

import click.testing
import pytest
from pytest_mock import MockFixture

from pdf_split_tool import console

@pytest.fixture
def runner() -> click.testing.CliRunner:
    """Fixture for invoking command-line interfaces."""
    return click.testing.CliRunner()

@pytest.fixture
def mock_pdf_splitter_pdfsplitter(mocker: MockFixture) -> Mock:
    """Fixture for mocking pdf_splitter.PdfSplitter."""
    return mocker.patch("pdf_split_tool.pdf_splitter.PdfSplitter", autospec=True)

def test_main_uses_specified_filepath(
    runner: click.testing.CliRunner,
    mock_pdf_splitter_pdfsplitter: Mock,
) -> None:
    """It uses the specified filepath."""
    result = runner.invoke(console.main, ["test.pdf"])
    assert result.exit_code == 0
</code>```

I couldn't see why it is giving since the debugger did not enter the first line of function main(). Any ideas of what could be wrong?

答:
I've changed your test method to the following. However, this is more an augmentation to apoorva kamath's answer.

def test_main_uses_specified_filepath() -> None:
    runner = click.testing.CliRunner()
    with runner.isolated_filesystem():
        with open('test.pdf', 'w') as f:
            f.write('Hello World!')

        result = runner.invoke(main, ["test.pdf"])
    assert result.exit_code == 0
```

Simply put, it creates an isolated file system that gets cleaned up after the text is executed. So any files created there are destroyed with it.

For more information, Click's Isolated Filesystem documentation might come in handy.

Alternatively, you can remove the exists=True parameter to your file path.

Title: Testing argument using Python Click

Body:
I have a command-line script with Python-click with an argument and option:

# console.py
import click

@click.command()
@click.version_option()
@click.argument("filepath", type=click.Path(exists=True), default=".")
@click.option(
    "-m",
    "--max-size",
    type=int,
    help="Max size in megabytes.",
    default=20,
    show_default=True,
)
def main(filepath: str, max_size: int) -> None:
    max_size_bytes = max_size * 1024 * 1024  # convert to MB
    if filepath.endswith(".pdf"):
        print("success")
    else:
        print(max_size_bytes)

Both the argument and option have default values and work on the command-line and using the CLI it behaves as expected. But when I try testing it following Click documentation and debug it, it does not enter the first line:

# test_console.py
from unittest.mock import Mock

import click.testing
import pytest
from pytest_mock import MockFixture

from pdf_split_tool import console

@pytest.fixture
def runner() -> click.testing.CliRunner:
    """Fixture for invoking command-line interfaces."""
    return click.testing.CliRunner()

@pytest.fixture
def mock_pdf_splitter_pdfsplitter(mocker: MockFixture) -> Mock:
    """Fixture for mocking pdf_splitter.PdfSplitter."""
    return mocker.patch("pdf_split_tool.pdf_splitter.PdfSplitter", autospec=True)

def test_main_uses_specified_filepath(
    runner: click.testing.CliRunner,
    mock_pdf_splitter_pdfsplitter: Mock,
) -> None:
    """It uses the specified filepath."""
    result = runner.invoke(console.main, ["test.pdf"])
    assert result.exit_code == 0

I couldn't see why it is giving since the debugger did not enter the first line of function main(). Any ideas of what could be wrong?

Body:
I've changed your test method to the following. However, this is more an augmentation to apoorva kamath's answer.

def test_main_uses_specified_filepath() -> None:
    runner = click.testing.CliRunner()
    with runner.isolated_filesystem():
        with open('test.pdf', 'w') as f:
            f.write('Hello World!')

        result = runner.invoke(main, ["test.pdf"])
    assert result.exit_code == 0

Simply put, it creates an isolated file system that gets cleaned up after the text is executed. So any files created there are destroyed with it.

For more information, Click's Isolated Filesystem documentation might come in handy.

Alternatively, you can remove the exists=True parameter to your file path.


问:
Multiple authenticationProvider in Micronaut
Is it possible to define multiple authenticationProviders in Micronaut?

Let's say I have an entity A which can be logged using authenticationProviderA: which given a user and pass checks the DB table of A.

Is it possible to add an entity B and its authenticationProviderB which given a user and pass will check the DB table of B?
If so, how do you define in your controller which authenticationProvider you want to use?

答:
After taking a look at io.micronaut.security.authentication.Authenticator I've seen it's possible to have multiple authenticationProviders in Micronaut.

The documentation says:

An Authenticator operates on several {@link AuthenticationProvider} instances returning the first authenticated {@link AuthenticationResponse}.

From what I've seen you just have to implement AuthenticationProvider and the Authenticator will include the implementations (even if it isn't annotated!) in an internal list of AuthenticationProviders.

IMHO this isn't a good way to provide multiple ways to authenticate. In the example provided in the question, the authentication for A and B both require calls to DB which means depending on the order of the execution of the AuthenticationProviders unneeded BD calls will be executed.

I think would be better to provide a way to indicate which AuthenticationProviders has to be used by controller or endpoint.
Maybe there is a way to do that and I just don't know, so feel free to comment if so.


问:
SQL to returns the value before last value in an ordered partition of a result set
I want to get a data into a new column (previous year end head count) after doing partition on the year and taking latest headcount value from that partition and setting it in the subsequent year for the new column.

Create table and insert data script:

```<code>    CREATE TABLE #test1(
        [DateTime] [date] NULL,
        [HeadCount] [int] NULL
    )
    GO
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-06-02' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-05-02' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-02-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-01-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-06-05' AS Date), 7)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-05-01' AS Date), 7)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-04-20' AS Date), 5)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-01-02' AS Date), 5)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-12-15' AS Date), 8)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-10-02' AS Date), 9)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-09-12' AS Date), 6)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-08-06' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-07-10' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-06-05' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-03-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-02-10' AS Date), 7)
</code>```

Solution I have tried:

```<code>    SELECT
    datetime,headcount,
    LAST_VALUE(headcount) OVER(
                PARTITION BY year(datetime)
            ORDER BY datetime desc
            RANGE BETWEEN
                UNBOUNDED PRECEDING AND
                UNBOUNDED FOLLOWING
        ) PrevYearEndHeadCnt
    FROM
        #test1 order by datetime desc
</code>```

Result I am getting vs expectation:

```<code>    datetime    headcount   PrevYearEndHeadCnt  Expected
    02-06-2020  2           3                   7
    02-05-2020  2           3                   7
    20-02-2020  3           3                   7
    20-01-2020  3           3                   7
    05-06-2019  7           5                   8
    01-05-2019  7           5                   8
    20-04-2019  5           5                   8
    02-01-2019  5           5                   8
    15-12-2018  8           7                   0
    02-10-2018  9           7                   0
    12-09-2018  6           7                   0
    06-08-2018  3           7                   0
    10-07-2018  2           7                   0
    05-06-2018  3           7                   0
    20-03-2018  3           7                   0
    10-02-2018  7           7                   0
</code>```

答:
This should help you get your expected result set. I am just using self join to compare this year with last year and getting the latest headcount from last year using the rank function. </p>

```<code>    SELECT curr.datetime,curr.headcount,
           ISNULL(prev.HeadCount,0) as PrevYearEndHeadCnt
    FROM #test1 curr
    LEFT JOIN (Select datetime,HeadCount,
                      RANK() OVER (PARTITION BY year(datetime) ORDER BY datetime desc) as rn_headcount
               FROM #test1) prev ON YEAR(prev.DateTime) = YEAR(curr.DateTime) - 1
                                AND rn_headcount = 1
    ORDER BY curr.datetime DESC
</code>```

Body:
I want to get a data into a new column (previous year end head count) after doing partition on the year and taking latest headcount value from that partition and setting it in the subsequent year for the new column.

Create table and insert data script:

    CREATE TABLE #test1(
        [DateTime] [date] NULL,
        [HeadCount] [int] NULL
    )
    GO
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-06-02' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-05-02' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-02-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-01-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-06-05' AS Date), 7)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-05-01' AS Date), 7)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-04-20' AS Date), 5)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-01-02' AS Date), 5)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-12-15' AS Date), 8)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-10-02' AS Date), 9)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-09-12' AS Date), 6)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-08-06' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-07-10' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-06-05' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-03-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-02-10' AS Date), 7)

Solution I have tried:

    SELECT
    datetime,headcount,
    LAST_VALUE(headcount) OVER(
                PARTITION BY year(datetime)
            ORDER BY datetime desc
            RANGE BETWEEN
                UNBOUNDED PRECEDING AND
                UNBOUNDED FOLLOWING
        ) PrevYearEndHeadCnt
    FROM
        #test1 order by datetime desc

Result I am getting vs expectation:

    datetime    headcount   PrevYearEndHeadCnt  Expected
    02-06-2020  2           3                   7
    02-05-2020  2           3                   7
    20-02-2020  3           3                   7
    20-01-2020  3           3                   7
    05-06-2019  7           5                   8
    01-05-2019  7           5                   8
    20-04-2019  5           5                   8
    02-01-2019  5           5                   8
    15-12-2018  8           7                   0
    02-10-2018  9           7                   0
    12-09-2018  6           7                   0
    06-08-2018  3           7                   0
    10-07-2018  2           7                   0
    05-06-2018  3           7                   0
    20-03-2018  3           7                   0
    10-02-2018  7           7                   0

Body:
This should help you get your expected result set. I am just using self join to compare this year with last year and getting the latest headcount from last year using the rank function.

    SELECT curr.datetime,curr.headcount,
           ISNULL(prev.HeadCount,0) as PrevYearEndHeadCnt
    FROM #test1 curr
    LEFT JOIN (Select datetime,HeadCount,
                      RANK() OVER (PARTITION BY year(datetime) ORDER BY datetime desc) as rn_headcount
               FROM #test1) prev ON YEAR(prev.DateTime) = YEAR(curr.DateTime) - 1
                                AND rn_headcount = 1
    ORDER BY curr.datetime DESC


问:
conda build - recommended way to add heavy test data
I am working on a conda package for a software which test suite needs rather heavy test data (~50MB)
The conda documentation indicates how to use test data that are included in the recipe. When the test data are heavy, I would guess that it is better to download them on the fly rather than including the data in the recipe, but what is the best way to declare that in the meta.yml? Should the download and extraction of the data archive be done in build.sh or somewhere else?</p>

答:
I recommend listing the test data as an additional source to download.

Most conda recipes only download from a single source tarball (or git repository, etc.), but recipes are permitted to list multiple sources if necessary, all of which are downloaded.  Here's a quick example:

{% set name = "foo" %}
{% set version = "0.1" %}

package:
  name: {{ name|lower }}
  version: {{ version }}

source:
  # Main source code
  - url: http://example.com/yada/yada/foo-{{ version }}.tar.gz
    sha256: 90e64c6eca4be47bbf1d61f53dc003c6621213738d4ea7a35e5cf1ac2de9bab1

  # Also download test data into a folder named 'test-data'
  - url: http://example.com/yada/yada/my-test-data.tar.gz
    sha256: 3b9c5e0f09ca14a54454319b64af98a02d0ae1b3eb1122c95e2130736f440cd1
    folder: test-data

build:
  number: 0

requirements:
  # etc, etc, ...

test:
  source_files:
    - test-data
  commands:
    - run_my_tests --data-dir=test-data
```

Notes:

Provide a folder name to specify where your additional source should be unpacked within the work directory.  Otherwise, it will be unpacked at the root of the work directory, just like the first source.

The work directory is deleted before the test phase begins, so you'll need to list your test data directory in the test:source_files: section to ensure that it is copied to the folder in which the tests are executed.

Body:
I recommend listing the test data as an additional source to download.

Most conda recipes only download from a single source tarball (or git repository, etc.), but recipes are permitted to list multiple sources if necessary, all of which are downloaded.  Here's a quick example:

{% set name = "foo" %}
{% set version = "0.1" %}

package:
  name: {{ name|lower }}
  version: {{ version }}

source:
  # Main source code
  - url: http://example.com/yada/yada/foo-{{ version }}.tar.gz
    sha256: 90e64c6eca4be47bbf1d61f53dc003c6621213738d4ea7a35e5cf1ac2de9bab1

  # Also download test data into a folder named 'test-data'
  - url: http://example.com/yada/yada/my-test-data.tar.gz
    sha256: 3b9c5e0f09ca14a54454319b64af98a02d0ae1b3eb1122c95e2130736f440cd1
    folder: test-data

build:
  number: 0

requirements:
  # etc, etc, ...

test:
  source_files:
    - test-data
  commands:
    - run_my_tests --data-dir=test-data

Notes:

Provide a folder name to specify where your additional source should be unpacked within the work directory.  Otherwise, it will be unpacked at the root of the work directory, just like the first source.

The work directory is deleted before the test phase begins, so you'll need to list your test data directory in the test:source_files: section to ensure that it is copied to the folder in which the tests are executed.


问:
Difference of n dictionaries
I'm looking for a way to determine the difference of n dictionaries in the following scenario:
There are n dictionaries. Some of their keys match, but not all. Like this:

```<code>dict_a = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyC': 'valueC',
    'keyD': 'valueD',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}
</code>```

```<code>dict_b = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyX': 'valueX',
    'keyD': 'valueH',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}
</code>```

I want to be able, to tell if the value of a key is different from the value of the same key in another dictionary. In the examble above keyD should be returned, because its value is different in dict_a and dict_b. keyX should not be returned, as it only occurs in dict_b This is relatively easy with only two dictionaries, but what is the best practise to accomplish this with n dictionaries?

答:
```<code>dict_a = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyC': 'valueC',
    'keyD': 'valueD',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}

dict_b = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyX': 'valueX',
    'keyD': 'valueH',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}

dict_c = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyX': 'valueX',
    'keyD': 'valueH',
    'keyE': 'valueO',    # <- here is additional difference
    'keyF': 'valueF',
    'keyG': 'valueG'
}

# Step 1: prepare list of all dict

dicts = [dict_a, dict_b, dict_c]

# Step 2: get all common keys

ks = [set(i.keys()) for i in dicts]
ks_i = list(ks[0].intersection(*ks[1:]))
ks_i

Out[1]:  # here is the list of common keys
['keyB', 'keyE', 'keyF', 'keyD', 'keyG', 'keyA']

# Step 3: get set of values taken from the different dict by the same keys

unequal = [{i[k] for i in dicts} for k in ks_i]
unequal
Out[2]:                 #show set of values for same keys
[{'valueB'},            # for keyB
 {'valueE', 'valueO'},  # for keyE
 {'valueF'},            # and so on
 {'valueD', 'valueH'},
 {'valueG'},
 {'valueA'}]

# Step 4: check if the length of set and chooe appropriate keys
# if the set has length >1 then it has different values inside

[ks_i[ind] for ind,v in enumerate(unequal) if len(v) >1]

Out[3]:
['keyE', 'keyD']
</code>```

Title: Difference of n dictionaries

Body:
I'm looking for a way to determine the difference of n dictionaries in the following scenario:
There are n dictionaries. Some of their keys match, but not all. Like this:

dict_a = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyC': 'valueC',
    'keyD': 'valueD',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}

dict_b = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyX': 'valueX',
    'keyD': 'valueH',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}

I want to be able, to tell if the value of a key is different from the value of the same key in another dictionary. In the examble above keyD should be returned, because its value is different in dict_a and dict_b. keyX should not be returned, as it only occurs in dict_b This is relatively easy with only two dictionaries, but what is the best practise to accomplish this with n dictionaries?


问:
(TS) Type '{}' is missing the following properties from type
I have a Functional Component defined using TS that I am passing in object on Props to give the component access to some actionCreators.   There are no actual Props values to pass in.  However, I am using the prop mechanism to pass in the a type to access the actionCreator methods.

```<code>import * as React from 'react';
import { connect, useSelector, useDispatch } from 'react-redux';
import { ApplicationState } from "../store";
import * as VerifyCheckStore from "../store/VerifyCheck";

type VerifyCheckProps = typeof VerifyCheckStore.actionCreators;

const VerifyCheckVerificationSuccess: React.FunctionComponent<VerifyCheckProps> = (props) =>
{
    const selectVerifyCheckState = (state: ApplicationState) => state.verifyCheck;
    const verifyCheckState: any = useSelector(selectVerifyCheckState);
    const dispatch = useDispatch();

    const submitData = (processState: string) => {
    VerifyCheckStore.actionCreators.setProcessState(processState);
}

return <div>
    <div>Check has been verified as a valid AutoCheck</div>
    <div>Do you wish to adopt this Autocheck for the purpose of using the check to pay for a customer's vehicle?</div>
    <button className="btn btn-primary" name="btnAdopt" onClick={() => { submitData("adoptStart") }} >Adopt</button>
    <button className="btn btn-primary" name="btnAdopt" onClick={() => { submitData("start"); }} >Cancel</button>
</div>;
}
VerifyCheckVerificationSuccess.defaultProps = {}
export default connect()(VerifyCheckVerificationSuccess);
</code>```

When I go to use the FC i get the following TS error.

Error   TS2739  (TS) Type '{}' is missing the following properties from type 'Pick<{ setProcessState: (processState: string) => AppThunkAction; postdata: (checkNumber: string, verificationCode: string) => AppThunkAction; requestVerifyCheck: () => AppThunkAction<...>; }, "setProcessState" | ... 1 more ... | "requestVerifyCheck">': setProcessState, postdata, requestVerifyCheck

How can i pass in objects on the props mechanism without having to define the values when using the FC?

If this is not the correct way to get access to the actionCreator methods please let me know.   I am new to React and just learning.

答:
I was able to get the error to go away by adding "as any" to the export default connect.  I know this is a hack and not really using TS as it was intended but I got to move on.</p>

```<code>export default connect()(VerifyCheckVerificationSuccess as any);
</code>```

Body:
I have a Functional Component defined using TS that I am passing in object on Props to give the component access to some actionCreators.   There are no actual Props values to pass in.  However, I am using the prop mechanism to pass in the a type to access the actionCreator methods.

import * as React from 'react';
import { connect, useSelector, useDispatch } from 'react-redux';
import { ApplicationState } from "../store";
import * as VerifyCheckStore from "../store/VerifyCheck";

type VerifyCheckProps = typeof VerifyCheckStore.actionCreators;

const VerifyCheckVerificationSuccess: React.FunctionComponent<VerifyCheckProps> = (props) =>
{
    const selectVerifyCheckState = (state: ApplicationState) => state.verifyCheck;
    const verifyCheckState: any = useSelector(selectVerifyCheckState);
    const dispatch = useDispatch();

    const submitData = (processState: string) => {
    VerifyCheckStore.actionCreators.setProcessState(processState);
}

return

Check has been verified as a valid AutoCheck

Do you wish to adopt this Autocheck for the purpose of using the check to pay for a customer's vehicle?

    <button className="btn btn-primary" name="btnAdopt" onClick={() => { submitData("adoptStart") }} >Adopt</button>
    <button className="btn btn-primary" name="btnAdopt" onClick={() => { submitData("start"); }} >Cancel</button>

;
}
VerifyCheckVerificationSuccess.defaultProps = {}
export default connect()(VerifyCheckVerificationSuccess);

When I go to use the FC i get the following TS error.

Error   TS2739  (TS) Type '{}' is missing the following properties from type 'Pick<{ setProcessState: (processState: string) => AppThunkAction; postdata: (checkNumber: string, verificationCode: string) => AppThunkAction; requestVerifyCheck: () => AppThunkAction<...>; }, "setProcessState" | ... 1 more ... | "requestVerifyCheck">': setProcessState, postdata, requestVerifyCheck

How can i pass in objects on the props mechanism without having to define the values when using the FC?

If this is not the correct way to get access to the actionCreator methods please let me know.   I am new to React and just learning.

Body:
I was able to get the error to go away by adding "as any" to the export default connect.  I know this is a hack and not really using TS as it was intended but I got to move on.

export default connect()(VerifyCheckVerificationSuccess as any);


问:
JQuery: Why Unobtrusive JavaScript / Document Ready function rather than OnClick event?
I've just started looking at JQuery. I don't have any AJAX in my web application at present.

My existing JavaScript in my HTML looks like:

```<code><form ...>
<p>Find what? <input ...></p>
<div class="ButtonArray">
  <a href="AddRecord.ASP&Action=ADD">ADD</a>
  <a href="#" onClick="return MyFormSubmit();">FIND</a>
</div>
</form>
</code>```

This displays Buttons for [Add] and [Find].  For Find it is necessary to Submit the form, and I use MyFormSubmit() which validates the data, adds a visual effect to the page, and then POSTs the data.

I could add a CLASS or ID to the  for the Find button and in JQuery I could write something like:

```<code>$(function() {
  $(".MySearchButtonClass").click(function() {
    // validate and process form here
  });
});
</code>```

At my "novice" stage of understanding with JQuery I don't get why I would do it this way

My old way identifies the Method near the object. There may be a risk that the JS has not loaded before the user presses the button (is there? The LOAD for the JS is right at the top of the page).

The JQuery Document Ready method won't be activated until the document is loaded (which I assume guarantees that the JS is all present and ready to be run?), but it moves the code to a separate part of my HTML file - so when I see the MyButtonArray DIV in the HTML source it isn't obvious to me which objects have methods, and which do not.

Can you please help me understand what my options are and the benefits / gotchas that I should look out for?

Edit: I'm comfortable that DOM manipulation - such as a LightBox that can appear when any thumbnail with class "LightBoxThumb" is clicked - would use Unobtrusive Javascript.

However I am struggling to persuade myself that a button that has a specific action should have its method applied in that way. (I certainly wouldn't put any code on the button other than a single function call to something "elsewhere", but to my mind that is my best clue as to what that button does, and layers of Unobtrusive Javascript may make that much harder to determine.)

Edit2 - Accepted Answer

I've taken Russ Cams answer. It describes Unobtrusive Javascript in a way that has been helpful to me in understanding more about how & when that should be used.

For the moment (may change when I have more experience!) I'll stick with an OnClick event for a single, non-changing, action on an object as I feel that will be easier for me to debug - and diagnose if problems arise. For ZebraStripes on a table that allows click on heading column to sort (and situations of that type) I can see the benefits of the Unobtrusive Javascript approach

Russ's final comment was particularly helpful, repeated here:

"@Kristen - You're right, like a lot
  of programming topics, there is more
  than one approach and people will
  vehemently stand by their beliefs! If
  we're talking about a single method
  for a single button, I totally
  understand where you're coming from...

If we're talking about lots of
  JavaScript, with same function calls
  for more than one element, different
  function calls for different methods,
  etc. I think that it would be more
  difficult for oneself to mix inline
  and unobtrusive approaches, and it
  would be better to adopt one or the
  other approach"

答: You do it this way to seperate the UI logic from the actual HTML design.</p>

OwnerDisplayName: Kristen

ContentLicense: CC BY-SA 2.5

Body:
I've just started looking at JQuery. I don't have any AJAX in my web application at present.

My existing JavaScript in my HTML looks like:

<form ...>

Find what? <input ...>

  ADD
  FIND

</form>

This displays Buttons for [Add] and [Find].  For Find it is necessary to Submit the form, and I use MyFormSubmit() which validates the data, adds a visual effect to the page, and then POSTs the data.

I could add a CLASS or ID to the  for the Find button and in JQuery I could write something like:

$(function() {
  $(".MySearchButtonClass").click(function() {
    // validate and process form here
  });
});

At my "novice" stage of understanding with JQuery I don't get why I would do it this way

My old way identifies the Method near the object. There may be a risk that the JS has not loaded before the user presses the button (is there? The LOAD for the JS is right at the top of the page).

The JQuery Document Ready method won't be activated until the document is loaded (which I assume guarantees that the JS is all present and ready to be run?), but it moves the code to a separate part of my HTML file - so when I see the MyButtonArray DIV in the HTML source it isn't obvious to me which objects have methods, and which do not.

Can you please help me understand what my options are and the benefits / gotchas that I should look out for?

Edit: I'm comfortable that DOM manipulation - such as a LightBox that can appear when any thumbnail with class "LightBoxThumb" is clicked - would use Unobtrusive Javascript.

However I am struggling to persuade myself that a button that has a specific action should have its method applied in that way. (I certainly wouldn't put any code on the button other than a single function call to something "elsewhere", but to my mind that is my best clue as to what that button does, and layers of Unobtrusive Javascript may make that much harder to determine.)

Edit2 - Accepted Answer

I've taken Russ Cams answer. It describes Unobtrusive Javascript in a way that has been helpful to me in understanding more about how & when that should be used.

For the moment (may change when I have more experience!) I'll stick with an OnClick event for a single, non-changing, action on an object as I feel that will be easier for me to debug - and diagnose if problems arise. For ZebraStripes on a table that allows click on heading column to sort (and situations of that type) I can see the benefits of the Unobtrusive Javascript approach

Russ's final comment was particularly helpful, repeated here:

"@Kristen - You're right, like a lot
  of programming topics, there is more
  than one approach and people will
  vehemently stand by their beliefs! If
  we're talking about a single method
  for a single button, I totally
  understand where you're coming from...

If we're talking about lots of
  JavaScript, with same function calls
  for more than one element, different
  function calls for different methods,
  etc. I think that it would be more
  difficult for oneself to mix inline
  and unobtrusive approaches, and it
  would be better to adopt one or the
  other approach"

LastEditorDisplayName: Kristen

OwnerDisplayName: Thomas Stock


问:
Does Spring boot Support Fast fail on Liquibase
From Spring DB Initialization docs, Spring boot DB initialization using Spring JDBC supports
feature Fast fail - that means if there are any issues in DB init script or migration scripts then Spring boot Context initialization failed. as result Spring boot server won't start.

now can we have this functionality when we use Advanced DB Migration tool like liquibase?

Spring Docs Doesn't say anything about this in liquibase section. Does this feature only works in Spring JDBC initialization?

答: whenever there is an issue in your liquibase script, application won't start because datasource is not properly initialised. </p>


问:
How to keep figure in focus, no matter what
How do I keep a figure in focus of my system, even when I click on other things, outside of MATLAB? The idea is to 'pin a figure' on top, like an important forum post.</p>

答:
This page illustrates how it can be done.

An example:

First, create the figure:

```<code>figure
f = gcf;
</code>```

Then, use JavaFrame undocumented magic:

```<code>fJFrame = get(f,'JavaFrame');
jClient = fJFrame.fHG2Client;
jWindow = jClient.getWindow;
jWindow.setAlwaysOnTop(true);
</code>```

All credits to Yair Altman.

Body:
This page illustrates how it can be done.

An example:

First, create the figure:

figure
f = gcf;

Then, use JavaFrame undocumented magic:

fJFrame = get(f,'JavaFrame');
jClient = fJFrame.fHG2Client;
jWindow = jClient.getWindow;
jWindow.setAlwaysOnTop(true);

All credits to Yair Altman.


问:
Create a string from object array
I have two arrays as below:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];
```

<p>I want to loop through the array and print the following:</p>

<ol>
<li>If product 1, output <code>you have 2 One Plus</code></li>
<li>If product 2, output <code>you have 1 One Plus and 1 Apple</code></li>
</ol>

<p>Below is the code that I tried.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);</code>```

I’m able to get the JSON output, but how can I get it in the sentence format?

答:
```<code>const product1s = product1.reduce((acc, product) => {
acc[product.Brand] = (acc[product.Brand] || 0) + 1;
return acc;
}, {});

console.log(
`You have ${
Object.keys(product1s).map(product => `${product1s[product]} ${product}`).join(" and ")
}`
);
</code>```

Title: Create a string from object array

Body:
I have two arrays as below:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

I want to loop through the array and print the following:

If product 1, output you have 2 One Plus

If product 2, output you have 1 One Plus and 1 Apple

Below is the code that I tried.

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);

I’m able to get the JSON output, but how can I get it in the sentence format?


问:
Using tweepy with discord.py to post tweets to a specific channel
So, I'm trying to teach myself a bit of Python using a combination of tutorials, documentation, and online examples to build a Discord bot that implements some features of one or more existing bots. One of those features is posting (new) tweets from a certain set of Twitter accounts to a specific channel on my Discord server. I've found several bits and pieces of code that I've cobbled together to read from a Twitter stream and "tweaked" a few things here and there to try to accomplish this.

However, I keep running into an issue with actually getting the on_status code to execute properly. I've tried a variety of ways to get it working, but everything I've tried results in some sort of error. Below is the pertinent code (redacted) from the most recent iteration that I've been testing:

import discord
import tweepy

from discord.ext import commands
from tweepy import Stream
from tweepy.streaming import StreamListener

class TweetListener(StreamListener):
    def on_status(self, status):
        if status.in_reply_to_status_id is None:
            TweetText = status.text

            for DGuild in MyBot.guilds:
                for DChannel in DGuild.text_channels:
                    if DChannel.name == 'testing':
                        TwitterEmbed = discord.Embed(title='New Tweet', description='New Tweet from my timeline.', color=0xFF0000)
                        TwitterEmbed.set_author(name='@TwitterHandle', icon_url=bot.user.default_avatar_url)
                        DChannel.send(TweetText, embed = TwitterEmbed)

DISCORD_TOKEN = 'dtoken'
TWITTER_CONSUMER_KEY = 'ckey'
TWITTER_CONSUMER_SECRET = 'csecret'
TWITTER_ACCESS_TOKEN = 'atoken'
TWITTER_ACCESS_SECRET = 'asecret'

MyBot = commands.Bot(command_prefix='!', description='This is a testing bot')
TwitterAuth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
TwitterAuth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET)
TweetAPI = tweepy.API(TwitterAuth)
NewListener = TweetListener()
NewStream = tweepy.Stream(auth=TweetAPI.auth, listener=NewListener)
NewStream.filter(follow=['USER IDS HERE'], is_async=True)

@bot.event
async def on_ready():
    print(MyBot.user.name,'has successfully logged in ('+str(MyBot.user.id)+')')
    print('Ready to respond')

MyBot.run(DISCORD_TOKEN)
```
<p>The <code>channel.send()</code> method generates the following message when I post a tweet to my testing account's timeline:</p>
```RuntimeWarning: coroutine 'Messageable.send' was never awaited
```
<p>I understand the message - the <code>channel.send()</code> method is an asynchronous method, but the <code>on_status()</code> event handler is a synchronous method and I can't <code>await channel.send()</code>  inside <code>on_status()</code> - but I can't figure out how to make it work. I tried to make the <code>on_status()</code> method an asynchronous method:</p>
<pre class="lang-py prettyprint-override"><code>    async def on_status(self, status):
        <same code for checking the tweet and finding the channel>
        await DChannel.send(TweetText, embed = TwitterEmbed)
</code>```

but this always resulted in a similar warning:

```<code>RuntimeWarning: coroutine 'TweetListener.on_status' was never awaited
if self.on_status(status) is False:
</code>```

I found the question, How do I async on_status from tweepy? and followed the links there, but I didn't see anything that clued me in to whatever my coding error is.

Through additional research, I also tried using some calls from the asyncio library to make the call:

    #channel.send(message, embed = TwitterEmbed)
    #---ASYNCIO TEST---
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(DChannel.send(embed=TwitterEmbed)))
    loop.close()
```
<p>Unfortunately, this results in an unhandled exception when it attempts to execute <code>loop=asyncio.get_event_loop()</code> indicating <code>There is no current event loop in thread 'Thread-6'.</code> (so it won't even get to the <code>run_until_complete()</code> method to see if <em>that</em> will work, although I'm not exactly optimistic at this point).</p>
<p>I realize there are existing Discord bots like MEE6 that can already do what I'm trying to do here, but I'd like to be able to make this bot "my own" while teaching myself a little about Python. I'm probably overlooking something simple here, but I've not been able to find anything in the API documentation for either <code>tweepy</code> or <code>discord.py</code> that seems to be pointing me in the correct direction, and my <em>Google-fu</em> is apparently not that strong. All of the examples I've been able to find so far appear to be out-of-date as  they seem to refer to deprecated methods and older versions of either or both libraries. There are other things that I still have to figure out how to do as well (<em>e.g., get the <code>@TwitterHandle</code> to correctly populate the embed</em>), but I've got to get it able to read and push the tweet before I can worry about getting to that point.</p>
<hr />
<h2>ENVIRONMENT INFO</h2>
<p>Visual Studio 2017 CE</p>
<p>Python 3.6</p>
<p>discord.py 1.3.3</p>
<p>tweepy 3.8.0</p>
<hr />
<h2>UPDATE: ADDITIONAL TESTING</h2>
<p>So, just to prove to myself that my <code>TweetListener</code> class is actually working, I went ahead and commented out all of the interaction with Discord in the <code>on_status</code> method (<em>everything from <code>for Guild in MyBot.guilds</code> to the end of the method</em>), then added a simple <code>print(TweetText)</code>. I ran the code again, logged in to the testing Twitter account I have for this project, and posted an update. Checking the console, it correctly output the <code>status.text</code> of my tweet, as I expected it to. As I thought, the only issue I'm having here is trying to <code>send</code> that text to Discord.</p>
<p>I also tried initializing the <code>tweepy.Stream.filter</code> in synchronous mode instead of asynchronous - <code>NewStream.filter(follow=['USER IDS'])</code>. This only resulted in my application basically "hanging" on startup. I realized this was due to its position in the code, so I moved all three lines of the <code>TweetListener</code> initialization to the <code>on_ready</code> event method. I left the Discord code commented out and tested, and it again "worked" in that it printed the <code>status.text</code> of another test tweet to the console. However, the bot won't respond to anything else (still "waiting" on the stream, I assume).</p>
<p>Even so, just to see if it would make any difference, I went ahead and uncommented the Discord interaction code and tried again. The result was the same as I had initially, only this time the Discord bot won't respond to activity in the channel (<em>there are a couple of super simple <code>@bot.command</code> declarations elsewhere in the code</em>), which once again basically leads me back to my original code with the same issue.</p>
<p>I'm certain there are better ways to code this entire thing. As I said above, I'm just now starting to play around with Python and still learning syntax rules and such. Even so, I'm still not sure what I'm doing wrong and/or overlooking that's preventing me from achieving what I had thought would be a fairly simple task.</p>
<hr />
<h2>MORE TESTING</h2>
<p>I went back and found some more <code>asyncio</code> examples and tried another iteration in the Discord interaction in <code>on_status</code>:</p>
<pre class="lang-py prettyprint-override"><code>    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    result=loop.run_until_complete(DChannel.send(embed=TwitterEmbed))
</code>```

This time I got a different unhandled exception than I've gotten before. The error occurs on the run_until_complete line when it picks up a new tweet:

```<code>Timeout context manager should be used inside a task
</code>```

I consider this progress, but I'm obviously still not quite there, so back to Google and I found information on the asgiref library with its sync_to_async and async_to_sync methods, so I figured I'd give that a try.

    asgiref.sync.async_to_sync(DChannel.send)(embed=TwitterEmbed)
```

Unfortunately, I get the same unhandled exception as with the asyncio version. I feel like I'm right on the edge of figuring this out, but it simply hasn't "clicked" yet.

ANOTHER ROUND

Okay, so after looking for information about the Timeout context manager exception I was getting above, I stumbled across another SO question that has given me a tiny glimmer of hope. This answer on RuntimeError: Timeout context manager should be used inside a task once again takes me back to using asyncio and gives a brief but descriptive explanation of the reason behind the OP's issue before providing a useful suggestion using the asyncio.run_coroutine_threadsafe method. Looking at the recommended code, it made sense that this could help me initiate the sync->async method communication effectively. I implemented the suggested changes (created a global variable for a Thread object on which to run the bot, added a "startup" method that generated the bot in that loop, then changed the Discord interaction in on_status to bring it all together.

The "good news" is that I'm no longer getting any errors when I post a tweet. Also, testing the bot command seems to work just fine as well. The bad news is that it still didn't send the message to the channel. Since it didn't produce any errors, there's no telling where the message ended up.

答:
I went through the same problem as you have, and got the exact links from google and tried all of them but as you have mentioned nothing worked.

So, after lots of trying and tinkering I realised, I could pass the main loop to the tweepy listener and execute async functions with run_coroutine_threadsafe.

Here is the gist of my code:

the listener:

```<code>class EpicListener(tweepy.StreamListener):
    def __init__(self, discord, loop, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.discord = discord # this is just a function which sends a message to a channel
        self.loop = loop # this is the loop of discord client

    def on_status(self, status):
        self.send_message(status._json)

    def send_message(self, msg):
        # Submit the coroutine to a given loop
        future = asyncio.run_coroutine_threadsafe(self.discord(msg), self.loop)
        # Wait for the result with an optional timeout argument
        future.result()
</code>```

the discord client:

```<code>class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    async def on_ready(self):
        myStream = tweepy.Stream(
                    auth=api.auth, listener=EpicListener(discord=self.sendtwitter, loop=asyncio.get_event_loop())
                )
        myStream.filter(follow=['mohitwr'], is_async=True)
        print(myStream)
</code>```

Hope this helps.

Body:
So, I'm trying to teach myself a bit of Python using a combination of tutorials, documentation, and online examples to build a Discord bot that implements some features of one or more existing bots. One of those features is posting (new) tweets from a certain set of Twitter accounts to a specific channel on my Discord server. I've found several bits and pieces of code that I've cobbled together to read from a Twitter stream and "tweaked" a few things here and there to try to accomplish this.

However, I keep running into an issue with actually getting the on_status code to execute properly. I've tried a variety of ways to get it working, but everything I've tried results in some sort of error. Below is the pertinent code (redacted) from the most recent iteration that I've been testing:

import discord
import tweepy

from discord.ext import commands
from tweepy import Stream
from tweepy.streaming import StreamListener

class TweetListener(StreamListener):
    def on_status(self, status):
        if status.in_reply_to_status_id is None:
            TweetText = status.text

            for DGuild in MyBot.guilds:
                for DChannel in DGuild.text_channels:
                    if DChannel.name == 'testing':
                        TwitterEmbed = discord.Embed(title='New Tweet', description='New Tweet from my timeline.', color=0xFF0000)
                        TwitterEmbed.set_author(name='@TwitterHandle', icon_url=bot.user.default_avatar_url)
                        DChannel.send(TweetText, embed = TwitterEmbed)

DISCORD_TOKEN = 'dtoken'
TWITTER_CONSUMER_KEY = 'ckey'
TWITTER_CONSUMER_SECRET = 'csecret'
TWITTER_ACCESS_TOKEN = 'atoken'
TWITTER_ACCESS_SECRET = 'asecret'

MyBot = commands.Bot(command_prefix='!', description='This is a testing bot')
TwitterAuth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
TwitterAuth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET)
TweetAPI = tweepy.API(TwitterAuth)
NewListener = TweetListener()
NewStream = tweepy.Stream(auth=TweetAPI.auth, listener=NewListener)
NewStream.filter(follow=['USER IDS HERE'], is_async=True)

@bot.event
async def on_ready():
    print(MyBot.user.name,'has successfully logged in ('+str(MyBot.user.id)+')')
    print('Ready to respond')

MyBot.run(DISCORD_TOKEN)

The channel.send() method generates the following message when I post a tweet to my testing account's timeline:

RuntimeWarning: coroutine 'Messageable.send' was never awaited

I understand the message - the channel.send() method is an asynchronous method, but the on_status() event handler is a synchronous method and I can't await channel.send()  inside on_status() - but I can't figure out how to make it work. I tried to make the on_status() method an asynchronous method:

    async def on_status(self, status):
        <same code for checking the tweet and finding the channel>
        await DChannel.send(TweetText, embed = TwitterEmbed)

but this always resulted in a similar warning:

RuntimeWarning: coroutine 'TweetListener.on_status' was never awaited
if self.on_status(status) is False:

I found the question, How do I async on_status from tweepy? and followed the links there, but I didn't see anything that clued me in to whatever my coding error is.

Through additional research, I also tried using some calls from the asyncio library to make the call:

    #channel.send(message, embed = TwitterEmbed)
    #---ASYNCIO TEST---
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(DChannel.send(embed=TwitterEmbed)))
    loop.close()

Unfortunately, this results in an unhandled exception when it attempts to execute loop=asyncio.get_event_loop() indicating There is no current event loop in thread 'Thread-6'. (so it won't even get to the run_until_complete() method to see if that will work, although I'm not exactly optimistic at this point).

I realize there are existing Discord bots like MEE6 that can already do what I'm trying to do here, but I'd like to be able to make this bot "my own" while teaching myself a little about Python. I'm probably overlooking something simple here, but I've not been able to find anything in the API documentation for either tweepy or discord.py that seems to be pointing me in the correct direction, and my Google-fu is apparently not that strong. All of the examples I've been able to find so far appear to be out-of-date as  they seem to refer to deprecated methods and older versions of either or both libraries. There are other things that I still have to figure out how to do as well (e.g., get the @TwitterHandle to correctly populate the embed), but I've got to get it able to read and push the tweet before I can worry about getting to that point.

ENVIRONMENT INFO

Visual Studio 2017 CE

Python 3.6

discord.py 1.3.3

tweepy 3.8.0

UPDATE: ADDITIONAL TESTING

So, just to prove to myself that my TweetListener class is actually working, I went ahead and commented out all of the interaction with Discord in the on_status method (everything from for Guild in MyBot.guilds to the end of the method), then added a simple print(TweetText). I ran the code again, logged in to the testing Twitter account I have for this project, and posted an update. Checking the console, it correctly output the status.text of my tweet, as I expected it to. As I thought, the only issue I'm having here is trying to send that text to Discord.

I also tried initializing the tweepy.Stream.filter in synchronous mode instead of asynchronous - NewStream.filter(follow=['USER IDS']). This only resulted in my application basically "hanging" on startup. I realized this was due to its position in the code, so I moved all three lines of the TweetListener initialization to the on_ready event method. I left the Discord code commented out and tested, and it again "worked" in that it printed the status.text of another test tweet to the console. However, the bot won't respond to anything else (still "waiting" on the stream, I assume).

Even so, just to see if it would make any difference, I went ahead and uncommented the Discord interaction code and tried again. The result was the same as I had initially, only this time the Discord bot won't respond to activity in the channel (there are a couple of super simple @bot.command declarations elsewhere in the code), which once again basically leads me back to my original code with the same issue.

I'm certain there are better ways to code this entire thing. As I said above, I'm just now starting to play around with Python and still learning syntax rules and such. Even so, I'm still not sure what I'm doing wrong and/or overlooking that's preventing me from achieving what I had thought would be a fairly simple task.

MORE TESTING

I went back and found some more asyncio examples and tried another iteration in the Discord interaction in on_status:

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    result=loop.run_until_complete(DChannel.send(embed=TwitterEmbed))

This time I got a different unhandled exception than I've gotten before. The error occurs on the run_until_complete line when it picks up a new tweet:

Timeout context manager should be used inside a task

I consider this progress, but I'm obviously still not quite there, so back to Google and I found information on the asgiref library with its sync_to_async and async_to_sync methods, so I figured I'd give that a try.

    asgiref.sync.async_to_sync(DChannel.send)(embed=TwitterEmbed)

Unfortunately, I get the same unhandled exception as with the asyncio version. I feel like I'm right on the edge of figuring this out, but it simply hasn't "clicked" yet.

ANOTHER ROUND

Okay, so after looking for information about the Timeout context manager exception I was getting above, I stumbled across another SO question that has given me a tiny glimmer of hope. This answer on RuntimeError: Timeout context manager should be used inside a task once again takes me back to using asyncio and gives a brief but descriptive explanation of the reason behind the OP's issue before providing a useful suggestion using the asyncio.run_coroutine_threadsafe method. Looking at the recommended code, it made sense that this could help me initiate the sync->async method communication effectively. I implemented the suggested changes (created a global variable for a Thread object on which to run the bot, added a "startup" method that generated the bot in that loop, then changed the Discord interaction in on_status to bring it all together.

The "good news" is that I'm no longer getting any errors when I post a tweet. Also, testing the bot command seems to work just fine as well. The bad news is that it still didn't send the message to the channel. Since it didn't produce any errors, there's no telling where the message ended up.

Body:
I went through the same problem as you have, and got the exact links from google and tried all of them but as you have mentioned nothing worked.

So, after lots of trying and tinkering I realised, I could pass the main loop to the tweepy listener and execute async functions with run_coroutine_threadsafe.

Here is the gist of my code:

the listener:

class EpicListener(tweepy.StreamListener):
    def __init__(self, discord, loop, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.discord = discord # this is just a function which sends a message to a channel
        self.loop = loop # this is the loop of discord client

    def on_status(self, status):
        self.send_message(status._json)

    def send_message(self, msg):
        # Submit the coroutine to a given loop
        future = asyncio.run_coroutine_threadsafe(self.discord(msg), self.loop)
        # Wait for the result with an optional timeout argument
        future.result()

the discord client:

class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    async def on_ready(self):
        myStream = tweepy.Stream(
                    auth=api.auth, listener=EpicListener(discord=self.sendtwitter, loop=asyncio.get_event_loop())
                )
        myStream.filter(follow=['mohitwr'], is_async=True)
        print(myStream)

Hope this helps.


问:
How do I check if an input is in fact in a column in pandas?
Example of the dataFrame:

```<code>df = {'column': 'hello'}
</code>```

The input should be an entry in the dataFrame

```<code>if 'hello' in df['column']:
   print("hello")
else:
  print("Couldn't find entry)
</code>```

What I would want as the output would be:

```<code>Hello
</code>```

However, the output comes out as:

```<code>Couldn't find entry
</code>```

I've checked and the value entered in the input is definitely inside that column of the dataFrame
I don't know if im doing anything incorrectly or why it is not working

答:
Use df.values:</p>

```<code>for i in df.values:
 if 'hello' in i:
    print("hello")
 else:
    print("Couldn't find entry")
</code>```

Body:
Example of the dataFrame:

df = {'column': 'hello'}

The input should be an entry in the dataFrame

if 'hello' in df['column']:
   print("hello")
else:
  print("Couldn't find entry)

What I would want as the output would be:

Hello

However, the output comes out as:

Couldn't find entry

I've checked and the value entered in the input is definitely inside that column of the dataFrame
I don't know if im doing anything incorrectly or why it is not working

Body:
Use df.values:

for i in df.values:
 if 'hello' in i:
    print("hello")
 else:
    print("Couldn't find entry")


答:
This is how BigQuery UI visualize arrays (repeated fields)!

In both Classic and Console UI

Meantime, this is just matter of how given Tool represents / visualize certain data types

For example, in Goliath (part of Potens.io Suite) same will be represented as

with ability then to drill down to specific data cell and see it as (for example)

Title: Comma is generating separate rows for a particular value in a column while exporting table from pyspark cluster to BigQuery

Body:
I was exporting a spark df to bigquery by using the code below

gcs_bucket = 'main'
bq_dataset = 'table'
bq_table = 'user'

Rules.write \
  .format("bigquery") \
  .option("table","{}.{}".format(bq_dataset, bq_table)) \
  .option("temporaryGcsBucket", gcs_bucket) \
  .mode('overwrite') \
  .save()

Below is the output i was getting within the cluster

+-----------+----------+-------------------+------------------+
| antecedent|consequent|         confidence|              lift|
+-----------+----------+-------------------+------------------+
|[19, 6, 39]|      [44]|  0.418945963975984|10.602038775664845|
|[19, 6, 39]|      [35]|0.47298198799199465| 7.423073393311932|
|[19, 6, 39]|     [322]|   0.47631754503002|4.6520592549063995|
|[19, 6, 39]|     [308]| 0.4496330887258172| 5.856259667533207|
|[19, 6, 39]|     [345]| 0.5196797865243495|5.4970336458402285|

when exported the above df to bigquery, i am getting the table in the below format. Why is that? and how can i fix it?


问:
Azure container instances (ACI) deployment to virtual network fails (region: westeurope)
my ACI deployment to a virtual network (target subnet is delegated to container instances) stopped working over the week-end with a strange error message:

"The requested resource is not available in the location 'westeurope' at this moment. Please retry with a different resource request or in another location. Resource requested: '1' CPU '1.5' GB memory 'Linux' OS virtual network"

Here is the deployment script:

az container create --resource-group $(resourceGroupName) --name $(containerName) --image $(image) --cpu 1 --memory 1 --registry-login-server $(registryServer) --registry-username $(registryUsername) --registry-password $(registryPassword) --ports $(port) --vnet $(vnet) --subnet $(subnet) --command-line "..."

Also the manual deployment does not work - it allows me to select all the options accordingly but faily during the deployment with the above error message.

According to the docs at https://learn.microsoft.com/de-de/azure/container-instances/container-instances-region-availability deployment to virtual networks should work fine for ACIs in westeurope. Last Thursday it worked fine. Do you have any ideas? Many thanks in advance.

Edit: leaving out the --vnet and --subnet options makes the deployment work. But this cannot be the solution as I need the container instance deployed within the specified subnet.

答:
I would recommend to reach out to Azure Support, this might be running out of capacity temporarily.

Also, have a look at creating Quota Request, asking for ACI quota in westeurope.


问:
Hide elements using Typescript
I'm new to Typescript and Angular Material. I want to hide elements inside elements like this.

```<code><div id="abc">
   <div id="123">
      <p>Hello!</p>
   </div>
      <p>World</p>
</div>
<div id="def">
    <p>Hello World</p>
</div>
</code>```

I want to hide div block(id:123).I tried in this way.

```<code>var formElement = <HTMLFormElement>document.getElementById('123');
formElement.style.display='block';
</code>```

It gets an error saying Cannot read property 'style' of null.... How can I solve this problem.

答:
```<code>@Component({
  selector: 'my-app',
  template: `
   <div #id>
      <p>Hide This!</p>
   </div>
<div>
    <p>Hello World</p>
</div>
  `,
})
export class AppComponent {
@ViewChild('id') id:ElementRef;
  constructor() {}
  ngOnInit()
  {
     this.id.nativeElement.hidden=true;
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Hide elements using Typescript

Body:
I'm new to Typescript and Angular Material. I want to hide elements inside elements like this.

Hello!

World

Hello World

I want to hide div block(id:123).I tried in this way.

var formElement = <HTMLFormElement>document.getElementById('123');
formElement.style.display='block';

It gets an error saying Cannot read property 'style' of null.... How can I solve this problem.


问:
Django App Not Working After Deployment to heroku
The App is A Blog Post App That is Working fine Locally But After I Deployed It To Heroku, The App Cannot run. I did more Than a week trying to fix it through the views and models with no success.

This Is The Error When Trying To Open The App

views.py

```<code>from django.shortcuts import render,get_object_or_404, get_list_or_404
from posts.models import Post, Category
# Create your views here.

import datetime

 def index(request):

    now = datetime.datetime.now()
    big_slider_list = Post.objects.filter(category__name='Big_Slider')
    news_box_list = Post.objects.filter(category__name='People')

    cote_divoire_list = Post.objects.filter(category__name="Côte d'Ivoire").exclude(position=1)
    block1_big = Post.objects.filter(position=1)

    culture_list = Post.objects.filter(category__name="Culture").exclude(position=2)
    block2_big = Post.objects.filter(position=2)

    sport_list = Post.objects.filter(category__name="Sports").exclude(position=3)
    block3_big = Post.objects.filter(position=3)

    infrast_et_devel_list = Post.objects.filter(category__name="Infrastructures Et Dévelopements")

    context = {
        'now': now,

        'big_slider_list': big_slider_list[:10],
        'news_box_list': news_box_list[:4],

        'cote_divoire_list': cote_divoire_list[:4],
        'block1_big': block1_big[0],

        'culture_list': culture_list[:3],
        'block2_big': block2_big[0],

        'sport_list': sport_list[:3],
        'block3_big': block3_big[0],

        'infrast_et_devel_list': infrast_et_devel_list[:3],

    }
    return render(request, 'home/index.html', context)
</code>```

models.py :

```<code>from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
# Create your models here.

User = get_user_model()

STATUS = (
    (0, "Draft"),
    (1, "Publish")
)

POSITIONS = [
    (0, ' '),
    (1, 'BIG_BLOCK_1'),
    (2, 'BIG_BLOCK_2'),
    (3, 'BIG_BLOCK_3'),
    (4, 'BIG_BLOCK_4'),

]

class Author(models.Model):
    name = models.CharField(max_length=50)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_picture = models.ImageField(null=True, blank=True)
    email = models.EmailField(unique=True)
    active = models.BooleanField(default=False)
    created_on = models.DateTimeField(auto_now_add=True)
    last_logged_in = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username

class Category(models.Model):
    country = models.CharField(max_length=200, blank=True)
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE,)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('posts:post_by_category', args=[self.slug])

class Tag(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE,)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('posts:post_by_tag', args=[self.slug])

class Post(models.Model):
    status = models.IntegerField(choices=STATUS, default=0)
    position = models.IntegerField(choices=POSITIONS, default=0)
    title = models.CharField(max_length=300)
    short_title = models.CharField(max_length=200)
    display_image = models.ImageField(null=True, blank=True)
    post_image = models.ImageField(null=True, blank=True)
    content = models.TextField(max_length=8000)
    slug = models.SlugField(max_length=300, unique=True)
    updated_on = models.DateTimeField(auto_now=True, auto_now_add=False)
    created_on = models.DateTimeField(auto_now=False, auto_now_add=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE,)
    category = models.ForeignKey(Category, on_delete=models.CASCADE,)
    tags = models.ManyToManyField(Tag,)
    comment_count = models.IntegerField(default=0)

    class Meta:
        ordering = ['-created_on']
        verbose_name = "All Post"

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('posts:post_detail', kwargs={'slug': self.slug})

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return 'Comment {} by {}'.format(self.body, self.name)
</code>```

答: It's something to do with the migrations. Your local DB has all the migrations applied, while your Database on Heroku doesn't have the post field. Maybe you added/edited the field later so your two DBs are out of sync. Since this seems to be a new project without data it would be easier for you to heroku reset your heroku database and push the local db to heroku. Here are the instructions: https://devcenter.heroku.com/articles/heroku-postgres-import-export

Body:
The App is A Blog Post App That is Working fine Locally But After I Deployed It To Heroku, The App Cannot run. I did more Than a week trying to fix it through the views and models with no success.

This Is The Error When Trying To Open The App

views.py

from django.shortcuts import render,get_object_or_404, get_list_or_404
from posts.models import Post, Category
# Create your views here.

import datetime

 def index(request):

    now = datetime.datetime.now()
    big_slider_list = Post.objects.filter(category__name='Big_Slider')
    news_box_list = Post.objects.filter(category__name='People')

    cote_divoire_list = Post.objects.filter(category__name="Côte d'Ivoire").exclude(position=1)
    block1_big = Post.objects.filter(position=1)

    culture_list = Post.objects.filter(category__name="Culture").exclude(position=2)
    block2_big = Post.objects.filter(position=2)

    sport_list = Post.objects.filter(category__name="Sports").exclude(position=3)
    block3_big = Post.objects.filter(position=3)

    infrast_et_devel_list = Post.objects.filter(category__name="Infrastructures Et Dévelopements")

    context = {
        'now': now,

        'big_slider_list': big_slider_list[:10],
        'news_box_list': news_box_list[:4],

        'cote_divoire_list': cote_divoire_list[:4],
        'block1_big': block1_big[0],

        'culture_list': culture_list[:3],
        'block2_big': block2_big[0],

        'sport_list': sport_list[:3],
        'block3_big': block3_big[0],

        'infrast_et_devel_list': infrast_et_devel_list[:3],

    }
    return render(request, 'home/index.html', context)

models.py :

from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
# Create your models here.

User = get_user_model()

STATUS = (
    (0, "Draft"),
    (1, "Publish")
)

POSITIONS = [
    (0, ' '),
    (1, 'BIG_BLOCK_1'),
    (2, 'BIG_BLOCK_2'),
    (3, 'BIG_BLOCK_3'),
    (4, 'BIG_BLOCK_4'),

]

class Author(models.Model):
    name = models.CharField(max_length=50)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_picture = models.ImageField(null=True, blank=True)
    email = models.EmailField(unique=True)
    active = models.BooleanField(default=False)
    created_on = models.DateTimeField(auto_now_add=True)
    last_logged_in = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username

class Category(models.Model):
    country = models.CharField(max_length=200, blank=True)
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE,)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('posts:post_by_category', args=[self.slug])

class Tag(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE,)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('posts:post_by_tag', args=[self.slug])

class Post(models.Model):
    status = models.IntegerField(choices=STATUS, default=0)
    position = models.IntegerField(choices=POSITIONS, default=0)
    title = models.CharField(max_length=300)
    short_title = models.CharField(max_length=200)
    display_image = models.ImageField(null=True, blank=True)
    post_image = models.ImageField(null=True, blank=True)
    content = models.TextField(max_length=8000)
    slug = models.SlugField(max_length=300, unique=True)
    updated_on = models.DateTimeField(auto_now=True, auto_now_add=False)
    created_on = models.DateTimeField(auto_now=False, auto_now_add=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE,)
    category = models.ForeignKey(Category, on_delete=models.CASCADE,)
    tags = models.ManyToManyField(Tag,)
    comment_count = models.IntegerField(default=0)

    class Meta:
        ordering = ['-created_on']
        verbose_name = "All Post"

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('posts:post_detail', kwargs={'slug': self.slug})

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return 'Comment {} by {}'.format(self.body, self.name)


问:
How to start @KafkaListener based on start flag
I'm trying to start my KafkaListener only when a flag is set to true.

```<code>@Component
public class KafkaTopicConsumer {

//Somehow wrap the listener to only start when a property value is set to true

@KafkaListener(topics = "#{@consumerTopic}", groupId = "#{@groupName}")
public void consumeMessage(ConsumerRecord<String, String> message) throws IOException {
    logger.info("Consumed message from topic: {} with message: {}", message.topic(), message);
}
</code>```

Is there a way to only make sure the listener is started when said a property such as start.consumer property is set to true? I don't want the listener starting every time the application is started only when I specify that I want it to be started. Is there a good way to approach this use case?

答:
First, you need to set autoStartup to false and give your container a name. Then you need to start it manually based on a flag using @EventListener.

@Component
public class KafkaTopicConsumer {
    @Autowired
    private KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;

    @Value("${start.consumer}")
    private boolean shouldStart;

    @KafkaListener(id = "myListener", autoStartup = "false", topics = "#{@consumerTopic}", groupId = "#{@groupName}")
    public void consumeMessage(ConsumerRecord<String, String> message) throws IOException {
        logger.info("Consumed message from topic: {} with message: {}", message.topic(), message);
    }

    @EventListener
    public void onStarted(ApplicationStartedEvent event) {
        if (shouldStart) {
            MessageListenerContainer listenerContainer = kafkaListenerEndpointRegistry.getListenerContainer("myListener");
            listenerContainer.start();
        }
    }
}
```

<p><strong>Note:</strong> <code>@EventListener</code> will make sure containers are properly loaded, if you use <code>@PostConstruct</code> it probably won't work.</p>

<p><strong>EDIT</strong>: </p>

<p>Added the actual reading of the property using the <code>@Value</code> annotation.</p>

<p><strong>Note:</strong> This approach has the added flexibility of allowing the <code>start</code> and <code>stop</code> methods to also be called dynamically (using JMX for example) with just a few changes. This facilitates the scenario where we want to disable a consumer and enable it later without restarting the application. </p>

<p>Another good approach, as correctly stated in @Makoton's answer, is to use <code>@ConditionalOnProperty</code>. Just to note that in your example, you can use it with <code>@Component</code> instead of defining the <code>@Bean</code> manually. </p>

<pre class="lang-java prettyprint-override"><code>@Component
@ConditionalOnProperty(
        value = "start.consumer",
        havingValue = "true")
public class KafkaTopicConsumer { // ...
</code>```

It all comes down to the level of flexibility you need.

Body:
I'm trying to start my KafkaListener only when a flag is set to true.

@Component
public class KafkaTopicConsumer {

//Somehow wrap the listener to only start when a property value is set to true

@KafkaListener(topics = "#{@consumerTopic}", groupId = "#{@groupName}")
public void consumeMessage(ConsumerRecord<String, String> message) throws IOException {
    logger.info("Consumed message from topic: {} with message: {}", message.topic(), message);
}

Is there a way to only make sure the listener is started when said a property such as start.consumer property is set to true? I don't want the listener starting every time the application is started only when I specify that I want it to be started. Is there a good way to approach this use case?

Body:
First, you need to set autoStartup to false and give your container a name. Then you need to start it manually based on a flag using @EventListener.

@Component
public class KafkaTopicConsumer {
    @Autowired
    private KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;

    @Value("${start.consumer}")
    private boolean shouldStart;

    @KafkaListener(id = "myListener", autoStartup = "false", topics = "#{@consumerTopic}", groupId = "#{@groupName}")
    public void consumeMessage(ConsumerRecord<String, String> message) throws IOException {
        logger.info("Consumed message from topic: {} with message: {}", message.topic(), message);
    }

    @EventListener
    public void onStarted(ApplicationStartedEvent event) {
        if (shouldStart) {
            MessageListenerContainer listenerContainer = kafkaListenerEndpointRegistry.getListenerContainer("myListener");
            listenerContainer.start();
        }
    }
}

Note: @EventListener will make sure containers are properly loaded, if you use @PostConstruct it probably won't work.

EDIT:

Added the actual reading of the property using the @Value annotation.

Note: This approach has the added flexibility of allowing the start and stop methods to also be called dynamically (using JMX for example) with just a few changes. This facilitates the scenario where we want to disable a consumer and enable it later without restarting the application.

Another good approach, as correctly stated in @Makoton's answer, is to use @ConditionalOnProperty. Just to note that in your example, you can use it with @Component instead of defining the @Bean manually.

@Component
@ConditionalOnProperty(
        value = "start.consumer",
        havingValue = "true")
public class KafkaTopicConsumer { // ...

It all comes down to the level of flexibility you need.


问:
How to protect a column in excel against changes using openpyxl?
I'd like to lock out some of the columns in the  for changes. To do that, I first locked out the entire file.

```<code>ws = wb["RFI"]
ws.protection.sheet = True
</code>```

But then I try lock some of columns

```<code>for col in ['U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD']:
    ws[col].protection = Protection(locked=False)
</code>```

I got

```<code>AttributeError: 'tuple' object has no attribute 'protection'
</code>```

答:
When you are using worksheet['<some letter>'] what you get back is a tuple of all the cells in that column:

```<code>ws['A'] -> (Cell A1, Cell A2 ... Cell A<max_row>)
</code>```

After you lock the sheet you need to iterate over the cells that you want to unlock:

```<code>ws = wb["RFI"]
ws.protection.sheet = True

for col in ['U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD']:
        for cell in ws[col]:
            cell.protection = Protection(locked=False)
</code>```

This way your sheet will be locked but those specific columns will not be.

Body:
I'd like to lock out some of the columns in the  for changes. To do that, I first locked out the entire file.

ws = wb["RFI"]
ws.protection.sheet = True

But then I try lock some of columns

for col in ['U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD']:
    ws[col].protection = Protection(locked=False)

I got

AttributeError: 'tuple' object has no attribute 'protection'

Body:
When you are using worksheet['<some letter>'] what you get back is a tuple of all the cells in that column:

ws['A'] -> (Cell A1, Cell A2 ... Cell A<max_row>)

After you lock the sheet you need to iterate over the cells that you want to unlock:

ws = wb["RFI"]
ws.protection.sheet = True

for col in ['U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD']:
        for cell in ws[col]:
            cell.protection = Protection(locked=False)

This way your sheet will be locked but those specific columns will not be.


问:
Accumulated count for each element in a range
I have a table x, where start and end are hour of the day.

x = data.table(start=c(5,7,9,12), end=c(12,14,15,20), val = 7:10)

I want the output table to be:

for each hour from  hour 4 (not 5) to the 21 (not 20), has the accumulated value such as:

```<code>hour total
4    0
5    7
6    7
7    15(7+8)
</code>```

Body:
I have a table x, where start and end are hour of the day.

x = data.table(start=c(5,7,9,12), end=c(12,14,15,20), val = 7:10)

I want the output table to be:

for each hour from  hour 4 (not 5) to the 21 (not 20), has the accumulated value such as:

hour total
4    0
5    7
6    7
7    15(7+8)

Body:
Here's a simple base R solution:

hour  <- min(x$start):max(x$end)
total <- sapply(hour, function(i) sum(x$val[x$start <= i & x$end >= i])))
data.frame(hour, total)
#>    hour total
#> 1     5     7
#> 2     6     7
#> 3     7    15
#> 4     8    15
#> 5     9    24
#> 6    10    24
#> 7    11    24
#> 8    12    34
#> 9    13    27
#> 10   14    27
#> 11   15    19
#> 12   16    10
#> 13   17    10
#> 14   18    10
#> 15   19    10
#> 16   20    10


问:
Date is not coming out correctly in Kibana
I am having a strange issue
i have sent the date like below
2020-05-26T13:53:01.762+0000
i see in kibana like below
020-05-26T13: 53:01.762+0000

This is causing not to populate fields correctly.

Can you Please help me with this?

答:
You can change the date format in index pattern settings for that field.
In the index pattern settings page for a date field.</p>


问:
Extracting 'single item' from Multi Dimensional Array (c#)
Say I have the code

```<code>var marray = new int[,]{{0,1},{2,3},{4,5}};
</code>```

Is it possible to get a reference to the first item  - i.e. something that looked like:

```<code>var _marray = marray[0];
//would look like: var _marray = new int[,]{{0,1}};
</code>```

Instead, when referencing marray from a one dimensional context, it sees marray as having  length of 6

(i.e. new int[]{0,1,2,3,4,5})

答:
Use a jagged array</p>

```<code>var marray = new[] { new[] { 0, 1 }, new[] { 2, 3 }, new[] { 4, 5 } };
Console.WriteLine(marray[0][1]);
</code>```

Body:
Say I have the code

var marray = new int[,]{{0,1},{2,3},{4,5}};

Is it possible to get a reference to the first item  - i.e. something that looked like:

var _marray = marray[0];
//would look like: var _marray = new int[,]{{0,1}};

Instead, when referencing marray from a one dimensional context, it sees marray as having  length of 6

(i.e. new int[]{0,1,2,3,4,5})

Body:
Use a jagged array

var marray = new[] { new[] { 0, 1 }, new[] { 2, 3 }, new[] { 4, 5 } };
Console.WriteLine(marray[0][1]);


问:
Is it possible to sort using XSLT template recursive loops?
I have an assignment to make a table using data for a car's make, model, color, and a description. I am then asked to make a recursive loop using templates, in order to sort by the make, which is car_rental/car/manufacturer_brand/text(), in ascending order. Here's a version without sorting and templates.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="/">
       <html>
           <body>
               <table border="1">
                   <tr bgcolor="#FF5E6D">
                       <th>Car Make</th>
                       <th>Model</th>
                       <th>Color</th>
                       <th>Description</th>
                   </tr>
                   <xsl:for-each select="car_rental/car">
                       <tr>
                           <td><xsl:value-of select="manufacturer_brand/text()"/></td>
                           <td><xsl:value-of select="manufacturer_brand/model"/></td>
                           <td><xsl:value-of select="main_characteristics/extra_car_info/@color"/></td>
                           <td><xsl:value-of select="manufacturer_brand/mini_model_description"/></td>
                       </tr>
                   </xsl:for-each>
               </table>
           </body>
       </html>
   </xsl:template>
</xsl:stylesheet>
</code>```

They haven't given us any clues on how to sort using templates, which has made things worse. Does anyone have any tips?

答:
I figured it out by using this previous post. Here is my final code:</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
            <body>
                <table border="1">
                    <tr bgcolor="#FF5E6D">
                        <th>Car Make</th>
                        <th>Model</th>
                        <th>Color</th>
                        <th>Description</th>
                    </tr>
                        <xsl:apply-templates select="car_rental/car">
                            <xsl:sort select="manufacturer_brand/text()"/>
                        </xsl:apply-templates>
                </table>
            </body>
        </html>
    </xsl:template>

    <xsl:template match="car">
        <tr>
            <td><xsl:value-of select="manufacturer_brand/text()"/></td>
            <td><xsl:value-of select="manufacturer_brand/model"/></td>
            <td><xsl:value-of select="main_characteristics/extra_car_info/@color"/></td>
            <td><xsl:value-of select="manufacturer_brand/mini_model_description"/></td><br/>
        </tr>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
I have an assignment to make a table using data for a car's make, model, color, and a description. I am then asked to make a recursive loop using templates, in order to sort by the make, which is car_rental/car/manufacturer_brand/text(), in ascending order. Here's a version without sorting and templates.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="/">

                       Car Make
                       Model
                       Color
                       Description

                   <xsl:for-each select="car_rental/car">

                           <xsl:value-of select="manufacturer_brand/text()"/>
                           <xsl:value-of select="manufacturer_brand/model"/>
                           <xsl:value-of select="main_characteristics/extra_car_info/@color"/>
                           <xsl:value-of select="manufacturer_brand/mini_model_description"/>

                   </xsl:for-each>

   </xsl:template>
</xsl:stylesheet>

They haven't given us any clues on how to sort using templates, which has made things worse. Does anyone have any tips?

Body:
I figured it out by using this previous post. Here is my final code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
            <body>
                <table border="1">
                    <tr bgcolor="#FF5E6D">
                        <th>Car Make</th>
                        <th>Model</th>
                        <th>Color</th>
                        <th>Description</th>
                    </tr>
                        <xsl:apply-templates select="car_rental/car">
                            <xsl:sort select="manufacturer_brand/text()"/>
                        </xsl:apply-templates>
                </table>
            </body>
        </html>
    </xsl:template>

    <xsl:template match="car">
        <tr>
            <td><xsl:value-of select="manufacturer_brand/text()"/></td>
            <td><xsl:value-of select="manufacturer_brand/model"/></td>
            <td><xsl:value-of select="main_characteristics/extra_car_info/@color"/></td>
            <td><xsl:value-of select="manufacturer_brand/mini_model_description"/></td><br/>
        </tr>
    </xsl:template>
</xsl:stylesheet>


问:
Error: constructor ModuleRegistryAdapter in class ModuleRegistryAdapter cannot be applied to given types, new ModuleRegistryAdapter()
Hello im getting the fallowing error on console:

```<code>error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
/Users/user/Desktop/.../android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java:82: error: constructor ModuleRegistryAdapter in class ModuleRegistryAdapter cannot be applied to given types;
      new ModuleRegistryAdapter(),
      ^
  required: ReactModuleRegistryProvider
  found:    no arguments
  reason: actual and formal argument lists differ in length
1 error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
</code>```

on android studio:

```<code>/Users/username/.../project_name/android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java:82: error: constructor ModuleRegistryAdapter in class ModuleRegistryAdapter cannot be applied to given types;
      new ModuleRegistryAdapter(),
      ^
  required: ReactModuleRegistryProvider
  found: no arguments
  reason: actual and formal argument lists differ in length
</code>```

"react-native": "~0.61.5",
"react-native-unimodules": "^0.9.1",

It seems a recent react-native-unimodules bug on android, any solutions?
this is the same error:
https://www.gitmemory.com/issue/unimodules/react-native-unimodules/58/530738183

答: If you use react-native-unimodules, check if you also have "@unimodules/react-native-adapter" in your package.json. If so, try removing it and rebuild. It worked for me.</p>

Body:
Hello im getting the fallowing error on console:

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
/Users/user/Desktop/.../android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java:82: error: constructor ModuleRegistryAdapter in class ModuleRegistryAdapter cannot be applied to given types;
      new ModuleRegistryAdapter(),
      ^
  required: ReactModuleRegistryProvider
  found:    no arguments
  reason: actual and formal argument lists differ in length
1 error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

on android studio:

/Users/username/.../project_name/android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java:82: error: constructor ModuleRegistryAdapter in class ModuleRegistryAdapter cannot be applied to given types;
      new ModuleRegistryAdapter(),
      ^
  required: ReactModuleRegistryProvider
  found: no arguments
  reason: actual and formal argument lists differ in length

"react-native": "~0.61.5",
"react-native-unimodules": "^0.9.1",

It seems a recent react-native-unimodules bug on android, any solutions?
this is the same error:
https://www.gitmemory.com/issue/unimodules/react-native-unimodules/58/530738183


问:
typeorm querybuilder innerjoin only gives the first element
I have this querybuilder here:

```<code>this.repository.createQueryBuilder('house')
    .innerJoinAndSelect('house.items', 'items')
    .innerJoinAndSelect('house.owner', 'owner')
    .innerJoinAndSelect('house.rooms', 'rooms')
    .innerJoinAndSelect('rooms.name', 'name')
    .innerJoinAndSelect('rooms.roomitems', 'roomitems')
    .where({ 'house.id': id })
    .getOne().then(house => {
        // house.rooms.length === 1
    })
</code>```

I get my full object with this; a list of items, the owner and a list of rooms with all properties.

The problem is that the list of Rooms only contains one item. When I do use .find, I find four rooms.

what do I do wrong?

Edit:

```<code>this.repository.findOne(id, {relation: ['rooms']}).then(house => {
    // house.rooms.length === 4
})
</code>```

答:
It's hard to tell without seeing the whole database, but it could be linked with the difference with innerjoin and leftjoin in SQL.

With innerJoin, only the element with both side of the relation are returned,
and with leftjoin, element who do not have a right side of the relation are shown with Null in place of the right element.

you should try doing your query with leftJoinAndSelect to see if it's return all the rooms. If it does, I guessed correctly.

Body:
I have this querybuilder here:

this.repository.createQueryBuilder('house')
    .innerJoinAndSelect('house.items', 'items')
    .innerJoinAndSelect('house.owner', 'owner')
    .innerJoinAndSelect('house.rooms', 'rooms')
    .innerJoinAndSelect('rooms.name', 'name')
    .innerJoinAndSelect('rooms.roomitems', 'roomitems')
    .where({ 'house.id': id })
    .getOne().then(house => {
        // house.rooms.length === 1
    })

I get my full object with this; a list of items, the owner and a list of rooms with all properties.

The problem is that the list of Rooms only contains one item. When I do use .find, I find four rooms.

what do I do wrong?

Edit:

this.repository.findOne(id, {relation: ['rooms']}).then(house => {
    // house.rooms.length === 4
})