问:
Trying to import SQL File with command
I want to import a sql file to a database. I work on Windows 10 and I want to use the commands lines.

I tried this :

```<code>C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql -u {username} -p{password} db_test < F:\BDD\_databasetest\test.sql
</code>```

But I have an error : "C:\Program not recognized"

So I tried to go by step :

```<code>cd C:\Program Files\MySQL\MySQL Server 8.0\bin
mysql -u {username} -p{password}
mysql db_test < F:\BDD\_databasetest\test.sql
</code>```

But at the third command, I have this error :

ERROR:
Unknown command '\B'.
ERROR:
Unknown command '_'.
Outfile disabled.

For the command "mysql db_test < F:\BDD_databasetest\test.sql" I'm not sure about the "mysql" part so I tried both, with the same error. I tried to double the \ in the path, and I tried to used '' and "" for the path, without succes.

PS : english is not my native language. I clarifications are needed, don't hesitate.

答:
with the first mysql commad you can't to the database so the mnexe must be a sql command

For both options the database has to exit already, if in the sql is no CREATE DATABASE ...

use

```<code>mysql -u root -p db_test < D:\BDD\_databasetest\test.sql
</code>```

or

```<code>mysql -u {username} -p{password}

mysql> use db_test ;

mysql> source D:/BDD/_databasetest/test.sql;
</code>```

Note in the last command the / instad of \

Title: Trying to import SQL File with command

Body:
I want to import a sql file to a database. I work on Windows 10 and I want to use the commands lines.

I tried this :

C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql -u {username} -p{password} db_test < F:\BDD\_databasetest\test.sql

But I have an error : "C:\Program not recognized"

So I tried to go by step :

cd C:\Program Files\MySQL\MySQL Server 8.0\bin
mysql -u {username} -p{password}
mysql db_test < F:\BDD\_databasetest\test.sql

But at the third command, I have this error :

ERROR:
Unknown command '\B'.
ERROR:
Unknown command '_'.
Outfile disabled.

For the command "mysql db_test < F:\BDD_databasetest\test.sql" I'm not sure about the "mysql" part so I tried both, with the same error. I tried to double the \ in the path, and I tried to used '' and "" for the path, without succes.

PS : english is not my native language. I clarifications are needed, don't hesitate.

Body:
with the first mysql commad you can't to the database so the mnexe must be a sql command

For both options the database has to exit already, if in the sql is no CREATE DATABASE ...

use

mysql -u root -p db_test < D:\BDD\_databasetest\test.sql

or

mysql -u {username} -p{password}

mysql> use db_test ;

mysql> source D:/BDD/_databasetest/test.sql;

Note in the last command the / instad of \


来源: stackexchange

问:
For command, print numbers up to 5 that are divisible by a number which the user enters
I ran into a task that says to make a program that told me to print numbers up to 5 that are divisible by the number which user enters  with the "for" command.

#include<iostream>

using namespace std;

int main{

    int a;

    cout<<"Type in a:  "<<endl;
    cin>>a;
    for(int i;i<6;i++){

    if((a%1)==0)
        cout<<i<<endl;

    else if((a%2)==0)
        cout<<i<<endl;

    else if((a%3)==0)
        cout<<i<<endl;

    else if((a%4)==0)
        cout<<i<<endl;

    else if((a%5))
        cout<<i<<endl;

    cout<<i<<endl;
}

    return 0;

}
```

答:
First, you need to initialize i in

```<code>for(int i;i<6;i++){
</code>```

Like:

```<code>for(int i=0;i<6;i++){
</code>```

Second, you don't really need to test

```<code>if((a%1)==0)
</code>```

It will always be 0

ContentLicense: CC BY-SA 4.0

Body:
First, you need to initialize i in

for(int i;i<6;i++){

Like:

for(int i=0;i<6;i++){

Second, you don't really need to test

if((a%1)==0)

It will always be 0


问:
How to style FormControlLabel font size
How do you set the in-line font size on a Material-UI FormControlLabel?  The below attempt does not work.</p>

```<code>const styles: any = createStyles({
   formControlLabel: { fontSize: '0.6rem',
   '& label': { fontSize: '0.6rem' } }
});

<FormControlLabel style={styles.formControlLabel}
  control={<Checkbox value="Hello" color="primary" />}
           label="World"
/>
</code>```

Title: How to style FormControlLabel font size

Body:
How do you set the in-line font size on a Material-UI FormControlLabel?  The below attempt does not work.

const styles: any = createStyles({
   formControlLabel: { fontSize: '0.6rem',
   '& label': { fontSize: '0.6rem' } }
});

<FormControlLabel style={styles.formControlLabel}
  control={<Checkbox value="Hello" color="primary" />}
           label="World"
/>

Body:
Here's another option to achieve the same thing, but without the extra p that using <Typography /> will give you (referencing MUI v4 as the post is from before v5, although I'm sure this solution will work there too).

By referring to the docs for the FormControlLabel you can see the styles for the label can be modified with the label rule (kinda like you've tried to do already), however another approach would be to style the label by using withStyles

const StyledFormControlLabel = withStyles(() => ({
  label: {
    fontSize: '0.6rem',
  }
}))(FormControlLabel);

...

<StyledFormControlLabel
  control={<Checkbox value="Hello" color="primary" />}
  label="World"
/>


问:
Django mod_wsgi Apache Server, ModuleNotFoundError: No Module Named Django
I read ton of articles, but still can't figure out what I'm missing. I'm running a django website from virtualenv. Here's my config file. The website address is replaced by <domain.com>, can't use that here.

Config

```<code><VirtualHost *:80>

        ServerAdmin sidharth@collaboration-management
        ServerName <domain.com>
        ServerAlias <domain.com>
        DocumentRoot /home/sidharth/Downloads/gmcweb

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        Alias /static /home/sidharth/Downloads/gmcweb/static

        <Directory /home/sidharth/Downloads/gmcweb/static>
                Require all granted
        </Directory>

        <Directory /home/sidharth/Downloads/gmcweb/gmcweb>
                <Files wsgi.py>
                        Require all granted
                </Files>
        </Directory>

        WSGIDaemonProcess gmcweb python-home=/home/sidharth/Downloads/gmcwebenvlin python-path=/home/sidharth/Downloads/gmcweb
        WSGIProcessGroup gmcweb
        WSGIScriptAlias / /home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py
</VirtualHost>
</code>```

Here's my WSGI.py file, didn't change anything never had to earlier

```<code>import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gmcweb.settings')

application = get_wsgi_application()
</code>```

Python Versions

My virtualenv python version is 3.9.5
Default Google VM python version is 3.6.9

Python Installed Libraries

```<code>Package                  Version
------------------------ ---------
asgiref                  3.4.0
attrs                    21.2.0
autopep8                 1.5.7
beautifulsoup4           4.9.3
certifi                  2021.5.30
cffi                     1.14.5
chardet                  4.0.0
cryptography             3.4.7
defusedxml               0.7.1
Django                   3.2.4
django-allauth           0.44.0
django-livereload-server 0.3.2
idna                     2.10
jsonschema               3.2.0
oauthlib                 3.1.1
pip                      21.2.3
pycodestyle              2.7.0
pycparser                2.20
PyJWT                    2.1.0
pyrsistent               0.18.0
python3-openid           3.2.0
pytz                     2021.1
requests                 2.25.1
requests-oauthlib        1.3.0
setuptools               57.4.0
six                      1.16.0
soupsieve                2.2.1
sqlparse                 0.4.1
toml                     0.10.2
tornado                  6.1
urllib3                  1.26.6
</code>```

I installed apache modwsgi as well sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3

Error Log File

```<code>[Thu Sep 23 15:05:06.554545 2021] [mpm_event:notice] [pid 32077:tid 140392561593280] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations
[Thu Sep 23 15:05:06.554594 2021] [core:notice] [pid 32077:tid 140392561593280] AH00094: Command line: '/usr/sbin/apache2'
[Thu Sep 23 15:05:19.081581 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] mod_wsgi (pid=32617): Target WSGI script '/home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py' c$
[Thu Sep 23 15:05:19.081638 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] mod_wsgi (pid=32617): Exception occurred processing WSGI script '/home/sidharth/Downloads/g$
[Thu Sep 23 15:05:19.081828 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] Traceback (most recent call last):
[Thu Sep 23 15:05:19.081849 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604]   File "/home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py", line 12, in <module>
[Thu Sep 23 15:05:19.081853 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604]     from django.core.wsgi import get_wsgi_application
[Thu Sep 23 15:05:19.081867 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] ModuleNotFoundError: No module named 'django'
[Thu Sep 23 15:05:32.244779 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916] mod_wsgi (pid=32617): Target WSGI script '/home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py' c$
[Thu Sep 23 15:05:32.244845 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916] mod_wsgi (pid=32617): Exception occurred processing WSGI script '/home/sidharth/Downloads/g$
[Thu Sep 23 15:05:32.244924 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916] Traceback (most recent call last):
[Thu Sep 23 15:05:32.244946 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916]   File "/home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py", line 12, in <module>
[Thu Sep 23 15:05:32.244951 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916]     from django.core.wsgi import get_wsgi_application
[Thu Sep 23 15:05:32.244966 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916] ModuleNotFoundError: No module named 'django'
</code>```

答:
libapache2-mod-wsgi-py3 can be used only with python 3.6.9 in ubuntu 18!!
if your virtualenv uses another version of python, you should download mod_wsgi from this link: mod_wsgi

at this time the latest version of mod_wsgi is 4.9.0. follow the steps below:

```<code>$ sudo apt install apache2 apache2-dev
$ wget https://codeload.github.com/GrahamDumpleton/mod_wsgi/tar.gz/4.9.0
$ tar -xf 4.9.0
$ cd mod_wsgi-4.9.0/
$ ./configure --with-python=/your virtualenv path/bin/python[version]
   # example:  ./configure --with-python=/virtualenv/bin/python3.9
$ make
$ sudo make install

$ sudo systemctl restart apache2
</code>```

Body:
I read ton of articles, but still can't figure out what I'm missing. I'm running a django website from virtualenv. Here's my config file. The website address is replaced by <domain.com>, can't use that here.

Config

<VirtualHost *:80>

        ServerAdmin sidharth@collaboration-management
        ServerName <domain.com>
        ServerAlias <domain.com>
        DocumentRoot /home/sidharth/Downloads/gmcweb

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        Alias /static /home/sidharth/Downloads/gmcweb/static

        <Directory /home/sidharth/Downloads/gmcweb/static>
                Require all granted
        </Directory>

        <Directory /home/sidharth/Downloads/gmcweb/gmcweb>
                <Files wsgi.py>
                        Require all granted
                </Files>
        </Directory>

        WSGIDaemonProcess gmcweb python-home=/home/sidharth/Downloads/gmcwebenvlin python-path=/home/sidharth/Downloads/gmcweb
        WSGIProcessGroup gmcweb
        WSGIScriptAlias / /home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py
</VirtualHost>

Here's my WSGI.py file, didn't change anything never had to earlier

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gmcweb.settings')

application = get_wsgi_application()

Python Versions

My virtualenv python version is 3.9.5
Default Google VM python version is 3.6.9

Python Installed Libraries

Package                  Version
------------------------ ---------
asgiref                  3.4.0
attrs                    21.2.0
autopep8                 1.5.7
beautifulsoup4           4.9.3
certifi                  2021.5.30
cffi                     1.14.5
chardet                  4.0.0
cryptography             3.4.7
defusedxml               0.7.1
Django                   3.2.4
django-allauth           0.44.0
django-livereload-server 0.3.2
idna                     2.10
jsonschema               3.2.0
oauthlib                 3.1.1
pip                      21.2.3
pycodestyle              2.7.0
pycparser                2.20
PyJWT                    2.1.0
pyrsistent               0.18.0
python3-openid           3.2.0
pytz                     2021.1
requests                 2.25.1
requests-oauthlib        1.3.0
setuptools               57.4.0
six                      1.16.0
soupsieve                2.2.1
sqlparse                 0.4.1
toml                     0.10.2
tornado                  6.1
urllib3                  1.26.6

I installed apache modwsgi as well sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3

Error Log File

[Thu Sep 23 15:05:06.554545 2021] [mpm_event:notice] [pid 32077:tid 140392561593280] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations
[Thu Sep 23 15:05:06.554594 2021] [core:notice] [pid 32077:tid 140392561593280] AH00094: Command line: '/usr/sbin/apache2'
[Thu Sep 23 15:05:19.081581 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] mod_wsgi (pid=32617): Target WSGI script '/home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py' c$
[Thu Sep 23 15:05:19.081638 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] mod_wsgi (pid=32617): Exception occurred processing WSGI script '/home/sidharth/Downloads/g$
[Thu Sep 23 15:05:19.081828 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] Traceback (most recent call last):
[Thu Sep 23 15:05:19.081849 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604]   File "/home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py", line 12, in <module>
[Thu Sep 23 15:05:19.081853 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604]     from django.core.wsgi import get_wsgi_application
[Thu Sep 23 15:05:19.081867 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] ModuleNotFoundError: No module named 'django'
[Thu Sep 23 15:05:32.244779 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916] mod_wsgi (pid=32617): Target WSGI script '/home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py' c$
[Thu Sep 23 15:05:32.244845 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916] mod_wsgi (pid=32617): Exception occurred processing WSGI script '/home/sidharth/Downloads/g$
[Thu Sep 23 15:05:32.244924 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916] Traceback (most recent call last):
[Thu Sep 23 15:05:32.244946 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916]   File "/home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py", line 12, in <module>
[Thu Sep 23 15:05:32.244951 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916]     from django.core.wsgi import get_wsgi_application
[Thu Sep 23 15:05:32.244966 2021] [wsgi:error] [pid 32617:tid 140392325842688] [remote 103.206.177.13:52916] ModuleNotFoundError: No module named 'django'

Body:
libapache2-mod-wsgi-py3 can be used only with python 3.6.9 in ubuntu 18!!
if your virtualenv uses another version of python, you should download mod_wsgi from this link: mod_wsgi

at this time the latest version of mod_wsgi is 4.9.0. follow the steps below:

$ sudo apt install apache2 apache2-dev
$ wget https://codeload.github.com/GrahamDumpleton/mod_wsgi/tar.gz/4.9.0
$ tar -xf 4.9.0
$ cd mod_wsgi-4.9.0/
$ ./configure --with-python=/your virtualenv path/bin/python[version]
   # example:  ./configure --with-python=/virtualenv/bin/python3.9
$ make
$ sudo make install

$ sudo systemctl restart apache2


问:
How to sort an array of pointers with a pointer to NULL?
I tried to implement a bubble sort of array of pointers, from greatest to least value that they point to, basically I have to put a pointer to NULL in the middle of the elements (second cell), and when I try to sort them, I want the NULL pointer to be put to the last position of the cell (2) and the other ones to be in order except for this one that is put to the last position.
But this gives me a segmentation fault:</p>
```<code>typedef struct example{
     int data;
}exp;

exp *arr[3];

static void sort_arr(exp *[]);

int main(){

 arr[0] = malloc(sizeof(*arr[0]));
 arr[0]->data = 1;

 arr[1] = NULL;

 arr[2] = malloc(sizeof(*arr[2]));
 arr[2]->data = 2;

 sort_arr(arr);

 return 0;
}

static void sort_arr(exp *pass_arr[]){
    for (int i = 0; i < 3; i++)
    {
        for (int j = i + 1; j < 3; ++j)
        {
            if (pass_arr[i]->data < pass_arr[j]->data)
            {
                exp *temp = pass_arr[i];
                pass_arr[i] = pass_arr[j];
                pass_arr[j] = temp;
            }
        }
    }
    return;
}
</code>```

答:
You need to check whether an array element is NULL, and treat it as lower than the other value.

```<code>            if (pass_arr[i] == NULL ||
                (pass_arr[j] != NULL && pass_arr[i]->data < pass_arr[j]->data))
            {
                exp *temp = pass_arr[i];
                pass_arr[i] = pass_arr[j];
                pass_arr[j] = temp;
            }
</code>```

Body:
I tried to implement a bubble sort of array of pointers, from greatest to least value that they point to, basically I have to put a pointer to NULL in the middle of the elements (second cell), and when I try to sort them, I want the NULL pointer to be put to the last position of the cell (2) and the other ones to be in order except for this one that is put to the last position.
But this gives me a segmentation fault:

typedef struct example{
     int data;
}exp;

exp *arr[3];

static void sort_arr(exp *[]);

int main(){

 arr[0] = malloc(sizeof(*arr[0]));
 arr[0]->data = 1;

 arr[1] = NULL;

 arr[2] = malloc(sizeof(*arr[2]));
 arr[2]->data = 2;

 sort_arr(arr);

 return 0;
}

static void sort_arr(exp *pass_arr[]){
    for (int i = 0; i < 3; i++)
    {
        for (int j = i + 1; j < 3; ++j)
        {
            if (pass_arr[i]->data < pass_arr[j]->data)
            {
                exp *temp = pass_arr[i];
                pass_arr[i] = pass_arr[j];
                pass_arr[j] = temp;
            }
        }
    }
    return;
}

Body:
You need to check whether an array element is NULL, and treat it as lower than the other value.

            if (pass_arr[i] == NULL ||
                (pass_arr[j] != NULL && pass_arr[i]->data < pass_arr[j]->data))
            {
                exp *temp = pass_arr[i];
                pass_arr[i] = pass_arr[j];
                pass_arr[j] = temp;
            }


答:
Use a comparison function that is pointer-aware, something like

```<code>#define EQ  0
#define LT -1
#define GT +1

static int cmp( x *exp, y *exp )
{
  if ( x == NULL && y == NULL ) return EQ ; // Two NULLs compare equal
  if ( x == NULL && y != NULL ) return GT ; // NULL compares high with respect to non-NULL
  if ( x != NULL && y == NULL ) return GT ; // NULL compares high with respect to non-NULL

  // if we get here both X and Y are non-null,
  // and so can safely be de-referenced

  if ( x->data < y->data ) return LT ;
  if ( x->data > y->data ) return GT ;

  // must be equal

  return EQ;
}
</code>```

Your test in your sort routine changes then from

```<code>if ( pass_arr[i]->data < pass_arr[j]->data )
. . .
</code>```

to

```<code>if ( cmp( pass_arr[i] , pass_arr[j] ) < 0 )
. . .
</code>```

Title: How to sort an array of pointers with a pointer to NULL?

Body:
Use a comparison function that is pointer-aware, something like

#define EQ  0
#define LT -1
#define GT +1

static int cmp( x *exp, y *exp )
{
  if ( x == NULL && y == NULL ) return EQ ; // Two NULLs compare equal
  if ( x == NULL && y != NULL ) return GT ; // NULL compares high with respect to non-NULL
  if ( x != NULL && y == NULL ) return GT ; // NULL compares high with respect to non-NULL

  // if we get here both X and Y are non-null,
  // and so can safely be de-referenced

  if ( x->data < y->data ) return LT ;
  if ( x->data > y->data ) return GT ;

  // must be equal

  return EQ;
}

Your test in your sort routine changes then from

if ( pass_arr[i]->data < pass_arr[j]->data )
. . .

to

if ( cmp( pass_arr[i] , pass_arr[j] ) < 0 )
. . .


问:
why I get undefined value instead my input value
I'm new in JavaScript and I have a problem, it'll be great if someone could help me.
I'm trying to write something from one
 to h4.
my code is:

function ok() {
  document.getElementById("out").innerHTML = document.getElementById("name").value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label id="label">your text is:</label>
<br>
<input type="text" />
<p id="name" style="font-family: 'Courier New', Courier, monospace;"></p>
<button type="submit" id="click" onclick="ok()">click</button>
<h4 id="out" style="font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;"></h4></code>```

but when I'm doing it I get undefined.
If someone could help me understand what I'm doing wrong it'll be great.

答:
You should give a id to input then receive value of that:

function ok() {
  document.getElementById("out").innerHTML = document.getElementById("input").value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label id="label">your text is:</label>
<br>
<input type="text" id="input"/>
<p id="name" style="font-family: 'Courier New', Courier, monospace;"></p>
<button type="submit" id="click" onclick="ok()">click</button>
<h4 id="out" style="font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;"></h4></code>```

Body:
I'm new in JavaScript and I have a problem, it'll be great if someone could help me.
I'm trying to write something from one
 to h4.
my code is:

function ok() {
  document.getElementById("out").innerHTML = document.getElementById("name").value;
}

your text is:

<input type="text" />

<button type="submit" id="click" onclick="ok()">click</button>

but when I'm doing it I get undefined.
If someone could help me understand what I'm doing wrong it'll be great.

Body:
You should give a id to input then receive value of that:

function ok() {
  document.getElementById("out").innerHTML = document.getElementById("input").value;
}

<label id="label">your text is:</label>
<br>
<input type="text" id="input"/>
<p id="name" style="font-family: 'Courier New', Courier, monospace;"></p>
<button type="submit" id="click" onclick="ok()">click</button>
<h4 id="out" style="font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;"></h4>


问:
Macro button under customized ribbon tab tries to open old Excel file
I created a custom ribbon tab on my Excel like Excel_app_v1.xlsm, and a button under this ribbon tab is connected to a macro. So when I click this button, the macro does some table importing applications.

The first strange thing is that I created this ribbon tab and the button for only this Excel file, but the ribbon tab and the button appear in all other Excel files, even if the original Excel file Excel_app_v1.xlsm is not open.

The second problem is that I created a second version of my previous Excel file with "Save-as" option. So the new Excel file is like Excel_app_v2.xlsm. When I click the button under the ribbon tab, it opens the first Excel file Excel_app_v1.xlsm, even if it is not open. I deleted the first Excel file, but then I got an error like "Couldn't find the Excel_app_v1.xlsm on the path".

So obviously the macro button under the customized ribbon tab is linked to the first Excel file, but I couldn't find the menu option to change this. I added ThisWorkbook before all the sheet expressions in the vba code, but it didn't solve the problem. The button-click is still trying to open the old excel file.

The VBA code is below. The button is linked to the Sub ImportTable. Firstly it asks the user if the user wants to continue with the process. It opens the previous Excel file right after clicking on the button, at the same time as the Message Box appears.

```<code>Sub ImportTable()

  Application.ScreenUpdating = False
  YearMonth = ThisWorkbook.Sheets("tab1").Cells(11, 2).Value
  ' The Macro button opens the previous Excel file before clicking Yes or No on the message box
  answer = MsgBox("Warning! Brings the newest source file. You want to continue?", vbYesNo + vbQuestion, "")

  If answer = vbYes Then

     RunSASCodeViaBatFile  ' Another Sub which runs bat file to run a SAS-code. But it doesn't matter. Because the problem happens before I click on Yes or No.
     InsertSASFileIntoExcel

   Else  ' Nothing happens if clicking No on the Message Box
   End If

End Sub
</code>```

答:
Does this still work? I have done this in the past with success but can't seem to get it to work now.
I export the file, edit it and import it back in.
it appears to work, but when i close the Ribbon options pane, my custom buttons disappear.</p>

ContentLicense: CC BY-SA 3.0

Body:
I created a custom ribbon tab on my Excel like Excel_app_v1.xlsm, and a button under this ribbon tab is connected to a macro. So when I click this button, the macro does some table importing applications.

The first strange thing is that I created this ribbon tab and the button for only this Excel file, but the ribbon tab and the button appear in all other Excel files, even if the original Excel file Excel_app_v1.xlsm is not open.

The second problem is that I created a second version of my previous Excel file with "Save-as" option. So the new Excel file is like Excel_app_v2.xlsm. When I click the button under the ribbon tab, it opens the first Excel file Excel_app_v1.xlsm, even if it is not open. I deleted the first Excel file, but then I got an error like "Couldn't find the Excel_app_v1.xlsm on the path".

So obviously the macro button under the customized ribbon tab is linked to the first Excel file, but I couldn't find the menu option to change this. I added ThisWorkbook before all the sheet expressions in the vba code, but it didn't solve the problem. The button-click is still trying to open the old excel file.

The VBA code is below. The button is linked to the Sub ImportTable. Firstly it asks the user if the user wants to continue with the process. It opens the previous Excel file right after clicking on the button, at the same time as the Message Box appears.

Sub ImportTable()

  Application.ScreenUpdating = False
  YearMonth = ThisWorkbook.Sheets("tab1").Cells(11, 2).Value
  ' The Macro button opens the previous Excel file before clicking Yes or No on the message box
  answer = MsgBox("Warning! Brings the newest source file. You want to continue?", vbYesNo + vbQuestion, "")

  If answer = vbYes Then

     RunSASCodeViaBatFile  ' Another Sub which runs bat file to run a SAS-code. But it doesn't matter. Because the problem happens before I click on Yes or No.
     InsertSASFileIntoExcel

   Else  ' Nothing happens if clicking No on the Message Box
   End If

End Sub


问:
Blocking commits to branches with no-direct-commit policies
I work with git repos hosted in Azure Devops (AzDO). Usually the master branch has AzDO policy that you can't push directly to it, and must use pull requests. However, some folks accidentally commit locally to master, and then their master branch gets out of sync with the origin, and they need to reset it with git reset --hard origin. I want to avoid this.

I know I can prevent commits to master using pre-commit hooks, with scripts or utils that will block (See answers to this question, and also this answer to a similar question). The richest util for this - https://pre-commit.com/hooks.html - only has a manually-configured no-commit-to-branch list.

Is there a solution that will block commits to any branch with policies in AzDO?

Edit in response to comments:

I disagree it's a training issue. A tool should do its best to guard users from mistake (just like saws have hand guard/etc.). IMO git fails at it, and git/AzDO could do better.

That said, maybe the git checkout master/git checkout -b mybranch is at fault here. So git fetch/git checkout -b mybranch origin/master would be safer.

I know one can reset/rebase, and that's the workaround for folks that got into this situation. However, I'd like to avoid that, especially for people with lower git skills.

答:
tl;dr: One possible solution is to sidestep the issue. Instruct your users (that are not super comfortable with Git yet) to delete their local copy of master and never checkout the master branch again. Instead they can update their copy of the remote branches often with git fetch, and they can use origin/master when making new branches or rebasing/merging to update their branches with the latest origin/master. I don't know that I would go so far as to prevent users from checking out master though, since more advanced users of Git might still wish to do so for some reason, and they would be perfectly comfortable resetting or renaming that local branch as needed.

I have recommended this approach to my co-workers and anecdotal evidence (of approximately 50 developers over the last few years) shows it seems to work fairly well. I also eat my own dog food most of the time; I still occasionally checkout out shared branches when I need to commit to one directly (and either bypass policies to push, or on very rare occasions, force push).

Additional Notes:

When you use remote tracking branches (such as origin/master) to create new branches, by default the new local branch will track that remote branch, which you normally don't want. So, when creating branches this way you'll probably want to use --no-track. In general, to make pushing for the first time slightly easier I recommend using the config setting of push.default to current. More info here.

Here are some recommended conventions for using origin/master:

```<code># Update your local copy of the remote branches often,
#   especially before creating or updating branches
git fetch

# Create a new branch (newer syntax)
git switch -c my-branch origin/master --no-track
# Create a new branch (old syntax)
git checkout -b my-branch origin/master --no-track

# Pushing out changes for the first time
git push -u origin my-branch
# Pushing out changes for the first time with config set to current
git push -u
# Subsequent pushes
git push

# Update your feature branch using rebase
git switch my-branch
git fetch
git rebase origin/master
git push --force-with-lease

# Update your feature branch using merge
git switch my-branch
git fetch
git merge origin/master
git push
</code>```

Also, you mentioned:

A tool should do its best to guard users from mistake...

I generally agree, though you do need to make sure your solution works for everyone. Ideally there would be a way to enable using training wheels for those that want/need them, without forcing them on those who can ride effectively without them.
As I mentioned above I wouldn't want to be prevented from checking out (or committing to) a shared branch, since I sometimes actually need to. That being said, since using pre-commit hooks are at the user's discretion, I could simply not use the hook, or perhaps disable it temporarily when I need to bypass it, so I would not be too bothered by that sort of hook.

On the other hand, here's a really silly example that would bother me. In one of the Git repos I work out of we have a (strongly urged but not yet enforced) policy that all commit titles should begin with a capital letter. I recently demoed a pre-commit hook that warns you when you create a commit starting with a lowercase letter. Someone asked me if that hook could be changed to prevent from creating commits that don't begin with a capital letter, and I told them that I didn't want that, because I happen to purposefully make lots of local commits beginning with a lowercase letter. I'm referring to my WIP temporary commits, for which I use a lowercase letter as a note-to-self that I need to rewrite the commit before PR'ing it into a shared branch. If others wish to use the same mnemonic, they too would need that hook to be only a warning rather than a block. I would however support a block on the server side to prevent merging in commits that don't begin with a capital letter, as long as someone had the capability to override it, to cover the case where certain commits cannot (or should not) be re-written.

Body:
tl;dr: One possible solution is to sidestep the issue. Instruct your users (that are not super comfortable with Git yet) to delete their local copy of master and never checkout the master branch again. Instead they can update their copy of the remote branches often with git fetch, and they can use origin/master when making new branches or rebasing/merging to update their branches with the latest origin/master. I don't know that I would go so far as to prevent users from checking out master though, since more advanced users of Git might still wish to do so for some reason, and they would be perfectly comfortable resetting or renaming that local branch as needed.

I have recommended this approach to my co-workers and anecdotal evidence (of approximately 50 developers over the last few years) shows it seems to work fairly well. I also eat my own dog food most of the time; I still occasionally checkout out shared branches when I need to commit to one directly (and either bypass policies to push, or on very rare occasions, force push).

Additional Notes:

When you use remote tracking branches (such as origin/master) to create new branches, by default the new local branch will track that remote branch, which you normally don't want. So, when creating branches this way you'll probably want to use --no-track. In general, to make pushing for the first time slightly easier I recommend using the config setting of push.default to current. More info here.

Here are some recommended conventions for using origin/master:

# Update your local copy of the remote branches often,
#   especially before creating or updating branches
git fetch

# Create a new branch (newer syntax)
git switch -c my-branch origin/master --no-track
# Create a new branch (old syntax)
git checkout -b my-branch origin/master --no-track

# Pushing out changes for the first time
git push -u origin my-branch
# Pushing out changes for the first time with config set to current
git push -u
# Subsequent pushes
git push

# Update your feature branch using rebase
git switch my-branch
git fetch
git rebase origin/master
git push --force-with-lease

# Update your feature branch using merge
git switch my-branch
git fetch
git merge origin/master
git push

Also, you mentioned:

A tool should do its best to guard users from mistake...

I generally agree, though you do need to make sure your solution works for everyone. Ideally there would be a way to enable using training wheels for those that want/need them, without forcing them on those who can ride effectively without them.
As I mentioned above I wouldn't want to be prevented from checking out (or committing to) a shared branch, since I sometimes actually need to. That being said, since using pre-commit hooks are at the user's discretion, I could simply not use the hook, or perhaps disable it temporarily when I need to bypass it, so I would not be too bothered by that sort of hook.

On the other hand, here's a really silly example that would bother me. In one of the Git repos I work out of we have a (strongly urged but not yet enforced) policy that all commit titles should begin with a capital letter. I recently demoed a pre-commit hook that warns you when you create a commit starting with a lowercase letter. Someone asked me if that hook could be changed to prevent from creating commits that don't begin with a capital letter, and I told them that I didn't want that, because I happen to purposefully make lots of local commits beginning with a lowercase letter. I'm referring to my WIP temporary commits, for which I use a lowercase letter as a note-to-self that I need to rewrite the commit before PR'ing it into a shared branch. If others wish to use the same mnemonic, they too would need that hook to be only a warning rather than a block. I would however support a block on the server side to prevent merging in commits that don't begin with a capital letter, as long as someone had the capability to override it, to cover the case where certain commits cannot (or should not) be re-written.


问:
How to handle pop up/lookup windows in selenium
I am doing some web automation using Selenium RC. Am new to Selenium RC and am facing problems (may be learning curve) while doing automation. I am using java with Eclipse IDE to code selenium RC.

Scenario: I have a screen with a link. while clicking, it will open a lookup window which contains lot of names (grid). Now I have to select a value from grid by directly clicking any row/record. Or I can use search option and select the record. The problems are

my recorded script is NOT responding to pop-up windows.

Is there any command for "double-click" in selenium.

@rs79 - It didn't work for me. Here is my code:

```<code>selenium.click("link=eName");   //click the link to open the lookup window
//lookup window
selenium.focus("Associate"); <br>
selenium.waitForPopUp("Associat", "20000");
selenium.selectWindow("Associat");
selenium.type("id=SearchTextBox", "xyz"); //Enter the text in search field of lookup
selenium.click("id=SearchButton"); // click search button on lookup window <br>
</code>```

Please correct me if I am wrong. Appreciated if anyone give me more suggestions.

答:
If its a popup not an popup window then you can try the firebug to locate the element or record you want.

Now copy its xpath and use it in your code.

Same problem I have faced and solved by this method as xpath from fire bug is detailed and locates the proper window.

After coping xpath please verify the path has // at starting.

Thanks

Body:
I am doing some web automation using Selenium RC. Am new to Selenium RC and am facing problems (may be learning curve) while doing automation. I am using java with Eclipse IDE to code selenium RC.

Scenario: I have a screen with a link. while clicking, it will open a lookup window which contains lot of names (grid). Now I have to select a value from grid by directly clicking any row/record. Or I can use search option and select the record. The problems are

my recorded script is NOT responding to pop-up windows.

Is there any command for "double-click" in selenium.

@rs79 - It didn't work for me. Here is my code:

selenium.click("link=eName");   //click the link to open the lookup window
//lookup window
selenium.focus("Associate");

selenium.waitForPopUp("Associat", "20000");
selenium.selectWindow("Associat");
selenium.type("id=SearchTextBox", "xyz"); //Enter the text in search field of lookup
selenium.click("id=SearchButton"); // click search button on lookup window

Please correct me if I am wrong. Appreciated if anyone give me more suggestions.


问:
Does React Native works well on MacBook M1?
I have to buy MacBook Air with M1. As I see, it supports react native (npm, expo etc.). Yes?

Edited 11.02: ok, solved. Thank you all!

答:
It works well but it depends on what modules are you using. Some old modules are not compatible and iOS builds may fail.

2023 UPDATE

Everything is now compatible.


问:
SQL query to get multiple records into multiple columns
I have a CSV that I am trying to create and pull data for. The CSV template has multiple columns for Status (IE: Status1, Status2, Status3). Some locations have only one status and some can have up to 3. I am trying to find a way in SQL that I can have 3 status columns and populate those based on the number of records for a location. For example, a location called John's Office could have a status of Ready. Another location called IT Workroom may have 3 statuses, Ready, In-Repair, and In-Use. The columns in the SQL query would look something like this:

```<code>Location          Status1         Status2        Status3
----------------------------------------------------------
John's Office     Ready
IT Workroom       Ready           In-Repair       In-Use
</code>```

The column names Status1, Status2, etc would be column names that are just made up. I would want to populate Status1 with the first record that returns, regardless of the actual status name. So Status1 would always be populated. Status2 will only be populated if their is a second status.

In the original table that holds this information, it looks like this:

```<code>LocationName           StatusName
------------------------------------
IT Workroom            In-Repair
IT Workroom            Ready
John's Office          Ready
IT Workroom            In-Use
</code>```

I have tried PIVOT, but I realized that this is not what I need as I am not technically aggregating the data.

答:
Please try the following solution mimicking PIVOT operation.

SQL

```<code>-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, LocationName VARCHAR(30), StatusName VARCHAR(50));
INSERT INTO @tbl VALUES
('IT Workroom', 'In-Repair'),
('IT Workroom', 'Ready'),
('John''s Office', 'Ready'),
('IT Workroom', 'In-Use');
-- DDL and sample data population, end

SELECT  LocationName
   , MAX(CASE WHEN StatusName = 'Ready' THEN StatusName ELSE '' END) [Status1]
   , MAX(CASE WHEN StatusName = 'In-Repair' THEN StatusName ELSE '' END) [Status2]
   , MAX(CASE WHEN StatusName = 'In-Use' THEN StatusName ELSE '' END) [Status3]
FROM @tbl
GROUP BY LocationName
ORDER BY LocationName;
</code>```

Output

```<code>+---------------+---------+-----------+---------+
| LocationName  | Status1 |  Status2  | Status3 |
+---------------+---------+-----------+---------+
| IT Workroom   | Ready   | In-Repair | In-Use  |
| John's Office | Ready   |           |         |
+---------------+---------+-----------+---------+
</code>```

Body:
I have a CSV that I am trying to create and pull data for. The CSV template has multiple columns for Status (IE: Status1, Status2, Status3). Some locations have only one status and some can have up to 3. I am trying to find a way in SQL that I can have 3 status columns and populate those based on the number of records for a location. For example, a location called John's Office could have a status of Ready. Another location called IT Workroom may have 3 statuses, Ready, In-Repair, and In-Use. The columns in the SQL query would look something like this:

Location          Status1         Status2        Status3
----------------------------------------------------------
John's Office     Ready
IT Workroom       Ready           In-Repair       In-Use

The column names Status1, Status2, etc would be column names that are just made up. I would want to populate Status1 with the first record that returns, regardless of the actual status name. So Status1 would always be populated. Status2 will only be populated if their is a second status.

In the original table that holds this information, it looks like this:

LocationName           StatusName
------------------------------------
IT Workroom            In-Repair
IT Workroom            Ready
John's Office          Ready
IT Workroom            In-Use

I have tried PIVOT, but I realized that this is not what I need as I am not technically aggregating the data.

Body:
Please try the following solution mimicking PIVOT operation.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, LocationName VARCHAR(30), StatusName VARCHAR(50));
INSERT INTO @tbl VALUES
('IT Workroom', 'In-Repair'),
('IT Workroom', 'Ready'),
('John''s Office', 'Ready'),
('IT Workroom', 'In-Use');
-- DDL and sample data population, end

SELECT  LocationName
   , MAX(CASE WHEN StatusName = 'Ready' THEN StatusName ELSE '' END) [Status1]
   , MAX(CASE WHEN StatusName = 'In-Repair' THEN StatusName ELSE '' END) [Status2]
   , MAX(CASE WHEN StatusName = 'In-Use' THEN StatusName ELSE '' END) [Status3]
FROM @tbl
GROUP BY LocationName
ORDER BY LocationName;

Output

+---------------+---------+-----------+---------+
| LocationName  | Status1 |  Status2  | Status3 |
+---------------+---------+-----------+---------+
| IT Workroom   | Ready   | In-Repair | In-Use  |
| John's Office | Ready   |           |         |
+---------------+---------+-----------+---------+


问:
A generic error occurred in GDI+
I loaded an image into a Picture Box using:

```<code>picturebox1.Image = Image.FromFile()
</code>```

and I save it by using:

```<code>Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(FileName, ImageFormat.Bmp);
</code>```

It works perfectly fine when creating a new file, but when I try to replace the existing image, I get thrown the following runtime error:

A generic error occurred in GDI+

So what can I do to solve this problem??

答:
The FromFile method locks the file, so use the Image.FromStream() method for reading the image:

```<code>byte[] bytes = System.IO.File.ReadAllBytes(filename);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
pictureBox1.Image = Image.FromStream(ms);
</code>```

Then save like you were before.

Title: A generic error occurred in GDI+

Body:
I loaded an image into a Picture Box using:

picturebox1.Image = Image.FromFile()

and I save it by using:

Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(FileName, ImageFormat.Bmp);

It works perfectly fine when creating a new file, but when I try to replace the existing image, I get thrown the following runtime error:

A generic error occurred in GDI+

So what can I do to solve this problem??

Body:
The FromFile method locks the file, so use the Image.FromStream() method for reading the image:

byte[] bytes = System.IO.File.ReadAllBytes(filename);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
pictureBox1.Image = Image.FromStream(ms);

Then save like you were before.


问:
Merging both merge sort and heap sort together
Suppose you want to improve Merge Sort by first applying Heap Sort to a number of consecutive subarrays. Given an array A, your algorithm subdivides A into subarrays A1, A2 · · · Ak, where k is some power of 2, and applies Heap Sort on each subarray Ai alone. The algorithm proceeds into merging pairs of consecutive subarrays until the array is sorted. For example, if k = 4, you first apply Heap Sort to sort each Ai and then you merge A1 with A2 and A3 with A4, then you apply the merge function once to get the sorted array. (a) Does the proposed algorithm improve the asymptotic running time of Merge Sort when k = 2? How about the case k = log n (or a power of 2 that is closest to log n)? Justify. (b) Is the proposed algorithm stable? Is it in-place? Prove your answers.

So I have this problem to solve, I was thinking that for k=2, the threshold value is too low and inefficient, but I'm not sure when k is at logn or more. If 2 sorting algorithms have the same complexity, won’t merging them be pointless in terms of running time? For b), i think the merged algorithim would be stable and not in place.

what do you think?

答:
(a) No, for any k this algorithm would not improve the running time of merge sort as it is a comparison-based sorting algorithm and it can be proven that any such algorithm is Ω(n ln n), and merge sort already is O(n ln n).

(b) This algorithm can be in-place because heap sort is an in-place algorithm (using standard binary max heap implementation with array) and there exists an in-place stable merging algorithm. This algorithm can also be made stable using any stable merging and stable heap sort (can be achieved by using pairs (value, initial position) in the heap and lexicographic comparison). Making this algorithm both stable and in-place requires a stable in-place heap and as far as I know, such heap has not yet been invented.


问:
POST request to Wordpress REST API returns an empty object
I am creating a Gutenberg block inside a plugin with a MediaUpload for zip files. Then I am trying to add a callback that will use the id of the zip file to get the attachment url, make a new folder in a separate assets area if there is not one yet, and unzip the file into the folder.

Right now I am trying to do this with REST using wp.apiFetch.

I've gotten as far as testing the response, but even though the response comes through properly, the object is empty.

This is the Edit.js file:

```<code>wp.apiFetch({
  path: '/name-support/v1/zipped/',
  method: 'POST',
  data: { id: 'test test test' },
}).then(data => {
  console.log('response: ', data);
});
</code>```

This is the REST API rout setup and the callback function:

```<code>add_action( 'rest_api_init', function () {
  register_rest_route( 'name-support/v1', '/zipped/',
      [
        'methods' => WP_REST_Server::EDITABLE,
        'callback' => 'name_image_sequence_unzip',
        'permission_callback' => '__return_true'
      ]
  );
});

function name_image_sequence_unzip($data) {
    return rest_ensure_response( $data );
}
</code>```

答:
I fixed this issue by specifying the content type in the headers option as application/json:

```<code>wp.apiFetch({
  path: '/name-support/v1/zipped/',
  method: 'POST',
  headers: {
        "Content-Type": "application/json",
      },
  data: { id: 'test test test' },
}).then(data => {
  console.log('response: ', data);
});
</code>```

Body:
I am creating a Gutenberg block inside a plugin with a MediaUpload for zip files. Then I am trying to add a callback that will use the id of the zip file to get the attachment url, make a new folder in a separate assets area if there is not one yet, and unzip the file into the folder.

Right now I am trying to do this with REST using wp.apiFetch.

I've gotten as far as testing the response, but even though the response comes through properly, the object is empty.

This is the Edit.js file:

wp.apiFetch({
  path: '/name-support/v1/zipped/',
  method: 'POST',
  data: { id: 'test test test' },
}).then(data => {
  console.log('response: ', data);
});

This is the REST API rout setup and the callback function:

add_action( 'rest_api_init', function () {
  register_rest_route( 'name-support/v1', '/zipped/',
      [
        'methods' => WP_REST_Server::EDITABLE,
        'callback' => 'name_image_sequence_unzip',
        'permission_callback' => '__return_true'
      ]
  );
});

function name_image_sequence_unzip($data) {
    return rest_ensure_response( $data );
}

Body:
I fixed this issue by specifying the content type in the headers option as application/json:

wp.apiFetch({
  path: '/name-support/v1/zipped/',
  method: 'POST',
  headers: {
        "Content-Type": "application/json",
      },
  data: { id: 'test test test' },
}).then(data => {
  console.log('response: ', data);
});


问:
Python wordlist creation
So far I am creating a world based game the only thing I need help with is creating a wordlist without having to type each word or re formate hundreds into the correct formatting. Any tips?

so far I have this:

```<code>fiveLetterWords = ["abuse", "adult", "drama", "drain", "enemy", "entry", "catch", "could", "would", "track", "train", "plain", "plane"]
sixLetterWords = ["people", "things", "really", "abroad", "accept", "belief", "scraps", "trashy", "camera", "create"]
</code>```

I would like to have a few more words than this and if there's a site that has this listed in this format comment it thanks!

答:
Search for the most frequent English words in Kaggle datasets. then you can grab those which contain 5, 6, or ... letters. also, you can use this dataset that contains the most frequent 5 letters meaningful English words that is a combination of two datasets and without any repetition.

simply use this line of code to read the .csv file:

import pandas as pd
pd.read_csv("frequent_5_char_words.csv" , sep=" " , header=None)
```

Title: Python wordlist creation

Body:
So far I am creating a world based game the only thing I need help with is creating a wordlist without having to type each word or re formate hundreds into the correct formatting. Any tips?

so far I have this:

fiveLetterWords = ["abuse", "adult", "drama", "drain", "enemy", "entry", "catch", "could", "would", "track", "train", "plain", "plane"]
sixLetterWords = ["people", "things", "really", "abroad", "accept", "belief", "scraps", "trashy", "camera", "create"]

I would like to have a few more words than this and if there's a site that has this listed in this format comment it thanks!


问:
How to remove all empty lines from beginning and end of file
I have a file that looks like

```<code>Blank Line
Blank Line
Blank Line
Blank Line
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi a justo egestas, malesuada lacus ut, euismod purus.
Etiam faucibus felis ac orci varius cursus.

Praesent tincidunt nibh condimentum, finibus odio non, euismod tortor.
Quisque eget ligula eu turpis consequat rutrum.

Cras non ipsum vel ipsum sodales ullamcorper non vitae dui.
Blank Line
Blank Line
Blank Line
Blank Line
</code>```

The Blank Line is literally blank line. I could not put blank lines in the beginning and end in the code block so using the text Blank Line.

I need to remove all the blank lines from the beginning and end of this file. Please notice that there are blank lines in between lines. I do not want to remove those.

I have come up with the following code that remove all blank lines from the beginning of the file. But I could not manage to remove all the blank lines at the end of the file.

```<code>#!/usr/bin/env python3

import sys
import argparse
import logging

parser = argparse.ArgumentParser()
parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin)
parser.add_argument(
    '-d',
    '--debug',
    help="Print lots of debugging statements",
    action="store_const",
    dest="loglevel",
    const=logging.DEBUG,
    default=logging.WARNING,
)
parser.add_argument(
    '-v',
    '--verbose',
    help="Be verbose",
    action="store_const",
    dest="loglevel",
    const=logging.INFO,
)
args = parser.parse_args()

if sys.stdin.isatty() and args.infile.name == "<stdin>":
    sys.exit("Please give some input")

logging.basicConfig(level=args.loglevel)

# Business Logic Here
do_not_print_all_lines = True

for line in args.infile:
    if not line.strip() and do_not_print_all_lines:
        pass
    else:
        do_not_print_all_lines = False

    if not do_not_print_all_lines:
        print(line)
</code>```

How can I do that?

答:
Something like this:</p>
```<code>my_file = open("sample-file.txt", "r")
lines = my_file.readlines()
# inspection starting from beginning of list
for n in range(len(lines)):
    line = lines[n].strip()
    if line == "":
        frm= n
    else:
        break
# inspection starting from end of list
for n in range(len(lines)-1,-1,-1):
    line = lines[n].strip()
    if line == "":
        to= n
    else:
        break
newlines = lines[frm+1:to]
print(newlines)
</code>```

Body:
I have a file that looks like

Blank Line
Blank Line
Blank Line
Blank Line
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi a justo egestas, malesuada lacus ut, euismod purus.
Etiam faucibus felis ac orci varius cursus.

Praesent tincidunt nibh condimentum, finibus odio non, euismod tortor.
Quisque eget ligula eu turpis consequat rutrum.

Cras non ipsum vel ipsum sodales ullamcorper non vitae dui.
Blank Line
Blank Line
Blank Line
Blank Line

The Blank Line is literally blank line. I could not put blank lines in the beginning and end in the code block so using the text Blank Line.

I need to remove all the blank lines from the beginning and end of this file. Please notice that there are blank lines in between lines. I do not want to remove those.

I have come up with the following code that remove all blank lines from the beginning of the file. But I could not manage to remove all the blank lines at the end of the file.

#!/usr/bin/env python3

import sys
import argparse
import logging

parser = argparse.ArgumentParser()
parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin)
parser.add_argument(
    '-d',
    '--debug',
    help="Print lots of debugging statements",
    action="store_const",
    dest="loglevel",
    const=logging.DEBUG,
    default=logging.WARNING,
)
parser.add_argument(
    '-v',
    '--verbose',
    help="Be verbose",
    action="store_const",
    dest="loglevel",
    const=logging.INFO,
)
args = parser.parse_args()

if sys.stdin.isatty() and args.infile.name == "<stdin>":
    sys.exit("Please give some input")

logging.basicConfig(level=args.loglevel)

# Business Logic Here
do_not_print_all_lines = True

for line in args.infile:
    if not line.strip() and do_not_print_all_lines:
        pass
    else:
        do_not_print_all_lines = False

    if not do_not_print_all_lines:
        print(line)

How can I do that?

Body:
Something like this:

my_file = open("sample-file.txt", "r")
lines = my_file.readlines()
# inspection starting from beginning of list
for n in range(len(lines)):
    line = lines[n].strip()
    if line == "":
        frm= n
    else:
        break
# inspection starting from end of list
for n in range(len(lines)-1,-1,-1):
    line = lines[n].strip()
    if line == "":
        to= n
    else:
        break
newlines = lines[frm+1:to]
print(newlines)


问:
Save file as .mat in python
I want to save a list of elements (r) to .mat file format inside python
I convert it to array

```<code>r = Lattice([Marker('l000015$start', NumIntSteps=40, length=array(0.)), Marker('ip.1', NumIntSteps=40, length=array(0.)), Drift('drift_0', 2.2002250210956804), Quadrupole('qc1l1.1', 1.2, -0.6451875623775719, NumIntSteps=40), Monitor('BPM0'), Drift('drift_1', 0.08000000000000007), Monitor('BPM1'), Quadrupole('qc1r2.1', 1.0, 0.34045204285588043, NumIntSteps=40), Monitor('BPM2'), Drift('drift_2', 0.08000000000000007), Monitor('BPM3'), Quadrupole('qc1r3.1', 1.0, 0.18818867758026042, NumIntSteps=40), Monitor('BPM4'), Drift('drift_3', 0.2999999999999998), Quadrupole('qc2r1.1', 1.25, 0.026716664923441297, NumIntSteps=40), Monitor('BPM5'), Drift('drift_4', 0.08000000000000096), Monitor('BPM6'), Quadrupole('qc2r2.1', 1.25, -0.02041914442905664, NumIntSteps=40), Monitor('BPM7'),..........

import numpy as np
import scipy.io
arr = np.array(r)
</code>```

Then i tried to save it using

```<code>scipy.io.savemat('file.mat', arr)
</code>```

I got the error massage

```<code>AttributeError: 'numpy.ndarray' object has no attribute 'items'
</code>```

Could you please clarify to me what is the "items" means,

I imported this list from .mat in python then i added some elements to it inside python and now i want to save it in .mat format.

答:
The second argument needs to be a dictionary containing all variables that you want to save. So, we can fix your code as follows.</p>
```<code>scipy.io.savemat('file.mat', {'matrix_name':arr})
</code>```

Title: Save file as .mat in python

Body:
I want to save a list of elements (r) to .mat file format inside python
I convert it to array

r = Lattice([Marker('l000015$start', NumIntSteps=40, length=array(0.)), Marker('ip.1', NumIntSteps=40, length=array(0.)), Drift('drift_0', 2.2002250210956804), Quadrupole('qc1l1.1', 1.2, -0.6451875623775719, NumIntSteps=40), Monitor('BPM0'), Drift('drift_1', 0.08000000000000007), Monitor('BPM1'), Quadrupole('qc1r2.1', 1.0, 0.34045204285588043, NumIntSteps=40), Monitor('BPM2'), Drift('drift_2', 0.08000000000000007), Monitor('BPM3'), Quadrupole('qc1r3.1', 1.0, 0.18818867758026042, NumIntSteps=40), Monitor('BPM4'), Drift('drift_3', 0.2999999999999998), Quadrupole('qc2r1.1', 1.25, 0.026716664923441297, NumIntSteps=40), Monitor('BPM5'), Drift('drift_4', 0.08000000000000096), Monitor('BPM6'), Quadrupole('qc2r2.1', 1.25, -0.02041914442905664, NumIntSteps=40), Monitor('BPM7'),..........

import numpy as np
import scipy.io
arr = np.array(r)

Then i tried to save it using

scipy.io.savemat('file.mat', arr)

I got the error massage

AttributeError: 'numpy.ndarray' object has no attribute 'items'

Could you please clarify to me what is the "items" means,

I imported this list from .mat in python then i added some elements to it inside python and now i want to save it in .mat format.

Body:
The second argument needs to be a dictionary containing all variables that you want to save. So, we can fix your code as follows.

scipy.io.savemat('file.mat', {'matrix_name':arr})


问:
Jackson XML deserialize Sub-Nodes as Plain String
I have an XML Sttructure and want to Deserialize this to an Object with a Property Description as a Plain HTML-String

<ItemList>
  <Item ID="1">
    <Description>

        This is a HTML Description

        With undefined number of subnodes

    </Description>
  </Item>
  <Item ID="2">
    <Description>

        This is a HTML Description

Some Other Nodes

    </Description>
  </Item>
</ItemList>
```
<p>The description tag contains only HTML text and i don't want to define classes for all possible HTML-Tags. Is there a solution, for example with a custom Deserializer, to parse the Tags inside Description as Plain Html-Text?</p>
<p>My classes look like this</p>
<pre class="lang-kotlin prettyprint-override"><code>data class ItemList(
  @JacksonXmlProperty(localName = "Item")
  @JacksonXmlElementWrapper(useWrapping = false)
  val items: List<Item> = listOf()
)

data class Item(
  @JacksonXmlProperty(localName = "ID", isAttribute = true)
  val id: String? = null,

  @JacksonXmlProperty(localName = "Description")
  val description: HtmlText? = null
)

data class HtmlText(
  val text: String? // This should be the Plain HTML-String
)
</code>```

private val xmlMapper = XmlMapper()
    .registerKotlinModule()
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

val itemlist = xmlMapper.readValue<ItemList>(stream) // stream is the XML file described above
```

答:
I'm not as well versed in Kotlin, so I wrote up the Java that should be cover this.  Basically, you need to accept the ObjectNode in the mutator so that you can serialize it back to XML using a XML Mapper.</p>
```<code>public class TestMe3 {
    public static void main(String[] args) throws IOException, XMLStreamException {
        var inputString =
                "<ItemList>\n" +
                        "   <Item ID=\"1\">\n" +
                        "       <Description>\n" +
                        "           <p>\n" +
                        "               <span>This is a HTML Description</span>\n" +
                        "           </p>\n" +
                        "           <p>\n" +
                        "               With undefined number of subnodes\n" +
                        "           </p>\n" +
                        "       </Description>\n" +
                        "   </Item>\n" +
                        "   <Item ID =\"2\">\n" +
                        "       <Description>\n" +
                        "           <p>\n" +
                        "               <span> This is a HTML Description</span>\n" +
                        "           </p>\n" +
                        "           <ul>\n" +
                        "               <li>Some Other Nodes</li>\n" +
                        "           </ul>\n" +
                        "       </Description>\n" +
                        "   </Item>\n" +
                        "</ItemList>";
        Reader reader = new StringReader(inputString);
        XMLInputFactory factory = XMLInputFactory.newInstance(); // Or newFactory()
        XMLStreamReader xmlReader = factory.createXMLStreamReader(reader);

        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        ItemList returnObj = xmlMapper.readValue(xmlReader, ItemList.class);
        System.out.println(returnObj.items.get(0).description);
        System.out.println(returnObj.items.get(1).description);
    }

    @JacksonXmlRootElement(localName = "ItemList")
    static class ItemList {
        @JacksonXmlProperty(localName = "Item")
        @JacksonXmlElementWrapper(useWrapping = false)
        List<Item> items;
    }

    @JacksonXmlRootElement(localName = "Item")
    static class Item {
        @JacksonXmlProperty(localName = "ID", isAttribute = true)
        String id;

        @JacksonXmlElementWrapper(localName = "Description")
        String description;

        public void setDescription(ObjectNode xml) throws JsonProcessingException {
            XmlMapper xmlMapper = new XmlMapper();
            description = xmlMapper.writer().withRootName("Description").writeValueAsString(xml);
        }
    }

}
</code>```

Body:
I have an XML Sttructure and want to Deserialize this to an Object with a Property Description as a Plain HTML-String

<ItemList>
  <Item ID="1">
    <Description>

        This is a HTML Description

        With undefined number of subnodes

    </Description>
  </Item>
  <Item ID="2">
    <Description>

        This is a HTML Description

Some Other Nodes

    </Description>
  </Item>
</ItemList>

The description tag contains only HTML text and i don't want to define classes for all possible HTML-Tags. Is there a solution, for example with a custom Deserializer, to parse the Tags inside Description as Plain Html-Text?

My classes look like this

data class ItemList(
  @JacksonXmlProperty(localName = "Item")
  @JacksonXmlElementWrapper(useWrapping = false)
  val items: List<Item> = listOf()
)

data class Item(
  @JacksonXmlProperty(localName = "ID", isAttribute = true)
  val id: String? = null,

  @JacksonXmlProperty(localName = "Description")
  val description: HtmlText? = null
)

data class HtmlText(
  val text: String? // This should be the Plain HTML-String
)

private val xmlMapper = XmlMapper()
    .registerKotlinModule()
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

val itemlist = xmlMapper.readValue<ItemList>(stream) // stream is the XML file described above

Body:
I'm not as well versed in Kotlin, so I wrote up the Java that should be cover this.  Basically, you need to accept the ObjectNode in the mutator so that you can serialize it back to XML using a XML Mapper.

public class TestMe3 {
    public static void main(String[] args) throws IOException, XMLStreamException {
        var inputString =
                "<ItemList>\n" +
                        "   <Item ID=\"1\">\n" +
                        "       <Description>\n" +
                        "           <p>\n" +
                        "               <span>This is a HTML Description</span>\n" +
                        "           </p>\n" +
                        "           <p>\n" +
                        "               With undefined number of subnodes\n" +
                        "           </p>\n" +
                        "       </Description>\n" +
                        "   </Item>\n" +
                        "   <Item ID =\"2\">\n" +
                        "       <Description>\n" +
                        "           <p>\n" +
                        "               <span> This is a HTML Description</span>\n" +
                        "           </p>\n" +
                        "           <ul>\n" +
                        "               <li>Some Other Nodes</li>\n" +
                        "           </ul>\n" +
                        "       </Description>\n" +
                        "   </Item>\n" +
                        "</ItemList>";
        Reader reader = new StringReader(inputString);
        XMLInputFactory factory = XMLInputFactory.newInstance(); // Or newFactory()
        XMLStreamReader xmlReader = factory.createXMLStreamReader(reader);

        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        ItemList returnObj = xmlMapper.readValue(xmlReader, ItemList.class);
        System.out.println(returnObj.items.get(0).description);
        System.out.println(returnObj.items.get(1).description);
    }

    @JacksonXmlRootElement(localName = "ItemList")
    static class ItemList {
        @JacksonXmlProperty(localName = "Item")
        @JacksonXmlElementWrapper(useWrapping = false)
        List<Item> items;
    }

    @JacksonXmlRootElement(localName = "Item")
    static class Item {
        @JacksonXmlProperty(localName = "ID", isAttribute = true)
        String id;

        @JacksonXmlElementWrapper(localName = "Description")
        String description;

        public void setDescription(ObjectNode xml) throws JsonProcessingException {
            XmlMapper xmlMapper = new XmlMapper();
            description = xmlMapper.writer().withRootName("Description").writeValueAsString(xml);
        }
    }

}


问:
Filtering Wordle words using a DataFrame
I have a DataFrame with random 5 letter "words". I'd like to filter them using some criteria from the game Wordle.

For example, find all words which satisfy the following:

Contains 'a' in position 0

Does not contain 'b'

Contains 'c' in position 2

Contains 'd' somewhere

Does not contain 'e'

That would correspond to guessing 'abcde' and getting the response: a=green, b=black, c=green, d=yellow, e=black.

I got it working using a MultiIndex and building a column for the presence of each letter, which feels rather inefficient. Is there a better approach?

```<code>import random
import string
import pandas as pd

rand_words = [''.join(random.choice(string.ascii_lowercase) for _ in range(5)) for _ in range(20000)]

tuples = [list(word) for word in rand_words]

index = pd.MultiIndex.from_tuples(tuples, names=["L0", "L1", "L2", "L3", "L4"])

df = pd.DataFrame({"word":rand_words}, index=index)

for ch in string.ascii_lowercase:
    df[ch] = df['word'].map(lambda word: ch in word)

# filter for 'a' and 'c' in positions 0 and 2
# then query for rows that don't contain 'b' or 'e', but do contain 'd'
print(df.xs(('a','c'), level=(0,2), drop_level=False).query('~b & d & ~e')['word'])
</code>```

Output:

```<code>L0  L1  L2  L3  L4
a   d   c   j   q     adcjq
    h   c   d   n     ahcdn
    c   c   d   k     accdk
    s   c   z   d     asczd
</code>```

答:
Here is a way using the str accesor, sometimes with contains or the inverse ~, sometimes with position [] to get one letter and equal (eq) or not (ne). So in your case, you can do

```<code>random.seed(1) # for reproductibility
rand_words = [''.join(random.choice(string.ascii_lowercase)
              for _ in range(5)) for _ in range(20000)]
df = pd.DataFrame({"word":rand_words})

print(
    df.loc[
        df['word'].str[0].eq('a')
        & ~df['word'].str.contains('b')
        & df['word'].str[2].eq('c')
        & df['word'].str.contains('d') & df['word'].str[3].ne('d')
        & ~df['word'].str.contains('e')
    ]
)

#         word
# 8902   agcsd
# 14816  adcyr
</code>```

Note the part & df['word'].str[3].ne('d') that ensure that d is not at this position while existing in the word df['word'].str.contains('d') as I understand yellow would means.

Body:
I have a DataFrame with random 5 letter "words". I'd like to filter them using some criteria from the game Wordle.

For example, find all words which satisfy the following:

Contains 'a' in position 0

Does not contain 'b'

Contains 'c' in position 2

Contains 'd' somewhere

Does not contain 'e'

That would correspond to guessing 'abcde' and getting the response: a=green, b=black, c=green, d=yellow, e=black.

I got it working using a MultiIndex and building a column for the presence of each letter, which feels rather inefficient. Is there a better approach?

import random
import string
import pandas as pd

rand_words = [''.join(random.choice(string.ascii_lowercase) for _ in range(5)) for _ in range(20000)]

tuples = [list(word) for word in rand_words]

index = pd.MultiIndex.from_tuples(tuples, names=["L0", "L1", "L2", "L3", "L4"])

df = pd.DataFrame({"word":rand_words}, index=index)

for ch in string.ascii_lowercase:
    df[ch] = df['word'].map(lambda word: ch in word)

# filter for 'a' and 'c' in positions 0 and 2
# then query for rows that don't contain 'b' or 'e', but do contain 'd'
print(df.xs(('a','c'), level=(0,2), drop_level=False).query('~b & d & ~e')['word'])

Output:

L0  L1  L2  L3  L4
a   d   c   j   q     adcjq
    h   c   d   n     ahcdn
    c   c   d   k     accdk
    s   c   z   d     asczd

Body:
Here is a way using the str accesor, sometimes with contains or the inverse ~, sometimes with position [] to get one letter and equal (eq) or not (ne). So in your case, you can do

random.seed(1) # for reproductibility
rand_words = [''.join(random.choice(string.ascii_lowercase)
              for _ in range(5)) for _ in range(20000)]
df = pd.DataFrame({"word":rand_words})

print(
    df.loc[
        df['word'].str[0].eq('a')
        & ~df['word'].str.contains('b')
        & df['word'].str[2].eq('c')
        & df['word'].str.contains('d') & df['word'].str[3].ne('d')
        & ~df['word'].str.contains('e')
    ]
)

#         word
# 8902   agcsd
# 14816  adcyr

Note the part & df['word'].str[3].ne('d') that ensure that d is not at this position while existing in the word df['word'].str.contains('d') as I understand yellow would means.


问:
Unable to obtain configuration from well-known/openid-configuration
I am using ASP.NET 5, In my solution I have Web API, Identity Server and Angular 2 project and I am authenticating Angular 2 client by using Identity Server, Angular 2 client consumes web api by passing token in http request and web api authenticate token and gives response, for this I have written a custom attribute which checks that user is authenticated or not

When I consume API I am getting following exception and Web API returns 500 internal server error.

System.InvalidOperationException: IDX10803: Unable to obtain
  configuration from:
  'http://xx.xx.xx.x:3926/.well-known/openid-configuration'. --->
  System.IO.IOException: IDX10804: Unable to retrieve document from:
  'http://xx.xx.xx.x:3926/.well-known/openid-configuration'. --->
  System.AggregateException: One or more errors occurred. --->
  System.Net.Http.HttpRequestException: An error occurred while sending
  the request. ---> System.Net.WebException: Unable to connect to the
  remote server ---> System.Net.Sockets.SocketException: A connection
  attempt failed because the connected party did not properly respond
  after a period of time, or established connection failed because
  connected host has failed to respond xx.xx.xx.x:3926 at
  System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) at
  System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
  Socket s4, Socket s6, Socket& socket, IPAddress& address,
  ConnectSocketState state, IAsyncResult asyncResult, Exception&
  exception)

答:
In my case I was missing this:</p>
```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseIdentityServer();
    ...
}
</code>```

Body:
In my case I was missing this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseIdentityServer();
    ...
}


问:
problem while creating button with many divs

This is the menu I'm trying to build. Now I'm confused and can't figure out how to make it.

One div (blue arrow) needs negative margin to get outside the box, another div for blue button background and inside the button two another divs or spans for the text colors. But on hover they need to look same (white color).

I've tried many times to build it but i failed. I get some bugs while loading. Maybe it need any jquery code but I'm very new on it, and I have no idea what to do.

I'm working local and I can't give any link to show it, but there is an image of what I want to make.

I hope you understand me because my English is not good.

答:
See: http://jsbin.com/ihugut

This works in all modern browsers, and IE8+ (it degrades reasonably in IE7).

(edit: it turned out that this must work perfectly in IE7, so see the end of my answer for that solution)

The one problem you might have is that because I aimed to keep the HTML as simple as possible, the CSS is complicated, so it could be difficult to make changes.

HTML:

```<code><ol id="menu">
    <li><a href="#">Ballina g</a></li>
    <li><a href="#">Konferenca g</a></li>
    <li><a href="#">Folesit g</a></li>
</ol>
</code>```

CSS:

```<code>body {
    margin: 50px;
    background: #aaa
}
#menu {
    list-style: none;
    counter-reset: num;
    background: #444;
    float: left;
    margin: 0;
    padding: 12px 0 0 0;
    font: bold 19px sans-serif
}
#menu li {
    margin: 0 0 12px 0;
    float: left;
    clear: both;

}
#menu a {
    counter-increment: num;
    padding: 3px 15px 3px 50px;
    float: left;
    position: relative;
    color: #0cf;
    text-decoration: none
}
#menu a:hover {
    color: #fff
}
#menu a:before {
    content: counter(num, decimal-leading-zero);
    color: #ccc;
    position: absolute;
    left: 21px;
    font-weight: normal
}
#menu a:hover:before {
    color: #fff;
}
#menu li:hover {
    background: #0cf;
    margin-left: -5px;
    margin-right: 5px
}
#menu li:hover a {
    left: 5px
}
#menu a:hover:after {
    content: ' ';
    position: absolute;
    top: 0;
    left: -15px;
    width: 0;
    height: 0;
    border-top: 15px solid transparent;
    border-bottom: 15px solid transparent;
    border-right: 10px solid #0cf
}
</code>```

Here's a version that works fully in IE7: http://jsbin.com/ihugut/3

The HTML had to be defiled:

```<code><ol id="menu">
    <li><a href="#"><span>01</span>Ballina g<span class="arrow"></span></a></li>
    <li><a href="#"><span>02</span>Konferenca g<span class="arrow"></span></a></li>
    <li><a href="#"><span>03</span>Folesit g<span class="arrow"></span></a></li>
</ol>
</code>```

Body:
See: http://jsbin.com/ihugut

This works in all modern browsers, and IE8+ (it degrades reasonably in IE7).

(edit: it turned out that this must work perfectly in IE7, so see the end of my answer for that solution)

The one problem you might have is that because I aimed to keep the HTML as simple as possible, the CSS is complicated, so it could be difficult to make changes.

HTML:

<ol id="menu">
    <li><a href="#">Ballina g</a></li>
    <li><a href="#">Konferenca g</a></li>
    <li><a href="#">Folesit g</a></li>
</ol>

CSS:

body {
    margin: 50px;
    background: #aaa
}
#menu {
    list-style: none;
    counter-reset: num;
    background: #444;
    float: left;
    margin: 0;
    padding: 12px 0 0 0;
    font: bold 19px sans-serif
}
#menu li {
    margin: 0 0 12px 0;
    float: left;
    clear: both;

}
#menu a {
    counter-increment: num;
    padding: 3px 15px 3px 50px;
    float: left;
    position: relative;
    color: #0cf;
    text-decoration: none
}
#menu a:hover {
    color: #fff
}
#menu a:before {
    content: counter(num, decimal-leading-zero);
    color: #ccc;
    position: absolute;
    left: 21px;
    font-weight: normal
}
#menu a:hover:before {
    color: #fff;
}
#menu li:hover {
    background: #0cf;
    margin-left: -5px;
    margin-right: 5px
}
#menu li:hover a {
    left: 5px
}
#menu a:hover:after {
    content: ' ';
    position: absolute;
    top: 0;
    left: -15px;
    width: 0;
    height: 0;
    border-top: 15px solid transparent;
    border-bottom: 15px solid transparent;
    border-right: 10px solid #0cf
}

Here's a version that works fully in IE7: http://jsbin.com/ihugut/3

The HTML had to be defiled:

<ol id="menu">
    <li><a href="#"><span>01</span>Ballina g<span class="arrow"></span></a></li>
    <li><a href="#"><span>02</span>Konferenca g<span class="arrow"></span></a></li>
    <li><a href="#"><span>03</span>Folesit g<span class="arrow"></span></a></li>
</ol>


问:
Can I add a variable into warnings message?
I have an application that will open many files and will convert these files into a pandas data frame. I want to ensure that all pandas' data frames have the same structure so I want to create a warning if the number of the column is not equal that 10. I also want to know which file was the one that arise the warning.

How can I introduce the file_name into the warning message?

```<code>def load_data(self):

    some code

    file_name = file_name
    if df.shape[1] !=10:
        warning.warns("File_name is wrong"
    return pandas_df2

</code>```

答:
you can use format strings as below

```<code>wrld = 'world'
A = 2
B = 5
print(f'Hello {wrld} {A + B} times')
</code>```

output :

```<code>Hello world 7 times
</code>```

pretty much anything in curly braces is python code

Body:
I have an application that will open many files and will convert these files into a pandas data frame. I want to ensure that all pandas' data frames have the same structure so I want to create a warning if the number of the column is not equal that 10. I also want to know which file was the one that arise the warning.

How can I introduce the file_name into the warning message?

def load_data(self):

    some code

    file_name = file_name
    if df.shape[1] !=10:
        warning.warns("File_name is wrong"
    return pandas_df2

Body:
you can use format strings as below

wrld = 'world'
A = 2
B = 5
print(f'Hello {wrld} {A + B} times')

output :

Hello world 7 times

pretty much anything in curly braces is python code


问:
Why is the space key being filtered out by MUI's Text Field component?
When I place one of MUI's Text Field components inside the column header of a Data Grid component, I'm unable to type a space into the text field. Similarly, if I press the right or left arrow key while the text field has focus, the text field loses focus rather than changing the position of the cursor within the text field.

Sandbox: https://codesandbox.io/s/cant-add-space-to-muis-textfield-erpvc?file=/src/App.js

```<code>import React from "react";
import { DataGrid } from "@mui/x-data-grid";
import TextField from "@mui/material/TextField";
import "./styles.css";

export default function App() {
  const rows = [
    { id: 1, "Column 1": 1, "Column 2": 2 },
    { id: 2, "Column 1": 3, "Column 2": 4 },
    { id: 3, "Column 1": 4, "Column 2": 5 }
  ];
  const createColumn = (name) => {
    return {
      field: name,
      align: "center",
      editable: true,
      sortable: false
    };
  };
  const columns = [
    createColumn("Column 1"),
    createColumn("Column 2"),
    {
      field: "Add a split",
      width: 225,
      sortable: false,
      renderHeader: (params) => {
        return (
          <TextField
            placeholder="Enter column name"
            size="small"
            onKeyDown={(event) => console.log("Key down: ", event.key)}
            onKeyUp={(event) => console.log("Key up: ", event.key)}
            onKeyPress={(event) => console.log("Key press: ", event.key)}
          />
        );
      }
    }
  ];

  return (
    <div className="App">
      <DataGrid
        className="App-data-grid"
        rows={rows}
        columns={columns}
        disableSelectionOnClick
        disableColumnMenu
      />
    </div>
  );
}
</code>```

答:
In the accessibility portion of the documentation, you can find keyboard navigation details for the data grid. Arrow keys are used to navigate between cells and space (among other things) is used to navigate to the next scrollable page. You can find the handling of those keys in the handleCellNavigationKeyDown function in useGridKeyboardNavigation.ts.

When a key down event happens for one of those special navigation characters, MUI calls event.preventDefault() which in your case prevents the key from having its default effect within the input. You can prevent that by using event.stopPropagation() within the TextField onKeyDown such that the event never reaches the grid's keyboard navigation handling code. Keep in mind though that by doing this, you may be harming some of the keyboard accessibility features.

Here's a modified version of your sandbox demonstrating this: https://codesandbox.io/s/cant-add-space-to-muis-textfield-33joy?file=/src/App.js:863-902.

Body:
When I place one of MUI's Text Field components inside the column header of a Data Grid component, I'm unable to type a space into the text field. Similarly, if I press the right or left arrow key while the text field has focus, the text field loses focus rather than changing the position of the cursor within the text field.

Sandbox: https://codesandbox.io/s/cant-add-space-to-muis-textfield-erpvc?file=/src/App.js

import React from "react";
import { DataGrid } from "@mui/x-data-grid";
import TextField from "@mui/material/TextField";
import "./styles.css";

export default function App() {
  const rows = [
    { id: 1, "Column 1": 1, "Column 2": 2 },
    { id: 2, "Column 1": 3, "Column 2": 4 },
    { id: 3, "Column 1": 4, "Column 2": 5 }
  ];
  const createColumn = (name) => {
    return {
      field: name,
      align: "center",
      editable: true,
      sortable: false
    };
  };
  const columns = [
    createColumn("Column 1"),
    createColumn("Column 2"),
    {
      field: "Add a split",
      width: 225,
      sortable: false,
      renderHeader: (params) => {
        return (
          <TextField
            placeholder="Enter column name"
            size="small"
            onKeyDown={(event) => console.log("Key down: ", event.key)}
            onKeyUp={(event) => console.log("Key up: ", event.key)}
            onKeyPress={(event) => console.log("Key press: ", event.key)}
          />
        );
      }
    }
  ];

  return (

      <DataGrid
        className="App-data-grid"
        rows={rows}
        columns={columns}
        disableSelectionOnClick
        disableColumnMenu
      />

  );
}


问:
Can't modify a string in C++ array
Trying to learn datastructures, I made this class for a stack. It works just fine with integers but it throws a mysterious error with strings.
The class List is the API for my stack. Its meant to resize automatically when it reaches the limit. The whole code is just for the sake of learning but the error I get doesn't make any sense and it happens somewhere in some assembly code.</p>
```<code>#include <iostream>
#include<string>
using namespace std;

class List {
private:

    int N = 0;
    string* list = new string[1];
    void resize(int sz) {
        max = sz;
        string* oldlist = list;
        string* list = new string[max];
        for (int i = 0; i < N; i++) {
            list[i] = oldlist[i];
        }

    }
    int max = 1;
public:
    void push(string str) {
        if (N == max) {
            resize(2 * N);
        }
        cout << max << endl;
        list[N] = str;
        N++;
    }
    void pop() {
        cout << list[--N] << endl;
    }

};
int main()
{

    string in;
    List list;
    while (true) {
        cin >> in;
        if (in == "-") {
            list.pop();
        }
        else {
            list.push(in);
        }
    }
}
</code>```

答:
string* list = new string[max]; in the resize method defines a new variable named list that "shadows", replaces, the member variable list. The member list goes unchanged and the local variable list goes out of scope at the end of the function, losing all of the work.

To fix: Change

```<code>string* list = new string[max];
</code>```

to

```<code>list = new string[max];
</code>```

so that the function will use the member variable.

Don't forget to delete[] oldlist; when you're done with it to free up the storage it points at.

Title: Can't modify a string in C++ array

Body:
Trying to learn datastructures, I made this class for a stack. It works just fine with integers but it throws a mysterious error with strings.
The class List is the API for my stack. Its meant to resize automatically when it reaches the limit. The whole code is just for the sake of learning but the error I get doesn't make any sense and it happens somewhere in some assembly code.

#include <iostream>
#include<string>
using namespace std;

class List {
private:

    int N = 0;
    string* list = new string[1];
    void resize(int sz) {
        max = sz;
        string* oldlist = list;
        string* list = new string[max];
        for (int i = 0; i < N; i++) {
            list[i] = oldlist[i];
        }

    }
    int max = 1;
public:
    void push(string str) {
        if (N == max) {
            resize(2 * N);
        }
        cout << max << endl;
        list[N] = str;
        N++;
    }
    void pop() {
        cout << list[--N] << endl;
    }

};
int main()
{

    string in;
    List list;
    while (true) {
        cin >> in;
        if (in == "-") {
            list.pop();
        }
        else {
            list.push(in);
        }
    }
}

Body:
string* list = new string[max]; in the resize method defines a new variable named list that "shadows", replaces, the member variable list. The member list goes unchanged and the local variable list goes out of scope at the end of the function, losing all of the work.

To fix: Change

string* list = new string[max];

to

list = new string[max];

so that the function will use the member variable.

Don't forget to delete[] oldlist; when you're done with it to free up the storage it points at.


问:
Does union of bit fields make any sense
I recently came across a third party code snippet inside our application that does not make any sense to me. What puzzled me first it that it has been in production for at least 10 years and seemed to work. It is basically a union of bit fields:

```<code>union
{
    unsigned longitude : 2;         //!< status of the longitude (offset: 0)
    unsigned latitude : 2;          //!< status of the latitude (offset: 2)
    unsigned xPosition : 2;         //!< status of the x position relative to starting position (offset: 4)
    unsigned yPosition : 2;         //!< status of the y position relative to starting position (offset: 6)
    // ... Many more 2-bit fields... Total 26 fields
    unsigned reserved : 12;
    unsigned long status[2];            //!< raw status data
} status;
</code>```

I am pretty sure that this is a bug and what the author really wanted to write was:

```<code>union
{
    struct
    {
        unsigned longitude : 2;         //!< status of the longitude (offset: 0)
        unsigned latitude : 2;          //!< status of the latitude (offset: 2)
        unsigned xPosition : 2;         //!< status of the x position relative to starting position (offset: 4)
        unsigned yPosition : 2;         //!< status of the y position relative to starting position (offset: 6)
        // ... Many more 2-bit fields... Total 26 fields
        unsigned reserved : 12;
    };
    unsigned status[2];         //!< raw status data (should not be long!)
} status;
</code>```

The reason it was kind of working is that only one of those 26 bit fields was actually used!
But this bug made raised a few questions:

Is the compiler required to use the same first 2 bits of the same unsigned for all fields (despite what the comments say)?

Is there any real usage for a union of bit fields? I cannot think of any situation where this would make sense.

If that doesn't make any sense, how come that no compilers we are using (neither Clang, GCC nor MSVC) were issuing any warning?

答:
Is the compiler required to use the same first 2 bits of the same unsigned for all fields (despite what the comments say)?

No. C 2018 6.7.2.1 says “An implementation may allocate any addressable storage unit large enough to hold a bit-field… The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined…”

It does not say the addressable storage unit will be the same for all bit-fields of the same size. If it did, then all the union bit-field members of the same size would have to use the same bits, and certainly any reasonable C implementation would do so.

However, consider bit-fields of different sizes. It is reasonable that a compiler would allocate a one-byte storage unit for a bit-field of 2 bits and a four-byte storage unit for a bit-field of 17 bits. If it is a little-endian system and puts the bits in high-order to low-order, then the 2-bit field would be in bits 27 and 26 of byte 0, and the 17-bit field would be in all bits of bytes 3 and 2 (bits 231 to 216 of the four-byte little-endian storage unit) and bit 27 of byte 1 (bit 215 of the storage unit). So there would be no overlap between these two union members.

Is there any real usage for a union of bit fields? I cannot think of any situation where this would make sense.

Sure, I might have some field in a data structure that sometimes needs to store a 17-bit fromitz number and other times needs to store a 13-bit gizmo number. Unions were originally for storing one thing or another, not for reinterpreting bits of one type as another type.

Title: Does union of bit fields make any sense

Body:
I recently came across a third party code snippet inside our application that does not make any sense to me. What puzzled me first it that it has been in production for at least 10 years and seemed to work. It is basically a union of bit fields:

union
{
    unsigned longitude : 2;         //!< status of the longitude (offset: 0)
    unsigned latitude : 2;          //!< status of the latitude (offset: 2)
    unsigned xPosition : 2;         //!< status of the x position relative to starting position (offset: 4)
    unsigned yPosition : 2;         //!< status of the y position relative to starting position (offset: 6)
    // ... Many more 2-bit fields... Total 26 fields
    unsigned reserved : 12;
    unsigned long status[2];            //!< raw status data
} status;

I am pretty sure that this is a bug and what the author really wanted to write was:

union
{
    struct
    {
        unsigned longitude : 2;         //!< status of the longitude (offset: 0)
        unsigned latitude : 2;          //!< status of the latitude (offset: 2)
        unsigned xPosition : 2;         //!< status of the x position relative to starting position (offset: 4)
        unsigned yPosition : 2;         //!< status of the y position relative to starting position (offset: 6)
        // ... Many more 2-bit fields... Total 26 fields
        unsigned reserved : 12;
    };
    unsigned status[2];         //!< raw status data (should not be long!)
} status;

The reason it was kind of working is that only one of those 26 bit fields was actually used!
But this bug made raised a few questions:

Is the compiler required to use the same first 2 bits of the same unsigned for all fields (despite what the comments say)?

Is there any real usage for a union of bit fields? I cannot think of any situation where this would make sense.

If that doesn't make any sense, how come that no compilers we are using (neither Clang, GCC nor MSVC) were issuing any warning?


问:
utilities of AdWhirl over other ads Network
Can anyone tell me what are the advantages of using Adwhirl in comparism to AdMob,Millenial,Google AdSense for Mobile Applications,ZestADZ.Is there any disadvantage if i use AdMob or ZestADZ instead of AdWhirl...

with regards
Anshuman

答:
Question is off-topic, but the advantage is that Adwhirl precisely rotate between all those ads providers for you.

When one doesn't provide any ad, it will display another ad from another network.

Nevertheless, adwhirl API is really poorly documented and I would say "for experts" only. It took me quite a lot of time to make it working with admob,millenia and two others. And the result gave me the feeling of a week app.

I decided to add these feature myself, rotating ads from 2 main providers that pay well per click and have good geographic coverage (mobfox and admob).

But now, I am not even sure adwhirl is still actively maintained by admob, and moreover, mobfox or admob allow for a "backfill" option that does almost the same, they provide ads from other networks when they don't have any ad for you. For admob it's google ads, and mobfox allows ads from admob.

Regards,
 Stéphane