问:
How to enable CORS in ASP.net Core WebAPI
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

```<code>    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });
</code>```

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

```<code>    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }
</code>```

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

```<code>[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller
</code>```

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

```<code>.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")
</code>```

These are other headers I tried which failed

```<code>.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")
</code>```

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

```<code>app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));
</code>```

答:
Simple and easy way to do it.

Install package

Install-Package Microsoft.AspNetCore.Cors

Put this below code in startup.cs file

app.UseCors(options => options.AllowAnyOrigin());

Body:
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")

These are other headers I tried which failed

.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));


来源: stackexchange

问:
ModuleNotFoundError: No module named 'pynput' Python3 and pip3
I want to use 'pynput', so I used pip to add it to my environment.
The installation proceeds without problem.
But I am unable to import it into my project.

I am using python 3.8.1 on my environment.
I used pip3 for installation.
I have already tried to install pynput, uninstall it and reinstall it multiple times.
My .py file doesn't have a confusing name like "pynput.py"
I am comfortable with my environment when I try to execute my file.
I am trying to run from my terminal or VSCodium, and neither of them works.
And I work on Debian 10.

pip freeze :

```<code>pynput==1.6.7
python-xlib==0.26
six==1.14.0
</code>```

Traceback :

```<code>Traceback (most recent call last):
  File "./play.py", line 6, in <module>
    from pynput import keyboard
ModuleNotFoundError: No module named 'pynput'
</code>```

So I don't understand why it doesn't work.

thank you in advance for your help :)

答:
When creating my project, I was not working under an environment, so I used the classic shebang: #!/bin/python3.

Then, I went under an environment to use pynput, but I just forgot to change my shebang to #!/usr/bin/env python.

So, actually, I didn't risk finding pynput

ContentLicense: CC BY-SA 4.0

Body:
I want to use 'pynput', so I used pip to add it to my environment.
The installation proceeds without problem.
But I am unable to import it into my project.

I am using python 3.8.1 on my environment.
I used pip3 for installation.
I have already tried to install pynput, uninstall it and reinstall it multiple times.
My .py file doesn't have a confusing name like "pynput.py"
I am comfortable with my environment when I try to execute my file.
I am trying to run from my terminal or VSCodium, and neither of them works.
And I work on Debian 10.

pip freeze :

pynput==1.6.7
python-xlib==0.26
six==1.14.0

Traceback :

Traceback (most recent call last):
  File "./play.py", line 6, in <module>
    from pynput import keyboard
ModuleNotFoundError: No module named 'pynput'

So I don't understand why it doesn't work.

thank you in advance for your help :)


问:
SwiftUI ForEach-Loops getting errors
I'm trying to build a ForEach()-Loop in SwiftUI for building UI-Elements, but I'm getting this error-message:

Unable to infer complex closure return type; add explicit type to disambiguate

Here is my code:

```<code>    var body: some View {
        HStack {
            HStack {
                VStack {
                    ForEach((1...10).reversed(), id: \.self) {
                        Text("\($0)")
                        Spacer()
                    }
                    Spacer()
                }
                Spacer()
            }
            Spacer()
        }
    }
</code>```

The Error is pointing on the Line with the ForEach-Statement. I tried to follow the tutorial by Paul Hudson, see: https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-views-in-a-loop-using-foreach

答:
In short: remove Spacer() from ForEach.
ForEach expects to return one value of type some View.
You could wrap your Text() and Spacer() into HStack or VStack, but in this case you couldn't access the each number in your array via closure syntax ($0 notation should be changed to { element in } ).
So the next code would work:

var body: some View {
    HStack {
        HStack {
            VStack {
                ForEach((1...10).reversed(), id: \.self) { number in
                    HStack {
                        Text("\(number)")
                        Spacer()
                    }
                }
                Spacer()
            }
            Spacer()
        }
        Spacer()
    }
}
```

Title: SwiftUI ForEach-Loops getting errors

Body:
I'm trying to build a ForEach()-Loop in SwiftUI for building UI-Elements, but I'm getting this error-message:

Unable to infer complex closure return type; add explicit type to disambiguate

Here is my code:

    var body: some View {
        HStack {
            HStack {
                VStack {
                    ForEach((1...10).reversed(), id: \.self) {
                        Text("\($0)")
                        Spacer()
                    }
                    Spacer()
                }
                Spacer()
            }
            Spacer()
        }
    }

The Error is pointing on the Line with the ForEach-Statement. I tried to follow the tutorial by Paul Hudson, see: https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-views-in-a-loop-using-foreach


问:
How to calculate the clipping area of an image after scaling and translating
I have an image on a canvas and a ScaleTranform and a TranslateTransform attached to the image's RenderTranform. So with a bit of mouse event handling I can move and zoom the image within the 350 by 450 bounds of the canvas.

How would I calculate the clipping rectangle on the original BitmapImage, to that of the visible area on the screen, after some scaling and translation. I'd like to crop the original BitmapImage.

```<code><Border BorderBrush="Black" BorderThickness="2">
  <Canvas Name="canvas" ClipToBounds="True" Height="450" Width="350">
    <Image Name="image" Opacity="1" RenderTransformOrigin="0.5,0.5" Height="450" Width="350">
       <Image.Source>
          <BitmapImage UriSource="test.jpg"/>
       </Image.Source>
     </Image>
  </Canvas>
</Border>
</code>```

Thanks

答:
Simply apply the calculations done to the Image by the Transformations to the bounds...
(And do it in the same order...)

So if you Scale it up by a factor of 2 in X and Y
the resulting Canvas will be 450/2 x 350/2 (in size - origin is still unknown)

And i guess it would be easier to avoid the TranslateTransform and simply play with the
Origin of the ScaleTransform... whereas an Origin of 0 should give you an Clip-origin of 0
and a X&Y Origin of 1 will result in the image to be lower right...

so to set up some simple formula..:

```<code>double W = 450;
double H = 350;

double SX = 2;
double SY = 2;

double OX = .3;
double OY = .3;

double newW = W / SX;
double newH = H / SY;

double newX = (W-newW) * OX;
double newY = (H-newH) * OY;
</code>```

so newX,Y,W and H contain the data you are looking for!

regards,
 dave

ContentLicense: CC BY-SA 3.0

Body:
I have an image on a canvas and a ScaleTranform and a TranslateTransform attached to the image's RenderTranform. So with a bit of mouse event handling I can move and zoom the image within the 350 by 450 bounds of the canvas.

How would I calculate the clipping rectangle on the original BitmapImage, to that of the visible area on the screen, after some scaling and translation. I'd like to crop the original BitmapImage.

<Border BorderBrush="Black" BorderThickness="2">
  <Canvas Name="canvas" ClipToBounds="True" Height="450" Width="350">
    <Image Name="image" Opacity="1" RenderTransformOrigin="0.5,0.5" Height="450" Width="350">
       <Image.Source>
          <BitmapImage UriSource="test.jpg"/>
       </Image.Source>
     </Image>
  </Canvas>
</Border>

Thanks

Body:
Simply apply the calculations done to the Image by the Transformations to the bounds...
(And do it in the same order...)

So if you Scale it up by a factor of 2 in X and Y
the resulting Canvas will be 450/2 x 350/2 (in size - origin is still unknown)

And i guess it would be easier to avoid the TranslateTransform and simply play with the
Origin of the ScaleTransform... whereas an Origin of 0 should give you an Clip-origin of 0
and a X&Y Origin of 1 will result in the image to be lower right...

so to set up some simple formula..:

double W = 450;
double H = 350;

double SX = 2;
double SY = 2;

double OX = .3;
double OY = .3;

double newW = W / SX;
double newH = H / SY;

double newX = (W-newW) * OX;
double newY = (H-newH) * OY;

so newX,Y,W and H contain the data you are looking for!

regards,
 dave


问:
Self contained component data model vs master root data model
I looking for feedback regarding how I am implementing Vue components.

I have a Vue instance that contains a list of orders and a reference to the current order. Let’s call this root instance "orders".

When the current order is set (based on clicking on one of the orders in the list), I create a new component inside "orders" called "current-order". "current-order" has a property that the parent passes it called "order_id", this property is used within "current-order" to recall the data for the order and present an editable form.

Within "current-order", besides the meta-data associated with the order (customer, etc), I have a third component to contain a group of items, let’s call this final instance "item-group".

Here is the general layout of how these instances would look:

```<code>orders
  current-order
    item-group
    item-group
    item-group
</code>```

"orders" only saves a list of the orders; it does not save any order data.
"current-order" saves the meta-data associated with the order, as well as the item data.

Discussing this model with a co-worker, he explained to me that this is not the best-practice way to implement this. He felt that the proper way to implement this would be to save all of the data for all of the components on the root instance "orders", versus the way I implemented it - data saved at each level.

The model he explained seems less maintainable to me. "current-order" may be used on other pages of our application, so if I maintained its data in the root instance, I would have to do that in all of the root instances that I attach it to.

With the way I have implemented it, all you have to pass the component is an order_id, and it will fill itself with data.

He continued to explain to me that saving data on the component like I am doing can be reset by re-renders of the instance, which I didn't quite understand.

Both the way I implemented, and the way he described would work, but I'm trying to find out what the best-practice approach would be for maintainability.

Note: This is not a large SPA, and I don’t think Vuex would suite what we are trying to achieve right now.

Any feedback would be appreciated.

答:
It all depends on what your child-components are responsible for. If a child is extending the functionality of your parent component then the state should always be maintained in your parent component. For example in a CRUD based situation instead of creating separate components for create and update you can write only one and maintain its state (updated/created) in your parent component.

If in your current-order you are not updating anything related to the order then no need to maintain its state in your order i.e. if meta-data can be treated as a separate entity of your order no need to maintain it in the parent. But in case both order and its meta is one single entity, you should maintain its state in your parent.

Body:
I looking for feedback regarding how I am implementing Vue components.

I have a Vue instance that contains a list of orders and a reference to the current order. Let’s call this root instance "orders".

When the current order is set (based on clicking on one of the orders in the list), I create a new component inside "orders" called "current-order". "current-order" has a property that the parent passes it called "order_id", this property is used within "current-order" to recall the data for the order and present an editable form.

Within "current-order", besides the meta-data associated with the order (customer, etc), I have a third component to contain a group of items, let’s call this final instance "item-group".

Here is the general layout of how these instances would look:

orders
  current-order
    item-group
    item-group
    item-group

"orders" only saves a list of the orders; it does not save any order data.
"current-order" saves the meta-data associated with the order, as well as the item data.

Discussing this model with a co-worker, he explained to me that this is not the best-practice way to implement this. He felt that the proper way to implement this would be to save all of the data for all of the components on the root instance "orders", versus the way I implemented it - data saved at each level.

The model he explained seems less maintainable to me. "current-order" may be used on other pages of our application, so if I maintained its data in the root instance, I would have to do that in all of the root instances that I attach it to.

With the way I have implemented it, all you have to pass the component is an order_id, and it will fill itself with data.

He continued to explain to me that saving data on the component like I am doing can be reset by re-renders of the instance, which I didn't quite understand.

Both the way I implemented, and the way he described would work, but I'm trying to find out what the best-practice approach would be for maintainability.

Note: This is not a large SPA, and I don’t think Vuex would suite what we are trying to achieve right now.

Any feedback would be appreciated.


问:
Generic java.util.function.Function for Grouping as per input
I have class Foo which has some field and I want to group them to Map<Object,List<Foo>> by fields as follow:

```<code>class Foo {
    private String cassette;
    private List<String> organ; //not able to group on List<String>
    private LocalDate date;
    //getter setter toString
}

enum Group{
    CASSETTE,
    ORGAN,
    DATE
}
</code>```

I have a switch case for Grouping by java.util.function.Function for Collectors.groupingBy() as follow:

```<code>Function<Foo, Object> keyCriteria;

Group groupBy = Group.values()[1];//ordinal
switch (groupBy) {
case CASSETTE:
    keyCriteria = p -> p.getCassette();
    break;
case DATE:
    keyCriteria = p -> p.getDate();
    break;
case ORGAN:
    keyCriteria = p -> p.getOrgan(); //facing problem while grouping with List<String>
    break;
default:
    keyCriteria = p -> p.getCassette();
}

Map<Object, List<Foo>> mapByCriteria = fooList.stream()
        .collect(Collectors.groupingBy(keyCriteria));
System.out.println(mapByCriteria);
</code>```

Everything works fine except case ORGAN:

Result getting:

{[Lung, Liver]=[Foo [cassette=1A, organ=[Lung, Liver],
  date=2020-01-13]], [Liver]=[Foo [cassette=2A, organ=[Liver],
  date=2020-01-15]]}

Expected result:

{Liver=[Foo [cassette=1A, organ=[Lung, Liver], date=2020-01-13], Foo
  [cassette=2A, organ=[Liver], date=2020-01-15]], Lung=[Foo
  [cassette=1A, organ=[Lung, Liver], date=2020-01-13]]}

Achieved expected result by work around following:

```<code>Map<Object, List<Foo>> collect = fooList.stream()
                .flatMap(f -> f.getOrgan().stream().map(o -> new SimpleEntry<>(o, f))).collect(Collectors
                        .groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
</code>```

I'm looking for a switch case and Generic solution.

答:
You can not handle fundamentally different operations, like a plain mapping and a flattening, with the same code. You have to handle the special case specially:

```<code>public static Map<String, List<Foo>> mapByCriteria(List<Foo> fooList, Group criteria) {
    Function<Foo, String> simpleKeyCriteria;
    switch(criteria) {
        case CASSETTE: simpleKeyCriteria = Foo::getCassette; break;
        case DATE: simpleKeyCriteria = p -> p.getDate().toString(); break;
        case ORGAN:
            return fooList.stream()
                .flatMap(foo -> foo.getOrgan().stream()
                    .map(organ -> new AbstractMap.SimpleEntry<>(organ, foo)))
                .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
        default:
            throw new AssertionError(criteria);
    }
    return fooList.stream().collect(Collectors.groupingBy(simpleKeyCriteria));
}
</code>```

In principle, it would possible to share more common operations, by splitting the stream statement into parts, but it would produce even more code while the only common code is fooList.stream(). So in this specific case, this is no win. But for completeness:

```<code>public static Map<String, List<Foo>> mapByCriteria(List<Foo> fooList, Group criteria) {
    Stream<Foo> stream = fooList.stream(); // imagine more chained common operations
    Function<Foo, String> simpleKeyCriteria = null;
    Collector<Foo, ?, Map<String, List<Foo>>> collector = null;
    switch(criteria) {
        case CASSETTE: simpleKeyCriteria = Foo::getCassette; break;
        case DATE: simpleKeyCriteria = p -> p.getDate().toString(); break;
        case ORGAN: collector = Collectors.flatMapping(
            foo -> foo.getOrgan().stream()
                .map(organ -> new AbstractMap.SimpleEntry<>(organ, foo)),
            Collectors.groupingBy(Map.Entry::getKey,
                Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
        default:
            throw new AssertionError(criteria);
    }
    if(collector == null) collector = Collectors.groupingBy(simpleKeyCriteria);
    return stream.collect(collector);
}
</code>```

This bears absolutely no code duplication, but as demonstrated, is not necessarily a win over accepting small code duplication.

Body:
I have class Foo which has some field and I want to group them to Map<Object,List<Foo>> by fields as follow:

class Foo {
    private String cassette;
    private List<String> organ; //not able to group on List<String>
    private LocalDate date;
    //getter setter toString
}

enum Group{
    CASSETTE,
    ORGAN,
    DATE
}

I have a switch case for Grouping by java.util.function.Function for Collectors.groupingBy() as follow:

Function<Foo, Object> keyCriteria;

Group groupBy = Group.values()[1];//ordinal
switch (groupBy) {
case CASSETTE:
    keyCriteria = p -> p.getCassette();
    break;
case DATE:
    keyCriteria = p -> p.getDate();
    break;
case ORGAN:
    keyCriteria = p -> p.getOrgan(); //facing problem while grouping with List<String>
    break;
default:
    keyCriteria = p -> p.getCassette();
}

Map<Object, List<Foo>> mapByCriteria = fooList.stream()
        .collect(Collectors.groupingBy(keyCriteria));
System.out.println(mapByCriteria);

Everything works fine except case ORGAN:

Result getting:

{[Lung, Liver]=[Foo [cassette=1A, organ=[Lung, Liver],
  date=2020-01-13]], [Liver]=[Foo [cassette=2A, organ=[Liver],
  date=2020-01-15]]}

Expected result:

{Liver=[Foo [cassette=1A, organ=[Lung, Liver], date=2020-01-13], Foo
  [cassette=2A, organ=[Liver], date=2020-01-15]], Lung=[Foo
  [cassette=1A, organ=[Lung, Liver], date=2020-01-13]]}

Achieved expected result by work around following:

Map<Object, List<Foo>> collect = fooList.stream()
                .flatMap(f -> f.getOrgan().stream().map(o -> new SimpleEntry<>(o, f))).collect(Collectors
                        .groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

I'm looking for a switch case and Generic solution.

Body:
You can not handle fundamentally different operations, like a plain mapping and a flattening, with the same code. You have to handle the special case specially:

public static Map<String, List<Foo>> mapByCriteria(List<Foo> fooList, Group criteria) {
    Function<Foo, String> simpleKeyCriteria;
    switch(criteria) {
        case CASSETTE: simpleKeyCriteria = Foo::getCassette; break;
        case DATE: simpleKeyCriteria = p -> p.getDate().toString(); break;
        case ORGAN:
            return fooList.stream()
                .flatMap(foo -> foo.getOrgan().stream()
                    .map(organ -> new AbstractMap.SimpleEntry<>(organ, foo)))
                .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
        default:
            throw new AssertionError(criteria);
    }
    return fooList.stream().collect(Collectors.groupingBy(simpleKeyCriteria));
}

In principle, it would possible to share more common operations, by splitting the stream statement into parts, but it would produce even more code while the only common code is fooList.stream(). So in this specific case, this is no win. But for completeness:

public static Map<String, List<Foo>> mapByCriteria(List<Foo> fooList, Group criteria) {
    Stream<Foo> stream = fooList.stream(); // imagine more chained common operations
    Function<Foo, String> simpleKeyCriteria = null;
    Collector<Foo, ?, Map<String, List<Foo>>> collector = null;
    switch(criteria) {
        case CASSETTE: simpleKeyCriteria = Foo::getCassette; break;
        case DATE: simpleKeyCriteria = p -> p.getDate().toString(); break;
        case ORGAN: collector = Collectors.flatMapping(
            foo -> foo.getOrgan().stream()
                .map(organ -> new AbstractMap.SimpleEntry<>(organ, foo)),
            Collectors.groupingBy(Map.Entry::getKey,
                Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
        default:
            throw new AssertionError(criteria);
    }
    if(collector == null) collector = Collectors.groupingBy(simpleKeyCriteria);
    return stream.collect(collector);
}

This bears absolutely no code duplication, but as demonstrated, is not necessarily a win over accepting small code duplication.


问:
ping from docker container cannot reach outside hosts
I am trying to ping from a docker container running along with other services controlled with docker-compose.
Basic requirement is to connect to external db servers, which is not working. To debug I tried to ping the external box, which as expected don't return. I can however ping the external box from vm host.

The /etc/hosts has entry as I have provided following line in docker-compose.yml

```<code>extra_hosts:
     - "externalhostname:10.40.154.27"
</code>```

From docker inspect the following is the network details

```<code>"Networks": {
        "echo_service_default": {
            "IPAMConfig": null,
            "Links": null,
            "Aliases": [
                "python-interpreter",
                "3767f3a7ad80"
            ],
            "NetworkID": "10ca2ec9a1dbc3659cef91014c2c64c8df17e9d720350d1bdd198a53c6c0a946",
            "EndpointID": "c920443c34ff00ffefe2c669bc4b80e121c27d1b8ebc44fa9f5efb16e71561a4",
            "Gateway": "172.19.0.1",
            "IPAddress": "172.19.0.6",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "MacAddress": "02:42:ac:13:00:06",
            "DriverOpts": null
        }
</code>```

ifconfig in host gives

```<code>docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
        inet6 fe80::42:b6ff:fe86:fb71  prefixlen 64  scopeid 0x20<link>
        ether 02:42:b6:86:fb:71  txqueuelen 0  (Ethernet)
        RX packets 204  bytes 90455 (88.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 5080  bytes 459752 (448.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
</code>```

The service entry from docker-compose.yml

```<code>  python-interpreter:
image: image name
hostname: python-interpreter
volumes:
 - /scratch/share:/var/python-interpreter/data:ro
 - shared:/var/shared
extra_hosts:
 - "externalhostname:10.40.154.27"
</code>```

so the service is running with bridge network with no -p option

答:
it seems it is working now..
i changed to host mode

```<code>python-interpreter:
      image: ...
    hostname: ...
    **network_mode: host**
    volumes:
     ...
    extra_hosts:
     - "whf00aqw.in.oracle.com:10.40.154.27"
</code>```

I believe (not sure.)because it was going to bridge , it was restricting network access to within host. Now that i have made it host , it is able to share host network and able to access.

Body:
I am trying to ping from a docker container running along with other services controlled with docker-compose.
Basic requirement is to connect to external db servers, which is not working. To debug I tried to ping the external box, which as expected don't return. I can however ping the external box from vm host.

The /etc/hosts has entry as I have provided following line in docker-compose.yml

extra_hosts:
     - "externalhostname:10.40.154.27"

From docker inspect the following is the network details

"Networks": {
        "echo_service_default": {
            "IPAMConfig": null,
            "Links": null,
            "Aliases": [
                "python-interpreter",
                "3767f3a7ad80"
            ],
            "NetworkID": "10ca2ec9a1dbc3659cef91014c2c64c8df17e9d720350d1bdd198a53c6c0a946",
            "EndpointID": "c920443c34ff00ffefe2c669bc4b80e121c27d1b8ebc44fa9f5efb16e71561a4",
            "Gateway": "172.19.0.1",
            "IPAddress": "172.19.0.6",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "MacAddress": "02:42:ac:13:00:06",
            "DriverOpts": null
        }

ifconfig in host gives

docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
        inet6 fe80::42:b6ff:fe86:fb71  prefixlen 64  scopeid 0x20<link>
        ether 02:42:b6:86:fb:71  txqueuelen 0  (Ethernet)
        RX packets 204  bytes 90455 (88.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 5080  bytes 459752 (448.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

The service entry from docker-compose.yml

  python-interpreter:
image: image name
hostname: python-interpreter
volumes:
 - /scratch/share:/var/python-interpreter/data:ro
 - shared:/var/shared
extra_hosts:
 - "externalhostname:10.40.154.27"

so the service is running with bridge network with no -p option

Body:
it seems it is working now..
i changed to host mode

python-interpreter:
      image: ...
    hostname: ...
    **network_mode: host**
    volumes:
     ...
    extra_hosts:
     - "whf00aqw.in.oracle.com:10.40.154.27"

I believe (not sure.)because it was going to bridge , it was restricting network access to within host. Now that i have made it host , it is able to share host network and able to access.


问:
Searching and adding product in cart of bigbasket using selenium
I was trying to search and add product in the cart using selenium but was not able to successfully do it

```<code>  driver.get("https://www.bigbasket.com/cl/fruits-vegetables/?nc=nb");
  List<WebElement> product = driver.findElements(By.xpath("//div[@qa=\'product\']"));
    System.out.println("prdoduct=" + product.size());
    for(int i=0;i<product.size();i++)
    {
        String name = product.get(i).getText();
        System.out.println("NAME is" + name);

        String  xp= "(//button[@qa=\'add\'])" + "["+i+ "]";
        System.out.println("xp="+xp);
        if(name.contains("Cauliflower"))
        {
            System.out.println("xp" +xp);
            driver.findElement(By.xpath(xp)).click();
         }
     }
</code>```

In this previous product is getting selected but when I was debugging it was on the cauliflower     but still the previous product is getting selected

答:
Induce WebDriverWait() and wait for visibilityOfAllElementsLocatedBy() and use following css selector and xpath.

```<code>driver.get("https://www.bigbasket.com/cl/fruits-vegetables/?nc=nb");
List<WebElement> product =new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div[qa='product_name']>a")));
System.out.println("prdoduct=" + product.size());
   for(int i=0;i<product.size();i++)
        {
            String name = product.get(i).getText();
            System.out.println("NAME is" + name);

            if(name.contains("Cauliflower"))
            {
                driver.findElement(By.xpath("//div[@qa='product_name']//a[text()='" + name + "']/following::button[1]")).click();
             }
         }
</code>```

Body:
I was trying to search and add product in the cart using selenium but was not able to successfully do it

  driver.get("https://www.bigbasket.com/cl/fruits-vegetables/?nc=nb");
  List<WebElement> product = driver.findElements(By.xpath("//div[@qa=\'product\']"));
    System.out.println("prdoduct=" + product.size());
    for(int i=0;i<product.size();i++)
    {
        String name = product.get(i).getText();
        System.out.println("NAME is" + name);

        String  xp= "(//button[@qa=\'add\'])" + "["+i+ "]";
        System.out.println("xp="+xp);
        if(name.contains("Cauliflower"))
        {
            System.out.println("xp" +xp);
            driver.findElement(By.xpath(xp)).click();
         }
     }

In this previous product is getting selected but when I was debugging it was on the cauliflower     but still the previous product is getting selected

Body:
Induce WebDriverWait() and wait for visibilityOfAllElementsLocatedBy() and use following css selector and xpath.

driver.get("https://www.bigbasket.com/cl/fruits-vegetables/?nc=nb");
List<WebElement> product =new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div[qa='product_name']>a")));
System.out.println("prdoduct=" + product.size());
   for(int i=0;i<product.size();i++)
        {
            String name = product.get(i).getText();
            System.out.println("NAME is" + name);

            if(name.contains("Cauliflower"))
            {
                driver.findElement(By.xpath("//div[@qa='product_name']//a[text()='" + name + "']/following::button[1]")).click();
             }
         }


问:
Plotly: How to assign background colors to different ranges in a radar or polar chart?
I'm trying to change the background color of a radar chart in a way, that different value ranges get different colors, e.g. a radar chart with a range from 1-5, where 1-3 gets a red background color and 3-5 gets a green background color.
There is a possibility to change the color, but only for the whole circle.

Do you have any ideas?

EDIT

This is the sample code that I've used with the only possibilities that I've found to add colors.

```<code>import plotly.graph_objects as go

categories = ['processing cost','mechanical properties','chemical stability',
              'thermal stability', 'device integration']

fig = go.Figure()

fig.add_trace(go.Scatterpolar(
      r=[1, 5, 2, 2, 3],
      theta=categories,
      fill='toself',
      name='Product A'
))
fig.add_trace(go.Scatterpolar(
      r=[4, 3, 2.5, 1, 2],
      theta=categories,
      fill='toself',
      name='Product B'
))

fig.update_layout(
  paper_bgcolor="red",
  polar=dict(
    radialaxis=dict(
      color="red",
      visible=True,
      range=[0, 5]
    )),
  showlegend=False
)

fig.show()
</code>```

答:
There's no direct way to specify different background colors for different parts of the plot. But I if I understand correctly what you're aiming for here, you can do so with the correct combination of some go.Barpolar() and go.Scatterpolar() traces:

Code:

```<code># imports
import plotly.graph_objects as go
import numpy as np

# categories:
categories = ['processing cost','mechanical properties','chemical stability',
              'thermal stability', 'device integration']

# values:
rVars1=[1, 5, 2, 2, 3]
rVars2=[4, 3, 2.5, 1, 2]

# colors
values = [3,5]
colors = ['rgba(255, 0, 0, 0.8)', 'rgba(0, 255, 0, 0.8)']

# some calcultations to place all elements
slices=len(rVars1)
fields=[max(rVars1)]*slices
circle_split = [360/slices]*(slices)
theta= 0
thetas=[0]
for t in circle_split:
    theta=theta+t
    thetas.append(theta)
thetas

# plotly
fig = go.Figure()

# "background"
for t in range(0, len(colors)):
    fig.add_trace(go.Barpolar(
        r=[values[t]],
        width=360,
        marker_color=[colors[t]],
        opacity=0.6,
        name = 'Range ' + str(t+1)
        #showlegend=False,
    ))
    t=t+1

# trace 1
fig.add_trace(go.Scatterpolar(
       text = categories,
        r = rVars1,
        mode = 'lines+text+markers',
        fill='toself',
        fillcolor='rgba(0, 0, 255, 0.4)',
        textposition='bottom center',
        marker = dict(color = 'blue'),
        name = 'Product A'))

# adjust layout
fig.update_layout(
    template=None,
    polar = dict(radialaxis = dict(gridwidth=0.5,
                               range=[0, max(fields)],
                              showticklabels=True, ticks='', gridcolor = "grey"),
                 angularaxis = dict(showticklabels=False, ticks='',
                               rotation=45,
                               direction = "clockwise",
                               gridcolor = "white")))

fig.update_yaxes(showline=True, linewidth=2, linecolor='white')
fig.show()
</code>```

Edit: Multiple traces

Your sample code covers multiple traces. And that would quickly turn into a fine mess with my initial approach. Below is a snippet that covers multiple traces. To make this look good, I've put the category names at the edge of the circle in it's own trace with various text positions to make the names fall on the outside of the circle. Then I'm adding a single trace for each Product A and B. I hope this will be useful.

Plot 2:

Code 2:

```<code># imports
import plotly.graph_objects as go
import numpy as np
import pandas as pd

# categories:
categories = ['processing cost','mechanical properties','chemical stability',
              'thermal stability', 'device integration']

# values:
rVars1=[1, 5, 2, 2, 3]
rVars2=[4, 3, 2.5, 1, 2]

rAllMax = max(rVars1+rVars2)

# colors
values = [3,5]
colors = ['rgba(255, 0, 0, 0.9)', 'rgba(0, 255, 0, 0.9)', ]

# some calcultations to place all elements
slices=len(rVars1)
fields=[max(rVars1)]*slices
circle_split = [360/slices]*(slices)
theta= 0
thetas=[0]
for t in circle_split:
    theta=theta+t
    thetas.append(theta)
thetas

# set up label positions
df_theta=pd.DataFrame({'theta':thetas, 'positions':['middle right', 'middle right',
                                                    'bottom center', 'middle left',
                                                    'middle left', 'middle left']})

# plotly
fig = go.Figure()

# "background"
for t in range(0, len(colors)):
    fig.add_trace(go.Barpolar(
        r=[values[t]],
        width=360,
        marker_color=[colors[t]],
        opacity=0.6,
        name = 'Range ' + str(t+1)
        #showlegend=False,
    ))
    t=t+1

for r, cat in enumerate(categories):
    #print(r, cat)
    fig.add_trace(go.Scatterpolar(
            text = cat,
            r = [rAllMax],
            theta = [thetas[r]],
            mode = 'lines+text+markers',
            fill='toself',
            fillcolor='rgba(255, 255, 255, 0.4)',
            line = dict(color='black'),
            #textposition='bottom center',
            textposition=df_theta[df_theta['theta']==thetas[r]]['positions'].values[0],
            marker = dict(line_color='white', color = 'black'),
            marker_symbol ='circle',
            name = cat,
            showlegend = False))

# trace 1
fig.add_trace(go.Scatterpolar(
        #text = categories,
        r = rVars1,
        mode = 'lines+text+markers',
        fill='toself',
        fillcolor='rgba(0, 0, 255, 0.4)',
        textposition='bottom center',
        marker = dict(color = 'blue'),
        marker_symbol ='square',
        name = 'Product A'))

# trace 2
fig.add_trace(go.Scatterpolar(
        #text = categories,
        r = rVars2,
        mode = 'lines+text+markers',
        fill='toself',
        fillcolor='rgba(0, 255, 0, 0.4)',
        textposition='bottom center',
        marker = dict(color = 'Green'),
        name = 'Product B'))

# adjust layout
fig.update_layout(
    template=None,
    polar = dict(radialaxis = dict(gridwidth=0.5,
                               range=[0, max(fields)],
                              showticklabels=True, ticks='', gridcolor = "grey"),
                 angularaxis = dict(showticklabels=False, ticks='',
                               rotation=45,
                               direction = "clockwise",
                               gridcolor = "white")))

fig.update_yaxes(showline=True, linewidth=2, linecolor='white')
fig.show()
</code>```

Body:
I'm trying to change the background color of a radar chart in a way, that different value ranges get different colors, e.g. a radar chart with a range from 1-5, where 1-3 gets a red background color and 3-5 gets a green background color.
There is a possibility to change the color, but only for the whole circle.

Do you have any ideas?

EDIT

This is the sample code that I've used with the only possibilities that I've found to add colors.

import plotly.graph_objects as go

categories = ['processing cost','mechanical properties','chemical stability',
              'thermal stability', 'device integration']

fig = go.Figure()

fig.add_trace(go.Scatterpolar(
      r=[1, 5, 2, 2, 3],
      theta=categories,
      fill='toself',
      name='Product A'
))
fig.add_trace(go.Scatterpolar(
      r=[4, 3, 2.5, 1, 2],
      theta=categories,
      fill='toself',
      name='Product B'
))

fig.update_layout(
  paper_bgcolor="red",
  polar=dict(
    radialaxis=dict(
      color="red",
      visible=True,
      range=[0, 5]
    )),
  showlegend=False
)

fig.show()

Body:
There's no direct way to specify different background colors for different parts of the plot. But I if I understand correctly what you're aiming for here, you can do so with the correct combination of some go.Barpolar() and go.Scatterpolar() traces:

Code:

# imports
import plotly.graph_objects as go
import numpy as np

# categories:
categories = ['processing cost','mechanical properties','chemical stability',
              'thermal stability', 'device integration']

# values:
rVars1=[1, 5, 2, 2, 3]
rVars2=[4, 3, 2.5, 1, 2]

# colors
values = [3,5]
colors = ['rgba(255, 0, 0, 0.8)', 'rgba(0, 255, 0, 0.8)']

# some calcultations to place all elements
slices=len(rVars1)
fields=[max(rVars1)]*slices
circle_split = [360/slices]*(slices)
theta= 0
thetas=[0]
for t in circle_split:
    theta=theta+t
    thetas.append(theta)
thetas

# plotly
fig = go.Figure()

# "background"
for t in range(0, len(colors)):
    fig.add_trace(go.Barpolar(
        r=[values[t]],
        width=360,
        marker_color=[colors[t]],
        opacity=0.6,
        name = 'Range ' + str(t+1)
        #showlegend=False,
    ))
    t=t+1

# trace 1
fig.add_trace(go.Scatterpolar(
       text = categories,
        r = rVars1,
        mode = 'lines+text+markers',
        fill='toself',
        fillcolor='rgba(0, 0, 255, 0.4)',
        textposition='bottom center',
        marker = dict(color = 'blue'),
        name = 'Product A'))

# adjust layout
fig.update_layout(
    template=None,
    polar = dict(radialaxis = dict(gridwidth=0.5,
                               range=[0, max(fields)],
                              showticklabels=True, ticks='', gridcolor = "grey"),
                 angularaxis = dict(showticklabels=False, ticks='',
                               rotation=45,
                               direction = "clockwise",
                               gridcolor = "white")))

fig.update_yaxes(showline=True, linewidth=2, linecolor='white')
fig.show()

Edit: Multiple traces

Your sample code covers multiple traces. And that would quickly turn into a fine mess with my initial approach. Below is a snippet that covers multiple traces. To make this look good, I've put the category names at the edge of the circle in it's own trace with various text positions to make the names fall on the outside of the circle. Then I'm adding a single trace for each Product A and B. I hope this will be useful.

Plot 2:

Code 2:

# imports
import plotly.graph_objects as go
import numpy as np
import pandas as pd

# categories:
categories = ['processing cost','mechanical properties','chemical stability',
              'thermal stability', 'device integration']

# values:
rVars1=[1, 5, 2, 2, 3]
rVars2=[4, 3, 2.5, 1, 2]

rAllMax = max(rVars1+rVars2)

# colors
values = [3,5]
colors = ['rgba(255, 0, 0, 0.9)', 'rgba(0, 255, 0, 0.9)', ]

# some calcultations to place all elements
slices=len(rVars1)
fields=[max(rVars1)]*slices
circle_split = [360/slices]*(slices)
theta= 0
thetas=[0]
for t in circle_split:
    theta=theta+t
    thetas.append(theta)
thetas

# set up label positions
df_theta=pd.DataFrame({'theta':thetas, 'positions':['middle right', 'middle right',
                                                    'bottom center', 'middle left',
                                                    'middle left', 'middle left']})

# plotly
fig = go.Figure()

# "background"
for t in range(0, len(colors)):
    fig.add_trace(go.Barpolar(
        r=[values[t]],
        width=360,
        marker_color=[colors[t]],
        opacity=0.6,
        name = 'Range ' + str(t+1)
        #showlegend=False,
    ))
    t=t+1

for r, cat in enumerate(categories):
    #print(r, cat)
    fig.add_trace(go.Scatterpolar(
            text = cat,
            r = [rAllMax],
            theta = [thetas[r]],
            mode = 'lines+text+markers',
            fill='toself',
            fillcolor='rgba(255, 255, 255, 0.4)',
            line = dict(color='black'),
            #textposition='bottom center',
            textposition=df_theta[df_theta['theta']==thetas[r]]['positions'].values[0],
            marker = dict(line_color='white', color = 'black'),
            marker_symbol ='circle',
            name = cat,
            showlegend = False))

# trace 1
fig.add_trace(go.Scatterpolar(
        #text = categories,
        r = rVars1,
        mode = 'lines+text+markers',
        fill='toself',
        fillcolor='rgba(0, 0, 255, 0.4)',
        textposition='bottom center',
        marker = dict(color = 'blue'),
        marker_symbol ='square',
        name = 'Product A'))

# trace 2
fig.add_trace(go.Scatterpolar(
        #text = categories,
        r = rVars2,
        mode = 'lines+text+markers',
        fill='toself',
        fillcolor='rgba(0, 255, 0, 0.4)',
        textposition='bottom center',
        marker = dict(color = 'Green'),
        name = 'Product B'))

# adjust layout
fig.update_layout(
    template=None,
    polar = dict(radialaxis = dict(gridwidth=0.5,
                               range=[0, max(fields)],
                              showticklabels=True, ticks='', gridcolor = "grey"),
                 angularaxis = dict(showticklabels=False, ticks='',
                               rotation=45,
                               direction = "clockwise",
                               gridcolor = "white")))

fig.update_yaxes(showline=True, linewidth=2, linecolor='white')
fig.show()


问:
List of List C# question or something else any pointers in coding this
I need some help in coding this in C#

I have a list of Baskets and their Global_Weights in overall Basket in Kilograms:

Basket1, Basket2, Basket3, Basket4

0.1, 0.3, 0.9,0.6

Each of the Basket consist of the following thing:

Name,Level1, level2,Local_Weights

Name: String type

Level1:Double Type

Level2:Double Type

Local_Weights:Double Type

Each Basket will consist of N number of (Name,Level1, level2,Local_Weights) and there are M Baskets
N and M are variable which will be user Input

Should I be using List of list for this or something else any pointer on how to go about coding this?

How will I be accessing the members inside each of the Basket and perform calculation on them.

答:
Something like this perhaps?

```<code>class Basket
{
    private List<Payload> _payload = new List<Payload>();

    public List<Payload> Payload
    {
        get { return _payload; }
    }

    public double Weight
    {
        get { /* calculate total weight */; }
    }
}

class Payload
{
    public string Name { get; set; }
    public double Level1 { get; set; }
    public double Level2 { get; set; }
    public double Local_Weight { get; set; }
}
</code>```

And perhaps some usage, like this:

```<code>var baskets = new List<Basket>();

// Create a new basket with some payload
var newBasket = new Basket();
newBasket.Payload.Add(
    new Payload {Name = "MyName", Level1 = 1, Level2 = 2, Local_Weight = 3});
baskets.Add(newBasket);

// Access all payloads in all baskets for example
foreach (var payload in baskets.SelectMany(basket => basket.Payload))
{
    Console.WriteLine(payload.Name);
}
</code>```

Perhaps a book like Head First C# could also be of use. Good luck!

Body:
Something like this perhaps?

class Basket
{
    private List<Payload> _payload = new List<Payload>();

    public List<Payload> Payload
    {
        get { return _payload; }
    }

    public double Weight
    {
        get { /* calculate total weight */; }
    }
}

class Payload
{
    public string Name { get; set; }
    public double Level1 { get; set; }
    public double Level2 { get; set; }
    public double Local_Weight { get; set; }
}

And perhaps some usage, like this:

var baskets = new List<Basket>();

// Create a new basket with some payload
var newBasket = new Basket();
newBasket.Payload.Add(
    new Payload {Name = "MyName", Level1 = 1, Level2 = 2, Local_Weight = 3});
baskets.Add(newBasket);

// Access all payloads in all baskets for example
foreach (var payload in baskets.SelectMany(basket => basket.Payload))
{
    Console.WriteLine(payload.Name);
}

Perhaps a book like Head First C# could also be of use. Good luck!


问:
How to make the link inside Button change color on hover without hovering over link
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

```<code>btn:hover{
color: black;
}
</code>```

This does not work.

```<code>a:hover{
color:black
}
</code>```

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.

答:
Well you have few ways to do it.
Here are two examples, the one that you should probably use because you need to expand link dimensions because of the false click,and second is how you did it probably.

```<code>.btn:hover a{
  color:black;
}
</code>```

https://jsfiddle.net/zmirko/rf473kbs/15/

Body:
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

btn:hover{
color: black;
}

This does not work.

a:hover{
color:black
}

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.

Body:
Well you have few ways to do it.
Here are two examples, the one that you should probably use because you need to expand link dimensions because of the false click,and second is how you did it probably.

.btn:hover a{
  color:black;
}

https://jsfiddle.net/zmirko/rf473kbs/15/


问:
Mule Parse Template Multiple elements
I have a set of orders and want to generate an html document with the orders, I want to use parse template for that but I do not know how this will work for multiple order items in the payload. I want to generate something like this:

```<code>     <html>
      <body>
            <table border=4>
            <tr>
                    <th>Order No</th>
                    <th>Order Description</th>
                    <th>Provisioning Date</th>
            </tr>
            <tr>
                  <td>#[payload[0]['order_no']]</td>
                  <td>#[payload[0]['order_description']]</td>
                  <td>#[payload[0]['provisioning_date']]</td>
            </tr>
             <tr>
                  <td>#[payload[1]['order_no']]</td>
                  <td>#[payload[1]['order_description']]</td>
                  <td>#[payload[1]['provisioning_date']]</td>
            </tr>
               ...... to n orders
            </table>
    </body>
 </html>
</code>```

This is what I am trying to accomplish. How can I achieve this with parse-template?

答:
you can use javascript for looping in parse template:</p>

```<code>var addressList = #[payload]
for (var i = 0; i < payload.length; i++)
    document.getElementById('table').innerHTML += '<tr><td>' + addressList
    [i].order_no + '</td><td>' + addressList [i].order_description + '</td>
    <td>' + addressList[i].provisioning_date + '</td></tr>'
</code>```

Title: Mule Parse Template Multiple elements

Body:
I have a set of orders and want to generate an html document with the orders, I want to use parse template for that but I do not know how this will work for multiple order items in the payload. I want to generate something like this:

                    Order No
                    Order Description
                    Provisioning Date

                  #[payload[0]['order_no']]
                  #[payload[0]['order_description']]
                  #[payload[0]['provisioning_date']]

                  #[payload[1]['order_no']]
                  #[payload[1]['order_description']]
                  #[payload[1]['provisioning_date']]

               ...... to n orders

This is what I am trying to accomplish. How can I achieve this with parse-template?

Body:
you can use javascript for looping in parse template:

var addressList = #[payload]
for (var i = 0; i < payload.length; i++)
    document.getElementById('table').innerHTML += '<tr><td>' + addressList
    [i].order_no + '</td><td>' + addressList [i].order_description + '</td>
    <td>' + addressList[i].provisioning_date + '</td></tr>'


问:
Google Cloud Functions Public URL
How to set public route to HTTP GCF?
So, currently the default path something like this.

https://us-central1-poised-breaker-162819.cloudfunctions.net/function-1

But I want to use it in this way

https://myfunction.com

or

https://myfunction.com/thisroute

So actually it is the question of namespacing or even proxying of the requests to appropriate function. How this can be achieved?

Update 1

It seems, like we can use an Endpoints service for that. But it still unclear would it work with GCF or not.

答:
I think better not to use the HTTP invoke mechanism since it's doesn't require any of the authentication to invoke.
Try using other options instead -- https://cloud.google.com/functions/docs/calling</p>

Title: Google Cloud Functions Public URL


问:
How to feature-detect whether a browser supports dynamic ES6 module loading?

Background

The JavaScript ES6 specification supports module imports aka ES6 modules.

The static imports are quite obvious to use and do already have quite a good browser support, but dynamic import is still lacking behind.

So it is reasonably possible that your code uses static modules (when these would be not supported the code would not even execute), but the browser may miss support for dynamic import. Thus, detecting whether dynamic loading works (before trying to actually load code) may be useful. And as browser detection is frowned upon, of course I'd like to use feature detection.

Use cases may be to show an error, fallback to some other data/default/loading algorithm, provide developers with the advantages of dynamic loading (of data e.g. in a lazy-mode style) in a module, while allowing a fallback to passing the data directly etc. Basically, all the usual use cases where feature detection may be used.

Problem

Now, as dynamic modules are imported with import('/modules/my-module.js') one would obviously try to just detect whether the function is there, like this:

// this code does NOT work
if (import) {
    console.log("dynamic import supported")
}
```

I guess, for every(?) other function this would work, but the problem seems to be: As import is, respectively was, a reserved keyword in ECMAScript, and is now obviously also used for indicating the static import, it is not a real function. As MDN says it, it is "function-like".

Tries

import() results in a syntax error, so this is not really usable and import("") results in a Promise that rejects, which may be useful, but looks really hackish/like a workaround. Also, it requires an async context (await etc.) just for feature-detecting, which is not really nice.

typeeof import also fails directly, causing a syntax error, because of the keyword ("unexpected token: keyword 'import'").

So what is the best way to reliably feature-detect that a browser does support dynamic ES6 modules?

Edit: As I see some answers, please note that the solution should of course be as generally usable as possible, i.e. e.g. CSPs may prevent the use of eval and in PWAs you shall not assume you are always online, so just trying a request for some abitrary file may cause incorrect results.

答:
Three ways come to mind, all relying on getting a syntax error using import():

In eval (but runs afoul some CSPs)

Inserting a script tag

Using multiple static script tags

Common bits

You have the import() use foo or some such. That's an invalid module specifier unless it's in your import map, so shouldn't cause a network request. Use a catch handler to catch the load error, and a try/catch around the import() "call" just to catch any synchronous errors regarding the module specifier, to avoid cluttering up your error console. Note that on browsers that don't support it, I don't think you can avoid the syntax error in the console (at least, window.onerror didn't for me on Legacy Edge).

With eval

...since eval isn't necessarily evil; e.g., if guaranteed to use your own content (but, again, CSPs may limit):

let supported = false;
try {
    eval("try { import('foo').catch(() => {}); } catch (e) { }");
    supported = true;
} catch (e) {
}
document.body.insertAdjacentHTML("beforeend", `Supported: ${supported}`);```
</div>
</div>
</p>

<h2>Inserting a <code>script</code></h2>

```let supported = false;
const script = document.createElement("script");
script.textContent = "try { import('foo').catch(() => { }); } catch (e) { } supported = true;";
document.body.appendChild(script);
document.body.insertAdjacentHTML("beforeend", `Supported: ${supported}`);
```

<h2>Using multiple static <code>script</code> tags</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
let supported = false;
</script>
<script>
try {
    import("foo").catch(() => {});
} catch (e) {
}
supported = true;
</script>
<script>
document.body.insertAdjacentHTML("beforeend", `Supported: ${supported}`);
</script></code>```

Those all silently report true on Chrome, Chromium Edge, Firefox, etc.; and false on Legacy Edge (with a syntax error).

Body:
Background

The JavaScript ES6 specification supports module imports aka ES6 modules.

The static imports are quite obvious to use and do already have quite a good browser support, but dynamic import is still lacking behind.

So it is reasonably possible that your code uses static modules (when these would be not supported the code would not even execute), but the browser may miss support for dynamic import. Thus, detecting whether dynamic loading works (before trying to actually load code) may be useful. And as browser detection is frowned upon, of course I'd like to use feature detection.

Use cases may be to show an error, fallback to some other data/default/loading algorithm, provide developers with the advantages of dynamic loading (of data e.g. in a lazy-mode style) in a module, while allowing a fallback to passing the data directly etc. Basically, all the usual use cases where feature detection may be used.

Problem

Now, as dynamic modules are imported with import('/modules/my-module.js') one would obviously try to just detect whether the function is there, like this:

// this code does NOT work
if (import) {
    console.log("dynamic import supported")
}

I guess, for every(?) other function this would work, but the problem seems to be: As import is, respectively was, a reserved keyword in ECMAScript, and is now obviously also used for indicating the static import, it is not a real function. As MDN says it, it is "function-like".

Tries

import() results in a syntax error, so this is not really usable and import("") results in a Promise that rejects, which may be useful, but looks really hackish/like a workaround. Also, it requires an async context (await etc.) just for feature-detecting, which is not really nice.

typeeof import also fails directly, causing a syntax error, because of the keyword ("unexpected token: keyword 'import'").

So what is the best way to reliably feature-detect that a browser does support dynamic ES6 modules?

Edit: As I see some answers, please note that the solution should of course be as generally usable as possible, i.e. e.g. CSPs may prevent the use of eval and in PWAs you shall not assume you are always online, so just trying a request for some abitrary file may cause incorrect results.

Body:
Three ways come to mind, all relying on getting a syntax error using import():

In eval (but runs afoul some CSPs)

Inserting a script tag

Using multiple static script tags

Common bits

You have the import() use foo or some such. That's an invalid module specifier unless it's in your import map, so shouldn't cause a network request. Use a catch handler to catch the load error, and a try/catch around the import() "call" just to catch any synchronous errors regarding the module specifier, to avoid cluttering up your error console. Note that on browsers that don't support it, I don't think you can avoid the syntax error in the console (at least, window.onerror didn't for me on Legacy Edge).

With eval

...since eval isn't necessarily evil; e.g., if guaranteed to use your own content (but, again, CSPs may limit):

let supported = false;
try {
    eval("try { import('foo').catch(() => {}); } catch (e) { }");
    supported = true;
} catch (e) {
}
document.body.insertAdjacentHTML("beforeend", `Supported: ${supported}`);

Inserting a script

let supported = false;
const script = document.createElement("script");
script.textContent = "try { import('foo').catch(() => { }); } catch (e) { } supported = true;";
document.body.appendChild(script);
document.body.insertAdjacentHTML("beforeend", `Supported: ${supported}`);

Using multiple static script tags

<script>
let supported = false;
</script>
<script>
try {
    import("foo").catch(() => {});
} catch (e) {
}
supported = true;
</script>
<script>
document.body.insertAdjacentHTML("beforeend", `Supported: ${supported}`);
</script>

Those all silently report true on Chrome, Chromium Edge, Firefox, etc.; and false on Legacy Edge (with a syntax error).


问:
Azure Search: Indexed document count does not match the total number of uploaded records
I have been trying to upload 31 distinct records from the SQL server to azure cloud using Azure Search .NET SDK. I am able to upload the records without getting any technical errors. Even the logs confirm that all 31 records got indexed by return the status code as 200 for all 31 records

However in the azure portal when i see the document count on the index i only see 27. This means 4 records for some reason didnt get indexed. if two records have same party ids then only one gets uploaded.
In order to avoid this i created a new key in the dto which
is the combination of party id and tag id to ensure the keys are unique for every row. However this didnt help and i keep losing the rows which have duplicate partyIds.

Could someone please explain to me why the records are missing? i tried googling for related articles but no luck so far.

Below is the Object Dto

```<code>public class PartyTagMappingDto
{
    [Key] //combination of partyId and TagId
    public string Id { get; set; }

    [IsFilterable,IsSearchable]
    public string PartyId { get; set; }
    [IsSearchable,IsFilterable]
    public string TagId { get; set; }

    [IsSearchable,IsFilterable]
    public string TagName { get; set; }

    public string Description { get; set; }
}
</code>```

答:
Maybe this is possible you are sending duplicated data if you want to check please add this code you can find out where your 4 record going.

```<code>var batch = IndexBatch.New(actions);
try
{
    var data = GetIndexClient(IndexName).Documents.Index(batch);

    var passResultCount = data.Results.Where(x => x.Succeeded).Count();
    var failResultCount = data.Results.Where(x => x.Succeeded==false).Count();
    var MessageResult = data.Results.Where(x => !string.IsNullOrEmpty(x.ErrorMessage));
    var keyResult = data.Results.Where(x => !string.IsNullOrEmpty(x.Key)).Select(x=>x.Key).ToList();
    var unikKey = keyResult.Distinct().ToList();
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
}
catch (IndexBatchException e)
{
    // Sometimes when your Search service is under load, indexing will fail for some of the documents in
    // the batch. Depending on your application, you can take compensating actions like delaying and
    // retrying. For this simple demo, we just log the failed document keys and continue.
    Console.WriteLine(
        "Failed to index some of the documents: {0}",
        String.Join(", ", e.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key)));
}

</code>```

Note: in unikKey result can find out the actual result which one update or created in azure server.

Body:
I have been trying to upload 31 distinct records from the SQL server to azure cloud using Azure Search .NET SDK. I am able to upload the records without getting any technical errors. Even the logs confirm that all 31 records got indexed by return the status code as 200 for all 31 records

However in the azure portal when i see the document count on the index i only see 27. This means 4 records for some reason didnt get indexed. if two records have same party ids then only one gets uploaded.
In order to avoid this i created a new key in the dto which
is the combination of party id and tag id to ensure the keys are unique for every row. However this didnt help and i keep losing the rows which have duplicate partyIds.

Could someone please explain to me why the records are missing? i tried googling for related articles but no luck so far.

Below is the Object Dto

public class PartyTagMappingDto
{
    [Key] //combination of partyId and TagId
    public string Id { get; set; }

    [IsFilterable,IsSearchable]
    public string PartyId { get; set; }
    [IsSearchable,IsFilterable]
    public string TagId { get; set; }

    [IsSearchable,IsFilterable]
    public string TagName { get; set; }

    public string Description { get; set; }
}

Body:
Maybe this is possible you are sending duplicated data if you want to check please add this code you can find out where your 4 record going.

var batch = IndexBatch.New(actions);
try
{
    var data = GetIndexClient(IndexName).Documents.Index(batch);

    var passResultCount = data.Results.Where(x => x.Succeeded).Count();
    var failResultCount = data.Results.Where(x => x.Succeeded==false).Count();
    var MessageResult = data.Results.Where(x => !string.IsNullOrEmpty(x.ErrorMessage));
    var keyResult = data.Results.Where(x => !string.IsNullOrEmpty(x.Key)).Select(x=>x.Key).ToList();
    var unikKey = keyResult.Distinct().ToList();
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
}
catch (IndexBatchException e)
{
    // Sometimes when your Search service is under load, indexing will fail for some of the documents in
    // the batch. Depending on your application, you can take compensating actions like delaying and
    // retrying. For this simple demo, we just log the failed document keys and continue.
    Console.WriteLine(
        "Failed to index some of the documents: {0}",
        String.Join(", ", e.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key)));
}

Note: in unikKey result can find out the actual result which one update or created in azure server.


问:
Angular Universal + Firebase Cloud Function causing memory limit exceeded
Currently I'm working on an Angular 8 application which uses Firebase as backend.

I followed Jeff Delaney's Tutorial and suceeded to deploy on a cloud function called ssr my express server.

Everything works fine... almost ! When the ssr function is deployed, I can see an increase of memory usage of all my cloud functions even the smallest (1 transaction with a get and 1 update in the transaction) :

functions/src/index.ts

```<code>// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
import * as functions from 'firebase-functions';
// The Firebase Admin SDK to access Firestore.
import * as admin from 'firebase-admin';

admin.initializeApp();

export const ssr = functions.https.onRequest(require(`${process.cwd()}/dist/server`).app);

export const unsubscribeToMeal = functions.region('europe-west1').https.onCall((data) => {
  const mealDoc = admin.firestore().doc('meals/' + data.meal.uid);
  const adminDoc = admin.firestore().doc('users/' + data.meal.adminId);
  return admin.firestore().runTransaction(t => {
    return t.get(mealDoc)
      .then(doc => {
        const meal = doc.data();
        if (doc.exists && meal) {
          const promises = [];
          const participantIndex = meal.users.findIndex((element: any) => {
            return element.detail.uid === data.userToUnsubscribe.uid;
          });
          meal.users.splice(participantIndex, 1);
          const pendingRequest = meal.users.filter((user: any) => user.status === 'pending').length > 0;
          const p4 = t.update(mealDoc, { 'users': meal.users, 'participantId': admin.firestore.FieldValue.arrayRemove(data.userToUnsubscribe.uid), 'nbRemainingPlaces': meal['nbRemainingPlaces'] + 1, 'pendingRequest': pendingRequest })
          promises.push(p4);
          if (promises.length > 0) {
            return Promise.all(promises)
              .then(() => console.log('user unsubscribed'))
              .catch((err: any) => console.log('error unsubscribing user : ' + data.userToUnsubscribe.first_name + ' ' + data.userToUnsubscribe.last_name + ' of the meal ' + meal.uid + '. Err : ' + err))
          }
          else {
            // doc.data() will be undefined in this case
            throw new functions.https.HttpsError('not-found', 'no such document!');
          }
        } else {
          // doc.data() will be undefined in this case
          console.log('doc does not exist');
          throw new functions.https.HttpsError('not-found', 'no such document!');
        }
      })
  })
});
</code>```

Triggering unsubscribeToMeal function goes from 60MB memory usage without the ssr function deployed to 240MB memory usage with.

So I am wondering what is happening ? It looks like the express server app is bootstrap on each cloud function instance which causes an increase of memory use and so more billing.

I limited global variables to minimze cold start as Doug Stevenson explains here, so it shouldn't be that.

server.ts

```<code>(global as any).WebSocket = require('ws');
(global as any).XMLHttpRequest = require('xhr2');

import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
export const app = express();
import * as cookieParser from 'cookie-parser';
import { from } from 'rxjs';
app.use(cookieParser());

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist/browser');

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP, ngExpressEngine, provideModuleMap } = require('./dist/server/main');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', DIST_FOLDER);

// Example Express Rest API endpoints
// app.get('/api/**', (req, res) => { });
// Serve static files from /browser
app.get('*.*', express.static(DIST_FOLDER, {
  maxAge: '1y'
}));

// All regular routes use the Universal engine
app.get('*', (req: express.Request, res: express.Response) => {
  res.render('index2', {
    req
  });
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});
</code>```

Any solution to still have low memory usage (without increasing memory limit of the function) and at the same time ssr function with express server for angular universal ?

答:
Yes vitooh ! You need to split each function into a ts or js file. Here is my new structure:

/functions

/src

index.ts

/my_functs

ssr.ts

unsubscribeToMeal.ts

... other functions

Each function file need to start with exports = module.exports = functions...
For instance, here is the code for my new express function (you can compare to what I had in my first post)

```<code>functions/src/my_functs/ssr.ts file
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
import * as functions from 'firebase-functions';

exports = module.exports = functions.https.onRequest(require(`${process.cwd()}/dist/server`).app);
</code>```

Don't forget to import in each file what is needed such as "import * as functions from 'firebase-functions';". I also changed my index.ts file which is used when deploying to firebase with : firebase deploy --only functions and installed glob (npm i glob) from the functions folder.

```<code>functions/src/index.ts file

const glob = require("glob");
if (process.env.FUNCTION_NAME) {
  // Specific function requested, find and export only that function
  const functionName = process.env.FUNCTION_NAME;
  const files = glob.sync(`./my_functs/${functionName}.@(js|ts)`, { cwd: __dirname, ignore: './node_modules/**' });
  const file = files[0];
  exports[functionName] = require(file);
} else {
  // Name not specified, export all functions
  const files = glob.sync('./my_functs/*.@(js|ts)', { cwd: __dirname, ignore: './node_modules/**' });
  for (let f = 0, fl = files.length; f < fl; f++) {
    const file = files[f];
    const functionName = file.split('/').pop().slice(0, -3); // Strip off '.(js|ts)'
    exports[functionName] = require(file);
  }
}
</code>```

Body:
Currently I'm working on an Angular 8 application which uses Firebase as backend.

I followed Jeff Delaney's Tutorial and suceeded to deploy on a cloud function called ssr my express server.

Everything works fine... almost ! When the ssr function is deployed, I can see an increase of memory usage of all my cloud functions even the smallest (1 transaction with a get and 1 update in the transaction) :

functions/src/index.ts

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
import * as functions from 'firebase-functions';
// The Firebase Admin SDK to access Firestore.
import * as admin from 'firebase-admin';

admin.initializeApp();

export const ssr = functions.https.onRequest(require(`${process.cwd()}/dist/server`).app);

export const unsubscribeToMeal = functions.region('europe-west1').https.onCall((data) => {
  const mealDoc = admin.firestore().doc('meals/' + data.meal.uid);
  const adminDoc = admin.firestore().doc('users/' + data.meal.adminId);
  return admin.firestore().runTransaction(t => {
    return t.get(mealDoc)
      .then(doc => {
        const meal = doc.data();
        if (doc.exists && meal) {
          const promises = [];
          const participantIndex = meal.users.findIndex((element: any) => {
            return element.detail.uid === data.userToUnsubscribe.uid;
          });
          meal.users.splice(participantIndex, 1);
          const pendingRequest = meal.users.filter((user: any) => user.status === 'pending').length > 0;
          const p4 = t.update(mealDoc, { 'users': meal.users, 'participantId': admin.firestore.FieldValue.arrayRemove(data.userToUnsubscribe.uid), 'nbRemainingPlaces': meal['nbRemainingPlaces'] + 1, 'pendingRequest': pendingRequest })
          promises.push(p4);
          if (promises.length > 0) {
            return Promise.all(promises)
              .then(() => console.log('user unsubscribed'))
              .catch((err: any) => console.log('error unsubscribing user : ' + data.userToUnsubscribe.first_name + ' ' + data.userToUnsubscribe.last_name + ' of the meal ' + meal.uid + '. Err : ' + err))
          }
          else {
            // doc.data() will be undefined in this case
            throw new functions.https.HttpsError('not-found', 'no such document!');
          }
        } else {
          // doc.data() will be undefined in this case
          console.log('doc does not exist');
          throw new functions.https.HttpsError('not-found', 'no such document!');
        }
      })
  })
});

Triggering unsubscribeToMeal function goes from 60MB memory usage without the ssr function deployed to 240MB memory usage with.

So I am wondering what is happening ? It looks like the express server app is bootstrap on each cloud function instance which causes an increase of memory use and so more billing.

I limited global variables to minimze cold start as Doug Stevenson explains here, so it shouldn't be that.

server.ts

(global as any).WebSocket = require('ws');
(global as any).XMLHttpRequest = require('xhr2');

import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
export const app = express();
import * as cookieParser from 'cookie-parser';
import { from } from 'rxjs';
app.use(cookieParser());

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist/browser');

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP, ngExpressEngine, provideModuleMap } = require('./dist/server/main');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', DIST_FOLDER);

// Example Express Rest API endpoints
// app.get('/api/**', (req, res) => { });
// Serve static files from /browser
app.get('*.*', express.static(DIST_FOLDER, {
  maxAge: '1y'
}));

// All regular routes use the Universal engine
app.get('*', (req: express.Request, res: express.Response) => {
  res.render('index2', {
    req
  });
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});

Any solution to still have low memory usage (without increasing memory limit of the function) and at the same time ssr function with express server for angular universal ?

Body:
Yes vitooh ! You need to split each function into a ts or js file. Here is my new structure:

/functions

/src

index.ts

/my_functs

ssr.ts

unsubscribeToMeal.ts

... other functions

Each function file need to start with exports = module.exports = functions...
For instance, here is the code for my new express function (you can compare to what I had in my first post)

functions/src/my_functs/ssr.ts file
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
import * as functions from 'firebase-functions';

exports = module.exports = functions.https.onRequest(require(`${process.cwd()}/dist/server`).app);

Don't forget to import in each file what is needed such as "import * as functions from 'firebase-functions';". I also changed my index.ts file which is used when deploying to firebase with : firebase deploy --only functions and installed glob (npm i glob) from the functions folder.

functions/src/index.ts file

const glob = require("glob");
if (process.env.FUNCTION_NAME) {
  // Specific function requested, find and export only that function
  const functionName = process.env.FUNCTION_NAME;
  const files = glob.sync(`./my_functs/${functionName}.@(js|ts)`, { cwd: __dirname, ignore: './node_modules/**' });
  const file = files[0];
  exports[functionName] = require(file);
} else {
  // Name not specified, export all functions
  const files = glob.sync('./my_functs/*.@(js|ts)', { cwd: __dirname, ignore: './node_modules/**' });
  for (let f = 0, fl = files.length; f < fl; f++) {
    const file = files[f];
    const functionName = file.split('/').pop().slice(0, -3); // Strip off '.(js|ts)'
    exports[functionName] = require(file);
  }
}


问:
FutureBuilder works fine on the debug stage but on apk build always throws error
I have the following code which should show a process indicator during the process of fetching a JSON data from the web. It works fine when I run in the debug mode. But as soon as I make it to an apk, the app opens and with no time delays, it throws this error:

SocketException:

How to get rid of these issues?

```<code>import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Quize It Up'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    getCategories();
  }

  Future<List> getCategories() async {
    var url = 'https://opentdb.com/api_category.php';
    var response = await http
        .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});

    var jsonResponse = convert.jsonDecode(response.body);
    List categories = jsonResponse["trivia_categories"];

    return categories;
  }

  Widget mainGui() {
    return Container(
        child: FutureBuilder(
            future: getCategories(),
            builder: (BuildContext context, AsyncSnapshot<List> asyncSnapshot) {
              switch (asyncSnapshot.connectionState) {
                case ConnectionState.active:
                case ConnectionState.waiting:
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                case ConnectionState.none:
                  return RaisedButton(
                    onPressed: () => getCategories(),
                  );
                case ConnectionState.done:
                  if (asyncSnapshot.hasData)
                    return Text(asyncSnapshot.error.toString());
                  else
                    return ListView.builder(
                      itemCount: asyncSnapshot.data.length,
                      itemBuilder: (context, int index) {
                        return ListTile(
                          title: Text(asyncSnapshot.data[index]['name']),
                        );
                      },
                    );
              }
            }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        child: mainGui(),
      ),
    );
  }
}
</code>```

答: Yes the solution was to add <uses-permission android:name="android.permission.INTERNET"/> , but you have to add it in the AndroidManifest.xml file in the location /android/src/main in your flutter project

Body:
I have the following code which should show a process indicator during the process of fetching a JSON data from the web. It works fine when I run in the debug mode. But as soon as I make it to an apk, the app opens and with no time delays, it throws this error:

SocketException:

How to get rid of these issues?

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Quize It Up'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    getCategories();
  }

  Future<List> getCategories() async {
    var url = 'https://opentdb.com/api_category.php';
    var response = await http
        .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});

    var jsonResponse = convert.jsonDecode(response.body);
    List categories = jsonResponse["trivia_categories"];

    return categories;
  }

  Widget mainGui() {
    return Container(
        child: FutureBuilder(
            future: getCategories(),
            builder: (BuildContext context, AsyncSnapshot<List> asyncSnapshot) {
              switch (asyncSnapshot.connectionState) {
                case ConnectionState.active:
                case ConnectionState.waiting:
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                case ConnectionState.none:
                  return RaisedButton(
                    onPressed: () => getCategories(),
                  );
                case ConnectionState.done:
                  if (asyncSnapshot.hasData)
                    return Text(asyncSnapshot.error.toString());
                  else
                    return ListView.builder(
                      itemCount: asyncSnapshot.data.length,
                      itemBuilder: (context, int index) {
                        return ListTile(
                          title: Text(asyncSnapshot.data[index]['name']),
                        );
                      },
                    );
              }
            }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        child: mainGui(),
      ),
    );
  }
}


问:
How can I return in a ObsevableCollection<T> using C# Linq, all items if no one is selected or just selected items if at least one is selected?
I'm trying to get items in C# in an ObservableCollection<MyClassSelectable> using Linq and Lambda in the following cases :

Returns All items if no one is selected

Or

Returns just selected items if at least one is selected.

MyClassSelectable has a property named Selected of bool type.

Is it possible to do it, in only one Linq query line ?

Thank you.

答:
You can first group by the Selected property. This will get you 2 groups if there are selected and not-selected items OR 1 group if all items are either selected or not-selected. Then, order the groups by the selected property. This will put the group with selected items in the first place if there are 2 groups. Then, return the first group.

```<code>ObservableCollection<MyClassSelectable> myClassesSelectable;

List<MyClassSelectable> result = myClassesSelectable
    // group by the Selected property
    .GroupBy(mcs => mcs.Selected)
    // order (=> true first, false second)
    .OrderByDescending(g => g.Key)
    // return the first
    .FirstOrDefault()
    ?.ToList();
</code>```

Body:
You can first group by the Selected property. This will get you 2 groups if there are selected and not-selected items OR 1 group if all items are either selected or not-selected. Then, order the groups by the selected property. This will put the group with selected items in the first place if there are 2 groups. Then, return the first group.

ObservableCollection<MyClassSelectable> myClassesSelectable;

List<MyClassSelectable> result = myClassesSelectable
    // group by the Selected property
    .GroupBy(mcs => mcs.Selected)
    // order (=> true first, false second)
    .OrderByDescending(g => g.Key)
    // return the first
    .FirstOrDefault()
    ?.ToList();