问:
How do I create the expected output in this Arithmetic Operators problem on HackerRank?
I am a beginner in Python 3 and I am trying to practice more of my Python 3 skills by trying to solve  HackerRank problems but I am a little stuck on this one problem. I have already written some code but I am having trouble with getting the expected output. Can someone please help?

The instructions:

Read two integers from STDIN and print three lines where:

The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.

Output Format

Print the three lines as explained above.

Sample Input

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

Sample Output

```<code>5
1
6
</code>```

Here is my code, I created three functions to add, subtract, and multiply the inputted numbers but I need to know how to write some code that will iterate through a list and make the outputted numbers move vertically:

```<code>def addition(a, b):
    print (a + b)

#Main
a = int(input())
b = int(input())
addition(a, b)

def subtraction (a, b):
    print (a - b)

#Main
a = int(input())
b = int(input())
subtraction(a, b)

def multiplication(a, b):
    print (a * b)

#Main
a = int(input())
b = int(input())
multiplication(a, b)
</code>```

答:
You should not read the input multiple times. Read only once and then perform the operations</p>

```<code>def addition(a, b):
    print (a + b)

#Main
a = int(input())
b = int(input())
addition(a, b)

def subtraction (a, b):
    print (a - b)

subtraction(a, b)

def multiplication(a, b):
    print (a * b)

multiplication(a, b)
</code>```

Body:
I am a beginner in Python 3 and I am trying to practice more of my Python 3 skills by trying to solve  HackerRank problems but I am a little stuck on this one problem. I have already written some code but I am having trouble with getting the expected output. Can someone please help?

The instructions:

Read two integers from STDIN and print three lines where:

The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.

Output Format

Print the three lines as explained above.

Sample Input

3
2

Sample Output

5
1
6

Here is my code, I created three functions to add, subtract, and multiply the inputted numbers but I need to know how to write some code that will iterate through a list and make the outputted numbers move vertically:

def addition(a, b):
    print (a + b)

#Main
a = int(input())
b = int(input())
addition(a, b)

def subtraction (a, b):
    print (a - b)

#Main
a = int(input())
b = int(input())
subtraction(a, b)

def multiplication(a, b):
    print (a * b)

#Main
a = int(input())
b = int(input())
multiplication(a, b)

Body:
You should not read the input multiple times. Read only once and then perform the operations

def addition(a, b):
    print (a + b)

#Main
a = int(input())
b = int(input())
addition(a, b)

def subtraction (a, b):
    print (a - b)

subtraction(a, b)

def multiplication(a, b):
    print (a * b)

multiplication(a, b)


来源: stackexchange

问:
Python compare part of string to list
I have multiple strings that looks like this:

```<code>“BPBA-SG790-NGTP-W-AU-BUN-3Y”
</code>```

I want to compare the string to my list and if part of the string is in the list, I want to get only the part that is found on the list as a new variable.

This is my code:

```<code>    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> ['770', '790', '1470', '1490']
</code>```

For example this is what I want to get:

```<code>    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> 790
</code>```

Any idea how to do this?

答:
Like this, you can use a list comprehension:

```<code>mylist = ["770", "790", "1470", "1490"]
sq = "BPBA-SG790-NGTP-W-AU-BUN-3Y"

matching = [m for m in mylist if m in sq]

print(matching)
</code>```

Output:

```<code>['790']
</code>```

ContentLicense: CC BY-SA 4.0

Title: Python compare part of string to list

Body:
I have multiple strings that looks like this:

“BPBA-SG790-NGTP-W-AU-BUN-3Y”

I want to compare the string to my list and if part of the string is in the list, I want to get only the part that is found on the list as a new variable.

This is my code:

    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> ['770', '790', '1470', '1490']

For example this is what I want to get:

    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> 790

Any idea how to do this?

Body:
Like this, you can use a list comprehension:

mylist = ["770", "790", "1470", "1490"]
sq = "BPBA-SG790-NGTP-W-AU-BUN-3Y"

matching = [m for m in mylist if m in sq]

print(matching)

Output:

['790']


问:
How to wait for tomcat restart before exit the Play in Ansible?
I am using handler to restart my tomcat if there is any configuration change happens. What i want to do is

Do a tomcat restart using handler

wait for it to be up and running

Once it is up then exit the Play and don't proceed further.

/roles/appconfig/task/main.yml -

```<code> - name: Copying Application Configuration files to tomcat nodes
   template:
      src: "{{ item }}"
      dest: "{{config_location}}/{{ item | basename | regex_replace('.j2$', '') }}"
      mode: 0755
   with_fileglob:
    - /home/ansible/properties/dev/*.j2
   register: config_var
   notify: Restart tomcat
</code>```

/roles/appconfig/handlers/main.yml -

```<code>---
 - block:
    - name: Restart service
      listen: "Restart tomcat"
      debug:
        msg: "Restarting tomcat as there are only configuration changes as a part of this Release."

    - name: Wait for tomcat start for 300 seconds and continue with play
      listen: "Restart tomcat"
      timeout: 10

## This is the way to check the tomcat status if it's online ##
    - name: Check the State of tomcat service on the remote host
      listen: "Restart tomcat"
      shell: "svcs tomcat"
      register: result

## task to check if tomcat started and register "tomcat_state"

    - name: End the play if tomcat returns status online
      listen: "Restart tomcat"
      meta: end_play
      when: result.stdout_lines.1.split().0 == "online"
   when: target_release_version == current_release
</code>```

This is how I am restarting my tomcat in the handler. Now How do i wait for it to be up and running and then exit the Play.

Please advice.

答:
This should work :

Call handlers from your task. Handlers will be for restarting tomcat, wait, checking the status and finally to exit.

```<code>- name: Copying Application Configuration files to tomcat nodes
   ## Task to do, will notify handlers
   notify: "Restart tomcat"
</code>```

Handlers file to have below :

```<code># handlers file for tomcat_service_start_check
- name: Restart service
  listen: "Restart tomcat"
  shell: <script/command to start tomcat>

- name: Wait for tomcat start for N seconds and continue with play
  listen: "Restart tomcat"
  local_action:
    module: wait_for
      host={{ inventory_hostname }}
      port=8080
      delay=10

- name: Get tomcat status by hitting URL
  listen: "Restart tomcat"
  uri:
    url: http://localhost:8080
  register: tomcat_state

- name: End the play if tomcat returns HTTP 200
  listen: "Restart tomcat"
  meta: end_play
  when:
  - tomcat_state == '200'
</code>```

Now, all handlers listen to "Restart tomcat". And once triggered, they will be executed in the order they are defined.

Reference :
https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html#handlers-running-operations-on-change

Notify handlers are always run in the same order they are defined, not
  in the order listed in the notify-statement. This is also the case for
  handlers using listen.

Body:
I am using handler to restart my tomcat if there is any configuration change happens. What i want to do is

Do a tomcat restart using handler

wait for it to be up and running

Once it is up then exit the Play and don't proceed further.

/roles/appconfig/task/main.yml -

 - name: Copying Application Configuration files to tomcat nodes
   template:
      src: "{{ item }}"
      dest: "{{config_location}}/{{ item | basename | regex_replace('.j2$', '') }}"
      mode: 0755
   with_fileglob:
    - /home/ansible/properties/dev/*.j2
   register: config_var
   notify: Restart tomcat

/roles/appconfig/handlers/main.yml -

---
 - block:
    - name: Restart service
      listen: "Restart tomcat"
      debug:
        msg: "Restarting tomcat as there are only configuration changes as a part of this Release."

    - name: Wait for tomcat start for 300 seconds and continue with play
      listen: "Restart tomcat"
      timeout: 10

## This is the way to check the tomcat status if it's online ##
    - name: Check the State of tomcat service on the remote host
      listen: "Restart tomcat"
      shell: "svcs tomcat"
      register: result

## task to check if tomcat started and register "tomcat_state"

    - name: End the play if tomcat returns status online
      listen: "Restart tomcat"
      meta: end_play
      when: result.stdout_lines.1.split().0 == "online"
   when: target_release_version == current_release

This is how I am restarting my tomcat in the handler. Now How do i wait for it to be up and running and then exit the Play.

Please advice.

Body:
This should work :

Call handlers from your task. Handlers will be for restarting tomcat, wait, checking the status and finally to exit.

- name: Copying Application Configuration files to tomcat nodes
   ## Task to do, will notify handlers
   notify: "Restart tomcat"

Handlers file to have below :

# handlers file for tomcat_service_start_check
- name: Restart service
  listen: "Restart tomcat"
  shell: <script/command to start tomcat>

- name: Wait for tomcat start for N seconds and continue with play
  listen: "Restart tomcat"
  local_action:
    module: wait_for
      host={{ inventory_hostname }}
      port=8080
      delay=10

- name: Get tomcat status by hitting URL
  listen: "Restart tomcat"
  uri:
    url: http://localhost:8080
  register: tomcat_state

- name: End the play if tomcat returns HTTP 200
  listen: "Restart tomcat"
  meta: end_play
  when:
  - tomcat_state == '200'

Now, all handlers listen to "Restart tomcat". And once triggered, they will be executed in the order they are defined.

Reference :
https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html#handlers-running-operations-on-change

Notify handlers are always run in the same order they are defined, not
  in the order listed in the notify-statement. This is also the case for
  handlers using listen.


答:
[s for s in mylist if s in sq]

For those who dislike brevity:

This is a list comprehension. It evaluates to a list of strings s in mylist that satisfy the predicate s in sq (i.e., s is a substring of sq).

Title: Python compare part of string to list


问:
React saving dynamic UI components
Is there any way in react to save UI and load it later ?

I came across several solutions like saving the UI state into a database but this solution is not smart if you are building a dynamic dashboard or a page builder for example with unlimited number of possibilities.

Also we can use reactdomserver from server or client side , data should be passed as props but in the case of a dynamic dashboard this solution will be very hard to implement.

I am new to react and will be very happy to know that there is a solution that can save dynamic content to a file or a database.

答:
Don't save the DOM when you're doing React. You will always find a case that will break whatever assumptions you initially made.

Save the state/props that lead to the UI you need. Then pass those same props again to your component.

Title: React saving dynamic UI components


问:
Justify content is not active over 768px
I cannot understand why my justify-content: space-between; is not working. As I see it then when the viewport hit 768px the container should flex and have space between the 2 columns.

What am I missing here?

.call-out-container {
        max-width: 1200px;
        margin: 40px auto 0 auto;
    }
    .call-out {
        padding: 20px;
        box-sizing: border-box;
        margin-bottom: 20px;
        flex-basis: 50%;
    }
    .call-out:nth-child(1) {background-color: pink}
    .call-out:nth-child(2) {background-color:blueviolet}

    @media (min-width: 768px) {
        .call-out-container {
            display:flex;
            justify-content: space-between;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="call-out-container">
    <div class="call-out">
        <h4>Feature 2</h4>
        <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa</p>
    </div>
    <div class="call-out">
        <h4>Feature 2</h4>
        <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium</p>
    </div>
</div></code>```

答:
It's taking full width because of the content inside the class call-out.
Try limiting the width of that class to see the result.

For example add this to your css:

```<code>.call-out{max-width: 300px}
</code>```

justify-content is working just fine.

Body:
I cannot understand why my justify-content: space-between; is not working. As I see it then when the viewport hit 768px the container should flex and have space between the 2 columns.

What am I missing here?

.call-out-container {
        max-width: 1200px;
        margin: 40px auto 0 auto;
    }
    .call-out {
        padding: 20px;
        box-sizing: border-box;
        margin-bottom: 20px;
        flex-basis: 50%;
    }
    .call-out:nth-child(1) {background-color: pink}
    .call-out:nth-child(2) {background-color:blueviolet}

    @media (min-width: 768px) {
        .call-out-container {
            display:flex;
            justify-content: space-between;
        }
    }

Feature 2

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa

Feature 2

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium

Body:
It's taking full width because of the content inside the class call-out.
Try limiting the width of that class to see the result.

For example add this to your css:

.call-out{max-width: 300px}

justify-content is working just fine.


问:
Problems loading Google Maps API callback script in Webpack bundle
I have a function initMap() that is supposed to be called when the Google Maps API has finished loading. This function manages all of the settings for the map I use in my web-app.

initMap() lives in a file called init-map.js.

I'm migrating to Webpack, so init-map.js is now being included in index.js using require('./scripts/init-map.js.

I'm getting an error InvalidValueError: initMap is not a function, but when I load init-map.js using its own

        ....
        <script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>

```

<p><strong>Works without issue:</strong></p>

```

        ...
        <script src="bundle.js"></script>
        <script src="./scripts/init-map.js"></script>

        ....
        <script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>

```

I don't understand how to make initMap() available for the Google Maps API when it makes the callback.

I would also prefer to have the init-map.js managed within index.js.

答: I believe this is because the bundler changes the name of your initMap function to something like a single letter, e.g. e or f.

ContentLicense: CC BY-SA 3.0

Body:
I have a function initMap() that is supposed to be called when the Google Maps API has finished loading. This function manages all of the settings for the map I use in my web-app.

initMap() lives in a file called init-map.js.

I'm migrating to Webpack, so init-map.js is now being included in index.js using require('./scripts/init-map.js.

I'm getting an error InvalidValueError: initMap is not a function, but when I load init-map.js using its own

        ....

Works without issue:

        ...

        ....

I don't understand how to make initMap() available for the Google Maps API when it makes the callback.

I would also prefer to have the init-map.js managed within index.js.


问:
Python: using .format method to populate string with list items
This seems like a question that should already have an answer, but I didn't find one.  If anyone knows of another question that has already answered this, please post a comment with the link.

My question is, is there a way to input the items from a list into a string using the .format method?  Using specific indices to format is kind of a pain, I am wondering if it is possible to use a "for i in list" technique.

So rather than this:

```<code> x = [1, 2, 3, 4, 5]

print 'The first 4 items in my list are {}, {}, {}, {}'.format([x[0], x[1], x[2], x[3])
</code>```

I could do something like:

```<code>x = [1, 2, 3, 4, 5]

print 'The first 4 items in my list are {}, {}, {}, {}'.format([i for i in x if i < 5])
</code>```

if I try something along these lines, it won't work and I will get a "tuple index out of range" error, because it sees this as only 1 item rather than 4 separate items.  I'm just wondering if this is possible.

答:
```<code>rev_arr = [4,3,2,1]
str_arr.format(', '.join([str(element) for element in rev_arr]))
</code>```

I want that it should give an ouput like this 4 3 2 1 but its returning an empty string .
I am not able to understand why its returning an empty string.
I am newbie please elaborate the second line of the snippet to me

Body:
This seems like a question that should already have an answer, but I didn't find one.  If anyone knows of another question that has already answered this, please post a comment with the link.

My question is, is there a way to input the items from a list into a string using the .format method?  Using specific indices to format is kind of a pain, I am wondering if it is possible to use a "for i in list" technique.

So rather than this:

 x = [1, 2, 3, 4, 5]

print 'The first 4 items in my list are {}, {}, {}, {}'.format([x[0], x[1], x[2], x[3])

I could do something like:

x = [1, 2, 3, 4, 5]

print 'The first 4 items in my list are {}, {}, {}, {}'.format([i for i in x if i < 5])

if I try something along these lines, it won't work and I will get a "tuple index out of range" error, because it sees this as only 1 item rather than 4 separate items.  I'm just wondering if this is possible.

Body:
rev_arr = [4,3,2,1]
str_arr.format(', '.join([str(element) for element in rev_arr]))

I want that it should give an ouput like this 4 3 2 1 but its returning an empty string .
I am not able to understand why its returning an empty string.
I am newbie please elaborate the second line of the snippet to me


问:
Converting json results to a date

Possible Duplicate:

  How to format a JSON date?

I have the following result from a $getJSON call from JavaScript.  How do I convert the start property to a proper date in JavaScript?

[
  {"id":1,"start":"/Date(1238540400000)/"},
  {"id":2,"start":"/Date(1238626800000)/"}
  ]

Thanks!

答:
I use this:

```<code>function parseJsonDate(jsonDateString){
    return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}
</code>```

Update 2018:

This is an old question. Instead of still using this old non standard serialization format I would recommend to modify the server code to return better format for date. Either an ISO string containing time zone information, or only the milliseconds. If you use only the milliseconds for transport it should be UTC on server and client.

2018-07-31T11:56:48Z - ISO string can be parsed using new Date("2018-07-31T11:56:48Z") and obtained from a Date object
using dateObject.toISOString()

1533038208000 - milliseconds since midnight January 1, 1970, UTC - can be parsed using new Date(1533038208000) and obtained from a Date object
using dateObject.getTime()

Title: Converting json results to a date

Body:
I use this:

function parseJsonDate(jsonDateString){
    return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}

Update 2018:

This is an old question. Instead of still using this old non standard serialization format I would recommend to modify the server code to return better format for date. Either an ISO string containing time zone information, or only the milliseconds. If you use only the milliseconds for transport it should be UTC on server and client.

2018-07-31T11:56:48Z - ISO string can be parsed using new Date("2018-07-31T11:56:48Z") and obtained from a Date object
using dateObject.toISOString()

1533038208000 - milliseconds since midnight January 1, 1970, UTC - can be parsed using new Date(1533038208000) and obtained from a Date object
using dateObject.getTime()


问:
Building ffplay with CMake
I tried to build ffplay, using the description of the following library: electron-ffplay, but on a Linux system.

Specifically, I tried to build with:

```<code>cmake . -DFFMPEG_SRC_DIR=/FFmpeg
cmake --build .
</code>```

but all I got is the following error:

```<code>[6%] Building CXX object CMakeFiles/ff_binding-linux-x64.abi-83.dir/src/win_delay_load_hook.cc.o
c++: error: /ignore:4090: No such file or directory
make[2]: *** [CMakeFiles/ff_binding-linux-x64.abi-83.dir/build.make:63: CMakeFiles/ff_binding-linux-x64.abi-83.dir/src/win_delay_load_hook.cc.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:73: CMakeFiles/ff_binding-linux-x64.abi-83.dir/all] Error 2
make: *** [Makefile:84: all] Error 2
</code>```

[Edit: I use that library because I need to run FFplay with electron]

答:
Line 160 in the CMake code in this repository has the line:

```<code>set_target_properties(${_TARGET} PROPERTIES COMPILE_FLAGS "/ignore:4090")
</code>```

which looks like it was intended to disable MSVC compiler warning 4090. Unfortunately, Visual Studio does not recognize the /ignore compile flag, nor does your Linux-based compiler. You can simply comment out this line in the CMake code to get rid of that error.

FWIW, the build instructions for this repository are Windows-based, so it may not support building on a Linux environment. It is highly possible that you will encounter more issues trying to build this repository on Linux.

Title: Building ffplay with CMake

Body:
I tried to build ffplay, using the description of the following library: electron-ffplay, but on a Linux system.

Specifically, I tried to build with:

cmake . -DFFMPEG_SRC_DIR=/FFmpeg
cmake --build .

but all I got is the following error:

[6%] Building CXX object CMakeFiles/ff_binding-linux-x64.abi-83.dir/src/win_delay_load_hook.cc.o
c++: error: /ignore:4090: No such file or directory
make[2]: *** [CMakeFiles/ff_binding-linux-x64.abi-83.dir/build.make:63: CMakeFiles/ff_binding-linux-x64.abi-83.dir/src/win_delay_load_hook.cc.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:73: CMakeFiles/ff_binding-linux-x64.abi-83.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

[Edit: I use that library because I need to run FFplay with electron]

Body:
Line 160 in the CMake code in this repository has the line:

set_target_properties(${_TARGET} PROPERTIES COMPILE_FLAGS "/ignore:4090")

which looks like it was intended to disable MSVC compiler warning 4090. Unfortunately, Visual Studio does not recognize the /ignore compile flag, nor does your Linux-based compiler. You can simply comment out this line in the CMake code to get rid of that error.

FWIW, the build instructions for this repository are Windows-based, so it may not support building on a Linux environment. It is highly possible that you will encounter more issues trying to build this repository on Linux.


问:
UI in Xcode (Swift): I only want the collapsing functionality of UIStackView, not standardised spacing. Still worth using one?
I have a UITableViewCell, in which I'd like to have two UILabels, a UIImageView, followed by a UIButton beneath (all stacked vertically). Diagrammatically, it would look like this:

```<code>
UILabel

1 point vertical spacing

UILabel2

6 points vertical spacing

UImageView

4 points vertical spacing

UIButton
</code>```

Any two of these may not be present (except the two labels), and the rest must resize accordingly, collapsing the empty space. Would a UIStackView be worth using here, keeping in mind that custom spacing would need to be used.

As an example, in a stack view, the UIImageView could be easily collapsed if we did not have an image to show, whereas without one, I can't think of a way of doing it without messing about with height constraints of the UIImageView in code. Perhaps this can be achieved with hiding the  UIImageView?

What approach would you recommend?

答:
UIStackView handles hiding / un-hiding views very well and lets the non-hidden elements take up any extra space. Would highly recommend using a UIStackView in this scenario. Custom spacing is no big deal, and can be accomplished like this:

stackView.setCustomSpacing(6, after: UILabel2)

Body:
I have a UITableViewCell, in which I'd like to have two UILabels, a UIImageView, followed by a UIButton beneath (all stacked vertically). Diagrammatically, it would look like this:

UILabel

1 point vertical spacing

UILabel2

6 points vertical spacing

UImageView

4 points vertical spacing

UIButton

Any two of these may not be present (except the two labels), and the rest must resize accordingly, collapsing the empty space. Would a UIStackView be worth using here, keeping in mind that custom spacing would need to be used.

As an example, in a stack view, the UIImageView could be easily collapsed if we did not have an image to show, whereas without one, I can't think of a way of doing it without messing about with height constraints of the UIImageView in code. Perhaps this can be achieved with hiding the  UIImageView?

What approach would you recommend?


问:
Return highest number and associated name from object in Javascript
This is my react app - https://imgur.com/a/QSuK8rY

I'm trying to return the highest and lowest latitude and the name of the city. I have it working to return the latitude but the name is coming up undefined... It is weird because in my jest testing, my function is working fine. I'm using React, Javascript and my API to load and store data... What I'm doing in this function is putting all the latitudes into an array then doing Math.max then looping through this.cities to see which latitude in the object matches the highest latitude that we put into mostNorthLat, then getting the name of the city that matches the lat.

This is my javascript file with my pure functions:

```<code>//Loads cities in API and injects it into this.cities

    async loadCities() {
            const data = await postData(url + "all");
            //Create a dictionary of cities and keep track of the last key
            const cities = {};
            data.forEach(x => {
                cities[x.key] = x;
                this.lastKey = (x.key > this.lastKey) ? x.key : this.lastKey;
            });

            this.cities = cities;
        }

//This is my add function I use for adding new cities to my API, which then React uses to create my cards for each object in my cities object in the API

    async addOrUpdate(city) {
            let theUrl;

            if (city.key) {
                theUrl = url + 'update'
            } else {
                theUrl = url + 'add'
                this.lastKey++;
                city.key = this.lastKey;
                city.population = Number(city.population)
            }
            await postData(theUrl, city);
            this.cities[city.key] = city;
    }

//My functions that are running the most North and most South

    getMostNorthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostNorthLat = Math.max.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostNorthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostNorthLat}°`
            }
        }

    getMostSouthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostSouthLat = Math.min.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostSouthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostSouthLat}°`
            }
        }
</code>```

Here is what a city object looks like:

```<code>    {
        "key": 1,
        "latitude": "1",
        "longitude": "1",
        "name": "City",
        "population": 49500
    },
</code>```

Each city object is held in a main object called 'cities'

```<code>    constructor() {
            this.cities = {};
            this.lastKey = 0;
        }
</code>```

So this is an what 3 cities inside the object looks like:

```<code>    {
            '1': City {
              name: "Gangster's Paradise",
              latitude: -15,
              longitude: 5,
              population: 10,
              key: 1
            },
            '2': City {
              name: 'Pho City',
              latitude: 5,
              longitude: 52,
              population: 1050,
              key: 2
            },
            '3': City {
              name: 'Frisbee Land',
              latitude: 0,
              longitude: 12,
              population: 1000000,
              key: 3
            }
    }
</code>```

My React portion:

```<code>    function CitiesApp() {
       const classes = useStyles();
       const [message, setMessage] = useState('')

       const [count, setCount] = useState(0)

       const [total, setTotal] = useState()
       const [northest, setNorthest] = useState()
       const [southest, setSouthest] = useState()

       useEffect(() => {
          //Load cities from the API - re-render when count is updated
          async function fetchData() {
             try {
                await cityCtrl.loadCities()
                updateSummary()
             } catch (e) {
                userMsg('Turn on the server')
             }
          }
          fetchData();
       }, [count]);

       async function onSave(city) {
          await cityCtrl.addOrUpdate(city)
          setCount(count + 1)
          updateSummary()
       }

       async function deleteCard(thekey) {
          await cityCtrl.deleteCard(thekey)
          setCount(count + 1)
          updateSummary()
       }

       async function moveIn(thekey, num) {
          await cityCtrl.movedIn(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       async function moveOut(thekey, num) {
          await cityCtrl.movedOut(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       function updateSummary() {
          setTotal(cityCtrl.getTotalPopulation())
          setNorthest(cityCtrl.getMostNorthern())
          setSouthest(cityCtrl.getMostSouthern())
       }
    }
</code>```

答:
I think you could simplify things by doing all your work in a single loop through this.cities:

```<code>getMostNorthern() {
  if (!this.cities.length) return '';
  let mostNorthernCity;
  for (const key in this.cities) {
    if (!mostNorthernCity) {
      mostNorthernCity = this.cities[key];
      continue;
    }
    if (this.cities[key].latitude > mostNorthernCity.latitude) {
      mostNorthernCity = this.cities[key];
    }
  }
  return `${mostNorthernCity.name} at ${mostNorthernCity.latitude}`;
}
</code>```

getMostSouthern would work the same way but you might rename the variable to mostSouthernCity and use the less than comparator.

Body:
This is my react app - https://imgur.com/a/QSuK8rY

I'm trying to return the highest and lowest latitude and the name of the city. I have it working to return the latitude but the name is coming up undefined... It is weird because in my jest testing, my function is working fine. I'm using React, Javascript and my API to load and store data... What I'm doing in this function is putting all the latitudes into an array then doing Math.max then looping through this.cities to see which latitude in the object matches the highest latitude that we put into mostNorthLat, then getting the name of the city that matches the lat.

This is my javascript file with my pure functions:

//Loads cities in API and injects it into this.cities

    async loadCities() {
            const data = await postData(url + "all");
            //Create a dictionary of cities and keep track of the last key
            const cities = {};
            data.forEach(x => {
                cities[x.key] = x;
                this.lastKey = (x.key > this.lastKey) ? x.key : this.lastKey;
            });

            this.cities = cities;
        }

//This is my add function I use for adding new cities to my API, which then React uses to create my cards for each object in my cities object in the API

    async addOrUpdate(city) {
            let theUrl;

            if (city.key) {
                theUrl = url + 'update'
            } else {
                theUrl = url + 'add'
                this.lastKey++;
                city.key = this.lastKey;
                city.population = Number(city.population)
            }
            await postData(theUrl, city);
            this.cities[city.key] = city;
    }

//My functions that are running the most North and most South

    getMostNorthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostNorthLat = Math.max.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostNorthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostNorthLat}°`
            }
        }

    getMostSouthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostSouthLat = Math.min.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostSouthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostSouthLat}°`
            }
        }

Here is what a city object looks like:

    {
        "key": 1,
        "latitude": "1",
        "longitude": "1",
        "name": "City",
        "population": 49500
    },

Each city object is held in a main object called 'cities'

    constructor() {
            this.cities = {};
            this.lastKey = 0;
        }

So this is an what 3 cities inside the object looks like:

    {
            '1': City {
              name: "Gangster's Paradise",
              latitude: -15,
              longitude: 5,
              population: 10,
              key: 1
            },
            '2': City {
              name: 'Pho City',
              latitude: 5,
              longitude: 52,
              population: 1050,
              key: 2
            },
            '3': City {
              name: 'Frisbee Land',
              latitude: 0,
              longitude: 12,
              population: 1000000,
              key: 3
            }
    }

My React portion:

    function CitiesApp() {
       const classes = useStyles();
       const [message, setMessage] = useState('')

       const [count, setCount] = useState(0)

       const [total, setTotal] = useState()
       const [northest, setNorthest] = useState()
       const [southest, setSouthest] = useState()

       useEffect(() => {
          //Load cities from the API - re-render when count is updated
          async function fetchData() {
             try {
                await cityCtrl.loadCities()
                updateSummary()
             } catch (e) {
                userMsg('Turn on the server')
             }
          }
          fetchData();
       }, [count]);

       async function onSave(city) {
          await cityCtrl.addOrUpdate(city)
          setCount(count + 1)
          updateSummary()
       }

       async function deleteCard(thekey) {
          await cityCtrl.deleteCard(thekey)
          setCount(count + 1)
          updateSummary()
       }

       async function moveIn(thekey, num) {
          await cityCtrl.movedIn(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       async function moveOut(thekey, num) {
          await cityCtrl.movedOut(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       function updateSummary() {
          setTotal(cityCtrl.getTotalPopulation())
          setNorthest(cityCtrl.getMostNorthern())
          setSouthest(cityCtrl.getMostSouthern())
       }
    }

Body:
I think you could simplify things by doing all your work in a single loop through this.cities:

getMostNorthern() {
  if (!this.cities.length) return '';
  let mostNorthernCity;
  for (const key in this.cities) {
    if (!mostNorthernCity) {
      mostNorthernCity = this.cities[key];
      continue;
    }
    if (this.cities[key].latitude > mostNorthernCity.latitude) {
      mostNorthernCity = this.cities[key];
    }
  }
  return `${mostNorthernCity.name} at ${mostNorthernCity.latitude}`;
}

getMostSouthern would work the same way but you might rename the variable to mostSouthernCity and use the less than comparator.


答:
You don't even need to use functions for these simple, built-in tasks.

```<code>a = int(input())
b = int(input())
print(a+b)
print(a-b)
print(a*b)
</code>```

This will work too.

Hope this helps :)

Title: How do I create the expected output in this Arithmetic Operators problem on HackerRank?

Body:
I am a beginner in Python 3 and I am trying to practice more of my Python 3 skills by trying to solve  HackerRank problems but I am a little stuck on this one problem. I have already written some code but I am having trouble with getting the expected output. Can someone please help?

The instructions:

Read two integers from STDIN and print three lines where:

The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.

Output Format

Print the three lines as explained above.

Sample Input

3
2

Sample Output

5
1
6

Here is my code, I created three functions to add, subtract, and multiply the inputted numbers but I need to know how to write some code that will iterate through a list and make the outputted numbers move vertically:

def addition(a, b):
    print (a + b)

#Main
a = int(input())
b = int(input())
addition(a, b)

def subtraction (a, b):
    print (a - b)

#Main
a = int(input())
b = int(input())
subtraction(a, b)

def multiplication(a, b):
    print (a * b)

#Main
a = int(input())
b = int(input())
multiplication(a, b)

Body:
You don't even need to use functions for these simple, built-in tasks.

a = int(input())
b = int(input())
print(a+b)
print(a-b)
print(a*b)

This will work too.

Hope this helps :)


问:
Why do I get Android errors on Qt projects loading?
I do not use any Android features of Qt, my only purpose is to program some little softwares for Windows with minGW and QMake, no other project configurations is relevant for my needs. I'm simply curious if I missed a part, it does not affect the fonctionnality.

Project ERROR: You need to set the ANDROID_NDK_ROOT environment variable
  to point to your Android NDK

And a bunch of other errors like that. Its my 4th clean install of 4 different version of Qt bundle, (now I carefully unselect everything except minGW32 and it still showing up!) God's sake why?

Did I missed a part on How to use Qt? Do I need extra-steps to remove it manually on a project creation?

答:
So if I understand, I can't remove "Android options" from Qt as it is pre-installed for all platforms.

Then yes, even if I don't use it, I must install Android NDK. Then continue to unselect the kit. Then these Error messages will disapear.


问:
ASP.NET Send Cookies to client Browser
I'm integrating a single sign on over 2 ASP.Net applications. For that matter i have a web service that is called by the main app. when a user logs in. this web service authenticates the user in my second application and brings back the authentication cookies i need to deliver to the client browser so he can navigate freely and logged in both applications.

I was planning to use HttpContext.Current.Response.Cookies.Add(cookie) in order to deliver the new cookies but this seems not to work as no cookies are added what so ever...

Any ideas on what might be going wrong?

here is my code:

```<code>var service = new localhost.UserManagement();
service.CookieContainer = new CookieContainer();
if (service.AuthenticateUser("test@user.pt", "test"))
{
    var collection = service.CookieContainer.GetCookies(new Uri("http://localhost"));
    foreach (Cookie item in collection)
    {
        HttpContext.Current.Response.Cookies.Add(CookieConverter(item));
    }
    HttpContext.Current.Response.Flush();
    return true;
}

return false;
</code>```

Note: CookieConverter(item) is used to convert Cookie object i receive to HttpCookie

Thanks

```<code>
private HttpCookie CookieConverter(Cookie cookie)
        {
            var result = new HttpCookie(cookie.Name);

            result.Value = cookie.Value;
            result.Domain = cookie.Domain;
            result.Expires = cookie.Expires;
            result.Path = cookie.Path;
            result.Secure = cookie.Secure;
            result.HttpOnly = cookie.HttpOnly;

            return result;
        }
</code>```

答:
You should check:

collection is empty? Could you set braeakpoint and check collection?

where is this code located? (.aspx page, web service, http handler?)

try to create minimalistic "Cookie setter" that just add simple cookie in any way

Title: ASP.NET Send Cookies to client Browser

Body:
I'm integrating a single sign on over 2 ASP.Net applications. For that matter i have a web service that is called by the main app. when a user logs in. this web service authenticates the user in my second application and brings back the authentication cookies i need to deliver to the client browser so he can navigate freely and logged in both applications.

I was planning to use HttpContext.Current.Response.Cookies.Add(cookie) in order to deliver the new cookies but this seems not to work as no cookies are added what so ever...

Any ideas on what might be going wrong?

here is my code:

var service = new localhost.UserManagement();
service.CookieContainer = new CookieContainer();
if (service.AuthenticateUser("test@user.pt", "test"))
{
    var collection = service.CookieContainer.GetCookies(new Uri("http://localhost"));
    foreach (Cookie item in collection)
    {
        HttpContext.Current.Response.Cookies.Add(CookieConverter(item));
    }
    HttpContext.Current.Response.Flush();
    return true;
}

return false;

Note: CookieConverter(item) is used to convert Cookie object i receive to HttpCookie

Thanks

private HttpCookie CookieConverter(Cookie cookie)
        {
            var result = new HttpCookie(cookie.Name);

            result.Value = cookie.Value;
            result.Domain = cookie.Domain;
            result.Expires = cookie.Expires;
            result.Path = cookie.Path;
            result.Secure = cookie.Secure;
            result.HttpOnly = cookie.HttpOnly;

            return result;
        }


问:
SocketException: OS Error: Connection refused, errno = 111 in flutter using django backend
I m building a flutter app with django rest-framework. The registration api is working fine in Postman but after some successful registration from the flutter app it is showing the above error. The request is been sent on https address.

Removed csrf. Nothing happens.

Request:

```<code>var data = {'email':signupemailidcontroller.text,
            'password1':passwordcontroller.text,
            'password2':confirmpasswordcontroller.text,
           };
        //http request here
        await http.post(websitesignupurl,
                        headers: headers,
                        body: json.encode(data))
          .then((onResponse){
            print(onResponse.body);
          }).catchError((onerror){
            print(onerror.toString());
        });
</code>```

Output in Console:

SocketException: OS Error: Connection refused, errno = 111

I Expect the response of this request to be a Json object containing the user and token.

答: I fixed this with $ adb tcpip <port-your-local-server>

Body:
I m building a flutter app with django rest-framework. The registration api is working fine in Postman but after some successful registration from the flutter app it is showing the above error. The request is been sent on https address.

Removed csrf. Nothing happens.

Request:

var data = {'email':signupemailidcontroller.text,
            'password1':passwordcontroller.text,
            'password2':confirmpasswordcontroller.text,
           };
        //http request here
        await http.post(websitesignupurl,
                        headers: headers,
                        body: json.encode(data))
          .then((onResponse){
            print(onResponse.body);
          }).catchError((onerror){
            print(onerror.toString());
        });

Output in Console:

SocketException: OS Error: Connection refused, errno = 111

I Expect the response of this request to be a Json object containing the user and token.


问:
How can I query a table for transitive matches?
Giving the following tables

Units:

```<code>| id | singular | plural |
|----|----------|--------|
| 3  | onion    | onions |
| 4  | bag      | bags   |
| 5  | gram     | grams  |
| 6  | ml       | ml     |
| 7  | mm       | mm     |
</code>```

and

Conversions:

```<code>| id | convert_from | convert_to | factor |
|----|--------------|------------|--------|
| 3  | 4            | 3          | 5      |
| 4  | 3            | 5          | 125    |
</code>```

How could I obtain all possible conversion factors from (for example) bag (unit 4)?

I would expect the answers to resemble the form

```<code>| convert_from | convert_to | factor |
|--------------|------------|--------|
| 4            | 3          | 5      |
| 4            | 5          | 625    |
</code>```

Caveats:

There is no guarantee about which column of the conversions table (convert_from, convert_to) a unit might appear in.

Conversions that transit through units 5, 6, or 7 should be ignored.

That is to say,
1->2->4->5 is valid, 1->2->4->5->7 is not.

A SQL solution (or re-architecting of the database to facilitate a SQL solution) would be ideal, but a code solution that makes multiple SQL queries would also be appreciated.

There will be other units in the units table that should be ignored if they do not form part of the conversion graph (or if they form part of the branch through an invalid transition (5, 6, or 7)). This is a simplified view.

Illustrative example

Ignoring SQL and retrieving the data for a moment, here's what I'm trying to achieve:

I want to build a system where users can store household products. A product has a unit associated with it. The unit might be an SI unit, such as mm, ml, g.. or it might be a discrete unit such as onion, or can.

Units can have relationships amongst themselves, so for example 1 can -> 330 ml.
The complexity of my question comes from the fact that the conversions for a single unit might be spread across many products.

Considering the can example again, we can have a product called pepsi (crate of 24) with the unit being crate, and another product called pepsi (can) with the unit of can.

When the user creates the pepsi (can) product, they provide the following conversion:

```<code>1 can -> 330 ml
</code>```

Later, the user creates the pepsi (crate of 24) product, and provides the following conversion:

```<code>1 crate -> 24 can
</code>```

Finally, the user asks the question "how much pepsi do I have?"

I'd like to be able to answer:

25 cans

1.0417 crates

8250 ml.

However, I don't know how to convert crates to ml.

Here's another example in illustrated form:

Edit:

Changed mms and mls to mm and ml. Not sure what I was thinking...

Added diagram to help clarify what i'm looking for rather than the solution.

答:
You can use a recursive CTE, assuming there are no cycles in the data.

I added an extra is_terminal column to identify the terminal units where you don't want to convert from anymore (5, 6, and 7). The query is:

```<code>with recursive
e (convert_from, convert_to, factor, is_terminal) as (
  select id, id, 1, is_terminal from units where id = 4 -- bag
 union all
  select e.convert_from, c.convert_to, e.factor * c.factor, u.is_terminal
  from e
  join conversions c on c.convert_from = e.convert_to
  join units u on u.id = c.convert_to
  where not e.is_terminal
)
select * from e where convert_from <> convert_to
</code>```

Result:

```<code>convert_from  convert_to  factor  is_terminal
------------  ----------  ------  -----------
4             3           5       false
4             5           625     true
</code>```

See running example at DB Fiddle . Here's the data script I used to test:

```<code>create table units (
  id int,
  is_terminal boolean
);

insert into units (id, is_terminal) values
  (3, false), (4, false),
  (5, true), (6, true), (7, true);

create table conversions (
  id int,
  convert_from int,
  convert_to int,
  factor int
);

insert into conversions (id, convert_from, convert_to, factor) values
  (3, 4, 3, 5),
  (4, 3, 5, 125);
</code>```

Body:
Giving the following tables

Units:

| id | singular | plural |
|----|----------|--------|
| 3  | onion    | onions |
| 4  | bag      | bags   |
| 5  | gram     | grams  |
| 6  | ml       | ml     |
| 7  | mm       | mm     |

and

Conversions:

| id | convert_from | convert_to | factor |
|----|--------------|------------|--------|
| 3  | 4            | 3          | 5      |
| 4  | 3            | 5          | 125    |

How could I obtain all possible conversion factors from (for example) bag (unit 4)?

I would expect the answers to resemble the form

| convert_from | convert_to | factor |
|--------------|------------|--------|
| 4            | 3          | 5      |
| 4            | 5          | 625    |

Caveats:

There is no guarantee about which column of the conversions table (convert_from, convert_to) a unit might appear in.

Conversions that transit through units 5, 6, or 7 should be ignored.

That is to say,
1->2->4->5 is valid, 1->2->4->5->7 is not.

A SQL solution (or re-architecting of the database to facilitate a SQL solution) would be ideal, but a code solution that makes multiple SQL queries would also be appreciated.

There will be other units in the units table that should be ignored if they do not form part of the conversion graph (or if they form part of the branch through an invalid transition (5, 6, or 7)). This is a simplified view.

Illustrative example

Ignoring SQL and retrieving the data for a moment, here's what I'm trying to achieve:

I want to build a system where users can store household products. A product has a unit associated with it. The unit might be an SI unit, such as mm, ml, g.. or it might be a discrete unit such as onion, or can.

Units can have relationships amongst themselves, so for example 1 can -> 330 ml.
The complexity of my question comes from the fact that the conversions for a single unit might be spread across many products.

Considering the can example again, we can have a product called pepsi (crate of 24) with the unit being crate, and another product called pepsi (can) with the unit of can.

When the user creates the pepsi (can) product, they provide the following conversion:

1 can -> 330 ml

Later, the user creates the pepsi (crate of 24) product, and provides the following conversion:

1 crate -> 24 can

Finally, the user asks the question "how much pepsi do I have?"

I'd like to be able to answer:

25 cans

1.0417 crates

8250 ml.

However, I don't know how to convert crates to ml.

Here's another example in illustrated form:

Edit:

Changed mms and mls to mm and ml. Not sure what I was thinking...

Added diagram to help clarify what i'm looking for rather than the solution.

Body:
You can use a recursive CTE, assuming there are no cycles in the data.

I added an extra is_terminal column to identify the terminal units where you don't want to convert from anymore (5, 6, and 7). The query is:

with recursive
e (convert_from, convert_to, factor, is_terminal) as (
  select id, id, 1, is_terminal from units where id = 4 -- bag
 union all
  select e.convert_from, c.convert_to, e.factor * c.factor, u.is_terminal
  from e
  join conversions c on c.convert_from = e.convert_to
  join units u on u.id = c.convert_to
  where not e.is_terminal
)
select * from e where convert_from <> convert_to

Result:

convert_from  convert_to  factor  is_terminal
------------  ----------  ------  -----------
4             3           5       false
4             5           625     true

See running example at DB Fiddle . Here's the data script I used to test:

create table units (
  id int,
  is_terminal boolean
);

insert into units (id, is_terminal) values
  (3, false), (4, false),
  (5, true), (6, true), (7, true);

create table conversions (
  id int,
  convert_from int,
  convert_to int,
  factor int
);

insert into conversions (id, convert_from, convert_to, factor) values
  (3, 4, 3, 5),
  (4, 3, 5, 125);


答:
I don't think you need to iterate through a list of numbers. The evaluator will run for code several times and do that vertical formatting for you. The following should suffice.

You don't need to take the input multiple times. Just store it once and call the three functions you have written.

def addition(a, b):
    print (a + b)

def subtraction (a, b):
    print (a - b)

def multiplication(a, b):
    print (a * b)

#Main
a = int(input())
b = int(input())
## Note this
addition(a, b)
subtraction (a, b)
multiplication(a, b)
```

<p>The print function in python by default prints in different lines and the last three lines of your code makes sure that is how it is printed.
However, for your own testing (so that you don't have to move your code around too much) you can try the following:</p>

<pre class="lang-py prettyprint-override"><code>def addition(a, b):
    print (a + b)

def subtraction (a, b):
    print (a - b)

def multiplication(a, b):
    print (a * b)

def getOutput(a,b):
    #a = int(input())
    #b = int(input())
    addition(a, b)
    subtraction (a, b)
    multiplication(a, b)

listA=[1,2,3,45,9]
listB=[2,3,4,70,1]
for i in range(len(listA)):
   getOutput(listA[i],listB[i])
</code>```

You will have to however submit code in the format of the first code.

Body:
I don't think you need to iterate through a list of numbers. The evaluator will run for code several times and do that vertical formatting for you. The following should suffice.

You don't need to take the input multiple times. Just store it once and call the three functions you have written.

def addition(a, b):
    print (a + b)

def subtraction (a, b):
    print (a - b)

def multiplication(a, b):
    print (a * b)

#Main
a = int(input())
b = int(input())
## Note this
addition(a, b)
subtraction (a, b)
multiplication(a, b)

The print function in python by default prints in different lines and the last three lines of your code makes sure that is how it is printed.
However, for your own testing (so that you don't have to move your code around too much) you can try the following:

def addition(a, b):
    print (a + b)

def subtraction (a, b):
    print (a - b)

def multiplication(a, b):
    print (a * b)

def getOutput(a,b):
    #a = int(input())
    #b = int(input())
    addition(a, b)
    subtraction (a, b)
    multiplication(a, b)

listA=[1,2,3,45,9]
listB=[2,3,4,70,1]
for i in range(len(listA)):
   getOutput(listA[i],listB[i])

You will have to however submit code in the format of the first code.


问:
Normalization of grayscale fingerprint images
I'm trying to normalize grayscale fingerprint images as proposed in this paper in Section 2.3. To test it I used this gray fingerprint and after normalization I want it to look like this normalized fingerprint.

Here is the function I used to normalize the fingerprint

```<code>import numpy as np
from glob import glob
from PIL import Image
import matplotlib.pyplot as plt

def normalization(im_arr, M0, VAR0):
    """
    im_arr: image as array
    M0: desired mean
    VAR0: desired variance

    G: normalized image as array
    """
    row, col = im_arr.shape
    # Mean and variance calculation
    M = (1 / (row ** 2)) * np.sum(im_arr)
    VAR = (1 / (row ** 2)) * np.sum((im_arr - M) ** 2)

    G = np.zeros(im_arr.shape)
    for i in range(row):
        for j in range(col):
            if im_arr[i, j] > M:
                G[i, j] = M0 + np.sqrt((VAR0 * (im_arr[i, j] - M) ** 2) / VAR)
            else:
                G[i, j] = M0 - np.sqrt((VAR0 * (im_arr[i, j] - M) ** 2) / VAR)
    return G
</code>```

and here is the code I used to read the data

```<code>data = 'greyfp.JPG'

img = Image.open(data).convert('L')
img = img.resize((200, 200))
img_arr = np.array(img).astype(float)
img_arr = img_arr / np.max(img_arr)

G = normalization(img_arr, 0.5, 0.5)
</code>```

If I now check the mean and the variance of the new image, I get the desired results. But when I try to plot the normalized fingerprint from its matrix it looks exactly the same as the input image

```<code>fig, ax = plt.subplots(1, 2)
grey = ax[0].imshow(img, cmap='gray')
norm = ax[1].imshow(G, cmap='gray')
plt.show()
</code>```

However, if I save the new image and plot it with

```<code>img = Image.fromarray(G, 'L')
img.save('G.JPG')
plt.imshow(img, cmap='gray')
plt.show()
</code>```

it looks completely different, but still not like my desired output.

Could anybody help me to get the same result as in the paper and maybe help me understand, why the plots from the matrix and the image-type look totally different?

答:
See this update of your code:</p>

```<code>import numpy as np
from glob import glob
from PIL import Image
import matplotlib.pyplot as plt

def normalization(im_arr, M0, VAR0):
    """
    im_arr: image as array
    M0: desired mean
    VAR0: desired variance

    G: normalized image as array
    """
    row, col = im_arr.shape
    print("row,col = ", row, col)
    # Mean and variance calculation
    M = (1 / (row ** 2)) * np.sum(im_arr)
    VAR = (1 / (row ** 2)) * np.sum((im_arr - M) ** 2)

    G = np.zeros(im_arr.shape)
    for i in range(row):
        for j in range(col):

            if im_arr[i, j] > M:
                G[i, j] = M0 + np.sqrt((VAR0 * (im_arr[i, j] - M) ** 2) / VAR)
            else:
                G[i, j] = M0 - np.sqrt((VAR0 * (im_arr[i, j] - M) ** 2) / VAR)
    return G

data = 'test.jpg'

img = Image.open(data).convert('L')
img = img.resize((200, 200))
img_arr = np.array(img).astype(float)
img_arr = img_arr / np.max(img_arr)

G = normalization(img_arr, 0.5, 0.5)
G=G*255
G=np.where(G<=255,G,255)
G=np.array(G).astype(np.uint8)
cv2.imshow("G",G)

img = Image.fromarray(G, 'L')
img.save('G.JPG')
plt.imshow(img, cmap='gray')
plt.show()
</code>```

Body:
I'm trying to normalize grayscale fingerprint images as proposed in this paper in Section 2.3. To test it I used this gray fingerprint and after normalization I want it to look like this normalized fingerprint.

Here is the function I used to normalize the fingerprint

import numpy as np
from glob import glob
from PIL import Image
import matplotlib.pyplot as plt

def normalization(im_arr, M0, VAR0):
    """
    im_arr: image as array
    M0: desired mean
    VAR0: desired variance

    G: normalized image as array
    """
    row, col = im_arr.shape
    # Mean and variance calculation
    M = (1 / (row ** 2)) * np.sum(im_arr)
    VAR = (1 / (row ** 2)) * np.sum((im_arr - M) ** 2)

    G = np.zeros(im_arr.shape)
    for i in range(row):
        for j in range(col):
            if im_arr[i, j] > M:
                G[i, j] = M0 + np.sqrt((VAR0 * (im_arr[i, j] - M) ** 2) / VAR)
            else:
                G[i, j] = M0 - np.sqrt((VAR0 * (im_arr[i, j] - M) ** 2) / VAR)
    return G

and here is the code I used to read the data

data = 'greyfp.JPG'

img = Image.open(data).convert('L')
img = img.resize((200, 200))
img_arr = np.array(img).astype(float)
img_arr = img_arr / np.max(img_arr)

G = normalization(img_arr, 0.5, 0.5)

If I now check the mean and the variance of the new image, I get the desired results. But when I try to plot the normalized fingerprint from its matrix it looks exactly the same as the input image

fig, ax = plt.subplots(1, 2)
grey = ax[0].imshow(img, cmap='gray')
norm = ax[1].imshow(G, cmap='gray')
plt.show()

However, if I save the new image and plot it with

img = Image.fromarray(G, 'L')
img.save('G.JPG')
plt.imshow(img, cmap='gray')
plt.show()

it looks completely different, but still not like my desired output.

Could anybody help me to get the same result as in the paper and maybe help me understand, why the plots from the matrix and the image-type look totally different?

Body:
See this update of your code:

import numpy as np
from glob import glob
from PIL import Image
import matplotlib.pyplot as plt

def normalization(im_arr, M0, VAR0):
    """
    im_arr: image as array
    M0: desired mean
    VAR0: desired variance

    G: normalized image as array
    """
    row, col = im_arr.shape
    print("row,col = ", row, col)
    # Mean and variance calculation
    M = (1 / (row ** 2)) * np.sum(im_arr)
    VAR = (1 / (row ** 2)) * np.sum((im_arr - M) ** 2)

    G = np.zeros(im_arr.shape)
    for i in range(row):
        for j in range(col):

            if im_arr[i, j] > M:
                G[i, j] = M0 + np.sqrt((VAR0 * (im_arr[i, j] - M) ** 2) / VAR)
            else:
                G[i, j] = M0 - np.sqrt((VAR0 * (im_arr[i, j] - M) ** 2) / VAR)
    return G

data = 'test.jpg'

img = Image.open(data).convert('L')
img = img.resize((200, 200))
img_arr = np.array(img).astype(float)
img_arr = img_arr / np.max(img_arr)

G = normalization(img_arr, 0.5, 0.5)
G=G*255
G=np.where(G<=255,G,255)
G=np.array(G).astype(np.uint8)
cv2.imshow("G",G)

img = Image.fromarray(G, 'L')
img.save('G.JPG')
plt.imshow(img, cmap='gray')
plt.show()


问:
Related products based on grouping tags limit memory. Use instead collection with certain handle tag
By starting from this point https://www.shopify.com/partners/blog/related-products
I end up to this custom and working code:

```<code>    {% comment %}
     Get dynamic tag from product and create static collection handle
    {% endcomment %}
        {% for tag in product.tags %}
            {% if tag contains 'IDSeries_' %}
                {% assign ser_tag = tag %}
                    <li>
                        <a href="/collections/all/{{ ser_tag | handleize }}">
                            <h2>{{ ser_tag | remove: "IDSeries_" | prepend: "Go to products with Serie ID number:" }}</h2>
                        </a>
                    </li>
            {% endif %}
        {% endfor %}

    {% comment %}
     Return products by using the extracted tag
    {% endcomment %}
        {% for product in collections.all.products %}
            {% if product.tags contains ser_tag %}
                {{ product.title }}
            {% endif %}
        {% endfor %}
</code>```

This above does work. But it's not the solution!

because limited memory, it works only for the first bunch of products and not for all.

By considering I have twenty five thousands products all with an incremental "IDSeries_'INT'"

My goal is: to show products with same specific "IDSeries_'INT'".

Since when this already happens at collection tag url like this

I was wondering if I can return products (into a section products) that are already filtered at the collection handle tag url layer.

So at Themes/Debut/Sections/product-template.liquid

I am trying the following with no luck:

```<code>{% assign collection_handle = ser_tag %}
    {% for product in collections.all[collection_handle].products %}
        {{ product.title }}
    {% endfor %}
</code>```

Question:

Any clue on how to achieve a consistent result for such a big stock of products?

Extra question:

For a store with 30k products each with five tags (so 150k tags in
total).

Does tags have any limitation?

I also created a Shopify community topic href="https://community.shopify.com/c/Technical-Q-A/Related-products-based-on-grouping-tags-limit-memory-Use-instead/td-p/759705" rel="nofollow noreferrer">https://community.shopify.com/c/Technical-Q-A/Related-products-based-on-grouping-tags-limit-memory-Use-instead/td-p/759705

答:
I can think of two solutions for your problem, that doesn't affect the speed of the site.

Search based + Javascript

The search page on Shopify can search for tags as well.

So if you make a fetch request to the search page like so:

```<code>fetch('/search?q=IDSeries_*').then(res => res).then(res => console.log(res))
</code>```

This will return you the products that include this tag combination and you can append it with javascript.

So you will populate the products with javascript.

GraphQL

You can use the Storefront GraphQL API to make a request and get products by specific tag, like so:

```<code>{
    products(first: 10, query:"tag:>'IDSeries_'"){
    edges {
      cursor
      node {
        title
      }
    }
  }
}
</code>```

This will require understanding of GraphQL and especially their Store-Front API (not the Admin API).

For a store with 30k products each with five tags (so 150k tags in total).

Does tags have any limitation?

The all_tags object for the collection can return up to 1000 tags, the rest will be skipped. They need to be unique tags, repeatable tags doesn't count.

Other than that there are no limitations to my knowledge.

Body:
By starting from this point https://www.shopify.com/partners/blog/related-products
I end up to this custom and working code:

    {% comment %}
     Get dynamic tag from product and create static collection handle
    {% endcomment %}
        {% for tag in product.tags %}
            {% if tag contains 'IDSeries_' %}
                {% assign ser_tag = tag %}

{{ ser_tag | remove: "IDSeries_" | prepend: "Go to products with Serie ID number:" }}

            {% endif %}
        {% endfor %}

    {% comment %}
     Return products by using the extracted tag
    {% endcomment %}
        {% for product in collections.all.products %}
            {% if product.tags contains ser_tag %}
                {{ product.title }}
            {% endif %}
        {% endfor %}

This above does work. But it's not the solution!

because limited memory, it works only for the first bunch of products and not for all.

By considering I have twenty five thousands products all with an incremental "IDSeries_'INT'"

My goal is: to show products with same specific "IDSeries_'INT'".

Since when this already happens at collection tag url like this

I was wondering if I can return products (into a section products) that are already filtered at the collection handle tag url layer.

So at Themes/Debut/Sections/product-template.liquid

I am trying the following with no luck:

{% assign collection_handle = ser_tag %}
    {% for product in collections.all[collection_handle].products %}
        {{ product.title }}
    {% endfor %}

Question:

Any clue on how to achieve a consistent result for such a big stock of products?

Extra question:

For a store with 30k products each with five tags (so 150k tags in
total).

Does tags have any limitation?

I also created a Shopify community topic https://community.shopify.com/c/Technical-Q-A/Related-products-based-on-grouping-tags-limit-memory-Use-instead/td-p/759705

Body:
I can think of two solutions for your problem, that doesn't affect the speed of the site.

Search based + Javascript

The search page on Shopify can search for tags as well.

So if you make a fetch request to the search page like so:

fetch('/search?q=IDSeries_*').then(res => res).then(res => console.log(res))

This will return you the products that include this tag combination and you can append it with javascript.

So you will populate the products with javascript.

GraphQL

You can use the Storefront GraphQL API to make a request and get products by specific tag, like so:

{
    products(first: 10, query:"tag:>'IDSeries_'"){
    edges {
      cursor
      node {
        title
      }
    }
  }
}

This will require understanding of GraphQL and especially their Store-Front API (not the Admin API).

For a store with 30k products each with five tags (so 150k tags in total).

Does tags have any limitation?

The all_tags object for the collection can return up to 1000 tags, the rest will be skipped. They need to be unique tags, repeatable tags doesn't count.

Other than that there are no limitations to my knowledge.


问:
Azure Application Gateway : Backend server certificate expired. Please upload a valid certificate
We have an Azure Application Gateway V2 setup with WAF feature enabled. We ran into trouble when suddenly, the health of all our backend pools (3 in our case) started showing unhealthy and the error was being shown when we checked backend health:

Backend server certificate expired. Please upload a valid certificate.

Now, the same certificate is applied on application gateway and on the backend pool servers/VMs. We had to switch to non-SSL port for our backend servers to make the problem go away.

I am not able to pinpoint the problem as if any certificate is expired when applied to backend pool VM should give the same error once applied to the application gateway itself. Can someone help to identify the actual root cause of the problem and why it is showing error only at the backend pool level?

Very important thing is that the certificates being shown in browser when the backend pool URL is opened is showing still more than 2 months before it expires.

Thanks.

答:
I can't comment as I have not enough reputation point but this might be connected to the fact that Sectigo's legacy AddTrust External CA Root certificate expires on May 30, 2020
https://support.sectigo.com/articles/Knowledge/Sectigo-AddTrust-External-CA-Root-Expiring-May-30-2020
In my case, the browser was also showing that everything is ok, but HttpClient responsible for doing the healtheck was not able to connect to the endpoint. What is interesting is the fact that I wasn't able to hit the endpoint with HttpClient running on dotnet core 2.1 but on dotnetcore 3.1 everything was fine</p>


问:
create an alert using css, jquery/javascript arrays or switch
I'm doing some experimenting. So this may look bad to javascript experts here. But I'm trying to learn.

I have a header div that will show a larger image when the user mouses over each thumbnail image. I used jQuery to create this effect. The header div contains a button. Once the button is clicked, an alert will pop up to tell the user the artist's name of image. The button is wired to an ID of a paragraph. Problem is, my code is not working. I don't want to use "onclick" inline javascript (which is what I am using to call the showArtistname() function). I want unobtrusive javascript like jQuery is. I'm not sure how to do this. I don't know if I should use an array or if I'm even approaching this correctly. Well, it's not correct, because it's not working...

Here is my jQuery code:

```<code>$(function(){
$("a:has(img.small)").mouseover(function(){
var bigImage= $(this).attr("href");
$("#heading").attr({src: bigImage});
return false;
});

});
</code>```

Here is my javascript code:

```<code>function showArtistname(){

var a = document.getElementById   ("bluesails", "purplemountains", "bigsky", "nightlights", "fireysunset", "brilliantsunrise").innerHTML;

switch(a) {
case "bluesails":
    alert("Arthur MacKenzie")
    break
case "purplemountains":
    alert("Maggie Laing")
    break

case "bigsky":
    alert("Arthur MacKenzie")
    break

case "nightlights":
    alert("Aria Soriano")
    break

case "fireysunset":
    alert("Felix Buckley")
    break

case "brilliantsunrise":
    alert("Felix Buckley")

}
}
</code>```

Here is my HTML:

```<code><div class="container_12" id="_container">

<div class="grid_12" id="12_header" >

    <div class="hc_left_pic"> <img src="images/01_md.jpg" id="heading" alt="Big Image." />
 <div id="showImage" onclick="showArtistname()"></div>
  </a></div>
</div>

<div class="clear"></div>

<div class="grid_4" id="artist_container1">
<a href="images/01_md.jpg"><img src="images/01_sm.jpg" width="100" height="100" class="small" alt="Small image Blue Sails" /></a>
    <p class="text" id="bluesails">Blue Sails</p>
</div>

<div class="grid_4" id="artist_container2">
<a href="images/02_md.jpg"><img src="images/02_sm.jpg" width="100" height="100" class="small" alt="Small Image Purple Mountains"/></a>
    <p class="text" id="purplemountains">Purple Mountains</p>
</div>

<div class="grid_4" id="artist_container3">
<a href="images/03_md.jpg"><img src="images/03_sm.jpg" width="100" height="100" class="small" alt="Small Image Big Sky"/></a>
    <p class="text" id="bigsky">Big Sky</p>
</div>

<div class="clear"></div>

<div class="grid_4" id="artist_container4">
<a href="images/04_md.jpg"><img src="images/04_sm.jpg" width="100" height="100" class="small" alt="Small Image Night Lights" /></a>
    <p class="text" id="nightlights">Night Lights</p>
</div>

 <div class="grid_4" id="artist_container5">
<a href="images/05_md.jpg"><img src="images/05_sm.jpg" width="100" height="100" class="small"  alt="Small Product Image Firey Sunset"/></a>
    <p class="text" id="fireysunset">Firey Sunset</p>
</div>

<div class="grid_4" id="artist_container6">
<a href="images/06_md.jpg"><img src="images/06_sm.jpg" width="100" height="100" class="small"  alt="Small Product Image Brilliant Sunrise"/></a>
    <p class="text" id="brilliantsunrise">Brilliant Sunrise</p>
</div>
</code>```

Here is my CSS:

```<code>.container_12 .grid_4 {
  width: 274px;
  height: 370px;
  background-color:#ccc;
  border: 3px solid #999;
  padding-left:10px;
  padding-right:10px;
  padding-bottom:10px;
 }

#showImage{
margin: -170px 20px 80px 700px;
width: 176px;
height: 48px;
background:url(../images/showimage.jpg);
position:relative;
z-index:100;
}

 .grid_4 img {
position:relative;
left:100px;
top:20px;
padding:0 0 60px 0;
border:none;

}
.grid_4 p {
position:relative;
text-align:center;
}

p.text {
font-family:Arial, Helvetica, sans-serif;
font-size:.75em;
color:#000;
line-height:1.25em;
font-weight:bold;
}

#12_header {
display: inline;
background-color:#e5e5e5;
border: 3px solid #bfbfbf;
height:225px;
font-family:Arial, Helvetica, sans-serif;
font-size:;
color:#000;
font-weight:bold;
line-height:1.2em;

}

.hc_left_pic {
float:left;
margin-top:15px;
background-color:#e5e5e5;
border: 3px solid #bfbfbf;
width:935px;
height:250px;
}
</code>```

I hope I've given enough information to get a solution to this.

Thanks

答:
The problem is in your showArtistname function: it always gives the variable a the innerHtml of the element with id "bluesails".

Now there are many possible solutions to achieve your goal. Here is mine:```<code>
// JQuery part of the code
$(function(){
     $("a:has(img.small)").mouseover(function(){
        var bigImage= $(this).attr("href");
         $("#heading").attr({src: bigImage});
         $("#_container").attr({hoveredImage: $(this)});  // Extends your container div with a hoveredImage property, which returns the currently hovered image or undefined
         return false;
     });
  });<br>
// Plain JavaScript part of the code
oArtistNamesByImageId = {
"bluesails":        "Arthur MacKenzie",
"purplemountains":  "Maggie Laing",
"bigsky":           "Arthur MacKenzie",
"nightlights":      "Aria Soriano",
"fireysunset":      "Felix Buckley",
"brilliantsunrise": "Felix Buckley"
};<br>
function showArtistname(){
    var img = document.getElementById("_container").hoveredImage;
    if(img)alert(oArtistNamesByImageId[img.id]);
}</code>```

Body:
I'm doing some experimenting. So this may look bad to javascript experts here. But I'm trying to learn.

I have a header div that will show a larger image when the user mouses over each thumbnail image. I used jQuery to create this effect. The header div contains a button. Once the button is clicked, an alert will pop up to tell the user the artist's name of image. The button is wired to an ID of a paragraph. Problem is, my code is not working. I don't want to use "onclick" inline javascript (which is what I am using to call the showArtistname() function). I want unobtrusive javascript like jQuery is. I'm not sure how to do this. I don't know if I should use an array or if I'm even approaching this correctly. Well, it's not correct, because it's not working...

Here is my jQuery code:

$(function(){
$("a:has(img.small)").mouseover(function(){
var bigImage= $(this).attr("href");
$("#heading").attr({src: bigImage});
return false;
});

});

Here is my javascript code:

function showArtistname(){

var a = document.getElementById   ("bluesails", "purplemountains", "bigsky", "nightlights", "fireysunset", "brilliantsunrise").innerHTML;

switch(a) {
case "bluesails":
    alert("Arthur MacKenzie")
    break
case "purplemountains":
    alert("Maggie Laing")
    break

case "bigsky":
    alert("Arthur MacKenzie")
    break

case "nightlights":
    alert("Aria Soriano")
    break

case "fireysunset":
    alert("Felix Buckley")
    break

case "brilliantsunrise":
    alert("Felix Buckley")

}
}

Here is my HTML:

Blue Sails

Purple Mountains

Big Sky

Night Lights

Firey Sunset

Brilliant Sunrise

Here is my CSS:

.container_12 .grid_4 {
  width: 274px;
  height: 370px;
  background-color:#ccc;
  border: 3px solid #999;
  padding-left:10px;
  padding-right:10px;
  padding-bottom:10px;
 }

#showImage{
margin: -170px 20px 80px 700px;
width: 176px;
height: 48px;
background:url(../images/showimage.jpg);
position:relative;
z-index:100;
}

 .grid_4 img {
position:relative;
left:100px;
top:20px;
padding:0 0 60px 0;
border:none;

}
.grid_4 p {
position:relative;
text-align:center;
}

p.text {
font-family:Arial, Helvetica, sans-serif;
font-size:.75em;
color:#000;
line-height:1.25em;
font-weight:bold;
}

#12_header {
display: inline;
background-color:#e5e5e5;
border: 3px solid #bfbfbf;
height:225px;
font-family:Arial, Helvetica, sans-serif;
font-size:;
color:#000;
font-weight:bold;
line-height:1.2em;

}

.hc_left_pic {
float:left;
margin-top:15px;
background-color:#e5e5e5;
border: 3px solid #bfbfbf;
width:935px;
height:250px;
}

I hope I've given enough information to get a solution to this.

Thanks

Body:
The problem is in your showArtistname function: it always gives the variable a the innerHtml of the element with id "bluesails".

Now there are many possible solutions to achieve your goal. Here is mine:

// JQuery part of the code
$(function(){
     $("a:has(img.small)").mouseover(function(){
        var bigImage= $(this).attr("href");
         $("#heading").attr({src: bigImage});
         $("#_container").attr({hoveredImage: $(this)});  // Extends your container div with a hoveredImage property, which returns the currently hovered image or undefined
         return false;
     });
  });

// Plain JavaScript part of the code
oArtistNamesByImageId = {
"bluesails":        "Arthur MacKenzie",
"purplemountains":  "Maggie Laing",
"bigsky":           "Arthur MacKenzie",
"nightlights":      "Aria Soriano",
"fireysunset":      "Felix Buckley",
"brilliantsunrise": "Felix Buckley"
};

function showArtistname(){
    var img = document.getElementById("_container").hoveredImage;
    if(img)alert(oArtistNamesByImageId[img.id]);
}


问:
Install the package from the specific channel with conda
I need the version 5.12 of the qt package in anaconda, but version 5.9.7 is installed.

```<code>>>> conda list qt -f
# packages in environment at /PATH/anaconda3/env/my_env
#
# Name                    Version                   Build  Channel
qt                        5.9.7                h5867ecd_1
</code>```

Since the latest version of qt in the default channel anaconda is 5.9.7(https://anaconda.org/anaconda/qt), I want to install qt package from the channel conda-forge, which has the version 5.12.5(https://anaconda.org/conda-forge/qt).

So I tried to install qt from conda-forge channel with this command.

```<code>>>> conda install qt -c conda-forge --override-channels
</code>```

But conda didn't install qt from the new channel and printed that all packages are already installed.

```<code>Collecting package metadata (current_repodata.json): done
Solving environment: done

# All requested packages already installed.
</code>```

FYI, my channel configuration in .condarc is

```<code>channels:
  - defaults
  - conda-forge
channel_priority: disabled
</code>```

Why does not conda update qt and how to install qt from the channel conda-forge?

答:
Your .condarc file is mis-specified if you want conda-forge to take priority.  You want this:

channels:
  - conda-forge
  - defaults
channel_priority: flexible  # or 'strict'
```</li>
<li><p>If you want a specific version, try specifying the version in your command.  You can even both version and specific build id:</p>

<pre class="lang-sh prettyprint-override"><code># This effectively means qt 5.12.*
conda install -c conda-forge qt=5.12

# You can also specify the exact version and build ID, if you happen to know them:
conda install -c conda-forge qt=5.12.5=hd8c4c69_1
</code>```

Body:
I need the version 5.12 of the qt package in anaconda, but version 5.9.7 is installed.

>>> conda list qt -f
# packages in environment at /PATH/anaconda3/env/my_env
#
# Name                    Version                   Build  Channel
qt                        5.9.7                h5867ecd_1

Since the latest version of qt in the default channel anaconda is 5.9.7(https://anaconda.org/anaconda/qt), I want to install qt package from the channel conda-forge, which has the version 5.12.5(https://anaconda.org/conda-forge/qt).

So I tried to install qt from conda-forge channel with this command.

>>> conda install qt -c conda-forge --override-channels

But conda didn't install qt from the new channel and printed that all packages are already installed.

Collecting package metadata (current_repodata.json): done
Solving environment: done

# All requested packages already installed.

FYI, my channel configuration in .condarc is

channels:
  - defaults
  - conda-forge
channel_priority: disabled

Why does not conda update qt and how to install qt from the channel conda-forge?

Body:
Your .condarc file is mis-specified if you want conda-forge to take priority.  You want this:

channels:
  - conda-forge
  - defaults
channel_priority: flexible  # or 'strict'

If you want a specific version, try specifying the version in your command.  You can even both version and specific build id:

# This effectively means qt 5.12.*
conda install -c conda-forge qt=5.12

# You can also specify the exact version and build ID, if you happen to know them:
conda install -c conda-forge qt=5.12.5=hd8c4c69_1


问:
AVAudioEngine connect - code exiting function without throwing error
This may well be me being ignorant of swift but I am confused..

I have the following (simplified) code - note I have pulled a lot out of it as it (generally) functions as expected:

```<code>engine = AVAudioEngine() //engine being a class variable

AVAudioUnit.instantiate(with: mixerDesc, options: [.loadOutOfProcess], completionHandler: {(audioUnit, auError) in
    //configure matrix mixer
    self.matrixMixer = au
    engine.attach(au)

    print("make connections")
    engine.connect(engine.inputNode, to: au, format: inputFormat)
    engine.connect(au, to: engine.mainMixerNode, format: inputFormat)
    print("connections done")

    try! engine.start()
}
</code>```

This code works 99% of the time, however there are occasions (mainly when the default input/output device changes) that an error is being generated when the connections are being made. The thing I don't understand is that this error is causing the function to exit at the point the error happens (when the connections are made), but doesn't cause the application to terminate - I am asuming this is because the error is just killing that thread.

Is there any way to catch that error? I've tried adding a defer {} to the start of the function, but this isn't called either. It's frustrating as it's meaning the application is getting out of sync and I'm not clear how to catch it.

FYI the error being thrown is:

```<code>2020-05-31 22:33:22.219189+0100 StageSound[20887:289670] [General] required condition is false: IsFormatSampleRateAndChannelCountValid(hwFormat)
2020-05-31 22:33:22.221812+0100 StageSound[20887:289670] [General] (
    0   CoreFoundation                      0x00007fff332f1be7 __exceptionPreprocess + 250
    1   libobjc.A.dylib                     0x00007fff6c0c95bf objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff3331ad98
</code>```

and the crash log continues..

答:
It looks like an NSException is thrown from Objective-C code.
You cannot catch NSExceptions directly from Swift but there is a way by creating a bridge between Objective-C and Swift. This way you can convert NSException into something Swift understands (NSError for example).

For details about this bridging have a look at: https://stackoverflow.com/a/36454808

Body:
This may well be me being ignorant of swift but I am confused..

I have the following (simplified) code - note I have pulled a lot out of it as it (generally) functions as expected:

engine = AVAudioEngine() //engine being a class variable

AVAudioUnit.instantiate(with: mixerDesc, options: [.loadOutOfProcess], completionHandler: {(audioUnit, auError) in
    //configure matrix mixer
    self.matrixMixer = au
    engine.attach(au)

    print("make connections")
    engine.connect(engine.inputNode, to: au, format: inputFormat)
    engine.connect(au, to: engine.mainMixerNode, format: inputFormat)
    print("connections done")

    try! engine.start()
}

This code works 99% of the time, however there are occasions (mainly when the default input/output device changes) that an error is being generated when the connections are being made. The thing I don't understand is that this error is causing the function to exit at the point the error happens (when the connections are made), but doesn't cause the application to terminate - I am asuming this is because the error is just killing that thread.

Is there any way to catch that error? I've tried adding a defer {} to the start of the function, but this isn't called either. It's frustrating as it's meaning the application is getting out of sync and I'm not clear how to catch it.

FYI the error being thrown is:

2020-05-31 22:33:22.219189+0100 StageSound[20887:289670] [General] required condition is false: IsFormatSampleRateAndChannelCountValid(hwFormat)
2020-05-31 22:33:22.221812+0100 StageSound[20887:289670] [General] (
    0   CoreFoundation                      0x00007fff332f1be7 __exceptionPreprocess + 250
    1   libobjc.A.dylib                     0x00007fff6c0c95bf objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff3331ad98

and the crash log continues..


问:
How to use ruby 2.7 on my Ruby on Rails applications
I updating my applications that are running in AWS OpsWorks so I need to use Ruby 2.7, but the newest version showing is 2.6.
Can I force my stack to use 2.7 version?</p>

答:
According to this page: https://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-ruby.html

Version 2.7 is not yet available for OpsWorks.


问:
How to assign an ID to identify duplicate array elements?
I have a multi-dimensional array which contains a string and another array for each element.

```<code>duplicates =
[["link_A", [247936, 672212, 248156, 671720]],
 ["link_B", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["link_C", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["link_D", [247471, 671767, 247567, 671846]],
 ["link_E", [247471, 671767, 247567, 671846]],    # Same coordinates as previous line
 ["link_F", [247567, 671846, 247775, 671680]],
 ["link_G", [247567, 671846, 247775, 671680]]]    # Same coordinates as previous line
</code>```

I have my data in a format that I want in order to go through the "duplicates" array using "each" and export the data to .csv.

The only thing I want at this point is for an assigned ID/number for every duplicate that has the same coordinates. Happy to have it as an element in the array, such as:

Desired Output:

```<code>duplicates =
[["1", "link_A", [247936, 672212, 248156, 671720]],
 ["1", "link_B", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["1", "link_C", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["2", "link_D", [247471, 671767, 247567, 671846]],
 ["2", "link_E", [247471, 671767, 247567, 671846]],    # Same coordinates as previous line
 ["3", "link_F", [247567, 671846, 247775, 671680]],
 ["3", "link_G", [247567, 671846, 247775, 671680]]]    # Same coordinates as previous line
</code>```

What's the best way of going about this?

Many thanks.

Edit:

Thank you for the responses. The current 3 answers (from 1. Siim Liiser, 2. Cary Swoveland and 3. iGian) all work well for me with slight variation (I believe - correct me if I'm wrong!):

Doesn't mutate "duplicates" // Doesn't assume in order

Doesn't mutate "duplicates" // Assumes duplicates in order

Mutates "duplicates" // Doesn't assume in order

I didn't mention it in the question but I was okay with duplicates itself being mutated. I had previously used "group_by" (little bit more info below) to create duplicates so the order shouldn't really matter either. Thanks again.

Original array (seen as 'segment_store' below) at very start holds the link name (e.g. "link_A") and an array of coords (two XY coords) - these represent link segments. As I was looking to find duplicates, I used:

```<code>duplicates = segment_store.group_by{|i| i[1]}.select{|k,v| v.length > 1}.values.flatten(1)
</code>```

to get duplicates as seen in original question (pre-edit).

Body:
I have a multi-dimensional array which contains a string and another array for each element.

duplicates =
[["link_A", [247936, 672212, 248156, 671720]],
 ["link_B", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["link_C", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["link_D", [247471, 671767, 247567, 671846]],
 ["link_E", [247471, 671767, 247567, 671846]],    # Same coordinates as previous line
 ["link_F", [247567, 671846, 247775, 671680]],
 ["link_G", [247567, 671846, 247775, 671680]]]    # Same coordinates as previous line

I have my data in a format that I want in order to go through the "duplicates" array using "each" and export the data to .csv.

The only thing I want at this point is for an assigned ID/number for every duplicate that has the same coordinates. Happy to have it as an element in the array, such as:

Desired Output:

duplicates =
[["1", "link_A", [247936, 672212, 248156, 671720]],
 ["1", "link_B", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["1", "link_C", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["2", "link_D", [247471, 671767, 247567, 671846]],
 ["2", "link_E", [247471, 671767, 247567, 671846]],    # Same coordinates as previous line
 ["3", "link_F", [247567, 671846, 247775, 671680]],
 ["3", "link_G", [247567, 671846, 247775, 671680]]]    # Same coordinates as previous line

What's the best way of going about this?

Many thanks.

Edit:

Thank you for the responses. The current 3 answers (from 1. Siim Liiser, 2. Cary Swoveland and 3. iGian) all work well for me with slight variation (I believe - correct me if I'm wrong!):

Doesn't mutate "duplicates" // Doesn't assume in order

Doesn't mutate "duplicates" // Assumes duplicates in order

Mutates "duplicates" // Doesn't assume in order

I didn't mention it in the question but I was okay with duplicates itself being mutated. I had previously used "group_by" (little bit more info below) to create duplicates so the order shouldn't really matter either. Thanks again.

Original array (seen as 'segment_store' below) at very start holds the link name (e.g. "link_A") and an array of coords (two XY coords) - these represent link segments. As I was looking to find duplicates, I used:

duplicates = segment_store.group_by{|i| i[1]}.select{|k,v| v.length > 1}.values.flatten(1)

to get duplicates as seen in original question (pre-edit).

Body:
That can be done with one pass through duplicates:

duplicates.each_with_object([]) do |(link,a),arr|
  arr <<
    if arr.empty?
      ['1', link, a]
    else
      i, _, b = arr.last
      [a == b ? i : (i.to_i+1).to_s, link, a]
    end
end
  #=> [["1", "link_A", [247936, 672212, 248156, 671720]],
  #    ["1", "link_B", [247936, 672212, 248156, 671720]],
  #    ["1", "link_C", [247936, 672212, 248156, 671720]],
  #    ["2", "link_D", [247471, 671767, 247567, 671846]],
  #    ["2", "link_E", [247471, 671767, 247567, 671846]],
  #    ["3", "link_F", [247567, 671846, 247775, 671680]],
  #    ["3", "link_G", [247567, 671846, 247775, 671680]]]

One could alternatively write:

duplicates.
  drop(1).each_with_object([["1",*duplicates.first]]) do |(link,a),arr|
  i, _, b = arr.last
  arr << [a == b ? i : (i.to_i+1).to_s, link, a]
end


问:
Remove unwanted space inside a column while placing image at end in flutter?
am new for flutter development i have got struck in placing the image in corner of the column which i have shown in the image

Need to remove the spacing  which i have marked with arrow how to do this? now let me post what i tried so far:

```<code>Card(
                  margin: EdgeInsets.all(10),
                  clipBehavior: Clip.antiAlias,
                  shape: RoundedRectangleBorder(
                    side: BorderSide(color: Colors.white, width: 1),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  color: Colors.white,
                  child: Container(
                    width: MediaQuery.of(context).size.width / 2.3,
                    height: 200,
                    // color: Colors.pink,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          color: Colors.red,
                          child: Image.asset('assets/intersection_png.png',
                          fit: BoxFit.cover,),
                        )
                      ],
                    ),
                  ),
                )
</code>```

Thanks in advance!!

答:
The image you posted has padding around it. Thus, Flutter displays it with padding. To fix this, you can open it in an image editor like GIMP and shrink the image size.

Here is the same image but with removed padding. Try this one out:

This comes with a downside, as it looks like the image had the padding so it could display elevation. You can either remove the elevation completely from the image and add it in Flutter yourself or you can keep the original image and use something like a Stack in combination with a Positioned widget to position it (but that would be a whole different question on its own).

As far as I can tell, none of the other answers will actually do what you desire due to your actual image, but perhaps I am wrong.

Edit: I also just realized I made a slight mistake when changing your image--I removed the padding on the left and bottom side. You can fix your original image yourself in an image editor and remove just top and right side padding.

Body:
am new for flutter development i have got struck in placing the image in corner of the column which i have shown in the image

Need to remove the spacing  which i have marked with arrow how to do this? now let me post what i tried so far:

Card(
                  margin: EdgeInsets.all(10),
                  clipBehavior: Clip.antiAlias,
                  shape: RoundedRectangleBorder(
                    side: BorderSide(color: Colors.white, width: 1),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  color: Colors.white,
                  child: Container(
                    width: MediaQuery.of(context).size.width / 2.3,
                    height: 200,
                    // color: Colors.pink,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          color: Colors.red,
                          child: Image.asset('assets/intersection_png.png',
                          fit: BoxFit.cover,),
                        )
                      ],
                    ),
                  ),
                )

Thanks in advance!!