问:
How to install MySQLdb (Python data access library to MySQL) on Mac OS X?
How do I get MySQLdb working on Mac OS X?</p>

答:
Here's another step I had to go through, after receiving an error on completing Step 9:

```<code>ImportError: dlopen(/Users/rick/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib

    sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
</code>```

Reference: Thanks! http://ageekstory.blogspot.com/2011_04_01_archive.html

Body:
Here's another step I had to go through, after receiving an error on completing Step 9:

ImportError: dlopen(/Users/rick/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib

    sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

Reference: Thanks! http://ageekstory.blogspot.com/2011_04_01_archive.html


来源: stackexchange

问:
Regular expression to match any folder path of any length on Windows and Unix
Is it possible to make regular expression that will match any folder path of any length on Windows and Unix?
So, for example, regex should match: C:Users/Hp Workstation, as well as: C:Users/User1/Downloads and C:Users/Desktop/Python/python-2.7.7-docs, and even much longer paths...
This was just example. I meant some kind of universal regex to match absolutely any path(any partition, any folder, any subfolder...)
I would like to do it in Python.
Thanks in advance!

ONE OF THE ANSWERS:
This is one of the possible solutions I came to, that works for the vast majority of different paths, in most programming languages.

```<code>^([a-zA-Z]?\:?[^\/\\:*?"<>|]*|[\/\\]{1,2}[^\/\\:*?"<>|]+[\/\\][^\/\\:*?"<>|]+)([\/\\][^\/\\:*?"<>|]+)+
</code>```

答:
You can try this, this matches local as well as network paths.

^(C:[\S\s]+|\\[\S\s]+) or ^(C:.*|\\.*)

example

```<code>a = 'C:Users/Hp Workstation'
b = 'C:Users/User1/Downloads'
c = 'Users/Desktop/Python/python-2.7.7-docs'
d = '\\lol.com\Dfsdd\Dfsrerere\ytererwe\9jungnjfl\Projects'
e = 'lol.com\Dfsdd\Dfsrerere\ytererwe\9jungnjfl\Projects'
lis=[a,b,c,d,e]
for item in lis:
    print(re.findall(r'^(C:[\S\s]+|\\[\S\s]+)', item ))
</code>```

output

```<code>['C:Users/Hp Workstation']
['C:Users/User1/Downloads']
[]
['\\lol.com\\Dfsdd\\Dfsrerere\\ytererwe\\9jungnjfl\\Projects']
[]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to make regular expression that will match any folder path of any length on Windows and Unix?
So, for example, regex should match: C:Users/Hp Workstation, as well as: C:Users/User1/Downloads and C:Users/Desktop/Python/python-2.7.7-docs, and even much longer paths...
This was just example. I meant some kind of universal regex to match absolutely any path(any partition, any folder, any subfolder...)
I would like to do it in Python.
Thanks in advance!

ONE OF THE ANSWERS:
This is one of the possible solutions I came to, that works for the vast majority of different paths, in most programming languages.

^([a-zA-Z]?\:?[^\/\\:*?"<>|]*|[\/\\]{1,2}[^\/\\:*?"<>|]+[\/\\][^\/\\:*?"<>|]+)([\/\\][^\/\\:*?"<>|]+)+

Body:
You can try this, this matches local as well as network paths.

^(C:[\S\s]+|\\[\S\s]+) or ^(C:.*|\\.*)

example

a = 'C:Users/Hp Workstation'
b = 'C:Users/User1/Downloads'
c = 'Users/Desktop/Python/python-2.7.7-docs'
d = '\\lol.com\Dfsdd\Dfsrerere\ytererwe\9jungnjfl\Projects'
e = 'lol.com\Dfsdd\Dfsrerere\ytererwe\9jungnjfl\Projects'
lis=[a,b,c,d,e]
for item in lis:
    print(re.findall(r'^(C:[\S\s]+|\\[\S\s]+)', item ))

output

['C:Users/Hp Workstation']
['C:Users/User1/Downloads']
[]
['\\lol.com\\Dfsdd\\Dfsrerere\\ytererwe\\9jungnjfl\\Projects']
[]


问:
Is there a way to use Rg.Plugins with Xamarin Forms Shell?
From what I can see Xamarin Forms Shell is a "work in progress" and has been for a long time. With that in mind is there a way to use Rg.Plugins with Shell?

Having a problem doing things like this:

```<code>await Navigation.PushPopupAsync(PopupPage);
</code>```

When there is no Navigation property with Shell.

Would appreciate any advice on what I can do, suggestions on another plugin that could help me or can I just do the same thing with my own custom code to open up another page?

For those people who have been in the same situation as me, what did you do?
now

答:
First of all, Rg.Plugins add support to Shell Navigation, this demand was added this to To Do in Todo List.
https://github.com/rotorgames/Rg.Plugins.Popup/issues/441,

But I test Rg.Plugins in the ShellContent,  ShellContent use a ContentPage to display the Button, then click the Button to pop up a window. it worked as normal. Here is running screenshot.

Xamarin forms shell achieve the Navigation that provide following ways.
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/navigation

I test Rg.Plugins with above ways. It cannot worked. It do not support the Rg.Plugins page.

Body:
From what I can see Xamarin Forms Shell is a "work in progress" and has been for a long time. With that in mind is there a way to use Rg.Plugins with Shell?

Having a problem doing things like this:

await Navigation.PushPopupAsync(PopupPage);

When there is no Navigation property with Shell.

Would appreciate any advice on what I can do, suggestions on another plugin that could help me or can I just do the same thing with my own custom code to open up another page?

For those people who have been in the same situation as me, what did you do?
now


问:
Spring Config Server - No such label: master
I have a simple Spring Cloud Config Server which consume configuration from git server.

ConfigServer bootstrap.yml :

```<code>spring:
  application:
    name: config-service
  cloud:
    config:
      server:
        git:
          uri: ssh://git@mydomain:myport/myrepo.git
          searchPaths: "configurations/{application}/{profile}"
server:
  port: 8888
</code>```

When I deploy ConfigServer on local, I can retrieve configuration from http://localhost:8888/myapp/test. But when I deploy ConfigServer on test server, it throws No such label: master when I hit http://testserverip:8888/myapp/test.

Any help would be most appreciated!

答:
I faced this same annoying scenario.

I'll first state how I solved this scenario and will later emphasize my mistakes which I did in my previous approaches.
In my context, I'm using application.properties

My application overview looks like below:
I have a config-server which is centralized & provides the respective configuration data to the respective micro-services.

For instance, a micro-service 'limits-service', requires some configuration data, it gets it from the central configuration server('spring-cloud-config-server').
Hence to achieve this, 'limits-service' queries the central config server which in-turn fetches the requested data from a remote git branch('spring-cloud-samples').

```<code>                            ┌---------------------- <--> [currency-exchange-service]
    [git] <--> [spring-cloud-config-server] ------- <--> [limits-service]
                            └---------------------- <--> [currency-conversion-service]
</code>```

Solution:

I simply created a new Git Repository (spring-cloud-samples) for all the configuration files which would be consumed by several micro-services through a central configuration server.

In the application.properties file of central configuration server('spring-cloud-config-server'), I have provided a property as:

```<code>spring.cloud.config.server.git.uri=https://github.com/{username}/{git-reponame.git}
</code>```

which might look like

spring.cloud.config.server.git.uri=https://github.com/alice123/spring-cloud-samples.git
That's it!

On starting my central-config-server & observe the log which is as follows:

```<code>2020-02-17 05:25:07.867  INFO 15000 --- [nio-8888-exec-9] o.s.c.c.s.e.NativeEnvironmentRepository  : Adding property source: file:/D:/Users/{userName}/AppData/Local/Temp/config-repo-3453413414/limits-service.properties
</code>```

Moreover, I also consumed the config-data through my 'limits-service' & it worked like a charm!

I tried the following things that resulted in failures and a lot of screaming & yelling. XD

I'm posting it, just so that someone who's trying this same concept might save a night's work or maybe less :p

1) Initially, I was using my Git Repositories SSH URL in my application.properties file of central-config-server like follows:

```<code>spring.cloud.config.server.git.uri=git@github.com:alice123/spring-cloud-samples.git
spring.cloud.config.server.git.username=alice123
spring.cloud.config.server.git.password=alice123Pwd
</code>```

which resulted in the following error:

```<code>2020-02-17 05:22:45.091  WARN 15000 --- [nio-8888-exec-1] .c.s.e.MultipleJGitEnvironmentRepository : Error occured cloning to base directory.
org.eclipse.jgit.api.errors.TransportException: git@github.com:aniketrb-github/spring-cloud-samples.git: Auth fail
</code>```

2) Later, I tried to read the config data from a native/local git directory, which was pointing to my Git remote branch(spring-cloud-samples)
Then I provided the following in my application.properties file:

```<code>spring.cloud.config.server.git.uri=file://D:\aniket-workspace\github-ws\microservices\udemy-microservices\git-localconfig-repo
</code>```

This crashed with:

```<code>java.lang.IllegalStateException: Failed to load property source from location 'classpath:/application.properties'
</code>```

3) Later after enough googling, I changed the above property to below which worked!!:

```<code>spring.cloud.config.server.git.uri=D:\\\\alice-workspace\\\\github-ws\\\\microservices\\\\git-localconfig-repo
</code>```

The 'limits-service' eventually failed while it tried to get the config-data from 'spring.cloud.config.server' with following error:

```<code>404: Not Found - "org.springframework.cloud.config.server.environment.NoSuchLabelException: No such label: master"
</code>```

The solution I've stated worked for me due to all the failures I came across which I mentioned above.
Please correct me if I'm wrong & improvise if necessary. I hope this helps and saves some crucial time.

References: spring-cloud-config, https-or-ssh, git-ssh-windows, git-ssh-windows-troubleshooting

ContentLicense: CC BY-SA 3.0

Body:
I have a simple Spring Cloud Config Server which consume configuration from git server.

ConfigServer bootstrap.yml :

spring:
  application:
    name: config-service
  cloud:
    config:
      server:
        git:
          uri: ssh://git@mydomain:myport/myrepo.git
          searchPaths: "configurations/{application}/{profile}"
server:
  port: 8888

When I deploy ConfigServer on local, I can retrieve configuration from http://localhost:8888/myapp/test. But when I deploy ConfigServer on test server, it throws No such label: master when I hit http://testserverip:8888/myapp/test.

Any help would be most appreciated!

Body:
I faced this same annoying scenario.

I'll first state how I solved this scenario and will later emphasize my mistakes which I did in my previous approaches.
In my context, I'm using application.properties

My application overview looks like below:
I have a config-server which is centralized & provides the respective configuration data to the respective micro-services.

For instance, a micro-service 'limits-service', requires some configuration data, it gets it from the central configuration server('spring-cloud-config-server').
Hence to achieve this, 'limits-service' queries the central config server which in-turn fetches the requested data from a remote git branch('spring-cloud-samples').

                            ┌---------------------- <--> [currency-exchange-service]
    [git] <--> [spring-cloud-config-server] ------- <--> [limits-service]
                            └---------------------- <--> [currency-conversion-service]

Solution:

I simply created a new Git Repository (spring-cloud-samples) for all the configuration files which would be consumed by several micro-services through a central configuration server.

In the application.properties file of central configuration server('spring-cloud-config-server'), I have provided a property as:

spring.cloud.config.server.git.uri=https://github.com/{username}/{git-reponame.git}

which might look like

spring.cloud.config.server.git.uri=https://github.com/alice123/spring-cloud-samples.git
That's it!

On starting my central-config-server & observe the log which is as follows:

2020-02-17 05:25:07.867  INFO 15000 --- [nio-8888-exec-9] o.s.c.c.s.e.NativeEnvironmentRepository  : Adding property source: file:/D:/Users/{userName}/AppData/Local/Temp/config-repo-3453413414/limits-service.properties

Moreover, I also consumed the config-data through my 'limits-service' & it worked like a charm!

I tried the following things that resulted in failures and a lot of screaming & yelling. XD

I'm posting it, just so that someone who's trying this same concept might save a night's work or maybe less :p

1) Initially, I was using my Git Repositories SSH URL in my application.properties file of central-config-server like follows:

spring.cloud.config.server.git.uri=git@github.com:alice123/spring-cloud-samples.git
spring.cloud.config.server.git.username=alice123
spring.cloud.config.server.git.password=alice123Pwd

which resulted in the following error:

2020-02-17 05:22:45.091  WARN 15000 --- [nio-8888-exec-1] .c.s.e.MultipleJGitEnvironmentRepository : Error occured cloning to base directory.
org.eclipse.jgit.api.errors.TransportException: git@github.com:aniketrb-github/spring-cloud-samples.git: Auth fail

2) Later, I tried to read the config data from a native/local git directory, which was pointing to my Git remote branch(spring-cloud-samples)
Then I provided the following in my application.properties file:

spring.cloud.config.server.git.uri=file://D:\aniket-workspace\github-ws\microservices\udemy-microservices\git-localconfig-repo

This crashed with:

java.lang.IllegalStateException: Failed to load property source from location 'classpath:/application.properties'

3) Later after enough googling, I changed the above property to below which worked!!:

spring.cloud.config.server.git.uri=D:\\\\alice-workspace\\\\github-ws\\\\microservices\\\\git-localconfig-repo

The 'limits-service' eventually failed while it tried to get the config-data from 'spring.cloud.config.server' with following error:

404: Not Found - "org.springframework.cloud.config.server.environment.NoSuchLabelException: No such label: master"

The solution I've stated worked for me due to all the failures I came across which I mentioned above.
Please correct me if I'm wrong & improvise if necessary. I hope this helps and saves some crucial time.

References: spring-cloud-config, https-or-ssh, git-ssh-windows, git-ssh-windows-troubleshooting


问:
Multiplying variables giving '0' answer every time
I am using this code and it gives 0 answer every time when I click on Button.
Here is The code.

<input type="text" id="first">
<input type="text" id="second">
<input type="text" id="ans">
<button id="btn">Count</button>
```

答:
The reason is that when you click the button in your original code it gets executed with 0 values because you have not asked them to get initiated after each button click. So what you are trying to do is just that both first and second text fileds will get their values in the initial page load this means those values are empty. So then when you click the button it get current values(0) and multiple. So its always 0.

In below example what @Jacob doing is he first get the target button via  var b = document.getElementById('btn'); and then he have wrapped the variables inside click function . So each time you click the button and function get called and each variable get current values.

At last what he did is that he when you click the button he asks for each button current values . So it also get the current value from the elements.

Just move the onclick like up, so it gets the new values when the user clicks.

<input type="text" id="first">
<input type="text" id="second">
<input type="text" id="ans">
<button id="btn">Count</button>
```
</div>
</div>
</p>

<p>Or to only get the elements once.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="first">
<input type="text" id="second">
<input type="text" id="ans">
<button id="btn">Count</button>
<script>
  var b = document.getElementById('btn');
  var f = document.getElementById('first');
  var s = document.getElementById('second');
  var ans = document.getElementById('ans');
  b.onclick = function() {
    ans.value = f.value * s.value;
  }
</script></code>```

Body:
The reason is that when you click the button in your original code it gets executed with 0 values because you have not asked them to get initiated after each button click. So what you are trying to do is just that both first and second text fileds will get their values in the initial page load this means those values are empty. So then when you click the button it get current values(0) and multiple. So its always 0.

In below example what @Jacob doing is he first get the target button via  var b = document.getElementById('btn'); and then he have wrapped the variables inside click function . So each time you click the button and function get called and each variable get current values.

At last what he did is that he when you click the button he asks for each button current values . So it also get the current value from the elements.

Just move the onclick like up, so it gets the new values when the user clicks.

<input type="text" id="first">
<input type="text" id="second">
<input type="text" id="ans">
<button id="btn">Count</button>
<script>
  var b = document.getElementById('btn');
  b.onclick = function() {
    var f = document.getElementById('first').value;
    var s = document.getElementById('second').value;
    var ans = document.getElementById('ans');
    ans.value = f * s;
  }
</script>

Or to only get the elements once.

<input type="text" id="first">
<input type="text" id="second">
<input type="text" id="ans">
<button id="btn">Count</button>
<script>
  var b = document.getElementById('btn');
  var f = document.getElementById('first');
  var s = document.getElementById('second');
  var ans = document.getElementById('ans');
  b.onclick = function() {
    ans.value = f.value * s.value;
  }
</script>


问:
.net core identity 'IsSignedIn' always returns false, even after successful login
I have a .net core 3 identity project that I'm having issues with authentication.

Login.cshtml.cs

```<code>public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl ??= Url.Content("~/");

    if (ModelState.IsValid)
    {
        // Modified base identity to allow login by email or username
        var user = await _userManager.FindByNameAsync(Input.Username);

        if (user == null)
        {
            user = await _userManager.FindByEmailAsync(Input.Username);
        }

        var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: true);

        if (result.Succeeded)
        {
            return LocalRedirect(returnUrl);
        }

        if (result.IsNotAllowed)
        {
            return RedirectToPage("./ConfirmEmail");
        }

        if (result.IsLockedOut)
        {
            return RedirectToPage("./Lockout");
        }

        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
        return Page();
    }

    return Page();
}
</code>```

From the Login page, this line of code: var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: true); returns result.Succeeded, but from the page view, this code always returns false:

```<code>@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
}
</code>```

When I step through the code for the IsSignedIn method from the code below, it is failing because principal.Identities.AuthenticationType is always null.

SignInManager.cs

```<code>public override bool IsSignedIn(ClaimsPrincipal principal)
{
    if (principal == null)
    {
        throw new ArgumentNullException(nameof(principal));
    }
    return principal?.Identities != null &&
       principal.Identities.Any(i => i.AuthenticationType == IdentityConstants.ApplicationScheme);
</code>```

}

My first thought is this is a configuration issue in Startup.cs, but I'm not sure what or where the AuthenticationType gets set?

Startup.cs

```<code>    public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IDbConnection>((sp) => new SqlConnection(Configuration.GetConnectionString("Database")));
    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddDefaultTokenProviders();
        services.ConfigureApplicationCookie(options =>
        {
            options.AccessDeniedPath ="/Account/AccessDenied";
            options.Cookie.Name = "MyApp";
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
            options.LoginPath = "/Account/Login";
            // ReturnUrlParameter requires
            //using Microsoft.AspNetCore.Authentication.Cookies;
            options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
            options.SlidingExpiration = true;
        });
    services.AddMemoryCache();
    services.AddMvc(options => { options.EnableEndpointRouting = false; });
    services.AddRazorPages();
    services.AddSession();
    services.AddTransient<IUserStore<ApplicationUser>, CustomUserStore>();
    services.AddTransient<IRoleStore<ApplicationRole>, CustomRoleStore>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddSerilog();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseMvcWithDefaultRoute();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();
    app.UseSession();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapRazorPages();
    });
}
</code>```

答:
app.UseMvcWithDefaultRoute() is required to be placed after app.UseAuthentication().

Since you have used app.UseMvc() in your Configure method , just remove app.UseMvcWithDefaultRoute(); line or place it after app.UseAuthentication()  in your code could resolve it.

Body:
I have a .net core 3 identity project that I'm having issues with authentication.

Login.cshtml.cs

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl ??= Url.Content("~/");

    if (ModelState.IsValid)
    {
        // Modified base identity to allow login by email or username
        var user = await _userManager.FindByNameAsync(Input.Username);

        if (user == null)
        {
            user = await _userManager.FindByEmailAsync(Input.Username);
        }

        var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: true);

        if (result.Succeeded)
        {
            return LocalRedirect(returnUrl);
        }

        if (result.IsNotAllowed)
        {
            return RedirectToPage("./ConfirmEmail");
        }

        if (result.IsLockedOut)
        {
            return RedirectToPage("./Lockout");
        }

        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
        return Page();
    }

    return Page();
}

From the Login page, this line of code: var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: true); returns result.Succeeded, but from the page view, this code always returns false:

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
}

When I step through the code for the IsSignedIn method from the code below, it is failing because principal.Identities.AuthenticationType is always null.

SignInManager.cs

public override bool IsSignedIn(ClaimsPrincipal principal)
{
    if (principal == null)
    {
        throw new ArgumentNullException(nameof(principal));
    }
    return principal?.Identities != null &&
       principal.Identities.Any(i => i.AuthenticationType == IdentityConstants.ApplicationScheme);

}

My first thought is this is a configuration issue in Startup.cs, but I'm not sure what or where the AuthenticationType gets set?

Startup.cs

    public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IDbConnection>((sp) => new SqlConnection(Configuration.GetConnectionString("Database")));
    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddDefaultTokenProviders();
        services.ConfigureApplicationCookie(options =>
        {
            options.AccessDeniedPath ="/Account/AccessDenied";
            options.Cookie.Name = "MyApp";
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
            options.LoginPath = "/Account/Login";
            // ReturnUrlParameter requires
            //using Microsoft.AspNetCore.Authentication.Cookies;
            options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
            options.SlidingExpiration = true;
        });
    services.AddMemoryCache();
    services.AddMvc(options => { options.EnableEndpointRouting = false; });
    services.AddRazorPages();
    services.AddSession();
    services.AddTransient<IUserStore<ApplicationUser>, CustomUserStore>();
    services.AddTransient<IRoleStore<ApplicationRole>, CustomRoleStore>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddSerilog();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseMvcWithDefaultRoute();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();
    app.UseSession();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapRazorPages();
    });
}


问:
Is destructuring this possible?
I am new to destructuring and need help finding the best solution. I have a pretty complicated object coming back as a response and would like to clean it up. Without doing anything, it looks like this:

```<code>
const homeTeam = {

totalPlaysFor: res.data.stats.home.teamStats[0].miscellaneous.offensePlays,

totalPlaysAgainst: res.data.stats.away.teamStats[0].miscellaneous.offensePlays

}

</code>```

I know I can do something like:

```<code>
const { offensePlays } = res.data.stats.home.teamStats[0].miscellaneous;

</code>```

but that only solves my problem for one of them and would leave the other still long and tough to read.

答:
You can destructure as much as you want!

const homeTeam = {
  totalPlaysFor: res.data.stats.home.teamStats[0].miscellaneous.offensePlays,
  totalPlaysAgainst: res.data.stats.away.teamStats[0].miscellaneous.offensePlays
}
```

<p>You can even use a combination of array destructuring / object destructuring here:</p>

<pre class="lang-js prettyprint-override"><code>const [ home ] = res.data.stats.home.teamStats
const [ away ] = res.data.stats.away.teamStats

const { offensePlays: totalPlaysFor } = home.miscellaneous
const { offensePlays: totalPlaysAgainst } = away.miscellaneous

const hometeam = { totalPlaysFor, totalPlaysAgainst }
</code>```

Or, if you want a more reusable solution, you can use parameter destructuring:

const getTeam = (
  { miscellaneous: { offensePlays: totalPlaysFor } },
  { miscellaneous: { offensePlays: totalPlaysAgainst } }
) => ({
  totalPlaysFor,
  totalPlaysAgainst
})
```

<p>Then you can use it like:</p>

<pre class="lang-js prettyprint-override"><code>const [ home ] = res.data.stats.home.teamStats
const [ away ] = res.data.stats.away.teamStats
const homeTeam = getTeam(home, away)
</code>```

Title: Is destructuring this possible?

Body:
I am new to destructuring and need help finding the best solution. I have a pretty complicated object coming back as a response and would like to clean it up. Without doing anything, it looks like this:

const homeTeam = {

totalPlaysFor: res.data.stats.home.teamStats[0].miscellaneous.offensePlays,

totalPlaysAgainst: res.data.stats.away.teamStats[0].miscellaneous.offensePlays

}

I know I can do something like:

const { offensePlays } = res.data.stats.home.teamStats[0].miscellaneous;

but that only solves my problem for one of them and would leave the other still long and tough to read.

Body:
You can destructure as much as you want!

const homeTeam = {
  totalPlaysFor: res.data.stats.home.teamStats[0].miscellaneous.offensePlays,
  totalPlaysAgainst: res.data.stats.away.teamStats[0].miscellaneous.offensePlays
}

You can even use a combination of array destructuring / object destructuring here:

const [ home ] = res.data.stats.home.teamStats
const [ away ] = res.data.stats.away.teamStats

const { offensePlays: totalPlaysFor } = home.miscellaneous
const { offensePlays: totalPlaysAgainst } = away.miscellaneous

const hometeam = { totalPlaysFor, totalPlaysAgainst }

Or, if you want a more reusable solution, you can use parameter destructuring:

const getTeam = (
  { miscellaneous: { offensePlays: totalPlaysFor } },
  { miscellaneous: { offensePlays: totalPlaysAgainst } }
) => ({
  totalPlaysFor,
  totalPlaysAgainst
})

Then you can use it like:

const [ home ] = res.data.stats.home.teamStats
const [ away ] = res.data.stats.away.teamStats
const homeTeam = getTeam(home, away)


问:
DappNode mainnet syncing stuck
I installed a new machine with DappNode. Admin panel shows that Mainnet syncing is in progress. But it has been stuck at 18% since last 2 days. Message 'Syncing snapshot: 788 / 4286' is not changing.
Any idea how to troubleshoot this?</p>

答: From System Packages -> ETHChain -> Controls, restarted the process. This resolved the issue.</p>

Title: DappNode mainnet syncing stuck


问:
How to send xml file content to webservice using php curl
I have a datafile.xml that needs to be sent to a webservice.
I am using php curl to send the file.  The problem is I don't know how to access and send the contents of the datafile.xml.

Here is content of the datafile.xml -

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<inventoryUpdateRequest version="1.0">
<action name="bookupdate">
<username>user</username>
<password>issecret</password>
</action>
<WebList>
<Website>
<transactionType>delete</transactionType>
<vendorBookID>FaNuPh1</vendorBookID>
</Website>
</WebList>
</inventoryUpdateRequest>
</code>```

Here is my send php file -

```<code><?php require_once('post_xml.php');?>
<?php

$xml = HERE IS MY LACK OF UNDERSTANDING HOW TO EXTRACT datafile.xml CONTENT;

$url ='https://inventoryupdate.website.com';
$port = 80;
$response = xml_post($xml, $url, $port);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<P><?=nl2br(htmlentities($response));?></P>
</body>
</html>
</code>```

And here is the post_xml.php file that uses cURL -

```<code><?php
// open a http channel, transmit data and return received buffer
function xml_post($post_xml, $url, $port)
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];

$ch = curl_init();    // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_FAILONERROR, 1);              // Fail on errors

if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off'))
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    // allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_PORT, $port);          //Set the port number
curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_xml); // add POST fields
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);

if($port==443)
{
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
}

$data = curl_exec($ch);

curl_close($ch);

return $data;
}
?>
</code>```

Any help would be much appreciated!

答:
If you don't need to parse the XML file, then I'd suggest fopen() or file_get_contents().

For simplicity sake, assuming datafile.xml is in the same directory, try:

```<code>$xml = file_get_contents('datafile.xml');
</code>```

Body:
I have a datafile.xml that needs to be sent to a webservice.
I am using php curl to send the file.  The problem is I don't know how to access and send the contents of the datafile.xml.

Here is content of the datafile.xml -

<?xml version="1.0" encoding="ISO-8859-1"?>
<inventoryUpdateRequest version="1.0">
<action name="bookupdate">
<username>user</username>
<password>issecret</password>
</action>
<WebList>
<Website>
<transactionType>delete</transactionType>
<vendorBookID>FaNuPh1</vendorBookID>
</Website>
</WebList>
</inventoryUpdateRequest>

Here is my send php file -

<?php require_once('post_xml.php');?>
<?php

$xml = HERE IS MY LACK OF UNDERSTANDING HOW TO EXTRACT datafile.xml CONTENT;

$url ='https://inventoryupdate.website.com';
$port = 80;
$response = xml_post($xml, $url, $port);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>

<?=nl2br(htmlentities($response));?>

And here is the post_xml.php file that uses cURL -

<?php
// open a http channel, transmit data and return received buffer
function xml_post($post_xml, $url, $port)
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];

$ch = curl_init();    // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_FAILONERROR, 1);              // Fail on errors

if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off'))
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    // allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_PORT, $port);          //Set the port number
curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_xml); // add POST fields
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);

if($port==443)
{
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
}

$data = curl_exec($ch);

curl_close($ch);

return $data;
}
?>

Any help would be much appreciated!

Body:
If you don't need to parse the XML file, then I'd suggest fopen() or file_get_contents().

For simplicity sake, assuming datafile.xml is in the same directory, try:

$xml = file_get_contents('datafile.xml');


问:
sounds storaged in local files in vuejs
I am trying to find a way to storage a sound for my Battleship game in my local file instead of reference its link on internet,
my code referring to the method that triggers this sound is this

```<code> @click.prevent="fireSound('http://soundbible.com/grab.php?id=1794&type=mp3')"
</code>```

I did try to do it as if it was an image , i mean

```<code> @click.prevent="fireSound('src:'../.../....mp3')"
</code>```

but it didn't work!!!

答:
I dont know where you put your sound, but in my project I put my sound.mp3 file
on assets/music/sound.mp3

```<code>playSound(sound) {
  if (sound) {
    const audio = new Audio(require('@/assets/music/sound.mp3'));
    audio.play();
  }
},
</code>```

@ mean root folder project, Can you share your structure folder to put your file ?

Title: sounds storaged in local files in vuejs

Body:
I am trying to find a way to storage a sound for my Battleship game in my local file instead of reference its link on internet,
my code referring to the method that triggers this sound is this

 @click.prevent="fireSound('http://soundbible.com/grab.php?id=1794&type=mp3')"

I did try to do it as if it was an image , i mean

 @click.prevent="fireSound('src:'../.../....mp3')"

but it didn't work!!!

Body:
I dont know where you put your sound, but in my project I put my sound.mp3 file
on assets/music/sound.mp3

playSound(sound) {
  if (sound) {
    const audio = new Audio(require('@/assets/music/sound.mp3'));
    audio.play();
  }
},

@ mean root folder project, Can you share your structure folder to put your file ?


问:
How can I round the elements of a vector?
-replace each element with its integer
for (2.72,4.34,9.82, 1.0,4.05,2.45)
cout 2 4 9 1 4 2.

i tried this

```<code>#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int n;
    double v[100],i;
    cin>>n;
    for(i=1;i<=n;i++)
        cin>>v[i];
    for(i=1;i<=n;i++)
    {
        round(v[i]);
    }
    for(i=1;i<=n;i++)
        cout<<v[i]<<" ";
}
</code>```

but i get this error :

```<code>|10|error: invalid types 'double [100][double]' for array subscript|
|13|error: invalid types 'double [100][double]' for array subscript|
|16|error: invalid types 'double [100][double]' for array subscript|
</code>```

答:
I see the following questions and suggestions:

The iterator of an array should use an integer variable, not a double.

According to the example you gave, you should round down instead of rounding, so you should use floor instead of round. It should be v[i] = floor(v [i]);.

Generally speaking, if the array size is not fixed, dynamic allocation will be used. For example, use new function double *v = new double[n];, and remember to delete when using up.

Array v contains 100 elements. It starts from v[0], v[1]...to v[99], so variable I is better to start from 0 to prevent overstepping.

Body:
-replace each element with its integer
for (2.72,4.34,9.82, 1.0,4.05,2.45)
cout 2 4 9 1 4 2.

i tried this

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int n;
    double v[100],i;
    cin>>n;
    for(i=1;i<=n;i++)
        cin>>v[i];
    for(i=1;i<=n;i++)
    {
        round(v[i]);
    }
    for(i=1;i<=n;i++)
        cout<<v[i]<<" ";
}

but i get this error :

|10|error: invalid types 'double [100][double]' for array subscript|
|13|error: invalid types 'double [100][double]' for array subscript|
|16|error: invalid types 'double [100][double]' for array subscript|


问:
Unable to upload file to folder in Google Drive
I'm trying to upload a local file to a a specified folder in Google Drive, and I'm only successful in getting it uploaded to Drive, not in the folder I'm telling it to. I've tested with a shared folder as well as a non-shared folder and I'm getting the same result. No error, just the file being in the root Drive directory.

```<code>
    creds = GetGoogleCredentials()
    service = build('drive', 'v3', credentials=creds)
    # Call the Drive v3 API
    FileSearch = service.files().list(q="name='{0}'".format(file), fields="nextPageToken, files(id, name)").execute()
    items = FileSearch.get('files', [])
    FolderID = 'IDHere'
    if not items:
        file_metadata = {'name': file,
                         "parents": FolderID
                        }

        media = MediaFileUpload('folder/en/' + file,resumable=True)
        service.files().create(body=file_metadata,media_body=media,fields='id').execute()
    else:
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))
</code>```

Based off what I've found, the "parents": FolderID entry should be what I need, but it's like the create method is ignoring it.

答:
You want to upload a file to the specific folder in Google Drive using Drive API v3.

You want to achieve this using googleapis with python.

You have already uploaded a file to Google Drive using your script.

If my understanding is correct, how about this modification? Please modify parents in the object of file_metadata as follows.

From:

```<code>"parents": FolderID
</code>```

To:

```<code>"parents": [FolderID]
</code>```

At Google Drive, a file has several parents. So in this case, the folder ID is set in an array.

Reference:

Files: create

If this was not the direct solution of your issue, I apologize.

Body:
I'm trying to upload a local file to a a specified folder in Google Drive, and I'm only successful in getting it uploaded to Drive, not in the folder I'm telling it to. I've tested with a shared folder as well as a non-shared folder and I'm getting the same result. No error, just the file being in the root Drive directory.

    creds = GetGoogleCredentials()
    service = build('drive', 'v3', credentials=creds)
    # Call the Drive v3 API
    FileSearch = service.files().list(q="name='{0}'".format(file), fields="nextPageToken, files(id, name)").execute()
    items = FileSearch.get('files', [])
    FolderID = 'IDHere'
    if not items:
        file_metadata = {'name': file,
                         "parents": FolderID
                        }

        media = MediaFileUpload('folder/en/' + file,resumable=True)
        service.files().create(body=file_metadata,media_body=media,fields='id').execute()
    else:
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))

Based off what I've found, the "parents": FolderID entry should be what I need, but it's like the create method is ignoring it.

Body:
You want to upload a file to the specific folder in Google Drive using Drive API v3.

You want to achieve this using googleapis with python.

You have already uploaded a file to Google Drive using your script.

If my understanding is correct, how about this modification? Please modify parents in the object of file_metadata as follows.

From:

"parents": FolderID

To:

"parents": [FolderID]

At Google Drive, a file has several parents. So in this case, the folder ID is set in an array.

Reference:

Files: create

If this was not the direct solution of your issue, I apologize.


问:
Add/Subtract months/years to date in dart?
I saw that in dart there is a class Duration but it cant be used add/subtract years or month. How did you managed this issue, I need to subtract 6 months from an date. Is there something like moment.js for dart or something around?
Thank you</p>

答:
You can use the subtract and add methods

```<code> date1.subtract(Duration(days: 7, hours: 3, minutes: 43, seconds: 56));

 date1.add(Duration(days: 1, hours: 23)));
</code>```

Flutter Docs:

Subtract

Add

UPDATE

Above is the way to manually manipulate the date, to use years/months as parameters you can use Jiffy plugin, after install:

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

DateTime d = Jiffy().subtract(months: 6).dateTime;  // 6 months from DateTime.now()
DateTime d = Jiffy().add(months: 6).dateTime;

DateTime d = Jiffy(DateTime date).add(years: 6).dateTime;  // Ahead of a specific date given to Jifffy()
DateTime d = Jiffy(DateTime date).subtract(months: 6, years 3).dateTime;
</code>```

Body:
You can use the subtract and add methods

 date1.subtract(Duration(days: 7, hours: 3, minutes: 43, seconds: 56));

 date1.add(Duration(days: 1, hours: 23)));

Flutter Docs:

Subtract

Add

UPDATE

Above is the way to manually manipulate the date, to use years/months as parameters you can use Jiffy plugin, after install:

import 'package:jiffy/jiffy.dart';

DateTime d = Jiffy().subtract(months: 6).dateTime;  // 6 months from DateTime.now()
DateTime d = Jiffy().add(months: 6).dateTime;

DateTime d = Jiffy(DateTime date).add(years: 6).dateTime;  // Ahead of a specific date given to Jifffy()
DateTime d = Jiffy(DateTime date).subtract(months: 6, years 3).dateTime;


问:
TabController listener called multiple times. How does indexIsChanging work?
I need to know which Tab is clicked. Therefore I added the SingleTickerProviderStateMixin, created a TabController field in my State and added a Listener (huge boilerplate IMHO...).

```<code>class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        print('click, ${_tabController.index}');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
//...
}
}
</code>```

However every time I click a Tab, multiple statements are printed instead of just one, as I expected. Why is indexIsChanging not working?

答:
Reason From https://github.com/flutter/flutter/issues/13848

Source code of TabController , notifyListeners() call twice https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/material/tab_controller.dart#L162

```<code>if (duration != null) {
      _indexIsChangingCount += 1;
      notifyListeners(); // Because the value of indexIsChanging may have changed.
      _animationController
        .animateTo(_index.toDouble(), duration: duration, curve: curve)
        .whenCompleteOrCancel(() {
          _indexIsChangingCount -= 1;
          notifyListeners();
        });
</code>```

Solution To print current index only one time

code snippet from https://github.com/flutter/flutter/issues/13848#issuecomment-486051402

```<code>@override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: choices.length)
      ..addListener(() {
        if(_tabController.indexIsChanging) {
          print("tab is animating. from active (getting the index) to inactive(getting the index) ");
        }else {
          //tab is finished animating you get the current index
          //here you can get your index or run some method once.
          print(_tabController.index);
        }
      });
  }
</code>```

working demo

full test code

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

class AppBarBottomSample extends StatefulWidget {
  @override
  _AppBarBottomSampleState createState() => _AppBarBottomSampleState();
}

class _AppBarBottomSampleState extends State<AppBarBottomSample>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: choices.length)
      ..addListener(() {
        if(_tabController.indexIsChanging) {
          print("tab is animating. from active (getting the index) to inactive(getting the index) ");
        }else {
          //tab is finished animating you get the current index
          //here you can get your index or run some method once.
          print(_tabController.index);
        }
      });
  }

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

  void _nextPage(int delta) {
    final int newIndex = _tabController.index + delta;
    if (newIndex < 0 || newIndex >= _tabController.length) return;
    _tabController.animateTo(newIndex);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('AppBar Bottom Widget'),
          leading: IconButton(
            tooltip: 'Previous choice',
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              _nextPage(-1);
            },
          ),
          actions: <Widget>[
            IconButton(
              icon: const Icon(Icons.arrow_forward),
              tooltip: 'Next choice',
              onPressed: () {
                _nextPage(1);
              },
            ),
          ],
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(48.0),
            child: Theme(
              data: Theme.of(context).copyWith(accentColor: Colors.white),
              child: Container(
                height: 48.0,
                alignment: Alignment.center,
                child: TabPageSelector(controller: _tabController),
              ),
            ),
          ),
        ),
        body: TabBarView(
          controller: _tabController,
          children: choices.map((Choice choice) {
            return Padding(
              padding: const EdgeInsets.all(16.0),
              child: ChoiceCard(choice: choice),
            );
          }).toList(),
        ),
      ),
    );
  }
}

class Choice {
  const Choice({this.title, this.icon});

  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: 'CAR', icon: Icons.directions_car),
  const Choice(title: 'BICYCLE', icon: Icons.directions_bike),
  const Choice(title: 'BOAT', icon: Icons.directions_boat),
  const Choice(title: 'BUS', icon: Icons.directions_bus),
  const Choice(title: 'TRAIN', icon: Icons.directions_railway),
  const Choice(title: 'WALK', icon: Icons.directions_walk),
];

class ChoiceCard extends StatelessWidget {
  const ChoiceCard({Key key, this.choice}) : super(key: key);

  final Choice choice;

  @override
  Widget build(BuildContext context) {
    final TextStyle textStyle = Theme.of(context).textTheme.display1;
    return Card(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Icon(choice.icon, size: 128.0, color: textStyle.color),
            Text(choice.title, style: textStyle),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(AppBarBottomSample());
}
</code>```

Body:
I need to know which Tab is clicked. Therefore I added the SingleTickerProviderStateMixin, created a TabController field in my State and added a Listener (huge boilerplate IMHO...).

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        print('click, ${_tabController.index}');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
//...
}
}

However every time I click a Tab, multiple statements are printed instead of just one, as I expected. Why is indexIsChanging not working?

Body:
Reason From https://github.com/flutter/flutter/issues/13848

Source code of TabController , notifyListeners() call twice https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/material/tab_controller.dart#L162

if (duration != null) {
      _indexIsChangingCount += 1;
      notifyListeners(); // Because the value of indexIsChanging may have changed.
      _animationController
        .animateTo(_index.toDouble(), duration: duration, curve: curve)
        .whenCompleteOrCancel(() {
          _indexIsChangingCount -= 1;
          notifyListeners();
        });

Solution To print current index only one time

code snippet from https://github.com/flutter/flutter/issues/13848#issuecomment-486051402

@override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: choices.length)
      ..addListener(() {
        if(_tabController.indexIsChanging) {
          print("tab is animating. from active (getting the index) to inactive(getting the index) ");
        }else {
          //tab is finished animating you get the current index
          //here you can get your index or run some method once.
          print(_tabController.index);
        }
      });
  }

working demo

full test code

import 'package:flutter/material.dart';

class AppBarBottomSample extends StatefulWidget {
  @override
  _AppBarBottomSampleState createState() => _AppBarBottomSampleState();
}

class _AppBarBottomSampleState extends State<AppBarBottomSample>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: choices.length)
      ..addListener(() {
        if(_tabController.indexIsChanging) {
          print("tab is animating. from active (getting the index) to inactive(getting the index) ");
        }else {
          //tab is finished animating you get the current index
          //here you can get your index or run some method once.
          print(_tabController.index);
        }
      });
  }

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

  void _nextPage(int delta) {
    final int newIndex = _tabController.index + delta;
    if (newIndex < 0 || newIndex >= _tabController.length) return;
    _tabController.animateTo(newIndex);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('AppBar Bottom Widget'),
          leading: IconButton(
            tooltip: 'Previous choice',
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              _nextPage(-1);
            },
          ),
          actions: <Widget>[
            IconButton(
              icon: const Icon(Icons.arrow_forward),
              tooltip: 'Next choice',
              onPressed: () {
                _nextPage(1);
              },
            ),
          ],
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(48.0),
            child: Theme(
              data: Theme.of(context).copyWith(accentColor: Colors.white),
              child: Container(
                height: 48.0,
                alignment: Alignment.center,
                child: TabPageSelector(controller: _tabController),
              ),
            ),
          ),
        ),
        body: TabBarView(
          controller: _tabController,
          children: choices.map((Choice choice) {
            return Padding(
              padding: const EdgeInsets.all(16.0),
              child: ChoiceCard(choice: choice),
            );
          }).toList(),
        ),
      ),
    );
  }
}

class Choice {
  const Choice({this.title, this.icon});

  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: 'CAR', icon: Icons.directions_car),
  const Choice(title: 'BICYCLE', icon: Icons.directions_bike),
  const Choice(title: 'BOAT', icon: Icons.directions_boat),
  const Choice(title: 'BUS', icon: Icons.directions_bus),
  const Choice(title: 'TRAIN', icon: Icons.directions_railway),
  const Choice(title: 'WALK', icon: Icons.directions_walk),
];

class ChoiceCard extends StatelessWidget {
  const ChoiceCard({Key key, this.choice}) : super(key: key);

  final Choice choice;

  @override
  Widget build(BuildContext context) {
    final TextStyle textStyle = Theme.of(context).textTheme.display1;
    return Card(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Icon(choice.icon, size: 128.0, color: textStyle.color),
            Text(choice.title, style: textStyle),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(AppBarBottomSample());
}


问:
Typescript change property type recursively
How to change property type recursively, im only able to do it in single dimension, judging from utility-types it seem to possible to achive that, i have tried coupe of times but can't get it right</p>

```<code>type Convert<V, O extends object> = {
    [Key in keyof O] : V
}

// single
{
    let original = {
        data1 : 1,
        data2 : 1,

    };

    let converted : Convert<string, typeof original> = {
        data1: 'a',
        data2: 'a',
    };
}

// recursive
{
    let original = {
        data1 : 1,
        data2 : 1,
        data3 : {
            data1 : 1,
            data2 : 1,
        }
    };

    let converted : Convert<string, typeof original> = {
        data1: 'a',
        data2: 'a',
        data3 : {
            data1 : 'a',
            data2 : 'a',
        }
    };
}
</code>```

答:
I'm pretty sure you want a recursive conditional type where you only recurse down into properties which are themselves objects:

```<code>type Convert<V, O extends object> = {
    [K in keyof O]: O[K] extends object ? Convert<V, O[K]> : V
}
</code>```

This will cause your example code to succeed, but there may be edge cases surrounding non-primitive properties you don't want to recurse into (e.g., arrays?), so you should test it thoroughly.

Hope that helps; good luck!

Playground link to code

Body:
How to change property type recursively, im only able to do it in single dimension, judging from utility-types it seem to possible to achive that, i have tried coupe of times but can't get it right

type Convert<V, O extends object> = {
    [Key in keyof O] : V
}

// single
{
    let original = {
        data1 : 1,
        data2 : 1,

    };

    let converted : Convert<string, typeof original> = {
        data1: 'a',
        data2: 'a',
    };
}

// recursive
{
    let original = {
        data1 : 1,
        data2 : 1,
        data3 : {
            data1 : 1,
            data2 : 1,
        }
    };

    let converted : Convert<string, typeof original> = {
        data1: 'a',
        data2: 'a',
        data3 : {
            data1 : 'a',
            data2 : 'a',
        }
    };
}

Body:
I'm pretty sure you want a recursive conditional type where you only recurse down into properties which are themselves objects:

type Convert<V, O extends object> = {
    [K in keyof O]: O[K] extends object ? Convert<V, O[K]> : V
}

This will cause your example code to succeed, but there may be edge cases surrounding non-primitive properties you don't want to recurse into (e.g., arrays?), so you should test it thoroughly.

Hope that helps; good luck!

Playground link to code


问:
Not understanding logical operators in a specific situation
I was looking into another person's code and found this specific part where I don't understand what the logic operators are being used for. (Mind that I'm still starting out with JavaScript, but also did as much research as I could before coming for your aid.)

```<code>const createStream = (options) => {
  const stream = new PassThrough({
    highWaterMark: options && options.highWaterMark || null,
  });
  stream.destroy = () => { stream._isDestroyed = true; };
  return stream;
};
</code>```

So, as far as I understand, this is a function createStream(options), basically, and it creates a variable called stream, which is a stream.PassThrough object.

Now, the part that bugs me a bit is the highWaterMark: options && options.highWaterMark || null, part.
I simply don't understand any of this. I know how to use logical operators in if() statements for instance, but this just doesn't make sense to me, and I couldn't find a lot online to explain me this.

Appreciate any help I can get.

答:
Both && and || have the same operator precedence and operate left-to-right. So

```<code>highWaterMark: options && options.highWaterMark || null,
</code>```

is equivalent to

```<code>highWaterMark: (options && options.highWaterMark) || null,
</code>```

Additionally, keep in mind that && resolves to the left side if the left side is falsy, otherwise it resolves to the right side. So if options is undefined, (options && options.highWaterMark) resolves to undefined.

The && is needed there because if the options parameter doesn't exist (eg undefined or null), simply doing

```<code>highWaterMark: options.highWaterMark || null,
</code>```

would throw an error, because you can't access properties of undefined or null.

Then, for the || part: it will resolve to the left side if the left side is truthy, else it'll resolve to the right side. So there are two possible paths:

```<code>// options starts out undefined
  highWaterMark: options && options.highWaterMark || null,
// equivalent to
  highWaterMark: (options && options.highWaterMark) || null,
  highWaterMark: (undefined && options.highWaterMark) || null,
  highWaterMark: undefined || null,
  highWaterMark: null,
</code>```

Or:

```<code>// options starts out as an object
  highWaterMark: options && options.highWaterMark || null,
// equivalent to
  highWaterMark: (options && options.highWaterMark) || null,
  highWaterMark: (options.highWaterMark) || null,
  highWaterMark: options.highWaterMark,
</code>```

So, what the code does is it

checks to see if the options variable is truthy

If so, it assigns the highWaterMark property of options to the highWaterMark property of the object

Otherwise, it assigns null to that property

It's equivalent to the following:

```<code>let highWaterMark;
if (options) {
  highWaterMark = options.highWaterMark;
} else {
  highWaterMark = null;
}
const stream = new PassThrough({ highWaterMark });
</code>```

This allows callers of createStream to be either of the type:

```<code>createStream();
</code>```

or

```<code>createStream({ highWaterMark: 'foo' });
</code>```

Body:
I was looking into another person's code and found this specific part where I don't understand what the logic operators are being used for. (Mind that I'm still starting out with JavaScript, but also did as much research as I could before coming for your aid.)

const createStream = (options) => {
  const stream = new PassThrough({
    highWaterMark: options && options.highWaterMark || null,
  });
  stream.destroy = () => { stream._isDestroyed = true; };
  return stream;
};

So, as far as I understand, this is a function createStream(options), basically, and it creates a variable called stream, which is a stream.PassThrough object.

Now, the part that bugs me a bit is the highWaterMark: options && options.highWaterMark || null, part.
I simply don't understand any of this. I know how to use logical operators in if() statements for instance, but this just doesn't make sense to me, and I couldn't find a lot online to explain me this.

Appreciate any help I can get.

Body:
Both && and || have the same operator precedence and operate left-to-right. So

highWaterMark: options && options.highWaterMark || null,

is equivalent to

highWaterMark: (options && options.highWaterMark) || null,

Additionally, keep in mind that && resolves to the left side if the left side is falsy, otherwise it resolves to the right side. So if options is undefined, (options && options.highWaterMark) resolves to undefined.

The && is needed there because if the options parameter doesn't exist (eg undefined or null), simply doing

highWaterMark: options.highWaterMark || null,

would throw an error, because you can't access properties of undefined or null.

Then, for the || part: it will resolve to the left side if the left side is truthy, else it'll resolve to the right side. So there are two possible paths:

// options starts out undefined
  highWaterMark: options && options.highWaterMark || null,
// equivalent to
  highWaterMark: (options && options.highWaterMark) || null,
  highWaterMark: (undefined && options.highWaterMark) || null,
  highWaterMark: undefined || null,
  highWaterMark: null,

Or:

// options starts out as an object
  highWaterMark: options && options.highWaterMark || null,
// equivalent to
  highWaterMark: (options && options.highWaterMark) || null,
  highWaterMark: (options.highWaterMark) || null,
  highWaterMark: options.highWaterMark,

So, what the code does is it

checks to see if the options variable is truthy

If so, it assigns the highWaterMark property of options to the highWaterMark property of the object

Otherwise, it assigns null to that property

It's equivalent to the following:

let highWaterMark;
if (options) {
  highWaterMark = options.highWaterMark;
} else {
  highWaterMark = null;
}
const stream = new PassThrough({ highWaterMark });

This allows callers of createStream to be either of the type:

createStream();

or

createStream({ highWaterMark: 'foo' });


问:
Access rightmost two columns of pandas dataframe, by number
I'm hoping to overwrite some values in a df when a condition is met. Using the df below, when col B is equal to values in lst, I want to replace values in col C,D with X.

This can achieved using the method below but I'm hoping to use indexing to select the last two columns, rather than using hard coded labels.

```<code>df = pd.DataFrame({
    'A' : [1,1,1,1,1,1,1,1],
    'B' : ['X','Foo','X','Cat','A','A','X','D'],
    'C' : [1,1,1,1,1,1,1,1],
    'D' : [1,1,1,1,1,1,1,1],
    })

lst = ['Foo','Cat']
df.loc[df.B.isin(lst), ['C','D']] = 'X'
</code>```

Attempt:

```<code>df.loc[df.B.isin(lst), df.loc[:-2]] = 'X'
</code>```

Intended:

```<code>   A    B  C  D
0  1    X  1  1
1  1  Foo  X  X
2  1    X  1  1
3  1  Cat  X  X
4  1    A  1  1
5  1    A  1  1
6  1    X  1  1
7  1    D  1  1
</code>```

答:
If I understood the question, it looks like you are searching for iloc:

```<code>df.iloc[df.B.isin(lst).values, -2:] = 'X'
</code>```

In most cases, df.loc[df.B.isin(lst), -2:] = 'X' will also return the same result, but the interpretation of -2: slice will vary if the column names are of integer type.

Body:
I'm hoping to overwrite some values in a df when a condition is met. Using the df below, when col B is equal to values in lst, I want to replace values in col C,D with X.

This can achieved using the method below but I'm hoping to use indexing to select the last two columns, rather than using hard coded labels.

df = pd.DataFrame({
    'A' : [1,1,1,1,1,1,1,1],
    'B' : ['X','Foo','X','Cat','A','A','X','D'],
    'C' : [1,1,1,1,1,1,1,1],
    'D' : [1,1,1,1,1,1,1,1],
    })

lst = ['Foo','Cat']
df.loc[df.B.isin(lst), ['C','D']] = 'X'

Attempt:

df.loc[df.B.isin(lst), df.loc[:-2]] = 'X'

Intended:

   A    B  C  D
0  1    X  1  1
1  1  Foo  X  X
2  1    X  1  1
3  1  Cat  X  X
4  1    A  1  1
5  1    A  1  1
6  1    X  1  1
7  1    D  1  1

Body:
If I understood the question, it looks like you are searching for iloc:

df.iloc[df.B.isin(lst).values, -2:] = 'X'

In most cases, df.loc[df.B.isin(lst), -2:] = 'X' will also return the same result, but the interpretation of -2: slice will vary if the column names are of integer type.


问:
What is the best approach to handle Bluetooth streams in background using a repository pattern?
I need a handler for Bluetooth connection with a frequency of 1Hz  and using like a Repository  pattern, save data in SQliteDB and display info on several views of the App.

My current choice is RxBluetooth + service, but I'm looking for other straight forward alternatives but without compromising performance. I saw there are new stuffs on Android Jetpack, maybe RxBus, or other RxJava features, etc.

I just want simplest but efficient approach to face this.

I read you, Thanks in advance.

答: Well, I found that a combination of RxBluetooth+Service to keep an event-based consistent reception, LiveData+ViewModel to keep the UI state and Room for persistence model is perfect for my requirements. </p>


问:
Dynamically hiding Xamarin Forms ListView item and setting the height of invisible item to 0 not working on iOS
In a Xamarin Forms ListView, a StackLayout is placed in a ViewCell. The following trigger is used to set the StackLayout's height and margin to 0 so that there is no gap in the ListView.

```<code><StackLayout.Triggers>
    <Trigger TargetType="StackLayout" Property="IsVisible" Value="False">
        <Setter Property="HeightRequest" Value="0" />
        <Setter Property="Margin" Value="0" />
    </Trigger>
</StackLayout.Triggers>
</code>```

The code works perfectly on Android. But there are still gaps on iOS.

Normally calling ViewCell.ForceUpdateSize on a tapping event can help resolve such an issue. But we need to do it grammatically. So I tried to create a CustomViewCell but it doesn't help.

```<code>public class CustomViewCell : ViewCell
{
    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();

        var viewModel = (tecommobile.ViewModels.Input)BindingContext;
        viewModel.PropertyChanged += (sender, e) =>
        {
            if (Device.RuntimePlatform == Device.iOS)
            {
                if (e.PropertyName == "IsVisible")
                {
                    //ForceUpdateSize(); crashes, the possible cause could be the height of the StackLayout is already set to 0. The test shows that the tapped event doesn't fire if the height is 0.
                }
            }
        };
    }
}
</code>```

Please advise a solution or any workaround. Thanks.

答:
We should use an TriggerAction to change this value, and tell the ViewCell to update its size.

```<code>public class ForceUpdateSizeTriggerAction : TriggerAction<VisualElement>
{
    public double HeighRequest { set; get; }  // you could set it as bindable property if you want to binding its value in runtime

    public Thickness CustomMargin { set; get; }

    public ForceUpdateSizeTriggerAction() : base()
    {

    }
    protected override void Invoke(VisualElement sender)
    {

        var parent = sender.Parent;
        while (parent != null && !(parent is ViewCell))
        {
            parent = parent.Parent;
        }
        if (parent is ViewCell cell)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                var view = sender as View;
                view.HeightRequest = HeighRequest;
                view.Margin = CustomMargin;
                cell.ForceUpdateSize();
            });
        }
    }
}
</code>```

in xaml

```<code><StackLayout.Style>
   <Style TargetType="StackLayout">
       <Setter Property="HeightRequest" Value="xxx"/> //default height
          <Style.Triggers>
            <DataTrigger TargetType="StackLayout" Binding="{Binding xxx}"  Value="False">  /// xxx here is the property which binding to the IsVisible of stacklayout
                   <DataTrigger.EnterActions>
                        <local:ForceUpdateSizeTriggerAction HeighRequest="0.01" CustomMargin="0"/>
                   </DataTrigger.EnterActions>

                   <DataTrigger.ExitActions>
                        <local:ForceUpdateSizeTriggerAction HeighRequest="xxx" CustomMargin="xxx"/> // set the default value of height and margin here
                   </DataTrigger.ExitActions>
          </DataTrigger>
       </Style.Triggers>
   </Style>
</StackLayout.Style>
</code>```

And don't forget to set HasUnevenRows="True" of listview.

Body:
In a Xamarin Forms ListView, a StackLayout is placed in a ViewCell. The following trigger is used to set the StackLayout's height and margin to 0 so that there is no gap in the ListView.

<StackLayout.Triggers>
    <Trigger TargetType="StackLayout" Property="IsVisible" Value="False">
        <Setter Property="HeightRequest" Value="0" />
        <Setter Property="Margin" Value="0" />
    </Trigger>
</StackLayout.Triggers>

The code works perfectly on Android. But there are still gaps on iOS.

Normally calling ViewCell.ForceUpdateSize on a tapping event can help resolve such an issue. But we need to do it grammatically. So I tried to create a CustomViewCell but it doesn't help.

public class CustomViewCell : ViewCell
{
    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();

        var viewModel = (tecommobile.ViewModels.Input)BindingContext;
        viewModel.PropertyChanged += (sender, e) =>
        {
            if (Device.RuntimePlatform == Device.iOS)
            {
                if (e.PropertyName == "IsVisible")
                {
                    //ForceUpdateSize(); crashes, the possible cause could be the height of the StackLayout is already set to 0. The test shows that the tapped event doesn't fire if the height is 0.
                }
            }
        };
    }
}

Please advise a solution or any workaround. Thanks.

Body:
We should use an TriggerAction to change this value, and tell the ViewCell to update its size.

public class ForceUpdateSizeTriggerAction : TriggerAction<VisualElement>
{
    public double HeighRequest { set; get; }  // you could set it as bindable property if you want to binding its value in runtime

    public Thickness CustomMargin { set; get; }

    public ForceUpdateSizeTriggerAction() : base()
    {

    }
    protected override void Invoke(VisualElement sender)
    {

        var parent = sender.Parent;
        while (parent != null && !(parent is ViewCell))
        {
            parent = parent.Parent;
        }
        if (parent is ViewCell cell)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                var view = sender as View;
                view.HeightRequest = HeighRequest;
                view.Margin = CustomMargin;
                cell.ForceUpdateSize();
            });
        }
    }
}

in xaml

<StackLayout.Style>
   <Style TargetType="StackLayout">
       <Setter Property="HeightRequest" Value="xxx"/> //default height
          <Style.Triggers>
            <DataTrigger TargetType="StackLayout" Binding="{Binding xxx}"  Value="False">  /// xxx here is the property which binding to the IsVisible of stacklayout
                   <DataTrigger.EnterActions>
                        <local:ForceUpdateSizeTriggerAction HeighRequest="0.01" CustomMargin="0"/>
                   </DataTrigger.EnterActions>

                   <DataTrigger.ExitActions>
                        <local:ForceUpdateSizeTriggerAction HeighRequest="xxx" CustomMargin="xxx"/> // set the default value of height and margin here
                   </DataTrigger.ExitActions>
          </DataTrigger>
       </Style.Triggers>
   </Style>
</StackLayout.Style>

And don't forget to set HasUnevenRows="True" of listview.


问:
Download EC2 instance contents with only aws login info and no pem key
I've been given access to an aws account and asked to extract all the data stored on it so that it can be deleted. My issue is that I don't have a pem key because I didn't create the instance, the only thing I have is the email and password of the aws account itself.

I know there is data stored on an ec2 instance and on s3

I've tried logging in using the browser-based ssh that is an option when you select connect for an instance, but I get the error There was a problem setting up the instance connection and a retry button but retrying does nothing

I don't have access to the pem key because I didn't set up the instance, and the person that set up the instance can't send it to me because I don't have their contact info

Everything I try to connect doesn't work because I'm missing the Pem key.

Any ideas? or any ideas how to pull the data from a server (that wasn't set up with version control so i can't do that either) without being able to ssh into it?

答:
If the data is stored on an EBS volume you can detach it from the existing instance and attach it to a new instance, for which you have the key. Otherwise I don't think you are going to be able to get it.

I'm a little confused by "the person that set up the instance can't add me to it." A PEM isn't something you have to be added to. If you have it you can use it. Is there a reason that person can't share it with you?


问:
How to refresh state when navigating back
I would like to be able to navigate to the previous page in my app but I don't want the page to keep it's previous state. How would I go about doing this?</p>

答:
You can use then in Navigator to call setState after return to the previous page:</p>

```<code>Navigator.push(context,MaterialPageRoute(builder: (context) =>NextPage())).then((_) {
  setState(() {});
});
</code>```

Body:
You can use then in Navigator to call setState after return to the previous page:

Navigator.push(context,MaterialPageRoute(builder: (context) =>NextPage())).then((_) {
  setState(() {});
});


问:
React Hooks / localStorage
Hello I am making a theme switch and I came across a following situation:

I have a key on localstorage where:

theme: dark or light

but if I change my key to something like red blue without quotes I get the following error:
×

Error: A cross-origin error was thrown

gif :

I don't know I could avoid this situation in some way

my code:

```<code>export default function useTheme(defaultTheme = lightTheme) {
  const [theme, _setTheme] = useState(getInitialTheme);

  function getInitialTheme() {
    const savedTheme = JSON.parse(localStorage.getItem('theme'));
    return savedTheme === 'dark' ? darkTheme : defaultTheme;
  }
  useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(theme.type));
  }, [theme]);

  return {
    ...theme,
    setTheme: ({ setTheme, ...theme }) => {
      if (theme.type === 'dark') {
        return _setTheme(darkTheme);
      } else {
        return _setTheme(lightTheme);
      }
    },
  };
}
</code>```

basically the problem is when I use JSON.parser

```<code>const savedTheme = JSON.parse(localStorage.getItem('theme'));
</code>```

答:
You are changing it from a string "dark" to just red. You need to use "red"

const retreivedTheme = localStorage.getItem('theme')
if (typeof retreivedTheme !== 'string') {
  // handle
  return
}
const savedTheme = JSON.parse(retreivedTheme);
return savedTheme === 'dark' ? darkTheme : defaultTheme;
```

<p>Or if you just want to default to <code>dark</code> lets say.</p>

<pre class="lang-js prettyprint-override"><code>const retreivedTheme = localStorage.getItem('theme')
const savedTheme = typeof retreivedTheme === 'string' ? JSON.parse(retreivedTheme) : "dark"
return savedTheme === 'dark' ? darkTheme : defaultTheme;
</code>```

However, the only time it will not be a string is if the user manual opens dev tools to change it to some malformed value. Which should probably result in an error to show them they should not be doing this.

Title: React Hooks / localStorage

Body:
Hello I am making a theme switch and I came across a following situation:

I have a key on localstorage where:

theme: dark or light

but if I change my key to something like red blue without quotes I get the following error:
×

Error: A cross-origin error was thrown

gif :

I don't know I could avoid this situation in some way

my code:

export default function useTheme(defaultTheme = lightTheme) {
  const [theme, _setTheme] = useState(getInitialTheme);

  function getInitialTheme() {
    const savedTheme = JSON.parse(localStorage.getItem('theme'));
    return savedTheme === 'dark' ? darkTheme : defaultTheme;
  }
  useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(theme.type));
  }, [theme]);

  return {
    ...theme,
    setTheme: ({ setTheme, ...theme }) => {
      if (theme.type === 'dark') {
        return _setTheme(darkTheme);
      } else {
        return _setTheme(lightTheme);
      }
    },
  };
}

basically the problem is when I use JSON.parser

const savedTheme = JSON.parse(localStorage.getItem('theme'));

Body:
You are changing it from a string "dark" to just red. You need to use "red"

const retreivedTheme = localStorage.getItem('theme')
if (typeof retreivedTheme !== 'string') {
  // handle
  return
}
const savedTheme = JSON.parse(retreivedTheme);
return savedTheme === 'dark' ? darkTheme : defaultTheme;

Or if you just want to default to dark lets say.

const retreivedTheme = localStorage.getItem('theme')
const savedTheme = typeof retreivedTheme === 'string' ? JSON.parse(retreivedTheme) : "dark"
return savedTheme === 'dark' ? darkTheme : defaultTheme;

However, the only time it will not be a string is if the user manual opens dev tools to change it to some malformed value. Which should probably result in an error to show them they should not be doing this.


问:
ImportError: Missing required dependencies ['numpy'] ONLY when running from .bat file
I am running Python 3.7 on an Anaconda distribution with Windows 10.

I have a script that runs without error in a Spyder ipython console. However, I need to run it from a .bat file.

I've replicated the error with the following Python code (just an import):

```<code>import pandas
</code>```

And the following .bat:

```<code>C:\Users\user\Anaconda3\python "L:\path\baterrorimporttest.py"
</code>```

I get the following error:

```<code>Traceback (most recent call last):
File "L:\path\baterrorimporttest.py", line 1, in <module>
import pandas
File "C:\Users\user\Anaconda3\lib\site-packages\pandas\__init__.py", line 19, in <module>
"Missing required dependencies {0}".format(missing_dependencies))
ImportError: Missing required dependencies ['numpy']
</code>```

I have no issues running this script, importing pandas, using numpy, etc. in my Spyder console.

Any tips?

答:
to me worked with this piece of code:</p>

```<code>call "C:\Anaconda\Scripts\activate.bat" "C:\Anaconda"
"C:\Anaconda\python.exe" "C:\Users\...\ml001.py"
pause
</code>```

Body:
I am running Python 3.7 on an Anaconda distribution with Windows 10.

I have a script that runs without error in a Spyder ipython console. However, I need to run it from a .bat file.

I've replicated the error with the following Python code (just an import):

import pandas

And the following .bat:

C:\Users\user\Anaconda3\python "L:\path\baterrorimporttest.py"

I get the following error:

Traceback (most recent call last):
File "L:\path\baterrorimporttest.py", line 1, in <module>
import pandas
File "C:\Users\user\Anaconda3\lib\site-packages\pandas\__init__.py", line 19, in <module>
"Missing required dependencies {0}".format(missing_dependencies))
ImportError: Missing required dependencies ['numpy']

I have no issues running this script, importing pandas, using numpy, etc. in my Spyder console.

Any tips?

Body:
to me worked with this piece of code:

call "C:\Anaconda\Scripts\activate.bat" "C:\Anaconda"
"C:\Anaconda\python.exe" "C:\Users\...\ml001.py"
pause


问:
Azure AD Graph API - Get Group Memberships in one shot
I am working on a project to audit security on the Azure platform. As such, it is necessary to iterate Azure AD Groups to ascertain direct and transitive Group membership. While there is a route for "get all Groups", there is no documented route for "get all direct members for all Groups". Rather, there seems to only be a single call, which is intended to get direct members of an individual group. Thus, this API must be called multiple times, once per Group.

Given that the AD Graph can mutate between API calls, is it even possible to obtain a temporally valid/consistent set of Group memberships for a given point in time? Even calling the API for every group, in parallel, will still leave the possibility of mutation open, albeit lessening the probability.

I am using this API route, where {{variableName}} represents a variable passed at runtime:

```<code>https://graph.windows.net/{{tenantId}}/groups/{{adGroupId}}/$links/members?api-version=1.6
</code>```

The documentation, such as it is, may be found here:
Operations on groups | Graph API reference

In order to obtain all group memberships, it seems necessary to call this API for every single AD Group. Based on this technique, if the AD Group memberships mutate during the calls to this API, it seems that it will not be feasible to obtain an accurate, reliable picture of Group membership for a given point in time across the entire Directory. Am I missing something?

答: You are right, we need to call this API for every single AD Group. The best solution is picking an appropriate time and calling the API for every group in parallel. We can not avoid the mutation even when we just call the single API. </p>

Body:
I am working on a project to audit security on the Azure platform. As such, it is necessary to iterate Azure AD Groups to ascertain direct and transitive Group membership. While there is a route for "get all Groups", there is no documented route for "get all direct members for all Groups". Rather, there seems to only be a single call, which is intended to get direct members of an individual group. Thus, this API must be called multiple times, once per Group.

Given that the AD Graph can mutate between API calls, is it even possible to obtain a temporally valid/consistent set of Group memberships for a given point in time? Even calling the API for every group, in parallel, will still leave the possibility of mutation open, albeit lessening the probability.

I am using this API route, where {{variableName}} represents a variable passed at runtime:

https://graph.windows.net/{{tenantId}}/groups/{{adGroupId}}/$links/members?api-version=1.6

The documentation, such as it is, may be found here:
Operations on groups | Graph API reference

In order to obtain all group memberships, it seems necessary to call this API for every single AD Group. Based on this technique, if the AD Group memberships mutate during the calls to this API, it seems that it will not be feasible to obtain an accurate, reliable picture of Group membership for a given point in time across the entire Directory. Am I missing something?


问:
How to find which module defines an annotation

From the IDE, or from the command line, how can I reverse-look up which module defines a particular annotation?

For example, in the attached screenshot, how can I check which dependency module contains the definition of @NotFound. (Of course, this is an example. Actual issue is when I'm reading a code that has 50 dependency at the top of the file and tons of various annotation being used). Is there an easy way find the actual module?

答: It looks like you are using IntelliJ IDEA. If so, you can search for text occurrences through the whole project or through specific module by using search everywhere feature. Press Ctrl+Shift+F to open the search window.


问:
How do you handle checks to see if a user changed something in a dialog
Talking .NET WinForms here:

If you have an application where someone can change items using some properties dialog for example, how do you determine if a user has changed something when he clicks on cancel (to decide whether to display a cancel confirmation message box, or not).

I can think of 2 methods:

Defining a dirty bit and handling all "changed" events to set this bit to true.

Clone the original object and write some comparison code to determine if the modified object really was modified compared with the original

Is there any more elegant and/or more generic way to do that?

答:
Both options are valid.

However consider the following: a user changes a value, and then changes it back to the original.

According to the dirty bit method it is changed. But according to the clone and compare method, it is not. So this method is prefered.

OwnerDisplayName: Stefan Koell

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Drew Noakes

OwnerDisplayName: Gamecat


问:
How to bypass python function definition with decorator?
I would like to know if its possible to control Python function definition based on global settings (e.g. OS). Example:

```<code>@linux
def my_callback(*args, **kwargs):
    print("Doing something @ Linux")
    return

@windows
def my_callback(*args, **kwargs):
    print("Doing something @ Windows")
    return
</code>```

Then, if someone is using Linux, the first definition of my_callback will be used and the second will be silently ignored.

Its not about determining the OS, its about function definition / decorators.

答:
I wrote my code before read other answers. After I finished my code, I found @Todd's code is the best answer.
Anyway I post my answer because I felt fun while I was solving this problem. I learned new things thanks to this good question.
The drawback of my code is that there exists overhead to retrieve dictionaries every time functions are called.</p>

```<code>from collections import defaultdict
import inspect
import os

class PlatformFunction(object):
    mod_funcs = defaultdict(dict)

    @classmethod
    def get_function(cls, mod, func_name):
        return cls.mod_funcs[mod][func_name]

    @classmethod
    def set_function(cls, mod, func_name, func):
        cls.mod_funcs[mod][func_name] = func

def linux(func):
    frame_info = inspect.stack()[1]
    mod = inspect.getmodule(frame_info.frame)
    if os.environ['OS'] == 'linux':
        PlatformFunction.set_function(mod, func.__name__, func)

    def call(*args, **kwargs):
        return PlatformFunction.get_function(mod, func.__name__)(*args,
                                                                 **kwargs)

    return call

def windows(func):
    frame_info = inspect.stack()[1]
    mod = inspect.getmodule(frame_info.frame)
    if os.environ['OS'] == 'windows':
        PlatformFunction.set_function(mod, func.__name__, func)

    def call(*args, **kwargs):
        return PlatformFunction.get_function(mod, func.__name__)(*args,
                                                                 **kwargs)

    return call

@linux
def myfunc(a, b):
    print('linux', a, b)

@windows
def myfunc(a, b):
    print('windows', a, b)

if __name__ == '__main__':
    myfunc(1, 2)
</code>```

Body:
I would like to know if its possible to control Python function definition based on global settings (e.g. OS). Example:

@linux
def my_callback(*args, **kwargs):
    print("Doing something @ Linux")
    return

@windows
def my_callback(*args, **kwargs):
    print("Doing something @ Windows")
    return

Then, if someone is using Linux, the first definition of my_callback will be used and the second will be silently ignored.

Its not about determining the OS, its about function definition / decorators.

Body:
I wrote my code before read other answers. After I finished my code, I found @Todd's code is the best answer.
Anyway I post my answer because I felt fun while I was solving this problem. I learned new things thanks to this good question.
The drawback of my code is that there exists overhead to retrieve dictionaries every time functions are called.

from collections import defaultdict
import inspect
import os

class PlatformFunction(object):
    mod_funcs = defaultdict(dict)

    @classmethod
    def get_function(cls, mod, func_name):
        return cls.mod_funcs[mod][func_name]

    @classmethod
    def set_function(cls, mod, func_name, func):
        cls.mod_funcs[mod][func_name] = func

def linux(func):
    frame_info = inspect.stack()[1]
    mod = inspect.getmodule(frame_info.frame)
    if os.environ['OS'] == 'linux':
        PlatformFunction.set_function(mod, func.__name__, func)

    def call(*args, **kwargs):
        return PlatformFunction.get_function(mod, func.__name__)(*args,
                                                                 **kwargs)

    return call

def windows(func):
    frame_info = inspect.stack()[1]
    mod = inspect.getmodule(frame_info.frame)
    if os.environ['OS'] == 'windows':
        PlatformFunction.set_function(mod, func.__name__, func)

    def call(*args, **kwargs):
        return PlatformFunction.get_function(mod, func.__name__)(*args,
                                                                 **kwargs)

    return call

@linux
def myfunc(a, b):
    print('linux', a, b)

@windows
def myfunc(a, b):
    print('windows', a, b)

if __name__ == '__main__':
    myfunc(1, 2)