问:
Identity Server 4 can't find Certificate when deployed to Azure AppService
I have an asp.net core hosted blazor wasm application. I used the default template with authentication via Identity Server 4. When I test it locally in Release Mode it works as expected. But when I deploy to Azure AppService I get this exception:

```<code>    2020-05-08 07:45:50.244 +00:00 [ERR] An unhandled exception has occurred while executing the request.
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The system cannot find the file specified.
   at System.Security.Cryptography.CngKey.Open(String keyName, CngProvider provider, CngKeyOpenOptions openOptions)
   at System.Security.Cryptography.CngKey.Open(String keyName, CngProvider provider)
   at Internal.Cryptography.Pal.CertificatePal.GetPrivateKey[T](Func`2 createCsp, Func`2 createCng)
   at Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()
   at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
   at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKey()
   at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKeyStatus()
   at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.FoundPrivateKey(SecurityKey key)
   at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures)
   at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures, CryptoProviderFactory cryptoProviderFactory)
   at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures)
   at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm)
   at Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(String input, SigningCredentials signingCredentials)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
   at IdentityServer4.Services.DefaultTokenCreationService.CreateJwtAsync(JwtSecurityToken jwt)
   at IdentityServer4.Services.DefaultTokenCreationService.CreateTokenAsync(Token token)
   at IdentityServer4.Services.DefaultTokenService.CreateSecurityTokenAsync(Token token)
   at IdentityServer4.ResponseHandling.TokenResponseGenerator.CreateAccessTokenAsync(ValidatedTokenRequest request)
   at IdentityServer4.ResponseHandling.TokenResponseGenerator.ProcessAuthorizationCodeRequestAsync(TokenRequestValidationResult request)
   at IdentityServer4.ResponseHandling.TokenResponseGenerator.ProcessAsync(TokenRequestValidationResult request)
   at IdentityServer4.Endpoints.TokenEndpoint.ProcessTokenRequestAsync(HttpContext context)
   at IdentityServer4.Endpoints.TokenEndpoint.ProcessAsync(HttpContext context)
   at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
   at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
   at IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
   at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
</code>```

In my appsettings I have this config:

```<code>  "IdentityServer": {
    "Clients": {
      "ApplySupportTool.Client": {
        "Profile": "IdentityServerSPA"
      }
    },
    "Key": {
      "Type": "File",
      "FilePath": "applysupporttool.pfx",
      "Password": "{Password}"
    }
  }
</code>```

And in my Startup.cs I have this in the ConfigureServices Method:

```<code>        services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, SupportToolContext>();

        services.AddAuthentication()
            .AddIdentityServerJwt();
</code>```

And this in the Configure Method:

```<code>        app.UseIdentityServer();
        app.UseAuthentication();
        app.UseAuthorization();
</code>```

Which I made according to the asp.net core blazor wasm template with individual auth.

The passwod are correctly filled on Azure itself. What is different on Azure than on my System?

答:
I ran into this when setting up IdentityServer on AWS ElasticBeanstalk infrastructure. I found that the app pools on the EC2 instances did not have Load User Profile set true. When set, the permissions model changes and allows the process to load in the cert. You can enable through the IIS management UI on the app pool details, or use a version of the script below. </p>

```<code>Import-Module WebAdministration
Set-ItemProperty "IIS:\AppPools\DefaultAppPool" -Name "processModel.loadUserProfile" -Value "True"
</code>```

Body:
I have an asp.net core hosted blazor wasm application. I used the default template with authentication via Identity Server 4. When I test it locally in Release Mode it works as expected. But when I deploy to Azure AppService I get this exception:

    2020-05-08 07:45:50.244 +00:00 [ERR] An unhandled exception has occurred while executing the request.
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The system cannot find the file specified.
   at System.Security.Cryptography.CngKey.Open(String keyName, CngProvider provider, CngKeyOpenOptions openOptions)
   at System.Security.Cryptography.CngKey.Open(String keyName, CngProvider provider)
   at Internal.Cryptography.Pal.CertificatePal.GetPrivateKey[T](Func`2 createCsp, Func`2 createCng)
   at Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()
   at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
   at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKey()
   at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKeyStatus()
   at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.FoundPrivateKey(SecurityKey key)
   at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures)
   at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures, CryptoProviderFactory cryptoProviderFactory)
   at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures)
   at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm)
   at Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(String input, SigningCredentials signingCredentials)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
   at IdentityServer4.Services.DefaultTokenCreationService.CreateJwtAsync(JwtSecurityToken jwt)
   at IdentityServer4.Services.DefaultTokenCreationService.CreateTokenAsync(Token token)
   at IdentityServer4.Services.DefaultTokenService.CreateSecurityTokenAsync(Token token)
   at IdentityServer4.ResponseHandling.TokenResponseGenerator.CreateAccessTokenAsync(ValidatedTokenRequest request)
   at IdentityServer4.ResponseHandling.TokenResponseGenerator.ProcessAuthorizationCodeRequestAsync(TokenRequestValidationResult request)
   at IdentityServer4.ResponseHandling.TokenResponseGenerator.ProcessAsync(TokenRequestValidationResult request)
   at IdentityServer4.Endpoints.TokenEndpoint.ProcessTokenRequestAsync(HttpContext context)
   at IdentityServer4.Endpoints.TokenEndpoint.ProcessAsync(HttpContext context)
   at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
   at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
   at IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
   at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)

In my appsettings I have this config:

  "IdentityServer": {
    "Clients": {
      "ApplySupportTool.Client": {
        "Profile": "IdentityServerSPA"
      }
    },
    "Key": {
      "Type": "File",
      "FilePath": "applysupporttool.pfx",
      "Password": "{Password}"
    }
  }

And in my Startup.cs I have this in the ConfigureServices Method:

        services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, SupportToolContext>();

        services.AddAuthentication()
            .AddIdentityServerJwt();

And this in the Configure Method:

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

Which I made according to the asp.net core blazor wasm template with individual auth.

The passwod are correctly filled on Azure itself. What is different on Azure than on my System?

Body:
I ran into this when setting up IdentityServer on AWS ElasticBeanstalk infrastructure. I found that the app pools on the EC2 instances did not have Load User Profile set true. When set, the permissions model changes and allows the process to load in the cert. You can enable through the IIS management UI on the app pool details, or use a version of the script below.

Import-Module WebAdministration
Set-ItemProperty "IIS:\AppPools\DefaultAppPool" -Name "processModel.loadUserProfile" -Value "True"


来源: stackexchange

问:
How can I get correct/expected opacity to apply to elements that are displayed using $().fadeIn() in IE8?
I have a weird CSS/jQuery gotcha that I can't figure out.

I have three forms on my page, but only one can be displayed at a time, so I hide all them by default using CSS

```<code>form fieldset {
    display: none;
}
</code>```

I then display them dynamically using jQuery method fadeIn().

However, when I call the fadeIn() method on the each fieldset, the CSS rules for the label fonts are not being applied in IE8. IE Developer Tools says that font-family is Verdana, Arial, sans-serif, but the labels are all displayed with Arial.

CSS:

```<code>label {
    font-family: Verdana, Arial, sans-serif;
    font-size: 12px
    font-weight: bold;
}
</code>```

HTML:

```<code><label for="State">
    State *:
</label>
</code>```

答:
Ok. Here's the best solution I could come up with:</p>

```<code>$(this).fadeTo(350, 1, function(){
        $(this).removeAttr("style").css("display", "block");
        myHide($addressFormFieldSet);
        myHide($uploadFormFieldSet);
    });
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a weird CSS/jQuery gotcha that I can't figure out.

I have three forms on my page, but only one can be displayed at a time, so I hide all them by default using CSS

form fieldset {
    display: none;
}

I then display them dynamically using jQuery method fadeIn().

However, when I call the fadeIn() method on the each fieldset, the CSS rules for the label fonts are not being applied in IE8. IE Developer Tools says that font-family is Verdana, Arial, sans-serif, but the labels are all displayed with Arial.

CSS:

label {
    font-family: Verdana, Arial, sans-serif;
    font-size: 12px
    font-weight: bold;
}

HTML:

    State *:

Body:
Ok. Here's the best solution I could come up with:

$(this).fadeTo(350, 1, function(){
        $(this).removeAttr("style").css("display", "block");
        myHide($addressFormFieldSet);
        myHide($uploadFormFieldSet);
    });
}


问:
Heroku log - error H10 while deploying dashboard
I follow the instruction from this article, but my code give me the error:

```<code>at=error code=H10 desc="App crashed" method=GET path="/" host=peaceful-woodland-02831.herokuapp.com request_id=0c26d197-66d8-4c20-9a1d-f6357d771aee fwd="81.5.122.217" dyno= connect= service= status=503 bytes= protocol=https

2020-05-28T17:30:24.573582+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=peaceful-woodland-02831.herokuapp.com request_id=877a92c7-573b-4d35-90ff-338bbab28fba fwd="81.5.122.217" dyno= connect= service= status=503 bytes= protocol=https
</code>```

I found that problem could be in Procfile but no changes help and I had even tried to copy all code and files from the article Git. But still have the same issue.

I also have in heroku logs this:

```<code>2020-05-28T17:30:14.228953+00:00 app[web.1]: __import__(module)
2020-05-28T17:30:14.228999+00:00 app[web.1]: ModuleNotFoundError: No module named 'app'
</code>```

But didn`t cope with the debugging.

Locally both codes work perfect. Any idea how I can fix it?

答: In some mysterious way me helpped reboot of PC. I hope it will help for someone in future.</p>

ContentLicense: CC BY-SA 4.0

Body:
I follow the instruction from this article, but my code give me the error:

at=error code=H10 desc="App crashed" method=GET path="/" host=peaceful-woodland-02831.herokuapp.com request_id=0c26d197-66d8-4c20-9a1d-f6357d771aee fwd="81.5.122.217" dyno= connect= service= status=503 bytes= protocol=https

2020-05-28T17:30:24.573582+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=peaceful-woodland-02831.herokuapp.com request_id=877a92c7-573b-4d35-90ff-338bbab28fba fwd="81.5.122.217" dyno= connect= service= status=503 bytes= protocol=https

I found that problem could be in Procfile but no changes help and I had even tried to copy all code and files from the article Git. But still have the same issue.

I also have in heroku logs this:

2020-05-28T17:30:14.228953+00:00 app[web.1]: __import__(module)
2020-05-28T17:30:14.228999+00:00 app[web.1]: ModuleNotFoundError: No module named 'app'

But didn`t cope with the debugging.

Locally both codes work perfect. Any idea how I can fix it?


问:
What overheads on server-side are there when signing Git commits?
Git provides a way to sign commits using GPG keys. What additional overheads are involved on the git server-side (e.g. GitHub Enterprise, GitLab Self-Managed, etc.) compared to the same commit without signing?

How much more storage is needed per commit? Is it only the GPG key ID that is stored additionally? Or is something else also being stored.

How much more processing is needed per commit? Does git need to perform some resource intensive operation to verify the commits? Or only the GPG key ID is checked?

How much more data is sent over the network when pushing the commits? Only the GPG key ID or something more?

To be a little more concrete, between these examples, how much more overhead is incurred on the server-side?

Example 1 - with signing

git add example.txt
git commit -S -m 'My Commit'
git push
```

<p>Example 2 - without signing</p>

<pre class="lang-sh prettyprint-override"><code>git add example.txt
git commit -m 'My Commit'
git push
</code>```

example.txt (Not sure if this matters though)

```<code>Hello World!
</code>```

答:
The way signatures are stored in commits is as a header in a commit, and for a standard RSA OpenPGP key, the additional size is about 890 bytes before compression, which is minimal.  Ed25519 signatures are smaller, about 275 bytes.  The data is compressed in the actual commit object.  This data is also pushed over the network.

The hosting platform must also store the actual key to verify the signature, and the cost there is also negligible.  Keys are usually stored stripped of irrelevant signatures, and the size of a key is usually on the order of a couple kilobytes or less.

The cost to verify signatures is usually pretty minimal as well.  I have seen the CPU cost of actually verifying an Ed25519 signature to be about 120 ms of CPU time, and RSA is more efficient than that for verification.  The difference is again rather negligible, and Ed25519 is a better, more secure choice for keys all things considered.

The check that typically happens, at least on GitHub, is that the signature and all of the user's keys are sent over the connection to the verification service, which does the verification.  Because the signature contains the key fingerprint or key ID in almost all cases, it's trivial to determine which is the right key and check only that key for the signature.

Certainly if you have a large number of signatures there is some performance impact, but overall it is relatively small.  Cryptography these days is very fast, so if you'd like to sign commits for whatever reason, the performance impact is minimal, and you should feel confident in doing so.  I recommend using Ed25519 keys if you're creating new ones and using a reasonably recent version of GnuPG.

Body:
Git provides a way to sign commits using GPG keys. What additional overheads are involved on the git server-side (e.g. GitHub Enterprise, GitLab Self-Managed, etc.) compared to the same commit without signing?

How much more storage is needed per commit? Is it only the GPG key ID that is stored additionally? Or is something else also being stored.

How much more processing is needed per commit? Does git need to perform some resource intensive operation to verify the commits? Or only the GPG key ID is checked?

How much more data is sent over the network when pushing the commits? Only the GPG key ID or something more?

To be a little more concrete, between these examples, how much more overhead is incurred on the server-side?

Example 1 - with signing

git add example.txt
git commit -S -m 'My Commit'
git push

Example 2 - without signing

git add example.txt
git commit -m 'My Commit'
git push

example.txt (Not sure if this matters though)

Hello World!


问:
Is there any hack to close the current tab in an Angular yet with a button clicked?
I have a method onExit() and trying to close the browser's current tab/exit from the application. I have tried with this code component.ts

```<code>onExit() {
    console.log("closing the web!");

    window.close();
  }
</code>```

and compoent.html

```<code><button type="button" id="F1" class="btn btn-secondary" (click)="onExit()">Exit (F1)</button>
</code>```

But getting the console warning says "Scripts may close only the windows that were opened by it."

If anyone knows the solution would be great.

Thanks.

答: No that is not possible due to security reasons.</p>

Body:
I have a method onExit() and trying to close the browser's current tab/exit from the application. I have tried with this code component.ts

onExit() {
    console.log("closing the web!");

    window.close();
  }

and compoent.html

<button type="button" id="F1" class="btn btn-secondary" (click)="onExit()">Exit (F1)</button>

But getting the console warning says "Scripts may close only the windows that were opened by it."

If anyone knows the solution would be great.

Thanks.


问:
Statement stmt problems netbeans
I'am working on this source code :

```<code>public class AuthentificationClient extends javax.swing.JFrame {

  connexion maconn;
  Statement stmt1;

    public AuthentificationClient() {
        initComponents();
    }

    private void numcompteActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        Bienvenue ret = new  Bienvenue  () ;
        ret.setVisible(true);
        this.dispose();
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        String requete ="Select * from Compte where numcompte='"+numcompte.getText()+"' and codec = '"+Arrays.toString(code.getPassword())+"'";
        try {
            Statement stmt1 = maconn.Obtenirconnexion().createStatement();
            ResultSet rs= stmt1.executeQuery(requete);
        } catch (SQLException ex) {
            Logger.getLogger(AuthentificationPharmacien.class.getName()).log(Level.SEVERE, null, ex);
        }
        OpClient oc = new  OpClient  () ;
        oc.setVisible(true);
        this.dispose();
    }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AuthentificationClient().setVisible(true);
            }
        });
    }
</code>```

There is no error but when I execute, it doesn't work correctly! This is the error message that I receive :

答:
Use PreparedStatement instead of Statement to avoid SQL Injection attack as well to simplify your code e.g. you won't need to enclose string literals within ' ' when you use PreparedStatement.

Perform null check on an object (e.g. maconn) before accessing any member (method/variable) using it.

Do it as follows:

```<code>String requete ="Select * from Compte where numcompte = ? and codec = ?";
PreparedStatement pstmt;
ResultSet rs;
try {
    if(maconn!=null && maconn.Obtenirconnexion()!=null) {
        pstmt = maconn.Obtenirconnexion().prepareStatement(requete);
        pstmt.setString(1, numcompte.getText());
        pstmt.setString(2, Arrays.toString(code.getPassword()));
        rs = pstmt.executeQuery(requete);
        //...
    }
}
</code>```

Title: Statement stmt problems netbeans

Body:
I'am working on this source code :

public class AuthentificationClient extends javax.swing.JFrame {

  connexion maconn;
  Statement stmt1;

    public AuthentificationClient() {
        initComponents();
    }

    private void numcompteActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        Bienvenue ret = new  Bienvenue  () ;
        ret.setVisible(true);
        this.dispose();
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        String requete ="Select * from Compte where numcompte='"+numcompte.getText()+"' and codec = '"+Arrays.toString(code.getPassword())+"'";
        try {
            Statement stmt1 = maconn.Obtenirconnexion().createStatement();
            ResultSet rs= stmt1.executeQuery(requete);
        } catch (SQLException ex) {
            Logger.getLogger(AuthentificationPharmacien.class.getName()).log(Level.SEVERE, null, ex);
        }
        OpClient oc = new  OpClient  () ;
        oc.setVisible(true);
        this.dispose();
    }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AuthentificationClient().setVisible(true);
            }
        });
    }

There is no error but when I execute, it doesn't work correctly! This is the error message that I receive :

Body:
Use PreparedStatement instead of Statement to avoid SQL Injection attack as well to simplify your code e.g. you won't need to enclose string literals within ' ' when you use PreparedStatement.

Perform null check on an object (e.g. maconn) before accessing any member (method/variable) using it.

Do it as follows:

String requete ="Select * from Compte where numcompte = ? and codec = ?";
PreparedStatement pstmt;
ResultSet rs;
try {
    if(maconn!=null && maconn.Obtenirconnexion()!=null) {
        pstmt = maconn.Obtenirconnexion().prepareStatement(requete);
        pstmt.setString(1, numcompte.getText());
        pstmt.setString(2, Arrays.toString(code.getPassword()));
        rs = pstmt.executeQuery(requete);
        //...
    }
}


问:
Android Room : Return Rows by custom date i.e -7day etc
I have overhauled my room database from String Dates to Date which is stored as a Long using type converters. I am unable to filter my results for specific times like -7 days or 3 months etc. Here is my configuration:

QUERY

```<code> SELECT *
 FROM moodBeforetable
 WHERE moodBeforetable.workoutDate >= datetime('now', '-1 year')
 ORDER BY moodBeforetable.workoutDate DESC
 LiveData<List<WorkoutLogsAllPojo>> getAllMoodLogs();
</code>```

The query works fine when the WHERE clause is commented out, however if I include that line above no data is returned.

This moodBeforetable.workoutDate variable is a DATE but its stored in the database as Long :1590705660000

Type Converter

```<code>    @TypeConverter
    public static Date toDate(Long timestamp){
    return timestamp == null ? null : new Date(timestamp);
    }

    @TypeConverter
    public static Long toTimestamp(Date date){
    return date == null ? null : date.getTime();
    }
</code>```

Any assistance on the root cause of why the WHERE clause is not returning any data or the specified amount of rows would be greatly appreciated.

答: Function datetime('now', '-1 year') returns timestamp as '%Y-%m-%d %H:%M:%S', for example 2019-05-28 23:29:42 (docs). To get the number of milliseconds since epoch, use 1000 * strftime('%s', datetime('now', '-1 year')) instead.

Body:
I have overhauled my room database from String Dates to Date which is stored as a Long using type converters. I am unable to filter my results for specific times like -7 days or 3 months etc. Here is my configuration:

QUERY

 SELECT *
 FROM moodBeforetable
 WHERE moodBeforetable.workoutDate >= datetime('now', '-1 year')
 ORDER BY moodBeforetable.workoutDate DESC
 LiveData<List<WorkoutLogsAllPojo>> getAllMoodLogs();

The query works fine when the WHERE clause is commented out, however if I include that line above no data is returned.

This moodBeforetable.workoutDate variable is a DATE but its stored in the database as Long :1590705660000

Type Converter

    @TypeConverter
    public static Date toDate(Long timestamp){
    return timestamp == null ? null : new Date(timestamp);
    }

    @TypeConverter
    public static Long toTimestamp(Date date){
    return date == null ? null : date.getTime();
    }

Any assistance on the root cause of why the WHERE clause is not returning any data or the specified amount of rows would be greatly appreciated.


问:
Grouping object entries into object arrays
How can I create arrays to group members depending on their tag?

Tags can be anything, these are just examples.

Example Input

[
  { tag: 'Red', member: 'Red-Steve' },
  { tag: 'Red', member: 'Red-Adam' },
  { tag: 'Blue', member: 'Blue-John' },
  { tag: 'Blue', member: 'Blue-James' },
  { tag: 'Blue', member: 'Blue-Igor' }
]
```

<p>Example Output</p>

<pre class="lang-js prettyprint-override"><code>{
  Red: ['Red-Steve', 'Red-Adam']
  Blue: ['Blue-John', 'Blue-James', 'Blue-Igor']
}
</code>```

Edit: I just made a test case on jsperf to compare the efficiency of the different answers and also the answer from the suggested duplicate question
https://jsperf.com/group-objects-reduce-vs-for-loop

The answer by @Majed Badawi was the most efficient

答:
You can use a simple set to group them by tag as follows:

let list = [
            { tag: 'Red', member: 'Red-Steve' },
            { tag: 'Red', member: 'Red-Adam' },
            { tag: 'Blue', member: 'Blue-John' },
            { tag: 'Blue', member: 'Blue-James' },
            { tag: 'Blue', member: 'Blue-Igor' }
];
let set = {};
for(let i = 0; i < list.length; i++){
     let current = list[i];
     if(!set[current.tag])
          set[current.tag] = [current.member];
     else
          set[current.tag].push(current.member);
}
console.log(set);```

Body:
How can I create arrays to group members depending on their tag?

Tags can be anything, these are just examples.

Example Input

[
  { tag: 'Red', member: 'Red-Steve' },
  { tag: 'Red', member: 'Red-Adam' },
  { tag: 'Blue', member: 'Blue-John' },
  { tag: 'Blue', member: 'Blue-James' },
  { tag: 'Blue', member: 'Blue-Igor' }
]

Example Output

{
  Red: ['Red-Steve', 'Red-Adam']
  Blue: ['Blue-John', 'Blue-James', 'Blue-Igor']
}

Edit: I just made a test case on jsperf to compare the efficiency of the different answers and also the answer from the suggested duplicate question
https://jsperf.com/group-objects-reduce-vs-for-loop

The answer by @Majed Badawi was the most efficient


问:
Can I change the image file of an existing Evas_Object?

I am developing a watch face with Tizen Native using the EFL libraries. After creating many objects with:

Evas_Object *view_create_parts(Evas_Object *parent, const char *image_path,
    int position_x, int position_y, int size_w, int size_h) {
    Evas_Object *parts = NULL;

    parts = elm_image_add(parent);

    elm_image_file_set(parts, image_path, NULL);

    evas_object_move(parts, position_x, position_y);
    evas_object_resize(parts, size_w, size_h);

    evas_object_show(parts);

    return parts;
}
```

I would like to change the image of some of the existing objects later on as needed. Is this possible? I know that I could also load all possible variants as individual objects and show/hide the objects accordingly. But I find it way simpler and elegant to just change the image of an existing object. Plus, this probably uses less resources too.

I tried to do this:

elm_image_file_set(<part_I_want_to_change_its_image>, "images/newimage.png", NULL));

But instead of changing to the correct image, the object just disappears. Any ideas?

答:
Yes, elm_image supports image conversion.
But the normal image is included in the container widget or works as an area of the layout, but in your example, it seems to be an isolated and drawn image on the canvas.

In this case, if the image file is changed, the old geometry is meaningless, so you need to set a new geometry value. do the below action after elm_image_file_set called.

```<code>evas_object_move(parts, position_x, position_y);
evas_object_resize(parts, size_w, size_h);
</code>```

Body:
I am developing a watch face with Tizen Native using the EFL libraries. After creating many objects with:

Evas_Object *view_create_parts(Evas_Object *parent, const char *image_path,
    int position_x, int position_y, int size_w, int size_h) {
    Evas_Object *parts = NULL;

    parts = elm_image_add(parent);

    elm_image_file_set(parts, image_path, NULL);

    evas_object_move(parts, position_x, position_y);
    evas_object_resize(parts, size_w, size_h);

    evas_object_show(parts);

    return parts;
}

I would like to change the image of some of the existing objects later on as needed. Is this possible? I know that I could also load all possible variants as individual objects and show/hide the objects accordingly. But I find it way simpler and elegant to just change the image of an existing object. Plus, this probably uses less resources too.

I tried to do this:

elm_image_file_set(<part_I_want_to_change_its_image>, "images/newimage.png", NULL));

But instead of changing to the correct image, the object just disappears. Any ideas?

Body:
Yes, elm_image supports image conversion.
But the normal image is included in the container widget or works as an area of the layout, but in your example, it seems to be an isolated and drawn image on the canvas.

In this case, if the image file is changed, the old geometry is meaningless, so you need to set a new geometry value. do the below action after elm_image_file_set called.

evas_object_move(parts, position_x, position_y);
evas_object_resize(parts, size_w, size_h);


问:
Expose C# classes in .net 4 class library to Silverlight App
I have a bunch of classes in a C# class library that I bought from a 3rd party company.

I want to use these classes and create my classes by inheriting them.
I have it all working on a .net 4 wpf application.

I want to then use these classes in my silverlight application.

What options do I have and which is the best option?
I want to use it in such a way that I can update the 3rd party company's DLL as they release their new version every month.

Just to re-inforce few points:

We have few options.
1. Link the classes (as an adding existing item but with a link)
2. Create interfaces and share them amongst WCF as a link class and let all classes inherit the interface
3. Use RIA service and let the web app create auto code to expose it to silverlight.

Are there other options? and if not then which one is better for the scenario that I am facing?

Thanks

答:
It's worth noting however that the .NET platform shipping with Silverlight is not the same as the one shipping with the full .NET Framework.

It means that there is little chance that the third party assembly will be compatible with Silverlight, even if SL uses the same IL. If the third party assembly only references mscorlib or System.dll, it could be compiled as a cross platform assembly between SL and WPF.

However, in all the other cases, the differences between the SL and full .NET platform will prevent the assembly from being compatible with Silverlight.

If the third party software has anything to do with UI or network, if the software uses Windows API... etc.. it won't work in a Silverlight App.

This is the reason why a general .NET assembly can't be referenced from a SL project. However, there are cases when a SL assembly can be used in an general .NET project.

If the assembly perform computational and asynchronous task however, you could execute it on the server, and send back the result to the Silverlight app.

For instance it's a great option if the class Library generates reports, files or images.

What does the third party library do?


问:
IdentityServer4, WindowsCryptographicException: The system cannot find the file specified
I create an IdentityServer4 project with several client apps. I use a self-signed certificate file my_certificate.pfx to generate login token. It works fine on localhost.

However, it does not work when employing it to a shared web hosting server.

The app that hosts the IdentityServer4 works fine, indicating that the server app can access the certificate file. However, it generates the following error when trying to log in from a client app:

```<code>WindowsCryptographicException: The system cannot find the file specified.
System.Security.Cryptography.CngKey.Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
System.Security.Cryptography.CngKey.Open(string keyName, CngProvider provider)
Internal.Cryptography.Pal.CertificatePal.GetPrivateKey<T>(Func<CspParameters, T> createCsp, Func<CngKey, T> createCng)
Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()
System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKey()
Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKeyStatus()
Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.FoundPrivateKey(SecurityKey key)
Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, string algorithm, bool willCreateSignatures)
Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, string algorithm, bool willCreateSignatures, CryptoProviderFactory cryptoProviderFactory)
Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, string algorithm, bool willCreateSignatures)
Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, string algorithm)
Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(string input, SigningCredentials signingCredentials)
System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
IdentityServer4.Services.DefaultTokenCreationService.CreateJwtAsync(JwtSecurityToken jwt)
IdentityServer4.Services.DefaultTokenCreationService.CreateTokenAsync(Token token)
IdentityServer4.Services.DefaultTokenService.CreateSecurityTokenAsync(Token token)
IdentityServer4.ResponseHandling.AuthorizeResponseGenerator.CreateImplicitFlowResponseAsync(ValidatedAuthorizeRequest request, string authorizationCode)
IdentityServer4.ResponseHandling.AuthorizeResponseGenerator.CreateHybridFlowResponseAsync(ValidatedAuthorizeRequest request)
IdentityServer4.ResponseHandling.AuthorizeResponseGenerator.CreateResponseAsync(ValidatedAuthorizeRequest request)
IdentityServer4.Endpoints.AuthorizeEndpointBase.ProcessAuthorizeRequestAsync(NameValueCollection parameters, ClaimsPrincipal user, ConsentResponse consent)
IdentityServer4.Endpoints.AuthorizeEndpoint.ProcessAsync(HttpContext context)
IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(HttpContext context)
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
</code>```

How to make the client app works?

Thanks

答:
I ran into this when setting up IdentityServer on AWS ElasticBeanstalk infrastructure and using a local file, rather than the certificate store - however the solution in my case is the same. I found that the app pools on the EC2 instances did not have Load User Profile set true. When set, the permissions model changes and allows the process to load in the cert. You can enable through the IIS management UI on the app pool details, or use a version of the script below. </p>

```<code>Import-Module WebAdministration
Set-ItemProperty "IIS:\AppPools\DefaultAppPool" -Name "processModel.loadUserProfile" -Value "True"
</code>```

Body:
I create an IdentityServer4 project with several client apps. I use a self-signed certificate file my_certificate.pfx to generate login token. It works fine on localhost.

However, it does not work when employing it to a shared web hosting server.

The app that hosts the IdentityServer4 works fine, indicating that the server app can access the certificate file. However, it generates the following error when trying to log in from a client app:

WindowsCryptographicException: The system cannot find the file specified.
System.Security.Cryptography.CngKey.Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
System.Security.Cryptography.CngKey.Open(string keyName, CngProvider provider)
Internal.Cryptography.Pal.CertificatePal.GetPrivateKey<T>(Func<CspParameters, T> createCsp, Func<CngKey, T> createCng)
Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()
System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKey()
Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKeyStatus()
Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.FoundPrivateKey(SecurityKey key)
Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, string algorithm, bool willCreateSignatures)
Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, string algorithm, bool willCreateSignatures, CryptoProviderFactory cryptoProviderFactory)
Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, string algorithm, bool willCreateSignatures)
Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, string algorithm)
Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(string input, SigningCredentials signingCredentials)
System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
IdentityServer4.Services.DefaultTokenCreationService.CreateJwtAsync(JwtSecurityToken jwt)
IdentityServer4.Services.DefaultTokenCreationService.CreateTokenAsync(Token token)
IdentityServer4.Services.DefaultTokenService.CreateSecurityTokenAsync(Token token)
IdentityServer4.ResponseHandling.AuthorizeResponseGenerator.CreateImplicitFlowResponseAsync(ValidatedAuthorizeRequest request, string authorizationCode)
IdentityServer4.ResponseHandling.AuthorizeResponseGenerator.CreateHybridFlowResponseAsync(ValidatedAuthorizeRequest request)
IdentityServer4.ResponseHandling.AuthorizeResponseGenerator.CreateResponseAsync(ValidatedAuthorizeRequest request)
IdentityServer4.Endpoints.AuthorizeEndpointBase.ProcessAuthorizeRequestAsync(NameValueCollection parameters, ClaimsPrincipal user, ConsentResponse consent)
IdentityServer4.Endpoints.AuthorizeEndpoint.ProcessAsync(HttpContext context)
IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(HttpContext context)
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

How to make the client app works?

Thanks

Body:
I ran into this when setting up IdentityServer on AWS ElasticBeanstalk infrastructure and using a local file, rather than the certificate store - however the solution in my case is the same. I found that the app pools on the EC2 instances did not have Load User Profile set true. When set, the permissions model changes and allows the process to load in the cert. You can enable through the IIS management UI on the app pool details, or use a version of the script below.

Import-Module WebAdministration
Set-ItemProperty "IIS:\AppPools\DefaultAppPool" -Name "processModel.loadUserProfile" -Value "True"


问:
BLE Health Thermometer Characteristic 2A1C Notification value decoding - React Native
I m using a BLE simulator app that simulates BLE Digital Thermometer standards - connected to my React Native App running on another device. I subscribe to notifications for the temperature measurement characteristic. After I get a notification after the set interval, the received_data.value is in the form byteArray example: [0, 0, 0, 12, 132] - for temperature reading of 35.

I m not sure how to transfer the byteArray [0, 0, 0, 12, 132] into 35 on my react native app? Any ideas on how to use JS/React-Native to solve this and temperature reading.

答:
[https://www.npmjs.com/package/convert-string][convert-string] is what you're looking </p>

```<code>import { bytesToString } from 'convert-string';
import { NativeModules, NativeEventEmitter } from 'react-native';

bleManagerEmitter.addListener(
    'BleManagerDidUpdateValueForCharacteristic',
    ({ value, peripheral, characteristic, service }) => {
        // Convert bytes array to string
        const data = bytesToString(value);
        console.log(`Recieved ${data} for characteristic ${characteristic}`);
    }
  );
</code>```

Body:
[https://www.npmjs.com/package/convert-string][convert-string] is what you're looking

import { bytesToString } from 'convert-string';
import { NativeModules, NativeEventEmitter } from 'react-native';

bleManagerEmitter.addListener(
    'BleManagerDidUpdateValueForCharacteristic',
    ({ value, peripheral, characteristic, service }) => {
        // Convert bytes array to string
        const data = bytesToString(value);
        console.log(`Recieved ${data} for characteristic ${characteristic}`);
    }
  );


问:
MaterialUI show an other view after onclick event
I'm completely new in MaterialUI. I'm working on my first project right now and trying to make use of templates form its page. I've loaded two .tsx files with log in view and main dashboard view. I'd like to show main dashboard view after clicking Login button on log in view. Both files have its own export default function FnName() function with   const classes = useStyles(); and it seems to cause my problems. The way of using hooks is the issue here I guess. But how to pass this function to onClick handler event button? You can see my project here:

https://codesandbox.io/s/adoring-leftpad-6nwv2?file=/src/SignIn.tsx

Somebody can help?

答:
Please check this example:

App Component

```<code>import React, {useEffect, useState} from 'react';
import SignIn from "./material-ui/signin-template/SignIn";
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";
import { createBrowserHistory as history} from 'history';
import MiniDrawer from "./material-ui/signin-template/Dashboard";

class App extends React.Component {
    render() {
        return (
            <div>
                <Router history={history}>
                    <Switch>
                        <Route path="/" exact component={SignIn}/>
                        <Route path="/dashboard" component={MiniDrawer}/>
                    </Switch>
                </Router>
            </div>
        )
    }
}
export default App;
</code>```

SingIn Component

```<code>import React from "react";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
import CssBaseline from "@material-ui/core/CssBaseline";
import TextField from "@material-ui/core/TextField";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Checkbox from "@material-ui/core/Checkbox";
import Link from "@material-ui/core/Link";
import Grid from "@material-ui/core/Grid";
import Box from "@material-ui/core/Box";
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
import Typography from "@material-ui/core/Typography";
import {makeStyles} from "@material-ui/core/styles";
import Container from "@material-ui/core/Container";
import {Redirect, useHistory} from "react-router-dom";

function Copyright() {
    return (
        <Typography variant="body2" color="textSecondary" align="center">
            {"Copyright © "}
            <Link color="inherit" href="https://material-ui.com/">
                Your Website
            </Link>{" "}
            {new Date().getFullYear()}
            {"."}
        </Typography>
    );
}

const useStyles = makeStyles(theme => ({
    paper: {
        marginTop: theme.spacing(8),
        display: "flex",
        flexDirection: "column",
        alignItems: "center"
    },
    avatar: {
        margin: theme.spacing(1),
        backgroundColor: theme.palette.secondary.main
    },
    form: {
        width: "100%", // Fix IE 11 issue.
        marginTop: theme.spacing(1)
    },
    submit: {
        margin: theme.spacing(3, 0, 2)
    }
}));

export default function SignIn() {
    const classes = useStyles();
    let history = useHistory();

    return (
        <Container component="main" maxWidth="xs">
            <CssBaseline/>
            <div className={classes.paper}>
                <Avatar className={classes.avatar}>
                    <LockOutlinedIcon/>
                </Avatar>
                <Typography component="h1" variant="h5">
                    Sign in
                </Typography>
                <form className={classes.form} noValidate>
                    <TextField
                        variant="outlined"
                        margin="normal"
                        required
                        fullWidth
                        id="email"
                        label="Email Address"
                        name="email"
                        autoComplete="email"
                        autoFocus
                    />
                    <TextField
                        variant="outlined"
                        margin="normal"
                        required
                        fullWidth
                        name="password"
                        label="Password"
                        type="password"
                        id="password"
                        autoComplete="current-password"
                    />
                    <FormControlLabel
                        control={<Checkbox value="remember" color="primary"/>}
                        label="Remember me"
                    />
                    <Button
                        onClick={()=>{
                            history.push('/dashboard')
                        }}
                        fullWidth
                        variant="contained"
                        color="primary"
                        className={classes.submit}
                    >
                        Sign In
                    </Button>
                    <Grid container>
                        <Grid item xs>
                            <Link href="#" variant="body2">
                                Forgot password?
                            </Link>
                        </Grid>
                        <Grid item>
                            <Link href="#" variant="body2">
                                {"Don't have an account? Sign Up"}
                            </Link>
                        </Grid>
                    </Grid>
                </form>
            </div>
            <Box mt={8}>
                <Copyright/>
            </Box>
        </Container>
    );
}
</code>```

Dashboard Component

```<code>import React from "react";
import clsx from "clsx";
import {
  createStyles,
  makeStyles,
  useTheme,
  Theme
} from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import Drawer from "@material-ui/core/Drawer";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import List from "@material-ui/core/List";
import CssBaseline from "@material-ui/core/CssBaseline";
import Typography from "@material-ui/core/Typography";
import Divider from "@material-ui/core/Divider";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import InboxIcon from "@material-ui/icons/MoveToInbox";
import MailIcon from "@material-ui/icons/Mail";
import MapOutlinedIcon from "@material-ui/icons/MapOutlined";
import DriveEtaOutlinedIcon from "@material-ui/icons/DriveEtaOutlined";
import PeopleAltOutlinedIcon from "@material-ui/icons/PeopleAltOutlined";
import DirectionsOutlinedIcon from "@material-ui/icons/DirectionsOutlined";
import AssessmentOutlinedIcon from "@material-ui/icons/AssessmentOutlined";
import ReportProblemOutlinedIcon from "@material-ui/icons/ReportProblemOutlined";
import AccountCircleOutlinedIcon from "@material-ui/icons/AccountCircleOutlined";
import { Redirect, useHistory } from "react-router-dom";
import ExitToAppIcon from "@material-ui/icons/ExitToApp";

const drawerWidth = 240;

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      display: "flex"
    },
    appBar: {
      zIndex: theme.zIndex.drawer + 1,
      transition: theme.transitions.create(["width", "margin"], {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen
      })
    },
    appBarShift: {
      marginLeft: drawerWidth,
      width: `calc(100% - ${drawerWidth}px)`,
      transition: theme.transitions.create(["width", "margin"], {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.enteringScreen
      })
    },
    menuButton: {
      marginRight: 36
    },
    hide: {
      display: "none"
    },
    drawer: {
      width: drawerWidth,
      flexShrink: 0,
      whiteSpace: "nowrap"
    },
    drawerOpen: {
      width: drawerWidth,
      transition: theme.transitions.create("width", {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.enteringScreen
      })
    },
    drawerClose: {
      transition: theme.transitions.create("width", {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen
      }),
      overflowX: "hidden",
      width: theme.spacing(7) + 1,
      [theme.breakpoints.up("sm")]: {
        width: theme.spacing(9) + 1
      }
    },
    toolbar: {
      display: "flex",
      alignItems: "center",
      justifyContent: "flex-end",
      padding: theme.spacing(0, 1),
      // necessary for content to be below app bar
      ...theme.mixins.toolbar
    },
    content: {
      flexGrow: 1,
      padding: theme.spacing(3)
    }
  })
);

function MiniDrawer() {
  const classes = useStyles();
  let history = useHistory();
  const theme = useTheme();
  const [open, setOpen] = React.useState(false);

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };

  return (
    <div className={classes.root}>
      <CssBaseline />
      <AppBar
        position="fixed"
        className={clsx(classes.appBar, {
          [classes.appBarShift]: open
        })}
      >
        <Toolbar>
          <IconButton
            color="inherit"
            aria-label="open drawer"
            onClick={handleDrawerOpen}
            edge="start"
            className={clsx(classes.menuButton, {
              [classes.hide]: open
            })}
          >
            <MenuIcon />
          </IconButton>
        </Toolbar>
      </AppBar>

      <Drawer
        variant="permanent"
        className={clsx(classes.drawer, {
          [classes.drawerOpen]: open,
          [classes.drawerClose]: !open
        })}
        classes={{
          paper: clsx({
            [classes.drawerOpen]: open,
            [classes.drawerClose]: !open
          })
        }}
      >
        <div className={classes.toolbar}>
          <IconButton onClick={handleDrawerClose}>
            {theme.direction === "rtl" ? (
              <ChevronRightIcon />
            ) : (
              <ChevronLeftIcon />
            )}
          </IconButton>
        </div>
        <div className={classes.toolbar} />
        <div className={classes.toolbar} />
        <div className={classes.toolbar} />
        <IconButton
          onClick={() => {
            history.push("/");
          }}
        >
          <ExitToAppIcon />
        </IconButton>
        <Divider />
        <List>
          {["Mapa", "Pojazdy", "Kierowcy", "Trasy", "Raporty", "Alerty"].map(
            (text, index) => (
              <ListItem
                button
                key={text}
                onClick={event => {
                  console.log(event.currentTarget);
                  history.push("/");
                }}
              >
                <ListItemIcon>
                  {index === 0 && <MapOutlinedIcon />}
                  {index === 1 && <DriveEtaOutlinedIcon />}
                  {index === 2 && <PeopleAltOutlinedIcon />}
                  {index === 3 && <DirectionsOutlinedIcon />}
                  {index === 4 && <AssessmentOutlinedIcon />}
                  {index === 5 && <ReportProblemOutlinedIcon />}
                </ListItemIcon>
                <ListItemText primary={text} />
              </ListItem>
            )
          )}
        </List>
      </Drawer>

      <main className={classes.content}>
        <div className={classes.toolbar} />
        <Typography paragraph />
      </main>
    </div>
  );
}
export default MiniDrawer;
</code>```

Here is the Code Sandbox

Body:
Please check this example:

App Component

import React, {useEffect, useState} from 'react';
import SignIn from "./material-ui/signin-template/SignIn";
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";
import { createBrowserHistory as history} from 'history';
import MiniDrawer from "./material-ui/signin-template/Dashboard";

class App extends React.Component {
    render() {
        return (
            <div>
                <Router history={history}>
                    <Switch>
                        <Route path="/" exact component={SignIn}/>
                        <Route path="/dashboard" component={MiniDrawer}/>
                    </Switch>
                </Router>
            </div>
        )
    }
}
export default App;

SingIn Component

import React from "react";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
import CssBaseline from "@material-ui/core/CssBaseline";
import TextField from "@material-ui/core/TextField";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Checkbox from "@material-ui/core/Checkbox";
import Link from "@material-ui/core/Link";
import Grid from "@material-ui/core/Grid";
import Box from "@material-ui/core/Box";
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
import Typography from "@material-ui/core/Typography";
import {makeStyles} from "@material-ui/core/styles";
import Container from "@material-ui/core/Container";
import {Redirect, useHistory} from "react-router-dom";

function Copyright() {
    return (
        <Typography variant="body2" color="textSecondary" align="center">
            {"Copyright © "}
            <Link color="inherit" href="https://material-ui.com/">
                Your Website
            </Link>{" "}
            {new Date().getFullYear()}
            {"."}
        </Typography>
    );
}

const useStyles = makeStyles(theme => ({
    paper: {
        marginTop: theme.spacing(8),
        display: "flex",
        flexDirection: "column",
        alignItems: "center"
    },
    avatar: {
        margin: theme.spacing(1),
        backgroundColor: theme.palette.secondary.main
    },
    form: {
        width: "100%", // Fix IE 11 issue.
        marginTop: theme.spacing(1)
    },
    submit: {
        margin: theme.spacing(3, 0, 2)
    }
}));

export default function SignIn() {
    const classes = useStyles();
    let history = useHistory();

    return (
        <Container component="main" maxWidth="xs">
            <CssBaseline/>
            <div className={classes.paper}>
                <Avatar className={classes.avatar}>
                    <LockOutlinedIcon/>
                </Avatar>
                <Typography component="h1" variant="h5">
                    Sign in
                </Typography>
                <form className={classes.form} noValidate>
                    <TextField
                        variant="outlined"
                        margin="normal"
                        required
                        fullWidth
                        id="email"
                        label="Email Address"
                        name="email"
                        autoComplete="email"
                        autoFocus
                    />
                    <TextField
                        variant="outlined"
                        margin="normal"
                        required
                        fullWidth
                        name="password"
                        label="Password"
                        type="password"
                        id="password"
                        autoComplete="current-password"
                    />
                    <FormControlLabel
                        control={<Checkbox value="remember" color="primary"/>}
                        label="Remember me"
                    />
                    <Button
                        onClick={()=>{
                            history.push('/dashboard')
                        }}
                        fullWidth
                        variant="contained"
                        color="primary"
                        className={classes.submit}
                    >
                        Sign In
                    </Button>
                    <Grid container>
                        <Grid item xs>
                            <Link href="#" variant="body2">
                                Forgot password?
                            </Link>
                        </Grid>
                        <Grid item>
                            <Link href="#" variant="body2">
                                {"Don't have an account? Sign Up"}
                            </Link>
                        </Grid>
                    </Grid>
                </form>
            </div>
            <Box mt={8}>
                <Copyright/>
            </Box>
        </Container>
    );
}

Dashboard Component

import React from "react";
import clsx from "clsx";
import {
  createStyles,
  makeStyles,
  useTheme,
  Theme
} from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import Drawer from "@material-ui/core/Drawer";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import List from "@material-ui/core/List";
import CssBaseline from "@material-ui/core/CssBaseline";
import Typography from "@material-ui/core/Typography";
import Divider from "@material-ui/core/Divider";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import InboxIcon from "@material-ui/icons/MoveToInbox";
import MailIcon from "@material-ui/icons/Mail";
import MapOutlinedIcon from "@material-ui/icons/MapOutlined";
import DriveEtaOutlinedIcon from "@material-ui/icons/DriveEtaOutlined";
import PeopleAltOutlinedIcon from "@material-ui/icons/PeopleAltOutlined";
import DirectionsOutlinedIcon from "@material-ui/icons/DirectionsOutlined";
import AssessmentOutlinedIcon from "@material-ui/icons/AssessmentOutlined";
import ReportProblemOutlinedIcon from "@material-ui/icons/ReportProblemOutlined";
import AccountCircleOutlinedIcon from "@material-ui/icons/AccountCircleOutlined";
import { Redirect, useHistory } from "react-router-dom";
import ExitToAppIcon from "@material-ui/icons/ExitToApp";

const drawerWidth = 240;

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      display: "flex"
    },
    appBar: {
      zIndex: theme.zIndex.drawer + 1,
      transition: theme.transitions.create(["width", "margin"], {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen
      })
    },
    appBarShift: {
      marginLeft: drawerWidth,
      width: `calc(100% - ${drawerWidth}px)`,
      transition: theme.transitions.create(["width", "margin"], {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.enteringScreen
      })
    },
    menuButton: {
      marginRight: 36
    },
    hide: {
      display: "none"
    },
    drawer: {
      width: drawerWidth,
      flexShrink: 0,
      whiteSpace: "nowrap"
    },
    drawerOpen: {
      width: drawerWidth,
      transition: theme.transitions.create("width", {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.enteringScreen
      })
    },
    drawerClose: {
      transition: theme.transitions.create("width", {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen
      }),
      overflowX: "hidden",
      width: theme.spacing(7) + 1,
      [theme.breakpoints.up("sm")]: {
        width: theme.spacing(9) + 1
      }
    },
    toolbar: {
      display: "flex",
      alignItems: "center",
      justifyContent: "flex-end",
      padding: theme.spacing(0, 1),
      // necessary for content to be below app bar
      ...theme.mixins.toolbar
    },
    content: {
      flexGrow: 1,
      padding: theme.spacing(3)
    }
  })
);

function MiniDrawer() {
  const classes = useStyles();
  let history = useHistory();
  const theme = useTheme();
  const [open, setOpen] = React.useState(false);

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };

  return (
    <div className={classes.root}>
      <CssBaseline />
      <AppBar
        position="fixed"
        className={clsx(classes.appBar, {
          [classes.appBarShift]: open
        })}
      >
        <Toolbar>
          <IconButton
            color="inherit"
            aria-label="open drawer"
            onClick={handleDrawerOpen}
            edge="start"
            className={clsx(classes.menuButton, {
              [classes.hide]: open
            })}
          >
            <MenuIcon />
          </IconButton>
        </Toolbar>
      </AppBar>

      <Drawer
        variant="permanent"
        className={clsx(classes.drawer, {
          [classes.drawerOpen]: open,
          [classes.drawerClose]: !open
        })}
        classes={{
          paper: clsx({
            [classes.drawerOpen]: open,
            [classes.drawerClose]: !open
          })
        }}
      >
        <div className={classes.toolbar}>
          <IconButton onClick={handleDrawerClose}>
            {theme.direction === "rtl" ? (
              <ChevronRightIcon />
            ) : (
              <ChevronLeftIcon />
            )}
          </IconButton>
        </div>
        <div className={classes.toolbar} />
        <div className={classes.toolbar} />
        <div className={classes.toolbar} />
        <IconButton
          onClick={() => {
            history.push("/");
          }}
        >
          <ExitToAppIcon />
        </IconButton>
        <Divider />
        <List>
          {["Mapa", "Pojazdy", "Kierowcy", "Trasy", "Raporty", "Alerty"].map(
            (text, index) => (
              <ListItem
                button
                key={text}
                onClick={event => {
                  console.log(event.currentTarget);
                  history.push("/");
                }}
              >
                <ListItemIcon>
                  {index === 0 && <MapOutlinedIcon />}
                  {index === 1 && <DriveEtaOutlinedIcon />}
                  {index === 2 && <PeopleAltOutlinedIcon />}
                  {index === 3 && <DirectionsOutlinedIcon />}
                  {index === 4 && <AssessmentOutlinedIcon />}
                  {index === 5 && <ReportProblemOutlinedIcon />}
                </ListItemIcon>
                <ListItemText primary={text} />
              </ListItem>
            )
          )}
        </List>
      </Drawer>

      <main className={classes.content}>
        <div className={classes.toolbar} />
        <Typography paragraph />
      </main>
    </div>
  );
}
export default MiniDrawer;

Here is the Code Sandbox


问:
How do I pass a visual range to a function without numbers or using :command in vim?
How do I pass a visual selection to a function from a script and NOT command line / mapping. I was wondering if something like this was possible? Or if there is a function that gets a range ?

What I want:

```<code>:call LowerToUpper('<,'>)
:call LowerToUpper(GetVisualRange())
</code>```

NOT THIS

```<code>:call LowerToUpper(1,5)
command! -range Edit call LowerToUpper(<line1>,<line2>)
:'<,'>LowerToUpper
</code>```

Here is the function example:

```<code>function! LowerToUpper(first,last) abort
for lineno in range(a:first,a:last)
    let line = getline(lineno)
    let newLine= substitute(line, '\v(\w)','\U\1','g')
    call setline(lineno,newLine)
endfor
endfunction
</code>```

The solution might be a hack to make a function that returns the visual selection GetVisualSelection().

答:
:call LowerToUpper('<,'>)

You're very very close. Use line() to get lines of the marks:

```<code>:call LowerToUpper(line("'<"), line("'>"))
</code>```

Body:
How do I pass a visual selection to a function from a script and NOT command line / mapping. I was wondering if something like this was possible? Or if there is a function that gets a range ?

What I want:

:call LowerToUpper('<,'>)
:call LowerToUpper(GetVisualRange())

NOT THIS

:call LowerToUpper(1,5)
command! -range Edit call LowerToUpper(<line1>,<line2>)
:'<,'>LowerToUpper

Here is the function example:

function! LowerToUpper(first,last) abort
for lineno in range(a:first,a:last)
    let line = getline(lineno)
    let newLine= substitute(line, '\v(\w)','\U\1','g')
    call setline(lineno,newLine)
endfor
endfunction

The solution might be a hack to make a function that returns the visual selection GetVisualSelection().

Body:
:call LowerToUpper('<,'>)

You're very very close. Use line() to get lines of the marks:

:call LowerToUpper(line("'<"), line("'>"))


问:
How do I determine what a function will be called if it's virtual and when it is not?
Look at this excerpt of a program.

I see that cout << obj->foo(); call is not polymorphic. Actually, it is obvious, because it has no virtual specificator.

But I am confused with cout << ((B*)obj)->foo(); Why the program does not use the B's definition of virtual function and will call the third version of foo()?

```<code> #include <iostream>
using namespace std;

class A{
public:
    int foo(){ return 1; }
};
class B: public A{
public:
    virtual int foo(){ return 2; }
};
class C: public B{
public:
    int foo(){ return 3; }
};

int main() {
    A* obj = new C;

    cout << obj->foo();
    cout << ((B*)obj)->foo();
    cout << ((C*)obj)->foo();

    return 0;
}
</code>```

答:
A::foo() is not virtual.  Calling foo() via an A* pointer (or A& reference) will call A::foo() directly without any polymorphic dispatch.

B::foo() is virtual.  Calling foo() via a B* pointer (or B& reference) will dispatch the call to the most derived implementation of foo() that exists in the object that the B* (or B&) refers to.

C derives from B, and C::foo() overrides B::foo(), and obj points to a C object, which is why C::foo() gets called by polymorphic dispatch when foo() is called via a B* or C* pointer (or a B& or C& reference).

Body:
Look at this excerpt of a program.

I see that cout << obj->foo(); call is not polymorphic. Actually, it is obvious, because it has no virtual specificator.

But I am confused with cout << ((B*)obj)->foo(); Why the program does not use the B's definition of virtual function and will call the third version of foo()?

 #include <iostream>
using namespace std;

class A{
public:
    int foo(){ return 1; }
};
class B: public A{
public:
    virtual int foo(){ return 2; }
};
class C: public B{
public:
    int foo(){ return 3; }
};

int main() {
    A* obj = new C;

    cout << obj->foo();
    cout << ((B*)obj)->foo();
    cout << ((C*)obj)->foo();

    return 0;
}


问:
How to "expand" an English sentence
I would like to get some steps and resources about, how to build program to expand a sentence in English.

For example, if an input sentence is

"My father is coaching and refereeing soccer and basketball."

Then the program would output four sentences:

"My father is coaching soccer."

"My father is coaching basketball."

"My father is refereeing soccer."

"My father is refereeing basketball."

The generated sentences must be valid English sentences and their meaning must follow from the meaning of the input sentence.

答:
This is not easy at all , if you want to use an AI it will need a huge amount of data and you cant event garantee the exact English sentence meaning , but still i can suggest to you two methods :

The AI method :

You can use a Recurrent Neural Network with LSTM , the idea is to inject as input your sentence ( which will be transformed using one of the NLP methods ) in your One to Many model , to have the different expanded number of sentences as output

Example :

```<code>Input                | Output
'i play xbox and ps' | [ 'i play xbox' , 'i play ps' ]
</code>```

The Classic method :

Here you have to use a class with the following attributes { subject , verb , object } and when you want to give an input , you'll have to precise each word of this input as its type , each of the attributes is a list which will append words , and then to expand it you'll parse these lists to see how many objects and verbs you have

Example ( in Java ) :

```<code>// Input : "i play xbox and ps"
Sentence sc = new Sentence();
sc.setSubject("i");
sc.setVerb("play");
sc.addObject("xbox");
sc.addObject("ps");

// for each object you'll do the following
for ( String object : sc.getObject() ) {
    System.out.println( sc.getSubject() + sc.getVerb() + object ) ;
}

// Output : i play xbox
//        : i play ps
</code>```

This is just a simple example but you can think of a way to make the process of adding verbs and objects automatic

Title: How to "expand" an English sentence

Body:
This is not easy at all , if you want to use an AI it will need a huge amount of data and you cant event garantee the exact English sentence meaning , but still i can suggest to you two methods :

The AI method :

You can use a Recurrent Neural Network with LSTM , the idea is to inject as input your sentence ( which will be transformed using one of the NLP methods ) in your One to Many model , to have the different expanded number of sentences as output

Example :

Input                | Output
'i play xbox and ps' | [ 'i play xbox' , 'i play ps' ]

The Classic method :

Here you have to use a class with the following attributes { subject , verb , object } and when you want to give an input , you'll have to precise each word of this input as its type , each of the attributes is a list which will append words , and then to expand it you'll parse these lists to see how many objects and verbs you have

Example ( in Java ) :

// Input : "i play xbox and ps"
Sentence sc = new Sentence();
sc.setSubject("i");
sc.setVerb("play");
sc.addObject("xbox");
sc.addObject("ps");

// for each object you'll do the following
for ( String object : sc.getObject() ) {
    System.out.println( sc.getSubject() + sc.getVerb() + object ) ;
}

// Output : i play xbox
//        : i play ps

This is just a simple example but you can think of a way to make the process of adding verbs and objects automatic


答:
Because ((B*)obj)->foo(); behaves by design like B* b = (B*)obj; b->foo() and calls C::foo. You may call the base's method explicitly like ((B*)obj)->B::foo();.

```<code>#include <iostream>
using namespace std;

class A{
public:
    int foo(){ return 1; }
};
class B: public A{
public:
    virtual int foo(){ return 2; }
};
class C: public B{
public:
    int foo() override { return 3; }
};

int main() {
    A* obj = new C;

    cout << obj->foo();
    cout << ((B*)obj)->B::foo();
    cout << ((C*)obj)->foo();

    return 0;
}
</code>```

Output: 123

Title: How do I determine what a function will be called if it's virtual and when it is not?

Body:
Because ((B*)obj)->foo(); behaves by design like B* b = (B*)obj; b->foo() and calls C::foo. You may call the base's method explicitly like ((B*)obj)->B::foo();.

#include <iostream>
using namespace std;

class A{
public:
    int foo(){ return 1; }
};
class B: public A{
public:
    virtual int foo(){ return 2; }
};
class C: public B{
public:
    int foo() override { return 3; }
};

int main() {
    A* obj = new C;

    cout << obj->foo();
    cout << ((B*)obj)->B::foo();
    cout << ((C*)obj)->foo();

    return 0;
}

Output: 123


答:
collect into object map using tag as key and appending to an array

d=[
  { tag: 'Red', member: 'Red-Steve' },
  { tag: 'Red', member: 'Red-Adam' },
  { tag: 'Blue', member: 'Blue-John' },
  { tag: 'Blue', member: 'Blue-James' },
  { tag: 'Blue', member: 'Blue-Igor' }
]
console.log(
d.reduce((acc,{tag,member})=>({...acc, [tag]: [...acc[tag]||[], member]}),{})
)```

Title: Grouping object entries into object arrays


问:
Git: How to ensure new branch is based on upstream master
I've been making a lot of rookie mistakes with github and as a result I'm seeking a foolproof (me-proof!) method for ensuring that:

a) All new branches I create on a fork are based on origin master, not some other branch, and...

b) That my origin master is always up-to-date with upstream master, and...

c) That when/before I commit (push?), my changes are rebased to upstream master.

Here's what I have so far...

To create new branch:

```<code>git fetch --all --tag
git pull upstream master
git push origin master
git checkout -b my_branch_name -t origin/master
</code>```

To store my changes to that branch:

```<code>git add -A
git commit -m "Summary of what changed"
git fetch --all --tag
git pull --rebase upstream master
git push origin my_branch_name
</code>```

To load an existing branch at a later date (eg. to do some additional changes resulting from PR feedback):

```<code>git fetch --all --tag
git pull upstream master
git push origin master
git checkout my_branch_name -t origin/master
</code>```

And then to save my updates to that branch:

```<code>git add -A
git commit --amend --no-edit
git fetch --all --tag
git pull --rebase upstream master
git push origin my_branch_name -f
</code>```

I must confess I don't fully comprehend what some of these commands do - there seems to be lots of ways to do lots of similar sounding things and despite lots of googling/reading I'm still a rookie.

Any guidance very much appreciated!

答:
after setting upstream</p>

```<code>git checkout -b branch-name
git fetch upstream
git reset --hard upstream/master
git push --set-upstream origin branch-name
</code>```

Body:
I've been making a lot of rookie mistakes with github and as a result I'm seeking a foolproof (me-proof!) method for ensuring that:

a) All new branches I create on a fork are based on origin master, not some other branch, and...

b) That my origin master is always up-to-date with upstream master, and...

c) That when/before I commit (push?), my changes are rebased to upstream master.

Here's what I have so far...

To create new branch:

git fetch --all --tag
git pull upstream master
git push origin master
git checkout -b my_branch_name -t origin/master

To store my changes to that branch:

git add -A
git commit -m "Summary of what changed"
git fetch --all --tag
git pull --rebase upstream master
git push origin my_branch_name

To load an existing branch at a later date (eg. to do some additional changes resulting from PR feedback):

git fetch --all --tag
git pull upstream master
git push origin master
git checkout my_branch_name -t origin/master

And then to save my updates to that branch:

git add -A
git commit --amend --no-edit
git fetch --all --tag
git pull --rebase upstream master
git push origin my_branch_name -f

I must confess I don't fully comprehend what some of these commands do - there seems to be lots of ways to do lots of similar sounding things and despite lots of googling/reading I'm still a rookie.

Any guidance very much appreciated!

Body:
after setting upstream

git checkout -b branch-name
git fetch upstream
git reset --hard upstream/master
git push --set-upstream origin branch-name


问:
windowWillReturnFieldEditor never called for NSTextView
Per protocol ref, windowWillReturnFieldEditor should be called for any text-displaying object when it needs a field editor. Indeed, my window delegate receives a call to this method for textfields, buttons, comboboxes, etc. — but never for textviews.

Is this normal? Does NSTextView carry its own field editor and never request one? Or what am I missing?

```<code>- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)anObject {
    if ([anObject isKindOfClass:[NSTextView class]])
        printf("\nwinWillRtnFldEdtor called for some textview."); // never happens
}
</code>```

答:
Drats. Looking at memory addresses of the field editors, it is apparent that every textview does indeed have its own distinct field editor (unlike the textfields, which share a common field editor), and so textviews never request a field editor and never call this method.

Which is unfortunate, since I need special routines to set up multiple distinct textviews just before they become active. (It was easier to do this with textfields.) The best workaround I can think of is to add a tag-like property to the textviews.

Body:
Per protocol ref, windowWillReturnFieldEditor should be called for any text-displaying object when it needs a field editor. Indeed, my window delegate receives a call to this method for textfields, buttons, comboboxes, etc. — but never for textviews.

Is this normal? Does NSTextView carry its own field editor and never request one? Or what am I missing?

- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)anObject {
    if ([anObject isKindOfClass:[NSTextView class]])
        printf("\nwinWillRtnFldEdtor called for some textview."); // never happens
}


答:
I think this will be a good way of achieving it in modern syntax. But may be there are some aggregate functions too.

var arr = [
  { tag: 'Red', member: 'Red-Steve' },
  { tag: 'Red', member: 'Red-Adam' },
  { tag: 'Blue', member: 'Blue-John' },
  { tag: 'Blue', member: 'Blue-James' },
  { tag: 'Blue', member: 'Blue-Igor' }
];

var newArr = [];
arr.forEach(o => {
  var existing = newArr[o.tag] && newArr[o.tag].length > 0 ? newArr[o.tag] : [];
  newArr[o.tag] = [...existing, ...[o.member]];
});

console.log('newArr', newArr);```

In Chrome it is giving following output in the console

We have a similar question here Most efficient method to groupby on an array of objects

Body:
I think this will be a good way of achieving it in modern syntax. But may be there are some aggregate functions too.

var arr = [
  { tag: 'Red', member: 'Red-Steve' },
  { tag: 'Red', member: 'Red-Adam' },
  { tag: 'Blue', member: 'Blue-John' },
  { tag: 'Blue', member: 'Blue-James' },
  { tag: 'Blue', member: 'Blue-Igor' }
];

var newArr = [];
arr.forEach(o => {
  var existing = newArr[o.tag] && newArr[o.tag].length > 0 ? newArr[o.tag] : [];
  newArr[o.tag] = [...existing, ...[o.member]];
});

console.log('newArr', newArr);

In Chrome it is giving following output in the console

We have a similar question here Most efficient method to groupby on an array of objects


问:
Anaconda Navigator won't launch (windows 10)
Anaconda navigator won't launch, I tried reinstalling it, that did not work either. anancondas' command prompt shows an error message. I've tried googling the answer, I guess I'm bad at it.
[this is what I see after opening anaconda prompt]

p.s. I use spyder on it

答:
So none of the above answers worked for me.

I performed the following steps in order to make it work for me :
OS : Windows 10 Home 64 Bit

Open Anaconda Prompt

```<code>conda remove anaconda-navigator
conda install anaconda-navigator
</code>```

conda install -c anaconda pywin32  // Had to install since I got a module not found error
                                   // with just the above two commands

And it worked for me!!

Body:
So none of the above answers worked for me.

I performed the following steps in order to make it work for me :
OS : Windows 10 Home 64 Bit

Open Anaconda Prompt

conda remove anaconda-navigator
conda install anaconda-navigator

conda install -c anaconda pywin32  // Had to install since I got a module not found error
                                   // with just the above two commands

And it worked for me!!


答:
Member function foo is virtual from class B downwards, i.e. also in C, even if it is not marked virtual or override there.

Thus, call ((B*)obj)->foo() is a virtual call, actually resulting in calling C::foo.


问:
Object of type is not JSON serializable
Just started with Django Rest framework and following the great tutorial:
https://sunscrapers.com/blog/ultimate-tutorial-django-rest-framework-part-1/

I have created a test model:

models.py

```<code>class Test(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField
</code>```

And to make the object available through the API, I have implemented a serializer. This would serialize to XML, YAML or JSON, the latter is what I am interested in. Below is my serialization class.

serializers.py

```<code>class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Test
        fields = ('name', 'age')
</code>```

app/views.py

```<code>class TestViewSet(viewsets.ModelViewSet):
    queryset = models.Test.objects.all()
    serializer_class = serializers.TestSerializer
</code>```

However, it doesn't seem to serialize to JSON as expected as the error below shows:

```<code>File "C:\Program Files\Python38\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type type is not JSON serializable
</code>```

Worth adding, that it worked for like 2 hours then just went bad.

答:
You missed a pair of parentheses in your Test class's age field:

```<code>class Test(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()  # <-- missed this pair
</code>```

Title: Object of type is not JSON serializable

Body:
Just started with Django Rest framework and following the great tutorial:
https://sunscrapers.com/blog/ultimate-tutorial-django-rest-framework-part-1/

I have created a test model:

models.py

class Test(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField

And to make the object available through the API, I have implemented a serializer. This would serialize to XML, YAML or JSON, the latter is what I am interested in. Below is my serialization class.

serializers.py

class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Test
        fields = ('name', 'age')

app/views.py

class TestViewSet(viewsets.ModelViewSet):
    queryset = models.Test.objects.all()
    serializer_class = serializers.TestSerializer

However, it doesn't seem to serialize to JSON as expected as the error below shows:

File "C:\Program Files\Python38\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type type is not JSON serializable

Worth adding, that it worked for like 2 hours then just went bad.

Body:
You missed a pair of parentheses in your Test class's age field:

class Test(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()  # <-- missed this pair


问:
modify link behaviour in Jekyll
I have an itchy issue I definitely need solve.

Every time I insert a link in my Jekyll website, independently if I write it in a Markdown file or an HTML file, I write the following:

example
```

<p>Obviously, it's way longer, more boring and more stressful than typing</p>

```[example](example.com)
```

Is there a way I can add by default the rel and target attributes (maybe in the _config.yml file) for every link so that I can easily insert a simple  tag and then it's parsed with all the extra stuff?

I know I could insert attributes also in Markdown, like this, but it's still quite a lot of typing...

Thanks a lot in advance, this would definitely change my game!

答:
Kramdown supports it this way (as you mentioned):

```<code>[example](example.com){:target="_blank"}{:rel="noopener noreferrer"}
</code>```

If you want to do it for all links across your site, you'd need to write a custom plugin, which wouldn't work on GitHub Pages, or use Javascript.

Title: modify link behaviour in Jekyll

Body:
I have an itchy issue I definitely need solve.

Every time I insert a link in my Jekyll website, independently if I write it in a Markdown file or an HTML file, I write the following:

example

Obviously, it's way longer, more boring and more stressful than typing

[example](example.com)

Is there a way I can add by default the rel and target attributes (maybe in the _config.yml file) for every link so that I can easily insert a simple  tag and then it's parsed with all the extra stuff?

I know I could insert attributes also in Markdown, like this, but it's still quite a lot of typing...

Thanks a lot in advance, this would definitely change my game!

Body:
Kramdown supports it this way (as you mentioned):

[example](example.com){:target="_blank"}{:rel="noopener noreferrer"}

If you want to do it for all links across your site, you'd need to write a custom plugin, which wouldn't work on GitHub Pages, or use Javascript.


问:
Time Series w/ multiple variables, groups
I'm trying to plot a time series in ggplot for certain export markets, for example-sake, Japan. I want to focus on a few different export items (e.g. pork, beef, wheat,etc.) by exporter (e.g. US, EU, Australia, etc.). I'd like to be able to set up the data so that I can use facet_wrap to show a graph for each of those goods in one image (representing the Japanese market), that has all relevant exporters. I've been trying to use geom_line but I have no idea how to arrange the data so that I can use facet_wrap, ggplot, etc.</p>

答:
You need two columns that specify the exporter and country, in long format (so each row is a unique combination of product, exporter, country and date). A reproducible example of this is shown below.

Then, the key plot element is using facet_grid(exporter~product).

```<code>export_data.df <- data.frame(
  value = runif(36),
  Date =  rep(c(rep(as.Date("1999/1/1"),3),
                rep(as.Date("1999/1/2"),3),
                rep(as.Date("1999/1/3"),3),
                rep(as.Date("1999/1/4"),3)),3),
  exporter = rep(rep(c("Japan","USA","NZ"),3),4),
  product = rep(c(rep("Pork",3),rep("Beef",3),rep("Chicken",3)),4)
)

ggplot(export_data.df) +
  geom_line(mapping = aes(x = Date,y = value)) +
  facet_grid(exporter~product)
</code>```

Output of above code

Body:
You need two columns that specify the exporter and country, in long format (so each row is a unique combination of product, exporter, country and date). A reproducible example of this is shown below.

Then, the key plot element is using facet_grid(exporter~product).

export_data.df <- data.frame(
  value = runif(36),
  Date =  rep(c(rep(as.Date("1999/1/1"),3),
                rep(as.Date("1999/1/2"),3),
                rep(as.Date("1999/1/3"),3),
                rep(as.Date("1999/1/4"),3)),3),
  exporter = rep(rep(c("Japan","USA","NZ"),3),4),
  product = rep(c(rep("Pork",3),rep("Beef",3),rep("Chicken",3)),4)
)

ggplot(export_data.df) +
  geom_line(mapping = aes(x = Date,y = value)) +
  facet_grid(exporter~product)

Output of above code


问:
How to change font type, font size and bold text in Android style (PopUpMenu)
How do I change things like font size, font type and bold text in a PopUpMenu?

```<code><style name="AppTheme.PopupMenu" parent="ThemeOverlay.AppCompat.Dark">
    <item name="android:textColor">@color/colorPrimary</item>
    <item name="android:textColorSecondary">@color/colorSecondary</item>
    <item name="android:popupBackground">@color/black</item>
</style>
</code>```

I'm doing like this to add this style:

```<code>Context wrapper = new ContextThemeWrapper(MainActivity.this, R.style.AddEffectsStyle);
PopupMenu popup = new PopupMenu(wrapper, binding.btnAddEffect);
</code>```

I tried adding, for example:

```<code>    <item name="android:textStyle">bold</item>
</code>```

but text won't turn bold.

How do I change thee things I mentioned?

答:
Try doing this:

```
</div>
</div>
</p>

<p>And for your java:</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-js lang-js prettyprint-override"><code>Context wrapper = new ContextThemeWrapper(MainActivity.this, R.style.YOURSTYLE);
PopupMenu popup = new PopupMenu(wrapper, view);
popup.inflate(R.menu.main_menu);
popup.show();</code>```

Works perfectly for me.

Here's how it looks

Body:
How do I change things like font size, font type and bold text in a PopUpMenu?

I'm doing like this to add this style:

Context wrapper = new ContextThemeWrapper(MainActivity.this, R.style.AddEffectsStyle);
PopupMenu popup = new PopupMenu(wrapper, binding.btnAddEffect);

I tried adding, for example:

    <item name="android:textStyle">bold</item>

but text won't turn bold.

How do I change thee things I mentioned?

Body:
Try doing this:

<style name="YOURSTYLE" parent="Widget.AppCompat.PopupMenu">
    <item name="android:textColor">@android:color/white</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textSize">24sp</item>
    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:itemBackground">@android:color/holo_red_light</item>
</style>

And for your java:

Context wrapper = new ContextThemeWrapper(MainActivity.this, R.style.YOURSTYLE);
PopupMenu popup = new PopupMenu(wrapper, view);
popup.inflate(R.menu.main_menu);
popup.show();

Works perfectly for me.

Here's how it looks


问:
Value undefined after a function
I have one class with one fuction in it, and another class that will import the first class and use that function. After the function operates i need one value, but i am not getting any value afte the function.

First class:

```<code>export class MoveEff {

    checkEffect(effectFaceOff1,moveEff1,moveEff2){
        if ( effectFaceOff1=== 'grassgrass') {

            moveEff1 = 10;
            console.log(moveEff1);

        }
    }
}
</code>```

Second class :

```<code>
import { Component, OnInit } from '@angular/core';
import {GenIService} from "../Pokemons/gen-i.service";
import {MovesService} from "../Moves/moves.service";
import {MoveDataClass} from "../MoveDATA/move-data-class";
import {MoveEff} from "../MoveDATA/move-eff";

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage implements OnInit {

  effectFaceOff1;
  moveEff1;
  moveEff2;

constructor(private moveeff: MoveEff) {}

 this.moveeff.checkEffect(this.effectFaceOff1,this.moveEff1,this.moveEff2);

 console.log(this.moveEff1,this.moveEff2);

</code>```

On the last console.log i should be seeing the 10 value of moveEff1, but it appears undefined.

Why? and how can i solve it?

答: Exporting the class may not be enough. Try exporting and importing all your methods as modules, or exporting the method directly.</p>

Title: Value undefined after a function

Body:
I have one class with one fuction in it, and another class that will import the first class and use that function. After the function operates i need one value, but i am not getting any value afte the function.

First class:

export class MoveEff {

    checkEffect(effectFaceOff1,moveEff1,moveEff2){
        if ( effectFaceOff1=== 'grassgrass') {

            moveEff1 = 10;
            console.log(moveEff1);

        }
    }
}

Second class :

import { Component, OnInit } from '@angular/core';
import {GenIService} from "../Pokemons/gen-i.service";
import {MovesService} from "../Moves/moves.service";
import {MoveDataClass} from "../MoveDATA/move-data-class";
import {MoveEff} from "../MoveDATA/move-eff";

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage implements OnInit {

  effectFaceOff1;
  moveEff1;
  moveEff2;

constructor(private moveeff: MoveEff) {}

 this.moveeff.checkEffect(this.effectFaceOff1,this.moveEff1,this.moveEff2);

 console.log(this.moveEff1,this.moveEff2);

On the last console.log i should be seeing the 10 value of moveEff1, but it appears undefined.

Why? and how can i solve it?