问:
Pandas sum-lag of a column
Lets say I have the data like this

```<code>df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})
</code>```

df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})
what I want to do is find the sum of the metric column =3378

```<code>MONTHS NEW_METRIC
 0       3378
 1       3378
 2       2948
 3       2794
 4       2730
 5       2807
 6       2768
</code>```

So here basically created a new row with 0 added and the corresponding new metric is the sum and for value 1 it is also the sum for new metric but from month=2 it should subtract the lag value of metric (3378-430) and similiarly for months3 it would be (3378-584) etc till the end.
As a first step I wanted to store the sum in result which failed

```<code>sum_METRIC = df.agg({"METRIC":"sum"}).collect()[0]
result = sum_METRIC["sum(METRIC)"]
</code>```

This threw error 'Series' object has no attribute 'collect'.

How do I sum and then use the lag to subtract?

答:
You can substract METRIC for the resulting sum:</p>

```<code>In [11]: df["METRIC"].sum() - df["METRIC"].reindex(np.arange(0, 7)).shift(2).fillna(0)
Out[11]:
0    3378.0
1    3378.0
2    2948.0
3    2794.0
4    2730.0
5    2807.0
6    2768.0
Name: METRIC, dtype: float64
</code>```

Title: Pandas sum-lag of a column

Body:
Lets say I have the data like this

df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})

df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})
what I want to do is find the sum of the metric column =3378

MONTHS NEW_METRIC
 0       3378
 1       3378
 2       2948
 3       2794
 4       2730
 5       2807
 6       2768

So here basically created a new row with 0 added and the corresponding new metric is the sum and for value 1 it is also the sum for new metric but from month=2 it should subtract the lag value of metric (3378-430) and similiarly for months3 it would be (3378-584) etc till the end.
As a first step I wanted to store the sum in result which failed

sum_METRIC = df.agg({"METRIC":"sum"}).collect()[0]
result = sum_METRIC["sum(METRIC)"]

This threw error 'Series' object has no attribute 'collect'.

How do I sum and then use the lag to subtract?

Body:
You can substract METRIC for the resulting sum:

In [11]: df["METRIC"].sum() - df["METRIC"].reindex(np.arange(0, 7)).shift(2).fillna(0)
Out[11]:
0    3378.0
1    3378.0
2    2948.0
3    2794.0
4    2730.0
5    2807.0
6    2768.0
Name: METRIC, dtype: float64


来源: stackexchange

问:
Swift Anagram checker
I am attempting to build an anagram checker for swift.  This is my code.  In case you don't know an anagram checker checks if two strings have the same characters in them but, order does not matter.

```<code>func checkForAnagram(#firstString: String, #secondString: String) -> Bool {
    var firstStringArray: [Character] = []
    var secondStringArray: [Character] = []
    /* if case matters delete the next four lines
    and make sure your variables are not constants */
    var first = firstString
    var second = secondString
    first = first.lowercaseString
    second = second.lowercaseString
    for charactersOne in first {
        firstStringArray += [charactersOne]
    }
    for charactersTwo in second {
        secondStringArray += [charactersTwo]
    }
    if firstStringArray.count != secondStringArray.count {
        return false
    } else {
        for elements in firstStringArray {
            if secondStringArray.contains(elements){
                return true
            } else {
                return false
            }
        }

}
}

var a = "Hello"
var b = "oellh"
var c = "World"
checkForAnagram(firstString: a, secondString: b)
</code>```

I am getting an error message of.

```<code>'[Character]' does not have a member 'contains'
</code>```

答:
Swift 4.1 Function will give you 3 questions answer for Anagram  :-

1. Input Strings (a,b) are Anagram ? //Bool

2. If not an Anagram then number of count require to change Characters  in strings(a,b) to make them  anagram ?  // Int

3. If not an Anagram then list of  Characters needs to be change in strings(a,b)  to make them  anagram ? // [Character]

STEP 1:- Copy and Paste below function in to your required class:-

```<code>  //MARK:-  Anagram checker
    func anagramChecker(a:String,b:String) -> (Bool,Int,[Character]) {
        var aCharacters = Array(a)
        var bCharacters = Array(b)
        var count = 0
        var isAnagram = true
        var replacementRequiredWords:[Character] = [Character]()
        if aCharacters.count == bCharacters.count {
            let listA = aCharacters.filter { !bCharacters.contains($0) }
            for i in 0 ..< listA.count {
                if !replacementRequiredWords.contains(listA[i]) {
                    count = count + 1
                    replacementRequiredWords.append(listA[i])
                    isAnagram = false
                }
            }
            let listB = bCharacters.filter { !aCharacters.contains($0) }
            for i in 0 ..< listB.count {
                if !replacementRequiredWords.contains(listB[i]) {
                    count = count + 1
                    replacementRequiredWords.append(listB[i])
                     isAnagram = false
                }
            }
        }else{
            //cant be an anagram
            count = -1
        }
         return (isAnagram,count,replacementRequiredWords)
    }
</code>```

STEP 2 :- Make two Input Strings for test

```<code>// Input Strings
var a = "aeb"
var b = "abs"
</code>```

STEP 3:- Print results :-

```<code>print("isAnagram : \(isAnagram(a: a, b: b).0)")

print("number of count require to change strings in anagram  : \(isAnagram(a: a, b: b).1)")//-1 will come in case of cant be a Anagram

print("list of  Characters needs to be change : \(isAnagram(a: a, b: b).2)")
</code>```

Results of above exercise:-

```<code>isAnagram : false
number of count require to change strings in anagram  : 2
list of  Characters needs to be change : ["e", "s"]
</code>```

Hope this 10 minutes exercise  will give some support to my Swift
  family for solving   Anagram related problems easily. :)

ContentLicense: CC BY-SA 3.0

Title: Swift Anagram checker

Body:
I am attempting to build an anagram checker for swift.  This is my code.  In case you don't know an anagram checker checks if two strings have the same characters in them but, order does not matter.

func checkForAnagram(#firstString: String, #secondString: String) -> Bool {
    var firstStringArray: [Character] = []
    var secondStringArray: [Character] = []
    /* if case matters delete the next four lines
    and make sure your variables are not constants */
    var first = firstString
    var second = secondString
    first = first.lowercaseString
    second = second.lowercaseString
    for charactersOne in first {
        firstStringArray += [charactersOne]
    }
    for charactersTwo in second {
        secondStringArray += [charactersTwo]
    }
    if firstStringArray.count != secondStringArray.count {
        return false
    } else {
        for elements in firstStringArray {
            if secondStringArray.contains(elements){
                return true
            } else {
                return false
            }
        }

}
}

var a = "Hello"
var b = "oellh"
var c = "World"
checkForAnagram(firstString: a, secondString: b)

I am getting an error message of.

'[Character]' does not have a member 'contains'

Body:
Swift 4.1 Function will give you 3 questions answer for Anagram  :-

1. Input Strings (a,b) are Anagram ? //Bool

2. If not an Anagram then number of count require to change Characters  in strings(a,b) to make them  anagram ?  // Int

3. If not an Anagram then list of  Characters needs to be change in strings(a,b)  to make them  anagram ? // [Character]

STEP 1:- Copy and Paste below function in to your required class:-

  //MARK:-  Anagram checker
    func anagramChecker(a:String,b:String) -> (Bool,Int,[Character]) {
        var aCharacters = Array(a)
        var bCharacters = Array(b)
        var count = 0
        var isAnagram = true
        var replacementRequiredWords:[Character] = [Character]()
        if aCharacters.count == bCharacters.count {
            let listA = aCharacters.filter { !bCharacters.contains($0) }
            for i in 0 ..< listA.count {
                if !replacementRequiredWords.contains(listA[i]) {
                    count = count + 1
                    replacementRequiredWords.append(listA[i])
                    isAnagram = false
                }
            }
            let listB = bCharacters.filter { !aCharacters.contains($0) }
            for i in 0 ..< listB.count {
                if !replacementRequiredWords.contains(listB[i]) {
                    count = count + 1
                    replacementRequiredWords.append(listB[i])
                     isAnagram = false
                }
            }
        }else{
            //cant be an anagram
            count = -1
        }
         return (isAnagram,count,replacementRequiredWords)
    }

STEP 2 :- Make two Input Strings for test

// Input Strings
var a = "aeb"
var b = "abs"

STEP 3:- Print results :-

print("isAnagram : \(isAnagram(a: a, b: b).0)")

print("number of count require to change strings in anagram  : \(isAnagram(a: a, b: b).1)")//-1 will come in case of cant be a Anagram

print("list of  Characters needs to be change : \(isAnagram(a: a, b: b).2)")

Results of above exercise:-

isAnagram : false
number of count require to change strings in anagram  : 2
list of  Characters needs to be change : ["e", "s"]

Hope this 10 minutes exercise  will give some support to my Swift
  family for solving   Anagram related problems easily. :)

ContentLicense: CC BY-SA 4.0


问:
React Admin with OpenID Connect
I'm trying to implement a simple OpenID Connect react-admin login using gitlab as OAuth2 service provider.

most of the react-admin examples about OpenID is simple username/password login. But OpenID Connect will do several redirects, and what I come with is make python/flask server redirect to http://example.com/#/login?token=<token>, and make react-admin to parsed the URL, and set token in localStorage.

basically is somethings like below:

```<code>
(({ theme, location, userLogin } ) => {
  let params = queryString.parse(location.search);
  if (params.token) {
    userLogin({token: params.token});
  }
  return (
    <MuiThemeProvider theme={ theme }>
      <Button href={ '/api/gitlab/login' }>
        Login via GitLab
      </Button>
    </MuiThemeProvider>
  );
});
</code>```

Obviously, that is not good enough, I want to have some advice about how can I improve this?

答:
I assume you followed this example https://marmelab.com/react-admin/Authentication.html, that does not cover the OAuth2 password grant.

// in src/authProvider.js
import { AUTH_LOGIN } from 'react-admin';

export default (type, params) => {
    if (type === AUTH_LOGIN) {
        const { username, password } = params;
        const request = new Request('https://mydomain.example.com/authenticate', {
            method: 'POST',
            body: JSON.stringify({ username, password }),
            headers: new Headers({ 'Content-Type': 'application/json' }),
        })
        return fetch(request)
            .then(response => {
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(response.statusText);
                }
                return response.json();
            })
            .then(({ token }) => {
                localStorage.setItem('token', token);
            });
    }
    return Promise.resolve();
}
```

<p>The GitLab guys / girls describe what grants they provide.
https://docs.gitlab.com/ee/api/oauth2.html#resource-owner-password-credentials-flow</p>

<p>Here is the example how you can get an access token using curl:</p>

<pre class="lang-sh prettyprint-override"><code>echo 'grant_type=password&username=<your_username>&password=<your_password>' > auth.txt
curl --data "@auth.txt" --request POST https://gitlab.com/oauth/token
</code>```

With the access token you can get some information from the user that is also described here: https://docs.gitlab.com/ee/api/oauth2.html#access-gitlab-api-with-access-token

Here is the example how you can get information from GitLab with the access token that you got from the previous call using curl:

curl --header "Authorization: Bearer OAUTH-TOKEN" https://gitlab.com/api/v4/user
```

<p>With some small adjustments in the react-admin example you can use the password credentials flow.</p>

<h1>Here you can find the example that works with GitLab:</h1>

<p>https://gist.github.com/rilleralle/b28574ec1c4cfe10ec7b05809514344b</p>

<pre class="lang-js prettyprint-override"><code>import { AUTH_LOGIN } from 'react-admin';

export default (type, params) => {
    if (type === AUTH_LOGIN) {
        const { username, password } = params;
        const oAuthParams = {
            grant_type: "password",
            username,
            password
        }
        const body = Object.keys(oAuthParams).map((key) => {
            return encodeURIComponent(key) + '=' + encodeURIComponent(oAuthParams[key]);
          }).join('&');
        const request = new Request('https://gitlab.com/oauth/token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
              },
            body
        })
        return fetch(request)
            .then(response => {
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(response.statusText);
                }
                return response.json();
            })
            .then(( {access_token} ) => {
                localStorage.setItem('token', access_token);
            });
    }
    return Promise.resolve();
}
</code>```

I hope this helps you.

Cheers
Ralf

Title: React Admin with OpenID Connect

Body:
I'm trying to implement a simple OpenID Connect react-admin login using gitlab as OAuth2 service provider.

most of the react-admin examples about OpenID is simple username/password login. But OpenID Connect will do several redirects, and what I come with is make python/flask server redirect to http://example.com/#/login?token=<token>, and make react-admin to parsed the URL, and set token in localStorage.

basically is somethings like below:

(({ theme, location, userLogin } ) => {
  let params = queryString.parse(location.search);
  if (params.token) {
    userLogin({token: params.token});
  }
  return (
    <MuiThemeProvider theme={ theme }>
      <Button href={ '/api/gitlab/login' }>
        Login via GitLab
      </Button>
    </MuiThemeProvider>
  );
});

Obviously, that is not good enough, I want to have some advice about how can I improve this?

Body:
I assume you followed this example https://marmelab.com/react-admin/Authentication.html, that does not cover the OAuth2 password grant.

// in src/authProvider.js
import { AUTH_LOGIN } from 'react-admin';

export default (type, params) => {
    if (type === AUTH_LOGIN) {
        const { username, password } = params;
        const request = new Request('https://mydomain.example.com/authenticate', {
            method: 'POST',
            body: JSON.stringify({ username, password }),
            headers: new Headers({ 'Content-Type': 'application/json' }),
        })
        return fetch(request)
            .then(response => {
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(response.statusText);
                }
                return response.json();
            })
            .then(({ token }) => {
                localStorage.setItem('token', token);
            });
    }
    return Promise.resolve();
}

The GitLab guys / girls describe what grants they provide.
https://docs.gitlab.com/ee/api/oauth2.html#resource-owner-password-credentials-flow

Here is the example how you can get an access token using curl:

echo 'grant_type=password&username=<your_username>&password=<your_password>' > auth.txt
curl --data "@auth.txt" --request POST https://gitlab.com/oauth/token

With the access token you can get some information from the user that is also described here: https://docs.gitlab.com/ee/api/oauth2.html#access-gitlab-api-with-access-token

Here is the example how you can get information from GitLab with the access token that you got from the previous call using curl:

curl --header "Authorization: Bearer OAUTH-TOKEN" https://gitlab.com/api/v4/user

With some small adjustments in the react-admin example you can use the password credentials flow.

Here you can find the example that works with GitLab:

https://gist.github.com/rilleralle/b28574ec1c4cfe10ec7b05809514344b

import { AUTH_LOGIN } from 'react-admin';

export default (type, params) => {
    if (type === AUTH_LOGIN) {
        const { username, password } = params;
        const oAuthParams = {
            grant_type: "password",
            username,
            password
        }
        const body = Object.keys(oAuthParams).map((key) => {
            return encodeURIComponent(key) + '=' + encodeURIComponent(oAuthParams[key]);
          }).join('&');
        const request = new Request('https://gitlab.com/oauth/token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
              },
            body
        })
        return fetch(request)
            .then(response => {
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(response.statusText);
                }
                return response.json();
            })
            .then(( {access_token} ) => {
                localStorage.setItem('token', access_token);
            });
    }
    return Promise.resolve();
}

I hope this helps you.

Cheers
Ralf


问:
Set up WinDbg as the default debugger
Whenever my application throws an unhandled exception, I would like WinDbg to catch that exception on my debugging machine rather than Dr. Watson, etc. How can this be configured?</p>

答:
Here is a registry file for setting WinDbg as the managed debugger and native debugger:

```<code>Windows Registry Editor Version 5.00

;This reg file installs just-in-time debuggers to capture a dump of all process
;crashes for the machine.
;
;Assumes 32-bit debugger is cdb.exe and is installed to C:\debuggers\x86\.
;Assumes 64-bit debugger is cdb.exe and is installed to C:\debuggers\x64\.
;
;Assumes crash dumps can be written to C:\crash_dumps\.
;Make sure all users have write access to this directory.

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]
"DbgManagedDebugger"="\"c:\\debuggers\\x64\\windbg.exe\" -pv -p %ld "
"DbgJITDebugLaunchSetting"=dword:00000002

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug]
"Debugger"="\"c:\\debuggers\\x64\\windbg.exe\" -pv -p %ld "
"Auto"="1"

;The following keys are only used on 64-bit versions of Windows (note Wow6432Node).
;They can be safely created with no side-effects on 32-bit versions of Windows.
;Alternatively, you can delete the remainder of this file if you’re running a
;32-bit version of Windows.

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug]
"Debugger"="\"c:\\debuggers\\x86\\windbg.exe\" -pv -p %ld "
"Auto"="1"
</code>```

Automatically Capturing a Dump When a Process Crashes is a writeup about this from the CLR team.

Title: Set up WinDbg as the default debugger

Body:
Here is a registry file for setting WinDbg as the managed debugger and native debugger:

Windows Registry Editor Version 5.00

;This reg file installs just-in-time debuggers to capture a dump of all process
;crashes for the machine.
;
;Assumes 32-bit debugger is cdb.exe and is installed to C:\debuggers\x86\.
;Assumes 64-bit debugger is cdb.exe and is installed to C:\debuggers\x64\.
;
;Assumes crash dumps can be written to C:\crash_dumps\.
;Make sure all users have write access to this directory.

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]
"DbgManagedDebugger"="\"c:\\debuggers\\x64\\windbg.exe\" -pv -p %ld "
"DbgJITDebugLaunchSetting"=dword:00000002

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug]
"Debugger"="\"c:\\debuggers\\x64\\windbg.exe\" -pv -p %ld "
"Auto"="1"

;The following keys are only used on 64-bit versions of Windows (note Wow6432Node).
;They can be safely created with no side-effects on 32-bit versions of Windows.
;Alternatively, you can delete the remainder of this file if you’re running a
;32-bit version of Windows.

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug]
"Debugger"="\"c:\\debuggers\\x86\\windbg.exe\" -pv -p %ld "
"Auto"="1"

Automatically Capturing a Dump When a Process Crashes is a writeup about this from the CLR team.


问:
Identifying if a string ONLY has specific text
I have a column with a string that sometimes has one name, two, names or several names separated by semi-colons. I want to identify if a row matches all the specified names, but not if a row contains only some of the specified names.

SME

Row 1 - John;Ralph;Susan;Joe

Row 2 - Ralph

Row 3 - Susan;Ralph;Robert;Margaret

Row 4 - Ralph;Susan

```<code>df1['SME'] = df1.SMES.str.ONLY contains('Ralph', na=False, case=True)
df2['SME'] = df1.SMES.str.ONLY contains('Ralph;Susan', na=False, case=True)
</code>```

Expecting df1

Row 1 - False

Row 2 - True

Row 3 - False

Row 4 - False

Expecting df2

Row 1 - False

Row 2 - False

Row 3 - False

Row 4 - True

答:
make some lambda functions:

```<code>f1 = lambda x: True if 'Ralph' in x else False
</code>```

so you will the .apply to make a new column.

```<code>df['has_Ralph'] = df['SME'].apply(f1)
</code>```

so yu can select these columns:

```<code>df_Ralph = df[df['SME'] == True]
</code>```

Body:
I have a column with a string that sometimes has one name, two, names or several names separated by semi-colons. I want to identify if a row matches all the specified names, but not if a row contains only some of the specified names.

SME

Row 1 - John;Ralph;Susan;Joe

Row 2 - Ralph

Row 3 - Susan;Ralph;Robert;Margaret

Row 4 - Ralph;Susan

df1['SME'] = df1.SMES.str.ONLY contains('Ralph', na=False, case=True)
df2['SME'] = df1.SMES.str.ONLY contains('Ralph;Susan', na=False, case=True)

Expecting df1

Row 1 - False

Row 2 - True

Row 3 - False

Row 4 - False

Expecting df2

Row 1 - False

Row 2 - False

Row 3 - False

Row 4 - True

Body:
make some lambda functions:

f1 = lambda x: True if 'Ralph' in x else False

so you will the .apply to make a new column.

df['has_Ralph'] = df['SME'].apply(f1)

so yu can select these columns:

df_Ralph = df[df['SME'] == True]


问:
Wordpress Images not displaying on Mobile
Wordpress Images will display correctly on Desktop but not on Mobile. Sometimes upon refreshing, a different set of images will display each time?

I have attempting in uninstalling all plugins already, and am not sure if anyone can inspect the issue using their mobile device or offer some additional options

.htaccess:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
# BEGIN WP-HUMMINGBIRD-CACHING
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault A0
<FilesMatch "\.(txt|xml|js)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(css)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav|mp4|m4v|ogg|webm|aac|eot|ttf|otf|woff|svg)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(jpg|jpeg|png|gif|swf|webp)$">
ExpiresDefault A691200
</FilesMatch>
</IfModule>
<IfModule mod_headers.c>
  <FilesMatch "\.(txt|xml|js)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(css)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav|mp4|m4v|ogg|webm|aac|eot|ttf|otf|woff|svg)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(jpg|jpeg|png|gif|swf|webp)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
</IfModule>
# END WP-HUMMINGBIRD-CACHING
# BEGIN ShortPixelWebp

# END ShortPixelWebp
</code>```

答:
Since it looks like you have/had ShortPixel with WebP rewriting active, my guess would be that the WebP images have gotten stuck in an "upstream" cache. When you load the page in Chrome, Firefox, Edge (anything except Safari), cached WebP images will load just fine. But try viewing the page on an iPhone, and none of the cached WebP images will load.

An upstream cache would include anything like Cloudflare, Sucuri's CloudProxy, or even a server-side cache that doesn't support varying the content based on the Accept header (the client browser's way of signaling support for WebP images).

If you clear said cache, that should resolve things for you.

But as Neil said, that's just shooting in the dark since you didn't give us enough information.

Body:
Wordpress Images will display correctly on Desktop but not on Mobile. Sometimes upon refreshing, a different set of images will display each time?

I have attempting in uninstalling all plugins already, and am not sure if anyone can inspect the issue using their mobile device or offer some additional options

.htaccess:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
# BEGIN WP-HUMMINGBIRD-CACHING
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault A0
<FilesMatch "\.(txt|xml|js)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(css)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav|mp4|m4v|ogg|webm|aac|eot|ttf|otf|woff|svg)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(jpg|jpeg|png|gif|swf|webp)$">
ExpiresDefault A691200
</FilesMatch>
</IfModule>
<IfModule mod_headers.c>
  <FilesMatch "\.(txt|xml|js)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(css)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav|mp4|m4v|ogg|webm|aac|eot|ttf|otf|woff|svg)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(jpg|jpeg|png|gif|swf|webp)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
</IfModule>
# END WP-HUMMINGBIRD-CACHING
# BEGIN ShortPixelWebp

# END ShortPixelWebp


问:
Two values being compared before function returns the value
I have some code where a function (which contains a promise) runs and then returns a boolean value. I then check to see if that value is true, and if so run some other code. I had the values logging to the console to do some debugging, and I noticed that the if statement that checks to see if the function returned true was running before the function even returned anything.

I have attempted to use "await" and "async" but I haven't found any success in using them.

```<code>javascript
function myFunc()
   promise()
      .then(value => {
         console.log('Returned true');
         return true;
      })
      .catch(err => {
         console.log('Error', err);
      });
end

if (myFunc()) {
   console.log('Value was true');
} else {
   console.log('Value was false');
}
</code>```

Expected:

```<code>Returned true
Value was true
</code>```

Actual:

```<code>Value was false
Returned true
</code>```

答:
You need to use "await" to wait the promise response</p>

```<code>promise = () => new Promise( (resolve, reject ) => resolve(true) );

async function myFunc(){
   try {
     let value = await promise();

     if (value === true){
       console.log('Returned true');
       return true;
     }
   } catch (err) {
     console.log('Error', err);
   }
}

async function main(){

  if ( await myFunc() ) {
   console.log('Value was true');
  } else {
   console.log('Value was false');
  }
}

main();
</code>```

Body:
I have some code where a function (which contains a promise) runs and then returns a boolean value. I then check to see if that value is true, and if so run some other code. I had the values logging to the console to do some debugging, and I noticed that the if statement that checks to see if the function returned true was running before the function even returned anything.

I have attempted to use "await" and "async" but I haven't found any success in using them.

javascript
function myFunc()
   promise()
      .then(value => {
         console.log('Returned true');
         return true;
      })
      .catch(err => {
         console.log('Error', err);
      });
end

if (myFunc()) {
   console.log('Value was true');
} else {
   console.log('Value was false');
}

Expected:

Returned true
Value was true

Actual:

Value was false
Returned true

Body:
You need to use "await" to wait the promise response

promise = () => new Promise( (resolve, reject ) => resolve(true) );

async function myFunc(){
   try {
     let value = await promise();

     if (value === true){
       console.log('Returned true');
       return true;
     }
   } catch (err) {
     console.log('Error', err);
   }
}

async function main(){

  if ( await myFunc() ) {
   console.log('Value was true');
  } else {
   console.log('Value was false');
  }
}

main();


问:
controlsfx CustomTextField add ImageView click event is often not triggered
After adding ImageView, the imageview click event is often not triggered. Clicking ten times may trigger one or two times. I don't know why.

enter image description here

```<code><CustomTextField prefHeight="45.0" prefWidth="300.0" promptText="搜索" fx:id="fieldSearch">
    <right>
        <ImageView fx:id="imageView">
            <image>
                <Image url="@../static/img/search.png"/>
            </image>
        </ImageView>
    </right>
</CustomTextField>
</code>```

```<code>    @FXML
    public ImageView imageView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        imageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                onSearchClick();
            }
        });
    }

    public void onSearchClick(){
        System.out.println("搜索");
    }
</code>```

答:
You should set

```<code>imageView.setPickOnBounds(true);
</code>```

in your initialize() method. This makes transparent parts of the image also clickable

Body:
After adding ImageView, the imageview click event is often not triggered. Clicking ten times may trigger one or two times. I don't know why.

enter image description here

<CustomTextField prefHeight="45.0" prefWidth="300.0" promptText="搜索" fx:id="fieldSearch">
    <right>
        <ImageView fx:id="imageView">
            <image>
                <Image url="@../static/img/search.png"/>
            </image>
        </ImageView>
    </right>
</CustomTextField>

    @FXML
    public ImageView imageView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        imageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                onSearchClick();
            }
        });
    }

    public void onSearchClick(){
        System.out.println("搜索");
    }

Body:
You should set

imageView.setPickOnBounds(true);

in your initialize() method. This makes transparent parts of the image also clickable


问:
How to run Powershell on a list of computers
I'm trying to run a remote command on a list of computers that available in plain text file (1 computer per line) in a file named 1.txt available under c:\1\1.txt.

What I run the powershell script the variable $comp is being run as $comp instead of being changed to the computer name

```<code>$computers = Get-Content c:\1\1.txt

foreach ($comp in $computers){
$LicenseInfo = Get-WmiObject SoftwareLicensingProduct -ComputerName $comp | Where-Object { $_.partialProductKey -and $_.ApplicationID -eq "55c92734-d682-4d71-983e-d6ec3f16059f" } | Select-Object PartialProductKey, Description, ProductKeyChannel, @{ N = "LicenseStatus"; E = { $lstat["$($_.LicenseStatus)"] } }
echo $LicenseInfo, $comp
}
</code>```

run the powershell command with the Computername $comp - where $comp will be changed everytime in the loop for another name of a computer available in the c:\1\1.txt file

答:
The reason you are getting the Select-Object error is because echo is not a command in Powershell that is for batch. Powershell uses Write-Host There is more information here:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-host?view=powershell-4.0

As far as the code adding a delimiter switch to get-content will separate each computer name

Get-Content -Path c:\1\1.txt -Delimiter `r

The `r stands for a carriage return

Body:
I'm trying to run a remote command on a list of computers that available in plain text file (1 computer per line) in a file named 1.txt available under c:\1\1.txt.

What I run the powershell script the variable $comp is being run as $comp instead of being changed to the computer name

$computers = Get-Content c:\1\1.txt

foreach ($comp in $computers){
$LicenseInfo = Get-WmiObject SoftwareLicensingProduct -ComputerName $comp | Where-Object { $_.partialProductKey -and $_.ApplicationID -eq "55c92734-d682-4d71-983e-d6ec3f16059f" } | Select-Object PartialProductKey, Description, ProductKeyChannel, @{ N = "LicenseStatus"; E = { $lstat["$($_.LicenseStatus)"] } }
echo $LicenseInfo, $comp
}

run the powershell command with the Computername $comp - where $comp will be changed everytime in the loop for another name of a computer available in the c:\1\1.txt file


问:
What System.Drawing classes count as GDI objects?
I have been having difficulties understanding which exact objects from the System.Drawing namespace actually contribute to the system total GDI object count. For instance, do Matrix objects count? GraphicsPath? Pen?

In order to test this, I ran the following code on Form initialization.

```<code>public partial class Form1 : Form
{
    Timer timer = new Timer();
    List<Pen> pens = new List<Pen>();

    public Form1()
    {
        InitializeComponent();

        var r = new Random();
        for (int i = 0; i < 1000; i++)
        {
            var p = new Pen(
                Color.FromArgb(r.Next(255), r.Next(255), r.Next(255)),
                (float)r.NextDouble() * 10);
            pens.Add(p);
        }

        timer.Interval = 30;
        timer.Tick += timer_Tick;
        timer.Start();
    }

    void timer_Tick(object sender, EventArgs e)
    {
        panel1.Invalidate();
    }

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        for (int i = 0; i < pens.Count; i++)
        {
            e.Graphics.DrawLine(pens[i], (int)(20 + i * 0.1), 20, (int)(50 + i * 0.1), 50);
        }
    }
}
</code>```

I was surprised to find that my application GDI object count was 32 (measured with Task Manager > Details > GDI objects column). This was true even if I kept the list around and forced the Paint event to draw individual lines with each of the generated pens. I even tried creating random colors to ensure that nothing got reused and still the GDI count kept steady at 32.

There are a lot of posts worrying about caching and reusing Pen instances and other objects, but it is not clear to me whether all System.Drawing objects contribute to this count.

Maybe modern GDI+ implementations are actually lazy and delay allocation only to when you are actually drawing something?

Update:
GSerg pointed out that the MSDN official documentation says

When you use GDI+, you don't have to be as concerned with handles and
  device contexts as you do when you use GDI.

It seems that GDI+ abstracts over GDI handle and avoids using them as much as possible. This is also consistent with reports elsewhere that seem to indicate that GDI+ only actually creates a GDI handle when it absolutely has to. For example, a Bitmap is only backed by a handle if you call methods that require a handle to exist, e.g. GetHBitmap().

It seems that, at least in modern GDI+, Pen, Brush and many other System.Drawing objects do not actually contribute to the total GDI object count. Of course, in C# they still leak unmanaged memory if they are not disposed, since they are backed by unmanaged GDI+ objects, but native memory is not such a harsh mistress as GDI memory.

If this current interpretation is not contested, I will move it to an answer over the next few days.

答:
The following objects cause a GDI handle to be created:

Bitmap

Brush

DC

Enhanced Metafile

Enhanced Metafile DC

Font

Memory DC

Metafile

Metafile DC

Palette

Pen

Extended Pen

Region

This list was drawn up by using the information from here:
https://learn.microsoft.com/en-gb/windows/desktop/SysInfo/gdi-objects

Body:
I have been having difficulties understanding which exact objects from the System.Drawing namespace actually contribute to the system total GDI object count. For instance, do Matrix objects count? GraphicsPath? Pen?

In order to test this, I ran the following code on Form initialization.

public partial class Form1 : Form
{
    Timer timer = new Timer();
    List<Pen> pens = new List<Pen>();

    public Form1()
    {
        InitializeComponent();

        var r = new Random();
        for (int i = 0; i < 1000; i++)
        {
            var p = new Pen(
                Color.FromArgb(r.Next(255), r.Next(255), r.Next(255)),
                (float)r.NextDouble() * 10);
            pens.Add(p);
        }

        timer.Interval = 30;
        timer.Tick += timer_Tick;
        timer.Start();
    }

    void timer_Tick(object sender, EventArgs e)
    {
        panel1.Invalidate();
    }

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        for (int i = 0; i < pens.Count; i++)
        {
            e.Graphics.DrawLine(pens[i], (int)(20 + i * 0.1), 20, (int)(50 + i * 0.1), 50);
        }
    }
}

I was surprised to find that my application GDI object count was 32 (measured with Task Manager > Details > GDI objects column). This was true even if I kept the list around and forced the Paint event to draw individual lines with each of the generated pens. I even tried creating random colors to ensure that nothing got reused and still the GDI count kept steady at 32.

There are a lot of posts worrying about caching and reusing Pen instances and other objects, but it is not clear to me whether all System.Drawing objects contribute to this count.

Maybe modern GDI+ implementations are actually lazy and delay allocation only to when you are actually drawing something?

Update:
GSerg pointed out that the MSDN official documentation says

When you use GDI+, you don't have to be as concerned with handles and
  device contexts as you do when you use GDI.

It seems that GDI+ abstracts over GDI handle and avoids using them as much as possible. This is also consistent with reports elsewhere that seem to indicate that GDI+ only actually creates a GDI handle when it absolutely has to. For example, a Bitmap is only backed by a handle if you call methods that require a handle to exist, e.g. GetHBitmap().

It seems that, at least in modern GDI+, Pen, Brush and many other System.Drawing objects do not actually contribute to the total GDI object count. Of course, in C# they still leak unmanaged memory if they are not disposed, since they are backed by unmanaged GDI+ objects, but native memory is not such a harsh mistress as GDI memory.

If this current interpretation is not contested, I will move it to an answer over the next few days.


问:
insmod error in kernel module programming
I am just starting with modular programming.

Above are my two files:

hello.c

```<code>#include <linux/init.h>
#include <linux/module.h>

static int hello_init(void)
{
    printk(KERN_ALERT "TEST: Hello world\n");
    return 0;
}

static void hello_exit(void)
{
    printk(KERN_ALERT "TEST: Good Bye");
}

module_init(hello_init);
module_exit(hello_exit);
</code>```

Makefile

```<code>obj-m += hello.o

KDIR = /usr/src/linux-headers-3.13.0-46-generic

all:
    $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules

clean:
    rm -rf *.o *.ko *.mod.* *.symvers *.order
</code>```

And here's my terminal output showing error in insmod command, kindly help.

```<code>anubhav@anubhav-Inspiron-3421:~/Desktop/os$ make
make -C /usr/src/linux-headers-3.13.0-46-generic  SUBDIRS=/home/anubhav/Desktop/os modules
make[1]: Entering directory `/usr/src/linux-headers-3.13.0-46-generic'
Building modules, stage 2.
MODPOST 1 modules
make[1]: Leaving directory `/usr/src/linux-headers-3.13.0-46-generic'
anubhav@anubhav-Inspiron-3421:~/Desktop/os$ insmod hello.ko
insmod: ERROR: could not insert module hello.ko: Operation not permitted
</code>```

答:
If you have secure boot enabled, the newer kernels won't allow inserting arbitrary kernel modules. So, either you can disable secure boot in your BIOS or you need to sign the kernel modules you want to install.

Steps to securely sign your kernel modules:

Create a X509 certificate that can be imported in firmware

Enrolling the  public key just created

Sign the module you want to install

Install the module

You need to be root to do steps 2 & 4. The detailed process is described in a nice Ubuntu blog.

Body:
I am just starting with modular programming.

Above are my two files:

hello.c

#include <linux/init.h>
#include <linux/module.h>

static int hello_init(void)
{
    printk(KERN_ALERT "TEST: Hello world\n");
    return 0;
}

static void hello_exit(void)
{
    printk(KERN_ALERT "TEST: Good Bye");
}

module_init(hello_init);
module_exit(hello_exit);

Makefile

obj-m += hello.o

KDIR = /usr/src/linux-headers-3.13.0-46-generic

all:
    $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules

clean:
    rm -rf *.o *.ko *.mod.* *.symvers *.order

And here's my terminal output showing error in insmod command, kindly help.

anubhav@anubhav-Inspiron-3421:~/Desktop/os$ make
make -C /usr/src/linux-headers-3.13.0-46-generic  SUBDIRS=/home/anubhav/Desktop/os modules
make[1]: Entering directory `/usr/src/linux-headers-3.13.0-46-generic'
Building modules, stage 2.
MODPOST 1 modules
make[1]: Leaving directory `/usr/src/linux-headers-3.13.0-46-generic'
anubhav@anubhav-Inspiron-3421:~/Desktop/os$ insmod hello.ko
insmod: ERROR: could not insert module hello.ko: Operation not permitted


问:
Equal frame size in a multiplot 3x4
I have the following multiplot

```<code>set encoding iso_8859_1

set xtics font "Helvetica,16"
set ytics font "Helvetica,16"

set terminal postscript eps enhanced color size 12in,6in
set grid

set key box vertical width 2 height 0.75 maxcols 1 #spacing 1
load "../estilos.txt"

# TMARGIN = "set tmargin at screen 0.90; set bmargin at screen 0.55"
# BMARGIN = "set tmargin at screen 0.55; set bmargin at screen 0.20"
# LMARGIN = "set lmargin at screen 0.15; set rmargin at screen 0.55"
# RMARGIN = "set lmargin at screen 0.55; set rmargin at screen 0.95"
############################################################################################
set output "_Mult_16R_4Chk_mp.eps"

set title "Minimum number of contention intervals, {/Symbol D}=1" font "Helvetica,17"

set multiplot layout 3,4 columnsfirst
set xlabel ""
set ylabel "T [s]" font "Helvetica,19"
set key top left font "Helvetica,16"
# @TMARGIN @LMARGIN
plot [0:40][0:140] "contention_1/sys-time-4-16-80-15-2.txt" u ($1/60):2 every 2  ls 20   ps 0.35  title "MSL=80%"

set title ""
set key top left font "Helvetica,16"
set ylabel "Queue length [batches]" font "Helvetica,19"
# @BMARGIN; @LMARGIN
plot [0:40][0:70] "contention_1/queue-length-4-16-50-15-1.txt"  using ($1/60):2 every 2 with lines  ls 20    lw 1.5   title "MSL=50%" ,\
                  "contention_1/queue-length-4-16-80-15-2.txt" using  ($1/60):2  every 2 with lines  ls 2200  lw 1.5   title "MSL=80%" ,\
                  "contention_1/queue-length-4-16-98-15-3.txt" using  ($1/60):2  every 2 with lines  ls 5550  lw 1.5   title "MSL=98%"

set key bottom right font "Helvetica,16"
set ylabel "Inventory ratio, {/Symbol g}" font "Helvetica,19"
set xlabel "Operation time [minutes]" font "Helvetica,19"

# @BMARGIN; @LMARGIN
plot [0:40][0:1] "contention_1/known-ratio-4-16-50-15-1.txt"  using ($1/60):2 every 2 w linespoints  ls 20   ps 0.75 lw 1.5    title "MSL=50%" ,\
                 "contention_1/known-ratio-4-16-80-15-2.txt" using  ($1/60):2  every 2 w linespoints  ls 2200 ps 0.75 lw 1.5       title "MSL=80%" ,\
                 "contention_1/known-ratio-4-16-98-15-3.txt" using  ($1/60):2  every 2 w linespoints  ls 5550 ps 0.75 lw 1.5         title "MSL=98%"

############################################################################################

set title "Minimum number of contention intervals, {/Symbol D}=100" font "Helvetica,17"

set xlabel ""
set ylabel ""
set key top left font "Helvetica,16"
plot [0:40][0:140] "contention_100/sys-time-4-16-80-15-2.txt" u ($1/60):2 every 2  ls 20   ps 0.35  title "MSL=80%"

set title ""
set key top left font "Helvetica,16"
plot [0:40][0:70] "contention_100/queue-length-4-16-50-15-1.txt"  using ($1/60):2 every 2 with lines  ls 20    lw 1.5   title "MSL=50%" ,\
                  "contention_100/queue-length-4-16-80-15-2.txt" using  ($1/60):2  every 2 with lines  ls 2200  lw 1.5   title "MSL=80%" ,\
                  "contention_100/queue-length-4-16-98-15-3.txt" using  ($1/60):2  every 2 with lines  ls 5550  lw 1.5   title "MSL=98%"

set key bottom right font "Helvetica,16"
set xlabel "Operation time [minutes]" font "Helvetica,19"

plot [0:40][0:1] "contention_100/known-ratio-4-16-50-15-1.txt"  using ($1/60):2 every 2 w linespoints  ls 20   ps 0.75 lw 1.5    title "MSL=50%" ,\
                 "contention_100/known-ratio-4-16-80-15-2.txt" using  ($1/60):2  every 2 w linespoints  ls 2200 ps 0.75 lw 1.5       title "MSL=80%" ,\
                 "contention_100/known-ratio-4-16-98-15-3.txt" using  ($1/60):2  every 2 w linespoints  ls 5550 ps 0.75 lw 1.5         title "MSL=98%"

############################################################################################

set title "Minimum number of contention intervals, {/Symbol D}=200" font "Helvetica,17"

set xlabel ""
set ylabel ""
set key top left font "Helvetica,16"
plot [0:40][0:140] "contention_200/sys-time-4-16-80-15-2.txt" u ($1/60):2 every 2  ls 20   ps 0.35  title "MSL=80%"

set title ""
set key top left font "Helvetica,16"
plot [0:40][0:70] "contention_200/queue-length-4-16-50-15-1.txt"  using ($1/60):2 every 2 with lines  ls 20    lw 1.5   title "MSL=50%" ,\
                  "contention_200/queue-length-4-16-80-15-2.txt" using  ($1/60):2  every 2 with lines  ls 2200  lw 1.5   title "MSL=80%" ,\
                  "contention_200/queue-length-4-16-98-15-3.txt" using  ($1/60):2  every 2 with lines  ls 5550  lw 1.5   title "MSL=98%"

set key bottom right font "Helvetica,16"
set xlabel "Operation time [minutes]" font "Helvetica,19"

plot [0:40][0:1] "contention_200/known-ratio-4-16-50-15-1.txt"  using ($1/60):2 every 2 w linespoints  ls 20   ps 0.75 lw 1.5    title "MSL=50%" ,\
                 "contention_200/known-ratio-4-16-80-15-2.txt" using  ($1/60):2  every 2 w linespoints  ls 2200 ps 0.75 lw 1.5       title "MSL=80%" ,\
                 "contention_200/known-ratio-4-16-98-15-3.txt" using  ($1/60):2  every 2 w linespoints  ls 5550 ps 0.75 lw 1.5         title "MSL=98%"

############################################################################################

set title "Minimum number of contention intervals, {/Symbol D}=300" font "Helvetica,17"

set xlabel ""
set ylabel ""
# set ylabel "T [s]" font "Helvetica,19"
set key top left font "Helvetica,16"
plot [0:40][0:140] "contention_300/sys-time-4-16-80-15-300-2.txt" u ($1/60):2 every 2  ls 20   ps 0.35  title "MSL=80%"

set title ""
set key top left font "Helvetica,16"
plot [0:40][0:70] "contention_300/queue-length-4-16-50-15-300-1.txt"  using ($1/60):2 every 2 with lines  ls 20    lw 1.5   title "MSL=50%" ,\
                  "contention_300/queue-length-4-16-80-15-300-2.txt" using  ($1/60):2  every 2 with lines  ls 2200  lw 1.5   title "MSL=80%" ,\
                  "contention_300/queue-length-4-16-98-15-300-3.txt" using  ($1/60):2  every 2 with lines  ls 5550  lw 1.5   title "MSL=98%"

set key bottom right font "Helvetica,16"
set xlabel "Operation time [minutes]" font "Helvetica,19"

plot [0:40][0:1] "contention_300/known-ratio-4-16-50-15-300-1.txt"  using ($1/60):2 every 2 w linespoints  ls 20   ps 0.75 lw 1.5    title "MSL=50%" ,\
                 "contention_300/known-ratio-4-16-80-15-300-2.txt" using  ($1/60):2  every 2 w linespoints  ls 2200 ps 0.75 lw 1.5       title "MSL=80%" ,\
                 "contention_300/known-ratio-4-16-98-15-300-3.txt" using  ($1/60):2  every 2 w linespoints  ls 5550 ps 0.75 lw 1.5  title "MSL=98%"

unset multiplot
</code>```

The data files are linked here.

The plot looks like this:

which has the information I want to show.

However, the frames are not equal in size. For example, the first row is shorter because it has titles,  the middle row of plots is bigger, and the bottom row is also small. The widths of single plots are differents too.

I have seen in this post of Gnuplotting Multiplot – placing graphs next to each other that using set l/b/r/tmargin at screen value is the way to set the sizes of the frames in a multiplot 2x2, but in my case multiplot 3x4 and with tics and separation between single plots result more difficult to achieve.

答:
To my opinion, you probably should forget about set multiplot layout 3,4. Instead, set the sizes and origins of the plots yourself and insert the titles and xlabels as labels at the top and at the bottom. Then use a few parameters to tune your layout. If the code might not be self-explaining enough do not hesitate to ask.

Code:

```<code>### customized multiplot
reset session

# Parameters to tune
PlotRows = 3
PlotCols = 4
TitlePosY = 0.98
MultiPlotTop = 0.93
SizeScalingX = 0.90
SizeScalingY = 0.95
MultiPlotBottom = 0.05
XLabelPosY = 0.03
MultiPlotLeft = 0.07
YLabelPosX = 0.02
set lmargin 2

# define origin functions
PlotGridX = (1-MultiPlotLeft)/PlotCols
PlotOriginX(n) = ((n-1)%PlotCols)*PlotGridX + MultiPlotLeft
PlotGridY = (MultiPlotTop-MultiPlotBottom)/PlotRows
PlotOriginY(n) = (PlotRows-1-int((n-1)/PlotCols))*PlotGridY + MultiPlotBottom

# set size
    set size SizeScalingX*(1-MultiPlotLeft)/PlotCols, SizeScalingY*(MultiPlotTop+MultiPlotBottom)/PlotRows

# set your titles and labels
TitleStd = "Minimum number of \ncontention intervals, {/Symbol D}="
TitleVar = "1 100 200 300"
XLabelStd = "Operation time [minutes]"
do for [i=1:PlotCols] {
    set label i at screen PlotOriginX(i), screen TitlePosY TitleStd.word(TitleVar,i) font "Helvetica,8"
    set label i+10 at screen PlotOriginX(i), screen XLabelPosY XLabelStd font "Helvetica,8"
}
YLabels = '"T [s]" "Queue length [batches]" "Inventory ratio, {/Symbol g}"'
do for [i=1:PlotRows] {
    set label i+20 at screen YLabelPosX, screen PlotOriginY(i*PlotCols)+PlotGridY*0.5 word(YLabels,i) rotate by 90 center
}

set multiplot
    do for [i=1:12] {   # do your 3x4 plots here and increase "counter" i after each plot
        set origin PlotOriginX(i), PlotOriginY(i)
        plot 10**((i-1)/4)*sin(0.1*i*x) notitle
    }
unset multiplot
### end of code
</code>```

Result:

Title: Equal frame size in a multiplot 3x4

Body:
I have the following multiplot

set encoding iso_8859_1

set xtics font "Helvetica,16"
set ytics font "Helvetica,16"

set terminal postscript eps enhanced color size 12in,6in
set grid

set key box vertical width 2 height 0.75 maxcols 1 #spacing 1
load "../estilos.txt"

# TMARGIN = "set tmargin at screen 0.90; set bmargin at screen 0.55"
# BMARGIN = "set tmargin at screen 0.55; set bmargin at screen 0.20"
# LMARGIN = "set lmargin at screen 0.15; set rmargin at screen 0.55"
# RMARGIN = "set lmargin at screen 0.55; set rmargin at screen 0.95"
############################################################################################
set output "_Mult_16R_4Chk_mp.eps"

set title "Minimum number of contention intervals, {/Symbol D}=1" font "Helvetica,17"

set multiplot layout 3,4 columnsfirst
set xlabel ""
set ylabel "T [s]" font "Helvetica,19"
set key top left font "Helvetica,16"
# @TMARGIN @LMARGIN
plot [0:40][0:140] "contention_1/sys-time-4-16-80-15-2.txt" u ($1/60):2 every 2  ls 20   ps 0.35  title "MSL=80%"

set title ""
set key top left font "Helvetica,16"
set ylabel "Queue length [batches]" font "Helvetica,19"
# @BMARGIN; @LMARGIN
plot [0:40][0:70] "contention_1/queue-length-4-16-50-15-1.txt"  using ($1/60):2 every 2 with lines  ls 20    lw 1.5   title "MSL=50%" ,\
                  "contention_1/queue-length-4-16-80-15-2.txt" using  ($1/60):2  every 2 with lines  ls 2200  lw 1.5   title "MSL=80%" ,\
                  "contention_1/queue-length-4-16-98-15-3.txt" using  ($1/60):2  every 2 with lines  ls 5550  lw 1.5   title "MSL=98%"

set key bottom right font "Helvetica,16"
set ylabel "Inventory ratio, {/Symbol g}" font "Helvetica,19"
set xlabel "Operation time [minutes]" font "Helvetica,19"

# @BMARGIN; @LMARGIN
plot [0:40][0:1] "contention_1/known-ratio-4-16-50-15-1.txt"  using ($1/60):2 every 2 w linespoints  ls 20   ps 0.75 lw 1.5    title "MSL=50%" ,\
                 "contention_1/known-ratio-4-16-80-15-2.txt" using  ($1/60):2  every 2 w linespoints  ls 2200 ps 0.75 lw 1.5       title "MSL=80%" ,\
                 "contention_1/known-ratio-4-16-98-15-3.txt" using  ($1/60):2  every 2 w linespoints  ls 5550 ps 0.75 lw 1.5         title "MSL=98%"

############################################################################################

set title "Minimum number of contention intervals, {/Symbol D}=100" font "Helvetica,17"

set xlabel ""
set ylabel ""
set key top left font "Helvetica,16"
plot [0:40][0:140] "contention_100/sys-time-4-16-80-15-2.txt" u ($1/60):2 every 2  ls 20   ps 0.35  title "MSL=80%"

set title ""
set key top left font "Helvetica,16"
plot [0:40][0:70] "contention_100/queue-length-4-16-50-15-1.txt"  using ($1/60):2 every 2 with lines  ls 20    lw 1.5   title "MSL=50%" ,\
                  "contention_100/queue-length-4-16-80-15-2.txt" using  ($1/60):2  every 2 with lines  ls 2200  lw 1.5   title "MSL=80%" ,\
                  "contention_100/queue-length-4-16-98-15-3.txt" using  ($1/60):2  every 2 with lines  ls 5550  lw 1.5   title "MSL=98%"

set key bottom right font "Helvetica,16"
set xlabel "Operation time [minutes]" font "Helvetica,19"

plot [0:40][0:1] "contention_100/known-ratio-4-16-50-15-1.txt"  using ($1/60):2 every 2 w linespoints  ls 20   ps 0.75 lw 1.5    title "MSL=50%" ,\
                 "contention_100/known-ratio-4-16-80-15-2.txt" using  ($1/60):2  every 2 w linespoints  ls 2200 ps 0.75 lw 1.5       title "MSL=80%" ,\
                 "contention_100/known-ratio-4-16-98-15-3.txt" using  ($1/60):2  every 2 w linespoints  ls 5550 ps 0.75 lw 1.5         title "MSL=98%"

############################################################################################

set title "Minimum number of contention intervals, {/Symbol D}=200" font "Helvetica,17"

set xlabel ""
set ylabel ""
set key top left font "Helvetica,16"
plot [0:40][0:140] "contention_200/sys-time-4-16-80-15-2.txt" u ($1/60):2 every 2  ls 20   ps 0.35  title "MSL=80%"

set title ""
set key top left font "Helvetica,16"
plot [0:40][0:70] "contention_200/queue-length-4-16-50-15-1.txt"  using ($1/60):2 every 2 with lines  ls 20    lw 1.5   title "MSL=50%" ,\
                  "contention_200/queue-length-4-16-80-15-2.txt" using  ($1/60):2  every 2 with lines  ls 2200  lw 1.5   title "MSL=80%" ,\
                  "contention_200/queue-length-4-16-98-15-3.txt" using  ($1/60):2  every 2 with lines  ls 5550  lw 1.5   title "MSL=98%"

set key bottom right font "Helvetica,16"
set xlabel "Operation time [minutes]" font "Helvetica,19"

plot [0:40][0:1] "contention_200/known-ratio-4-16-50-15-1.txt"  using ($1/60):2 every 2 w linespoints  ls 20   ps 0.75 lw 1.5    title "MSL=50%" ,\
                 "contention_200/known-ratio-4-16-80-15-2.txt" using  ($1/60):2  every 2 w linespoints  ls 2200 ps 0.75 lw 1.5       title "MSL=80%" ,\
                 "contention_200/known-ratio-4-16-98-15-3.txt" using  ($1/60):2  every 2 w linespoints  ls 5550 ps 0.75 lw 1.5         title "MSL=98%"

############################################################################################

set title "Minimum number of contention intervals, {/Symbol D}=300" font "Helvetica,17"

set xlabel ""
set ylabel ""
# set ylabel "T [s]" font "Helvetica,19"
set key top left font "Helvetica,16"
plot [0:40][0:140] "contention_300/sys-time-4-16-80-15-300-2.txt" u ($1/60):2 every 2  ls 20   ps 0.35  title "MSL=80%"

set title ""
set key top left font "Helvetica,16"
plot [0:40][0:70] "contention_300/queue-length-4-16-50-15-300-1.txt"  using ($1/60):2 every 2 with lines  ls 20    lw 1.5   title "MSL=50%" ,\
                  "contention_300/queue-length-4-16-80-15-300-2.txt" using  ($1/60):2  every 2 with lines  ls 2200  lw 1.5   title "MSL=80%" ,\
                  "contention_300/queue-length-4-16-98-15-300-3.txt" using  ($1/60):2  every 2 with lines  ls 5550  lw 1.5   title "MSL=98%"

set key bottom right font "Helvetica,16"
set xlabel "Operation time [minutes]" font "Helvetica,19"

plot [0:40][0:1] "contention_300/known-ratio-4-16-50-15-300-1.txt"  using ($1/60):2 every 2 w linespoints  ls 20   ps 0.75 lw 1.5    title "MSL=50%" ,\
                 "contention_300/known-ratio-4-16-80-15-300-2.txt" using  ($1/60):2  every 2 w linespoints  ls 2200 ps 0.75 lw 1.5       title "MSL=80%" ,\
                 "contention_300/known-ratio-4-16-98-15-300-3.txt" using  ($1/60):2  every 2 w linespoints  ls 5550 ps 0.75 lw 1.5  title "MSL=98%"

unset multiplot

The data files are linked here.

The plot looks like this:

which has the information I want to show.

However, the frames are not equal in size. For example, the first row is shorter because it has titles,  the middle row of plots is bigger, and the bottom row is also small. The widths of single plots are differents too.

I have seen in this post of Gnuplotting Multiplot – placing graphs next to each other that using set l/b/r/tmargin at screen value is the way to set the sizes of the frames in a multiplot 2x2, but in my case multiplot 3x4 and with tics and separation between single plots result more difficult to achieve.

Body:
To my opinion, you probably should forget about set multiplot layout 3,4. Instead, set the sizes and origins of the plots yourself and insert the titles and xlabels as labels at the top and at the bottom. Then use a few parameters to tune your layout. If the code might not be self-explaining enough do not hesitate to ask.

Code:

### customized multiplot
reset session

# Parameters to tune
PlotRows = 3
PlotCols = 4
TitlePosY = 0.98
MultiPlotTop = 0.93
SizeScalingX = 0.90
SizeScalingY = 0.95
MultiPlotBottom = 0.05
XLabelPosY = 0.03
MultiPlotLeft = 0.07
YLabelPosX = 0.02
set lmargin 2

# define origin functions
PlotGridX = (1-MultiPlotLeft)/PlotCols
PlotOriginX(n) = ((n-1)%PlotCols)*PlotGridX + MultiPlotLeft
PlotGridY = (MultiPlotTop-MultiPlotBottom)/PlotRows
PlotOriginY(n) = (PlotRows-1-int((n-1)/PlotCols))*PlotGridY + MultiPlotBottom

# set size
    set size SizeScalingX*(1-MultiPlotLeft)/PlotCols, SizeScalingY*(MultiPlotTop+MultiPlotBottom)/PlotRows

# set your titles and labels
TitleStd = "Minimum number of \ncontention intervals, {/Symbol D}="
TitleVar = "1 100 200 300"
XLabelStd = "Operation time [minutes]"
do for [i=1:PlotCols] {
    set label i at screen PlotOriginX(i), screen TitlePosY TitleStd.word(TitleVar,i) font "Helvetica,8"
    set label i+10 at screen PlotOriginX(i), screen XLabelPosY XLabelStd font "Helvetica,8"
}
YLabels = '"T [s]" "Queue length [batches]" "Inventory ratio, {/Symbol g}"'
do for [i=1:PlotRows] {
    set label i+20 at screen YLabelPosX, screen PlotOriginY(i*PlotCols)+PlotGridY*0.5 word(YLabels,i) rotate by 90 center
}

set multiplot
    do for [i=1:12] {   # do your 3x4 plots here and increase "counter" i after each plot
        set origin PlotOriginX(i), PlotOriginY(i)
        plot 10**((i-1)/4)*sin(0.1*i*x) notitle
    }
unset multiplot
### end of code

Result:


问:
Angular 5 event emitter triggered twice
I am using angular 5. In which I am passing data from one component to another component using eventemitter.

At first click event emitter is not subscribe the value in child component. On second click event emitter triggered twice.

Header component.ts

```<code> this.testservice.sendsearchdata.next( this.searchdataform.value)
</code>```

Search component.ts

```<code>this.testservice.sendsearchdata.subscribe(value=>{
    console.log( value)
})
</code>```

testservice.ts

```<code>  public testservice: EventEmitter<any> = new EventEmitter ():
</code>```

While passing reactive form data from header component to search component it's not triggered at first click. On next click it has triggered twice.

答:
My event emitter was bound to button click event.
<button class="signin-button btn-primary btn" (click)="submit()">Create Account</button>

By switching the button input to an a tag.
Create Account

It stopped triggering more than one event.

Title: Angular 5 event emitter triggered twice

Body:
I am using angular 5. In which I am passing data from one component to another component using eventemitter.

At first click event emitter is not subscribe the value in child component. On second click event emitter triggered twice.

Header component.ts

 this.testservice.sendsearchdata.next( this.searchdataform.value)

Search component.ts

this.testservice.sendsearchdata.subscribe(value=>{
    console.log( value)
})

testservice.ts

  public testservice: EventEmitter<any> = new EventEmitter ():

While passing reactive form data from header component to search component it's not triggered at first click. On next click it has triggered twice.

Body:
My event emitter was bound to button click event.
<button class="signin-button btn-primary btn" (click)="submit()">Create Account</button>

By switching the button input to an a tag.
<a class="signin-button btn-primary btn" (click)="submit()">Create Account</a>

It stopped triggering more than one event.


问:
Easily strip alpha channel from images in Mathematica
What is the simplest way to strip the alpha channel (and possible convert images to greyscale) in Mathematica?

I would like to use ImageAssemble, but some of the images come with and some without an alpha channel.  Is there a simpler built-in way than manipulating the ImageData directly?

答: The RemoveAlphaChannel function will do this.


问:
5 Column background DIV to fill empty space
I need all of my columns on a page to appear be the same height. I'd be fine doing this if there were just one background colour but there are 5, taking up 20% of the width each on a desktop.

.container {
    display: table;
    float: left;
    width: 100%;
    background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
}

.col1 {
    float: left;
    width: 20%;
    background-color: #91F5AD;
}

@media only screen and (max-width: 500px) {
.col1{
    float: left;
    width: 100%;
    background-color: #91F5AD;
}
}

.col2 {
    float: left;
    width: 20%;
    background-color: #8FBFE0;
}

@media only screen and (max-width: 500px) {
.col2{
    float: left;
    width: 100%;
    background-color: #8FBFE0;
}
}

.col3 {
    float: left;
    width: 20%;
    background-color: #7C77B9;
}

@media only screen and (max-width: 500px) {
.col3{
    float: left;
    width: 100%;
    background-color: #7C77B9;
}
}

.col4 {
    float: left;
    width: 20%;
    background-color: #0BC9CD;
}

@media only screen and (max-width: 500px) {
.col4{
    float: left;
    width: 100%;
    background-color: #0BC9CD;
}
}

.col5 {
    float: left;
    width: 20%;
    background-color: #05A8AA;
}

@media only screen and (max-width: 500px) {
.col5{
    float: left;
    width: 100%;
    background-color: #05A8AA;
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="col1"><br></div>
<div class="col2"><br></div>
<div class="col3"><br></div>
<div class="col4"><br></div>
<div class="col5"><br></div>
</div></code>```

I need the container to replicate the pattern of the DIV backgrounds in order to make it seem as though they're all the same height.

If you see below, you'll see the issue.

    .container {
        display: table;
        float: left;
        width: 100%;
        background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
    }

    .col1 {
        float: left;
        width: 20%;
        background-color: #91F5AD;
    }

    @media only screen and (max-width: 500px) {
    .col1{
        float: left;
        width: 100%;
        background-color: #91F5AD;
    }
    }

    .col2 {
        float: left;
        width: 20%;
        background-color: #8FBFE0;
    }

    @media only screen and (max-width: 500px) {
    .col2{
        float: left;
        width: 100%;
        background-color: #8FBFE0;
    }
    }

    .col3 {
        float: left;
        width: 20%;
        background-color: #7C77B9;
    }

    @media only screen and (max-width: 500px) {
    .col3{
        float: left;
        width: 100%;
        background-color: #7C77B9;
    }
    }

    .col4 {
        float: left;
        width: 20%;
        background-color: #0BC9CD;
    }

    @media only screen and (max-width: 500px) {
    .col4{
        float: left;
        width: 100%;
        background-color: #0BC9CD;
    }
    }

    .col5 {
        float: left;
        width: 20%;
        background-color: #05A8AA;
    }

    @media only screen and (max-width: 500px) {
    .col5{
        float: left;
        width: 100%;
        background-color: #05A8AA;
    }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="col1"><br></div>
<div class="col2"><br></div>
<div class="col3"><br></div>
<div class="col4"><br></div>
<div class="col5"><br></div>
<br><br>
</div>
<p>The green is fine but the rest don't match above themselves</p></code>```

Any help would be appreciated. Thanks in advance.

答:
Make the display of the children divs table-cell since you have the parent's display as table, and remove the floats:

```<code>.container > div {
display:table-cell;
}
</code>```

Example:

.container {
  display: table;
  float: left;
  width: 100%;
  background: linear-gradient(to right, #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
}

.col1 {
  width: 20%;
  background-color: #91F5AD;
}

.container>div {
  display: table-cell;
}

@media only screen and (max-width: 500px) {
  .col1 {
    width: 100%;
    background-color: #91F5AD;
  }
}

.col2 {
  width: 20%;
  background-color: #8FBFE0;
}

@media only screen and (max-width: 500px) {
  .col2 {
    width: 100%;
    background-color: #8FBFE0;
  }
}

.col3 {
  width: 20%;
  background-color: #7C77B9;
}

@media only screen and (max-width: 500px) {
  .col3 {
    width: 100%;
    background-color: #7C77B9;
  }
}

.col4 {
  width: 20%;
  background-color: #0BC9CD;
}

@media only screen and (max-width: 500px) {
  .col4 {
    width: 100%;
    background-color: #0BC9CD;
  }
}

.col5 {
  width: 20%;
  background-color: #05A8AA;
}

@media only screen and (max-width: 500px) {
  .col5 {
    width: 100%;
    background-color: #05A8AA;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="col1"><br></div>
  <div class="col2"><br></div>
  <div class="col3"><br></div>
  <div class="col4"><br></div>
  <div class="col5"><br></div>
  <br><br>
</div>
<p>The green is fine but the rest don't match above themselves</p></code>```

Body:
I need all of my columns on a page to appear be the same height. I'd be fine doing this if there were just one background colour but there are 5, taking up 20% of the width each on a desktop.

.container {
    display: table;
    float: left;
    width: 100%;
    background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
}

.col1 {
    float: left;
    width: 20%;
    background-color: #91F5AD;
}

@media only screen and (max-width: 500px) {
.col1{
    float: left;
    width: 100%;
    background-color: #91F5AD;
}
}

.col2 {
    float: left;
    width: 20%;
    background-color: #8FBFE0;
}

@media only screen and (max-width: 500px) {
.col2{
    float: left;
    width: 100%;
    background-color: #8FBFE0;
}
}

.col3 {
    float: left;
    width: 20%;
    background-color: #7C77B9;
}

@media only screen and (max-width: 500px) {
.col3{
    float: left;
    width: 100%;
    background-color: #7C77B9;
}
}

.col4 {
    float: left;
    width: 20%;
    background-color: #0BC9CD;
}

@media only screen and (max-width: 500px) {
.col4{
    float: left;
    width: 100%;
    background-color: #0BC9CD;
}
}

.col5 {
    float: left;
    width: 20%;
    background-color: #05A8AA;
}

@media only screen and (max-width: 500px) {
.col5{
    float: left;
    width: 100%;
    background-color: #05A8AA;
}
}

I need the container to replicate the pattern of the DIV backgrounds in order to make it seem as though they're all the same height.

If you see below, you'll see the issue.

    .container {
        display: table;
        float: left;
        width: 100%;
        background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
    }

    .col1 {
        float: left;
        width: 20%;
        background-color: #91F5AD;
    }

    @media only screen and (max-width: 500px) {
    .col1{
        float: left;
        width: 100%;
        background-color: #91F5AD;
    }
    }

    .col2 {
        float: left;
        width: 20%;
        background-color: #8FBFE0;
    }

    @media only screen and (max-width: 500px) {
    .col2{
        float: left;
        width: 100%;
        background-color: #8FBFE0;
    }
    }

    .col3 {
        float: left;
        width: 20%;
        background-color: #7C77B9;
    }

    @media only screen and (max-width: 500px) {
    .col3{
        float: left;
        width: 100%;
        background-color: #7C77B9;
    }
    }

    .col4 {
        float: left;
        width: 20%;
        background-color: #0BC9CD;
    }

    @media only screen and (max-width: 500px) {
    .col4{
        float: left;
        width: 100%;
        background-color: #0BC9CD;
    }
    }

    .col5 {
        float: left;
        width: 20%;
        background-color: #05A8AA;
    }

    @media only screen and (max-width: 500px) {
    .col5{
        float: left;
        width: 100%;
        background-color: #05A8AA;
    }
    }

The green is fine but the rest don't match above themselves

Any help would be appreciated. Thanks in advance.

Body:
Make the display of the children divs table-cell since you have the parent's display as table, and remove the floats:

.container > div {
display:table-cell;
}

Example:

.container {
  display: table;
  float: left;
  width: 100%;
  background: linear-gradient(to right, #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
}

.col1 {
  width: 20%;
  background-color: #91F5AD;
}

.container>div {
  display: table-cell;
}

@media only screen and (max-width: 500px) {
  .col1 {
    width: 100%;
    background-color: #91F5AD;
  }
}

.col2 {
  width: 20%;
  background-color: #8FBFE0;
}

@media only screen and (max-width: 500px) {
  .col2 {
    width: 100%;
    background-color: #8FBFE0;
  }
}

.col3 {
  width: 20%;
  background-color: #7C77B9;
}

@media only screen and (max-width: 500px) {
  .col3 {
    width: 100%;
    background-color: #7C77B9;
  }
}

.col4 {
  width: 20%;
  background-color: #0BC9CD;
}

@media only screen and (max-width: 500px) {
  .col4 {
    width: 100%;
    background-color: #0BC9CD;
  }
}

.col5 {
  width: 20%;
  background-color: #05A8AA;
}

@media only screen and (max-width: 500px) {
  .col5 {
    width: 100%;
    background-color: #05A8AA;
  }
}

<div class="container">
  <div class="col1"><br></div>
  <div class="col2"><br></div>
  <div class="col3"><br></div>
  <div class="col4"><br></div>
  <div class="col5"><br></div>
  <br><br>
</div>
<p>The green is fine but the rest don't match above themselves</p>


问:
Google Big Query SPLIT() function using #standardsql
I am trying to use the SPLIT() function to convert an array of strings into individual rows.

The data looks something like this:

```<code>id   ticket
1    1,2,3,4,5,6,7,8,9...etc.
2    11,12,13,14,15,16,17,18,19...etc.
3    21,22,23,24,25,26,27,28,29...etc.
</code>```

I would want the data to look like this:

```<code>id   ticket
1    1
1    2
1    3
1    4
1    5
1    6
1    7
1    8
1    9
2    11
2    12
2    13
2    14
2    15
2    16
</code>```

...and so on. When I use the following:
SELECT id, SPLIT(ticket) FROM table, I get exactly the result I want. The problem is, I have to join this table with another table which is partitioned and I cannot use legacy SQL. Because of the multiple tickets associated with each id (up to 200), typing out each one seems inefficient. The ticket numbers are also formatted as a string.

If anyone has a solution for this, it would be greatly appreciated!

答:
Below example for BigQuery Standard SQL

```<code>#standardSQL
SELECT id, CAST(ticket AS INT64) ticket
FROM `project.dataset.table`,
UNNEST(SPLIT(ticket)) ticket
</code>```

You can test, play with above using sample data from your question as in example below

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 id, '1,2,3,4,5,6,7,8,9' ticket UNION ALL
  SELECT 2, '11,12,13,14,15,16,17,18,19' UNION ALL
  SELECT 3, '21,22,23,24,25,26,27,28,29'
)
SELECT id, CAST(ticket AS INT64) ticket
FROM `project.dataset.table`,
UNNEST(SPLIT(ticket)) ticket
</code>```

with result

```<code>Row id  ticket
1   1   1
2   1   2
3   1   3
4   1   4
5   1   5
6   1   6
7   1   7
8   1   8
9   1   9
10  2   11
11  2   12
12  2   13
13  2   14
14  2   15
15  2   16
16  2   17
17  2   18
18  2   19
19  3   21
20  3   22
21  3   23
22  3   24
23  3   25
24  3   26
25  3   27
26  3   28
27  3   29
</code>```

Body:
I am trying to use the SPLIT() function to convert an array of strings into individual rows.

The data looks something like this:

id   ticket
1    1,2,3,4,5,6,7,8,9...etc.
2    11,12,13,14,15,16,17,18,19...etc.
3    21,22,23,24,25,26,27,28,29...etc.

I would want the data to look like this:

id   ticket
1    1
1    2
1    3
1    4
1    5
1    6
1    7
1    8
1    9
2    11
2    12
2    13
2    14
2    15
2    16

...and so on. When I use the following:
SELECT id, SPLIT(ticket) FROM table, I get exactly the result I want. The problem is, I have to join this table with another table which is partitioned and I cannot use legacy SQL. Because of the multiple tickets associated with each id (up to 200), typing out each one seems inefficient. The ticket numbers are also formatted as a string.

If anyone has a solution for this, it would be greatly appreciated!

Body:
Below example for BigQuery Standard SQL

#standardSQL
SELECT id, CAST(ticket AS INT64) ticket
FROM `project.dataset.table`,
UNNEST(SPLIT(ticket)) ticket

You can test, play with above using sample data from your question as in example below

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 id, '1,2,3,4,5,6,7,8,9' ticket UNION ALL
  SELECT 2, '11,12,13,14,15,16,17,18,19' UNION ALL
  SELECT 3, '21,22,23,24,25,26,27,28,29'
)
SELECT id, CAST(ticket AS INT64) ticket
FROM `project.dataset.table`,
UNNEST(SPLIT(ticket)) ticket

with result

Row id  ticket
1   1   1
2   1   2
3   1   3
4   1   4
5   1   5
6   1   6
7   1   7
8   1   8
9   1   9
10  2   11
11  2   12
12  2   13
13  2   14
14  2   15
15  2   16
16  2   17
17  2   18
18  2   19
19  3   21
20  3   22
21  3   23
22  3   24
23  3   25
24  3   26
25  3   27
26  3   28
27  3   29


问:
How view different categorized articles in cshtml?
I am trying to build a blog website. There are 3 different categories in my database: art, technology, design.

I want to show the last added article for each category. I mean:

```<code>ART                       TECHNOLOGY                DESIGN
last articles             last article              last article
</code>```

In ActionResult, sended all articles here:

```<code>public ActionResult Index()
{
   using (MvcBlogContext context = new MvcBlogContext())
   {
      List<Article> article= context.Article.ToList();
      return View(article);
   }
}
</code>```

How to code to view for each category's last article in cshtml?

答:
You can do it by Grouping according to Category then SelectMany to select from each category after ordering by CreationDate desc. and Take top 1 of each category
as following:

```<code>public ActionResult Index()
{
   using (MvcBlogContext context = new MvcBlogContext())
   {
      List<Article> article= context.Article.GroupBy(x => x.Category)
                            .SelectMany(x => x.OrderByDescending(s => s.CreationDate).Take(1)).ToList();
      return View(article);
   }
}
</code>```

Body:
I am trying to build a blog website. There are 3 different categories in my database: art, technology, design.

I want to show the last added article for each category. I mean:

ART                       TECHNOLOGY                DESIGN
last articles             last article              last article

In ActionResult, sended all articles here:

public ActionResult Index()
{
   using (MvcBlogContext context = new MvcBlogContext())
   {
      List
 article= context.Article.ToList();
      return View(article);
   }
}

How to code to view for each category's last article in cshtml?

Body:
You can do it by Grouping according to Category then SelectMany to select from each category after ordering by CreationDate desc. and Take top 1 of each category
as following:

public ActionResult Index()
{
   using (MvcBlogContext context = new MvcBlogContext())
   {
      List<Article> article= context.Article.GroupBy(x => x.Category)
                            .SelectMany(x => x.OrderByDescending(s => s.CreationDate).Take(1)).ToList();
      return View(article);
   }
}


问:
Python OpenCV: Image Denoising for Text Recognition
I have this set of images I want to de-noise in order to run OCR on it:

I am trying to read the 7810 from the image.

I have tried

```<code>cv2.threshold(img, 128, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
cv2.fastNlMeansDenoising(img,None,60,10,20)
</code>```

and some morphological expressions but none seem to work to clear this image sufficiently.

Any recommendations on how to filter this image sufficiently that I could run OCR or some ML detection scripts on this like pytesseract?

答:
You can try using cv2.adaptiveThreshold since your image has different lighting conditions in different areas.

```<code>import cv2

image = cv2.imread("1.jpg",0)
thresh = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,21,2)

cv2.imshow('thresh', thresh)
cv2.waitKey(0)
</code>```

Body:
I have this set of images I want to de-noise in order to run OCR on it:

I am trying to read the 7810 from the image.

I have tried

cv2.threshold(img, 128, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
cv2.fastNlMeansDenoising(img,None,60,10,20)

and some morphological expressions but none seem to work to clear this image sufficiently.

Any recommendations on how to filter this image sufficiently that I could run OCR or some ML detection scripts on this like pytesseract?

Body:
You can try using cv2.adaptiveThreshold since your image has different lighting conditions in different areas.

import cv2

image = cv2.imread("1.jpg",0)
thresh = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,21,2)

cv2.imshow('thresh', thresh)
cv2.waitKey(0)


问:
Alternative to nested ternary operator in JS
I personally love ternary operators, and in my humble opinion, they make complicated expressions very easy to digest. Take this one:

```<code>  const word = (distance === 0) ? 'a'
    : (distance === 1 && diff > 3) ? 'b'
    : (distance === 2 && diff > 5 && key.length > 5) ? 'c'
    : 'd';
</code>```

However in our project's ESLINT rules nested ternary operators are forbidden, so I have to get rid of the above.

I'm trying to find out alternatives to this approach. I really don't want to turn it into a huge if / else statement, but don't know if there's any other options.

答:
We can simplify it using basic operators like && and ||

let obj = {}

function checkWord (res) {
      return (res.distance === 0)   && 'a'
             || (res.distance === 1 && res.difference > 3) && 'b'
             || (res.distance === 2 && res.difference > 5  && String(res.key).length > 5) && 'c'
             || 'd';

}

// case 1 pass
obj.distance = 0
console.log(checkWord(obj))

// case 2 pass
obj.distance = 1
obj.difference = 4
console.log(checkWord(obj))

// case 3 pass
obj.distance = 2
obj.difference = 6
obj.key = [1,2,3,4,5,6]
console.log(checkWord(obj))

// case 4 fail all cases
obj.distance = -1
console.log(checkWord(obj))```

Body:
I personally love ternary operators, and in my humble opinion, they make complicated expressions very easy to digest. Take this one:

  const word = (distance === 0) ? 'a'
    : (distance === 1 && diff > 3) ? 'b'
    : (distance === 2 && diff > 5 && key.length > 5) ? 'c'
    : 'd';

However in our project's ESLINT rules nested ternary operators are forbidden, so I have to get rid of the above.

I'm trying to find out alternatives to this approach. I really don't want to turn it into a huge if / else statement, but don't know if there's any other options.


答: Didn't get you what you exactly trying to achieve , but as far as I understood you need gradient background for all of your col. , I think in bootstrap you can easily achieve that by setting background gradient - col-12 and then drop your col. Like col-3, col-3 ....</p>

Title: 5 Column background DIV to fill empty space


问:
After updating Excel I'm no longer able to get the data using a SQL query
I updated the version of Excel to 2016 and now I am unable to simply paste SQL query.

The "Get Data" button is missing.

This is how it was before an update:

Before, I could easily go to "Data"--> GetData --> From Database --> From SQL Server Database...

答:
To get to the same window you can use "New Query" button instead of "Get Data".

Also you can to click on "From Other Sources" and then 1st option will be SQL Server:


答:
Depending on how you want the output, you could try like this:

```<code>foreach ($comp in $computers) {

    $LicenseInfo = Get-WmiObject SoftwareLicensingProduct -ComputerName $comp | Where-Object { $_.partialProductKey -and $_.ApplicationID -eq "55c92734-d682-4d71-983e-d6ec3f16059f" } | Select-Object PartialProductKey, Description, ProductKeyChannel, @{ N = "LicenseStatus"; E = { $lstat["$($_.LicenseStatus)"] } }

    $LicenseInfo
    $comp

}
</code>```

The positional parameter error you're getting in your code is because you're giving echo variables and text, and the text isn't encapsulated in quotes.

You don't need echo or even Write-Host here if you just want to output the contents of your variables.

Title: How to run Powershell on a list of computers

Body:
Depending on how you want the output, you could try like this:

foreach ($comp in $computers) {

    $LicenseInfo = Get-WmiObject SoftwareLicensingProduct -ComputerName $comp | Where-Object { $_.partialProductKey -and $_.ApplicationID -eq "55c92734-d682-4d71-983e-d6ec3f16059f" } | Select-Object PartialProductKey, Description, ProductKeyChannel, @{ N = "LicenseStatus"; E = { $lstat["$($_.LicenseStatus)"] } }

    $LicenseInfo
    $comp

}

The positional parameter error you're getting in your code is because you're giving echo variables and text, and the text isn't encapsulated in quotes.

You don't need echo or even Write-Host here if you just want to output the contents of your variables.


问:
Invalid byte sequence allthough string is a valid UTF8
I'm trying to write a txt to postgres bulk importer. The code currently crashes as the string which should get inserted to postgres isn't a valid UTF8: pq: invalid byte sequence for encoding UTF8: 0x00

In my code I'm checking if the strings are a valid UTF8 or not.

What am I missing?

Code:

```<code>for {
        line, more := <-lineChannel

        splitLine := strings.SplitN(line, ":", 2)

        if len(splitLine) == 2 {
            if utf8.Valid([]byte(splitLine[0])) && utf8.Valid([]byte(splitLine[1])) {
                lineCount++
                _, err = stmt.Exec(splitLine[0], splitLine[1])

                if lineCount%int64(copySize) == 0 {

                    _, err = stmt.Exec()
                    if err != nil {
                        log.Fatal("Failed at stmt.Exec", err)
                    }

                    err = stmt.Close()
                    if err != nil {
                        log.Fatal("Failed at stmt.Close", err)
                    }

                    err = txn.Commit()
                    if err != nil {
                        log.Fatal("failed at txn.Commit", err)
                    }

                    txn, err = db.Begin()
                    if err != nil {
                        log.Fatal("failed at db.Begin", err)
                    }

                    stmt, err = txn.Prepare(pq.CopyIn("pwned", "username", "password"))
                    if err != nil {
                        log.Fatal("failed at txn.Prepare", err)
                    }

                    if lineCount%(int64(copySize)*10) == 0 {
                        log.Printf("Inserted %v lines", lineCount)
                    }
                }

                if err != nil {
                    log.Println("error:", splitLine[0], splitLine[1])
                    log.Fatal(err)
                }
            }
</code>```

EDIT:
Line which makes the error:

Byte[]: [116 109 97 105 108 46 99 111 109 58 104 117 115 104 112 117 112 112 105 101 115 108 111 118 101]

line: username@hotmail.whatever:hushpuppieslove

splitLine[0] + splitLine[1]: username@hotmail.whatever hushpuppieslove

答:
0x00 is the null character and postgres does not allow this in strings.  From the docs:

The NULL (0) character is not allowed because text data types cannot store such bytes.

You'll need to strip out the null characters.

Body:
I'm trying to write a txt to postgres bulk importer. The code currently crashes as the string which should get inserted to postgres isn't a valid UTF8: pq: invalid byte sequence for encoding UTF8: 0x00

In my code I'm checking if the strings are a valid UTF8 or not.

What am I missing?

Code:

for {
        line, more := <-lineChannel

        splitLine := strings.SplitN(line, ":", 2)

        if len(splitLine) == 2 {
            if utf8.Valid([]byte(splitLine[0])) && utf8.Valid([]byte(splitLine[1])) {
                lineCount++
                _, err = stmt.Exec(splitLine[0], splitLine[1])

                if lineCount%int64(copySize) == 0 {

                    _, err = stmt.Exec()
                    if err != nil {
                        log.Fatal("Failed at stmt.Exec", err)
                    }

                    err = stmt.Close()
                    if err != nil {
                        log.Fatal("Failed at stmt.Close", err)
                    }

                    err = txn.Commit()
                    if err != nil {
                        log.Fatal("failed at txn.Commit", err)
                    }

                    txn, err = db.Begin()
                    if err != nil {
                        log.Fatal("failed at db.Begin", err)
                    }

                    stmt, err = txn.Prepare(pq.CopyIn("pwned", "username", "password"))
                    if err != nil {
                        log.Fatal("failed at txn.Prepare", err)
                    }

                    if lineCount%(int64(copySize)*10) == 0 {
                        log.Printf("Inserted %v lines", lineCount)
                    }
                }

                if err != nil {
                    log.Println("error:", splitLine[0], splitLine[1])
                    log.Fatal(err)
                }
            }

EDIT:
Line which makes the error:

Byte[]: [116 109 97 105 108 46 99 111 109 58 104 117 115 104 112 117 112 112 105 101 115 108 111 118 101]

line: username@hotmail.whatever:hushpuppieslove

splitLine[0] + splitLine[1]: username@hotmail.whatever hushpuppieslove


答:
Make your children divs position:relative then apply a height of 100% on them. Note: Also add   inside them (if you have no other content to put into them) so the height css property takes.

  .container {
        display: table;
        float: left;
        width: 100%;
        background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
    }

    .col1 {
        height:100%;
        position:relative;
        float: left;
        width: 20%;
        background-color: #91F5AD;
    }

    @media only screen and (max-width: 500px) {
    .col1{
        height:100%;
        position:relative;
        float: left;
        width: 100%;
        background-color: #91F5AD;
    }
    }

    .col2 {
        height:100%;
        position:relative;
        float: left;
        width: 20%;
        background-color: #8FBFE0;
    }

    @media only screen and (max-width: 500px) {
    .col2{
        height:100%;
        position:relative;
        float: left;
        width: 100%;
        background-color: #8FBFE0;
    }
    }

    .col3 {
        height:100%;
        position:relative;
        float: left;
        width: 20%;
        background-color: #7C77B9;
    }

    @media only screen and (max-width: 500px) {
    .col3{
        height:100%;
        position:relative;
        float: left;
        width: 100%;
        background-color: #7C77B9;
    }
    }

    .col4 {
        height:100%;
        position:relative;
        float: left;
        width: 20%;
        background-color: #0BC9CD;
    }

    @media only screen and (max-width: 500px) {
    .col4{
        height:100%;
        position:relative;
        float: left;
        width: 100%;
        background-color: #0BC9CD;
    }
    }

    .col5 {
        height:100%;
        position:relative;
        float: left;
        width: 20%;
        background-color: #05A8AA;
    }

    @media only screen and (max-width: 500px) {
    .col5{
        height:100%;
        position:relative;
        float: left;
        width: 100%;
        background-color: #05A8AA;
    }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="col1"><br>
 </div>
<div class="col2"><br>
 </div>
<div class="col3"><br>
 </div>
<div class="col4"><br>
 </div>
<div class="col5"><br>
 </div>
<br><br>
</div>
<p>The green is fine but the rest don't match above themselves</p></code>```

Body:
Make your children divs position:relative then apply a height of 100% on them. Note: Also add &nbsp; inside them (if you have no other content to put into them) so the height css property takes.

  .container {
        display: table;
        float: left;
        width: 100%;
        background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
    }

    .col1 {
        height:100%;
        position:relative;
        float: left;
        width: 20%;
        background-color: #91F5AD;
    }

    @media only screen and (max-width: 500px) {
    .col1{
        height:100%;
        position:relative;
        float: left;
        width: 100%;
        background-color: #91F5AD;
    }
    }

    .col2 {
        height:100%;
        position:relative;
        float: left;
        width: 20%;
        background-color: #8FBFE0;
    }

    @media only screen and (max-width: 500px) {
    .col2{
        height:100%;
        position:relative;
        float: left;
        width: 100%;
        background-color: #8FBFE0;
    }
    }

    .col3 {
        height:100%;
        position:relative;
        float: left;
        width: 20%;
        background-color: #7C77B9;
    }

    @media only screen and (max-width: 500px) {
    .col3{
        height:100%;
        position:relative;
        float: left;
        width: 100%;
        background-color: #7C77B9;
    }
    }

    .col4 {
        height:100%;
        position:relative;
        float: left;
        width: 20%;
        background-color: #0BC9CD;
    }

    @media only screen and (max-width: 500px) {
    .col4{
        height:100%;
        position:relative;
        float: left;
        width: 100%;
        background-color: #0BC9CD;
    }
    }

    .col5 {
        height:100%;
        position:relative;
        float: left;
        width: 20%;
        background-color: #05A8AA;
    }

    @media only screen and (max-width: 500px) {
    .col5{
        height:100%;
        position:relative;
        float: left;
        width: 100%;
        background-color: #05A8AA;
    }
    }

<div class="container">
<div class="col1"><br>
&nbsp;</div>
<div class="col2"><br>
&nbsp;</div>
<div class="col3"><br>
&nbsp;</div>
<div class="col4"><br>
&nbsp;</div>
<div class="col5"><br>
&nbsp;</div>
<br><br>
</div>
<p>The green is fine but the rest don't match above themselves</p>