问:
Regex for matching all words between a set of curly braces
A simple question for most regex experts I know, but I'm trying to return all matches for the words between some curly braces in a sentence; however Ruby is only returning a single match, and I cannot figure out why exactly.

I'm using this example sentence:

```<code>sentence = hello {name} is {thing}
</code>```

with this regex to try and return both "{name}" and "{thing}":

```<code>sentence[/\{(.*?)\}/]
</code>```

However, Ruby is only returning "{name}".  Can anyone explain why it doesn't match for both words?

答:
One can do that using a positive lookbehind, (?<=\{), to require that the match be immediately preceded by a left brace, and a positive lookahead, to require that the match be immediately followed by a right brace.

```<code>str = "hello {name} is {thing}"
str.scan /(?<=\{).*?(?=\})/
  #=> ["name", "thing"]
</code>```

If there could be nested braces and only the strings within the inner braces were desired, .*? needs to be replace with [^{]*?:

```<code>str = "hello {my {name} is {thing} from} the swamp"
str.scan /(?<=\{)[^{]*?(?=\})/
  #=> ["name", "thing"]
</code>```

Body:
A simple question for most regex experts I know, but I'm trying to return all matches for the words between some curly braces in a sentence; however Ruby is only returning a single match, and I cannot figure out why exactly.

I'm using this example sentence:

sentence = hello {name} is {thing}

with this regex to try and return both "{name}" and "{thing}":

sentence[/\{(.*?)\}/]

However, Ruby is only returning "{name}".  Can anyone explain why it doesn't match for both words?

Body:
One can do that using a positive lookbehind, (?<=\{), to require that the match be immediately preceded by a left brace, and a positive lookahead, to require that the match be immediately followed by a right brace.

str = "hello {name} is {thing}"
str.scan /(?<=\{).*?(?=\})/
  #=> ["name", "thing"]

If there could be nested braces and only the strings within the inner braces were desired, .*? needs to be replace with [^{]*?:

str = "hello {my {name} is {thing} from} the swamp"
str.scan /(?<=\{)[^{]*?(?=\})/
  #=> ["name", "thing"]


来源: stackexchange

问:
Android studio error "cannot resolve method"
I am facing a problem in the Java code of my application

```<code>        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s)
        {
            Message message = dataSnapshot.getValue(Message.class);
            message.setKey(dataSnapshot.getKey());
            messages.add(message);
            displayMessages(messages);
        }
</code>```

Error thrown :  "cannot resolve method"

答:
Sometimes, all I need to do was.

File
- Invalidate Cache / Restart

ContentLicense: CC BY-SA 4.0

Body:
I am facing a problem in the Java code of my application

        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s)
        {
            Message message = dataSnapshot.getValue(Message.class);
            message.setKey(dataSnapshot.getKey());
            messages.add(message);
            displayMessages(messages);
        }

Error thrown :  "cannot resolve method"


问:
Moved node_modules folder to parent folder and get this error
I have moved the node_modules folder to the parent folder of the project to be able to share it between projects. Then when I execute "npm run dev" command inside the project folder I get this error:

```
E:\NodeApps\MyApp>npm run dev

> testapp@1.0.0 dev E:\NodeApps\MyApp
> cross-env NODE_ENV=development webpack-dev-server --open --hot

'cross-env' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! testapp@1.0.0 dev: `cross-env NODE_ENV=development webpack-dev-server --open --hot`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the testapp@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\me\AppData\Roaming\npm-cache\_logs\2019-05-27T23_51_07_151Z-debug.log
```

The solution was working fine before I moved the node_modules. I have read that the runtime will search up the directory-tree to find node_modules.

What are the steps to make the project work without moving node_modules back again?

答:
Every project has it's own package.json which have their own dependencies and devdependencies which is required to the particular project and copying node_modules doesn't change the path or modify related things.Also Set the path in ENVIRONMENT VARIABLES(already done then leave that).

Run this command:

```<code>npm install
</code>```

Body:
I have moved the node_modules folder to the parent folder of the project to be able to share it between projects. Then when I execute "npm run dev" command inside the project folder I get this error:

E:\NodeApps\MyApp>npm run dev

> testapp@1.0.0 dev E:\NodeApps\MyApp
> cross-env NODE_ENV=development webpack-dev-server --open --hot

'cross-env' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! testapp@1.0.0 dev: `cross-env NODE_ENV=development webpack-dev-server --open --hot`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the testapp@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\me\AppData\Roaming\npm-cache\_logs\2019-05-27T23_51_07_151Z-debug.log

The solution was working fine before I moved the node_modules. I have read that the runtime will search up the directory-tree to find node_modules.

What are the steps to make the project work without moving node_modules back again?

Body:
Every project has it's own package.json which have their own dependencies and devdependencies which is required to the particular project and copying node_modules doesn't change the path or modify related things.Also Set the path in ENVIRONMENT VARIABLES(already done then leave that).

Run this command:

npm install


问:
jqGrid: fixed row
Is it possible to set a row on a fixed position? For example, we have now a total row, and we always want the total on top, after sorting etc.

Is there a plugin for this?

We have tried to do this in the onLoadComplete by redrawing the whole table like so:

```<code>var rowIDs = $(this).getDataIDs();
var rowID, columnID;
$(this).clearGridData();
for (rowID in rowIDs) {
  for (columnID in data.rows[rowID]) {
    $(this).addRowData(rowIDs[rowID], data.rows[rowID], (data.rows[rowID][columnID].first ? 'first' : null));
    break; // Only do this for the first column
  }
}
</code>```

but that is bad for performance, we have thousands of rows.

after Oleg's comment:

The total row is just a row from our dataset. The dataset has this format:

Columns: 'Network', 'Clicks', 'Views'

```<code>data = [
  {
    'Network': {value:'Google'}, 'Clicks': {value:38392882}, 'Views':{value:3939922}
  },
  {
    'Network': {value:'Sanoma'}, 'Clicks': {value:177883}, 'Views':{value:39293}
  },
  ...
  ,
  {
    'Network': {value:'Total'}, 'Clicks': {value:993832732223}, 'Views':{value:3932293939}, 'first': true
  },
  ...

]
}
</code>```

So we set in our datarow which row we want to have on top ('first':true).

By processing, we use that to set in on top of the table. Hopefully this is more understandable :)

Thanks in advance,

Eddy

答:
The footer are placed in the div with the class "ui-jqgrid-sdiv" and it is placed typically below the div with the class "ui-jqgrid-bdiv" where the main grid contain are placed. So to move the footer on top of page you need to move the the footer div. Additionally you should place bottom border in the style which you need. The code could be like the following:

```<code>$('div.ui-jqgrid-sdiv').css({
    "border-bottom-style":"solid",
    "border-bottom-color":"#a6c9e2",
    "border-bottom-width":"2px"
}).insertBefore($('div.ui-jqgrid-bdiv'));
</code>```

as the result you will receive

See the demo live here.

ContentLicense: CC BY-SA 3.0

Title: jqGrid: fixed row

Body:
Is it possible to set a row on a fixed position? For example, we have now a total row, and we always want the total on top, after sorting etc.

Is there a plugin for this?

We have tried to do this in the onLoadComplete by redrawing the whole table like so:

var rowIDs = $(this).getDataIDs();
var rowID, columnID;
$(this).clearGridData();
for (rowID in rowIDs) {
  for (columnID in data.rows[rowID]) {
    $(this).addRowData(rowIDs[rowID], data.rows[rowID], (data.rows[rowID][columnID].first ? 'first' : null));
    break; // Only do this for the first column
  }
}

but that is bad for performance, we have thousands of rows.

after Oleg's comment:

The total row is just a row from our dataset. The dataset has this format:

Columns: 'Network', 'Clicks', 'Views'

data = [
  {
    'Network': {value:'Google'}, 'Clicks': {value:38392882}, 'Views':{value:3939922}
  },
  {
    'Network': {value:'Sanoma'}, 'Clicks': {value:177883}, 'Views':{value:39293}
  },
  ...
  ,
  {
    'Network': {value:'Total'}, 'Clicks': {value:993832732223}, 'Views':{value:3932293939}, 'first': true
  },
  ...

]
}

So we set in our datarow which row we want to have on top ('first':true).

By processing, we use that to set in on top of the table. Hopefully this is more understandable :)

Thanks in advance,

Eddy

Body:
The footer are placed in the div with the class "ui-jqgrid-sdiv" and it is placed typically below the div with the class "ui-jqgrid-bdiv" where the main grid contain are placed. So to move the footer on top of page you need to move the the footer div. Additionally you should place bottom border in the style which you need. The code could be like the following:

$('div.ui-jqgrid-sdiv').css({
    "border-bottom-style":"solid",
    "border-bottom-color":"#a6c9e2",
    "border-bottom-width":"2px"
}).insertBefore($('div.ui-jqgrid-bdiv'));

as the result you will receive

See the demo live here.


问:
Grouping Appenders At Logback?
I have two appenders. One of them is DB appender and the other one is SMTPAppender. When I log a string with a special marker I want to use both my custom db appender and SMTPAppender. However I don't want to define two appenders everythime as like that:

```<code><logger name="com.MyClass" level="DEBUG" additivity="false">
    <appender-ref ref="CUSTOM_DB"/>
    <appender-ref ref="CUSTOM_EMAIL"/>
</logger>
</code>```

I want a special reference that as like that:

```<code><appender-group ref="CUSTOM_COMBO">
    <appender-ref ref="CUSTOM_DB"/>
    <appender-ref ref="CUSTOM_EMAIL"/>
</appender-group>

<logger name="com.MyClass" level="DEBUG" additivity="false">
    <appender-ref ref="CUSTOM_COMBO"/>
</logger>
</code>```

It should both call CUSTOM_DB and CUSTOM_EMAIL. How can I do that at Logback with slf4j?

答:
So from https://tersesystems.com/blog/2019/05/27/application-logging-in-java-part-5/

```<code>public class CompositeAppender<E> extends UnsynchronizedAppenderBase<E> implements AppenderAttachable<E> {

    protected AppenderAttachableImpl<E> aai = new AppenderAttachableImpl<E>();

    @Override
    protected void append(E eventObject) {
        aai.appendLoopOnAppenders(eventObject);
    }

    // AppenderAttachable API delegates to aai in all cases
}
</code>```

and

```<code><configuration>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%-5level] %logger{15} -  message%n%xException{10}</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>file.log</file>
        <encoder>
            <pattern>%date - %message</pattern>
        </encoder>
    </appender>

    <appender name="CONSOLE_AND_FILE" class="com.tersesystems.logback.CompositeAppender">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </appender>

    <root level="TRACE">
        <appender-ref ref="CONSOLE_AND_FILE"/>
    </root>
</configuration>
</code>```

Title: Grouping Appenders At Logback?

Body:
I have two appenders. One of them is DB appender and the other one is SMTPAppender. When I log a string with a special marker I want to use both my custom db appender and SMTPAppender. However I don't want to define two appenders everythime as like that:

<logger name="com.MyClass" level="DEBUG" additivity="false">
    <appender-ref ref="CUSTOM_DB"/>
    <appender-ref ref="CUSTOM_EMAIL"/>
</logger>

I want a special reference that as like that:

<appender-group ref="CUSTOM_COMBO">
    <appender-ref ref="CUSTOM_DB"/>
    <appender-ref ref="CUSTOM_EMAIL"/>
</appender-group>

<logger name="com.MyClass" level="DEBUG" additivity="false">
    <appender-ref ref="CUSTOM_COMBO"/>
</logger>

It should both call CUSTOM_DB and CUSTOM_EMAIL. How can I do that at Logback with slf4j?

Body:
So from https://tersesystems.com/blog/2019/05/27/application-logging-in-java-part-5/

public class CompositeAppender<E> extends UnsynchronizedAppenderBase<E> implements AppenderAttachable<E> {

    protected AppenderAttachableImpl<E> aai = new AppenderAttachableImpl<E>();

    @Override
    protected void append(E eventObject) {
        aai.appendLoopOnAppenders(eventObject);
    }

    // AppenderAttachable API delegates to aai in all cases
}

and

<configuration>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%-5level] %logger{15} -  message%n%xException{10}</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>file.log</file>
        <encoder>
            <pattern>%date - %message</pattern>
        </encoder>
    </appender>

    <appender name="CONSOLE_AND_FILE" class="com.tersesystems.logback.CompositeAppender">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </appender>

    <root level="TRACE">
        <appender-ref ref="CONSOLE_AND_FILE"/>
    </root>
</configuration>


问:
how to return a string from a for loop instead of printing out one by one
Im trying to make my for loop return a string of the whole word with a dash or each letter depending on guess_letters instead of print out each letter one by one for my hangman game.

Ive tried to print letter as a string, return letter then set a variable  to that function then print the variable.

```<code>import random

words = ['apple','python','parent']
def randomword(words):
  return random.choice(words)
chosenword = randomword(words)
tries = 10

guess_letters = []
def dashshow(guess_letters):
  for letter in chosenword:
    if letter in guess_letters:
      return str(letter)
      string_letter = dashshow(guess_letters)
      print(string_Letter)
    else:
      return '-'
      dash_letter = dashshow(guess_letters)
      print(dash_letter)

def playgame(tries):
  while  tries != 0 and "_" in chosenword:
    print(f"You have {tries} tries left")
    guess = str(input("Guess a letter of the word")).lower()
    guess_letters.append(guess)
    if guess in chosenword:
      print("You got a letter correct!")
      turns -= 1
    else:
      print("That letter is not in the word")
      turns -= 1

playgame(tries)
</code>```

I thought it would print out the string with dashes or letters depending on the guessed_letters list but it doesn't print anything.

答:
here is way you can. just modify as you need.Also, You can compare your code with this one. to find mistake.</p>

```<code>import random

words = ['apple','python','parent']
def randomword(words):
    return random.choice(words)
chosenword = randomword(words)
print (chosenword) #this is random word you can delete this line.
tries = 10

guess_letters = []

def dashshow(guess_letter):
    guess_letters.append(guess_letter)
    print(guess_letters) # just to debug you can remove.
    if len(guess_letters) == len(chosenword):
        print("You Won Dear!")
        exit()

def playgame(tries):
  while tries != 0 :
    print(f"You have {tries} tries left")
    guess = str(input("Guess a letter of the word:> ")).lower()
    if any(guess in s for s in chosenword):
      print("You got a letter correct!")
      dashshow(guess)
      tries -= 1
    else:
      print("That letter is not in the word")
      tries -= 1

playgame(tries)
</code>```

Body:
Im trying to make my for loop return a string of the whole word with a dash or each letter depending on guess_letters instead of print out each letter one by one for my hangman game.

Ive tried to print letter as a string, return letter then set a variable  to that function then print the variable.

import random

words = ['apple','python','parent']
def randomword(words):
  return random.choice(words)
chosenword = randomword(words)
tries = 10

guess_letters = []
def dashshow(guess_letters):
  for letter in chosenword:
    if letter in guess_letters:
      return str(letter)
      string_letter = dashshow(guess_letters)
      print(string_Letter)
    else:
      return '-'
      dash_letter = dashshow(guess_letters)
      print(dash_letter)

def playgame(tries):
  while  tries != 0 and "_" in chosenword:
    print(f"You have {tries} tries left")
    guess = str(input("Guess a letter of the word")).lower()
    guess_letters.append(guess)
    if guess in chosenword:
      print("You got a letter correct!")
      turns -= 1
    else:
      print("That letter is not in the word")
      turns -= 1

playgame(tries)

I thought it would print out the string with dashes or letters depending on the guessed_letters list but it doesn't print anything.

Body:
here is way you can. just modify as you need.Also, You can compare your code with this one. to find mistake.

import random

words = ['apple','python','parent']
def randomword(words):
    return random.choice(words)
chosenword = randomword(words)
print (chosenword) #this is random word you can delete this line.
tries = 10

guess_letters = []

def dashshow(guess_letter):
    guess_letters.append(guess_letter)
    print(guess_letters) # just to debug you can remove.
    if len(guess_letters) == len(chosenword):
        print("You Won Dear!")
        exit()

def playgame(tries):
  while tries != 0 :
    print(f"You have {tries} tries left")
    guess = str(input("Guess a letter of the word:> ")).lower()
    if any(guess in s for s in chosenword):
      print("You got a letter correct!")
      dashshow(guess)
      tries -= 1
    else:
      print("That letter is not in the word")
      tries -= 1

playgame(tries)


问:
How do I add a timeseries plot to a regular plot?
I made a moving average of my timeseries and I'd like to super-impose it on top of my timeseries.

Here's my series ggplot(daily_revenue, aes(day, revenue)) + geom_line()

Here's my moving average ma(ts(daily_rev_full$revenue, start = c(2014, 1), frequency = 365), order = 15) %>% autoplot()

I tried to add them together by including them as separate geom_line values. I also tried to add autoplot to ggplot and I tried to create a regular plot and then add the moving average with lines().

答:
Using the forecast package you can generate a plot of time series objects using autoplot(). In order to superimpose your moving average you can use the autolayer() function. See below reprex.

library(forecast)

autoplot(WWWusage) +
  autolayer(ma(WWWusage, order = 10), colour = TRUE)
#> Warning: Removed 10 rows containing missing values (geom_path).
```

Created on 2019-05-28 by the reprex package (v0.2.1)

Body:
Using the forecast package you can generate a plot of time series objects using autoplot(). In order to superimpose your moving average you can use the autolayer() function. See below reprex.

library(forecast)

autoplot(WWWusage) +
  autolayer(ma(WWWusage, order = 10), colour = TRUE)
#> Warning: Removed 10 rows containing missing values (geom_path).

Created on 2019-05-28 by the reprex package (v0.2.1)


问:
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.

答:
You are observing only the first page of search. Where you have the list of articles. To get the content of article you have to send request to the article and fetch content from there.

Here I am fetching Title, Author, Publish Date, Content and storing them in a list. From that list we can create a DataFrame later, if required.

newyork_times_list = []
for a in search_results.find_all('a', href=True):

    newyork_times = {}
    page_url = "https://www.nytimes.com" + a['href']

    try:
        # URL
        newyork_times['URL'] =  page_url

        # Invoke URL
        page = requests.get(page_url)
        page_soup = BeautifulSoup(page.content, 'lxml')

        # Title
        newyork_times['Title'] = page_soup.find('title').text

        # Content
        page_content = ''
        page_soup_div = page_soup.find_all("div", {"class":"StoryBodyCompanionColumn"})
        for p_content in page_soup_div:
            page_content = page_content + p_content.text

        # Content
        newyork_times['Content'] =  page_content

        # Date Time
        page_soup_span = page_soup.find_all("time")
        newyork_times['Publish Date'] = page_soup_span[0].text

        # Author
        page_soup_span = page_soup.find_all("span", {"itemprop": "name"})
        newyork_times['Author'] =  page_soup_span[0].text

        newyork_times_list.append(newyork_times)

        print('Processed', page_url)
    except:
        print('ERROR!', page_url)

print('Done')
```

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.


问:
Query to get one to many and many to one employee project relationship
I have the following table:

Table:

```<code>create table emp_project_mapping
(
    emp_id varchar(10),
    pro_id varchar(10)
)
</code>```

Records:

```<code>insert into emp_project_mapping values('E101','P1'),
                                      ('E101','P2'),
                                      ('E102','P1'),
                                      ('E103','P3'),
                                      ('E104','P3'),
                                      ('E105','P4');
</code>```

Query 1: Find the employee who is working on more than one project.

Expected Result:

```<code>emp_id  pro_id
--------------
E101    P1
E101    P2
</code>```

Query 2: Find the more than one employees working on the same project.

```<code>emp_id  pro_id
--------------
E103    P3
E104    P3
E101    P1
E102    P1
</code>```

Try:

Query 1:

```<code>;WITH CTE
AS
(
    SELECT  emp_id,
            pro_id,
            DENSE_RANK() over(order by emp_id) empid_rank,
            DENSE_RANK() over(order by pro_id) proid_rank
    FROM emp_project_mapping
)
SELECT emp_id,pro_id
FROM CTE
WHERE empid_rank = 1 and proid_rank>1
</code>```

Output:

```<code>emp_id  pro_id
---------------
E101    P2
</code>```

Query 2:

```<code>;WITH CTE
AS
(
    SELECT  emp_id,
            pro_id,
            DENSE_RANK() over(order by emp_id) empid_rank,
            DENSE_RANK() over(order by pro_id) proid_rank
    FROM emp_project_mapping
)
SELECT emp_id,pro_id
FROM CTE
WHERE empid_rank > 1 and proid_rank = 1
</code>```

Output:

```<code>emp_id  pro_id
----------------
E102    P1
</code>```

答:
You may try this....

For first solution

```<code>        ;WITH CTE
        AS
        (
            SELECT  emp_id,
                    pro_id,
                    ROW_NUMBER() OVER (PARTITION BY emp_id ORDER BY pro_id) empid_rank
            FROM emp_project_mapping
        )
        SELECT * from emp_project_mapping WHERE emp_id IN (SELECT emp_id
        FROM CTE
        WHERE empid_rank > 1 )
</code>```

For second solution

```<code>        ;WITH CTE
        AS
        (
            SELECT  emp_id,
                    pro_id,
                    ROW_NUMBER() OVER (PARTITION BY pro_id ORDER BY emp_id) proid_rank
            FROM emp_project_mapping
        )
        SELECT * FROM emp_project_mapping WHERE pro_id IN (SELECT pro_id
        FROM CTE
        WHERE proid_rank>1)
</code>```

Body:
I have the following table:

Table:

create table emp_project_mapping
(
    emp_id varchar(10),
    pro_id varchar(10)
)

Records:

insert into emp_project_mapping values('E101','P1'),
                                      ('E101','P2'),
                                      ('E102','P1'),
                                      ('E103','P3'),
                                      ('E104','P3'),
                                      ('E105','P4');

Query 1: Find the employee who is working on more than one project.

Expected Result:

emp_id  pro_id
--------------
E101    P1
E101    P2

Query 2: Find the more than one employees working on the same project.

emp_id  pro_id
--------------
E103    P3
E104    P3
E101    P1
E102    P1

Try:

Query 1:

;WITH CTE
AS
(
    SELECT  emp_id,
            pro_id,
            DENSE_RANK() over(order by emp_id) empid_rank,
            DENSE_RANK() over(order by pro_id) proid_rank
    FROM emp_project_mapping
)
SELECT emp_id,pro_id
FROM CTE
WHERE empid_rank = 1 and proid_rank>1

Output:

emp_id  pro_id
---------------
E101    P2

Query 2:

;WITH CTE
AS
(
    SELECT  emp_id,
            pro_id,
            DENSE_RANK() over(order by emp_id) empid_rank,
            DENSE_RANK() over(order by pro_id) proid_rank
    FROM emp_project_mapping
)
SELECT emp_id,pro_id
FROM CTE
WHERE empid_rank > 1 and proid_rank = 1

Output:

emp_id  pro_id
----------------
E102    P1

Body:
You may try this....

For first solution

        ;WITH CTE
        AS
        (
            SELECT  emp_id,
                    pro_id,
                    ROW_NUMBER() OVER (PARTITION BY emp_id ORDER BY pro_id) empid_rank
            FROM emp_project_mapping
        )
        SELECT * from emp_project_mapping WHERE emp_id IN (SELECT emp_id
        FROM CTE
        WHERE empid_rank > 1 )

For second solution

        ;WITH CTE
        AS
        (
            SELECT  emp_id,
                    pro_id,
                    ROW_NUMBER() OVER (PARTITION BY pro_id ORDER BY emp_id) proid_rank
            FROM emp_project_mapping
        )
        SELECT * FROM emp_project_mapping WHERE pro_id IN (SELECT pro_id
        FROM CTE
        WHERE proid_rank>1)


问:
BI - fact table design with incompatible grains
I'm quite new to BI designing DB, and here some point I do not understand well.
I'm trying to import french census data, where I got population for each city. For each city, I have population with different age classification, that can't really relate with each other.

For instance, let's say that one classification is 00 to 20 years old, 21 to 59, and 60+
And the other is way more precise : 00 to 02, 03 to 05, etc. but the bounds are never the same as the first one classification : I don't have 15 to 20, but 18 to 22, for example.

So those 2 classifications are incompatible. How can I use them in my fact table ? Should I use 2 fact tables and 2 cubes ? Should I use one fact table, and 2 dimensions for 1 cube ? But in this case, I will have double counted facts when I'll sum to have total population for a city, won't I ?

This is national census data, and national classifications, so changing that or estimating population to mix those classifications is not an option. And to be clear, one row doesn't relate to one person, but to one city. My facts are not individuals but cities' populations.
So this table is like :
Line 1 : One city - one amount of population - one code for dim age (ex. 00 to 19 yo) of this population - code (m/f) for the dim gender of that population - date of the census
Line 2 : Same city - one amount of population - one code for dim age (ex. 20 to 34) of this population - code (m/f) for the dim gender - date of the census
And so it goes for a lot of cities, both gender, and multiple years.
Same

I hope this question is clear enough, as english is not my native language and as I'm quite new in DB and BI !

Thanks for helping me with that.

答:
you can crate one dimention as below

young 1-20
adult 21-59
senior 60+

Classification is
young city 1 : 1-20
young city 2 : 4-23

```<code> id  field1   field2         field3          field4  .......

 1   1 year   young_city_1   other           .......
 2   2 year   young_city_1   other           .......
 3   3 year   young_city_1   other           .......
 4   4 year   young_city_1   young_city_2    .......
</code>```

Now you can report from any item and with any division

i hope it is help you

Body:
you can crate one dimention as below

young 1-20
adult 21-59
senior 60+

Classification is
young city 1 : 1-20
young city 2 : 4-23

 id  field1   field2         field3          field4  .......

 1   1 year   young_city_1   other           .......
 2   2 year   young_city_1   other           .......
 3   3 year   young_city_1   other           .......
 4   4 year   young_city_1   young_city_2    .......

Now you can report from any item and with any division

i hope it is help you


问:
Delete node from AST in Go
Is there any way to delete specific type node from AST? (for example, i want to delete all Expr Statements) Or maybe there is a way to replace it with empty ast.Expr node?

I didnt find any documentation about it so any help would be appreciated. Thanks in advance!

UPD:

```<code>func find_node(file *ast.File) {

    ast.Inspect(file, func(node ast.Node) bool {

        switch x := node.(type) {

        case *ast.ExprStmt:

           var e ast.Expr
           e = x.X

           fmt.Printf("Expression found: %s\n", e)

        }

    return true
})
</code>```

}

答: You can try the astutil package. See the delete example in the tests at rewrite_test.go.</p>

Title: Delete node from AST in Go

Body:
Is there any way to delete specific type node from AST? (for example, i want to delete all Expr Statements) Or maybe there is a way to replace it with empty ast.Expr node?

I didnt find any documentation about it so any help would be appreciated. Thanks in advance!

UPD:

func find_node(file *ast.File) {

    ast.Inspect(file, func(node ast.Node) bool {

        switch x := node.(type) {

        case *ast.ExprStmt:

           var e ast.Expr
           e = x.X

           fmt.Printf("Expression found: %s\n", e)

        }

    return true
})

}


问:
Functional Interface Implementations and use cases
I was just trying to write a functional interface to understand the different use cases.

Looking at the below code which I have written, I understand that I can have different implementations using lambda expressions. Apart from this can anyone show the complex implementations?

Is it possible to use other default method i.e. addLikeOtherWay in lambda expression? if yes how in my example?

Why would I have interface with only one abstract method? What would be the use case of having only single abstract method in my interface?

```<code>public class Calculator {

    public static void main(String[] args) {
        ICalculator i = (int a, int b) -> a + b;
        System.out.println(i.add(5, 2));
        i = (int a, int b) -> a + b + a;
        System.out.println(i.add(5, 2));
    }
}

@FunctionalInterface
interface ICalculator {

    public int add(int a, int b);

    default int addLikeThis(int a, int b) {
        return a + b;
    }

    default int addLikeOtherWay(int a, int b) {
        return a + b + a + b;
    }

}
</code>```

答:
Why would I have interface with only one abstract method? What would be the use case of having only single abstract method in my interface?

To facilitate the use of lambda expressions , which are nameless functions.
Lambda expressions make code expressive and reduce clutter. It also makes code more readable.  This is based  my experience working with lambda expressions.

Body:
I was just trying to write a functional interface to understand the different use cases.

Looking at the below code which I have written, I understand that I can have different implementations using lambda expressions. Apart from this can anyone show the complex implementations?

Is it possible to use other default method i.e. addLikeOtherWay in lambda expression? if yes how in my example?

Why would I have interface with only one abstract method? What would be the use case of having only single abstract method in my interface?

public class Calculator {

    public static void main(String[] args) {
        ICalculator i = (int a, int b) -> a + b;
        System.out.println(i.add(5, 2));
        i = (int a, int b) -> a + b + a;
        System.out.println(i.add(5, 2));
    }
}

@FunctionalInterface
interface ICalculator {

    public int add(int a, int b);

    default int addLikeThis(int a, int b) {
        return a + b;
    }

    default int addLikeOtherWay(int a, int b) {
        return a + b + a + b;
    }

}


问:
excel VBA break execution when there's no break key on keyboard
I'm just noticing that on my laptop (Dell XPS 15z) there's no BREAK key (no dedicated number keypad). I'm running the debugger step-by-step and then when all seems fine, I just let it play out. However, it's running in an infinite loop and now I'm realizing there's no way to stop it without the break key!!!!

Is this a bad joke? I had to reboot the computer; is there a more graceful way??

答:
I found this thread and saw the solution that has the most votes, but then realized my laptop has no Pause, Break or ScrLk) keys. I tried other proposed solutions, like 'OnScreen Keyboard' or alternative key combinations, but those didn't work either.

Then it hit me: if it's a phantom break point associated with particular line(s) of code, why not just get rid of the line(s)?

So that's what I did:

I cut the line(s) where execution was breaking.

Ran the macro again (it didn't break this time)

Pasted the line(s) again.

It worked for me, when no other key combination (onscreen or physical) worked. Hope it helps someone!


问:
HelpScreen overlay in React-native
I am working with help screens in React-native. My idea of help screen is something like this :

The workaround I tried is, I have created images from the screenshot and shown on the top of the actual screen whenever I need to show the help screen. I am wondering whether is this right way to do this ? or is there any other standard method available to do this?

答: try this library, react-native-app-tour</p>

Title: HelpScreen overlay in React-native

Body: try this library, react-native-app-tour


问:
jQuery convert element ids into comma seperated string
I have a simple html and jquery script like below, I am trying to get a comma seperated list of data-item-id so would look like...

```<code>1,2,3,4,5
</code>```

var items = $('.container').children();
console.log(items);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div></code>```

I have grabbed the items but how can I convert this into the comma seperated string?

答:
Another alternative with JQuery could be using .each() to traverse the items while grabbing the data-item-id with .data() and adding it to a string.

$(document).ready(function()
{
    var itemList = "";

    $('.container .item').each(function()
    {
        itemList += $(this).data('item-id') + ",";
    });

    console.log("Ids:", itemList.slice(0,-1));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}</code>```

Item 1

Item 2

Item 3

Item 4

Item 5

```

Body:
I have a simple html and jquery script like below, I am trying to get a comma seperated list of data-item-id so would look like...

1,2,3,4,5

var items = $('.container').children();
console.log(items);

Item 1

Item 2

Item 3

Item 4

Item 5

I have grabbed the items but how can I convert this into the comma seperated string?

Body:
Another alternative with JQuery could be using .each() to traverse the items while grabbing the data-item-id with .data() and adding it to a string.

$(document).ready(function()
{
    var itemList = "";

    $('.container .item').each(function()
    {
        itemList += $(this).data('item-id') + ",";
    });

    console.log("Ids:", itemList.slice(0,-1));
});

.as-console {background-color:black !important; color:lime;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div>


问:
How can I upload a picture in a server using Android and Retrofit?
I am trying to upload a picture in a server with Retrofit but I get HTTP 400 error. I know that this error mean that the call has not been done correctly but I do dont know when I am doing wrong. I only need to upload a single image.

I have tried adding headers multipart/form-data and also content-type: image/jpeg and also without but it keeps throwing 400 error.

This code in the interface:

```<code>@Multipart
@POST("https://myweb.com/endpoint")
Observable<DefaultResponse> uploadUserImageRx(
    @Part MultipartBody.Part image
);
</code>```

And here the call:

```<code>var file = // initialized file here

var filePart = MultipartBody.Part.createFormData("file",file.getName(),   RequestBody.create(MediaType.parse("image/jpeg"), file))

unsubscribeUploadPhoto()
uploadPhotoSubscription = MyApiClient.getApi()
    .uploadUserImageRx(filePart)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(object : SubscriberAdapter<DefaultResponse>()
        {
          //Notify everything went well.
        })
</code>```

I expect the photo to be upload but i get this error instead.

The requirements of the endpoint are:

Authorization(header) as String

答:
This error mean that you didn,t attached headers correctly as I think there should be a header like  access token. check if there is something like that  then implement your API like below.</p>

```<code>@Multipart
@POST("https://myweb.com/endpoint")
Observable<DefaultResponse> uploadUserImageRx(
    @Header("Authorization") String authorization,
    @Part MultipartBody.Part image
);
</code>```

Body:
I am trying to upload a picture in a server with Retrofit but I get HTTP 400 error. I know that this error mean that the call has not been done correctly but I do dont know when I am doing wrong. I only need to upload a single image.

I have tried adding headers multipart/form-data and also content-type: image/jpeg and also without but it keeps throwing 400 error.

This code in the interface:

@Multipart
@POST("https://myweb.com/endpoint")
Observable<DefaultResponse> uploadUserImageRx(
    @Part MultipartBody.Part image
);

And here the call:

var file = // initialized file here

var filePart = MultipartBody.Part.createFormData("file",file.getName(),   RequestBody.create(MediaType.parse("image/jpeg"), file))

unsubscribeUploadPhoto()
uploadPhotoSubscription = MyApiClient.getApi()
    .uploadUserImageRx(filePart)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(object : SubscriberAdapter<DefaultResponse>()
        {
          //Notify everything went well.
        })

I expect the photo to be upload but i get this error instead.

The requirements of the endpoint are:

Authorization(header) as String

Body:
This error mean that you didn,t attached headers correctly as I think there should be a header like  access token. check if there is something like that  then implement your API like below.

@Multipart
@POST("https://myweb.com/endpoint")
Observable<DefaultResponse> uploadUserImageRx(
    @Header("Authorization") String authorization,
    @Part MultipartBody.Part image
);


问:
ValueError at /accounts/profile/ The 'image' attribute has no file associated with it
This error occurs when a user is either not a superuser or doesn't have a profile image (submitted via userprofile in admin).

ValueError at /accounts/profile/
The 'image' attribute has no file associated with it.
Request Method: GET
Request URL:    http://127.0.0.1:8000/accounts/profile/

Error during template rendering

```<code>In template /Users/joseph/Documents/django/tutorial/accounts/templates/base.html, error at line 17
The 'image' attribute has no file associated with it.
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

9     <meta charset="utf-8">
10    <html lang="en" dir="ltr">
11
12  <!-- Navigation bar -->
13
14    <br>
15    <nav class="navbar navbar-expand-lg navbar-green bg-light">
16    <a class="navbar-brand" href="/accounts/home">MySite</a>
17    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
18      <span class="navbar-toggler-icon"></span>
19    </button>
20        {% if user.is_authenticated %}
21    <div class="collapse navbar-collapse" id="navbarNav">
22      <ul class="nav navbar-nav ml-auto">
23        <li class="nav-item">
24          <a class="nav-link"   href="/accounts/explore/">Explore</a>
25        </li>
26        </ul>
27      <ul class="nav navbar-nav ml-auto">
</code>```

models.py:

```<code>class UserProfile(models.Model):
   user = models.OneToOneField(User, models.CASCADE)
   description = models.CharField(max_length=100, blank=True, default='')
   city = models.CharField(max_length=100, blank=True, default='')
   website = models.URLField(blank=True, default='')
   contactNumber = models.IntegerField(blank=True, default=0)
   image = models.ImageField(upload_to='profile_image', blank=True)

def __str__(self):
    return self.user.username
</code>```

Why does this happen? It can't actually be base.html(extended)? If there is anything else that needs adding to help solve the problem, please let me know .Thanks

答:
Look for the line (in your template file, e.g. base.html) where you're rendering the image and add an if condition. Something like:

```<code>{% if item.image %}
  <img target="_blank" src="{{ item.image.url }}" />
{% endif %}
</code>```

I think it's self-explanatory, but don't hesitate to ask anything if needed.

Body:
This error occurs when a user is either not a superuser or doesn't have a profile image (submitted via userprofile in admin).

ValueError at /accounts/profile/
The 'image' attribute has no file associated with it.
Request Method: GET
Request URL:    http://127.0.0.1:8000/accounts/profile/

Error during template rendering

In template /Users/joseph/Documents/django/tutorial/accounts/templates/base.html, error at line 17
The 'image' attribute has no file associated with it.
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

9     <meta charset="utf-8">
10
11
12
13
14

15
16    MySite
17    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
18
19    </button>
20        {% if user.is_authenticated %}
21

22

23

24          Explore
25

26

27

models.py:

class UserProfile(models.Model):
   user = models.OneToOneField(User, models.CASCADE)
   description = models.CharField(max_length=100, blank=True, default='')
   city = models.CharField(max_length=100, blank=True, default='')
   website = models.URLField(blank=True, default='')
   contactNumber = models.IntegerField(blank=True, default=0)
   image = models.ImageField(upload_to='profile_image', blank=True)

def __str__(self):
    return self.user.username

Why does this happen? It can't actually be base.html(extended)? If there is anything else that needs adding to help solve the problem, please let me know .Thanks

Body:
Look for the line (in your template file, e.g. base.html) where you're rendering the image and add an if condition. Something like:

{% if item.image %}
  <img target="_blank" src="{{ item.image.url }}" />
{% endif %}

I think it's self-explanatory, but don't hesitate to ask anything if needed.


问:
I'd like to apply margin-top inside the box
Apply this code and you can see it. The margine-top of the internal box is applied to the outside. How can inBox not affect the box?</p>

```<code><!DOCTYPE html>
<html>
<head>
  <style>
.box{
  width: 400px;
  height: 400px;
  background-color: red;
}
.inBox{
  width: 200px;
  height: 200px;
  background-color: white;

  margin-top: 100px;
}
  </style>
  <meta charset="utf-8">
</head>
<body>
  <div class = "box">
    <div class = "inBox">
  </div>
</body>
</html>
</code>```

答:
So you actually can have margin-top on the child element. As mentioned by others, vertical margins can collapse. This is one of the least intuitive instances, where the margin-top of the child is apparently going right through the parent.

You can counter this by adding any amount of padding to the parent. I added 1px of padding-top and the margin suddenly appears to behave as originally expected:

.box {
  width: 400px;
  height: 400px;
  background-color: red;
  padding-top: 1px;
}

.inBox {
  width: 200px;
  height: 200px;
  background-color: white;
  margin-top: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="inBox">.inBox has margin-top</div>
</div></code>```

As recommended by others I would also probably just use padding-top on the parent to create all of the space but this trick exposes an interesting nuance of margin collapse.

Body:
Apply this code and you can see it. The margine-top of the internal box is applied to the outside. How can inBox not affect the box?

<!DOCTYPE html>

  <meta charset="utf-8">

Body:
So you actually can have margin-top on the child element. As mentioned by others, vertical margins can collapse. This is one of the least intuitive instances, where the margin-top of the child is apparently going right through the parent.

You can counter this by adding any amount of padding to the parent. I added 1px of padding-top and the margin suddenly appears to behave as originally expected:

.box {
  width: 400px;
  height: 400px;
  background-color: red;
  padding-top: 1px;
}

.inBox {
  width: 200px;
  height: 200px;
  background-color: white;
  margin-top: 100px;
}

<div class="box">
  <div class="inBox">.inBox has margin-top</div>
</div>

As recommended by others I would also probably just use padding-top on the parent to create all of the space but this trick exposes an interesting nuance of margin collapse.


问:
How To Set Ajax Url with Variable
i want to add some string to the url in ajax process, but fail every time i access the function.
when i submit the form it only access this url 'Master_data/' </p>

```<code>var jenis_submit = document.getElementById('jenis_submit');
var submit_url = '';
if (jenis_submit == '1') {

    submit_url = "func_save_instansi";
} else if (jenis_submit == '2') {

    submit_url = "func_update_instansi";
}

$.ajax({
    url: '<?php echo base_url();?>Master_data/' + submit_url,
    method: 'POST',
    data: dataKirim,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data) {
        // console.log(data);
        $('#notif').html(data);
    }
});
</code>```

答:
Just assign the php value to a js variable and concat both

```<code>var url = '<?php echo base_url();?>Master_data/';
</code>```

and then in ajax

```<code>url: url + submit_url,
</code>```

UPDATED:

I missed one other mistake in your code

```<code>var number = document.getElementById("number").value; //in your code `.value` is missing
</code>```

as mentioned in the above(M.Hemant)'s answer.

Title: How To Set Ajax Url with Variable

Body:
i want to add some string to the url in ajax process, but fail every time i access the function.
when i submit the form it only access this url 'Master_data/'

var jenis_submit = document.getElementById('jenis_submit');
var submit_url = '';
if (jenis_submit == '1') {

    submit_url = "func_save_instansi";
} else if (jenis_submit == '2') {

    submit_url = "func_update_instansi";
}

$.ajax({
    url: '<?php echo base_url();?>Master_data/' + submit_url,
    method: 'POST',
    data: dataKirim,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data) {
        // console.log(data);
        $('#notif').html(data);
    }
});

Body:
Just assign the php value to a js variable and concat both

var url = '<?php echo base_url();?>Master_data/';

and then in ajax

url: url + submit_url,

UPDATED:

I missed one other mistake in your code

var number = document.getElementById("number").value; //in your code `.value` is missing

as mentioned in the above(M.Hemant)'s answer.


问:
Selecting default item from Combobox C#
I have few items on my ComboBox items collection, and i'd like to select one item from this list and set it as default item - when app starts - this item is already on comboBox.

I'm trying something like that:

```<code>SelectPrint11.SelectedIndex=2;
</code>```

but error is:

```<code>System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex'
</code>```

Edit:

In mylist are 3 items, Printer1, Printer2, Printer3. All are added in ComboBox Properties -> Items -> Collection

答: This means that your selectedindex is out of the range of the array of items in the combobox.  The array of items in your combo box is zero-based, so if you have 2 items, it's item 0 and item 1.

Title: Selecting default item from Combobox C#

Body:
I have few items on my ComboBox items collection, and i'd like to select one item from this list and set it as default item - when app starts - this item is already on comboBox.

I'm trying something like that:

SelectPrint11.SelectedIndex=2;

but error is:

System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex'

Edit:

In mylist are 3 items, Printer1, Printer2, Printer3. All are added in ComboBox Properties -> Items -> Collection


答:
In order to scrape Newspaper Articles you can simply use goose library which is simple and elegant. This results you in cleaned article text and title too. For Date you can try using BeautifulSoup.</p>

```<code>from goose import Goose
from requests import get

response = get('http://www.nytimes.com/2015/05/19/health/study-finds-dense-breast-tissue-isnt-always-a-high-cancer-risk.html?src=me&ref=general')
extractor = Goose()
article = extractor.extract(raw_html=response.content)
text = article.cleaned_text
title = article.title
</code>```

Title: How to scrape newspaper articles from website using selenium and beautifulsoup in python?

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:
In order to scrape Newspaper Articles you can simply use goose library which is simple and elegant. This results you in cleaned article text and title too. For Date you can try using BeautifulSoup.

from goose import Goose
from requests import get

response = get('http://www.nytimes.com/2015/05/19/health/study-finds-dense-breast-tissue-isnt-always-a-high-cancer-risk.html?src=me&ref=general')
extractor = Goose()
article = extractor.extract(raw_html=response.content)
text = article.cleaned_text
title = article.title


问:
error "/clang:-1: linker command failed with exit code 1 (use -v to see invocation)" in Xcode
I've installed some pods in my Xcode project and run the pods init and pods update commands to create workspace file. I'm using Xcode 10.1 (because my code is in Swift 3 and no latest Xcode doesn't support that). I've tried searching internet a lot but every time I run the project, I'm getting this error -

ld: symbol(s) not found for architecture x86_64 clang: error: linker
command failed with exit code 1 (use -v to see invocation)

I've installed following libraries in my pod file -

I've tried to to change Bitcode to 'No', and Reflection Metadata Level to 'None' but it doesn't work. And yes, of course, I'm using the .xcworkspace file and not the .xcodeproj file. I did the pod update command too in terminal but that doesn't help either!

This is my podfile -

```<code># Uncomment the next line to define a global platform for your project
# platform :ios, '10.0'

# Pods for myproj
target 'myproj' do
  use_frameworks!
  pod 'Alamofire'
  pod 'AlamofireImage', '~> 3.1'
  pod 'AlamofireObjectMapper'
  pod 'Eureka'
  pod 'Firebase'
  pod 'Firebase/Core'
  pod 'Firebase/RemoteConfig'
  pod 'IQKeyboardManagerSwift', '5.0.0'
  pod 'SideMenuController'
  pod 'SnapKit', '~> 3.2.0'
  pod 'Fabric'
  pod 'Crashlytics'
  pod 'MGSwipeTableCell'
  pod 'SSZipArchive'
  pod 'RealmSwift'
  pod 'Realm'
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'DevSupport',
    'RCTText',
    'CxxBridge',
    'RCTNetwork',
    'RCTImage',
    'RCTAnimation',
    'RCTLinkingIOS',
#    'RCTWebSocket', # needed for debugging
    # Add any other subspecs you want to use in your project
  ]
  pod 'react-native-image-picker', :path => '../node_modules/react-native-image-picker'
  # Explicitly include Yoga if you are using RN >= 0.42.0
  pod "yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
  pod 'react-native-image-picker', :path => '../node_modules/react-native-image-picker'

 end
</code>```

答:
In case anyone is having similar problem, let me tell you that I was able to solve the problem by adding the following frameworks to Pods>React>General>Linked Frameworks and Libraries - </p>

```<code>DoubleConversion.framework
glog.framework
folly.framework
Foundation.framework
JavaScriptCore.framework
yoga.framework
</code>```

Body:
I've installed some pods in my Xcode project and run the pods init and pods update commands to create workspace file. I'm using Xcode 10.1 (because my code is in Swift 3 and no latest Xcode doesn't support that). I've tried searching internet a lot but every time I run the project, I'm getting this error -

ld: symbol(s) not found for architecture x86_64 clang: error: linker
command failed with exit code 1 (use -v to see invocation)

I've installed following libraries in my pod file -

I've tried to to change Bitcode to 'No', and Reflection Metadata Level to 'None' but it doesn't work. And yes, of course, I'm using the .xcworkspace file and not the .xcodeproj file. I did the pod update command too in terminal but that doesn't help either!

This is my podfile -

# Uncomment the next line to define a global platform for your project
# platform :ios, '10.0'

# Pods for myproj
target 'myproj' do
  use_frameworks!
  pod 'Alamofire'
  pod 'AlamofireImage', '~> 3.1'
  pod 'AlamofireObjectMapper'
  pod 'Eureka'
  pod 'Firebase'
  pod 'Firebase/Core'
  pod 'Firebase/RemoteConfig'
  pod 'IQKeyboardManagerSwift', '5.0.0'
  pod 'SideMenuController'
  pod 'SnapKit', '~> 3.2.0'
  pod 'Fabric'
  pod 'Crashlytics'
  pod 'MGSwipeTableCell'
  pod 'SSZipArchive'
  pod 'RealmSwift'
  pod 'Realm'
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'DevSupport',
    'RCTText',
    'CxxBridge',
    'RCTNetwork',
    'RCTImage',
    'RCTAnimation',
    'RCTLinkingIOS',
#    'RCTWebSocket', # needed for debugging
    # Add any other subspecs you want to use in your project
  ]
  pod 'react-native-image-picker', :path => '../node_modules/react-native-image-picker'
  # Explicitly include Yoga if you are using RN >= 0.42.0
  pod "yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
  pod 'react-native-image-picker', :path => '../node_modules/react-native-image-picker'

 end

Body:
In case anyone is having similar problem, let me tell you that I was able to solve the problem by adding the following frameworks to Pods>React>General>Linked Frameworks and Libraries -

DoubleConversion.framework
glog.framework
folly.framework
Foundation.framework
JavaScriptCore.framework
yoga.framework


答:
Because who wouldn't want to add destructuring as well ..... (Kudos to CertainPerformance)

const items = Array.from(
  document.querySelectorAll('.container > .item'),
  ({ dataset: { itemId: i } }) => i
)
  .join(',');
console.log(items);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div></code>```

Title: jQuery convert element ids into comma seperated string

Body:
Because who wouldn't want to add destructuring as well ..... (Kudos to CertainPerformance)

const items = Array.from(
  document.querySelectorAll('.container > .item'),
  ({ dataset: { itemId: i } }) => i
)
  .join(',');
console.log(items);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div>


问:
CSS inner id selectors
I've got below id selectors in a CSS file. Headerphoto and logo-box are inner id-selectors of header id. Do I really need to add those two as inner id-selectors? I can add them as just normal id selectors. What is the best way of doing this? What are the pros and cons?

Thank you!

```<code>/* Header styles */
#header {
    position: relative;
    height: 176px;
    text-align: left;
    margin: 0; padding: 0;
    background: #FFF;
}

#header #headerphoto {
    position: absolute;
    right: 15px ; top: 15px;
    width: 455px;
    height: 156px;
    background: #FFF url(headerphoto.jpg) no-repeat;
}

#header #logo-box {
    position: absolute;
    left: 15px ; top: 15px;
    width: 280px;
    height: 156px;
    background:#1c1e27;
}
</code>```

答: you don't have to add the #header selector, but i've heard the page rendering is faster the more precise the selector was declared. In my opinion it doesn't matter.</p>

Title: CSS inner id selectors

Body:
I've got below id selectors in a CSS file. Headerphoto and logo-box are inner id-selectors of header id. Do I really need to add those two as inner id-selectors? I can add them as just normal id selectors. What is the best way of doing this? What are the pros and cons?

Thank you!

/* Header styles */
#header {
    position: relative;
    height: 176px;
    text-align: left;
    margin: 0; padding: 0;
    background: #FFF;
}

#header #headerphoto {
    position: absolute;
    right: 15px ; top: 15px;
    width: 455px;
    height: 156px;
    background: #FFF url(headerphoto.jpg) no-repeat;
}

#header #logo-box {
    position: absolute;
    left: 15px ; top: 15px;
    width: 280px;
    height: 156px;
    background:#1c1e27;
}


问:
C# SaveAs to CSV Display Long Text as # Instead of Value
MS Excel turn text cell into ### when it is long, but it still have value when I click on it. But when the file is converted to CSV, the value is gone and only the ### is saved.

```<code>Excel.Application excel = new Excel.Application();
Excel.Workbook workBook = excel.Workbooks.Open(filePath);

workBook.WebOptions.Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
   workBook.SaveAs(
      "foo.csv",
      Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV
   );
workBook.Close(true);
excel.Quit();
</code>```

The expected output for the text cell should be a text, but it save as ### instead.

答:
You could try saving it as a csv file without making it a workbook?
this has a good example on how to do so.
https://www.mytecbits.com/microsoft/dot-net/write-data-into-csv-file-in-c</p>

Body:
MS Excel turn text cell into ### when it is long, but it still have value when I click on it. But when the file is converted to CSV, the value is gone and only the ### is saved.

Excel.Application excel = new Excel.Application();
Excel.Workbook workBook = excel.Workbooks.Open(filePath);

workBook.WebOptions.Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
   workBook.SaveAs(
      "foo.csv",
      Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV
   );
workBook.Close(true);
excel.Quit();

The expected output for the text cell should be a text, but it save as ### instead.


问:
Removing icon from BottomNavigationView
I want my menu items on the BottomNavigationBar to have text-only labels with no icon. Unfortunately, it looks like design_bottom_navigation_item.xml always has a 24x24dp space reserved for the icon, with no publicly-exposed way to set it to gone. And even after getting past that, the label layout is set to a layout_gravity of bottom|center_horizontal, and it doesn't look like there's a way to programatically set layout_gravity to centered.

What is the fastest, easiest way to achieve the goal of a text-only menu item on the bottom nav bar? I'm thinking I can do this by creating a custom version of the item layout, then subclassing BottomNavigationItemView, BottomNavigationMenuView, and BottomNavigationView to specify that custom layout... but that seems like an awful lot of work for one little change. Am I missing something simpler?

答:
Just use the code below. I tried hard to do this easy way but failed.Then I made an alternative. Just use transparent color instead of icon drawble

```<code><item
    android:icon="@android:color/transparent"
    android:id="@+id/navigation_id"
    android:title="title" />
</code>```

Title: Removing icon from BottomNavigationView

Body:
Just use the code below. I tried hard to do this easy way but failed.Then I made an alternative. Just use transparent color instead of icon drawble

<item
    android:icon="@android:color/transparent"
    android:id="@+id/navigation_id"
    android:title="title" />


问:
Why are my comments moving the page down?
I'm working on page that displays user posts.  I would like to keep all of the content from this page contained within the window so the viewer doesn't have to scroll down.

Right now the page contains posts, comments, and the replies to the comments.  The posts will stay on the left side of the page while comments and replies stay on the right side of the page.

So far everything is on the correct side of the page, and my content fits within the window until the post gets comments and replies.  When a post has comments an extra bit of space is placed underneath the post on the left side even though my comments are stored on the right side of the page.

I was wondering if someone could look at my code and explain why the extra space is added below the post when there are comments on the right side.

If you have any other questions I will be more than happy to answer.

My code

```<code><div class="homeBody">
        <?php
            getPost($conn);
        ?>
</div> ...
function getPost($conn) { ...

                        if (mysqli_num_rows($commentresult)==0) {
                            echo '';
                        }
                        else {
                            $commenterid = $commentrow['userid'];
                            $commentersql = "SELECT * FROM users WHERE userid = '$commenterid'";
                            $commenterresult = mysqli_query($conn, $commentersql);
                            while ($commenterrow = mysqli_fetch_assoc($commenterresult)) {

                                echo    '<div class="PostCommentSet"> <div class="PostComments">';

                                    if ($commenterrow['profileimg'] == 1) {
                                        $filename = "profilepics/profile".$commenterid."*";
                                        $fileinfo = glob($filename);
                                        $fileext = explode(".", $fileinfo[0]);
                                        $fileactualext = $fileext[1];
                                        echo "<div class='CommentProfilePicture'><img src='profilepics/profile".$commenterid.".".$fileactualext."?".mt_rand()."'></div>";
                                    }
                                    else {
                                        echo "<div class='CommentProfilePicture'><img src='profilepics/noUser.png'></div>";
                                    }

                                echo    "<div class='CommentUserName'>".$commenterrow['userName']."</div>";
                                echo    "<div class='CommenterComment'>".$commentrow['comment']."</div> </div>";
                            }

                            $currentcommentid = $commentrow['commentid'];
                            $replysql = "SELECT * FROM posts WHERE hostid = '$hostid' AND postid = '$postid' AND commentid = '$currentcommentid' AND replyid > 0";
                            $replyresult = mysqli_query($conn, $replysql);
                            while ($replyrow = mysqli_fetch_assoc($replyresult)) {
                                if (mysqli_num_rows($replyresult)==0) {
                                    echo '';
                                }
                                else {
                                    echo '
                                            <div class="PostReplies">
                                                <div class="ReplierReply">'.$replyrow['reply'].'</div>
                                            </div>
                                        </div>
                                    ';
                                }
                            }
                        }
                    }
                }
            }
        }
    }
</code>```

My Css

```<code>.homeBody {
        margin: 60px 0px 37px 0px;
        width: 100%;
        height: calc(100vh - 97px);
        background-color: #777;

    }
.PostBox {
        width: 65%;
        height: calc(100vh - 97px);
        background-color: #555;
        color: white;
        position: relative;
    }
    .PostImg {
        width: 60%;
        height: 70vh;
        object-fit: contain;
    }
    .PostCommentSet {
        position: absolute;
        right: 10px;
        top: 60px;
        width: 30%;
    }
    .PostComments {
        background-color: #555;
        padding: 10px;
        border-radius: 4px;
        color: white;
    }
    .PostReplies {
        background-color: #555;
        padding: 10px;
        color: white;
        right: 0px;
        border-radius: 4px;
    }

    /* Comments */

        .CommentUserName {
            position: relative;
            left: 40px;
            top: -25px;
            font-size: 20px;
            font-weight: 550;
        }
        .CommentProfilePicture {
            width: 30px;
            height: 30px;
            margin: 0px;
        }
        .CommentProfilePicture img {
            width: 30px;
            height: 30px;
            object-fit: cover;
            top: 1px;
            left: 1px;
            border-radius: 5px;
        }
        .CommenterComment {
            position: relative;
            left: 40px;
            top: -8px;
        }
        .ReplierReply {

        }
</code>```

答: You don’t have any width or height set for the actual comment and reply div tags</p>

Body:
I'm working on page that displays user posts.  I would like to keep all of the content from this page contained within the window so the viewer doesn't have to scroll down.

Right now the page contains posts, comments, and the replies to the comments.  The posts will stay on the left side of the page while comments and replies stay on the right side of the page.

So far everything is on the correct side of the page, and my content fits within the window until the post gets comments and replies.  When a post has comments an extra bit of space is placed underneath the post on the left side even though my comments are stored on the right side of the page.

I was wondering if someone could look at my code and explain why the extra space is added below the post when there are comments on the right side.

If you have any other questions I will be more than happy to answer.

My code

        <?php
            getPost($conn);
        ?>

 ...
function getPost($conn) { ...

                        if (mysqli_num_rows($commentresult)==0) {
                            echo '';
                        }
                        else {
                            $commenterid = $commentrow['userid'];
                            $commentersql = "SELECT * FROM users WHERE userid = '$commenterid'";
                            $commenterresult = mysqli_query($conn, $commentersql);
                            while ($commenterrow = mysqli_fetch_assoc($commenterresult)) {

                                echo    '

';

                                    if ($commenterrow['profileimg'] == 1) {
                                        $filename = "profilepics/profile".$commenterid."*";
                                        $fileinfo = glob($filename);
                                        $fileext = explode(".", $fileinfo[0]);
                                        $fileactualext = $fileext[1];
                                        echo "

";
                                    }
                                    else {
                                        echo "

";
                                    }

                                echo    "
".$commenterrow['userName']."
";
                                echo    "
".$commentrow['comment']."

";
                            }

                            $currentcommentid = $commentrow['commentid'];
                            $replysql = "SELECT * FROM posts WHERE hostid = '$hostid' AND postid = '$postid' AND commentid = '$currentcommentid' AND replyid > 0";
                            $replyresult = mysqli_query($conn, $replysql);
                            while ($replyrow = mysqli_fetch_assoc($replyresult)) {
                                if (mysqli_num_rows($replyresult)==0) {
                                    echo '';
                                }
                                else {
                                    echo '

'.$replyrow['reply'].'

                                    ';
                                }
                            }
                        }
                    }
                }
            }
        }
    }

My Css

.homeBody {
        margin: 60px 0px 37px 0px;
        width: 100%;
        height: calc(100vh - 97px);
        background-color: #777;

    }
.PostBox {
        width: 65%;
        height: calc(100vh - 97px);
        background-color: #555;
        color: white;
        position: relative;
    }
    .PostImg {
        width: 60%;
        height: 70vh;
        object-fit: contain;
    }
    .PostCommentSet {
        position: absolute;
        right: 10px;
        top: 60px;
        width: 30%;
    }
    .PostComments {
        background-color: #555;
        padding: 10px;
        border-radius: 4px;
        color: white;
    }
    .PostReplies {
        background-color: #555;
        padding: 10px;
        color: white;
        right: 0px;
        border-radius: 4px;
    }

    /* Comments */

        .CommentUserName {
            position: relative;
            left: 40px;
            top: -25px;
            font-size: 20px;
            font-weight: 550;
        }
        .CommentProfilePicture {
            width: 30px;
            height: 30px;
            margin: 0px;
        }
        .CommentProfilePicture img {
            width: 30px;
            height: 30px;
            object-fit: cover;
            top: 1px;
            left: 1px;
            border-radius: 5px;
        }
        .CommenterComment {
            position: relative;
            left: 40px;
            top: -8px;
        }
        .ReplierReply {

        }


问:
These lines should change all objects in the list into integers, but they're still showing up as strings
So I have a list, playerlocation, which I am using as coordinates. The coordinates are entered with an input() command, so they appear as strings rather than integers. I thought this block of code would solve it,

playerlocation =(input("Player location?"))
playerlocation = list(playerlocation.split(","))

for x in playerlocation:
try:
     x = int(x)
     coordsareintegers = True
     print(playerlocation)
except:
     coordsareintegers = False
```

but print(playerlocation) is returning something like ['1','1'], meaning they're still strings.

I've tried using an int() command wherever the coordinates are used, but that's really tedious.

答:
What you need is a while loop with try except to keep asking the user to input the right player location format, and it will quit the loop and print player location in case entries are valid integers comma separated:

```<code>while True:
    try:
        x, y = input("Player location: ").split(',')
        player_location = [int(x), int(y)]
        print('player location:', player_location)
        break
    except:
        print('error: you should enter an integers x,y for player location, try again!\n')
</code>```

example output:

```<code>Player location: blah..blah
error: you should enter an integers x,y for player location, try again!

Player location: 3,4
player location: [3, 4]
</code>```

Body:
So I have a list, playerlocation, which I am using as coordinates. The coordinates are entered with an input() command, so they appear as strings rather than integers. I thought this block of code would solve it,

playerlocation =(input("Player location?"))
playerlocation = list(playerlocation.split(","))

for x in playerlocation:
try:
     x = int(x)
     coordsareintegers = True
     print(playerlocation)
except:
     coordsareintegers = False

but print(playerlocation) is returning something like ['1','1'], meaning they're still strings.

I've tried using an int() command wherever the coordinates are used, but that's really tedious.

Body:
What you need is a while loop with try except to keep asking the user to input the right player location format, and it will quit the loop and print player location in case entries are valid integers comma separated:

while True:
    try:
        x, y = input("Player location: ").split(',')
        player_location = [int(x), int(y)]
        print('player location:', player_location)
        break
    except:
        print('error: you should enter an integers x,y for player location, try again!\n')

example output:

Player location: blah..blah
error: you should enter an integers x,y for player location, try again!

Player location: 3,4
player location: [3, 4]


问:
Interleaving components on an HTML page
I am a newbie in Angular.

I have a big external component(imported from some external libraries) that renders an image and navigation links and the header component.

I created a new component and want to add in the section where the above component is being rendered.

How do I control positioning of the above component?

答:
Add the HTML selector of new component in the component where you want to load.

New Component

```<code>@Component({
  selector: 'app-home', \\this is the html selector
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
</code>```

HTML

```<code><app-home></app-home>  //add this in the old component HTML page
</code>```

Title: Interleaving components on an HTML page

Body:
Add the HTML selector of new component in the component where you want to load.

New Component

@Component({
  selector: 'app-home', \\this is the html selector
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

HTML

<app-home></app-home>  //add this in the old component HTML page


问:
How can i disable a checkbox field in woocommerce?
I have added a checkbox field in woocommerce and I want to only view its result on the accounts screen. I have added the checkbox using an example like:

```<code>            'register-checkboxes' => array(
            'type'     => 'checkboxes',
            'label'    => __( 'Regions of Construction', 'woo' ),
            'options'  => array(
                'qld1' => __( 'QLD Zone Q1', 'woo' ),
                'qld2' => __( 'QLD Zone Q2', 'woo' ),
                'qld3' => __( 'QLD Zone Q3', 'woo' ),
            ),
            'hide_in_registration' => true,
            'required' => true,
        ),
</code>```

But when I add:

```<code>$field_args['custom_attributes'] = array( 'disabled' => 'disabled' );
</code>```

On the Account screen this works for disabling Text inputs and selects but not checkbox options.

I am using: https://rudrastyh.com/woocommerce/woocommerce_form_field.html as a guide but it seems you can't pass an array of Custom Attributes to each option of the checkboxes? What am I missing?

答:
woocommerce_form_field() function doesn't provide such ability at checkbox input type, see here:

```<code>case 'checkbox':
                $field = '<label class="checkbox ' . implode( ' ', $args['label_class'] ) . '" ' . implode( ' ', $custom_attributes ) . '>
                        <input type="' . esc_attr( $args['type'] ) . '" class="input-checkbox ' . esc_attr( implode( ' ', $args['input_class'] ) ) . '" name="' . esc_attr( $key ) . '" id="' . esc_attr( $args['id'] ) . '" value="1" ' . checked( $value, 1, false ) . ' /> ' . $args['label'] . $required . '</label>';
</code>```

You can take help of javascript to disabled the input field, either use wp_add_inline_script() or can add Javascript code normally on some .js files.

Disbled input field using jQuery

or Can rewrite woocommerce_form_field() function at your plugin files. may not work adding on child theme functional file, not sure on this.

Thanks

Body:
I have added a checkbox field in woocommerce and I want to only view its result on the accounts screen. I have added the checkbox using an example like:

            'register-checkboxes' => array(
            'type'     => 'checkboxes',
            'label'    => __( 'Regions of Construction', 'woo' ),
            'options'  => array(
                'qld1' => __( 'QLD Zone Q1', 'woo' ),
                'qld2' => __( 'QLD Zone Q2', 'woo' ),
                'qld3' => __( 'QLD Zone Q3', 'woo' ),
            ),
            'hide_in_registration' => true,
            'required' => true,
        ),

But when I add:

$field_args['custom_attributes'] = array( 'disabled' => 'disabled' );

On the Account screen this works for disabling Text inputs and selects but not checkbox options.

I am using: https://rudrastyh.com/woocommerce/woocommerce_form_field.html as a guide but it seems you can't pass an array of Custom Attributes to each option of the checkboxes? What am I missing?

Body:
woocommerce_form_field() function doesn't provide such ability at checkbox input type, see here:

case 'checkbox':
                $field = '<label class="checkbox ' . implode( ' ', $args['label_class'] ) . '" ' . implode( ' ', $custom_attributes ) . '>
                        <input type="' . esc_attr( $args['type'] ) . '" class="input-checkbox ' . esc_attr( implode( ' ', $args['input_class'] ) ) . '" name="' . esc_attr( $key ) . '" id="' . esc_attr( $args['id'] ) . '" value="1" ' . checked( $value, 1, false ) . ' /> ' . $args['label'] . $required . '</label>';

You can take help of javascript to disabled the input field, either use wp_add_inline_script() or can add Javascript code normally on some .js files.

Disbled input field using jQuery

or Can rewrite woocommerce_form_field() function at your plugin files. may not work adding on child theme functional file, not sure on this.

Thanks


问:
How do I put async error handling into a separate function?
I'd like to put the error handling showed in the below example into a single function:

```<code>import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../auth/auth.service';
import { tap, flatMap, concatMap } from 'rxjs/operators';
import { AlertController } from '@ionic/angular';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService, private alertCon: AlertController) { }

    errorCodeToMessage = {
        500: "Internal server error has occurred. Please contact support.",
        404: "This resource can not be found. Please contact support.",
        403: "Access denied. Are you logged in?"
    };

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if(req.url != this.auth.LOGIN_URL && req.url != this.auth.REGISTRATION_URL)
            return this.auth.getToken()
            .pipe(
                concatMap((token: string) => {
                        req = req.clone({
                            setHeaders: {
                                'authorization': token
                            }
                        });
                    // Also handle errors globally
                    return next.handle(req).pipe(
                        tap(x => x,
                            async (error) => {
                            const alert = await this.alertCon.create({
                                header: 'Error',
                                subHeader: null,
                                message: this.errorCodeToMessage[error.status],
                                buttons: ['OK']
                              });

                            await alert.present();
                        }
                        )
                    );
                }))
                ;
        else
            return next.handle(req).pipe(
                        tap(x => x, async (error) => {
                            console.log("the error is: ");
                            console.log(error);
                            const alert = await this.alertCon.create({
                                header: 'Error',
                                subHeader: null,
                                message: this.errorCodeToMessage[error.status],
                                buttons: ['OK']
                              });

                            await alert.present();
                        })
                    );
    }

}
</code>```

However, when I do that, the injected AlertController no longer seems to be available.

```<code>import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../auth/auth.service';
import { tap, flatMap, concatMap } from 'rxjs/operators';
import { AlertController } from '@ionic/angular';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService, private alertCon: AlertController) { }

    errorCodeToMessage = {
        500: "Internal server error has occurred. Please contact support.",
        404: "This resource can not be found. Please contact support.",
        403: "Access denied. Are you logged in?"
    };

    async handleError(error) {
        console.log(error);
        const alert = await this.alertCon.create({
            header: 'Error',
            subHeader: null,
            message: this.errorCodeToMessage[error.status],
            buttons: ['OK']
          });

        await alert.present();
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if(req.url != this.auth.LOGIN_URL && req.url != this.auth.REGISTRATION_URL)
            return this.auth.getToken()
            .pipe(
                concatMap((token: string) => {
                        req = req.clone({
                            setHeaders: {
                                'authorization': token
                            }
                        });
                    // Also handle errors globally
                    return next.handle(req).pipe(
                        tap(x => x, this.handleError)
                    );
                }))
                ;
        else
            return next.handle(req).pipe(
                        tap(x => x, this.handleError)
                    );
    }

}
</code>```

Runtime error:

```<code>    ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'create' of undefined
TypeError: Cannot read property 'create' of undefined
    at TapSubscriber.<anonymous> (api.interceptor.ts:23)
    at step (tslib.es6.js:97)
    at Object.next (tslib.es6.js:78)
    at tslib.es6.js:71
    at new ZoneAwarePromise (zone.js:910)
    at Module.__awaiter (tslib.es6.js:67)
    at TapSubscriber.push../src/app/api/api.interceptor.ts.ApiInterceptor.handleError [as _tapError] (api.interceptor.ts:21)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:55)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at XMLHttpRequest.onLoad (http.js:1640)
    at resolvePromise (zone.js:831)
    at new ZoneAwarePromise (zone.js:913)
    at Module.__awaiter (tslib.es6.js:67)
    at TapSubscriber.push../src/app/api/api.interceptor.ts.ApiInterceptor.handleError [as _tapError] (api.interceptor.ts:21)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:55)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at XMLHttpRequest.onLoad (http.js:1640)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
</code>```

I'm guessing it has something to do with being outside of the closure, but I may be wrong. Why is that happening and what can I do to get a single function to do the error handling?

答:
Following changes in the code.

immutable logic to update the request header. Use the same logic to
update the params too.

instead of tap operator use catchError operator.

```<code>intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (
      req.url !== this.auth.LOGIN_URL &&
      req.url !== this.auth.REGISTRATION_URL
    ) {
      return this.auth.getToken().pipe(
        concatMap((token: string) => {
          const updatedReq = req.clone({
            headers: req.headers.set('authorization', token)
          });
          // Also handle errors globally
          return next.handle(updatedReq).pipe(catchError(this.handleError));
        })
      );
    } else {
      return next.handle(req).pipe(catchError(this.handleError));
    }
  }

 handleError(err): Observable<any> {
    // error logs updation logics here.
    return throwError(err);
  }

</code>```

Body:
I'd like to put the error handling showed in the below example into a single function:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../auth/auth.service';
import { tap, flatMap, concatMap } from 'rxjs/operators';
import { AlertController } from '@ionic/angular';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService, private alertCon: AlertController) { }

    errorCodeToMessage = {
        500: "Internal server error has occurred. Please contact support.",
        404: "This resource can not be found. Please contact support.",
        403: "Access denied. Are you logged in?"
    };

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if(req.url != this.auth.LOGIN_URL && req.url != this.auth.REGISTRATION_URL)
            return this.auth.getToken()
            .pipe(
                concatMap((token: string) => {
                        req = req.clone({
                            setHeaders: {
                                'authorization': token
                            }
                        });
                    // Also handle errors globally
                    return next.handle(req).pipe(
                        tap(x => x,
                            async (error) => {
                            const alert = await this.alertCon.create({
                                header: 'Error',
                                subHeader: null,
                                message: this.errorCodeToMessage[error.status],
                                buttons: ['OK']
                              });

                            await alert.present();
                        }
                        )
                    );
                }))
                ;
        else
            return next.handle(req).pipe(
                        tap(x => x, async (error) => {
                            console.log("the error is: ");
                            console.log(error);
                            const alert = await this.alertCon.create({
                                header: 'Error',
                                subHeader: null,
                                message: this.errorCodeToMessage[error.status],
                                buttons: ['OK']
                              });

                            await alert.present();
                        })
                    );
    }

}

However, when I do that, the injected AlertController no longer seems to be available.

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../auth/auth.service';
import { tap, flatMap, concatMap } from 'rxjs/operators';
import { AlertController } from '@ionic/angular';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService, private alertCon: AlertController) { }

    errorCodeToMessage = {
        500: "Internal server error has occurred. Please contact support.",
        404: "This resource can not be found. Please contact support.",
        403: "Access denied. Are you logged in?"
    };

    async handleError(error) {
        console.log(error);
        const alert = await this.alertCon.create({
            header: 'Error',
            subHeader: null,
            message: this.errorCodeToMessage[error.status],
            buttons: ['OK']
          });

        await alert.present();
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if(req.url != this.auth.LOGIN_URL && req.url != this.auth.REGISTRATION_URL)
            return this.auth.getToken()
            .pipe(
                concatMap((token: string) => {
                        req = req.clone({
                            setHeaders: {
                                'authorization': token
                            }
                        });
                    // Also handle errors globally
                    return next.handle(req).pipe(
                        tap(x => x, this.handleError)
                    );
                }))
                ;
        else
            return next.handle(req).pipe(
                        tap(x => x, this.handleError)
                    );
    }

}

Runtime error:

    ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'create' of undefined
TypeError: Cannot read property 'create' of undefined
    at TapSubscriber.<anonymous> (api.interceptor.ts:23)
    at step (tslib.es6.js:97)
    at Object.next (tslib.es6.js:78)
    at tslib.es6.js:71
    at new ZoneAwarePromise (zone.js:910)
    at Module.__awaiter (tslib.es6.js:67)
    at TapSubscriber.push../src/app/api/api.interceptor.ts.ApiInterceptor.handleError [as _tapError] (api.interceptor.ts:21)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:55)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at XMLHttpRequest.onLoad (http.js:1640)
    at resolvePromise (zone.js:831)
    at new ZoneAwarePromise (zone.js:913)
    at Module.__awaiter (tslib.es6.js:67)
    at TapSubscriber.push../src/app/api/api.interceptor.ts.ApiInterceptor.handleError [as _tapError] (api.interceptor.ts:21)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:55)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at XMLHttpRequest.onLoad (http.js:1640)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)

I'm guessing it has something to do with being outside of the closure, but I may be wrong. Why is that happening and what can I do to get a single function to do the error handling?

Body:
Following changes in the code.

immutable logic to update the request header. Use the same logic to
update the params too.

instead of tap operator use catchError operator.

intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (
      req.url !== this.auth.LOGIN_URL &&
      req.url !== this.auth.REGISTRATION_URL
    ) {
      return this.auth.getToken().pipe(
        concatMap((token: string) => {
          const updatedReq = req.clone({
            headers: req.headers.set('authorization', token)
          });
          // Also handle errors globally
          return next.handle(updatedReq).pipe(catchError(this.handleError));
        })
      );
    } else {
      return next.handle(req).pipe(catchError(this.handleError));
    }
  }

 handleError(err): Observable<any> {
    // error logs updation logics here.
    return throwError(err);
  }