问:
Check if elements from array are in a string
I want to check if there is one of my elements in my array in an string
Like: ['12', '13', '14'] is my array and my string is '123456789' and if one of my Array elements is in my string then it should be True

Is there a way to do this?

答:
here is simple solution using in operator.
Steps -

Iterating over each element of an array.

Checking whether element is present or Not.

If present the print True and break.

```<code>l = ['12','13','14']
s = '123456789'

for i in l:
    if i in s:
        print(True)
        break;
</code>```

Body:
here is simple solution using in operator.
Steps -

Iterating over each element of an array.

Checking whether element is present or Not.

If present the print True and break.

l = ['12','13','14']
s = '123456789'

for i in l:
    if i in s:
        print(True)
        break;


来源: stackexchange

问:
HttpClient request crashes on a Xamarin Notification Service Extensions iOS
I'm trying to request some data from an API using HttpClient in DidReceiveNotificationRequest method (Xamarin iOS Notification Service Extensions project).

When the GetAsync (HttpClient) the extension just crashes.

Am I doing something wrong?

```<code>public override async void DidReceiveNotificationRequest(UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
{
    ...

    using (HttpClient client = new HttpClient())
    {
        await client.GetAsync("https://google.com").ConfigureAwait(false); // crashes here
    }

    ...
}
</code>```

I also tried to use a NSUrlSessionHandler as the HttpClient handler, but no success.

答:
try use with Uri:

```<code>Uri uri = new Uri(string.Format(client.BaseAddress + resource, string.Empty));
HttpResponseMessage responseMessage = await client.GetAsync(uri);
</code>```

and for iOS need add to .plist - NSLocalNetworkUsageDescription

maybe need add HttpMessageHandler:

```<code> client = new HttpClient(CreateClientHandler()) { BaseAddress = new Uri($"https://{Address}:5001") };
....

private HttpClientHandler CreateClientHandler()
    {
       return new HttpClientHandler
       {
           ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
       };
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to request some data from an API using HttpClient in DidReceiveNotificationRequest method (Xamarin iOS Notification Service Extensions project).

When the GetAsync (HttpClient) the extension just crashes.

Am I doing something wrong?

public override async void DidReceiveNotificationRequest(UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
{
    ...

    using (HttpClient client = new HttpClient())
    {
        await client.GetAsync("https://google.com").ConfigureAwait(false); // crashes here
    }

    ...
}

I also tried to use a NSUrlSessionHandler as the HttpClient handler, but no success.

Body:
try use with Uri:

Uri uri = new Uri(string.Format(client.BaseAddress + resource, string.Empty));
HttpResponseMessage responseMessage = await client.GetAsync(uri);

and for iOS need add to .plist - NSLocalNetworkUsageDescription

maybe need add HttpMessageHandler:

 client = new HttpClient(CreateClientHandler()) { BaseAddress = new Uri($"https://{Address}:5001") };
....

private HttpClientHandler CreateClientHandler()
    {
       return new HttpClientHandler
       {
           ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
       };
    }


问:
Vert.x: How to send a post request?
My first Vertx Web app :

I expect To get the index.html at localhost.8080/Test then find a way to retrieve the data, but the page doesn't show

I have a RequestResponseExample class:

```<code>public class RequestResponseExample extends AbstractVerticle {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();

        Router router = Router.router(vertx);

        router.post("/Test").handler(rc -> rc.response().sendFile("index.html"));

        vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
    }

}
</code>```

And My Html Code index.html

  <meta charSet="UTF-8">
  <title>OTP Authenticator Verification Example Page</title>

<form action="/" method="post" encType="multipart/form-data">

    Code:
    <input type="text" name="code"/>

    <input type="submit" value="Submit"/>

</form>

```

答:
I think that you send a GET request, but you handle a POST request to return the html file.
I think firstly you have to handle a GET request that's return the html page, and also write a route for the form.

Title: Vert.x: How to send a post request?

Body:
My first Vertx Web app :

I expect To get the index.html at localhost.8080/Test then find a way to retrieve the data, but the page doesn't show

I have a RequestResponseExample class:

public class RequestResponseExample extends AbstractVerticle {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();

        Router router = Router.router(vertx);

        router.post("/Test").handler(rc -> rc.response().sendFile("index.html"));

        vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
    }

}

And My Html Code index.html

  <meta charSet="UTF-8">
  <title>OTP Authenticator Verification Example Page</title>

<form action="/" method="post" encType="multipart/form-data">

    Code:
    <input type="text" name="code"/>

    <input type="submit" value="Submit"/>

</form>


问:
I have issues when I run laravel project from github
i cloned laravel project from GitHub but when i try to open it by wiring composer install it appeared</p>
```<code>No composer.lock file present. Updating dependencies to latest instead of installing from lock file. See https://getcomposer.org/install for more information.

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires fzaninotto/faker ^1.7 -> satisfiable by fzaninotto/faker[v1.7.0, ..., v1.9.2].
    - fzaninotto/faker[v1.7.0, ..., v1.9.2] require php ^5.3.3 || ^7.0 -> your php version (8.0.13) does not satisfy that requirement.
  Problem 2
    - phpunit/phpunit[5.7.0, ..., 5.7.27] require php ^5.6 || ^7.0 -> your php version (8.0.13) does not satisfy that requirement.
    - Root composer.json requires phpunit/phpunit ~5.7 -> satisfiable by phpunit/phpunit[5.7.0, ..., 5.7.27].
</code>```

答: try run composer update if not working you need to upgrade composer</p>

Body:
i cloned laravel project from GitHub but when i try to open it by wiring composer install it appeared

No composer.lock file present. Updating dependencies to latest instead of installing from lock file. See https://getcomposer.org/install for more information.

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires fzaninotto/faker ^1.7 -> satisfiable by fzaninotto/faker[v1.7.0, ..., v1.9.2].
    - fzaninotto/faker[v1.7.0, ..., v1.9.2] require php ^5.3.3 || ^7.0 -> your php version (8.0.13) does not satisfy that requirement.
  Problem 2
    - phpunit/phpunit[5.7.0, ..., 5.7.27] require php ^5.6 || ^7.0 -> your php version (8.0.13) does not satisfy that requirement.
    - Root composer.json requires phpunit/phpunit ~5.7 -> satisfiable by phpunit/phpunit[5.7.0, ..., 5.7.27].


问:
How to open mobsf using docker
```<code>

                        ##         .
                  ## ## ##        ==
               ## ## ## ## ##    ===
           /"""""""""""""""""\___/ ===
      ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
           \______ o           __/
             \    \         __/
              \____\_______/

docker is configured to use the default machine with IP 192.168.99.100
For help getting started, check out the docs at https://docs.docker.com

Start interactive shell

laptop@LAPTOP-MDLBUKKN MINGW64 /c/Program Files/Docker Toolbox
$ docker pull opensecurity/mobile-security-framework-mobsf
Using default tag: latest
latest: Pulling from opensecurity/mobile-security-framework-mobsf
d51af753c3d3: Pull complete                                                                                fc878cd0a91c: Pull complete                                                                                6154df8ff988: Pull complete                                                                                fee5db0ff82f: Pull complete                                                                                2147c66bc825: Pull complete                                                                                0adbcd19651f: Pull complete                                                                                c941f22acae2: Pull complete                                                                                2b48d720aadd: Pull complete                                                                                c88c099643b2: Pull complete                                                                                00718adcba2f: Pull complete                                                                                9ec8cb716172: Pull complete                                                                                98b4a4bffe15: Pull complete                                                                                3d492495d95b: Pull complete                                                                                ab0f85fef3b0: Pull complete                                                                                0df7809d4cce: Pull complete                                                                                8aa79076efbd: Pull complete                                                                                Digest: sha256:7be8e3b29f2f3ce92077078ac3b053c3bdb33a627ea07256730e92a0fe20d3cb
Status: Downloaded newer image for opensecurity/mobile-security-framework-mobsf:latest
docker.io/opensecurity/mobile-security-framework-mobsf:latest

laptop@LAPTOP-MDLBUKKN MINGW64 /c/Program Files/Docker Toolbox
$ # Static Analysis Only

laptop@LAPTOP-MDLBUKKN MINGW64 /c/Program Files/Docker Toolbox
$ docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
[2020-05-01 03:06:02 +0000] [1] [INFO] Starting gunicorn 20.0.4
[2020-05-01 03:06:02 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2020-05-01 03:06:02 +0000] [1] [INFO] Using worker: threads
[2020-05-01 03:06:02 +0000] [7] [INFO] Booting worker with pid: 7
</code>```

How to open mobsf using docker , I have typed some commands , and any mistakes I have made? I still can't open ,dunno know how to open it ..please tell me the solution of the question , thanks !

答:
You can run docker instance of mobsf via the prebuilt image using below commands

```<code>docker pull opensecurity/mobile-security-framework-mobsf
docker run -it --rm -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
</code>```

For more options for running mobsf docker, please view official documentation here

Title: How to open mobsf using docker

Body:
                        ##         .
                  ## ## ##        ==
               ## ## ## ## ##    ===
           /"""""""""""""""""\___/ ===
      ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
           \______ o           __/
             \    \         __/
              \____\_______/

docker is configured to use the default machine with IP 192.168.99.100
For help getting started, check out the docs at https://docs.docker.com

Start interactive shell

laptop@LAPTOP-MDLBUKKN MINGW64 /c/Program Files/Docker Toolbox
$ docker pull opensecurity/mobile-security-framework-mobsf
Using default tag: latest
latest: Pulling from opensecurity/mobile-security-framework-mobsf
d51af753c3d3: Pull complete                                                                                fc878cd0a91c: Pull complete                                                                                6154df8ff988: Pull complete                                                                                fee5db0ff82f: Pull complete                                                                                2147c66bc825: Pull complete                                                                                0adbcd19651f: Pull complete                                                                                c941f22acae2: Pull complete                                                                                2b48d720aadd: Pull complete                                                                                c88c099643b2: Pull complete                                                                                00718adcba2f: Pull complete                                                                                9ec8cb716172: Pull complete                                                                                98b4a4bffe15: Pull complete                                                                                3d492495d95b: Pull complete                                                                                ab0f85fef3b0: Pull complete                                                                                0df7809d4cce: Pull complete                                                                                8aa79076efbd: Pull complete                                                                                Digest: sha256:7be8e3b29f2f3ce92077078ac3b053c3bdb33a627ea07256730e92a0fe20d3cb
Status: Downloaded newer image for opensecurity/mobile-security-framework-mobsf:latest
docker.io/opensecurity/mobile-security-framework-mobsf:latest

laptop@LAPTOP-MDLBUKKN MINGW64 /c/Program Files/Docker Toolbox
$ # Static Analysis Only

laptop@LAPTOP-MDLBUKKN MINGW64 /c/Program Files/Docker Toolbox
$ docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
[2020-05-01 03:06:02 +0000] [1] [INFO] Starting gunicorn 20.0.4
[2020-05-01 03:06:02 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2020-05-01 03:06:02 +0000] [1] [INFO] Using worker: threads
[2020-05-01 03:06:02 +0000] [7] [INFO] Booting worker with pid: 7

How to open mobsf using docker , I have typed some commands , and any mistakes I have made? I still can't open ,dunno know how to open it ..please tell me the solution of the question , thanks !

Body:
You can run docker instance of mobsf via the prebuilt image using below commands

docker pull opensecurity/mobile-security-framework-mobsf
docker run -it --rm -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest

For more options for running mobsf docker, please view official documentation here


问:
Python - Plotting histogram of a for loop for dice rolls
I am trying to plot a histogram for the sum of 20 dice rolls when the simulation is ran 1000 times.

```<code>def dice(n):
total = 0
for i in range(1000):
    total += random.randint(1, 6)
    plt.hist(total)
    plt.title('Outcome of 20 Rolls')
return total
</code>```

I would really appreciate some help. Thanks.

答:
Try this:</p>
```<code>def main():
    import random
    import matplotlib.pyplot as plt
    import numpy as np
    #create a list of 20 random numbers between 1 and 6
    dice_rolls = []
    for i in range(1000):
        dice_rolls.append(sum(random.sample(range(1,7),20)))
    #plot a histogram of the list
    plt.hist(dice_rolls,bins=range(2,38))
    plt.xlabel('Sum of 20 dice rolls')
    plt.ylabel('Frequency')
    plt.title('Histogram of Sum of 20 dice rolls')
    plt.show()
</code>```

Body:
I am trying to plot a histogram for the sum of 20 dice rolls when the simulation is ran 1000 times.

def dice(n):
total = 0
for i in range(1000):
    total += random.randint(1, 6)
    plt.hist(total)
    plt.title('Outcome of 20 Rolls')
return total

I would really appreciate some help. Thanks.

Body:
Try this:

def main():
    import random
    import matplotlib.pyplot as plt
    import numpy as np
    #create a list of 20 random numbers between 1 and 6
    dice_rolls = []
    for i in range(1000):
        dice_rolls.append(sum(random.sample(range(1,7),20)))
    #plot a histogram of the list
    plt.hist(dice_rolls,bins=range(2,38))
    plt.xlabel('Sum of 20 dice rolls')
    plt.ylabel('Frequency')
    plt.title('Histogram of Sum of 20 dice rolls')
    plt.show()


问:
Make HTML element disappear with CSS animation
I want to know if there is a way to make an HTML element disappear with an animation of CSS. So when the element gets removed from the page by some script, an animation shall display before the element actually gets removed.

Is this possible in an easy way? Or do I need to set a timer to my script that starts the animation with a duration of X and removes the element after time X?

答:
```<code>transition: .5s;
</code>```

invisible:

```<code>opacity: 0;
</code>```

visible:

```<code>opacity: 1;
</code>```

transition will make it appear and disappear smoothly.

ContentLicense: CC BY-SA 3.0

Body:
transition: .5s;

invisible:

opacity: 0;

visible:

opacity: 1;

transition will make it appear and disappear smoothly.


问:
How to get the every week by google spread sheet
I want to have date of every weeks.

I put 07/02/2022 in F5 cell and put =EDATE(F5 + 7) in G5 cell

But N/A comes in G5

I guess maybe I put 07/02/2022 in F5 in a wrong way..

What should I do?

答:
read the error message:

Wrong number of arguments to EDATE. Expected 2 arguments, but got 1 arguments.

correct G5 to =EDATE(F5,7)

In case you refer to tomorrow's date, that is 2/7/2022.
You are, if you read the help, adding 7 months with the command above.


问:
Subdomain to point to subdirectory of main site?
I have my website running at:

www.example.com

I also have this other domain:

www.example.net

Is it possible to point "www.example.net" to a subdirectory of "www.example.com"? For example:

www.example.net-> www.example.com/other

?

It's not just a redirect, I need to serve the pages and see "www.example.net" in the user's browser.

What do you think?

We use IIS7 and everything is ASP.NET (aspx pages, ascx controls, etc).

答:
You're looking at two methods for this:

URL rewriter

Server.Execute method

The first is a httpmodule that silently redirects the request without changing the url in the address bar, the second is a method you can call within aspx code. I think the latter is only good though if you're working in the same application, so I would go with the URL rewriter.

There is an official iis7 URL rewriter available on www.iis.net afaik.

-Oisin

OwnerDisplayName: AnonUser

ContentLicense: CC BY-SA 2.5


问:
how to count the num of ports in docker ps cmd?
```<code>docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                           NAMES
f56084659b2a        nginx:alpine        "/docker-entrypoint.…"   35 seconds ago      Up 33 seconds       0.0.0.0:3456->3456/tcp, 0.0.0.0:38080->80/tcp   xenodochial_perlman
</code>```

what is the cmd to actually count num of ports from PORTS column in 1 line?

答:
Using inspect :

```<code>docker inspect -f "{{len .NetworkSettings.Ports}}" f56084659b2a
</code>```

Body:
docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                           NAMES
f56084659b2a        nginx:alpine        "/docker-entrypoint.…"   35 seconds ago      Up 33 seconds       0.0.0.0:3456->3456/tcp, 0.0.0.0:38080->80/tcp   xenodochial_perlman

what is the cmd to actually count num of ports from PORTS column in 1 line?

Body:
Using inspect :

docker inspect -f "{{len .NetworkSettings.Ports}}" f56084659b2a


问:
Add + 1 every multiple of 10 in C#
I'm making an endless runner game with Unity and in this game for every 10 coins I collect, it increases the level by 1 with a maximum of 10. Currently, I'm doing this:

```<code>IF(coins >= 10 and coins < 20) level = 2
IF(coins >= 20 and coins <= 30) level = 3
</code>```

and so on till level 10.

But I'm sure that this code is badly written, I'm thinking in use the for statement but I'm a newbie to C#, any ideas?

答:
try this</p>
```<code>var level = coins < 90 ? (coins / 10 + 1) : 10;
</code>```

Title: Add + 1 every multiple of 10 in C#

Body:
I'm making an endless runner game with Unity and in this game for every 10 coins I collect, it increases the level by 1 with a maximum of 10. Currently, I'm doing this:

IF(coins >= 10 and coins < 20) level = 2
IF(coins >= 20 and coins <= 30) level = 3

and so on till level 10.

But I'm sure that this code is badly written, I'm thinking in use the for statement but I'm a newbie to C#, any ideas?

Body:
try this

var level = coins < 90 ? (coins / 10 + 1) : 10;


问:
How to pass SwiftUI View as function parameter?
I want to show SwiftUI Views as subview of a UIViewController.  These views must implement a protocol.

I have this:

```<code>protocol ContentViewProtocol : View
{
    var values: [CGFloat] { get }
}

...

import SwiftUI

struct SearchContentView : ContentViewProtocol
{
    var values: [CGFloat] = [0.5, 0.7]

    var body: some View
    {
        VStack
        {
            ...
        }
    }
}

...

func showContent(view: ContentViewProtocol) <=== ERROR
{
    var child = UIHostingController(rootView: view) <=== SAME ERROR

    ...
}
</code>```

I get the following error: Protocol 'ContentViewProtocol' can only be used as a generic constraint because it has Self or associated type requirements

I get the same error when using a plain View as function parameter type (so with func showContent(view: View)).

How can I prevent this?

答:
You can do what the error says, and use ContentViewProtocol as a generic constraint. Make showContent generic:

```<code>func showContent<V: ContentViewProtocol>(view: V)
{
    let child = UIHostingController(rootView: view)
    ...
}
</code>```

Body:
I want to show SwiftUI Views as subview of a UIViewController.  These views must implement a protocol.

I have this:

protocol ContentViewProtocol : View
{
    var values: [CGFloat] { get }
}

...

import SwiftUI

struct SearchContentView : ContentViewProtocol
{
    var values: [CGFloat] = [0.5, 0.7]

    var body: some View
    {
        VStack
        {
            ...
        }
    }
}

...

func showContent(view: ContentViewProtocol) <=== ERROR
{
    var child = UIHostingController(rootView: view) <=== SAME ERROR

    ...
}

I get the following error: Protocol 'ContentViewProtocol' can only be used as a generic constraint because it has Self or associated type requirements

I get the same error when using a plain View as function parameter type (so with func showContent(view: View)).

How can I prevent this?

Body:
You can do what the error says, and use ContentViewProtocol as a generic constraint. Make showContent generic:

func showContent<V: ContentViewProtocol>(view: V)
{
    let child = UIHostingController(rootView: view)
    ...
}


问:
An error, "failed to solve with frontend dockerfile.v0"
I was trying to build my Docker image for my Gatsby application. Whenever I run the command docker build . -t gatsbyapp, it gives me an error:

failed to solve with frontend dockerfile.v0: failed to build LLB:
failed to compute cache key: "/.env" not found: not found
```
<p>Meanwhile my Dockerfile is shown below:</p>
<pre class="lang-none prettyprint-override"><code>FROM node:13

WORKDIR /app

COPY package.json .

RUN yarn global add gatsby-cli

RUN yarn install

COPY gatsby-config.js .

COPY .env .

EXPOSE 8000

CMD ["gatsby","develop","-H","0.0.0.0"]
</code>```

答:
In case you previously executed docker buildx install, your docker command is aliased to docker buildx, which is based on Docker Buildkit, which is currently not supported (sadly) for Windows containers.

To remove the alias, execute the following command:

```<code>docker buildx uninstall
</code>```

I hope that will save time to people like me, who forgot about this alias

Body:
I was trying to build my Docker image for my Gatsby application. Whenever I run the command docker build . -t gatsbyapp, it gives me an error:

failed to solve with frontend dockerfile.v0: failed to build LLB:
failed to compute cache key: "/.env" not found: not found

Meanwhile my Dockerfile is shown below:

FROM node:13

WORKDIR /app

COPY package.json .

RUN yarn global add gatsby-cli

RUN yarn install

COPY gatsby-config.js .

COPY .env .

EXPOSE 8000

CMD ["gatsby","develop","-H","0.0.0.0"]

Body:
In case you previously executed docker buildx install, your docker command is aliased to docker buildx, which is based on Docker Buildkit, which is currently not supported (sadly) for Windows containers.

To remove the alias, execute the following command:

docker buildx uninstall

I hope that will save time to people like me, who forgot about this alias


问:
How to pass the Client Id for google authetication in .Net Core 6
I am trying to use a google authentication in .Net Core 6. I have already generated the credentials in google developer console and added in the code.

```<code>
using LoginKud.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<AppDbContext>();

builder.Services.AddAuthentication().AddGoogle(options => {
    options.ClientId = builder.Configuration["591241482908-66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com"];
    options.ClientSecret = builder.Configuration["GOCSPX-jHKaxxxxxxx"];
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();

</code>```

I have provided both client Id and Client Secret Id but I get
The 'ClientId' option must be provided. (Parameter 'ClientId') error
every time I run the program. How can I solve this?

答:
I thing the problem is inside this 2 lines:

```<code>   options.ClientId = builder.Configuration["591241482908-66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com"];
options.ClientSecret = builder.Configuration["GOCSPX-jHKaxxxxxxx"];
</code>```

You should pass there the key from your settings, not the value.

Try to pass values directly for now:

```<code>   options.ClientId = "591241482908 66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com";
   options.ClientSecret = "GOCSPX-jHKaxxxxxxx";
</code>```

And if it helps put in your configuration keys and values, like this:

```<code>"clientId":"591241482908 66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com",
"clientSecret":"GOCSPX-jHKaxxxxxxx"
</code>```

And rewrite your code to:

```<code>options.ClientId = builder.Configuration["clientId"];
options.ClientSecret = builder.Configuration["clientSecret"];
</code>```

Body:
I am trying to use a google authentication in .Net Core 6. I have already generated the credentials in google developer console and added in the code.

using LoginKud.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<AppDbContext>();

builder.Services.AddAuthentication().AddGoogle(options => {
    options.ClientId = builder.Configuration["591241482908-66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com"];
    options.ClientSecret = builder.Configuration["GOCSPX-jHKaxxxxxxx"];
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();

I have provided both client Id and Client Secret Id but I get
The 'ClientId' option must be provided. (Parameter 'ClientId') error
every time I run the program. How can I solve this?

Body:
I thing the problem is inside this 2 lines:

   options.ClientId = builder.Configuration["591241482908-66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com"];
options.ClientSecret = builder.Configuration["GOCSPX-jHKaxxxxxxx"];

You should pass there the key from your settings, not the value.

Try to pass values directly for now:

   options.ClientId = "591241482908 66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com";
   options.ClientSecret = "GOCSPX-jHKaxxxxxxx";

And if it helps put in your configuration keys and values, like this:

"clientId":"591241482908 66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com",
"clientSecret":"GOCSPX-jHKaxxxxxxx"

And rewrite your code to:

options.ClientId = builder.Configuration["clientId"];
options.ClientSecret = builder.Configuration["clientSecret"];


问:
PHP & MySQL: How can I use "SET @rank=0;" in $query=
In my PHP file, I use this line to pull data from my mySQL database:

```<code>$query = "SET @rank=0; SELECT @rank:=@rank +1 as rank, Blah Blah...";
</code>```

If I check the SELECT statement in phpMyAdmin's SQL window (without $query= ) it works fine.

But, if I use it in PHP, then I get an error. It doesn't like the "SET @rank=0;" bit. Is there a way to use "SET @rank=0;" when it's in "$query=" ? Is there a workaround?

The rest of the code is standard stuff for pulling data from a db:

```<code>public function getmyData() {

 $mysql = mysql_connect(connection stuff);

 $query = "SELECT @rank:=@rank +1 as rank, formatted_school_name,  blah blah";

 $result = mysql_query($query);

            $ret = array();
                 while ($row = mysql_fetch_object($result)) {
                    $tmp = new VOmyData1();
                    $tmp->stuff1 = $row-> stuff1;
                    $tmp->stuff2 = $row->stuff2;

                    $ret[] = $tmp;
                        }
                 mysql_free_result($result);

                 return $ret;

    }
</code>```

Update: I'm trying to use Amerb's suggestion of using multi-query. I concatenated the query like so:

```<code>$query = "SET @rank = 0";

$query .= "SELECT @rank:=@rank +1 as rank...
</code>```

I changed the result to:

```<code>$result = $mysqli_multi_query($query);
</code>```

But, it's failing for some reason. I'm on a machine running PHP 5.2. Any suggestions?

答: You have to enable the use of multiple queries in one, but i forgot how do do this at the moment. It's a security feature.</p>

Body:
In my PHP file, I use this line to pull data from my mySQL database:

$query = "SET @rank=0; SELECT @rank:=@rank +1 as rank, Blah Blah...";

If I check the SELECT statement in phpMyAdmin's SQL window (without $query= ) it works fine.

But, if I use it in PHP, then I get an error. It doesn't like the "SET @rank=0;" bit. Is there a way to use "SET @rank=0;" when it's in "$query=" ? Is there a workaround?

The rest of the code is standard stuff for pulling data from a db:

public function getmyData() {

 $mysql = mysql_connect(connection stuff);

 $query = "SELECT @rank:=@rank +1 as rank, formatted_school_name,  blah blah";

 $result = mysql_query($query);

            $ret = array();
                 while ($row = mysql_fetch_object($result)) {
                    $tmp = new VOmyData1();
                    $tmp->stuff1 = $row-> stuff1;
                    $tmp->stuff2 = $row->stuff2;

                    $ret[] = $tmp;
                        }
                 mysql_free_result($result);

                 return $ret;

    }

Update: I'm trying to use Amerb's suggestion of using multi-query. I concatenated the query like so:

$query = "SET @rank = 0";

$query .= "SELECT @rank:=@rank +1 as rank...

I changed the result to:

$result = $mysqli_multi_query($query);

But, it's failing for some reason. I'm on a machine running PHP 5.2. Any suggestions?


问:
Spring Cloud Config does not fetch config files
I just upgraded our spring boot projects to v2.6.2 from boot and 2021.0.0 from spring cloud.

And now nothing of my remote configuration fetching works, and the app does not fetch the correct property file

[main] INFO  o.s.c.c.c.ConfigServicePropertySourceLocator - Fetching config from server at : http://localhost:8080

[main] WARN  o.s.c.c.c.ConfigServicePropertySourceLocator - Could not locate PropertySource: Could not extract response: no suitable HttpMessageConverter found for response type [class org.springframework.cloud.config.environment.Environment] and content type [text/html;charset=UTF-8]

[main] INFO  eu.hermes.esb.cloud.Application - No active profile set, falling back to default profiles: default

[main] INFO  o.s.b.c.config.ConfigDataLoader - Fetching config from server at : http://localhost:8080

[main] INFO  o.s.d.r.c.RepositoryConfigurationDelegate - Bootstrapping Spring Data JPA repositories in DEFAULT mode.**

we use spring cloud config based on git repo that is filled with our config yml files in the following structures.

app-one-dev.yml

app-one-prod.yml

app-two-dev.yml

app-two-prod.yml
and so on

I tried adding these two dependencies to the client service as suggested by some answers but nothing worked.

spring-cloud-starter-config

spring-cloud-starter-bootstrap

this is my config service yml:

```<code>spring.cloud.config.server:
    git:
      uri: https://bitbucket-prod.doa.otc.hlg.de/scm/inp-cloud/esb-spring-boot-config.git
      username: foo
      password: bar
      force-pull: true
 spring.security:
 basic:
   enabled: true
 user:
   name: inp
   password: hermes
</code>```

and my app runs with these properties:

```<code>-Dspring.config.import=configserver:http://inp:hermes@localhost:8080
-Dspring.cloud.config.name=esb-config-service
-Dspring.cloud.config.username=foo
-Dspring.cloud.config.username=bar
-Dspring.application.name=app-one
-Dspring.profiles.active=dev,console,gelf
</code>```

our services run on Kubernetes in OKD. but I replicated the same situation locally on a windows machine so I do not think it is an environment specific.

答:
The problem is most likely wrong credentials, i.e. username and password, in the client configuration.

It's hard to say for sure with the information provided. In particular, as the credentials given in the question are probably anonymized. But please note that in the given config snippet, you set the username twice and not the password. Furthermore, the snippet for the server config is not correctly indented. The properties for the client should probably contain

```<code>-Dspring.config.import=configserver:http://localhost:8080
-Dspring.cloud.config.username=inp
-Dspring.cloud.config.username=hermes
</code>```

Spring Boot's auto-configuration of Spring Security is not a perfect match for the Spring Cloud Config Server. The problem is that the server forwards to the login page when the default Accept Header of the config client is sent with bad credentials. That's why the config client receives a response body with media type HTML, which the client does not understand.

Please double-check the credentials in your configuration. The most straight-forward method to prevent the problem in the future is to disable the login page in the config server, if you don't need it. Then you get a clear log message in the client for bad credentials.

Body:
I just upgraded our spring boot projects to v2.6.2 from boot and 2021.0.0 from spring cloud.

And now nothing of my remote configuration fetching works, and the app does not fetch the correct property file

[main] INFO  o.s.c.c.c.ConfigServicePropertySourceLocator - Fetching config from server at : http://localhost:8080

[main] WARN  o.s.c.c.c.ConfigServicePropertySourceLocator - Could not locate PropertySource: Could not extract response: no suitable HttpMessageConverter found for response type [class org.springframework.cloud.config.environment.Environment] and content type [text/html;charset=UTF-8]

[main] INFO  eu.hermes.esb.cloud.Application - No active profile set, falling back to default profiles: default

[main] INFO  o.s.b.c.config.ConfigDataLoader - Fetching config from server at : http://localhost:8080

[main] INFO  o.s.d.r.c.RepositoryConfigurationDelegate - Bootstrapping Spring Data JPA repositories in DEFAULT mode.**

we use spring cloud config based on git repo that is filled with our config yml files in the following structures.

app-one-dev.yml

app-one-prod.yml

app-two-dev.yml

app-two-prod.yml
and so on

I tried adding these two dependencies to the client service as suggested by some answers but nothing worked.

spring-cloud-starter-config

spring-cloud-starter-bootstrap

this is my config service yml:

spring.cloud.config.server:
    git:
      uri: https://bitbucket-prod.doa.otc.hlg.de/scm/inp-cloud/esb-spring-boot-config.git
      username: foo
      password: bar
      force-pull: true
 spring.security:
 basic:
   enabled: true
 user:
   name: inp
   password: hermes

and my app runs with these properties:

-Dspring.config.import=configserver:http://inp:hermes@localhost:8080
-Dspring.cloud.config.name=esb-config-service
-Dspring.cloud.config.username=foo
-Dspring.cloud.config.username=bar
-Dspring.application.name=app-one
-Dspring.profiles.active=dev,console,gelf

our services run on Kubernetes in OKD. but I replicated the same situation locally on a windows machine so I do not think it is an environment specific.

Body:
The problem is most likely wrong credentials, i.e. username and password, in the client configuration.

It's hard to say for sure with the information provided. In particular, as the credentials given in the question are probably anonymized. But please note that in the given config snippet, you set the username twice and not the password. Furthermore, the snippet for the server config is not correctly indented. The properties for the client should probably contain

-Dspring.config.import=configserver:http://localhost:8080
-Dspring.cloud.config.username=inp
-Dspring.cloud.config.username=hermes

Spring Boot's auto-configuration of Spring Security is not a perfect match for the Spring Cloud Config Server. The problem is that the server forwards to the login page when the default Accept Header of the config client is sent with bad credentials. That's why the config client receives a response body with media type HTML, which the client does not understand.

Please double-check the credentials in your configuration. The most straight-forward method to prevent the problem in the future is to disable the login page in the config server, if you don't need it. Then you get a clear log message in the client for bad credentials.


问:
Link transaction details with Product
I'm trying to link some models together to show what product a user is holding as well as the price they paid and the amount they hold. Which will be displayed within a table.

I have Profile Product, Holding models, and want to add a Transaction model that is linked to the Profile, and Holding model to be able to add purchased amount and price.

I'm not sure what the best way to link these models is to be able to easily present the data within a table.

Models:

```<code>class Product(models.Model):

    product_name = models.CharField(max_length=255, blank=False, unique=True)
    product_slug = models.CharField(max_length=50, blank=True,null=True)
    product_symbol = models.CharField(max_length=50, blank=True,null=True)
    product_price = models.FloatField(blank=True,null=True)
    product_capture_date = models.DateField(blank=True,null=True)
    product_logo_address = models.URLField(max_length=255, blank=True)

    def __str__(self):
        return str(self.product_name)

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    products = models.ManyToManyField(Product, blank=True, through='Holding')
    website = models.URLField(max_length=50, blank=True)
    twitter = models.CharField(max_length=50, blank=True)
    meta = models.CharField(max_length=50, blank=True)
    github = models.CharField(max_length=50, blank=True)

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

class Holding(models.Model):

    product_name = models.ForeignKey(Product, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    product_holding = models.FloatField(max_length=50, blank=True, null=True)

    def __str__(self):
        return str(self.product_name)

class Transaction(models.Model):

    product = models.ForeignKey(Holding, on_delete=models.CASCADE)
    amount = models.FloatField(max_length=50, blank=True, null=True)
    price = models.FloatField(max_length=50, blank=True, null=True)
    transaction_date = models.DateField(null=True, blank=True)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
</code>```

I've created the transaction model and linked it with a FK to Holding and Profile - this seems to work for allocating the data to the model and allows me to add multiple transactions to a product for a profile.

But I think there is a better way to work within the view, bearing in mind that a product could have multiple transactions assigned and wouldn't all the transactions listed just the total amount and average price.

```<code>profile = Profile.objects.get(user = request.user)
transact = Transaction.objects.filter(profile = profile)

</code>```

So within my table, I want to show the product_name, transaction.price, and product_holding.

答:
Looks good except that you don't need profile field on Transaction because it's already on product/Holding item. As well as not clear why need to have ManyToMany on Profile with product.

So I would refactor that as follows (see comments inline):

```<code>class Product(models.Model):
    # no need to say 'product_name' because it is on model Product
    name = models.CharField(max_length=255, blank=False, unique=True)
    slug = models.CharField(max_length=50, blank=True,null=True)
    symbol = models.CharField(max_length=50, blank=True,null=True)

    # Float does not suite price due to its low precision. Use Decimal instrad
    price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    capture_date = models.DateField(blank=True,null=True)
    logo_address = models.URLField(max_length=255, blank=True)

    def __str__(self):
        return self.name

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

    # no need of products here - can be find via Holding
    # products = models.ManyToManyField(Product, blank=True, through='Holding')
    website = models.URLField(max_length=50, blank=True)
    twitter = models.CharField(max_length=50, blank=True)
    meta = models.CharField(max_length=50, blank=True)
    github = models.CharField(max_length=50, blank=True)

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

class Holding(models.Model):
    # the field is not product_name - it is actually `product` itself
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    product_holding = models.FloatField(max_length=50, blank=True, null=True)

    def __str__(self):
        return str(self.product_name)

class Transaction(models.Model):

    product = models.ForeignKey(Holding, on_delete=models.CASCADE)
    amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    price = models.FloatField(max_length=50, blank=True, null=True)
    transaction_date = models.DateField(null=True, blank=True)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
</code>```

And filtering:

```<code>profile = Profile.objects.get(user = request.user)

transactions = Transaction.objects.filter(
    holding__in=Holding.objects.filter(profile=profile)
)

for t in transactions:
    product_name = t.holding.product.product_name
    price = t.price
    product_holding = t.holding.product_holding
</code>```

If you want to know the products of a specific user (since we removed ManyToMany):

```<code>products = [x.product for x in Holding.objects.filter(profile=profile)]
</code>```

Or if a specific user hold specific product:

```<code>product = Product.objects.get(name='specific_product')
exists = Holding.objects.filter(profile=profile, product=product).exists()
</code>```

Title: Link transaction details with Product

Body:
I'm trying to link some models together to show what product a user is holding as well as the price they paid and the amount they hold. Which will be displayed within a table.

I have Profile Product, Holding models, and want to add a Transaction model that is linked to the Profile, and Holding model to be able to add purchased amount and price.

I'm not sure what the best way to link these models is to be able to easily present the data within a table.

Models:

class Product(models.Model):

    product_name = models.CharField(max_length=255, blank=False, unique=True)
    product_slug = models.CharField(max_length=50, blank=True,null=True)
    product_symbol = models.CharField(max_length=50, blank=True,null=True)
    product_price = models.FloatField(blank=True,null=True)
    product_capture_date = models.DateField(blank=True,null=True)
    product_logo_address = models.URLField(max_length=255, blank=True)

    def __str__(self):
        return str(self.product_name)

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    products = models.ManyToManyField(Product, blank=True, through='Holding')
    website = models.URLField(max_length=50, blank=True)
    twitter = models.CharField(max_length=50, blank=True)
    meta = models.CharField(max_length=50, blank=True)
    github = models.CharField(max_length=50, blank=True)

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

class Holding(models.Model):

    product_name = models.ForeignKey(Product, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    product_holding = models.FloatField(max_length=50, blank=True, null=True)

    def __str__(self):
        return str(self.product_name)

class Transaction(models.Model):

    product = models.ForeignKey(Holding, on_delete=models.CASCADE)
    amount = models.FloatField(max_length=50, blank=True, null=True)
    price = models.FloatField(max_length=50, blank=True, null=True)
    transaction_date = models.DateField(null=True, blank=True)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)

I've created the transaction model and linked it with a FK to Holding and Profile - this seems to work for allocating the data to the model and allows me to add multiple transactions to a product for a profile.

But I think there is a better way to work within the view, bearing in mind that a product could have multiple transactions assigned and wouldn't all the transactions listed just the total amount and average price.

profile = Profile.objects.get(user = request.user)
transact = Transaction.objects.filter(profile = profile)

So within my table, I want to show the product_name, transaction.price, and product_holding.

Body:
Looks good except that you don't need profile field on Transaction because it's already on product/Holding item. As well as not clear why need to have ManyToMany on Profile with product.

So I would refactor that as follows (see comments inline):

class Product(models.Model):
    # no need to say 'product_name' because it is on model Product
    name = models.CharField(max_length=255, blank=False, unique=True)
    slug = models.CharField(max_length=50, blank=True,null=True)
    symbol = models.CharField(max_length=50, blank=True,null=True)

    # Float does not suite price due to its low precision. Use Decimal instrad
    price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    capture_date = models.DateField(blank=True,null=True)
    logo_address = models.URLField(max_length=255, blank=True)

    def __str__(self):
        return self.name

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

    # no need of products here - can be find via Holding
    # products = models.ManyToManyField(Product, blank=True, through='Holding')
    website = models.URLField(max_length=50, blank=True)
    twitter = models.CharField(max_length=50, blank=True)
    meta = models.CharField(max_length=50, blank=True)
    github = models.CharField(max_length=50, blank=True)

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

class Holding(models.Model):
    # the field is not product_name - it is actually `product` itself
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    product_holding = models.FloatField(max_length=50, blank=True, null=True)

    def __str__(self):
        return str(self.product_name)

class Transaction(models.Model):

    product = models.ForeignKey(Holding, on_delete=models.CASCADE)
    amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    price = models.FloatField(max_length=50, blank=True, null=True)
    transaction_date = models.DateField(null=True, blank=True)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)

And filtering:

profile = Profile.objects.get(user = request.user)

transactions = Transaction.objects.filter(
    holding__in=Holding.objects.filter(profile=profile)
)

for t in transactions:
    product_name = t.holding.product.product_name
    price = t.price
    product_holding = t.holding.product_holding

If you want to know the products of a specific user (since we removed ManyToMany):

products = [x.product for x in Holding.objects.filter(profile=profile)]

Or if a specific user hold specific product:

product = Product.objects.get(name='specific_product')
exists = Holding.objects.filter(profile=profile, product=product).exists()


问:
jQuery .remove() does not work with div created inside the function
I've tried a couple of things since yesterday, but I can't achieve my goal.

The idea is :

When clicking on a character "Div", it appears a little menu to change a parameter inside my website. The problem is, I want to remove the "Class Picker", but it just does not work.

```<code>var CharacterClasses = [
    { id: 1, name: 'Warrior', cssClass: 'warrior'},
    { id: 2, name: 'Paladin', cssClass: 'paladin'},
    ...
]

$('.group_miniature').click( function(){

    // Removing all existant class choices
    $(".group-panel_class_picker").remove()

    // Creating the class picker
    var Panel = $("<div id=\"panel_class_picker\"></div>").addClass('group-panel_class_picker')

    // Append the whole thing
    $(this).append(Panel)

    // Iterating each class to add a div
    CharacterClasses.forEach( function(item){

        // Creating the div
        let btn_class = $("<div>&nbsp</div>").addClass( [item.cssClass,'group-btn_class'] )

        Panel.append(btn_class)

        Panel.on("click", ".group-btn_class", function(event){
            $(this).parent().remove() // This is my problem, it does not remove the parent
            console.log('Click :)') // This appears in my console
        })

    })

})
</code>```

答:
```<code>Panel.on("click", ".group-btn_class", function(event){
            $(this).parent().hide()
            event.stopPropagation()
            console.log('Click criss')
        })
</code>```

I discovered that I had to add event.stopPropagation()

Now it works just fine ! :)

Body:
I've tried a couple of things since yesterday, but I can't achieve my goal.

The idea is :

When clicking on a character "Div", it appears a little menu to change a parameter inside my website. The problem is, I want to remove the "Class Picker", but it just does not work.

var CharacterClasses = [
    { id: 1, name: 'Warrior', cssClass: 'warrior'},
    { id: 2, name: 'Paladin', cssClass: 'paladin'},
    ...
]

$('.group_miniature').click( function(){

    // Removing all existant class choices
    $(".group-panel_class_picker").remove()

    // Creating the class picker
    var Panel = $("

").addClass('group-panel_class_picker')

    // Append the whole thing
    $(this).append(Panel)

    // Iterating each class to add a div
    CharacterClasses.forEach( function(item){

        // Creating the div
        let btn_class = $("
&nbsp
").addClass( [item.cssClass,'group-btn_class'] )

        Panel.append(btn_class)

        Panel.on("click", ".group-btn_class", function(event){
            $(this).parent().remove() // This is my problem, it does not remove the parent
            console.log('Click :)') // This appears in my console
        })

    })

})

Body:
Panel.on("click", ".group-btn_class", function(event){
            $(this).parent().hide()
            event.stopPropagation()
            console.log('Click criss')
        })

I discovered that I had to add event.stopPropagation()

Now it works just fine ! :)


问:
Can't Install Apache2 on Ubuntu 20.04
I get this error whenever i try to install apache2 or reinstall it.

I tried to delete all its packages already and did an autoremove but that didn't work.

sudo apt-get remove --purge apache2

sudo apt-get autoremove

I deleted apache2.data also.

I made sure there is no folder of apache2 left on my computer from previous installations.

whereis apache2

and i removed all folders.

Then i tried to install it again :

sudo apt-get install apache2

答:
Some service is already running on port 80 and hence you're getting that error. You may need to change your apache2 port to something else.
For this, open /etc/apache2/sites-available/000-default.conf:

```<code>sudo nano /etc/apache2/sites-available/000-default.conf
</code>```

Then change <VirtualHost *:80> to <VirtualHost *:8080>.
Then run:

```<code>sudo nano /etc/apache2/ports.conf
</code>```

And change Listen 80 to Listen 8080.
And now, run:

```<code>sudo systemctl start apache2
</code>```

This should start apache2 server on localhost:8080.

Title: Can't Install Apache2 on Ubuntu 20.04

Body:
Some service is already running on port 80 and hence you're getting that error. You may need to change your apache2 port to something else.
For this, open /etc/apache2/sites-available/000-default.conf:

sudo nano /etc/apache2/sites-available/000-default.conf

Then change <VirtualHost *:80> to <VirtualHost *:8080>.
Then run:

sudo nano /etc/apache2/ports.conf

And change Listen 80 to Listen 8080.
And now, run:

sudo systemctl start apache2

This should start apache2 server on localhost:8080.


问:
Pausing/Breaking execution in javascript for debugging, but only for certain javascript files
Do any browsers support pausing execution / stepping through code, but only for certain files or regions? I'm using jQuery and several other libraries, and I'm not interested in stepping through their code in 99% of cases, as it is my code that is wrong. All my code is in my script file, other libraries are included separately.

If I use the pause button, I tend to find that I am very quickly taken to some part of jquery with code I don't understand or need to understand. If I click the step into button a lot, I sometimes get taken to a point in my script, sometimes not.

I could manually click every single line of my code to add a breakpoint, but this would be extremely tedious, and I couldn't un-pause execution easily. If there is a browser that lets you select multiple lines and add breakpoints to all of them in one click, that would be a great alternative, though.

答: There are some new features in the Chrome developer tools that can help you get a good entry point into a new code base. Event listener breakpoints will let you pause execution at a given event handler:</p>


问:
MySQL Finding intersection where 2 entered dates intersect between a start_date and end_date
I am trying to find if 2 entered dates have an intersection between a start date/time and end date/time.

Example in my database table "reservation" we have a row(s) with the following

start_date = 2022-02-28 09:00:00
end_date = 2022-02-28 11:00:00

I would like to build a query where i can select this row when i pass in the following inputs

start date = 2022-02-28 08:30:00
end date = 2022-02-28 12:30:00

Now this filter should select any rows where the date/time intersect with it. I built the below query, however,  this does not select the intersection that i want. Is there anything i can do to adjust the below query? This query works for the most part (when dates are truly inside the start/end date) but does not do any intersection like this. This query works for the most part but just not this scenario.

```<code>SELECT
    rp.product_id
FROM
    reservation r
    INNER JOIN reservation_product AS rp ON r.reservation_id = rp.reservation_id
WHERE
    (
        '2022-02-28 08:30:00' BETWEEN r.start_date
        AND r.end_date
    )
    OR (
        '2022-02-28 12:30:00' BETWEEN r.start_date
        AND r.end_date
    )
</code>```

Example Data - The below inputs should select that row in the square.

start date = 2022-02-28 08:30:00
end date = 2022-02-28 12:30:00

答:
You can find intersections if start_date is less than the max of the 2 dates and end_date is greater than the min of the 2 dates:

```<code>WHERE r.end_date >= '2022-02-28 08:30:00'
  AND r.start_date <= '2022-02-28 12:30:00'
</code>```

Body:
I am trying to find if 2 entered dates have an intersection between a start date/time and end date/time.

Example in my database table "reservation" we have a row(s) with the following

start_date = 2022-02-28 09:00:00
end_date = 2022-02-28 11:00:00

I would like to build a query where i can select this row when i pass in the following inputs

start date = 2022-02-28 08:30:00
end date = 2022-02-28 12:30:00

Now this filter should select any rows where the date/time intersect with it. I built the below query, however,  this does not select the intersection that i want. Is there anything i can do to adjust the below query? This query works for the most part (when dates are truly inside the start/end date) but does not do any intersection like this. This query works for the most part but just not this scenario.

SELECT
    rp.product_id
FROM
    reservation r
    INNER JOIN reservation_product AS rp ON r.reservation_id = rp.reservation_id
WHERE
    (
        '2022-02-28 08:30:00' BETWEEN r.start_date
        AND r.end_date
    )
    OR (
        '2022-02-28 12:30:00' BETWEEN r.start_date
        AND r.end_date
    )

Example Data - The below inputs should select that row in the square.

start date = 2022-02-28 08:30:00
end date = 2022-02-28 12:30:00

Body:
You can find intersections if start_date is less than the max of the 2 dates and end_date is greater than the min of the 2 dates:

WHERE r.end_date >= '2022-02-28 08:30:00'
  AND r.start_date <= '2022-02-28 12:30:00'


答:
The intervals A and B intersection condition is A.start<=B.End AND B.start <= A.End

```<code>..
WHERE
    (
        '2022-02-28 08:30:00' < r.end_date
    )
    AND (
        '2022-02-28 12:30:00' > r.start_date
    )
</code>```

Title: MySQL Finding intersection where 2 entered dates intersect between a start_date and end_date

Body:
The intervals A and B intersection condition is A.start<=B.End AND B.start <= A.End

..
WHERE
    (
        '2022-02-28 08:30:00' < r.end_date
    )
    AND (
        '2022-02-28 12:30:00' > r.start_date
    )


问:
How to get if statement to print a value inside array
In this example, I am trying to make it so that if variable == one of the values in the array, it prints "This Works".

```<code>array = [1, 2]

one = 1
two = 2

def trying():
    if one == array:
        print("This Works")

print(trying())
</code>```

I understand that one and array isn't the same, but how do I go about getting one and the value 1 to equal, so that this code works

答:
Try this:</p>
```<code>from array import array

array = array('i', [1,2,3,4,5,6,7,8,9,10])
one = array[0]
two = array[1]

def get_if_statement(array, one, two):
    if array[0] == 1:
        print(array[0])
    elif array[1] == 2:
        print(array[1])
    else:
        print("None")
</code>```

Body:
In this example, I am trying to make it so that if variable == one of the values in the array, it prints "This Works".

array = [1, 2]

one = 1
two = 2

def trying():
    if one == array:
        print("This Works")

print(trying())

I understand that one and array isn't the same, but how do I go about getting one and the value 1 to equal, so that this code works

Body:
Try this:

from array import array

array = array('i', [1,2,3,4,5,6,7,8,9,10])
one = array[0]
two = array[1]

def get_if_statement(array, one, two):
    if array[0] == 1:
        print(array[0])
    elif array[1] == 2:
        print(array[1])
    else:
        print("None")


问:
Is there a way to declare a type for a value that possibly extends some other type?
In Typescript, can we create a type Possibly<T> that only accepts values that maybe, but not necessarily, extend T? Or in other words, values that could be asserted as T without a "neither type sufficiently overlaps with the other" error?

Alternative ways of constraining the parameter that are not describable as a utility type are also fine. However, they must work at compile time (this is a Typescript question after all, not Javascript).

```<code>// NOTE: AliveCat and DeadCat are examples, not actual types that can be modified.
//       Assume that asserting (casting) a DeadCat to AliveCat is a compile error.
declare const garfield: AliveCat;
declare const tom: DeadCat;
declare const schrodingersCat: AliveCat | DeadCat;

function feed(cat: Possibly<AliveCat>) {
    if (unspecifiedAliveCheck(cat)) {
        unspecifiedCastOrUnwrap(cat).food++;
    } else {
        throw new Error(" :( ");
    }
}

garfield as Alive; // obviously works, probably warns about being useless
feed(garfield); // so should also work

schrodingersCat as AliveCat; // compiles
feed(schrodingersCat); // so should also compile

tom as AliveCat; // doesn't compile: "neither type sufficiently overlaps with the other"
feed(tom); // so should not compile either
</code>```

Not solutions, because they accept a DeadCat:

```<code>declare function feed(cat: AliveCat | DeadCat);
declare function feed(cat: unknown);
declare function feed(cat: any); // yuk!
</code>```

Or for a more mundane example:

```<code>// NOTE: the type guard return type is nice to have but optional
function isArray(a: Possibly<any[]>): a is any[] { ... }
isArray([]); // well yeah, but okay, double-checking is fine
isArray(true); // of course not!
isArray(... as true | number); // let's see and find out!
</code>```

答:
A workaround would be to just use a cast (or assertion, in good Typescriptian) where this already works. Unfortunately this extra bit of safety comes at a price, because the intent of the code becomes much less clear.

```<code>/**
 * @param cat may also be something else, it's checked at runtime
 */
declare function feed(cat: AliveCat);
feed(garfield);
feed(tom as AliveCat); // cast error

// cast allowed, though now it looks as if the programmer already
// knew it's alive
feed(schrodingersCat as AliveCat);
</code>```

This may be mitigated a bit with a helper function:

```<code>/**
 * Cast v to O for the type system, keeping in mind that the runtime type
 * of v may not actually be O!
 *
 * TODO needs shorter name. assume?
 */
function tentativeCast<I, O extends I>(v: I): O {
    return v as O
}

feed(tentativeCast(schrodingersCat)); // inferred
</code>```

It's a little bit dangerous though, because the result of tentativeCast still does have a technically illegal type, which may accidentally end up in some local variable anyway. Fortunately, it can be made safer with some more runtime overhead:

```<code>class Uncertain<T> {
  readonly #value: T;
  constructor(value: T) { this.#value = value; }
  get value() { return this.#value; }
}

type Possibly<T> = T | Uncertain<T>;

declare function feed(cat: Possibly<AliveCat>): void;

/**
 * Cast v to O for the type system, keeping in mind that the runtime type
 * of v may not actually be O!
 *
 * TODO needs shorter name. assume?
 */
function tentativeCast<I, O extends I>(v: I): Uncertain<O> {
    return new Uncertain(v as O);
}

feed(tentativeCast(garfield)); // allowed
feed(tentativeCast(tom)); // not allowed
const certainlyAlive: AliveCat = tentativeCast(schrodingersCat); // not allowed, Uncertain<AliveCat> is not AliveCat
feed(tentativeCast(schrodingersCat)); // allowed, Uncertain<AliveCat> extends Possibly<AliveCat>
</code>```

Body:
In Typescript, can we create a type Possibly<T> that only accepts values that maybe, but not necessarily, extend T? Or in other words, values that could be asserted as T without a "neither type sufficiently overlaps with the other" error?

Alternative ways of constraining the parameter that are not describable as a utility type are also fine. However, they must work at compile time (this is a Typescript question after all, not Javascript).

// NOTE: AliveCat and DeadCat are examples, not actual types that can be modified.
//       Assume that asserting (casting) a DeadCat to AliveCat is a compile error.
declare const garfield: AliveCat;
declare const tom: DeadCat;
declare const schrodingersCat: AliveCat | DeadCat;

function feed(cat: Possibly<AliveCat>) {
    if (unspecifiedAliveCheck(cat)) {
        unspecifiedCastOrUnwrap(cat).food++;
    } else {
        throw new Error(" :( ");
    }
}

garfield as Alive; // obviously works, probably warns about being useless
feed(garfield); // so should also work

schrodingersCat as AliveCat; // compiles
feed(schrodingersCat); // so should also compile

tom as AliveCat; // doesn't compile: "neither type sufficiently overlaps with the other"
feed(tom); // so should not compile either

Not solutions, because they accept a DeadCat:

declare function feed(cat: AliveCat | DeadCat);
declare function feed(cat: unknown);
declare function feed(cat: any); // yuk!

Or for a more mundane example:

// NOTE: the type guard return type is nice to have but optional
function isArray(a: Possibly<any[]>): a is any[] { ... }
isArray([]); // well yeah, but okay, double-checking is fine
isArray(true); // of course not!
isArray(... as true | number); // let's see and find out!

Body:
A workaround would be to just use a cast (or assertion, in good Typescriptian) where this already works. Unfortunately this extra bit of safety comes at a price, because the intent of the code becomes much less clear.

/**
 * @param cat may also be something else, it's checked at runtime
 */
declare function feed(cat: AliveCat);
feed(garfield);
feed(tom as AliveCat); // cast error

// cast allowed, though now it looks as if the programmer already
// knew it's alive
feed(schrodingersCat as AliveCat);

This may be mitigated a bit with a helper function:

/**
 * Cast v to O for the type system, keeping in mind that the runtime type
 * of v may not actually be O!
 *
 * TODO needs shorter name. assume?
 */
function tentativeCast<I, O extends I>(v: I): O {
    return v as O
}

feed(tentativeCast(schrodingersCat)); // inferred

It's a little bit dangerous though, because the result of tentativeCast still does have a technically illegal type, which may accidentally end up in some local variable anyway. Fortunately, it can be made safer with some more runtime overhead:

class Uncertain<T> {
  readonly #value: T;
  constructor(value: T) { this.#value = value; }
  get value() { return this.#value; }
}

type Possibly<T> = T | Uncertain<T>;

declare function feed(cat: Possibly<AliveCat>): void;

/**
 * Cast v to O for the type system, keeping in mind that the runtime type
 * of v may not actually be O!
 *
 * TODO needs shorter name. assume?
 */
function tentativeCast<I, O extends I>(v: I): Uncertain<O> {
    return new Uncertain(v as O);
}

feed(tentativeCast(garfield)); // allowed
feed(tentativeCast(tom)); // not allowed
const certainlyAlive: AliveCat = tentativeCast(schrodingersCat); // not allowed, Uncertain<AliveCat> is not AliveCat
feed(tentativeCast(schrodingersCat)); // allowed, Uncertain<AliveCat> extends Possibly<AliveCat>


问:
How to Ensure the apps info.plist contains a value for CFBundleIdentifier?
The app will not run on the simulator or the device but the trouble started when i went to get it on device. Running the latest and greatest Xcode and macOS. Any suggestions are most welcome.

I suspect this issue is related to the unit testing targets but there is also odd behaviour in the "Signing and Capabilities", when i type in the bundle identifier "com.sw.fw" and hit enter the text in the the textfield vanishes and the "Signing (Release)" duplication appears below with that bundle id. I also created a fresh mobile provisioning profile with the appropriate bundle id com.sw.fw

I also know that Xcode is doing something with the bundle id that i'm giving it because it appears on the Certificates, Identifiers & Profiles page of developer.apple.com as can be seen here.

Here's the target signing after hitting enter.

Here's the "Build Settings" for the target

Here's my info.plist it is the same as an app i have running on device.

Here's a unit test signing

Here's the "Build Settings" for a unit test target

App Targets "General" pane doesn't let me type anything in the Bundle Identifier Field. You can see it reads <Multiple Values>.

答:
Target > Build Settings > Packaging

In "Info.plist File" add "Target_Name/Info.plist"


问:
List all global variables
As noted elsewhere, you can list all user-defined symbols with this:

```<code>Names["Global`*"]
</code>```

But I'd like to find just my global variables (I'm in the middle of some hairy debugging), not my function definitions.  Something like this is close:

```<code>Select[Names["Global`*"], Head@Symbol[#]=!=Symbol && Head@Symbol[#]=!=Function&]
</code>```

But that misses variables whose value is a symbol (perhaps I have x = Pi).

I could probably beat that thing into submission but maybe there's a cleaner, more direct way?

答: One might consider a variable to be a Global` symbol that does not pass FunctionQ.

Title: List all global variables

Body:
As noted elsewhere, you can list all user-defined symbols with this:

Names["Global`*"]

But I'd like to find just my global variables (I'm in the middle of some hairy debugging), not my function definitions.  Something like this is close:

Select[Names["Global`*"], Head@Symbol[#]=!=Symbol && Head@Symbol[#]=!=Function&]

But that misses variables whose value is a symbol (perhaps I have x = Pi).

I could probably beat that thing into submission but maybe there's a cleaner, more direct way?


问:
How to write Yup schema in typescript in Nextjs
Actually getting error when defining yup schema:

Error: Cannot read properties of undefined (reading 'object')

```<code>import Yup, { object } from 'yup'
import { useFormik } from 'formik'

interface Account {
  username: string;
  email: string;
  password: string;
}

const loginSchema: Yup.SchemaOf<Account> = Yup.object().shape({
    email: Yup.string().email().required(),
    username: Yup.string().min(3).max(25).required().matches(/^[a-z0-9]+$/i, "Username should contain alphabets and numbers only"),
    password: Yup.string().required().min(4).matches(/^[a-z0-9]+$/i, "Password should contain alphabets and numbers only")
  })
</code>```

Actually i am new to yup and typescript, so pls tell me the actual way of defining yup in ts

答:
There is nothing wrong with the code itself except from the import statement.

change

import Yup, { object } from 'yup'

to

import * as Yup from "yup";

You are accessing the object function through the Yup

Body:
Actually getting error when defining yup schema:

Error: Cannot read properties of undefined (reading 'object')

import Yup, { object } from 'yup'
import { useFormik } from 'formik'

interface Account {
  username: string;
  email: string;
  password: string;
}

const loginSchema: Yup.SchemaOf<Account> = Yup.object().shape({
    email: Yup.string().email().required(),
    username: Yup.string().min(3).max(25).required().matches(/^[a-z0-9]+$/i, "Username should contain alphabets and numbers only"),
    password: Yup.string().required().min(4).matches(/^[a-z0-9]+$/i, "Password should contain alphabets and numbers only")
  })

Actually i am new to yup and typescript, so pls tell me the actual way of defining yup in ts


问:
Building C++ project using build-appveyor
I do not know C++, but I need to build C++ application - Osmium tool. I have not known that it is really hard to build C++ programs.  What I want is just create .exe file to merge maps. That is my simple goal.

So docs says:

On Windows you can compile with the Visual Studio C++ compiler and nmake. The necessary dependencies can be installed with conda. See appveyor.yml for the necessary commands to compile osmium-tool.

appveyor.yml docs says:

environment: matrix:
    - config: Debug
    - config: Release

shallow_clone: true

Operating system (build VM template) os: Visual Studio 2015

platform: x64

scripts that are called at very beginning, before repo cloning init:

clone directory clone_folder: c:\projects\osmium-tool

install:
    - cd c:\projects
    - git clone --depth 1 https://github.com/osmcode/libosmium
    - git clone --depth 1 https://github.com/mapbox/protozero

build_script:
    - cd c:\projects/osmium-tool
    - build-appveyor.bat

I've done all the above steps and now I'm trying to run in Windows 10:

```<code>build-appveyor.bat
</code>```

However,I see the error:

```<code>System cannot find the path specified
</code>```

An image:

Guys what am I doing wrong? Please, help me! Any help would be greatly appreciated.

答:
I just got osmium to compile for Windows after a bit of trial of error and research (wasn't very familiar with c++ when I started). Here are my notes -

Download and install prebuilt 64-bit boost

```<code>https://downloads.sourceforge.net/project/boost/boost-binaries/1.63.0/boost_1_63_0-msvc-14.0-64.exe
</code>```

In C:\projects

```<code>git clone --depth 1 https://github.com/osmcode/libosmium
git clone --depth 1 https://github.com/mapbox/protozero
git clone https://github.com/osmcode/osmium-tool
    - Checkout latest osmium-tool tag
</code>```

VS2019

```<code>- Install desktop development with c++
- Install MSVC v140 - VS 2015 C++ build tools (v14.00)

build-appveyor.bat
- Update vcvarsall.bat location for VS2019 install location (VC\Auxiliary\Build\vcvarsall.bat)
- Changed cmake_cmd "Visual Studio 14 Win64" to "Visual Studio 16"
- Changed toolsversion from 14.0 to Current
- ensure DBOOST_ROOT path matches installed path of DBOOST e.g.  C:/local/boost_1_63_0
</code>```

VS2015 community edition

```<code>Download cmake, add to path e.g. C:\Program Files\CMake\bin
build-appveyor.bat
- Update vcvarsall.bat location for VS2019 install location (VC\vcvarsall.bat)
- ensure DBOOST_ROOT path matches installed path of DBOOST e.g.  C:/local/boost_1_63_0
</code>```

Download latest nuget.exe and place in path (won't work in system32)

Ensure nuget source is configured: nuget.exe sources Add -Name nuget.org -Source https://api.nuget.org/v3/index.json

Run build-local.bat

Copy 64-bit release DLLs from bzip2, libexpat nuget pacakges to the same directory as osmium.exe

Body:
I do not know C++, but I need to build C++ application - Osmium tool. I have not known that it is really hard to build C++ programs.  What I want is just create .exe file to merge maps. That is my simple goal.

So docs says:

On Windows you can compile with the Visual Studio C++ compiler and nmake. The necessary dependencies can be installed with conda. See appveyor.yml for the necessary commands to compile osmium-tool.

appveyor.yml docs says:

environment: matrix:
    - config: Debug
    - config: Release

shallow_clone: true

Operating system (build VM template) os: Visual Studio 2015

platform: x64

scripts that are called at very beginning, before repo cloning init:

clone directory clone_folder: c:\projects\osmium-tool

install:
    - cd c:\projects
    - git clone --depth 1 https://github.com/osmcode/libosmium
    - git clone --depth 1 https://github.com/mapbox/protozero

build_script:
    - cd c:\projects/osmium-tool
    - build-appveyor.bat

I've done all the above steps and now I'm trying to run in Windows 10:

build-appveyor.bat

However,I see the error:

System cannot find the path specified

An image:

Guys what am I doing wrong? Please, help me! Any help would be greatly appreciated.

Body:
I just got osmium to compile for Windows after a bit of trial of error and research (wasn't very familiar with c++ when I started). Here are my notes -

Download and install prebuilt 64-bit boost

https://downloads.sourceforge.net/project/boost/boost-binaries/1.63.0/boost_1_63_0-msvc-14.0-64.exe

In C:\projects

git clone --depth 1 https://github.com/osmcode/libosmium
git clone --depth 1 https://github.com/mapbox/protozero
git clone https://github.com/osmcode/osmium-tool
    - Checkout latest osmium-tool tag

VS2019

- Install desktop development with c++
- Install MSVC v140 - VS 2015 C++ build tools (v14.00)

build-appveyor.bat
- Update vcvarsall.bat location for VS2019 install location (VC\Auxiliary\Build\vcvarsall.bat)
- Changed cmake_cmd "Visual Studio 14 Win64" to "Visual Studio 16"
- Changed toolsversion from 14.0 to Current
- ensure DBOOST_ROOT path matches installed path of DBOOST e.g.  C:/local/boost_1_63_0

VS2015 community edition

Download cmake, add to path e.g. C:\Program Files\CMake\bin
build-appveyor.bat
- Update vcvarsall.bat location for VS2019 install location (VC\vcvarsall.bat)
- ensure DBOOST_ROOT path matches installed path of DBOOST e.g.  C:/local/boost_1_63_0

Download latest nuget.exe and place in path (won't work in system32)

Ensure nuget source is configured: nuget.exe sources Add -Name nuget.org -Source https://api.nuget.org/v3/index.json

Run build-local.bat

Copy 64-bit release DLLs from bzip2, libexpat nuget pacakges to the same directory as osmium.exe


问:
python postgres can I fetchall() 1 million rows?
I am using psycopg2 module in python to read from postgres database, I need to some operation on all rows in a column, that has more than 1 million rows.

I would like to know would cur.fetchall() fail or cause my server to go down? (since my RAM might not be that big to hold all that data)

```<code>q="SELECT names from myTable;"
cur.execute(q)
rows=cur.fetchall()
for row in rows:
    doSomething(row)
</code>```

what is the smarter way to do this?

答:
As I was reading comments and answers I thought I should clarify something about fetchone and Server-side cursors for future readers.

With normal cursors (client-side), Psycopg fetches all the records returned by the backend, transferring them to the client process. The whole records are buffered in the client's memory. It is when you execute a query like curs.execute('SELECT * FROM ...'.

This question also confirms that.

All the fetch* methods are there for accessing this stored data.

Q: So how fetchone can help us memory wise ?

A: It fetches only one record from the stored data and creates a single Python object and hands you in your Python code while fetchall will fetch and create n Python objects from this data and hands it to you all in one chunk.

So If your table has 1,000,000 records, this is what's going on in memory:

curs.execute --> whole 1,000,000 result set  +  fetchone --> 1 Python object
curs.execute --> whole 1,000,000 result set  +  fetchall --> 1,000,000 Python objects
```

Of-course fetchone helped but still we have the whole records in memory. This is where Server-side cursors comes into play:

PostgreSQL also has its own concept of cursor (sometimes also called
portal). When a database cursor is created, the query is not
necessarily completely processed: the server might be able to produce
results only as they are needed. Only the results requested are
transmitted to the client: if the query result is very large but the
client only needs the first few records it is possible to transmit
only them.
...
their interface is the same, but behind the scene they
send commands to control the state of the cursor on the server (for
instance when fetching new records or when moving using scroll()).

So you won't get the whole result set in one chunk.

The draw-back :

The downside is that the server needs to keep track of the partially
processed results, so it uses more memory and resources on the server.

Body:
I am using psycopg2 module in python to read from postgres database, I need to some operation on all rows in a column, that has more than 1 million rows.

I would like to know would cur.fetchall() fail or cause my server to go down? (since my RAM might not be that big to hold all that data)

q="SELECT names from myTable;"
cur.execute(q)
rows=cur.fetchall()
for row in rows:
    doSomething(row)

what is the smarter way to do this?

Body:
As I was reading comments and answers I thought I should clarify something about fetchone and Server-side cursors for future readers.

With normal cursors (client-side), Psycopg fetches all the records returned by the backend, transferring them to the client process. The whole records are buffered in the client's memory. It is when you execute a query like curs.execute('SELECT * FROM ...'.

This question also confirms that.

All the fetch* methods are there for accessing this stored data.

Q: So how fetchone can help us memory wise ?

A: It fetches only one record from the stored data and creates a single Python object and hands you in your Python code while fetchall will fetch and create n Python objects from this data and hands it to you all in one chunk.

So If your table has 1,000,000 records, this is what's going on in memory:

curs.execute --> whole 1,000,000 result set  +  fetchone --> 1 Python object
curs.execute --> whole 1,000,000 result set  +  fetchall --> 1,000,000 Python objects

Of-course fetchone helped but still we have the whole records in memory. This is where Server-side cursors comes into play:

PostgreSQL also has its own concept of cursor (sometimes also called
portal). When a database cursor is created, the query is not
necessarily completely processed: the server might be able to produce
results only as they are needed. Only the results requested are
transmitted to the client: if the query result is very large but the
client only needs the first few records it is possible to transmit
only them.
...
their interface is the same, but behind the scene they
send commands to control the state of the cursor on the server (for
instance when fetching new records or when moving using scroll()).

So you won't get the whole result set in one chunk.

The draw-back :

The downside is that the server needs to keep track of the partially
processed results, so it uses more memory and resources on the server.


问:
Append columns with typed access to rows with Deedle
Let's say I want to

Read persons from CSV with name, weight and height with typed access to whole rows. The weight is optional.  E.g.

```<code>     Name Weight    Height
0 -> Joe  80        1.88
1 -> Ann  <missing> 1.66
</code>```

Apply a given transformation, e.g. calculate bmi.

Save the result in a new column and get a new Frame without changing the old one.

Read the result of 3 and apply another transformation, e.g. round.

Result:

```<code>     Name Weight    Height  BMI           BMI_rounded
0 -> Joe  80        1.88    22.6346763241 22.6
1 -> Ann  <missing> 1.66    <missing>     <missing>
</code>```

It is not clear to me how to make an appendColumn function.

I have tried:

#r "nuget: Deedle"

open Deedle
open System.IO

type IPerson =
    abstract Name : string
    abstract Weight : OptionalValue<int>
    abstract Height: float

type IPersonWithBmi =
    abstract Bmi : OptionalValue<float>
    inherit IPerson

let data = "Name;Weight;Height\nJoe;80;1.88\nAnn;;1.66"

//https://stackoverflow.com/questions/44344061/converting-a-string-to-a-stream/44344794
let bytes = System.Text.Encoding.UTF8.GetBytes data
let stream =  new MemoryStream( bytes )

let df:Frame<int,string> = Frame.ReadCsv(
    stream = stream,
    separators = ";",
    hasHeaders = true
)

let getBMI  (h:float) (w:int):Option<float> = if h>0.0 then Some ((float w)/(h*h)) else None

df.Print()

let rows = df.GetRowsAs<IPerson>()

rows |> Series.mapValues (fun (row:IPerson) -> row.Weight |> OptionalValue.asOption |> Option.bind (getBMI row.Height) |> OptionalValue.ofOption)

//Pseudocode
let df2 = appendColumn df "BMI" rows

let round (f:float):int = int (System.Math.Round(f, 0))

let rows2 = df.GetRowsAs<IPersonWithBmi>()

rows2 |> Series.mapValues (fun (row:IPersonWithBmi) -> row.Bmi |> OptionalValue.map round )

//Pseudocode
let df3 = appendColumn df2 "BMI_rounded" rows2

```

答:
This is what Frame.Join does. So if you have a BMI series like this:

let bmi =
    df
        |> Frame.mapRowValues (fun row ->
            row.TryGetAs<int>("Weight")
                |> OptionalValue.asOption
                |> Option.bind (getBMI <| row.GetAs<float>("Height"))
                |> OptionalValue.ofOption)
```
<p>You can join it to your frame like this:</p>
<pre class="lang-ml prettyprint-override"><code>let df2 = df.Join("BMI", bmi)
df2.Print()
</code>```

Output is:

```<code>     Name Weight    Height BMI
0 -> Joe  80        1.88   22.634676324128566
1 -> Ann  <missing> 1.66   <missing>
</code>```

The rounded BMI column could be created the same way.

Body:
Let's say I want to

Read persons from CSV with name, weight and height with typed access to whole rows. The weight is optional.  E.g.

     Name Weight    Height
0 -> Joe  80        1.88
1 -> Ann  <missing> 1.66

Apply a given transformation, e.g. calculate bmi.

Save the result in a new column and get a new Frame without changing the old one.

Read the result of 3 and apply another transformation, e.g. round.

Result:

     Name Weight    Height  BMI           BMI_rounded
0 -> Joe  80        1.88    22.6346763241 22.6
1 -> Ann  <missing> 1.66    <missing>     <missing>

It is not clear to me how to make an appendColumn function.

I have tried:

#r "nuget: Deedle"

open Deedle
open System.IO

type IPerson =
    abstract Name : string
    abstract Weight : OptionalValue<int>
    abstract Height: float

type IPersonWithBmi =
    abstract Bmi : OptionalValue<float>
    inherit IPerson

let data = "Name;Weight;Height\nJoe;80;1.88\nAnn;;1.66"

//https://stackoverflow.com/questions/44344061/converting-a-string-to-a-stream/44344794
let bytes = System.Text.Encoding.UTF8.GetBytes data
let stream =  new MemoryStream( bytes )

let df:Frame<int,string> = Frame.ReadCsv(
    stream = stream,
    separators = ";",
    hasHeaders = true
)

let getBMI  (h:float) (w:int):Option<float> = if h>0.0 then Some ((float w)/(h*h)) else None

df.Print()

let rows = df.GetRowsAs<IPerson>()

rows |> Series.mapValues (fun (row:IPerson) -> row.Weight |> OptionalValue.asOption |> Option.bind (getBMI row.Height) |> OptionalValue.ofOption)

//Pseudocode
let df2 = appendColumn df "BMI" rows

let round (f:float):int = int (System.Math.Round(f, 0))

let rows2 = df.GetRowsAs<IPersonWithBmi>()

rows2 |> Series.mapValues (fun (row:IPersonWithBmi) -> row.Bmi |> OptionalValue.map round )

//Pseudocode
let df3 = appendColumn df2 "BMI_rounded" rows2

Body:
This is what Frame.Join does. So if you have a BMI series like this:

let bmi =
    df
        |> Frame.mapRowValues (fun row ->
            row.TryGetAs<int>("Weight")
                |> OptionalValue.asOption
                |> Option.bind (getBMI <| row.GetAs<float>("Height"))
                |> OptionalValue.ofOption)

You can join it to your frame like this:

let df2 = df.Join("BMI", bmi)
df2.Print()

Output is:

     Name Weight    Height BMI
0 -> Joe  80        1.88   22.634676324128566
1 -> Ann  <missing> 1.66   <missing>

The rounded BMI column could be created the same way.


问:
Warning: Received `false` for a non-boolean attribute `border`. in react?
I. am getting below warning . I don't know where I am doing wrong .I am using style component in my demo application.

```<code>react_devtools_backend.js:4061 Warning: Received `false` for a non-boolean attribute `border`.

If you want to write it to the DOM, pass a string instead: border="false" or border={value.toString()}.

If you used to conditionally omit it with border={condition && value}, pass border={condition ? value : undefined} instead.
</code>```

I do like this . i create a component like this. I also added few console to debug. here is my debug statement

```<code> console.log('========',depth,depth === 1);
</code>```

debug statement output
======== 3 false

```<code>5MobileHeader.tsx:63 ======== 4 false
MobileHeader.tsx:63 ======== 3 false
3MobileHeader.tsx:63 ======== 4 false
</code>```

component call

<CardHeader border={depth === 1}>

component definition

```<code>interface CardHeaderProps {
  border: boolean;
}

export const CardHeader = styled(Card.Header)<CardHeaderProps>`
  background-color: transparent;
  border-radius: 0 !important;
  border: 0;
  padding: 10px 20px;

  ${props =>
    props.border &&
    css`
      border-bottom: 1px solid #dad8d8;
    `}
`;
</code>```

答:
There are 2 things you can do.

Don't forward the border props to Card.Header, as Card.Header does not have a border prop, and will forward the border prop to the underlying div which also doesn't support border prop. Use shouldForwardProp option and forward prop if it is not border.

https://styled-components.com/docs/api#shouldforwardprop (applicable also if u are using mui styled)

```<code>   export const CardHeader = styled(Card.Header, { shouldForwardProp: (prop)=> prop !== 'border'})<CardHeaderProps>`
        background-color: transparent;
        border-radius: 0 !important;
        border: 0;
        padding: 10px 20px;
        border-bottom: ${(props) => props.border ? '1px solid #dad8d8' : 'none'};
    `;
</code>```

If you do not want to use shouldForwardProp (which you should be using, refer to link above), then use

```<code> <CardHeader border={depth === 1 ? 1 : 0}> // instead of true/false. When u inspect the element you will see the border prop after rendering.
</code>```

Cleaner styled code

```<code>export const CardHeader = styled(Card.Header, { shouldForwardProp: (prop)=> prop !== 'border'})(({ theme, border })`
    border-bottom: ${border ? 'some code' : 'none'};

`)
</code>```

Body:
I. am getting below warning . I don't know where I am doing wrong .I am using style component in my demo application.

react_devtools_backend.js:4061 Warning: Received `false` for a non-boolean attribute `border`.

If you want to write it to the DOM, pass a string instead: border="false" or border={value.toString()}.

If you used to conditionally omit it with border={condition && value}, pass border={condition ? value : undefined} instead.

I do like this . i create a component like this. I also added few console to debug. here is my debug statement

 console.log('========',depth,depth === 1);

debug statement output
======== 3 false

5MobileHeader.tsx:63 ======== 4 false
MobileHeader.tsx:63 ======== 3 false
3MobileHeader.tsx:63 ======== 4 false

component call

<CardHeader border={depth === 1}>

component definition

interface CardHeaderProps {
  border: boolean;
}

export const CardHeader = styled(Card.Header)<CardHeaderProps>`
  background-color: transparent;
  border-radius: 0 !important;
  border: 0;
  padding: 10px 20px;

  ${props =>
    props.border &&
    css`
      border-bottom: 1px solid #dad8d8;
    `}
`;

Body:
There are 2 things you can do.

Don't forward the border props to Card.Header, as Card.Header does not have a border prop, and will forward the border prop to the underlying div which also doesn't support border prop. Use shouldForwardProp option and forward prop if it is not border.

https://styled-components.com/docs/api#shouldforwardprop (applicable also if u are using mui styled)

   export const CardHeader = styled(Card.Header, { shouldForwardProp: (prop)=> prop !== 'border'})<CardHeaderProps>`
        background-color: transparent;
        border-radius: 0 !important;
        border: 0;
        padding: 10px 20px;
        border-bottom: ${(props) => props.border ? '1px solid #dad8d8' : 'none'};
    `;

If you do not want to use shouldForwardProp (which you should be using, refer to link above), then use

 <CardHeader border={depth === 1 ? 1 : 0}> // instead of true/false. When u inspect the element you will see the border prop after rendering.

Cleaner styled code

export const CardHeader = styled(Card.Header, { shouldForwardProp: (prop)=> prop !== 'border'})(({ theme, border })`
    border-bottom: ${border ? 'some code' : 'none'};

`)


问:
Approach to send a large JSON payload to a web service
Consider a small Go application that reads a large JSON file 2GB+, marshals the JSON data into a struct, and POSTs the JSON data to a web service endpoint.

The web service receiving the payload changed its functionality, and now has a limit of 25MB per payload. What would be the best approach to overcome this issue using Go? I've thought of the following, however I'm not sure it is the best approach:

Creating a function to split the large JSON file into multiple smaller ones (up to 20MB), and then iterate over the files sending multiple smaller requests.

Similar function to the one being used to currently send the entire JSON payload:

```<code>func sendDataToService(data StructData) {
    payload, err := json.Marshal(data)
    if err != nil {
        log.Println("ERROR:", err)
    }

    request, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(payload))
    if err != nil {
        log.Println("ERROR:", err)
    }

    client := &http.Client{}
    response, err := client.Do(request)
    log.Println("INFORMATIONAL:", request)
    if err != nil {
        log.Println("ERROR:", err)
    }
    defer response.Body.Close()
}
</code>```

答:
As the server-side can process data progressively, I assume that the large JSON object can be split into smaller pieces. From this point, I can propose several options.

Use HTTP requests

Pros: Pretty simple to implement on the client-side.

Cons: Making hundreds of HTTP requests might be slow. You will also need to handle timeouts - this is additional complexity.

Use WebSocket messages

If the receiving side supports WebSockets, a step-by-step flow will look like this:

Split the input data into smaller pieces.

Connect to the WebSocket server.

Start sending messages with the smaller pieces till the end of the file.

Close connection to the server.

This solution might be more performant as you won't need to connect and disconnect from the server each time you send a message, as you'd do with HTTP.

However, both solutions suppose that you need to assemble all pieces on the server-side. For example, you would probably need to send along with the data a correlation ID to let the server know what file you are sending right now and a specific end-of-file message to let the server know when the file ends. In the case of the WebSocket server, you could assume that the entire file is sent during a single connection session if it is relevant.

Body:
Consider a small Go application that reads a large JSON file 2GB+, marshals the JSON data into a struct, and POSTs the JSON data to a web service endpoint.

The web service receiving the payload changed its functionality, and now has a limit of 25MB per payload. What would be the best approach to overcome this issue using Go? I've thought of the following, however I'm not sure it is the best approach:

Creating a function to split the large JSON file into multiple smaller ones (up to 20MB), and then iterate over the files sending multiple smaller requests.

Similar function to the one being used to currently send the entire JSON payload:

func sendDataToService(data StructData) {
    payload, err := json.Marshal(data)
    if err != nil {
        log.Println("ERROR:", err)
    }

    request, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(payload))
    if err != nil {
        log.Println("ERROR:", err)
    }

    client := &http.Client{}
    response, err := client.Do(request)
    log.Println("INFORMATIONAL:", request)
    if err != nil {
        log.Println("ERROR:", err)
    }
    defer response.Body.Close()
}


问:
UISearchBar displays in the root view but not in any other view on the tab bar
I have implemented the search bar for the table in the first tab and this works fine and filters fine, however, with the same code and the xib linked up all the same etc on the second tab it no longer displays the search bar. Is there a simple reason to this?</p>

答: Separate out the UISearchBar into its own class and then call it from the multiple views.  It is not meant to be reinstantiated for each view controller.</p>