问:
How to authorise with Openiddict in integration tests?
I've got an ASP.NET Core application.

The configuration regarding Openiddict is as follows:

builder.Services.AddOpenIddict()

       // Register the OpenIddict core components.
       .AddCore(options =>
                {
                    options.UseEntityFrameworkCore().UseDbContext<IdentityDataContext>();

                    options.Services.TryAddTransient<OpenIddictQuartzJob>();

                    // Note: TryAddEnumerable() is used here to ensure the initializer is registered only once.
                    builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<QuartzOptions>, OpenIddictQuartzConfiguration>());
                })

       // Register the OpenIddict server components.
       .AddServer(options =>
                      options.SetAuthorizationEndpointUris("/connect/authorize")
                             .SetLogoutEndpointUris("/connect/logout")
                             .SetTokenEndpointUris("/connect/token")
                             .SetUserinfoEndpointUris("/connect/userinfo")

                             // Mark the "email", "profile" and "roles" scopes as supported scopes.
                             .RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles)

                             // Note: the sample uses the code and refresh token flows but you can enable
                             // the other flows if you need to support implicit, password or client credentials.
                             .AllowAuthorizationCodeFlow()
                             .AllowRefreshTokenFlow()

                             // Register the signing and encryption credentials.
                             .AddDevelopmentEncryptionCertificate()
                             .AddDevelopmentSigningCertificate()

                             // Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
                             .UseAspNetCore()

                             .EnableAuthorizationEndpointPassthrough()
                             .EnableLogoutEndpointPassthrough()
                             .EnableUserinfoEndpointPassthrough()
                             .EnableTokenEndpointPassthrough()

                             .EnableStatusCodePagesIntegration())

       // Register the OpenIddict validation components.
       .AddValidation(options =>
                      {
                          // Import the configuration from the local OpenIddict server instance.
                          options.UseLocalServer();

                          // Register the ASP.NET Core host.
                          options.UseAspNetCore();
                      });

builder.Services.ConfigureApplicationCookie(options => options.LoginPath = "/account/auth");
```
<p>In tests I use a server factory:</p>
<pre class="lang-cs prettyprint-override"><code>public class InMemoryWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup>
    where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder) =>
        builder.ConfigureServices(services =>
        {
            var descriptor = services.SingleOrDefault(
                d => d.ServiceType ==
                     typeof(DbContextOptions<IdentityDataContext>))!;

            services.Remove(descriptor);

            services.AddDbContext<IdentityDataContext>(options =>
                                                       {
                                                           options.UseInMemoryDatabase("InMemoryDbForTesting");
                                                           // without this I get a NPE
                                                           options.UseOpenIddict();
                                                       });

            var sp = services.BuildServiceProvider();

            using var scope = sp.CreateScope();
            var scopedServices = scope.ServiceProvider;
            var db = scopedServices.GetRequiredService<IdentityDataContext>();

            db.Database.EnsureCreated();
        });

    protected override void ConfigureClient(HttpClient client)
    {
        base.ConfigureClient(client);

        // without this I get Bad request due to Opeiddict filters
        client.DefaultRequestHeaders.Host = client.BaseAddress!.Host;
    }
}
</code>```

The test looks like this (taken from here):

    [Fact]
    public async Task AuthorizedRequestReturnsValue()
    {
        var client = _factory.WithWebHostBuilder(builder => builder
                .ConfigureTestServices(services => services.AddAuthentication("TestScheme")
                .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("TestScheme", _ => { })))
            .CreateClient();

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("TestScheme");

        var response = await client.GetAsync(new Uri("https://localhost/connect/userinfo"));

        // I get Unauthorized here instead
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }
```
<p>The <code>/connect/userinfo</code> is as follows:</p>
<pre class="lang-cs prettyprint-override"><code>    [HttpGet("~/connect/userinfo")]
    [HttpPost("~/connect/userinfo")]
    [IgnoreAntiforgeryToken]
    [Produces("application/json")]
    public async Task<IActionResult> Userinfo()
    {
        var user = await _userManager.FindByIdAsync(User.GetClaim(Claims.Subject)!);

        if (user is null)
        {
            return Challenge(
                properties: new AuthenticationProperties(new Dictionary<string, string?>
                {
                    [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidToken,
                    [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                        "The specified access token is bound to an account that no longer exists.",
                }),
                authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
        }

        var claims = new Dictionary<string, object>(StringComparer.Ordinal)
        {
            // Note: the "sub" claim is a mandatory claim and must be included in the JSON response.
            [Claims.Subject] = await _userManager.GetUserIdAsync(user),
        };

        claims[Claims.Email] = (await _userManager.GetEmailAsync(user))!;
        claims[Claims.EmailVerified] = await _userManager.IsEmailConfirmedAsync(user);

        claims[Claims.Name] = (await _userManager.GetUserNameAsync(user))!;

        claims[Claims.PhoneNumber] = (await _userManager.GetPhoneNumberAsync(user))!;
        claims[Claims.PhoneNumberVerified] = await _userManager.IsPhoneNumberConfirmedAsync(user);

        claims[Claims.Role] = await _userManager.GetRolesAsync(user);

        // Note: the complete list of standard claims supported by the OpenID Connect specification
        // can be found here: http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
        return Ok(claims);
    }
</code>```

As far as I understand by default the TestScheme should be used for authentication. But it is not and OpenidDict takes precedence.

Is there a way to make authenticated/authorized requests in integration tests?

P.S. The test was working OK until I added OpenIddict. Before that I used Asp Identity directly for authentication

Body:
I've got an ASP.NET Core application.

The configuration regarding Openiddict is as follows:

builder.Services.AddOpenIddict()

       // Register the OpenIddict core components.
       .AddCore(options =>
                {
                    options.UseEntityFrameworkCore().UseDbContext<IdentityDataContext>();

                    options.Services.TryAddTransient<OpenIddictQuartzJob>();

                    // Note: TryAddEnumerable() is used here to ensure the initializer is registered only once.
                    builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<QuartzOptions>, OpenIddictQuartzConfiguration>());
                })

       // Register the OpenIddict server components.
       .AddServer(options =>
                      options.SetAuthorizationEndpointUris("/connect/authorize")
                             .SetLogoutEndpointUris("/connect/logout")
                             .SetTokenEndpointUris("/connect/token")
                             .SetUserinfoEndpointUris("/connect/userinfo")

                             // Mark the "email", "profile" and "roles" scopes as supported scopes.
                             .RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles)

                             // Note: the sample uses the code and refresh token flows but you can enable
                             // the other flows if you need to support implicit, password or client credentials.
                             .AllowAuthorizationCodeFlow()
                             .AllowRefreshTokenFlow()

                             // Register the signing and encryption credentials.
                             .AddDevelopmentEncryptionCertificate()
                             .AddDevelopmentSigningCertificate()

                             // Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
                             .UseAspNetCore()

                             .EnableAuthorizationEndpointPassthrough()
                             .EnableLogoutEndpointPassthrough()
                             .EnableUserinfoEndpointPassthrough()
                             .EnableTokenEndpointPassthrough()

                             .EnableStatusCodePagesIntegration())

       // Register the OpenIddict validation components.
       .AddValidation(options =>
                      {
                          // Import the configuration from the local OpenIddict server instance.
                          options.UseLocalServer();

                          // Register the ASP.NET Core host.
                          options.UseAspNetCore();
                      });

builder.Services.ConfigureApplicationCookie(options => options.LoginPath = "/account/auth");

In tests I use a server factory:

public class InMemoryWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup>
    where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder) =>
        builder.ConfigureServices(services =>
        {
            var descriptor = services.SingleOrDefault(
                d => d.ServiceType ==
                     typeof(DbContextOptions<IdentityDataContext>))!;

            services.Remove(descriptor);

            services.AddDbContext<IdentityDataContext>(options =>
                                                       {
                                                           options.UseInMemoryDatabase("InMemoryDbForTesting");
                                                           // without this I get a NPE
                                                           options.UseOpenIddict();
                                                       });

            var sp = services.BuildServiceProvider();

            using var scope = sp.CreateScope();
            var scopedServices = scope.ServiceProvider;
            var db = scopedServices.GetRequiredService<IdentityDataContext>();

            db.Database.EnsureCreated();
        });

    protected override void ConfigureClient(HttpClient client)
    {
        base.ConfigureClient(client);

        // without this I get Bad request due to Opeiddict filters
        client.DefaultRequestHeaders.Host = client.BaseAddress!.Host;
    }
}

The test looks like this (taken from here):

    [Fact]
    public async Task AuthorizedRequestReturnsValue()
    {
        var client = _factory.WithWebHostBuilder(builder => builder
                .ConfigureTestServices(services => services.AddAuthentication("TestScheme")
                .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("TestScheme", _ => { })))
            .CreateClient();

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("TestScheme");

        var response = await client.GetAsync(new Uri("https://localhost/connect/userinfo"));

        // I get Unauthorized here instead
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }

The /connect/userinfo is as follows:

    [HttpGet("~/connect/userinfo")]
    [HttpPost("~/connect/userinfo")]
    [IgnoreAntiforgeryToken]
    [Produces("application/json")]
    public async Task<IActionResult> Userinfo()
    {
        var user = await _userManager.FindByIdAsync(User.GetClaim(Claims.Subject)!);

        if (user is null)
        {
            return Challenge(
                properties: new AuthenticationProperties(new Dictionary<string, string?>
                {
                    [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidToken,
                    [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                        "The specified access token is bound to an account that no longer exists.",
                }),
                authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
        }

        var claims = new Dictionary<string, object>(StringComparer.Ordinal)
        {
            // Note: the "sub" claim is a mandatory claim and must be included in the JSON response.
            [Claims.Subject] = await _userManager.GetUserIdAsync(user),
        };

        claims[Claims.Email] = (await _userManager.GetEmailAsync(user))!;
        claims[Claims.EmailVerified] = await _userManager.IsEmailConfirmedAsync(user);

        claims[Claims.Name] = (await _userManager.GetUserNameAsync(user))!;

        claims[Claims.PhoneNumber] = (await _userManager.GetPhoneNumberAsync(user))!;
        claims[Claims.PhoneNumberVerified] = await _userManager.IsPhoneNumberConfirmedAsync(user);

        claims[Claims.Role] = await _userManager.GetRolesAsync(user);

        // Note: the complete list of standard claims supported by the OpenID Connect specification
        // can be found here: http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
        return Ok(claims);
    }

As far as I understand by default the TestScheme should be used for authentication. But it is not and OpenidDict takes precedence.

Is there a way to make authenticated/authorized requests in integration tests?

P.S. The test was working OK until I added OpenIddict. Before that I used Asp Identity directly for authentication


来源: stackexchange

问:
Flutter Testing: Dependency Injection
When my Widget is build, I want a logger class to register this. (In real life this is written to a database).
Now in a WidgetTest, I want to make sure this logger is really called. How can I achieve this?

Here the code that needs to be tested:

```<code>import 'package:flutter/material.dart';

class Logger {
  static log(String text) {
    debugPrint("Real logger logs: $text");
  }
}

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});

  @override
  Widget build(BuildContext context) {
    Logger.log("MyWidget built.");
    return Scaffold(
      body: Text("Widget under test"),
    );
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Flutter Testing: Dependency Injection

Body:
When my Widget is build, I want a logger class to register this. (In real life this is written to a database).
Now in a WidgetTest, I want to make sure this logger is really called. How can I achieve this?

Here the code that needs to be tested:

import 'package:flutter/material.dart';

class Logger {
  static log(String text) {
    debugPrint("Real logger logs: $text");
  }
}

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});

  @override
  Widget build(BuildContext context) {
    Logger.log("MyWidget built.");
    return Scaffold(
      body: Text("Widget under test"),
    );
  }
}


问:
default date range selection in React-daterangepicker
I do not want to pre-select any value from date range in react-daterangepicker, by default it gives some value already selected if i choose for defined date range?

try to give its initialsetting prop a value start : "", end: "" but it gives undefined


问:
how to convert any language to Devanagari Unicode using core php?
I want to convert any language to devnagri without select any language like "aaye" to "आए" and print in the array like "hello" to array('h','e','l','l','o') in core php ?

enter image description here

in this image display after clicke search button "a,a,y,e" but I want this in Hindi "आ,ए"


问:
Pandas mutiples rows to column with data
I have this data:

```<code>product_code,field_type1,field_type1_id,Field_type1_name,field_type2,field_type2_id,Field_type2_name,field_type3,field_type1_id3,Field_type1_name3,field_type4,field_type4_id,Field_type4_name,field_type5,field_type5_id,Field_type5_name,field_type6,field_type6_id,Field_type6_name,field_type7,field_type7_id,Field_type7_name,field_type8,field_type8_id,Field_type8_name,field_type9,field_type9_id,Field_type9_name,field_type10,field_type10_id,Field_type10_name,field_type11,field_type11_id,Field_type11_name,field_type12,field_type12_id,Field_type12_name,field_type13,field_type13_id,Field_type13_name
300413,Marca,28,Brother,2,Tipo,178,Equipo multifuncion,61,Tecnologia impresion,1,Laser,62,Velocidad impresion,4,+ de 30 pag/minuto,63,Tamano impresion,2,Din a4,,,,,,,,,,,,,,,,,,,,
300003,Uso,5,Lapiz,1,Marca,417,Tombow,2,Tipo,218,Goma,,,,,,,,,,,,,,,,,,,,,,,,,,,,
166133,Capacidad,61,1 l,36,Presentacion,6,Tetra brick,1,Marca,373,Alpro,2,Tipo,989,Bebida vegetal,,,,,,,,,,,,,,,,,,,,,,,,
</code>```

I want this output:

```<code>Product_code,Marca_id,Marca_name
300413,28,Brother
300003,417,Tombow
166133,373,Alpor
</code>```

I have 39 colum, grouped by 3 colum, type,id and name but Marca type can located in any of 13(total 39) fields.

not much idea, if use pivot, melt or need hardcode with loops and other conditional.

Body:
I have this data:

product_code,field_type1,field_type1_id,Field_type1_name,field_type2,field_type2_id,Field_type2_name,field_type3,field_type1_id3,Field_type1_name3,field_type4,field_type4_id,Field_type4_name,field_type5,field_type5_id,Field_type5_name,field_type6,field_type6_id,Field_type6_name,field_type7,field_type7_id,Field_type7_name,field_type8,field_type8_id,Field_type8_name,field_type9,field_type9_id,Field_type9_name,field_type10,field_type10_id,Field_type10_name,field_type11,field_type11_id,Field_type11_name,field_type12,field_type12_id,Field_type12_name,field_type13,field_type13_id,Field_type13_name
300413,Marca,28,Brother,2,Tipo,178,Equipo multifuncion,61,Tecnologia impresion,1,Laser,62,Velocidad impresion,4,+ de 30 pag/minuto,63,Tamano impresion,2,Din a4,,,,,,,,,,,,,,,,,,,,
300003,Uso,5,Lapiz,1,Marca,417,Tombow,2,Tipo,218,Goma,,,,,,,,,,,,,,,,,,,,,,,,,,,,
166133,Capacidad,61,1 l,36,Presentacion,6,Tetra brick,1,Marca,373,Alpro,2,Tipo,989,Bebida vegetal,,,,,,,,,,,,,,,,,,,,,,,,

I want this output:

Product_code,Marca_id,Marca_name
300413,28,Brother
300003,417,Tombow
166133,373,Alpor

I have 39 colum, grouped by 3 colum, type,id and name but Marca type can located in any of 13(total 39) fields.

not much idea, if use pivot, melt or need hardcode with loops and other conditional.


问:
I am trying to post image on Facebook using asp.net but I am getting exception as Thread was being aborted
C# Code

I am using ASPSnippets.FaceBookAPI to upload image on Facebook in local machine I get exception as Thread was being aborted and if I try on live domain it says "Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings"

```<code>protected void Page_Load(object sender, EventArgs e)
{
    FaceBookConnect.API_Key = "gfafsa";
    FaceBookConnect.API_Secret = "bdhsafvhj";
    if (!IsPostBack)
    {
        try
        {
            string code = Request.QueryString["code"];
            if (!string.IsNullOrEmpty(code))
            {

                if (Session["File"] != null)
                {
                    FaceBookConnect.PostFile(code, "me/photos", (HttpPostedFile)Session["File"], Session["Message"].ToString());
                }
                else
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("message", Session["Message"].ToString());
                    FaceBookConnect.Post(code, "me/feed", data);
                }

                Session["File"] = null;
                Session["Message"] = null;
            }
        }
        catch(Exception ex)
        {

        }
        finally
        {

        }
    }
}

protected void lbtnSubmit_Click(object sender, EventArgs e)
{
    try
    {
        if (FileUpload1.HasFile)
            Session["File"] = FileUpload1.PostedFile;
        Session["Message"] = txtCaption.Text;
       FaceBookConnect.Authorize("user_photos,publish_actions", Request.Url.AbsoluteUri.Split('?')[0]);
        Response.Redirect("", false);
    }
    catch(Exception ex)
    {
        Response.Write(ex);
    }
    finally
    {

    }
}
</code>```

Body:
C# Code

I am using ASPSnippets.FaceBookAPI to upload image on Facebook in local machine I get exception as Thread was being aborted and if I try on live domain it says "Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings"

protected void Page_Load(object sender, EventArgs e)
{
    FaceBookConnect.API_Key = "gfafsa";
    FaceBookConnect.API_Secret = "bdhsafvhj";
    if (!IsPostBack)
    {
        try
        {
            string code = Request.QueryString["code"];
            if (!string.IsNullOrEmpty(code))
            {

                if (Session["File"] != null)
                {
                    FaceBookConnect.PostFile(code, "me/photos", (HttpPostedFile)Session["File"], Session["Message"].ToString());
                }
                else
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("message", Session["Message"].ToString());
                    FaceBookConnect.Post(code, "me/feed", data);
                }

                Session["File"] = null;
                Session["Message"] = null;
            }
        }
        catch(Exception ex)
        {

        }
        finally
        {

        }
    }
}

protected void lbtnSubmit_Click(object sender, EventArgs e)
{
    try
    {
        if (FileUpload1.HasFile)
            Session["File"] = FileUpload1.PostedFile;
        Session["Message"] = txtCaption.Text;
       FaceBookConnect.Authorize("user_photos,publish_actions", Request.Url.AbsoluteUri.Split('?')[0]);
        Response.Redirect("", false);
    }
    catch(Exception ex)
    {
        Response.Write(ex);
    }
    finally
    {

    }
}


问:
How to resolve ANR for MapsInitializer.initialize?
The MapsInitializer.initialize method forces you to be called on main thread, and yet it causes ANRs.

ANR:

```<code>ii: Application Not Responding for at least 5000 ms.
    at android.os.BinderProxy.transactNative(Binder.java)
    at android.os.BinderProxy.transact(Binder.java:511)
    at android.content.ContentProviderProxy.call(ContentProviderNative.java:644)
    at android.content.ContentResolver.call(ContentResolver.java:1447)
    at com.google.maps.api.android.lib6.drd.o.A(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:41)
    at com.google.maps.api.android.lib6.impl.ay.a(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:8)
    at fjj.a(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:1)
    at com.google.android.gms.maps.internal.CreatorImpl.c(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:35)
    at com.google.android.gms.maps.internal.CreatorImpl.logInitialization(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:1)
    at com.google.android.gms.maps.internal.i.bo(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:5)
    at baw.onTransact(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:4)
    at android.os.Binder.transact(Binder.java:392)
    at js8.A(com.google.android.gms:play-services-maps@@18.1.0:8)
    at h49.N0(com.google.android.gms:play-services-maps@@18.1.0:13)
    at q84.a(com.google.android.gms:play-services-maps@@18.1.0:99)
</code>```

Running on non main thread:

```<code> java.lang.IllegalStateException: Method addObserver must be called on the main thread
                                at xy.j(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:0)
                                at xy.b(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:1)
                                at com.google.android.libraries.geo.crash.monitoring.UncleanTerminationDetector.i(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:6)
                                at com.google.android.gms.maps.internal.CreatorImpl.c(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:53)
                                at com.google.android.gms.maps.internal.CreatorImpl.logInitialization(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:1)
                                at com.google.android.gms.maps.internal.i.bm(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:5)
                                at ayk.onTransact(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:4)
                                at android.os.Binder.transact(Binder.java:1164)
                                at com.google.android.gms.internal.maps.zza.zzc(com.google.android.gms:play-services-maps@@18.1.0:2)
                                at com.google.android.gms.maps.internal.zze.zzl(com.google.android.gms:play-services-maps@@18.1.0:4)
                                at com.google.android.gms.maps.MapsInitializer.initialize(com.google.android.gms:play-services-maps@@18.1.0:12)
</code>```

Body:
The MapsInitializer.initialize method forces you to be called on main thread, and yet it causes ANRs.

ANR:

ii: Application Not Responding for at least 5000 ms.
    at android.os.BinderProxy.transactNative(Binder.java)
    at android.os.BinderProxy.transact(Binder.java:511)
    at android.content.ContentProviderProxy.call(ContentProviderNative.java:644)
    at android.content.ContentResolver.call(ContentResolver.java:1447)
    at com.google.maps.api.android.lib6.drd.o.A(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:41)
    at com.google.maps.api.android.lib6.impl.ay.a(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:8)
    at fjj.a(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:1)
    at com.google.android.gms.maps.internal.CreatorImpl.c(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:35)
    at com.google.android.gms.maps.internal.CreatorImpl.logInitialization(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:1)
    at com.google.android.gms.maps.internal.i.bo(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:5)
    at baw.onTransact(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200031.477283333.477283333:4)
    at android.os.Binder.transact(Binder.java:392)
    at js8.A(com.google.android.gms:play-services-maps@@18.1.0:8)
    at h49.N0(com.google.android.gms:play-services-maps@@18.1.0:13)
    at q84.a(com.google.android.gms:play-services-maps@@18.1.0:99)

Running on non main thread:

 java.lang.IllegalStateException: Method addObserver must be called on the main thread
                                at xy.j(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:0)
                                at xy.b(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:1)
                                at com.google.android.libraries.geo.crash.monitoring.UncleanTerminationDetector.i(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:6)
                                at com.google.android.gms.maps.internal.CreatorImpl.c(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:53)
                                at com.google.android.gms.maps.internal.CreatorImpl.logInitialization(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:1)
                                at com.google.android.gms.maps.internal.i.bm(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:5)
                                at ayk.onTransact(:com.google.android.gms.policy_maps_core_dynamite@223812200@223812200065.477283333.477283333:4)
                                at android.os.Binder.transact(Binder.java:1164)
                                at com.google.android.gms.internal.maps.zza.zzc(com.google.android.gms:play-services-maps@@18.1.0:2)
                                at com.google.android.gms.maps.internal.zze.zzl(com.google.android.gms:play-services-maps@@18.1.0:4)
                                at com.google.android.gms.maps.MapsInitializer.initialize(com.google.android.gms:play-services-maps@@18.1.0:12)


问:
Is it possible to redirect to the localhost of the user in LemonLdap
In my LemonLDAP server, I try to configure an host for redirect user connection to the localhost app of the connected user (where App is running in local).

Localhost seems to be redirect to "server localhost" and not the localhost of the computer used by user.

It is possible to apply this configuration ?


问:
I want to run spark with yarn, but I get a java.net.ConnectException error
I want to run spark on yarn

```<code>root@server01:/export/server/spark# bin/spark-shell --master yarn
</code>```

But it goes to error like this

```<code>root@server01:/export/server/spark# bin/spark-shell --master yarn
22/12/06 07:51:42 WARN Utils: Your hostname, server01 resolves to a loopback address: 127.0.1.1; using 192.168.40.133 instead (on interface ens33)
22/12/06 07:51:42 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
22/12/06 07:51:51 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
22/12/06 07:57:58 ERROR YarnClientSchedulerBackend: The YARN application has already ended! It might have been killed or the Application Master may have failed to start. Check the YARN application logs for more details.
22/12/06 07:57:58 ERROR SparkContext: Error initializing SparkContext.
org.apache.spark.SparkException: Application application_1670312235175_0001 failed 2 times due to Error launching appattempt_1670312235175_0001_000002. Got exception: java.net.ConnectException: Call From localhost/127.0.0.1 to localhost:41647 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
</code>```

spark-defaults.conf

```<code>spark.eventLog.enabled     true
spark.eventLog.dir         hdfs://node1:8020/sparklog/
spark.eventLog.compress    true
# spark-yarn jar package
spark.yarn.jars  hdfs://node1:8020/spark/jars/*
# spark and yarn history server
spark.yarn.historyServer.address    node1:18080
</code>```

yarn-site.xml

```<code>    <property>
        <name>yarn.log.server.url</name>
        <value>http://node1:19888/jobhistory/logs</value>
    </property>

    <property>
      <name>yarn.log-aggregation.retain-seconds</name>
      <value>604800</value>
    </property>
</code>```

I verify the spark.yarn.historyServer to node1:19888 and restart spark,but it doesn't work.

Body:
I want to run spark on yarn

root@server01:/export/server/spark# bin/spark-shell --master yarn

But it goes to error like this

root@server01:/export/server/spark# bin/spark-shell --master yarn
22/12/06 07:51:42 WARN Utils: Your hostname, server01 resolves to a loopback address: 127.0.1.1; using 192.168.40.133 instead (on interface ens33)
22/12/06 07:51:42 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
22/12/06 07:51:51 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
22/12/06 07:57:58 ERROR YarnClientSchedulerBackend: The YARN application has already ended! It might have been killed or the Application Master may have failed to start. Check the YARN application logs for more details.
22/12/06 07:57:58 ERROR SparkContext: Error initializing SparkContext.
org.apache.spark.SparkException: Application application_1670312235175_0001 failed 2 times due to Error launching appattempt_1670312235175_0001_000002. Got exception: java.net.ConnectException: Call From localhost/127.0.0.1 to localhost:41647 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused

spark-defaults.conf

spark.eventLog.enabled     true
spark.eventLog.dir         hdfs://node1:8020/sparklog/
spark.eventLog.compress    true
# spark-yarn jar package
spark.yarn.jars  hdfs://node1:8020/spark/jars/*
# spark and yarn history server
spark.yarn.historyServer.address    node1:18080

yarn-site.xml

    <property>
        <name>yarn.log.server.url</name>
        <value>http://node1:19888/jobhistory/logs</value>
    </property>

    <property>
      <name>yarn.log-aggregation.retain-seconds</name>
      <value>604800</value>
    </property>

I verify the spark.yarn.historyServer to node1:19888 and restart spark,but it doesn't work.


问:
On submit form model comes null to the cotroller
The View:
@model NPI-Project.ViewModels.Search

@using (Html.BeginForm("NpiSearch", "Home", FormMethod.Post))
{

@Html.LabelFor(m => m.LastOrgName, "Provider Name", new { @class="form-label d-md-block" })
@Html.TextBoxFor(m => m.LastOrgName, new { @class = "form-control" })

@Html.LabelFor(m => m.FirstName, "First Name", new { @class="form-label d-none d-md-block" })
@Html.TextBoxFor(m => m.FirstName, new { @class="form-control" })

@Html.LabelFor(m => m.Npi, "NPI Number", new { @class="form-label d-md-block" })
@Html.TextBoxFor(m => m.Npi, new { @class="form-control" })

@Html.LabelFor(m => m.City, "Location", new { @class="form-label d-md-block" })
@Html.TextBoxFor(m => m.City, new { @class="form-control" })

/Find Providers

}

The controller:
[HttpPost]
public IActionResult NpiSearch(Search model)
{
the model comes with null properties here
}

I deleted some html so this is more readable.
I tried with Http.Get and Post. Tried adding [FromForm] before the param. Have no idea what is wrong. Please help.
Sorry if it looks ugly. First time posting a question.


问:
Binding data to @progress/kendo-drawing path Angular
I'm integrating angular kendo-drawing in my project. The main purpose of using this package is to draw shapes.

I was successfully able to draw the shapes based on my API response.

I want to bind data to each shape I have drawn using kendo drawing.

Can someone please help me with this?

I have followed the below tutorial to integrate kendo-drawing in my project
https://www.telerik.com/kendo-angular-ui/components/drawing/basic-shapes/


问:
Python sqlalchemy catch sql message
Working with Python and SQL Server I'm trying to catch the SQL Messages (PRINT or RAISERROR) that may ossure when exeuting SQL command or stored procedure.

On the SQL Server I have the following procedure (simplified for my question)

```<code>CREATE PROCEDURE dbo.pyTest (@n int)
AS
SET NOCOUNT ON
IF OBJECT_ID('dbo.tablename') IS NULL RAISERROR(N'Error. Destination table not found.',0,0)
ELSE INSERT INTO dbo.tablename VALUES (@n);
</code>```

In Python I'm executing this script

```<code>server = 'server_name'
db = 'database_name'
from sqlalchemy import create_engine
engine = create_engine(f"mssql+pyodbc://{server}/{db}?trusted_connection=yes&driver=ODBC+Driver+17+for+SQL+Server")
query="INSERT INTO dbo.tablename VALUES (1)"
#query="SELECT GETDATE()"
with engine.begin() as conn:
    conn.execute(query)

</code>```

My question is: How do I catch the messages being produced from the stored procedure?

When I execute "EXEC dbo.pyTest 1" in SSMS

I get the following text in the Messages tab

"Error. Destination table not found."

But when I do the same in Python I get "Process finished with exit code 0"

I have been reading a lot of suggestions from Goggle, but have not been able to find similar question.

Title: Python sqlalchemy catch sql message

Body:
Working with Python and SQL Server I'm trying to catch the SQL Messages (PRINT or RAISERROR) that may ossure when exeuting SQL command or stored procedure.

On the SQL Server I have the following procedure (simplified for my question)

CREATE PROCEDURE dbo.pyTest (@n int)
AS
SET NOCOUNT ON
IF OBJECT_ID('dbo.tablename') IS NULL RAISERROR(N'Error. Destination table not found.',0,0)
ELSE INSERT INTO dbo.tablename VALUES (@n);

In Python I'm executing this script

server = 'server_name'
db = 'database_name'
from sqlalchemy import create_engine
engine = create_engine(f"mssql+pyodbc://{server}/{db}?trusted_connection=yes&driver=ODBC+Driver+17+for+SQL+Server")
query="INSERT INTO dbo.tablename VALUES (1)"
#query="SELECT GETDATE()"
with engine.begin() as conn:
    conn.execute(query)

My question is: How do I catch the messages being produced from the stored procedure?

When I execute "EXEC dbo.pyTest 1" in SSMS

I get the following text in the Messages tab

"Error. Destination table not found."

But when I do the same in Python I get "Process finished with exit code 0"

I have been reading a lot of suggestions from Goggle, but have not been able to find similar question.


问:
react-pdf : avoid fetching twice the pdf file
I'm using react-pdf to display a pdf file in the following way :

```<code>import React, { FC, useState } from 'react'
import { Document, Page, pdfjs } from 'react-pdf'

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`

export interface PDFProps {
  url: string
  width?: number
  onLoadError?: Document['props']['onLoadError']
  onSuccess?: () => void
}

export const PDF: FC<PDFProps> = ({ url, onSuccess }) => {
  const [pageNumbers, setPageNumbers] = useState<number[]>([])

  const onLoadSuccess: Document['props']['onLoadSuccess'] = ({ numPages }) => {
    if (numPages !== pageNumbers.length) {
      const pagesIndex = [...Array(numPages).keys()].map(
        (pageIndex) => pageIndex + 1,
      )

      setPageNumbers(pagesIndex)
      if (onSuccess) {
        onSuccess()
      }
    }
  }

  return (
    <Document
      options={{
        standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts`,
      }}
      file={{ url, withCredentials: true }}
      onLoadSuccess={onLoadSuccess}
    >
      {pageNumbers.map((pageNumber: number) => (
        <div key={pageNumber}>
          <Page pageNumber={pageNumber} />
        </div>
      ))}
    </Document>
  )
}
</code>```

Almost everything is working well, the file is correctly opened and I can navigate through all the pages but I have the following issue : When the document loads for the first time, it does a network request to fetch the file, but then the onSuccess callback is called and this one affect the state (setPageNumbers) causing the document to rerender and so doing again the same network request to fetch the file, this could be seen in the network tab :

I've tried memoizing the file object following this discussion but this didn't change anything :

```<code>import React, { FC, useMemo, useState } from 'react'
import { Document, Page, pdfjs } from 'react-pdf'

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`

export interface PDFProps {
  url: string
  width?: number
  onLoadError?: Document['props']['onLoadError']
  onSuccess?: () => void
}

export const PDF: FC<PDFProps> = ({ url, onSuccess }) => {
  const [pageNumbers, setPageNumbers] = useState<number[]>([])

  const data = { url, withCredentials: true }

  const file = useMemo(() => data, [data])

  const onLoadSuccess: Document['props']['onLoadSuccess'] = ({ numPages }) => {
    if (numPages !== pageNumbers.length) {
      const pagesIndex = [...Array(numPages).keys()].map(
        (pageIndex) => pageIndex + 1,
      )

      setPageNumbers(pagesIndex)
      if (onSuccess) {
        onSuccess()
      }
    }
  }

  return (
    <Document
      options={{
        standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts`,
      }}
      file={file}
      onLoadSuccess={onLoadSuccess}
    >
      {pageNumbers.map((pageNumber: number) => (
        <div key={pageNumber}>
          <Page pageNumber={pageNumber} />
        </div>
      ))}
    </Document>
  )
}
</code>```

Body:
I'm using react-pdf to display a pdf file in the following way :

import React, { FC, useState } from 'react'
import { Document, Page, pdfjs } from 'react-pdf'

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`

export interface PDFProps {
  url: string
  width?: number
  onLoadError?: Document['props']['onLoadError']
  onSuccess?: () => void
}

export const PDF: FC<PDFProps> = ({ url, onSuccess }) => {
  const [pageNumbers, setPageNumbers] = useState<number[]>([])

  const onLoadSuccess: Document['props']['onLoadSuccess'] = ({ numPages }) => {
    if (numPages !== pageNumbers.length) {
      const pagesIndex = [...Array(numPages).keys()].map(
        (pageIndex) => pageIndex + 1,
      )

      setPageNumbers(pagesIndex)
      if (onSuccess) {
        onSuccess()
      }
    }
  }

  return (
    <Document
      options={{
        standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts`,
      }}
      file={{ url, withCredentials: true }}
      onLoadSuccess={onLoadSuccess}
    >
      {pageNumbers.map((pageNumber: number) => (

          <Page pageNumber={pageNumber} />

      ))}
    </Document>
  )
}

Almost everything is working well, the file is correctly opened and I can navigate through all the pages but I have the following issue : When the document loads for the first time, it does a network request to fetch the file, but then the onSuccess callback is called and this one affect the state (setPageNumbers) causing the document to rerender and so doing again the same network request to fetch the file, this could be seen in the network tab :

I've tried memoizing the file object following this discussion but this didn't change anything :

import React, { FC, useMemo, useState } from 'react'
import { Document, Page, pdfjs } from 'react-pdf'

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`

export interface PDFProps {
  url: string
  width?: number
  onLoadError?: Document['props']['onLoadError']
  onSuccess?: () => void
}

export const PDF: FC<PDFProps> = ({ url, onSuccess }) => {
  const [pageNumbers, setPageNumbers] = useState<number[]>([])

  const data = { url, withCredentials: true }

  const file = useMemo(() => data, [data])

  const onLoadSuccess: Document['props']['onLoadSuccess'] = ({ numPages }) => {
    if (numPages !== pageNumbers.length) {
      const pagesIndex = [...Array(numPages).keys()].map(
        (pageIndex) => pageIndex + 1,
      )

      setPageNumbers(pagesIndex)
      if (onSuccess) {
        onSuccess()
      }
    }
  }

  return (
    <Document
      options={{
        standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts`,
      }}
      file={file}
      onLoadSuccess={onLoadSuccess}
    >
      {pageNumbers.map((pageNumber: number) => (

          <Page pageNumber={pageNumber} />

      ))}
    </Document>
  )
}


问:
gorm Selecting Specific Fields
I want to select like this; how can use one struct replace "in Select text"

```<code>    db.Table(model.TableName()).Select("ag_anchor.id,ag_anchor.name,ag_apply_record.id,ag_apply_record.name,ag_apply_record.id,ag_apply_record.price").Joins("left join ag_anchor anchor on anchor.id = ag_apply_record.anchor_id").Find(&data, "user_id = ?", userID)
</code>```

I want to select like this; how can use one struct replace "in Select text"

Title: gorm Selecting Specific Fields

Body:
I want to select like this; how can use one struct replace "in Select text"

    db.Table(model.TableName()).Select("ag_anchor.id,ag_anchor.name,ag_apply_record.id,ag_apply_record.name,ag_apply_record.id,ag_apply_record.price").Joins("left join ag_anchor anchor on anchor.id = ag_apply_record.anchor_id").Find(&data, "user_id = ?", userID)

I want to select like this; how can use one struct replace "in Select text"


问:
Setting the fill pattern on a custom conditional rule in a javascript Excel add-in
Is there a way to set the fill pattern in conditional format using excel-js add-in?

No problem to set the conditional format fill color but I can not find any properties to set the fill pattern style or the fill pattern color.

Is there any way to around that? (I'm thinking something similar to setting valuesAsJSON...)


问:
fail to inser data when using TDengine
I encountered an error when inserting data into TDengine.

I can see the error report in its log.

ERROR vgId:5, msg:0x7fea18137cb0 failed to put into vnode queue since Invalid Vgroup ID, type:submit qtype:3 contLen:455, gtid:0x11ba042c4fef0043:0x66040e62c4f0003a

I googled this information, and no valuable information was gained.

Title: fail to inser data when using TDengine


问:
Xamarin Forms iOS and Android projects not able to run In Mac?
The below are the issues I am getting when I am cleaning and Building the project.

When we are running the project iOS or Android both is occurring same
error:

```<code>/Library/Frameworks/Mono.framework/Versions/6.12.0/lib/mono/xbuild/Current/Microsoft.Common.props(3,3): Error MSB4019: The imported project "/Users/…..iOS/obj/ABSConfigurator.iOS.csproj.*.props" was not found. Confirm that the expression in the Import declaration “ABSConfigurator.iOS.csproj.*.props" is correct, and that the file exists on disk. (MSB4019)
</code>```

When I am restoring the package then below are the error:

```<code>Error: NuGet packages need to be restored before building. NuGet MSBuild targets are missing and are needed for building. The NuGet MSBuild targets are generated when the NuGet packages are restored.
</code>```

Body:
The below are the issues I am getting when I am cleaning and Building the project.

When we are running the project iOS or Android both is occurring same
error:

/Library/Frameworks/Mono.framework/Versions/6.12.0/lib/mono/xbuild/Current/Microsoft.Common.props(3,3): Error MSB4019: The imported project "/Users/…..iOS/obj/ABSConfigurator.iOS.csproj.*.props" was not found. Confirm that the expression in the Import declaration “ABSConfigurator.iOS.csproj.*.props" is correct, and that the file exists on disk. (MSB4019)

When I am restoring the package then below are the error:

Error: NuGet packages need to be restored before building. NuGet MSBuild targets are missing and are needed for building. The NuGet MSBuild targets are generated when the NuGet packages are restored.


问:
User Warning in Model.fit
I'm working on image classification (multiclass). This is a custom dataset. When fitting the model, I get this warning, and validation loss and accuracy are not displayed. How do I fix this?

```<code>Epoch 1/20
 61/365 [====>.........................] - ETA: 8:05 - loss: 6.7683 - accuracy: 0.2262/usr/local/lib/python3.8/dist-packages/PIL/TiffImagePlugin.py:788: UserWarning: Corrupt EXIF data.  Expecting to read 4 bytes but only got 0.    warnings.warn(str(msg))
</code>```

Please help me solving this.

Title: User Warning in Model.fit

Body:
I'm working on image classification (multiclass). This is a custom dataset. When fitting the model, I get this warning, and validation loss and accuracy are not displayed. How do I fix this?

Epoch 1/20
 61/365 [====>.........................] - ETA: 8:05 - loss: 6.7683 - accuracy: 0.2262/usr/local/lib/python3.8/dist-packages/PIL/TiffImagePlugin.py:788: UserWarning: Corrupt EXIF data.  Expecting to read 4 bytes but only got 0.    warnings.warn(str(msg))

Please help me solving this.


问:
MSI created using InstallShield application is unable to create start menu shortcut
I have one MSI installer created using Install Shield installer.
When I install exe using MSI for the first time, it creates the start menu icon properly.
I have uninstalled the exe and deleted the short-cut.
While reinstalling the exe, MSI is not creating the short-cut.

Why this is happening?
Is there some cache regarding the short had been created.

Tried to find out where the information regarding start menu icon is stored.


问:
Deploying a nextjs app and wordpress app together on cloudways
I created a PHP application on cloudways in my server and deployed a nextjs application in the public_html/frontend folder to be used as a frontend.

I created a WordPress instance in the public_html/backend to be used as a headless CMS. I am using its rest API.

Folder structure:

```<code>-- public_html
|
---- backend ( wordpress )
|
---- frontend ( nextjs )
</code>```

My frontend and backend is working fine but the wp-json i.e the rest API, is not working. It is showing me a 404 error page that is coming from nextjs

Body:
I created a PHP application on cloudways in my server and deployed a nextjs application in the public_html/frontend folder to be used as a frontend.

I created a WordPress instance in the public_html/backend to be used as a headless CMS. I am using its rest API.

Folder structure:

-- public_html
|
---- backend ( wordpress )
|
---- frontend ( nextjs )

My frontend and backend is working fine but the wp-json i.e the rest API, is not working. It is showing me a 404 error page that is coming from nextjs


问:
Liquibase breaks backward compatibility with old PostgreSQL versions < 10 (serial vs identity columns)
I have marked column like that:

```<code><column name="id" type="bigserial">
    <constraints primaryKey="true"/>
</column>
</code>```

which generates sequence and column with default value on version 9.x but identity on version 15:

```<code>id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL
</code>```

How to keep it behaving like bigserial from sql in all versions?

Can I revert it back to bigserial without rewriting that changelog?

What are the pros of identity when I have to use sequence to do batch insert in spring boot?

Body:
I have marked column like that:

<column name="id" type="bigserial">
    <constraints primaryKey="true"/>
</column>

which generates sequence and column with default value on version 9.x but identity on version 15:

id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL

How to keep it behaving like bigserial from sql in all versions?

Can I revert it back to bigserial without rewriting that changelog?

What are the pros of identity when I have to use sequence to do batch insert in spring boot?


问:
What is the difference between these 2 ways of use dependency injection
I have a hard time wrapping my head around the difference between thees 2 way of using the IlogService, or maybe I am wrong and there is only one that is correct if I want to use dependency injection?

This way in class that use ILogService....

```<code>private static readonly ILogService _log = new LogService();
</code>```

Or this way in class that use ILogService...

```<code>   private readonly ILogService _logger;

    public MyClassThatUseIlogerService(ILogService logger)
    {
        _logger = logger;
    }
</code>```

Interface

```<code>public interface ILogService
{
    void Add(string val);
}

public class LogService :ILogService
{

    public void Add(string val)
    {
        Console.WriteLine(val;
    }

  }
</code>```

Body:
I have a hard time wrapping my head around the difference between thees 2 way of using the IlogService, or maybe I am wrong and there is only one that is correct if I want to use dependency injection?

This way in class that use ILogService....

private static readonly ILogService _log = new LogService();

Or this way in class that use ILogService...

   private readonly ILogService _logger;

    public MyClassThatUseIlogerService(ILogService logger)
    {
        _logger = logger;
    }

Interface

public interface ILogService
{
    void Add(string val);
}

public class LogService :ILogService
{

    public void Add(string val)
    {
        Console.WriteLine(val;
    }

  }


问:
NodeRed not loading up when adding modules to the flow
I'm working on a project using NodeRed deployed with docker, I am using nginx location block to navigate to the particular container like http://localhost/project/projectId/port/? when I trigger this url first time it is showing up the node red flow but when I add modules from the Manage pallet and hit the same url http://localhost/project/projectId/port/? is not opening the flow and it is getting stuck at loading, what is the thing happening when adding modules to not adding modules and how to resolve this issue is any thing we can do it from nginx location block?

Before adding modules

After adding modules

Nginx configuration

```<code>   location ~ "/project/projectid/([0-9]+)/(.*)" {
            set $port $3;
            set $token $4;
            rewrite ^/project/projectid/[0-9]+(.*) $1 break;
            proxy_pass http://127.0.0.1:$port/$token;
            proxy_set_header Host $host;
            add_header Access-Control-Allow-Methods *;
            proxy_set_header Connection upgrade;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
    }
</code>```

The one i see in the console is

Failed to load resource: the server responded with a status of 400 (Bad Request)

http://localhost/project/projectId/port/nodes/messages?lng=en-GB&_=1670325432158 1

Loading Node catalogs screen stuck there

Body:
I'm working on a project using NodeRed deployed with docker, I am using nginx location block to navigate to the particular container like http://localhost/project/projectId/port/? when I trigger this url first time it is showing up the node red flow but when I add modules from the Manage pallet and hit the same url http://localhost/project/projectId/port/? is not opening the flow and it is getting stuck at loading, what is the thing happening when adding modules to not adding modules and how to resolve this issue is any thing we can do it from nginx location block?

Before adding modules

After adding modules

Nginx configuration

   location ~ "/project/projectid/([0-9]+)/(.*)" {
            set $port $3;
            set $token $4;
            rewrite ^/project/projectid/[0-9]+(.*) $1 break;
            proxy_pass http://127.0.0.1:$port/$token;
            proxy_set_header Host $host;
            add_header Access-Control-Allow-Methods *;
            proxy_set_header Connection upgrade;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
    }

The one i see in the console is

Failed to load resource: the server responded with a status of 400 (Bad Request)

http://localhost/project/projectId/port/nodes/messages?lng=en-GB&_=1670325432158 1

Loading Node catalogs screen stuck there


问:
Windows : What happens to the UI when the app is minimized?
I was wondering what will happen to the UI when the app is minimized. Will it refresh the UI [With respect to its content] even when the app is minimized?

In the thumbnail[ When we hover on the app icon in taskbar ] we cant see apps UI being refreshed when app is minimized, but we can see the UI being refreshed in thumbnail when app goes to background and new app comes on the foreground.

What I think is, when the app is minimized, the UI thread/Main thread will keep updating the apps UI [depending on the content], but the changes will not be rendered on the screen. the changes will be stacked on a buffer and when the app is brought up, top of the buffer is rendered. Is this right?

It would be of great help if you can help me get a detailed understanding in it.

Thank you


问:
Calculated value from JS function cannot be read in ASP.Net
I calculate value from two text boxes and successfully insert to result textbox using JS function. As I checked, the typeof(num3.value) is string. Refer JS function below.

```<code>   <script type="text/javascript">
    var num1 = document.getElementById('<%= txtDuration.ClientID %>');
    var num2 = document.getElementById('<%= txtHeadcount.ClientID %>');
    var num3 = document.getElementById('<%= txtTotalHours.ClientID %>');
    num1.onchange = multiplyNumbers;
    num2.onchange = multiplyNumbers;

    function multiplyNumbers() {
        num3.value = parseFloat(num1.value) * parseFloat(num2.value);
    }
   </script>
</code>```

But once I want to store it the value using my stored procedure, it does not read any value and return [FormatException: Input string was not in a correct format.] error.

My store procedure

```<code>Using con As New SqlConnection(SqlConnection)
        Using cmd As New SqlCommand
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = "Training_InsertTraining"
            cmd.Parameters.Add("@THours", SqlDbType.Float).Value = txtTotalHours.Text
            cmd.Connection = con
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            con.Dispose()
         End Using
    End Using
</code>```

Please someone know whats the problem. txtTotalHours.Text return Nothing

Body:
I calculate value from two text boxes and successfully insert to result textbox using JS function. As I checked, the typeof(num3.value) is string. Refer JS function below.

But once I want to store it the value using my stored procedure, it does not read any value and return [FormatException: Input string was not in a correct format.] error.

My store procedure

Using con As New SqlConnection(SqlConnection)
        Using cmd As New SqlCommand
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = "Training_InsertTraining"
            cmd.Parameters.Add("@THours", SqlDbType.Float).Value = txtTotalHours.Text
            cmd.Connection = con
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            con.Dispose()
         End Using
    End Using

Please someone know whats the problem. txtTotalHours.Text return Nothing


问:
EmberJs served on nginx - Set Cache-Control header in request
My application is build using EmberJs and is served on Nginx. I am able to set Cache-Control header in response using add_header in nginx.conf

```<code>location ~* \.(css|eot|gif|jpe?g|js|png|svg|ttf|woff2?)$ {
          expires max;
          add_header Pragma public;
          add_header Cache-Control "public, must-revalidate, proxy-revalidate";
        }
</code>```

But this alone doesn't work as request header is set to no-cache. So, browser always goes to backend and doesn't use its cache ever.

Response Headers

```<code>cache-control: max-age=315360000
cache-control: public, must-revalidate, proxy-revalidate
expires: Thu, 31 Dec 2037 23:55:55 GMT
pragma: public
</code>```

Request Headers

```<code>Cache-Control: no-cache
Pragma: no-cache
</code>```

I understand that Cahce-Control in request is causing the problem. But I am not able to find how to set this header with some other value. Does ember build or nginx conf support this?

This is the index.html generated by ember which has links for vendor js and css which are supposed to be reused using cache by browser.

Body:
My application is build using EmberJs and is served on Nginx. I am able to set Cache-Control header in response using add_header in nginx.conf

location ~* \.(css|eot|gif|jpe?g|js|png|svg|ttf|woff2?)$ {
          expires max;
          add_header Pragma public;
          add_header Cache-Control "public, must-revalidate, proxy-revalidate";
        }

But this alone doesn't work as request header is set to no-cache. So, browser always goes to backend and doesn't use its cache ever.

Response Headers

cache-control: max-age=315360000
cache-control: public, must-revalidate, proxy-revalidate
expires: Thu, 31 Dec 2037 23:55:55 GMT
pragma: public

Request Headers

Cache-Control: no-cache
Pragma: no-cache

I understand that Cahce-Control in request is causing the problem. But I am not able to find how to set this header with some other value. Does ember build or nginx conf support this?

This is the index.html generated by ember which has links for vendor js and css which are supposed to be reused using cache by browser.


问:
How to display location on map with a given address using Geocode?
So I want to display the location of the place i am displaying. For example, I want to display the location Kuala Lumpur Tower I grab the name of the place, use geocode to get the coordinates and show them on the map. However it says that I have not initialized the longitude and latitude. How do I fix this?

Here is my code:

```<code>import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geocode/geocode.dart';

class PlaceInfo extends StatefulWidget {
  final PackageModel packageModel;
  PlaceInfo({Key? key, required this.packageModel}):super(key:key);

  @override
  State<PlaceInfo> createState() => _PlaceInfoState();
}

class _PlaceInfoState extends State<PlaceInfo> {

  late double _latitude;
  late double _longitude;

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

  Future <void> getLatLon() async {
    GeoCode geoCode = GeoCode();

    try {
      Coordinates coordinates = await geoCode.forwardGeocoding(
          address: "${widget.packageModel.destination}");
      final lat = coordinates.latitude!;
      final lon = coordinates.longitude!;
      print("Latitude: ${coordinates.latitude}");
      print("Longitude: ${coordinates.longitude}");

      setState((){
        _latitude = lat;
        _longitude = lon;
      });

    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title: Image.asset('assets/logo.png', scale: 3.2),
        centerTitle: true,
        backgroundColor: Colors.indigo[900],
      ),
      drawer: NavBar(),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 30, vertical: 20),
              child: Column(
                children: [
                  //Title
                  Container(
                    child: Text("${widget.packageModel.destination}",
                      style: TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),

                  //Location
                  Container(
                    padding: EdgeInsets.only(top: 20),
                    height: MediaQuery.of(context).size.height / 2.5,
                    width: MediaQuery.of(context).size.width,
                    child: GoogleMap(
                      scrollGesturesEnabled: true,
                      mapType: MapType.normal,
                      initialCameraPosition: CameraPosition(
                        target: LatLng(_latitude, _longitude),
                        zoom: 14
                      )
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
</code>```

I want to get the coordinates of widget.packageModel.destination as coordinates so that i can use it in my map.

Body:
So I want to display the location of the place i am displaying. For example, I want to display the location Kuala Lumpur Tower I grab the name of the place, use geocode to get the coordinates and show them on the map. However it says that I have not initialized the longitude and latitude. How do I fix this?

Here is my code:

import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geocode/geocode.dart';

class PlaceInfo extends StatefulWidget {
  final PackageModel packageModel;
  PlaceInfo({Key? key, required this.packageModel}):super(key:key);

  @override
  State<PlaceInfo> createState() => _PlaceInfoState();
}

class _PlaceInfoState extends State<PlaceInfo> {

  late double _latitude;
  late double _longitude;

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

  Future <void> getLatLon() async {
    GeoCode geoCode = GeoCode();

    try {
      Coordinates coordinates = await geoCode.forwardGeocoding(
          address: "${widget.packageModel.destination}");
      final lat = coordinates.latitude!;
      final lon = coordinates.longitude!;
      print("Latitude: ${coordinates.latitude}");
      print("Longitude: ${coordinates.longitude}");

      setState((){
        _latitude = lat;
        _longitude = lon;
      });

    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title: Image.asset('assets/logo.png', scale: 3.2),
        centerTitle: true,
        backgroundColor: Colors.indigo[900],
      ),
      drawer: NavBar(),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 30, vertical: 20),
              child: Column(
                children: [
                  //Title
                  Container(
                    child: Text("${widget.packageModel.destination}",
                      style: TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),

                  //Location
                  Container(
                    padding: EdgeInsets.only(top: 20),
                    height: MediaQuery.of(context).size.height / 2.5,
                    width: MediaQuery.of(context).size.width,
                    child: GoogleMap(
                      scrollGesturesEnabled: true,
                      mapType: MapType.normal,
                      initialCameraPosition: CameraPosition(
                        target: LatLng(_latitude, _longitude),
                        zoom: 14
                      )
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

I want to get the coordinates of widget.packageModel.destination as coordinates so that i can use it in my map.


问:
How can we add condition for targetClass in AnyMetaDef?
When a value is deleted from the table, I do not delete that value from the database; I just change the status column value to 'DELETED'. I prevent deleted values from returning with the @Where(clause = "status != 'DELETED'") condition at the beginning of each Entity(Book,VHS,DVD) class.

```<code> @Entity
 @Where(clause = "status != 'DELETED'")
 public class Book ....
</code>```

However;

```<code>    @Any(metaColumn = @Column(name = "ITEM_TYPE"),fetch = FetchType.LAZY)
    @AnyMetaDef(idType = "long", metaType = "string",
            metaValues = {
             @MetaValue(targetEntity = Book.class, value = "B"),
             @MetaValue(targetEntity = VHS.class, value = "V"),
             @MetaValue(targetEntity = DVD.class, value = "D")
       })
    @JoinColumn(name="ITEM_ID", insertable = false, updatable = false)
    private Object item;
</code>```

If I use the this code block, it also pulls the DELETED values. I think when we do targetEntity = Book.class, it does not see the @Where condition written in BookEntity.

How can I add the Where run here or how do I prevent withdrawals of 'DELETED' status here?

Body:
When a value is deleted from the table, I do not delete that value from the database; I just change the status column value to 'DELETED'. I prevent deleted values from returning with the @Where(clause = "status != 'DELETED'") condition at the beginning of each Entity(Book,VHS,DVD) class.

 @Entity
 @Where(clause = "status != 'DELETED'")
 public class Book ....

However;

    @Any(metaColumn = @Column(name = "ITEM_TYPE"),fetch = FetchType.LAZY)
    @AnyMetaDef(idType = "long", metaType = "string",
            metaValues = {
             @MetaValue(targetEntity = Book.class, value = "B"),
             @MetaValue(targetEntity = VHS.class, value = "V"),
             @MetaValue(targetEntity = DVD.class, value = "D")
       })
    @JoinColumn(name="ITEM_ID", insertable = false, updatable = false)
    private Object item;

If I use the this code block, it also pulls the DELETED values. I think when we do targetEntity = Book.class, it does not see the @Where condition written in BookEntity.

How can I add the Where run here or how do I prevent withdrawals of 'DELETED' status here?


问:
Slow while loop in tkinter after reboot
i'm trying to add some windows on the top of an existing vb6 app.

`

```<code>from threading import Thread
from tkinter import *
import pyautogui
import win32gui
import time

#coordinates of the target image that i use to decide if i have to show the tk windows
target=(83,396)
target2=(612,73)
targetp=(153,204,0)
target2p=(247,87,70)

#windows geometry
wg1=(221,229,795,160)
wg2=(154,162,11,482)

f = True

#names of the vb program's windows that have to cover the left window
ws = ["Parametri di lavorazione", "Opzioni", "Configurazione tabelle DXF"]

#windows thread
def wins():
    global win10
    global win20
    win10 = Tk()
    win10.overrideredirect(True)
    win10.geometry('%dx%d+%d+%d' % wg1)
    img1 = PhotoImage(file = "c:\\users\\utente\\desktop\\img1.png")
    l1= Label(win10, i=img1)
    l1.pack()
    win20 = Toplevel(win10)
    img2 = PhotoImage(file = "c:\\users\\utente\\desktop\\img2.png")
    l2 = Label(win20, i=img2)
    l2.pack()
    win20.geometry('%dx%d+%d+%d' % wg2)
    win20.overrideredirect(True)
    win10.mainloop()

#thread to check if the windows have to be showed based on the first target
def cl():
    global win10
    global win20
    s = True
    while True:
        if s:
            if pyautogui.pixel(target[0],target[1]) != targetp:
                win10.withdraw()
                win20.withdraw()
                s = False
        else:
            if pyautogui.pixel(target[0],target[1]) == targetp:
                win10.deiconify()
                win20.deiconify()
                s = True

#thread to handle other windows on the original app
def rd():
    ws2 = []
    while True:
        for i in ws:
            ws2.append(win32gui.FindWindow(0,i))
        for i in ws2:
            if i:
                a,b,c,d= win32gui.GetWindowRect(i)
                win32gui.MoveWindow(i,1024-(c-a-8),-8,c-a,d-b,True)
                while True:
                    if pyautogui.pixel(target2[0],target2[1]) != target2p:
                        win10.withdraw()
                        break
                while True:
                    if pyautogui.pixel(target2[0],target2[1]) == target2p:
                        win10.deiconify()
                        break
        ws2=[]

t1 = Thread(target=wins)
t2 = Thread(target=cl)
t3 = Thread(target=rd)
t1.start()
time.sleep(1)
t2.start()
t3.start()

#while loop to make my windows always on top
while True:
    win10.attributes("-topmost",True)
    win20.attributes("-topmost",True)
</code>```

`

The old app is set to be always on top, so i had to add a while loop at the end of the code that sets the two new windows topmost.
If i don't do this, my windows disappear as soon as i click on the old program's main window.
The code runs fine on my windows 10 machine until i reboot the operating system.
After the reboot, the last while loop become very slow, so that even the operation of minimizing the main window takes about 5 seconds.
Do you have any idea on how to fix this?

I also tried to insert the while loop in a thread letting the windows mainloop outside any method, but same result.
Until the reboot it all goes fine, after i power on the machine again in becomes very slow.

Title: Slow while loop in tkinter after reboot

Body:
i'm trying to add some windows on the top of an existing vb6 app.

`

from threading import Thread
from tkinter import *
import pyautogui
import win32gui
import time

#coordinates of the target image that i use to decide if i have to show the tk windows
target=(83,396)
target2=(612,73)
targetp=(153,204,0)
target2p=(247,87,70)

#windows geometry
wg1=(221,229,795,160)
wg2=(154,162,11,482)

f = True

#names of the vb program's windows that have to cover the left window
ws = ["Parametri di lavorazione", "Opzioni", "Configurazione tabelle DXF"]

#windows thread
def wins():
    global win10
    global win20
    win10 = Tk()
    win10.overrideredirect(True)
    win10.geometry('%dx%d+%d+%d' % wg1)
    img1 = PhotoImage(file = "c:\\users\\utente\\desktop\\img1.png")
    l1= Label(win10, i=img1)
    l1.pack()
    win20 = Toplevel(win10)
    img2 = PhotoImage(file = "c:\\users\\utente\\desktop\\img2.png")
    l2 = Label(win20, i=img2)
    l2.pack()
    win20.geometry('%dx%d+%d+%d' % wg2)
    win20.overrideredirect(True)
    win10.mainloop()

#thread to check if the windows have to be showed based on the first target
def cl():
    global win10
    global win20
    s = True
    while True:
        if s:
            if pyautogui.pixel(target[0],target[1]) != targetp:
                win10.withdraw()
                win20.withdraw()
                s = False
        else:
            if pyautogui.pixel(target[0],target[1]) == targetp:
                win10.deiconify()
                win20.deiconify()
                s = True

#thread to handle other windows on the original app
def rd():
    ws2 = []
    while True:
        for i in ws:
            ws2.append(win32gui.FindWindow(0,i))
        for i in ws2:
            if i:
                a,b,c,d= win32gui.GetWindowRect(i)
                win32gui.MoveWindow(i,1024-(c-a-8),-8,c-a,d-b,True)
                while True:
                    if pyautogui.pixel(target2[0],target2[1]) != target2p:
                        win10.withdraw()
                        break
                while True:
                    if pyautogui.pixel(target2[0],target2[1]) == target2p:
                        win10.deiconify()
                        break
        ws2=[]

t1 = Thread(target=wins)
t2 = Thread(target=cl)
t3 = Thread(target=rd)
t1.start()
time.sleep(1)
t2.start()
t3.start()

#while loop to make my windows always on top
while True:
    win10.attributes("-topmost",True)
    win20.attributes("-topmost",True)

`

The old app is set to be always on top, so i had to add a while loop at the end of the code that sets the two new windows topmost.
If i don't do this, my windows disappear as soon as i click on the old program's main window.
The code runs fine on my windows 10 machine until i reboot the operating system.
After the reboot, the last while loop become very slow, so that even the operation of minimizing the main window takes about 5 seconds.
Do you have any idea on how to fix this?

I also tried to insert the while loop in a thread letting the windows mainloop outside any method, but same result.
Until the reboot it all goes fine, after i power on the machine again in becomes very slow.


问:
Why getting exception time out error or element not found on this line By.CSS_SELECTOR, "#typeahead-input-control-35 .up-menu-item-text"
Problem Here I don't know why I am getting these errors on this line wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#typeahead-input-control-35 .up-menu-item-text"))).click() even I am not getting any error If I am running this code in a separate file, But when I merge this code to my main code this line not worked.

Problem line wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#typeahead-input-control-35 .up-menu-item-text"))).click()

Code that works fine if run in a separate file

```<code>import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('F:\\work\\chromedriver_win32\\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 10)

url = "https://www.upwork.com/nx/jobs/search/?sort=recency"
driver.get(url)
keys = ["Web Scraping", "Selenium Webdriver", "Data Scraping", "Selenium", "Beautiful Soup", "Scrapy", "Data Extraction", "Automation"]
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button#onetrust-accept-btn-handler')))
time.sleep(5)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button#onetrust-accept-btn-handler'))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[contains(@title,"Advanced Search")]'))).click()
wait.until(EC.element_to_be_clickable((By.XPATH,'//input[contains(@aria-labelledby,"tokenizer-label")]'))).clear()
wait.until(EC.element_to_be_clickable((By.XPATH, '//input[contains(@aria-labelledby,"tokenizer-label")]'))).click()
time.sleep(3)
for i in range(len(keys)):
    search_field = wait.until(EC.element_to_be_clickable((By.XPATH, '//input[contains(@aria-labelledby,"tokenizer-label")]')))
    search_field.click()
    for character in keys[i]:
        search_field.send_keys(character)
        time.sleep(0.05)
    time.sleep(2)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#typeahead-input-control-35 .up-menu-item-text"))).click()
    time.sleep(2)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'[data-test="modal-advanced-search-search-btn"]'))).click()
</code>```

line not work in this code

```<code>import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.proxy import Proxy, ProxyType
from fake_useragent import UserAgent
import pyttsx3
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def main():
    options = Options()
    service = Service('F:\\work\\chromedriver_win32\\chromedriver.exe')
    options.add_argument("start-maximized")
    options.add_argument('--disable-blink-features=AutomationControlled') #Adding the argument
    options.add_experimental_option("excludeSwitches",["enable-automation"])#Disable chrome contrlled message (Exclude the collection of enable-automation switches)
    options.add_experimental_option('useAutomationExtension', False) #Turn-off useAutomationExtension
    options.add_experimental_option('useAutomationExtension', False) #Turn-off useAutomationExtension
    prefs = {"credentials_enable_service": False,
     "profile.password_manager_enabled": False}
    options.add_experimental_option("prefs", prefs)
    ua = UserAgent()
    userAgent = ua.random
    options.add_argument(f'user-agent={userAgent}')
    driver = webdriver.Chrome(service=service , options=options)
    wait = WebDriverWait(driver, 10)
    url = 'https://www.upwork.com/nx/jobs/search/?sort=recency'
    driver.get(url)
    time.sleep(7)

    logbtn = driver.find_element(By.XPATH,'//a[contains(@class,"nav-item login-link d-none d-lg-block px-20")]')
    logbtn.click()
    time.sleep(7)
    pop_one = driver.find_element(By.XPATH, '//*[@id="onetrust-accept-btn-handler"]')
    pop_one.click()
    time.sleep(7)

    search_box = driver.find_element(By.NAME, "login[username]")
    search_box.send_keys('my_mailaccountid@gmail.com')
    time.sleep(7)

    Login_button = driver.find_element(By.ID, "login_password_continue")
    Login_button.submit()
    time.sleep(7)

    pass_box = driver.find_element(By.ID, "login_password")
    pass_box.send_keys('myupworkpassword000')
    Login_btn = driver.find_element(By.ID, "login_control_continue")
    Login_btn.submit()
    time.sleep(7)

    closebtn = driver.find_element(By.XPATH, '//*[@id="main"]/div/div/aside/div/div[1]/div[1]/section/div[2]/div[2]/div/div/div/div[3]/div/div[2]/div[2]/div[2]/div[3]/div/button')
    closebtn.click()

    url = 'https://www.upwork.com/nx/jobs/search/?sort=recency'
    driver.get(url)
    time.sleep(7)

    for i in range(0,20):
        box1 = driver.find_element(By.XPATH,'//span[contains(text(),"Intermediate")]')
        box1.click()
        time.sleep (3)
        box2 = driver.find_element(By.XPATH,'//span[contains(text(),"Expert")]')
        box2.click()
        time.sleep (3)
        box3 = driver.find_element(By.XPATH,'//span[contains(text(),"Less than 5")]')
        box3.click()
        time.sleep (3)
        box4 = driver.find_element(By.XPATH,'//span[contains(text(),"5 to 10")]')
        box4.click()
        time.sleep (3)
        box5 = driver.find_element(By.XPATH,'//span[contains(text(),"Payment verified")]')
        box5.click()
        time.sleep (7)
        cat1 = driver.find_element(By.XPATH,'//strong[contains(text(),"Job type")]')
        cat1.click()
        time.sleep (7)
        box6 = driver.find_element(By.XPATH,'//span[contains(text(),"Hourly")]')
        box6.click()
        time.sleep (3)
        box7 = driver.find_element(By.XPATH,'//span[contains(text(),"Less than $100")]')
        box7.click()
        time.sleep (3)
        box8 = driver.find_element(By.XPATH,'//span[contains(text(),"$100 to $500")]')
        box8.click()
        time.sleep (3)
        keys = ["Web Scraping", "Selenium Webdriver", "Data Scraping", "Selenium", "Beautiful Soup", "Scrapy", "Data Extraction", "Automation"]
        wait.until(EC.element_to_be_clickable((By.XPATH, '//button[contains(@title,"Advanced Search")]'))).click()
        wait.until(EC.element_to_be_clickable((By.XPATH,'//input[contains(@aria-labelledby,"tokenizer-label")]'))).clear()
        wait.until(EC.element_to_be_clickable((By.XPATH, '//input[contains(@aria-labelledby,"tokenizer-label")]'))).click()
        time.sleep(3)
        for i in range(len(keys)):
            search_field = wait.until(EC.element_to_be_clickable((By.XPATH, '//input[contains(@aria-labelledby,"tokenizer-label")]')))
            search_field.click()
            for character in keys[i]:
                search_field.send_keys(character)
                time.sleep(0.05)
            time.sleep(7)
            wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#typeahead-input-control-35 .up-menu-item-text"))).click()
            time.sleep(7)
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'[data-test="modal-advanced-search-search-btn"]'))).click()
main()
</code>```

Body:
Problem Here I don't know why I am getting these errors on this line wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#typeahead-input-control-35 .up-menu-item-text"))).click() even I am not getting any error If I am running this code in a separate file, But when I merge this code to my main code this line not worked.

Problem line wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#typeahead-input-control-35 .up-menu-item-text"))).click()

Code that works fine if run in a separate file

import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('F:\\work\\chromedriver_win32\\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 10)

url = "https://www.upwork.com/nx/jobs/search/?sort=recency"
driver.get(url)
keys = ["Web Scraping", "Selenium Webdriver", "Data Scraping", "Selenium", "Beautiful Soup", "Scrapy", "Data Extraction", "Automation"]
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button#onetrust-accept-btn-handler')))
time.sleep(5)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button#onetrust-accept-btn-handler'))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[contains(@title,"Advanced Search")]'))).click()
wait.until(EC.element_to_be_clickable((By.XPATH,'//input[contains(@aria-labelledby,"tokenizer-label")]'))).clear()
wait.until(EC.element_to_be_clickable((By.XPATH, '//input[contains(@aria-labelledby,"tokenizer-label")]'))).click()
time.sleep(3)
for i in range(len(keys)):
    search_field = wait.until(EC.element_to_be_clickable((By.XPATH, '//input[contains(@aria-labelledby,"tokenizer-label")]')))
    search_field.click()
    for character in keys[i]:
        search_field.send_keys(character)
        time.sleep(0.05)
    time.sleep(2)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#typeahead-input-control-35 .up-menu-item-text"))).click()
    time.sleep(2)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'[data-test="modal-advanced-search-search-btn"]'))).click()

line not work in this code

import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.proxy import Proxy, ProxyType
from fake_useragent import UserAgent
import pyttsx3
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def main():
    options = Options()
    service = Service('F:\\work\\chromedriver_win32\\chromedriver.exe')
    options.add_argument("start-maximized")
    options.add_argument('--disable-blink-features=AutomationControlled') #Adding the argument
    options.add_experimental_option("excludeSwitches",["enable-automation"])#Disable chrome contrlled message (Exclude the collection of enable-automation switches)
    options.add_experimental_option('useAutomationExtension', False) #Turn-off useAutomationExtension
    options.add_experimental_option('useAutomationExtension', False) #Turn-off useAutomationExtension
    prefs = {"credentials_enable_service": False,
     "profile.password_manager_enabled": False}
    options.add_experimental_option("prefs", prefs)
    ua = UserAgent()
    userAgent = ua.random
    options.add_argument(f'user-agent={userAgent}')
    driver = webdriver.Chrome(service=service , options=options)
    wait = WebDriverWait(driver, 10)
    url = 'https://www.upwork.com/nx/jobs/search/?sort=recency'
    driver.get(url)
    time.sleep(7)

    logbtn = driver.find_element(By.XPATH,'//a[contains(@class,"nav-item login-link d-none d-lg-block px-20")]')
    logbtn.click()
    time.sleep(7)
    pop_one = driver.find_element(By.XPATH, '//*[@id="onetrust-accept-btn-handler"]')
    pop_one.click()
    time.sleep(7)

    search_box = driver.find_element(By.NAME, "login[username]")
    search_box.send_keys('my_mailaccountid@gmail.com')
    time.sleep(7)

    Login_button = driver.find_element(By.ID, "login_password_continue")
    Login_button.submit()
    time.sleep(7)

    pass_box = driver.find_element(By.ID, "login_password")
    pass_box.send_keys('myupworkpassword000')
    Login_btn = driver.find_element(By.ID, "login_control_continue")
    Login_btn.submit()
    time.sleep(7)

    closebtn = driver.find_element(By.XPATH, '//*[@id="main"]/div/div/aside/div/div[1]/div[1]/section/div[2]/div[2]/div/div/div/div[3]/div/div[2]/div[2]/div[2]/div[3]/div/button')
    closebtn.click()

    url = 'https://www.upwork.com/nx/jobs/search/?sort=recency'
    driver.get(url)
    time.sleep(7)

    for i in range(0,20):
        box1 = driver.find_element(By.XPATH,'//span[contains(text(),"Intermediate")]')
        box1.click()
        time.sleep (3)
        box2 = driver.find_element(By.XPATH,'//span[contains(text(),"Expert")]')
        box2.click()
        time.sleep (3)
        box3 = driver.find_element(By.XPATH,'//span[contains(text(),"Less than 5")]')
        box3.click()
        time.sleep (3)
        box4 = driver.find_element(By.XPATH,'//span[contains(text(),"5 to 10")]')
        box4.click()
        time.sleep (3)
        box5 = driver.find_element(By.XPATH,'//span[contains(text(),"Payment verified")]')
        box5.click()
        time.sleep (7)
        cat1 = driver.find_element(By.XPATH,'//strong[contains(text(),"Job type")]')
        cat1.click()
        time.sleep (7)
        box6 = driver.find_element(By.XPATH,'//span[contains(text(),"Hourly")]')
        box6.click()
        time.sleep (3)
        box7 = driver.find_element(By.XPATH,'//span[contains(text(),"Less than $100")]')
        box7.click()
        time.sleep (3)
        box8 = driver.find_element(By.XPATH,'//span[contains(text(),"$100 to $500")]')
        box8.click()
        time.sleep (3)
        keys = ["Web Scraping", "Selenium Webdriver", "Data Scraping", "Selenium", "Beautiful Soup", "Scrapy", "Data Extraction", "Automation"]
        wait.until(EC.element_to_be_clickable((By.XPATH, '//button[contains(@title,"Advanced Search")]'))).click()
        wait.until(EC.element_to_be_clickable((By.XPATH,'//input[contains(@aria-labelledby,"tokenizer-label")]'))).clear()
        wait.until(EC.element_to_be_clickable((By.XPATH, '//input[contains(@aria-labelledby,"tokenizer-label")]'))).click()
        time.sleep(3)
        for i in range(len(keys)):
            search_field = wait.until(EC.element_to_be_clickable((By.XPATH, '//input[contains(@aria-labelledby,"tokenizer-label")]')))
            search_field.click()
            for character in keys[i]:
                search_field.send_keys(character)
                time.sleep(0.05)
            time.sleep(7)
            wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#typeahead-input-control-35 .up-menu-item-text"))).click()
            time.sleep(7)
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'[data-test="modal-advanced-search-search-btn"]'))).click()
main()


问:
Javax mail uses A1 LOGIN to authentificate instead of AUTHENTICATE XOAUTH2
I use the code to authenticate:

Properties props = new Properties();

props.put("mail.imap.ssl.protocols", "TLSv1.2");
props.put("mail.store.protocol", "imap");
props.put("mail.imap.host", "outlook.office365.com");
props.put("mail.imap.port", "993");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.auth", "true");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.plain.disable", "true");
props.put("mail.imap.user", "mail@mail.com");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");

props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");
```
<p>If I run locally on Java, it connects:</p>
<pre class="lang-none prettyprint-override"><code>DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: AUTH: XOAUTH2
DEBUG IMAP: protocolConnect login, host=outlook.office365.com, user=@ha.com, password=<non-null>
A1 AUTHENTICATE XOAUTH2 dXNlcj1lZGlvcmRlcnMuY3oubWNkLnNtc28udGVzdEBoYXZpLmNvbQFhdXRoPUJlYXJlciBleUowZVhBaU9pSktWMVFpTENKdWIyNWpaU0k2SWpaYVVISmFRVnBVY
</code>```

If I run on OpenJDK it uses

A0 OK CAPABILITY completed.
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: AUTH: XOAUTH2
DEBUG IMAP: protocolConnect login, host=outlook.office365.com, user=ediorders.cz.mcd.smso.test@havi.com, password=<non-null>
A1 A1 LOGIN mail@email.com
+AGVkaW9yZGVycy5jei5tY2Quc21zby50ZXN0QGhhdmkuY29tAGV5SjBlWEFpT2lKS1YxUWlMQ0p1YjI1alpTSTZJbGhYYmtoaVkzZ3dkMmxsWWpCR
A1 NO AUTHENTICATE failed.
```

Can you please help me to understand why this stuff is using LOGIN to authenticate?

I used all available options with sals also.

Body:
I use the code to authenticate:

Properties props = new Properties();

props.put("mail.imap.ssl.protocols", "TLSv1.2");
props.put("mail.store.protocol", "imap");
props.put("mail.imap.host", "outlook.office365.com");
props.put("mail.imap.port", "993");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.auth", "true");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.plain.disable", "true");
props.put("mail.imap.user", "mail@mail.com");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");

props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");

If I run locally on Java, it connects:

DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: AUTH: XOAUTH2
DEBUG IMAP: protocolConnect login, host=outlook.office365.com, user=@ha.com, password=<non-null>
A1 AUTHENTICATE XOAUTH2 dXNlcj1lZGlvcmRlcnMuY3oubWNkLnNtc28udGVzdEBoYXZpLmNvbQFhdXRoPUJlYXJlciBleUowZVhBaU9pSktWMVFpTENKdWIyNWpaU0k2SWpaYVVISmFRVnBVY

If I run on OpenJDK it uses

A0 OK CAPABILITY completed.
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: AUTH: XOAUTH2
DEBUG IMAP: protocolConnect login, host=outlook.office365.com, user=ediorders.cz.mcd.smso.test@havi.com, password=<non-null>
A1 A1 LOGIN mail@email.com
+AGVkaW9yZGVycy5jei5tY2Quc21zby50ZXN0QGhhdmkuY29tAGV5SjBlWEFpT2lKS1YxUWlMQ0p1YjI1alpTSTZJbGhYYmtoaVkzZ3dkMmxsWWpCR
A1 NO AUTHENTICATE failed.

Can you please help me to understand why this stuff is using LOGIN to authenticate?

I used all available options with sals also.


问:
How can I use jQuery in Django REST framework @API_view
I got some problems with using jquery and in Django REST framework @API_view.

I want to view only logined, and add this code below.

```<code>views.py

from django.shortcuts import render
from rest_framework.decorators import api_view, permission_classes
@api_view()
@permission_classes([IsAuthenticated])
def index(request):
    return render(request, "index.html")
</code>```

I can get the JWT code with Djoser endpoint /jwt/create
and I added it in the localstorage()

```<code>  $.ajax({
    type: "POST",
    url: f.attr('action'),
    dataType: "json",
    contentType: "application/json; charset=UTF-8",
    data: JSON.stringify(data),
    beforeSend: function(msg) {
        m.addClass("is-active"),
        m.find(".content-block.is-active").html('<img src="/assets/img/ads/loader.svg" alt>');
    },
    success: function(msg) {

        var a = msg.access,
            r = msg.refresh,

        console.log(a),
        console.log(r),
        localStorage.setItem("access", a),
        localStorage.setItem("refresh", r);}
  })
</code>```

But how can I get the view "index.html" within the heard("JWT"+"token XXXXXXX")

when I get the page example.com/ there is only a view like this.

Body:
I got some problems with using jquery and in Django REST framework @API_view.

I want to view only logined, and add this code below.

views.py

from django.shortcuts import render
from rest_framework.decorators import api_view, permission_classes
@api_view()
@permission_classes([IsAuthenticated])
def index(request):
    return render(request, "index.html")

I can get the JWT code with Djoser endpoint /jwt/create
and I added it in the localstorage()

  $.ajax({
    type: "POST",
    url: f.attr('action'),
    dataType: "json",
    contentType: "application/json; charset=UTF-8",
    data: JSON.stringify(data),
    beforeSend: function(msg) {
        m.addClass("is-active"),
        m.find(".content-block.is-active").html('');
    },
    success: function(msg) {

        var a = msg.access,
            r = msg.refresh,

        console.log(a),
        console.log(r),
        localStorage.setItem("access", a),
        localStorage.setItem("refresh", r);}
  })

But how can I get the view "index.html" within the heard("JWT"+"token XXXXXXX")

when I get the page example.com/ there is only a view like this.


问:
How to change the heading tag of the page-title from H5 to H1
I'm trying to change the page title from h5 to h1 i tried to copy the

```<code>/inc/template-tags.php

</code>```

into the child theme and made the edit to the function but its still loading the old template. I'm currently using the Constico theme.

Example page link

Thank you!

I tried copying the

```<code>/inc/template-tags.php
</code>```

file from the parent theme to the child theme and made edits but it didn't work as wordpress is saying the function is being called twice giving an error!

Body:
I'm trying to change the page title from h5 to h1 i tried to copy the

/inc/template-tags.php

into the child theme and made the edit to the function but its still loading the old template. I'm currently using the Constico theme.

Example page link

Thank you!

I tried copying the

/inc/template-tags.php

file from the parent theme to the child theme and made edits but it didn't work as wordpress is saying the function is being called twice giving an error!


问:
How to configure the global tooltip style in echarts
there are multiple places that use tooltip in the project, how to unify the style

in addition to configuration in each tooltip, is there any other way?enter image description here

enter image description here