问:
How can I scrape "view" count of a comment with BeautifulSoup?
I'm trying to scrape customer complaint data on a website. I can get the headline and date but cannot figure out how to get the view count.

This is the code to get the headline:

```<code>headers = {'User-Agent':'Mozilla/5.0'}

complaints = []
time = []

for i in range(100):
  r = requests.get(f'https://www.sikayetvar.com/sikayetler?brand=bosch&page={i}')
  soup = bs(r.content, 'html.parser')
  complaints += soup.find_all('h5', {"class":"card-title"})
  time += soup.find_all('span', {"class":"info-icn time-tooltip"})
</code>```

The count of the complaints:

I try to get the number "479" with this code:

```<code>site = 'https://www.sikayetvar.com/sikayetler?brand=bosch'

r = requests.get(site)
soup = bs(r.content, 'html.parser')
time = soup.find_all('span', {"class":"count"})
</code>```

It returns:

```<code>print(time[0])
<span class="count">-</span>

print(time[0].text)
-
</code>```

I just get "-" instead of "479". Can anyone tell me what I'm doing wrong or a way to get that number?

Thanks in advance

答:
Those views are shown by javascript and there is always a high chance of finding an XHR request related to that in Network Tab.
I found this site which returns those views in a JSON. https://collector.sikayetvar.com/complaints/view-count?complaints=14793971%2C14792534%2C14791327%2C14789107%2C14787731%2C14787333%2C14787160%2C14784871%2C14784832%2C14784823%2C14784535%2C14783714%2C14762547%2C14783312%2C14783264%2C14782822

These complaints are the id of each complaint separated by a comma and they can be found in the source of https://www.sikayetvar.com/sikayetler?brand=bosch we just have to replace the comma with '%2C' and make a full string of them
m

```<code>import requests
import lxml
from bs4 import BeautifulSoup

headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.125'}

brand = 'bosch'

site = f'https://www.sikayetvar.com/sikayetler?brand={brand}'
req = requests.get(site, headers=headers)
soup = BeautifulSoup(req.content, 'lxml')
complaints = soup.find_all('span', {'class':'js-view-count'})
complaints = '%2C'.join(i['data-id'] for i in complaints)
print(complaints)

site = f'https://collector.sikayetvar.com/complaints/view-count?complaints={complaints}'
r = requests.get(site)
print(r.json())
</code>```

Output:-

```<code>[{'id': 14793971, 'viewCount': 43, 'uniqueViewCount': 29}, {'id': 14792534,'viewCount': 501, 'uniqueViewCount': 263}, {'id': 14791327, 'viewCount': 218,'uniqueViewCount': 134}, {'id': 14789107, 'viewCount': 492, 'uniqueViewCount': 286},{'id': 14787731, 'viewCount': 581, 'uniqueViewCount': 342}, {'id': 14787333, 'viewCount':506, 'uniqueViewCount': 287}, {'id': 14787160, 'viewCount': 428,'uniqueViewCount': 249}, {'id': 14784871, 'viewCount': 25, 'uniqueViewCount': 16},{'id': 14784832, 'viewCount': 29, 'uniqueViewCount': 15}, {'id': 14784823, 'viewCount':20, 'uniqueViewCount': 8}, {'id': 14784535, 'viewCount': 99, 'uniqueViewCount': 57}, {'id':14783714, 'viewCount': 510, 'uniqueViewCount': 280}, {'id': 14762547, 'viewCount':139, 'uniqueViewCount': 85}, {'id': 14783312, 'viewCount': 142,'uniqueViewCount': 78}, {'id': 14783264, 'viewCount': 190, 'uniqueViewCount': 114},{'id': 14782822, 'viewCount': 216, 'uniqueViewCount': 120}]
</code>```

The other way is to go in every complaint which will take a lot of time as well as the Website can block you if you keep scraping

Body:
I'm trying to scrape customer complaint data on a website. I can get the headline and date but cannot figure out how to get the view count.

This is the code to get the headline:

headers = {'User-Agent':'Mozilla/5.0'}

complaints = []
time = []

for i in range(100):
  r = requests.get(f'https://www.sikayetvar.com/sikayetler?brand=bosch&page={i}')
  soup = bs(r.content, 'html.parser')
  complaints += soup.find_all('h5', {"class":"card-title"})
  time += soup.find_all('span', {"class":"info-icn time-tooltip"})

The count of the complaints:

I try to get the number "479" with this code:

site = 'https://www.sikayetvar.com/sikayetler?brand=bosch'

r = requests.get(site)
soup = bs(r.content, 'html.parser')
time = soup.find_all('span', {"class":"count"})

It returns:

print(time[0])
-

print(time[0].text)
-

I just get "-" instead of "479". Can anyone tell me what I'm doing wrong or a way to get that number?

Thanks in advance

Body:
Those views are shown by javascript and there is always a high chance of finding an XHR request related to that in Network Tab.
I found this site which returns those views in a JSON. https://collector.sikayetvar.com/complaints/view-count?complaints=14793971%2C14792534%2C14791327%2C14789107%2C14787731%2C14787333%2C14787160%2C14784871%2C14784832%2C14784823%2C14784535%2C14783714%2C14762547%2C14783312%2C14783264%2C14782822

These complaints are the id of each complaint separated by a comma and they can be found in the source of https://www.sikayetvar.com/sikayetler?brand=bosch we just have to replace the comma with '%2C' and make a full string of them
m

import requests
import lxml
from bs4 import BeautifulSoup

headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.125'}

brand = 'bosch'

site = f'https://www.sikayetvar.com/sikayetler?brand={brand}'
req = requests.get(site, headers=headers)
soup = BeautifulSoup(req.content, 'lxml')
complaints = soup.find_all('span', {'class':'js-view-count'})
complaints = '%2C'.join(i['data-id'] for i in complaints)
print(complaints)

site = f'https://collector.sikayetvar.com/complaints/view-count?complaints={complaints}'
r = requests.get(site)
print(r.json())

Output:-

[{'id': 14793971, 'viewCount': 43, 'uniqueViewCount': 29}, {'id': 14792534,'viewCount': 501, 'uniqueViewCount': 263}, {'id': 14791327, 'viewCount': 218,'uniqueViewCount': 134}, {'id': 14789107, 'viewCount': 492, 'uniqueViewCount': 286},{'id': 14787731, 'viewCount': 581, 'uniqueViewCount': 342}, {'id': 14787333, 'viewCount':506, 'uniqueViewCount': 287}, {'id': 14787160, 'viewCount': 428,'uniqueViewCount': 249}, {'id': 14784871, 'viewCount': 25, 'uniqueViewCount': 16},{'id': 14784832, 'viewCount': 29, 'uniqueViewCount': 15}, {'id': 14784823, 'viewCount':20, 'uniqueViewCount': 8}, {'id': 14784535, 'viewCount': 99, 'uniqueViewCount': 57}, {'id':14783714, 'viewCount': 510, 'uniqueViewCount': 280}, {'id': 14762547, 'viewCount':139, 'uniqueViewCount': 85}, {'id': 14783312, 'viewCount': 142,'uniqueViewCount': 78}, {'id': 14783264, 'viewCount': 190, 'uniqueViewCount': 114},{'id': 14782822, 'viewCount': 216, 'uniqueViewCount': 120}]

The other way is to go in every complaint which will take a lot of time as well as the Website can block you if you keep scraping


来源: stackexchange

问:
split string and set values to class variable in java 8
```<code>String decodedChecksum="A01046085|T98494055e|1200|2020-05-31T06:12:46.365Z"
String[] splitArray = decodedChecksum.split("|");
/* here i want to set values to getter setter*/
{
sample.setAppNo(A01046085)
sample.setId(T98494055e)
 ..
}
</code>```

Please provide solution to iterate the array and set valuease to varibale

答:
It heavily depends on how your code is structured. If you're 100% sure of the structure of that string, it's as easy as:</p>

```<code>String decodedChecksum="A01046085|T98494055e|1200|2020-05-31T06:12:46.365Z"
String[] splitArray = decodedChecksum.split("\\|");

sample.setAppNo(splitArray[0]);
sample.setId(splitArray[1]);
...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
String decodedChecksum="A01046085|T98494055e|1200|2020-05-31T06:12:46.365Z"
String[] splitArray = decodedChecksum.split("|");
/* here i want to set values to getter setter*/
{
sample.setAppNo(A01046085)
sample.setId(T98494055e)
 ..
}

Please provide solution to iterate the array and set valuease to varibale

Body:
It heavily depends on how your code is structured. If you're 100% sure of the structure of that string, it's as easy as:

String decodedChecksum="A01046085|T98494055e|1200|2020-05-31T06:12:46.365Z"
String[] splitArray = decodedChecksum.split("\\|");

sample.setAppNo(splitArray[0]);
sample.setId(splitArray[1]);
...


问:
file_put_contents(/homepages/storage/framework/views/c8d540ced881ee3d14baa6e1259a7deab143b7fa.php): failed to open stream: No such file or directory
I have a Laravel 5 project that I copied from my friend with FTP to work on it in locally. I ran composer install to install the vendor.

The server is up, but when I enter localhost:8000, it shows me this error:

file_put_contents(/homepages/17/d595652778/htdocs/oneQ/storage/framework/views/c8d540ced881ee3d14baa6e1259a7deab143b7fa.php): failed to open stream: No such file or directory

答:
I had a similar issue and i managed to fix it by running:

```<code>composer install
</code>```

from within the project directory or the container if you a using Docker-based development tool such as ddev.

Body:
I had a similar issue and i managed to fix it by running:

composer install

from within the project directory or the container if you a using Docker-based development tool such as ddev.


问:
Trying to segment characters using opencv - Contour problem
My code is detecting another box when there is no letter!

```<code># Create sort_contours() function to grab the contour of each digit from left to right
def sort_contours(cnts,reverse = False):
    i = 0
    boundingBoxes = [cv2.boundingRect(c) for c in cnts]
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
                                        key=lambda b: b[1][i], reverse=reverse))
    return cnts

cont, _  = cv2.findContours(thre_mor, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# creat a copy version "test_roi" of plat_image to draw bounding box
test_roi = plate_image.copy()

# Initialize a list which will be used to append charater image
crop_characters = []

# define standard width and height of character
digit_w, digit_h = 40, 80 #40,80

for c in sort_contours(cont):
    (x, y, w, h) = cv2.boundingRect(c)
    ratio = h/w
    if 1<=ratio<=2.5: # Only select contour with defined ratio
        if h/plate_image.shape[0]>=0.4: # Select contour which has the height larger than 50% of the plate
            # Draw bounding box arroung digit number
            cv2.rectangle(test_roi, (x, y), (x + w, y + h), (0, 255,0), 2)

            # Sperate number and gibe prediction
            curr_num = thre_mor[y:y+h,x:x+w]
            curr_num = cv2.resize(curr_num, dsize=(digit_w, digit_h))
            _, curr_num = cv2.threshold(curr_num, 220, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
            crop_characters.append(curr_num)

print("Detect {} letters...".format(len(crop_characters)))
fig = plt.figure(figsize=(10,6))
plt.axis(False)
plt.imshow(test_roi)
</code>```

The image it is this:

With this binary image:

This is the result:

Do you see the last 5? The goal it is avoid this.

Why this is happening?

The way I procces the image it is:

```<code>gray = cv2.cvtColor(plate_image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(7,7),0)
binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel3 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
thre_mor = cv2.morphologyEx(binary, cv2.MORPH_DILATE, kernel3)
</code>```

Grayscale

Blur

Binarization

Segmentation

I think it's because of the contour, how could I remove the contour better?

答:
Using morphological reconstruction, you can easily remove elements that touch the edges from a binary image. This is similar to the imclearborder() function from Matlab / Octave.

```<code>import cv2
import numpy as np

img = cv2.imread('CpO0b.png')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)[1]
marker=thresh.copy()
marker[1:-1,1:-1]=0
kernel = np.ones((3,3),np.uint8)

while True:
    tmp=marker.copy()
    marker=cv2.dilate(marker, kernel)
    marker=cv2.min(thresh, marker)
    difference = cv2.subtract(marker, tmp)
    if cv2.countNonZero(difference) == 0:
        break
mask=cv2.bitwise_not(marker)
out=cv2.bitwise_and(thresh, mask)
cv2.imwrite('out.png', out)
cv2.imshow('result', out )
</code>```

Body:
My code is detecting another box when there is no letter!

# Create sort_contours() function to grab the contour of each digit from left to right
def sort_contours(cnts,reverse = False):
    i = 0
    boundingBoxes = [cv2.boundingRect(c) for c in cnts]
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
                                        key=lambda b: b[1][i], reverse=reverse))
    return cnts

cont, _  = cv2.findContours(thre_mor, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# creat a copy version "test_roi" of plat_image to draw bounding box
test_roi = plate_image.copy()

# Initialize a list which will be used to append charater image
crop_characters = []

# define standard width and height of character
digit_w, digit_h = 40, 80 #40,80

for c in sort_contours(cont):
    (x, y, w, h) = cv2.boundingRect(c)
    ratio = h/w
    if 1<=ratio<=2.5: # Only select contour with defined ratio
        if h/plate_image.shape[0]>=0.4: # Select contour which has the height larger than 50% of the plate
            # Draw bounding box arroung digit number
            cv2.rectangle(test_roi, (x, y), (x + w, y + h), (0, 255,0), 2)

            # Sperate number and gibe prediction
            curr_num = thre_mor[y:y+h,x:x+w]
            curr_num = cv2.resize(curr_num, dsize=(digit_w, digit_h))
            _, curr_num = cv2.threshold(curr_num, 220, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
            crop_characters.append(curr_num)

print("Detect {} letters...".format(len(crop_characters)))
fig = plt.figure(figsize=(10,6))
plt.axis(False)
plt.imshow(test_roi)

The image it is this:

With this binary image:

This is the result:

Do you see the last 5? The goal it is avoid this.

Why this is happening?

The way I procces the image it is:

gray = cv2.cvtColor(plate_image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(7,7),0)
binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel3 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
thre_mor = cv2.morphologyEx(binary, cv2.MORPH_DILATE, kernel3)

Grayscale

Blur

Binarization

Segmentation

I think it's because of the contour, how could I remove the contour better?

Body:
Using morphological reconstruction, you can easily remove elements that touch the edges from a binary image. This is similar to the imclearborder() function from Matlab / Octave.

import cv2
import numpy as np

img = cv2.imread('CpO0b.png')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)[1]
marker=thresh.copy()
marker[1:-1,1:-1]=0
kernel = np.ones((3,3),np.uint8)

while True:
    tmp=marker.copy()
    marker=cv2.dilate(marker, kernel)
    marker=cv2.min(thresh, marker)
    difference = cv2.subtract(marker, tmp)
    if cv2.countNonZero(difference) == 0:
        break
mask=cv2.bitwise_not(marker)
out=cv2.bitwise_and(thresh, mask)
cv2.imwrite('out.png', out)
cv2.imshow('result', out )


答:
You need to escape the | because it's a special symbol in regex.

```<code>String decodedChecksum="A01046085|T98494055e|1200|2020-05-31T06:12:46.365Z";
String[] splitArray = decodedChecksum.split("\\|");

sample.setAppNo(splitArray[0]); // splitArray[0] = A01046085
sample.setId(splitArray[1]);    // splitArray[0] = T98494055e
...
</code>```

Title: split string and set values to class variable in java 8

Body:
You need to escape the | because it's a special symbol in regex.

String decodedChecksum="A01046085|T98494055e|1200|2020-05-31T06:12:46.365Z";
String[] splitArray = decodedChecksum.split("\\|");

sample.setAppNo(splitArray[0]); // splitArray[0] = A01046085
sample.setId(splitArray[1]);    // splitArray[0] = T98494055e
...


问:
nginx on server cant connect to docker php-fpm
I am running nginx on the server and not within a docker container because of troubles with getting a working SSL. I have a docker container set up separately running my-sql and php-fpm. When I have all this running I get file not found and I can't work out why.

When I run sudo nginx -t it says everything is fine but I still get file not found after I run sudo systemctl restart nginx

My Nginx file:

```<code>server {
    listen 80;
    listen [::]:80;
    server_name njord-assets.com www.njord-assets.com;

client_max_body_size 108M;

    access_log /var/log/nginx/application.access.log;

    root /var/www/njord-assets.com/public;
    index index.php;

    if (!-e $request_filename) {
        rewrite ^.*$ /index.php last;
    }

    location ~ \.php$ {
        fastcgi_pass localhost:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PHP_VALUE "error_log=/var/log/nginx/application_php_errors.log";
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        include fastcgi_params;
    }

}

server {
    listen 443 ssl;
    server_name njord-assets.com www.njord-assets.com;

    ssl_certificate /etc/letsencrypt/live/njord-assets.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/njord-assets.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/njord-assets.com/chain.pem;

client_max_body_size 108M;

    access_log /var/log/nginx/application.access.log;

    root /var/www/njord-assets.com/public;
    index index.php;

    if (!-e $request_filename) {
        rewrite ^.*$ /index.php last;
    }

    location ~ \.php$ {
        fastcgi_pass localhost:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PHP_VALUE "error_log=/var/log/nginx/application_php_errors.log";
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        include fastcgi_params;
    }

}
</code>```

Docker-compose file:

```<code>###############################################################################
#                          Generated on dev.io                          #
###############################################################################
version: "3.1"
services:

    redis:
      restart: always
      image: redis:alpine
      container_name: my-asset-management-redis

    mysql:
      restart: always
      image: mysql:8.0
      container_name: my-asset-management-mysql
      working_dir: /application
      volumes:
        - .:/application
        - mysql-data:/var/lib/mysql
      environment:
        - MYSQL_ROOT_PASSWORD=root
        - MYSQL_DATABASE=app
        - MYSQL_USER=user
        - MYSQL_PASSWORD=pass

    php-fpm:
      restart: always
      build: docker/production/php-fpm
      container_name: my-asset-management-php-fpm
      working_dir: /application
      volumes:
        - .:/application
        - ./docker/production/php-fpm/php-ini-extras.ini:/etc/php/7.4/fpm/conf.d/99-extras.ini
      ports:
        - "9000:9000"
</code>```

I have checked and my Nginx error logs are returning

```<code>2020/05/31 10:50:50 [error] 932#932: *570 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 81.149.1.9, server: njord-assets.com, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "njord-assets.com"
</code>```

答:
The problem was that the nginx file needed to have the root be the root within the container and not outside so this:

```<code>root /var/www/njord-assets.com/public;
</code>```

should be:

```<code>root /application/public;
</code>```

Body:
I am running nginx on the server and not within a docker container because of troubles with getting a working SSL. I have a docker container set up separately running my-sql and php-fpm. When I have all this running I get file not found and I can't work out why.

When I run sudo nginx -t it says everything is fine but I still get file not found after I run sudo systemctl restart nginx

My Nginx file:

server {
    listen 80;
    listen [::]:80;
    server_name njord-assets.com www.njord-assets.com;

client_max_body_size 108M;

    access_log /var/log/nginx/application.access.log;

    root /var/www/njord-assets.com/public;
    index index.php;

    if (!-e $request_filename) {
        rewrite ^.*$ /index.php last;
    }

    location ~ \.php$ {
        fastcgi_pass localhost:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PHP_VALUE "error_log=/var/log/nginx/application_php_errors.log";
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        include fastcgi_params;
    }

}

server {
    listen 443 ssl;
    server_name njord-assets.com www.njord-assets.com;

    ssl_certificate /etc/letsencrypt/live/njord-assets.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/njord-assets.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/njord-assets.com/chain.pem;

client_max_body_size 108M;

    access_log /var/log/nginx/application.access.log;

    root /var/www/njord-assets.com/public;
    index index.php;

    if (!-e $request_filename) {
        rewrite ^.*$ /index.php last;
    }

    location ~ \.php$ {
        fastcgi_pass localhost:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PHP_VALUE "error_log=/var/log/nginx/application_php_errors.log";
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        include fastcgi_params;
    }

}

Docker-compose file:

###############################################################################
#                          Generated on dev.io                          #
###############################################################################
version: "3.1"
services:

    redis:
      restart: always
      image: redis:alpine
      container_name: my-asset-management-redis

    mysql:
      restart: always
      image: mysql:8.0
      container_name: my-asset-management-mysql
      working_dir: /application
      volumes:
        - .:/application
        - mysql-data:/var/lib/mysql
      environment:
        - MYSQL_ROOT_PASSWORD=root
        - MYSQL_DATABASE=app
        - MYSQL_USER=user
        - MYSQL_PASSWORD=pass

    php-fpm:
      restart: always
      build: docker/production/php-fpm
      container_name: my-asset-management-php-fpm
      working_dir: /application
      volumes:
        - .:/application
        - ./docker/production/php-fpm/php-ini-extras.ini:/etc/php/7.4/fpm/conf.d/99-extras.ini
      ports:
        - "9000:9000"

I have checked and my Nginx error logs are returning

2020/05/31 10:50:50 [error] 932#932: *570 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 81.149.1.9, server: njord-assets.com, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "njord-assets.com"

Body:
The problem was that the nginx file needed to have the root be the root within the container and not outside so this:

root /var/www/njord-assets.com/public;

should be:

root /application/public;


问:
Finding frequency of words in Python and frequencies in a descending order
I am trying to find the frequency of the words in a .txt file and enrich it by sorting the number of occurrences of each word.

So far, I completed %90 of the task. What is left is to sort the number of occurrences in descending order.

Here is my code:

```<code>def frequency_check(lines):
    print("Frequency of words in file")
    words = re.findall(r"\w+", lines)
    item_list = []

    for item in words:
        if item not in item_list:
            item_count = words.count(item)
            print("{} : {} times".format(item, item_count))
            item_list.append(item)

with open("original-3.txt", 'r') as file1:
    lines = file1.read().lower()
    frequency_check(lines)
</code>```

This is the .txt file on which I am finding the word frequency,

Here's the output I get:

```<code>Frequency of words in file
return : 2 times
all : 1 times
non : 1 times
overlapping : 1 times
matches : 3 times
of : 5 times
pattern : 3 times
in : 4 times
string : 2 times
as : 1 times
a : 3 times
list : 3 times
strings : 1 times
the : 6 times
is : 1 times
scanned : 1 times
left : 1 times
to : 1 times
right : 1 times
and : 1 times
are : 3 times
returned : 1 times
order : 1 times
found : 1 times
if : 2 times
one : 2 times
or : 1 times
more : 2 times
groups : 2 times
present : 1 times
this : 1 times
will : 1 times
be : 1 times
tuples : 1 times
has : 1 times
than : 1 times
group : 1 times
empty : 1 times
included : 1 times
result : 1 times
unless : 1 times
they : 1 times
touch : 1 times
beginning : 1 times
another : 1 times
match : 1 times

Process finished with exit code 0
</code>```

It would be a great challenge to sort these and output from highest number of occurrences to lowest.

PS:I thought about using dictionaries, however, dictionaries are immutable and I can't use sort method on them

Any ideas?

Thank you very much

答:
I still think you should have used a dictionary.
they are mutable.
However, for your exact output, you can use the "sorted" function, that works on lists as well as on a dictionary.

for your current list the way you put it:

```<code>lst = ["order : 1 times", "returned : 3 times"]
new_lst = sorted(lst, key = lambda x : x.split(" ")[2])
</code>```

notice that your integer value is in the 2nd index when u use split the way I did.

sorted gives you back a list.
if you want to use the current list you are using, you could also use the function "sort" all lists have:

```<code>lst.sort(key=lambda x: x.split(" ")[2])
</code>```

If you choose to switch this to a directory, notice in my example, the key is the word and the value is the counts, you'll be able to use this instead:

```<code>xs = {"order":3, "and":15}
sorted(xs.items(), key=lambda x: x[1])
</code>```

Body:
I am trying to find the frequency of the words in a .txt file and enrich it by sorting the number of occurrences of each word.

So far, I completed %90 of the task. What is left is to sort the number of occurrences in descending order.

Here is my code:

def frequency_check(lines):
    print("Frequency of words in file")
    words = re.findall(r"\w+", lines)
    item_list = []

    for item in words:
        if item not in item_list:
            item_count = words.count(item)
            print("{} : {} times".format(item, item_count))
            item_list.append(item)

with open("original-3.txt", 'r') as file1:
    lines = file1.read().lower()
    frequency_check(lines)

This is the .txt file on which I am finding the word frequency,

Here's the output I get:

Frequency of words in file
return : 2 times
all : 1 times
non : 1 times
overlapping : 1 times
matches : 3 times
of : 5 times
pattern : 3 times
in : 4 times
string : 2 times
as : 1 times
a : 3 times
list : 3 times
strings : 1 times
the : 6 times
is : 1 times
scanned : 1 times
left : 1 times
to : 1 times
right : 1 times
and : 1 times
are : 3 times
returned : 1 times
order : 1 times
found : 1 times
if : 2 times
one : 2 times
or : 1 times
more : 2 times
groups : 2 times
present : 1 times
this : 1 times
will : 1 times
be : 1 times
tuples : 1 times
has : 1 times
than : 1 times
group : 1 times
empty : 1 times
included : 1 times
result : 1 times
unless : 1 times
they : 1 times
touch : 1 times
beginning : 1 times
another : 1 times
match : 1 times

Process finished with exit code 0

It would be a great challenge to sort these and output from highest number of occurrences to lowest.

PS:I thought about using dictionaries, however, dictionaries are immutable and I can't use sort method on them

Any ideas?

Thank you very much

Body:
I still think you should have used a dictionary.
they are mutable.
However, for your exact output, you can use the "sorted" function, that works on lists as well as on a dictionary.

for your current list the way you put it:

lst = ["order : 1 times", "returned : 3 times"]
new_lst = sorted(lst, key = lambda x : x.split(" ")[2])

notice that your integer value is in the 2nd index when u use split the way I did.

sorted gives you back a list.
if you want to use the current list you are using, you could also use the function "sort" all lists have:

lst.sort(key=lambda x: x.split(" ")[2])

If you choose to switch this to a directory, notice in my example, the key is the word and the value is the counts, you'll be able to use this instead:

xs = {"order":3, "and":15}
sorted(xs.items(), key=lambda x: x[1])


问:
"Uncaught SecurityError: Failed to read the 'cookie' property from 'Document': Cookies are disabled inside 'data:' URLs." Flutter webview
```<code>WebView(initialUrl:Uri.dataFromString('<script type="text/javascript" src="https://cdn.embedly.com/widgets/platform.js"></script>'+<html>Some code</html>,mimeType: 'text/html').toString(), javascriptMode: JavascriptMode.unrestricted,),
</code>```

This CDN is throwing this error:

Uncaught SecurityError: Failed to read the 'cookie' property from 'Document': Cookies are disabled inside 'data:' URLs." Flutter webview

答:
You can try my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

In your case, you can use the initialData argument and set your custom HTML through the InAppWebViewInitialData.data attribute and set the InAppWebViewInitialData.baseUrl to http://localhost:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;
  String customHTML = "";

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
                initialData: InAppWebViewInitialData(data: """
<!doctype html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>InAppWebViewInitialDataTest</title>

        $customHTML

                    """, baseUrl: 'http://localhost'),
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                  debuggingEnabled: true,
              )
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {

            },
            onLoadStop:(InAppWebViewController controller, String url) {

            },
          ))
        ])),
      ),
    );
  }
}
```

Now you have access to document.cookie using JavaScript!

Another way is to put your HTML in an asset file (see the Load a file inside assets folder Section) and, then, you can use InAppLocalhostServer to start a local server to serve your HTML file with your script.

Body:
WebView(initialUrl:Uri.dataFromString(''+Some code,mimeType: 'text/html').toString(), javascriptMode: JavascriptMode.unrestricted,),

This CDN is throwing this error:

Uncaught SecurityError: Failed to read the 'cookie' property from 'Document': Cookies are disabled inside 'data:' URLs." Flutter webview

Body:
You can try my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

In your case, you can use the initialData argument and set your custom HTML through the InAppWebViewInitialData.data attribute and set the InAppWebViewInitialData.baseUrl to http://localhost:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;
  String customHTML = "";

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
                initialData: InAppWebViewInitialData(data: """
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>InAppWebViewInitialDataTest</title>
        <script type="text/javascript" src="https://cdn.embedly.com/widgets/platform.js"></script>
    </head>
    <body>
        $customHTML
    </body>
</html>
                    """, baseUrl: 'http://localhost'),
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                  debuggingEnabled: true,
              )
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {

            },
            onLoadStop:(InAppWebViewController controller, String url) {

            },
          ))
        ])),
      ),
    );
  }
}

Now you have access to document.cookie using JavaScript!

Another way is to put your HTML in an asset file (see the Load a file inside assets folder Section) and, then, you can use InAppLocalhostServer to start a local server to serve your HTML file with your script.


问:
How to generate an MD5 checksum for a file in Android?
In my app I have a requirement to generate an MD5 checksum for a file. Could you please tell me if there is any way in which this can be achieved?

Thank you.

答:
Kotlin version:</p>

```<code>

fun File.getMD5Hash(path: String): ByteArray {
    val md = MessageDigest.getInstance("MD5")
    val stream: InputStream
    stream = FileInputStream(this)

    val buffer = ByteArray(8192)
    var read: Int
    while (stream.read(buffer).also { read = it } > 0) {
        md.update(buffer, 0, read)
    }
    stream.close()
    return md.digest()
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Kotlin version:

fun File.getMD5Hash(path: String): ByteArray {
    val md = MessageDigest.getInstance("MD5")
    val stream: InputStream
    stream = FileInputStream(this)

    val buffer = ByteArray(8192)
    var read: Int
    while (stream.read(buffer).also { read = it } > 0) {
        md.update(buffer, 0, read)
    }
    stream.close()
    return md.digest()
}


问:
How to register the following datatype to allow serialization?
I am using QJson to serialize a QObject-derived class. I am able to serialize the class itself without any problems, but when it comes to one of its members, I am having a bit of trouble.

The class is named CProject and it contains a property files which is defined as:

```<code>QList<CProjectFile> files;
</code>```

When serializing an instance of CProject, I get a message in the console:

QMetaProperty::read: Unable to handle unregistered datatype 'QList<CProjectFile>' for property 'CProject::files'

I read somewhere that I have to register the datatype, so I added the following after the declaration of CProject:

```<code>Q_DECLARE_METATYPE(QList<CProjectFile>)
</code>```

...and when that did nothing, I added:

```<code>qRegisterMetaType< QList<CProjectFile> >();
</code>```

Nothing is working. What am I doing wrong?

答:
I don't know how QJson works but perhaps it requires stream operators. Try as below after declaration of CProjectFile class

```<code>class CProjectFile
{
   ...
};

    Q_DECLARE_METATYPE(CProjectFile)

    qRegisterMetaType<CProjectFile>("CProjectFile");//Do this if you need signal/slots

    qRegisterMetaTypeStreamOperators<QList<CProjectFile> >("CProjectFileList");
</code>```

See also QT Doc for stream operators

Body:
I am using QJson to serialize a QObject-derived class. I am able to serialize the class itself without any problems, but when it comes to one of its members, I am having a bit of trouble.

The class is named CProject and it contains a property files which is defined as:

QList<CProjectFile> files;

When serializing an instance of CProject, I get a message in the console:

QMetaProperty::read: Unable to handle unregistered datatype 'QList<CProjectFile>' for property 'CProject::files'

I read somewhere that I have to register the datatype, so I added the following after the declaration of CProject:

Q_DECLARE_METATYPE(QList<CProjectFile>)

...and when that did nothing, I added:

qRegisterMetaType< QList<CProjectFile> >();

Nothing is working. What am I doing wrong?

Body:
I don't know how QJson works but perhaps it requires stream operators. Try as below after declaration of CProjectFile class

class CProjectFile
{
   ...
};

    Q_DECLARE_METATYPE(CProjectFile)

    qRegisterMetaType<CProjectFile>("CProjectFile");//Do this if you need signal/slots

    qRegisterMetaTypeStreamOperators<QList<CProjectFile> >("CProjectFileList");

See also QT Doc for stream operators


问:
Minimum number of steps to convert one integer to another
Recently i came across a problem, given 2 integers A and B, we need to convert A to B in minimum number of steps.
We can perform following operations on A:

If A is odd, decrease by 1

If A is even, increase by 1

Multiply A(even or odd) by 2

if A is even, divide by 2

again, we have to find the minimum number of steps needed to convert A to B.

The constraints are 0 < A, B < 10^18

My approach:
I tried to solve the problem using Breadth First Search, adding all the possible reachable numbers from a step into a queue, but it fails on higher constraints i.e. time outs.

Can anyone suggest a faster alternative?

EDIT: A is not necessarily less than B

答:
The list of available operations is symmetric: 2 sets of operations, each the opposite of the other:

the last bit can be flipped

the number can be shifted left one position or right one position if the low bit is 0.

Hence it takes the same number of operations to go from A to B or from B to A.

Going from A to B takes at most the number of operations to go from A to 0 plus the number of operations to go from B to 0. These operations strictly decrease the values of A and B. If along the way an intermediary value can be reached from both A and B, there is no need to go all the way to 0.

Here is a simple function that performs the individual steps on A and B and stops as soon as this common number is found:

def num_ops(a, b):
    # compute the number of ops to transform a into b
    # by symmetry, the same number of ops is needed to transform b into a
    count = 0
    while a != b:
        if a > b:
            if (a & 1) != 0:
                a -= 1
            else:
                a >>= 1
        else:
            if (b & 1) != 0:
                b -= 1
            else:
                b >>= 1
        count += 1
    return count
```


问:
In Kops v 1.16, Getting Status NeedsUpdate and Ready 0 in "kops rolling-update cluster" in aws spot instance group though cluster is running good
I am getting Status NeedsUpdate  and Ready  0 in response of command kops rolling-update cluster in aws  spot instance group though all are running fine. I have run kops rolling-update cluster --yes  for several times and got successfully completed rolling update. But still, Getting NeedsUpdate status. How can I solve this issue?

```<code>kops rolling-update cluster

NAME                    STATUS          NEEDUPDATE      READY   MIN     MAX     NODES
master-ap-south-1       Ready           0               1       1       1       1
nodes                   Ready           0               0       0       5       0
nodes-spot              NeedsUpdate     2               0       2       7       2
</code>```

答:
From kops issues tab I see there is some issue with sport instance.

According to this

This issue is fixed in 1.18 and should be testable with Kops 1.18.0-alpha.2.

Body:
I am getting Status NeedsUpdate  and Ready  0 in response of command kops rolling-update cluster in aws  spot instance group though all are running fine. I have run kops rolling-update cluster --yes  for several times and got successfully completed rolling update. But still, Getting NeedsUpdate status. How can I solve this issue?

kops rolling-update cluster

NAME                    STATUS          NEEDUPDATE      READY   MIN     MAX     NODES
master-ap-south-1       Ready           0               1       1       1       1
nodes                   Ready           0               0       0       5       0
nodes-spot              NeedsUpdate     2               0       2       7       2


问:
ResourceNotFoundException for existing DynamoDB table
I've already read this question on the topic, but it doesn't help (see below).

I have a DDB Table my_table in eu-west-1, which I can (successfully) scan from my EC2 (same region, with AmazonDynamoDBFullAccess attached to its IAM) instance with AWS CLI:

```<code>aws dynamodb scan --table-name my_table --region eu-west-1
</code>```

This is the Java model that I've created:

```<code>@DynamoDBTable(tableName="my_table")
public class TableModel {
  @DynamoDBHashKey(attributeName = "partition_key")
  private final Long partitionKey;
  // ...
}
</code>```

And this is how I query it (code executed from same EC2):

```<code>public class DDBQuery {
    private DynamoDBMapper dynamoDBMapper;
    public DDBQuery() {
        dynamoDBMapper = new DynamoDBMapper(AmazonDynamoDBClientBuilder.standard()
                .withRegion(Regions.EU_WEST_1).build());
    }
    public void scan() {
        final List<DRTFacet> result = dynamoDBMapper.scan(TableModel.class, new DynamoDBScanExpression()); // Exception!
    }
}
</code>```

However, I get the title exception.
Note: vars have been renaming for sake of simplicity and confidentiality.

答:
it's either you don't have a Table with that name or it is in CREATING status . This info from awsdocs . But I think , you missed to add attributes DynamoDbcScannExpression. You might need to add some attributes like :

DynamoDBScanExpression dynamoDBScanExpression = new DynamoDBScanExpression()
            .withFilterExpression("#timestamp < :from")
            .withExpressionAttributeNames(attributeNames)
            .withExpressionAttributeValues(attributeValues);

```<code>List<Login> logins = dynamoDBMapper.scan(Login.class, dynamoDBScanExpression);

return logins;
</code>```

Body:
I've already read this question on the topic, but it doesn't help (see below).

I have a DDB Table my_table in eu-west-1, which I can (successfully) scan from my EC2 (same region, with AmazonDynamoDBFullAccess attached to its IAM) instance with AWS CLI:

aws dynamodb scan --table-name my_table --region eu-west-1

This is the Java model that I've created:

@DynamoDBTable(tableName="my_table")
public class TableModel {
  @DynamoDBHashKey(attributeName = "partition_key")
  private final Long partitionKey;
  // ...
}

And this is how I query it (code executed from same EC2):

public class DDBQuery {
    private DynamoDBMapper dynamoDBMapper;
    public DDBQuery() {
        dynamoDBMapper = new DynamoDBMapper(AmazonDynamoDBClientBuilder.standard()
                .withRegion(Regions.EU_WEST_1).build());
    }
    public void scan() {
        final List<DRTFacet> result = dynamoDBMapper.scan(TableModel.class, new DynamoDBScanExpression()); // Exception!
    }
}

However, I get the title exception.
Note: vars have been renaming for sake of simplicity and confidentiality.

Body:
it's either you don't have a Table with that name or it is in CREATING status . This info from awsdocs . But I think , you missed to add attributes DynamoDbcScannExpression. You might need to add some attributes like :

DynamoDBScanExpression dynamoDBScanExpression = new DynamoDBScanExpression()
            .withFilterExpression("#timestamp < :from")
            .withExpressionAttributeNames(attributeNames)
            .withExpressionAttributeValues(attributeValues);

List<Login> logins = dynamoDBMapper.scan(Login.class, dynamoDBScanExpression);

return logins;


问:
How to build OneHot Decoder in python
I have encoded my images(masks) with dimensions (img_width x img_height x 1) with OneHotEncoder in this way:

```<code>import numpy as np

def OneHotEncoding(im,n_classes):
  one_hot = np.zeros((im.shape[0], im.shape[1], n_classes),dtype=np.uint8)
  for i, unique_value in enumerate(np.unique(im)):
    one_hot[:, :, i][im == unique_value] = 1
  return one_hot
</code>```

After doing some data manipulation with deep learning, softmax activation function will result in probabilities instead of 0 and 1 values, so in my Decoder I wanted to implement the following approach:

Threshold the output to obtain 0 or 1 only.

Multiply each channel with weight equal to the channel index.

take the max between labels along channels axis.

```<code>import numpy as np

arr = np.array([
    [[0.1,0.2,0,5],[0.2,0.4,0.7],[0.3,0.5,0.8]],
    [[0.3,0.6,0  ],[0.4,0.9,0.1],[0  ,0  ,0.2]],
    [[0.7,0.1,0.1],[0,6,0.1,0.1],[0.6,0.6,0.3]],
    [[0.6,0.2,0.3],[0.4,0.5,0.3],[0.1,0.2,0.7]]
])

# print(arr.dtype,arr.shape)

def oneHotDecoder(img):
    # Thresholding
    img[img<0.5]=0
    img[img>=0.5]=1
    # weigts of the labels
    img = [i*img[:,:,i] for i in range(img.shape[2])]
    # take the max label
    img = np.amax(img,axis=2)
    print(img.shape)
    return img

arr2 = oneHotDecoder(arr)
print(arr2)

</code>```

My questions is:

How to git rid of the error:
  line 15, in oneHotDecoder
  img[img<0.5]=0 TypeError: '<' not supported between instances of 'list' and 'float'

Is there any other issues in my implementaion that you suggest to improve?

Thanks in advance.

Title: How to build OneHot Decoder in python

Body:
I have encoded my images(masks) with dimensions (img_width x img_height x 1) with OneHotEncoder in this way:

import numpy as np

def OneHotEncoding(im,n_classes):
  one_hot = np.zeros((im.shape[0], im.shape[1], n_classes),dtype=np.uint8)
  for i, unique_value in enumerate(np.unique(im)):
    one_hot[:, :, i][im == unique_value] = 1
  return one_hot

After doing some data manipulation with deep learning, softmax activation function will result in probabilities instead of 0 and 1 values, so in my Decoder I wanted to implement the following approach:

Threshold the output to obtain 0 or 1 only.

Multiply each channel with weight equal to the channel index.

take the max between labels along channels axis.

import numpy as np

arr = np.array([
    [[0.1,0.2,0,5],[0.2,0.4,0.7],[0.3,0.5,0.8]],
    [[0.3,0.6,0  ],[0.4,0.9,0.1],[0  ,0  ,0.2]],
    [[0.7,0.1,0.1],[0,6,0.1,0.1],[0.6,0.6,0.3]],
    [[0.6,0.2,0.3],[0.4,0.5,0.3],[0.1,0.2,0.7]]
])

# print(arr.dtype,arr.shape)

def oneHotDecoder(img):
    # Thresholding
    img[img<0.5]=0
    img[img>=0.5]=1
    # weigts of the labels
    img = [i*img[:,:,i] for i in range(img.shape[2])]
    # take the max label
    img = np.amax(img,axis=2)
    print(img.shape)
    return img

arr2 = oneHotDecoder(arr)
print(arr2)

My questions is:

How to git rid of the error:
  line 15, in oneHotDecoder
  img[img<0.5]=0 TypeError: '<' not supported between instances of 'list' and 'float'

Is there any other issues in my implementaion that you suggest to improve?

Thanks in advance.

Body:
You have typos with commas and dots with some of your items (e.g. your first list should be [0.1, 0.2, 0.5] instead of [0.1, 0.2, 0, 5]).

The fixed list is:

l = [
      [[0.1,0.2,0.5],[0.2,0.4,0.7],[0.3,0.5,0.8]],
      [[0.3,0.6,0  ],[0.4,0.9,0.1],[0  ,0  ,0.2]],
      [[0.7,0.1,0.1],[0.6,0.1,0.1],[0.6,0.6,0.3]],
      [[0.6,0.2,0.3],[0.4,0.5,0.3],[0.1,0.2,0.7]]
]

Then you could do:

np.array(l)  # np.dstack(l) would work as well

Which would yield:

array([[[0.1, 0.2, 0.5],
        [0.2, 0.4, 0.7],
        [0.3, 0.5, 0.8]],
       [[0.3, 0.6, 0. ],
        [0.4, 0.9, 0.1],
        [0. , 0. , 0.2]],
       [[0.7, 0.1, 0.1],
        [0.6, 0.1, 0.1],
        [0.6, 0.6, 0.3]],
       [[0.6, 0.2, 0.3],
        [0.4, 0.5, 0.3],
        [0.1, 0.2, 0.7]]])


问:
@Vue/test-utils shallowMount outputs "[Vue warn]: Unknown custom element" for vuetify components
My unit test in Vue outputs the following warning not just for <v-col> but for every single vuetify component:

[Vue warn]: Unknown custom element: < v-col> - did you register the
  component correctly? For recursive components, make sure to provide
  the "name" option.

I created a localVue and added Vuetify, but that doesn't seem to work. This is my test case:

```<code>import { shallowMount, createLocalVue } from '@vue/test-utils'
import expect from 'expect'
import ProjetoShow from '../../views/Projeto/ProjetoShow.vue'
import Vuetify from 'vuetify'

describe('ProjetoShow component', () => {
    let wrapper
    let localVue
    beforeEach(() => {
        localVue = createLocalVue()
        localVue.use(Vuetify)
    })

    it('renders correctly', ()=> {
        let vuetify = new Vuetify()
        wrapper = shallowMount(ProjetoShow, {localVue, vuetify})
        expect(wrapper.find('h2').text()).toContain('PROJETO')
    })

})
</code>```

my packages versions in package.json

```<code>"devDependencies": {
    "@vue/test-utils": "^1.0.0-beta.31",
    "axios": "^0.19.0",
    "cross-env": "^5.1",
    "expect": "^24.9.0",
    "jsdom": "^15.1.1",
    "jsdom-global": "^3.0.2",
    "laravel-mix": "^4.0.7",
    "lodash": "^4.17.13",
    "mocha": "^6.2.0",
    "mochapack": "^1.1.5",
    "resolve-url-loader": "^2.3.1",
    "sass": "^1.15.2",
    "sass-loader": "^7.1.0",
    "vue": "^2.5.17",
    "vue-template-compiler": "^2.6.10"
},
"dependencies": {
    "vue-router": "^3.1.3",
    "vuetify": "^2.2.15",
    "vuex": "^3.1.1"
},
</code>```

答:
I found two different solutions:

One, register vuetify in test file (of moment i did not found a way to declare globally)

```<code>import Vue from 'vue'
import Vuetify from 'vuetify'
Vue.use(Vuetify)
</code>```

Two, add stubs to wrapper with specific vuetify components

```<code>wrapper = shallowMount(ProjetoShow, {stubs: ['v-col']})
</code>```

Edit, i found the solution for declare globally, is necessary create a  file setup.js in tests folder as the doc says and add the path in test configuration file, in case of jest in jest.config.js adding setupFiles: ['./tests/setup.js']

Body:
My unit test in Vue outputs the following warning not just for <v-col> but for every single vuetify component:

[Vue warn]: Unknown custom element: < v-col> - did you register the
  component correctly? For recursive components, make sure to provide
  the "name" option.

I created a localVue and added Vuetify, but that doesn't seem to work. This is my test case:

import { shallowMount, createLocalVue } from '@vue/test-utils'
import expect from 'expect'
import ProjetoShow from '../../views/Projeto/ProjetoShow.vue'
import Vuetify from 'vuetify'

describe('ProjetoShow component', () => {
    let wrapper
    let localVue
    beforeEach(() => {
        localVue = createLocalVue()
        localVue.use(Vuetify)
    })

    it('renders correctly', ()=> {
        let vuetify = new Vuetify()
        wrapper = shallowMount(ProjetoShow, {localVue, vuetify})
        expect(wrapper.find('h2').text()).toContain('PROJETO')
    })

})

my packages versions in package.json

"devDependencies": {
    "@vue/test-utils": "^1.0.0-beta.31",
    "axios": "^0.19.0",
    "cross-env": "^5.1",
    "expect": "^24.9.0",
    "jsdom": "^15.1.1",
    "jsdom-global": "^3.0.2",
    "laravel-mix": "^4.0.7",
    "lodash": "^4.17.13",
    "mocha": "^6.2.0",
    "mochapack": "^1.1.5",
    "resolve-url-loader": "^2.3.1",
    "sass": "^1.15.2",
    "sass-loader": "^7.1.0",
    "vue": "^2.5.17",
    "vue-template-compiler": "^2.6.10"
},
"dependencies": {
    "vue-router": "^3.1.3",
    "vuetify": "^2.2.15",
    "vuex": "^3.1.1"
},

Body:
I found two different solutions:

One, register vuetify in test file (of moment i did not found a way to declare globally)

import Vue from 'vue'
import Vuetify from 'vuetify'
Vue.use(Vuetify)

Two, add stubs to wrapper with specific vuetify components

wrapper = shallowMount(ProjetoShow, {stubs: ['v-col']})

Edit, i found the solution for declare globally, is necessary create a  file setup.js in tests folder as the doc says and add the path in test configuration file, in case of jest in jest.config.js adding setupFiles: ['./tests/setup.js']


问:
Google sheets numbered list
I'm looking for a way (formula) to implement google docs functionality called numbered list in google sheets

Example:

I want:

答:
FORMULA TO INCREMENT A1:

```<code>=left(A1,len(A1)-FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1)))))&"."&(RIGHT(A1,FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1))))-1)+1)
</code>```

EXPLANATION:

```<code>=ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1)))
</code>```

Return the reverse of A1. e.g. if A1 is 2.1.32, the reverse will be 23.1.2

```<code>=FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1))))
</code>```

Find the number of characters to the last "." of the string in A1

```<code>=RIGHT(A1,FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1))))-1)+1
</code>```

Retrieves the rightmost integer in A1 and increments it by 1 (i.e. if A1 is "2.1.32" this formula returns 33)

```<code>=left(A1,len(A1)-FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1)))))&"."&(RIGHT(A1,FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1))))-1)+1)
</code>```

Takes the left part of A1, excluding the last integer, and concatenates the incremented rightmost integer

GOOGLE SHEET THAT IMPLEMENTS THIS:
https://docs.google.com/spreadsheets/d/1QSAhyzJxdcq47VxpUb-x-YMHqw8yzeZh3ZzRgGCEUIM/edit?usp=sharing

Title: Google sheets numbered list

Body:
FORMULA TO INCREMENT A1:

=left(A1,len(A1)-FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1)))))&"."&(RIGHT(A1,FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1))))-1)+1)

EXPLANATION:

=ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1)))

Return the reverse of A1. e.g. if A1 is 2.1.32, the reverse will be 23.1.2

=FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1))))

Find the number of characters to the last "." of the string in A1

=RIGHT(A1,FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1))))-1)+1

Retrieves the rightmost integer in A1 and increments it by 1 (i.e. if A1 is "2.1.32" this formula returns 33)

=left(A1,len(A1)-FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1)))))&"."&(RIGHT(A1,FIND(".",ArrayFormula(concatenate(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1))))-1)+1)

Takes the left part of A1, excluding the last integer, and concatenates the incremented rightmost integer

GOOGLE SHEET THAT IMPLEMENTS THIS:
https://docs.google.com/spreadsheets/d/1QSAhyzJxdcq47VxpUb-x-YMHqw8yzeZh3ZzRgGCEUIM/edit?usp=sharing


问:
How do I break a looping menu on Python
I have a little problem on making ecounter for fast food, the problems is at continuing order.
I don't know how to use True and False in python..
I choose three food as a beginner. It's end up failing..
So I tried to use True by copying other people code.
at first the code was success, but when i changed a little thing in code, it went wrong and I don't know how to fix it.

so far this is my code:

```<code>hcount = 0
scount = 0
fcount = 0
y = True
n = False
cstm= input("Please enter your name: ")
print("                                       ")
print("                                       ")
print("Hi MR/MS " + cstm)
print("WELCOME TO MACDUNNO ECOUNTER")

print("CHOOSE YOUR FOOD")

while True:

    print("  ")
    print('MENU MAC DUNNO')
    print("1. HAMBURGER = $1.50")
    print("2. SODA      = $1.15")
    print("3. FRIES   = $1.25")

    choice = int(input('ENTER NUMBER 1-3: '))

    if choice == 1:
        amount = int(input("ENTER THE AMOUNT: "))
        hcount += amount
    elif choice == 2:
        amount = int(input("ENTER THE AMOUNT: "))
        scount += amount
    elif choice == 3:
        amount = int(input("ENTER THE AMOUNT: "))
        fcount += amount

    countinue = input("ARE YOU STILL WANT TO ORDER? (y/n)")
    if countinue == n:
        sub = (hcount * 1.50) + (scount * 1.15) + (fcount * 1.25)
        tax = sub * 0.09
        total = sub + tax
        print("                                           ")
        print("                                           ")
        print("************")
        print("PAYMENT")
        print("************")
        print('TOTAL HAMBURGER: {0}'.format(hcount))
        print('TOTAL SODA: {0}'.format(scount))
        print('TOTAL FRIES: {0}'.format(fcount))
        print(" ")
        print('SUBTOTAL: {:0.2f}'.format(sub))
        print('TAX : {:0.2f}'.format(tax))
        print("   ")
        print("__________________________________")
        print('TOTAL: {:0.2f}'.format(total))
        print("   ")
        pay =int(input("INSERT PAYMENT:"))

        if pay > total :
            exchange = pay - total
            print(' ')
            print(' ')
            print('EXCHANGE : {:0.2f}'.format(exchange))
            print("THANK YOU, PLEASE COME AGAIN")
            import time
            time.sleep(5)

        else:
            print(' ')
            print(' ')
            print("INSUFFICIENT AMOUNT")
            print("PLEASE INSERT THE RIGHT AMOUNT")
            scpay = int(input("INSERT PAYMENT : "))
        if scpay > total :
            exchange = scpay - total
            print(' ')
            print(' ')
            print('EXCHANGE     : {:0.2f}'.format(exchange))
            print("THANK YOU, PLEASE COME AGAIN")
            import time
            time.sleep(5)

        else:
            print("  ")
            print("ORDER TERMINATED")
            import time
            time.sleep(5)
</code>```

答:
place break after a statement after which you want to stop your loop
for ex.</p>

```<code>if choice == 1:
        amount = int(input("ENTER THE AMOUNT: "))
        hcount += amount
</code>```

Title: How do I break a looping menu on Python

Body:
I have a little problem on making ecounter for fast food, the problems is at continuing order.
I don't know how to use True and False in python..
I choose three food as a beginner. It's end up failing..
So I tried to use True by copying other people code.
at first the code was success, but when i changed a little thing in code, it went wrong and I don't know how to fix it.

so far this is my code:

hcount = 0
scount = 0
fcount = 0
y = True
n = False
cstm= input("Please enter your name: ")
print("                                       ")
print("                                       ")
print("Hi MR/MS " + cstm)
print("WELCOME TO MACDUNNO ECOUNTER")

print("CHOOSE YOUR FOOD")

while True:

    print("  ")
    print('MENU MAC DUNNO')
    print("1. HAMBURGER = $1.50")
    print("2. SODA      = $1.15")
    print("3. FRIES   = $1.25")

    choice = int(input('ENTER NUMBER 1-3: '))

    if choice == 1:
        amount = int(input("ENTER THE AMOUNT: "))
        hcount += amount
    elif choice == 2:
        amount = int(input("ENTER THE AMOUNT: "))
        scount += amount
    elif choice == 3:
        amount = int(input("ENTER THE AMOUNT: "))
        fcount += amount

    countinue = input("ARE YOU STILL WANT TO ORDER? (y/n)")
    if countinue == n:
        sub = (hcount * 1.50) + (scount * 1.15) + (fcount * 1.25)
        tax = sub * 0.09
        total = sub + tax
        print("                                           ")
        print("                                           ")
        print("************")
        print("PAYMENT")
        print("************")
        print('TOTAL HAMBURGER: {0}'.format(hcount))
        print('TOTAL SODA: {0}'.format(scount))
        print('TOTAL FRIES: {0}'.format(fcount))
        print(" ")
        print('SUBTOTAL: {:0.2f}'.format(sub))
        print('TAX : {:0.2f}'.format(tax))
        print("   ")
        print("__________________________________")
        print('TOTAL: {:0.2f}'.format(total))
        print("   ")
        pay =int(input("INSERT PAYMENT:"))

        if pay > total :
            exchange = pay - total
            print(' ')
            print(' ')
            print('EXCHANGE : {:0.2f}'.format(exchange))
            print("THANK YOU, PLEASE COME AGAIN")
            import time
            time.sleep(5)

        else:
            print(' ')
            print(' ')
            print("INSUFFICIENT AMOUNT")
            print("PLEASE INSERT THE RIGHT AMOUNT")
            scpay = int(input("INSERT PAYMENT : "))
        if scpay > total :
            exchange = scpay - total
            print(' ')
            print(' ')
            print('EXCHANGE     : {:0.2f}'.format(exchange))
            print("THANK YOU, PLEASE COME AGAIN")
            import time
            time.sleep(5)

        else:
            print("  ")
            print("ORDER TERMINATED")
            import time
            time.sleep(5)

Body:
place break after a statement after which you want to stop your loop
for ex.

if choice == 1:
        amount = int(input("ENTER THE AMOUNT: "))
        hcount += amount


问:
A python syntax error that cannot find and answer
def calculate_money_made(**trips):
    total_money_made = 0

```<code>for trip_id, trip from trips.items():
    trip_revenue = trip.cost - trip.driver.cost
    total_money_made += trip_revenue

return total_money_made
</code>```

gives an error! cannot figure out
File "script.py", line 41
    for trip_id, trip from trips.items():
                         ^
SyntaxError: invalid syntax

答:
Change "from" to "in"

for trip_id, trip in trip.items():

Body:
def calculate_money_made(**trips):
    total_money_made = 0

for trip_id, trip from trips.items():
    trip_revenue = trip.cost - trip.driver.cost
    total_money_made += trip_revenue

return total_money_made

gives an error! cannot figure out
File "script.py", line 41
    for trip_id, trip from trips.items():
                         ^
SyntaxError: invalid syntax


问:
Template metaprogramming to match function signature exactly
With template meta-programming it's possible to query properties of types. For example in the case below I'm checking if a certain type has a member function "foo" which takes in another type as the argument.

Is there a way to check if the parameter type is an exact match for the template vs. one that be converted to it, e.g. double or char can be converted into float (causing main to print true twice) but I'm trying to see if there is a way to structure my_test_t so that it matches perfectly, i.e. main() prints false unless T2 = float.

```<code>struct S2
{
   int foo(float x)
   {
      return 0;
   }
};

template <typename T1, typename T2>
using my_test_t = decltype(declval<T1>().foo(declval<T2>()));

template <typename T1, typename T2, typename = void>
struct is_formed : std::false_type
{
};

template <typename T1, typename T2>
struct is_formed<T1, T2, void_t<my_test_t<T1, T2>>> : std::true_type
{
};

int main()
{
   cout << boolalpha << is_formed<S2, double>::value << endl;
   cout << boolalpha << is_formed<S2, char>::value << endl;
}
</code>```

答:
You were almost there. I changed the test so that I take the address of foo and test the type of the resulting pointer-to-member by static_casting it to itself.

```<code>#include <type_traits>
#include <iostream>
using namespace std;

struct S2
{
   int foo(float x)
   {
      return 0;
   }
};

template <typename T1, typename T2>
using my_test_t = decltype( static_cast<int(T1::*)(T2)>(&T1::foo) );

template <typename T1, typename T2, typename = void>
struct is_formed : std::false_type
{ };

template <typename T1, typename T2>
struct is_formed<T1, T2, void_t< my_test_t<T1,T2> >> : std::true_type
{ };

int main()
{
   cout << boolalpha << is_formed<S2, float>::value << endl;  // true
   cout << boolalpha << is_formed<S2, double>::value << endl; // false
   cout << boolalpha << is_formed<S2, char>::value << endl;   // false
}
</code>```

(The code above compiles with C++17 because there's no std::void_t in C++14 - you need to write your own.)

Body:
With template meta-programming it's possible to query properties of types. For example in the case below I'm checking if a certain type has a member function "foo" which takes in another type as the argument.

Is there a way to check if the parameter type is an exact match for the template vs. one that be converted to it, e.g. double or char can be converted into float (causing main to print true twice) but I'm trying to see if there is a way to structure my_test_t so that it matches perfectly, i.e. main() prints false unless T2 = float.

struct S2
{
   int foo(float x)
   {
      return 0;
   }
};

template <typename T1, typename T2>
using my_test_t = decltype(declval<T1>().foo(declval<T2>()));

template <typename T1, typename T2, typename = void>
struct is_formed : std::false_type
{
};

template <typename T1, typename T2>
struct is_formed<T1, T2, void_t<my_test_t<T1, T2>>> : std::true_type
{
};

int main()
{
   cout << boolalpha << is_formed<S2, double>::value << endl;
   cout << boolalpha << is_formed<S2, char>::value << endl;
}

Body:
You were almost there. I changed the test so that I take the address of foo and test the type of the resulting pointer-to-member by static_casting it to itself.

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

struct S2
{
   int foo(float x)
   {
      return 0;
   }
};

template <typename T1, typename T2>
using my_test_t = decltype( static_cast<int(T1::*)(T2)>(&T1::foo) );

template <typename T1, typename T2, typename = void>
struct is_formed : std::false_type
{ };

template <typename T1, typename T2>
struct is_formed<T1, T2, void_t< my_test_t<T1,T2> >> : std::true_type
{ };

int main()
{
   cout << boolalpha << is_formed<S2, float>::value << endl;  // true
   cout << boolalpha << is_formed<S2, double>::value << endl; // false
   cout << boolalpha << is_formed<S2, char>::value << endl;   // false
}

(The code above compiles with C++17 because there's no std::void_t in C++14 - you need to write your own.)


问:
Select the value of an element by name
How to access the value of this input field that is checked by its name attribute using Javascript :

```<code><input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">
</code>```

I write this :

```<code>document.querySelector('input[name="rate"]:checked').value;
</code>```

but there is an error:

```<code>TypeError: document.querySelector(...) is null
</code>```

And I do not want to be checked any inputs by default

答:
you should call function for each radio button change event

function handleRadioButtonChange() {
  console.log(document.querySelector('input[name="rate"]:checked').value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" class="radioButton" name="rate" value="1" onchange="handleRadioButtonChange()">
<input type="radio" class="radioButton" name="rate" value="2" onchange="handleRadioButtonChange()">
<input type="radio" class="radioButton" name="rate" value="3" onchange="handleRadioButtonChange()">
<input type="radio" class="radioButton" name="rate" value="4" onchange="handleRadioButtonChange()"></code>```

Title: Select the value of an element by name

Body:
How to access the value of this input field that is checked by its name attribute using Javascript :

<input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">

I write this :

document.querySelector('input[name="rate"]:checked').value;

but there is an error:

TypeError: document.querySelector(...) is null

And I do not want to be checked any inputs by default

Body:
you should call function for each radio button change event

function handleRadioButtonChange() {
  console.log(document.querySelector('input[name="rate"]:checked').value);
}

<input type="radio" class="radioButton" name="rate" value="1" onchange="handleRadioButtonChange()">
<input type="radio" class="radioButton" name="rate" value="2" onchange="handleRadioButtonChange()">
<input type="radio" class="radioButton" name="rate" value="3" onchange="handleRadioButtonChange()">
<input type="radio" class="radioButton" name="rate" value="4" onchange="handleRadioButtonChange()">


问:
Server Side Render Dynamic Page based on Route Param
I'm starting with Next.js and after going through docs, I cannot figure out how to get the route param code inside getStaticPaths method as shown below!?. code is not known before hand by any means and it can be anything.

I don't want to call api and get the data using useEffect inside the component.

File: pages/post/[code].js

```<code>import React from 'react';
import apiCall from 'api/something';

export default ({post}) => {
     return <>
        render components here based on prop `post`
    </>
}

export async function getStaticPaths() {
    // How to get [code] from the route here, which can be used below?
    return {
        paths: // NEED [code] HERE from current route,
        fallback: false
    }
}

export async function getStaticProps(ctx) {
    return {
        props: {
         // [ctx.code] resolved from current route with the help of getStaticPaths,
         post: apiCall(ctx.code)
        }
    }
}
</code>```

I've tried getServerSideProps which works for me:

```<code>export const getServerSideProps = async (ctx) => {
    return {
        props: {
            post: await apiCall(ctx.query.code)
        }
    };
};
</code>```

But it fails when I do next export stating:

pages with getServerSideProps can not be exported. See more info here: https://err.sh/next.js/gssp-export

After investigating further on this error I found this solution, which is not feasible for me as my app is hosted on Heroku.

I'm trying to server-side render the html along with the data based on the route param code. But not able to do so now.

答:
As I understand, you want to statically generate dynamic routes at build time.

To do so you need to let Next.js know what pages to generate, by specifying all codes.

```<code>export async function getStaticPaths() {
    // you don't need here a code from current route
    // but you need to specify all known post codes
    return {
        paths: [
          { params: { code: '1' } },
          { params: { code: '2' } },
          { params: { code: '3' } },
        ]
        fallback: false
    }
}
</code>```

You would need to re-build app every time you change the posts.

Use getServerSideProps if you don't want to re-build project every time. Then the data would be fetched at request time. You can't export it because it requires Node.js server.

Body:
I'm starting with Next.js and after going through docs, I cannot figure out how to get the route param code inside getStaticPaths method as shown below!?. code is not known before hand by any means and it can be anything.

I don't want to call api and get the data using useEffect inside the component.

File: pages/post/[code].js

import React from 'react';
import apiCall from 'api/something';

export default ({post}) => {
     return <>
        render components here based on prop `post`
    </>
}

export async function getStaticPaths() {
    // How to get [code] from the route here, which can be used below?
    return {
        paths: // NEED [code] HERE from current route,
        fallback: false
    }
}

export async function getStaticProps(ctx) {
    return {
        props: {
         // [ctx.code] resolved from current route with the help of getStaticPaths,
         post: apiCall(ctx.code)
        }
    }
}

I've tried getServerSideProps which works for me:

export const getServerSideProps = async (ctx) => {
    return {
        props: {
            post: await apiCall(ctx.query.code)
        }
    };
};

But it fails when I do next export stating:

pages with getServerSideProps can not be exported. See more info here: https://err.sh/next.js/gssp-export

After investigating further on this error I found this solution, which is not feasible for me as my app is hosted on Heroku.

I'm trying to server-side render the html along with the data based on the route param code. But not able to do so now.

Body:
As I understand, you want to statically generate dynamic routes at build time.

To do so you need to let Next.js know what pages to generate, by specifying all codes.

export async function getStaticPaths() {
    // you don't need here a code from current route
    // but you need to specify all known post codes
    return {
        paths: [
          { params: { code: '1' } },
          { params: { code: '2' } },
          { params: { code: '3' } },
        ]
        fallback: false
    }
}

You would need to re-build app every time you change the posts.

Use getServerSideProps if you don't want to re-build project every time. Then the data would be fetched at request time. You can't export it because it requires Node.js server.


问:
Create a response table with a Google sheet which saves responses in another sheet
I'm trying to create a response table with a Google sheet that lets people enter their responses. Then compile that information into another Google Sheet by specified columns at the bottom of the previous response.

I have tried numerous ways but I cannot seem to get the script to work.

Broken Down, I need the Script/Guide to be able to:

Allow multiple people to record their response individually by the given link of Google sheet Form

Give a dynamic Sum Total in the Total Row

Have an Add row Icon so as to let respondent add rows dynamically and make their own choice of inputs

Create a Submit Icon, which records the response to another google sheet

The intended sheet is below

https://docs.google.com/spreadsheets/d/1cQTBONtpLiMbRmtVgSyOT_mShzzwbrX7-w46zy9w9I4/copy?usp=sharing

This may be a simple question that I didn't sound any solution

答:
```<code>function sendData() {

  var sprsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = sprsheet.getActiveSheet();

  var range = sheet.getRange("A2:G4");
  var values = range.getValues();

  var mainsprsheet = SpreadsheetApp.openById("main sheet id");

// 1. this "main sheet id" should say something like: "1cQTBONtpLiMbRmtVgSyOT_mShzzwbrX7-w46zy9w9I4", you can xopy/paste the id from your address bar in your browser

// ==> https://docs.google.com/spreadsheets/d/1cQTBONtpLiMbRmtVgSyOT_mShzzwbrX7-w46zy9w9I4/edit?ts=5ed39726#gid=0

  var targetSheet = mainsprsheet.getActiveSheet();

targetSheet.appendRow(values);

// 2. appendRow() accepts an array like for example this array with strings ["Fabric Code", "Thickness","Width","Length","Finish","Quality type","Quantity"]

// method getValues() returns an array of arrays (or 2D array) like for example this one[["Fabric Code", "Thickness","Width","Length","Finish","Quality type","Quantity"]]

  // Think of the outer [..] as row indicator and the inner [..] as the array that holds the columns(fields) of the record.

    // i would change your code to: (remove the //s)
    // var lr = targetSheet.getLastRow()
    // var lc = targetSheet.getLastColumn()
    // targetSheet.getRange(lr+1 , 1, values.length, values[0].length).setValues(values)
    //Clear the cells (optional)
      range.clearContent();

}
</code>```


问:
Removing header column from pandas dataframe
I have the foll. dataframe:

df

```<code>   A   B
0  23  12
1  21  44
2  98  21
</code>```

How do I remove the column names A and B from this dataframe? One way might be to write it into a csv file and then read it in specifying header=None. is there a way to do that without writing out to csv and re-reading?

答:
I had the same problem but solved it in this way:</p>
```<code>df = pd.read_csv('your-array.csv', skiprows=[0])
</code>```

Body:
I have the foll. dataframe:

df

   A   B
0  23  12
1  21  44
2  98  21

How do I remove the column names A and B from this dataframe? One way might be to write it into a csv file and then read it in specifying header=None. is there a way to do that without writing out to csv and re-reading?

Body:
I had the same problem but solved it in this way:

df = pd.read_csv('your-array.csv', skiprows=[0])


问:
get_field() does not work inside my foreach loop
I've made a custom field for my product categories so that I could select icons accordingly using ACF plugin. I called all the categories like this (But the values of the custom fields return nothing as I've tried var_dumping it):</p>

```<code><?php

            $orderby = 'date';
            $order = 'DESC';
            $hide_empty = false ;
            $cat_args = array(
                'orderby'    => $orderby,
                'order'      => $order,
                'hide_empty' => $hide_empty,
            );

            $product_categories = get_terms( 'product_cat', $cat_args );

            if( !empty($product_categories) ){
                foreach ($product_categories as $key => $category) {
                    $icon = get_field('icon_classname');
                    if (empty($icon)) { $icon = 'flaticon-002-coat'; }
            ?>

            <div class="cat-item">
                <div class="cat cat-1">
                    <div class="cat-wrap">
                        <a class="category" href="<?php echo get_term_link($category); ?>">
                            <i class="icon fimanager <?php echo $icon; ?>"></i>
                            <span class="cat-title"><?php echo $category->name; ?></span>
                        </a>
                    </div>
                </div>
            </div>

            <?php

                } wp_reset_postdata();
            }

            ?>
</code>```

答:
please check it :<br>
 you should replace these two lines : </p>

```<code> foreach( $product_categories as $cat) {
  $icon = get_field('icon_classname', 'category_'.$cat->term_id);
</code>```

Body:
I've made a custom field for my product categories so that I could select icons accordingly using ACF plugin. I called all the categories like this (But the values of the custom fields return nothing as I've tried var_dumping it):

<?php

            $orderby = 'date';
            $order = 'DESC';
            $hide_empty = false ;
            $cat_args = array(
                'orderby'    => $orderby,
                'order'      => $order,
                'hide_empty' => $hide_empty,
            );

            $product_categories = get_terms( 'product_cat', $cat_args );

            if( !empty($product_categories) ){
                foreach ($product_categories as $key => $category) {
                    $icon = get_field('icon_classname');
                    if (empty($icon)) { $icon = 'flaticon-002-coat'; }
            ?>

                        <a class="category" href="<?php echo get_term_link($category); ?>">
                            <i class="icon fimanager <?php echo $icon; ?>">
                            <?php echo $category->name; ?>

            <?php

                } wp_reset_postdata();
            }

            ?>

Body:
please check it :

 you should replace these two lines :

 foreach( $product_categories as $cat) {
  $icon = get_field('icon_classname', 'category_'.$cat->term_id);


问:
DiscordAPIError: While starting the bot
Here's the API error:

DiscordAPIError
    at RequestHandler.execute (/rbd/pnpm-volume/04d08e99-6e35-44ec-9f4c-98cf4b966f51/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
    at processTicksAndRejections (internal/process/task_queues.js:88:5) {
  name: 'DiscordAPIError',
  message: '',
  method: 'get',
  path: '/gateway/bot',
  code: undefined,
  httpStatus: 403
}
```

I have no idea what any of this means or what I need to fix, it was working fine before, I didn't change any of the code :c

答:
Since the error included the method 'GET', we know there was likely a failure requesting data from some part of the Discord API.
In the Discord API Docs, the following is stated:

403 responses are avoided by inspecting role or channel permissions and by not making requests that are restricted by such permissions

Your client may be attempting to do something that they don't have access to, e.g editing a role above their highest role, renaming a channel without sufficient guild permissions, etc.
Look through your code and see if you can find what's making it do that.

Title: DiscordAPIError: While starting the bot

Body:
Here's the API error:

DiscordAPIError
    at RequestHandler.execute (/rbd/pnpm-volume/04d08e99-6e35-44ec-9f4c-98cf4b966f51/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
    at processTicksAndRejections (internal/process/task_queues.js:88:5) {
  name: 'DiscordAPIError',
  message: '',
  method: 'get',
  path: '/gateway/bot',
  code: undefined,
  httpStatus: 403
}

I have no idea what any of this means or what I need to fix, it was working fine before, I didn't change any of the code :c


问:
Push-Notification Badge auto increment
I've been implementing the push service to my application, and I've been thinking about the application's badge. My app is a mail app (sorta) and I want to notify the user via push for new messages added to the inbox, I want the badge = number of new messages in the inbox.

I thought of doing it server sided (provider) checking for new messages and sending the number as the badge.

The question is:
Is there a way to auto-increment the application's badge, without having to calculate the badge value server sided and afterwards sending it as a part of the push payload to the APSN?

Maybe there's a way to send in JSON badge field some variable like "++" or something like that.
Any hack for that? Or do I need to go with the counting system server-sided??

答:
It is now possible to have the client auto-increment the badge using a UNNotificationServiceExtension.

Extensions have the ability to modify notification payloads before iOS displays them. In summary, store a badge counter in UserDefaults and modify the notification's badge count as needed. You'll need to add the App Groups capability to share User Defaults.

Here's a detailed step-by-step guide: https://prodocs.cometchat.com/docs/ios-increment-app-icon-badge-count

ContentLicense: CC BY-SA 2.5

Title: Push-Notification Badge auto increment


答:
I tackled similar problem recently.
What helped me was using assign() function inside for loop:

example:

```<code> for (i in 1:3){
      assign(x = paste0("variable",i),value = i*10)}
</code>```

What automates process of manual assignment like:

```<code>variable1 = 10
variable2 = 20
variable3 = 30
</code>```

Title: How to make a loop for these regressions?

Body:
I have a dataframe with 10 columns like this:

df = structure(list(X1 = c(-0.158841494166799, 1.74997712540787,
-0.603638753496694, -0.253379995687274, -1.13536828104642, -2.72698649676692,
0.0243826193956672, 3.21776393858788, -2.3633921387719, 0.0305028420399468,
-4.26940546325382, 1.55584592541131, -1.05118869595721, -2.84985861365441,
0.729293004856561, -3.80058253179317, 1.31191742952459, 2.33589025288871,
-0.315014740930705, 2.92302109498542, 2.26246357678861, 1.37039290089958,
0.0582396621450368, -0.902295561314538, 2.14889801735908, 0.391493314141552,
2.33280118206325, -0.0490864536654898, 0.068965431468872, 1.24553936025063
), X2 = c(0.428917030889186, 1.38179284926331, 2.83063848525283,
-0.926689840680047, -1.3903457418351, 0.708618895316463, -0.750232095654876,
0.894660121671367, 0.124277732759992, -1.98558522788821, 2.34165530946135,
2.85945910959032, 2.36563560772223, 0.0185741299096399, -2.48859548768527,
-1.26592501904523, -0.790849261930494, -0.828149152178906, 3.2014616981455,
-0.15442363719638, -0.516775154465199, -0.176649448869891, -1.41825025459806,
2.17806157731774, -0.44973481848562, 2.24655423722927, 2.47628395430464,
1.91613790409017, -0.393928617864301, -0.148584327095393), X3 = c(-0.430287082709084,
-0.625327045828844, -0.514958706302276, 0.751266821352889, 1.18006572060265,
-0.802136052260364, 0, 0.105706401868772, 0.442778243504233,
0.905950590121364, -1.26899829497004, 0.745801518841586, -0.978033251950966,
0.113286791573796, 1.20968420311602, -0.635010679093886, 0.858274389205649,
-1.009308286611, 0, 0.167623720006668, -0.720624475890533, -0.443172067136528,
-0.0181650919153045, -0.818017257660172, 1.18137870264753, -0.0566121497554404,
0.572314218120067, -1.01361737919216, 0.637155618813563, 0.00507063594816648
), X4 = c(1.05105923858325, -0.808507106602501, 1.01063388325313,
-0.363828197971125, -0.889357817262751, 0.0808507106602501, 0,
0.4851042639615, 0.687231040612125, -1.53616350254475, 2.02126776650625,
-1.09148459391338, -0.929783172592876, 0.323402842641, 0.768081751272376,
0.444678908631375, -1.53616350254475, 0.970208527923, 0, 0.646805685282001,
-1.01063388325313, 0.40425355330125, -0.323402842641, -0.202126776650625,
1.09148459391338, -0.970208527923, -0.606380329951876, 0, 0.606380329951876,
0.161701421320499), X5 = c(-1.68622583629267, -2.11651291900176,
-2.7418399648306, -3.25679867113288, -2.50553184977999, -1.32546612917734,
-2.12760218143771, -2.12760218143771, -2.02189577956894, -1.5791175360647,
-0.67316694594334, -1.94216524091338, -1.19636372207179, -2.17439697402276,
-2.06111018244896, -0.85142597933294, -1.48643665842683, -0.628162269221177,
-1.63747055583218, -1.63747055583218, -1.46984683582551, -2.19047131171604,
-2.63364337885257, -2.65180847076788, -3.46982572842805, -2.28844702578052,
-2.34505917553596, -1.77274495741589, -2.78636233660805, -2.14920671779449
), X6 = c(-3.52265292326337, -2.47159368468012, -3.28010079128262,
-2.26946690802949, -2.63329510600062, -3.52265292326337, -3.44180221260312,
-3.44180221260312, -2.95669794864162, -2.26946690802949, -3.80563041057424,
-1.78436264406799, -2.87584723798137, -3.80563041057424, -3.48222756793324,
-2.71414581666087, -2.26946690802949, -3.80563041057424, -2.83542188265124,
-2.83542188265124, -2.18861619736924, -3.19925008062237, -2.79499652732112,
-3.11839936996212, -3.32052614661274, -2.22904155269937, -3.19925008062237,
-3.80563041057424, -3.80563041057424, -3.19925008062237), X7 = c(1,
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 1, 0, 0), X8 = c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0),
    X9 = c(1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0), X10 = c(3.2936,
    3.283, 3.264, 3.3162, 3.31, 3.3485, 3.3017, 3.2927, 3.3186,
    3.3004, 3.3043, 3.0945, 2.7868, 2.7635, 2.749, 2.5605, 2.5571,
    2.2133, 2.0783, 2.0981, 2.0209, 2.0148, 1.973, 2.0567, 2.0214,
    2.0315, 2.0057, 2.078, 2.0152, 2.0277)), row.names = c(NA,
30L), class = "data.frame")

What I want to do is be much faster in the implementation of the following code:

p = 3

instru1 = df$X7[1:(30-p)]
instru2 = df$X8[1:(30-p)]
instru3 = df$X9[1:(30-p)]

var <- VAR(df[, c(1:4,10)], p, type = "const")

summary(lm(var$varresult$[# the name of the first variable that appears]$residuals ~ instru1))

linearHypothesis(lm(var$varresult$[# the name of the first variable that appears]$residuals ~ instru1), "instru1 = 0", test = "F", vcov = vcovHAC, type = "HC1")

I did this code only for instru1 and for one column of interest (col 10 in df). I would like to do the same exercise, for instru1, instru2 and instru3 and, in addition to

VAR(df[, c(1:4,10)], p, type = "const")

for

VAR(df[, c(1:4,5)], p, type = "const")

and

VAR(df[, c(1:4,6)], p, type = "const").

In other words, I would like to avoid doing:

p = 3

instru1 = df$X7[1:(30-p)]
instru2 = df$X8[1:(30-p)]
instru3 = df$X9[1:(30-p)]

var1 <- VAR(df[, c(1:4,5)], p, type = "const")

summary(lm(var1$varresult$[# the name of the first variable that appears]$residuals ~ instru1))

linearHypothesis(lm(var1$varresult$[# the name of the first variable that appears]$residuals ~ instru1), "instru1 = 0", test = "F", vcov = vcovHAC, type = "HC1")

var2 <- VAR(df[, c(1:4,6)], p, type = "const")

summary(lm(var2$varresult$[# the name of the first variable that appears]$residuals ~ instru1))

linearHypothesis(lm(var2$varresult$[# the name of the first variable that appears]$residuals ~ instru1), "instru1 = 0", test = "F", vcov = vcovHAC, type = "HC1")

# and then the same but plugging instru2 and instru3 in place of instru1. Is it possible to have all in one loop?

Ideally I would like to have everything in one loop but, if not feasible, it is also fine to have a code for the VAR part and then I will update the 'instru' bit manually.

Can anyone help me?

Thanks a lot!

Body:
I tackled similar problem recently.
What helped me was using assign() function inside for loop:

example:

 for (i in 1:3){
      assign(x = paste0("variable",i),value = i*10)}

What automates process of manual assignment like:

variable1 = 10
variable2 = 20
variable3 = 30


问:
How to find all enhancements in SAP system?
I need to prepare a document which includes all enhancements implemented in the SAP system of the company, what are all steps that I have to go through?</p>

答: Try running SAP Standard program SNIF in se38. It might help. For more information refer to this blog post. https://blogs.sap.com/2012/04/16/lets-find-enhancements/


问:
Can not open devtools
I can not open chrome dev-tools by url when using nativescript via angular:

chrome-devtools://devtools/bundled/inspector.html?experiments=true&ws=localhost:40000

But when copied the link and paste to google chrome, the result is just search

I tried to reinstall google chrome. Delete node_modules folder, package-lock file, and reinstall npm. But can't resolve problem

答:
Chrome 83 broke the devtools url. There's a fix to the NativeScript CLI in 6.7.4 but in the meantime you can just use this url instead: </p>

```<code>devtools://devtools/bundled/inspector.html?ws=localhost:40000
</code>```

Title: Can not open devtools

Body:
Chrome 83 broke the devtools url. There's a fix to the NativeScript CLI in 6.7.4 but in the meantime you can just use this url instead:

devtools://devtools/bundled/inspector.html?ws=localhost:40000


问:
Matching a C++ style regex with sed?
Does anyone know how to match this C++ style regex using sed?  Specifically to break it into multiple parts using (pattern) and \n?

```<code>// ZIP code pattern: XXddddd-dddd and variants
regex pat (R"(\w{2}\s*\d{5}(−\d{4})?)");
</code>```

For instance the following string would match AB00000-0000 and \1, \2, \3 would print appropriate substrings from pattern space.

SOLUTION:
Here is the sed answer, which accounts for initial two characters.

```<code>$ echo AB00000-0000 | sed 's/\([[:alpha:]]\{2\}\)[[:space:]]*\([[:digit:]]\{5\}\)\(-\([[:digit:]]\{4\}\)\)\{0,1\}/\1 \2 \4/'
AB 00000 0000
</code>```

Thank you

答:
This:

```<code>\w{2}\s*\d{5}(−\d{4})?
</code>```

is a PCRE (as would work in perl or GNU grep -P and can be written as a POSIX ERE (as would work in awk or grep -E or GNU/OSX sed -E) as:

```<code>[[:alnum:]_]{2}[[:space:]]*[[:digit:]]{5}(−[[:digit:]]{4})?
</code>```

or in a POSIX BRE (as would work in grep or sed without -E) as:

```<code>[[:alnum:]_]\{2\}[[:space:]]*[[:digit:]]\{5\}\(−[[:digit:]]\{4\}\)\{0,1\}
</code>```

Title: Matching a C++ style regex with sed?

Body:
Does anyone know how to match this C++ style regex using sed?  Specifically to break it into multiple parts using (pattern) and \n?

// ZIP code pattern: XXddddd-dddd and variants
regex pat (R"(\w{2}\s*\d{5}(−\d{4})?)");

For instance the following string would match AB00000-0000 and \1, \2, \3 would print appropriate substrings from pattern space.

SOLUTION:
Here is the sed answer, which accounts for initial two characters.

$ echo AB00000-0000 | sed 's/\([[:alpha:]]\{2\}\)[[:space:]]*\([[:digit:]]\{5\}\)\(-\([[:digit:]]\{4\}\)\)\{0,1\}/\1 \2 \4/'
AB 00000 0000

Thank you

Body:
This:

\w{2}\s*\d{5}(−\d{4})?

is a PCRE (as would work in perl or GNU grep -P and can be written as a POSIX ERE (as would work in awk or grep -E or GNU/OSX sed -E) as:

[[:alnum:]_]{2}[[:space:]]*[[:digit:]]{5}(−[[:digit:]]{4})?

or in a POSIX BRE (as would work in grep or sed without -E) as:

[[:alnum:]_]\{2\}[[:space:]]*[[:digit:]]\{5\}\(−[[:digit:]]\{4\}\)\{0,1\}