问:
error:14094438:SSL routines:SSL3_READ_BYTES:tlsv1 alert internal error,stream_socket_client(): SSL operation failed with code 1
We Are Config SSl certificate in our server then after this error message is coming. How to resolve this issue

stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages: error:14094438:SSL routines:SSL3_READ_BYTES:tlsv1 alert internal error

答:
Similar error came while connecting spark mongo..

At mongo server end it was giving error like this  SSL: error:14094438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error

There was the same problem with me when we were trying to connect mongo db with spark locally on spark.

Few things to check make sure your spark command is correct.
 i)spark-submit --master local[8] --class
--conf spark.executor.extraJavaOptions=-Djavax.net.ssl.trustStore=
--driver-java-options -Djavax.net.ssl.trustStore=

ii) also check the mongo configuration of the server i used below
net:
 bindIp: 0.0.0.0,localhost
 port: 27017
 ssl:
  mode: requireSSL
  PEMKeyFile: test-server1.pem
  disabledProtocols: TLS1_0,TLS1_1

Issue for us was that we were using CAFile: /etc/ssl/caToValidateClientCertificates.pem property in mongo file . So the CA certificate of java trust store was not matching with the java one.

Make sure also if CA certs are matching . if not then remove the line of CAFile:  from mongo .


来源: stackexchange

问:
Is there a way to save time by not calculating unnecessary sums?

The objective

Given a 2-dimensional array A, I have to keep adding +1 to the value of the first row in each column until the sums of the columns equal to the same value, for example 28.

My solution

It is probably not the best of solutions, but considering the point I'd like to make, it will do. This is meant to be a simplified example. In the original version it is based on a probability distribution whether the first or the second row gets the +1, and it differs among columns. Plus it has to be done one by one, for the probability distribution changes due to whether the first or the second row of a column got the +1 in the previous cycle. So summation of columns and iteration are necessary.

import numpy as np

A = np.arange(20).reshape(2, 10)
print(A)

MASK = A.sum(axis=0) < 28
print(A.sum(axis=0) < 28)

while np.any(MASK):
    LUCKYROW = np.repeat(0, np.count_nonzero(MASK))
    A[LUCKYROW, MASK] += 1
    MASK = A.sum(axis=0) < 28
    print(A.sum(axis=0) < 28)
print(A)
```

<p>Let's take a look at the output:</p>

```[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True False False]
[ True  True  True  True  True  True  True  True False False]
[ True  True  True  True  True  True  True False False False]
[ True  True  True  True  True  True  True False False False]
[ True  True  True  True  True  True False False False False]
[ True  True  True  True  True  True False False False False]
[ True  True  True  True  True False False False False False]
[ True  True  True  True  True False False False False False]
[ True  True  True  True False False False False False False]
[ True  True  True  True False False False False False False]
[ True  True  True False False False False False False False]
[ True  True  True False False False False False False False]
[ True  True False False False False False False False False]
[ True  True False False False False False False False False]
[ True False False False False False False False False False]
[ True False False False False False False False False False]
[False False False False False False False False False False]
[[18 17 16 15 14 13 12 11 10  9]
 [10 11 12 13 14 15 16 17 18 19]]
```

<p>Alright, it works, but why do I calculate the sum of each column in each cycle? Based on previous cycles I know which column's sum has already reached the target value. If I make use of this information, I can save time maybe.</p>

<h2>My second solution</h2>

<pre class="lang-py prettyprint-override"><code>import numpy as np

A = np.arange(20).reshape(2, 10)
print(A)

MASK = A.sum(axis=0) < 28
print(A.sum(axis=0) < 28)

while np.any(MASK):
    LUCKYROW = np.repeat(0, np.count_nonzero(MASK))
    A[LUCKYROW, MASK] += 1
    MASK[MASK] = A[:, MASK].sum(axis=0) < 28
    print(A[:, MASK].sum(axis=0) < 28)
print(A)
</code>```

And the output:

```<code>[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True]
[ True  True  True  True  True  True]
[ True  True  True  True  True  True]
[ True  True  True  True  True]
[ True  True  True  True  True]
[ True  True  True  True]
[ True  True  True  True]
[ True  True  True]
[ True  True  True]
[ True  True]
[ True  True]
[ True]
[ True]
[]
[[18 17 16 15 14 13 12 11 10  9]
 [10 11 12 13 14 15 16 17 18 19]]
</code>```

It seems to work. Although one problem emerges. It is not faster than the first solution. I have tried with 25000 columns and 74998 as target value, but they are roughly equal timewise.

My request

I think I may have a fundamental misunderstanding of either ndarray operations or ndarray indexing. The second solution should do less and less calculation with each cycle, so I'd expect a significant performance improvement. I am unable to find explanation. Where is my train of thought faulty?

答:
A quick demo of how indexing affects sums:

```<code>In [140]: x = np.arange(10000)
In [141]: timeit x.sum()
13.4 µs ± 183 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

summing half the items, even with a fast slice view doesn't save that much time:

```<code>In [142]: timeit x[:5000].sum()
10.8 µs ± 78.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Advanced indexing or masking is slower:

```<code>In [143]: %%timeit idx=np.arange(5000)
     ...: x[idx].sum()

21.3 µs ± 1.12 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [144]: %%timeit
     ...: x[x<=5000].sum()

34.4 µs ± 1.34 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

On a modern computers basic math like addition isn't that expensive.  Selecting items and iterating through arrays is as expensive, timewise, as the addition itself.

ContentLicense: CC BY-SA 4.0

Body:
The objective

Given a 2-dimensional array A, I have to keep adding +1 to the value of the first row in each column until the sums of the columns equal to the same value, for example 28.

My solution

It is probably not the best of solutions, but considering the point I'd like to make, it will do. This is meant to be a simplified example. In the original version it is based on a probability distribution whether the first or the second row gets the +1, and it differs among columns. Plus it has to be done one by one, for the probability distribution changes due to whether the first or the second row of a column got the +1 in the previous cycle. So summation of columns and iteration are necessary.

import numpy as np

A = np.arange(20).reshape(2, 10)
print(A)

MASK = A.sum(axis=0) < 28
print(A.sum(axis=0) < 28)

while np.any(MASK):
    LUCKYROW = np.repeat(0, np.count_nonzero(MASK))
    A[LUCKYROW, MASK] += 1
    MASK = A.sum(axis=0) < 28
    print(A.sum(axis=0) < 28)
print(A)

Let's take a look at the output:

[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True False False]
[ True  True  True  True  True  True  True  True False False]
[ True  True  True  True  True  True  True False False False]
[ True  True  True  True  True  True  True False False False]
[ True  True  True  True  True  True False False False False]
[ True  True  True  True  True  True False False False False]
[ True  True  True  True  True False False False False False]
[ True  True  True  True  True False False False False False]
[ True  True  True  True False False False False False False]
[ True  True  True  True False False False False False False]
[ True  True  True False False False False False False False]
[ True  True  True False False False False False False False]
[ True  True False False False False False False False False]
[ True  True False False False False False False False False]
[ True False False False False False False False False False]
[ True False False False False False False False False False]
[False False False False False False False False False False]
[[18 17 16 15 14 13 12 11 10  9]
 [10 11 12 13 14 15 16 17 18 19]]

Alright, it works, but why do I calculate the sum of each column in each cycle? Based on previous cycles I know which column's sum has already reached the target value. If I make use of this information, I can save time maybe.

My second solution

import numpy as np

A = np.arange(20).reshape(2, 10)
print(A)

MASK = A.sum(axis=0) < 28
print(A.sum(axis=0) < 28)

while np.any(MASK):
    LUCKYROW = np.repeat(0, np.count_nonzero(MASK))
    A[LUCKYROW, MASK] += 1
    MASK[MASK] = A[:, MASK].sum(axis=0) < 28
    print(A[:, MASK].sum(axis=0) < 28)
print(A)

And the output:

[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True]
[ True  True  True  True  True  True]
[ True  True  True  True  True  True]
[ True  True  True  True  True]
[ True  True  True  True  True]
[ True  True  True  True]
[ True  True  True  True]
[ True  True  True]
[ True  True  True]
[ True  True]
[ True  True]
[ True]
[ True]
[]
[[18 17 16 15 14 13 12 11 10  9]
 [10 11 12 13 14 15 16 17 18 19]]

It seems to work. Although one problem emerges. It is not faster than the first solution. I have tried with 25000 columns and 74998 as target value, but they are roughly equal timewise.

My request

I think I may have a fundamental misunderstanding of either ndarray operations or ndarray indexing. The second solution should do less and less calculation with each cycle, so I'd expect a significant performance improvement. I am unable to find explanation. Where is my train of thought faulty?

Body:
A quick demo of how indexing affects sums:

In [140]: x = np.arange(10000)
In [141]: timeit x.sum()
13.4 µs ± 183 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

summing half the items, even with a fast slice view doesn't save that much time:

In [142]: timeit x[:5000].sum()
10.8 µs ± 78.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Advanced indexing or masking is slower:

In [143]: %%timeit idx=np.arange(5000)
     ...: x[idx].sum()

21.3 µs ± 1.12 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [144]: %%timeit
     ...: x[x<=5000].sum()

34.4 µs ± 1.34 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

On a modern computers basic math like addition isn't that expensive.  Selecting items and iterating through arrays is as expensive, timewise, as the addition itself.


问:
What is the proper structure of a nodejs/express backend to retrieve mysql data and send to react
I am learning full-stack development and have successfully completed a few courses, primarily learning nodejs, express, react and mysql.  I feel like I have a decent understanding of the fundamentals.  However, I am a bit lost on how I smartly design the backend server / API that interacts with MYSQL.

Is there a common design pattern for creating objects that wrap up the database functionality?  For instance, if I am retrieving configuration data from a database to display in the react front-end, is there a smart way to wrap up those operations in classes -- other than simply using app.get/app.post functions in the nodejs/express server?

答:
From the Backend perspective, you might want to consider the following structure, although it varies depending on how one wants to use Node.js:

app.js

routes/ (export routers grouped by domain/ function)

views/ (if any)

database/init (connection pool initializations)

repository/ (database functions)

controllers/ (business logic)

config/ (default environment variables/ config settings)

In the case of database initialization, make sure the DB object is created in a single location and only once when the app is started and is being reused across all database calls.

Whether or not to use classes depends on how you end up using Javascript/ Typescript with Node.js (OOPS or Functional way). In the case of OOPS, it makes sense to create a Singleton Class and re-use the database object.


问:
Remote mysql connection works in workbench but not in python
I setup a mysql server (using mariadb) and database on my raspi and am now trying to connect to it from my MacBook.

Version:
mysql  Ver 15.1 Distrib 10.1.38-MariaDB, for debian-linux-gnueabihf (armv7l) using readline 5.2

The connection works in Workbench(on the Mac)but I can't get it to connect in python or command line

the /etc/my.cnf on the raspi looks like this:

bind-address = 0.0.0.0

[mysqld]

I have added a superuser with all permissions and am trying to connect on my Mac command line with this:

```<code>mysql -u {superuser} -p {superuser} -h '192.168.x.x' -P '3307' -D {securities_master}
</code>```

Which doesn’t work.

In python I have tried different variations of this:

host = '192.168.x.x'
user='superuser'
password='superuser'
database='securities_master'

import mysql.connector
cnx = mysql.connector.connect(user=user, password=password, host=host, port='3307')
print(cnx.get_server_info()) ```

command line returns this:
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 3

python script returns this:
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '192.168.x.x' ([Errno 61] Connection refused)")

Workbench connection is solid

答:
I have just same issue solved like that:

check if your mysql has granted "root" or "youruserID" the right to access from localhost(127.0.0.1) and LAN(192.168.x.x) the DB privileges? For this just ssh into remote server and:

```<code> $ mysql -u root -p
 mysql> SHOW GRANTS
</code>```

For me it shows:

```<code> Grants for root@localhost
----------
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD ‘*———‘ WITH GRANT OPTION |
| GRANT PROXY ON ''@'%' TO 'root'@'localhost' WITH GRANT OPTION                                                                             |
</code>```

which means it has been granted privilege from anywhere(@'%') incl. localhost(127.0.0.1)

python access remotely you need to install mysql connector:

```<code> $ pip install mysql-connector-python
</code>```

within Python3 you can try this (if mariaDB the port is 3307, default mysql is 3306):

```<code> >>> import mysql.connector
 >>> cnx =mysql.connector.connect(user='root', password='xxx', host='yourraspyi_sql_ip', port='3307')
 >>> print(cnx.get_server_info())
</code>```

Body:
I setup a mysql server (using mariadb) and database on my raspi and am now trying to connect to it from my MacBook.

Version:
mysql  Ver 15.1 Distrib 10.1.38-MariaDB, for debian-linux-gnueabihf (armv7l) using readline 5.2

The connection works in Workbench(on the Mac)but I can't get it to connect in python or command line

the /etc/my.cnf on the raspi looks like this:

bind-address = 0.0.0.0

[mysqld]

I have added a superuser with all permissions and am trying to connect on my Mac command line with this:

mysql -u {superuser} -p {superuser} -h '192.168.x.x' -P '3307' -D {securities_master}

Which doesn’t work.

In python I have tried different variations of this:

host = '192.168.x.x'
user='superuser'
password='superuser'
database='securities_master'

import mysql.connector
cnx = mysql.connector.connect(user=user, password=password, host=host, port='3307')
print(cnx.get_server_info())

command line returns this:
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 3

python script returns this:
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '192.168.x.x' ([Errno 61] Connection refused)")

Workbench connection is solid

Body:
I have just same issue solved like that:

check if your mysql has granted "root" or "youruserID" the right to access from localhost(127.0.0.1) and LAN(192.168.x.x) the DB privileges? For this just ssh into remote server and:

 $ mysql -u root -p
 mysql> SHOW GRANTS

For me it shows:

 Grants for root@localhost
----------
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD ‘*———‘ WITH GRANT OPTION |
| GRANT PROXY ON ''@'%' TO 'root'@'localhost' WITH GRANT OPTION                                                                             |

which means it has been granted privilege from anywhere(@'%') incl. localhost(127.0.0.1)

python access remotely you need to install mysql connector:

 $ pip install mysql-connector-python

within Python3 you can try this (if mariaDB the port is 3307, default mysql is 3306):

 >>> import mysql.connector
 >>> cnx =mysql.connector.connect(user='root', password='xxx', host='yourraspyi_sql_ip', port='3307')
 >>> print(cnx.get_server_info())


问:
How to add numbers between strings in a list?
I have a mixed list with strings and ints and I need to get to the sum of the numbers between each strings. Ideally the end result would be a list of tuples since each string and following numbers belong together (so order is important).

I can extract the number with iteration using isinstance but the actual list is very large and I sometimes I have 1 or 2 numbers for each string.

my_list = ['a', 2, 1, 'b', 3, 'h', 50, 4, 'd', 4, 'v', 20, 7]

ideal_output = [('a', 3) ('b', 3), ('h', 54), ('d', 4), (v, 27)]

```

答:
Here's a solution using itertools.groupby:

```<code>my_list = ['a', 2, 1, 'b', 3, 'h', 50, 4, 'd', 4, 'v', 20, 7]

from itertools import groupby

groups = groupby(my_list, key=type) # group-by the type of the value

result = []
for key, group in groups:
    string = next(group) # get the string first, we'll skip over it otherwise
    if key is str:
        _, values = next(groups) # move the generator forward to get to the numbers
        result.append((string, sum(values))) # sum up the numbers
print(result)
</code>```

Output:

```<code>[('a', 3), ('b', 3), ('h', 54), ('d', 4), ('v', 27)]
</code>```

It does assume that there will be at least one number between the strings. If not you can check on the len of g and if that's more than 1, add a 0 for the value of the first value in g

Body:
Here's a solution using itertools.groupby:

my_list = ['a', 2, 1, 'b', 3, 'h', 50, 4, 'd', 4, 'v', 20, 7]

from itertools import groupby

groups = groupby(my_list, key=type) # group-by the type of the value

result = []
for key, group in groups:
    string = next(group) # get the string first, we'll skip over it otherwise
    if key is str:
        _, values = next(groups) # move the generator forward to get to the numbers
        result.append((string, sum(values))) # sum up the numbers
print(result)

Output:

[('a', 3), ('b', 3), ('h', 54), ('d', 4), ('v', 27)]

It does assume that there will be at least one number between the strings. If not you can check on the len of g and if that's more than 1, add a 0 for the value of the first value in g


问:
how to compare the sequence of characters in two strings
Python version is 2.7.9
In python, I have the baseline strings and other strings to be compared:

```<code>baseline_string="c1,c2,c3,c4,c5,c6,c7,c8,c9,c10"
#all the characters appeared as the sequence defined in base line string ,this is ok
compared1="c1,c2,c3,c4,c5,c6,c7,c8,c9,c10"
#all the characters appeared as the sequence defined in base line string,some charaters don't appear such as c2 and c7 don't appear ,this is ok
compared2="c1,c3,c4,c5,c6,c8,c9,c10"
#some character does not appear as the defind sequece,such as c4 is before c3 ,and c110 is before c9
</code>```

The difflib.SequenceMatcher can not solve my problem.
Need the python guru to give some advice.
Thanks a lot.

答:
Try this, using the itertools will help you overcome the strings being of different lengths.
.zip compares character for character in each of the strings and returns them in tuples.

```<code>import itertools

compared1 = "c1,c2,c3,c4,c5,c6,c7,c8,c9,c10"

compared2 = "c1,c3,c4,c5,c6,c8,c9,c10"

words = itertools.zip_longest(compared1,compared2,fillvalue=None)

incorrect = len([c for c,d in words if c!=d])

print(incorrect)
</code>```

Body:
Python version is 2.7.9
In python, I have the baseline strings and other strings to be compared:

baseline_string="c1,c2,c3,c4,c5,c6,c7,c8,c9,c10"
#all the characters appeared as the sequence defined in base line string ,this is ok
compared1="c1,c2,c3,c4,c5,c6,c7,c8,c9,c10"
#all the characters appeared as the sequence defined in base line string,some charaters don't appear such as c2 and c7 don't appear ,this is ok
compared2="c1,c3,c4,c5,c6,c8,c9,c10"
#some character does not appear as the defind sequece,such as c4 is before c3 ,and c110 is before c9

The difflib.SequenceMatcher can not solve my problem.
Need the python guru to give some advice.
Thanks a lot.

Body:
Try this, using the itertools will help you overcome the strings being of different lengths.
.zip compares character for character in each of the strings and returns them in tuples.

import itertools

compared1 = "c1,c2,c3,c4,c5,c6,c7,c8,c9,c10"

compared2 = "c1,c3,c4,c5,c6,c8,c9,c10"

words = itertools.zip_longest(compared1,compared2,fillvalue=None)

incorrect = len([c for c,d in words if c!=d])

print(incorrect)


问:
Help with JQuery selector :not(:last)
I'm trying to select all the bullets except the last bullet but I am doing something incorrectly.

Here is my html

```<code><ul>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
</ul>

<ul>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
</ul>

<ul>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
</ul>
</code>```

And my jQuery:

```<code>jQuery('ul li:not(:last)').append(" | ");
</code>```

It's adding the pipe to every bullet however...

答:
Because your html contains multiple unordered lists, $('ul li') will selects every single
, in all of the
s. :last then selects the final element in that list. Use :last-child, which gets the last
 in each of the
s.

```<code>$('ul li:not(:last-child)').append(' | ');
</code>```

http://jsfiddle.net/mattball/qmVdb/1/

ContentLicense: CC BY-SA 3.0

Title: Help with JQuery selector :not(:last)

Body:
I'm trying to select all the bullets except the last bullet but I am doing something incorrectly.

Here is my html

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

And my jQuery:

jQuery('ul li:not(:last)').append(" | ");

It's adding the pipe to every bullet however...

Body:
Because your html contains multiple unordered lists, $('ul li') will selects every single <li>, in all of the <ul>s. :last then selects the final element in that list. Use :last-child, which gets the last <li> in each of the <ul>s.

$('ul li:not(:last-child)').append(' | ');

http://jsfiddle.net/mattball/qmVdb/1/


问:
How can I get master branch of a dependency when using Go modules
I am using Go-modules for a project. When I retrieve the dependency for a package, it retrieves an old release. How can I get the code in the master branch?</p>

答:
Use:

```<code>go get foo@master
</code>```

```<code>go get foo@v1.2.3    //for v1.2.3 tag
go get foo@master    // for master
go get foo@e3702bed2 // for a specific commit
</code>```

There are some more details about versioning here:

https://github.com/golang/go/wiki/Modules#daily-workflow

Body:
Use:

go get foo@master

go get foo@v1.2.3    //for v1.2.3 tag
go get foo@master    // for master
go get foo@e3702bed2 // for a specific commit

There are some more details about versioning here:

https://github.com/golang/go/wiki/Modules#daily-workflow


问:
Eclipse -> Run Button -> Shortcut
Is there any shortcut key that I can use to run my program? Sick and tired of going to the top of the screen and clicking on the green run button. And yes, I've looked everywhere to find for a shortcut and trust me, I can't find it anywhere.

I'm currently working with Python 3.x and using a Mac.
And no, Ctrl+F11 does not work. It only increases my volume.

答: Try F9. On Windows it is working.</p>

Title: Eclipse -> Run Button -> Shortcut

Body: Try F9. On Windows it is working.


问:
Dataframe can't fill NaN values in pandas
I have a DataFrame with some NaN values, that I want to fit with the mean of my DataFrame

```<code>data.fillna(data.mean())
</code>```

afterwards, I check to see if there are any NaN or null values left

```<code> print('is nan', data.isna().values.any()) #prints True
 print('is null', data.isnull().values.any()) #prints True
</code>```

before prints to be true, and I don't understand since the NaN values should be filled.

Am I missing something?

答:
This is a sample reproducible example.</p>

```<code>import pandas as pd
# generate sample dataframe some filled with NaN
data = pd.DataFrame([[1, 2], [np.nan, 4], [5, 6], [7, np.nan]], columns=["A", "B"])
# apply per-column and substitue the mean of that columns
data.apply(lambda x: x.fillna(x.mean()),axis=1)
</code>```

Body:
I have a DataFrame with some NaN values, that I want to fit with the mean of my DataFrame

data.fillna(data.mean())

afterwards, I check to see if there are any NaN or null values left

 print('is nan', data.isna().values.any()) #prints True
 print('is null', data.isnull().values.any()) #prints True

before prints to be true, and I don't understand since the NaN values should be filled.

Am I missing something?

Body:
This is a sample reproducible example.

import pandas as pd
# generate sample dataframe some filled with NaN
data = pd.DataFrame([[1, 2], [np.nan, 4], [5, 6], [7, np.nan]], columns=["A", "B"])
# apply per-column and substitue the mean of that columns
data.apply(lambda x: x.fillna(x.mean()),axis=1)


问:
C++: pointers and compiler (aliasing?) optimization
I've ran into a trouble with compiler optimization so I need some help.
I've got the following code:

```<code>typedef struct {
   int32_t  DataLen;
   char     Data[1];
} MTEMSG;
MTEMSG *IfaceData;
int Interface = MTEStructure2(ConnectionHandle, &IfaceData);
int32_t * pointer = (int32_t *)IfaceData->Data;
ReadFromBuf(pointer);
</code>```

MTEStructure2 is a third-party function, that allocates a block of memory starting with IfaceData->Data and having IfaceData->DataLen length. This buffer consists of multiple 1-byte character lines, each line is preceded by that line's length (a 4-byte integer). So I've got a function to read one line:

```<code>int * MTEGetString(int * pointer, std::string & result)
{
    int datalen = 0;
    datalen = *pointer;
    char * data;
    data = (char *) (pointer + 1);
    result = std::string(data, datalen);
    pointer = (int *)(data + datalen);
    return pointer;
}
</code>```

It is called from ReadFromBuf like this:

```<code>int* ReadFromBuf(int * pointer)
{
    std::string name="", caption="", description="";
    pointer = MTEGetString(pointer, name);
    pointer = MTEGetString(pointer, caption);
    pointer = MTEGetString(pointer, description);
    // etc
}
</code>```

And everything works fine in debug mode (I'm using Qt 5.0.1 with gcc 4.7.2 under WinXP). But as long as I switch to release mode, the program crashes on result = std::string(data, datalen);, because datalen (and by that moment the whole buffer, I guess) is not valid. Everything works fine again after I disable optimization for release builds (QMAKE_CXXFLAGS_RELEASE -= -O2).

I've done some reading, and the closest thing I've found is an aliasing optimization. But compiler gives no warning even with -Wall option, and -fno-strict-aliasing doesn't help, so I'm totally in the dark. Of course, I could build the project with disabled optimization, but I would really like to understand what's going on.
Thanks in advance.

答: After some research I've found that I had both -std=gnu++11 and -std=c++1x in gcc call for release build. After I removed -std=gnu++11 everything worked like a charm.

Body:
I've ran into a trouble with compiler optimization so I need some help.
I've got the following code:

typedef struct {
   int32_t  DataLen;
   char     Data[1];
} MTEMSG;
MTEMSG *IfaceData;
int Interface = MTEStructure2(ConnectionHandle, &IfaceData);
int32_t * pointer = (int32_t *)IfaceData->Data;
ReadFromBuf(pointer);

MTEStructure2 is a third-party function, that allocates a block of memory starting with IfaceData->Data and having IfaceData->DataLen length. This buffer consists of multiple 1-byte character lines, each line is preceded by that line's length (a 4-byte integer). So I've got a function to read one line:

int * MTEGetString(int * pointer, std::string & result)
{
    int datalen = 0;
    datalen = *pointer;
    char * data;
    data = (char *) (pointer + 1);
    result = std::string(data, datalen);
    pointer = (int *)(data + datalen);
    return pointer;
}

It is called from ReadFromBuf like this:

int* ReadFromBuf(int * pointer)
{
    std::string name="", caption="", description="";
    pointer = MTEGetString(pointer, name);
    pointer = MTEGetString(pointer, caption);
    pointer = MTEGetString(pointer, description);
    // etc
}

And everything works fine in debug mode (I'm using Qt 5.0.1 with gcc 4.7.2 under WinXP). But as long as I switch to release mode, the program crashes on result = std::string(data, datalen);, because datalen (and by that moment the whole buffer, I guess) is not valid. Everything works fine again after I disable optimization for release builds (QMAKE_CXXFLAGS_RELEASE -= -O2).

I've done some reading, and the closest thing I've found is an aliasing optimization. But compiler gives no warning even with -Wall option, and -fno-strict-aliasing doesn't help, so I'm totally in the dark. Of course, I could build the project with disabled optimization, but I would really like to understand what's going on.
Thanks in advance.


问:
Import .csv file through SSIS Package without double Quotes
SQL 2005

I am importing .csv file to SQL Table through SSIS Package !! On doing so, I am getting double quotes on every column header or field value !!

How to remove double quotes, while importing .csv file ???

答:
The csv file is using the " as a text qualifier.

When importing you must specify inform SSIS of this.

See How to strip out double quotes from an import file in SQL Server Integration Services SSIS


答:
You can just use simple iteration as well without groupby, this will be slightly faster because it only does one pass:

```<code>my_list = ['a', 2, 1, 'b', 3, 'h', 50, 4, 'd', 4, 'v', 20, 7]
new_list = []
new_element = []
for element in my_list:
    if isinstance(element, str):
        if new_element:
            new_list.append(tuple(new_element))
        new_element = [element, 0]
    else:
        new_element[1] += element
if new_element:
    new_list.append(new_element)
print(new_list)
</code>```

Output:

```<code>[('a', 3), ('b', 3), ('h', 54), ('d', 4), ('v', 27)]
</code>```

Title: How to add numbers between strings in a list?

Body:
I have a mixed list with strings and ints and I need to get to the sum of the numbers between each strings. Ideally the end result would be a list of tuples since each string and following numbers belong together (so order is important).

I can extract the number with iteration using isinstance but the actual list is very large and I sometimes I have 1 or 2 numbers for each string.

my_list = ['a', 2, 1, 'b', 3, 'h', 50, 4, 'd', 4, 'v', 20, 7]

ideal_output = [('a', 3) ('b', 3), ('h', 54), ('d', 4), (v, 27)]

Body:
You can just use simple iteration as well without groupby, this will be slightly faster because it only does one pass:

my_list = ['a', 2, 1, 'b', 3, 'h', 50, 4, 'd', 4, 'v', 20, 7]
new_list = []
new_element = []
for element in my_list:
    if isinstance(element, str):
        if new_element:
            new_list.append(tuple(new_element))
        new_element = [element, 0]
    else:
        new_element[1] += element
if new_element:
    new_list.append(new_element)
print(new_list)

Output:

[('a', 3), ('b', 3), ('h', 54), ('d', 4), ('v', 27)]


问:
How can I project into the same DTO type twice?
The goal here is to update an IQueryable that projects into a dto so it only includes a subset of the properties that it originally included. The "subset" is being provided as a list of strings that maps to the properties of the dto.

I already have code that turns this into a projection but the problem is I cannot project into the same dto type twice. Luckily I can reproduce the problem by just having 2 selects into the same type:

public IEnumerable<OrderDto> GetOrderDtos( IEnumerable<string> properties ) {
    IQueryable<OrderDto> results = dbContext.Orders
        .Select( getOrderProjection( ) );

    if(properties != null && properties.Any()){
        results = results.applyPropertyList(properties);
    }

    return results.ToList( );
}

private Expression<Func<FixTradeRequest, OrderDto>> getOrderProjection(){
    return o => new OrderDto {
        Id = o.Id,
        AccountId = o.AccountId,
        AccountNumber = o.Account.Info.AccountNumber,
        Application = o.TradeRequestInstance.RequestType,
        WarningMessage = o.WarningMessage
        //trimmed for brevity, this has about 100 properties mapped
    };
}

private IQueryable<OrderDto> applyPropertyList( IQueryable<OrderDto> source, IEnumerable<string> properties ){
    /*in reality this is dynamically created from the provided list
    of properties, but this static projection shows the problem*/
    return source.Select( o => new OrderDto {
        Id = o.Id,
        WarningMessage = o.WarningMessage
    } );
}
```

As written this returns an error "The type 'OrderDto' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order."

I've figured out a solution that modifies the expression returned from getOrderProjection however this is not ideal because in other places the IQueryable I would like to modify is far more complex than just a projection like this one.

Therefore the solution must only include changes to the applyPropertyList function. I'm thinking some kind of ExpressionVisitor could merge these two together but I don't know where to start or if that would even work.

答:
I figured it out. The answer was by using an ExpressionVisitor. The TrimProjection method here takes the place of the applyPropertyList in the question.

public static partial class QueryableExtensions {
    public static IQueryable<TResult> TrimProjection<TResult>( this IQueryable<TResult> source, IEnumerable<string> targetPropeties ) {
        var visitor = new ProjectionReducer<TResult>( targetPropeties );
        var expression = visitor.Visit( source.Expression );
        if( expression != source.Expression )
            return source.Provider.CreateQuery<TResult>( expression );
        return source;
    }

    private class ProjectionReducer<TResult> : ExpressionVisitor {
        private readonly List<string> propNames;
        public ProjectionReducer( IEnumerable<string> targetPropeties ) {
            if( targetPropeties == null || !targetPropeties.Any( ) ) {
                throw new ArgumentNullException( nameof( targetPropeties ) );
            }
            this.propNames = targetPropeties.ToList( );
        }

        protected override Expression VisitNew( NewExpression node ) {
            return base.VisitNew( node );
        }
        protected override Expression VisitLambda<T>( Expression<T> node ) {
            //if the node returns the type we are acting upon
            if( node.ReturnType == typeof( TResult ) ) {
                //create a new expression from this one that is the same thing with some of the bindings omitted
                var mie = (node.Body as MemberInitExpression);
                var currentBindings = mie.Bindings;

                var newBindings = new List<MemberBinding>( );

                foreach( var b in currentBindings ) {
                    if( propNames.Contains( b.Member.Name, StringComparer.CurrentCultureIgnoreCase ) ) {
                        newBindings.Add( b );
                    }
                }

                Expression testExpr = Expression.MemberInit(
                    mie.NewExpression,
                    newBindings
                );

                return Expression.Lambda( testExpr, node.Parameters );
            }
            return base.VisitLambda( node );
        }
    }
}
```

Body:
The goal here is to update an IQueryable that projects into a dto so it only includes a subset of the properties that it originally included. The "subset" is being provided as a list of strings that maps to the properties of the dto.

I already have code that turns this into a projection but the problem is I cannot project into the same dto type twice. Luckily I can reproduce the problem by just having 2 selects into the same type:

public IEnumerable<OrderDto> GetOrderDtos( IEnumerable<string> properties ) {
    IQueryable<OrderDto> results = dbContext.Orders
        .Select( getOrderProjection( ) );

    if(properties != null && properties.Any()){
        results = results.applyPropertyList(properties);
    }

    return results.ToList( );
}

private Expression<Func<FixTradeRequest, OrderDto>> getOrderProjection(){
    return o => new OrderDto {
        Id = o.Id,
        AccountId = o.AccountId,
        AccountNumber = o.Account.Info.AccountNumber,
        Application = o.TradeRequestInstance.RequestType,
        WarningMessage = o.WarningMessage
        //trimmed for brevity, this has about 100 properties mapped
    };
}

private IQueryable<OrderDto> applyPropertyList( IQueryable<OrderDto> source, IEnumerable<string> properties ){
    /*in reality this is dynamically created from the provided list
    of properties, but this static projection shows the problem*/
    return source.Select( o => new OrderDto {
        Id = o.Id,
        WarningMessage = o.WarningMessage
    } );
}

As written this returns an error "The type 'OrderDto' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order."

I've figured out a solution that modifies the expression returned from getOrderProjection however this is not ideal because in other places the IQueryable I would like to modify is far more complex than just a projection like this one.

Therefore the solution must only include changes to the applyPropertyList function. I'm thinking some kind of ExpressionVisitor could merge these two together but I don't know where to start or if that would even work.


问:
Using heaps for schedulers
On the Python official docs here, the following is mentioned regarding heaps:

A nice feature of this sort is that you can efficiently insert new
  items while the sort is going on, provided that the inserted items are
  not “better” than the last 0’th element you extracted. This is
  especially useful in simulation contexts, where the tree holds all
  incoming events, and the “win” condition means the smallest scheduled
  time. When an event schedules other events for execution, they are
  scheduled into the future, so they can easily go into the heap

I can only think of the following simple algorithm to implement a scheduler using heap:

```<code># Priority queue using heap
pq = []
# The first element in the tuple represents the time at which the task should run.
task1 = (1, Task(...))
task2 = (2, Task(...))
add_task(pq, task1)
add_task(pq, task2)
# Add a few more root-level tasks
while pq:
    next_task = heapq.heappop()
    next_task.perform()
    for child_task in next_task.get_child_tasks():
        # Add new child tasks if available
        heapq.heappush(pq, child_task)
</code>```

In this, where does sorting even come into the picture?

And even if the future child tasks have a time for the 'past', still this algorithm would work correctly.

So, why is the author warning about the child events only being scheduled for the future??

And what does this mean:

you can efficiently insert new items while the sort is going on,
  provided that the inserted items are not “better” than the last 0’th
  element you extracted.

答:
Heap are used as data structure for priority queue, in fact the fundamental in a min heap is that you have the lowest priority on top (or in max heap the higher priority on top). Therefore you can always extract lowest or highest element without search it.

You can always insert new element during the sorting, try to look how the heapSort works. Every time you need to build your heap and then extract the maximum value and put it on the end of the array, after you decrement the heap.length of 1.
If you already sorted some numbers: [..., 13, 15, 16] and you insert a new number that is higher of the last element that is extracted (13 = 0’th element) you will get a wrong solution, because you will extract the new number but you won't put it in the right place: [1, 2, 5, 7, 14, 13, 15, 16]. It will be placed before 13 because it swap the element on heap.length position.
This is obviously wrong so you can only insert element that are less of the 0’th element.

Title: Using heaps for schedulers

Body:
On the Python official docs here, the following is mentioned regarding heaps:

A nice feature of this sort is that you can efficiently insert new
  items while the sort is going on, provided that the inserted items are
  not “better” than the last 0’th element you extracted. This is
  especially useful in simulation contexts, where the tree holds all
  incoming events, and the “win” condition means the smallest scheduled
  time. When an event schedules other events for execution, they are
  scheduled into the future, so they can easily go into the heap

I can only think of the following simple algorithm to implement a scheduler using heap:

# Priority queue using heap
pq = []
# The first element in the tuple represents the time at which the task should run.
task1 = (1, Task(...))
task2 = (2, Task(...))
add_task(pq, task1)
add_task(pq, task2)
# Add a few more root-level tasks
while pq:
    next_task = heapq.heappop()
    next_task.perform()
    for child_task in next_task.get_child_tasks():
        # Add new child tasks if available
        heapq.heappush(pq, child_task)

In this, where does sorting even come into the picture?

And even if the future child tasks have a time for the 'past', still this algorithm would work correctly.

So, why is the author warning about the child events only being scheduled for the future??

And what does this mean:

you can efficiently insert new items while the sort is going on,
  provided that the inserted items are not “better” than the last 0’th
  element you extracted.


问:
In racket how do i combine strings in a list to create one sentence
Essentially I want to combine string values in a list.
For example I want
(Join(list "cat" "is" "hungry")) to execute ("cat is hungry")

(define(join l) )

答:
Use string-append*

See https://docs.racket-lang.org/reference/strings.html?q=string-append*#%28def._%28%28lib._racket%2Fstring..rkt%29._string-append%2A%29%29


问:
Why is there space between the parallelogram-divs?
I've made a few parallelograms in a row like that, but there is some space between them. I want to remove that space. margin-left: -1px; works, but I'm afraid that it's a bad solution to this problem.

Here is a fiddle: https://jsfiddle.net/rw40ugq1/

Here is the code:

body {
    font-size: 0;
    margin: 0;
}

.parallelogram {
    background-color: red;
    display: inline-block;
    height: 100px;
    width: 85px;
    transform: skew(20deg);
    position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div class="parallelogram"></div>
    <div class="parallelogram"></div>
    <div class="parallelogram"></div>
    <div class="parallelogram"></div>
    <div class="parallelogram"></div>
    <div class="parallelogram"></div>
</body></code>```

答:
You can add a small outline:

.container {
  font-size: 0;
  margin: 0;
}

.button {
  height: 100px;
  background-color: red;
  width: 85px;
  display: inline-block;
  position: relative;
  transform: skew(20deg);
  outline:0.1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
</div></code>```

Body:
You can add a small outline:

.container {
  font-size: 0;
  margin: 0;
}

.button {
  height: 100px;
  background-color: red;
  width: 85px;
  display: inline-block;
  position: relative;
  transform: skew(20deg);
  outline:0.1px solid red;
}

<div class="container">
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
</div>


问:
Failing consul health check on local machine
I have Consul running via docker using docker-compose

```<code>version: '3'

services:
  consul:
    image: unifio/consul:latest
    ports:
      - "8500:8500"
      - "8300:8300"
    volumes:
      - ./config:/config
      - ./.data/consul:/data
    command: agent -server -data-dir=/data -ui -bind 0.0.0.0 -client 0.0.0.0 -bootstrap-expect=1
  mongo:
    image: mongo
    ports:
      - "27017:27017"
      - "27018:27018"
    volumes:
      - ./.data/mongodb:/data/db
    command: mongod --bind_ip_all
</code>```

and have a nodejs service running on port 6001 which exposes a /health endpoint for health checks.
I am able to register the service via this consul package.
However, visiting the consul UI I can see that the service has a status of failing because the health check is not working.

The UI show this message:

```<code>Get http://127.0.0.1:6001/health: dial tcp 127.0.0.1:6001: getsockopt: connection refused
</code>```

Not sure why is not working exactly, but I kind of sense that i may have misconfigured consul.
Any help would be great.

答:
While Zeitounator's answer is perfectly fine and answers your direct question,
the "indirect" solution to your problem would be to manage the nodejs service
through docker-compose.

IMHO it's a good idea to manage all services involved using the same tool,
as then their lifecycles are aligned and also it's easy to configure them to talk
to each other (at least that's the case for docker-compose).

Moreover, letting containers access services on the host is risky in terms of security.
In production environments you usually want to shield host services from containers,
as otherwise the containers lose their "containment" role.

So, in your case you would need to add the nodejs service to docker-compose.yml:

```<code>services:
  (...)
  nodejs-service:
    image: nodejs-service-image
    ports:
    - "6001:6001" [this is only required if you need to expose the port on the host]
    command: nodejs service.js
</code>```

And then your Consul service would be able to access nodejs-service
through http://nodejs-service:6001/health.

Body:
I have Consul running via docker using docker-compose

version: '3'

services:
  consul:
    image: unifio/consul:latest
    ports:
      - "8500:8500"
      - "8300:8300"
    volumes:
      - ./config:/config
      - ./.data/consul:/data
    command: agent -server -data-dir=/data -ui -bind 0.0.0.0 -client 0.0.0.0 -bootstrap-expect=1
  mongo:
    image: mongo
    ports:
      - "27017:27017"
      - "27018:27018"
    volumes:
      - ./.data/mongodb:/data/db
    command: mongod --bind_ip_all

and have a nodejs service running on port 6001 which exposes a /health endpoint for health checks.
I am able to register the service via this consul package.
However, visiting the consul UI I can see that the service has a status of failing because the health check is not working.

The UI show this message:

Get http://127.0.0.1:6001/health: dial tcp 127.0.0.1:6001: getsockopt: connection refused

Not sure why is not working exactly, but I kind of sense that i may have misconfigured consul.
Any help would be great.

Body:
While Zeitounator's answer is perfectly fine and answers your direct question,
the "indirect" solution to your problem would be to manage the nodejs service
through docker-compose.

IMHO it's a good idea to manage all services involved using the same tool,
as then their lifecycles are aligned and also it's easy to configure them to talk
to each other (at least that's the case for docker-compose).

Moreover, letting containers access services on the host is risky in terms of security.
In production environments you usually want to shield host services from containers,
as otherwise the containers lose their "containment" role.

So, in your case you would need to add the nodejs service to docker-compose.yml:

services:
  (...)
  nodejs-service:
    image: nodejs-service-image
    ports:
    - "6001:6001" [this is only required if you need to expose the port on the host]
    command: nodejs service.js

And then your Consul service would be able to access nodejs-service
through http://nodejs-service:6001/health.


问:
Problems with stopping html5 audio and restarting playback
if i stop audio playback with .pause() method then set .currentTime=0 and finally call .play() method again i hear a scratch... Sometimes it sounds like the playback starts at position 1sec, but should start at 0! My Code:

HTML:

```<code><audio id="sound" preload="auto" autobuffer>
    <source src="a.mp3" />
</audio>
</code>```

JS:

```<code>var sound = $('#sound')[0];

function playSound(){
    sound.pause();
    sound.currentTime = 0;
    sound.play();
}
</code>```

If i call the function eventdriven, sometimes the above explained error occures.

Any ideas? Thx.

答: Code looks good. Have you tried in different browsers? HTML5 is not final yet and browser vendors are working on the implementations. Maybe a bug?</p>

ContentLicense: CC BY-SA 2.5

Body:
if i stop audio playback with .pause() method then set .currentTime=0 and finally call .play() method again i hear a scratch... Sometimes it sounds like the playback starts at position 1sec, but should start at 0! My Code:

HTML:

<audio id="sound" preload="auto" autobuffer>
    <source src="a.mp3" />
</audio>

JS:

var sound = $('#sound')[0];

function playSound(){
    sound.pause();
    sound.currentTime = 0;
    sound.play();
}

If i call the function eventdriven, sometimes the above explained error occures.

Any ideas? Thx.


问:
Firestore cannot get path onsnapshot
I am listening to changes on the database for collection_group
I cannot access ref (which has path) of a DocumentSnapshot I keep getting the error:

```<code>AttributeError: 'DocumentSnapshot' object has no attribute 'ref'
</code>```

Here is my code:

```<code>doc_ref = firestore_db.collection_group(u'collection_name')
doc_ref.on_snapshot(self.__get_snapshot(args))
</code>```

This is my __get_snapshot method:

```<code>def __get_snapshot(self, args):
    def on_snapshot(doc_snapshot, changes, read_time):
        for doc in doc_snapshot: #crashes
            print(u'Received document snapshot: {}'.format(doc.ref))
        for change in changes:
            if(change.type.name == "MODIFIED"):
                print(change.document.ref) #crashes
                print(change.document.get("field"))#this works fine
return on_snapshot
</code>```

答: The API documentation for DocumentSnapshot says that the reference of the document can be found in its reference property.  So you will want to use this: doc.reference.

Title: Firestore cannot get path onsnapshot

Body:
I am listening to changes on the database for collection_group
I cannot access ref (which has path) of a DocumentSnapshot I keep getting the error:

AttributeError: 'DocumentSnapshot' object has no attribute 'ref'

Here is my code:

doc_ref = firestore_db.collection_group(u'collection_name')
doc_ref.on_snapshot(self.__get_snapshot(args))

This is my __get_snapshot method:

def __get_snapshot(self, args):
    def on_snapshot(doc_snapshot, changes, read_time):
        for doc in doc_snapshot: #crashes
            print(u'Received document snapshot: {}'.format(doc.ref))
        for change in changes:
            if(change.type.name == "MODIFIED"):
                print(change.document.ref) #crashes
                print(change.document.get("field"))#this works fine
return on_snapshot


问:
Set the width of a column in a datagrid?
How do I set the width of a column in a DataGrid (not a DataGridView)?

答:
Private Sub dgColumnWidths()
'Var = 0 for first column
Dim Var As Integer
DataGrid1.Columns(Var).Width = 1000
End Sub</p>


问:
Is it better practice to performSegueWithIdentifier or presentViewController
If I am using storyboards, is it better practice to create a segue and use performSegueWithIdentifier or just use presentViewController to move the user from one View Controller to the next.

For this example, let's assume we are using Swift 5 and I have 2 view controllers: a TableView of Contacts on MainViewController and the details of that Contact on DetailViewController.

In my code, I am using presentViewController, but as I am new to iOS development, I'm not sure if this is the best approach.

答:
Both of them do the same thing, But i usually use Present so when i want to change the behaviour for example, make the button open another VC, i just change the identifier, i don't have to remove the segue and create a new one.
Also many segues would make your storyboard look spaghetti</p>


问:
Are there any pitfalls in displaying a "No JavaScript" warning in the following fashion?
I have a webpage that has a comment box that can be toggled by clicking a link (the opening and closing of the box is controlled using JavaScript, specifically JQuery). This box is hidden by default, so naturally, it's impossible to display without the use of JavaScript. I'm not concerned by this fact: the comment box is not a "necessary" feature and this is a small personal site, so I don't mind that a tiny percentage of visitors may not experience full functionality. However, I would like to display a warning if the user does not have JavaScript enabled.

I've considered the idea of doing this by presenting a small message (with the use of a simple HTML
 tag) near the link that toggles the comment box, using the following bit of code:

```<code><p class="alert" id="nojs-warning">You must have JavaScript enabled to leave a comment.</p>
</code>```

Of course, I don't want to display this if JavaScript is enabled, so I have the following JQuery trigger set up to immediately hide the box when the page is loaded:

```<code>$(function() {
    $('#nojs-warning').hide();
});
</code>```

Thus, if the user has JavaScript enabled, the event will fire and the warning will be hidden; if the user doesn't have JavaScript enabled, the event won't fire, and thus the warning will still be displayed.

For such a small, personal site, this seems like an elegant solution. Are there any pitfalls to this approach?

答: Why not use the  tag? That's what it's intended for.

OwnerDisplayName: mipadi

Body:
I have a webpage that has a comment box that can be toggled by clicking a link (the opening and closing of the box is controlled using JavaScript, specifically JQuery). This box is hidden by default, so naturally, it's impossible to display without the use of JavaScript. I'm not concerned by this fact: the comment box is not a "necessary" feature and this is a small personal site, so I don't mind that a tiny percentage of visitors may not experience full functionality. However, I would like to display a warning if the user does not have JavaScript enabled.

I've considered the idea of doing this by presenting a small message (with the use of a simple HTML
 tag) near the link that toggles the comment box, using the following bit of code:

You must have JavaScript enabled to leave a comment.

Of course, I don't want to display this if JavaScript is enabled, so I have the following JQuery trigger set up to immediately hide the box when the page is loaded:

$(function() {
    $('#nojs-warning').hide();
});

Thus, if the user has JavaScript enabled, the event will fire and the warning will be hidden; if the user doesn't have JavaScript enabled, the event won't fire, and thus the warning will still be displayed.

For such a small, personal site, this seems like an elegant solution. Are there any pitfalls to this approach?

Body: Why not use the <noscript> tag? That's what it's intended for.

OwnerDisplayName: Franci Penov


问:
php update limit not work in a mysql_fetch_array loop
I want to let my database article reclassified. I explode the text of a given article, and then see if there is one word of the article match 1 tag which it has appear in the category table, then update this article in this category name. My code is here. I want make a limit that every category max has 5 articles. but the update limit not work. Thanks.

```<code><?php
header('Content-type:text/html; charset=utf-8');
$db = mysql_connect("localhost","root","root") or die("can not connect Mysql Server");
mysql_select_db("12",$db);
$result = mysql_query("SELECT title,content,id,cat,date FROM articles Order By date DESC"); //get all the articles
$count = 0;
$ids = array();
$categories = array('1','2','3','4','5','6','7','8','9','10');//category numbers, for 1 = art, 2 = travel... these are stored in another refrenced DB table
$curCategory = array_shift($categories);
echo $curCategory;
while ($row = mysql_fetch_array($result))
{
$tt = $row['title'].' '.$row['content'];
$tt = preg_replace('/[^a-zA-Z0-9 ]/','',$tt);
$words = preg_split("/\s+/",$tt);
$uniqueWords = array_keys(array_flip($words)); // broken article sentence into words
$parts = '';
foreach($uniqueWords as $word){
$parts[] = " tag1 = '$word' OR tag2 = '$word' OR tag3 = '$word' OR tag4 = '$word' OR tag5 = '$word' ";
}
$where = implode(" OR ", $parts);
mysql_select_db("12",$db);
mysql_query("SET NAMES utf8");
    $query1 = mysql_query("SELECT count(*) as count FROM tag1 WHERE ($where) AND category ='count($categories)' ");  //put the break words into reference table match out the category number
    $count = 0;
    while ($row = mysql_fetch_array($query1)) {
        $count = $row['count'];
    }
    if($count) {
        $ids[] = $row['id'];
        $count++;
        if($count == 5) {
             mysql_query("UPDATE articles SET cat = '$curCategory' WHERE id in ('".implode("', '", $ids)."')"); //update every category max articles
            if(!$curCategory = array_shift($categories)) {
                break;
            }
            $count = 0;
            $ids = array();
        }
    }
}
?>
</code>```

reference table

```<code>category | tag1    | tag2   | tag3       | tag4    |  tag5
1        | paint   | picture| sculpture  | photo   |  bronze
2        | tourism | travel | tour       | journey |  trip
3        | style   | vogue  | fashion    | mode    |  Popular
... // 10 categories, category 1 = art , category 2 = travel ...
</code>```

答:
Scary.

The code is messy, as other answers explain well, but your choice of structure for the tag data is also going to cause you trouble.

Rather than 5 columns for 5 tags, create a separate tag table and link it to your articles:

```<code>article | tag       |
  1     | paint     |
  1     | picture   |
  1     | sculpture |
  1     | photo     |
  1     | bronze    |
  2     | tourism   |
  2     | travel    |
  2     | tour      |
</code>```

Then when you tag, you don't need to worry about whether the tag is tag1 or tag2, or whether tag3 is NULL, or whether you're changing your mind and want 6 tags after all. The structure will work for anywhere between 0 and any number of tags, by making your "parts" bit of the query something like:

```<code>$parts = " tag in ('"
        .implode($uniqueWords,"', '")
        ."')";
// e.g. if uniqueWords = ['one','two','three'], $parts= "tag in ('one','two','three','')"
</code>```

That implode probably needs tweaking to get all the quotes and brackets in the right places.

None of that answers your actual problem though. It's not clear to me if you're trying to find the first 5 keywords for your article, or any 5 tags, or the best 5 tags. I would suggest something like this.

Explode your article and when looking for unique words, count word occurrences, excluding common English words like "the". Then sort the unique words in occurrence order, most repeated words first. You have a list of the main words in your article, take the first five, they are the tags. Insert into table.

Alternatively, here is a solution that may sound messy but may be more efficient in the end. Write a database procedure to carry out this process entirely in MySQL. You need two tables:

```<code>tagstable - 1 column "tag" is the PK
| paint     |
| picture   |    articlewordstable - 1 column "word" is the PK - empty
| sculpture |    | -   |
| photo     |    | -   |
| bronze    |
</code>```

Insert the tokenised words into articlewordstable. Then query that table joining with tagstable:

```<code>SELECT word FROM articlewordstable
INNER JOIN tagstable
ON tag = word;
</code>```

you'll get a list of words that are also tags. You can set a limit of 5 results, you could also do

```<code>SELECT word, count(word) occurrences FROM articlewordstable
INNER JOIN tagstable
ON tag = word
GROUP BY word
ORDER BY occurrences DESC;
</code>```

Which would give you the most used words that also appear in your tags list. That too, can be limited to 5, then use as you see fit.

Hope this helps!

Body:
I want to let my database article reclassified. I explode the text of a given article, and then see if there is one word of the article match 1 tag which it has appear in the category table, then update this article in this category name. My code is here. I want make a limit that every category max has 5 articles. but the update limit not work. Thanks.

<?php
header('Content-type:text/html; charset=utf-8');
$db = mysql_connect("localhost","root","root") or die("can not connect Mysql Server");
mysql_select_db("12",$db);
$result = mysql_query("SELECT title,content,id,cat,date FROM articles Order By date DESC"); //get all the articles
$count = 0;
$ids = array();
$categories = array('1','2','3','4','5','6','7','8','9','10');//category numbers, for 1 = art, 2 = travel... these are stored in another refrenced DB table
$curCategory = array_shift($categories);
echo $curCategory;
while ($row = mysql_fetch_array($result))
{
$tt = $row['title'].' '.$row['content'];
$tt = preg_replace('/[^a-zA-Z0-9 ]/','',$tt);
$words = preg_split("/\s+/",$tt);
$uniqueWords = array_keys(array_flip($words)); // broken article sentence into words
$parts = '';
foreach($uniqueWords as $word){
$parts[] = " tag1 = '$word' OR tag2 = '$word' OR tag3 = '$word' OR tag4 = '$word' OR tag5 = '$word' ";
}
$where = implode(" OR ", $parts);
mysql_select_db("12",$db);
mysql_query("SET NAMES utf8");
    $query1 = mysql_query("SELECT count(*) as count FROM tag1 WHERE ($where) AND category ='count($categories)' ");  //put the break words into reference table match out the category number
    $count = 0;
    while ($row = mysql_fetch_array($query1)) {
        $count = $row['count'];
    }
    if($count) {
        $ids[] = $row['id'];
        $count++;
        if($count == 5) {
             mysql_query("UPDATE articles SET cat = '$curCategory' WHERE id in ('".implode("', '", $ids)."')"); //update every category max articles
            if(!$curCategory = array_shift($categories)) {
                break;
            }
            $count = 0;
            $ids = array();
        }
    }
}
?>

reference table

category | tag1    | tag2   | tag3       | tag4    |  tag5
1        | paint   | picture| sculpture  | photo   |  bronze
2        | tourism | travel | tour       | journey |  trip
3        | style   | vogue  | fashion    | mode    |  Popular
... // 10 categories, category 1 = art , category 2 = travel ...

Body:
Scary.

The code is messy, as other answers explain well, but your choice of structure for the tag data is also going to cause you trouble.

Rather than 5 columns for 5 tags, create a separate tag table and link it to your articles:

article | tag       |
  1     | paint     |
  1     | picture   |
  1     | sculpture |
  1     | photo     |
  1     | bronze    |
  2     | tourism   |
  2     | travel    |
  2     | tour      |

Then when you tag, you don't need to worry about whether the tag is tag1 or tag2, or whether tag3 is NULL, or whether you're changing your mind and want 6 tags after all. The structure will work for anywhere between 0 and any number of tags, by making your "parts" bit of the query something like:

$parts = " tag in ('"
        .implode($uniqueWords,"', '")
        ."')";
// e.g. if uniqueWords = ['one','two','three'], $parts= "tag in ('one','two','three','')"

That implode probably needs tweaking to get all the quotes and brackets in the right places.

None of that answers your actual problem though. It's not clear to me if you're trying to find the first 5 keywords for your article, or any 5 tags, or the best 5 tags. I would suggest something like this.

Explode your article and when looking for unique words, count word occurrences, excluding common English words like "the". Then sort the unique words in occurrence order, most repeated words first. You have a list of the main words in your article, take the first five, they are the tags. Insert into table.

Alternatively, here is a solution that may sound messy but may be more efficient in the end. Write a database procedure to carry out this process entirely in MySQL. You need two tables:

tagstable - 1 column "tag" is the PK
| paint     |
| picture   |    articlewordstable - 1 column "word" is the PK - empty
| sculpture |    | -   |
| photo     |    | -   |
| bronze    |

Insert the tokenised words into articlewordstable. Then query that table joining with tagstable:

SELECT word FROM articlewordstable
INNER JOIN tagstable
ON tag = word;

you'll get a list of words that are also tags. You can set a limit of 5 results, you could also do

SELECT word, count(word) occurrences FROM articlewordstable
INNER JOIN tagstable
ON tag = word
GROUP BY word
ORDER BY occurrences DESC;

Which would give you the most used words that also appear in your tags list. That too, can be limited to 5, then use as you see fit.

Hope this helps!


问:
Can't save data into my Access 2007 database
I cannot save data in Access 2007. When I tried to click the Save button, I get the message

Syntax Error in Insert Into Statement.

What is the error in my code?

```<code>Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click
    If Len(Trim(TxtUserid.Text)) = 0 Then
        MessageBox.Show("Please enter Student No.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        TxtUserid.Focus()
        Exit Sub
    End If

    If Len(Trim(TxtUsername.Text)) = 0 Then
        MessageBox.Show("Please enter Username", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        TxtUsername.Focus()
        Exit Sub
    End If
    If Len(Trim(txtreenterpassword.Text)) = 0 Then
        MessageBox.Show("Please enter Password", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        txtreenterpassword.Focus()
        Exit Sub
    End If

    Try
        con = New OleDbConnection(cs)
        con.Open()
        Dim ct As String = "select Userid from Users where Userid=@find"

        cmd = New OleDbCommand(ct)
        cmd.Connection = con
        cmd.Parameters.Add(New OleDbParameter("@find", System.Data.OleDb.OleDbType.VarChar, 20, "Userid"))
        cmd.Parameters("@find").Value = TxtUserid.Text
        rdr = cmd.ExecuteReader()

        If rdr.Read Then
            MessageBox.Show("Student No. Already Exists", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

            If Not rdr Is Nothing Then
                rdr.Close()
            End If
        Else
            con = New OleDbConnection(cs)
            con.Open()

            Dim ab As String = "insert into Users(Userid,USERNAME,USERTYPE,PASSWORD,FIRSTNAME,MI,LASTNAME,CONTACT,BIRTHDAY,Age) VALUES (@a1,@a2,@a3,@a4,@a5,@a6,@a7,@a8,@a9,@a10)"

            cmd = New OleDbCommand(ab)
            cmd.Connection = con
            cmd.Parameters.Add(New OleDbParameter("@a1", System.Data.OleDb.OleDbType.VarChar, 20, "Userid"))
            cmd.Parameters.Add(New OleDbParameter("@a2", System.Data.OleDb.OleDbType.VarChar, 100, "USERNAME"))
            cmd.Parameters.Add(New OleDbParameter("@a3", System.Data.OleDb.OleDbType.VarChar, 250, "USERTYPE"))
            cmd.Parameters.Add(New OleDbParameter("@a4", System.Data.OleDb.OleDbType.VarChar, 50, "PASSWORD"))
            cmd.Parameters.Add(New OleDbParameter("@a5", System.Data.OleDb.OleDbType.VarChar, 200, "FIRSTNAME"))
            cmd.Parameters.Add(New OleDbParameter("@a6", System.Data.OleDb.OleDbType.VarChar, 150, "MI"))
            cmd.Parameters.Add(New OleDbParameter("@a7", System.Data.OleDb.OleDbType.VarChar, 15, "LASTNAME"))
            cmd.Parameters.Add(New OleDbParameter("@a8", System.Data.OleDb.OleDbType.VarChar, 250, "CONTACT"))
            cmd.Parameters.Add(New OleDbParameter("@a9", System.Data.OleDb.OleDbType.VarChar, 15, "BIRTHDAY"))
            cmd.Parameters.Add(New OleDbParameter("@a10", System.Data.OleDb.OleDbType.VarChar, 250, "Age"))

            cmd.Parameters("@a1").Value = TxtUserid.Text
            cmd.Parameters("@a2").Value = TxtUsername.Text
            cmd.Parameters("@a3").Value = Cmbusertype.Text
            cmd.Parameters("@a4").Value = txtreenterpassword.Text
            cmd.Parameters("@a5").Value = TxtFirstname.Text
            cmd.Parameters("@a6").Value = txtMi.Text
            cmd.Parameters("@a7").Value = TxtLastname.Text
            cmd.Parameters("@a8").Value = TxtContact.Text
            cmd.Parameters("@a9").Value = DateTimePicker3.Text
            cmd.Parameters("@a10").Value = TxtAge.Text

            cmd.ExecuteReader()

            MessageBox.Show("Successfully Saved", "Issued Details", MessageBoxButtons.OK, MessageBoxIcon.Information)

            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Close()
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        con.Dispose()
    End Try
End Sub
</code>```

答:
Have moved things around a bit. Comments in code.

```<code>Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click
    'don't do everything is one huge procedure
    'this procedure is about saving data
    'Off load Validation code to a separate function
    If Not ValidInput() Then
        Exit Sub
    End If
    If Not UniqueUserID() Then
        Exit Sub
    End If

    Using con As New OleDbConnection(cs)
        'Notic the brackest surrounding PASSWORD
        Dim ab As String = "insert into Users(Userid,USERNAME,USERTYPE,[PASSWORD],FIRSTNAME,MI,LASTNAME,CONTACT,BIRTHDAY,Age) VALUES (@a1,@a2,@a3,@a4,@a5,@a6,@a7,@a8,@a9,@a10)"
        Using cmd As New OleDbCommand(ab, con)
            cmd.Connection = con
            'Excellent way to add parameters with the type and size
            cmd.Parameters.Add("@a1", System.Data.OleDb.OleDbType.VarChar, 20, "Userid").Value = TxtUserid.Text
            cmd.Parameters.Add("@a2", System.Data.OleDb.OleDbType.VarChar, 100, "USERNAME").Value = TxtUsername.Text
            cmd.Parameters.Add("@a3", System.Data.OleDb.OleDbType.VarChar, 250, "USERTYPE").Value = Cmbusertype.Text
            cmd.Parameters.Add("@a4", System.Data.OleDb.OleDbType.VarChar, 50, "[PASSWORD]").Value = txtreenterpassword.Text
            cmd.Parameters.Add("@a5", System.Data.OleDb.OleDbType.VarChar, 200, "FIRSTNAME").Value = TxtFirstname.Text
            cmd.Parameters.Add("@a6", System.Data.OleDb.OleDbType.VarChar, 150, "MI").Value = txtMi.Text
            cmd.Parameters.Add("@a7", System.Data.OleDb.OleDbType.VarChar, 15, "LASTNAME").Value = TxtLastname.Text
            cmd.Parameters.Add("@a8", System.Data.OleDb.OleDbType.VarChar, 250, "CONTACT").Value = TxtContact.Text
            cmd.Parameters.Add("@a9", System.Data.OleDb.OleDbType.VarChar, 15, "BIRTHDAY").Value = DateTimePicker3.Text
            cmd.Parameters.Add("@a10", System.Data.OleDb.OleDbType.VarChar, 250, "Age").Value = TxtAge.Text
            'Don't open the connection until right before it is used
            con.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
    MessageBox.Show("Successfully Saved", "Issued Details", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

Private Function ValidInput() As Boolean
    If Len(Trim(TxtUserid.Text)) = 0 Then
        MessageBox.Show("Please enter Student No.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        TxtUserid.Focus()
        Return False
    End If
    If Len(Trim(TxtUsername.Text)) = 0 Then
        MessageBox.Show("Please enter Username", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        TxtUsername.Focus()
        Return False
    End If
    If Len(Trim(txtreenterpassword.Text)) = 0 Then
        MessageBox.Show("Please enter Password", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        txtreenterpassword.Focus()
        Return False
    End If
    Return True
End Function

Private Function UniqueUserID() As Boolean
    Dim ReturnValue As Object 'We are using Object because it might have to hold a value of Nothing
    'Keep your database objects local so you can be sure they are closed and disposed
    'Using...End Using blocks to the for you
    Using con As New OleDbConnection(cs)
        'You can pass the command text and the connection directly to the constructor of the command
        Using cmd As New OleDbCommand("select 1 from Users where Userid=@find", con)
            'The add method will create the Parameter for you. No need for New Parameter
            'You can also add the .Value property directly in this line
            cmd.Parameters.Add("@find", System.Data.OleDb.OleDbType.VarChar, 20, "Userid").Value = TxtUserid.Text
            con.Open()
            ReturnValue = cmd.ExecuteScalar() 'Retrieves the first column of the first row in the resultset
        End Using
    End Using
    If ReturnValue Is Nothing Then
        'insert the record
        Return True
    ElseIf CInt(ReturnValue) = 1 Then
        MessageBox.Show("Student No. Already Exists", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Return False
    Else
        Return False
    End If
End Function
</code>```

As a side note it is not a good idea to store age in a database. It can change the very next day! Just store the birthday and calculated age as needed.

Another note; you might want to check what text the DateTimePicker is returning. I believe it varies depending on the settings. Short seems to work nicely.

Body:
I cannot save data in Access 2007. When I tried to click the Save button, I get the message

Syntax Error in Insert Into Statement.

What is the error in my code?

Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click
    If Len(Trim(TxtUserid.Text)) = 0 Then
        MessageBox.Show("Please enter Student No.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        TxtUserid.Focus()
        Exit Sub
    End If

    If Len(Trim(TxtUsername.Text)) = 0 Then
        MessageBox.Show("Please enter Username", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        TxtUsername.Focus()
        Exit Sub
    End If
    If Len(Trim(txtreenterpassword.Text)) = 0 Then
        MessageBox.Show("Please enter Password", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        txtreenterpassword.Focus()
        Exit Sub
    End If

    Try
        con = New OleDbConnection(cs)
        con.Open()
        Dim ct As String = "select Userid from Users where Userid=@find"

        cmd = New OleDbCommand(ct)
        cmd.Connection = con
        cmd.Parameters.Add(New OleDbParameter("@find", System.Data.OleDb.OleDbType.VarChar, 20, "Userid"))
        cmd.Parameters("@find").Value = TxtUserid.Text
        rdr = cmd.ExecuteReader()

        If rdr.Read Then
            MessageBox.Show("Student No. Already Exists", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

            If Not rdr Is Nothing Then
                rdr.Close()
            End If
        Else
            con = New OleDbConnection(cs)
            con.Open()

            Dim ab As String = "insert into Users(Userid,USERNAME,USERTYPE,PASSWORD,FIRSTNAME,MI,LASTNAME,CONTACT,BIRTHDAY,Age) VALUES (@a1,@a2,@a3,@a4,@a5,@a6,@a7,@a8,@a9,@a10)"

            cmd = New OleDbCommand(ab)
            cmd.Connection = con
            cmd.Parameters.Add(New OleDbParameter("@a1", System.Data.OleDb.OleDbType.VarChar, 20, "Userid"))
            cmd.Parameters.Add(New OleDbParameter("@a2", System.Data.OleDb.OleDbType.VarChar, 100, "USERNAME"))
            cmd.Parameters.Add(New OleDbParameter("@a3", System.Data.OleDb.OleDbType.VarChar, 250, "USERTYPE"))
            cmd.Parameters.Add(New OleDbParameter("@a4", System.Data.OleDb.OleDbType.VarChar, 50, "PASSWORD"))
            cmd.Parameters.Add(New OleDbParameter("@a5", System.Data.OleDb.OleDbType.VarChar, 200, "FIRSTNAME"))
            cmd.Parameters.Add(New OleDbParameter("@a6", System.Data.OleDb.OleDbType.VarChar, 150, "MI"))
            cmd.Parameters.Add(New OleDbParameter("@a7", System.Data.OleDb.OleDbType.VarChar, 15, "LASTNAME"))
            cmd.Parameters.Add(New OleDbParameter("@a8", System.Data.OleDb.OleDbType.VarChar, 250, "CONTACT"))
            cmd.Parameters.Add(New OleDbParameter("@a9", System.Data.OleDb.OleDbType.VarChar, 15, "BIRTHDAY"))
            cmd.Parameters.Add(New OleDbParameter("@a10", System.Data.OleDb.OleDbType.VarChar, 250, "Age"))

            cmd.Parameters("@a1").Value = TxtUserid.Text
            cmd.Parameters("@a2").Value = TxtUsername.Text
            cmd.Parameters("@a3").Value = Cmbusertype.Text
            cmd.Parameters("@a4").Value = txtreenterpassword.Text
            cmd.Parameters("@a5").Value = TxtFirstname.Text
            cmd.Parameters("@a6").Value = txtMi.Text
            cmd.Parameters("@a7").Value = TxtLastname.Text
            cmd.Parameters("@a8").Value = TxtContact.Text
            cmd.Parameters("@a9").Value = DateTimePicker3.Text
            cmd.Parameters("@a10").Value = TxtAge.Text

            cmd.ExecuteReader()

            MessageBox.Show("Successfully Saved", "Issued Details", MessageBoxButtons.OK, MessageBoxIcon.Information)

            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Close()
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        con.Dispose()
    End Try
End Sub

Body:
Have moved things around a bit. Comments in code.

Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click
    'don't do everything is one huge procedure
    'this procedure is about saving data
    'Off load Validation code to a separate function
    If Not ValidInput() Then
        Exit Sub
    End If
    If Not UniqueUserID() Then
        Exit Sub
    End If

    Using con As New OleDbConnection(cs)
        'Notic the brackest surrounding PASSWORD
        Dim ab As String = "insert into Users(Userid,USERNAME,USERTYPE,[PASSWORD],FIRSTNAME,MI,LASTNAME,CONTACT,BIRTHDAY,Age) VALUES (@a1,@a2,@a3,@a4,@a5,@a6,@a7,@a8,@a9,@a10)"
        Using cmd As New OleDbCommand(ab, con)
            cmd.Connection = con
            'Excellent way to add parameters with the type and size
            cmd.Parameters.Add("@a1", System.Data.OleDb.OleDbType.VarChar, 20, "Userid").Value = TxtUserid.Text
            cmd.Parameters.Add("@a2", System.Data.OleDb.OleDbType.VarChar, 100, "USERNAME").Value = TxtUsername.Text
            cmd.Parameters.Add("@a3", System.Data.OleDb.OleDbType.VarChar, 250, "USERTYPE").Value = Cmbusertype.Text
            cmd.Parameters.Add("@a4", System.Data.OleDb.OleDbType.VarChar, 50, "[PASSWORD]").Value = txtreenterpassword.Text
            cmd.Parameters.Add("@a5", System.Data.OleDb.OleDbType.VarChar, 200, "FIRSTNAME").Value = TxtFirstname.Text
            cmd.Parameters.Add("@a6", System.Data.OleDb.OleDbType.VarChar, 150, "MI").Value = txtMi.Text
            cmd.Parameters.Add("@a7", System.Data.OleDb.OleDbType.VarChar, 15, "LASTNAME").Value = TxtLastname.Text
            cmd.Parameters.Add("@a8", System.Data.OleDb.OleDbType.VarChar, 250, "CONTACT").Value = TxtContact.Text
            cmd.Parameters.Add("@a9", System.Data.OleDb.OleDbType.VarChar, 15, "BIRTHDAY").Value = DateTimePicker3.Text
            cmd.Parameters.Add("@a10", System.Data.OleDb.OleDbType.VarChar, 250, "Age").Value = TxtAge.Text
            'Don't open the connection until right before it is used
            con.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
    MessageBox.Show("Successfully Saved", "Issued Details", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

Private Function ValidInput() As Boolean
    If Len(Trim(TxtUserid.Text)) = 0 Then
        MessageBox.Show("Please enter Student No.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        TxtUserid.Focus()
        Return False
    End If
    If Len(Trim(TxtUsername.Text)) = 0 Then
        MessageBox.Show("Please enter Username", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        TxtUsername.Focus()
        Return False
    End If
    If Len(Trim(txtreenterpassword.Text)) = 0 Then
        MessageBox.Show("Please enter Password", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        txtreenterpassword.Focus()
        Return False
    End If
    Return True
End Function

Private Function UniqueUserID() As Boolean
    Dim ReturnValue As Object 'We are using Object because it might have to hold a value of Nothing
    'Keep your database objects local so you can be sure they are closed and disposed
    'Using...End Using blocks to the for you
    Using con As New OleDbConnection(cs)
        'You can pass the command text and the connection directly to the constructor of the command
        Using cmd As New OleDbCommand("select 1 from Users where Userid=@find", con)
            'The add method will create the Parameter for you. No need for New Parameter
            'You can also add the .Value property directly in this line
            cmd.Parameters.Add("@find", System.Data.OleDb.OleDbType.VarChar, 20, "Userid").Value = TxtUserid.Text
            con.Open()
            ReturnValue = cmd.ExecuteScalar() 'Retrieves the first column of the first row in the resultset
        End Using
    End Using
    If ReturnValue Is Nothing Then
        'insert the record
        Return True
    ElseIf CInt(ReturnValue) = 1 Then
        MessageBox.Show("Student No. Already Exists", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Return False
    Else
        Return False
    End If
End Function

As a side note it is not a good idea to store age in a database. It can change the very next day! Just store the birthday and calculated age as needed.

Another note; you might want to check what text the DateTimePicker is returning. I believe it varies depending on the settings. Short seems to work nicely.


问:
How to Insert a Row to a Sorted Table While Maintaining Order
The problem is that it will not allow me to insert a row into my table using jQuery. I tried using .eq() with index to find the correct position to insert and .after() to insert the row. However, it will not add the row.

This is the HTML:

```<code><table class="ResultsTable" hidden="hidden">
    <thead class="header">
        <tr>
            <td class="rankColumn"></td>
            <td class="nameColumn"></td>
            <td class="ageColumn"></td>
        </tr>
    </thead>
    <tbody id="resultsTableBody"></tbody>
</table>
</code>```

This is my jQuery:

```<code>function insert(data){
    $('#resultsTableBody > tr')
    .eq(data['Status'] - 1).after('<tr>' +
    '<td class=\'rankColumn ' + data['Rank'] + ' \' ></td>' +
    '<td class=\'nameColumn\'>' + data['Name'] + '</td>' +
    '<td class=\'ageColumn\'>' + data['Age'] + '</td>' +
    '</tr>');
}
</code>```

Why is it that it wont insert anything into the table body? Rank is like an index which represents how high up the list a row should be. With rank being from 1 to 3. So this code should insert a row into the correct position in the table. The table is empty to start with.

Expected result is:

```<code>1 | John      | 24
1 | Bob       | 19
1 | Misha     | 27
2 | Laura     | 22
3 | Hannah    | 31
3 | Paul      | 43
</code>```

They should be placed in order like above based on their rank. However, the table just shows the header and the body is blank. Where am I going wrong?

The data will all not be available when inserting they will be retrieved one at a time and it will find its place in the table based on the others.

答:
So I've come up with another solution, you could look for the index in the DOM tree of the last rank's parent (
) using the :contains selector function (and also .index() function) and then just use the .eq() as you tried (you had the good idea) in conjunction with the .after() or .before function to add the new item at the good place.

Please note that I've changed the classes of the titles in the
 to avoid confusing them with the actual data inserted.

```<code>function insert(data) {
    var dataToAppend = '<tr><td class="rankColumn">'+data[0].rank+'</td><td class="nameColumn">'+data[0].name+'</td><td class="ageColumn">'+data[0].age+'</td></tr>';
if ($('#resultsTableBody > tr').length == 0) {
    $('#resultsTableBody').append(dataToAppend);
} else {
    var arrayRanks = [];
    $('.rankColumn').each(function(i, val) {
        arrayRanks[$(val).parent().index()] = $(val).html();
    });
    arrayRanks.push(data[0].rank)
    arrayRanks.sort(function (a, b) {
        return a - b;
    });
    var index = arrayRanks.indexOf(data[0].rank);
    if (index == 0) {
        $('#resultsTableBody > tr').eq(index).before(dataToAppend);
    } else {
        $('#resultsTableBody > tr').eq(index-1).after(dataToAppend);
    }
}
</code>```

}

```<code>insert([{ rank: 1, name: 'John', age: 24 }]);
insert([{ rank: 2, name: 'Laura', age: 22 }]);
insert([{ rank: 3, name: 'Hannah', age: 31 }]);
insert([{ rank: 1, name: 'Misha', age: 27 }]);
insert([{ rank: 3, name: 'Paul', age: 43 }]);
insert([{ rank: 1, name: 'Bob', age: 19 }]);
</code>```

Working example below :

function insert(data) {
 var dataToAppend = '
'+data[0].rank+'	'+data[0].name+'	'+data[0].age+'
';
if ($('#resultsTableBody > tr').length == 0) {
    $('#resultsTableBody').append(dataToAppend);
} else {
 var arrayRanks = [];
 $('.rankColumn').each(function(i, val) {
  arrayRanks[$(val).parent().index()] = $(val).html();
 });
 arrayRanks.push(data[0].rank)
 arrayRanks.sort(function (a, b) {
  return a - b;
 });
 var index = arrayRanks.indexOf(data[0].rank);
 if (index == 0) {
  $('#resultsTableBody > tr').eq(index).before(dataToAppend);
 } else {
  $('#resultsTableBody > tr').eq(index-1).after(dataToAppend);
 }
}
}

    insert([{ rank: 1, name: 'John', age: 24 }]);
    insert([{ rank: 2, name: 'Laura', age: 22 }]);
    insert([{ rank: 3, name: 'Hannah', age: 31 }]);
    insert([{ rank: 1, name: 'Misha', age: 27 }]);
    insert([{ rank: 3, name: 'Paul', age: 43 }]);
    insert([{ rank: 1, name: 'Bob', age: 19 }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="ResultsTable">
    <thead class="header">
        <tr>
            <td class="rankText">Rank</td>
            <td class="nameText">Name</td>
            <td class="ageText">Age</td>
        </tr>
    </thead>
    <tbody id="resultsTableBody"></tbody>
</table></code>```

Body:
The problem is that it will not allow me to insert a row into my table using jQuery. I tried using .eq() with index to find the correct position to insert and .after() to insert the row. However, it will not add the row.

This is the HTML:

This is my jQuery:

function insert(data){
    $('#resultsTableBody > tr')
    .eq(data['Status'] - 1).after('
' +
    '	' +
    '' + data['Name'] + '	' +
    '' + data['Age'] + '	' +
    '
');
}

Why is it that it wont insert anything into the table body? Rank is like an index which represents how high up the list a row should be. With rank being from 1 to 3. So this code should insert a row into the correct position in the table. The table is empty to start with.

Expected result is:

1 | John      | 24
1 | Bob       | 19
1 | Misha     | 27
2 | Laura     | 22
3 | Hannah    | 31
3 | Paul      | 43

They should be placed in order like above based on their rank. However, the table just shows the header and the body is blank. Where am I going wrong?

The data will all not be available when inserting they will be retrieved one at a time and it will find its place in the table based on the others.

Body:
So I've come up with another solution, you could look for the index in the DOM tree of the last rank's parent (<tr>) using the :contains selector function (and also .index() function) and then just use the .eq() as you tried (you had the good idea) in conjunction with the .after() or .before function to add the new item at the good place.

Please note that I've changed the classes of the titles in the <thead> to avoid confusing them with the actual data inserted.

function insert(data) {
    var dataToAppend = '<tr><td class="rankColumn">'+data[0].rank+'</td><td class="nameColumn">'+data[0].name+'</td><td class="ageColumn">'+data[0].age+'</td></tr>';
if ($('#resultsTableBody > tr').length == 0) {
    $('#resultsTableBody').append(dataToAppend);
} else {
    var arrayRanks = [];
    $('.rankColumn').each(function(i, val) {
        arrayRanks[$(val).parent().index()] = $(val).html();
    });
    arrayRanks.push(data[0].rank)
    arrayRanks.sort(function (a, b) {
        return a - b;
    });
    var index = arrayRanks.indexOf(data[0].rank);
    if (index == 0) {
        $('#resultsTableBody > tr').eq(index).before(dataToAppend);
    } else {
        $('#resultsTableBody > tr').eq(index-1).after(dataToAppend);
    }
}

}

insert([{ rank: 1, name: 'John', age: 24 }]);
insert([{ rank: 2, name: 'Laura', age: 22 }]);
insert([{ rank: 3, name: 'Hannah', age: 31 }]);
insert([{ rank: 1, name: 'Misha', age: 27 }]);
insert([{ rank: 3, name: 'Paul', age: 43 }]);
insert([{ rank: 1, name: 'Bob', age: 19 }]);

Working example below :

function insert(data) {
 var dataToAppend = '<tr><td class="rankColumn">'+data[0].rank+'</td><td class="nameColumn">'+data[0].name+'</td><td class="ageColumn">'+data[0].age+'</td></tr>';
if ($('#resultsTableBody > tr').length == 0) {
    $('#resultsTableBody').append(dataToAppend);
} else {
 var arrayRanks = [];
 $('.rankColumn').each(function(i, val) {
  arrayRanks[$(val).parent().index()] = $(val).html();
 });
 arrayRanks.push(data[0].rank)
 arrayRanks.sort(function (a, b) {
  return a - b;
 });
 var index = arrayRanks.indexOf(data[0].rank);
 if (index == 0) {
  $('#resultsTableBody > tr').eq(index).before(dataToAppend);
 } else {
  $('#resultsTableBody > tr').eq(index-1).after(dataToAppend);
 }
}
}

    insert([{ rank: 1, name: 'John', age: 24 }]);
    insert([{ rank: 2, name: 'Laura', age: 22 }]);
    insert([{ rank: 3, name: 'Hannah', age: 31 }]);
    insert([{ rank: 1, name: 'Misha', age: 27 }]);
    insert([{ rank: 3, name: 'Paul', age: 43 }]);
    insert([{ rank: 1, name: 'Bob', age: 19 }]);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="ResultsTable">
    <thead class="header">
        <tr>
            <td class="rankText">Rank</td>
            <td class="nameText">Name</td>
            <td class="ageText">Age</td>
        </tr>
    </thead>
    <tbody id="resultsTableBody"></tbody>
</table>


问:
"unexpected console statement no-console"
I'm getting this error in Brackets.

I want to stress the fact that it's literally the second time I opened a JS file.
As I stressed It I want also to emphasize the fact that I have no clue what Eslint and node.js are.

All the fixes on the StackOverflow and other sites assume knowing how abovementioned entities work.

Please help to a complete newb to fix the problem and learn something new.

Thank you in advance!

Here's the piece of code, but I don't think it will help with anything.

Html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>

</head>
<body>
<h1>Javascript starter</h1>

    <script src=Script.js> </script>
</body>
</html>
</code>```

Javascript:

```<code>var now = 2018;
var yearJohn = 1989;
var fullAge = 18;

//Multiple operators
var isFullAge = now - yearJohn >= fullAge; //true
сonsole.log(isFullAge);

//Grouping

    var ageJohn = now - yearJohn;
    var ageMark = 35;
    var average = (ageJohn + ageMark)/2;
    console.log(average);

    // Multiple assigments
    var x, y;
    x = y = (3 + 5) * 4 - 6; // 8 * 4 - 6 // 32 - 6 // 26

    console.log(x, y);

    // More operators
    x *= 2;
    console.log(x);
    x += 10;
    // eslint-disable-next-line no-console
    console.log(x);
</code>```

答:
If it really is ESLint that is causing errors for this change, you can fix it by disabling the rule for that particular line:</p>

```<code>// eslint-disable-next-line no-console
console.log(isFullAge);
</code>```

Body:
I'm getting this error in Brackets.

I want to stress the fact that it's literally the second time I opened a JS file.
As I stressed It I want also to emphasize the fact that I have no clue what Eslint and node.js are.

All the fixes on the StackOverflow and other sites assume knowing how abovementioned entities work.

Please help to a complete newb to fix the problem and learn something new.

Thank you in advance!

Here's the piece of code, but I don't think it will help with anything.

Html:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>JavaScript</title>

Javascript starter

Javascript:

var now = 2018;
var yearJohn = 1989;
var fullAge = 18;

//Multiple operators
var isFullAge = now - yearJohn >= fullAge; //true
сonsole.log(isFullAge);

//Grouping

    var ageJohn = now - yearJohn;
    var ageMark = 35;
    var average = (ageJohn + ageMark)/2;
    console.log(average);

    // Multiple assigments
    var x, y;
    x = y = (3 + 5) * 4 - 6; // 8 * 4 - 6 // 32 - 6 // 26

    console.log(x, y);

    // More operators
    x *= 2;
    console.log(x);
    x += 10;
    // eslint-disable-next-line no-console
    console.log(x);

Body:
If it really is ESLint that is causing errors for this change, you can fix it by disabling the rule for that particular line:

// eslint-disable-next-line no-console
console.log(isFullAge);


问:
Could not install package 'BitMiracle.LibTiff.NET 2.4.633'...project that targets '.NETFramework,Version=v3.5'
Trying to upgrade BitMiracle.LibTiff.NET via NuGet from v2.4.633 to v2.4.626

Error: Could not install package 'BitMiracle.LibTiff.NET 2.4.633'. You are trying to install this package into a project that targets '.NETFramework,Version=v3.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

626 has dependencies set to NETStandard.Library (>= 1.6.1)
633 is set to NETStandard.Library (>= 2.0.0)

Is .Net Framework 3.5 supported?

答:
.NET Standard requires Framework 4.5 as a minimum. .NET Standard 2.0, which libtiff.net uses, requires 4.6.1 or better.

https://learn.microsoft.com/en-us/dotnet/standard/net-standard

Looking at their github, it seems they are trying to multi target Framework 2.0, Framework 4.0, netstandard1.3, and netstandard2.0. That should let you use it via the Framework 2.0 components, but in my experience those multi target packages often don’t work quite right. You could try opening a bug report with them and see if there’s something that could be tweaked in the package to make older frameworks behave.


问:
How does the react `Router` component communicate with the `Route` component?
I know that the Router component, say BrowserRouter creates a history object for keeping track of paths and so on, and that a Route component renders its view only when its path matches the current location, which I assume is read from the history. My question is how does the Route component get access to the history object that is created by the BrowserRouter. Is there some under the hood communication going on that is making this possible?

答:
This is a context api 'magic'.

<BrowserRouter/> renders <Router/>:

```<code>class BrowserRouter extends React.Component {
  history = createHistory(this.props);

  render() {
    return <Router history={this.history} children={this.props.children} />;
  }
}
</code>```

<Router/> renders <RouterContext.Provider/>:

```<code>  <RouterContext.Provider
    children={this.props.children || null}
    value={{
      history: this.props.history,
</code>```

<Route/> uses <RouterContext.Consumer> to provide access to data from provider.

Using context api allows to provide data/methods many levels down the tree without the need of passing down props expliticely (on each level). You can read more about this on docs or search for tutorials.

Body:
This is a context api 'magic'.

<BrowserRouter/> renders <Router/>:

class BrowserRouter extends React.Component {
  history = createHistory(this.props);

  render() {
    return <Router history={this.history} children={this.props.children} />;
  }
}

<Router/> renders <RouterContext.Provider/>:

  <RouterContext.Provider
    children={this.props.children || null}
    value={{
      history: this.props.history,

<Route/> uses <RouterContext.Consumer> to provide access to data from provider.

Using context api allows to provide data/methods many levels down the tree without the need of passing down props expliticely (on each level). You can read more about this on docs or search for tutorials.