问:
pytest: `foo is Enum.FOO` tests True locally, False on travis-ci
Halp! I'm having weird issues with checking equality for Enums. Locally my tests pass, but on Travis they fail. Here's a sample of a test failure from Travis:

_____________________________ test_extract_object ______________________________
    def test_extract_object():
        """Test UmlCreator.extract_object()."""
        creator = UmlCreator(".")
        with pytest.raises(ValueError):
            creator.extract_object(["no", "klass", "included"])
        obj = creator.extract_object(
            [
                "public",
                "static",
                "class",
                "StaticKlass",
                ":",
                "ICanBeImplemented,",
                "IComparable,",
                "IEquatable<Klass>",
            ]
        )
        assert obj.__class__.__name__ == "UmlClass"
>       assert obj.access is Access.PUBLIC
E       assert Access("public") is Access("public")
E        +  where Access("public") = UmlClass(['StaticKlass', ':', 'ICanBeImplemented,', 'IComparable,', 'IEquatable<Klass>'], **{'nsp': None, 'access': Access("public"), 'attrs': [], 'modifiers': [Modifier("static")], 'repo_url': None}).access
E        +  and   Access("public") = Access.PUBLIC
tests/test_creator.py:44: AssertionError
```

<p>If I change the offending line to <code>assert obj.access.value == Access.PUBLIC.value</code> it passes on Travis as well, but I'm stumped as to why this fails in one place and passes in another with basically the same setup, and it of course also affects non-test code, meaning that everywhere I use <code>foo is Enum.VAL</code> in my code, tests for those methods fail as well:</p>

<pre class="lang-py prettyprint-override"><code>tests/test_creator.py:44: AssertionError
_________________________ test_uml_class_display_name __________________________
    def test_uml_class_display_name():
        """Test UmlClass.display_name()."""
        klass = UmlClass(["Classy"])
        assert klass.display_name() == "Classy"
        abstract_klass = UmlClass(["Classy"], modifiers=[Modifier.ABSTRACT])
>       assert abstract_klass.is_abstract()
E       assert False
</code>```

Local

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.4 LTS
Release:        18.04
Codename:       bionic
$ pip list
Package            Version
------------------ --------
appdirs            1.4.3
astroid            2.3.3
attrs              19.3.0
bandit             1.6.2
black              19.10b0
Click              7.0
coverage           5.0.3
gitdb2             2.0.6
GitPython          3.0.7
importlib-metadata 1.5.0
isort              4.3.21
lazy-object-proxy  1.4.3
mccabe             0.6.1
more-itertools     8.2.0
packaging          20.1
pathspec           0.7.0
pbr                5.4.4
pip                20.0.2
pluggy             0.13.1
py                 1.8.1
pylint             2.4.4
pyparsing          2.4.6
pytest             5.3.5
pytest-cov         2.8.1
PyYAML             5.3
regex              2020.1.8
rope               0.16.0
setuptools         45.1.0
six                1.14.0
smmap2             2.0.5
stevedore          1.32.0
toml               0.10.0
typed-ast          1.4.1
wcwidth            0.1.8
wheel              0.34.2
wrapt              1.11.2
zipp               2.2.0
$ pipenv run test
===== test session starts =====
platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
rootdir: /mnt/c/Users/thy/source/repos/uml.cs, inifile: pytest.ini
plugins: cov-2.8.1
collected 41 items
```

<h3>Travis</h3>

<pre class="lang-sh prettyprint-override"><code>$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.3 LTS
Release:    18.04
Codename:   bionic
$ pip list
Package            Version
------------------ ----------
appdirs            1.4.3
astroid            2.3.3
atomicwrites       1.3.0    !
attrs              19.3.0
bandit             1.6.2
black              19.10b0
certifi            2019.6.16 !
Click              7.0
coverage           5.0.3
gitdb2             2.0.6
GitPython          3.0.7
importlib-metadata 1.5.0
isort              4.3.21
lazy-object-proxy  1.4.3
mccabe             0.6.1
mock               3.0.5 !
more-itertools     8.2.0
nose               1.3.7 !
numpy              1.18.0 !
packaging          20.1
pathspec           0.7.0
pbr                5.4.4
pip                19.3.1
pipenv             2018.11.26
pluggy             0.13.1
py                 1.8.1
pylint             2.4.4
pyparsing          2.4.6
pytest             5.3.5
pytest-cov         2.8.1
PyYAML             5.3
regex              2020.1.8
rope               0.16.0
setuptools         42.0.2
six                1.14.0
smmap2             2.0.5
stevedore          1.32.0
toml               0.10.0
typed-ast          1.4.1
virtualenv         16.6.1
virtualenv-clone   0.5.3
wcwidth            0.1.8
wheel              0.33.6
wrapt              1.11.2
zipp               2.2.0
python -m pytest
===== test session starts =====
platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
rootdir: /home/travis/build/kthy/uml.cs, inifile: pytest.ini
plugins: cov-2.8.1
collected 41 items
</code>```

For easier comparison, here's a table of the differences:

```
| Local (WSL)        | Travis                 |
| ------------------ | ---------------------- |
| Ubuntu 18.04.4 LTS | Ubuntu 18.04.3 LTS     |
|                    | atomicwrites-1.3.0     |
|                    | certifi-2019.6.16      |
|                    | mock-3.0.5             |
|                    | nose-1.3.7             |
|                    | numpy-1.18.0           |
| pip-20.0.2         | pip-19.3.1             |
|                    | pipenv-2018.11.26      |
| setuptools-45.1.0  | setuptools-42.0.2      |
|                    | virtualenv-16.6.1      |
|                    | virtualenv-clone-0.5.3 |
| wheel-0.34.2       | wheel-0.33.6           |
```

Full build log from Travis can be seen e.g. here.

答:
So, as pointed out by Ethan the problem was my imports. For whatever reason I was importing the Enums like

try:
  from features import Access
except (ImportError, ModuleNotFoundError):
  from umldotcs.features import Access
```

- I can't remember why, but probably because I had had some problems with imports before. Cargo cult programming strikes again!  Running pytest locally used the second import, whereas Travis for some reason chose the first, triggering Issue30545 which is user error, not a python bug. Making sure all Enums were imported in the same way resolved the problem.

Body:
Halp! I'm having weird issues with checking equality for Enums. Locally my tests pass, but on Travis they fail. Here's a sample of a test failure from Travis:

_____________________________ test_extract_object ______________________________
    def test_extract_object():
        """Test UmlCreator.extract_object()."""
        creator = UmlCreator(".")
        with pytest.raises(ValueError):
            creator.extract_object(["no", "klass", "included"])
        obj = creator.extract_object(
            [
                "public",
                "static",
                "class",
                "StaticKlass",
                ":",
                "ICanBeImplemented,",
                "IComparable,",
                "IEquatable<Klass>",
            ]
        )
        assert obj.__class__.__name__ == "UmlClass"
>       assert obj.access is Access.PUBLIC
E       assert Access("public") is Access("public")
E        +  where Access("public") = UmlClass(['StaticKlass', ':', 'ICanBeImplemented,', 'IComparable,', 'IEquatable<Klass>'], **{'nsp': None, 'access': Access("public"), 'attrs': [], 'modifiers': [Modifier("static")], 'repo_url': None}).access
E        +  and   Access("public") = Access.PUBLIC
tests/test_creator.py:44: AssertionError

If I change the offending line to assert obj.access.value == Access.PUBLIC.value it passes on Travis as well, but I'm stumped as to why this fails in one place and passes in another with basically the same setup, and it of course also affects non-test code, meaning that everywhere I use foo is Enum.VAL in my code, tests for those methods fail as well:

tests/test_creator.py:44: AssertionError
_________________________ test_uml_class_display_name __________________________
    def test_uml_class_display_name():
        """Test UmlClass.display_name()."""
        klass = UmlClass(["Classy"])
        assert klass.display_name() == "Classy"
        abstract_klass = UmlClass(["Classy"], modifiers=[Modifier.ABSTRACT])
>       assert abstract_klass.is_abstract()
E       assert False

Local

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.4 LTS
Release:        18.04
Codename:       bionic
$ pip list
Package            Version
------------------ --------
appdirs            1.4.3
astroid            2.3.3
attrs              19.3.0
bandit             1.6.2
black              19.10b0
Click              7.0
coverage           5.0.3
gitdb2             2.0.6
GitPython          3.0.7
importlib-metadata 1.5.0
isort              4.3.21
lazy-object-proxy  1.4.3
mccabe             0.6.1
more-itertools     8.2.0
packaging          20.1
pathspec           0.7.0
pbr                5.4.4
pip                20.0.2
pluggy             0.13.1
py                 1.8.1
pylint             2.4.4
pyparsing          2.4.6
pytest             5.3.5
pytest-cov         2.8.1
PyYAML             5.3
regex              2020.1.8
rope               0.16.0
setuptools         45.1.0
six                1.14.0
smmap2             2.0.5
stevedore          1.32.0
toml               0.10.0
typed-ast          1.4.1
wcwidth            0.1.8
wheel              0.34.2
wrapt              1.11.2
zipp               2.2.0
$ pipenv run test
===== test session starts =====
platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
rootdir: /mnt/c/Users/thy/source/repos/uml.cs, inifile: pytest.ini
plugins: cov-2.8.1
collected 41 items

Travis

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.3 LTS
Release:    18.04
Codename:   bionic
$ pip list
Package            Version
------------------ ----------
appdirs            1.4.3
astroid            2.3.3
atomicwrites       1.3.0    !
attrs              19.3.0
bandit             1.6.2
black              19.10b0
certifi            2019.6.16 !
Click              7.0
coverage           5.0.3
gitdb2             2.0.6
GitPython          3.0.7
importlib-metadata 1.5.0
isort              4.3.21
lazy-object-proxy  1.4.3
mccabe             0.6.1
mock               3.0.5 !
more-itertools     8.2.0
nose               1.3.7 !
numpy              1.18.0 !
packaging          20.1
pathspec           0.7.0
pbr                5.4.4
pip                19.3.1
pipenv             2018.11.26
pluggy             0.13.1
py                 1.8.1
pylint             2.4.4
pyparsing          2.4.6
pytest             5.3.5
pytest-cov         2.8.1
PyYAML             5.3
regex              2020.1.8
rope               0.16.0
setuptools         42.0.2
six                1.14.0
smmap2             2.0.5
stevedore          1.32.0
toml               0.10.0
typed-ast          1.4.1
virtualenv         16.6.1
virtualenv-clone   0.5.3
wcwidth            0.1.8
wheel              0.33.6
wrapt              1.11.2
zipp               2.2.0
python -m pytest
===== test session starts =====
platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
rootdir: /home/travis/build/kthy/uml.cs, inifile: pytest.ini
plugins: cov-2.8.1
collected 41 items

For easier comparison, here's a table of the differences:

| Local (WSL)        | Travis                 |
| ------------------ | ---------------------- |
| Ubuntu 18.04.4 LTS | Ubuntu 18.04.3 LTS     |
|                    | atomicwrites-1.3.0     |
|                    | certifi-2019.6.16      |
|                    | mock-3.0.5             |
|                    | nose-1.3.7             |
|                    | numpy-1.18.0           |
| pip-20.0.2         | pip-19.3.1             |
|                    | pipenv-2018.11.26      |
| setuptools-45.1.0  | setuptools-42.0.2      |
|                    | virtualenv-16.6.1      |
|                    | virtualenv-clone-0.5.3 |
| wheel-0.34.2       | wheel-0.33.6           |

Full build log from Travis can be seen e.g. here.

Body:
So, as pointed out by Ethan the problem was my imports. For whatever reason I was importing the Enums like

try:
  from features import Access
except (ImportError, ModuleNotFoundError):
  from umldotcs.features import Access

- I can't remember why, but probably because I had had some problems with imports before. Cargo cult programming strikes again!  Running pytest locally used the second import, whereas Travis for some reason chose the first, triggering Issue30545 which is user error, not a python bug. Making sure all Enums were imported in the same way resolved the problem.


来源: stackexchange

问:
How to highlight item of recyclerView after long press like Telegram?
If you know in Telegram to delete chat or group we hold item(long press) and clicking another item then we add the group to chat, to delete the list, I cant do it.

Currently I can listening just only click like this:

```<code> itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(itemView.getContext(),"Short Click",Toast.LENGTH_SHORT).show();
        }
    });
</code>```

and listening long click:

```<code> itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(itemView.getContext(),"Short Click",Toast.LENGTH_SHORT).show();
            return false;
        }
    });
</code>```

In my case, I want to listen to long-press and then I want to highlight item(of course, the item is part of recyclerView) with just click(not long click) I googled but it did not help me.

答:
I believe the simplest solution is the following:

In OnLongClickListener iterate through RecyclerView views and set new OnClickListener to handle selection.

Store some flag to switch behavior in onBindViewHolder.

ContentLicense: CC BY-SA 4.0

Body:
If you know in Telegram to delete chat or group we hold item(long press) and clicking another item then we add the group to chat, to delete the list, I cant do it.

Currently I can listening just only click like this:

 itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(itemView.getContext(),"Short Click",Toast.LENGTH_SHORT).show();
        }
    });

and listening long click:

 itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(itemView.getContext(),"Short Click",Toast.LENGTH_SHORT).show();
            return false;
        }
    });

In my case, I want to listen to long-press and then I want to highlight item(of course, the item is part of recyclerView) with just click(not long click) I googled but it did not help me.


问:
Combining words from two lists
I'm experimenting and having a look at creating a randomizer from two lists.

```<code>$List = ’Red’,’Pink’,’Green’
$List1 = ’Warning’,’Election’,’Marriage’
</code>```

What I'm looking to do is pick a random word from $List and $List1. I'm aware that you can pick from a singular with :

Get-Random -InputObject $List

However, I'm not quite sure how I would be able to grab from both lists and combine them.

My expected output would be:

RedMarriage

PinkWarning

GreenElection

答:
This should do the trick:</p>

```<code>$list1 = @( 'Red','Pink','Green' )
$list2 = @('Warning','Election','Marriage')

$idx1 = Get-Random -Minimum 0 -Maximum $list1.Count
$idx2 = Get-Random -Minimum 0 -Maximum $list2.Count

$result = "$($list1[$idx1])$($list2[$idx2])"

$result
</code>```

Title: Combining words from two lists

Body:
I'm experimenting and having a look at creating a randomizer from two lists.

$List = ’Red’,’Pink’,’Green’
$List1 = ’Warning’,’Election’,’Marriage’

What I'm looking to do is pick a random word from $List and $List1. I'm aware that you can pick from a singular with :

Get-Random -InputObject $List

However, I'm not quite sure how I would be able to grab from both lists and combine them.

My expected output would be:

RedMarriage

PinkWarning

GreenElection

Body:
This should do the trick:

$list1 = @( 'Red','Pink','Green' )
$list2 = @('Warning','Election','Marriage')

$idx1 = Get-Random -Minimum 0 -Maximum $list1.Count
$idx2 = Get-Random -Minimum 0 -Maximum $list2.Count

$result = "$($list1[$idx1])$($list2[$idx2])"

$result


问:
Can C cope with sub-byte instruction addressing?
For example if an architecture supports nibble length instructions but data is byte aligned, will:

```<code>void *PointerToAnything;
</code>```

work? In other words, can the compiler handle this?

答:
In C, it is impossible to access data elements in units smaller than 8 bits, as the smallest possible type is char, which has CHAR_BIT bits, which is 8 at least. Bitfields are an exception, but don't allow pointers to their members; a data-pointer with sub-(8-)byte-precision can not exist in C.

However, instructions (and therefore functions) might be stored differently, and function-pointers could have sub-byte-precision. In general, function pointers and data pointers are not interchangeable, so you can not (correctly) store such a function pointer in a void* pointer. C does not support accessing the machine code anyways, so there would be no support for accessing instructions that have sub-byte-alignment and/or size.

Even on platforms with at least byte-instruction size & alignment, function pointers and data pointers might not be interchangeable, as function pointers might be larger or smaller than data pointers (imagine a system with 256 RAM bytes for data, and 64kB flash bytes for program memory). Therefore, C does not guarantee that void* can point to everything. However, some platforms such as POSIX do explicitly allow this, to allow e.g. dlsym() to work.

Body:
For example if an architecture supports nibble length instructions but data is byte aligned, will:

void *PointerToAnything;

work? In other words, can the compiler handle this?


问:
Function classes as a comparator
1) If I want the set to store elements in descending order, I could write:

```<code>set<int, greater<int>> s;
</code>```

but i can also

```<code>set<int, greater<>> s;
</code>```

how does the compiler understand this?

2) Why in the following case

```<code>vector<int> a;
binary_search(a.begin(), a.end(), 5, greater<>());
</code>```

I have to write greater<>(), instead of greater<>. This has some reason why it could not be done the same everywhere?

答:
1) how does the compiler understand this?

Because since C++14, the template parameter T of std::greater has a default value void; then std::greater<> is just the same as std::greater<void>.

The standard library provides a specialization of std::greater when T is not specified, which leaves the parameter types and return type to be deduced.

and

2) This has some reason why it could not be done the same everywhere?

Because binary_search is a function and expects its argument as object. greater<> (i.e. greater<void>) is a type, while greater<>() is an object (which is a temporary object in context of binary_search(a.begin(), a.end(), 5, greater<>());).

BTW: In set<int, greater<>> s;, you're specifying greater<> as the template argument. The 2nd template parameter of std::set is a type template parameter
, then it's fine to specify greater<> (which is a type) as the template argument.

Title: Function classes as a comparator

Body:
1) If I want the set to store elements in descending order, I could write:

set<int, greater<int>> s;

but i can also

set<int, greater<>> s;

how does the compiler understand this?

2) Why in the following case

vector<int> a;
binary_search(a.begin(), a.end(), 5, greater<>());

I have to write greater<>(), instead of greater<>. This has some reason why it could not be done the same everywhere?


问:
How do you organize your code for Angular app? (code organisation patterns)
I am struggling with the best pattern for code structure in my Angular app.

I have a project which contains more modules; every module has components tests, etc..

```<code>/app
    /commons
        /components
        /constants
            constant-1.constant.ts
            constant-2.constant.ts
            constant-3.constant.ts
            constant-4.constant.ts
            ...
        /helpers
            helper-1.helper.ts
            helper-2.helper.ts
            ...
    /module-name-1
         /commons
             /helpers
             /constants
         /component-name-1
            /component-name-subcomponent-1
               component-name-subcomponent-1.component.ts
         /component-name-2
            component-name-subcomponent-2.component.ts
         module-name-1.module.ts
         module-name-1-routing.module.ts
</code>```

This is how my code organization looks like. I would like to ask you, how do you struggle with some shared/common parts as constants/functions/helpers... Eg. constants - I tried to keep shared constants in one folder in the module, or if they are shared between modules, in the app path. But sometimes, I use constant just in one component, or 2 of them, and then I have followed by components tree to some far away shared folder where i have defined two lines of code. The same with interfaces - i keep all of them in one folder, but sometimes interface is used just in one component, or sometimes in their childs. How do you organize it? What is the best practice for bigger projects?

I wonder about one commons/ folder in-app route, with the similar structure as rest of app /module/component/ and there keeps interfaces and constants related to the components and keep a common path to them - but when I tried it - it also messed, and there are no helpful tools to manage it.

Any suggestions?

答:
This question will have highly opinionated answers, but according to

angular style guide one should have a angular app architecture like this :

```<code>|-- app
         |--Feature Modules Folder
           |-- Feature-1 Module  // comprising of feature-1 components
               |-- [+] components
               |-- [+] services // service provide by feature module
               |-- feature-1-routing.module.ts
               |-- feature-1.module.ts
         |-- Core Module Folder // all core functionality and singleton services
           which will be imported by root module and consist of no exports
           |-- [+] authentication
           |-- [+] footer
           |-- [+] guards
           |-- [+] http
           |-- [+] interceptors
           |-- [+] mocks
           |-- [+] services
           |-- [+] header
           |-- core.module.ts
           |-- logger.service.ts
         |-- Shared Module Folder // this modules containes components
              etc which are used multiple times across the app, Shared
              Module is imported by Features Module
              |-- [+] components
              |-- [+] directives
              |-- [+] pipes
              |-- [+] models
              |-- SharedModule.module.ts
         |-- [+] configs
    |-- assets
         |-- scss/ css
              |-- styles.scss/styles.css
</code>```

Body:
I am struggling with the best pattern for code structure in my Angular app.

I have a project which contains more modules; every module has components tests, etc..

/app
    /commons
        /components
        /constants
            constant-1.constant.ts
            constant-2.constant.ts
            constant-3.constant.ts
            constant-4.constant.ts
            ...
        /helpers
            helper-1.helper.ts
            helper-2.helper.ts
            ...
    /module-name-1
         /commons
             /helpers
             /constants
         /component-name-1
            /component-name-subcomponent-1
               component-name-subcomponent-1.component.ts
         /component-name-2
            component-name-subcomponent-2.component.ts
         module-name-1.module.ts
         module-name-1-routing.module.ts

This is how my code organization looks like. I would like to ask you, how do you struggle with some shared/common parts as constants/functions/helpers... Eg. constants - I tried to keep shared constants in one folder in the module, or if they are shared between modules, in the app path. But sometimes, I use constant just in one component, or 2 of them, and then I have followed by components tree to some far away shared folder where i have defined two lines of code. The same with interfaces - i keep all of them in one folder, but sometimes interface is used just in one component, or sometimes in their childs. How do you organize it? What is the best practice for bigger projects?

I wonder about one commons/ folder in-app route, with the similar structure as rest of app /module/component/ and there keeps interfaces and constants related to the components and keep a common path to them - but when I tried it - it also messed, and there are no helpful tools to manage it.

Any suggestions?

Body:
This question will have highly opinionated answers, but according to

angular style guide one should have a angular app architecture like this :

|-- app
         |--Feature Modules Folder
           |-- Feature-1 Module  // comprising of feature-1 components
               |-- [+] components
               |-- [+] services // service provide by feature module
               |-- feature-1-routing.module.ts
               |-- feature-1.module.ts
         |-- Core Module Folder // all core functionality and singleton services
           which will be imported by root module and consist of no exports
           |-- [+] authentication
           |-- [+] footer
           |-- [+] guards
           |-- [+] http
           |-- [+] interceptors
           |-- [+] mocks
           |-- [+] services
           |-- [+] header
           |-- core.module.ts
           |-- logger.service.ts
         |-- Shared Module Folder // this modules containes components
              etc which are used multiple times across the app, Shared
              Module is imported by Features Module
              |-- [+] components
              |-- [+] directives
              |-- [+] pipes
              |-- [+] models
              |-- SharedModule.module.ts
         |-- [+] configs
    |-- assets
         |-- scss/ css
              |-- styles.scss/styles.css


问:
SQL Find MAX Values for multiple rows
Data Set

Name    Number  Value
Alabama  254    100
Atlas    156    200
Alabama  354    300
Atlas    800    400
```

<p>SQL Statement as to return the Max Number per Name. </p>

<p>desired outcome </p>

<pre class="lang-none prettyprint-override"><code>Alabama  354    300
Atlas    800    400
</code>```

答:
SQL Statement as to return the Max Number per Name.

What you describe sounds like:

```<code>select t.*
from t
where t.number = (select max(t2.number) from t t2 where t2.name = t.name);
</code>```

In most databases, this has optimal or close-to optimal performance with an index on (name, number).

Title: SQL Find MAX Values for multiple rows

Body:
Data Set

Name    Number  Value
Alabama  254    100
Atlas    156    200
Alabama  354    300
Atlas    800    400

SQL Statement as to return the Max Number per Name.

desired outcome

Alabama  354    300
Atlas    800    400

Body:
SQL Statement as to return the Max Number per Name.

What you describe sounds like:

select t.*
from t
where t.number = (select max(t2.number) from t t2 where t2.name = t.name);

In most databases, this has optimal or close-to optimal performance with an index on (name, number).


问:
Different agent pool or demands for the same Azure Pipeline based on trigger
I have an Azure Pipeline written in YAML which runs from a CI trigger whenever changes are made to the master branch.  It can also be manually triggered from Pull Requests or by users against any branch.

Due to the use of a number of licensed components, the build from master needs to run on a specific agent.  The other builds do not, and in fact I would rather they run on other agent(s).

So my question is, is there any way to specify a different agent/pool within the YAML pipeline based on what triggered the build, or what branch the build is building?  I'd like this to be behaviour which is configured in the pipeline permanently, rather than requiring users to update the YAML on each branch they wish to build elsewhere.

I can't see anything obvious in the sections of the documentation on the pool/demands/condition keywords.

答:
Could you try expressions? I've used this with success on variable groups so it might work on agent pools.

```<code>- ${{ if eq(variables['build.SourceBranchName'], 'prod') }}:
  - pool: Host1
- ${{ if eq(variables['build.SourceBranchName'], 'staging') }}:
  - pool: Host2
- ${{ if not(and(eq(variables['build.SourceBranchName'], 'staging'), eq(variables['build.SourceBranchName'], 'prod'))) }}:
  - pool: Host3
</code>```

Credit for original workaround for dynamically pulling variable groups here: https://github.com/MicrosoftDocs/vsts-docs/issues/3702#issuecomment-574278829

Body:
Could you try expressions? I've used this with success on variable groups so it might work on agent pools.

- ${{ if eq(variables['build.SourceBranchName'], 'prod') }}:
  - pool: Host1
- ${{ if eq(variables['build.SourceBranchName'], 'staging') }}:
  - pool: Host2
- ${{ if not(and(eq(variables['build.SourceBranchName'], 'staging'), eq(variables['build.SourceBranchName'], 'prod'))) }}:
  - pool: Host3

Credit for original workaround for dynamically pulling variable groups here: https://github.com/MicrosoftDocs/vsts-docs/issues/3702#issuecomment-574278829


问:
How do I use Dataframe apply function to normalize Data
I'm trying to normalize new data with the mean and std values which I already have got.

```<code>t = np.array([[1,2,3],
     [4,5,6],
     [7,8,9]])

tt = np.array([[1,1,1],
     [100,100,100]])

a = pd.DataFrame(t, columns=['a','b','c'])
b = pd.DataFrame(tt, columns=['a', 'b', 'c'], index=['mean', 'std'])

def standardize(x, y):
    return (x - y.loc['mean']) / y.loc['std']
</code>```

```<code>a.apply(standardize(a,b))
</code>```

I want to get normalized dataframe that each values is calculated by 'b' dataframe's mean and std on each columns with apply function

ex) a[0]['a'] = (a[0]['a'] - b['mean']['a']) / b['std'][a]

any better ways would be fine as well. Thanks..

答:
```<code>(a-b.loc['mean'])/b.loc['std']
</code>```

If you define b as b=b.T, then

```<code>(a-b['mean'])/b['std']
</code>```

Body:
I'm trying to normalize new data with the mean and std values which I already have got.

t = np.array([[1,2,3],
     [4,5,6],
     [7,8,9]])

tt = np.array([[1,1,1],
     [100,100,100]])

a = pd.DataFrame(t, columns=['a','b','c'])
b = pd.DataFrame(tt, columns=['a', 'b', 'c'], index=['mean', 'std'])

def standardize(x, y):
    return (x - y.loc['mean']) / y.loc['std']

a.apply(standardize(a,b))

I want to get normalized dataframe that each values is calculated by 'b' dataframe's mean and std on each columns with apply function

ex) a[0]['a'] = (a[0]['a'] - b['mean']['a']) / b['std'][a]

any better ways would be fine as well. Thanks..

Body:
(a-b.loc['mean'])/b.loc['std']

If you define b as b=b.T, then

(a-b['mean'])/b['std']


问:
Changing the color of the parent component based upon the selection in the child component
I have a child component which is having a dropdrown of colors.Based upon what is selected in the dropdown list, the colour of the parent component should change.

As of now I am able to successfully change the color of the child component based upon the color selection ,but i want to change the color of the parent component.
Any help?
I am also able to print the Value of the dropdown in the parent component as I am using a reference variable but I want the color to change as well.

header.component.html:

```<code>import { Component, OnInit,Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  styles: string[] = [];
  selectedStyle: string;

  constructor() {

  }

  ngOnInit(){

    this.styles = ['red','green','blue','none'];
    }

}
</code>```

header.component.html

```<code><div [ngClass]="selectedStyle" >

    <select [(ngModel)]="selectedStyle">
       <option *ngFor="let s of styles" [ngValue]="s">{{s}}</option>
    </select>

    </div>
</code>```

app.component.html

```<code><div [ngClass]="child.selectedStyle"><app-header #child></app-header></div>
  <h2>{{title}}</h2>
  <h1>{{child.selectedStyle}}</h1>
</code>```

答:
Handle the select change event in your header component HTML.

header.component.html

```<code><select [ngModel]="selectedStyle" (ngModelChange)="onStyleChange($event)">
  <option *ngFor="let s of styles" [ngValue]="s">{{s}}</option>
</select>

</code>```

Add an event handler for your select and an event emitter to your header component typescript.

header.component.ts

```<code>
// trigger events using this
@Output() styleChange: EventEmitter<string> = new EventEmitter<string>();

// handle style change events using this
onStyleChange(style: string): void {
  // trigger event
  this.selectedStyle = style;
  this.styleChange.emit(style);
}
</code>```

Handle the style change event in the parent HTML.

app.component.html

```<code><app-header #child (styleChange)="onStyleChange($event)">
</app-header>
</code>```

Handle the style change event in your parent typescript, and set a property that is available to your parent's HTML.

app.component.ts

```<code>style: string;

onStyleChange(style: string): void {
  this.style = style;
}
</code>```

Whatever style is emitted from the child component is now available to the parent.

Body:
I have a child component which is having a dropdrown of colors.Based upon what is selected in the dropdown list, the colour of the parent component should change.

As of now I am able to successfully change the color of the child component based upon the color selection ,but i want to change the color of the parent component.
Any help?
I am also able to print the Value of the dropdown in the parent component as I am using a reference variable but I want the color to change as well.

header.component.html:

import { Component, OnInit,Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  styles: string[] = [];
  selectedStyle: string;

  constructor() {

  }

  ngOnInit(){

    this.styles = ['red','green','blue','none'];
    }

}

header.component.html

    <select [(ngModel)]="selectedStyle">
       <option *ngFor="let s of styles" [ngValue]="s">{{s}}</option>
    </select>

app.component.html

<app-header #child></app-header>

{{title}}

{{child.selectedStyle}}

Body:
Handle the select change event in your header component HTML.

header.component.html

<select [ngModel]="selectedStyle" (ngModelChange)="onStyleChange($event)">
  <option *ngFor="let s of styles" [ngValue]="s">{{s}}</option>
</select>

Add an event handler for your select and an event emitter to your header component typescript.

header.component.ts

// trigger events using this
@Output() styleChange: EventEmitter<string> = new EventEmitter<string>();

// handle style change events using this
onStyleChange(style: string): void {
  // trigger event
  this.selectedStyle = style;
  this.styleChange.emit(style);
}

Handle the style change event in the parent HTML.

app.component.html

<app-header #child (styleChange)="onStyleChange($event)">
</app-header>

Handle the style change event in your parent typescript, and set a property that is available to your parent's HTML.

app.component.ts

style: string;

onStyleChange(style: string): void {
  this.style = style;
}

Whatever style is emitted from the child component is now available to the parent.


问:
Unique Ways To Give Change- Not Outputting Expected Values
I'm trying to create a program that outputs all the possible unique ways to make change for a given input using ONLY recursion and constant memory(so no loops).

For an amount of 25 cents it should print out all possible combinations in the following example format:

```<code>0*25+0*10+1*5+20*1
0*25+0*10+2*5+15*1
etc..
</code>```

Where 0* is the number of quarters(25) used as an example

The problem with my program is that it only prints out:

```<code>0=0*25+0*10+0*5+25*1+
</code>```

and not the rest of the combinations. I suspect this is due to me messing up the printCombinations and getLargerCombinations methods (which are basically recursive methods that simulate a for loop), but I can't figure out what the problem is.

Here is the whole code:

```<code>public class HW {

    static int[] coins = {25,10,5,1};
    static int[] counts = new int[coins.length];

    static void getCombinations(int[] counts, int startIndex, int totalAmount) {
        if(startIndex>= coins.length) {
            System.out.print(""+totalAmount+"=");
            printCombinations(0);
            return;
        }

        if(startIndex == coins.length - 1) {

            if(totalAmount%coins[startIndex]==0) //good combo
            {
                //setting count of coins at start index
                counts[startIndex] = totalAmount/coins[startIndex];
                //move on to recursive calls
                getCombinations(counts, startIndex + 1, 0);
            }
        }

        else //still need to choose 0-N larger coins
        {
            getLargerCoins(0, totalAmount, startIndex);

        }

    }

    //Prints out all the possible combinations of change
    static void printCombinations(int i) {
        if(i >= coins.length) {
            System.out.print("\n");
            return;
        }
        System.out.print("" + counts[i] + "*" + coins[i] + "+");
        printCombinations(++i);
    }

    static void getLargerCoins(int j, int totalAmount, int startIndex) {
        if(j >= totalAmount/coins[startIndex]) {
            return;
        }
        //for every cycle in the loop, we choose an arbitray # of larger coins and proceed next
        counts[startIndex] = j;
        getCombinations(counts, startIndex+1, totalAmount-coins[startIndex]*j);
        j++;
    }

    public static void main(String[] args) {
        getCombinations(counts, 0, 25);
    }

}
</code>```

****EDIT:*****

Under the getLargerCoins method I just iterated j++ but forgot to call the getLargerCoins method to continue the recursion. Fixed the line by writing:

```<code>getLargerCoins(++j, totalAmount, startIndex);
</code>```

Output when running the program:

```<code>0=0*25+0*10+0*5+25*1+
0=0*25+0*10+1*5+20*1+
0=0*25+0*10+2*5+15*1+
0=0*25+0*10+3*5+10*1+
0=0*25+0*10+4*5+5*1+
0=0*25+1*10+0*5+15*1+
0=0*25+1*10+1*5+10*1+
0=0*25+1*10+2*5+5*1+
</code>```

However, it is still not outputting all the possible combinations

答:
What makes you think recursion consumes less memory than loops?

ONLY recursion and constant memory(so no loops).

For your problem, I think iterative is simpler and faster.

```<code>public class MyClass {
  public static void main(String args[]) {

    int[] coins = {25,10,5,1};
    int[] counts = {0,0,0,0};

    long recStart = System.currentTimeMillis();
    recursive(25,0,coins,counts);
    long recEnd = System.currentTimeMillis();
    System.out.println("recursive millis: "+( recEnd- recStart));

    long iterativeStart = System.currentTimeMillis();
    iterative(25);
    long iterativeEnd = System.currentTimeMillis();
    System.out.println("iterative millis: "+( iterativeEnd- iterativeStart));

}

public static void recursive(int restValue, int level, int[] coins, int[] counts){
    if(restValue==0){
       System.out.println(counts[0]+"*25+"+counts[1]+"*10+"+counts[2]+"*5+"+counts[3]+"*1");
    }else if(restValue>0 && level<4){
        for(int i = 0; i<= restValue/coins[level]; i++ ){
             int rest= restValue - ( i*coins[level] );
             counts[level]=i;
             recursive(rest,level+1,coins,counts);
        }
    }
}

public static void iterative(int desiredValue){
    int q1=25;
    int q2=10;
    int q3=5;

    for(int i1 = 0; i1<= desiredValue/q1; i1++ ){
        int rest1= desiredValue - ( i1*q1 );

        for(int i2 = 0; i2<= rest1/q2; i2++ ){
            int rest2= rest1 - ( i2*q2 );
            for(int i3 = 0; i3<= rest2/q3; i3++ ){
                int rest3= rest2 - ( i3*q3 );
                System.out.println(i1+"*25+"+i2+"*10+"+i3+"*5+"+rest3+"*1");
            }
        }
    }
}
</code>```

}

Body:
I'm trying to create a program that outputs all the possible unique ways to make change for a given input using ONLY recursion and constant memory(so no loops).

For an amount of 25 cents it should print out all possible combinations in the following example format:

0*25+0*10+1*5+20*1
0*25+0*10+2*5+15*1
etc..

Where 0* is the number of quarters(25) used as an example

The problem with my program is that it only prints out:

0=0*25+0*10+0*5+25*1+

and not the rest of the combinations. I suspect this is due to me messing up the printCombinations and getLargerCombinations methods (which are basically recursive methods that simulate a for loop), but I can't figure out what the problem is.

Here is the whole code:

public class HW {

    static int[] coins = {25,10,5,1};
    static int[] counts = new int[coins.length];

    static void getCombinations(int[] counts, int startIndex, int totalAmount) {
        if(startIndex>= coins.length) {
            System.out.print(""+totalAmount+"=");
            printCombinations(0);
            return;
        }

        if(startIndex == coins.length - 1) {

            if(totalAmount%coins[startIndex]==0) //good combo
            {
                //setting count of coins at start index
                counts[startIndex] = totalAmount/coins[startIndex];
                //move on to recursive calls
                getCombinations(counts, startIndex + 1, 0);
            }
        }

        else //still need to choose 0-N larger coins
        {
            getLargerCoins(0, totalAmount, startIndex);

        }

    }

    //Prints out all the possible combinations of change
    static void printCombinations(int i) {
        if(i >= coins.length) {
            System.out.print("\n");
            return;
        }
        System.out.print("" + counts[i] + "*" + coins[i] + "+");
        printCombinations(++i);
    }

    static void getLargerCoins(int j, int totalAmount, int startIndex) {
        if(j >= totalAmount/coins[startIndex]) {
            return;
        }
        //for every cycle in the loop, we choose an arbitray # of larger coins and proceed next
        counts[startIndex] = j;
        getCombinations(counts, startIndex+1, totalAmount-coins[startIndex]*j);
        j++;
    }

    public static void main(String[] args) {
        getCombinations(counts, 0, 25);
    }

}

****EDIT:*****

Under the getLargerCoins method I just iterated j++ but forgot to call the getLargerCoins method to continue the recursion. Fixed the line by writing:

getLargerCoins(++j, totalAmount, startIndex);

Output when running the program:

0=0*25+0*10+0*5+25*1+
0=0*25+0*10+1*5+20*1+
0=0*25+0*10+2*5+15*1+
0=0*25+0*10+3*5+10*1+
0=0*25+0*10+4*5+5*1+
0=0*25+1*10+0*5+15*1+
0=0*25+1*10+1*5+10*1+
0=0*25+1*10+2*5+5*1+

However, it is still not outputting all the possible combinations

Body:
What makes you think recursion consumes less memory than loops?

ONLY recursion and constant memory(so no loops).

For your problem, I think iterative is simpler and faster.

public class MyClass {
  public static void main(String args[]) {

    int[] coins = {25,10,5,1};
    int[] counts = {0,0,0,0};

    long recStart = System.currentTimeMillis();
    recursive(25,0,coins,counts);
    long recEnd = System.currentTimeMillis();
    System.out.println("recursive millis: "+( recEnd- recStart));

    long iterativeStart = System.currentTimeMillis();
    iterative(25);
    long iterativeEnd = System.currentTimeMillis();
    System.out.println("iterative millis: "+( iterativeEnd- iterativeStart));

}

public static void recursive(int restValue, int level, int[] coins, int[] counts){
    if(restValue==0){
       System.out.println(counts[0]+"*25+"+counts[1]+"*10+"+counts[2]+"*5+"+counts[3]+"*1");
    }else if(restValue>0 && level<4){
        for(int i = 0; i<= restValue/coins[level]; i++ ){
             int rest= restValue - ( i*coins[level] );
             counts[level]=i;
             recursive(rest,level+1,coins,counts);
        }
    }
}

public static void iterative(int desiredValue){
    int q1=25;
    int q2=10;
    int q3=5;

    for(int i1 = 0; i1<= desiredValue/q1; i1++ ){
        int rest1= desiredValue - ( i1*q1 );

        for(int i2 = 0; i2<= rest1/q2; i2++ ){
            int rest2= rest1 - ( i2*q2 );
            for(int i3 = 0; i3<= rest2/q3; i3++ ){
                int rest3= rest2 - ( i3*q3 );
                System.out.println(i1+"*25+"+i2+"*10+"+i3+"*5+"+rest3+"*1");
            }
        }
    }
}

}


问:
Using XSL to move from one node to another
So I want to convert the following using XSL

```<code><doc>
    <data id="priority" level="2" include="true">
        <name>Priority</name>
    </data>
    <data id="cost" level="1" leveltype="number">
        <name>Cost</name>
    </data>
    <data id="date" level="3" include="true">
        <name>Date</name>
    </data>
</doc>
</code>```

To this

```<code><doc>
    <data id="priority">
        <name>Priority</name>
    </data>
    <data id="cost">
        <name>Cost</name>
    </data>
    <data id="date">
        <name>Date</name>
    </data>

    <!-- ordering matters, though if necessary I can reorder this manually via the DOM instead of XSL -->
    <levels>
        <level id="cost" include="false" type="number"/>
        <level id="priority" include="true"/>
        <level id="date" include="true"/>
    </level>
</doc>
</code>```

Basically I want to take the level attributes and make them their own thing. A huge bonus would be if there were some way to remove the level number and use the order of the node instead to represent that.

答:
Here's the solution:

```<code><xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:strip-space elements="*"/>
  <xsl:output indent="yes"/>

  <!-- attribute suppression template -->
  <xsl:template match="@*" priority="2"/>

  <xsl:template match="/doc">
    <xsl:copy>
      <xsl:apply-templates select="*" mode="data"/>
      <levels>
        <xsl:apply-templates select="*" mode="levels">
          <xsl:sort select="@level" data-type="number"/>
        </xsl:apply-templates>
      </levels>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@*|node()" mode="data">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" mode="data"/>
    </xsl:copy></xsl:template><!-- identity template -->

  <xsl:template match="@*" mode="data"/><!-- suppress -->
  <xsl:template match="@id" mode="data" priority="2"><!-- keep -->
    <xsl:copy-of select="."/></xsl:template>

  <xsl:template match="@*|node()" mode="levels">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" mode="levels"/>
    </xsl:copy></xsl:template><!-- identity template -->

  <xsl:template match="data" mode="levels">
    <level>
      <xsl:apply-templates select="@*" mode="levels"/>
    </level></xsl:template>

  <xsl:template match="@level" mode="levels"/><!-- suppress -->
  <xsl:template match="@leveltype" mode="levels"><!-- rename -->
    <xsl:attribute name="type"><xsl:value-of select="."/>
    </xsl:attribute></xsl:template>

</xsl:stylesheet>
</code>```

I assume that <level id="cost" include="false" type="number"/> in your expected output is a copy/paste artefact as the attribute is missing from level[@id="cost"] in the input.

ContentLicense: CC BY-SA 3.0

Body:
So I want to convert the following using XSL

<doc>
    <data id="priority" level="2" include="true">
        <name>Priority</name>
    </data>
    <data id="cost" level="1" leveltype="number">
        <name>Cost</name>
    </data>
    <data id="date" level="3" include="true">
        <name>Date</name>
    </data>
</doc>

To this

<doc>
    <data id="priority">
        <name>Priority</name>
    </data>
    <data id="cost">
        <name>Cost</name>
    </data>
    <data id="date">
        <name>Date</name>
    </data>

    <levels>
        <level id="cost" include="false" type="number"/>
        <level id="priority" include="true"/>
        <level id="date" include="true"/>
    </level>
</doc>

Basically I want to take the level attributes and make them their own thing. A huge bonus would be if there were some way to remove the level number and use the order of the node instead to represent that.

Body:
Here's the solution:

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:strip-space elements="*"/>
  <xsl:output indent="yes"/>

  <!-- attribute suppression template -->
  <xsl:template match="@*" priority="2"/>

  <xsl:template match="/doc">
    <xsl:copy>
      <xsl:apply-templates select="*" mode="data"/>
      <levels>
        <xsl:apply-templates select="*" mode="levels">
          <xsl:sort select="@level" data-type="number"/>
        </xsl:apply-templates>
      </levels>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@*|node()" mode="data">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" mode="data"/>
    </xsl:copy></xsl:template><!-- identity template -->

  <xsl:template match="@*" mode="data"/><!-- suppress -->
  <xsl:template match="@id" mode="data" priority="2"><!-- keep -->
    <xsl:copy-of select="."/></xsl:template>

  <xsl:template match="@*|node()" mode="levels">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" mode="levels"/>
    </xsl:copy></xsl:template><!-- identity template -->

  <xsl:template match="data" mode="levels">
    <level>
      <xsl:apply-templates select="@*" mode="levels"/>
    </level></xsl:template>

  <xsl:template match="@level" mode="levels"/><!-- suppress -->
  <xsl:template match="@leveltype" mode="levels"><!-- rename -->
    <xsl:attribute name="type"><xsl:value-of select="."/>
    </xsl:attribute></xsl:template>

</xsl:stylesheet>

I assume that <level id="cost" include="false" type="number"/> in your expected output is a copy/paste artefact as the attribute is missing from level[@id="cost"] in the input.


问:
Error: timed out waiting for the condition during long helm tests
How can I force helm to wait for the end of the test suite?</p>

```<code> $ helm test $RELEASE --namespace $NAMESPACE
 NAME: myproject-test
 LAST DEPLOYED: Fri Feb 14 10:43:04 2020
 NAMESPACE: myproject-test-vjuh-init-helm
 STATUS: deployed
 REVISION: 1
 TEST SUITE:     myproject-test-django-test
 Last Started:   Fri Feb 14 10:45:53 2020
 Last Completed: Fri Feb 14 10:50:54 2020
 Phase:          Failed
 NOTES:
 Deployed
 Error: timed out waiting for the condition
 ERROR: Job failed: exit code 1
</code>```

答:
Add --timeout 30m or longer to your helm command:

```<code>helm test $RELEASE --namespace $NAMESPACE --timeout 30m
</code>```

As stated in the manual helm test --help:

```<code>--timeout duration   time to wait for any individual Kubernetes operation (like Jobs for hooks) (default 5m0s)
</code>```

Body:
How can I force helm to wait for the end of the test suite?

 $ helm test $RELEASE --namespace $NAMESPACE
 NAME: myproject-test
 LAST DEPLOYED: Fri Feb 14 10:43:04 2020
 NAMESPACE: myproject-test-vjuh-init-helm
 STATUS: deployed
 REVISION: 1
 TEST SUITE:     myproject-test-django-test
 Last Started:   Fri Feb 14 10:45:53 2020
 Last Completed: Fri Feb 14 10:50:54 2020
 Phase:          Failed
 NOTES:
 Deployed
 Error: timed out waiting for the condition
 ERROR: Job failed: exit code 1

Body:
Add --timeout 30m or longer to your helm command:

helm test $RELEASE --namespace $NAMESPACE --timeout 30m

As stated in the manual helm test --help:

--timeout duration   time to wait for any individual Kubernetes operation (like Jobs for hooks) (default 5m0s)


问:
Bazel - How to Read a String from An Environment File?
I have several k8s_object rules in my project and I supply each of them with the same cluster name like this:

```<code>k8s_object(
  name = "k8s_service",
  kind = "service",
  cluster = "gke_cents-ideas_europe-west3-b_cents-ideas",
  template = ":gateway.service.yaml",
)
</code>```

So whenever I want to change the cluster name, I have to change it in many different places.

Goal

I would prefer to set the cluster name in a .env file like this:

```<code>KUBERNETES_CLUSTER=my-cluster-name
</code>```

and let Bazel automatically pick up this value.

答:
https://docs.bazel.build/versions/2.0.0/skylark/tutorial-sharing-variables.html

Create a .bzl file in which you can declare a variable. Import this bzl file in all BUILD files referencing the variable.

Body:
I have several k8s_object rules in my project and I supply each of them with the same cluster name like this:

k8s_object(
  name = "k8s_service",
  kind = "service",
  cluster = "gke_cents-ideas_europe-west3-b_cents-ideas",
  template = ":gateway.service.yaml",
)

So whenever I want to change the cluster name, I have to change it in many different places.

Goal

I would prefer to set the cluster name in a .env file like this:

KUBERNETES_CLUSTER=my-cluster-name

and let Bazel automatically pick up this value.


问:
nvim-typescript wrongly complains about non-existent type
I'm trying to use neovim with the following minimal configuration:

```<code>call plug#begin()

Plug 'mhartington/nvim-typescript', {'do': './install.sh'}
Plug 'leafgarland/typescript-vim'

Plug 'HerringtonDarkholme/yats.vim'
Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }
Plug 'Shougo/denite.nvim'

call plug#end()
</code>```

In a nodejs project, I installed pg and @types/pg:

```<code>npm i pg; npm i -D @types/pg;
</code>```

Then in a .ts file, I'm importing from pg:

```<code>import * as pg from 'pg';
</code>```

yet I get the following error from this line:

```<code>const queryLogger = (queryRes: QueryResult<object>): string => ...
> 2304: Cannot find name 'QueryResult'.
</code>```

but if I force an error as such, the type is clearly known as it references QueryResult<T>:

```<code>const { Pool } = pg;
const pool = new Pool();

pool.query(sql, params) as string;
> 2352: Conversion of type 'Promise<QueryResult<any>>' ...
</code>```

even more strangely, building and running the code throws no errors - everything seems to work as expected, regardless of the error.

What is going on? Is there anything further I can do to debug the issue?

nvim-typescript issue

答: Horribly simple answer - the type was pg.QueryResult<T>.

Body:
I'm trying to use neovim with the following minimal configuration:

call plug#begin()

Plug 'mhartington/nvim-typescript', {'do': './install.sh'}
Plug 'leafgarland/typescript-vim'

Plug 'HerringtonDarkholme/yats.vim'
Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }
Plug 'Shougo/denite.nvim'

call plug#end()

In a nodejs project, I installed pg and @types/pg:

npm i pg; npm i -D @types/pg;

Then in a .ts file, I'm importing from pg:

import * as pg from 'pg';

yet I get the following error from this line:

const queryLogger = (queryRes: QueryResult<object>): string => ...
> 2304: Cannot find name 'QueryResult'.

but if I force an error as such, the type is clearly known as it references QueryResult<T>:

const { Pool } = pg;
const pool = new Pool();

pool.query(sql, params) as string;
> 2352: Conversion of type 'Promise<QueryResult<any>>' ...

even more strangely, building and running the code throws no errors - everything seems to work as expected, regardless of the error.

What is going on? Is there anything further I can do to debug the issue?

nvim-typescript issue


问:
How to include class in symfony 5?
I have a php file with Paysafecard class. File is called Paysafecard.php. I'd like to include it in my controller. How can I do it?</p>

答:
If you are using Symfony surely you are using the composer autoload.

Go to the root directory path of your project and search the composer.json file.

Within it you find a directive like this :

```<code> "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },

</code>```

This sentence indicates the mapping between the name and the directory.

Now look at the actual file path, for example /src/lib/Paymenterio.php

Go to the controller where you want to use the class replace the path with the autoload alias and remove the extension.

```<code>use App\lib\Paymenterio;
</code>```

Title: How to include class in symfony 5?

Body:
If you are using Symfony surely you are using the composer autoload.

Go to the root directory path of your project and search the composer.json file.

Within it you find a directive like this :

 "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },

This sentence indicates the mapping between the name and the directory.

Now look at the actual file path, for example /src/lib/Paymenterio.php

Go to the controller where you want to use the class replace the path with the autoload alias and remove the extension.

use App\lib\Paymenterio;


问:
requirement failed: Wrong or missing inputCols annotators in johnsnowlabs.nlp
I'm using com.johnsnowlabs.nlp-2.2.2 with spark-2.4.4 to process some articles. In those articles, there are some very long words I'm not interested in and which slows down the POS tagging a lot.
I would to like to exclude them after the tokenization and before the POSTagging.

I tried to write the smaller code to reproduce my issues

import sc.implicits._
val documenter = new DocumentAssembler().setInputCol("text").setOutputCol("document").setIdCol("id")
val tokenizer = new Tokenizer().setInputCols(Array("document")).setOutputCol("token")
val normalizer = new Normalizer().setInputCols("token").setOutputCol("normalized").setLowercase(true)

val df = Seq("This is a very useless/ugly sentence").toDF("text")

val document = documenter.transform(df.withColumn("id", monotonically_increasing_id()))
val token = tokenizer.fit(document).transform(document)

val token_filtered = token
  .drop("token")
  .join(token
    .select(col("id"), col("token"))
    .withColumn("tmp", explode(col("token")))
    .groupBy("id")
    .agg(collect_list(col("tmp")).as("token")),
    Seq("id"))
token_filtered.select($"token").show(false)
val normal = normalizer.fit(token_filtered).transform(token_filtered)
```

<p>I have this error when I transform <code>token_filtered</code></p>

```+--------------------+---+--------------------+--------------------+--------------------+
|                text| id|            document|            sentence|               token|
+--------------------+---+--------------------+--------------------+--------------------+
|This is a very us...|  0|[[document, 0, 35...|[[document, 0, 35...|[[token, 0, 3, Th...|
+--------------------+---+--------------------+--------------------+--------------------+

Exception in thread "main" java.lang.IllegalArgumentException:
requirement failed: Wrong or missing inputCols annotators in NORMALIZER_4bde2f08742a.
Received inputCols: token.
Make sure such annotators exist in your pipeline, with the right output
names and that they have following annotator types: token
```

It works fine if I directly fit and transform token in normalizer
It seems that during the explode/groupBy/collect_list, some information is lost, but the schema and data looks the same.

Any idea ?

答:
To update the answer given by @ticapix which is correct, however, in the new release there are two features added to SentenceDetector and Tokenizer which are minLenght and maxLength:

https://github.com/JohnSnowLabs/spark-nlp/pull/712

https://github.com/JohnSnowLabs/spark-nlp/pull/711

You can simply filter out the tokens you don't wish to give through the pipeline:

val tokenizer = new Tokenizer()
      .setInputCols("document")
      .setOutputCol("token")
      .setMinLength(4)
      .setMaxLength(10)
```

References:

https://github.com/JohnSnowLabs/spark-nlp

https://github.com/JohnSnowLabs/spark-nlp-models

https://github.com/JohnSnowLabs/spark-nlp-workshop

Body:
I'm using com.johnsnowlabs.nlp-2.2.2 with spark-2.4.4 to process some articles. In those articles, there are some very long words I'm not interested in and which slows down the POS tagging a lot.
I would to like to exclude them after the tokenization and before the POSTagging.

I tried to write the smaller code to reproduce my issues

import sc.implicits._
val documenter = new DocumentAssembler().setInputCol("text").setOutputCol("document").setIdCol("id")
val tokenizer = new Tokenizer().setInputCols(Array("document")).setOutputCol("token")
val normalizer = new Normalizer().setInputCols("token").setOutputCol("normalized").setLowercase(true)

val df = Seq("This is a very useless/ugly sentence").toDF("text")

val document = documenter.transform(df.withColumn("id", monotonically_increasing_id()))
val token = tokenizer.fit(document).transform(document)

val token_filtered = token
  .drop("token")
  .join(token
    .select(col("id"), col("token"))
    .withColumn("tmp", explode(col("token")))
    .groupBy("id")
    .agg(collect_list(col("tmp")).as("token")),
    Seq("id"))
token_filtered.select($"token").show(false)
val normal = normalizer.fit(token_filtered).transform(token_filtered)

I have this error when I transform token_filtered

+--------------------+---+--------------------+--------------------+--------------------+
|                text| id|            document|            sentence|               token|
+--------------------+---+--------------------+--------------------+--------------------+
|This is a very us...|  0|[[document, 0, 35...|[[document, 0, 35...|[[token, 0, 3, Th...|
+--------------------+---+--------------------+--------------------+--------------------+

Exception in thread "main" java.lang.IllegalArgumentException:
requirement failed: Wrong or missing inputCols annotators in NORMALIZER_4bde2f08742a.
Received inputCols: token.
Make sure such annotators exist in your pipeline, with the right output
names and that they have following annotator types: token

It works fine if I directly fit and transform token in normalizer
It seems that during the explode/groupBy/collect_list, some information is lost, but the schema and data looks the same.

Any idea ?

Body:
To update the answer given by @ticapix which is correct, however, in the new release there are two features added to SentenceDetector and Tokenizer which are minLenght and maxLength:

https://github.com/JohnSnowLabs/spark-nlp/pull/712

https://github.com/JohnSnowLabs/spark-nlp/pull/711

You can simply filter out the tokens you don't wish to give through the pipeline:

val tokenizer = new Tokenizer()
      .setInputCols("document")
      .setOutputCol("token")
      .setMinLength(4)
      .setMaxLength(10)

References:

https://github.com/JohnSnowLabs/spark-nlp

https://github.com/JohnSnowLabs/spark-nlp-models

https://github.com/JohnSnowLabs/spark-nlp-workshop


问:
Test if an Excel cell is empty
I created below SAPGUI script for creation of PO's.

The script is working fine most of the times. However I would like to improve it a bit more.

First question:

For instance if the script stops in the middle of the process were you have a list (Excel input sheet) of 50 materials for which you need to create same amount of PO's. If the script stops for example at material number 30 I can't just start the script again because it will start from the beginning again but PO's for those materials are already created.

Now as you can see in the code the script puts in comment "Finished" in column 6 in each row after PO is created: objSheet.Cells(i, 6) = "Finished"

It also fetches the created PO number from SAP and puts it in the column next to it (column 7): objSheet.Cells(i, 7).Value = Mid(session.findById("wnd[0]/sbar").Text, 38)

I would like to add an "if code" saying that if there is PO number in column 7 that is skips those rows from the excel input sheet and instead go to the next row for which cell in column 7 is empty.

Second question:

```<code>session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/tbar[0]/btn[11]").press
</code>```

Above is Enter recorded 3 times followed by the Save.
I would like to add to the script if this save is not successful that it presses save one more time. Sometimes the script just stops at this step. However if Save is pressed manually one more time the PO is saved and created. I have no clue why the script stops at this step sometimes but for certain materials it does. Again everything is filled in by the script  and all that is left is to press save which is what I do if this problem occurs. So I save the PO manually and put PO number into Excel input sheet and since we solved 1st problem I can just restart the script again and it will continue again from first empty cell in column 7 (if isEmpty(objSheet.cells(i,7)) then).

So I would like the script to press Save only when the first save is unsuccessful. If I would to add session.findById("wnd[0]/tbar[0]/btn[11]").press two times after one another the script will be stopped if the first save is successful. Then for the second save the SAP will say there is nothing to be saved, hence the script will stop working due to this unsuspected event/message. So if possible I would like the script to only press save one more time if the first save is unsuccessful. Basically a code saying iferror after first save then repeat the save again.

```<code>    Set SapGuiAuto  = GetObject("SAPGUI")
    Set application = SapGuiAuto.GetScriptingEngine
    End If
    If Not IsObject(connection) Then
    Set connection = application.Children(0)
    End If
    If Not IsObject(session) Then
    Set session    = connection.Children(0)
    End If
    If IsObject(WScript) Then
    WScript.ConnectObject session,     "on"
    WScript.ConnectObject application, "on"
    End If
    session.findById("wnd[0]").maximize

    REM ADDED BY EXCEL *************************************

    Dim objExcel
    Dim objSheet, intRow, i
    Set objExcel = GetObject(,"Excel.Application")
    Set objSheet = objExcel.ActiveWorkbook.ActiveSheet

    For i = 2 to objSheet.UsedRange.Rows.Count
    COL2 = Trim(CStr(objSheet.Cells(i, 2).Value)) 'Column2 Agreement number
    COL3 = Trim(CStr(objSheet.Cells(i, 3).Value)) 'Column3 Agreement Line Item
    COL4 = Trim(CStr(objSheet.Cells(i, 4).Value)) 'Column4 PO Quantity
    COL5 = Trim(CStr(objSheet.Cells(i, 5).Value)) 'Column5 Delivery date

    REM ADDED BY EXCEL *************************************

    session.findById("wnd[0]/tbar[0]/okcd").text = "/nme21n"
    session.findById("wnd[0]").sendVKey 0

session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0013/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/ctxtMEPO1211-KONNR[29,0]").text = COL2
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0013/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-KTPNR[30,0]").text = COL3
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0013/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-KTPNR[30,0]").setFocus
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0013/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-KTPNR[30,0]").caretPosition = 0
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0020/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-MENGE[6,0]").text = COL4
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0020/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/ctxtMEPO1211-EEIND[9,0]").text = COL5
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0020/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/ctxtMEPO1211-EEIND[9,0]").setFocus
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0020/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/ctxtMEPO1211-EEIND[9,0]").caretPosition = 0
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0020/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-MENGE[6,0]").text = COL4
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/tbar[0]/btn[11]").press

      objSheet.Cells(i, 6) = "Finished"

      objSheet.Cells(i, 7).Value = Mid(session.findById("wnd[0]/sbar").Text, 38)

      REM FINALIZATION CONTROL CHECK ************************

      aux=col2 & " " & col3 & " " & col4 & " " & col5
      CreateObject("WScript.Shell").run("cmd /c @echo %date% %time% " & aux & " >>
      C:\SCRIPT\PlOrCreationLog.txt")
      next

      msgbox "Process Completed Forza Juve! :)"

      REM FINALIZATION CONTROL CHECK ************************
</code>```

答:
You may test if the cell in row i and in column 7 is empty by using If IsEmpty(objSheet.cells(i,7)) Then.

for example:

```<code>...
For i = 2 to objSheet.UsedRange.Rows.Count
 if isEmpty(objSheet.cells(i,7)) then
    COL2 = Trim(CStr(objSheet.Cells(i, 2).Value)) 'Column2 Agreement number
    ...
    CreateObject("WScript.Shell").run("cmd /c @echo %date% %time% " & aux & " >>
  C:\SCRIPT\PlOrCreationLog.txt")
 end if
next
...
</code>```

Regards, ScriptMan

Title: Test if an Excel cell is empty

Body:
I created below SAPGUI script for creation of PO's.

The script is working fine most of the times. However I would like to improve it a bit more.

First question:

For instance if the script stops in the middle of the process were you have a list (Excel input sheet) of 50 materials for which you need to create same amount of PO's. If the script stops for example at material number 30 I can't just start the script again because it will start from the beginning again but PO's for those materials are already created.

Now as you can see in the code the script puts in comment "Finished" in column 6 in each row after PO is created: objSheet.Cells(i, 6) = "Finished"

It also fetches the created PO number from SAP and puts it in the column next to it (column 7): objSheet.Cells(i, 7).Value = Mid(session.findById("wnd[0]/sbar").Text, 38)

I would like to add an "if code" saying that if there is PO number in column 7 that is skips those rows from the excel input sheet and instead go to the next row for which cell in column 7 is empty.

Second question:

session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/tbar[0]/btn[11]").press

Above is Enter recorded 3 times followed by the Save.
I would like to add to the script if this save is not successful that it presses save one more time. Sometimes the script just stops at this step. However if Save is pressed manually one more time the PO is saved and created. I have no clue why the script stops at this step sometimes but for certain materials it does. Again everything is filled in by the script  and all that is left is to press save which is what I do if this problem occurs. So I save the PO manually and put PO number into Excel input sheet and since we solved 1st problem I can just restart the script again and it will continue again from first empty cell in column 7 (if isEmpty(objSheet.cells(i,7)) then).

So I would like the script to press Save only when the first save is unsuccessful. If I would to add session.findById("wnd[0]/tbar[0]/btn[11]").press two times after one another the script will be stopped if the first save is successful. Then for the second save the SAP will say there is nothing to be saved, hence the script will stop working due to this unsuspected event/message. So if possible I would like the script to only press save one more time if the first save is unsuccessful. Basically a code saying iferror after first save then repeat the save again.

    Set SapGuiAuto  = GetObject("SAPGUI")
    Set application = SapGuiAuto.GetScriptingEngine
    End If
    If Not IsObject(connection) Then
    Set connection = application.Children(0)
    End If
    If Not IsObject(session) Then
    Set session    = connection.Children(0)
    End If
    If IsObject(WScript) Then
    WScript.ConnectObject session,     "on"
    WScript.ConnectObject application, "on"
    End If
    session.findById("wnd[0]").maximize

    REM ADDED BY EXCEL *************************************

    Dim objExcel
    Dim objSheet, intRow, i
    Set objExcel = GetObject(,"Excel.Application")
    Set objSheet = objExcel.ActiveWorkbook.ActiveSheet

    For i = 2 to objSheet.UsedRange.Rows.Count
    COL2 = Trim(CStr(objSheet.Cells(i, 2).Value)) 'Column2 Agreement number
    COL3 = Trim(CStr(objSheet.Cells(i, 3).Value)) 'Column3 Agreement Line Item
    COL4 = Trim(CStr(objSheet.Cells(i, 4).Value)) 'Column4 PO Quantity
    COL5 = Trim(CStr(objSheet.Cells(i, 5).Value)) 'Column5 Delivery date

    REM ADDED BY EXCEL *************************************

    session.findById("wnd[0]/tbar[0]/okcd").text = "/nme21n"
    session.findById("wnd[0]").sendVKey 0

session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0013/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/ctxtMEPO1211-KONNR[29,0]").text = COL2
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0013/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-KTPNR[30,0]").text = COL3
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0013/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-KTPNR[30,0]").setFocus
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0013/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-KTPNR[30,0]").caretPosition = 0
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0020/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-MENGE[6,0]").text = COL4
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0020/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/ctxtMEPO1211-EEIND[9,0]").text = COL5
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0020/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/ctxtMEPO1211-EEIND[9,0]").setFocus
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0020/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/ctxtMEPO1211-EEIND[9,0]").caretPosition = 0
session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0020/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-MENGE[6,0]").text = COL4
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/tbar[0]/btn[11]").press

      objSheet.Cells(i, 6) = "Finished"

      objSheet.Cells(i, 7).Value = Mid(session.findById("wnd[0]/sbar").Text, 38)

      REM FINALIZATION CONTROL CHECK ************************

      aux=col2 & " " & col3 & " " & col4 & " " & col5
      CreateObject("WScript.Shell").run("cmd /c @echo %date% %time% " & aux & " >>
      C:\SCRIPT\PlOrCreationLog.txt")
      next

      msgbox "Process Completed Forza Juve! :)"

      REM FINALIZATION CONTROL CHECK ************************

Body:
You may test if the cell in row i and in column 7 is empty by using If IsEmpty(objSheet.cells(i,7)) Then.

for example:

...
For i = 2 to objSheet.UsedRange.Rows.Count
 if isEmpty(objSheet.cells(i,7)) then
    COL2 = Trim(CStr(objSheet.Cells(i, 2).Value)) 'Column2 Agreement number
    ...
    CreateObject("WScript.Shell").run("cmd /c @echo %date% %time% " & aux & " >>
  C:\SCRIPT\PlOrCreationLog.txt")
 end if
next
...

Regards, ScriptMan


问:
Returns without a "return" command

C programming language, compiled with gcc, terminal bash in WSL

I have written a recursive function, to find the lowest number in an array, which works just fine.

```<code>/*01*/    int minimo(int array[], int n)
/*02*/    {
/*03*/      static int min = 0;
/*04*/
/*05*/      if (n == N)
/*06*/      {
/*07*/          return array[n-1];
/*08*/      }
/*09*/      else
/*10*/      {
/*11*/          min = minimo(array, n+1);
/*12*/          if(array[n]<min){
/*13*/              min = array[n];
/*14*/          }
/*15*/      }
/*16*/    }
</code>```

The only problem is that it shouldn't work, because it doesn't return "min" to the caller...

```<code>int main()
{
    //Var
    int array[N] = {10, 2, 5, 1, 7};
    printf("Min: %d\n", minimo(array, 0));
}
</code>```

My concern is actually a problem, but not on my machine onto which the function works just fine as it is;
it is a problem on my friends' laptops and IDEs, I tried copying to XCode on a friend's Macbook and it wouldn't work if the line "return min;" wasn't added at the end of the function.

Between line 15-16 I have to add return min;

```<code>/*15*/      }
            return min;
/*16*/    }
</code>```

My questions for you are the following:

How can  a function return a variable automatically?

Is it possible that it does return the only variable that I created (static int min)?

Or is it a "problem" related to the static attribute that the variable has?

Does it have anything to do with the nature of the function (recursive)?

This is my first post, please be kind if I'm breaking any forum rule.

答:
How can a function return a variable automatically?

It follows the protocol.  It knows that the return of the function should find the returned value at some location and an explicit return from that function will fill that location.  If you do not call return, some random value will be preserved at the given location.

Is it possible that it does return the only variable that I created (static int min)?

No, it is undefined what it returns.  It can be whatever.

Or is it a "problem" related to the static attribute that the variable has?

Again, what it returns is undefined.

Does it have anything to do with the nature of the function (recursive)?

Yes and no.  If the function is defined as external the returned value follows another protocol as in the case of static functions.

It can happen anything in the final code, the C language does not impose the way of implementing a function, be it recursive or not.  For example, in case the function is recursive and can be precomputed, only the final value can be replaced at the place of call.  This is also correct as time as the final result of the program is the expected result, conforming to the operational semantics that defines C in ISO9899.

I quote from the official document:

4   In the abstract machine, all expressions are evaluated as specified by the semantics. An
      actual implementation need not evaluate part of an expression if it can deduce that its
      value is not used and that no needed side effects are produced (including any caused by
       calling a function or accessing a volatile object).

It also can replace a call with the value of that call and this is correct.

So at all your questions, the answer is undefined behavior.

Title: Returns without a "return" command

Body:
C programming language, compiled with gcc, terminal bash in WSL

I have written a recursive function, to find the lowest number in an array, which works just fine.

/*01*/    int minimo(int array[], int n)
/*02*/    {
/*03*/      static int min = 0;
/*04*/
/*05*/      if (n == N)
/*06*/      {
/*07*/          return array[n-1];
/*08*/      }
/*09*/      else
/*10*/      {
/*11*/          min = minimo(array, n+1);
/*12*/          if(array[n]<min){
/*13*/              min = array[n];
/*14*/          }
/*15*/      }
/*16*/    }

The only problem is that it shouldn't work, because it doesn't return "min" to the caller...

int main()
{
    //Var
    int array[N] = {10, 2, 5, 1, 7};
    printf("Min: %d\n", minimo(array, 0));
}

My concern is actually a problem, but not on my machine onto which the function works just fine as it is;
it is a problem on my friends' laptops and IDEs, I tried copying to XCode on a friend's Macbook and it wouldn't work if the line "return min;" wasn't added at the end of the function.

Between line 15-16 I have to add return min;

/*15*/      }
            return min;
/*16*/    }

My questions for you are the following:

How can  a function return a variable automatically?

Is it possible that it does return the only variable that I created (static int min)?

Or is it a "problem" related to the static attribute that the variable has?

Does it have anything to do with the nature of the function (recursive)?

This is my first post, please be kind if I'm breaking any forum rule.


问:
making unequal array control
I have an array ,vehicle owners and tools are available, there is no stability in the array there are three car owners,vehicles they own show. in short; I have 3 car owners and I wanted to show on the page which of these three vehicles are ford, male, scania

code it gives me
enter image description here

i want to do
enter image description here

```<code><?php
$vehicles = array(

    array(
     "vehicleowner" =>("john"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

    array(
     "vehicleowner" =>("alex"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

     array(
     "vehicleowner" =>("Robert"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

 );

echo '<table border="1">
<thead>
<tr>
<td>vehicleowner</td>
<td>Ford</td>
<td>Scania</td>
<td>Man</td>
';

foreach($vehicles as $i => $value){
     // echo "```";
    // print_r($value);

    $ford = $value["vehicles"][$i]["id"]==1;

    if($ford){ $fordd = $value["vehicles"][$i]["brand"];}

    $scania = $value["vehicles"][$i]["id"]==2;
    if($scania){ $scaniaa = $value["vehicles"][$i]["brand"];}

    $man = $value["vehicles"][$i]["id"]==3;
    if($man){ $mann = $value["vehicles"][$i]["brand"];}

?>

 <?php echo $value["vehicleowner"]?>
 <?php echo isset($fordd) ? $fordd : '-';?>
 <?php echo isset($scaniaa) ? $scaniaa : '-';?>
 <?php echo isset($mann) ? $mann : '-';?>

<?php } ?>
```

答:
@SisError thank you so much

```<code>echo $cars[$column] ?? '-';
</code>```

quite successful
but

```<code><td><?php echo $cars["scania"];?></td>
</code>```

error

enter image description here

```<code>$store = [];
$unique = [];
foreach ($vehicles as $object) {
    foreach ($object['vehicles'] as $vehicle) {
        $unique[$vehicle['model']] = true;
        $store[$object['vehicleowner']][$vehicle['model']] = $vehicle['brand'];
    }
}
foreach ($store as $owner => $cars) {
    $owner;
    foreach ($unique as $column => $_) {
        $cars[$column] ?? '-';
    }

?>

<tr>
<td><?php echo $owner?></td>
<td><?php echo $cars["ford"];?></td>
<td><?php echo $cars["scania"];?></td>
<td><?php echo $cars["man"];?></td>
<tr>

<?php } ?>
</code>```

@misorude SisError thank you so much ,quite successful

Title: making unequal array control

Body:
I have an array ,vehicle owners and tools are available, there is no stability in the array there are three car owners,vehicles they own show. in short; I have 3 car owners and I wanted to show on the page which of these three vehicles are ford, male, scania

code it gives me
enter image description here

i want to do
enter image description here

<?php
$vehicles = array(

    array(
     "vehicleowner" =>("john"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

    array(
     "vehicleowner" =>("alex"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

     array(
     "vehicleowner" =>("Robert"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

 );

echo '

vehicleowner
Ford
Scania
Man
';

foreach($vehicles as $i => $value){
     // echo "
";
    // print_r($value);

    $ford = $value["vehicles"][$i]["id"]==1;

    if($ford){ $fordd = $value["vehicles"][$i]["brand"];}

    $scania = $value["vehicles"][$i]["id"]==2;
    if($scania){ $scaniaa = $value["vehicles"][$i]["brand"];}

    $man = $value["vehicles"][$i]["id"]==3;
    if($man){ $mann = $value["vehicles"][$i]["brand"];}

?>

 <?php echo $value["vehicleowner"]?>
 <?php echo isset($fordd) ? $fordd : '-';?>
 <?php echo isset($scaniaa) ? $scaniaa : '-';?>
 <?php echo isset($mann) ? $mann : '-';?>

<?php } ?>

Body:
@SisError thank you so much

echo $cars[$column] ?? '-';

quite successful
but

<td><?php echo $cars["scania"];?></td>

error

enter image description here

$store = [];
$unique = [];
foreach ($vehicles as $object) {
    foreach ($object['vehicles'] as $vehicle) {
        $unique[$vehicle['model']] = true;
        $store[$object['vehicleowner']][$vehicle['model']] = $vehicle['brand'];
    }
}
foreach ($store as $owner => $cars) {
    $owner;
    foreach ($unique as $column => $_) {
        $cars[$column] ?? '-';
    }

?>

<tr>
<td><?php echo $owner?></td>
<td><?php echo $cars["ford"];?></td>
<td><?php echo $cars["scania"];?></td>
<td><?php echo $cars["man"];?></td>
<tr>

<?php } ?>

@misorude SisError thank you so much ,quite successful


问:
Does not have http ok status error in angular with webapi
i tried to pass my form data from angular to webapi, my webapi works fine by using postman, while passing through angular i am getting below screenshot error for reference. Please see my code and suggest me any modifications.
I Searched in google for Solution, I added proxy.conf.json this also in angular. As of my knowledge i added all details correctly only, Plz suggest me if i done wrong in any place. Help me on this

My WebPAIConfig.cs code:

```<code>        public static void Register(HttpConfiguration config)
    {
        //EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
        //config.EnableCors();
        //var cors = new EnableCorsAttribute("*", "*", "*");
        //config.EnableCors(cors);
        config.EnableCors();
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }
</code>```

My WebAPI Cors Code in webConfig.cs:

```<code> <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
  </customHeaders>
</httpProtocol>
</code>```

```<code>My WebAPI: [Route("api/CLOInfo/SaveUpdateCLODetails/")]
    [AcceptVerbs("POST", "GET")]
    [HttpPost]
    public HttpResponseMessage Post([FromBody]CustomModel model)
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Succdess");
    } public class CustomModel
{
    public string Name { get; set; }
}
</code>```

My ANgular Service call:
I tried both http and httpclient services also.

```<code>CLODetailsSave(SaveCLODetails: CLOModels): Observable<Response> {
    let requestOptions: RequestOptionsArgs = {
        headers: new Headers({ 'content-type': 'application/json' })
      };

      return this._http.post(this.baseUrl + 'SaveUpdateCLODetails', SaveCLODetails, requestOptions);

    //return this._httpclient.post(this.baseUrl + "SaveUpdateCLODetails", SaveCLODetails);

    // return this._httpclient.post<void>(this.baseUrl + "SaveUpdateCLODetails", SaveCLODetails, {
    //     headers: new HttpHeaders({

    //         'Content-Type': 'application/json',
    //         'mode': 'no-cors'
    //     })
    //   });
}
</code>```

My Angular calling Method :

```<code>this._CLoAPiService.CLODetailsSave(this._CLODetails).subscribe(res => {
  console.log(res);
})
</code>```

答:
You need to enable CORS on your WebApi

config.EnableCors();
```

For more detailed explanation see this.

Body:
i tried to pass my form data from angular to webapi, my webapi works fine by using postman, while passing through angular i am getting below screenshot error for reference. Please see my code and suggest me any modifications.
I Searched in google for Solution, I added proxy.conf.json this also in angular. As of my knowledge i added all details correctly only, Plz suggest me if i done wrong in any place. Help me on this

My WebPAIConfig.cs code:

        public static void Register(HttpConfiguration config)
    {
        //EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
        //config.EnableCors();
        //var cors = new EnableCorsAttribute("*", "*", "*");
        //config.EnableCors(cors);
        config.EnableCors();
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }

My WebAPI Cors Code in webConfig.cs:

 <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
  </customHeaders>
</httpProtocol>

My WebAPI: [Route("api/CLOInfo/SaveUpdateCLODetails/")]
    [AcceptVerbs("POST", "GET")]
    [HttpPost]
    public HttpResponseMessage Post([FromBody]CustomModel model)
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Succdess");
    } public class CustomModel
{
    public string Name { get; set; }
}

My ANgular Service call:
I tried both http and httpclient services also.

CLODetailsSave(SaveCLODetails: CLOModels): Observable<Response> {
    let requestOptions: RequestOptionsArgs = {
        headers: new Headers({ 'content-type': 'application/json' })
      };

      return this._http.post(this.baseUrl + 'SaveUpdateCLODetails', SaveCLODetails, requestOptions);

    //return this._httpclient.post(this.baseUrl + "SaveUpdateCLODetails", SaveCLODetails);

    // return this._httpclient.post<void>(this.baseUrl + "SaveUpdateCLODetails", SaveCLODetails, {
    //     headers: new HttpHeaders({

    //         'Content-Type': 'application/json',
    //         'mode': 'no-cors'
    //     })
    //   });
}

My Angular calling Method :

this._CLoAPiService.CLODetailsSave(this._CLODetails).subscribe(res => {
  console.log(res);
})

Body:
You need to enable CORS on your WebApi

config.EnableCors();

For more detailed explanation see this.


问:
Overriding windows menu
I am in need of blocking windows menu: when I press the windows button in keyboard, I don't want any actions to be performed, how should I do programatically.</p>

答:
Its actually a registry hack. Please read the support page from MS. You can try adding the registry key through your program.

Or simply remove the key from the keyboard.

Edit: Took 5 secs to search for your answer in Google. It's less than the time taken for you to type the question.

OwnerDisplayName: Vinoth

Title: Overriding windows menu

LastEditorDisplayName: abatishchev

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Drew Noakes


问:
ActiveJob::DeserializationError in a after_create callback - Record Not Found
In a Rails 6 app, I have the following code.

```<code>class Reservation < ApplicationRecord
  after_create     :publish_creation

  def publish_creation
    Publishers::Reservations::CreateJob.perform_later(self)
  end
end

class Publishers::Reservations::CreateJob < ApplicationJob
  queue_as :default

  def perform(reservation)
    puts reservation.inspect #dummy code for testing
  end
end
</code>```

The majority of times I create a Reservation (the record is always created in the DB), I get the error below

2020-02-14T09:54:03.707Z pid=81787 tid=1xmj WARN:
  ActiveJob::DeserializationError: Error while trying to deserialize
  arguments: Couldn't find Reservation with 'id'= 35651cf7-35bc-4da0-bb0d-6285ac093d22

The first time Sidekiq retries to process the job, it always finds the Reservation and everything works fine.

Reservation id: "35651cf7-35bc-4da0-bb0d-6285ac093d22", analysis_id:
  "6b3b167b-1279-49c0-991a-b580c375fd0f", reservable_type: "User",
  reservable_id: "94f60c16-29d4-4372-983b-7544c393a7e6",
  reserved_between: 2020-02-10 08:00:00 UTC..2020-02-10 08:10:00 UTC,
  state: "scheduled", created_at: "2020-02-14 10:02:28", updated_at:
  "2020-02-14 10:02:28"

Am I missing anything here?
Is this something related to the fact I'm running in development mode and it should disappear once I move to production?

答:
You should use after_commit instead of after_create. This is because

after_create - Is called after Model.save on new objects that haven‘t been saved yet (no record exists). In the case of after_create, this will always be before the call to save (or create) returns. Rails wraps every save inside a transaction and the before/after create callbacks run inside that transaction.

after_commit - Is called after the database transaction is completed. With after_commit, your code doesn't run until after the outermost transaction was committed.

Body:
In a Rails 6 app, I have the following code.

class Reservation < ApplicationRecord
  after_create     :publish_creation

  def publish_creation
    Publishers::Reservations::CreateJob.perform_later(self)
  end
end

class Publishers::Reservations::CreateJob < ApplicationJob
  queue_as :default

  def perform(reservation)
    puts reservation.inspect #dummy code for testing
  end
end

The majority of times I create a Reservation (the record is always created in the DB), I get the error below

2020-02-14T09:54:03.707Z pid=81787 tid=1xmj WARN:
  ActiveJob::DeserializationError: Error while trying to deserialize
  arguments: Couldn't find Reservation with 'id'= 35651cf7-35bc-4da0-bb0d-6285ac093d22

The first time Sidekiq retries to process the job, it always finds the Reservation and everything works fine.

Reservation id: "35651cf7-35bc-4da0-bb0d-6285ac093d22", analysis_id:
  "6b3b167b-1279-49c0-991a-b580c375fd0f", reservable_type: "User",
  reservable_id: "94f60c16-29d4-4372-983b-7544c393a7e6",
  reserved_between: 2020-02-10 08:00:00 UTC..2020-02-10 08:10:00 UTC,
  state: "scheduled", created_at: "2020-02-14 10:02:28", updated_at:
  "2020-02-14 10:02:28"

Am I missing anything here?
Is this something related to the fact I'm running in development mode and it should disappear once I move to production?


问:
Dynamic ASSIGN of table row expression
In my ABAP report I have some structure:

```<code>data:
  begin of struct1,
    field1 type char10,
  end of struct1.
</code>```

I can access to it's field field1 directly:

```<code>data(val) = struct1-field1
</code>```

or dynamically with assign:

```<code>assign ('struct1-field1') to field-symbol(<val>).
</code>```

Also I have some internal table:

```<code>data: table1 like standard table of struct1 with default key.
append initial line to table1.
</code>```

I can access to column field1 of first row directly:

```<code>data(val) = table1[ 1 ]-field1.
</code>```

But I can not get access to field1 with dynamic assign:

```<code>assign ('table1[ 1 ]-field1') to field-symbol(<val>).
</code>```

After assignment sy-subrc equals "4".

Why?

答:
Sandra is absolutely right, if table expressions are not specified in help, then they are not allowed.

You can use ASSIGN COMPONENT statement for your dynamicity:

```<code>FIELD-SYMBOLS: <tab> TYPE INDEX TABLE.

ASSIGN ('table1') TO <tab>.
ASSIGN COMPONENT 'field1' OF STRUCTURE <tab>[ 1 ] TO FIELD-SYMBOL(<val>).
</code>```

However, such dynamics is only possible with index tables (standard + sorted) due to the nature of this version of row specification. If you try to pass hashed table into the field symbol, it will dump.

Title: Dynamic ASSIGN of table row expression

Body:
In my ABAP report I have some structure:

data:
  begin of struct1,
    field1 type char10,
  end of struct1.

I can access to it's field field1 directly:

data(val) = struct1-field1

or dynamically with assign:

assign ('struct1-field1') to field-symbol(<val>).

Also I have some internal table:

data: table1 like standard table of struct1 with default key.
append initial line to table1.

I can access to column field1 of first row directly:

data(val) = table1[ 1 ]-field1.

But I can not get access to field1 with dynamic assign:

assign ('table1[ 1 ]-field1') to field-symbol(<val>).

After assignment sy-subrc equals "4".

Why?

Body:
Sandra is absolutely right, if table expressions are not specified in help, then they are not allowed.

You can use ASSIGN COMPONENT statement for your dynamicity:

FIELD-SYMBOLS: <tab> TYPE INDEX TABLE.

ASSIGN ('table1') TO <tab>.
ASSIGN COMPONENT 'field1' OF STRUCTURE <tab>[ 1 ] TO FIELD-SYMBOL(<val>).

However, such dynamics is only possible with index tables (standard + sorted) due to the nature of this version of row specification. If you try to pass hashed table into the field symbol, it will dump.