问:
My DNN return the same prediction for all test data (tensorflow)
I am trying to run this code on my data for regression. It seems the the network can predict the first test data but all other predictions are the same as the first one. The first function generates random weights for initialization. The number of predictors is 54 and the number of outputs is 4. Here is my code:</p>

```<code>def init_weights(shape):
   weights = tf.random_uniform(shape, -2,2)
   return tf.Variable(weights)

def forwardprop(X, w, b, sig):
   if sig==1:
       yhat = tf.sigmoid(tf.add(tf.matmul(X, w),b))
   else:
       yhat = tf.add(tf.matmul(X, w),0.)
return yhat

def main(itr,starter_learning_rate):

   x_size = train_X.shape[1]
   h_size = 4
   y_size = train_y.shape[1]

   X = tf.placeholder("float", shape = [None, x_size])
   y = tf.placeholder("float", shape = [None, y_size])

   w_1 = init_weights((x_size, h_size))
   b_1 =  tf.constant(1.)

   w_2 = init_weights((h_size, y_size))
   b_2 =  tf.constant(1.)

   yhat_1 = forwardprop(X, w_1, b_1, 1)
   yhat =  forwardprop(yhat_1, w_2, b_2, 0)

   n_samples = train_X.shape[0]
   cost = tf.reduce_sum(tf.pow(yhat-y, 2))/(2*n_samples)
   updates = tf.train.GradientDescentOptimizer(starter_learning_rate).minimize(cost)

   sess = tf.Session()
   init = tf.global_variables_initializer()
   sess.run(init)

   for epoch in range(itr):
       sess.run(updates, feed_dict={X: train_X, y: train_y})
       train_err = train_y - sess.run(yhat, feed_dict={X: train_X, y: train_y})
       train_accuracy = np.mean(train_err**2)

       test_err  = test_y - sess.run(yhat, feed_dict={X: test_X, y: test_y})
       test_accuracy  =np.mean(test_err**2)

   print(sess.run(yhat, feed_dict={X: test_X, y: test_y}))
   sess.close()
if __name__ == '__main__':
   main(itr=10000,starter_learning_rate=0.001)
</code>```

答: Normalization of the label vector was the solution.</p>

Body:
I am trying to run this code on my data for regression. It seems the the network can predict the first test data but all other predictions are the same as the first one. The first function generates random weights for initialization. The number of predictors is 54 and the number of outputs is 4. Here is my code:

def init_weights(shape):
   weights = tf.random_uniform(shape, -2,2)
   return tf.Variable(weights)

def forwardprop(X, w, b, sig):
   if sig==1:
       yhat = tf.sigmoid(tf.add(tf.matmul(X, w),b))
   else:
       yhat = tf.add(tf.matmul(X, w),0.)
return yhat

def main(itr,starter_learning_rate):

   x_size = train_X.shape[1]
   h_size = 4
   y_size = train_y.shape[1]

   X = tf.placeholder("float", shape = [None, x_size])
   y = tf.placeholder("float", shape = [None, y_size])

   w_1 = init_weights((x_size, h_size))
   b_1 =  tf.constant(1.)

   w_2 = init_weights((h_size, y_size))
   b_2 =  tf.constant(1.)

   yhat_1 = forwardprop(X, w_1, b_1, 1)
   yhat =  forwardprop(yhat_1, w_2, b_2, 0)

   n_samples = train_X.shape[0]
   cost = tf.reduce_sum(tf.pow(yhat-y, 2))/(2*n_samples)
   updates = tf.train.GradientDescentOptimizer(starter_learning_rate).minimize(cost)

   sess = tf.Session()
   init = tf.global_variables_initializer()
   sess.run(init)

   for epoch in range(itr):
       sess.run(updates, feed_dict={X: train_X, y: train_y})
       train_err = train_y - sess.run(yhat, feed_dict={X: train_X, y: train_y})
       train_accuracy = np.mean(train_err**2)

       test_err  = test_y - sess.run(yhat, feed_dict={X: test_X, y: test_y})
       test_accuracy  =np.mean(test_err**2)

   print(sess.run(yhat, feed_dict={X: test_X, y: test_y}))
   sess.close()
if __name__ == '__main__':
   main(itr=10000,starter_learning_rate=0.001)


来源: stackexchange

问:
Split string into two parts of same size by words only in java/android
how to split one string into two parts of same size but not between word ?

i want to split one string into two same size parts but string should not be split between words but it only be spit between white spaces only.

答:
For Split String with odd Length and even Length I use below Code and I answered.</p>

```<code>String st= (String) st.getText().toString().trim();
              int length = st.length();
                boolean flag = length%2==0?true:false;
                String[] splits = new String[2];
                if(flag){
                    splits[0] = st.substring(0, length/2);
                    splits[1] = st.substring(length/2, length);
                }else{
                    int middle = length/2;
                    splits[0] = st.substring(0, middle);
                    splits[1] = st.substring(middle, length);
                }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For Split String with odd Length and even Length I use below Code and I answered.

String st= (String) st.getText().toString().trim();
              int length = st.length();
                boolean flag = length%2==0?true:false;
                String[] splits = new String[2];
                if(flag){
                    splits[0] = st.substring(0, length/2);
                    splits[1] = st.substring(length/2, length);
                }else{
                    int middle = length/2;
                    splits[0] = st.substring(0, middle);
                    splits[1] = st.substring(middle, length);
                }


问:
how to convert the x-axis accelerator signal into spectrogram in python?
my dataset (patient No., time/millisecond, x, y, z, label)

```<code>1,15,70,39,-970,0
1,31,70,39,-970,0
1,46,60,49,-960,0
1,62,60,49,-960,0
1,78,50,39,-960,0
1,93,50,39,-960,0
.
.
.
</code>```

i am trying to to use the spectrogam for x-axis signal in preprocessing stage to use it then as the input data for a machine learning model instead of using the original raw x-axis data

here is what i tried to do

```<code>import matplotlib.pyplot as plt
import numpy as np

dt = 0.0005
t = np.arange(0.0, 20.0, dt)

data = np.loadtxt("trainingdataset.txt", delimiter=",")
x = data[:]

NFFT = 1024       # the length of the windowing segments
Fs = int(1.0/dt)  # the sampling frequency

ax1 = plt.subplot(211)
plt.plot(x)
plt.subplot(212, sharex=ax1)
Pxx, freqs, bins, im = plt.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
plt.show()
</code>```

it gets me the following error

```<code>Warning (from warnings module):
  File "C:\Users\hadeer.elziaat\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 7221
    Z = 10. * np.log10(spec)
RuntimeWarning: divide by zero encountered in log10
</code>```

答: If x is your signal and you can assume that your sampling rate is the mean of time/millisecond, then probably you can use the librosa library to compute the mel-spectrogram using librosa.feature.melspectrogram, there's also other utils to compute signal related features.

Body:
my dataset (patient No., time/millisecond, x, y, z, label)

1,15,70,39,-970,0
1,31,70,39,-970,0
1,46,60,49,-960,0
1,62,60,49,-960,0
1,78,50,39,-960,0
1,93,50,39,-960,0
.
.
.

i am trying to to use the spectrogam for x-axis signal in preprocessing stage to use it then as the input data for a machine learning model instead of using the original raw x-axis data

here is what i tried to do

import matplotlib.pyplot as plt
import numpy as np

dt = 0.0005
t = np.arange(0.0, 20.0, dt)

data = np.loadtxt("trainingdataset.txt", delimiter=",")
x = data[:]

NFFT = 1024       # the length of the windowing segments
Fs = int(1.0/dt)  # the sampling frequency

ax1 = plt.subplot(211)
plt.plot(x)
plt.subplot(212, sharex=ax1)
Pxx, freqs, bins, im = plt.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
plt.show()

it gets me the following error

Warning (from warnings module):
  File "C:\Users\hadeer.elziaat\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 7221
    Z = 10. * np.log10(spec)
RuntimeWarning: divide by zero encountered in log10


问:
Racket syntax error using 'let star'
In the program listed below, I'm getting the error message:

let*: bad syntax (not an identifier and expression for a binding) in: pokemon1inPokedex

I'm not sure why, any advice would be appreciated!

my code

```<code>(define (in-order? pokemon1name pokemon2name)
  (let*
    [pokemon1inPokedex (inPokedex? pokemon1name)]
    [pokemon2inPokedex (inPokedex? pokemon2name)])
  (cond [(and pokemon1inPokedex pokemon2inPokedex) (greater pokemon1name pokemon2name)]
        [(true? pokemon1inPokedex) #t]
        [(true? pokemon2inPokedex) #f]
        [else #f]))
</code>```

答:
The problem is that you have incorrect syntax with let*.

From the racket guide, the syntax for let* is

```<code>(let* ([id val-expr] ...) body ...+)
</code>```

Note the missing ( and ) parens for the identifiers you are binding, as well as your moved closing ).

Modifying your example to use the the let* form correctly will result in code that looks something like:

```<code>(define (in-order? pokemon1name pokemon2name)
  (let* ([pokemon1inPokedex ...]
         [pokemon2inPokedex ...])
    (cond [(and pokemon1inPokedex) ...]
          [pokemon1inPokedex ...]
          [pokemon2inPokedex ...]
          [else ...]))
</code>```

Obviously I've left the ... for you to fill in.

As a side note, pokemon1inPokedex doesn't really follow any normal Racket naming convention that I am aware of. Following standard naming conventions in Racket would give you pokemon1-in-pokedex?

Title: Racket syntax error using 'let star'

Body:
In the program listed below, I'm getting the error message:

let*: bad syntax (not an identifier and expression for a binding) in: pokemon1inPokedex

I'm not sure why, any advice would be appreciated!

my code

(define (in-order? pokemon1name pokemon2name)
  (let*
    [pokemon1inPokedex (inPokedex? pokemon1name)]
    [pokemon2inPokedex (inPokedex? pokemon2name)])
  (cond [(and pokemon1inPokedex pokemon2inPokedex) (greater pokemon1name pokemon2name)]
        [(true? pokemon1inPokedex) #t]
        [(true? pokemon2inPokedex) #f]
        [else #f]))

Body:
The problem is that you have incorrect syntax with let*.

From the racket guide, the syntax for let* is

(let* ([id val-expr] ...) body ...+)

Note the missing ( and ) parens for the identifiers you are binding, as well as your moved closing ).

Modifying your example to use the the let* form correctly will result in code that looks something like:

(define (in-order? pokemon1name pokemon2name)
  (let* ([pokemon1inPokedex ...]
         [pokemon2inPokedex ...])
    (cond [(and pokemon1inPokedex) ...]
          [pokemon1inPokedex ...]
          [pokemon2inPokedex ...]
          [else ...]))

Obviously I've left the ... for you to fill in.

As a side note, pokemon1inPokedex doesn't really follow any normal Racket naming convention that I am aware of. Following standard naming conventions in Racket would give you pokemon1-in-pokedex?


问:
level of the child in the table recursion php?
The problem is to deduce the level of nesting relative to id. Here is an example of db:
http://sqlfiddle.com/#!9/22b0d2/1

Here is an example of the php code:

```<code>function getCats($res){

    $levels = array();
    $tree = array();
    $cur = array();

    while($rows = mysqli_fetch_assoc($res)){

        $cur = &$levels[$rows['id']];
        $cur['parent_id'] = $rows['parent_id'];
        $cur['name'] = $rows['name'];

        if($rows['parent_id'] == 0){
            $tree[$rows['id']] = &$cur;
        }
        else{
            $levels[$rows['parent_id']]['children'][$rows['id']] = &$cur;
        }

    }

    return $tree;

}

function getTree($arr){

    $out = '';
    $counter = 1;

    $out .= '<ul>';
    foreach($arr as $k=>$v){
        $out .= '<li><a href="?id='.$k.'">'.$v['name'].'</a></li>';
        if(!empty($v['children'])){
            $out .= getTree($v['children']);
        }

    }
    $out .= '</ul>';
    return $out;

}
$mysql = new mysqli('localhost', 'root', '', 'testids');
$res = $mysql->query("SELECT * FROM categories ORDER BY id");
$cats = getCats($res);
echo getTree($cats);
</code>```

Please help remake the function so that it's like this:
Just look not from the
, but from the
. If we look from the id = 1, then at the first level we have id 2 and id 3, and on the second level id 5, because they are children from id 1.

```<code>    Array
(
    [1] => Array
        (
            [parent_id] => 0
            [name] => name1
            [children] => Array
                (
                    [2] => Array
                        (
                            [parent_id] => 1
                            [name] => name2
                            [children] => Array
                                (
                                    [4] => Array
                                        (
                                            [parent_id] => 2
                                            [name] => name4
                                            [children] => Array
                                                (
                                                    [5] => Array
                                                        (
                                                            [parent_id] => 4
                                                            [name] => name5
                                                        )

                                                )

                                        )

                                )

                        )

                    [3] => Array
                        (
                            [parent_id] => 1
                            [name] => name3
                        )

                )

        )

)
</code>```

答:
There are several solutions out there for this problem.

The one below is modified from https://www.sitepoint.com/hierarchical-data-database/

```<code><?php

function getConnection() {
    try {
        $con = new PDO('sqlite:db.sqlite3') or die('connot open database');
        return $con;
    } catch(PDOException $e) {
        echo $e;
        return null;
    }
}

function showChildren($parent, $level) {
    $con = getConnection();
    if ($con) {
       $stmt = $con->query('SELECT id, name, parent_id from categories WHERE parent_id = ' . $parent);
       while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
          echo '<tr>';
          echo '<td>' . $row['id'] . '</td>';
          echo '<td>' . $level . '</td>';
          echo '<td>' . $row['name'] . '</td>';
          echo '</tr>';
          showChildren($row['id'], $level+1);
      }
   }
}

echo '<table>';
echo '<tr><th>ID</th><th>LEVEL</th><th>NAME</th></tr>';

showChildren(0, 0);

echo '</table>';
</code>```

Please note this is probably terrible PHP code.  Positive it doesn't adhear to recent coding standards, such as template strings, prepared statements and such.  However it will create the table in your question.

Body:
The problem is to deduce the level of nesting relative to id. Here is an example of db:
http://sqlfiddle.com/#!9/22b0d2/1

Here is an example of the php code:

function getCats($res){

    $levels = array();
    $tree = array();
    $cur = array();

    while($rows = mysqli_fetch_assoc($res)){

        $cur = &$levels[$rows['id']];
        $cur['parent_id'] = $rows['parent_id'];
        $cur['name'] = $rows['name'];

        if($rows['parent_id'] == 0){
            $tree[$rows['id']] = &$cur;
        }
        else{
            $levels[$rows['parent_id']]['children'][$rows['id']] = &$cur;
        }

    }

    return $tree;

}

function getTree($arr){

    $out = '';
    $counter = 1;

    $out .= '
';
    foreach($arr as $k=>$v){
        $out .= '
'.$v['name'].'
';
        if(!empty($v['children'])){
            $out .= getTree($v['children']);
        }

    }
    $out .= '
';
    return $out;

}
$mysql = new mysqli('localhost', 'root', '', 'testids');
$res = $mysql->query("SELECT * FROM categories ORDER BY id");
$cats = getCats($res);
echo getTree($cats);

Please help remake the function so that it's like this:
Just look not from the
, but from the
. If we look from the id = 1, then at the first level we have id 2 and id 3, and on the second level id 5, because they are children from id 1.

    Array
(
    [1] => Array
        (
            [parent_id] => 0
            [name] => name1
            [children] => Array
                (
                    [2] => Array
                        (
                            [parent_id] => 1
                            [name] => name2
                            [children] => Array
                                (
                                    [4] => Array
                                        (
                                            [parent_id] => 2
                                            [name] => name4
                                            [children] => Array
                                                (
                                                    [5] => Array
                                                        (
                                                            [parent_id] => 4
                                                            [name] => name5
                                                        )

                                                )

                                        )

                                )

                        )

                    [3] => Array
                        (
                            [parent_id] => 1
                            [name] => name3
                        )

                )

        )

)

Body:
There are several solutions out there for this problem.

The one below is modified from https://www.sitepoint.com/hierarchical-data-database/

<?php

function getConnection() {
    try {
        $con = new PDO('sqlite:db.sqlite3') or die('connot open database');
        return $con;
    } catch(PDOException $e) {
        echo $e;
        return null;
    }
}

function showChildren($parent, $level) {
    $con = getConnection();
    if ($con) {
       $stmt = $con->query('SELECT id, name, parent_id from categories WHERE parent_id = ' . $parent);
       while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
          echo '<tr>';
          echo '<td>' . $row['id'] . '</td>';
          echo '<td>' . $level . '</td>';
          echo '<td>' . $row['name'] . '</td>';
          echo '</tr>';
          showChildren($row['id'], $level+1);
      }
   }
}

echo '<table>';
echo '<tr><th>ID</th><th>LEVEL</th><th>NAME</th></tr>';

showChildren(0, 0);

echo '</table>';

Please note this is probably terrible PHP code.  Positive it doesn't adhear to recent coding standards, such as template strings, prepared statements and such.  However it will create the table in your question.


问:
Efficient way to iterate through a very large csv file with integers?
Input 1: A .csv file with a long list of integers. Ex:

```<code>1
10
23
2450
12
560
320
705
...
</code>```

Input 2: A .csv file with a list of integers, and a blank position next to each integer

```<code>5 -
12 -
15 -
13 -
350 -
</code>```

Output: Find the count of integers from input 1 that the input 2 integer is greater than or equal to and append the number into the .csv file.

The catch is that this involves DNA sequencing, and input 1 has over a million data entries. What would be an efficient way to approach this problem?

My thoughts were to read in all entries of input 1 into one large array and sort it, but that seems both inefficient and requires a lot of memory. Any guidance would be greatly appreciated.

Edit:

Output (same file as input 2):

int, count

```<code>5 1
12 3
15 3
13 3
350 5
</code>```

答:
Put the numbers from the second file into a sorted map, with a value zero:

```<code>TreeMap<Integer, Integer> counts = new TreeMap<>();
for (Integer i : fromFile2) {
  counts.put(i, 0);
}
</code>```

Then, for each number your read from the first file, increment the counts up to that number:

```<code>for (Integer i : fromFile1) {
  counts.headMap(i).replaceAll((k, v) -> v + 1);
}
</code>```

Note that this second loop doesn't require you to read the entire file into memory: you can just read them one at a time.

Also, note that headMap(i) returns entries with keys strictly less than i. Assuming i < Integer.MAX_VALUE, you can simply add 1 to that value.

Body:
Input 1: A .csv file with a long list of integers. Ex:

1
10
23
2450
12
560
320
705
...

Input 2: A .csv file with a list of integers, and a blank position next to each integer

5 -
12 -
15 -
13 -
350 -

Output: Find the count of integers from input 1 that the input 2 integer is greater than or equal to and append the number into the .csv file.

The catch is that this involves DNA sequencing, and input 1 has over a million data entries. What would be an efficient way to approach this problem?

My thoughts were to read in all entries of input 1 into one large array and sort it, but that seems both inefficient and requires a lot of memory. Any guidance would be greatly appreciated.

Edit:

Output (same file as input 2):

int, count

5 1
12 3
15 3
13 3
350 5

Body:
Put the numbers from the second file into a sorted map, with a value zero:

TreeMap<Integer, Integer> counts = new TreeMap<>();
for (Integer i : fromFile2) {
  counts.put(i, 0);
}

Then, for each number your read from the first file, increment the counts up to that number:

for (Integer i : fromFile1) {
  counts.headMap(i).replaceAll((k, v) -> v + 1);
}

Note that this second loop doesn't require you to read the entire file into memory: you can just read them one at a time.

Also, note that headMap(i) returns entries with keys strictly less than i. Assuming i < Integer.MAX_VALUE, you can simply add 1 to that value.


问:
sp_blitz Monitoring and Alerts

I'd like to use sp_blitz for Monitoring.  I have Alerts 16 - 25 configured, as well as 823, 824, 825.

    These are the names:

```<code>Fatal Error Database  Integrity Suspect Severity 023
Fatal Error in Current Process Severity 020
Fatal Error in Database Process Severity 021
Fatal Error in Resource Severity 019
Fatal Error Severity 025
Fatal Error Table Integrity Suspect Severity 022
Hardware Error Severity 024
Insufficient Resources Severity 017
IO Error Corruption Error Number 824
Memory Error Error Number 823
Misc User Error Severity 016
Nonfatal Internal Error Severity 018
Possible IO Error Corruption Error Number 825
</code>```

  I have the alerts configured, an operator, and the notification sent to email for that operator.  I have all of the alerts configured, but sp_blitz is not finding

Since I'm new at sp_blitz, and MS SQL, I'm searching to see if I've done something not right, or at least not right for sp_blitz which is such a great tool.  I named the alerts to be more informational, could that be an issue?

Executing sp_blitz shows errors in the FindingsGroup 'Monitoring' for (1) alerts not configured with a followup, No alerts for corruption, no alerts for sev 19-25, no operators configured, No operators enabled, not all alerts are configured.

答:
It's entirely possible that you've found a bug. (I know, right? Impossible!)

The nice thing about open source is that you can just edit it. Look at the script, and do a control-F to find the section of the script that matches up with the alerts you're getting. I promise, it's super-simple to read.

Then, copy out that query, and try to run it. Look at which DMVs appear to be giving false results. Maybe an alert is disabled, for example.

Then, if you think you've found a bug, file a bug report over in the Github repo for the First Responder Kit. Read down that page - there's plenty of info there on how to contribute, file issues, and get help.

ContentLicense: CC BY-SA 4.0

Title: sp_blitz Monitoring and Alerts

Body:
I'd like to use sp_blitz for Monitoring.  I have Alerts 16 - 25 configured, as well as 823, 824, 825.

    These are the names:

Fatal Error Database  Integrity Suspect Severity 023
Fatal Error in Current Process Severity 020
Fatal Error in Database Process Severity 021
Fatal Error in Resource Severity 019
Fatal Error Severity 025
Fatal Error Table Integrity Suspect Severity 022
Hardware Error Severity 024
Insufficient Resources Severity 017
IO Error Corruption Error Number 824
Memory Error Error Number 823
Misc User Error Severity 016
Nonfatal Internal Error Severity 018
Possible IO Error Corruption Error Number 825

  I have the alerts configured, an operator, and the notification sent to email for that operator.  I have all of the alerts configured, but sp_blitz is not finding

Since I'm new at sp_blitz, and MS SQL, I'm searching to see if I've done something not right, or at least not right for sp_blitz which is such a great tool.  I named the alerts to be more informational, could that be an issue?

Executing sp_blitz shows errors in the FindingsGroup 'Monitoring' for (1) alerts not configured with a followup, No alerts for corruption, no alerts for sev 19-25, no operators configured, No operators enabled, not all alerts are configured.


问:
SQL Finding MAX number in a VARCHAR typed column
I have got SQL table where I have column DISTANCE (varchar50). It's number with dot.

```<code>+----+--------+--------+----------+
| ID | USERID | MONTH  | DISTANCE |
+----+--------+--------+----------+
| 1  |    1   | 201707 |   7.25   |
+----+--------+--------+----------+
| 2  |    2   | 201707 |   9.17   |
+----+--------+--------+----------+
| 3  |    2   | 201707 |  10.31   |
+----+--------+--------+----------+
| 4  |    1   | 201706 |  10.08   |
+----+--------+--------+----------+
</code>```

I would like to display MAX value od DISTANCE. If I ORDER BY distance DESC the result is:

```<code>SELECT * FROM mytable ORDER BY distance DESC
9.17
7.25
10.31
10.08
</code>```

I try to find the MAX but still is not correct

```<code>SELECT MAX(distance) AS mvzd FROM mytable
9.17
</code>```

How I can have correct max distance value which should be 10.31 with the provided sample data ?

答:
The problem is that you use wrong data type of the DISTANCE. In your case you store the distance values as varchar and that's why the ORDER BY and MAX() functions does not work as expected - in this case the ORDER BY is sorting values as a string from the very first character. In your example you tried to sorted in descending order to be like from lowest to larger - this will give you "unexpected" results if there will be value like 98.76 or 111.15.

All you need is to set the data type of DISTANCE column to float - a small number with a floating decimal point.

Change settings of your table to use float:

```<code>ALTER TABLE `mytable`
  CHANGE COLUMN `distance` `distance`
  FLOAT NULL DEFAULT NULL AFTER `month`;
</code>```

Data stored as float will support all native functions such as MIN, MAX, ORDER BY etc. which will work as expected without any workarounds.

Here is corrected example using float: http://sqlfiddle.com/#!9/1f8692/1

Here is extended example using incorrect varchar(50): http://sqlfiddle.com/#!9/4da754e/1

Body:
I have got SQL table where I have column DISTANCE (varchar50). It's number with dot.

+----+--------+--------+----------+
| ID | USERID | MONTH  | DISTANCE |
+----+--------+--------+----------+
| 1  |    1   | 201707 |   7.25   |
+----+--------+--------+----------+
| 2  |    2   | 201707 |   9.17   |
+----+--------+--------+----------+
| 3  |    2   | 201707 |  10.31   |
+----+--------+--------+----------+
| 4  |    1   | 201706 |  10.08   |
+----+--------+--------+----------+

I would like to display MAX value od DISTANCE. If I ORDER BY distance DESC the result is:

SELECT * FROM mytable ORDER BY distance DESC
9.17
7.25
10.31
10.08

I try to find the MAX but still is not correct

SELECT MAX(distance) AS mvzd FROM mytable
9.17

How I can have correct max distance value which should be 10.31 with the provided sample data ?

Body:
The problem is that you use wrong data type of the DISTANCE. In your case you store the distance values as varchar and that's why the ORDER BY and MAX() functions does not work as expected - in this case the ORDER BY is sorting values as a string from the very first character. In your example you tried to sorted in descending order to be like from lowest to larger - this will give you "unexpected" results if there will be value like 98.76 or 111.15.

All you need is to set the data type of DISTANCE column to float - a small number with a floating decimal point.

Change settings of your table to use float:

ALTER TABLE `mytable`
  CHANGE COLUMN `distance` `distance`
  FLOAT NULL DEFAULT NULL AFTER `month`;

Data stored as float will support all native functions such as MIN, MAX, ORDER BY etc. which will work as expected without any workarounds.

Here is corrected example using float: http://sqlfiddle.com/#!9/1f8692/1

Here is extended example using incorrect varchar(50): http://sqlfiddle.com/#!9/4da754e/1


问:
Are either of os.rmdir or shutil.rmtree guaranteed or supposed to be synchronous on Windows?
It appears that shutil.rmtree is not synchronous on Windows, as I've had the second line in the following code raise an error that the directory already exists

```<code>shutil.rmtree(my_dir)
os.makedirs(my_dir) #intermittently raises Windows error 183 - already exists
</code>```

We see a similar issue in .NET on windows - see this question . Are there any good options to deal with this in python other than polling to see if the folder really is gone?

答:
If you're okay with the folder still existing, and you're on Python 3, you can do pass exist_ok=True to os.makedirs, and it will ignore the case where you try to make a directory that already exists:

```<code>shutil.rmtree(my_dir)
os.makedirs(my_dir, exist_ok=True)
</code>```

Failing that, you're stuck polling. Run your code in a loop (ideally with a small sleep to avoid hammering the disk), and don't end the loop until the makedirs finishes without error:

```<code>import errno, os, shutil, time

while True:
    # Blow away directory
    shutil.rmtree(my_dir, ignore_errors=True)
    try:
        # Try to recreate
        os.makedirs(my_dir)
    except OSError as e:
        # If problem is that directory still exists, wait a bit and try again
        if e.winerror == 183:
            time.sleep(0.01)
            continue
        # Otherwise, unrecognized error, let it propagate
        raise
    else:
        # Successfully created empty dir, exit loop
        break
</code>```

On Python 3.3+, you can probably change:

```<code>    except WindowsError as e:
        # If problem is that directory still exists, wait a bit and try again
        if e.errno == errno.EEXIST:
            time.sleep(0.01)
            continue
        # Otherwise, unrecognized error, let it propagate
        raise
</code>```

to just:

```<code>    except FileExistsError:
        # If problem is that directory still exists, wait a bit and try again
        time.sleep(0.01)
</code>```

as there is a specific exception type for "file exists" which you can catch directly (and let all other OSError/WindowsError exceptions propagate without interruption).

Body:
It appears that shutil.rmtree is not synchronous on Windows, as I've had the second line in the following code raise an error that the directory already exists

shutil.rmtree(my_dir)
os.makedirs(my_dir) #intermittently raises Windows error 183 - already exists

We see a similar issue in .NET on windows - see this question . Are there any good options to deal with this in python other than polling to see if the folder really is gone?

Body:
If you're okay with the folder still existing, and you're on Python 3, you can do pass exist_ok=True to os.makedirs, and it will ignore the case where you try to make a directory that already exists:

shutil.rmtree(my_dir)
os.makedirs(my_dir, exist_ok=True)

Failing that, you're stuck polling. Run your code in a loop (ideally with a small sleep to avoid hammering the disk), and don't end the loop until the makedirs finishes without error:

import errno, os, shutil, time

while True:
    # Blow away directory
    shutil.rmtree(my_dir, ignore_errors=True)
    try:
        # Try to recreate
        os.makedirs(my_dir)
    except OSError as e:
        # If problem is that directory still exists, wait a bit and try again
        if e.winerror == 183:
            time.sleep(0.01)
            continue
        # Otherwise, unrecognized error, let it propagate
        raise
    else:
        # Successfully created empty dir, exit loop
        break

On Python 3.3+, you can probably change:

    except WindowsError as e:
        # If problem is that directory still exists, wait a bit and try again
        if e.errno == errno.EEXIST:
            time.sleep(0.01)
            continue
        # Otherwise, unrecognized error, let it propagate
        raise

to just:

    except FileExistsError:
        # If problem is that directory still exists, wait a bit and try again
        time.sleep(0.01)

as there is a specific exception type for "file exists" which you can catch directly (and let all other OSError/WindowsError exceptions propagate without interruption).


问:
JayDeBeApi Crashing on Connection
I'm trying to connect to a GoodData warehouse through Python using the JayDeBeApi modules but for whatever reason whenever I make the connection the console immediately crashes.

I've been able to successfully connect using the SQL client DBVisualizer with the jar file they have me but it doesn't appear to be working for Python.

code:

```<code>import jaydebeapi

connection = jaydebeapi.connect('com.gooddata.dss.jdbc.driver.DssDriver',
                            ['jdbc:dss://na1.secure.gooddata.com/gdc/dss/instances/INSTANCE_ID','user','password'],
                            'JAR_FILE')
</code>```

Anyone have any insight into why this may be crashing? I'm not able to get any error logging returned. If there is another module you can use to connect to JDBC DB that'd also be helpful.

Appreciate the help!

答:
In my case it was crashing on connection because I had a 32-bit version of Python installed but a 64-bit version of Java. This is listed as a cause of crashes in JPype's documentation:

Mixing 64 bit Python with 32 bit Java and vice versa crashes on import jpype.

After installing 64-bit Python and using that instead, I was able to connect without any problems.

Title: JayDeBeApi Crashing on Connection

Body:
I'm trying to connect to a GoodData warehouse through Python using the JayDeBeApi modules but for whatever reason whenever I make the connection the console immediately crashes.

I've been able to successfully connect using the SQL client DBVisualizer with the jar file they have me but it doesn't appear to be working for Python.

code:

import jaydebeapi

connection = jaydebeapi.connect('com.gooddata.dss.jdbc.driver.DssDriver',
                            ['jdbc:dss://na1.secure.gooddata.com/gdc/dss/instances/INSTANCE_ID','user','password'],
                            'JAR_FILE')

Anyone have any insight into why this may be crashing? I'm not able to get any error logging returned. If there is another module you can use to connect to JDBC DB that'd also be helpful.

Appreciate the help!


问:
Hornetq Core Bridge - one publisher, multiple consumers
Server A publishes data to the topic source/topic and two durable subscribers sub-b and sub-c are configured to listen to the topic. Subscribers  sub-b and sub-c will receive the identical data.

Is there a way to configure in HornetQ using multiple core bridges to publish message from sub-b channel to server B and from sub-c channel to server C.

As per the Horentq documentation they suggest to use core bridge instead of JMS bridge if possible.

It's always preferable to use a core bridge if you can.

bridgeType Schema definition does not seem to support to use subscriber name as in the case of JMS bridge bean definition.

The workaround I came up with is to use JMS but I was wondering if anyone came across this issue before and would you mind sharing your thoughts on this?

答:
A JMS topic (i.e. source/topic) is represented in the broker simply as an address.  A JMS subscription (i.e. sub-b and sub-c) is represented in the broker as a queue associated with the relevant address (source/topic in this case).  The queues internal name is a combination of details from the JMS subscriber (e.g. client ID, subscription name, etc.).  When a message is sent to the JMS topic the broker routes a reference to that message to each subscription so that every subscription gets every message (assuming their selectors match).

A core bridge listens for messages arriving in an queue and then forwards those messages to an address either locally or on a remote broker.

In your case, you can create a bridge which listens on the queue of the JMS subscription and then forwards that message to a remote broker of your choosing.


问:
Can't connect from IIS to localDB
I'm trying to develop a WebService between me and my roomate (so a local one).

I created a Database (.mdf) saved in one of my folders and some aspx pages that access to it and retrieve informations.
Now I was trying to deploy the project under IIS and I'm getting a problem when I have to access to the local db.

provider: SQL Network Interfaces, error: 50 Server not found or not
  accessible.

Everything from Web Visual Studio works fine! So if I try to connect the DB just running from VS on Google Chrome everything is fine. This error appears only when I try to run it under IIS 8.0

```<code>(my string connection = Server=(LocalDB)\\v11.0;

AttachDbFilename=C:\\Users\\Asus\\Desktop\\RobaMia\\SQLSERVER\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database2.mdf;
Integrated Security=True;Connect Timeout=30;User Instance=False)
</code>```

Could it be that "User Instance = False" makes the trick?

I say also that all my application pools are user-set
http://i.imgur.com/jrOZxTO.jpg

答:
I had this in my web.config. Removing it fixed the issue for me

<identity impersonate="true" />

Title: Can't connect from IIS to localDB

Body:
I'm trying to develop a WebService between me and my roomate (so a local one).

I created a Database (.mdf) saved in one of my folders and some aspx pages that access to it and retrieve informations.
Now I was trying to deploy the project under IIS and I'm getting a problem when I have to access to the local db.

provider: SQL Network Interfaces, error: 50 Server not found or not
  accessible.

Everything from Web Visual Studio works fine! So if I try to connect the DB just running from VS on Google Chrome everything is fine. This error appears only when I try to run it under IIS 8.0

(my string connection = Server=(LocalDB)\\v11.0;

AttachDbFilename=C:\\Users\\Asus\\Desktop\\RobaMia\\SQLSERVER\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database2.mdf;
Integrated Security=True;Connect Timeout=30;User Instance=False)

Could it be that "User Instance = False" makes the trick?

I say also that all my application pools are user-set
http://i.imgur.com/jrOZxTO.jpg


问:
GRPC server response latency
First off, has anyone done a performance comparison for throughput/latency between a GRPC client-server implementation v/s a websocket+protobuf client-server implementation? Or at least something similary.

In order to reach this goal, I am trying out the example JAVA helloworld grpc client-server and trying to compare the latency of the response with a similar websocket client-server. Currently i am trying this out with both client and server on my local machine.

The websocket client-server has a simple while loop on the server side. For the grpc server i notice that it uses an asynchronous execution model. I suspect it creates a new thread for each client request, resulting in additional processing overheads. For instance, the websocket response latency i am measuring is in the order of 6-7 ms and the grpc example is showing a latency of about 600-700ms, accounting for protobuf overhead.

In order to do a similar comparison for grpc, is there a way to run the grpc server synchronously? I want to be able to eliminate the overhead of the thread creation/dispatch and other such internal overhead introduced by the asynchronous handling.

I do understand that there is a protobuf overhead involved in grpc that is not there in my websocket client-server example. However i can account for that by measuring the overhead introduced by protobuf processing.

Also, if i cannot run the grpc server synchronously, can i at least measure the thread dispatch/asynchronous processing overhead?

I am relatively new to JAVA, so pardon my ignorance.

答:
Benchmarking in Java is easy to get wrong. You need to do many seconds worth of warm-up for multiple levels of JIT to kick in. You also need time for the heap size to level-off. In a simplistic one-shot benchmark, it's easy to see the code that runs last is fastest (independent of what that code is), due to class loading. 600 ms is an insanely large number for gRPC latency; we see around 300 µs median latency on Google Compute Engine between two machines, with TLS. I expect you have no warm-ups, so you are counting the time it takes for Java to load gRPC and are measuring Java using its interpreter with gRPC.

There is not a synchronous version of the gRPC server, and even if there was it would still run with a separate thread by default. grpc-java uses a cached thread pool, so after an initial request gRPC should be able to re-use a thread for calling the service.

The cost of jumping between threads is generally low, although it can add tail latency. In some in-process NOOP benchmarks we see RPC completion in 8 µs using the extra threads and 4 µs without. If you really want though, you can use serverBuilder.directExecutor() to avoid the thread hop. Note that most services would get slower with that option and have really poor tail latency, as service processing can delay I/O.

Title: GRPC server response latency


问:
AWS Cognito User Pool - read-only client
The question is already stated in the title - is there any way to create an App client for Amazon Cognito User Pool, which will have read permissions only? It's a bit weird but when I untick all the boxes in "Writable Attributes" section (User pool -> General settings -> Add another app client), it gives back this warning:

All attributes are writable by default because none are selected. Select attributes to make only those writable

That's cool, but my intention was to create 1 trustable private client with all write permissions and 1 public read-only client to be embedded into the app. I managed to reduce the number of writable attributes to a single one, which is not so important for me, but this solution looks hacky. Did anyone manage to crack this properly?

I also tried to play with App client OAuth 2.0 settings, but had no luck. Thanks for any info.

答:
all attributes are writable by default because none are selected.
  Select attributes to make only those writable

The service provider is basically constraining you to their anticipated use case. Currently, I think your solution is the only work around.


问:
clever way to add nested properties?
```<code>const data = {
  "orders" : [
    { "items" : {"count":3} },
    { "items" : {"count":1} },
    { "items" : {"count":2} }
  ]
}
let total = 0
data.orders.map((order) => order.items.map((item) => (total += item.count)))
console.log(total)
</code>```

Is there a more clever way to do that, where I could say console.log(someoperation(data)) ?

答:
What you have works, but you can also use the array .reduce method:

const data = {
  "orders" : [
    { "items" : {"count":3} },
    { "items" : {"count":1} },
    { "items" : {"count":2} }
  ]
}

const total = data.orders.reduce((cnt, item) => { return cnt+item.items.count; }, 0)

console.log(total)```
</div>
</div>
</p>

<p>EDIT:</p>

<p>Also, if you have lodash, this is even easier:</p>

```const total = _.sumBy(data.orders, x => x.items.count); // evaluates to 6
```

Title: clever way to add nested properties?

Body:
const data = {
  "orders" : [
    { "items" : {"count":3} },
    { "items" : {"count":1} },
    { "items" : {"count":2} }
  ]
}
let total = 0
data.orders.map((order) => order.items.map((item) => (total += item.count)))
console.log(total)

Is there a more clever way to do that, where I could say console.log(someoperation(data)) ?

Body:
What you have works, but you can also use the array .reduce method:

const data = {
  "orders" : [
    { "items" : {"count":3} },
    { "items" : {"count":1} },
    { "items" : {"count":2} }
  ]
}

const total = data.orders.reduce((cnt, item) => { return cnt+item.items.count; }, 0)

console.log(total)

EDIT:

Also, if you have lodash, this is even easier:

const total = _.sumBy(data.orders, x => x.items.count); // evaluates to 6


问:
Python- Remove all words that contain other words in a list
I have a list populated with words from a dictionary.  I want to find a way to remove all words, only considering root words that form at the beginning of the target word.

For example, the word "rodeo" would be removed from the list because it contains the English-valid word "rode."  "Typewriter" would be removed because it contains the English-valid word "type."  However, the word "snicker" is still valid even if it contains the word "nick" because "nick" is in the middle and not at the beginning of the word.

I was thinking something like this:

```<code> for line in wordlist:
        if line.find(...) --
</code>```

but I want that "if" statement to then run through every single word in the list checking to see if its found and, if so, remove itself from the list so that only root words remain.  Do I have to create a copy of wordlist to traverse?

答:
So you have two lists: the list of words you want to check and possibly remove, and a list of valid words.  If you like, you can use the same list for both purposes, but I'll assume you have two lists.

For speed, you should turn your list of valid words into a set.  Then you can very quickly check to see if any particular word is in that set.  Then, take each word, and check whether all its prefixes exist in the valid words list or not.  Since "a" and "I" are valid words in English, will you remove all valid words starting with 'a', or will you have a rule that sets a minimum length for the prefix?

I am using the file /usr/share/dict/words from my Ubuntu install.  This file has all sorts of odd things in it; for example, it seems to contain every letter by itself as a word.  Thus "k" is in there, "q", "z", etc.  None of these are words as far as I know, but they are probably in there for some technical reason.  Anyway, I decided to simply exclude anything shorter than three letters from my valid words list.

Here is what I came up with:

```<code># build valid list from /usr/dict/share/words
wfile = "/usr/dict/share/words"
valid = set(line.strip() for line in open(wfile) if len(line) >= 3)

lst = ["ark", "booze", "kite", "live", "rodeo"]

def subwords(word):
    for i in range(len(word) - 1, 0, -1):
        w = word[:i]
        yield w

newlst = []
for word in lst:
    # uncomment these for debugging to make sure it works
    # print "subwords", [w for w in subwords(word)]
    # print "valid subwords", [w for w in subwords(word) if w in valid]
    if not any(w in valid for w in subwords(word)):
        newlst.append(word)

print(newlst)
</code>```

If you are a fan of one-liners, you could do away with the for list and use a list comprehension:

```<code>newlst = [word for word in lst if not any(w in valid for w in subwords(word))]
</code>```

I think that's more terse than it should be, and I like being able to put in the print statements to debug.

Hmm, come to think of it, it's not too terse if you just add another function:

```<code>def keep(word):
    return not any(w in valid for w in subwords(word))

newlst = [word for word in lst if keep(word)]
</code>```

Python can be easy to read and understand if you make functions like this, and give them good names.

ContentLicense: CC BY-SA 2.5

Body:
I have a list populated with words from a dictionary.  I want to find a way to remove all words, only considering root words that form at the beginning of the target word.

For example, the word "rodeo" would be removed from the list because it contains the English-valid word "rode."  "Typewriter" would be removed because it contains the English-valid word "type."  However, the word "snicker" is still valid even if it contains the word "nick" because "nick" is in the middle and not at the beginning of the word.

I was thinking something like this:

 for line in wordlist:
        if line.find(...) --

but I want that "if" statement to then run through every single word in the list checking to see if its found and, if so, remove itself from the list so that only root words remain.  Do I have to create a copy of wordlist to traverse?

Body:
So you have two lists: the list of words you want to check and possibly remove, and a list of valid words.  If you like, you can use the same list for both purposes, but I'll assume you have two lists.

For speed, you should turn your list of valid words into a set.  Then you can very quickly check to see if any particular word is in that set.  Then, take each word, and check whether all its prefixes exist in the valid words list or not.  Since "a" and "I" are valid words in English, will you remove all valid words starting with 'a', or will you have a rule that sets a minimum length for the prefix?

I am using the file /usr/share/dict/words from my Ubuntu install.  This file has all sorts of odd things in it; for example, it seems to contain every letter by itself as a word.  Thus "k" is in there, "q", "z", etc.  None of these are words as far as I know, but they are probably in there for some technical reason.  Anyway, I decided to simply exclude anything shorter than three letters from my valid words list.

Here is what I came up with:

# build valid list from /usr/dict/share/words
wfile = "/usr/dict/share/words"
valid = set(line.strip() for line in open(wfile) if len(line) >= 3)

lst = ["ark", "booze", "kite", "live", "rodeo"]

def subwords(word):
    for i in range(len(word) - 1, 0, -1):
        w = word[:i]
        yield w

newlst = []
for word in lst:
    # uncomment these for debugging to make sure it works
    # print "subwords", [w for w in subwords(word)]
    # print "valid subwords", [w for w in subwords(word) if w in valid]
    if not any(w in valid for w in subwords(word)):
        newlst.append(word)

print(newlst)

If you are a fan of one-liners, you could do away with the for list and use a list comprehension:

newlst = [word for word in lst if not any(w in valid for w in subwords(word))]

I think that's more terse than it should be, and I like being able to put in the print statements to debug.

Hmm, come to think of it, it's not too terse if you just add another function:

def keep(word):
    return not any(w in valid for w in subwords(word))

newlst = [word for word in lst if keep(word)]

Python can be easy to read and understand if you make functions like this, and give them good names.


问:
How can I make my \n a new Line in HTML
Basically I have a string with \n and I want to display on a editable textbox in html. My problem is that in HTML i get everything in a new line and it's a big mess.

How can I replace the \n with
 or something like that  to make new lines in html??

JAVA GitLab.getProjectFile() Return this string (it's not this but it's the same format):

```<code>blablabla\nblablabla\nbla bla bla\n
</code>```

In HTML I'm calling like this:

```<code><div style="margin-top:20px;">
   <%
        String data = GitLab.getProjectFile();
    %>
    <%=data%>
</div>
</code>```

答:
You could just call replace:

```<code>String data = GitLab.getProjectFile().replace("\n", "<br/>");
</code>```

Title: How can I make my \n a new Line in HTML

Body:
Basically I have a string with \n and I want to display on a editable textbox in html. My problem is that in HTML i get everything in a new line and it's a big mess.

How can I replace the \n with
 or something like that  to make new lines in html??

JAVA GitLab.getProjectFile() Return this string (it's not this but it's the same format):

blablabla\nblablabla\nbla bla bla\n

In HTML I'm calling like this:

   <%
        String data = GitLab.getProjectFile();
    %>
    <%=data%>

Body:
You could just call replace:

String data = GitLab.getProjectFile().replace("\n", "<br/>");


问:
How to substitute a string in list from other lists where there is a match
Assume I have two source directories:

srcdir0 - Contains source files for generation 0 compile

srcdir1 - Contains subset of srcdir0 files

I create file list for srcdir0 and srcdir1

```<code>S0SRCS := $(wildcard $(srcdir0)/*.c)
S1SRCS := $(wildcard $(srcdir1)/*.c)
</code>```

I'm trying to create a final list that has the base srcdir0 files but are substituted by srcdir1 files of the same name. In other words the srcdir1 files take precedence.

I'm thinking that the filter or filter-out functions may be my friend here but I'm not experienced enough to know better.

答:
I think it suffices to filter out the names from the S1 directory from the names of the S0:

```<code>S0NAMES := $(notdir $(S0SRCS))
S1NAMES := $(notdir $(S1SRCS))
FINAL-LIST := $(addprefix $(srcdir0)/,$(filter-out $(S1NAMES),$(S0NAMES))) $(S1SRCS)
</code>```

Please test this first, I didn't have the opportunity to do so and wrote it just off the top of my head.

Body:
Assume I have two source directories:

srcdir0 - Contains source files for generation 0 compile

srcdir1 - Contains subset of srcdir0 files

I create file list for srcdir0 and srcdir1

S0SRCS := $(wildcard $(srcdir0)/*.c)
S1SRCS := $(wildcard $(srcdir1)/*.c)

I'm trying to create a final list that has the base srcdir0 files but are substituted by srcdir1 files of the same name. In other words the srcdir1 files take precedence.

I'm thinking that the filter or filter-out functions may be my friend here but I'm not experienced enough to know better.

Body:
I think it suffices to filter out the names from the S1 directory from the names of the S0:

S0NAMES := $(notdir $(S0SRCS))
S1NAMES := $(notdir $(S1SRCS))
FINAL-LIST := $(addprefix $(srcdir0)/,$(filter-out $(S1NAMES),$(S0NAMES))) $(S1SRCS)

Please test this first, I didn't have the opportunity to do so and wrote it just off the top of my head.


问:
sap.ui.unified.Calendar Issue in Different Logon Language
sap.ui.unified.Calendar is different based on different language:

For English, the calendar starts with Sunday as first day of week

For German, it starts with Monday.

How to make it consistent?

答:
The control sap.ui.unified.Calendar has the property firstDayOfWeek:

If set, the first day of the displayed week is this day. Valid values are 0 to 6. If not a valid value is set, the default of the used locale is used.

The default value is -1 meaning the first day of week is based on user's preferred language / locale.

0 is Sunday.

1 is Monday.


答:
Just wrap it in a function with params:</p>

```<code>function getTotal(startVal) {
  var total = startVal;
  data.orders.map((order) => order.items.map((item) => (total += item.count)))
  const data = {
    "orders" : [
      { "items" : {"count":3} },
      { "items" : {"count":1} },
      { "items" : {"count":2} }
    ]
  }
  return total;
}

console.log(getTotals(0));
</code>```

Title: clever way to add nested properties?

Body:
Just wrap it in a function with params:

function getTotal(startVal) {
  var total = startVal;
  data.orders.map((order) => order.items.map((item) => (total += item.count)))
  const data = {
    "orders" : [
      { "items" : {"count":3} },
      { "items" : {"count":1} },
      { "items" : {"count":2} }
    ]
  }
  return total;
}

console.log(getTotals(0));


问:
redirecting one to another Controller using spring mvc 3
below is my controller

```<code>  @RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String ABC(Registratio registration, ModelMap modelMap,
        HttpServletRequest request,HttpServletResponse response){
        if(somecondition=="false"){
           return "notok";  // here iam returning only the string
          }
          else{
               // here i want to redirect to another controller shown below
           }
}

 @RequestMapping(value="/checkPage",method = RequestMethod.GET,)
public String XYZ(ModelMap modelMap,
        HttpServletRequest request,HttpServletResponse response){
       return "check";   // this will return check.jsp page
}
</code>```

since the Controller ABC is @ResponceBody type  it will always return as string, but i want that in else contion it should be redirected to the XYZ controller and from which it return a jsp page which i can show.
 i tried using return "forward:checkPage"; also with  return "redirect:checkPage";
but doesn't work.
any help.

Thanks.

答:
```<code>return new ModelAndView("redirect:/admin/index");
</code>```

The code above works for me. I was redirecting from the present controller to index in AdminController.

Body:
below is my controller

  @RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String ABC(Registratio registration, ModelMap modelMap,
        HttpServletRequest request,HttpServletResponse response){
        if(somecondition=="false"){
           return "notok";  // here iam returning only the string
          }
          else{
               // here i want to redirect to another controller shown below
           }
}

 @RequestMapping(value="/checkPage",method = RequestMethod.GET,)
public String XYZ(ModelMap modelMap,
        HttpServletRequest request,HttpServletResponse response){
       return "check";   // this will return check.jsp page
}

since the Controller ABC is @ResponceBody type  it will always return as string, but i want that in else contion it should be redirected to the XYZ controller and from which it return a jsp page which i can show.
 i tried using return "forward:checkPage"; also with  return "redirect:checkPage";
but doesn't work.
any help.

Thanks.

Body:
return new ModelAndView("redirect:/admin/index");

The code above works for me. I was redirecting from the present controller to index in AdminController.


问:
Create object of type specified in a string
I have a bunch of classes generated by EF that are simple tables and have similar structures:

```<code>public class Contact
{
    public int ID { get; set; }
    public string Description { get; set; }
}

public class Member
{
    public int ID { get; set; }
    public string Description { get; set; }
}
</code>```

I've also got a method for returning an object of a specified type:

```<code>public T GetInstance<T>(string type)
{
    return (T)Activator.CreateInstance(Type.GetType(type));
}
</code>```

What I want to do is something like this:

```<code>public ActionResult GetAll(string ClassType)        // ClassType will be the name of one of the classes above
{
    Object LookupType = GetInstance<Object>(ClassType);

    List<LookupType> AllList = new List<LookupType>();

    AllList = repo.GetAll<LookupType>().ToList<LookupType>();    // some generic method that will return a list;
}
</code>```

This makes the compiler mad because I'm using a variable (LookupType) rather than a true type to build the list.  However, neither of these work either:

```<code>List<LookupType.GetType()> Items = new List<LookupType.GetType()>();
List<typeof(LookupType)> Items = new List<typeof(LookupType)>();
</code>```

Both cause an error - "Using generic type List requires 1 type argument".

Is there a proper way to do this?  Is there a way to convert ClassType directly to a type without first making it an object (from which I hope to derive the type)?

答:
You cannot do it with C#!!
Compiler must to know the parameter type.
In that maybe you would like to accomplish, interfaces will help you

```<code>public class Contact: IIdDescription
{
        public int ID { get; set; }
        public string Description { get; set; }
}

public class Member: IIdDescription
{
     public int ID { get; set; }
     public string Description { get; set; }
}

public interface IIdDescription
{
     int ID { get; set; }
     string Description { get; set; }
}

public ActionResult GetAll(string type)
{
   var AllList = new List<IIdDescription>();

   if(type == Member.GetType().Name)
      AllList = repo.Set<Member>().Cast<IIdDescription >().ToList();
   if(type == Contact.GetType().Name)
       AllList = repo.Set<Contact>().Cast<IIdDescription >().ToList();

   ...
}
</code>```

and into your view use interface as model, something like

```<code> @model IEnumerable<IIdDescription>
</code>```

Body:
I have a bunch of classes generated by EF that are simple tables and have similar structures:

public class Contact
{
    public int ID { get; set; }
    public string Description { get; set; }
}

public class Member
{
    public int ID { get; set; }
    public string Description { get; set; }
}

I've also got a method for returning an object of a specified type:

public T GetInstance<T>(string type)
{
    return (T)Activator.CreateInstance(Type.GetType(type));
}

What I want to do is something like this:

public ActionResult GetAll(string ClassType)        // ClassType will be the name of one of the classes above
{
    Object LookupType = GetInstance<Object>(ClassType);

    List<LookupType> AllList = new List<LookupType>();

    AllList = repo.GetAll<LookupType>().ToList<LookupType>();    // some generic method that will return a list;
}

This makes the compiler mad because I'm using a variable (LookupType) rather than a true type to build the list.  However, neither of these work either:

List<LookupType.GetType()> Items = new List<LookupType.GetType()>();
List<typeof(LookupType)> Items = new List<typeof(LookupType)>();

Both cause an error - "Using generic type List requires 1 type argument".

Is there a proper way to do this?  Is there a way to convert ClassType directly to a type without first making it an object (from which I hope to derive the type)?

Body:
You cannot do it with C#!!
Compiler must to know the parameter type.
In that maybe you would like to accomplish, interfaces will help you

public class Contact: IIdDescription
{
        public int ID { get; set; }
        public string Description { get; set; }
}

public class Member: IIdDescription
{
     public int ID { get; set; }
     public string Description { get; set; }
}

public interface IIdDescription
{
     int ID { get; set; }
     string Description { get; set; }
}

public ActionResult GetAll(string type)
{
   var AllList = new List<IIdDescription>();

   if(type == Member.GetType().Name)
      AllList = repo.Set<Member>().Cast<IIdDescription >().ToList();
   if(type == Contact.GetType().Name)
       AllList = repo.Set<Contact>().Cast<IIdDescription >().ToList();

   ...
}

and into your view use interface as model, something like

 @model IEnumerable<IIdDescription>


问:
Create a matrix where each value depends on it's own indices
I want to create a n*n matrix with entries Aij = 5/(i + 2j -1).

It's easy enough with a couple of for loops but I just wondered if there was a built in functionality that could do this?

答:
very simple just use meshgrid:

```<code> [j i]=meshgrid(1:n);
 A=5./(i+2*j-1);
</code>```

with n being the dimension you want.

An even simpler way to do that in your case, where both i and j go to n,  is this one line :

```<code>A=5./([1:n]'+2*[1:n]-1);
</code>```

Body:
very simple just use meshgrid:

 [j i]=meshgrid(1:n);
 A=5./(i+2*j-1);

with n being the dimension you want.

An even simpler way to do that in your case, where both i and j go to n,  is this one line :

A=5./([1:n]'+2*[1:n]-1);


问:
Height of Windows in WPF Application when Touch Keyboard appears
I'm in the process of writing an 'touch-able' WPF Application for Windows 10. Imagine a window containing the following grid:

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <TextBox Text="dsdsd"></TextBox>
    <TextBox Text="unten" Grid.Row="2" InputScope="Number"></TextBox>
</Grid>
</code>```

If my application is compiled using at least .NET 4.6.2 and its window is maximized, I can touch the lower TextBox and the touch-Keyboard opens. However I'm unable to see the control because the keyboard hides it. This behaviour is differs to windows 8.x where the render-canvas size was reduced when the keyboard opened. When doing the same thing in Windows Startbar-Search field, the field does move up so I can see the input field. When opening the keyboard with maximized explorer.exe the window gets smaller.

How can I implement this behaviour in an WPF Application?

Cheers,
Manuel

答:
have you tried use when creating the windows:

```<code>    this.SizeToContent = SizeToContent.WidthAndHeight;
</code>```

This will fix automatically the width and the height to fit the current size.

Source:
https://learn.microsoft.com/en-us/dotnet/framework/wpf/app-development/how-to-automatically-size-a-window-to-fit-its-content

Body:
I'm in the process of writing an 'touch-able' WPF Application for Windows 10. Imagine a window containing the following grid:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <TextBox Text="dsdsd"></TextBox>
    <TextBox Text="unten" Grid.Row="2" InputScope="Number"></TextBox>
</Grid>

If my application is compiled using at least .NET 4.6.2 and its window is maximized, I can touch the lower TextBox and the touch-Keyboard opens. However I'm unable to see the control because the keyboard hides it. This behaviour is differs to windows 8.x where the render-canvas size was reduced when the keyboard opened. When doing the same thing in Windows Startbar-Search field, the field does move up so I can see the input field. When opening the keyboard with maximized explorer.exe the window gets smaller.

How can I implement this behaviour in an WPF Application?

Cheers,
Manuel

Body:
have you tried use when creating the windows:

    this.SizeToContent = SizeToContent.WidthAndHeight;

This will fix automatically the width and the height to fit the current size.

Source:
https://learn.microsoft.com/en-us/dotnet/framework/wpf/app-development/how-to-automatically-size-a-window-to-fit-its-content


问:
How does Github Pages add a subdomain for each repository?
For every single github repository like https://github.com/user/repository there is a corresponding github pages subdomain repository.github.io, and github just creates these subdomains under github.io on the fly.

Anyone know how github does this?  I'm hoping there exists an easy to use DNS server / DNS Service that is also REST capable.

答:
My guess is that GitHub is just using a wildcard subdomain that maps from *.github.io to some internal GitHub server, which then serves the correct repository based on the requested URL.

I don't know what you're trying to do with GitHub's DNS server, but you can create a repo via the GitHub API: How to create repository in github through github API?


问:
What's the easiest way to create an Excel table with C#?
I have some tabular data that I'd like to turn into an Excel table.

Software available:

.NET 4 (C#)

Excel 2010 (using the Excel API is OK)

I prefer not to use any 3rd party libraries

Information about the data:

A couple million rows

5 columns, all strings (very simple and regular table structure)

In my script I'm currently using a nested List data structure but I can change that

Performance of the script is not critical

Searching online gives many results, and I'm confused whether I should use OleDb, ADO RecordSets, or something else. Some of these technologies seem like overkill for my scenario, and some seem like they might be obsolete.

What is the very simplest way to do this?

Edit: this is a one-time script I intend to run from my attended desktop.

答:
Honoring your request to avoid 3rd party tools and using COM objects, here's how I'd do it.

Add reference to project: Com object
Microsoft Excel 11.0.

Top of module add:

```<code>using Microsoft.Office.Interop.Excel;
</code>```

Add event logic like this:

```<code>private void DoThatExcelThing()
{

    ApplicationClass myExcel;
    try
    {
        myExcel = GetObject(,"Excel.Application")
    }
    catch (Exception ex)
    {
        myExcel = New ApplicationClass()
    }

    myExcel.Visible = true;
    Workbook wb1 = myExcel.Workbooks.Add("");
    Worksheet ws1 = (Worksheet)wb1.Worksheets[1];

    //Read the connection string from App.Config
    string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["NewConnString"].ConnectionString;

    //Open a connection to the database
    SqlConnection myConn = new SqlConnection();
    myConn.ConnectionString = strConn;
    myConn.Open();

    //Establish the query
    SqlCommand myCmd = new SqlCommand("select * from employees", myConn);
    SqlDataReader myRdr = myCmd.ExecuteReader();

    //Read the data and put into the spreadsheet.
    int j = 3;
    while (myRdr.Read())
    {
        for (int i=0 ; i < myRdr.FieldCount; i++)
        {
            ws1.Cells[j, i+1] = myRdr[i].ToString();
        }
        j++;
    }

    //Populate the column names
    for (int i = 0; i < myRdr.FieldCount ; i++)
    {
        ws1.Cells[2, i+1] = myRdr.GetName(i);
    }
    myRdr.Close();
    myConn.Close();

    //Add some formatting
    Range rng1 = ws1.get_Range("A1", "H1");
    rng1.Font.Bold = true;
    rng1.Font.ColorIndex = 3;
    rng1.HorizontalAlignment = XlHAlign.xlHAlignCenter;

    Range rng2 = ws1.get_Range("A2", "H50");
    rng2.WrapText = false;
    rng2.EntireColumn.AutoFit();

    //Add a header row
    ws1.get_Range("A1", "H1").EntireRow.Insert(XlInsertShiftDirection.xlShiftDown, Missing.Value);
    ws1.Cells[1, 1] = "Employee Contact List";
    Range rng3 = ws1.get_Range("A1", "H1");
    rng3.Merge(Missing.Value);
    rng3.Font.Size = 16;
    rng3.Font.ColorIndex = 3;
    rng3.Font.Underline = true;
    rng3.Font.Bold = true;
    rng3.VerticalAlignment = XlVAlign.xlVAlignCenter;

    //Save and close
    string strFileName = String.Format("Employees{0}.xlsx", DateTime.Now.ToString("HHmmss"));
    System.IO.File.Delete(strFileName);
    wb1.SaveAs(strFileName, XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
        XlSaveAsAccessMode.xlExclusive, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value);
    myExcel.Quit();

}
</code>```

Body:
Honoring your request to avoid 3rd party tools and using COM objects, here's how I'd do it.

Add reference to project: Com object
Microsoft Excel 11.0.

Top of module add:

using Microsoft.Office.Interop.Excel;

Add event logic like this:

private void DoThatExcelThing()
{

    ApplicationClass myExcel;
    try
    {
        myExcel = GetObject(,"Excel.Application")
    }
    catch (Exception ex)
    {
        myExcel = New ApplicationClass()
    }

    myExcel.Visible = true;
    Workbook wb1 = myExcel.Workbooks.Add("");
    Worksheet ws1 = (Worksheet)wb1.Worksheets[1];

    //Read the connection string from App.Config
    string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["NewConnString"].ConnectionString;

    //Open a connection to the database
    SqlConnection myConn = new SqlConnection();
    myConn.ConnectionString = strConn;
    myConn.Open();

    //Establish the query
    SqlCommand myCmd = new SqlCommand("select * from employees", myConn);
    SqlDataReader myRdr = myCmd.ExecuteReader();

    //Read the data and put into the spreadsheet.
    int j = 3;
    while (myRdr.Read())
    {
        for (int i=0 ; i < myRdr.FieldCount; i++)
        {
            ws1.Cells[j, i+1] = myRdr[i].ToString();
        }
        j++;
    }

    //Populate the column names
    for (int i = 0; i < myRdr.FieldCount ; i++)
    {
        ws1.Cells[2, i+1] = myRdr.GetName(i);
    }
    myRdr.Close();
    myConn.Close();

    //Add some formatting
    Range rng1 = ws1.get_Range("A1", "H1");
    rng1.Font.Bold = true;
    rng1.Font.ColorIndex = 3;
    rng1.HorizontalAlignment = XlHAlign.xlHAlignCenter;

    Range rng2 = ws1.get_Range("A2", "H50");
    rng2.WrapText = false;
    rng2.EntireColumn.AutoFit();

    //Add a header row
    ws1.get_Range("A1", "H1").EntireRow.Insert(XlInsertShiftDirection.xlShiftDown, Missing.Value);
    ws1.Cells[1, 1] = "Employee Contact List";
    Range rng3 = ws1.get_Range("A1", "H1");
    rng3.Merge(Missing.Value);
    rng3.Font.Size = 16;
    rng3.Font.ColorIndex = 3;
    rng3.Font.Underline = true;
    rng3.Font.Bold = true;
    rng3.VerticalAlignment = XlVAlign.xlVAlignCenter;

    //Save and close
    string strFileName = String.Format("Employees{0}.xlsx", DateTime.Now.ToString("HHmmss"));
    System.IO.File.Delete(strFileName);
    wb1.SaveAs(strFileName, XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
        XlSaveAsAccessMode.xlExclusive, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value);
    myExcel.Quit();

}


问:
How to add additional fields to register page in asp.net mvc?
I am trying to add a few extra fields to the register page in the default asp.net mvc application that we get when we open visual studio. I followed this tutorial.

Customize MVC 5 Register Page

These are the steps that I followed after opening the default project that we get in Visual studio for asp.net MVC.

First I ran the project and clicked on Register button and registered a random user. I did this so that the default database would get created.

Now that the database was generated, I went to the database and added extra columns like Gender, Birthday, FirstName, LastName and AboutUser and re-updated the database table called ASPNETUSERS.

Now I went to RegisterViewModel and added these same properties as well.

After that I went to ApplicationUser and added the same properties as well.

After that I changed the view for Register.cshtml to incorporate extra textboxes, textareas for the new fields that I created.

Now I went to the controller and added these properties in as well. Everything seems fine to me so far, except the fact that the database's definition changed from the beginning.

This is how the page looks after all these changes.

Now I ran the project and tried to register a person, but I keep getting this error.

I researched about this error, but the solutions suggest that I should try adding Database.SetInitializer<YourDbContext>(null); in the constructor of myDBContext. But the thing is, I don't have any context at all. So this solution doesn't seem to work for me.

答: just remove the record added to migration table</p>


问:
Python dictionary comprehension checking if something doesn't exist and setting a value
I have a dictionary that looks like this

```<code>old_dict = {"language":"english","gender":"female","job":"ceo"}
</code>```

The only keys i'm interested in are
"language","job","hobby"

Filtering out using this logic only works for the keys that exist in my original dictionary.

```<code>   dict_you_want = { your_key: old_dict[your_key]  for your_key in your_keys if your_key in your_keys }
</code>```

How can I alter this code to add conditions, if the key doesn't exist to set a null/none value to the key.

```<code>your_keys = ["language","job"]
</code>```

The output i'm looking for is

```<code>{"language":"english","job":"ceo","hobby":None}
</code>```

答:
```<code>{ key:old_dict.get(key,None) for key in ["language","job", "hobby"]}
</code>```

output:

```<code>{'hobby': None, 'job': 'ceo', 'language': 'english'}
</code>```

Body:
I have a dictionary that looks like this

old_dict = {"language":"english","gender":"female","job":"ceo"}

The only keys i'm interested in are
"language","job","hobby"

Filtering out using this logic only works for the keys that exist in my original dictionary.

   dict_you_want = { your_key: old_dict[your_key]  for your_key in your_keys if your_key in your_keys }

How can I alter this code to add conditions, if the key doesn't exist to set a null/none value to the key.

your_keys = ["language","job"]

The output i'm looking for is

{"language":"english","job":"ceo","hobby":None}

Body:
{ key:old_dict.get(key,None) for key in ["language","job", "hobby"]}

output:

{'hobby': None, 'job': 'ceo', 'language': 'english'}


问:
How to open different contents in the same pop up window
What is the best way to display different content in the same pop up window.

I'm doing the following:

```<code>    <a href = "javascript:openWin('content1.htm')">Content 1</a>
    <a href = "javascript:openWin('content2.htm')">Content 2</a>
    <a href = "javascript:openWin('content3.htm')">Content 3</a>
</code>```

And I have the following javascript:

```<code>       function openWin(url) {
        window.open(url, "_blank", "toolbar=no, scrollbars=no, resizable=no, top=200, left=300, width=870, height=650");
    }
</code>```

Now, after clicking each link, different pop ups opened. How can I target the same pop up window to display appropriate content, so I have only one pop up opened after clicking second or third link?

Thank you

答:
A tad late, but I think using the 'location' property will do what you want:

```<code>var windowName;  // global
function openWin(url) {
   if (windowName) {
      windowName.location = url;
      return;
   }
   else {
      windowName = window.open(url, "window_name", "<feature_list>");
   }
}
</code>```

I was researching this topic because my users want to have an app open on two different windows on different monitors, each window/monitor dedicated to different content within the app itself.  The above code opens up new content in the same window, but there's no "flash" or "pop" that tells the user new content has appeared.  CSS could certainly be used for this, but compare how the above code executes compared to this code:

```<code>var windowName;  // global
function openWin(url) {
   if (windowName) {
      windowName.close();
   }
   windowName = window.open(url, "window_name", "<feature_list>");
}
</code>```

I think I like the latter UX better.

Body:
What is the best way to display different content in the same pop up window.

I'm doing the following:

    Content 1
    Content 2
    Content 3

And I have the following javascript:

       function openWin(url) {
        window.open(url, "_blank", "toolbar=no, scrollbars=no, resizable=no, top=200, left=300, width=870, height=650");
    }

Now, after clicking each link, different pop ups opened. How can I target the same pop up window to display appropriate content, so I have only one pop up opened after clicking second or third link?

Thank you

Body:
A tad late, but I think using the 'location' property will do what you want:

var windowName;  // global
function openWin(url) {
   if (windowName) {
      windowName.location = url;
      return;
   }
   else {
      windowName = window.open(url, "window_name", "<feature_list>");
   }
}

I was researching this topic because my users want to have an app open on two different windows on different monitors, each window/monitor dedicated to different content within the app itself.  The above code opens up new content in the same window, but there's no "flash" or "pop" that tells the user new content has appeared.  CSS could certainly be used for this, but compare how the above code executes compared to this code:

var windowName;  // global
function openWin(url) {
   if (windowName) {
      windowName.close();
   }
   windowName = window.open(url, "window_name", "<feature_list>");
}

I think I like the latter UX better.


问:
Disable JPA Java Change Event Handler
I have been using Eclipse for many years (usually Jboss Developer Studio) and have been plagued by Eclipse often running, or waiting to run JPA Java Change Event Handler

Currently I am working on a project that doesnt use JPA, yet these Event Handler still appears.

I have seen varies other SO and forum posts related to this, but I have not found a solution that works.

I have tried removing Dali and any plugins that show when searching for JPA - but the problem still remains.  For example, I have removed the following - but the problem remains:

I am using Eclipse Version: Oxygen.1a Release

答:
Try this (It worked for me):

Windows:

```<code>cd eclipse_install_directory

mkdir disabled\features && mkdir disabled\plugins

move plugins\org.eclipse.jpt.* disabled\plugins
move features\org.eclipse.jpt.* disabled\features</code>```

Linux:

```<code>cd eclipse_install_directory

mkdir -p disabled/features && mkdir -p disabled/plugins

mv plugins/org.eclipse.jpt.* disabled/plugins
mv features/org.eclipse.jpt.* disabled/features</code>```

source: http://w3cgeek.com

Title: Disable JPA Java Change Event Handler

Body:
Try this (It worked for me):

Windows:

cd eclipse_install_directory

mkdir disabled\features && mkdir disabled\plugins

move plugins\org.eclipse.jpt.* disabled\plugins
move features\org.eclipse.jpt.* disabled\features

Linux:

cd eclipse_install_directory

mkdir -p disabled/features && mkdir -p disabled/plugins

mv plugins/org.eclipse.jpt.* disabled/plugins
mv features/org.eclipse.jpt.* disabled/features

source: http://w3cgeek.com


问:
Plot Discrete Distribution using np.linspace()
I'm trying to plot a simple discrete distribution using matplotlib:

If -1<=x<0, p=0.3;

If 0<=x<1, p=0.5;

If 1<=x<=2, p=0.2.

How can I start from x = np.linspace(-1, 2)?

What I tried so far is:

```<code>def mapDiscProb(x):
    if np.any(x < 0):
        return 0.3 + x * 0
    elif np.any(x >= 1):
        return 0.2 + x * 0
    else:
        return 0.5 + x * 0

x = np.linspace(-1, 2)
y = mapDiscProb(x4)

ax.plot(x, y, clip_on = False)
</code>```

And the outcome is just a whole line at 0.3 from -1 to 2 as if the     elif and     else are not excuted.

My expected output is three disconnected horizontal lines, as is standard for a discrete pmf.

答:
You may use

numpy.piecewise

numpy.piecewise allows to define a function dependent on some conditions. Here you have three conditions [x<0, x>=1, (x>=0) & (x<1)], and you may define a function to use for each of them.

```<code>import matplotlib.pyplot as plt
import numpy as np

l1 = lambda x: 0.3 + x * 0
l2 = lambda x: 0.2 + x * 0
l3 = lambda x: 0.5 + x * 0

mapDiscProb=lambda x: np.piecewise(x, [x<0, x>=1, (x>=0) & (x<1)],[l1,l2,l3])

x = np.linspace(-1, 2)
y = mapDiscProb(x)

fig, ax = plt.subplots()
ax.plot(x, y, clip_on = False)

plt.show()
</code>```

numpy.vectorize

numpy.vectorize vectorizes a function which is meant to be called with scalars, such that is evaluated for each element in an array. This allows if/else statements to be used as expected.

```<code>import matplotlib.pyplot as plt
import numpy as np

def mapDiscProb(x):
    if x < 0:
        return 0.3
    elif x >= 1:
        return 0.2
    else:
        return 0.5

x = np.linspace(-1, 2)
y = np.vectorize(mapDiscProb)(x)

fig, ax = plt.subplots()
ax.plot(x, y, clip_on = False)

plt.show()
</code>```

numpy.select

(credit to PaulH for this idea) numpy.select can choose select values from different arrays based on a condition. For piecewise constant functions this is an easy tool, because it does not require to build any additional functions (one-liner).

```<code>import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1, 2)
y = np.select([x<0, x<1, x>1], [0.3, 0.5, 0.2])

fig, ax = plt.subplots()
ax.plot(x, y, clip_on = False)

plt.show()
</code>```

Output in all cases:

No vertical lines

In case you don't want any vertical lines to appear, it makes sense to plot as many plots as you have conditions.

```<code>import matplotlib.pyplot as plt
import numpy as np

l1 = lambda x: 0.3 + x * 0
l2 = lambda x: 0.2 + x * 0
l3 = lambda x: 0.5 + x * 0

x = np.linspace(-1, 2)
func = [l1,l2,l3]
cond = [x<0, x>=1, (x>=0) & (x<1)]

fig, ax = plt.subplots()
for f,c in zip(func,cond):
    xi = x[c]
    ax.plot(xi, f(xi), color="C0")

plt.show()
</code>```

Alternatively, using numpy.select, you may modify the x array to surely include the values [0,1], which lie on the edge between conditions. Choosing the conditions to exclude those values explicitely, [x<0, (x>0) & (x<1), x>1] (note the lack of any equal sign) will allow to set those values to nan. Nan values are not shown, hence a gap appears.

```<code>import matplotlib.pyplot as plt
import numpy as np

x = np.sort(np.append(np.linspace(-1, 2),[0,1]))
y = np.select([x<0, (x>0) & (x<1), x>1], [0.3, 0.5, 0.2], np.nan)

fig, ax = plt.subplots()
ax.plot(x, y)

plt.show()
</code>```

Body:
I'm trying to plot a simple discrete distribution using matplotlib:

If -1<=x<0, p=0.3;

If 0<=x<1, p=0.5;

If 1<=x<=2, p=0.2.

How can I start from x = np.linspace(-1, 2)?

What I tried so far is:

def mapDiscProb(x):
    if np.any(x < 0):
        return 0.3 + x * 0
    elif np.any(x >= 1):
        return 0.2 + x * 0
    else:
        return 0.5 + x * 0

x = np.linspace(-1, 2)
y = mapDiscProb(x4)

ax.plot(x, y, clip_on = False)

And the outcome is just a whole line at 0.3 from -1 to 2 as if the     elif and     else are not excuted.

My expected output is three disconnected horizontal lines, as is standard for a discrete pmf.

Body:
You may use

numpy.piecewise

numpy.piecewise allows to define a function dependent on some conditions. Here you have three conditions [x<0, x>=1, (x>=0) & (x<1)], and you may define a function to use for each of them.

import matplotlib.pyplot as plt
import numpy as np

l1 = lambda x: 0.3 + x * 0
l2 = lambda x: 0.2 + x * 0
l3 = lambda x: 0.5 + x * 0

mapDiscProb=lambda x: np.piecewise(x, [x<0, x>=1, (x>=0) & (x<1)],[l1,l2,l3])

x = np.linspace(-1, 2)
y = mapDiscProb(x)

fig, ax = plt.subplots()
ax.plot(x, y, clip_on = False)

plt.show()

numpy.vectorize

numpy.vectorize vectorizes a function which is meant to be called with scalars, such that is evaluated for each element in an array. This allows if/else statements to be used as expected.

import matplotlib.pyplot as plt
import numpy as np

def mapDiscProb(x):
    if x < 0:
        return 0.3
    elif x >= 1:
        return 0.2
    else:
        return 0.5

x = np.linspace(-1, 2)
y = np.vectorize(mapDiscProb)(x)

fig, ax = plt.subplots()
ax.plot(x, y, clip_on = False)

plt.show()

numpy.select

(credit to PaulH for this idea) numpy.select can choose select values from different arrays based on a condition. For piecewise constant functions this is an easy tool, because it does not require to build any additional functions (one-liner).

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1, 2)
y = np.select([x<0, x<1, x>1], [0.3, 0.5, 0.2])

fig, ax = plt.subplots()
ax.plot(x, y, clip_on = False)

plt.show()

Output in all cases:

No vertical lines

In case you don't want any vertical lines to appear, it makes sense to plot as many plots as you have conditions.

import matplotlib.pyplot as plt
import numpy as np

l1 = lambda x: 0.3 + x * 0
l2 = lambda x: 0.2 + x * 0
l3 = lambda x: 0.5 + x * 0

x = np.linspace(-1, 2)
func = [l1,l2,l3]
cond = [x<0, x>=1, (x>=0) & (x<1)]

fig, ax = plt.subplots()
for f,c in zip(func,cond):
    xi = x[c]
    ax.plot(xi, f(xi), color="C0")

plt.show()

Alternatively, using numpy.select, you may modify the x array to surely include the values [0,1], which lie on the edge between conditions. Choosing the conditions to exclude those values explicitely, [x<0, (x>0) & (x<1), x>1] (note the lack of any equal sign) will allow to set those values to nan. Nan values are not shown, hence a gap appears.

import matplotlib.pyplot as plt
import numpy as np

x = np.sort(np.append(np.linspace(-1, 2),[0,1]))
y = np.select([x<0, (x>0) & (x<1), x>1], [0.3, 0.5, 0.2], np.nan)

fig, ax = plt.subplots()
ax.plot(x, y)

plt.show()


问:
Local vs Heroku Postgres speed
I have a local database with a single table which has roughly 5.5 million records. I created a new database (Basic Plan) on Heroku Postgres and restored the local dump into it. Firing up psql and doing some queries I noticed that the speed is significantly lower than locally. I then provisioned another database with the Crane plan and the numbers are similarly bad.

Here some numbers:

select count(*) from table;

Local: 1216.744 ms

Heroku (Basic): 4697.073 ms

Heroku (Crane): 2972.302 ms

select column from table where id = 123456;

Local: 0.249 ms

Heroku (Basic): 127.557 ms

Heroku (Crane): 137.617 ms

How are these huge differences possible? Could this be entirely related to hardware differences? Is there any easy way to increase the throughput?

答:
I created a new database (Basic Plan) on Heroku Postgres and restored the local dump into it.

Looks like you were playing with different DB at the same time.

```<code>select column from table where id = 123456;
Local: 0.249 ms
Heroku (Basic): 127.557 ms
Heroku (Crane): 137.617 ms
</code>```

I highly suspect your Heroku app and Heroku DB to not be hosted in the same region. Both need to be either in the US or EU.

Title: Local vs Heroku Postgres speed

Body:
I created a new database (Basic Plan) on Heroku Postgres and restored the local dump into it.

Looks like you were playing with different DB at the same time.

select column from table where id = 123456;
Local: 0.249 ms
Heroku (Basic): 127.557 ms
Heroku (Crane): 137.617 ms

I highly suspect your Heroku app and Heroku DB to not be hosted in the same region. Both need to be either in the US or EU.


问:
ScrollView that does not render views that aren't visible
I am attempting to improve the amount time it takes to fill the items into the ScrollView. If I hard code the height (not in pixels of course) of every RelativeLayout in the LinearLayout in the other LinearLayout in the ScrollView... can I get ScrollView to display the visible ones first and then when they are displayed to load up the rest later? The ScrollView should start off scrolled to a specific location.. not just the top of the screen. Now if we have to load from the top that is OK because there is about one third above the visible area and the rest below.

答: You could use ViewStub to inflate extra items only when you need it, but it sounds like you are describing what ListView does already.</p>


问:
Use component props in onClick redux-thunk dispatch React-Redux
Trying to use props from <button> of component in the dispatch of a redux-thunk function that has been set up for Async process but I can't quite get how to use both props and the function (that's being connected to the component through react-redux connect in the mapDispatchToProps) but I just can't figure out how to call both the props and the function.

```<code>function loadData(dispatch, medium) {
    console.log(dispatch)
    return dispatch({type: 'LOADING_COMPONENT'})

  return axios.get(`/professionals/${medium}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
    );
}

const mapDispatchToProps = (dispatch) => {
  return {
    LogInClick : () => dispatch(loadData()),
  }
}

const LoginButtons = ({props, LogInClick}) => (
    <button onClick={() => LogInClick(props.medium)} type="button">{props.buttonName}</button>
)

const LoginConnect = connect(null, mapDispatchToProps)(LoginButtons)
</code>```

And Then I export that and try to call it so it can be reused in the render file like

```<code><LoginConnect medium='suhhhh' buttonName='To log in to suhhh'/>
</code>```

答:
Try returning a function, which redux-thunk will then call with dispatch as an argument.

You can then call dispatch from that returned function:

```<code>function loadData(medium) {
  return (dispatch) => {
    dispatch({ type: 'LOADING_COMPONENT' })

    axios.get(`/professionals/${medium}`)
      .then(res => res.json())
      .then(
        data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
        err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
      )
  }
}
</code>```

Your LogInClick function can then take an argument which can be passed into loadData:

```<code>const mapDispatchToProps = (dispatch) => {
  return {
    LogInClick: (medium) => dispatch(loadData(medium)),
  }
}

const LoginButtons = (props) => (
  <button onClick={() => props.LogInClick(props.medium)} type="button">{props.buttonName}</button>
)
</code>```

I hope this helps.

Body:
Trying to use props from <button> of component in the dispatch of a redux-thunk function that has been set up for Async process but I can't quite get how to use both props and the function (that's being connected to the component through react-redux connect in the mapDispatchToProps) but I just can't figure out how to call both the props and the function.

function loadData(dispatch, medium) {
    console.log(dispatch)
    return dispatch({type: 'LOADING_COMPONENT'})

  return axios.get(`/professionals/${medium}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
    );
}

const mapDispatchToProps = (dispatch) => {
  return {
    LogInClick : () => dispatch(loadData()),
  }
}

const LoginButtons = ({props, LogInClick}) => (
    <button onClick={() => LogInClick(props.medium)} type="button">{props.buttonName}</button>
)

const LoginConnect = connect(null, mapDispatchToProps)(LoginButtons)

And Then I export that and try to call it so it can be reused in the render file like

<LoginConnect medium='suhhhh' buttonName='To log in to suhhh'/>

Body:
Try returning a function, which redux-thunk will then call with dispatch as an argument.

You can then call dispatch from that returned function:

function loadData(medium) {
  return (dispatch) => {
    dispatch({ type: 'LOADING_COMPONENT' })

    axios.get(`/professionals/${medium}`)
      .then(res => res.json())
      .then(
        data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
        err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
      )
  }
}

Your LogInClick function can then take an argument which can be passed into loadData:

const mapDispatchToProps = (dispatch) => {
  return {
    LogInClick: (medium) => dispatch(loadData(medium)),
  }
}

const LoginButtons = (props) => (
  <button onClick={() => props.LogInClick(props.medium)} type="button">{props.buttonName}</button>
)

I hope this helps.


问:
Grid Date formating in Kendo UI for Angular
I am trying to format a datetime field in the Kendo UI for Angular Grid and have the filter and editing features work.  I can use ng-template and pipe the date into the format I want but the filter and editing of the column does not work. The data is coming from a webapi service and the date is coming in the json data as 2017-9-12T00:00:00  </p>

答: Data needs to be mapped such that dates are parsed to actual JavaScript Date objects before data is bound to the Grid, so that they can be further formatted via the Grid column "format" property. For editing and filtering to work as expected, you need to specify the data type in the "filter" and "editor" properties.</p>


问:
Core Data update if exists or create new managed object. Can I make this faster?
I have the following code, and I was wondering if theres any way to make this faster. Basically my app downloads some JSON (about 4000 records) from the net, and updates or creates my managed objects based on the data. At the moment it's quite slow, and I can see why, but I'm new to core data so I was wondering if there's anything I can do to make it faster?

```<code> NSFetchRequest *request = [[NSFetchRequest alloc] init];
 NSEntityDescription *entity = [NSEntityDescription entityForName:@"Company" inManagedObjectContext:managedObjectContext];
 [request setEntity:entity];
 NSMutableArray *coreDataArray = [[managedObjectContext executeFetchRequest:request error:nil] mutableCopy];
 [request release];

 for (NSDictionary *dict in arr) {
  NSArray *filtered = [coreDataArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(code == %@)", [dict objectForKey:@"Code"]]];
  //NSLog(@"COREDATA ARRAY: %d FILTERED ARRAY: %d CODE: %@ COREDATA FIRST CODE: %@", [coreDataArray count], [filtered count], [dict objectForKey:@"Code"], [[coreDataArray objectAtIndex:0] code]);
  if ([filtered count] > 0) {
   Company *c = [filtered objectAtIndex:0];
   if ([dict objectForKey:@"Defunct"]) {
    NSLog(@"DELETED DEFUNCT COMPANY");
    [managedObjectContext deleteObject:c];
   } else {
    [c populateWithJSONDictionary:dict];
   }
  } else {
   Company *c = (Company *)[NSEntityDescription insertNewObjectForEntityForName:@"Company" inManagedObjectContext:managedObjectContext];
   [c populateWithJSONDictionary:dict];
  }

  float percent = (float)[arr indexOfObject:dict]/[arr count];
  [self performSelectorInBackground:@selector(updateProgressView:) withObject:[NSString stringWithFormat:@"%f",percent]];
 }

 [coreDataArray release];
</code>```

Many thanks for any help you can give.

答:
You should check out the Core Data Programming Guide: Performance section

It has some specific advice for data import performance.

In case Apple moves the documentation again, here is a good search query on Google site:developer.apple.com core data import performance

Body:
I have the following code, and I was wondering if theres any way to make this faster. Basically my app downloads some JSON (about 4000 records) from the net, and updates or creates my managed objects based on the data. At the moment it's quite slow, and I can see why, but I'm new to core data so I was wondering if there's anything I can do to make it faster?

 NSFetchRequest *request = [[NSFetchRequest alloc] init];
 NSEntityDescription *entity = [NSEntityDescription entityForName:@"Company" inManagedObjectContext:managedObjectContext];
 [request setEntity:entity];
 NSMutableArray *coreDataArray = [[managedObjectContext executeFetchRequest:request error:nil] mutableCopy];
 [request release];

 for (NSDictionary *dict in arr) {
  NSArray *filtered = [coreDataArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(code == %@)", [dict objectForKey:@"Code"]]];
  //NSLog(@"COREDATA ARRAY: %d FILTERED ARRAY: %d CODE: %@ COREDATA FIRST CODE: %@", [coreDataArray count], [filtered count], [dict objectForKey:@"Code"], [[coreDataArray objectAtIndex:0] code]);
  if ([filtered count] > 0) {
   Company *c = [filtered objectAtIndex:0];
   if ([dict objectForKey:@"Defunct"]) {
    NSLog(@"DELETED DEFUNCT COMPANY");
    [managedObjectContext deleteObject:c];
   } else {
    [c populateWithJSONDictionary:dict];
   }
  } else {
   Company *c = (Company *)[NSEntityDescription insertNewObjectForEntityForName:@"Company" inManagedObjectContext:managedObjectContext];
   [c populateWithJSONDictionary:dict];
  }

  float percent = (float)[arr indexOfObject:dict]/[arr count];
  [self performSelectorInBackground:@selector(updateProgressView:) withObject:[NSString stringWithFormat:@"%f",percent]];
 }

 [coreDataArray release];

Many thanks for any help you can give.