问:
Need help iterating over python dictionary values
I'm working on a program to search through a dictionaries value set and perform a method on values that match a user input. I have to compare and sort these values.

This is the code I'm working with right now

Code for value search and compare (very rough)

```<code>import nation
import pickle

KK = 1000000

pickle_in = open("nationsDict.dat","rb")
d = pickle.load(pickle_in)

k = raw_input("Enter a continent: ")

for value in d.values():
    if k in d.values()[0]:
        print d.values()[0]
</code>```

Code for Nation class

```<code>class Nations:

    KK = 1000000

    def __init__(self, ctry, cont, pop, area):
        self.country = ctry
        self.continent = cont
        self.population = float(pop)
        self.area = float(area)

    def popDensity(self):
        popDensity = (self.population*self.KK) / self.area
        popDensity = str(round(popDensity, 2))
        return popDensity
</code>```

Code for creating pickle dictionary

```<code>import nation
import pickle

i=0
dictUN = {}

with open('UN.txt') as f:
    for line in f:

        """Data get from file"""
        elements = line.strip().split(",")

        n = nation.Nations(elements[0],elements[1],elements[2],elements[3])

        """Density"""
        n.popDensity()
        print "The density of", n.country, "is",n.popDensity(),"people per square mile."

        """Dictionary creation"""
        dictVal = (n.continent, n.population, n.area)
        dictUN.update({n.country: dictVal})

pickle_out = open("nationsDict.dat", "wb")
pickle.dump(dictUN, pickle_out)
pickle_out.close()
</code>```

Here's a snippet from UN.txt

```<code>Mauritania,Africa,3.5,397954
Mauritius,Africa,1.3,787
Mexico,North America,120.3,761606
Micronesia,Australia/Oceania,.11,271
Monaco,Europe,.031,0.76
Mongolia,Asia,3.0,603909
Montenegro,Europe,.65,5019
Morocco,Africa,33.0,172414
</code>```

My problems at this point are pretty contained to the value search and compare. Specifically, my program has to

Allow the user to search a continent (first element in value list)

Perform the method, Nations.popDensity (contained in nation class) on all matching countries

Compare the nations and return the top 5 density values per continent

I would say my one big question is how to handle the search of a dictionary by an element in a value. I've also considered about making a temp dictionary with the continent element as the key, but I'm not sure that would make my life any easier as I have to perform the popDensity method on it.

Any help is appreciated, Thanks!

答:
Initialize pandas series object

Iterate through the dictionary.

If the continent matches:

a. calculate the population density.

b. if the value is larger than the smallest value in the pandas series:

i. remove the last entry

ii.append the value into the pandas series values and the country to the index

iii. sort the pandas series object ascending = False

If you're going to do this repeatedly, then creating a continent->country dictionary definitely will save time.

Body:
I'm working on a program to search through a dictionaries value set and perform a method on values that match a user input. I have to compare and sort these values.

This is the code I'm working with right now

Code for value search and compare (very rough)

import nation
import pickle

KK = 1000000

pickle_in = open("nationsDict.dat","rb")
d = pickle.load(pickle_in)

k = raw_input("Enter a continent: ")

for value in d.values():
    if k in d.values()[0]:
        print d.values()[0]

Code for Nation class

class Nations:

    KK = 1000000

    def __init__(self, ctry, cont, pop, area):
        self.country = ctry
        self.continent = cont
        self.population = float(pop)
        self.area = float(area)

    def popDensity(self):
        popDensity = (self.population*self.KK) / self.area
        popDensity = str(round(popDensity, 2))
        return popDensity

Code for creating pickle dictionary

import nation
import pickle

i=0
dictUN = {}

with open('UN.txt') as f:
    for line in f:

        """Data get from file"""
        elements = line.strip().split(",")

        n = nation.Nations(elements[0],elements[1],elements[2],elements[3])

        """Density"""
        n.popDensity()
        print "The density of", n.country, "is",n.popDensity(),"people per square mile."

        """Dictionary creation"""
        dictVal = (n.continent, n.population, n.area)
        dictUN.update({n.country: dictVal})

pickle_out = open("nationsDict.dat", "wb")
pickle.dump(dictUN, pickle_out)
pickle_out.close()

Here's a snippet from UN.txt

Mauritania,Africa,3.5,397954
Mauritius,Africa,1.3,787
Mexico,North America,120.3,761606
Micronesia,Australia/Oceania,.11,271
Monaco,Europe,.031,0.76
Mongolia,Asia,3.0,603909
Montenegro,Europe,.65,5019
Morocco,Africa,33.0,172414

My problems at this point are pretty contained to the value search and compare. Specifically, my program has to

Allow the user to search a continent (first element in value list)

Perform the method, Nations.popDensity (contained in nation class) on all matching countries

Compare the nations and return the top 5 density values per continent

I would say my one big question is how to handle the search of a dictionary by an element in a value. I've also considered about making a temp dictionary with the continent element as the key, but I'm not sure that would make my life any easier as I have to perform the popDensity method on it.

Any help is appreciated, Thanks!


来源: stackexchange

问:
How to prevent jquery global selector selects something outside of the Polymer element
I am trying to use a jquery based library within my Polymer element <my-element>. But once there are more than one of such <my-element> in one page, the library only selects first one because it is selecting an id that is unique within one instance of <my-element> but repeated in multiple ones. How to give jquery selector a domain so that it will only select within it?

答:
It doesn't work because jQuery's id selector is optimized to fetch just the first one:

Each id value must be used only once within a document. If more than
  one element has been assigned the same ID, queries that use that ID
  will only select the first matched element in the DOM. This behavior
  should not be relied on, however; a document with more than one
  element using the same ID is invalid.

You can pass jQuery selector's context as its second parameter (interestingly, if you pass multiple contexts, it selectes multiples ids):

// Initialize selected domains
$('#init-id', '.first-domain, .second-domain').initializeLibrary();

// Initialize all id in DOM
$('#init-id', '*').initializeLibrary();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="first-domain">
  <img id="init-id" />
</div>
<div class="second-domain">
  <img id="init-id" />
</div>
<div class="do-not-initialize-domain">
  <img id="init-id" />
</div></code>```

Alternatively, your component could initialize itself with Polymer.dom(this.root):

```<code><dom-module id="my-component">

  <template>
    My component - yay!
  </template>

  <script>

    Polymer({

      is: 'my-component',

      ready: function() {
        $(Polymer.dom(this.root)).initializeLibrary();
      }

    });

  </script>

</dom-module>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It doesn't work because jQuery's id selector is optimized to fetch just the first one:

Each id value must be used only once within a document. If more than
  one element has been assigned the same ID, queries that use that ID
  will only select the first matched element in the DOM. This behavior
  should not be relied on, however; a document with more than one
  element using the same ID is invalid.

You can pass jQuery selector's context as its second parameter (interestingly, if you pass multiple contexts, it selectes multiples ids):

// Initialize selected domains
$('#init-id', '.first-domain, .second-domain').initializeLibrary();

// Initialize all id in DOM
$('#init-id', '*').initializeLibrary();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="first-domain">
  <img id="init-id" />
</div>
<div class="second-domain">
  <img id="init-id" />
</div>
<div class="do-not-initialize-domain">
  <img id="init-id" />
</div>

Alternatively, your component could initialize itself with Polymer.dom(this.root):

<dom-module id="my-component">

  <template>
    My component - yay!
  </template>

  <script>

    Polymer({

      is: 'my-component',

      ready: function() {
        $(Polymer.dom(this.root)).initializeLibrary();
      }

    });

  </script>

</dom-module>


问:
There's an issue with Input in my Python code
so I'm a beginner in python and I was trying to get an input function to work. It looks to me like Python isn't taking the data I give it, like it's not reading user input correctly. here is my code:

```<code>var = input
    input("press ENTER to choose an app")
    if var==1:
        clock()
    elif var==2:
        oshelp()
    elif var==3:
        ebooks()
    elif var==4:
        what_is_new()
    else:
        print("Application Not Found.")
</code>```

right now, the IDLE just prints "Application Not Found" even when i type a valid number and I'm not sure why. can anyone help me with this? (please include examples). Thanks!

答:
Your issue occurs on the first line

var = input

You are setting var equal to the function input, not the returning value.

How you have it, if you were to write x = var("Enter: "), this would do the same as x = input("Enter: ").

You actually need to do var = input("Enter: "), but this will return a value, of type string, so when you compare this value to 1, even if the user enters 1, it will return false, as they are different data types.

You can either cast the input to an integer value, or compare the inputted value to strings.

```<code>var = input("Enter: ")
if var == "1":
</code>```

or

```<code>var = int(input("Enter: "))
if var == 1
</code>```

I would personally use the top one, as the program wouldn't crash if entered a non-int value.

Hope this helps!

Body:
so I'm a beginner in python and I was trying to get an input function to work. It looks to me like Python isn't taking the data I give it, like it's not reading user input correctly. here is my code:

var = input
    input("press ENTER to choose an app")
    if var==1:
        clock()
    elif var==2:
        oshelp()
    elif var==3:
        ebooks()
    elif var==4:
        what_is_new()
    else:
        print("Application Not Found.")

right now, the IDLE just prints "Application Not Found" even when i type a valid number and I'm not sure why. can anyone help me with this? (please include examples). Thanks!

Body:
Your issue occurs on the first line

var = input

You are setting var equal to the function input, not the returning value.

How you have it, if you were to write x = var("Enter: "), this would do the same as x = input("Enter: ").

You actually need to do var = input("Enter: "), but this will return a value, of type string, so when you compare this value to 1, even if the user enters 1, it will return false, as they are different data types.

You can either cast the input to an integer value, or compare the inputted value to strings.

var = input("Enter: ")
if var == "1":

or

var = int(input("Enter: "))
if var == 1

I would personally use the top one, as the program wouldn't crash if entered a non-int value.

Hope this helps!


问:
Printing items from a list in Python
I am trying to write a function in Python where I am given a list, l = [[2,3],[5,6],[4,8]], which contains other lists. I am supposed to print the first item in every list on one line with three spaces in between and the second item in every list in another line with also three spaces in between. I have made the following code - however it seems to print everything on one line, and I am not sure what I am doing wrong.

```<code>l = [[2,3],[5,6],[4,8]]
for item in l:
    print(item[0], end = '  ')
for obj in l:
    print(obj[1], end = '  ')
</code>```

答:
You can try this:

```<code>l = [[2,3],[5,6],[4,8]]
new_l = ["{}   {}   {}".format(*[b[i] for b in l]) for i in range(len(l[0]))]
for i in new_l:
   print(i)
</code>```

Output:

```<code>2   5   4
3   6   8
</code>```

Title: Printing items from a list in Python

Body:
I am trying to write a function in Python where I am given a list, l = [[2,3],[5,6],[4,8]], which contains other lists. I am supposed to print the first item in every list on one line with three spaces in between and the second item in every list in another line with also three spaces in between. I have made the following code - however it seems to print everything on one line, and I am not sure what I am doing wrong.

l = [[2,3],[5,6],[4,8]]
for item in l:
    print(item[0], end = '  ')
for obj in l:
    print(obj[1], end = '  ')

Body:
You can try this:

l = [[2,3],[5,6],[4,8]]
new_l = ["{}   {}   {}".format(*[b[i] for b in l]) for i in range(len(l[0]))]
for i in new_l:
   print(i)

Output:

2   5   4
3   6   8


Title: Calculate distance based on a lookup dataframe

Body:
I have a DataFrame and a lookup table. For a key in the DataFrame I would like to lookup the corresponding row in the lookup table and calculate the Euclidian distance for a number of columns. Mock data looks like

import pandas as pd
import numpy.random as rand

df = pd.DataFrame({'key':rand.randint(0, 5, 10),
                    'X': rand.randn(10),
                    'Y': rand.randn(10),
                    'Z': rand.randn(10)})

          X         Y         Z  key
0  0.163142  0.387871 -0.433157    3
1 -2.020957 -1.537615 -1.996704    0
2  1.249118  1.633246  0.028222    1
3 -0.019601  1.757136  0.787936    2
4 -0.039649  1.380557  0.123677    0
5  0.500814 -1.049591 -1.261868    3
6  1.175576 -0.310895  0.549420    0
7 -0.152696  0.139020  0.887219    2
8  0.491099  0.434652  0.791038    2
9 -0.231334  0.264414  0.913475    4

lookup = pd.DataFrame({'X': rand.randn(5),
                    'Y': rand.randn(5),
                    'Z': rand.randn(5)})

          X         Y         Z
0  0.242419 -0.630230 -0.254344
1  0.799573  0.354169  1.099456
2 -0.754582 -1.882192 -1.270382
3 -1.645707 -0.131905 -0.445954
4  0.743351  0.456220  0.975457
5  0.136197  0.278329 -2.336110

For example, the zeroth column has values

df.loc[0,'X':'Z'].values
[0.163142,0.387871,-0.433157]

the key is 3 so the row in the lookup is

lookup.iloc[3,:].values
[-1.645707 -0.131905 -0.445954]

The distance is

import numpy as np
np.linalg.norm(np.array([0.163142,0.387871,-0.433157]) - np.array([-0.754582, -1.882192, -1.270382]))
2.5877304853423202

I would like to do this for every row in df and return the value as a new column. Is there a slick way to do this?

Body:
IIUC.We using reindex here

[scipy.spatial.distance.euclidean(df1.iloc[:,:3].values[i], df2.reindex(df1.key).values[i]) for i in range(len(df1))]
Out[440]:
[1.882090741219987,
 2.9970046421720804,
 1.7279094194170017,
 4.245182958491777,
 2.0653635497011176,
 2.47293664565694,
 1.2723181192492703,
 3.0170858093764914,
 3.341996363028691,
 0.9953100819267331]


问:
get all tuples with maximum second value
How to fix the number of occurrence in a list of tuples and return an item with max value.

```<code>        given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

        expected = [('c',5),('a',3),('b',3)]
</code>```

How do you do this without doing anything to complex.

答:
A very straightforward approach is to group the tuples in a dictionary, then just get the maximum (letter, number) value from each letter key in the dictionary:

```<code>from collections import defaultdict
from operator import itemgetter

given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

d = defaultdict(list)
for key, value in given:
    d[key].append((key, value))

>>> print(dict(d))
{'b': [('b', 3)], 'a': [('a', 2), ('a', 3)], 'c': [('c', 5), ('c', 5)]}

>>> print([max(x[1], key = itemgetter(1)) for x in sorted(d.items())])
[('a', 3), ('b', 3), ('c', 5)]
</code>```

Without using external libraries:

```<code>given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

d = {}
for key, value in given:
    if key not in d:
        d[key] = []
    d[key].append((key, value))

>>> print(d)
{'b': [('b', 3)], 'a': [('a', 2), ('a', 3)], 'c': [('c', 5), ('c', 5)]}

>>> print([max(x[1], key = lambda x: x[1]) for x in sorted(d.items())])
[('a', 3), ('b', 3), ('c', 5)]
</code>```

Body:
How to fix the number of occurrence in a list of tuples and return an item with max value.

        given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

        expected = [('c',5),('a',3),('b',3)]

How do you do this without doing anything to complex.

Body:
A very straightforward approach is to group the tuples in a dictionary, then just get the maximum (letter, number) value from each letter key in the dictionary:

from collections import defaultdict
from operator import itemgetter

given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

d = defaultdict(list)
for key, value in given:
    d[key].append((key, value))

>>> print(dict(d))
{'b': [('b', 3)], 'a': [('a', 2), ('a', 3)], 'c': [('c', 5), ('c', 5)]}

>>> print([max(x[1], key = itemgetter(1)) for x in sorted(d.items())])
[('a', 3), ('b', 3), ('c', 5)]

Without using external libraries:

given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

d = {}
for key, value in given:
    if key not in d:
        d[key] = []
    d[key].append((key, value))

>>> print(d)
{'b': [('b', 3)], 'a': [('a', 2), ('a', 3)], 'c': [('c', 5), ('c', 5)]}

>>> print([max(x[1], key = lambda x: x[1]) for x in sorted(d.items())])
[('a', 3), ('b', 3), ('c', 5)]


问:
How to add zero to a time
I have a function that receives a time, in a string, and another number to add to the time:

```<code>def get_hours(hm):
   return int(hm.split(':')[0])

def get_minutes(hm):
   return int(hm.split(':')[1])

def add_minutes(hm, incr):
"""Increment the given time by the given amount of minutes.

Requires:
- hm str with a time represented as HH:MM;
- incr int with the number of minutes.
Ensures: str with a time represented as HH:MM, the result of incrementing hm by incr minutes.
"""
if get_minutes(hm)+incr>=60:
    if get_hours(hm)==23:
        return '00:'+str((get_minutes(hm)+incr)-60)
    else:
        return str(get_hours(hm)+1)+':'+str((get_minutes(hm)+incr)-60)
else:
    return str(get_hours(hm))+':'+str((get_minutes(hm)+incr))
</code>```

The problem is when the time is 16:05 or 04:06, it doesn't display the zeros, so it's just 16:5 and 4:6. How can i make this work?

答:
Generally, when working with time you want to use the built-in modules.</p>

```<code>import time
time.strftime('%H:%M')
'00:23'
</code>```

Title: How to add zero to a time

Body:
I have a function that receives a time, in a string, and another number to add to the time:

def get_hours(hm):
   return int(hm.split(':')[0])

def get_minutes(hm):
   return int(hm.split(':')[1])

def add_minutes(hm, incr):
"""Increment the given time by the given amount of minutes.

Requires:
- hm str with a time represented as HH:MM;
- incr int with the number of minutes.
Ensures: str with a time represented as HH:MM, the result of incrementing hm by incr minutes.
"""
if get_minutes(hm)+incr>=60:
    if get_hours(hm)==23:
        return '00:'+str((get_minutes(hm)+incr)-60)
    else:
        return str(get_hours(hm)+1)+':'+str((get_minutes(hm)+incr)-60)
else:
    return str(get_hours(hm))+':'+str((get_minutes(hm)+incr))

The problem is when the time is 16:05 or 04:06, it doesn't display the zeros, so it's just 16:5 and 4:6. How can i make this work?

Body:
Generally, when working with time you want to use the built-in modules.

import time
time.strftime('%H:%M')
'00:23'


问:
Error with composer install Facebook Ads SDK PHP
I am trying to install Facbeook Ads API following the tutorial here: Facebook Ads API SDK but when I run composer I get the following error:

```<code>composer update --lock
</code>```

Result:

```<code>Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: facebook/php-ads-sdk[2.8.1, dev-master].
    - Can only install one of: facebook/php-ads-sdk[2.8.2, dev-master].
    - Installation request for facebook/php-ads-sdk dev-master -> satisfiable by facebook/php-ads-sdk[dev-master].
    - Installation request for facebook/php-ads-sdk 2.8.* -> satisfiable by facebook/php-ads-sdk[2.8.1, 2.8.2].
</code>```

My composer.json:

```<code>{
    "name": "facebook/php-ads-sdk",
    "description": "PHP SDK for Facebook ads",
    "type": "library",
    "license": "Facebook Platform",
    "keywords": [
      "facebook",
      "ads",
      "sdk"
    ],
    "homepage": "https://developers.facebook.com/",
    "require-dev" : {
        "phpunit/phpunit": "~4.6",
        "symfony/finder": "~2.6"
    },
    "require": {
        "facebook/php-ads-sdk": "2.8.*"
    },
    "autoload": {
        "psr-4": {
            "FacebookAds\\": "src/FacebookAds/"
        }
    }
}
</code>```

If I try to run:

```<code>php composer.phar install --no-dev
</code>```

Result:

```<code>Could not open input file: composer.phar
</code>```

I am searching and I can not find the solution :(

Thank you!

答:
Try use

```<code>php composer.phar update facebook/php-ads-sdk
</code>```

If have errors

Try with

```<code>composer install
</code>```

instead of

```<code>php composer.phar install
</code>```

Body:
I am trying to install Facbeook Ads API following the tutorial here: Facebook Ads API SDK but when I run composer I get the following error:

composer update --lock

Result:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: facebook/php-ads-sdk[2.8.1, dev-master].
    - Can only install one of: facebook/php-ads-sdk[2.8.2, dev-master].
    - Installation request for facebook/php-ads-sdk dev-master -> satisfiable by facebook/php-ads-sdk[dev-master].
    - Installation request for facebook/php-ads-sdk 2.8.* -> satisfiable by facebook/php-ads-sdk[2.8.1, 2.8.2].

My composer.json:

{
    "name": "facebook/php-ads-sdk",
    "description": "PHP SDK for Facebook ads",
    "type": "library",
    "license": "Facebook Platform",
    "keywords": [
      "facebook",
      "ads",
      "sdk"
    ],
    "homepage": "https://developers.facebook.com/",
    "require-dev" : {
        "phpunit/phpunit": "~4.6",
        "symfony/finder": "~2.6"
    },
    "require": {
        "facebook/php-ads-sdk": "2.8.*"
    },
    "autoload": {
        "psr-4": {
            "FacebookAds\\": "src/FacebookAds/"
        }
    }
}

If I try to run:

php composer.phar install --no-dev

Result:

Could not open input file: composer.phar

I am searching and I can not find the solution :(

Thank you!

Body:
Try use

php composer.phar update facebook/php-ads-sdk

If have errors

Try with

composer install

instead of

php composer.phar install


问:
PM2 Heroku Deployment fails to launch application
I am following the directions here: http://pm2.keymetrics.io/docs/usage/use-pm2-with-cloud-providers/

Attempting to push a test app to Heroku and getting the error message:

[PM2] Spawning PM2 daemon with pm2_home=/app/.pm2
 2017-12-04T22:35:51.928946+00:00 app[web.1]: [PM2] PM2 Successfully daemonized
 2017-12-04T22:35:51.955730+00:00 app[web.1]: [PM2][ERROR] script not found : /app/dist/server.js
 2017-12-04T22:35:51.955882+00:00 app[web.1]: script not found : /app/dist/server.js
```
<p>My package.json:</p>
<pre class="lang-json prettyprint-override"><code>"scripts": {
  "preinstall": "npm install pm2 -g",
  "start": "pm2 start ./dist/server.js -i 1 --attach"
}
</code>```

This is the folder structure:

I am able to launch this locally by npm start. Any ideas or clues why this is happening?

答: Ensure that your dist folder is being pushed to git. Check the contents of .gitignore.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am following the directions here: http://pm2.keymetrics.io/docs/usage/use-pm2-with-cloud-providers/

Attempting to push a test app to Heroku and getting the error message:

[PM2] Spawning PM2 daemon with pm2_home=/app/.pm2
 2017-12-04T22:35:51.928946+00:00 app[web.1]: [PM2] PM2 Successfully daemonized
 2017-12-04T22:35:51.955730+00:00 app[web.1]: [PM2][ERROR] script not found : /app/dist/server.js
 2017-12-04T22:35:51.955882+00:00 app[web.1]: script not found : /app/dist/server.js

My package.json:

"scripts": {
  "preinstall": "npm install pm2 -g",
  "start": "pm2 start ./dist/server.js -i 1 --attach"
}

This is the folder structure:

I am able to launch this locally by npm start. Any ideas or clues why this is happening?


问:
Cloudformation error: Value of property NetworkInterfaces must be a list of objects
I get the error Value of property NetworkInterfaces must be a list of objects when referring to a NetworkInterface in a CloudFormation template.

Here is the relevant section:

  MyAppNetworkInterface:
    Type: AWS::EC2::NetworkInterface
    Properties:
      SubnetId: !Ref SubnetPrivate

MyApp:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t2.medium
      NetworkInterfaces:
        - !Ref MyAppNetworkInterface

答:
You can't do it that way.  Instead , create the two resources independently, then connect with a network interface attachment resource.

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html


问:
select and unselect tableview cell
I am going from tableViewControllerOne to tableViewControllerTwo. When this happens, tableViewControllerTwo scrolls to a certain cell. This works well, however, I want the cell to be selected or "highlighted" after the scroll, and then become unselected/unhighlighted so it looks like the rest of the cells.

After my segue, I have this statement called

    tableView.scrollToRow(at: indexPath, at: .top, animated: true)

I tried doing this instead

    tableView.selectRow(at: indexPath, animated: true, scrollPosition: .top)

but the cell would remain selected. I also tried this

    tableView.selectRow(at: indexPath, animated: true, scrollPosition: .top)
    tableView.deselectRow(at: indexPath, animated: true)

but they must both happen so quick that I never see the cell become selected.

答:
You can try delaying the deselectRow function in a way I found here:

```<code>let when = DispatchTime.now() + 2 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) {
   tableView.deselectRow(at: indexPath, animated: true)
}
</code>```

Title: select and unselect tableview cell

Body:
You can try delaying the deselectRow function in a way I found here:

let when = DispatchTime.now() + 2 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) {
   tableView.deselectRow(at: indexPath, animated: true)
}


答:
You need to add a print() in between your loops since you modified the default "\n" as the end character for the print.

Another way to achieve this would be:

```<code>>>> print(*a[0], sep = "   ")
>>> print(*b[1], sep = "   ")
</code>```

Title: Printing items from a list in Python

Body:
You need to add a print() in between your loops since you modified the default "\n" as the end character for the print.

Another way to achieve this would be:

>>> print(*a[0], sep = "   ")
>>> print(*b[1], sep = "   ")


问:
Multisort by distance
I have a multidimensional array and want to sort it by distance:

```<code>[clustermarkers] => [
            0 => [
                    0 => [
                      'name' => 'A',
                      'distance' => 10
                    ]
            ],
            1 => [
                    0 => [
                      'name' => 'B',
                      'distance' => 8
                    ]
            ],
            ...
];
</code>```

I have tried usort function, but something wrong:

```<code>usort($clustermarkers, function($a, $b) {
   return (int)$a['distance'] - (int)$b['distance'];
});
</code>```

答:
Almost:

```<code>usort($clustermarkers, function($a, $b) {
   return $a['distance'] > $b['distance']; //Distance ASC
});

usort($clustermarkers, function($a, $b) {
   return $a['distance'] < $b['distance']; //Distance DESC
});
</code>```

note the < and > operators and not casting to int

Title: Multisort by distance

Body:
I have a multidimensional array and want to sort it by distance:

[clustermarkers] => [
            0 => [
                    0 => [
                      'name' => 'A',
                      'distance' => 10
                    ]
            ],
            1 => [
                    0 => [
                      'name' => 'B',
                      'distance' => 8
                    ]
            ],
            ...
];

I have tried usort function, but something wrong:

usort($clustermarkers, function($a, $b) {
   return (int)$a['distance'] - (int)$b['distance'];
});

Body:
Almost:

usort($clustermarkers, function($a, $b) {
   return $a['distance'] > $b['distance']; //Distance ASC
});

usort($clustermarkers, function($a, $b) {
   return $a['distance'] < $b['distance']; //Distance DESC
});

note the < and > operators and not casting to int


问:
Using XACT_ABORT and TRY CATCH together in SQL Server break tSQLt Rollback
I am beginning to work with tSQLt unit tests for SQL Server in my production code.  Currently, I use Erland Sommarskog's error handling pattern for SQL Server.

```<code>USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.SommarskogRollback') IS NOT NULL
  DROP PROCEDURE dbo.SommarskogRollback;
GO

CREATE PROCEDURE dbo.SommarskogRollback
AS
BEGIN; /*Stored Procedure*/

  SET XACT_ABORT, NOCOUNT ON;

  BEGIN TRY;

    BEGIN TRANSACTION;

      RAISERROR('This is just a test.  Had this been an actual error, we would have given you some cryptic gobbledygook.', 16, 1);

    COMMIT TRANSACTION;

  END TRY
  BEGIN CATCH;

    IF @@TRANCOUNT > 0
      ROLLBACK TRANSACTION;

    THROW;

  END CATCH;

END;   /*Stored Procedure*/
GO
</code>```

Erland Sommarskog recommends that we always SET XACT_ABORT ON, because only then does SQL Server handle errors in a (mostly) consistent manner.

This creates a problem when using tSQLt, though.  tSQLt executes all tests inside an explicit transaction.  When the tests are complete the entire transaction rolls back.  This makes cleanup of the test artifacts completely painless. However, with XACT_ABORT ON, any error thrown inside a TRY block immediately dooms that transaction.  The transaction must roll back completely.  It cannot commit, and it cannot roll back to a save point.  In fact, nothing can write to the transaction log inside that session until the transaction rolls back.  However, tSQLt can't track the test results properly unless the transaction is open when the tests end.  tSQLt stops executing and throws a ROLLBACK ERROR for doomed transactions.  The test that failed shows a status of Error (rather than Success or Failure), and subsequent tests don't run.

Sebastian Meine, the creator of tSQLt, recommends a different error handling pattern.

```<code>USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.MeineRollback') IS NOT NULL
  DROP PROCEDURE dbo.MeineRollback;
GO

CREATE PROCEDURE dbo.MeineRollback
AS
BEGIN /*Stored Procedure*/

  SET NOCOUNT ON;

  /* We declare the error variables here, populate them inside the CATCH
   * block and then do our error handling after exiting the CATCH block
   */
  DECLARE @ErrorNumber      INT
         ,@MessageTemplate  NVARCHAR(4000)
         ,@ErrorMessage     NVARCHAR(4000)
         ,@ErrorProcedure   NVARCHAR(126)
         ,@ErrorLine        INT
         ,@ErrorSeverity    INT
         ,@ErrorState       INT
         ,@RaisErrorState   INT
         ,@ErrorLineFeed    NCHAR(1) = CHAR(10)
         ,@ErrorStatus      INT = 0
         ,@SavepointName    VARCHAR(32) = REPLACE( (CAST(NEWID() AS VARCHAR(36))), '-', '');
         /*Savepoint names are 32 characters and must be unique.  UNIQUEIDs are 36, four of which are dashes.*/

  BEGIN TRANSACTION; /*If a transaction is already in progress, this just increments the transaction count*/

  SAVE TRANSACTION @SavepointName;

  BEGIN TRY;

    RAISERROR('This is a test.  Had this been an actual error, Sebastian would have given you a meaningful error message.', 16, 1);

  END TRY
  BEGIN CATCH;

    /* Build a message string with placeholders for the original error information
     * Note:  "%d" & "%s" are placeholders (substitution parameters) which capture
     *        the values from the argument list of the original error message.
     */
    SET @MessageTemplate = N': Error %d, Severity %d, State %d, ' + @ErrorLineFeed
                         + N'Procedure %s, Line %d, '             + @ErrorLineFeed
                         + N', Message: %s';

    SELECT @ErrorStatus    = 1
          ,@ErrorMessage   = ERROR_MESSAGE()
          ,@ErrorNumber    = ERROR_NUMBER()
          ,@ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-')
          ,@ErrorLine      = ERROR_LINE()
          ,@ErrorSeverity  = ERROR_SEVERITY()
          ,@ErrorState     = ERROR_STATE()
          ,@RaisErrorState = CASE ERROR_STATE()
                               WHEN 0 /*RAISERROR Can't generate errors with State = 0*/
                                 THEN 1
                               ELSE ERROR_STATE()
                             END;

  END CATCH;

  /*Rollback to savepoint if error occurred.  This does not affect the transaction count.*/
  IF @ErrorStatus <> 0
    ROLLBACK TRANSACTION @SavepointName;

  /*If this procedure executed inside a transaction, then the commit just subtracts one from the transaction count.*/
  COMMIT TRANSACTION;

  IF @ErrorStatus = 0
    RETURN 0;

  ELSE
    BEGIN; /*Re-throw error*/

      /*Rethrow the error.  The msg_str parameter will contain the original error information*/
      RAISERROR( @MessageTemplate  /*msg_str parameter as message format template*/
                ,@ErrorSeverity    /*severity parameter*/
                ,@RaisErrorState   /*state parameter*/
                ,@ErrorNumber      /*argument: original error number*/
                ,@ErrorSeverity    /*argument: original error severity*/
                ,@ErrorState       /*argument: original error state*/
                ,@ErrorProcedure   /*argument: original error procedure name*/
                ,@ErrorLine        /*argument: original error line number*/
                ,@ErrorMessage     /*argument: original error message*/
                );

      RETURN -1;

    END;   /*Re-throw error*/

END  /*Stored Procedure*/
GO
</code>```

He declares the error variables, begins a transaction, sets a save point and then executes the procedure code inside a TRY block.  If the TRY block throws an error , execution passes to the CATCH block, which populates the error variables.  Then execution passes out of the TRY CATCH block.  On error, the transaction rolls back to the save point set at the beginning of the procedure.  Then the transaction commits.  Due to the way SQL Server handles nested transactions, this COMMIT just subtracts one from the transaction counter when executed inside another transaction.  (Nested Transactions really don't exist in SQL Server.)

Sebastian created a very neat and tidy pattern.  Each procedure in an execution chain cleans up its own transactions.  Unfortunately, this pattern has a big problem:  doomed transactions.  Doomed transactions break this pattern because they can't roll back to a save point or commit.  They can only roll back completely.  This, of course, means that you can't set XACT_ABORT ON when using TRY-CATCH blocks (and you should always use TRY-CATCH blocks.)  Even with XACT_ABORT OFF, many errors, such as compilation errors, will doom a transaction anyway.  Further, save points won't work with distributed transactions.

How can I work around this?  I need an error handling pattern that will work within the tSQLt test framework and also deliver consistent, correct error handling in production.  I could check the environment at run-time and adjust the behavior accordingly.  (See the example, below.)  I don't like that, however.  It feels like a hack to me.  It requires that the development environments be configured consistently.  Worse, I don't test my actual production code.  Does anyone have a brilliant solution?

```<code>USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.ModifiedRollback') IS NOT NULL
  DROP PROCEDURE dbo.ModifiedRollback;
GO

CREATE PROCEDURE dbo.ModifiedRollback
AS
BEGIN; /*Stored Procedure*/

  SET NOCOUNT ON;

  IF RIGHT(@@SERVERNAME, 9) = '\LOCALDEV'
    SET XACT_ABORT OFF;

  ELSE
    SET XACT_ABORT ON;

  BEGIN TRY;

    BEGIN TRANSACTION;

      RAISERROR('This is just a test.  Had this been an actual error, we would have given you some cryptic gobbledygook.', 16, 1);

    COMMIT TRANSACTION;

  END TRY
  BEGIN CATCH;

    IF @@TRANCOUNT > 0  AND  RIGHT(@@SERVERNAME,9) <> '\LOCALDEV'
      ROLLBACK TRANSACTION;

    THROW;

  END CATCH;

END;   /*Stored Procedure*/
GO
</code>```

EDIT:  After further testing, I find that my modified rollback doesn't work, either.  When the procedure throws an error it exits without either rolling back or committing.  tSQLt throws an error because @@TRANCOUNT when the procedure exits doesn't match the count when the procedure starts.  After some trial and error I found a workaround that works in my tests.  It combines the two error handling approaches - making the error handing much more complex, and some code paths can't be tested.  I'd love to find a better solution.

```<code>USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.TestedRollback') IS NOT NULL
  DROP PROCEDURE dbo.TestedRollback;
GO

CREATE PROCEDURE dbo.TestedRollback
AS
BEGIN /*Stored Procedure*/

  SET NOCOUNT ON;

  /* Due to the way tSQLt uses transactions and the way SQL Server handles errors, we declare our error-handling
   * variables here, populate them inside the CATCH block and then do our error-handling after exiting
   */
  DECLARE @ErrorStatus       BIT
         ,@ErrorNumber       INT
         ,@MessageTemplate   NVARCHAR(4000)
         ,@ErrorMessage      NVARCHAR(4000)
         ,@ErrorProcedure    NVARCHAR(126)
         ,@ErrorLine         INT
         ,@ErrorSeverity     INT
         ,@ErrorState        INT
         ,@RaisErrorState    INT
         ,@ErrorLineFeed     NCHAR(1) = CHAR(10)
         ,@FALSE             BIT = CAST(0 AS BIT)
         ,@TRUE              BIT = CAST(1 AS BIT)
         ,@tSQLtEnvironment  BIT
         ,@SavepointName     VARCHAR(32) = REPLACE( (CAST(NEWID() AS VARCHAR(36))), '-', '');
         /*Savepoint names are 32 characters long and must be unique.  UNIQUEIDs are 36, four of which are dashes*/

  /* The tSQLt Unit Testing Framework we use in our local development environments must maintain open transactions during testing.  So,
   * we don't roll back transactions during testing.  Also, doomed transactions can't stay open, so we SET XACT_ABORT OFF while testing.
   */
  IF RIGHT(@@SERVERNAME, 9) = '\LOCALDEV'
    SET @tSQLtEnvironment = @TRUE

  ELSE
    SET @tSQLtEnvironment = @FALSE;

  IF @tSQLtEnvironment = @TRUE
    SET XACT_ABORT OFF;

  ELSE
    SET XACT_ABORT ON;

  BEGIN TRY;

    SET ROWCOUNT 0; /*The ROWCOUNT setting can be updated outside the procedure and changes its behavior.  This sets it to the default.*/

    SET @ErrorStatus = @FALSE;

    BEGIN TRANSACTION;

      /*We need a save point to roll back to in the tSQLt Environment.*/
      IF @tSQLtEnvironment = @TRUE
        SAVE TRANSACTION @SavepointName;

      RAISERROR('Cryptic gobbledygook.', 16, 1);

    COMMIT TRANSACTION;

    RETURN 0;

  END TRY
  BEGIN CATCH;

    SET @ErrorStatus = @TRUE;

    /* Build a message string with placeholders for the original error information
     * Note:  "%d" & "%s" are placeholders (substitution parameters) which capture
     *        the values from the argument list of the original error message.
     */
    SET @MessageTemplate = N': Error %d, Severity %d, State %d, ' + @ErrorLineFeed
                         + N'Procedure %s, Line %d, '             + @ErrorLineFeed
                         + N', Message: %s';

    SELECT @ErrorMessage   = ERROR_MESSAGE()
          ,@ErrorNumber    = ERROR_NUMBER()
          ,@ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-')
          ,@ErrorLine      = ERROR_LINE()
          ,@ErrorSeverity  = ERROR_SEVERITY()
          ,@ErrorState     = ERROR_STATE()
          ,@RaisErrorState = CASE ERROR_STATE()
                               WHEN 0 /*RAISERROR Can't generate errors with State = 0*/
                                 THEN 1
                               ELSE ERROR_STATE()
                             END;
  END CATCH;

  /* Due to the way the tSQLt test framework uses transactions, we use two different error-handling schemes:
   * one for unit-testing and the other for our main Test/Staging/Production environments.  In those environments
   * we roll back transactions in the CATCH block in the event of an error.  In unit-testing, on the other hand,
   * we begin a transaction and set a save point.  If an error occurs we roll back to the save point and then
   * commit the transaction.  Since tSQLt executes all test in a single explicit transaction, starting a
   * transaction at the beginning of this stored procedure just adds one to @@TRANCOUNT.  Committing the
   * transaction subtracts one from @@TRANCOUNT.  Rolling back to a save point does not affect @@TRANCOUNT.
   */
  IF @ErrorStatus = @TRUE
    BEGIN; /*Error Handling*/

      IF @tSQLtEnvironment = @TRUE
        BEGIN; /*tSQLt Error Handling*/
          ROLLBACK TRANSACTION @SavepointName; /*Rolls back to save point but does not affect @@TRANCOUNT*/

          COMMIT TRANSACTION; /*Subtracts one from @@TRANCOUNT*/
        END;   /*tSQLt Error Handling*/

      ELSE IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;

      /*Rethrow the error.  The msg_str parameter will contain the original error information*/
      RAISERROR( @MessageTemplate  /*msg_str parameter as message format template*/
                ,@ErrorSeverity    /*severity parameter*/
                ,@RaisErrorState   /*state parameter*/
                ,@ErrorNumber      /*argument: original error number*/
                ,@ErrorSeverity    /*argument: original error severity*/
                ,@ErrorState       /*argument: original error state*/
                ,@ErrorProcedure   /*argument: original error procedure name*/
                ,@ErrorLine        /*argument: original error line number*/
                ,@ErrorMessage     /*argument: original error message*/
                );

    END;   /*Error Handling*/

END  /*Stored Procedure*/
GO
</code>```

答:
I'm testing a fix for this that modificaties the framework procedure tSQLt.Private_RunTest.   Basically, in the primary CATCH block, wherein it is trying to do a named rollback (Line 1448 for me), I am replacing

```<code>    ROLLBACK TRAN @TranName;
</code>```

with

```<code>    IF XACT_STATE() = 1 -- transaction is active
        ROLLBACK TRAN @TranName; -- execute original code
    ELSE IF XACT_STATE() = -1 -- transaction is doomed; cannot be partially rolled back
        ROLLBACK;   -- fully roll back

    IF (@@TRANCOUNT = 0)
        BEGIN TRAN; -- restart transaction to fulfill expectations below
</code>```

Preliminary testing looks good.  Stay tuned. (I'll submit to git after I gain some more confidence in this proposed edit.)

Body:
I am beginning to work with tSQLt unit tests for SQL Server in my production code.  Currently, I use Erland Sommarskog's error handling pattern for SQL Server.

USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.SommarskogRollback') IS NOT NULL
  DROP PROCEDURE dbo.SommarskogRollback;
GO

CREATE PROCEDURE dbo.SommarskogRollback
AS
BEGIN; /*Stored Procedure*/

  SET XACT_ABORT, NOCOUNT ON;

  BEGIN TRY;

    BEGIN TRANSACTION;

      RAISERROR('This is just a test.  Had this been an actual error, we would have given you some cryptic gobbledygook.', 16, 1);

    COMMIT TRANSACTION;

  END TRY
  BEGIN CATCH;

    IF @@TRANCOUNT > 0
      ROLLBACK TRANSACTION;

    THROW;

  END CATCH;

END;   /*Stored Procedure*/
GO

Erland Sommarskog recommends that we always SET XACT_ABORT ON, because only then does SQL Server handle errors in a (mostly) consistent manner.

This creates a problem when using tSQLt, though.  tSQLt executes all tests inside an explicit transaction.  When the tests are complete the entire transaction rolls back.  This makes cleanup of the test artifacts completely painless. However, with XACT_ABORT ON, any error thrown inside a TRY block immediately dooms that transaction.  The transaction must roll back completely.  It cannot commit, and it cannot roll back to a save point.  In fact, nothing can write to the transaction log inside that session until the transaction rolls back.  However, tSQLt can't track the test results properly unless the transaction is open when the tests end.  tSQLt stops executing and throws a ROLLBACK ERROR for doomed transactions.  The test that failed shows a status of Error (rather than Success or Failure), and subsequent tests don't run.

Sebastian Meine, the creator of tSQLt, recommends a different error handling pattern.

USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.MeineRollback') IS NOT NULL
  DROP PROCEDURE dbo.MeineRollback;
GO

CREATE PROCEDURE dbo.MeineRollback
AS
BEGIN /*Stored Procedure*/

  SET NOCOUNT ON;

  /* We declare the error variables here, populate them inside the CATCH
   * block and then do our error handling after exiting the CATCH block
   */
  DECLARE @ErrorNumber      INT
         ,@MessageTemplate  NVARCHAR(4000)
         ,@ErrorMessage     NVARCHAR(4000)
         ,@ErrorProcedure   NVARCHAR(126)
         ,@ErrorLine        INT
         ,@ErrorSeverity    INT
         ,@ErrorState       INT
         ,@RaisErrorState   INT
         ,@ErrorLineFeed    NCHAR(1) = CHAR(10)
         ,@ErrorStatus      INT = 0
         ,@SavepointName    VARCHAR(32) = REPLACE( (CAST(NEWID() AS VARCHAR(36))), '-', '');
         /*Savepoint names are 32 characters and must be unique.  UNIQUEIDs are 36, four of which are dashes.*/

  BEGIN TRANSACTION; /*If a transaction is already in progress, this just increments the transaction count*/

  SAVE TRANSACTION @SavepointName;

  BEGIN TRY;

    RAISERROR('This is a test.  Had this been an actual error, Sebastian would have given you a meaningful error message.', 16, 1);

  END TRY
  BEGIN CATCH;

    /* Build a message string with placeholders for the original error information
     * Note:  "%d" & "%s" are placeholders (substitution parameters) which capture
     *        the values from the argument list of the original error message.
     */
    SET @MessageTemplate = N': Error %d, Severity %d, State %d, ' + @ErrorLineFeed
                         + N'Procedure %s, Line %d, '             + @ErrorLineFeed
                         + N', Message: %s';

    SELECT @ErrorStatus    = 1
          ,@ErrorMessage   = ERROR_MESSAGE()
          ,@ErrorNumber    = ERROR_NUMBER()
          ,@ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-')
          ,@ErrorLine      = ERROR_LINE()
          ,@ErrorSeverity  = ERROR_SEVERITY()
          ,@ErrorState     = ERROR_STATE()
          ,@RaisErrorState = CASE ERROR_STATE()
                               WHEN 0 /*RAISERROR Can't generate errors with State = 0*/
                                 THEN 1
                               ELSE ERROR_STATE()
                             END;

  END CATCH;

  /*Rollback to savepoint if error occurred.  This does not affect the transaction count.*/
  IF @ErrorStatus <> 0
    ROLLBACK TRANSACTION @SavepointName;

  /*If this procedure executed inside a transaction, then the commit just subtracts one from the transaction count.*/
  COMMIT TRANSACTION;

  IF @ErrorStatus = 0
    RETURN 0;

  ELSE
    BEGIN; /*Re-throw error*/

      /*Rethrow the error.  The msg_str parameter will contain the original error information*/
      RAISERROR( @MessageTemplate  /*msg_str parameter as message format template*/
                ,@ErrorSeverity    /*severity parameter*/
                ,@RaisErrorState   /*state parameter*/
                ,@ErrorNumber      /*argument: original error number*/
                ,@ErrorSeverity    /*argument: original error severity*/
                ,@ErrorState       /*argument: original error state*/
                ,@ErrorProcedure   /*argument: original error procedure name*/
                ,@ErrorLine        /*argument: original error line number*/
                ,@ErrorMessage     /*argument: original error message*/
                );

      RETURN -1;

    END;   /*Re-throw error*/

END  /*Stored Procedure*/
GO

He declares the error variables, begins a transaction, sets a save point and then executes the procedure code inside a TRY block.  If the TRY block throws an error , execution passes to the CATCH block, which populates the error variables.  Then execution passes out of the TRY CATCH block.  On error, the transaction rolls back to the save point set at the beginning of the procedure.  Then the transaction commits.  Due to the way SQL Server handles nested transactions, this COMMIT just subtracts one from the transaction counter when executed inside another transaction.  (Nested Transactions really don't exist in SQL Server.)

Sebastian created a very neat and tidy pattern.  Each procedure in an execution chain cleans up its own transactions.  Unfortunately, this pattern has a big problem:  doomed transactions.  Doomed transactions break this pattern because they can't roll back to a save point or commit.  They can only roll back completely.  This, of course, means that you can't set XACT_ABORT ON when using TRY-CATCH blocks (and you should always use TRY-CATCH blocks.)  Even with XACT_ABORT OFF, many errors, such as compilation errors, will doom a transaction anyway.  Further, save points won't work with distributed transactions.

How can I work around this?  I need an error handling pattern that will work within the tSQLt test framework and also deliver consistent, correct error handling in production.  I could check the environment at run-time and adjust the behavior accordingly.  (See the example, below.)  I don't like that, however.  It feels like a hack to me.  It requires that the development environments be configured consistently.  Worse, I don't test my actual production code.  Does anyone have a brilliant solution?

USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.ModifiedRollback') IS NOT NULL
  DROP PROCEDURE dbo.ModifiedRollback;
GO

CREATE PROCEDURE dbo.ModifiedRollback
AS
BEGIN; /*Stored Procedure*/

  SET NOCOUNT ON;

  IF RIGHT(@@SERVERNAME, 9) = '\LOCALDEV'
    SET XACT_ABORT OFF;

  ELSE
    SET XACT_ABORT ON;

  BEGIN TRY;

    BEGIN TRANSACTION;

      RAISERROR('This is just a test.  Had this been an actual error, we would have given you some cryptic gobbledygook.', 16, 1);

    COMMIT TRANSACTION;

  END TRY
  BEGIN CATCH;

    IF @@TRANCOUNT > 0  AND  RIGHT(@@SERVERNAME,9) <> '\LOCALDEV'
      ROLLBACK TRANSACTION;

    THROW;

  END CATCH;

END;   /*Stored Procedure*/
GO

EDIT:  After further testing, I find that my modified rollback doesn't work, either.  When the procedure throws an error it exits without either rolling back or committing.  tSQLt throws an error because @@TRANCOUNT when the procedure exits doesn't match the count when the procedure starts.  After some trial and error I found a workaround that works in my tests.  It combines the two error handling approaches - making the error handing much more complex, and some code paths can't be tested.  I'd love to find a better solution.

USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.TestedRollback') IS NOT NULL
  DROP PROCEDURE dbo.TestedRollback;
GO

CREATE PROCEDURE dbo.TestedRollback
AS
BEGIN /*Stored Procedure*/

  SET NOCOUNT ON;

  /* Due to the way tSQLt uses transactions and the way SQL Server handles errors, we declare our error-handling
   * variables here, populate them inside the CATCH block and then do our error-handling after exiting
   */
  DECLARE @ErrorStatus       BIT
         ,@ErrorNumber       INT
         ,@MessageTemplate   NVARCHAR(4000)
         ,@ErrorMessage      NVARCHAR(4000)
         ,@ErrorProcedure    NVARCHAR(126)
         ,@ErrorLine         INT
         ,@ErrorSeverity     INT
         ,@ErrorState        INT
         ,@RaisErrorState    INT
         ,@ErrorLineFeed     NCHAR(1) = CHAR(10)
         ,@FALSE             BIT = CAST(0 AS BIT)
         ,@TRUE              BIT = CAST(1 AS BIT)
         ,@tSQLtEnvironment  BIT
         ,@SavepointName     VARCHAR(32) = REPLACE( (CAST(NEWID() AS VARCHAR(36))), '-', '');
         /*Savepoint names are 32 characters long and must be unique.  UNIQUEIDs are 36, four of which are dashes*/

  /* The tSQLt Unit Testing Framework we use in our local development environments must maintain open transactions during testing.  So,
   * we don't roll back transactions during testing.  Also, doomed transactions can't stay open, so we SET XACT_ABORT OFF while testing.
   */
  IF RIGHT(@@SERVERNAME, 9) = '\LOCALDEV'
    SET @tSQLtEnvironment = @TRUE

  ELSE
    SET @tSQLtEnvironment = @FALSE;

  IF @tSQLtEnvironment = @TRUE
    SET XACT_ABORT OFF;

  ELSE
    SET XACT_ABORT ON;

  BEGIN TRY;

    SET ROWCOUNT 0; /*The ROWCOUNT setting can be updated outside the procedure and changes its behavior.  This sets it to the default.*/

    SET @ErrorStatus = @FALSE;

    BEGIN TRANSACTION;

      /*We need a save point to roll back to in the tSQLt Environment.*/
      IF @tSQLtEnvironment = @TRUE
        SAVE TRANSACTION @SavepointName;

      RAISERROR('Cryptic gobbledygook.', 16, 1);

    COMMIT TRANSACTION;

    RETURN 0;

  END TRY
  BEGIN CATCH;

    SET @ErrorStatus = @TRUE;

    /* Build a message string with placeholders for the original error information
     * Note:  "%d" & "%s" are placeholders (substitution parameters) which capture
     *        the values from the argument list of the original error message.
     */
    SET @MessageTemplate = N': Error %d, Severity %d, State %d, ' + @ErrorLineFeed
                         + N'Procedure %s, Line %d, '             + @ErrorLineFeed
                         + N', Message: %s';

    SELECT @ErrorMessage   = ERROR_MESSAGE()
          ,@ErrorNumber    = ERROR_NUMBER()
          ,@ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-')
          ,@ErrorLine      = ERROR_LINE()
          ,@ErrorSeverity  = ERROR_SEVERITY()
          ,@ErrorState     = ERROR_STATE()
          ,@RaisErrorState = CASE ERROR_STATE()
                               WHEN 0 /*RAISERROR Can't generate errors with State = 0*/
                                 THEN 1
                               ELSE ERROR_STATE()
                             END;
  END CATCH;

  /* Due to the way the tSQLt test framework uses transactions, we use two different error-handling schemes:
   * one for unit-testing and the other for our main Test/Staging/Production environments.  In those environments
   * we roll back transactions in the CATCH block in the event of an error.  In unit-testing, on the other hand,
   * we begin a transaction and set a save point.  If an error occurs we roll back to the save point and then
   * commit the transaction.  Since tSQLt executes all test in a single explicit transaction, starting a
   * transaction at the beginning of this stored procedure just adds one to @@TRANCOUNT.  Committing the
   * transaction subtracts one from @@TRANCOUNT.  Rolling back to a save point does not affect @@TRANCOUNT.
   */
  IF @ErrorStatus = @TRUE
    BEGIN; /*Error Handling*/

      IF @tSQLtEnvironment = @TRUE
        BEGIN; /*tSQLt Error Handling*/
          ROLLBACK TRANSACTION @SavepointName; /*Rolls back to save point but does not affect @@TRANCOUNT*/

          COMMIT TRANSACTION; /*Subtracts one from @@TRANCOUNT*/
        END;   /*tSQLt Error Handling*/

      ELSE IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;

      /*Rethrow the error.  The msg_str parameter will contain the original error information*/
      RAISERROR( @MessageTemplate  /*msg_str parameter as message format template*/
                ,@ErrorSeverity    /*severity parameter*/
                ,@RaisErrorState   /*state parameter*/
                ,@ErrorNumber      /*argument: original error number*/
                ,@ErrorSeverity    /*argument: original error severity*/
                ,@ErrorState       /*argument: original error state*/
                ,@ErrorProcedure   /*argument: original error procedure name*/
                ,@ErrorLine        /*argument: original error line number*/
                ,@ErrorMessage     /*argument: original error message*/
                );

    END;   /*Error Handling*/

END  /*Stored Procedure*/
GO

Body:
I'm testing a fix for this that modificaties the framework procedure tSQLt.Private_RunTest.   Basically, in the primary CATCH block, wherein it is trying to do a named rollback (Line 1448 for me), I am replacing

    ROLLBACK TRAN @TranName;

with

    IF XACT_STATE() = 1 -- transaction is active
        ROLLBACK TRAN @TranName; -- execute original code
    ELSE IF XACT_STATE() = -1 -- transaction is doomed; cannot be partially rolled back
        ROLLBACK;   -- fully roll back

    IF (@@TRANCOUNT = 0)
        BEGIN TRAN; -- restart transaction to fulfill expectations below

Preliminary testing looks good.  Stay tuned. (I'll submit to git after I gain some more confidence in this proposed edit.)


问:
Read int vector in R, 4 bytes per int
I have a 1 GB file, which is a vector of 250M elements, each being a 4-byte-int (saved with C++).

How to load this into a R vector? Would this be the natural way?

```<code>f = file("myfile.dat")
readBin(f, integer(), n = 250000000, size = 4, endian = "little")
</code>```

答:
In fact the problem was just the open binary mode:

```<code>f = file("myfile.dat", open="rb")
readBin(f, integer(), n = 250000000, size = 4, endian = "little")
</code>```

Title: Read int vector in R, 4 bytes per int

Body:
I have a 1 GB file, which is a vector of 250M elements, each being a 4-byte-int (saved with C++).

How to load this into a R vector? Would this be the natural way?

f = file("myfile.dat")
readBin(f, integer(), n = 250000000, size = 4, endian = "little")

Body:
In fact the problem was just the open binary mode:

f = file("myfile.dat", open="rb")
readBin(f, integer(), n = 250000000, size = 4, endian = "little")


问:
Sending double from one activity to another Android Studio

Hi,
I am trying to send data from one activity to another activity using this method: how to retrieve a Double value from one activity to another?
Yet every time I open up my application it crashes as its because my code is in the onCreate:

```<code>double lat, longi;
Intent getLocation;
Bundle extras;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
getLocation = this.getIntent();
extras = getLocation.getExtras();
lat = extras.getDouble("lat");
longi = extras.getDouble("longi");
</code>```

but when I put it in a button instead It can't resolve this.getIntent();

```<code>public void getCoordinates(View view){
    Button coordinates = (Button) findViewById(R.id.getCoordinates);
    coordinates.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            getLocation = this.getIntent();
            extras = getLocation.getExtras();
            lat = extras.getDouble("lat");
            longi = extras.getDouble("longi");
        }
    });
}
</code>```

I would like to receive data either automatically or using a button.
I am quite new in mobile computing so please don't roast me.

答:
this meant isView.OnClickListener()  in your code .

And we need YourActivity.this as Context

You should use

```<code>public void getCoordinates(View view){
Button coordinates = (Button) findViewById(R.id.getCoordinates);
coordinates.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View view){
        getLocation = YourActivity.this.getIntent();
        extras = getLocation.getExtras();
        lat = extras.getDouble("lat");
        longi = extras.getDouble("longi");
    }
});
}
</code>```

Body:
Hi,
I am trying to send data from one activity to another activity using this method: how to retrieve a Double value from one activity to another?
Yet every time I open up my application it crashes as its because my code is in the onCreate:

double lat, longi;
Intent getLocation;
Bundle extras;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
getLocation = this.getIntent();
extras = getLocation.getExtras();
lat = extras.getDouble("lat");
longi = extras.getDouble("longi");

but when I put it in a button instead It can't resolve this.getIntent();

public void getCoordinates(View view){
    Button coordinates = (Button) findViewById(R.id.getCoordinates);
    coordinates.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            getLocation = this.getIntent();
            extras = getLocation.getExtras();
            lat = extras.getDouble("lat");
            longi = extras.getDouble("longi");
        }
    });
}

I would like to receive data either automatically or using a button.
I am quite new in mobile computing so please don't roast me.

Body:
this meant isView.OnClickListener()  in your code .

And we need YourActivity.this as Context

You should use

public void getCoordinates(View view){
Button coordinates = (Button) findViewById(R.id.getCoordinates);
coordinates.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View view){
        getLocation = YourActivity.this.getIntent();
        extras = getLocation.getExtras();
        lat = extras.getDouble("lat");
        longi = extras.getDouble("longi");
    }
});
}


答:
Another solution may be </p>

```<code>"%.2i:%.2i" % (get_hours(hm), get_minutes(hm))
</code>```

Title: How to add zero to a time

Body:
Another solution may be

"%.2i:%.2i" % (get_hours(hm), get_minutes(hm))


问:
C# new in method declaration
```<code>public new int AdjustedBaseValue
</code>```

<p>What does the new here mean or do? </p>

答:
Here is a good forum post with some examples between the differences of using new vs override

http://social.msdn.microsoft.com/Forums/en/Vsexpressvcs/thread/65e02299-300f-4b74-8f0a-679f490605f5

ContentLicense: CC BY-SA 2.5

Title: C# new in method declaration

Body:
public new int AdjustedBaseValue

What does the new here mean or do?


问:
Writing a dataframe to disk taking an unrealistically long time in Pyspark (Spark 2.1.1)
I'm running Pyspark on a single server with multiple CPUs. All other operations (reading, joining, filtering, custom UDFs) are executed quickly except for writing to disk. The dataframe I'm trying to save is of size around ~400 gb with 200 partitions.

```<code> sc.getConf().getAll()
</code>```

The driver memory is 16g, and working directory has enough space (> 10TB)

I'm trying to save using the following command:

```<code> df.repartition(1).write.csv("out.csv")
</code>```

Wondering if anyone has run into the same issue. Also will changing any of the config parameters before pyspark is invoked help solve the issue?

Edits (a few clarifications):

When I mean other operations were executed quickly, there was always an action after transformation, in my case they were row counts. So all the operations were executed super fast. Still haven't gotten around why writing takes such a ridiculous amount of time.

One of my colleagues brought up the fact that the disks in our server might have a limit on concurrent writing which might be slowing things down, still investigating on this. Interested in knowing if others are seeing slow write times on a Spark cluster too. I have confirmation from one user regarding this on AWS cluster.

答:
After a lot of trial and error, I realized that the issue was due to the method I used to read the file from disk. I was using the in-built read.csv function, and when I switched over to the read function in databricks-csv package the problem went away. I'm now able to write files to disk at a reasonable time. It's really strange, maybe it's a bug in 2.1.1 or databricks csv package is really optimized.

1.read.csv method

```<code>from pyspark.sql import SparkSession
spark = SparkSession \
    .builder \
    .appName("model") \
    .config("spark.worker.dir", "xxxx") \
    .getOrCreate()
df = spark.read.load("file.csv", format="csv", header = True)
write.csv("file_after_processing.csv")
</code>```

2.Using the databricks-csv package

```<code>from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('file.csv')
train.write.format('com.databricks.spark.csv').save('file_after_processing.csv')
</code>```

Body:
I'm running Pyspark on a single server with multiple CPUs. All other operations (reading, joining, filtering, custom UDFs) are executed quickly except for writing to disk. The dataframe I'm trying to save is of size around ~400 gb with 200 partitions.

 sc.getConf().getAll()

The driver memory is 16g, and working directory has enough space (> 10TB)

I'm trying to save using the following command:

 df.repartition(1).write.csv("out.csv")

Wondering if anyone has run into the same issue. Also will changing any of the config parameters before pyspark is invoked help solve the issue?

Edits (a few clarifications):

When I mean other operations were executed quickly, there was always an action after transformation, in my case they were row counts. So all the operations were executed super fast. Still haven't gotten around why writing takes such a ridiculous amount of time.

One of my colleagues brought up the fact that the disks in our server might have a limit on concurrent writing which might be slowing things down, still investigating on this. Interested in knowing if others are seeing slow write times on a Spark cluster too. I have confirmation from one user regarding this on AWS cluster.

Body:
After a lot of trial and error, I realized that the issue was due to the method I used to read the file from disk. I was using the in-built read.csv function, and when I switched over to the read function in databricks-csv package the problem went away. I'm now able to write files to disk at a reasonable time. It's really strange, maybe it's a bug in 2.1.1 or databricks csv package is really optimized.

1.read.csv method

from pyspark.sql import SparkSession
spark = SparkSession \
    .builder \
    .appName("model") \
    .config("spark.worker.dir", "xxxx") \
    .getOrCreate()
df = spark.read.load("file.csv", format="csv", header = True)
write.csv("file_after_processing.csv")

2.Using the databricks-csv package

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('file.csv')
train.write.format('com.databricks.spark.csv').save('file_after_processing.csv')


问:
Regex - Match up until there's an equal amount of 2 specific characters
For example if I have the following sentence:

a cat bit a dog on the butt before running away

If the 2 characters I want to use are 'a' and 'b' then I want to match up until the point where there are equal amounts of 'a' and 'b' like the following:

a cat bit a dog on the butt b

In the above case, the sentence has 5 a's and 3 b's. I want to much up to the point where I have 3 a's and 3 b's.

Thank you for the help.

答:
It's not possible.

an bn is not regular, thus matching with a regular expression is mathematically not possible, even with enhanced regular expressions.

You can use the following function to get the range which doesn't use a regular expression:

var input = "a cat bit a dog on the butt b";
console.log(getRange(input, "a", "b"));

function getRange(input, char1, char2){
  var indexStart = -1;
  var count1 = 0, count2 = 0;

  for(var i = 0; i < input.length; i++){
    var char = input[i];
    switch(char){
      case char1:
        count1 += 1; break
      case char2:
        count2 += 1; break;
    }
    if(char == char1 || char == char2){
      if(indexStart == -1)
        indexStart = i;

      if(count1 == count2)
        return [indexStart, i];
    }
  }

  return [-1, -1];
}```


问:
=LEFT(H2,5) To show data for all rows and stop at last row of data
Hi could someone enlighten me with some VBA code to insert formula =LEFT(H2,5) into column M and then stop at the last row of data.
The data it will be referencing will be inserted from the web so when i refresh the data pull the rows could be more or less so it can't be a fixed without using VB

Thanks
Rhys

答:
You don't need a loop for this:

```<code>Sub qwerty()
    Dim N As Long, r As Range
    N = Cells(Rows.Count, "H").End(xlUp).Row
    Set r = Range("M2:M" & N)
    r.Formula = "=LEFT(H2,5)"
End Sub
</code>```

You will find that the addresses in the formulas adjust just like in copy/paste.

Body:
You don't need a loop for this:

Sub qwerty()
    Dim N As Long, r As Range
    N = Cells(Rows.Count, "H").End(xlUp).Row
    Set r = Range("M2:M" & N)
    r.Formula = "=LEFT(H2,5)"
End Sub

You will find that the addresses in the formulas adjust just like in copy/paste.


问:
Is there a "null coalescing" operator in JavaScript?
Is there a null coalescing operator in Javascript?

For example, in C#, I can do this:

```<code>String someString = null;
var whatIWant = someString ?? "Cookies!";
</code>```

The best approximation I can figure out for Javascript is using the conditional operator:

```<code>var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
</code>```

Which is sorta icky IMHO. Can I do better?

答:
After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.

@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in == versus === in JavaScript especially when it comes to issues of checking for undefined and/or null.

There's a really good article about the difference in two terms here. Basically, understand that if you use == instead of ===, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.

OwnerDisplayName: Daniel Schaffer

Body:
Is there a null coalescing operator in Javascript?

For example, in C#, I can do this:

String someString = null;
var whatIWant = someString ?? "Cookies!";

The best approximation I can figure out for Javascript is using the conditional operator:

var someString = null;
var whatIWant = someString ? someString : 'Cookies!';

Which is sorta icky IMHO. Can I do better?

LastEditorDisplayName: Daniel Schaffer

OwnerDisplayName: Tom

LastEditorDisplayName: Tom


问:
Best practise for different column types on Rails
I have a model in rails that refers to a game_item that belongs to a user. This weapon has an is_equipped column that resembles whether the item is equipped or not. The game_item can be a weapon, a helmet and more (specified by item_type in game_item model).

Now, i'm looking for a good way to get the equipped item for every type. I can do things like get_equipped_item(type) and specify the type, or get_equipped_helmet, get_equipped_weapon etc.
I'm looking for the better way to do that, the rails way :) Any ideas ?

答:
You can use scopes for this.

Something like

```<code>scope :equipped, where(:is_equipped => true)
scope :helmet, where(:item_type => 'helmet')
scope :weapon, where(:item_type => 'weapon')
</code>```

Then use them as

```<code>ModelName.equipped # => all equipped items
ModelName.helmet.equipped # => all equipped helmets
</code>```

Further reading: http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html, http://asciicasts.com/episodes/215-advanced-queries-in-rails-3

Body:
You can use scopes for this.

Something like

scope :equipped, where(:is_equipped => true)
scope :helmet, where(:item_type => 'helmet')
scope :weapon, where(:item_type => 'weapon')

Then use them as

ModelName.equipped # => all equipped items
ModelName.helmet.equipped # => all equipped helmets

Further reading: http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html, http://asciicasts.com/episodes/215-advanced-queries-in-rails-3


问:
How to output a consoles log to another file as regular text
I'm trying to print the result of my console.log to another .txt file, how would I make this happen? this is what my console.log looks like this: https://imgur.com/o2Vo471

I'm wanting this printed as regular text to an output file e.g 'output.txt'

答:
This answer works, but it isn't what i'm aiming for it will work for most other people i'd assume. you're gonna want to run your program like so:

```<code>npm start > output.txt
</code>```

this will print your console output to the output.txt file I still need to achieve this with node fs so i'd appreciate anymore answers

Body:
This answer works, but it isn't what i'm aiming for it will work for most other people i'd assume. you're gonna want to run your program like so:

npm start > output.txt

this will print your console output to the output.txt file I still need to achieve this with node fs so i'd appreciate anymore answers


问:
Re-render React component on Redux state change
I have create a very simple React/Redux application and I am struggling with getting a simple component to re-render when the state changes. I am using create-react-app as a starting point. In the video series I've been watching by Dan Abramov (https://egghead.io/lessons/react-redux-react-todo-list-example-adding-a-todo), he subscribes a root render function to the store, which gets called each time a change is dispatched. Without using Connect, I'd like to understand how to cause the Value component to re-render on state change.

Thanks!

index.js

```<code>import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import registerServiceWorker from './registerServiceWorker'
import { createStore } from 'redux'

const counter = (state = 0, action) => {
  console.log(action)
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

const store = createStore(counter)

ReactDOM.render(<App store={store} />, document.getElementById('root'))
registerServiceWorker()
</code>```

app.js

```<code>import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
import Counter from './components/Counter'

class App extends Component {
  render() {
    return (
      <div className="App">
        <Counter
          value={this.props.store.getState()}
          onIncrement={() =>
            this.props.store.dispatch({
              type: 'INCREMENT'
            })
          }
          onDecrement={() =>
            this.props.store.dispatch({
              type: 'DECREMENT'
            })
          }></Counter>
      </div>
    )
  }
}

export default App;
</code>```

Counter.js

```<code>import React from 'react'
import Value from './Value'

const Counter = ({ value, onIncrement, onDecrement }) => {
  return (
    <div>
      <Value value={value}></Value>
      <button onClick={onIncrement}>+</button>
      <button onClick={onDecrement}>-</button>
    </div>
  )
}

export default Counter
</code>```

Value.js

```<code>import React from 'react'

const Counter = ({ value }) => {
  return (
    <h1>{value}</h1>
  )
}

export default Counter
</code>```

答:
Without using Connect, I'd like to understand how to cause the Value
  component to re-render on state change

First thing we have to do is subscribe to any redux-state changes. We will set the redux-state to your app's local state and update the state every time the redux-state is updated:

```<code>/* app.js */

componentDidMount(){
  this.props.store.subscribe(() => {
    this.setState({reduxState: this.props.store.getState()});
  });
}
</code>```

Then you pass the state to your child components:

```<code>render(){
  return (
    <Counter value={this.state.reduxState} ... />
  )
}
</code>```

Body:
I have create a very simple React/Redux application and I am struggling with getting a simple component to re-render when the state changes. I am using create-react-app as a starting point. In the video series I've been watching by Dan Abramov (https://egghead.io/lessons/react-redux-react-todo-list-example-adding-a-todo), he subscribes a root render function to the store, which gets called each time a change is dispatched. Without using Connect, I'd like to understand how to cause the Value component to re-render on state change.

Thanks!

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import registerServiceWorker from './registerServiceWorker'
import { createStore } from 'redux'

const counter = (state = 0, action) => {
  console.log(action)
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

const store = createStore(counter)

ReactDOM.render(<App store={store} />, document.getElementById('root'))
registerServiceWorker()

app.js

import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
import Counter from './components/Counter'

class App extends Component {
  render() {
    return (

        <Counter
          value={this.props.store.getState()}
          onIncrement={() =>
            this.props.store.dispatch({
              type: 'INCREMENT'
            })
          }
          onDecrement={() =>
            this.props.store.dispatch({
              type: 'DECREMENT'
            })
          }></Counter>

    )
  }
}

export default App;

Counter.js

import React from 'react'
import Value from './Value'

const Counter = ({ value, onIncrement, onDecrement }) => {
  return (

      <Value value={value}></Value>
      <button onClick={onIncrement}>+</button>
      <button onClick={onDecrement}>-</button>

  )
}

export default Counter

Value.js

import React from 'react'

const Counter = ({ value }) => {
  return (

{value}

  )
}

export default Counter

Body:
Without using Connect, I'd like to understand how to cause the Value
  component to re-render on state change

First thing we have to do is subscribe to any redux-state changes. We will set the redux-state to your app's local state and update the state every time the redux-state is updated:

/* app.js */

componentDidMount(){
  this.props.store.subscribe(() => {
    this.setState({reduxState: this.props.store.getState()});
  });
}

Then you pass the state to your child components:

render(){
  return (
    <Counter value={this.state.reduxState} ... />
  )
}


问:
How to merge distinct and redundant data into one element using XSLT?
Following is the input :

```<code><Parent>
 <child>
  <e1>ABC1</e1>
  <e2>XYX</e2>
  <e3>4382</e3>
  <e4>summary1</e4>
  <mName>PRICE</mName>
  <mValue>1234000</mValue>
 </child>
 <child>
  <e1>ABC1</e1>
  <e2>XYX</e2>
  <e3>4382</e3>
  <e4>summary1</e4>
  <mName>TYPE</mName>
  <mValue>SPORTS</mValue>
 </child>
 <child>
  <e1>ABC2</e1>
  <e2>QWE</e2>
  <e3>3456</e3>
  <e4>summary2</e4>
  <mName>TYPE</mName>
  <mValue>SEDAN</mValue>
 </child>
</Parent>
</code>```

I want to merge the child element in such a way that it has both redundant as well as the distinct elements.Below is the expected output,I am not sure how to achieve this using XSL any help appreciated.

Expected output :

```<code><Parent>
 <child>
  <e1>ABC1</e1>
  <e2>XYX</e2>
  <e3>4382</e3>
  <e4>summary</e4>
  <mName>PRICE</mName>
  <mValue>1234000</mValue>
  <mName>TYPE</mName>
  <mValue>SPORTS</mValue>
 </child>
 <child>
  <e1>ABC2</e1>
  <e2>QWE</e2>
  <e3>3456</e3>
  <e4>summary2</e4>
  <mName>TYPE</mName>
  <mValue>SEDAN</mValue>
 </child>
</Parent>
</code>```

Update from comments

All the child elements are uniquely
  identified by 'e1' element. Where two
  child elements have the same such e
  elements, they should be merged so
  there is one child with a list of
  multiple mName and mValue elements

答:
After much of research and efforts i came up with simpler approach and here is the xsl  which gives desired output '</p>

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:key name="Ids" match="Parent/child" use="e1"/>

    <xsl:template match="/Parent">
         <Parent>
            <xsl:for-each select="child[generate-id(.)
                                        = generate-id(key('Ids', e1)[1])]">
                 <child>
                    <xsl:copy-of select="e1|e2|e3|e4"/>
                     <xsl:for-each select="key('Ids', e1)">
                            <xsl:copy-of select="mName|mValue"/>
                     </xsl:for-each>
                </child >
            </xsl:for-each>
        </Parent>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
Following is the input :

<Parent>
 <child>
  <e1>ABC1</e1>
  <e2>XYX</e2>
  <e3>4382</e3>
  <e4>summary1</e4>
  <mName>PRICE</mName>
  <mValue>1234000</mValue>
 </child>
 <child>
  <e1>ABC1</e1>
  <e2>XYX</e2>
  <e3>4382</e3>
  <e4>summary1</e4>
  <mName>TYPE</mName>
  <mValue>SPORTS</mValue>
 </child>
 <child>
  <e1>ABC2</e1>
  <e2>QWE</e2>
  <e3>3456</e3>
  <e4>summary2</e4>
  <mName>TYPE</mName>
  <mValue>SEDAN</mValue>
 </child>
</Parent>

I want to merge the child element in such a way that it has both redundant as well as the distinct elements.Below is the expected output,I am not sure how to achieve this using XSL any help appreciated.

Expected output :

<Parent>
 <child>
  <e1>ABC1</e1>
  <e2>XYX</e2>
  <e3>4382</e3>
  <e4>summary</e4>
  <mName>PRICE</mName>
  <mValue>1234000</mValue>
  <mName>TYPE</mName>
  <mValue>SPORTS</mValue>
 </child>
 <child>
  <e1>ABC2</e1>
  <e2>QWE</e2>
  <e3>3456</e3>
  <e4>summary2</e4>
  <mName>TYPE</mName>
  <mValue>SEDAN</mValue>
 </child>
</Parent>

Update from comments

All the child elements are uniquely
  identified by 'e1' element. Where two
  child elements have the same such e
  elements, they should be merged so
  there is one child with a list of
  multiple mName and mValue elements

Body:
After much of research and efforts i came up with simpler approach and here is the xsl  which gives desired output '

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:key name="Ids" match="Parent/child" use="e1"/>

    <xsl:template match="/Parent">
         <Parent>
            <xsl:for-each select="child[generate-id(.)
                                        = generate-id(key('Ids', e1)[1])]">
                 <child>
                    <xsl:copy-of select="e1|e2|e3|e4"/>
                     <xsl:for-each select="key('Ids', e1)">
                            <xsl:copy-of select="mName|mValue"/>
                     </xsl:for-each>
                </child >
            </xsl:for-each>
        </Parent>
    </xsl:template>
</xsl:stylesheet>


问:
How to add zero to a time
I have a function that receives a time, in a string, and another number to add to the time:

```<code>def get_hours(hm):
   return int(hm.split(':')[0])

def get_minutes(hm):
   return int(hm.split(':')[1])

def add_minutes(hm, incr):
"""Increment the given time by the given amount of minutes.

Requires:
- hm str with a time represented as HH:MM;
- incr int with the number of minutes.
Ensures: str with a time represented as HH:MM, the result of incrementing hm by incr minutes.
"""
if get_minutes(hm)+incr>=60:
    if get_hours(hm)==23:
        return '00:'+str((get_minutes(hm)+incr)-60)
    else:
        return str(get_hours(hm)+1)+':'+str((get_minutes(hm)+incr)-60)
else:
    return str(get_hours(hm))+':'+str((get_minutes(hm)+incr))
</code>```

The problem is when the time is 16:05 or 04:06, it doesn't display the zeros, so it's just 16:5 and 4:6. How can i make this work?

答:
Here is an example on how you can work with datetime:

```<code>import datetime

def add_minutes(t, incr):
    return t + datetime.timedelta(minutes=incr)

# Create a datetime object
t = datetime.datetime.now() # 2017-12-05 01:29...

# Add minutes
t2 = add_minutes(t,5)

# Whenever you need to output use stftime:
print(t2.strftime("%H:%M"))
</code>```

Prints:

```<code>01:34
</code>```

Title: How to add zero to a time

Body:
I have a function that receives a time, in a string, and another number to add to the time:

def get_hours(hm):
   return int(hm.split(':')[0])

def get_minutes(hm):
   return int(hm.split(':')[1])

def add_minutes(hm, incr):
"""Increment the given time by the given amount of minutes.

Requires:
- hm str with a time represented as HH:MM;
- incr int with the number of minutes.
Ensures: str with a time represented as HH:MM, the result of incrementing hm by incr minutes.
"""
if get_minutes(hm)+incr>=60:
    if get_hours(hm)==23:
        return '00:'+str((get_minutes(hm)+incr)-60)
    else:
        return str(get_hours(hm)+1)+':'+str((get_minutes(hm)+incr)-60)
else:
    return str(get_hours(hm))+':'+str((get_minutes(hm)+incr))

The problem is when the time is 16:05 or 04:06, it doesn't display the zeros, so it's just 16:5 and 4:6. How can i make this work?

Body:
Here is an example on how you can work with datetime:

import datetime

def add_minutes(t, incr):
    return t + datetime.timedelta(minutes=incr)

# Create a datetime object
t = datetime.datetime.now() # 2017-12-05 01:29...

# Add minutes
t2 = add_minutes(t,5)

# Whenever you need to output use stftime:
print(t2.strftime("%H:%M"))

Prints:

01:34


问:
vscode launch config for next.js app
I'm developing a next.js app with Visual Studio Code (vscode) and I like that editor a lot! I've installed Debugger for Chrome from the extension store. The config below starts a new Chrome instance and I can start to debug. It stops on the breakpoint in vscode but here comes the problem. It doesn't show the values of the function and jumps into the node_modules event though I added it to "skipfiles".
Breakpoints also won't stop on the constructor. Is next.js somehow not supported?
I'm using async await syntax a lot. Debugging server side code works perfectly.</p>

```<code>    {
        "name": "My Client",
        "type": "chrome",
        "request": "launch",
        "url": "http://localhost:3000",
        "webRoot": "${workspaceRoot}/my-client/",
        "skipFiles": [
            "node_modules/**/*.js",
            "<node_internals>/**/*.js",
            "node_modules",
            ".next"
        ]
    }
</code>```

答:
I hope is not too late for you ma friend,
Here  you have the original documentation from VSCode that solve the issue:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Next: Chrome",
            "url": "http://localhost:3000",
            "webRoot": "${workspaceRoot}"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Next: Node",
            "runtimeExecutable": "next",
            "runtimeArgs": [
                "--inspect"
            ],
            "port": 9229,
            "console": "integratedTerminal"
        }
    ],
    "compounds": [
        {
            "name": "Next: Full",
            "configurations": ["Next: Node", "Next: Chrome"]
        }
    ]
}```

Title: vscode launch config for next.js app

Body:
I'm developing a next.js app with Visual Studio Code (vscode) and I like that editor a lot! I've installed Debugger for Chrome from the extension store. The config below starts a new Chrome instance and I can start to debug. It stops on the breakpoint in vscode but here comes the problem. It doesn't show the values of the function and jumps into the node_modules event though I added it to "skipfiles".
Breakpoints also won't stop on the constructor. Is next.js somehow not supported?
I'm using async await syntax a lot. Debugging server side code works perfectly.

    {
        "name": "My Client",
        "type": "chrome",
        "request": "launch",
        "url": "http://localhost:3000",
        "webRoot": "${workspaceRoot}/my-client/",
        "skipFiles": [
            "node_modules/**/*.js",
            "<node_internals>/**/*.js",
            "node_modules",
            ".next"
        ]
    }


问:
Use default settings.xml file instead of one in ~/.m2
Is there possibility for Maven to ignore settings.xml contained in .m2 folder?

I want it to use default repository, but my laptop has configured development environment for other repositories and I don't want to lose these settings. What's more, these repositories have priority over repos in my pom.xml and fail if they can't download artifact.

What are the options? Should I choose other settings.xml file or is there option to use none?

答:
You don't have to have a settings.xml in the .m2 folder. If there is none Maven uses <Maven installation folder>/conf/settings.xml, which has everything commented out by default.

See also Settings Reference, Quick Overview:

There are two locations where a settings.xml file may live:

The Maven install: ${maven.home}/conf/settings.xml

A user’s install: ${user.home}/.m2/settings.xml

You can use custom settings files with the command line options:

-s,--settings

    Alternate path for the user settings file

-gs, --global-settings

    Alternate path for the global settings file

And, BTW, .m2 is not the Maven home. It's the folder for user-specific configuration and local repository. I corrected the question's title acordingly.


答:
Does this help clarify the process?

class App extends Component {
  constructor (props) {
    super(props)
    this.state = { counter: 0 }
    const { store } = props
    this.unsubscribe = store.subscribe(() => {
      const counter = store.getState()
      if (counter !== this.state.counter) {
        this.setState({ counter })
      }
    })
  }

  render () {
    return (

        <Counter
          value={this.state.counter}
          onIncrement={() =>
            this.props.store.dispatch({
              type: 'INCREMENT'
            })
          }
          onDecrement={() =>
            this.props.store.dispatch({
              type: 'DECREMENT'
            })
          } />

    )
  }
}
```

A few things to note:

This isn't a good solution for anything other than learning. react-redux does this in a much more maintainable and performant way.

Obviously, Redux state would normally be an object and not a single integer.

.subscribe is essentially just a way to set an event listener. When the state updates, any attached handlers will be called. What you do in your handler is pretty much up to you, although sensible precautions against unnecessary rendering would be pretty high on the list.

Title: Re-render React component on Redux state change

Body:
Does this help clarify the process?

class App extends Component {
  constructor (props) {
    super(props)
    this.state = { counter: 0 }
    const { store } = props
    this.unsubscribe = store.subscribe(() => {
      const counter = store.getState()
      if (counter !== this.state.counter) {
        this.setState({ counter })
      }
    })
  }

  render () {
    return (
      <div className='App'>
        <Counter
          value={this.state.counter}
          onIncrement={() =>
            this.props.store.dispatch({
              type: 'INCREMENT'
            })
          }
          onDecrement={() =>
            this.props.store.dispatch({
              type: 'DECREMENT'
            })
          } />
      </div>
    )
  }
}

A few things to note:

This isn't a good solution for anything other than learning. react-redux does this in a much more maintainable and performant way.

Obviously, Redux state would normally be an object and not a single integer.

.subscribe is essentially just a way to set an event listener. When the state updates, any attached handlers will be called. What you do in your handler is pretty much up to you, although sensible precautions against unnecessary rendering would be pretty high on the list.


问:
Android : XML buttons and programmatically created buttons have slightly different font weight (with same attributes)
I have an app with multiple buttons in a ScrollView, and I add more programmatically after the Activity start (custom user buttons).

All buttons have the same styles and attributes, but on screen the ones that are created programmatically have slightly bolder text.

I examined them in the layout inspector and they all have the same values for attributes like getTextSize (20), getTypefaceStyle (NORMAL), height, width, styles, ...

What could cause a different in boldness with the same values for those attributes?

Example of one XML Button :

```<code>            <Button
            android:id="@+id/button_autre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/background_selector2o"
            android:text="Bonbons"
            android:textAppearance="@style/TextAppearance.AppCompat"
            android:textStyle="normal"
            android:textAllCaps="false"
            android:textColor="#ffffff"
            android:textSize="20sp"
            android:layout_marginTop="20dp"
            />
</code>```

Example of one created Button :

```<code>        LinearLayout layout = (LinearLayout) view.findViewById(R.id.buttons_container);

        LinearLayout.LayoutParams layoutparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutparams.setMargins(0, px, 0, 0); // px calculated to be 20dp

        ContextThemeWrapper ndfContext = new ContextThemeWrapper(getActivity(), R.style.button_style_xml);
        Button addbutton = new Button(ndfContext);
        addbutton.setLayoutParams(layoutparams);
        addbutton.setText("Bonbons");
        addbutton.setBackgroundResource(R.drawable.background_selector2o);
        layout.addView(addbutton);
</code>```

Content of button_style_xml :

```<code><resources>
    <style name="ndftype_style" parent="AppTheme.NoActionBar">
        <item name="android:background">@drawable/background_selector2o</item>
        <item name="android:textAppearance">@style/TextAppearance.AppCompat</item>
        <item name="android:textColor">#ffffff</item>
        <item name="android:textSize">20sp</item>
        <item name="android:layout_marginTop">20dp</item>
        <item name="android:textAllCaps">false</item>
        <item name="android:textStyle">normal</item>
    </style>
</resources>
</code>```

Result :

答:
As is often the case, I got an idea while writing the question, thanks Canary Effect.

Despite all buttons having the same style and no font assigned to them anywhere, it seems Android was attributing a different default font to both kinds. I'm not sure why this is the case.

Adding

```<code><item name="android:fontFamily">sans-serif</item>
</code>```

on my programmatically created buttons solved the issue.
You might want to add it to your XML buttons too to be safe.

If you target API level < 16, running the following on all your buttons should work :

```<code>button.setTypeface(Typeface.DEFAULT);
</code>```

Body:
I have an app with multiple buttons in a ScrollView, and I add more programmatically after the Activity start (custom user buttons).

All buttons have the same styles and attributes, but on screen the ones that are created programmatically have slightly bolder text.

I examined them in the layout inspector and they all have the same values for attributes like getTextSize (20), getTypefaceStyle (NORMAL), height, width, styles, ...

What could cause a different in boldness with the same values for those attributes?

Example of one XML Button :

            <Button
            android:id="@+id/button_autre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/background_selector2o"
            android:text="Bonbons"
            android:textAppearance="@style/TextAppearance.AppCompat"
            android:textStyle="normal"
            android:textAllCaps="false"
            android:textColor="#ffffff"
            android:textSize="20sp"
            android:layout_marginTop="20dp"
            />

Example of one created Button :

        LinearLayout layout = (LinearLayout) view.findViewById(R.id.buttons_container);

        LinearLayout.LayoutParams layoutparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutparams.setMargins(0, px, 0, 0); // px calculated to be 20dp

        ContextThemeWrapper ndfContext = new ContextThemeWrapper(getActivity(), R.style.button_style_xml);
        Button addbutton = new Button(ndfContext);
        addbutton.setLayoutParams(layoutparams);
        addbutton.setText("Bonbons");
        addbutton.setBackgroundResource(R.drawable.background_selector2o);
        layout.addView(addbutton);

Content of button_style_xml :

<resources>

</resources>

Result :

Body:
As is often the case, I got an idea while writing the question, thanks Canary Effect.

Despite all buttons having the same style and no font assigned to them anywhere, it seems Android was attributing a different default font to both kinds. I'm not sure why this is the case.

Adding

<item name="android:fontFamily">sans-serif</item>

on my programmatically created buttons solved the issue.
You might want to add it to your XML buttons too to be safe.

If you target API level < 16, running the following on all your buttons should work :

button.setTypeface(Typeface.DEFAULT);


答:
If you aren't allowed to use standard datetime library then you could at worst modify add_minutes so that:

```<code>your_return_string = hours + ':' + minutes

if get_minutes() < 10:
    your_return_string = hours + ':' + '0' + minutes

if get_hours() < 10:
    your_return_string = '0' + your_return_string
</code>```

Title: How to add zero to a time

Body:
If you aren't allowed to use standard datetime library then you could at worst modify add_minutes so that:

your_return_string = hours + ':' + minutes

if get_minutes() < 10:
    your_return_string = hours + ':' + '0' + minutes

if get_hours() < 10:
    your_return_string = '0' + your_return_string