问:
public ressources not accessible
I'm tring to access the bundles directory (which is located in : /usr/src/app/public/bundles) of my symfony project.
But, all files in public dir can't be accessed with my navigator. eg:

```<code>Request URL: http://localhost:8080/bundles/easyadmin/app.css
Request Method: GET
Status Code: 404 Not Found
</code>```

The file exists...

This is my nginx config :

```<code>server {
    server_name ~.*;

    location / {
        root /usr/src/app;
        try_files $uri /index.php$is_args$args;
    }

    client_max_body_size 100m;

    location ~ ^/index\.php(/|$) {
        if ($request_method ~* "(GET|POST|PATCH|DELETE)") {
            add_header "Access-Control-Allow-Origin" '*' always;
        }

        # Preflighted requests
        if ($request_method = OPTIONS ) {
            add_header "Access-Control-Allow-Origin" '*' always;
            add_header "Access-Control-Allow-Methods" "GET, POST, PATCH, DELETE, OPTIONS, HEAD";
            add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
            return 200;
        }

        fastcgi_pass php:9000;
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        fastcgi_read_timeout 600;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME /usr/src/app/public/index.php;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
    location ~ \.php$ {
        return 404;
    }

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;
}
</code>```

I don't know what is missconfigured...

答:
Without seeing any error log I can just guess the issue but lets check directories you are using.

First of all try to avoid root in locations.

Putting root inside of a location block will work and it’s perfectly valid. What’s wrong is when you start adding location blocks. If you add a root to every location block then a location block that isn’t matched will have no root. Therefore, it is important that a root directive occur prior to your location blocks, which can then override this directive if they need to.

The configuration should look like this:

```<code>root /usr/src/app/public/;
location / {
        try_files $uri /index.php$is_args$args;
    }
</code>```

Your location is missing the public directory. So why do see the 404:

For this request http://localhost:8080/bundles/easyadmin/app.css with your configuration NGINX will look into /usr/src/app/ for /bundles/easyadmin/app.css. And it will not be able to find it. But /usr/src/app/public/bundles/easyadmin/app.css` will be a valid path and should result in 200 OK.

Title: public ressources not accessible

Body:
I'm tring to access the bundles directory (which is located in : /usr/src/app/public/bundles) of my symfony project.
But, all files in public dir can't be accessed with my navigator. eg:

Request URL: http://localhost:8080/bundles/easyadmin/app.css
Request Method: GET
Status Code: 404 Not Found

The file exists...

This is my nginx config :

server {
    server_name ~.*;

    location / {
        root /usr/src/app;
        try_files $uri /index.php$is_args$args;
    }

    client_max_body_size 100m;

    location ~ ^/index\.php(/|$) {
        if ($request_method ~* "(GET|POST|PATCH|DELETE)") {
            add_header "Access-Control-Allow-Origin" '*' always;
        }

        # Preflighted requests
        if ($request_method = OPTIONS ) {
            add_header "Access-Control-Allow-Origin" '*' always;
            add_header "Access-Control-Allow-Methods" "GET, POST, PATCH, DELETE, OPTIONS, HEAD";
            add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
            return 200;
        }

        fastcgi_pass php:9000;
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        fastcgi_read_timeout 600;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME /usr/src/app/public/index.php;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
    location ~ \.php$ {
        return 404;
    }

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;
}

I don't know what is missconfigured...

Body:
Without seeing any error log I can just guess the issue but lets check directories you are using.

First of all try to avoid root in locations.

Putting root inside of a location block will work and it’s perfectly valid. What’s wrong is when you start adding location blocks. If you add a root to every location block then a location block that isn’t matched will have no root. Therefore, it is important that a root directive occur prior to your location blocks, which can then override this directive if they need to.

The configuration should look like this:

root /usr/src/app/public/;
location / {
        try_files $uri /index.php$is_args$args;
    }

Your location is missing the public directory. So why do see the 404:

For this request http://localhost:8080/bundles/easyadmin/app.css with your configuration NGINX will look into /usr/src/app/ for /bundles/easyadmin/app.css. And it will not be able to find it. But /usr/src/app/public/bundles/easyadmin/app.css` will be a valid path and should result in 200 OK.


来源: stackexchange

问:
Why do my $PATH environment always reset after I open a new terminal on my mac?
Usually I will nano .zsh_profile
Then I will edit the path

```<code>#PYTHON
export PATH=/Users/ffff/Library/Python/3.8/bin:$PATH

# JAVA
export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$JAVA_HOME/bin:$PATH

#ANDROID
export ANDROID_HOME=/Users/ffff/Library/Android/sdk
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/tools/bin:$PATH
</code>```

then I will save and exit
Then I will

```<code>source .zsh_profile
</code>```

I will test the Java and ADB all is good, but one I open a new Terminal from my mac, it will say ADB and JAVA and Android_HOME not found

Why is it not persist? Did I miss out anything? My mac version is 12.2.1

答:
The .zsh_profile file, has no special meaning. This is probably a confusion form Bash, where the bash_profile is executes for login shells. In Zsh, that equivalent would be ~/.zprofile. You might have some code in your .zshrc  file, that overrides the PATH variable  with something else. Because, as oppsed to .zprofile, the .zshrc file gets executed for every interactive non-login shells.

So my advice, checkout .zshrc and see if there's something overriding the PATH there, if so, maybe you want to change that, and NOT to execute these commands you want to add for every time a shell is opened, you should put them in .zprofile, so they only get executed once at login.

ContentLicense: CC BY-SA 4.0

Body:
Usually I will nano .zsh_profile
Then I will edit the path

#PYTHON
export PATH=/Users/ffff/Library/Python/3.8/bin:$PATH

# JAVA
export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$JAVA_HOME/bin:$PATH

#ANDROID
export ANDROID_HOME=/Users/ffff/Library/Android/sdk
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/tools/bin:$PATH

then I will save and exit
Then I will

source .zsh_profile

I will test the Java and ADB all is good, but one I open a new Terminal from my mac, it will say ADB and JAVA and Android_HOME not found

Why is it not persist? Did I miss out anything? My mac version is 12.2.1


问:
Accessing GDB through Eclipse CDT
Can anyone tell me if there is  any way to access a standard GNU Debugger programatically through C++?</p>

答:
Programatically means i have to update the GUI based on the debugged values.

It sounds as if you want to update Eclipse GUI depending on what GDB observes in the inferior (being debugged) process.

That is exactly what CDT itself does.

If that is in fact your question (which is exceedingly unclear), then MI interface is likely not the right answer. The right answer would be: look in CDT source and extend/modify it as appropriate. (FWIW, CDT itself uses MI interface to talk to GDB).

ContentLicense: CC BY-SA 3.0

Title: Accessing GDB through Eclipse CDT


问:
Wrapping currency expression in a constant in SwiftUI
I am learning Swift and Xcode and there is a task that I have problems wrapping my mind around.
There are three places where I use value formatter:

```<code>format: .currency(code: Locale.current.currencyCode ?? "PLN")
</code>```

I packed it into a constant and it doesn't throw any errors:

```<code>let currencyFormatter = { (amount: Double) -> FloatingPointFormatStyle<Double>.Currency in
.currency(code: Locale.current.currencyCode ?? "PLN")
}
</code>```

The execution though does throw several errors (they don't change if I swap the closure to void instead of accepting Double):

```<code>Text(totalPerPerson, format: currencyFormatter)
</code>```

Some of the errors:
1.

```<code>Cannot convert value of type 'Double' to expected argument type '((Double) -> FloatingPointFormatStyle<Double>.Currency).FormatInput'
</code>```

```<code>Initializer 'init(_:format:)' requires that '((Double) -> FloatingPointFormatStyle<Double>.Currency).FormatInput' conform to 'Equatable'
</code>```

答:
It seems that there is another variant of a viable answer to this question that puts greater emphasis on the type of the constant:

```<code> let currencyFormatter: FloatingPointFormatStyle<Double>.Currency = .currency(code: Locale.current.currencyCode ?? "PLN")
</code>```

But wouldn't find it without @Asperi's help.

Body:
I am learning Swift and Xcode and there is a task that I have problems wrapping my mind around.
There are three places where I use value formatter:

format: .currency(code: Locale.current.currencyCode ?? "PLN")

I packed it into a constant and it doesn't throw any errors:

let currencyFormatter = { (amount: Double) -> FloatingPointFormatStyle<Double>.Currency in
.currency(code: Locale.current.currencyCode ?? "PLN")
}

The execution though does throw several errors (they don't change if I swap the closure to void instead of accepting Double):

Text(totalPerPerson, format: currencyFormatter)

Some of the errors:
1.

Cannot convert value of type 'Double' to expected argument type '((Double) -> FloatingPointFormatStyle<Double>.Currency).FormatInput'

Initializer 'init(_:format:)' requires that '((Double) -> FloatingPointFormatStyle<Double>.Currency).FormatInput' conform to 'Equatable'

Body:
It seems that there is another variant of a viable answer to this question that puts greater emphasis on the type of the constant:

 let currencyFormatter: FloatingPointFormatStyle<Double>.Currency = .currency(code: Locale.current.currencyCode ?? "PLN")

But wouldn't find it without @Asperi's help.


Title: Changing datetime to hour or minute difference using pandas

Body:
I have a dataframe that has a column in datetime type such as:

                date  id
0   02/04/2015 02:34   1
1   06/04/2015 12:34   2
2   09/04/2015 23:03   3
3   12/04/2015 01:00   4
4   15/04/2015 07:12   5
5   21/04/2015 12:59   6
6   29/04/2015 17:33   7
7   04/05/2015 10:44   8
8   06/05/2015 11:12   9
9   10/05/2015 08:52  10
10  12/05/2015 14:19  11
11  19/05/2015 19:22  12
12  27/05/2015 22:31  13
13  01/06/2015 11:09  14
14  04/06/2015 12:57  15
15  10/06/2015 04:00  16
16  15/06/2015 03:23  17
17  19/06/2015 05:37  18
18  23/06/2015 13:41  19
19  27/06/2015 15:43  20

I would like to change the date column reference such that
the first value 02/04/2015 02:34 will be 0, and the second one will be the difference between 06/04/2015 12:34 - 02/04/2015 02:34 = 6360 minutes or 106 Hours.

and so on. How can I change the column in pandas to something similar to the above explanation.

Thanks

Body:
Convert date column to datetime64 and use diff. After that, use dt accessor to floor your date by hour and get total_seconds and divide by 60 or 3600:

df['date'] = pd.to_datetime(df['date'], dayfirst=True)

df['hours'] = df['date'].diff().dt.floor('H').dt.total_seconds().div(3600).fillna(0).astype(int)
# OR
df['minutes'] = df['date'].diff().dt.floor('H').dt.total_seconds().div(60).fillna(0).astype(int)

Output:

>>> df
                  date  id  hours  minutes
0  2015-04-02 02:34:00   1      0        0
1  2015-04-06 12:34:00   2    106     6360
2  2015-04-09 23:03:00   3     82     4920
3  2015-04-12 01:00:00   4     49     2940
4  2015-04-15 07:12:00   5     78     4680
5  2015-04-21 12:59:00   6    149     8940
6  2015-04-29 17:33:00   7    196    11760
7  2015-05-04 10:44:00   8    113     6780
8  2015-05-06 11:12:00   9     48     2880
9  2015-05-10 08:52:00  10     93     5580
10 2015-05-12 14:19:00  11     53     3180
11 2015-05-19 19:22:00  12    173    10380
12 2015-05-27 22:31:00  13    195    11700
13 2015-06-01 11:09:00  14    108     6480
14 2015-06-04 12:57:00  15     73     4380
15 2015-06-10 04:00:00  16    135     8100
16 2015-06-15 03:23:00  17    119     7140
17 2015-06-19 05:37:00  18     98     5880
18 2015-06-23 13:41:00  19    104     6240
19 2015-06-27 15:43:00  20     98     5880


问:
Django model field custom validator returned value not saved
I have the following implementation for the phone number custom validation. It does the validation correctly, but the returned value (formatted) is not saved in the model instance. I don't use a custom form and data is entered from admin panel.

custom validator

```<code>def phone_number_validator(value):
    if value:
        value = value.strip()
        value = value.replace(' ', '')

        digits = []
        non_digits = []
        for c in value:
            if c.isdigit():
                digits.append(c)
            else:
                non_digits.append(c)

        if len(non_digits):
            raise ValidationError('Only numbers and spaces are allowed for this field.')
        elif len(digits) < 10 or len(digits) > 10:
            raise ValidationError('Phone number should be exactly 10 digits.')
        elif (not value.startswith('07')) and (not value.startswith('0')):
            raise ValidationError('Invalid phone number.')

        if value.startswith('07'):  # mobile number
            value = f'{value[0:3]} {value[3:6]} {value[6:]}'
        elif value.startswith('0'):  # landline
            value = f'{value[0:3]} {value[3:4]} {value[4:7]} {value[7:]}'
        print(value) #### here the correct format is displayed
        return value
</code>```

models.py

```<code>hotline = models.CharField(max_length=PHONE_NUMBER_LENGTH, validators=[phone_number_validator])
</code>```

答:
The purpose of a validator is only to check the value against a set of criteria. It is not meant to modify value.

Reference: https://docs.djangoproject.com/en/4.0/ref/validators/

Body:
I have the following implementation for the phone number custom validation. It does the validation correctly, but the returned value (formatted) is not saved in the model instance. I don't use a custom form and data is entered from admin panel.

custom validator

def phone_number_validator(value):
    if value:
        value = value.strip()
        value = value.replace(' ', '')

        digits = []
        non_digits = []
        for c in value:
            if c.isdigit():
                digits.append(c)
            else:
                non_digits.append(c)

        if len(non_digits):
            raise ValidationError('Only numbers and spaces are allowed for this field.')
        elif len(digits) < 10 or len(digits) > 10:
            raise ValidationError('Phone number should be exactly 10 digits.')
        elif (not value.startswith('07')) and (not value.startswith('0')):
            raise ValidationError('Invalid phone number.')

        if value.startswith('07'):  # mobile number
            value = f'{value[0:3]} {value[3:6]} {value[6:]}'
        elif value.startswith('0'):  # landline
            value = f'{value[0:3]} {value[3:4]} {value[4:7]} {value[7:]}'
        print(value) #### here the correct format is displayed
        return value

models.py

hotline = models.CharField(max_length=PHONE_NUMBER_LENGTH, validators=[phone_number_validator])


问:
Where is _CONF_DIR being loaded from?
newbie question, where is _CONF_DIR being loaded from in:

std::string const ConfigMgr::GetConfigPath()
{
    std::lock_guard<std::mutex> lock(_configLock);

#if AC_PLATFORM == AC_PLATFORM_WINDOWS
    return "configs/";
#else
    return std::string(_CONF_DIR) + "/";
#endif
}
```

assumed it was an environment variable / cmd line variable but adding -D_CONF_DIR="..." doesn't seem to be doing anything; seems to be defaulting to /usr/local/etc

答: The variable was generated from cmake, which generated it from the input variable "CONF_DIR" - i.e. one of  the arguments I passed to cmake was -DCONF_DIR="/root/azerothcore-wotlk/env/dist/etc".

Title: Where is _CONF_DIR being loaded from?

Body:
newbie question, where is _CONF_DIR being loaded from in:

std::string const ConfigMgr::GetConfigPath()
{
    std::lock_guard<std::mutex> lock(_configLock);

#if AC_PLATFORM == AC_PLATFORM_WINDOWS
    return "configs/";
#else
    return std::string(_CONF_DIR) + "/";
#endif
}

assumed it was an environment variable / cmd line variable but adding -D_CONF_DIR="..." doesn't seem to be doing anything; seems to be defaulting to /usr/local/etc


答:
here is my solution:

import pandas as pd
df = pd.DataFrame(date, columns=['date'])
df['sec'] = pd.to_datetime(df['date']).astype('int64') // 10**9
df['diff_in_sec'] = df['sec'] - df['sec'].iloc[0]
```
<p>first, convert the date column into the DateTime column then convert it to UNIX timestamp and then calculate the difference in seconds.
if you want it as minutes or hours just divide diff_in_sec by 60 or 3600 like this:</p>
```df['diff_in_hour'] = df['diff_in_sec'].div(3600)
```

Body:
here is my solution:

import pandas as pd
df = pd.DataFrame(date, columns=['date'])
df['sec'] = pd.to_datetime(df['date']).astype('int64') // 10**9
df['diff_in_sec'] = df['sec'] - df['sec'].iloc[0]

first, convert the date column into the DateTime column then convert it to UNIX timestamp and then calculate the difference in seconds.
if you want it as minutes or hours just divide diff_in_sec by 60 or 3600 like this:

df['diff_in_hour'] = df['diff_in_sec'].div(3600)


问:
Return value from Ajax callback?
I have a JavaScript class that handles queries to a local DB (on a WebOs device). Now what I want to do is, create a model with all my basic queries to simplify my code.

So first I create a function:

```<code>getLists: function(){
          this.query( 'SELECT * FROM lists ORDER BY rowID DESC', {
                onSuccess:  enyo.bind(this,function(data) { this.getData(data); } ),
                onError: function() { return false; } } );
   }
</code>```

And than I have my callback function which receives the data:

```<code>getData: function(data){
       return data;
   }
</code>```

Now what I would like to do, is call it like this from my app:

```<code>var data = getLists();
</code>```

The problem is, this is not returning the data from my callback function (getData). My question is how can I have "getLists" return the data from the callback?

Thank you

答:
You're thinking imperial: C follows B follows A. Forget about that.

AJAX and modern JavaScript works differently. You never say "get data now", you say "call X when data is available".

So the solution is to write some code which does something useful with the data. Let's call this function a. Instead of:

```<code>var data = conn.getData();
a( data );
b( data );
c( data );
</code>```

you do

```<code>conn.getData( a ); // a has to call b which calls c.
</code>```

Eventually, the data will be there and a will be called with data as an argument.

See? You don't chain calls to a() and b() as in traditional programming. Instead, you create functions that do what you want and pass those functions around.

Title: Return value from Ajax callback?

Body:
I have a JavaScript class that handles queries to a local DB (on a WebOs device). Now what I want to do is, create a model with all my basic queries to simplify my code.

So first I create a function:

getLists: function(){
          this.query( 'SELECT * FROM lists ORDER BY rowID DESC', {
                onSuccess:  enyo.bind(this,function(data) { this.getData(data); } ),
                onError: function() { return false; } } );
   }

And than I have my callback function which receives the data:

getData: function(data){
       return data;
   }

Now what I would like to do, is call it like this from my app:

var data = getLists();

The problem is, this is not returning the data from my callback function (getData). My question is how can I have "getLists" return the data from the callback?

Thank you

Body:
You're thinking imperial: C follows B follows A. Forget about that.

AJAX and modern JavaScript works differently. You never say "get data now", you say "call X when data is available".

So the solution is to write some code which does something useful with the data. Let's call this function a. Instead of:

var data = conn.getData();
a( data );
b( data );
c( data );

you do

conn.getData( a ); // a has to call b which calls c.

Eventually, the data will be there and a will be called with data as an argument.

See? You don't chain calls to a() and b() as in traditional programming. Instead, you create functions that do what you want and pass those functions around.


问:
Error in connecting Database(MongoDB) with express server
As soon as I am connecting my database with express using

```<code>const db = require("./config/mongoose");
</code>```

It shows error

```<code>

SyntaxError: Invalid or unexpected token
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:\Users\DELL\Documents\Vs Code Folders\Feelare\node_modules\whatwg-url\lib\url-state-machine.js:8:31)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
[nodemon] app crashed - waiting for file changes before starting...

</code>```

How can I get out of it?

答:
This type of error generally comes when you do not provide valid JSON data.

For ex:-

```<code>JSON.stringify({x:})
</code>```

return error like this

```<code>Uncaught SyntaxError: Unexpected token '}'
</code>```

Please check your provided JSON data again.

And after that you still get error please show your mongoose connection code.

Body:
As soon as I am connecting my database with express using

const db = require("./config/mongoose");

It shows error

SyntaxError: Invalid or unexpected token
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:\Users\DELL\Documents\Vs Code Folders\Feelare\node_modules\whatwg-url\lib\url-state-machine.js:8:31)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
[nodemon] app crashed - waiting for file changes before starting...

How can I get out of it?

Body:
This type of error generally comes when you do not provide valid JSON data.

For ex:-

JSON.stringify({x:})

return error like this

Uncaught SyntaxError: Unexpected token '}'

Please check your provided JSON data again.

And after that you still get error please show your mongoose connection code.


问:
Command Line zsh bad assignment error when setting an Alias
In my mac terminal, I am running the following command and getting the following error.

```<code>(base) jgeorge ~ % alias pip = 'python3 -m pip'
>>> zsh: bad assignment
</code>```

When i try editing my .zshrc file with the same line of code, I get the same error when I refresh my terminal. Not really sure what is going wrong here. I tried changing the alias to a different word but the error persists

答:
Open the file /Users/me/.zshrc [this is the file where you were trying to add the path for Python]

Look for the line that is missing a '', and add that ''. [most likely it's going to be the line you added with Python], so look there first.

Save your file and exit.

then in your terminal, run this command: source ~/.zshrc this will refresh your .zshrc file.

Body:
In my mac terminal, I am running the following command and getting the following error.

(base) jgeorge ~ % alias pip = 'python3 -m pip'
>>> zsh: bad assignment

When i try editing my .zshrc file with the same line of code, I get the same error when I refresh my terminal. Not really sure what is going wrong here. I tried changing the alias to a different word but the error persists


问:
How to place NS from Google Cloud in Namecheap?
My web app is on Google Cloud. I have the following NS on Google Cloud:

I followed this tutorial to setup dns: https://www.wpmentor.com/setup-domain-google-cloud-platform/ I'm using Namecheap.

Under step 3 Configure Name Server, there are some differences. Nameservers can be found on the "Advanced DNS" section instead of the "Domain" section like in this older tutorial. There is nothing about nameservers in the "Domain" section, so it's probably moved to "Advanced DNS".

But when I want to insert my NS in the "Advanced DNS" section, it asks me to provide IP addresses. I'm confused, should I find somewhere an IP address of ns-cloud-a1.googledomains.com. somewhere?

答:
To connect a domain to a third-party server via nameservers that you received from your hosting provider, you need to set these nameservers as Custom for your domain as mentioned by @John Hanley. You can do that in the following way:

After signing into your account, select the Domain tab and click the Manage button next to your domain in the list. Then find the Nameservers section and select Custom DNS from the drop-down menu.

After that, enter your hosting nameservers one by one in each line (if you need to set more than 2 nameservers, press the Add nameserver). When the nameservers are entered, save changes.

It may take about 24-48 hours for your domain to propagate after the nameservers update to be resolving properly all over the world.

NOTE: Some hosting providers may provide you with nameservers with IP addresses for them. Entering nameservers would be enough.

Refer How to Connect a Domain to a Server or Hosting for information.


问:
How to get every possible combination without changing position efficiently?
I have a list of 2D list which row number is 60 and column number is not fixed. Here, row numbers mean position. How to get every possible combination without changing position?

Let me explain with an example:
Let's make it shorter to understand. Let's assume, row number is 3 instead of 60.
List:

list_val = [[1, 2, 3], [2, 3], [5]]
```
<p>I want to get the combination:</p>
```{1, 2, 5}, {1, 3, 5}, {2, 2, 5}, {2, 3, 5}, {3, 2, 5}, {3, 3, 5}
```

For three, it should be easy to write three nested loops. But for 60, writing 60 nested loops is not a good idea. Is there any better efficient way to write code in python?

答:
What you're looking for is itertools.product() which implements it in a reasonably efficient way so that you don't need to reinvent it and it's fine for large iterables.

Why is that? It's implemented in C (1, 2) therefore the performance is faster than with your standard pure-Python implementation of the loops unless you use tricks that could achieve comparable speed.

Don't forget to unpack the iterable that has iterables you want to use with star/asterisk (*) for the function or supply it with multiple variables (product(one, two, three)), otherwise it'll behave differently.

>>> from itertools import product
>>> list(product(*[[1, 2, 3], [2,3], [5]]))
[(1, 2, 5), (1, 3, 5), (2, 2, 5), (2, 3, 5), (3, 2, 5), (3, 3, 5)]
>>>
```

Body:
I have a list of 2D list which row number is 60 and column number is not fixed. Here, row numbers mean position. How to get every possible combination without changing position?

Let me explain with an example:
Let's make it shorter to understand. Let's assume, row number is 3 instead of 60.
List:

list_val = [[1, 2, 3], [2, 3], [5]]

I want to get the combination:

{1, 2, 5}, {1, 3, 5}, {2, 2, 5}, {2, 3, 5}, {3, 2, 5}, {3, 3, 5}

For three, it should be easy to write three nested loops. But for 60, writing 60 nested loops is not a good idea. Is there any better efficient way to write code in python?


问:
Convert Text-Formatted "Day Name, Month Name, Date of Month, Year" to "YYYY-MM-DD" Date Format
I have an Excel sheet with thousands of dates saved in Text format, written the following way:

I want these cells to be converted into "YYYY-MM-DD" format. However, Excel cannot detect these cells as Date Format; hence, when I try to use the "Format Cells" (or Ctrl+1) to change the date format, it does not work and stays the same. I need them to be in "YYYY-MM-DD" because I will be using the date in multiple functions throughout my workbook and the Text formatted Dates do not allow that.

答:
In addition to Harun's answer. For if one does not have Windows one could use:
=TEXT(MID(A1,FIND(",",A1)+2,LEN(A1)),"yyyy-mm-dd")


问:
Why do I get a multiple definition error while linking?
I use these two files here and here.

I created a class in two separate files:

modul1.h

```<code>#ifndef MODUL1_H
#define MODUL1_H

#include <iostream>
#include <fstream>

#include "easylogger.h"

class Modul1
{
    public:
        Modul1(std::string name);
    protected:
    private:
        easylogger::Logger *log;
};

#endif // MODUL1_H
</code>```

and modul1.cpp

```<code>#include "modul1.h"

Modul1::Modul1(std::string name):log(new easylogger::Logger(name))
{
    //ctor
    //std::ofstream *f = new std::ofstream(name.c_str(), std::ios_base::app);
    //log->Stream(*f);
    //log->Level(easylogger::LEVEL_DEBUG);
    //LOG_DEBUG(*log, "ctor ende!");
}
</code>```

Now I want to use this class in another file (main.cpp):

```<code>#include "modul1.h"

int main()
{
    std::cout << "Hello world!" << std::endl;
    Modul1 mod1("test.log");
    return 0;
}
</code>```

When I compile it with the following Makefile, I get a "multiple definition of..." error:

g++ main.o modul1.o -o main

modul1.o: In function easylogger::Logger::Format(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&):

modul1.cpp:(.text+0x0): multiple definition of
easylogger::Logger::Format(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)

main.o:main.cpp:(.text+0x0): first defined here

modul1.o: In function easylogger::Logger::WriteLog(easylogger::LogLevel, easylogger::Logger*, char const*, unsigned int, char const*, char const*):
modul1.cpp:(.text+0x2a): multiple definition of
easylogger::Logger::WriteLog(easylogger::LogLevel, easylogger::Logger*, char const*, unsigned int, char const*, char const*)

main.o:main.cpp:(.text+0x2a): first defined here

collect2: ld returned 1 exit status

(At first I compiled it with code::blocks and got the same error)

How can I modify my Modul1 in order not to get this linking error? I don't think it is important, but I am using some Ubuntu 64bit with g++ 4.4.3

Makefile:

```<code>CC=g++
CFLAGS=-c -Wall

all: log_test

log_test: main.o easylogger.h modul1.o
    $(CC) main.o modul1.o -o main

main.o: main.cpp modul1.h
    $(CC) $(CFLAGS) main.cpp

modul1.o: modul1.cpp modul1.h
    $(CC) $(CFLAGS) modul1.cpp
</code>```

答:
This isn't a solution for your specific case, but I will mention for others finding this topic it as it can produce the same error.

If you're running a compiler, and leave out the -o flag, and a copy of your binary already exists, the compiler will try to link the new object file with that binary.  Both the new object file and the binary it will have their own main and various other symbols, and give you warnings about them.

```<code>> g++ MyTest.cxx -g MyTest -I.
/usr/bin/ld: MyTest: in function `main':
/t/proj/MyTest/MyTest.cxx:172: multiple definition of `main'; /tmp/cccYfx2V.o:/t/proj/MyTest/MyTest.cxx:172: first defined here
:
:
:
collect2: error: ld returned 1 exit status
> g++ MyTest.cxx -g -o MyTest -I.
>
</code>```

Note the second command has the -o option, and succeeds without comment.

Body:
I use these two files here and here.

I created a class in two separate files:

modul1.h

#ifndef MODUL1_H
#define MODUL1_H

#include <iostream>
#include <fstream>

#include "easylogger.h"

class Modul1
{
    public:
        Modul1(std::string name);
    protected:
    private:
        easylogger::Logger *log;
};

#endif // MODUL1_H

and modul1.cpp

#include "modul1.h"

Modul1::Modul1(std::string name):log(new easylogger::Logger(name))
{
    //ctor
    //std::ofstream *f = new std::ofstream(name.c_str(), std::ios_base::app);
    //log->Stream(*f);
    //log->Level(easylogger::LEVEL_DEBUG);
    //LOG_DEBUG(*log, "ctor ende!");
}

Now I want to use this class in another file (main.cpp):

#include "modul1.h"

int main()
{
    std::cout << "Hello world!" << std::endl;
    Modul1 mod1("test.log");
    return 0;
}

When I compile it with the following Makefile, I get a "multiple definition of..." error:

g++ main.o modul1.o -o main

modul1.o: In function easylogger::Logger::Format(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&):

modul1.cpp:(.text+0x0): multiple definition of
easylogger::Logger::Format(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)

main.o:main.cpp:(.text+0x0): first defined here

modul1.o: In function easylogger::Logger::WriteLog(easylogger::LogLevel, easylogger::Logger*, char const*, unsigned int, char const*, char const*):
modul1.cpp:(.text+0x2a): multiple definition of
easylogger::Logger::WriteLog(easylogger::LogLevel, easylogger::Logger*, char const*, unsigned int, char const*, char const*)

main.o:main.cpp:(.text+0x2a): first defined here

collect2: ld returned 1 exit status

(At first I compiled it with code::blocks and got the same error)

How can I modify my Modul1 in order not to get this linking error? I don't think it is important, but I am using some Ubuntu 64bit with g++ 4.4.3

Makefile:

CC=g++
CFLAGS=-c -Wall

all: log_test

log_test: main.o easylogger.h modul1.o
    $(CC) main.o modul1.o -o main

main.o: main.cpp modul1.h
    $(CC) $(CFLAGS) main.cpp

modul1.o: modul1.cpp modul1.h
    $(CC) $(CFLAGS) modul1.cpp

Body:
This isn't a solution for your specific case, but I will mention for others finding this topic it as it can produce the same error.

If you're running a compiler, and leave out the -o flag, and a copy of your binary already exists, the compiler will try to link the new object file with that binary.  Both the new object file and the binary it will have their own main and various other symbols, and give you warnings about them.

> g++ MyTest.cxx -g MyTest -I.
/usr/bin/ld: MyTest: in function `main':
/t/proj/MyTest/MyTest.cxx:172: multiple definition of `main'; /tmp/cccYfx2V.o:/t/proj/MyTest/MyTest.cxx:172: first defined here
:
:
:
collect2: error: ld returned 1 exit status
> g++ MyTest.cxx -g -o MyTest -I.
>

Note the second command has the -o option, and succeeds without comment.


问:
rock paper scissor python program input error

import random

def rpc():
    a = ["rock", "paper", "scissor"]

    b = random.choice(a)

    print(b)

    userinput = input('please type rock, paper or scissor:')
    if userinput == "":
        print("please print the right thing")
        rpc()

    if userinput != "rock":
        print("type the right thing!")
        rpc()

    if userinput != "paper":
        print("type the right thing!")
        rpc()

    if userinput != "scissor":
        print("type the right thing!")
        rpc()

    while b == userinput:
        print("it is a draw, do you want to play another one?")
        c = input("type 'y' if you want to play one more time or press 'n': ")
        if c == 'y':
            rpc()
        elif c =='n':
            break
        else:
            print("print the right words please")

    if b == 'rock' and userinput == 'paper':
        print("you win!")
        rpc()

    elif b == 'rock' and userinput == 'scissor':
        print("you lost")
        rpc()

    elif b == 'paper' and userinput == 'scissor':
        print("you win!")
        rpc()

    elif b == 'paper' and userinput == 'rock':
        print("you lost!")
        rpc()

    elif b == 'scissor' and userinput == 'rock':
        print("you win!")
        rpc()

    elif b == 'scissor' and userinput == 'paper':
        print("you lost!")
        rpc()

rpc()
```

This is my code for rock paper and scissor, it's pretty simple but when I run my code and input my rock, paper and scissor, I get my please print the right thing statement, O have no idea why it's happening, any help would be wonderful, thank you!

答:
```<code>import random
def winner(riya,siya):
    if (riya==siya):
        return None
    elif (riya=="s"):
        if (siya=="p"):
            return False
        elif(siya=="k"):
            return True
    elif (riya=="p"):
        if (siya=="s"):
            return False
        elif (siya=="k"):
            return True
    elif (riya=="k"):
        if (siya=="s"):
            return True
        elif (siya=="p"):
            return False

print("riya pick: stone(s) paper(p) sessior(k)")
a= random.randint(1,3)
if a==1:
    riya="s"
elif a==2:
    riya="p"
elif a==3:
    riya="k"
siya=input(" siya pick: stone(s) paper(p) sessior(k)")
b=winner(riya,siya)
print(f"riya pick{riya}")
print(f"siya pick {siya}")
if b==None:
    print("tie")
elif b:
    print("winner")`enter code here`
else:enter code here
    print("loose")
</code>```

Body:
import random

def rpc():
    a = ["rock", "paper", "scissor"]

    b = random.choice(a)

    print(b)

    userinput = input('please type rock, paper or scissor:')
    if userinput == "":
        print("please print the right thing")
        rpc()

    if userinput != "rock":
        print("type the right thing!")
        rpc()

    if userinput != "paper":
        print("type the right thing!")
        rpc()

    if userinput != "scissor":
        print("type the right thing!")
        rpc()

    while b == userinput:
        print("it is a draw, do you want to play another one?")
        c = input("type 'y' if you want to play one more time or press 'n': ")
        if c == 'y':
            rpc()
        elif c =='n':
            break
        else:
            print("print the right words please")

    if b == 'rock' and userinput == 'paper':
        print("you win!")
        rpc()

    elif b == 'rock' and userinput == 'scissor':
        print("you lost")
        rpc()

    elif b == 'paper' and userinput == 'scissor':
        print("you win!")
        rpc()

    elif b == 'paper' and userinput == 'rock':
        print("you lost!")
        rpc()

    elif b == 'scissor' and userinput == 'rock':
        print("you win!")
        rpc()

    elif b == 'scissor' and userinput == 'paper':
        print("you lost!")
        rpc()

rpc()

This is my code for rock paper and scissor, it's pretty simple but when I run my code and input my rock, paper and scissor, I get my please print the right thing statement, O have no idea why it's happening, any help would be wonderful, thank you!


问:
Gradle for this Spring Boot project + jsp
Im using Gradle for this Spring boot project and my task is to create another jsp file , for example : index.jsp and do something that Spring boot can generate that index.jsp

My problem is when i create index.jsp in webapp -> WEB_INF -> index.jsp
it only return the message 'index' instead of what is in file index.

Application.java

```<code>package edu.msudenver.tsp.website;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

PledgeController.java

```<code>package edu.msudenver.tsp.website.controllers;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PledgeController {

    @GetMapping("/hello")
    public String getHelloMessage() {
        return "index";
    }
}
</code>```

Application.properties

```<code>spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
</code>```

build.gradle

```<code>buildscript {
    ext {
        springBootVersion = '1.5.6.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {

    compile('org.springframework.boot:spring-boot-starter-web')
    providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
    testCompile('org.springframework.boot:spring-boot-starter-test')

}
</code>```

index.jsp

```<code>> <%@ page contentType="text/html;charset=UTF-8" language="java" %>
> <html> <head>
>     <title>Hello Spring mvc</title> </head> <body>
</code>```

答: I had the same issue. It's not about the java code. The only solution I found was switching to maven. The only change was build.gradle -> pom.xml, and nothing else in  the controller or jsp file, what you have there is correct.

Body:
Im using Gradle for this Spring boot project and my task is to create another jsp file , for example : index.jsp and do something that Spring boot can generate that index.jsp

My problem is when i create index.jsp in webapp -> WEB_INF -> index.jsp
it only return the message 'index' instead of what is in file index.

Application.java

package edu.msudenver.tsp.website;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

PledgeController.java

package edu.msudenver.tsp.website.controllers;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PledgeController {

    @GetMapping("/hello")
    public String getHelloMessage() {
        return "index";
    }
}

Application.properties

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

build.gradle

buildscript {
    ext {
        springBootVersion = '1.5.6.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {

    compile('org.springframework.boot:spring-boot-starter-web')
    providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
    testCompile('org.springframework.boot:spring-boot-starter-test')

}

index.jsp

> <%@ page contentType="text/html;charset=UTF-8" language="java" %>
>
>     <title>Hello Spring mvc</title>


问:
Checking if Inserting values in order into an initially empty minimum binary heap is correct
Can someone tell me if I have produced the right minimum binary heap after inserting these values in order into an initially empty minimum binary heap?

[23, 41, 19, 59, 10, 15, 40]

答:
Yes. That is the correct result for that input.

The heap evolves as follows:

       23
```
<pre class="lang-none prettyprint-override"><code>      _23
     /
   41
</code>```

      _19_
     /    \
   41      23
```
<pre class="lang-none prettyprint-override"><code>      _19_
     /    \
   41      23
  /
 59
</code>```

      _10_
     /    \
   19      23
  /  \
 59  41
```
<pre class="lang-none prettyprint-override"><code>      _10_
     /    \
   19      15
  /  \    /
 59  41  23
</code>```

      _10_
     /    \
   19      15
  /  \    /  \
 59  41  23  40
```

Body:
Yes. That is the correct result for that input.

The heap evolves as follows:

       23

      _23
     /
   41

      _19_
     /    \
   41      23

      _19_
     /    \
   41      23
  /
 59

      _10_
     /    \
   19      23
  /  \
 59  41

      _10_
     /    \
   19      15
  /  \    /
 59  41  23

      _10_
     /    \
   19      15
  /  \    /  \
 59  41  23  40


问:
Django 4 how to do annotation over boolean field queryset?
I found this discussion about annotation over querysets. I wonder, if that ever got implemented?

When I run the following annotation:

```<code>x = Isolate.objects.all().annotate(sum_shipped=Sum('shipped'))
x[0].sum_shipped
>>> True
</code>```

shipped is a boolean field, so I would expect here the number of instances where shipped is set to True. Instead, I get True or 1. That is pretty inconvenient behaviour.

There is also this discussion on stackoverflow. However, this only covers django 1.

I would expect something like Sum([True, True, False]) -> 2.
Instead, True is returned.

Seems this was not touched since then. Is that discussion in the second link still the state-of-the-art ???

Is there a better way to do statistics with the content of the database than this, now that Django is in version 4?

My current database is sqlite3 for development and testing, but will be Postgres in production. I would very much like to get database independent results.

SUM(bool_field) on Oracle will return 1 also, because bools in Oracle are just a bit (1 or 0). Postgres has a specific bool type, and you can't sum a True/False without an implicit conversion to int. This is why I say SUM(bool) is only accidentally supported for a subset of databases. The field type that is returned is based on the backend get_db_converters and the actual values that come back.

Example model

```<code>class Isolate(models.Model):
    isolate_nbr = models.CharField(max_length=10, primary_key=True)
    growing = models.BooleanField(default=True)
    shipped = models.BooleanField(default=True)
    ....
</code>```

答:
I think you have a few options here, an annotate is not one of them at this time.

from django.db.models import Sum, Count

# Use aggregate with a filter
print(Isolate.objects.filter(shipped=True).aggregate(Sum('shipped')))

# Just filter then get the count of the queryset
print(Isolate.objects.filter(shipped=True).count())

# Just use aggregate without filter (this will only aggregate/Sum the True values)
print(Isolate.objects.aggregate(Sum('shipped')))

# WON'T WORK: annotate will only annotate on that row whatever that row's value is, not the aggregate across the table
print(Isolate.objects.annotate(sum_shipped==Count('shipped')).first().sum_shipped)
```

Body:
I found this discussion about annotation over querysets. I wonder, if that ever got implemented?

When I run the following annotation:

x = Isolate.objects.all().annotate(sum_shipped=Sum('shipped'))
x[0].sum_shipped
>>> True

shipped is a boolean field, so I would expect here the number of instances where shipped is set to True. Instead, I get True or 1. That is pretty inconvenient behaviour.

There is also this discussion on stackoverflow. However, this only covers django 1.

I would expect something like Sum([True, True, False]) -> 2.
Instead, True is returned.

Seems this was not touched since then. Is that discussion in the second link still the state-of-the-art ???

Is there a better way to do statistics with the content of the database than this, now that Django is in version 4?

My current database is sqlite3 for development and testing, but will be Postgres in production. I would very much like to get database independent results.

SUM(bool_field) on Oracle will return 1 also, because bools in Oracle are just a bit (1 or 0). Postgres has a specific bool type, and you can't sum a True/False without an implicit conversion to int. This is why I say SUM(bool) is only accidentally supported for a subset of databases. The field type that is returned is based on the backend get_db_converters and the actual values that come back.

Example model

class Isolate(models.Model):
    isolate_nbr = models.CharField(max_length=10, primary_key=True)
    growing = models.BooleanField(default=True)
    shipped = models.BooleanField(default=True)
    ....


问:
file_get_contents fails with "getaddrinfo failed: no address associated with hostname"
I'm trying to get the page from another host. I do as hph manual says:

```<code>    $page = file_get_contents('http://www.example.com/');
    echo $page;
</code>```

But it fails and in apache log i get the following:

```<code>[Mon Oct 12 18:58:47.676454 2015] [:error] [pid 2971] [client 127.0.0.1:49434] PHP Warning:  file_get_contents(): php_network_getaddresses: getaddrinfo failed: No address associated with hostname in /var/www/html/digest/ftry.php on line 2
[Mon Oct 12 18:58:47.704659 2015] [:error] [pid 2971] [client 127.0.0.1:49434] PHP Warning:  file_get_contents(http://www.example.com/): failed to open stream: php_network_getaddresses: getaddrinfo failed: No address associated with hostname in /var/www/html/digest/ftry.php on line 2
</code>```

While trying to figure out the reason of failure, I checked what nslookup says. When I run nslookup http://www.example.com/ it answers something like that:

```<code>nslookup http://www.example.com/
Server:         94.242.57.130
Address:        94.242.57.130#53

** server can't find http://www.example.com/: NXDOMAIN
</code>```

When I remove http:// from domain name it works fine, returns ip. But when I try to get file with file_get_contents without http://, it looks for the file in the local filesystem (and it's how it's supposed to be).

I've checked phpinfo, allow_url_fopen is On on both local and master levels. I've set the nameserver in my resolv.conf to 94.242.57.130 (nearest public dns).

答:
I met the same issue for file_get_contents even while allow_url_fopen is on. Also as CURL have a similar problem with the host.

Here is how the site owner solved this:

" Needed to add an extra A record to Directadmin, www was presented but not without www:

example.com. A xxx.xxx.xxx.xxx "

Body:
I'm trying to get the page from another host. I do as hph manual says:

    $page = file_get_contents('http://www.example.com/');
    echo $page;

But it fails and in apache log i get the following:

[Mon Oct 12 18:58:47.676454 2015] [:error] [pid 2971] [client 127.0.0.1:49434] PHP Warning:  file_get_contents(): php_network_getaddresses: getaddrinfo failed: No address associated with hostname in /var/www/html/digest/ftry.php on line 2
[Mon Oct 12 18:58:47.704659 2015] [:error] [pid 2971] [client 127.0.0.1:49434] PHP Warning:  file_get_contents(http://www.example.com/): failed to open stream: php_network_getaddresses: getaddrinfo failed: No address associated with hostname in /var/www/html/digest/ftry.php on line 2

While trying to figure out the reason of failure, I checked what nslookup says. When I run nslookup http://www.example.com/ it answers something like that:

nslookup http://www.example.com/
Server:         94.242.57.130
Address:        94.242.57.130#53

** server can't find http://www.example.com/: NXDOMAIN

When I remove http:// from domain name it works fine, returns ip. But when I try to get file with file_get_contents without http://, it looks for the file in the local filesystem (and it's how it's supposed to be).

I've checked phpinfo, allow_url_fopen is On on both local and master levels. I've set the nameserver in my resolv.conf to 94.242.57.130 (nearest public dns).


问:
Fetch Parent Record anyway even if child condition doesn't meet without using ON
I have two tables Employee and Address.
One Employee can have multiple Address.
Here I want to fetch 'active employee details' and 'active address details' of a particular emp_id. I can achieve this by below query :

```<code>Table Structure:
Employee(emp_id,name,is_active)
Address(add_id,emp_id,address,is_active)
</code>```

Query:

```<code>SELECT * FROM EMPLOYEE e
LEFT OUTER JOIN ADDRESS a
ON e.emp_id=a.emp_id
WHERE e.is_active='A'
AND a.is_active='A';
</code>```

Using above query it does not return any employee details if no active address. I want to return active employee details anyways even if it does not have any active address.

Note: as I am using Hibernate looking for a query without using ON . Only Where clause can be used here.

Kindly suggest.

答:
You need to put a.is_active='A' in ON clause not in WHERE clause

```<code>SELECT * FROM EMPLOYEE e
LEFT OUTER JOIN ADDRESS a
ON e.emp_id=a.emp_id AND a.is_active='A'
WHERE e.is_active='A';
</code>```

Since you have restrictions on using condition in on clause you can try below approach. It will return rows where address is active or address is not available (assuming that is_active column is never null in address table).

```<code>Schema and insert statements:

 create table EMPLOYEES(emp_id int, name varchar(20), is_active varchar(10));
 create table Address(add_id int ,emp_id int ,address varchar(50),is_active varchar(10));

 insert into EMPLOYEES values (1,'NAME1','A');
 insert into Address values(1,1,'addr1','N');
 insert into Address values(2,1,'addr1','N');
</code>```

Query:

```<code> SELECT * FROM EMPLOYEES e
 LEFT OUTER JOIN (select * from Address where is_active='A') a
 ON e.emp_id=a.emp_id
 WHERE e.is_active='A'
 AND (a.is_active='A' or a.is_active is null);
</code>```

Output:

EMP_ID
NAME
IS_ACTIVE
ADD_ID
EMP_ID
ADDRESS
IS_ACTIVE

1
NAME1
A
null
null
null
null

db<>fiddle here

Body:
I have two tables Employee and Address.
One Employee can have multiple Address.
Here I want to fetch 'active employee details' and 'active address details' of a particular emp_id. I can achieve this by below query :

Table Structure:
Employee(emp_id,name,is_active)
Address(add_id,emp_id,address,is_active)

Query:

SELECT * FROM EMPLOYEE e
LEFT OUTER JOIN ADDRESS a
ON e.emp_id=a.emp_id
WHERE e.is_active='A'
AND a.is_active='A';

Using above query it does not return any employee details if no active address. I want to return active employee details anyways even if it does not have any active address.

Note: as I am using Hibernate looking for a query without using ON . Only Where clause can be used here.

Kindly suggest.

Body:
You need to put a.is_active='A' in ON clause not in WHERE clause

SELECT * FROM EMPLOYEE e
LEFT OUTER JOIN ADDRESS a
ON e.emp_id=a.emp_id AND a.is_active='A'
WHERE e.is_active='A';

Since you have restrictions on using condition in on clause you can try below approach. It will return rows where address is active or address is not available (assuming that is_active column is never null in address table).

Schema and insert statements:

 create table EMPLOYEES(emp_id int, name varchar(20), is_active varchar(10));
 create table Address(add_id int ,emp_id int ,address varchar(50),is_active varchar(10));

 insert into EMPLOYEES values (1,'NAME1','A');
 insert into Address values(1,1,'addr1','N');
 insert into Address values(2,1,'addr1','N');

Query:

 SELECT * FROM EMPLOYEES e
 LEFT OUTER JOIN (select * from Address where is_active='A') a
 ON e.emp_id=a.emp_id
 WHERE e.is_active='A'
 AND (a.is_active='A' or a.is_active is null);

Output:

EMP_ID
NAME
IS_ACTIVE
ADD_ID
EMP_ID
ADDRESS
IS_ACTIVE

1
NAME1
A
null
null
null
null

db<>fiddle here


问:
Detecting CSS capabilities with Javascript
Is it possible to detect CSS support by using Javascript?

For example, is it possible to detect if the browser supports attribute selectors like this?

```<code>input[type='text'] { }
</code>```

答:
This is a bit speculative as I haven't tested it out, but I believe it would be possible via JS to add a style element followed by an element that it has an effect on, and then test the values:

Speculative untested code, may or may not work (jQuery used for brevity):

```<code>$('<style type="text/css" id="foo">input[type="text"]{ width: 10px; }</style>').appendTo('head');
$('<input type="text" id="bar">').appendTo('body');
if ($('#bar').width() == 10)
{
  //attr selector supported
}
$('#foo, #bar').remove();
</code>```

Body:
Is it possible to detect CSS support by using Javascript?

For example, is it possible to detect if the browser supports attribute selectors like this?

input[type='text'] { }

Body:
This is a bit speculative as I haven't tested it out, but I believe it would be possible via JS to add a style element followed by an element that it has an effect on, and then test the values:

Speculative untested code, may or may not work (jQuery used for brevity):

$('<style type="text/css" id="foo">input[type="text"]{ width: 10px; }</style>').appendTo('head');
$('<input type="text" id="bar">').appendTo('body');
if ($('#bar').width() == 10)
{
  //attr selector supported
}
$('#foo, #bar').remove();


问:
Unable to show Interstitial ad
I've gone through all the previous answers on this question , but my error and approach is slightly different from the previous questions'.

I've only three views in my app : Login , Signup and Main. I want to show an interstitial ad every time I transition from one view to another.

In order to accomplish this, I'm initializing , loading and showing the ad at the start of each view:

MainActivity.java

```<code>package com.brain.passive;

import android.content.Intent;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.*;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;

public class MainActivity extends AppCompatActivity {
    public EditText emailId, passwd;
    Button btnSignUp;
    TextView signIn;
    FirebaseAuth firebaseAuth;
    private FirebaseAuth.AuthStateListener authStateListener;
    private InterstitialAd mInterstitialAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        AdRequest adRequest = new AdRequest.Builder().build();

        InterstitialAd.load(this,"ca-app-pub-7147930999992278/2850010809", adRequest,
                new InterstitialAdLoadCallback() {
                    @Override
                    public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                        // The mInterstitialAd reference will be null until
                        // an ad is loaded.
                        mInterstitialAd = interstitialAd;
                        Log.i("Loaded", "onAdLoaded");
                    }

                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                        // Handle the error
                        Log.i("FailedError", loadAdError.getMessage());
                        mInterstitialAd = null;
                    }
                });

        mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
            @Override
            public void onAdDismissedFullScreenContent() {
                // Called when fullscreen content is dismissed.
                Log.d("TAG", "The ad was dismissed.");
            }

            @Override
            public void onAdFailedToShowFullScreenContent(AdError adError) {
                // Called when fullscreen content failed to show.
                Log.d("TAG", "The ad failed to show.");
            }

            @Override
            public void onAdShowedFullScreenContent() {
                // Called when fullscreen content is shown.
                // Make sure to set your reference to null so you don't
                // show it a second time.
                mInterstitialAd = null;
                Log.d("TAG", "The ad was shown.");
            }
        });

        if (mInterstitialAd != null) {
            mInterstitialAd.show(MainActivity.this);
        } else {
            Log.d("TAG", "The interstitial ad wasn't ready yet.");
        }

    \\Rest of the logic for App.

    }
}
</code>```

LoginActivity.java and SignupActivity.java follow the same format (Initializing and displaying the ad first then the rest of the logic).

The problem is that the ads are not being displayed. Here are the error logs:

```<code>E/cr_VariationsUtils: Failed reading seed file "/data/user/0/com.brain.passive/app_webview/variations_seed": /data/user/0/com.brain.passive/app_webview/variations_seed (No such file or directory)

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.brain.passive/com.brain.passive.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void c.b.b.a.a.x.a.b(c.b.b.a.a.k)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void c.b.b.a.a.x.a.b(c.b.b.a.a.k)' on a null object reference
        at com.brain.passive.MainActivity.onCreate(:2)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

In verbose these lines are also shown:

```<code>W/GooglePlayServicesUtil: Google Play services out of date for com.brainiac.passiveincome.  Requires 212800000 but found 202414022

W/GoogleApiManager: The service for c.b.b.a.h.c.c is not available: b{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}

W/VideoCapabilities: Unrecognized profile 4 for video/hevc
I/VideoCapabilities: Unsupported profile 4 for video/mp4v-es
W/cr_MediaCodecUtil: HW encoder for video/avc is not available on this device.

</code>```

I'm unable to figure out if this is a video incompatibility problem or if I've made some mistake in the google ads setup. Pls help.

答:
While overriding a function , calling the super is necessary. This what was causing the null pointer exceptions in the inner functions.</p>
```<code>InterstitialAd.load(this, "ca-app-pub-7147930999992246/2850110809", adRequest,
                new InterstitialAdLoadCallback() {
                    @Override
                    public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                        // The mInterstitialAd reference will be null until
                        // an ad is loaded.
                        Log.i("Loaded", "onAdLoaded");
                        interstitialAd.show(LoginActivity.this);
                        interstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
                            @Override
                            public void onAdFailedToShowFullScreenContent(AdError adError) {
                                // Called when fullscreen content failed to show.
                                super.onAdFailedToShowFullScreenContent(adError);
                                Log.d("TAG", "The ad failed to show.");
                            }

                            @Override
                            public void onAdDismissedFullScreenContent() {
                                // Called when fullscreen content is dismissed.
                                super.onAdDismissedFullScreenContent();
                                Log.d("TAG", "The ad was dismissed.");
                            }

                            @Override
                            public void onAdShowedFullScreenContent() {
                                // Called when fullscreen content is shown.
                                // Make sure to set your reference to null so you don't
                                // show it a second time.
                                super.onAdShowedFullScreenContent();
                                Log.d("TAG", "The ad was shown.");
                            }
                        });
                    }

                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                        // Handle the error
                        Log.i("FailedError", loadAdError.getMessage());
                    }
                });
</code>```

Title: Unable to show Interstitial ad

Body:
I've gone through all the previous answers on this question , but my error and approach is slightly different from the previous questions'.

I've only three views in my app : Login , Signup and Main. I want to show an interstitial ad every time I transition from one view to another.

In order to accomplish this, I'm initializing , loading and showing the ad at the start of each view:

MainActivity.java

package com.brain.passive;

import android.content.Intent;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.*;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;

public class MainActivity extends AppCompatActivity {
    public EditText emailId, passwd;
    Button btnSignUp;
    TextView signIn;
    FirebaseAuth firebaseAuth;
    private FirebaseAuth.AuthStateListener authStateListener;
    private InterstitialAd mInterstitialAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        AdRequest adRequest = new AdRequest.Builder().build();

        InterstitialAd.load(this,"ca-app-pub-7147930999992278/2850010809", adRequest,
                new InterstitialAdLoadCallback() {
                    @Override
                    public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                        // The mInterstitialAd reference will be null until
                        // an ad is loaded.
                        mInterstitialAd = interstitialAd;
                        Log.i("Loaded", "onAdLoaded");
                    }

                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                        // Handle the error
                        Log.i("FailedError", loadAdError.getMessage());
                        mInterstitialAd = null;
                    }
                });

        mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
            @Override
            public void onAdDismissedFullScreenContent() {
                // Called when fullscreen content is dismissed.
                Log.d("TAG", "The ad was dismissed.");
            }

            @Override
            public void onAdFailedToShowFullScreenContent(AdError adError) {
                // Called when fullscreen content failed to show.
                Log.d("TAG", "The ad failed to show.");
            }

            @Override
            public void onAdShowedFullScreenContent() {
                // Called when fullscreen content is shown.
                // Make sure to set your reference to null so you don't
                // show it a second time.
                mInterstitialAd = null;
                Log.d("TAG", "The ad was shown.");
            }
        });

        if (mInterstitialAd != null) {
            mInterstitialAd.show(MainActivity.this);
        } else {
            Log.d("TAG", "The interstitial ad wasn't ready yet.");
        }

    \\Rest of the logic for App.

    }
}

LoginActivity.java and SignupActivity.java follow the same format (Initializing and displaying the ad first then the rest of the logic).

The problem is that the ads are not being displayed. Here are the error logs:

E/cr_VariationsUtils: Failed reading seed file "/data/user/0/com.brain.passive/app_webview/variations_seed": /data/user/0/com.brain.passive/app_webview/variations_seed (No such file or directory)

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.brain.passive/com.brain.passive.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void c.b.b.a.a.x.a.b(c.b.b.a.a.k)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void c.b.b.a.a.x.a.b(c.b.b.a.a.k)' on a null object reference
        at com.brain.passive.MainActivity.onCreate(:2)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

In verbose these lines are also shown:

W/GooglePlayServicesUtil: Google Play services out of date for com.brainiac.passiveincome.  Requires 212800000 but found 202414022

W/GoogleApiManager: The service for c.b.b.a.h.c.c is not available: b{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}

W/VideoCapabilities: Unrecognized profile 4 for video/hevc
I/VideoCapabilities: Unsupported profile 4 for video/mp4v-es
W/cr_MediaCodecUtil: HW encoder for video/avc is not available on this device.

I'm unable to figure out if this is a video incompatibility problem or if I've made some mistake in the google ads setup. Pls help.

Body:
While overriding a function , calling the super is necessary. This what was causing the null pointer exceptions in the inner functions.

InterstitialAd.load(this, "ca-app-pub-7147930999992246/2850110809", adRequest,
                new InterstitialAdLoadCallback() {
                    @Override
                    public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                        // The mInterstitialAd reference will be null until
                        // an ad is loaded.
                        Log.i("Loaded", "onAdLoaded");
                        interstitialAd.show(LoginActivity.this);
                        interstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
                            @Override
                            public void onAdFailedToShowFullScreenContent(AdError adError) {
                                // Called when fullscreen content failed to show.
                                super.onAdFailedToShowFullScreenContent(adError);
                                Log.d("TAG", "The ad failed to show.");
                            }

                            @Override
                            public void onAdDismissedFullScreenContent() {
                                // Called when fullscreen content is dismissed.
                                super.onAdDismissedFullScreenContent();
                                Log.d("TAG", "The ad was dismissed.");
                            }

                            @Override
                            public void onAdShowedFullScreenContent() {
                                // Called when fullscreen content is shown.
                                // Make sure to set your reference to null so you don't
                                // show it a second time.
                                super.onAdShowedFullScreenContent();
                                Log.d("TAG", "The ad was shown.");
                            }
                        });
                    }

                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                        // Handle the error
                        Log.i("FailedError", loadAdError.getMessage());
                    }
                });


问:
openpyxl, changing row values to lowercase
I am trying to make my values lowercase in my row.

i've tried making a change to this lineval = r[filter_col - 1].value  such as adding .lower() to the end of it. I cannot seem to sitch the values in the column to lowercase.

Can anyone help with this?

code:

```<code>    for i,r in enumerate(ws.iter_rows()):
        if i==0:
            continue  # Of course, do not delete the header row
        rownum = i + 1  # when we use it, must by 1-indexed like Excel

        val = r[filter_col - 1].value
        if str(val) not in thePerson:
            delete_these.append(rownum)

</code>```

答:
r[filter_col - 1] is the cell.

r[filter_col - 1].value is the cell's value.

In order to change the value of the cell, you need to assign a new value to it: r[filter_col - 1].value = r[filter_col - 1].value.lower().

As itprorh66 pointed out, sometimes the value is None. The value needs to be of type str to call its lower() method. So you need to check beforehand, like so:

if isinstance(r[filter_col - 1].value, str):
   r[filter_col - 1].value = r[filter_col - 1].value.lower()
val = r[filter_col - 1].value
```

You can of course refactor that code, but there you go.

Body:
I am trying to make my values lowercase in my row.

i've tried making a change to this lineval = r[filter_col - 1].value  such as adding .lower() to the end of it. I cannot seem to sitch the values in the column to lowercase.

Can anyone help with this?

code:

    for i,r in enumerate(ws.iter_rows()):
        if i==0:
            continue  # Of course, do not delete the header row
        rownum = i + 1  # when we use it, must by 1-indexed like Excel

        val = r[filter_col - 1].value
        if str(val) not in thePerson:
            delete_these.append(rownum)

Body:
r[filter_col - 1] is the cell.

r[filter_col - 1].value is the cell's value.

In order to change the value of the cell, you need to assign a new value to it: r[filter_col - 1].value = r[filter_col - 1].value.lower().

As itprorh66 pointed out, sometimes the value is None. The value needs to be of type str to call its lower() method. So you need to check beforehand, like so:

if isinstance(r[filter_col - 1].value, str):
   r[filter_col - 1].value = r[filter_col - 1].value.lower()
val = r[filter_col - 1].value

You can of course refactor that code, but there you go.


问:
Returning an array of middleware from another middleware in express JS?
I have a route to view the information of a shop. The route looks like

```<code>router.param('userId',getUserById)
router.get("/store/:storeName/:userId?",isAuthenticated,getStoreDetail)
</code>```

Based on the condition I want to send a response. In the route the userId is optional. If the userId is not provided it sends only particular information of the shop as a response. And if the userId is provided then I should authenticate the user and then send all the details of the shop.

So I created a middleware to achieve this.

```<code>const isAuthenticated = (req, res, next) => {
    const { user } = req
    if (user) {
        return [
            expressJwt(jwtTokenProperty),
            (err, req, res, next) => {
                if (err) {
                    return res.status(401).json({
                        status: false,
                        error: err.message,
                        isJWTError: true
                    })
                }
                const checker = req.user && req.auth && req.user.id == req.auth.id
                if (!checker) {
                    return res.status(401).json({
                        status: false,
                        error: "Invalid Request"
                    })
                }
                next()
            }
        ]
    } else {
        next()
    }
}
</code>```

If the userId is not provided then I am getting a response as needed. But if the userId is provided I don't get any response.

答:
You forgot to return next().

Edit: You need to return a response rather than array containing a function.

```<code>const isAuthenticated = (req, res, next) => {
    const { user } = req
    return user
        ? [expressJwt(jwtTokenProperty), processResponse(req, res, next)]
        : next()
}

const processResponse = (req, res, next) => {
    const checker = req.user && req.auth && req.user.id == req.auth.id
    if (!checker) {
        return res.status(401).json({
            status: false,
            error: "Invalid Request"
        })
    }
    return next()
}
</code>```

Body:
I have a route to view the information of a shop. The route looks like

router.param('userId',getUserById)
router.get("/store/:storeName/:userId?",isAuthenticated,getStoreDetail)

Based on the condition I want to send a response. In the route the userId is optional. If the userId is not provided it sends only particular information of the shop as a response. And if the userId is provided then I should authenticate the user and then send all the details of the shop.

So I created a middleware to achieve this.

const isAuthenticated = (req, res, next) => {
    const { user } = req
    if (user) {
        return [
            expressJwt(jwtTokenProperty),
            (err, req, res, next) => {
                if (err) {
                    return res.status(401).json({
                        status: false,
                        error: err.message,
                        isJWTError: true
                    })
                }
                const checker = req.user && req.auth && req.user.id == req.auth.id
                if (!checker) {
                    return res.status(401).json({
                        status: false,
                        error: "Invalid Request"
                    })
                }
                next()
            }
        ]
    } else {
        next()
    }
}

If the userId is not provided then I am getting a response as needed. But if the userId is provided I don't get any response.

Body:
You forgot to return next().

Edit: You need to return a response rather than array containing a function.

const isAuthenticated = (req, res, next) => {
    const { user } = req
    return user
        ? [expressJwt(jwtTokenProperty), processResponse(req, res, next)]
        : next()
}

const processResponse = (req, res, next) => {
    const checker = req.user && req.auth && req.user.id == req.auth.id
    if (!checker) {
        return res.status(401).json({
            status: false,
            error: "Invalid Request"
        })
    }
    return next()
}


问:
Docker nginx php-fpm not serving php
I'm trying to setup nginx and php-fpm images to work together for a Laravel application. This is my set up:

docker-compose.yml

```<code>version: "3.8"

services:
    server:
        container_name: nginx
        build:
            context: .
            dockerfile: docker/nginx/Dockerfile
        volumes:
            - ./src/public:/var/www/html/public
        ports:
            - "8888:80"
        depends_on:
            - php
        networks:
            - laravel_net
    php:
        container_name: php
        build:
            context: .
            dockerfile: docker/php/Dockerfile
        ports:
            - "9000:9000"
        volumes:
            - ./src:/var/www/html
        networks:
            - laravel_net
networks:
    laravel_net:
        driver: 'bridge'
</code>```

Nginx

```<code>FROM nginx:stable-alpine

# puts app.conf into the container as /etc/nginx/nginx.conf
# has by default this: include /etc/nginx/conf.d/*.conf;
COPY docker/nginx/conf.d/*.conf /etc/nginx/conf.d/

WORKDIR /var/www/html
COPY ./src/public /var/www/html/public
</code>```

docker/nginx/conf.d/app.conf

```<code>server {
    listen 80;
    server_name laravel.local;
    index index.php index.html;
    error_log /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/html/public;

    location / {
        try_files $uri /index.php$is_args$args;
    }

    location ~ \.php {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_index index.php;
        fastcgi_pass php:9000;
    }
}
</code>```

PHP

```<code>FROM php:8.1-fpm-alpine

WORKDIR /var/www/html
COPY ./src /var/www/html

EXPOSE 9000
</code>```

Inside src folder is where the laravel app should live so for now I'm just outputting phpinfo() on the public dir just to check that everything is working as expected
src/public/index.php

```<code><?php

phpinfo();

</code>```

If I run docker-compose up --build and docker ps I can see the containers running

```<code>% docker ps
CONTAINER ID   IMAGE                 COMMAND                  CREATED         STATUS         PORTS                    NAMES
abc123   laravel_server   "/docker-entrypoint.…"   8 seconds ago   Up 6 seconds   0.0.0.0:8888->80/tcp     nginx
abc456   laravel_php      "docker-php-entrypoi…"   8 seconds ago   Up 7 seconds   0.0.0.0:9000->9000/tcp   php
</code>```

also on both docker-compose exec server /bin/sh and docker-compose exec php /bin/shI can see the index.php file inside the container

```<code>docker-compose exec server sh
/var/www/html # cat public/index.php
<?php

phpinfo();
/var/www/html # ls -la public
total 12
drwxr-xr-x    2 root     root          4096 Feb 12 13:41 .
drwxr-xr-x    1 root     root          4096 Feb 12 13:41 ..
-rw-r--r--    1 root     root            18 Feb 12 12:51 index.php

docker-compose exec php sh
/var/www/html # ls -lah public/
total 4K
drwxr-xr-x    3 root     root          96 Feb 12 13:42 .
drwxr-xr-x    3 root     root          96 Feb 10 21:28 ..
-rw-r--r--    1 root     root          18 Feb 12 13:42 index.php
/var/www/html # cat public/index.php
<?php

phpinfo();
</code>```

However when I try to access http://localhost:8888 from the browser I get the default Welcome to nginx! page. Any ideas what I'm doing wrong?

答:
Based on the comments of the other answer:

There is no prioritization of configuration files at all. They are all become on giant NGINX configuration time at runtime.

In your case the default NGINX configuration will listen on port 80 as default server name. That is where the default "Welcome to NGINX" page is configured.

In your app configuration you set the server_name to laravel.local. Sending this as a Host-header curl -v -H "Host: laravel.local" 127.0.0.1:8888 will let NGINX pick the server configuration from your app.conf for this specific Hostname.

You can add this to your clients /etc/hosts/ file to make it work from your web browser.

127.0.0.1 laravel.local

Title: Docker nginx php-fpm not serving php

Body:
I'm trying to setup nginx and php-fpm images to work together for a Laravel application. This is my set up:

docker-compose.yml

version: "3.8"

services:
    server:
        container_name: nginx
        build:
            context: .
            dockerfile: docker/nginx/Dockerfile
        volumes:
            - ./src/public:/var/www/html/public
        ports:
            - "8888:80"
        depends_on:
            - php
        networks:
            - laravel_net
    php:
        container_name: php
        build:
            context: .
            dockerfile: docker/php/Dockerfile
        ports:
            - "9000:9000"
        volumes:
            - ./src:/var/www/html
        networks:
            - laravel_net
networks:
    laravel_net:
        driver: 'bridge'

Nginx

FROM nginx:stable-alpine

# puts app.conf into the container as /etc/nginx/nginx.conf
# has by default this: include /etc/nginx/conf.d/*.conf;
COPY docker/nginx/conf.d/*.conf /etc/nginx/conf.d/

WORKDIR /var/www/html
COPY ./src/public /var/www/html/public

docker/nginx/conf.d/app.conf

server {
    listen 80;
    server_name laravel.local;
    index index.php index.html;
    error_log /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/html/public;

    location / {
        try_files $uri /index.php$is_args$args;
    }

    location ~ \.php {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_index index.php;
        fastcgi_pass php:9000;
    }
}

PHP

FROM php:8.1-fpm-alpine

WORKDIR /var/www/html
COPY ./src /var/www/html

EXPOSE 9000

Inside src folder is where the laravel app should live so for now I'm just outputting phpinfo() on the public dir just to check that everything is working as expected
src/public/index.php

<?php

phpinfo();

If I run docker-compose up --build and docker ps I can see the containers running

% docker ps
CONTAINER ID   IMAGE                 COMMAND                  CREATED         STATUS         PORTS                    NAMES
abc123   laravel_server   "/docker-entrypoint.…"   8 seconds ago   Up 6 seconds   0.0.0.0:8888->80/tcp     nginx
abc456   laravel_php      "docker-php-entrypoi…"   8 seconds ago   Up 7 seconds   0.0.0.0:9000->9000/tcp   php

also on both docker-compose exec server /bin/sh and docker-compose exec php /bin/shI can see the index.php file inside the container

docker-compose exec server sh
/var/www/html # cat public/index.php
<?php

phpinfo();
/var/www/html # ls -la public
total 12
drwxr-xr-x    2 root     root          4096 Feb 12 13:41 .
drwxr-xr-x    1 root     root          4096 Feb 12 13:41 ..
-rw-r--r--    1 root     root            18 Feb 12 12:51 index.php

docker-compose exec php sh
/var/www/html # ls -lah public/
total 4K
drwxr-xr-x    3 root     root          96 Feb 12 13:42 .
drwxr-xr-x    3 root     root          96 Feb 10 21:28 ..
-rw-r--r--    1 root     root          18 Feb 12 13:42 index.php
/var/www/html # cat public/index.php
<?php

phpinfo();

However when I try to access http://localhost:8888 from the browser I get the default Welcome to nginx! page. Any ideas what I'm doing wrong?


问:
POST method getting converted to GET in IE-9
I have this line of code in my JSP. (I'm using struts 1.3)

.
.
.

When the action corresponding to mine.do is invoked (using struts-config.xml), the page is getting submitted as GET instead of POST. All the request parameters including the required ones are getting lost due to this. This issue occcurs only in IE-9.

The response remains as POST when I use other versions of IE or any other browsers. How do I make the response to remain as POST in IE-9 ?

EDIT : I observed one more issue in this. Whenever the page is rendered in a new window, this issue occurs. Other places, the POST works fine in IE-9.

Also, this issue occurs in Win7/IE-8, but works absolutely fine in XP/IE-8. Is there something to do with the OS as well???

Any solutions would be useful.

Thanks!!

答: We have noticed that there are some security warnings that halt the processing in order for the user to acknowledge.  Once the use acknowledges the warning the browser sends a get rather than a post.  This has been happening in IE8, not sure if it still happens in IE9.</p>


问:
I can not focus this song on one of my ears with pydub
I wrote this code with pydub. I want to make to different variables with the same song.
One song would just play in the left ear and one song would just play in the right ear.

```<code>from pydub import AudioSegment

src = "or_test.mp3"
dst1 = "mono_left.mp3"
dst2 = "mono_right.mp3"    # enter code here

sound1 = AudioSegment.from_mp3(src)
sound2 = AudioSegment.from_mp3(src)

mono_audios1 = sound1.split_to_mono()
mono_audios2 = sound2.split_to_mono()

mono_left = mono_audios1[1].export(dst1, format="mp3")
mono_right = mono_audios1[0].export(dst2, format="mp3")
</code>```

When I run mono_right or mono_left the sound plays from both ears, but I don't want it like that.

How do I correct this?

答:
sound2 and mono_audios2 are not needed.
mono_audios indexes 0 and 1 - left and right - are inverted.
In  AudioSegment.from_mp3 you also need to specify a format.

```<code>from pydub import AudioSegment

src = "or_test.mp3"
dst1 = "mono_left.mp3"
dst2 = "mono_right.mp3"

stereo_audio = AudioSegment.from_file(src, format="mp3")
mono_audios = stereo_audio.split_to_mono()

mono_left = mono_audios[0].export(dst1, format="mp3")
mono_right = mono_audios[1].export(dst2, format="mp3")
</code>```

If this doesn't work, then it's the audio player.

Body:
I wrote this code with pydub. I want to make to different variables with the same song.
One song would just play in the left ear and one song would just play in the right ear.

from pydub import AudioSegment

src = "or_test.mp3"
dst1 = "mono_left.mp3"
dst2 = "mono_right.mp3"    # enter code here

sound1 = AudioSegment.from_mp3(src)
sound2 = AudioSegment.from_mp3(src)

mono_audios1 = sound1.split_to_mono()
mono_audios2 = sound2.split_to_mono()

mono_left = mono_audios1[1].export(dst1, format="mp3")
mono_right = mono_audios1[0].export(dst2, format="mp3")

When I run mono_right or mono_left the sound plays from both ears, but I don't want it like that.

How do I correct this?

Body:
sound2 and mono_audios2 are not needed.
mono_audios indexes 0 and 1 - left and right - are inverted.
In  AudioSegment.from_mp3 you also need to specify a format.

from pydub import AudioSegment

src = "or_test.mp3"
dst1 = "mono_left.mp3"
dst2 = "mono_right.mp3"

stereo_audio = AudioSegment.from_file(src, format="mp3")
mono_audios = stereo_audio.split_to_mono()

mono_left = mono_audios[0].export(dst1, format="mp3")
mono_right = mono_audios[1].export(dst2, format="mp3")

If this doesn't work, then it's the audio player.


问:
how to populate select options from json Array with VueJs
I am looking to populate select option from this json array :

[{"select":["option1","option2","option3","option4"]}]

with vuejs.
I found an example of countries but it is not the same (it doesn't work for me).

答:
Try like following snippet:

new Vue({
  el: '#demo',
  data() {
    return {
      items: [{"select":["option1","option2","option3","option4"]}],
      selected: ''
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <select v-model="selected">
    <option disabled >Please select option</option>
    <option v-for="(item, i) in items[0].select" :key="i" :value="item">
      {{ item }}
    </option>
  </select>
  <h3>{{ selected }}</h3>
</div></code>```

Body:
Try like following snippet:

new Vue({
  el: '#demo',
  data() {
    return {
      items: [{"select":["option1","option2","option3","option4"]}],
      selected: ''
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <select v-model="selected">
    <option disabled >Please select option</option>
    <option v-for="(item, i) in items[0].select" :key="i" :value="item">
      {{ item }}
    </option>
  </select>
  <h3>{{ selected }}</h3>
</div>