问:
Deploying To Azure throws Http Status 500 when from Command Line and works when from VS'17
I am trying to deploy to Azure using Command Line:

```<code>nuget restore MySolution.sln

msbuild MySolution.WebApi /P:DeployOnBuild=True /p:UserName='userName'    /p:PassWord='pass'  /p:PublishProfile=$publishProfile
</code>```

the deploy works fine, no errors are thrown.
When checking the API, I get  the following error :

```<code>**HTTP Error 500.0 - Internal Server Error**
* IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred.
* IIS was not able to process configuration for the Web site or application.
</code>```

When I use the VS 17 to deploy the APP using the same publish profile, I can verify that the API throws no errors. Its working fine.

Well, I checked Web.Config, App.json and buildConfig.json, they are all the same.

What else could cause this kind of situation ?

答:
I was missing an Output Path. </p>

```<code>msbuild MySolution.WebApi /t:Build  /p:Configuration='MyConfig' /p:OutputPath=$outputPath  /P:DeployOnBuild=True /p:UserName='userName'    /p:PassWord='pass' /p:PublishProfile=$publishProfile
</code>```

Body:
I am trying to deploy to Azure using Command Line:

nuget restore MySolution.sln

msbuild MySolution.WebApi /P:DeployOnBuild=True /p:UserName='userName'    /p:PassWord='pass'  /p:PublishProfile=$publishProfile

the deploy works fine, no errors are thrown.
When checking the API, I get  the following error :

**HTTP Error 500.0 - Internal Server Error**
* IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred.
* IIS was not able to process configuration for the Web site or application.

When I use the VS 17 to deploy the APP using the same publish profile, I can verify that the API throws no errors. Its working fine.

Well, I checked Web.Config, App.json and buildConfig.json, they are all the same.

What else could cause this kind of situation ?

Body:
I was missing an Output Path.

msbuild MySolution.WebApi /t:Build  /p:Configuration='MyConfig' /p:OutputPath=$outputPath  /P:DeployOnBuild=True /p:UserName='userName'    /p:PassWord='pass' /p:PublishProfile=$publishProfile


来源: stackexchange

问:
How to define an empty list of string in jshell in a shortest possible way?
I want to create an empty list of type List<String> in jshell

I am hoping jshell supports some sort of syntax shorthand for example:

```<code>  List<String> args = []
</code>```

However it failed with this error message:

```<code>|  Error:
|  illegal start of expression
|  List<String> args = [];
|                      ^
</code>```

Of course I can just use the standard java expression:

```<code>import com.google.common.collect.ImmutableList
List<String> args = ImmutableList.of()
</code>```

but I want to know if it can be more terse.

答:
If you're initialising a List you can do it as:

```<code>List<String> list = List.of();
</code>```

If instead it was an array, you could have initialized it as :

```<code>String[] arr = {}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to create an empty list of type List<String> in jshell

I am hoping jshell supports some sort of syntax shorthand for example:

  List<String> args = []

However it failed with this error message:

|  Error:
|  illegal start of expression
|  List<String> args = [];
|                      ^

Of course I can just use the standard java expression:

import com.google.common.collect.ImmutableList
List<String> args = ImmutableList.of()

but I want to know if it can be more terse.

Body:
If you're initialising a List you can do it as:

List<String> list = List.of();

If instead it was an array, you could have initialized it as :

String[] arr = {}


问:
extract values from list with the help of another list with condition in python
Extract items from the list with comes in between another list items

```<code>a = [4,8]
b = [1,2,3,4,5,6,7,8,9,0]
</code>```

I want to extract values from b list which comes in between 4 and 8 values of list a ?

Result should be

```<code>b = [5,6,7]
</code>```

Body:
Extract items from the list with comes in between another list items

a = [4,8]
b = [1,2,3,4,5,6,7,8,9,0]

I want to extract values from b list which comes in between 4 and 8 values of list a ?

Result should be

b = [5,6,7]

Body:
In [8]: a = [4,8]

In [9]: b = [1,2,3,4,5,6,7,8,9,0]

In [10]: [ item for item in b if a[0] < item < a[1]]
Out[10]: [5, 6, 7]


问:
how to reduce the size of file....in java

Possible Duplicate:

  Resize an image in Java - Any Open Source Library ?

```<code>InputStream is = new FileInputStream(file);
    long length = file.length();
    // if (length > Integer.MAX_VALUE) {
    // File is too large
    // }
    byte[] bytes = new byte[(int) length];
</code>```

if i enter large image....it should accept but size should be reduced

答:
First, you should use a buffer and read the data in buffer-size increments, otherwise you will probably have problems when the data is big.

Second, as suggested by other users, you should use compression, or, since we are talking about images, you can always downsample it as a last resource, if you are in a very memory constrained environment.

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  Resize an image in Java - Any Open Source Library ?

InputStream is = new FileInputStream(file);
    long length = file.length();
    // if (length > Integer.MAX_VALUE) {
    // File is too large
    // }
    byte[] bytes = new byte[(int) length];

if i enter large image....it should accept but size should be reduced


问:
Type 'Observable<Object>' is not assignable to type 'Observable<boolean>'
I have an error:
 Type 'Observable' is not assignable to type 'Observable'.
  Type 'Object' is not assignable to type 'boolean'.

```<code>  deleteUser(userId: string): Observable<boolean> {
    return this.httpClient
      .delete(url, this.getHttpOptions())
      .map(res => {
        return res;
      })
      .catch(this.handleError);
  }
</code>```

I got the type of res as a boolean when I tried to print it.

答:
The type of res needs to be boolean, by default it will be any.  Replace map by following :

```<code>map((res:boolean) => {
    return res;
  })
</code>```

Body:
I have an error:
 Type 'Observable' is not assignable to type 'Observable'.
  Type 'Object' is not assignable to type 'boolean'.

  deleteUser(userId: string): Observable<boolean> {
    return this.httpClient
      .delete(url, this.getHttpOptions())
      .map(res => {
        return res;
      })
      .catch(this.handleError);
  }

I got the type of res as a boolean when I tried to print it.

Body:
The type of res needs to be boolean, by default it will be any.  Replace map by following :

map((res:boolean) => {
    return res;
  })


问:
How to scrape newspaper articles from website using selenium and beautifulsoup in python?
I am trying to collect the date, title, and content from the newspaper (the new york times).

Date and title I got, but the full article I couldn't able to. Below is the code which I used to scrape date and title.

```<code>import time
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

base = "https://www.nytimes.com"
browser = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')
wait = WebDriverWait(browser, 10)
browser.get('https://www.nytimes.com/search?endDate=20190331&query=cybersecurity&sort=newest&startDate=20180401')

while True:
    try:
        time.sleep(1)
    show_more = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@type="button"][contains(.,"Show More")]')))
        show_more.click()
    except Exception as e:
            print(e)
            break

soup = BeautifulSoup(browser.page_source,'lxml')
search_results = soup.find('ol', {'data-testid':'search-results'})

links = search_results.find_all('a')
for link in links:
    title = link.find('h4').text
    date = link.find_next('time').text
    print(date + ': '+ title)

print("Complete")

browser.quit()
</code>```

Along with date, title, I also want to scrape full article.

答:
It is possible. You'll have to get each link to the article and pull that. I added it below and also cleaned up the article a bit as there were extra spaces and what not in the text when you join it all together.

```<code>import time
import requests
from bs4 import BeautifulSoup
import json
import string
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

base = "https://www.nytimes.com"
browser = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')
wait = WebDriverWait(browser, 10)
browser.get('https://www.nytimes.com/search?endDate=20190331&query=cybersecurity&sort=newest&startDate=20180401')

while True:
    try:
        time.sleep(1)
        show_more = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@type="button"][contains(.,"Show More")]')))
        show_more.click()
    except Exception as e:
            print(e)
            break

soup = BeautifulSoup(browser.page_source,'lxml')
search_results = soup.find('ol', {'data-testid':'search-results'})

links = search_results.find_all('a')
for link in links:
    link_url = link['href']

    title = link.find('h4').text
    date = link.find_next('time').text
    print(date + ': '+ title + '\n')

    response = requests.get(base + link_url)
    soup_link = BeautifulSoup(response.text, 'html.parser')
    scripts = soup_link.find_all('script')
    for script in scripts:
        if 'window.__preloadedData = ' in script.text:
            jsonStr = script.text
            jsonStr = jsonStr.split('window.__preloadedData = ')[-1]
            jsonStr = jsonStr.rsplit(';',1)[0]

            jsonData = json.loads(jsonStr)

            article = []
            for k, v in jsonData['initialState'].items():
                w=1
                try:
                    if v['__typename'] == 'TextInline':
                        article.append(v['text'])
                        #print (v['text'])
                except:
                    continue
            article = [ each.strip() for each in article ]
            article = ''.join([('' if c in string.punctuation else ' ')+c for c in article]).strip()
    print (article + '\n')

print("Complete")

browser.quit()
</code>```

Output:

```<code>March 31: Bezos’ Security Consultant Accuses Saudis of Hacking the Amazon C.E.O.’s Phone

SEATTLE — Jeff Bezos’ security consultant accused the Saudi government of gaining unauthorized access to the Amazon chief executive’s phone, as part of an effort to harm the world’s richest man. In an opinion article in The Daily Beast on Saturday, Gavin de Becker, Mr. Bezos’ security chief, alleged the Saudis wanted to hurt Mr. Bezos because he owns The Washington Post. The Post has aggressively reported on the murder of Jamal Khashoggi, one of its columnists, who was killed last year in Turkey. United States officials have concluded Mr. Khashoggi, who was critical of Saudi leaders, was killed on the orders of the Saudi crown prince, Mohammed bin Salman. Mr. de Becker said he had turned over his findings about the Saudis and their role against Mr. Bezos to law enforcement. “Our investigators and several experts concluded with high confidence that the Saudis had access to Bezos’ phone, and gained private information,” Mr. de Becker wrote. Mr. de Becker’s claims about the Saudis are difficult to verify and raise many questions. Throughout his article, the security consultant was vague on details. He did not reveal direct evidence of his accusations and wrote that he would not speak again publicly on the issue. On Sunday, American Media Inc., the parent company of The National Enquirer, which first reported earlier this year that Mr. Bezos was having an extramarital affair, issued a statement denying “the false and unsubstantiated claims of Mr. de Becker.” Amazon did not immediately have a comment about Mr. Bezos. An official with the Saudi embassy in Washington declined to comment on Saturday. Mr. de Becker’s allegations are the latest twist in a bizarre situation that has embroiled the largest U.S. tabloid publisher and Mr. Bezos, who runs Amazon and owns The Post. The unusual set of circumstances began in January, when Mr. Bezos announced that he and his wife, MacKenzie Bezos, were divorcing. The next day, The Enquirer published an exposé revealing that Mr. Bezos was romantically involved with Lauren Sanchez, a former Los Angeles TV anchor. Then in February, Mr. Bezos published a post on Medium accusing AMI of “extortion and blackmail.” Mr. Bezos said AMI had threatened to publish graphic photographs of him, including a “below-the-belt selfie,” if he did not publicly affirm that The Enquirer’s reporting on his affair was not motivated by political concerns. He said AMI, which has had ties to the Saudis, was “apoplectic” about The Post’s reporting on the Saudis. Mr. Bezos added that he had asked Mr. de Becker, his longtime security consultant, to investigate who had leaked information and photos about him. Earlier this month, The New York Times reported that two people with direct knowledge of The Enquirer’s reporting said that everything the tabloid received on Mr. Bezos’ affair, including the “below-the-belt selfie,” came from a single source. The Wall Street Journal later reported that AMI had paid Ms. Sanchez’s brother, Michael Sanchez, $200,000 for the texts. In its statement on Sunday, AMI said directly that its source was Mr. Sanchez. “The fact of the matter is, it was Michael Sanchez who tipped the National Enquirer off to the affair on Sept. 10, 2018, and over the course of four months provided all of the materials for our investigation.” AMI added, “There was no involvement by any other third party whatsover.” Mr. de Becker on Saturday said that the effort against Mr. Bezos went beyond Mr. Sanchez and also involved the Saudis. Mr. de Becker pointed to an article published on Saturday by The New York Post in which Mr. Sanchez said The Enquirer “had seen text exchanges between the secret couple” before he was in touch with the tabloid on the matter. “Reality is complicated, and can’t always be boiled down to a simple narrative like ‘the brother did it,’” Mr. de Becker wrote. Mr. de Becker said his investigation included interviews with cybersecurity experts and “people who personally know the Saudi Crown Prince Mohammed bin Salman.” But he stopped short of saying what methods he believed the Saudis may have used to access Mr. Bezos’ personal information. He added that AMI had wanted him to make a public statement “saying that my investigation had concluded they hadn’t relied upon ‘any form of electronic eavesdropping or hacking in their news-gathering process,’” and that the tabloid’s story was not “instigated, dictated or influenced in any manner by external forces, political or otherwise.” Mr. de Becker said he told AMI in a recorded call that those claims were “not my truth.”

March 29: In Ukraine, Russia Tests a New Facebook Tactic in Election Tampering

Campaigning for Ukraine’s presidential election had just begun to heat up when the authorities announced they had thwarted a Russian plot to use Facebook to undermine the vote. Unlike the 2016 interference in the United States, which centered on fake Facebook pages created by Russians in faraway St. Petersburg, the operation in Ukraine this year had ...

...
</code>```

Body:
I am trying to collect the date, title, and content from the newspaper (the new york times).

Date and title I got, but the full article I couldn't able to. Below is the code which I used to scrape date and title.

import time
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

base = "https://www.nytimes.com"
browser = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')
wait = WebDriverWait(browser, 10)
browser.get('https://www.nytimes.com/search?endDate=20190331&query=cybersecurity&sort=newest&startDate=20180401')

while True:
    try:
        time.sleep(1)
    show_more = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@type="button"][contains(.,"Show More")]')))
        show_more.click()
    except Exception as e:
            print(e)
            break

soup = BeautifulSoup(browser.page_source,'lxml')
search_results = soup.find('ol', {'data-testid':'search-results'})

links = search_results.find_all('a')
for link in links:
    title = link.find('h4').text
    date = link.find_next('time').text
    print(date + ': '+ title)

print("Complete")

browser.quit()

Along with date, title, I also want to scrape full article.

Body:
It is possible. You'll have to get each link to the article and pull that. I added it below and also cleaned up the article a bit as there were extra spaces and what not in the text when you join it all together.

import time
import requests
from bs4 import BeautifulSoup
import json
import string
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

base = "https://www.nytimes.com"
browser = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')
wait = WebDriverWait(browser, 10)
browser.get('https://www.nytimes.com/search?endDate=20190331&query=cybersecurity&sort=newest&startDate=20180401')

while True:
    try:
        time.sleep(1)
        show_more = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@type="button"][contains(.,"Show More")]')))
        show_more.click()
    except Exception as e:
            print(e)
            break

soup = BeautifulSoup(browser.page_source,'lxml')
search_results = soup.find('ol', {'data-testid':'search-results'})

links = search_results.find_all('a')
for link in links:
    link_url = link['href']

    title = link.find('h4').text
    date = link.find_next('time').text
    print(date + ': '+ title + '\n')

    response = requests.get(base + link_url)
    soup_link = BeautifulSoup(response.text, 'html.parser')
    scripts = soup_link.find_all('script')
    for script in scripts:
        if 'window.__preloadedData = ' in script.text:
            jsonStr = script.text
            jsonStr = jsonStr.split('window.__preloadedData = ')[-1]
            jsonStr = jsonStr.rsplit(';',1)[0]

            jsonData = json.loads(jsonStr)

            article = []
            for k, v in jsonData['initialState'].items():
                w=1
                try:
                    if v['__typename'] == 'TextInline':
                        article.append(v['text'])
                        #print (v['text'])
                except:
                    continue
            article = [ each.strip() for each in article ]
            article = ''.join([('' if c in string.punctuation else ' ')+c for c in article]).strip()
    print (article + '\n')

print("Complete")

browser.quit()

Output:

March 31: Bezos’ Security Consultant Accuses Saudis of Hacking the Amazon C.E.O.’s Phone

SEATTLE — Jeff Bezos’ security consultant accused the Saudi government of gaining unauthorized access to the Amazon chief executive’s phone, as part of an effort to harm the world’s richest man. In an opinion article in The Daily Beast on Saturday, Gavin de Becker, Mr. Bezos’ security chief, alleged the Saudis wanted to hurt Mr. Bezos because he owns The Washington Post. The Post has aggressively reported on the murder of Jamal Khashoggi, one of its columnists, who was killed last year in Turkey. United States officials have concluded Mr. Khashoggi, who was critical of Saudi leaders, was killed on the orders of the Saudi crown prince, Mohammed bin Salman. Mr. de Becker said he had turned over his findings about the Saudis and their role against Mr. Bezos to law enforcement. “Our investigators and several experts concluded with high confidence that the Saudis had access to Bezos’ phone, and gained private information,” Mr. de Becker wrote. Mr. de Becker’s claims about the Saudis are difficult to verify and raise many questions. Throughout his article, the security consultant was vague on details. He did not reveal direct evidence of his accusations and wrote that he would not speak again publicly on the issue. On Sunday, American Media Inc., the parent company of The National Enquirer, which first reported earlier this year that Mr. Bezos was having an extramarital affair, issued a statement denying “the false and unsubstantiated claims of Mr. de Becker.” Amazon did not immediately have a comment about Mr. Bezos. An official with the Saudi embassy in Washington declined to comment on Saturday. Mr. de Becker’s allegations are the latest twist in a bizarre situation that has embroiled the largest U.S. tabloid publisher and Mr. Bezos, who runs Amazon and owns The Post. The unusual set of circumstances began in January, when Mr. Bezos announced that he and his wife, MacKenzie Bezos, were divorcing. The next day, The Enquirer published an exposé revealing that Mr. Bezos was romantically involved with Lauren Sanchez, a former Los Angeles TV anchor. Then in February, Mr. Bezos published a post on Medium accusing AMI of “extortion and blackmail.” Mr. Bezos said AMI had threatened to publish graphic photographs of him, including a “below-the-belt selfie,” if he did not publicly affirm that The Enquirer’s reporting on his affair was not motivated by political concerns. He said AMI, which has had ties to the Saudis, was “apoplectic” about The Post’s reporting on the Saudis. Mr. Bezos added that he had asked Mr. de Becker, his longtime security consultant, to investigate who had leaked information and photos about him. Earlier this month, The New York Times reported that two people with direct knowledge of The Enquirer’s reporting said that everything the tabloid received on Mr. Bezos’ affair, including the “below-the-belt selfie,” came from a single source. The Wall Street Journal later reported that AMI had paid Ms. Sanchez’s brother, Michael Sanchez, $200,000 for the texts. In its statement on Sunday, AMI said directly that its source was Mr. Sanchez. “The fact of the matter is, it was Michael Sanchez who tipped the National Enquirer off to the affair on Sept. 10, 2018, and over the course of four months provided all of the materials for our investigation.” AMI added, “There was no involvement by any other third party whatsover.” Mr. de Becker on Saturday said that the effort against Mr. Bezos went beyond Mr. Sanchez and also involved the Saudis. Mr. de Becker pointed to an article published on Saturday by The New York Post in which Mr. Sanchez said The Enquirer “had seen text exchanges between the secret couple” before he was in touch with the tabloid on the matter. “Reality is complicated, and can’t always be boiled down to a simple narrative like ‘the brother did it,’” Mr. de Becker wrote. Mr. de Becker said his investigation included interviews with cybersecurity experts and “people who personally know the Saudi Crown Prince Mohammed bin Salman.” But he stopped short of saying what methods he believed the Saudis may have used to access Mr. Bezos’ personal information. He added that AMI had wanted him to make a public statement “saying that my investigation had concluded they hadn’t relied upon ‘any form of electronic eavesdropping or hacking in their news-gathering process,’” and that the tabloid’s story was not “instigated, dictated or influenced in any manner by external forces, political or otherwise.” Mr. de Becker said he told AMI in a recorded call that those claims were “not my truth.”

March 29: In Ukraine, Russia Tests a New Facebook Tactic in Election Tampering

Campaigning for Ukraine’s presidential election had just begun to heat up when the authorities announced they had thwarted a Russian plot to use Facebook to undermine the vote. Unlike the 2016 interference in the United States, which centered on fake Facebook pages created by Russians in faraway St. Petersburg, the operation in Ukraine this year had ...

...


问:
alternative for Not Like Operator in SQL
I want to exclude user accounts which ends with '_test' in table1.
I use

```<code>select * from table1 Not Like '%_test'.
</code>```

But this query doesn't work as expected.

答:
There's nothing wrong with LIKE and NOT LIKE. % and _ are wildcards. You asked to exclude rows that end with test and at least one character before that, any character.

If you want to use a wildcard as a literal character, you need to escape it  :

```<code>select * from table1
where SomeField not like '%[_]test'
</code>```

Given this table :

```<code>declare @table1 table (somefield varchar(100))

insert into @table1
values
('abc'),
('test'),
('atest'),
('ab_test'),
('_test')
</code>```

The following query :

```<code>SELECT *
FROM @table1
WHERE someField NOT LIKE '%[_]test'
</code>```

Returns :

```<code>somefield
---------
abc
test
atest
</code>```

The original query would return :

```<code>somefield
---------
abc
test
</code>```

Because %_test would match atest

UPDATE

The query returns empty fields or fields that contain spaces without any modification . Given this :

```<code>declare @table1 table (ID int identity,somefield varchar(100))

insert into @table1
values
('abc'),
('test'),
('atest'),
('ab_test'),
('_test'),
(''),
(' '),
(null)

SELECT *
FROM @table1
WHERE someField not LIKE '%[_]test'
</code>```

The results are :

```<code>ID  somefield
1   abc
2   test
3   atest
6
7
</code>```

NULL isn't just a blank. In SQL NULL means Unknown and any comparison with it results in an Unknown value as well. Even NOT UNKNOWN results in UNKNOWN. This means that neither LIKE, nor NOT LIKE can match a NULL value. The query would have to explicitly add an OR SomeField IS NULL clause to return the NULL :

```<code>SELECT *
FROM @table1
WHERE someField not LIKE '%[_]test'
    OR somefield is null
</code>```

This returns :

```<code>ID  somefield
1   abc
2   test
3   atest
6
7
8   NULL
</code>```

Body:
I want to exclude user accounts which ends with '_test' in table1.
I use

select * from table1 Not Like '%_test'.

But this query doesn't work as expected.

Body:
There's nothing wrong with LIKE and NOT LIKE. % and _ are wildcards. You asked to exclude rows that end with test and at least one character before that, any character.

If you want to use a wildcard as a literal character, you need to escape it  :

select * from table1
where SomeField not like '%[_]test'

Given this table :

declare @table1 table (somefield varchar(100))

insert into @table1
values
('abc'),
('test'),
('atest'),
('ab_test'),
('_test')

The following query :

SELECT *
FROM @table1
WHERE someField NOT LIKE '%[_]test'

Returns :

somefield
---------
abc
test
atest

The original query would return :

somefield
---------
abc
test

Because %_test would match atest

UPDATE

The query returns empty fields or fields that contain spaces without any modification . Given this :

declare @table1 table (ID int identity,somefield varchar(100))

insert into @table1
values
('abc'),
('test'),
('atest'),
('ab_test'),
('_test'),
(''),
(' '),
(null)

SELECT *
FROM @table1
WHERE someField not LIKE '%[_]test'

The results are :

ID  somefield
1   abc
2   test
3   atest
6
7

NULL isn't just a blank. In SQL NULL means Unknown and any comparison with it results in an Unknown value as well. Even NOT UNKNOWN results in UNKNOWN. This means that neither LIKE, nor NOT LIKE can match a NULL value. The query would have to explicitly add an OR SomeField IS NULL clause to return the NULL :

SELECT *
FROM @table1
WHERE someField not LIKE '%[_]test'
    OR somefield is null

This returns :

ID  somefield
1   abc
2   test
3   atest
6
7
8   NULL


问:
Python ping script always failed on 1st attempt
I'm facing failure issue when run python script to ping nodes in my network and it always fail on my 1st attempt ...when run again...it works. My environment is linux machine and I ping to only 3 devices.

To test it I just create simple script. For 1st attempt it will failed and if i run the script again and again...everything ok... then after i left for 15mins-30mins... I run and it will failed...then run again...ok... May I know if you guyz facing this kind of issue.

The code as follows;

```<code>def verify_ping():
    ipadd = "192.168.1.1"
    response = os.system("ping -c 1 " + ipadd)

    if response == 0:
        ipstatus = "UP"
    else:
        ipstatus = "DOWN"

    return ipstatus

ping_status = verify_ping()
</code>```

The PING failure a follows

```<code>PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
From 192.168.1.1 icmp_seq=1 Redirect Host(New nexthop: 192.168.1.100)

--- 192.168.1.1 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms
</code>```

Ping OK

```<code>PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
64 bytes from 192.168.1.1: icmp_seq=1 ttl=250 time=1.33 ms

--- 192.168.1.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
</code>```

At the same time I do continues ping to the IP and so far the IP up and reachable. Maybe someone face the issue or maybe something that i need to add to the script. Please advise further and thank you for your time.

答:
It may be related to an ARP issue. It may depends on the network architecture of your environment, and parameters of your network devices

(see https://learningnetwork.cisco.com/thread/85577)

Body:
I'm facing failure issue when run python script to ping nodes in my network and it always fail on my 1st attempt ...when run again...it works. My environment is linux machine and I ping to only 3 devices.

To test it I just create simple script. For 1st attempt it will failed and if i run the script again and again...everything ok... then after i left for 15mins-30mins... I run and it will failed...then run again...ok... May I know if you guyz facing this kind of issue.

The code as follows;

def verify_ping():
    ipadd = "192.168.1.1"
    response = os.system("ping -c 1 " + ipadd)

    if response == 0:
        ipstatus = "UP"
    else:
        ipstatus = "DOWN"

    return ipstatus

ping_status = verify_ping()

The PING failure a follows

PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
From 192.168.1.1 icmp_seq=1 Redirect Host(New nexthop: 192.168.1.100)

--- 192.168.1.1 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms

Ping OK

PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
64 bytes from 192.168.1.1: icmp_seq=1 ttl=250 time=1.33 ms

--- 192.168.1.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms

At the same time I do continues ping to the IP and so far the IP up and reachable. Maybe someone face the issue or maybe something that i need to add to the script. Please advise further and thank you for your time.


问:
Input Output vs ngrx Dispatch Oftype
Tell me please what is the best way to communicate data between components in angular if you use Ngrx Store.

Use Input Output

Use dispatch(action) ofType(action)

For example Component1 -> send data to -> Component2. After some time business tell me add new service, so I decide to create a new Component3 and add it between them.

So now I have to modify data flow. Component1 -> Component3 -> Component2.
So in which way it would be more code clean and simple to understand, with input outpt or despatch(action) ofType(action)?

答:
i think it depends on the size of your app and how many levels you have between components, imagine that you have a child5 component that have to communicate with child1, in that case it's not a good idea to use Input Output, on the picture bellow, if child component have to communicate to Grandparent it has to pass by Parent, the Parent participate in the flow even if it doesn't have anything to do with that data

better way here is to use Subject and create and EventBus, check my answer here https://stackoverflow.com/a/56291422/4399281

Ngrx store is the best options but if you really need it, don't implement a state management if you have few components only

Title: Input Output vs ngrx Dispatch Oftype


问:
How can I import functions from an other javascript file?
I'm pretty new in JS, and I have some trouble with importing.

I'm doing a Star Wars planet list application, where I'd like to import functions from an other JS file like this:

--- dataManager.js ---

```<code>export function getAllPlanetDataFromAPI() {

    let allPlanetsInfo = new XMLHttpRequest();
    allPlanetsInfo.open('GET', 'https://swapi.co/api/planets');
    allPlanetsInfo.onload = function () {
        console.log(allPlanetsInfo.responseText)
    };
    allPlanetsInfo.send();

}
</code>```

--- main.js ---

```<code>import { getAllPlanetDataFromAPI } from './dataManager';

getAllPlanetDataFromAPI();
</code>```

The error message I get is: "Uncaught SyntaxError: Unexpected token {"

Seems like the syntax is incorrect, but I have already checked all of the "import" articles on the web, and couldn't find what I'm doing wrong.

答:
You should change your file extensions to .mjs

then run your code with these command:

node --experimental-modules main.mjs

please feel free to ask me in comments.

Body:
I'm pretty new in JS, and I have some trouble with importing.

I'm doing a Star Wars planet list application, where I'd like to import functions from an other JS file like this:

--- dataManager.js ---

export function getAllPlanetDataFromAPI() {

    let allPlanetsInfo = new XMLHttpRequest();
    allPlanetsInfo.open('GET', 'https://swapi.co/api/planets');
    allPlanetsInfo.onload = function () {
        console.log(allPlanetsInfo.responseText)
    };
    allPlanetsInfo.send();

}

--- main.js ---

import { getAllPlanetDataFromAPI } from './dataManager';

getAllPlanetDataFromAPI();

The error message I get is: "Uncaught SyntaxError: Unexpected token {"

Seems like the syntax is incorrect, but I have already checked all of the "import" articles on the web, and couldn't find what I'm doing wrong.


问:
How to use export type in TypeScript?
I used a library from NPM

```<code>https://www.npmjs.com/package/yaml
</code>```

and this his the @types/yaml

```<code>https://www.npmjs.com/package/@types/yaml
</code>```

In my source code I did import to

```<code>import * as yaml from 'yaml';
</code>```

but I don't have access to YAMLError
it is define in the @types/yaml

```<code>export type YAMLError =
    | YAMLSyntaxError
    | YAMLSemanticError
    | YAMLReferenceError;

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/yaml/index.d.ts
</code>```

Can I use export type ?

答:
In your current situation, you would need to use yaml.YAMLError as you've namespaced your import.

You could do:

```<code>import { YAMLError } from 'yaml'
</code>```

It "should" automatically retrieve the correct type information for you.

Depending on your editor or IDE, it can do automatic imports for you if you have the right plugins like the TypeScript Language Server.

export type is to make your new type available to the rest of your code and be able to import it. If you were to make an addition to the existing type or a completely new one based of it like this example:

```<code>export type MyYAMLError = YAMLError | null
</code>```

You could start using MyYAMLERROR in your own code. Not sure if this is what you're looking for so I suggest redoing your imports as described above.

Title: How to use export type in TypeScript?

Body:
I used a library from NPM

https://www.npmjs.com/package/yaml

and this his the @types/yaml

https://www.npmjs.com/package/@types/yaml

In my source code I did import to

import * as yaml from 'yaml';

but I don't have access to YAMLError
it is define in the @types/yaml

export type YAMLError =
    | YAMLSyntaxError
    | YAMLSemanticError
    | YAMLReferenceError;

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/yaml/index.d.ts

Can I use export type ?

Body:
In your current situation, you would need to use yaml.YAMLError as you've namespaced your import.

You could do:

import { YAMLError } from 'yaml'

It "should" automatically retrieve the correct type information for you.

Depending on your editor or IDE, it can do automatic imports for you if you have the right plugins like the TypeScript Language Server.

export type is to make your new type available to the rest of your code and be able to import it. If you were to make an addition to the existing type or a completely new one based of it like this example:

export type MyYAMLError = YAMLError | null

You could start using MyYAMLERROR in your own code. Not sure if this is what you're looking for so I suggest redoing your imports as described above.


问:
Unable to use the subclass
Hello I have this code :

```<code>class A:
    def __init__(self, name):
        self.name = name

class B(A):
    def __init__(self):
        super.__init__()
</code>```

But I don't achieve to use the class B :

I tried to write :

```<code>C = B()
</code>```

But I get :

```<code>TypeError
Traceback (most recent call last)
<ipython-input-7-ea9745abfeb2> in <module>()
----> 1 C = B()

<ipython-input-4-2d2ef2cc5406> in __init__(self)
  5 class B(A):
  6   def __init__(self):
----> 7     super.__init__()

TypeError: descriptor '__init__' of 'super' object needs an argument
</code>```

Could you help me please ?

答:
These worked for me

For python 3:

```<code>class A:
    def __init__(self, name):
        self.name = name

class B(A):
    def __init__(self):
        super().__init__('temp name')

C = B()
</code>```

For python 2:

```<code>class A(object):
    def __init__(self, name):
        self.name = name

class B(A):
    def __init__(self):
        super(B, self).__init__("any name")

C = B()
</code>```

Title: Unable to use the subclass

Body:
Hello I have this code :

class A:
    def __init__(self, name):
        self.name = name

class B(A):
    def __init__(self):
        super.__init__()

But I don't achieve to use the class B :

I tried to write :

C = B()

But I get :

TypeError
Traceback (most recent call last)
<ipython-input-7-ea9745abfeb2> in <module>()
----> 1 C = B()

<ipython-input-4-2d2ef2cc5406> in __init__(self)
  5 class B(A):
  6   def __init__(self):
----> 7     super.__init__()

TypeError: descriptor '__init__' of 'super' object needs an argument

Could you help me please ?

Body:
These worked for me

For python 3:

class A:
    def __init__(self, name):
        self.name = name

class B(A):
    def __init__(self):
        super().__init__('temp name')

C = B()

For python 2:

class A(object):
    def __init__(self, name):
        self.name = name

class B(A):
    def __init__(self):
        super(B, self).__init__("any name")

C = B()


答:
You can fix it by removing your .map (which doesn't do anything):

```<code>deleteUser(userId: string): Observable<boolean> {
  return this.httpClient
    .delete(url, this.getHttpOptions())
    .catch(this.handleError);
}
</code>```

Title: Type 'Observable<Object>' is not assignable to type 'Observable<boolean>'

Body:
You can fix it by removing your .map (which doesn't do anything):

deleteUser(userId: string): Observable<boolean> {
  return this.httpClient
    .delete(url, this.getHttpOptions())
    .catch(this.handleError);
}


问:
Matching of cells in excel
It Sum of columns is storing in one cell and if I want the same answer to be printed in another cell, what is the formula to get this?</p>

答:
Let's say you want the value of cell A1 in cell B1. You would use this formula in B1:

```<code>= A1
</code>```

In code you would write something like this (example in VBA):

```<code>Dim sht as Worksheet
Set sht = ThisWorkbook.Worksheets("MySheet") //Or whatever your target sheet is
sht.Range("B1").Formula = "=" & sht.Range("A1").Address
</code>```

Title: Matching of cells in excel

Body:
Let's say you want the value of cell A1 in cell B1. You would use this formula in B1:

= A1

In code you would write something like this (example in VBA):

Dim sht as Worksheet
Set sht = ThisWorkbook.Worksheets("MySheet") //Or whatever your target sheet is
sht.Range("B1").Formula = "=" & sht.Range("A1").Address


问:
Concatenating special character strings in paste and paste0
I wonder how to concatenate special character string in paste0 like \item.

```<code>paste0("\item", "b")

paste0("a", "b")
#> [1] "ab"
  paste0("a", "\b")
#> [1] "a\b"
paste0("\item", "\b")
#> Error: '\i' is an unrecognized escape in character string starting ""\i"
</code>```

Edited

```<code>library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
  head(airquality) %>%
  mutate(Ozone1 = cat(paste0("\\item{", Ozone)))
#> \item{41 \item{36 \item{12 \item{18 \item{NA \item{28
#>   Ozone Solar.R Wind Temp Month Day
#> 1    41     190  7.4   67     5   1
#> 2    36     118  8.0   72     5   2
#> 3    12     149 12.6   74     5   3
#> 4    18     313 11.5   62     5   4
#> 5    NA      NA 14.3   56     5   5
#> 6    28      NA 14.9   66     5   6
</code>```

答:
As the error says, you need to escape the backslash. In order to print it with a single backslash, you need to use cat. Otherwise, it is interpreted as an escape. For this reason, you will not be able to add it as is in a data frame. For example,

```<code>library(dplyr)
iris %>% mutate(new = paste0("\\item", "b")) #both backslashes are printed
</code>```

We can't use cat inside mutate. The backslash is escaped. To define a single backslash, you need to use double backslash in the string.

Find more info here

Body:
I wonder how to concatenate special character string in paste0 like \item.

paste0("\item", "b")

paste0("a", "b")
#> [1] "ab"
  paste0("a", "\b")
#> [1] "a\b"
paste0("\item", "\b")
#> Error: '\i' is an unrecognized escape in character string starting ""\i"

Edited

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
  head(airquality) %>%
  mutate(Ozone1 = cat(paste0("\\item{", Ozone)))
#> \item{41 \item{36 \item{12 \item{18 \item{NA \item{28
#>   Ozone Solar.R Wind Temp Month Day
#> 1    41     190  7.4   67     5   1
#> 2    36     118  8.0   72     5   2
#> 3    12     149 12.6   74     5   3
#> 4    18     313 11.5   62     5   4
#> 5    NA      NA 14.3   56     5   5
#> 6    28      NA 14.9   66     5   6

Body:
As the error says, you need to escape the backslash. In order to print it with a single backslash, you need to use cat. Otherwise, it is interpreted as an escape. For this reason, you will not be able to add it as is in a data frame. For example,

library(dplyr)
iris %>% mutate(new = paste0("\\item", "b")) #both backslashes are printed

We can't use cat inside mutate. The backslash is escaped. To define a single backslash, you need to use double backslash in the string.

Find more info here


问:
passing values to a flag in bash script
I am preparing shell(.sh) scripts to use my kubernetes and pks command line
in kubernetes command we have flags like --image and i am not able to pass the arguments in it

i have tried the convential way of passing the arguments like
image=$1

echo $image

the echo statement prints the value well and good $ name is also passing in the command but the script give the error image  needed i.e image is not given in the command.

```<code>image=$1
hostPort=$2
name=$3
echo $image
kubectl --insecure-skip-tls-verify run $name --image= $image --port= $hostPort
</code>```

the echo statement prints the value well and good $ name is also passing in the command but the script give the error image  needed i.e image is not given in the command.

答: Options such as --image must typically be separated by either space or an equals sign from their value. So --image="$image" and --image "$image" will probably both work. "Typically" and "probably" because there's nothing stopping someone from writing some really crazy argument handling to actually support the way it's run here, but I've never seen that before.

Title: passing values to a flag in bash script

Body:
I am preparing shell(.sh) scripts to use my kubernetes and pks command line
in kubernetes command we have flags like --image and i am not able to pass the arguments in it

i have tried the convential way of passing the arguments like
image=$1

echo $image

the echo statement prints the value well and good $ name is also passing in the command but the script give the error image  needed i.e image is not given in the command.

image=$1
hostPort=$2
name=$3
echo $image
kubectl --insecure-skip-tls-verify run $name --image= $image --port= $hostPort

the echo statement prints the value well and good $ name is also passing in the command but the script give the error image  needed i.e image is not given in the command.


问:
Why spark is slower when compared to sqoop , when it comes to jdbc?
It is understood , while migrating/load from oracle db to hdfs/parquet , it is preferred to use SQOOP rather than SPARK with JDBC driver.

Spark suppose to be 100x faster when processing right ?
Then what is wrong with Spark ?
Why people prefer SQOOP while loading data from oracle db tables ?

Please suggest me what should i need to do make Spark faster when loading data from oracle.

答:
The major point is already covered in Alex's answer.

I just wanted to add an example,

```<code>from pyspark.sql import SparkSession

spark = SparkSession.builder.master("local[4]").appName("Test-JDBC").getOrCreate()

ds = spark.read.jdbc("jdbc:mysql://localhost:3306/stackexchange", "(select min(id), max(id) from post_history) as ph",
                     properties={"user": "devender", "password": "*****", "driver": "com.mysql.jdbc.Driver"})

r = ds.head()
minId = r[0]
maxId = r[1]

ds = spark.read.jdbc("jdbc:mysql://localhost:3306/stackexchange", "(select * from post_history) as ph",
                     properties={"user": "devender", "password": "*****", "driver": "com.mysql.jdbc.Driver"},
                     numPartitions=4, column="id", lowerBound=minId, upperBound=maxId)

count = ds.count()
print(count)
</code>```

For more details, https://gist.github.com/devender-yadav/5c4328918602b7910ba883e18b68fd87

Note: Sqoop automatically executes boundary query to fetch MIN, MAX value for split by column (that query can also be overridden)

Body:
The major point is already covered in Alex's answer.

I just wanted to add an example,

from pyspark.sql import SparkSession

spark = SparkSession.builder.master("local[4]").appName("Test-JDBC").getOrCreate()

ds = spark.read.jdbc("jdbc:mysql://localhost:3306/stackexchange", "(select min(id), max(id) from post_history) as ph",
                     properties={"user": "devender", "password": "*****", "driver": "com.mysql.jdbc.Driver"})

r = ds.head()
minId = r[0]
maxId = r[1]

ds = spark.read.jdbc("jdbc:mysql://localhost:3306/stackexchange", "(select * from post_history) as ph",
                     properties={"user": "devender", "password": "*****", "driver": "com.mysql.jdbc.Driver"},
                     numPartitions=4, column="id", lowerBound=minId, upperBound=maxId)

count = ds.count()
print(count)

For more details, https://gist.github.com/devender-yadav/5c4328918602b7910ba883e18b68fd87

Note: Sqoop automatically executes boundary query to fetch MIN, MAX value for split by column (that query can also be overridden)


问:
How to calculate size of scatter plot's marker in matplotlib
Let's say I create a simple matplotlib scatter plot.

How would I then draw the line between the edges of dots on scatter plot? Meaning that the line would start and end on edges of dots?

EDIT: Forgot to add code snippet

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

plt.scatter([0, 0, 0], [5, 3, 4], s=250)
plt.scatter([3, 3, 3], [5, 3, 4], s=350)

plt.arrow(0, 5, dx=3, dy=0, width=0.01)
plt.arrow(0, 3, dx=3, dy=0, width=0.01)
plt.arrow(0, 4, dx=3, dy=0, width=0.01)
plt.show()
</code>```

How do I subtract from dx to connect dots only from edges

答:
You could finagle with the sizes of the dots, but this is not how one should approach the problem. A better way would be to draw the dots after one draws the lines, so that the dots are placed on top.

This can be achieved with zorder. In your example, this would look like

import matplotlib.pyplot as plt

plt.scatter([0, 0, 0], [5, 3, 4], s=250, zorder=2)
plt.scatter([3, 3, 3], [5, 3, 4], s=350, zorder=2)

plt.arrow(0, 5, dx=3, dy=0, width=0.01, zorder=1)
plt.arrow(0, 3, dx=3, dy=0, width=0.01, zorder=1)
plt.arrow(0, 4, dx=3, dy=0, width=0.01, zorder=1)
plt.show()
```

and this produces the plot

As an aside, you probably also are not looking for arrow if you're only looking to draw lines between points. You are just looking for plot.

Body:
Let's say I create a simple matplotlib scatter plot.

How would I then draw the line between the edges of dots on scatter plot? Meaning that the line would start and end on edges of dots?

EDIT: Forgot to add code snippet

import matplotlib.pyplot as plt

plt.scatter([0, 0, 0], [5, 3, 4], s=250)
plt.scatter([3, 3, 3], [5, 3, 4], s=350)

plt.arrow(0, 5, dx=3, dy=0, width=0.01)
plt.arrow(0, 3, dx=3, dy=0, width=0.01)
plt.arrow(0, 4, dx=3, dy=0, width=0.01)
plt.show()

How do I subtract from dx to connect dots only from edges

Body:
You could finagle with the sizes of the dots, but this is not how one should approach the problem. A better way would be to draw the dots after one draws the lines, so that the dots are placed on top.

This can be achieved with zorder. In your example, this would look like

import matplotlib.pyplot as plt

plt.scatter([0, 0, 0], [5, 3, 4], s=250, zorder=2)
plt.scatter([3, 3, 3], [5, 3, 4], s=350, zorder=2)

plt.arrow(0, 5, dx=3, dy=0, width=0.01, zorder=1)
plt.arrow(0, 3, dx=3, dy=0, width=0.01, zorder=1)
plt.arrow(0, 4, dx=3, dy=0, width=0.01, zorder=1)
plt.show()

and this produces the plot

As an aside, you probably also are not looking for arrow if you're only looking to draw lines between points. You are just looking for plot.


问:
Why my state always is default value when call inside Callback?
I don't know exactly what is my problem.
I used some library.
When i use callback and trying to get state of Component, the state always is default value.

Example when i use mui-datatables https://github.com/gregnb/mui-datatables

```<code>import React, { useState } from 'react'
import MUIDataTable from "mui-datatables";

const columns = [
    {
        name: "name",
        label: "Name",
    },
    {
        name: "company",
        label: "Company",
    },
    {
        name: "city",
        label: "City",
    },
    {
        name: "state",
        label: "State",
    },
];

const data = [
    { name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
    { name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
    { name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
    { name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" },
];

const MyComponent = () => {

    const [myState, setMyState] = useState("default value");
    const onRowClick = (rowData, rowMeta) => {
        console.log(myState) //always default value
    }

    const options = {
        onRowClick: onRowClick
    }
    return (
        <div>
            <MUIDataTable
                title={"Employee List"}
                data={data}
                columns={columns}
                options={options}
            />

            <button onClick={ () => setMyState("State changed")}>Change state</button>
            <p>{myState}</p>

        </div>
    )
}

</code>```

First, I click button to change MyState, the state changed in p tag.
Next, I click any row to console MyState. But, it's always is default value.
Why?
Code in CodeSanBox: https://codesandbox.io/s/dreamy-germain-tuylh

答:
I have converted your component to a class, and now it's working as you wanted. You can see below the error that was happening when you were trying to use a functional component. This is probably due to how mui-datatables is built. It probably requires a class component to work.

Working example on CodeSandbox

```<code>import React from "react";
import ReactDOM from "react-dom";

import MUIDataTable from "mui-datatables";

const columns = [
  {
    name: "name",
    label: "Name"
  },
  {
    name: "company",
    label: "Company"
  },
  {
    name: "city",
    label: "City"
  },
  {
    name: "state",
    label: "State"
  }
];

const data = [
  { name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
  { name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
  { name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
  { name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" }
];

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      myState: "default value"
    };
    this.options = { onRowClick: this.onRowClick };
    this.onRowClick = this.onRowClick.bind(this);
  }

  onRowClick(rowData, rowMeta) {
    console.log(this.state.myState); //always default value
  }

  render() {
    return (
      <div>
        <MUIDataTable
          title={"Employee List"}
          data={data}
          columns={columns}
          options={{ onRowClick: this.onRowClick }}
        />

        <button onClick={() => this.setState({ myState: "State changed" })}>
          Change state
        </button>
        <p>{this.state.myState}</p>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyComponent />, rootElement);

</code>```

With your code, I was get the following error:

```<code>Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `WithStyles(Tooltip)`.
    in Tooltip (created by WithStyles(Tooltip))
    in WithStyles(Tooltip) (created by t)
    in t (created by l)
    in span (created by l)
    in div (created by l)
    in div (created by ForwardRef(Toolbar))
    in ForwardRef(Toolbar) (created by WithStyles(ForwardRef(Toolbar)))
    in WithStyles(ForwardRef(Toolbar)) (created by l)
    in l (created by t)
    in t (created by WithStyles(t))
    in WithStyles(t) (created by t)
    in t (created by t)
    in div (created by ForwardRef(Paper))
    in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
    in WithStyles(ForwardRef(Paper)) (created by t)
    in t (created by WithStyles(t))
    in WithStyles(t) (created by MyComponent)
    in div (created by MyComponent)
    in MyComponent
</code>```

Body:
I don't know exactly what is my problem.
I used some library.
When i use callback and trying to get state of Component, the state always is default value.

Example when i use mui-datatables https://github.com/gregnb/mui-datatables

import React, { useState } from 'react'
import MUIDataTable from "mui-datatables";

const columns = [
    {
        name: "name",
        label: "Name",
    },
    {
        name: "company",
        label: "Company",
    },
    {
        name: "city",
        label: "City",
    },
    {
        name: "state",
        label: "State",
    },
];

const data = [
    { name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
    { name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
    { name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
    { name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" },
];

const MyComponent = () => {

    const [myState, setMyState] = useState("default value");
    const onRowClick = (rowData, rowMeta) => {
        console.log(myState) //always default value
    }

    const options = {
        onRowClick: onRowClick
    }
    return (

            <MUIDataTable
                title={"Employee List"}
                data={data}
                columns={columns}
                options={options}
            />

            <button onClick={ () => setMyState("State changed")}>Change state</button>

{myState}

    )
}

First, I click button to change MyState, the state changed in p tag.
Next, I click any row to console MyState. But, it's always is default value.
Why?
Code in CodeSanBox: https://codesandbox.io/s/dreamy-germain-tuylh

Body:
I have converted your component to a class, and now it's working as you wanted. You can see below the error that was happening when you were trying to use a functional component. This is probably due to how mui-datatables is built. It probably requires a class component to work.

Working example on CodeSandbox

import React from "react";
import ReactDOM from "react-dom";

import MUIDataTable from "mui-datatables";

const columns = [
  {
    name: "name",
    label: "Name"
  },
  {
    name: "company",
    label: "Company"
  },
  {
    name: "city",
    label: "City"
  },
  {
    name: "state",
    label: "State"
  }
];

const data = [
  { name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
  { name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
  { name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
  { name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" }
];

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      myState: "default value"
    };
    this.options = { onRowClick: this.onRowClick };
    this.onRowClick = this.onRowClick.bind(this);
  }

  onRowClick(rowData, rowMeta) {
    console.log(this.state.myState); //always default value
  }

  render() {
    return (
      <div>
        <MUIDataTable
          title={"Employee List"}
          data={data}
          columns={columns}
          options={{ onRowClick: this.onRowClick }}
        />

        <button onClick={() => this.setState({ myState: "State changed" })}>
          Change state
        </button>
        <p>{this.state.myState}</p>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyComponent />, rootElement);

With your code, I was get the following error:

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `WithStyles(Tooltip)`.
    in Tooltip (created by WithStyles(Tooltip))
    in WithStyles(Tooltip) (created by t)
    in t (created by l)
    in span (created by l)
    in div (created by l)
    in div (created by ForwardRef(Toolbar))
    in ForwardRef(Toolbar) (created by WithStyles(ForwardRef(Toolbar)))
    in WithStyles(ForwardRef(Toolbar)) (created by l)
    in l (created by t)
    in t (created by WithStyles(t))
    in WithStyles(t) (created by t)
    in t (created by t)
    in div (created by ForwardRef(Paper))
    in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
    in WithStyles(ForwardRef(Paper)) (created by t)
    in t (created by WithStyles(t))
    in WithStyles(t) (created by MyComponent)
    in div (created by MyComponent)
    in MyComponent


问:
Why is a Base64 string displayed as empty in Message Box?
I have to encode some HTML source code into base64 format before form submission, and then decode it back to original code in the code behind. Here is the testing code by MsgBox:

```<code>MsgBox(HttpContext.Current.Request.Form("encodedSourceCode"))
MsgBox(Convert.ToString(HttpContext.Current.Request.Form("encodedSourceCode").GetType()))
Dim b = Convert.FromBase64String(HttpContext.Current.Request.Form("encodedSourceCode"))
Dim html = System.Text.Encoding.UTF8.GetString(b)
MsgBox(html)
</code>```

And I have added an alert() for encodedSourceCode in client script.

The results turn out to be:

First MsgBox: Empty

Second MsgBox: "System.String"

Last MsgBox: Original HTML source code

And the JS alert dialog shows the base64 string, which consists of a bunch of digits and alphabets.

In short, everything is fine, except the first MsgBox, which is supposed to be base64 encoded string but turns out to be empty. Why? Is it normal?

Actually it does not matter much because even the final result (after decoding) seems to have no problem, but I'm just curious why the interim result is not shown as what it's supposed to be.

答:
It definitely has nothing to do with base64 strings as they are simple strings. Here the proof:

```<code>    Dim myString = "Hello world, this is just an ɇxâmpŀƏ ʬith some non-ansi characters..."
    Dim myEncoding As Encoding = Encoding.UTF8
    MsgBox(myString)
    Dim myBase64 = Convert.ToBase64String(myEncoding.GetBytes(myString))
    MsgBox(myBase64)
    Dim myStringAgain = myEncoding.GetString(Convert.FromBase64String(myBase64))
    MsgBox(myStringAgain)
    MsgBox(If(StringComparer.Ordinal.Equals(myString, myStringAgain), "same", "different"))
</code>```

The line

```<code>MsgBox(Convert.ToString(HttpContext.Current.Request.Form("encodedSourceCode").GetType()))
</code>```

results in "System.String" because you convert the name of the type to a string (see xxx.GetType()).

Body:
I have to encode some HTML source code into base64 format before form submission, and then decode it back to original code in the code behind. Here is the testing code by MsgBox:

MsgBox(HttpContext.Current.Request.Form("encodedSourceCode"))
MsgBox(Convert.ToString(HttpContext.Current.Request.Form("encodedSourceCode").GetType()))
Dim b = Convert.FromBase64String(HttpContext.Current.Request.Form("encodedSourceCode"))
Dim html = System.Text.Encoding.UTF8.GetString(b)
MsgBox(html)

And I have added an alert() for encodedSourceCode in client script.

The results turn out to be:

First MsgBox: Empty

Second MsgBox: "System.String"

Last MsgBox: Original HTML source code

And the JS alert dialog shows the base64 string, which consists of a bunch of digits and alphabets.

In short, everything is fine, except the first MsgBox, which is supposed to be base64 encoded string but turns out to be empty. Why? Is it normal?

Actually it does not matter much because even the final result (after decoding) seems to have no problem, but I'm just curious why the interim result is not shown as what it's supposed to be.

Body:
It definitely has nothing to do with base64 strings as they are simple strings. Here the proof:

    Dim myString = "Hello world, this is just an ɇxâmpŀƏ ʬith some non-ansi characters..."
    Dim myEncoding As Encoding = Encoding.UTF8
    MsgBox(myString)
    Dim myBase64 = Convert.ToBase64String(myEncoding.GetBytes(myString))
    MsgBox(myBase64)
    Dim myStringAgain = myEncoding.GetString(Convert.FromBase64String(myBase64))
    MsgBox(myStringAgain)
    MsgBox(If(StringComparer.Ordinal.Equals(myString, myStringAgain), "same", "different"))

The line

MsgBox(Convert.ToString(HttpContext.Current.Request.Form("encodedSourceCode").GetType()))

results in "System.String" because you convert the name of the type to a string (see xxx.GetType()).


问:
C Matrix Multiplication Dynamically Allocated Matrices
I am working within a specific matrix memory allocation constraint that creates matrices as such:

```<code>float * matrix_data = (float *) malloc(rows * cols * sizeof(float));
</code>```

I am storing this matrix inside an array of structs like this:

```<code>#define MAX_MATRICES 100

struct matrix{
    char matrixName[50];
    int rows;
    int columns;
    float* matrix_data;
};
typedef struct matrix matrix_t;

matrix_t our_matrix[MAX_MATRICES];
</code>```

Given that this is the case, and I am not creating matrices by way of a 2d array like MATRIX[SIZE][SIZE]: what is the correct way to multiply two matrices created in this way?

With this current implementation if I want to do something like subtract, I do it as follows:

```<code>int max_col = our_matrix[matrix_index1].columns;
      free(our_matrix[number_of_matrices].matrix_data);
      our_matrix[number_of_matrices].data = (float *) malloc(our_matrix[matrix_index1].rows * our_matrix[matrix_index1].columns * sizeof(float));
      float *data1 = our_matrix[matrix_index1].matrix_data;
      float *data2 = our_matrix[matrix_index2].matrix_data;

      int col, row;
      for(col = 1; col <= our_matrix[matrix_index2].columns; col++){
        for(row = 1; row <= our_matrix[matrix_index2].rows; row++){
          our_matrix[number_of_matrices].matrix_data[(col-1) + (row-1) * max_col] =
            (data1[(col-1) + (row-1) * (max_col)]) - (data2[(col-1) + (row-1) * (max_col)]);
        }
      }
</code>```

This is simple enough because the dimensions of matrix_index1 and matrix_index2 are identical and the matrix that they return is also of identical dimensions.

How might I achieve matrix multiplication with this method of matrix construction?

答:
Write proper abstraction, then work your way up. It will be way easier:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct matrix_s {
    char matrixName[50];
    size_t columns;
    size_t rows;
    float* data;
};

typedef struct matrix_s matrix_t;

void m_init(matrix_t *t, size_t columns, size_t rows) {
    t->rows = rows;
    t->columns = columns;
    t->data = calloc(rows * columns, sizeof(*t->data));
    if (t->data == NULL) abort();
}

size_t m_columns(const matrix_t *t) {
    return t->columns;
}

size_t m_rows(const matrix_t *t) {
    return t->rows;
}

// matrix_get
// (x,y) = (col,row) always in that order
float *m_get(const matrix_t *t, size_t x, size_t y) {
    assert(x < m_columns(t));
    assert(y < m_rows(t));
    // __UNCONST
    // see for example `char *strstr(const char *haystack, ...`
    // it takes `const char*` but returns `char*` nonetheless.
    return (float*)&t->data[t->rows * x + y];
}

// fill matrix with a fancy patterns just so it's semi-unique
void m_init_seq(matrix_t *t, size_t columns, size_t rows) {
    m_init(t, columns, rows);
    for (size_t i = 0; i < t->columns; ++i) {
        for (size_t j = 0; j < t->rows; ++j) {
            *m_get(t, i, j) = i + 100 * j;
        }
    }
}

void m_print(const matrix_t *t) {
    printf("matrix %p\n", (void*)t->data);
    for (size_t i = 0; i < t->columns; ++i) {
        for (size_t j = 0; j < t->rows; ++j) {
            printf("%5g\t", *m_get(t, i, j));
        }
        printf("\n");
    }
    printf("\n");
}

void m_multiply(matrix_t *out, const matrix_t *a, const matrix_t *b) {
    assert(m_columns(b) == m_rows(a));
    assert(m_columns(out) == m_columns(a));
    assert(m_rows(out) == m_rows(b));
    // Index from 0, not from 1
    // don't do `(col-1) + (row-1)` strange things
    for (size_t col = 0; col < m_columns(out); ++col) {
        for (size_t row = 0; row < m_rows(out); ++row) {
            float sum = 0;
            for (size_t i = 0; i < m_rows(a); ++i) {
                sum += *m_get(a, col, i) * *m_get(b, i, row);
            }
            *m_get(out, col, row) = sum;
        }
    }
}

int main()
{
    matrix_t our_matrix[100];

    m_init_seq(&our_matrix[0], 4, 2);
    m_init_seq(&our_matrix[1], 2, 3);

    m_print(&our_matrix[0]);
    m_print(&our_matrix[1]);

    m_init(&our_matrix[2], 4, 3);
    m_multiply(&our_matrix[2], &our_matrix[0], &our_matrix[1]);

    m_print(&our_matrix[2]);

    return 0;
}
</code>```

Tested on onlinegdb, example output:

```<code>matrix 0xf9d010
    0     100
    1     101
    2     102
    3     103

matrix 0xf9d040
    0     100     200
    1     101     201

matrix 0xf9d060
  100   10100   20100
  101   10301   20501
  102   10502   20902
  103   10703   21303
</code>```

Without the abstraction it's just a big mess. That would be something along:

```<code>  int col, row;
  for(col = 0; col < our_matrix[number_of_matrices].columns; col++){
    for(row = 0; row < our_matrix[number_of_matrices].rows; row++){
        for (size_t i = 0; i < our_matrix[matrix_index1].rows; ++i) {
            our_matrix[number_of_matrices].data[col * our_matrix[number_of_matrices].columns + row] =
                our_matrix[matrix_index1].data[col * our_matrix[matrix_index1].columns + i] +
                our_matrix[matrix_index2].data[i * our_matrix[matrix_index2].columns + row];
        }
    }
  }
</code>```

Notes:

Iterating from 0 up to < is way easier to read then all the (col-1) * ... + (row-1).

Remember to check if the indexes are our of bounds. It's easy to do even with a simple assertion, ex. assert(row < matrix->rows && col < matrix->cols);

Use size_t type to represent object size and array count.

Body:
I am working within a specific matrix memory allocation constraint that creates matrices as such:

float * matrix_data = (float *) malloc(rows * cols * sizeof(float));

I am storing this matrix inside an array of structs like this:

#define MAX_MATRICES 100

struct matrix{
    char matrixName[50];
    int rows;
    int columns;
    float* matrix_data;
};
typedef struct matrix matrix_t;

matrix_t our_matrix[MAX_MATRICES];

Given that this is the case, and I am not creating matrices by way of a 2d array like MATRIX[SIZE][SIZE]: what is the correct way to multiply two matrices created in this way?

With this current implementation if I want to do something like subtract, I do it as follows:

int max_col = our_matrix[matrix_index1].columns;
      free(our_matrix[number_of_matrices].matrix_data);
      our_matrix[number_of_matrices].data = (float *) malloc(our_matrix[matrix_index1].rows * our_matrix[matrix_index1].columns * sizeof(float));
      float *data1 = our_matrix[matrix_index1].matrix_data;
      float *data2 = our_matrix[matrix_index2].matrix_data;

      int col, row;
      for(col = 1; col <= our_matrix[matrix_index2].columns; col++){
        for(row = 1; row <= our_matrix[matrix_index2].rows; row++){
          our_matrix[number_of_matrices].matrix_data[(col-1) + (row-1) * max_col] =
            (data1[(col-1) + (row-1) * (max_col)]) - (data2[(col-1) + (row-1) * (max_col)]);
        }
      }

This is simple enough because the dimensions of matrix_index1 and matrix_index2 are identical and the matrix that they return is also of identical dimensions.

How might I achieve matrix multiplication with this method of matrix construction?

Body:
Write proper abstraction, then work your way up. It will be way easier:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct matrix_s {
    char matrixName[50];
    size_t columns;
    size_t rows;
    float* data;
};

typedef struct matrix_s matrix_t;

void m_init(matrix_t *t, size_t columns, size_t rows) {
    t->rows = rows;
    t->columns = columns;
    t->data = calloc(rows * columns, sizeof(*t->data));
    if (t->data == NULL) abort();
}

size_t m_columns(const matrix_t *t) {
    return t->columns;
}

size_t m_rows(const matrix_t *t) {
    return t->rows;
}

// matrix_get
// (x,y) = (col,row) always in that order
float *m_get(const matrix_t *t, size_t x, size_t y) {
    assert(x < m_columns(t));
    assert(y < m_rows(t));
    // __UNCONST
    // see for example `char *strstr(const char *haystack, ...`
    // it takes `const char*` but returns `char*` nonetheless.
    return (float*)&t->data[t->rows * x + y];
}

// fill matrix with a fancy patterns just so it's semi-unique
void m_init_seq(matrix_t *t, size_t columns, size_t rows) {
    m_init(t, columns, rows);
    for (size_t i = 0; i < t->columns; ++i) {
        for (size_t j = 0; j < t->rows; ++j) {
            *m_get(t, i, j) = i + 100 * j;
        }
    }
}

void m_print(const matrix_t *t) {
    printf("matrix %p\n", (void*)t->data);
    for (size_t i = 0; i < t->columns; ++i) {
        for (size_t j = 0; j < t->rows; ++j) {
            printf("%5g\t", *m_get(t, i, j));
        }
        printf("\n");
    }
    printf("\n");
}

void m_multiply(matrix_t *out, const matrix_t *a, const matrix_t *b) {
    assert(m_columns(b) == m_rows(a));
    assert(m_columns(out) == m_columns(a));
    assert(m_rows(out) == m_rows(b));
    // Index from 0, not from 1
    // don't do `(col-1) + (row-1)` strange things
    for (size_t col = 0; col < m_columns(out); ++col) {
        for (size_t row = 0; row < m_rows(out); ++row) {
            float sum = 0;
            for (size_t i = 0; i < m_rows(a); ++i) {
                sum += *m_get(a, col, i) * *m_get(b, i, row);
            }
            *m_get(out, col, row) = sum;
        }
    }
}

int main()
{
    matrix_t our_matrix[100];

    m_init_seq(&our_matrix[0], 4, 2);
    m_init_seq(&our_matrix[1], 2, 3);

    m_print(&our_matrix[0]);
    m_print(&our_matrix[1]);

    m_init(&our_matrix[2], 4, 3);
    m_multiply(&our_matrix[2], &our_matrix[0], &our_matrix[1]);

    m_print(&our_matrix[2]);

    return 0;
}

Tested on onlinegdb, example output:

matrix 0xf9d010
    0     100
    1     101
    2     102
    3     103

matrix 0xf9d040
    0     100     200
    1     101     201

matrix 0xf9d060
  100   10100   20100
  101   10301   20501
  102   10502   20902
  103   10703   21303

Without the abstraction it's just a big mess. That would be something along:

  int col, row;
  for(col = 0; col < our_matrix[number_of_matrices].columns; col++){
    for(row = 0; row < our_matrix[number_of_matrices].rows; row++){
        for (size_t i = 0; i < our_matrix[matrix_index1].rows; ++i) {
            our_matrix[number_of_matrices].data[col * our_matrix[number_of_matrices].columns + row] =
                our_matrix[matrix_index1].data[col * our_matrix[matrix_index1].columns + i] +
                our_matrix[matrix_index2].data[i * our_matrix[matrix_index2].columns + row];
        }
    }
  }

Notes:

Iterating from 0 up to < is way easier to read then all the (col-1) * ... + (row-1).

Remember to check if the indexes are our of bounds. It's easy to do even with a simple assertion, ex. assert(row < matrix->rows && col < matrix->cols);

Use size_t type to represent object size and array count.


问:
Is there a way to see all resources sending logs to a log analytics workspace?
I know that I can go to "Azure Resources" to view the resources that are connected, but it doesn't list everything that I have set to point to the workspace. For instance, CDN endpoints don't have a setting that you can configure in the portal, but you can do it in powershell. They're not listed on the Azure Resources blade in the workspace, either. I have tried using the query

```<code>AzureDiagnostics
| where TimeGenerated > ago(1d)
| summarize count() by Category
</code>```

This only showed three categories. For nsgs and a key vault. I have a lot more resources connected to this workspace.

答:
we can enable CDN diagnostics logging with Azure PowerShell / Portal as well. For detailed instructions, please refer this tutorial.

As mentioned in this tutorial, CDN falls under the list of services that support AzureDiagnostics table logs (with the supported log category of 'CoreAnalytics' which helps to get the CDN endpoint metrics bandwidth, egress, etc.)

AFAIK the reason for not getting CDN related logs under your AzureDiagnostics table would be because the configuration of CDN to send diagnostic logs to Log Analytics was not done properly or else the CDN service hasn't generated any new log for some reason.

I would suggest you to (double check or) enable CDN diagnostics logging with Azure PowerShell / Portal as instructed here and see if it resolves the issue.

Hope this helps!!

Body:
I know that I can go to "Azure Resources" to view the resources that are connected, but it doesn't list everything that I have set to point to the workspace. For instance, CDN endpoints don't have a setting that you can configure in the portal, but you can do it in powershell. They're not listed on the Azure Resources blade in the workspace, either. I have tried using the query

AzureDiagnostics
| where TimeGenerated > ago(1d)
| summarize count() by Category

This only showed three categories. For nsgs and a key vault. I have a lot more resources connected to this workspace.


问:
Type 'Observable<Object>' is not assignable to type 'Observable<boolean>'
I have an error:
 Type 'Observable' is not assignable to type 'Observable'.
  Type 'Object' is not assignable to type 'boolean'.

```<code>  deleteUser(userId: string): Observable<boolean> {
    return this.httpClient
      .delete(url, this.getHttpOptions())
      .map(res => {
        return res;
      })
      .catch(this.handleError);
  }
</code>```

I got the type of res as a boolean when I tried to print it.

答:
At compile time, TypeScript doesn't know what actually comes from API call, it infers it from declarations and function signatures.

```<code>      .delete<boolean>(url, this.getHttpOptions())
</code>```

should work.

(And yes, ditch the map).

Body:
I have an error:
 Type 'Observable' is not assignable to type 'Observable'.
  Type 'Object' is not assignable to type 'boolean'.

  deleteUser(userId: string): Observable<boolean> {
    return this.httpClient
      .delete(url, this.getHttpOptions())
      .map(res => {
        return res;
      })
      .catch(this.handleError);
  }

I got the type of res as a boolean when I tried to print it.

Body:
At compile time, TypeScript doesn't know what actually comes from API call, it infers it from declarations and function signatures.

      .delete<boolean>(url, this.getHttpOptions())

should work.

(And yes, ditch the map).


问:
Open URL in new window/tab with SSJS
I would like to open an URL via SSJS via an xp:button e.g. via:

```<code>var extCont = facesContext.getExternalContext();
extCont.redirect("myURL");
</code>```

but this opens the URL in the same window/tab. I would like to open it in a new window.

I can not use the xp:link element because I want to have an icon in it. It seems my icon gets the css applied for an anchor element (blue color) and even the .btn-link class.

答: SSJS runs on the server, there there is no concept of the browser. You're SSJS needs to pass back client-side JavaScript in what it renders to the browser at the end of the request. Look at view.postscript() to post client-side JavaScript back to the browser.

Title: Open URL in new window/tab with SSJS

Body:
I would like to open an URL via SSJS via an xp:button e.g. via:

var extCont = facesContext.getExternalContext();
extCont.redirect("myURL");

but this opens the URL in the same window/tab. I would like to open it in a new window.

I can not use the xp:link element because I want to have an icon in it. It seems my icon gets the css applied for an anchor element (blue color) and even the .btn-link class.


问:
extract values from list with the help of another list with condition in python
Extract items from the list with comes in between another list items

```<code>a = [4,8]
b = [1,2,3,4,5,6,7,8,9,0]
</code>```

I want to extract values from b list which comes in between 4 and 8 values of list a ?

Result should be

```<code>b = [5,6,7]
</code>```

答:
Others have posted answers that rely on ordered lists of integers. However, if you are operating on unordered lists where values can be of any type, this answer will work where others do not.

result = b[b.index(a[0]) + 1 : b.index(a[1])]
```

```In[2]: a = [1, "a"]; b = [0.229, "b", 1, [], "c", 5, "5", 2, "a"]
In[3]: b[b.index(a[0]) + 1 : b.index(a[1])]
Out[4]: [[], 'c', 5, '5', 2]
```

Body:
Extract items from the list with comes in between another list items

a = [4,8]
b = [1,2,3,4,5,6,7,8,9,0]

I want to extract values from b list which comes in between 4 and 8 values of list a ?

Result should be

b = [5,6,7]

Body:
Others have posted answers that rely on ordered lists of integers. However, if you are operating on unordered lists where values can be of any type, this answer will work where others do not.

result = b[b.index(a[0]) + 1 : b.index(a[1])]

In[2]: a = [1, "a"]; b = [0.229, "b", 1, [], "c", 5, "5", 2, "a"]
In[3]: b[b.index(a[0]) + 1 : b.index(a[1])]
Out[4]: [[], 'c', 5, '5', 2]


问:
Search element in array based on another array and change property
I have two array of objects like this:

```<code>const officers: any[] = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor: any[] = [
  { id: 56, name: 'New Name', additionalData: 1 },
];
</code>```

I want to find elements from searchAndChangeFor in officers and modify content. Usually If I have one element I do this:

```<code>officers.map((item) => {
    // I want to modify id: 56 and update officers here.
    item.id === 56 ? { ...item, name: 'Change name for 56' } : item
});
</code>```

But I need to search by array not single element so I've tried this but not succeeded:

```<code>officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       item.id === item2.id? { ...item, name: 'Change name for 56' } : item
   });
});
</code>```

Expected Output:

```<code>  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'New Name', additionalData: 1 },
  { id: 88, name: 'Commander Jerjerrod' }
</code>```

It goes crazy with array. How can I find elements in officers based on searchAndChangeFor and change its name? I also want to keep all other existing items in officers.

答:
You could find the item and change with the found name or return the item without change.

const
    officers = [{ id: 20, name: 'Captain Piett' }, { id: 24, name: 'General Veers' }, { id: 56, name: 'Admiral Ozzel' }, { id: 88, name: 'Commander Jerjerrod' }],
    searchAndChangeFor = [{ id: 56, name: 'New Name', additionalData: 1 }],
    result = officers.map((item) => {
        let temp = searchAndChangeFor.find((item2) => item.id === item2.id);
        return temp ? { ...item, name: temp.name } : item;
    });

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have two array of objects like this:

const officers: any[] = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor: any[] = [
  { id: 56, name: 'New Name', additionalData: 1 },
];

I want to find elements from searchAndChangeFor in officers and modify content. Usually If I have one element I do this:

officers.map((item) => {
    // I want to modify id: 56 and update officers here.
    item.id === 56 ? { ...item, name: 'Change name for 56' } : item
});

But I need to search by array not single element so I've tried this but not succeeded:

officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       item.id === item2.id? { ...item, name: 'Change name for 56' } : item
   });
});

Expected Output:

  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'New Name', additionalData: 1 },
  { id: 88, name: 'Commander Jerjerrod' }

It goes crazy with array. How can I find elements in officers based on searchAndChangeFor and change its name? I also want to keep all other existing items in officers.

Body:
You could find the item and change with the found name or return the item without change.

const
    officers = [{ id: 20, name: 'Captain Piett' }, { id: 24, name: 'General Veers' }, { id: 56, name: 'Admiral Ozzel' }, { id: 88, name: 'Commander Jerjerrod' }],
    searchAndChangeFor = [{ id: 56, name: 'New Name', additionalData: 1 }],
    result = officers.map((item) => {
        let temp = searchAndChangeFor.find((item2) => item.id === item2.id);
        return temp ? { ...item, name: temp.name } : item;
    });

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Handle click events in Adapter/ViewHolder
Currently:
I'm implementing click events in my Adapter inside of onBindViewHolder, but I have noticed that the adapter positions get messed up when doing this. I done some research and found this, where he state:

As for why it is better in the ViewHolder instead of in onBindViewHolder(), that is because onBindViewHolder() is called for each and every item and setting the click listener is an unnecessary option to repeat when you can call it once in your ViewHolder constructor.

and the example he refer to looks like this:

```<code>public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnItemClickListener {
   public MyViewHolder(View view) {
      super(view);

      view.setOnClickListener(this);
   }

   @Override
   public void OnClick(View view) {
      // Get the item clicked
      // For this example, I'm assuming your data source is of type `List<MyObject>`
      MyObject myObject = mDataSource.get(getAdapterPosition());
      // Then you can do any actions on it, for example -
      myObject.setChecked();
   }
}
</code>```

This makes sense to me, but my issue is that I have a ImageButton inside my ViewHolder and his example is only showing how to handle click events for the ViewHolder itself. Please first have a look at how my adapter currently looks like:

```<code>public class MyAdapter extends Adapter<MyAdapter.ViewHolder> {
    ArrayList<Bitmap> bitmapArrayList;
    Context context;
    LayoutInflater layoutInflater;
    View myLayoutView;
    ArrayList<PathModel> swingThumbPathList;
    ArrayList<PathModel> swingVideoPathList = new ArrayList();

    class ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {
        TextView name;
        CircularImageView image;
        ImageButton viewholderOtions;

        ViewHolder(View itemView) {
            super(itemView);
        }
    }

    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        this.myLayoutView = LayoutInflater.from(this.context).inflate(R.layout.single_item, parent, false);
        return new ViewHolder(this.myLayoutView);
    }

    public void onBindViewHolder(ViewHolder myHolder, final int position) {
        final ViewHolder holder = myHolder;
        holder.viewholderOtions = (ImageButton) myLayoutView.findViewById(R.id.viewholderOptions);
        holder.name = (TextView) this.myLayoutView.findViewById(R.id.name);
        holder.image = (CircularImageView) this.myLayoutView.findViewById(R.id.image);
        holder.name.setText(Model.getPath());
        holder.image.setImageURI(Uri.parse(Model.getPath()));

        holder.viewholderOtions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(holder.itemView.getContext(), "Options was clicked", Toast.LENGTH_LONG).show();

                showPopupMenu(holder.viewholderOtions, position);

            }
        });

        holder.itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String uri = holder.name.getText().toString();

                Toast.makeText(holder.itemView.getContext(), uri, Toast.LENGTH_LONG).show();
            }

        });

    }

    private void showPopupMenu(final View view, final int position) {
        // inflate menu
        PopupMenu popup = new PopupMenu(view.getContext(), view);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.popup_menu, popup.getMenu());
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.delete:
                        //The correct position is being toasted
                        Toast.makeText(view.getContext(), position + "Delete", Toast.LENGTH_LONG).show();

                        return true;
                    case R.id.rename:
                        Toast.makeText(view.getContext(), "Rename", Toast.LENGTH_LONG).show();

                        return true;

                    default:

                        return true;
                }
            }

        });

        popup.show();
    }
</code>```

My Question

How can I handle click events of the ViewHolder itself and the ImageButton inside of the ViewHolder?

答:
I had a laugh looking back at this question, so answering my own question almost 2 years later.

Using the same logic provided in the question, this is how you will go about setting click event to the view itself, as well as the elements inside the view, inside viewholder instead of onBindViewHolder

```<code>public class MyAdapter extends Adapter<MyAdapter.ViewHolder> {
    ArrayList<Bitmap> bitmapArrayList;
    Context context;
    LayoutInflater layoutInflater;
    View myLayoutView;
    ArrayList<PathModel> swingThumbPathList;
    ArrayList<PathModel> swingVideoPathList = new ArrayList();

    class ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {
        TextView name;
        CircularImageView image;
        ImageButton viewholderOtions;

        ViewHolder(View itemView) {
            super(itemView);
            viewholderOtions = itemView.findViewById(R.id.viewholderOptions);
            videoName = itemView.findViewById(R.id.FilePath);
            videoThumb = itemView.findViewById(R.id.VideoThumbnail);
            //set OnClickListener's for the views we want click events for
            itemView.setOnClickListener(this);
            viewholderOtions.setOnClickListener(this);
            videoThumb.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            //get the tag that we have set in onBindViewHolder
            int position = (int) v.getTag();
            if (v == viewholderOtions) {
                //viewholderOtions was selected, we can use the position above to see what item, as shown below:
                Log.e("viewholderOtions at position =", String.valueOf(position);
            }
            if (v == itemView){
                //itemView was selected, we can use the position above to see what item, as shown below:
                Log.e("itemView at position =", String.valueOf(position);
            }
            if (v == videoThumbvideoThumb){
                //itemView was selected, we can use the position above to see what item, as shown below:
                Log.e("videoThumbvideoThumb at position =", String.valueOf(position);
            }
        }

    }

    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        this.myLayoutView = LayoutInflater.from(this.context).inflate(R.layout.single_item, parent, false);
        return new ViewHolder(this.myLayoutView);
    }

    public void onBindViewHolder(ViewHolder myHolder, final int position) {
        //set a tag so we can retrieve the position via the tag
        myHolder.viewholderOtions.setTag(position);

        //Set text to holder.name
        holder.name.setText(Model.getPath());
        //a better option to below is to use a library like picasso to handle the image loading
        holder.image.setImageURI(Uri.parse(Model.getPath()));

    }

}
</code>```

But to be honest, I still set the click events inside onBindViewHolder, then I just set the following to my RecyclerView inside my Activity - recyclerView.setHasFixedSize(true);. By doing the the positions will not get messed up, as stated in my question.

Body:
Currently:
I'm implementing click events in my Adapter inside of onBindViewHolder, but I have noticed that the adapter positions get messed up when doing this. I done some research and found this, where he state:

As for why it is better in the ViewHolder instead of in onBindViewHolder(), that is because onBindViewHolder() is called for each and every item and setting the click listener is an unnecessary option to repeat when you can call it once in your ViewHolder constructor.

and the example he refer to looks like this:

public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnItemClickListener {
   public MyViewHolder(View view) {
      super(view);

      view.setOnClickListener(this);
   }

   @Override
   public void OnClick(View view) {
      // Get the item clicked
      // For this example, I'm assuming your data source is of type `List<MyObject>`
      MyObject myObject = mDataSource.get(getAdapterPosition());
      // Then you can do any actions on it, for example -
      myObject.setChecked();
   }
}

This makes sense to me, but my issue is that I have a ImageButton inside my ViewHolder and his example is only showing how to handle click events for the ViewHolder itself. Please first have a look at how my adapter currently looks like:

public class MyAdapter extends Adapter<MyAdapter.ViewHolder> {
    ArrayList<Bitmap> bitmapArrayList;
    Context context;
    LayoutInflater layoutInflater;
    View myLayoutView;
    ArrayList<PathModel> swingThumbPathList;
    ArrayList<PathModel> swingVideoPathList = new ArrayList();

    class ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {
        TextView name;
        CircularImageView image;
        ImageButton viewholderOtions;

        ViewHolder(View itemView) {
            super(itemView);
        }
    }

    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        this.myLayoutView = LayoutInflater.from(this.context).inflate(R.layout.single_item, parent, false);
        return new ViewHolder(this.myLayoutView);
    }

    public void onBindViewHolder(ViewHolder myHolder, final int position) {
        final ViewHolder holder = myHolder;
        holder.viewholderOtions = (ImageButton) myLayoutView.findViewById(R.id.viewholderOptions);
        holder.name = (TextView) this.myLayoutView.findViewById(R.id.name);
        holder.image = (CircularImageView) this.myLayoutView.findViewById(R.id.image);
        holder.name.setText(Model.getPath());
        holder.image.setImageURI(Uri.parse(Model.getPath()));

        holder.viewholderOtions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(holder.itemView.getContext(), "Options was clicked", Toast.LENGTH_LONG).show();

                showPopupMenu(holder.viewholderOtions, position);

            }
        });

        holder.itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String uri = holder.name.getText().toString();

                Toast.makeText(holder.itemView.getContext(), uri, Toast.LENGTH_LONG).show();
            }

        });

    }

    private void showPopupMenu(final View view, final int position) {
        // inflate menu
        PopupMenu popup = new PopupMenu(view.getContext(), view);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.popup_menu, popup.getMenu());
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.delete:
                        //The correct position is being toasted
                        Toast.makeText(view.getContext(), position + "Delete", Toast.LENGTH_LONG).show();

                        return true;
                    case R.id.rename:
                        Toast.makeText(view.getContext(), "Rename", Toast.LENGTH_LONG).show();

                        return true;

                    default:

                        return true;
                }
            }

        });

        popup.show();
    }

My Question

How can I handle click events of the ViewHolder itself and the ImageButton inside of the ViewHolder?

Body:
I had a laugh looking back at this question, so answering my own question almost 2 years later.

Using the same logic provided in the question, this is how you will go about setting click event to the view itself, as well as the elements inside the view, inside viewholder instead of onBindViewHolder

public class MyAdapter extends Adapter<MyAdapter.ViewHolder> {
    ArrayList<Bitmap> bitmapArrayList;
    Context context;
    LayoutInflater layoutInflater;
    View myLayoutView;
    ArrayList<PathModel> swingThumbPathList;
    ArrayList<PathModel> swingVideoPathList = new ArrayList();

    class ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {
        TextView name;
        CircularImageView image;
        ImageButton viewholderOtions;

        ViewHolder(View itemView) {
            super(itemView);
            viewholderOtions = itemView.findViewById(R.id.viewholderOptions);
            videoName = itemView.findViewById(R.id.FilePath);
            videoThumb = itemView.findViewById(R.id.VideoThumbnail);
            //set OnClickListener's for the views we want click events for
            itemView.setOnClickListener(this);
            viewholderOtions.setOnClickListener(this);
            videoThumb.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            //get the tag that we have set in onBindViewHolder
            int position = (int) v.getTag();
            if (v == viewholderOtions) {
                //viewholderOtions was selected, we can use the position above to see what item, as shown below:
                Log.e("viewholderOtions at position =", String.valueOf(position);
            }
            if (v == itemView){
                //itemView was selected, we can use the position above to see what item, as shown below:
                Log.e("itemView at position =", String.valueOf(position);
            }
            if (v == videoThumbvideoThumb){
                //itemView was selected, we can use the position above to see what item, as shown below:
                Log.e("videoThumbvideoThumb at position =", String.valueOf(position);
            }
        }

    }

    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        this.myLayoutView = LayoutInflater.from(this.context).inflate(R.layout.single_item, parent, false);
        return new ViewHolder(this.myLayoutView);
    }

    public void onBindViewHolder(ViewHolder myHolder, final int position) {
        //set a tag so we can retrieve the position via the tag
        myHolder.viewholderOtions.setTag(position);

        //Set text to holder.name
        holder.name.setText(Model.getPath());
        //a better option to below is to use a library like picasso to handle the image loading
        holder.image.setImageURI(Uri.parse(Model.getPath()));

    }

}

But to be honest, I still set the click events inside onBindViewHolder, then I just set the following to my RecyclerView inside my Activity - recyclerView.setHasFixedSize(true);. By doing the the positions will not get messed up, as stated in my question.