问:
How to draw green lines on black region of an image?
This is the original picture：

I want to draw a green line on the area marked by the red part：

I want this effect：

Or like this：

But I use the following code to test, the effect is not good：

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

img = cv2.imread(r"E:\test_opencv\images\luyuan1.jpg")
blur_img = cv2.GaussianBlur(img, (3, 3), 0)
gray = cv2.cvtColor(blur_img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 150, 250, apertureSize=3)
rho = 1  #Distance resolution of the accumulator in pixels.
theta = np.pi/180 # Angle resolution of the accumulator in radians.
threshold  = 100 #Accumulator threshold parameter. Only those lines are returned that get enough votes ( >\texttt{threshold} ).
lines = cv2.HoughLines(edges, rho, theta, threshold)
if lines is not None:
    for i in range(len(lines)):
        for r,th in lines[i]:
            a = np.cos(th)
            b = np.sin(th)
            x0 = a*r
            y0 = b*r
            x1 = int(x0 + 1000*(-b))
            y1 = int(y0 + 1000*(a))
            x2 = int(x0 - 1000*(-b))
            y2 = int(y0 - 1000*(a))

            cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
            print(x1,y1,x2,y2)
# cv2.imshow('canny', edges)
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

The effect is this：

How should I modify it, I don't think edge detection and Huff transform are feasible.

I also tried using the following code：

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

src = cv2.imread(r"E:\test_opencv\images\luyuan1.jpg")
cv2.imshow("src", src)

hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
low_hsv = np.array([0, 0, 46])
high_hsv = np.array([180, 43, 220])
mask = cv2.inRange(hsv, lowerb=low_hsv, upperb=high_hsv)
cv2.imshow("mask", mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

But the effect is not good：

答:
Here is one way to extract the left side edge in Python/OpenCV.

Read input

Convert to grayscale

Apply adaptive threshold and invert white-black polarity

Erode to separate region of interest

Get largest contour

Draw filled contour on black background

Close the white region

Apply x-sobel edge to the region to get only the left-side edge

Overlay extracted edge to input image

Save output

Input:

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

# read image
img = cv2.imread("blinds.png")

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# apply gaussian blur (sigma=2)
blur = cv2.GaussianBlur(gray, (5,5), 0, 0)

# do adaptive threshold on gray image
thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 91, 7)

# invert
thresh = 255 - thresh

# apply morphology erode then close
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
erode = cv2.morphologyEx(thresh, cv2.MORPH_ERODE, kernel)

# Get largest contour
cnts = cv2.findContours(erode, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
result = img.copy()
area_thresh = 0
for c in cnts:
    area = cv2.contourArea(c)
    if area > area_thresh:
        area_thresh=area
        big_contour = c

# draw largest contour only
big_c = img.copy()
cv2.drawContours(big_c, [big_contour], -1, (0, 255, 0), 1)

# draw white contour region on black background image
region = np.full_like(img, (0,0,0))
cv2.drawContours(region, [big_contour], -1, (255,255,255), -1)

# apply morphology close to region
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (57,57))
closed = cv2.morphologyEx(region, cv2.MORPH_CLOSE, kernel)

# get left-side edge as single channel
sobel = cv2.Sobel(closed, cv2.CV_8U, 1, 0, 3)[:,:,0]

# get result image overlaying edge on input
result = img.copy()
result[sobel==255] = (0,0,255)

# write results to disk
cv2.imwrite("blinds_thresh.png", thresh)
cv2.imwrite("blinds_erode.png", erode)
cv2.imwrite("blinds_big_c.png", big_c)
cv2.imwrite("blinds_region.png", region)
cv2.imwrite("blinds_closed.png", closed)
cv2.imwrite("blinds_sobel.png", sobel)
cv2.imwrite("blinds_left_edge.png", result)

# display it
cv2.imshow("IMAGE", img)
cv2.imshow("THRESHOLD", thresh)
cv2.imshow("ERODE", erode)
cv2.imshow("BIG_C", big_c)
cv2.imshow("REGION", region)
cv2.imshow("CLOSED", closed)
cv2.imshow("SOBEL", sobel)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
</code>```

Inverted Threshold Image:

Eroded Image:

Contour Image:

Filled contour region on black Image:

Closed contour region Image:

Sobel edge Image:

Resulting Edge on input Image:

Body:
This is the original picture：

I want to draw a green line on the area marked by the red part：

I want this effect：

Or like this：

But I use the following code to test, the effect is not good：

import cv2
import numpy as np

img = cv2.imread(r"E:\test_opencv\images\luyuan1.jpg")
blur_img = cv2.GaussianBlur(img, (3, 3), 0)
gray = cv2.cvtColor(blur_img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 150, 250, apertureSize=3)
rho = 1  #Distance resolution of the accumulator in pixels.
theta = np.pi/180 # Angle resolution of the accumulator in radians.
threshold  = 100 #Accumulator threshold parameter. Only those lines are returned that get enough votes ( >\texttt{threshold} ).
lines = cv2.HoughLines(edges, rho, theta, threshold)
if lines is not None:
    for i in range(len(lines)):
        for r,th in lines[i]:
            a = np.cos(th)
            b = np.sin(th)
            x0 = a*r
            y0 = b*r
            x1 = int(x0 + 1000*(-b))
            y1 = int(y0 + 1000*(a))
            x2 = int(x0 - 1000*(-b))
            y2 = int(y0 - 1000*(a))

            cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
            print(x1,y1,x2,y2)
# cv2.imshow('canny', edges)
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

The effect is this：

How should I modify it, I don't think edge detection and Huff transform are feasible.

I also tried using the following code：

import cv2
import numpy as np

src = cv2.imread(r"E:\test_opencv\images\luyuan1.jpg")
cv2.imshow("src", src)

hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
low_hsv = np.array([0, 0, 46])
high_hsv = np.array([180, 43, 220])
mask = cv2.inRange(hsv, lowerb=low_hsv, upperb=high_hsv)
cv2.imshow("mask", mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

But the effect is not good：

Body:
Here is one way to extract the left side edge in Python/OpenCV.

Read input

Convert to grayscale

Apply adaptive threshold and invert white-black polarity

Erode to separate region of interest

Get largest contour

Draw filled contour on black background

Close the white region

Apply x-sobel edge to the region to get only the left-side edge

Overlay extracted edge to input image

Save output

Input:

import cv2
import numpy as np

# read image
img = cv2.imread("blinds.png")

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# apply gaussian blur (sigma=2)
blur = cv2.GaussianBlur(gray, (5,5), 0, 0)

# do adaptive threshold on gray image
thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 91, 7)

# invert
thresh = 255 - thresh

# apply morphology erode then close
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
erode = cv2.morphologyEx(thresh, cv2.MORPH_ERODE, kernel)

# Get largest contour
cnts = cv2.findContours(erode, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
result = img.copy()
area_thresh = 0
for c in cnts:
    area = cv2.contourArea(c)
    if area > area_thresh:
        area_thresh=area
        big_contour = c

# draw largest contour only
big_c = img.copy()
cv2.drawContours(big_c, [big_contour], -1, (0, 255, 0), 1)

# draw white contour region on black background image
region = np.full_like(img, (0,0,0))
cv2.drawContours(region, [big_contour], -1, (255,255,255), -1)

# apply morphology close to region
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (57,57))
closed = cv2.morphologyEx(region, cv2.MORPH_CLOSE, kernel)

# get left-side edge as single channel
sobel = cv2.Sobel(closed, cv2.CV_8U, 1, 0, 3)[:,:,0]

# get result image overlaying edge on input
result = img.copy()
result[sobel==255] = (0,0,255)

# write results to disk
cv2.imwrite("blinds_thresh.png", thresh)
cv2.imwrite("blinds_erode.png", erode)
cv2.imwrite("blinds_big_c.png", big_c)
cv2.imwrite("blinds_region.png", region)
cv2.imwrite("blinds_closed.png", closed)
cv2.imwrite("blinds_sobel.png", sobel)
cv2.imwrite("blinds_left_edge.png", result)

# display it
cv2.imshow("IMAGE", img)
cv2.imshow("THRESHOLD", thresh)
cv2.imshow("ERODE", erode)
cv2.imshow("BIG_C", big_c)
cv2.imshow("REGION", region)
cv2.imshow("CLOSED", closed)
cv2.imshow("SOBEL", sobel)
cv2.imshow("RESULT", result)
cv2.waitKey(0)

Inverted Threshold Image:

Eroded Image:

Contour Image:

Filled contour region on black Image:

Closed contour region Image:

Sobel edge Image:

Resulting Edge on input Image:


来源: stackexchange

问:
Heroku 403 Forbidden - Laravel 5
I have a Laravel 5.8 site

https://boss-security-2.herokuapp.com/

I deployed to Heorku to test with this script that I created

```<code>appName='boss-security-2'
echo 'appName =' $appName

# heroku apps
# heroku apps:destroy appName --confirm appName
# ----------------------

echo web: vendor/bin/heroku-php-apache2 public/ > Procfile
git init
git status
git add -A
git commit -m "Initial commit"

heroku create $appName
heroku git:remote -a $appName
heroku buildpacks:set heroku/php
heroku config:set APP_KEY=9O7AegDFJhVC16jLfNNepT7TEQ7FyFZc

git push heroku master

heroku apps:info
heroku open
echo "done"
#
</code>```

I kept getting

Forbidden

>

You don't have permission to access this resource

Anything wrong in my script ?

Composer.json

```<code>{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "guzzlehttp/guzzle": "~6.0",
        "laravel/framework": "5.8.*",
        "laravel/tinker": "^1.0",
        "laravelcollective/html": "~5.0",
        "nesbot/carbon": "^2.19",
        "pusher/pusher-php-server": "^3.4"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ],
        "post-install-cmd": [
            "php artisan clear-compiled",
            "chmod -R 777 public/"
        ]
    },

}
</code>```

Update 1

I checked the log, I saw this

Cannot serve directory /app/: No matching DirectoryIndex (index.php,index.html,index.htm) found, and server-generated directory index forbidden by Options directive

Update 2

I have no idea why my composer.json in my dyno doesn't seem to have my latest code. I SSHed in and check.

heroku ps:exec

Is this has something to do with my composer.lock ?

答:
try this to solve your problem. add this in your composer.json</p>

```<code> "post-install-cmd": [
     "php artisan clear-compiled",
     "chmod -R 777 public/"
 ]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Heroku 403 Forbidden - Laravel 5

Body:
I have a Laravel 5.8 site

https://boss-security-2.herokuapp.com/

I deployed to Heorku to test with this script that I created

appName='boss-security-2'
echo 'appName =' $appName

# heroku apps
# heroku apps:destroy appName --confirm appName
# ----------------------

echo web: vendor/bin/heroku-php-apache2 public/ > Procfile
git init
git status
git add -A
git commit -m "Initial commit"

heroku create $appName
heroku git:remote -a $appName
heroku buildpacks:set heroku/php
heroku config:set APP_KEY=9O7AegDFJhVC16jLfNNepT7TEQ7FyFZc

git push heroku master

heroku apps:info
heroku open
echo "done"
#

I kept getting

Forbidden

>

You don't have permission to access this resource

Anything wrong in my script ?

Composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "guzzlehttp/guzzle": "~6.0",
        "laravel/framework": "5.8.*",
        "laravel/tinker": "^1.0",
        "laravelcollective/html": "~5.0",
        "nesbot/carbon": "^2.19",
        "pusher/pusher-php-server": "^3.4"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ],
        "post-install-cmd": [
            "php artisan clear-compiled",
            "chmod -R 777 public/"
        ]
    },

}

Update 1

I checked the log, I saw this

Cannot serve directory /app/: No matching DirectoryIndex (index.php,index.html,index.htm) found, and server-generated directory index forbidden by Options directive

Update 2

I have no idea why my composer.json in my dyno doesn't seem to have my latest code. I SSHed in and check.

heroku ps:exec

Is this has something to do with my composer.lock ?

Body:
try this to solve your problem. add this in your composer.json

 "post-install-cmd": [
     "php artisan clear-compiled",
     "chmod -R 777 public/"
 ]


问:
How to size a modal by ts file ionic 4
I would like to size a modal from the TS File and not by the Global SCSS File.

There is a simple code where you size the modal by the Global SCSS File.

HTML File

    <ion-content>
      <ion-button expand="block" fill="outline" (click)="onModal()">
        <ion-icon name="apps"></ion-icon>
      </ion-button>
    </ion-content>
```

<p><strong>TS File:</strong></p>

<pre class="lang-js prettyprint-override"><code>
     export class HomePage {

      constructor(private modalController: ModalController) {}

      onModal() {
        this.dynamicPreview('Dynamic Modal');
      }

      async dynamicPreview(info: any) {
        const myModal = await this.modalController.create({
        component: DynamicModalPage,
        cssClass: 'dynamicModalCss',
        componentProps: {
            vInfo: info,
          }
        });
        return await myModal.present();
      }

    }
</code>```

Global SCSS File:

    .dynamicModalCss {
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        position: absolute;
        contain: strict;
        display: flex;
        justify-content: center;
        align-items: center;

        .modal-wrapper {
            width: 20rem;
            height: 40rem;
          }
    }

```

I have no idea about how to do this :(

Thanks for your suggestions and help

答:
The only way you can customize a modal is using css classes.

Instead of creating the class in the global.scss file, you could create it on each component scss file. In your case, in the HomePage.component.css file.

So, each component will have a different width and height for the modal depending on what you set in the corresponding scss file.

The properties that you have to use are css4 properties: --width, --height.

home.component.scss file

```<code>.my-modal {
  --width: 100px;
  --height: 50px;
}
</code>```

another.component.scss file

```<code>.my-modal {
  --width: 100px;
  --height: 50px;
}
</code>```

Title: How to size a modal by ts file ionic 4

Body:
I would like to size a modal from the TS File and not by the Global SCSS File.

There is a simple code where you size the modal by the Global SCSS File.

HTML File

    <ion-content>
      <ion-button expand="block" fill="outline" (click)="onModal()">
        <ion-icon name="apps"></ion-icon>
      </ion-button>
    </ion-content>

TS File:

     export class HomePage {

      constructor(private modalController: ModalController) {}

      onModal() {
        this.dynamicPreview('Dynamic Modal');
      }

      async dynamicPreview(info: any) {
        const myModal = await this.modalController.create({
        component: DynamicModalPage,
        cssClass: 'dynamicModalCss',
        componentProps: {
            vInfo: info,
          }
        });
        return await myModal.present();
      }

    }

Global SCSS File:

    .dynamicModalCss {
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        position: absolute;
        contain: strict;
        display: flex;
        justify-content: center;
        align-items: center;

        .modal-wrapper {
            width: 20rem;
            height: 40rem;
          }
    }

I have no idea about how to do this :(

Thanks for your suggestions and help

Body:
The only way you can customize a modal is using css classes.

Instead of creating the class in the global.scss file, you could create it on each component scss file. In your case, in the HomePage.component.css file.

So, each component will have a different width and height for the modal depending on what you set in the corresponding scss file.

The properties that you have to use are css4 properties: --width, --height.

home.component.scss file

.my-modal {
  --width: 100px;
  --height: 50px;
}

another.component.scss file

.my-modal {
  --width: 100px;
  --height: 50px;
}


问:
C++ including a ".h" file, function duplication confusion
I'm currently writing a program, and couldn't figure out why I got an error (note: I already fixed it, I'm curious about WHY the error was there and what this implies about including .h files).

Basically, my program was structured as follows:

The current file I'm working with, I'll call Current.cc (which is an implementation of Current.h).

Current.cc included a header file, named CalledByCurrent.h (which has an associated implementation called CalledByCurrent.cc).  CalledByCurrent.h contains a class definition.

There was a non-class function defined in CalledByCurrent.cc called thisFunction().  thisFunction() was not declared in CalledByCurrent.h since it was not actually a member function of the class (just a little helper function).  In Current.cc, I needed to use this function, so I just redefined thisFunction() at the top of Current.cc.  However, when I did this, I got an error saying that the function was duplicated.  Why is this, when myFunction() wasn't even declared in CalledByCurrent.h?

Thus, I just removed the function from Current.cc, now assuming that Current.cc had access to thisFunction() from CalledByCurrent.cc.  However, when I did this, I found that Current.cc did not know what function I was talking about.  What the heck?  I then copied the function definition for thisFunction() to the top of my CalledByCurrent.h file and this resolved the problem.  Could you help me understand this behavior?  Particularly, why would it think there was a duplicate, yet it didn't know how to use the original?

p.s - I apologize for how confusing this post is.  Please let me know if there's anything I can clear up.

答:
You are getting multiple definitions from the linker - it sees two functions with the same name and complains. For example:

```<code>// a.cpp
void f() {}

// b.cpp
void f() {}
</code>```

then

```<code>g++ a.cpp b.cpp
</code>```

gives:

```<code>C:\Users\neilb\Temp\ccZU9pkv.o:b.cpp:(.text+0x0): multiple definition of `f()'
</code>```

The way round this is to either put the definition in only one .cpp file, or to declare one or both of the functions as static:

```<code>// b.cpp
static void f() {}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You are getting multiple definitions from the linker - it sees two functions with the same name and complains. For example:

// a.cpp
void f() {}

// b.cpp
void f() {}

then

g++ a.cpp b.cpp

gives:

C:\Users\neilb\Temp\ccZU9pkv.o:b.cpp:(.text+0x0): multiple definition of `f()'

The way round this is to either put the definition in only one .cpp file, or to declare one or both of the functions as static:

// b.cpp
static void f() {}


问:
How can I send money from Stripe to my customer card?
I want send my Stripe account money to my customers. My customers already have save cards in the system. I just want to money from my Stripe balance to their cards. How can I do that?</p>

答: No, you cannot do that.  Depending on your use case - you should reach out to Support to make sure it's supported - you may be able to use Connect for this though.</p>


问:
WSO2 API Manager with ESB
In API Manager, I pass APIs in API Manager with respective services, also after reading documentacion of API Manager version 3.0.0 (https://apim.docs.wso2.com/en/latest/GettingStarted/overview/), I know in Publisher there exists a ESB, also in my case I work with this cases I think is part of ESB:

WSO2 OAuth Mediator(JAR).

File JSON by WSO2 OAuth Mediator, with endpoints referents to API's I'm cosuming.

In publisher page I add Custom Policies in request or response.

But existing WSO2 Enterprise Integrator (EI) version 6.6.0, this component have a ESB.

My questions are:

In my case, really I work with ESB?

How to integrate API Manager with EI?

答: WSO2 API Manager gateway is built on top of Synapse engine which is the same engine used in WSO2 EI (ESB). Using API Manager you can do simple mediation. But if you want to do any complex mediation, then you should use EI (ESB) along with API Manager. </p>

Title: WSO2 API Manager with ESB


问:
Implementing 3Legged Authentication with React
Is there a way to get an example of implementing the 3 legged authentication process in React without using Redux?

The boiler plate is just way complicated for the majority and I guess is good to have something more simple for "the rest of us".

答:
EDIT

To persist Redux states I can think of two options off the top of my head:

Open a new window session for the authentication and you can close the window and notify the parent window since they'd in the same domain once the callback arrives

Or persist all essential states to localStorage/sessionStorage to load back after direction

Although we don't exactly have a React sample to generate 3 legged tokens but the that very process has no more to do with your backend - you'd not want to generate a 3 legged token in your front end for security reasons.

So far as React or any front end framework is concerned it's a matter of redirecting the user to sign in to their Autodesk account and set up the callback handler in your backend properly to receive the access code - see our official tutorial for details and there's sample code for both front (albeit in vanialla JS) and back ends

Feel free to comment if you have any specific question re this process.


问:
Navigating back to start screen
I have two different documents with two different screens. After an e-mail validation on the first screen, I'm now able to go to the second screen. However, I want to return to the first screen. None of the mentioned approaches on the React Navigation 5.x documentation works for me.

This is the code on the App.js:

```<code>import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import firebase from './firebase';
import * as EmailValidator from 'email-validator';
import { HitTestResultTypes } from 'expo/build/AR';
import logo from './assets/Circulo.png';
import AgeInput from './AgeInput';

// Clase que representa el diseño de la pantalla inicial de la app
class HomeScreen extends Component {
  state = { username: null, password: null, nonValidInput: null }

  _onSubmit = ({ navigation }) =>{
    if(EmailValidator.validate(this.state.username) == true) {
      this.setState({ nonValidInput: false });
      const { username, password } = this.state;

      try {
        // THIS IS WHERE I GO TO THE SECOND SCREEN
        firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(() => this.props.navigation.navigate('Age'));
      } catch {
        Alert.alert(
          'Error',
          'Los datos no son correctos',
          [
            { text: 'Ok' }
          ],
          { cancelable: false }
        );
      }

    } else {
      this.setState({ nonValidInput: true });
    }
  }

  render() {
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
      enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
        <View style={styles.logo}>
          <Image source = {logo} style={styles.img}/>
          <Text style={styles.textLogoPrimary}>Neuron App</Text>
          <Text style={styles.textLogoSecondary}>Test</Text>
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Correo Electrónico</Text>
          <TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
          style={styles.formInput} />
          {this.state.nonValidInput ? (
            <Text style={styles.textAlert}>Correo electrónico no valido.</Text>
          ) : null}
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Contraseña</Text>
          <TextInput style={styles.formInput} placeholder='Contraseña' onChangeText={value => this.setState({ password: value })}
          secureTextEntry={true}/>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._onSubmit}>
            <Text style={styles.buttonText}>Iniciar</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

const Stack = createStackNavigator();

class App extends Component {
  render() {
    return (
      <NavigationContainer>
        <Stack.Navigator screenOptions={{headerShown: false}} initialRouteName="Home">
          <Stack.Screen name='Home' component={HomeScreen} />
          <Stack.Screen name='Age' component={AgeInput} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}
</code>```

and this is the code on the AgeInput.js

```<code>import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import Home from './App';

class App extends Component { // AgeInput
  state = { date: null, edad: null, day: null, month: null, year: null }

  _ageCalc = () => {
    if(this.state.day < 32 && this.state.day > 0 && this.state.month < 13 && this.state.month > 0 && this.state.year != 0) {
      var fecha = Date.parse(this.state.year + '-' + this.state.month + '-' + this.state.day);

      var hoy = new Date();
      var fechaNacimiento = new Date(fecha);
      var edad_ahora = hoy.getFullYear() - fechaNacimiento.getFullYear();
      var mes = hoy.getMonth() - fechaNacimiento.getMonth();

      if (mes < 0 || (mes === 0 && hoy.getDate() < fechaNacimiento.getDate())) {
        edad_ahora--;
      }

      this.setState({ edad: edad_ahora });
    } else {
      Alert.alert(
        'Error',
        'Por favor introduce una fecha valida',
        [
          { text: 'Ok' }
        ],
        { cancelable: false },
      );
    }
  }

  render () {
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled enableOnAndroid={true}
      resetScrollToCoords={{x:0, y:0}}>
        <View style={styles.topView}>
          // This is the button I press to go back to the first screen
          <TouchableOpacity style={styles.img} onPress={() => this.props.navigator.navigate('Home')}>
            <Image source={flecha} />
          </TouchableOpacity>
          <View style={styles.topTextWrapper}>
            <Text style={styles.topTextPrimary}>Bienvenido a Neuron</Text>
              <Text style={styles.topTextSecondary}>¿O no?</Text>
            </View>
        </View>

        <View style={styles.middleView}>
          <Text style={styles.formText}>Fecha de nacimiento</Text>
          <View style={styles.formRow}>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='DD' keyboardType='number-pad'
              onChangeText={ value => this.setState({ day: value }) }/>
            </View>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='MM' keyboardType='number-pad'
              onChangeText={ value => this.setState({ month: value }) }/>
            </View>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='AA' keyboardType='number-pad'
              onChangeText={ value => this.setState({ year: value }) }/>
            </View>
          </View>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._ageCalc}>
            <Text style={styles.buttonText}>CALCULAR EDAD</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.ageView}>
          <Text style={styles.ageTextPrimary}>Tu edad es:</Text>
          <Text style={styles.ageNumber}>{this.state.edad}</Text>
          <Text style={styles.ageTextSecondary}>Años</Text>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

export default App; // AgeInput
</code>```

Thanks for your help

答:
Just replace this :

```<code>// This is the button I press to go back to the first screen
          <TouchableOpacity style={styles.img} onPress={() => this.props.navigator.navigate('Home')}>
</code>```

with

```<code>// This is the button I press to go back to the first screen
          <TouchableOpacity style={styles.img} onPress={() => this.props.navigation.navigate('Home')}>
</code>```

Hope it help.s

Title: Navigating back to start screen

Body:
I have two different documents with two different screens. After an e-mail validation on the first screen, I'm now able to go to the second screen. However, I want to return to the first screen. None of the mentioned approaches on the React Navigation 5.x documentation works for me.

This is the code on the App.js:

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import firebase from './firebase';
import * as EmailValidator from 'email-validator';
import { HitTestResultTypes } from 'expo/build/AR';
import logo from './assets/Circulo.png';
import AgeInput from './AgeInput';

// Clase que representa el diseño de la pantalla inicial de la app
class HomeScreen extends Component {
  state = { username: null, password: null, nonValidInput: null }

  _onSubmit = ({ navigation }) =>{
    if(EmailValidator.validate(this.state.username) == true) {
      this.setState({ nonValidInput: false });
      const { username, password } = this.state;

      try {
        // THIS IS WHERE I GO TO THE SECOND SCREEN
        firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(() => this.props.navigation.navigate('Age'));
      } catch {
        Alert.alert(
          'Error',
          'Los datos no son correctos',
          [
            { text: 'Ok' }
          ],
          { cancelable: false }
        );
      }

    } else {
      this.setState({ nonValidInput: true });
    }
  }

  render() {
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
      enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
        <View style={styles.logo}>
          <Image source = {logo} style={styles.img}/>
          <Text style={styles.textLogoPrimary}>Neuron App</Text>
          <Text style={styles.textLogoSecondary}>Test</Text>
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Correo Electrónico</Text>
          <TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
          style={styles.formInput} />
          {this.state.nonValidInput ? (
            <Text style={styles.textAlert}>Correo electrónico no valido.</Text>
          ) : null}
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Contraseña</Text>
          <TextInput style={styles.formInput} placeholder='Contraseña' onChangeText={value => this.setState({ password: value })}
          secureTextEntry={true}/>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._onSubmit}>
            <Text style={styles.buttonText}>Iniciar</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

const Stack = createStackNavigator();

class App extends Component {
  render() {
    return (
      <NavigationContainer>
        <Stack.Navigator screenOptions={{headerShown: false}} initialRouteName="Home">
          <Stack.Screen name='Home' component={HomeScreen} />
          <Stack.Screen name='Age' component={AgeInput} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}

and this is the code on the AgeInput.js

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import Home from './App';

class App extends Component { // AgeInput
  state = { date: null, edad: null, day: null, month: null, year: null }

  _ageCalc = () => {
    if(this.state.day < 32 && this.state.day > 0 && this.state.month < 13 && this.state.month > 0 && this.state.year != 0) {
      var fecha = Date.parse(this.state.year + '-' + this.state.month + '-' + this.state.day);

      var hoy = new Date();
      var fechaNacimiento = new Date(fecha);
      var edad_ahora = hoy.getFullYear() - fechaNacimiento.getFullYear();
      var mes = hoy.getMonth() - fechaNacimiento.getMonth();

      if (mes < 0 || (mes === 0 && hoy.getDate() < fechaNacimiento.getDate())) {
        edad_ahora--;
      }

      this.setState({ edad: edad_ahora });
    } else {
      Alert.alert(
        'Error',
        'Por favor introduce una fecha valida',
        [
          { text: 'Ok' }
        ],
        { cancelable: false },
      );
    }
  }

  render () {
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled enableOnAndroid={true}
      resetScrollToCoords={{x:0, y:0}}>
        <View style={styles.topView}>
          // This is the button I press to go back to the first screen
          <TouchableOpacity style={styles.img} onPress={() => this.props.navigator.navigate('Home')}>
            <Image source={flecha} />
          </TouchableOpacity>
          <View style={styles.topTextWrapper}>
            <Text style={styles.topTextPrimary}>Bienvenido a Neuron</Text>
              <Text style={styles.topTextSecondary}>¿O no?</Text>
            </View>
        </View>

        <View style={styles.middleView}>
          <Text style={styles.formText}>Fecha de nacimiento</Text>
          <View style={styles.formRow}>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='DD' keyboardType='number-pad'
              onChangeText={ value => this.setState({ day: value }) }/>
            </View>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='MM' keyboardType='number-pad'
              onChangeText={ value => this.setState({ month: value }) }/>
            </View>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='AA' keyboardType='number-pad'
              onChangeText={ value => this.setState({ year: value }) }/>
            </View>
          </View>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._ageCalc}>
            <Text style={styles.buttonText}>CALCULAR EDAD</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.ageView}>
          <Text style={styles.ageTextPrimary}>Tu edad es:</Text>
          <Text style={styles.ageNumber}>{this.state.edad}</Text>
          <Text style={styles.ageTextSecondary}>Años</Text>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

export default App; // AgeInput

Thanks for your help

Body:
Just replace this :

// This is the button I press to go back to the first screen
          <TouchableOpacity style={styles.img} onPress={() => this.props.navigator.navigate('Home')}>

with

// This is the button I press to go back to the first screen
          <TouchableOpacity style={styles.img} onPress={() => this.props.navigation.navigate('Home')}>

Hope it help.s


问:
Creating a java Script function to make an api call and retrieve the data
A JavaScript function is needed to make an API call to Github and receive a response as JSON data.
The api link is as follows - https://api.github.com/users</p>

答:
```<code>axios.get('https://api.github.com/users')
.then(response=> {
    console.log(response.data);
})
.catch(error => console.error(error));
</code>```

I was able to obtain the users using this code

Body:
axios.get('https://api.github.com/users')
.then(response=> {
    console.log(response.data);
})
.catch(error => console.error(error));

I was able to obtain the users using this code


问:
Why does it return 1?
Goal of program: return 1 if two arrays are identical. if not return 0.
What I did:

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

int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            return 1;
        }
    }

}

int main ()
{
    int arr1[3] = {10,15,20};
    int arr2[3] = {10,15,21};
    printf("%d\n", identical(arr1, arr2, 3));

    return 0;
}
</code>```

It always returns 1 and I cannot find the reason why.
What's wrong?

答:
```<code>#include <stdio.h>

int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            if (i == len - 1){
              return 1;
            }
        }
    }

}

int main ()
{
    int arr1[3] = {10,15,20};
    int arr2[3] = {10,15,21};
    printf("%d\n", identical(arr1, arr2, 3));

    return 0;
}
</code>```

The problem with your code is that, you're returning from the function before the loop gets to complete its iterations.

Title: Why does it return 1?

Body:
Goal of program: return 1 if two arrays are identical. if not return 0.
What I did:

#include <stdio.h>

int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            return 1;
        }
    }

}

int main ()
{
    int arr1[3] = {10,15,20};
    int arr2[3] = {10,15,21};
    printf("%d\n", identical(arr1, arr2, 3));

    return 0;
}

It always returns 1 and I cannot find the reason why.
What's wrong?

Body:
#include <stdio.h>

int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            if (i == len - 1){
              return 1;
            }
        }
    }

}

int main ()
{
    int arr1[3] = {10,15,20};
    int arr2[3] = {10,15,21};
    printf("%d\n", identical(arr1, arr2, 3));

    return 0;
}

The problem with your code is that, you're returning from the function before the loop gets to complete its iterations.


问:
Finding out when an NSThread has finished
I have a few functions that I need to call when I press a button. I use [self getamountofdatacenters]; to call these functions. When I press the button, the simulator gets stuck until its done with all the functions, and this takes 5-7 seconds, so I'm trying to use NSThread:

```<code>[NSThread detachNewThreadSelector:@selector(GETAMOUNTDATACENTERS)
                         toTarget:self
                       withObject:nil];
</code>```

I'm doing this three times with different functions, but I want to find out what the progress is of an NSThread and to catch it when it's actually done. How can I do this? Thank you.

答:
One option is to "catch" the end of a thread's execution at the application level: in the code you post to an alternate thread, fire an NSNotification just as it completes. In the main thread you observe this notification and react accordingly.

You can also inspect a thread's state using -isExecuting, -isFinished and -isCancelled.

Body:
I have a few functions that I need to call when I press a button. I use [self getamountofdatacenters]; to call these functions. When I press the button, the simulator gets stuck until its done with all the functions, and this takes 5-7 seconds, so I'm trying to use NSThread:

[NSThread detachNewThreadSelector:@selector(GETAMOUNTDATACENTERS)
                         toTarget:self
                       withObject:nil];

I'm doing this three times with different functions, but I want to find out what the progress is of an NSThread and to catch it when it's actually done. How can I do this? Thank you.


问:
Delete padding or Force fitting or Delete empty space from square Vector asset to Fit a Rectangular button?
I'm trying to adjust the all_inclusive svg image to my rectangular button. The shape itself is rectangular as well but the vector asset is square (24x24) with white spaces above and under the shape. These spaces force the shape itself to be very small. How to make the all inclusive svg rectangular by deleting that padding on top and on bottom?

In this picture the image is set to fit the guidelines on the left, top and right side:

```<code>    <ImageView
        android:id="@+id/imgInfinity"
        app:srcCompat="@drawable/ic_infinity"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintTop_toTopOf="0.75"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="0.75"
        app:layout_constraintEnd_toEndOf="0.25" />
</code>```

Things that did not work:

pivot vector asset with a group -> I just cant figure out the dimensions without messing up the original shape. Same storty with scaleX/Y or translateX/Y. I got it to work on my other buttons with simpler shapes though.

adjusting android:viewportheight or android:height -> it deshapes the picture to a weird form

crop svg online --> as Googles original SVG pathData is already 580 characters long, cropping tools only make it to large for android to deal with (above 1000 charactes)

crop svg picture with word and extract from zip file-> it doesnt compress svg images so it stays rectangular with the white spaces above and under.

Set a seperate horizontal guideline for the top of the picture. It does the trick but one or multiple guidelines for each image gets very messy. There must be a better way, right?..

ACCEPTED SOLUTION (edit with InkShape):

Install InkShape

Open SVG

Click on picture once to select it

Go to File-> Document Properties and click 'Resize pager to drawing or selection' (this button is hidden on the first tab, click +Resize page to content to show the option);

Save

extract pathData and (viewport)width/heights from saved file.

答:
Here's the new update on this topic:

https://code.google.com/p/android/issues/detail?id=202019

It looks like using android:scaleType="fitXY" will make it scale correctly on Lollipop.

From a Google engineer:

Hi, Let me know if scaleType='fitXY' can be a workaround for you , in
  order to get the image look sharp.

The marshmallow Vs Lollipop is due to a special scaling treatment
  added into marshmallow.

Also, for your comments: " Correct behavior: The vector drawable
  should scale without quality loss. So if we want to use the same asset
  in 3 different sizes in our application, we don't have to duplicate
  vector_drawable.xml 3 times with different hardcoded sizes. "

Even though I totally agree this should be the case, in reality, the
  Android platform has performance concern such that we have not reach
  the ideal world yet. So it is actually recommended to use 3 different
  vector_drawable.xml for better performance if you are sure you want to
  draw 3 different size on the screen at the same time.

The technical detail is basically we are using a bitmap under the hook
  to cache the complex path rendering, such that we can get the best
  redrawing performance, on a par with redrawing a bitmap drawable.

Body:
I'm trying to adjust the all_inclusive svg image to my rectangular button. The shape itself is rectangular as well but the vector asset is square (24x24) with white spaces above and under the shape. These spaces force the shape itself to be very small. How to make the all inclusive svg rectangular by deleting that padding on top and on bottom?

In this picture the image is set to fit the guidelines on the left, top and right side:

    <ImageView
        android:id="@+id/imgInfinity"
        app:srcCompat="@drawable/ic_infinity"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintTop_toTopOf="0.75"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="0.75"
        app:layout_constraintEnd_toEndOf="0.25" />

Things that did not work:

pivot vector asset with a group -> I just cant figure out the dimensions without messing up the original shape. Same storty with scaleX/Y or translateX/Y. I got it to work on my other buttons with simpler shapes though.

adjusting android:viewportheight or android:height -> it deshapes the picture to a weird form

crop svg online --> as Googles original SVG pathData is already 580 characters long, cropping tools only make it to large for android to deal with (above 1000 charactes)

crop svg picture with word and extract from zip file-> it doesnt compress svg images so it stays rectangular with the white spaces above and under.

Set a seperate horizontal guideline for the top of the picture. It does the trick but one or multiple guidelines for each image gets very messy. There must be a better way, right?..

ACCEPTED SOLUTION (edit with InkShape):

Install InkShape

Open SVG

Click on picture once to select it

Go to File-> Document Properties and click 'Resize pager to drawing or selection' (this button is hidden on the first tab, click +Resize page to content to show the option);

Save

extract pathData and (viewport)width/heights from saved file.


问:
OpenCV giving an error whenever import cv2 is used
I installed cv2 with pip3 install opencv-contrib-python on terminal and it worked, but on the python IDLE whenever I try to import cv2 or run a vscode file with cv2 imported it says

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/cv2/__init__.py", line 3, in <module>
    from .cv2 import *
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/cv2/cv2.cpython-38-darwin.so, 2): Symbol not found: _inflateValidate
  Referenced from: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/cv2/.dylibs/libpng16.16.dylib (which was built for Mac OS X 10.13)
  Expected in: /usr/lib/libz.1.dylib
 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/cv2/.dylibs/libpng16.16.dylib
</code>```

in the terminal.
Any idea how to fix this?

答:
OpenCV is also referred to as cv2 in Python.

The installation of OpenCV varies betweenoperating systems, so below Iam providing instructions for Windows, Mac, and Linux:

Installing OpenCV on Windows

1.Open the command line and type:

pip install opencv-python

2.Then open a Python session and try:

import cv2

3.If you get no errors, then OpenCV has been successfully installed and you can skip the next steps.

4.If there is an error (usually saying that DLL load failed) then please download a precompiled wheel (.whl) file from this link and install it with pip. Make sure you downloadthe correct file for your Windows version and your Python version. For example, forPython 3.6 onWindows 64-bit you would do this:

pip install opencv_python3.2.0cp36cp36mwin_amd64.whl

5.Then try to import cv2 in Python again. If there's still an error, then please type the following again in the command line:

pip install opencv-python

6.Now you should successfully importcv2 in Python.

Installing OpenCV on Mac

Currently some functionalities of OpenCV are not supported for Python 3 on Mac OS, so it's best to install OpenCV for Python 2and use Python 2 to run the programsthat containscv2 code. Its' worth mentioning that Python 2 is installed by default on Mac, so no need to install Python 2. Here are the steps to correctly install OpenCV:

Install brew:

Open your terminal and paste the following:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
2. OpenCV depends on GTK+, so please install that dependencyfirst with brew (always from the terminal):

brew install gtk+

Install OpenCV with brew:

brew install opencv

Open Python 2 by typing:

python

Import cv2 in Python:

import cv2

If you get no errors, that means OpenCV has been successfully installed.

Installing OpenCV on Linux

1.Please open your terminal and execute the following commands one by one:

sudo apt-get install libqt4-dev
cmake -D WITH_QT=ON ..
make
sudo make install
2.If that doesn't work, please execute this:

sudo apt-get install libopencv-*
3.Then install OpenCV with pip:

pip install opencv-python

Import cv2 in Python.If there are no errors, OpenCVhas been successfully installed.

Body:
I installed cv2 with pip3 install opencv-contrib-python on terminal and it worked, but on the python IDLE whenever I try to import cv2 or run a vscode file with cv2 imported it says

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/cv2/__init__.py", line 3, in <module>
    from .cv2 import *
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/cv2/cv2.cpython-38-darwin.so, 2): Symbol not found: _inflateValidate
  Referenced from: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/cv2/.dylibs/libpng16.16.dylib (which was built for Mac OS X 10.13)
  Expected in: /usr/lib/libz.1.dylib
 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/cv2/.dylibs/libpng16.16.dylib

in the terminal.
Any idea how to fix this?


问:
Change your password on the Woocommerce Checkout-page
I'm working on a development and I need that users already registered on my site, change their password obligatorily on the woocommerce checkout-page.

I tried the classic solution:

```<code>add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');

function custom_override_checkout_fields($fields)
{
    $fields['account']['account_password'] = array(
      'type' => 'password',
      'required'  => true,
      'label' => __('Pass', 'woocommerce'),
      'placeholder' => _x('Pass', 'placeholder', 'woocommerce'),
      'class' => array('form-row-wide')
  );

    return $fields;
}
</code>```

This mode only works for me when the user is registering, but not for changing their password.

Do you think I should make a wp_set_password( $password, $user_id ); ? If so, where would you place the code?

I need a way to do an UPDATE and change user_pass from wp_users table.

答:
Try it.</p>

```<code>add_action( 'woocommerce_checkout_update_user_meta', 'wc_checkout_field_update_user_meta' );

   function wc_checkout_field_update_user_meta( $user_id, $data ) {

     if ( $data['account_password'] ) {

       update_user_meta( $user_id, 'account_password', $data['account_password'] );
     }

}
</code>```

Body:
I'm working on a development and I need that users already registered on my site, change their password obligatorily on the woocommerce checkout-page.

I tried the classic solution:

add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');

function custom_override_checkout_fields($fields)
{
    $fields['account']['account_password'] = array(
      'type' => 'password',
      'required'  => true,
      'label' => __('Pass', 'woocommerce'),
      'placeholder' => _x('Pass', 'placeholder', 'woocommerce'),
      'class' => array('form-row-wide')
  );

    return $fields;
}

This mode only works for me when the user is registering, but not for changing their password.

Do you think I should make a wp_set_password( $password, $user_id ); ? If so, where would you place the code?

I need a way to do an UPDATE and change user_pass from wp_users table.

Body:
Try it.

add_action( 'woocommerce_checkout_update_user_meta', 'wc_checkout_field_update_user_meta' );

   function wc_checkout_field_update_user_meta( $user_id, $data ) {

     if ( $data['account_password'] ) {

       update_user_meta( $user_id, 'account_password', $data['account_password'] );
     }

}


问:
How to resolve update lock issue in MySQL
I have 2 MySQL UPDATE Query problem on my website.

Problem 1

I run a content site that updates page views for posts when users read.

Each time I send push notifications, my server times out; when I comment on the Update query that increments the page views, everything returns to normal.

This I think maybe as a result of hundreds of UPDATE query trying to update the views on the same row.

```<code>**The query that updated the tablename**

update table set views='$newview' where id=1

Query Explain

id: 1
select_type: SIMPLE
table: new_jobs
type: range
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: NULL
rows: 1
Extra: Using where

**tablename create table**

CREATE TABLE `tablename` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `company_id` int(11) DEFAULT NULL,
 `job_title` varchar(255) DEFAULT NULL,
 `slug` varchar(255) DEFAULT NULL,
 `advert_date` date DEFAULT NULL,
 `expiry_date` date DEFAULT NULL,
 `no_deadline` int(1) DEFAULT 0,
 `source` varchar(20) DEFAULT NULL,
 `featured` int(1) DEFAULT 0,
 `views` int(11) DEFAULT 1,
 `email_status` int(1) DEFAULT 0,
 `draft` int(1) DEFAULT 0,
 `created_by` int(11) DEFAULT NULL,
 `show_company_name` int(1) DEFAULT 1,
 `display_application_method` int(1) DEFAULT 0,
 `status` int(1) DEFAULT 1,
 `upload_date` datetime DEFAULT NULL,
 `country` int(1) DEFAULT 1,
 `followers_email_status` int(1) DEFAULT 0,
 `og_img` varchar(255) DEFAULT NULL,
 `old_id` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`),
 KEY `new_jobs_company_id_index` (`company_id`),
 KEY `new_jobs_views_index` (`views`),
 KEY `new_jobs_draft_index` (`draft`),
 KEY `new_jobs_country_index` (`country`)
) ENGINE=InnoDB AUTO_INCREMENT=151359 DEFAULT CHARSET=utf8
</code>```

What is the best way of handling this?

[Scenario 2 removed on request]

答:
Scenario 1. I would expect the update of a 'view' count (or 'click' or 'like' or whatever) to be more like

```<code>UPDATE t SET views = views + 1 WHERE id = 123;
</code>```

I assume you have an index (probably the PRIMARY KEY) on id?

Since there are other things going on with that table, it may be wise to split off the rapidly incrementing counter into a separate table.  This would avoid interfering with other queries.  You can get other data, plus the counter, by using JOIN .. USING(id).

Scenario 2 does not make sense.  It seems to keep the latest date for each email, but what does country mean?  Since it seems like more than just a counter, you might want a separate table to log those 3 columns.

Please provide SHOW CREATE TABLE.

There are many things that novices perceive as a "crash".  Please describe further -- out of connections, out of disk space, sluggishness, the client gave error message, other operations taking too long, etc.  Each has a different remedy.

Query

Are you are currently logically doing

```<code>BEGIN;
$ct = SELECT views ... FOR UPDATE;
...
UPDATE ... SET views = $ct+1 WHERE ...;
COMMIT;
</code>```

If so, that is much less efficient than

```<code>(with autocommit = ON)
UPDATE ... SET views = views+1 ...;
</code>```

Note that the first version hangs onto the row longer.  If you fail to use FOR UPDATE, you will drop some counts.

Splitting into a separate table sort of forces you to run the UPDATE as its own transaction.

Other

innodb_flush_log_at_trx_commit:

Default is 1, which is secure, but leads to at least one IOPs for each transaction.

2 leads to a flush once a second.  During intense times, this is much more efficient.  But a crash could lose up to one second's worth of updates.  the inaccuracy of "view count" due to a rare crash is, in my opinion, acceptable.

KEY(views) needs to be updated every time views is changed.  But, thanks to the "change buffer", this is unlikely to involve any extra I/O, at least now while you are doing the UPDATE.

INT(1) takes 4 bytes; the (1) has no meaning.  Suggest changing to TINYINT (1 byte), thereby saving about 27 bytes per row.  (7 columns plus 2 indexes)

country INT(1) -- Is it a flag?  What is the meaning?  Is it normalized to another table?  Using 4 bytes for an id and an extra table when standard abbreviations ('US', 'UK', 'RU', 'IN', etc) would take 2 bytes?  Suggest country CHAR(2) CHARACTER SET ascii COLLATE ascii_general_ci.

Indexing flags rarely benefits.  Let's see the queries where you think such indexes might be used.  And the EXPLAIN SELECT ... for them.

Body:
I have 2 MySQL UPDATE Query problem on my website.

Problem 1

I run a content site that updates page views for posts when users read.

Each time I send push notifications, my server times out; when I comment on the Update query that increments the page views, everything returns to normal.

This I think maybe as a result of hundreds of UPDATE query trying to update the views on the same row.

**The query that updated the tablename**

update table set views='$newview' where id=1

Query Explain

id: 1
select_type: SIMPLE
table: new_jobs
type: range
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: NULL
rows: 1
Extra: Using where

**tablename create table**

CREATE TABLE `tablename` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `company_id` int(11) DEFAULT NULL,
 `job_title` varchar(255) DEFAULT NULL,
 `slug` varchar(255) DEFAULT NULL,
 `advert_date` date DEFAULT NULL,
 `expiry_date` date DEFAULT NULL,
 `no_deadline` int(1) DEFAULT 0,
 `source` varchar(20) DEFAULT NULL,
 `featured` int(1) DEFAULT 0,
 `views` int(11) DEFAULT 1,
 `email_status` int(1) DEFAULT 0,
 `draft` int(1) DEFAULT 0,
 `created_by` int(11) DEFAULT NULL,
 `show_company_name` int(1) DEFAULT 1,
 `display_application_method` int(1) DEFAULT 0,
 `status` int(1) DEFAULT 1,
 `upload_date` datetime DEFAULT NULL,
 `country` int(1) DEFAULT 1,
 `followers_email_status` int(1) DEFAULT 0,
 `og_img` varchar(255) DEFAULT NULL,
 `old_id` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`),
 KEY `new_jobs_company_id_index` (`company_id`),
 KEY `new_jobs_views_index` (`views`),
 KEY `new_jobs_draft_index` (`draft`),
 KEY `new_jobs_country_index` (`country`)
) ENGINE=InnoDB AUTO_INCREMENT=151359 DEFAULT CHARSET=utf8

What is the best way of handling this?

[Scenario 2 removed on request]

Body:
Scenario 1. I would expect the update of a 'view' count (or 'click' or 'like' or whatever) to be more like

UPDATE t SET views = views + 1 WHERE id = 123;

I assume you have an index (probably the PRIMARY KEY) on id?

Since there are other things going on with that table, it may be wise to split off the rapidly incrementing counter into a separate table.  This would avoid interfering with other queries.  You can get other data, plus the counter, by using JOIN .. USING(id).

Scenario 2 does not make sense.  It seems to keep the latest date for each email, but what does country mean?  Since it seems like more than just a counter, you might want a separate table to log those 3 columns.

Please provide SHOW CREATE TABLE.

There are many things that novices perceive as a "crash".  Please describe further -- out of connections, out of disk space, sluggishness, the client gave error message, other operations taking too long, etc.  Each has a different remedy.

Query

Are you are currently logically doing

BEGIN;
$ct = SELECT views ... FOR UPDATE;
...
UPDATE ... SET views = $ct+1 WHERE ...;
COMMIT;

If so, that is much less efficient than

(with autocommit = ON)
UPDATE ... SET views = views+1 ...;

Note that the first version hangs onto the row longer.  If you fail to use FOR UPDATE, you will drop some counts.

Splitting into a separate table sort of forces you to run the UPDATE as its own transaction.

Other

innodb_flush_log_at_trx_commit:

Default is 1, which is secure, but leads to at least one IOPs for each transaction.

2 leads to a flush once a second.  During intense times, this is much more efficient.  But a crash could lose up to one second's worth of updates.  the inaccuracy of "view count" due to a rare crash is, in my opinion, acceptable.

KEY(views) needs to be updated every time views is changed.  But, thanks to the "change buffer", this is unlikely to involve any extra I/O, at least now while you are doing the UPDATE.

INT(1) takes 4 bytes; the (1) has no meaning.  Suggest changing to TINYINT (1 byte), thereby saving about 27 bytes per row.  (7 columns plus 2 indexes)

country INT(1) -- Is it a flag?  What is the meaning?  Is it normalized to another table?  Using 4 bytes for an id and an extra table when standard abbreviations ('US', 'UK', 'RU', 'IN', etc) would take 2 bytes?  Suggest country CHAR(2) CHARACTER SET ascii COLLATE ascii_general_ci.

Indexing flags rarely benefits.  Let's see the queries where you think such indexes might be used.  And the EXPLAIN SELECT ... for them.


问:
two event processor hosts registered on the same event hub
I'm new on Azure services and I'm trying to learn the Event Hub.
I want to use the Event Hub as a fifo queue across multiple consumer. But I have some problems with lease management.
I have deployed two instances of my eph and I want use the same consumer group.
First of all I try the solution with only one instance and it's ok.
When I deploy the event processor host on another machine, I see that the first one eph loses the connection

```<code>com.microsoft.azure.eventhubs.ReceiverDisconnectedException
</code>```

Is It correct that two event processor hosts read from the same consumer group? Or this is the problem?
Can you suggest me any idea to approach or any improvement?

Thank you in advance!

答:
When you deploy second processor host, it will attempt to own half of the leases for load balancing purpose. During balancing attempt, it is OK for other host to observe some intermittent failures like LeaseLostExceptions and ReceiverDisconnectedExceptions. You should not see any failures after couple minutes or after both hosts reach a balanced state.

See https://learn.microsoft.com/en-us/azure/event-hubs/event-hubs-event-processor-host for more details.

Body:
I'm new on Azure services and I'm trying to learn the Event Hub.
I want to use the Event Hub as a fifo queue across multiple consumer. But I have some problems with lease management.
I have deployed two instances of my eph and I want use the same consumer group.
First of all I try the solution with only one instance and it's ok.
When I deploy the event processor host on another machine, I see that the first one eph loses the connection

com.microsoft.azure.eventhubs.ReceiverDisconnectedException

Is It correct that two event processor hosts read from the same consumer group? Or this is the problem?
Can you suggest me any idea to approach or any improvement?

Thank you in advance!


问:
How to, In Python PYGtk GUI, only use once pkexec then being root for the specific command
I'm trying to code something in Python, making Apache stop and start with a GUI application.
Everything works ok, I mean I execute the command (service start or service stop) with subprocess.Popen and call for pkexec as first argument so the user is prompted and can start or stop apache

The problem is, pkexec is runned everytime the user clicks on start or stop apache which is quite normal.
I thought after the first identification, the user would be as root inside my application, but he's not, i'm testing before and after the pkexec command...

Do you think I can find another solution for it ? Should I stick with the password dialog for ever

答:
I'm facing the same problem than you: My python GTK app needs to run commands as root, but using pkexec makes it asking each time for the root password, which is really annoying.

I see two ways to solve that "issue":

1. Run your app with pkexec

That solution would fit more for your case.

Write a shell script which runs your python app with pkexec. With that solution, the user is asked only once, and your app run as root, therefore it doesn't require to use pkexec anymore, and can run any commands.

The downside of this is that you could expect, after a while, that the password is again asked, just in the case an unauthorized person get access to the computer.

2. Split your app

My use case is an installer that ease the life of users by downloading, compiling and installing a software.

The previous solution would work, but I do prefer let the user run the installer, and get asked for the password when it actually hit the "Install" button.

The solution is then to split the app in 2 parts:

The GUI

The "engine" or command executor process

The GUI will run the "engine" using pkexec when it needs to start it (in your case, it would need to run with pkexec only the first time the user clicks the "Start/Stop" button), so that the GUI runs as the user, and the "engine" as root.

Now you need an inter-process communication so that the "engine" can report to the GUI, and the GUI can send commands to the "engine". To do so, the best option would be to use pipes like it is shown in this answer: https://stackoverflow.com/a/3806342/1996540.

Update

I have finally implemented my suggested answer in this project so you can have a look on a working example.


问:
create a resultset of calendar dates
I should use a stored procedure to fill a calendar for 10 years in a SQL database!

Three columns should I fill in with the records: date,weekday or weekend, dayname( monday,...).

Can somebody help me?

答:
USE THIS

```<code>set nocount on

SET DATEFIRST 7;

go
select date,
datename(dw,datepart(dw,date)) Day,
datepart(dw,date) Day,
'Segment' = case
when datepart(dw,date)in (5,6) then 'WEEK_END' else 'Week_day' end
from calenderdate

set nocount off
</code>```

```<code>> set nocount on
>
> select  date,
> substring(cast(datename(dw,datepart(dw,date))as
> varchar(10)),1,3) Day, 'Segment' =
> case   when datepart(dw,date)in (5,6)
> then 'WEEK_END' else 'Week_day' end
> from calenderdate
>
> set nocount off
</code>```

output

1/1/2011    Monday  7   Week_day
1/2/2011    Tuesday 1   Week_day

Title: create a resultset of calendar dates

Body:
USE THIS

set nocount on

SET DATEFIRST 7;

go
select date,
datename(dw,datepart(dw,date)) Day,
datepart(dw,date) Day,
'Segment' = case
when datepart(dw,date)in (5,6) then 'WEEK_END' else 'Week_day' end
from calenderdate

set nocount off

> set nocount on
>
> select  date,
> substring(cast(datename(dw,datepart(dw,date))as
> varchar(10)),1,3) Day, 'Segment' =
> case   when datepart(dw,date)in (5,6)
> then 'WEEK_END' else 'Week_day' end
> from calenderdate
>
> set nocount off

output

1/1/2011    Monday  7   Week_day
1/2/2011    Tuesday 1   Week_day


问:
How to Look-up values in Pandas dataframe
I have a dataframe like this.

```<code>Date        Ticker      Price
2019-03-21    AAPL        100
2019-03-21    GOOG        101
2019-03-21    IBM         102
2019-03-25    AAPL         90
2019-03-25    GOOG         91
2019-03-25    IBM          92
2019-03-27    AAPL        110
2019-03-27    GOOG        111
2019-03-27    IBM         112
</code>```

I am trying to add a column called 'LastPrice' which finds the Ticker's last date price. Dates are not consecutive. Thanks.

```<code>Date        Ticker      Price      LastPrice
2019-03-21    AAPL        100
2019-03-21    GOOG        101
2019-03-21    IBM         102
2019-03-25    AAPL         90            100
2019-03-25    GOOG         91            101
2019-03-25    IBM          92            102
2019-03-27    AAPL        110             90
2019-03-27    GOOG        111             91
2019-03-27    IBM         112             92
</code>```

答:
You can lookup values using many methods, here is one of the easier ways.

Look up the price for AAPL. df["Ticker"]=="AAPL" will return an array of True/False values. True when df["Ticker"] contains "AAPL". df.loc will locate in the dataframe, where the True value in the df["Ticker"]=="AAPL" array corresponds with the row in the dataframe. Thats why you only see rows where df["Ticker"]=="AAPL".

```<code>df # your df

df_AAPL = df.loc[df["Ticker"]=="AAPL"]
</code>```

To get the price, you can use df.loc to locate the price column.

```<code>df_AAPL_price = df_AAPL.loc[:,"Price"]
</code>```

To get the price when "Ticker" == "AAPL" on a certain date (assuming your date is in str), you can use a lambda function and apply it across the columns in the dataframe, hence axis = 1. This function takes in values in the rows and returns True if row["Date"] == "2019-03-27" and row["Ticker"] == "AAPL" else False. Same concept as in point 1, df.loc is used to locate where in the dataframe that True occurs in the array. You can think of it as dataframe = [1,2,3], array = [True, False, True], and match them up, then only take the value if it is True in the array. So, in this case it would be only "1" and "3".

```<code>df_new = df.loc[df.apply(lambda row:True if row["Date"] == "2019-03-27" and row["Ticker"] == "AAPL" else False ,axis=1)]
</code>```

Body:
I have a dataframe like this.

Date        Ticker      Price
2019-03-21    AAPL        100
2019-03-21    GOOG        101
2019-03-21    IBM         102
2019-03-25    AAPL         90
2019-03-25    GOOG         91
2019-03-25    IBM          92
2019-03-27    AAPL        110
2019-03-27    GOOG        111
2019-03-27    IBM         112

I am trying to add a column called 'LastPrice' which finds the Ticker's last date price. Dates are not consecutive. Thanks.

Date        Ticker      Price      LastPrice
2019-03-21    AAPL        100
2019-03-21    GOOG        101
2019-03-21    IBM         102
2019-03-25    AAPL         90            100
2019-03-25    GOOG         91            101
2019-03-25    IBM          92            102
2019-03-27    AAPL        110             90
2019-03-27    GOOG        111             91
2019-03-27    IBM         112             92

Body:
You can lookup values using many methods, here is one of the easier ways.

Look up the price for AAPL. df["Ticker"]=="AAPL" will return an array of True/False values. True when df["Ticker"] contains "AAPL". df.loc will locate in the dataframe, where the True value in the df["Ticker"]=="AAPL" array corresponds with the row in the dataframe. Thats why you only see rows where df["Ticker"]=="AAPL".

df # your df

df_AAPL = df.loc[df["Ticker"]=="AAPL"]

To get the price, you can use df.loc to locate the price column.

df_AAPL_price = df_AAPL.loc[:,"Price"]

To get the price when "Ticker" == "AAPL" on a certain date (assuming your date is in str), you can use a lambda function and apply it across the columns in the dataframe, hence axis = 1. This function takes in values in the rows and returns True if row["Date"] == "2019-03-27" and row["Ticker"] == "AAPL" else False. Same concept as in point 1, df.loc is used to locate where in the dataframe that True occurs in the array. You can think of it as dataframe = [1,2,3], array = [True, False, True], and match them up, then only take the value if it is True in the array. So, in this case it would be only "1" and "3".

df_new = df.loc[df.apply(lambda row:True if row["Date"] == "2019-03-27" and row["Ticker"] == "AAPL" else False ,axis=1)]


问:
WinAppDriver OutLook New Email Elements not found
Trying to mimic (automate) email sending through outlook using WinAppDriver, the "New E-mail" element is recognized and new window opens but on the new Window the "To","CC" etc controls are not recognized. </p>

<p>I suspect the new windows session is not available for the driver. </p>

```<code>try {
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setPlatform(Platform.WIN10);
    //capabilities.setCapability("appTopLevelWindow", "0xBB880A");
    capabilities.setCapability("app", "C:\\Program Files\\Microsoft Office\\Office14\\OUTLOOK.exe");
        outlookSession = new WindowsDriver(new URL("http://127.0.0.1:4723"), capabilities);
            outlookSession.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        newEmail = outlookSession.findElementByName("New E-mail");
        System.out.println("newEmail:::::: " + newEmail);
        newEmail.click();

        outlookSession.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        outlookSession.findElementByName("To").sendKeys("<email>"); (the 'To' element is not recognized.
</code>```

答:
You have to write the code for switching the window from outlook to New email.

```<code>            Thread.Sleep(TimeSpan.FromSeconds(5));
            var allWindowHandles1 = driver.WindowHandles;
            driver.SwitchTo().Window(allWindowHandles1[0]);
</code>```

When ever you have new window then you have to switch the control from one window to other.

Body:
Trying to mimic (automate) email sending through outlook using WinAppDriver, the "New E-mail" element is recognized and new window opens but on the new Window the "To","CC" etc controls are not recognized.

I suspect the new windows session is not available for the driver.

try {
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setPlatform(Platform.WIN10);
    //capabilities.setCapability("appTopLevelWindow", "0xBB880A");
    capabilities.setCapability("app", "C:\\Program Files\\Microsoft Office\\Office14\\OUTLOOK.exe");
        outlookSession = new WindowsDriver(new URL("http://127.0.0.1:4723"), capabilities);
            outlookSession.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        newEmail = outlookSession.findElementByName("New E-mail");
        System.out.println("newEmail:::::: " + newEmail);
        newEmail.click();

        outlookSession.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        outlookSession.findElementByName("To").sendKeys("<email>"); (the 'To' element is not recognized.

Body:
You have to write the code for switching the window from outlook to New email.

            Thread.Sleep(TimeSpan.FromSeconds(5));
            var allWindowHandles1 = driver.WindowHandles;
            driver.SwitchTo().Window(allWindowHandles1[0]);

When ever you have new window then you have to switch the control from one window to other.


问:
Angular How to add a loader animation while Fetch data from API?
I tried to show loader While fetching data from API, how should I achieve this, please help.
as of now if the length of product list is 0 then I'm showing loader bt this is not the proper way

HTML:

```<code><div *ngIf="! CoffeeItemList?.length" class="mt-5 text-center">
     <img src="https://chickenrecipeseasy.top/images/loader.gif"/>
</div>
</code>```

TS:

```<code>constructor(private getDataListingService: DataListingService) {}

ngOnInit(): void {
    this.getGlobalSearchList('');
    this.getAllData();
  }
  getAllData() {
    this.getDataListingService.getAllDataLists().subscribe(value => {
      this.CoffeeItemList = value.data;
    });
  }
  getGlobalSearchList(type) {
    this.CoffeeItemList = [];
    this.getDataListingService.getAllDataLists().subscribe(value => {
      let data = [];
      data = value.data;
      console.log(data);
    }
    });
  }
  getSmartSearchValues(search) {
    if (search === '' ) {
      this.getAllData();
      return false;
    } else {
      this.getGlobalSearchList(this.type);
      this.searchText = this.type;
      }
    this.getDataListingService.searchList(search).subscribe(value => {
      this.CoffeeItemList = value.data;
    });

  }
}
</code>```

答:
with ng if else and finalize pipe like so:

  getSmartSearchValues(search) {
    if (search === '' ) {
      this.getAllData();
      return false;
    } else {
      this.getGlobalSearchList(this.type);
      this.searchText = this.type;
      }
    this.isLoading = true;
    this.getDataListingService.searchList(search).pipe(
    finalize(() => {
      this.isLoading = false;
    })
  ).subscribe(value => {
      this.CoffeeItemList = value.data;
    });

  }
```

<pre class="lang-html prettyprint-override"><code><div *ngIf="!isLoading; else loading" class="mt-5 text-center">
       <img src="https://chickenrecipeseasy.top/images/loader.gif"/>
    </div>
<ng-template #loading>
 Loading...
</ng-template>

</code>```

Body:
I tried to show loader While fetching data from API, how should I achieve this, please help.
as of now if the length of product list is 0 then I'm showing loader bt this is not the proper way

HTML:

TS:

constructor(private getDataListingService: DataListingService) {}

ngOnInit(): void {
    this.getGlobalSearchList('');
    this.getAllData();
  }
  getAllData() {
    this.getDataListingService.getAllDataLists().subscribe(value => {
      this.CoffeeItemList = value.data;
    });
  }
  getGlobalSearchList(type) {
    this.CoffeeItemList = [];
    this.getDataListingService.getAllDataLists().subscribe(value => {
      let data = [];
      data = value.data;
      console.log(data);
    }
    });
  }
  getSmartSearchValues(search) {
    if (search === '' ) {
      this.getAllData();
      return false;
    } else {
      this.getGlobalSearchList(this.type);
      this.searchText = this.type;
      }
    this.getDataListingService.searchList(search).subscribe(value => {
      this.CoffeeItemList = value.data;
    });

  }
}

Body:
with ng if else and finalize pipe like so:

  getSmartSearchValues(search) {
    if (search === '' ) {
      this.getAllData();
      return false;
    } else {
      this.getGlobalSearchList(this.type);
      this.searchText = this.type;
      }
    this.isLoading = true;
    this.getDataListingService.searchList(search).pipe(
    finalize(() => {
      this.isLoading = false;
    })
  ).subscribe(value => {
      this.CoffeeItemList = value.data;
    });

  }

<div *ngIf="!isLoading; else loading" class="mt-5 text-center">
       <img src="https://chickenrecipeseasy.top/images/loader.gif"/>
    </div>
<ng-template #loading>
 Loading...
</ng-template>


问:
Appending items to a list
I want to append items to a list. but only the middle item is added to the list. here is the code I have written. </p>

```<code>while True:
    topping = input("Enter a topping which you want on your pizza: ")
    if topping != "quit":
        toppings = []
        toppings.append(topping)
        print("You have selected " + topping + " as a topping for your pizza")
    else:
        break
print("You have chosen ", end="")
print(toppings, end="")
print(" as toppings for your pizza")
</code>```

答:
Here's what you should do

```<code>toppings = []
while True:
    topping = input("Enter a topping which you want on your pizza: ")
    if topping != "quit":
        toppings.append(topping)
        print("You have selected " + topping + " as a topping for your pizza")
    else:
        break
print("You have chosen ", end="")
print(toppings, end="")
print(" as toppings for your pizza")
</code>```

Since toppings was declared inside the loop, it was being initialised to an empty list at every iteration

Title: Appending items to a list

Body:
I want to append items to a list. but only the middle item is added to the list. here is the code I have written.

while True:
    topping = input("Enter a topping which you want on your pizza: ")
    if topping != "quit":
        toppings = []
        toppings.append(topping)
        print("You have selected " + topping + " as a topping for your pizza")
    else:
        break
print("You have chosen ", end="")
print(toppings, end="")
print(" as toppings for your pizza")

Body:
Here's what you should do

toppings = []
while True:
    topping = input("Enter a topping which you want on your pizza: ")
    if topping != "quit":
        toppings.append(topping)
        print("You have selected " + topping + " as a topping for your pizza")
    else:
        break
print("You have chosen ", end="")
print(toppings, end="")
print(" as toppings for your pizza")

Since toppings was declared inside the loop, it was being initialised to an empty list at every iteration


问:
Need to Convert Array Output to String Outside of a For Loop
I'm trying to practice with arrays in prep for my Java SE 11 test and I need help getting my random name generator to work. Right now, I'm not concerned about the name being "valid" (a truly random name like Xvtwg is fine).

I have built a loop where a random value between 3 and 10 is generated (length of name) and then a random index between 0 and 25 is chosen for each loop pass to grab a random letter of the alphabet. All of this works, and I am able to take the output array from the loop and turn it into a concatenated string in the loop. The problem occurs later when I need to call the local variable nameFinal as a value for the set function.

I have tried to declare the output string both inside and outside the loop but both ways I return "nameFinal cannot be resolved to a variable." I have also tried moving my output array outside of the loop (and redefining its output), but return the same variable."

I added in a try/catch block to try to illustrate this issue better. Here is my code:

```<code>
public class Tester {
    public static void main(String[] args) {
        //Build random values
        Random rand = new Random();

        //Name random index 3-10 char
        int nmax = 10;
        int nmin = 3;
        int rand1 = (int)(Math.random() * (nmax - nmin + 1) + nmin);
        //Create random name from total number of letters
        //Define Array of letters
        String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
        //Create random index to pull a random letter over the length of the random index
        int lmax = 25;
        int lmin = 0;
        //I have also tried declaring newName and nameFinal here
        for(int i = 0; i <= rand1; i++) {
            int randl = (int)(Math.random() * (lmax - lmin + 1) + lmin);
            String[] newName;
            newName[i] = letters[i];
            String nameFinal = Arrays.toString(newName);
        }
        //Concatenate array of random letters into a "name"
        try{
            String nameFinal = Arrays.toString(newName);
            System.out.println(nameFinal);
        }catch(Exception e) {
            e.PrintStackTrace()
        }
        //Implementation omitted
    }
}
</code>```

答:
I have changed your code a bit. Hope this will help you!</p>
```<code>public static void main(String[] args) {
    //Build random values
    Random rand = new Random();
    Test test = new Test();
    test.randomName();
    test.createAge();
    test.createSSN();
}

//Name random index 3-10 char
public void randomName() {
    int nmax = 10;
    int nmin = 3;
    int rand1 = (int)(Math.random() * (nmax - nmin + 1) + nmin);
    //Create random name from total number of letters
    //Define Array of letters
    String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

    //Create random index to pull a random letter over the length of the random index
    int lmax = 25;
    int lmin = 0;

    ArrayList<String> name = new ArrayList<>(5);
    for(int i = 0; i <= rand1; i++) {
        int randl = (int)(Math.random() * (lmax - lmin + 1) + lmin);
        name.add(letters[rand1]);
    }
    System.out.println(name.toString());
}

//Age random number between 1 and 100
private void createAge(){
    int amax = 100;
    int amin = 1;
    int rand2 = (int)(Math.random() * (amax - amin + 1) + amin);
}

//SSN random 9 digit number
private void createSSN(){
    int smax = 999999999;
    int smin = 100000000;
    int rand3 = (int)(Math.random() * (smax - smin + 1) + smin);
}

}
</code>```

Body:
I'm trying to practice with arrays in prep for my Java SE 11 test and I need help getting my random name generator to work. Right now, I'm not concerned about the name being "valid" (a truly random name like Xvtwg is fine).

I have built a loop where a random value between 3 and 10 is generated (length of name) and then a random index between 0 and 25 is chosen for each loop pass to grab a random letter of the alphabet. All of this works, and I am able to take the output array from the loop and turn it into a concatenated string in the loop. The problem occurs later when I need to call the local variable nameFinal as a value for the set function.

I have tried to declare the output string both inside and outside the loop but both ways I return "nameFinal cannot be resolved to a variable." I have also tried moving my output array outside of the loop (and redefining its output), but return the same variable."

I added in a try/catch block to try to illustrate this issue better. Here is my code:

public class Tester {
    public static void main(String[] args) {
        //Build random values
        Random rand = new Random();

        //Name random index 3-10 char
        int nmax = 10;
        int nmin = 3;
        int rand1 = (int)(Math.random() * (nmax - nmin + 1) + nmin);
        //Create random name from total number of letters
        //Define Array of letters
        String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
        //Create random index to pull a random letter over the length of the random index
        int lmax = 25;
        int lmin = 0;
        //I have also tried declaring newName and nameFinal here
        for(int i = 0; i <= rand1; i++) {
            int randl = (int)(Math.random() * (lmax - lmin + 1) + lmin);
            String[] newName;
            newName[i] = letters[i];
            String nameFinal = Arrays.toString(newName);
        }
        //Concatenate array of random letters into a "name"
        try{
            String nameFinal = Arrays.toString(newName);
            System.out.println(nameFinal);
        }catch(Exception e) {
            e.PrintStackTrace()
        }
        //Implementation omitted
    }
}

Body:
I have changed your code a bit. Hope this will help you!

public static void main(String[] args) {
    //Build random values
    Random rand = new Random();
    Test test = new Test();
    test.randomName();
    test.createAge();
    test.createSSN();
}

//Name random index 3-10 char
public void randomName() {
    int nmax = 10;
    int nmin = 3;
    int rand1 = (int)(Math.random() * (nmax - nmin + 1) + nmin);
    //Create random name from total number of letters
    //Define Array of letters
    String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

    //Create random index to pull a random letter over the length of the random index
    int lmax = 25;
    int lmin = 0;

    ArrayList<String> name = new ArrayList<>(5);
    for(int i = 0; i <= rand1; i++) {
        int randl = (int)(Math.random() * (lmax - lmin + 1) + lmin);
        name.add(letters[rand1]);
    }
    System.out.println(name.toString());
}

//Age random number between 1 and 100
private void createAge(){
    int amax = 100;
    int amin = 1;
    int rand2 = (int)(Math.random() * (amax - amin + 1) + amin);
}

//SSN random 9 digit number
private void createSSN(){
    int smax = 999999999;
    int smin = 100000000;
    int rand3 = (int)(Math.random() * (smax - smin + 1) + smin);
}

}


问:
Configuring the application in one place
I have an application in React Native that I build and publish through AppCenter

Android

iOS

At the moment package and Bundle Id have been defined separately for Android and iOS

The situation is similar with application versioning for both systems. I have to do it separately

Is there any way to configure in one file?

I know there is an app.json file but in every project I see it looks like this:

```<code>{
  "name": "nameapp",
  "displayName": "NameApp"
}
</code>```

Only when someone uses Expo is additional information

I want to point out here that I don't use Expo

答:
use the react-native-rename npm package.

Install using

```<code>npm install react-native-rename -g
</code>```

Then from the root of your React Native project execute the following

```<code>react-native-rename "MyApp" -b com.mycompany.myapp
</code>```

Body:
I have an application in React Native that I build and publish through AppCenter

Android

iOS

At the moment package and Bundle Id have been defined separately for Android and iOS

The situation is similar with application versioning for both systems. I have to do it separately

Is there any way to configure in one file?

I know there is an app.json file but in every project I see it looks like this:

{
  "name": "nameapp",
  "displayName": "NameApp"
}

Only when someone uses Expo is additional information

I want to point out here that I don't use Expo

Body:
use the react-native-rename npm package.

Install using

npm install react-native-rename -g

Then from the root of your React Native project execute the following

react-native-rename "MyApp" -b com.mycompany.myapp


问:
How can I split a string and get just key part with regexp?
I have a string like <code>"A < -5.9 AND B >= 6 OR (C < 3)"</code> I have to get keys part.(A,B,C). So I thought I should split first AND and OR then I should get key part? Could you help me? I wrote just A,B,C but in my real example A can be any string. The important thing is that is value on the right side of
<,>,<=,>=  </p>

答:
Simplest way would be to split using a regex:</p>

```<code>"A < -5.9 AND B >= 6 OR (C < 3)".split(/ AND | OR /);

// ["A < -5.9", "B >= 6", "(C < 3)"]
</code>```

Body:
I have a string like "A < -5.9 AND B >= 6 OR (C < 3)" I have to get keys part.(A,B,C). So I thought I should split first AND and OR then I should get key part? Could you help me? I wrote just A,B,C but in my real example A can be any string. The important thing is that is value on the right side of
<,>,<=,>=

Body:
Simplest way would be to split using a regex:

"A < -5.9 AND B >= 6 OR (C < 3)".split(/ AND | OR /);

// ["A < -5.9", "B >= 6", "(C < 3)"]


答:
First, declare in component.ts - showLoader default false.

```<code>getAllData() {
    this.showLoader = true;
    this.getDataListingService.getAllDataLists().subscribe(value => {
      this.CoffeeItemList = value.data;
      this.showLoader = false;
    });
  }
</code>```

```<code><div *ngIf="showLoader" class="mt-5 text-center">
       <img src="https://chickenrecipeseasy.top/images/loader.gif"/>
    </div>
</code>```

Last where you show data *ngIf="!showLoader" add this condition.

Title: Angular How to add a loader animation while Fetch data from API?

Body:
First, declare in component.ts - showLoader default false.

getAllData() {
    this.showLoader = true;
    this.getDataListingService.getAllDataLists().subscribe(value => {
      this.CoffeeItemList = value.data;
      this.showLoader = false;
    });
  }

<div *ngIf="showLoader" class="mt-5 text-center">
       <img src="https://chickenrecipeseasy.top/images/loader.gif"/>
    </div>

Last where you show data *ngIf="!showLoader" add this condition.


问:
How do I recover from failure when uploading multiple files via my server to S3?
New to NodeJS and S3, I wrote the following exploratory code to upload files to S3 via my NodeJS server without saving the file to disk or memory:

```<code>var express = require('express');
var Busboy = require('busboy');
var S3 = require('../utils/s3Util');
var router = express.Router(); // mounted at /uploads

router.post("/", function (req, res, next) {
    let bb = new Busboy({ headers: req.headers });
    const uploads = [];
    bb.on('file', (fieldname, stream, filename, encoding, mimeType) => {
        console.log(`Uploaded fieldname: ${fieldname}; filename: ${filename}, mimeType: ${mimeType}`);
        uploads.push(S3.svc.upload({ Bucket: 'my-test-bucket', Key: filename, Body: stream }).promise());
    });
    bb.on('finish', () => {
        console.log("# of promises:", uploads.length);
        Promise.all(uploads).then(retVals => {
            for (let i = 0; retVals && i < retVals.length; i++) {
                console.log(`File ${i + 1}::`, retVals[i]);
            }
            res.end();
        }).catch(err => {
            console.log("Error::", err);
            res.status(500).send(`${err.name}: ${err.message}`);
        });
    });
    req.pipe(bb);
});

module.exports = router;
</code>```

In the general failure case, how do I handle the scenario where the upload of 1 or more of x files being uploaded fails? Some uploads would have succeeded, some would have failed. However, in the catch clause I wouldn't know which ones have failed...

It would be good to be able to make this upload process somewhat transactional (i.e., either all uploads succeed, or none do). When errors happen, ideally I would be able to "rollback" the subset of successful uploads.

答:
You could do it like this:

Push an object into uploads, with the data you need to retry, so:

```<code>uploads.push({
  fieldname,
  filename,
  mimeType,
  uploaded: S3.svc.upload({ Bucket: 'my-test-bucket', Key: filename, Body: stream })
    .promise()
    .then(() => true)
    .catch(() => false)
});

...

const failed = await
  (Promise.all(uploads.map(async upload => ({...upload, uploaded: await upload.uploaded})))).then(u => u.filter(upload => !upload.uploaded))

const failedFiles = failed.join(', ')

console.log(`The following files failed to upload: ${failedFiles}`);
</code>```

You need to make your event handlers async to use await inside them, so, for example:

```<code>bb.on('file', async (fieldname, stream, filename, encoding, mimeType) => {
</code>```

Body:
New to NodeJS and S3, I wrote the following exploratory code to upload files to S3 via my NodeJS server without saving the file to disk or memory:

var express = require('express');
var Busboy = require('busboy');
var S3 = require('../utils/s3Util');
var router = express.Router(); // mounted at /uploads

router.post("/", function (req, res, next) {
    let bb = new Busboy({ headers: req.headers });
    const uploads = [];
    bb.on('file', (fieldname, stream, filename, encoding, mimeType) => {
        console.log(`Uploaded fieldname: ${fieldname}; filename: ${filename}, mimeType: ${mimeType}`);
        uploads.push(S3.svc.upload({ Bucket: 'my-test-bucket', Key: filename, Body: stream }).promise());
    });
    bb.on('finish', () => {
        console.log("# of promises:", uploads.length);
        Promise.all(uploads).then(retVals => {
            for (let i = 0; retVals && i < retVals.length; i++) {
                console.log(`File ${i + 1}::`, retVals[i]);
            }
            res.end();
        }).catch(err => {
            console.log("Error::", err);
            res.status(500).send(`${err.name}: ${err.message}`);
        });
    });
    req.pipe(bb);
});

module.exports = router;

In the general failure case, how do I handle the scenario where the upload of 1 or more of x files being uploaded fails? Some uploads would have succeeded, some would have failed. However, in the catch clause I wouldn't know which ones have failed...

It would be good to be able to make this upload process somewhat transactional (i.e., either all uploads succeed, or none do). When errors happen, ideally I would be able to "rollback" the subset of successful uploads.

Body:
You could do it like this:

Push an object into uploads, with the data you need to retry, so:

uploads.push({
  fieldname,
  filename,
  mimeType,
  uploaded: S3.svc.upload({ Bucket: 'my-test-bucket', Key: filename, Body: stream })
    .promise()
    .then(() => true)
    .catch(() => false)
});

...

const failed = await
  (Promise.all(uploads.map(async upload => ({...upload, uploaded: await upload.uploaded})))).then(u => u.filter(upload => !upload.uploaded))

const failedFiles = failed.join(', ')

console.log(`The following files failed to upload: ${failedFiles}`);

You need to make your event handlers async to use await inside them, so, for example:

bb.on('file', async (fieldname, stream, filename, encoding, mimeType) => {