问:
ASP.NET CORE and BLAZOR : Reset Password
Hy,

I'm new to blazor and .net and was wondering how i can implement a password reset the best way possible.
Currently i'm using this example to login etc : Blazor Authentication Sample.
This example excludes an example for reseting the password.So i was searching for a solution myself.

This is what is have, it's a Razor Component

```<code>@page "/ResetPassword"

@inject UserManager<IdentityUser> userManager
@inject NavigationManager navigationManager
@inject IDataProtectionProvider dataProtectionProvider

@if (IsResetSend)
{
    <h3>Reset Password</h3>
    <div>
        A mail has been send with a password reset link, please click this link to set a new password.
    </div>
    <br />
    <a href="/">Back</a>
}
else
{
    <h3>Reset Password</h3>
    <EditForm Model="resetPassword" OnValidSubmit="@SendResetPassword">
        <div class="field">
            <label class="label">E-mail</label>
            <div class="control">
                <InputText id="email" class="input" type="email" @bind-Value="@resetPassword.Email"></InputText>
            </div>
        </div>
        <div class="field">
            <div class="control">
                <button type="submit" class="button is-primary">Sign in</button>
            </div>
        </div>
    </EditForm>
}

@code {

    ResetPassword resetPassword = new ResetPassword();

    bool IsResetSend = false;

    public async void SendResetPassword()
    {
        List<string> mailTo = new List<string>();

        string passwordResetToken;

        var user = await userManager.FindByEmailAsync(resetPassword.Email);

        if (user != null)
        {
            mailTo.Add(resetPassword.Email);

            passwordResetToken = await userManager.GeneratePasswordResetTokenAsync(user);

            //Send mail with the relevant token
            Webco.Email.Entities.EmailObject emailObject = new Webco.Email.Entities.EmailObject();
            emailObject.Email_To = mailTo;
            emailObject.Email_Subject = "Password Reset Webco !";
            emailObject.Email_Message = "Hy There, <br> Please click this link to reset your password : <br> https://localhost:44384/" + passwordResetToken;
            emailObject.SendEmail(emailObject);

            IsResetSend = true;
        }
    }

    public class ResetPassword
    {
        [Required]
        public string Email { get; set; }

    }
</code>```

As you can see, this is a staightforward approach, currently the one thing i can't seem to find is a way to store the password reset token, and capture it when it is being clicked in the mail.

Before i would;

Create a random token, store it in the database in the field ;
UserResetToken of the current user

When the user then click's the link, the token would be offered to the webpage [Parameter].

A stored procedure would then find the token and clear it, to alter the password afterwards on another user form.

I don't think this is best practice there it is based on a custom stored procedure. Could anybody guide me in this ?

Regards,

答:
After some searching, and thanks to the response of Marvin i came to the code bellow.
Maybe it can help anybody who searches for this topic.
Open for improvement...

I tested this at a server side application in development. Not on iis

Link for understanding the usermanager
kudvenkat, great youtube series on .net core

Razor Component

```<code>@page "/ResetPassword"

@inject UserManager<IdentityUser> userManager
@inject NavigationManager navigationManager
@inject IDataProtectionProvider dataProtectionProvider

@using Microsoft.AspNetCore.WebUtilities;
@using System.Text.Encodings.Web;
@using System.Text;

@* THIS IS THE PART HANDLING THE RESET TOKEN INCOMING VALIDATION *@
@if (IsResetToken)
{

    <h3>Reset Password</h3>
    <div>
        Please enter a new Password bellow;
    </div>
    <br />
    <EditForm Model="@validatePasswordModel" OnValidSubmit="@SetResetPassword">
        <DataAnnotationsValidator />
        <ValidationSummary />

        <div class="field">
            <label class="label">Password</label>
            <div class="control">
                <InputText id="password" class="input" type="password" @bind-Value="@validatePasswordModel.Password"></InputText>
            </div>
        </div>
        <div class="field">
            <label class="label">Confirm password</label>
            <div class="control">
                <InputText id="cpassword" class="input" type="password" @bind-Value="@validatePasswordModel.ConfirmPassword"></InputText>
            </div>
        </div>
        <div class="field">
            <div class="control">
                <button type="submit" class="button is-primary">Set Password</button>
            </div>
        </div>
    </EditForm>
    <br />
    <a href="/">Back</a>

}
else
{

    @* THIS IS THE PART HANDLING THE RESET TOKEN OUTGOING VALIDATION *@

    @if (IsResetSend)
    {
        <h3>Reset Password</h3>
        <div>
            A mail has been send with a password reset link, please click this link to set a new password.
        </div>
        <br />
        <a href="/">Back</a>
    }
    else
    {
        <h3>Reset Password</h3>
        <EditForm Model="requestPasswordModel" OnValidSubmit="@SendResetPassword">
            <div class="field">
                <label class="label">E-mail</label>
                <div class="control">
                    <InputText id="email" class="input" type="email" @bind-Value="@requestPasswordModel.Email"></InputText>
                </div>
            </div>
            <div class="field">
                <div class="control">
                    <button type="submit" class="button is-primary">Sign in</button>
                </div>
            </div>
        </EditForm>
    }
}

@code {

    InputModel requestPasswordModel = new InputModel();
    ResetPasswordModel validatePasswordModel = new ResetPasswordModel();

    string email = "";
    string token = "";

    bool IsResetSend = false;
    bool IsResetToken = false;

    protected override void OnInitialized()
    {

        GetHttpParameters();

    }

    public void GetHttpParameters()
    {
        var uriBuilder = new UriBuilder(navigationManager.Uri);
        var httpQuery = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);

        email = httpQuery["email"] ?? "";
        token = httpQuery["token"] ?? "";

        if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(token))
        {
            IsResetToken = true;

        }
    }

    public async void SendResetPassword()
    {
        List<string> mailTo = new List<string>();

        string passwordResetToken;
        string passwordResetUrl;

        var user = await userManager.FindByEmailAsync(requestPasswordModel.Email);

        if (user != null)
        {
            passwordResetUrl = navigationManager.BaseUri;

            passwordResetToken = await userManager.GeneratePasswordResetTokenAsync(user);

            passwordResetToken = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(passwordResetToken));

            passwordResetUrl = "https://localhost:44384/ResetPassword?email=" + user.Email + "&token=" + passwordResetToken;

            mailTo.Add(requestPasswordModel.Email);

            //Send mail with the relevant token
            Webco.Email.Entities.EmailObject emailObject = new Webco.Email.Entities.EmailObject();
            emailObject.Email_To = mailTo;
            emailObject.Email_Subject = "Password Reset Webco !";
            emailObject.Email_Message = $"Hy There, <br> Please click this link to reset your password : <br><a href='{HtmlEncoder.Default.Encode(passwordResetUrl)}'> clikcing here </a>.";
            emailObject.SendEmail(emailObject);

            IsResetSend = true;
        }
        else
        {
            //it's a lie
            IsResetSend = true;
        }
    }

    public async void SetResetPassword()
    {
        List<string> mailTo = new List<string>();

        var user = await userManager.FindByEmailAsync(email);

        if (user != null)
        {
            token = System.Text.Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(token));

            var result = await userManager.ResetPasswordAsync(user, token, validatePasswordModel.ConfirmPassword);

            if (result.Succeeded)
            {

                mailTo.Add(email);

                //Send mail with the relevant token
                Webco.Email.Entities.EmailObject emailObject = new Webco.Email.Entities.EmailObject();
                emailObject.Email_To = mailTo;
                emailObject.Email_Subject = "Password Reset Webco !";
                emailObject.Email_Message = $"Hy There, <br> You password was just reset at webco. Not you ? <br> Contact webco for support.";
                emailObject.SendEmail(emailObject);

                navigationManager.NavigateTo("/LoginUserResetPasswordComplete", true);
            }
            else
            {
                navigationManager.NavigateTo("/LoginUserResetPasswordError", true);
            }
        }
        else
        {
            navigationManager.NavigateTo("/LoginUserResetPasswordError",true);
        }

    }

    public class InputModel
    {
        [Required]
        [EmailAddress]
        public string Email { get; set; }
    }

    public class ResetPasswordModel
    {
        [Required]
        public string Password { get; set; }
        [Required]
        [Compare(nameof(Password))]
        public string ConfirmPassword { get; set; }
    }

}
</code>```

Body:
Hy,

I'm new to blazor and .net and was wondering how i can implement a password reset the best way possible.
Currently i'm using this example to login etc : Blazor Authentication Sample.
This example excludes an example for reseting the password.So i was searching for a solution myself.

This is what is have, it's a Razor Component

@page "/ResetPassword"

@inject UserManager<IdentityUser> userManager
@inject NavigationManager navigationManager
@inject IDataProtectionProvider dataProtectionProvider

@if (IsResetSend)
{

Reset Password

        A mail has been send with a password reset link, please click this link to set a new password.

    Back
}
else
{

Reset Password

    <EditForm Model="resetPassword" OnValidSubmit="@SendResetPassword">

            E-mail

                <InputText id="email" class="input" type="email" @bind-Value="@resetPassword.Email"></InputText>

                <button type="submit" class="button is-primary">Sign in</button>

    </EditForm>
}

@code {

    ResetPassword resetPassword = new ResetPassword();

    bool IsResetSend = false;

    public async void SendResetPassword()
    {
        List<string> mailTo = new List<string>();

        string passwordResetToken;

        var user = await userManager.FindByEmailAsync(resetPassword.Email);

        if (user != null)
        {
            mailTo.Add(resetPassword.Email);

            passwordResetToken = await userManager.GeneratePasswordResetTokenAsync(user);

            //Send mail with the relevant token
            Webco.Email.Entities.EmailObject emailObject = new Webco.Email.Entities.EmailObject();
            emailObject.Email_To = mailTo;
            emailObject.Email_Subject = "Password Reset Webco !";
            emailObject.Email_Message = "Hy There,
 Please click this link to reset your password :
 https://localhost:44384/" + passwordResetToken;
            emailObject.SendEmail(emailObject);

            IsResetSend = true;
        }
    }

    public class ResetPassword
    {
        [Required]
        public string Email { get; set; }

    }

As you can see, this is a staightforward approach, currently the one thing i can't seem to find is a way to store the password reset token, and capture it when it is being clicked in the mail.

Before i would;

Create a random token, store it in the database in the field ;
UserResetToken of the current user

When the user then click's the link, the token would be offered to the webpage [Parameter].

A stored procedure would then find the token and clear it, to alter the password afterwards on another user form.

I don't think this is best practice there it is based on a custom stored procedure. Could anybody guide me in this ?

Regards,

Body:
After some searching, and thanks to the response of Marvin i came to the code bellow.
Maybe it can help anybody who searches for this topic.
Open for improvement...

I tested this at a server side application in development. Not on iis

Link for understanding the usermanager
kudvenkat, great youtube series on .net core

Razor Component

@page "/ResetPassword"

@inject UserManager<IdentityUser> userManager
@inject NavigationManager navigationManager
@inject IDataProtectionProvider dataProtectionProvider

@using Microsoft.AspNetCore.WebUtilities;
@using System.Text.Encodings.Web;
@using System.Text;

@* THIS IS THE PART HANDLING THE RESET TOKEN INCOMING VALIDATION *@
@if (IsResetToken)
{

    <h3>Reset Password</h3>
    <div>
        Please enter a new Password bellow;
    </div>
    <br />
    <EditForm Model="@validatePasswordModel" OnValidSubmit="@SetResetPassword">
        <DataAnnotationsValidator />
        <ValidationSummary />

        <div class="field">
            <label class="label">Password</label>
            <div class="control">
                <InputText id="password" class="input" type="password" @bind-Value="@validatePasswordModel.Password"></InputText>
            </div>
        </div>
        <div class="field">
            <label class="label">Confirm password</label>
            <div class="control">
                <InputText id="cpassword" class="input" type="password" @bind-Value="@validatePasswordModel.ConfirmPassword"></InputText>
            </div>
        </div>
        <div class="field">
            <div class="control">
                <button type="submit" class="button is-primary">Set Password</button>
            </div>
        </div>
    </EditForm>
    <br />
    <a href="/">Back</a>

}
else
{

    @* THIS IS THE PART HANDLING THE RESET TOKEN OUTGOING VALIDATION *@

    @if (IsResetSend)
    {
        <h3>Reset Password</h3>
        <div>
            A mail has been send with a password reset link, please click this link to set a new password.
        </div>
        <br />
        <a href="/">Back</a>
    }
    else
    {
        <h3>Reset Password</h3>
        <EditForm Model="requestPasswordModel" OnValidSubmit="@SendResetPassword">
            <div class="field">
                <label class="label">E-mail</label>
                <div class="control">
                    <InputText id="email" class="input" type="email" @bind-Value="@requestPasswordModel.Email"></InputText>
                </div>
            </div>
            <div class="field">
                <div class="control">
                    <button type="submit" class="button is-primary">Sign in</button>
                </div>
            </div>
        </EditForm>
    }
}

@code {

    InputModel requestPasswordModel = new InputModel();
    ResetPasswordModel validatePasswordModel = new ResetPasswordModel();

    string email = "";
    string token = "";

    bool IsResetSend = false;
    bool IsResetToken = false;

    protected override void OnInitialized()
    {

        GetHttpParameters();

    }

    public void GetHttpParameters()
    {
        var uriBuilder = new UriBuilder(navigationManager.Uri);
        var httpQuery = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);

        email = httpQuery["email"] ?? "";
        token = httpQuery["token"] ?? "";

        if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(token))
        {
            IsResetToken = true;

        }
    }

    public async void SendResetPassword()
    {
        List<string> mailTo = new List<string>();

        string passwordResetToken;
        string passwordResetUrl;

        var user = await userManager.FindByEmailAsync(requestPasswordModel.Email);

        if (user != null)
        {
            passwordResetUrl = navigationManager.BaseUri;

            passwordResetToken = await userManager.GeneratePasswordResetTokenAsync(user);

            passwordResetToken = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(passwordResetToken));

            passwordResetUrl = "https://localhost:44384/ResetPassword?email=" + user.Email + "&token=" + passwordResetToken;

            mailTo.Add(requestPasswordModel.Email);

            //Send mail with the relevant token
            Webco.Email.Entities.EmailObject emailObject = new Webco.Email.Entities.EmailObject();
            emailObject.Email_To = mailTo;
            emailObject.Email_Subject = "Password Reset Webco !";
            emailObject.Email_Message = $"Hy There, <br> Please click this link to reset your password : <br><a href='{HtmlEncoder.Default.Encode(passwordResetUrl)}'> clikcing here </a>.";
            emailObject.SendEmail(emailObject);

            IsResetSend = true;
        }
        else
        {
            //it's a lie
            IsResetSend = true;
        }
    }

    public async void SetResetPassword()
    {
        List<string> mailTo = new List<string>();

        var user = await userManager.FindByEmailAsync(email);

        if (user != null)
        {
            token = System.Text.Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(token));

            var result = await userManager.ResetPasswordAsync(user, token, validatePasswordModel.ConfirmPassword);

            if (result.Succeeded)
            {

                mailTo.Add(email);

                //Send mail with the relevant token
                Webco.Email.Entities.EmailObject emailObject = new Webco.Email.Entities.EmailObject();
                emailObject.Email_To = mailTo;
                emailObject.Email_Subject = "Password Reset Webco !";
                emailObject.Email_Message = $"Hy There, <br> You password was just reset at webco. Not you ? <br> Contact webco for support.";
                emailObject.SendEmail(emailObject);

                navigationManager.NavigateTo("/LoginUserResetPasswordComplete", true);
            }
            else
            {
                navigationManager.NavigateTo("/LoginUserResetPasswordError", true);
            }
        }
        else
        {
            navigationManager.NavigateTo("/LoginUserResetPasswordError",true);
        }

    }

    public class InputModel
    {
        [Required]
        [EmailAddress]
        public string Email { get; set; }
    }

    public class ResetPasswordModel
    {
        [Required]
        public string Password { get; set; }
        [Required]
        [Compare(nameof(Password))]
        public string ConfirmPassword { get; set; }
    }

}


来源: stackexchange

问:
Mail routing with mailgun
I'm setting mailgun route to xx@me.com to forward an email to a server at http://xxx:7000/reply.
I tested already the email route and it's fine as well as the server is up both in browser and using curl. However sending an email to xx@me.com still nothing happens.

There is already a similar question but nobody answered:
Can't recieve incoming mail with Mailgun

答: Another reason for this error code may well be that you are trying to send stuff over SMTP whereas you've indicated on the sending properties of mailgun settings for your domain that you want to use the API...</p>

ContentLicense: CC BY-SA 3.0

Title: Mail routing with mailgun

ContentLicense: CC BY-SA 4.0


问:
Image display issue with PHP
I'm currently trying to display an image using PHP GD functions on a local website hosted by Apache (XAMPP). However, my navigator (Google chrome) displays a black screen with a white square instead of the red string. When I delete the "header(...)" line, it displays the image as text.
Does the error come from the Apache server ? Or from the "header(...)" line ? Or from somewhere else ?

Thanks a lot

<!DOCTYPE html>

 <meta http-equiv="Content-type" content="text/html" charset="UTF-8" />
 <title> Title </title>

<?php
  header("Content-Type: image/png");

  $im = imagecreatetruecolor(120, 20);
  $text_color = imagecolorallocate($im, 233, 14, 91);
  imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

  imagepng($im);

?>

```

答:
Just have a look at PHP Doc for header():

https://www.php.net/manual/en/function.header.php

"Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file."

Don't output HTML tags (nor whatever else) before calling header()

Title: Image display issue with PHP


问:
Trying to incorporate kitchen sink grid sample in Local app in Sencha/Extjs
Trying to incorporate kitchen sink grid sample in Local app in Sencha/Extjs

https://examples.sencha.com/extjs/6.2.0/examples/kitchensink/#array-grid

When I run sencha app watch open chrome tools inspector, I get this error:
Uncaught TypeError: Cannot read property 'isBufferedStore' of undefined

答: "Uncaught TypeError: Cannot read property 'isBufferedStore' of undefined" means the store in grid is undefined. Maybe you are using a store ID which is not registered as a global store..</p>


问:
IE CSS issue when hitting the browsers back button
I am having an issue with IE (9 in this case) where I have uploaded a new CSS file for a page and it works just fine when I go to the page.  The problem I am having is when I browse to any another page, if I then hit the back button it renders my page using a previous version of the CSS file.  I verified this using the F12 tool to see that the css file only had the entries from the previous version.  In this case, i was styling 'ol' and 'li' elements if that matters.

Is there anything I can do to make IE load the most current version of a css file when the browsers back button is used?

Again, the page loads perfectly if I browse to it in any "forward" manner, I also have my browser set to check for new versions every visit.  Its when I hit the back button it has problems. Also every other browser ive tested has no problem using the back button.

答:
you could add a parameter when calling the stylsheet...

```<code>?version=2
</code>```

...after you .css extension

Body:
you could add a parameter when calling the stylsheet...

?version=2

...after you .css extension


问:
How to handle NSNull values
In Objective C, a common practice is to often forgo checking for nil, instead relying on the fact that messaging nil silently fails.

For example, to validate a string:

```<code>if ([myString length] > 1) { // Short and sweet
</code>```

If myString is nil, this check will fail - as intended. It's a huge improvement over what one may assume would be the correct implementation, explicitly checking for nil:

```<code>if (myString && [myString length] > 1) { // Redundant nil check
</code>```

However, particularly in the case of a web API, myString could conceivable equal [NSNull null] - similar to nil, but with different behavior. Of primary concern, is that messaging NSNull causes an exception. For example, our short simple solution from earlier will cause an exception:

```<code>// Causes an exception, because [NSNull null] is an object
NSString *myString = (id)[NSNull null];
if ([myString length] > 1) {
</code>```

To further complicate things, a simple nil check will actually pass because [NSNull null] is a valid object:

```<code>NSString *myString = (id)[NSNull null];
if (myString) { // Evals to YES
</code>```

So, the only way to be completely safe is to both check for NSNull and do your regular implicit nil check, by calling a method:

```<code>if (myString != (id)[NSNull null] && [myString length] > 1) { // Short and sweet
</code>```

My Question: is this really necessary? Is there a more concise option with less duplicate code, that I've overlooked? Are my conclusions, in fact, correct?

答:
Another way to approach this is to use a Category:

@interface NSNull (Utilities)

- (NSString *)stringValue;

@end

@implementation NSNull (Utilities)

- (NSString *)stringValue
{
    return nil;
}

@end
```

<p>And then simply:</p>

<pre class="lang-c prettyprint-override"><code>[myDictionary[@"key"] stringValue] // returns nil for NSNull values
</code>```

Title: How to handle NSNull values

Body:
In Objective C, a common practice is to often forgo checking for nil, instead relying on the fact that messaging nil silently fails.

For example, to validate a string:

if ([myString length] > 1) { // Short and sweet

If myString is nil, this check will fail - as intended. It's a huge improvement over what one may assume would be the correct implementation, explicitly checking for nil:

if (myString && [myString length] > 1) { // Redundant nil check

However, particularly in the case of a web API, myString could conceivable equal [NSNull null] - similar to nil, but with different behavior. Of primary concern, is that messaging NSNull causes an exception. For example, our short simple solution from earlier will cause an exception:

// Causes an exception, because [NSNull null] is an object
NSString *myString = (id)[NSNull null];
if ([myString length] > 1) {

To further complicate things, a simple nil check will actually pass because [NSNull null] is a valid object:

NSString *myString = (id)[NSNull null];
if (myString) { // Evals to YES

So, the only way to be completely safe is to both check for NSNull and do your regular implicit nil check, by calling a method:

if (myString != (id)[NSNull null] && [myString length] > 1) { // Short and sweet

My Question: is this really necessary? Is there a more concise option with less duplicate code, that I've overlooked? Are my conclusions, in fact, correct?

Body:
Another way to approach this is to use a Category:

@interface NSNull (Utilities)

- (NSString *)stringValue;

@end

@implementation NSNull (Utilities)

- (NSString *)stringValue
{
    return nil;
}

@end

And then simply:

[myDictionary[@"key"] stringValue] // returns nil for NSNull values


问:
How to run scripts simultaneously with Puppeteer/Javascript?
I am using puppeteer to do some testing.

No code written because I don't even know how to approach this.

```<code>• I have a list of 10 IDs inside an array

• For each ID -  a new page/tab is opened

• I want to run the script for each page/ tab without having to wait for the previous page/tab
to finish before starting the next. Hence the simultaneous execution.
</code>```

So 10 pages will be running the same script at the same time?

Is this possible with Javascript and puppeteer?

答:
You might want to check out puppeteer-cluster (I'm the author of that library), which supports your use case. The library runs tasks in parallel, but also takes care of error handling, retrying and some other things.

You should also keep in mind that opening 10 pages for 10 URLs is quite costly in terms of CPU and memory. You can use puppeteer-cluster to use a pool of browsers or pages instead.

Code Sample

You can see a minimal example below. It's also possible to use the library in more complex settings.

const { Cluster } = require('puppeteer-cluster');

(async () => {
  const cluster = await Cluster.launch({
    concurrency: Cluster.CONCURRENCY_PAGE, // use one browser per worker
    maxConcurrency: 4, // Open up to four pages in parallel
  });

  // Define a task to be executed for your data, this function will be run for each URL
  await cluster.task(async ({ page, data: url }) => {
    await page.goto(url);
    // ...
  });

  // Queue URLs (you can of course read them from an array instead)
  cluster.queue('http://www.google.com/');
  cluster.queue('http://www.wikipedia.org/');
  // ...

  // Wait for cluster to idle and close it
  await cluster.idle();
  await cluster.close();
})();
```

Body:
I am using puppeteer to do some testing.

No code written because I don't even know how to approach this.

• I have a list of 10 IDs inside an array

• For each ID -  a new page/tab is opened

• I want to run the script for each page/ tab without having to wait for the previous page/tab
to finish before starting the next. Hence the simultaneous execution.

So 10 pages will be running the same script at the same time?

Is this possible with Javascript and puppeteer?


答:
Assuming the separator in the column is a whitespace, you can use str.split with expand=True:

```<code>df[['col1','col2','col3']] = df['column'].str.split(expand=True)
</code>```

Title: Data frame multiple columns splitting

Body:
I have a pandas dataframe of the following format.

0     06-10-2000 Deposit $40.00
1  09-12-2002 Withdraw $1000.00
2     27-06-2001 Deposit $47.00
3   07-12-2021 Withdraw $100.00
4    06-10-2022 Deposit $120.00
5     06-10-2000 Deposit $40.00
6    09-12-2024 Withdraw $50.00

How do I split each row in to 3 columns.
Ideal output wanted:

      Date       Status   Amount
0     06-10-2000 Deposit $40.00
1  09-12-2002 Withdraw $1000.00
2     27-06-2001 Deposit $47.00
3   07-12-2021 Withdraw $100.00
4    06-10-2022 Deposit $120.00
5     06-10-2000 Deposit $40.00
6    09-12-2024 Withdraw $50.00

Body:
Assuming the separator in the column is a whitespace, you can use str.split with expand=True:

df[['col1','col2','col3']] = df['column'].str.split(expand=True)


问:
how can i extract this value from a website, with python, selenium and chromedriver
```<code><div class="flexible row ng-scope">
    <!-- ngRepeat: graph in graphs track by $index --><figure class="figure-gauge flexible column ng-scope" data-ng-repeat="graph in graphs track by $index">
        <figcaption class="rigid">
            <div class="data-value">
                <b class="ng-binding">
                    334
                </b>
            </div>
</code>```

I need to extract the value (334) that appears, i take this from Chrome Web Inspector . I am using python and selenium, I have tried with many codes but none has worked for me, I appreciate any help.

I try whit this:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options

DRIVER_PATH = r'C:\chromedriver.exe'
options = Options()
options.headless = True
options.add_argument("--window-size=1920,1200")

driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH)
driver.get("https://iot.app.initialstate.com/embed/#/tiles/bkt_kb448kawjvmhe")
data = driver.find_element_by_class_name('ng-binding')
print
driver.quit()
</code>```

Error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".ng-binding"}
(Session info: headless chrome=83.0.4103.61)

Selenium 3.141.0
Python 3.8

答:
You need to provide some sleep() to load the value on the graph and then use below xpath to get the value.

```<code>driver.get("https://iot.app.initialstate.com/embed/#/tiles/bkt_kb448kawjvmhe")
time.sleep(3)
print(driver.find_element_by_xpath("(//div[@class='data-value']/b)[last()]").text.strip())
</code>```

Body:
                    334

I need to extract the value (334) that appears, i take this from Chrome Web Inspector . I am using python and selenium, I have tried with many codes but none has worked for me, I appreciate any help.

I try whit this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

DRIVER_PATH = r'C:\chromedriver.exe'
options = Options()
options.headless = True
options.add_argument("--window-size=1920,1200")

driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH)
driver.get("https://iot.app.initialstate.com/embed/#/tiles/bkt_kb448kawjvmhe")
data = driver.find_element_by_class_name('ng-binding')
print
driver.quit()

Error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".ng-binding"}
(Session info: headless chrome=83.0.4103.61)

Selenium 3.141.0
Python 3.8

Body:
You need to provide some sleep() to load the value on the graph and then use below xpath to get the value.

driver.get("https://iot.app.initialstate.com/embed/#/tiles/bkt_kb448kawjvmhe")
time.sleep(3)
print(driver.find_element_by_xpath("(//div[@class='data-value']/b)[last()]").text.strip())


问:
How to stop a setTimeout loop?
I'm trying to build a loading indicator with a image sprite and I came up with this function

```<code>function setBgPosition() {
   var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
       Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<numbers.length)
        {
            setTimeout(run, 200);
        }else
        {
            setBgPosition();
        }
    }
    setTimeout(run, 200);
}
</code>```

so the out put is looks like this

http://jsfiddle.net/TTkre/

I had to use setBgPosition(); inside else to keep this running in a loop so now my problem is how to stop this loop once I want [load finished]?

答:
Try something like this in case you want to stop the loop from inside the function:

```<code>let timer = setInterval(function(){
  // Have some code to do something

  if(/*someStopCondition*/){
    clearInterval(timer)
  }
},1000);

</code>```

You can also wrap this inside a another function, just make sure you have a timer variable and use clearInterval(theTimerVariable) to stop the loop

Title: How to stop a setTimeout loop?

Body:
I'm trying to build a loading indicator with a image sprite and I came up with this function

function setBgPosition() {
   var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
       Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<numbers.length)
        {
            setTimeout(run, 200);
        }else
        {
            setBgPosition();
        }
    }
    setTimeout(run, 200);
}

so the out put is looks like this

http://jsfiddle.net/TTkre/

I had to use setBgPosition(); inside else to keep this running in a loop so now my problem is how to stop this loop once I want [load finished]?

Body:
Try something like this in case you want to stop the loop from inside the function:

let timer = setInterval(function(){
  // Have some code to do something

  if(/*someStopCondition*/){
    clearInterval(timer)
  }
},1000);

You can also wrap this inside a another function, just make sure you have a timer variable and use clearInterval(theTimerVariable) to stop the loop


问:
How to make cells in UITableView not turn blue?
I am using a UITableView and the cells I am using in this view should do nothing when I click them. I can't turn off UserInteraction though because then I am not able to click on the accessory (detailDisclosureButton). So how can I make them stop turning blue and still allow them to click on the accessory?</p>

答:
When you're generating the UITableViewCell (within the UITableView's - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method call), simply set the selectionStyle property to UITableViewCellSelectionStyleNone.

Set the UITableViewCell Class Reference for more information.


问:
EMV card & APDU command to get the track 2
I trying to get the PAN from my card. I read a lot of topic about that, but I still understand :'(

I understand I have to find the AID I tried :

00A404000E315041592E5359532E4444463031

Thats works, but I don't really get some interesting informations ... If I correctly understand I have to find the 94 Application File Locator (AFL) (16 Byte) to be able to read the data...

Do i have to try another AID until I find the AFL ?

Thanks

答:
Track2(tag 57) is usually returned in in response to READ RECORDs. To issue READ RECORDs you need to get the AFL first. AFL is returned in response to GET PO.
In VISA contactless you will get track in GET PO itself and you will get AFL only if ODA is required.</p>


问:
Is it possible to use React Hooks outside of functional component, or i have to use mobx or redux?
I am new to React, and when I was reading about the docs, I found there were two ways to implement React components, functional-based and class-based. I know before React 16.8 it's not possible to manage state in functional components, but after that there is React Hooks.

The problem is, there seems to be one restriction for React Hooks, they can only be used inside functional components. Take a server-client as an example, which needs to change an isAuthenticated state while 401 received.

```<code>//client.js
import { useUserDispatch, signOut } from "auth";

export function request(url, args) {
  var dispatch = useUserDispatch();
  return fetch(url, args).then(response => {
  if (response.status === 401) {
    logout(dispatch);
  }
}
);

//auth.js
import React from "react";

var UserStateContext = React.createContext();
var UserDispatchContext = React.createContext();

function userReducer(state, action) {
  ...
}

function UserProvider({ children }) {
  var [state, dispatch] = React.useReducer(userReducer, {
    isAuthenticated: false,
  });

  return (
    <UserStateContext.Provider value={state}>
      <UserDispatchContext.Provider value={dispatch}>
        {children}
      </UserDispatchContext.Provider>
    </UserStateContext.Provider>
  );
}

function useUserState() {
  return React.useContext(UserStateContext);
}

function useUserDispatch() {
  return React.useContext(UserDispatchContext);
}

function signOut(dispatch) {
  dispatch({});
}

export { UserProvider, useUserState, useUserDispatch, loginUser, signOut };

</code>```

The client code above will produce error "Hooks can only be called inside of the body of a function component".
So maybe I have to move line var dispatch = useUserDispatch() upward to the component where request is called, and pass dispatch as props to request.
I feel this is not right, no only request is forced to care about some meaningless(to it) dispatch, but also this dispatch will spread everywhere a component needs to request.

For class-based components, this.state doesn't solve this problem either, but at least I can use mobx.

So are there some other ideal ways to solve this problem?

答:
Mobx and hooks are very similar in implementation. Both use a render context that is in a sense "global". React ties that render context to the component render context, but Mobx keeps that render context separate. Therefore that means that hooks have to be created within a component render lifecycle (but can sometimes be called outside that context). Mobx-react ties the Mobx render lifecycle to the react lifecycle, triggering a react re-render when observed objects change. So Mobx-react nests the react render context within the Mobx render context.

React internally keeps tracks of hooks by the number of times and order the hook is called within a component render cycle. Mobx, on the other hand, wraps any "observable" object with a proxy that lets the Mobx context know if any of its properties were referenced during a Mobx "run context" (an autorun call, essentially). Then when a property is changed, Mobx knows what "run contexts" care about that property, and re-runs those contexts. This means that anywhere you have access to an observable object you can change a property on it and Mobx will react to it.

For react state hooks, react provides a custom setter function for a state object. React then uses calls to that setter to know when it needs to re-render a component. That setter can be used anywhere, even outside a React render, but you can only create that hook inside a render call, because otherwise react has no way to tell what component to tie that hook to. Creating a hook implicitly connects it to the current render context, and that's why hooks have to be created inside render calls: hook builders have no meaning outside a render call, because they have no way to know what component they are connected to -- but once tied to a component, then they need to be available anywhere. In fact, actions like onClick or a fetch callback don't occur within a render context, although the callback is often created within that context - the action callback happens after react finishes rendering (because javascript is single threaded, so the render function must complete before anything else happens).

Body:
I am new to React, and when I was reading about the docs, I found there were two ways to implement React components, functional-based and class-based. I know before React 16.8 it's not possible to manage state in functional components, but after that there is React Hooks.

The problem is, there seems to be one restriction for React Hooks, they can only be used inside functional components. Take a server-client as an example, which needs to change an isAuthenticated state while 401 received.

//client.js
import { useUserDispatch, signOut } from "auth";

export function request(url, args) {
  var dispatch = useUserDispatch();
  return fetch(url, args).then(response => {
  if (response.status === 401) {
    logout(dispatch);
  }
}
);

//auth.js
import React from "react";

var UserStateContext = React.createContext();
var UserDispatchContext = React.createContext();

function userReducer(state, action) {
  ...
}

function UserProvider({ children }) {
  var [state, dispatch] = React.useReducer(userReducer, {
    isAuthenticated: false,
  });

  return (
    <UserStateContext.Provider value={state}>
      <UserDispatchContext.Provider value={dispatch}>
        {children}
      </UserDispatchContext.Provider>
    </UserStateContext.Provider>
  );
}

function useUserState() {
  return React.useContext(UserStateContext);
}

function useUserDispatch() {
  return React.useContext(UserDispatchContext);
}

function signOut(dispatch) {
  dispatch({});
}

export { UserProvider, useUserState, useUserDispatch, loginUser, signOut };

The client code above will produce error "Hooks can only be called inside of the body of a function component".
So maybe I have to move line var dispatch = useUserDispatch() upward to the component where request is called, and pass dispatch as props to request.
I feel this is not right, no only request is forced to care about some meaningless(to it) dispatch, but also this dispatch will spread everywhere a component needs to request.

For class-based components, this.state doesn't solve this problem either, but at least I can use mobx.

So are there some other ideal ways to solve this problem?


问:
Cosmos DB - ORDER BY clause only returns 1 document
I have about 500 documents with the same value for the partitionkey (/userprofileId) in one container and as soon as I add an ORDER BY clause to the SQL the results are incorrect.

SELECT * FROM c where c.userprofileId='LogSmsOutbound' returns all documents

SELECT * FROM c where c.userprofileId='LogSmsOutbound' ORDER BY c.MessageDTCreated returns only 1 document

SELECT * FROM c where c.userprofileId='LogSmsOutbound' ORDER BY c.MessageDTCreated OFFSET 0 LIMIT 5 returns ZERO documents

In summary it seems that the indexing policy needs to be changed, but before I do that I would need to know the justification, so could anyone provide information please?

It would seem strange that I need to change the indexing policy since I'm using the default one at the time of creating the container:

```<code>{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/*",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                },
                {
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                }
            ]
        }
    ],
    "excludedPaths": [
        {
            "path": "/\"_etag\"/?"
        }
    ]
}
</code>```

Sample document

```<code>    {
        "type": "LogSmsOutbound",
        "id": "SMce682b0a9d0f404682d59230d573fd5a23",
        "userprofileId": "LogSmsOutbound",
        "dtupdated": "2020-06-01T17:05:02.267599+00:00",
        "fromNr": "+XXXXXXXXXXXXXX",
        "status": "delivered",
        "toNr": "+YYYYYYYYYYY",
        "userIds": [
            "5FB72F43243245D5F14B0634232432A63EBA9C217E3299"
        ],
        "ttl": 2592000,
        "MessageDTCreated": "2020-06-01T17:02:51+00:00",
        "MessageDTSent": "2020-06-01T17:02:51+00:00",
    }
</code>```

I'm speculating that the indexing policy is incorrect and that the following section needs to be removed:

```<code>            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                },
                {
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                }
            ]
</code>```

答:
Your container needs to have a composite index defined for this type of query to work properly. You can see an example index policy for defining a composite index in Composite indexing policy examples.

Thanks.

Body:
I have about 500 documents with the same value for the partitionkey (/userprofileId) in one container and as soon as I add an ORDER BY clause to the SQL the results are incorrect.

SELECT * FROM c where c.userprofileId='LogSmsOutbound' returns all documents

SELECT * FROM c where c.userprofileId='LogSmsOutbound' ORDER BY c.MessageDTCreated returns only 1 document

SELECT * FROM c where c.userprofileId='LogSmsOutbound' ORDER BY c.MessageDTCreated OFFSET 0 LIMIT 5 returns ZERO documents

In summary it seems that the indexing policy needs to be changed, but before I do that I would need to know the justification, so could anyone provide information please?

It would seem strange that I need to change the indexing policy since I'm using the default one at the time of creating the container:

{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/*",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                },
                {
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                }
            ]
        }
    ],
    "excludedPaths": [
        {
            "path": "/\"_etag\"/?"
        }
    ]
}

Sample document

    {
        "type": "LogSmsOutbound",
        "id": "SMce682b0a9d0f404682d59230d573fd5a23",
        "userprofileId": "LogSmsOutbound",
        "dtupdated": "2020-06-01T17:05:02.267599+00:00",
        "fromNr": "+XXXXXXXXXXXXXX",
        "status": "delivered",
        "toNr": "+YYYYYYYYYYY",
        "userIds": [
            "5FB72F43243245D5F14B0634232432A63EBA9C217E3299"
        ],
        "ttl": 2592000,
        "MessageDTCreated": "2020-06-01T17:02:51+00:00",
        "MessageDTSent": "2020-06-01T17:02:51+00:00",
    }

I'm speculating that the indexing policy is incorrect and that the following section needs to be removed:

            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                },
                {
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                }
            ]


问:
How to publicly access an AWS EC2 instance that contains an SSL redirect?
I have a Node/Express server running on an EC2 instance that is maintained by Elastic Beanstalk (single instance no load balancer).
I am struggling with implementing a correct SSL redirect that works with EC2.

The SSL redirect is as follows:

```<code>const httpsOptions = {
  key: fs.readFileSync('/local/ssl/key.pem'),
  cert: fs.readFileSync('/local/ssl/cert.pem'),
  passphrase: '*****'
}

http.createServer(function (req, res) {
  let httpsHost = req.headers.host.replace('8081', '8443');
  res.writeHead(301, { "Location": "https://" + httpsHost + req.url });
  res.end();
}).listen(8081);

https.createServer(httpsOptions, app).listen(8443)

</code>```

This works great locally, but when I deploy to my EC2 instance and try to access the site, I get:

Here is a picture of my inbound rules as well:

Do I have the ports configured incorrectly? I cannot use port 80 and port 443 because it requires root permissions, and I won't run my server with root permissions.

答:
When I try to access your host on port 443 I get a response, which means the host is accessible. When I try to access your server on port 8443, I receive a "Connection timed out", what could possibly be caused by wrong firewall (ie. security group) settings.

Your server instance listens to port 8443 and 8081, but in your security group rules the ports 443 and 80 are configured. If you cannot use 443/80 as you wrote, please edit the inbound rules to allow traffic from ports 8443/8081 instead.

Body:
I have a Node/Express server running on an EC2 instance that is maintained by Elastic Beanstalk (single instance no load balancer).
I am struggling with implementing a correct SSL redirect that works with EC2.

The SSL redirect is as follows:

const httpsOptions = {
  key: fs.readFileSync('/local/ssl/key.pem'),
  cert: fs.readFileSync('/local/ssl/cert.pem'),
  passphrase: '*****'
}

http.createServer(function (req, res) {
  let httpsHost = req.headers.host.replace('8081', '8443');
  res.writeHead(301, { "Location": "https://" + httpsHost + req.url });
  res.end();
}).listen(8081);

https.createServer(httpsOptions, app).listen(8443)

This works great locally, but when I deploy to my EC2 instance and try to access the site, I get:

Here is a picture of my inbound rules as well:

Do I have the ports configured incorrectly? I cannot use port 80 and port 443 because it requires root permissions, and I won't run my server with root permissions.


问:
Apache error log showing very strange problems
I was wondering if anyone could point out what is causing the problem in the screenshot attached. It has happened a couple of times with different images. I can't see what is causing it.

The machine is my development machine.

I was hoping to post this on serverfault but I can't add the image I need.

答:
Not enough info yet, so just some debugging steps.

Try uploading it to a different machine and see if you get these same messages.

Check you don't have any Javascript doing anything with image urls - to me it looks like some loop somewhere might be going 'wacko', but could be client or server side.

Use tail -F on it in the terminal and refresh the page to see if the appearance of those entries coincides with the loading of the page.

Edit: maybe also have Firebug/etc open when you refresh the page with their Network panels open to see if you really are sending those requests. Really just want to find if it's a client or server issue to begin with.


问:
Angular CLI build without index.html
All our Angular applications are bootstrapped in other applications (.jsp files which load the javascript files and include the <app-root> tag), so we have no need for an index.html**.

However when I remove the index property from our angular.json it gives me the error:

Data path "" should have required property 'index'.

If I leave it empty it does build but I get the error:

...

   95% emitting index-html-webpack-pluginEISDIR: illegal operation on a directory, read

  Error: EISDIR: illegal operation on a directory, read

How can I perform an ng build without the index.html?

** our deploy process now actually copies the index.html to our CDN which is unwanted since we don't want to serve these files to the end users at all, the index.html is only used for developers during ng serve

答:
In case anyone is still having the same issue, this is how I solved it.

In your angular.json:

```<code>"architect": {
  "build": {
    ...
    "configurations": {
      "production": {
        "index": "", // Do not copy index.html
        ...
</code>```

ng build --prod will not copy the HTML file, while ng build and ng serve will keep using it as expected.

Title: Angular CLI build without index.html

Body:
In case anyone is still having the same issue, this is how I solved it.

In your angular.json:

"architect": {
  "build": {
    ...
    "configurations": {
      "production": {
        "index": "", // Do not copy index.html
        ...

ng build --prod will not copy the HTML file, while ng build and ng serve will keep using it as expected.


问:
matplotlib animation with scatter
I have the following code:

```<code>sim = simulator()
fig, ax = plt.subplots()
scat = ax.scatter(sim.XY[:,0],sim.XY[:,1])

def animate(i):
    sim.run()
    scat.set_offsets(sim.XY)  # update the data.
    return scat

ani = FuncAnimation(fig, animate, interval=10, blit=True, save_count=50)
</code>```

The "sim" object method "sim.run()" updates sim.XY which is (100,2) array.

After my 3rd line I get a scatter plot as expected.

But when I try to animate (from line 5 downwards) I get a error message saying. Can someone help please:

```<code>Traceback (most recent call last):
  File "C:\Users\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 216, in process
    func(*args, **kwargs)
  File "C:\Users\anaconda3\lib\site-packages\matplotlib\animation.py", line 953, in _start
    self._init_draw()
  File "C:\Users\\anaconda3\lib\site-packages\matplotlib\animation.py", line 1732, in _init_draw
    self._draw_frame(next(self.new_frame_seq()))
  File "C:\Users\anaconda3\lib\site-packages\matplotlib\animation.py", line 1761, in _draw_frame
    key=lambda x: x.get_zorder())

TypeError: 'PathCollection' object is not iterable
</code>```

答: What I observed is If I set blit=True the animation does not work and I get the error. Without the parameter the animation works. Can someone explain please what that parameter is doing</p>

Title: matplotlib animation with scatter

Body:
I have the following code:

sim = simulator()
fig, ax = plt.subplots()
scat = ax.scatter(sim.XY[:,0],sim.XY[:,1])

def animate(i):
    sim.run()
    scat.set_offsets(sim.XY)  # update the data.
    return scat

ani = FuncAnimation(fig, animate, interval=10, blit=True, save_count=50)

The "sim" object method "sim.run()" updates sim.XY which is (100,2) array.

After my 3rd line I get a scatter plot as expected.

But when I try to animate (from line 5 downwards) I get a error message saying. Can someone help please:

Traceback (most recent call last):
  File "C:\Users\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 216, in process
    func(*args, **kwargs)
  File "C:\Users\anaconda3\lib\site-packages\matplotlib\animation.py", line 953, in _start
    self._init_draw()
  File "C:\Users\\anaconda3\lib\site-packages\matplotlib\animation.py", line 1732, in _init_draw
    self._draw_frame(next(self.new_frame_seq()))
  File "C:\Users\anaconda3\lib\site-packages\matplotlib\animation.py", line 1761, in _draw_frame
    key=lambda x: x.get_zorder())

TypeError: 'PathCollection' object is not iterable


问:
Uncaught TypeError: Cannot read property 'innerHTML' of null at text inside this blog website I'm trying to write

var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //problem
  document.createElement("p").id = y;
  //
  document.getElementById(y).innerHTML = blogtext;
  //document.write("
"+blogtext+"
");
  x = x + 1;
}
```

When I run this code inside an HTML file the error: Uncaught TypeError occurs, the code is supposed to create a new paragraph tag whose content is the text inputted by the user inside the text area and each paragraph would have a different id as x increases.
Sorry, I'm new to coding this is one of my school's projects.

答:
You are not creating and appending the element coreectly

    var x = 0;

    function text() {
      var blogtext = document.getElementById("Textarea").value;
      var y = "p" + String(x);
      console.log(typeof y);

     var elem = document.createElement("p")
     document.body.append(elem)
     elem.id = y

     elem.innerHTML = blogtext;

      x = x + 1;
      console.log()
    }
```

Body:
var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //problem
  document.createElement("p").id = y;
  //
  document.getElementById(y).innerHTML = blogtext;
  //document.write("
"+blogtext+"
");
  x = x + 1;
}

When I run this code inside an HTML file the error: Uncaught TypeError occurs, the code is supposed to create a new paragraph tag whose content is the text inputted by the user inside the text area and each paragraph would have a different id as x increases.
Sorry, I'm new to coding this is one of my school's projects.


问:
Kendo-dropdownlist for VUE from array of objects shows "NO DATA FOUND" message
I'm having trouble getting the kendo-dropdownlist for VUE working inside a custom component. The component renders, there's no errors in the console, but no options are shown in the list.

I've broken the code down into this bit:

```<code><template>
  <div>
    <kendo-dropdownlist
      :data-items="months"
      :text-field="'text'"
      :data-item-key="'value'"
    ></kendo-dropdownlist>
  </div>
</template>
<script>
export default {
  name: "demo",
  data() {
    return {
      months: [
        {
          text: "January",
          value: 1,
          numDays: 31
        },
        {
          text: "February",
          value: 2,
          numDays: 28
        },
        {
          text: "March",
          value: 3,
          numDays: 31
        }
      ]
    };
  }
};
</script>
</code>```

Does anyone see what I'm doing wrong?

答:
You are writting wrong props, see docs:</p>

```<code><kendo-dropdownlist
    :data-source="months"
    :data-text-field="'text'"
    :data-value-field="'value'">
</kendo-dropdownlist>
</code>```

Body:
I'm having trouble getting the kendo-dropdownlist for VUE working inside a custom component. The component renders, there's no errors in the console, but no options are shown in the list.

I've broken the code down into this bit:

<template>

    <kendo-dropdownlist
      :data-items="months"
      :text-field="'text'"
      :data-item-key="'value'"
    ></kendo-dropdownlist>

</template>

Does anyone see what I'm doing wrong?

Body:
You are writting wrong props, see docs:

<kendo-dropdownlist
    :data-source="months"
    :data-text-field="'text'"
    :data-value-field="'value'">
</kendo-dropdownlist>


问:
With EclipseLink, send a statement to the database on each new connection
I'm using EclipseLink to access an SQLite database. SQLite, by default, because of backwards compatibility, does not enforce foreign key constraints. Foreign keys constraints can be enabled on per-connection basis using connection.createStatement().execute("PRAGMA foreign_keys=ON").

When using JDBC, the following code does the trick:

```<code>Connection connection = DriverManager.getConnection("jdbc:sqlite:example.db");
Statement statement = connection.createStatement();
statement.execute("PRAGMA foreign_keys=ON");
// From now on, foreign key constraints are enforced on 'connection'
</code>```

How would I get the same effect with JPA/EclipseLink?

答:
You can use a native query.

em.createNativeQuery("PRAGMA foreign_keys=ON").executeUpdate();

You could also register an EclipseLink SessionEventListener in your persistence.xml to have this always done for every connection (postAcquireConnection event).

You may also be able to configure it on your database, to avoid having to execute this SQL on every connection.

Body:
I'm using EclipseLink to access an SQLite database. SQLite, by default, because of backwards compatibility, does not enforce foreign key constraints. Foreign keys constraints can be enabled on per-connection basis using connection.createStatement().execute("PRAGMA foreign_keys=ON").

When using JDBC, the following code does the trick:

Connection connection = DriverManager.getConnection("jdbc:sqlite:example.db");
Statement statement = connection.createStatement();
statement.execute("PRAGMA foreign_keys=ON");
// From now on, foreign key constraints are enforced on 'connection'

How would I get the same effect with JPA/EclipseLink?


问:
Renaming multiple columns using their index
How can i rename multiple columns of a dataframe using their index?
For example i want to rename the columns at positions 5,6,7,8 to 'five','six','seven','eight' respectively. I don't want to enter the keys in the dictionary individually.</p>

答:
In the case of already having a dictionary, you can use rename to map to the new axis values:

```<code>df = pd.DataFrame(columns=range(10))
d = {5:'five', 6:'six', 7:'seven', 8:'eight'}
df = df.rename(d, axis=1)
# Index([0, 1, 2, 3, 4, 'five', 'six', 'seven', 'eight', 9], dtype='object')
</code>```

Or, as @ch3ster points out, rename takes both index and column parameters allowing to rename both independently:

```<code>df = df.rename(columns=d)
</code>```

In the case you know the range of columns to rename, and have a list of new column names, you could build a dictionary as and rename with:

```<code>l = ['five', 'six', 'seven', 'eight', 'nine']
df = df.rename(columns=dict(zip(range(5,9), l)))
</code>```

Body:
In the case of already having a dictionary, you can use rename to map to the new axis values:

df = pd.DataFrame(columns=range(10))
d = {5:'five', 6:'six', 7:'seven', 8:'eight'}
df = df.rename(d, axis=1)
# Index([0, 1, 2, 3, 4, 'five', 'six', 'seven', 'eight', 9], dtype='object')

Or, as @ch3ster points out, rename takes both index and column parameters allowing to rename both independently:

df = df.rename(columns=d)

In the case you know the range of columns to rename, and have a list of new column names, you could build a dictionary as and rename with:

l = ['five', 'six', 'seven', 'eight', 'nine']
df = df.rename(columns=dict(zip(range(5,9), l)))


问:
How to target a Font Awesome 5 svg icon in JavaScript?
It renders after the page loads but I have no idea how I can target that. It's wrapped in an anchor tag and I tried to set the z-index of that anchor tag to like 9999 so it's goes above the icon and I can target that but it's not working either.</p>

```<code> <nav class="menu">
        <div class="icon-list">
          <a class="highlight" href="#szolgáltatásaim"><i class="far fa-bell"></i><span>Szolgáltatásaim</span></a>
          <a class="highlight" href="#rólam"><i class="far fa-user"></i><span>Rólam</span></a>
          <a class="highlight" href="#munkáim"
          ><i class="far fa-folder-open"></i><span>Munkáim</span></a>
        <a class="highlight" href="#oktatás">
        <i class="fas fa-chalkboard"></i><span>Oktatás</span></a>
        <a class="highlight" href="#árak"
        ><i class="far fa-bookmark"></i><span>Árak</span></a >
          <a class="highlight" href="#marketing"
            ><i class="far fa-lightbulb"></i><span>Marketing</span></a>

          <a class="highlight" href="#üzenet"
            ><i class="far fa-envelope"></i><span>Üzenet</span></a>
          </div>
       </nav>
</code>```

答:
I think your question needs more details so we can help you better. That being said, if you're trying to target multiple elements use class. If you're trying to target one specific element use ID. For this to work you'll need to add such properties to your  icons in your html code. Here's an example snippet. Is this what you need?

function changeAll() {
 var elements = document.querySelectorAll('.far,.fas'); // To target multiple elements use class
 for(var i = 0; i < elements.length; i++){
  elements[i].style.color = "red";
 }
}
function changeBell() {
  document.getElementById("bell").style.color = "green"; // To target one specific element use ID
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script async src="https://kit.fontawesome.com/0f49cf42f1.js" crossorigin="anonymous"></script>
<nav class="menu">
  <div class="icon-list">
    <i class="far fa-bell" id="bell"></i><span>Szolgáltatásaim</span>
    <i class="far fa-user"></i><span>Rólam</span>
    <i class="far fa-folder-open"></i><span>Munkáim</span>

      <i class="fas fa-chalkboard"></i><span>Oktatás</span>
    <i class="far fa-bookmark"></i><span>Árak</span></a >
          <i class="far fa-lightbulb"></i><span>Marketing</span>

    class="highlight" href="#üzenet"><i class="far fa-envelope"></i><span>Üzenet</span>
  </div>
</nav>
<br>
<button type="button" onclick="changeAll()">Change color of all icons</button>
<br>
<button type="button" onclick="changeBell()">Change color of bell only</button></code>```

Body:
It renders after the page loads but I have no idea how I can target that. It's wrapped in an anchor tag and I tried to set the z-index of that anchor tag to like 9999 so it's goes above the icon and I can target that but it's not working either.

          Szolgáltatásaim
          Rólam
          Munkáim

        Oktatás
        Árak
          Marketing

          Üzenet

Body:
I think your question needs more details so we can help you better. That being said, if you're trying to target multiple elements use class. If you're trying to target one specific element use ID. For this to work you'll need to add such properties to your <i> icons in your html code. Here's an example snippet. Is this what you need?

function changeAll() {
 var elements = document.querySelectorAll('.far,.fas'); // To target multiple elements use class
 for(var i = 0; i < elements.length; i++){
  elements[i].style.color = "red";
 }
}
function changeBell() {
  document.getElementById("bell").style.color = "green"; // To target one specific element use ID
}

<script async src="https://kit.fontawesome.com/0f49cf42f1.js" crossorigin="anonymous"></script>
<nav class="menu">
  <div class="icon-list">
    <a class="highlight" href="#szolgáltatásaim"><i class="far fa-bell" id="bell"></i><span>Szolgáltatásaim</span></a>
    <a class="highlight" href="#rólam"><i class="far fa-user"></i><span>Rólam</span></a>
    <a class="highlight" href="#munkáim"><i class="far fa-folder-open"></i><span>Munkáim</span></a>
    <a class="highlight" href="#oktatás">
      <i class="fas fa-chalkboard"></i><span>Oktatás</span></a>
    <a class="highlight" href="#árak"><i class="far fa-bookmark"></i><span>Árak</span></a >
          <a class="highlight" href="#marketing"
            ><i class="far fa-lightbulb"></i><span>Marketing</span></a>

    <a class="highlight" href="#üzenet"><i class="far fa-envelope"></i><span>Üzenet</span></a>
  </div>
</nav>
<br>
<button type="button" onclick="changeAll()">Change color of all icons</button>
<br>
<button type="button" onclick="changeBell()">Change color of bell only</button>


问:
MongoDB - Get a field from all matching objects in an array?
I have been migrationing mySQL to mongoDB.
I wanted to embed teaches, course table to instructor table.
I have a mongo database structure as follow.

```<code>{
"_id" : "14365",
"ID" : "14365",
"name" : "Lembr",
"dept_name" : "Accounting",
"salary" : 32241.56,
"teaches" : [
    {
        "ID" : "14365",
        "course_id" : "200",
        "sec_id" : "1",
        "semester" : "Spring",
        "year" : 2007.0,
        "course" : {
            "course_id" : "200",
            "title" : "The Music of the Ramones",
            "dept_name" : "Accounting",
            "credits" : 4.0
        }
    },
    {
        "ID" : "14365",
        "course_id" : "843",
        "sec_id" : "1",
        "semester" : "Fall",
        "year" : 2010.0,
        "course" : {
            "course_id" : "843",
            "title" : "Environmental Law",
            "dept_name" : "Math",
            "credits" : 4.0
        }
    }
]
</code>```

}

I want to query like the following SQL query.

```<code>SELECT name, title From instructor Natural join teaches Natural join course;
</code>```

How I can query in mongodb?

答:
You need to MongoDB's aggregation operator $reduce :

```<code>db.collection.aggregate([
  /** Using project stage we'll project only needed fields */
  {
    $project: {
      _id: 0, // _id is by default included - you need to exclude it
      name: 1,
      title: {
        $reduce: {
          input: "$teaches", // Iterate on objects of `teaches` array
          initialValue: [], // Initial value
          in: {
            $cond: [
              { $eq: ["$$this.course.dept_name", "$dept_name"] }, // condition to check
              {
                $concatArrays: ["$$value", ["$$this.course.title"]], // If condition is met push values to array
              },
              "$$value" // If not send same holding array back for this iteration
            ]
          }
        }
      }
    }
  }
]);
</code>```

Test : mongoplayground

Test : $filter: mongoplayground

Note :

We've used $reduce to bring all title's from different objects in teaches array to an array. You can also use $filter to achieve similar thing. If in any case if your title is just a single element in array (no duplicate dept_name in teaches array) then you can use $unwind or $arrayElemAt to convert title array to string.

Body:
I have been migrationing mySQL to mongoDB.
I wanted to embed teaches, course table to instructor table.
I have a mongo database structure as follow.

{
"_id" : "14365",
"ID" : "14365",
"name" : "Lembr",
"dept_name" : "Accounting",
"salary" : 32241.56,
"teaches" : [
    {
        "ID" : "14365",
        "course_id" : "200",
        "sec_id" : "1",
        "semester" : "Spring",
        "year" : 2007.0,
        "course" : {
            "course_id" : "200",
            "title" : "The Music of the Ramones",
            "dept_name" : "Accounting",
            "credits" : 4.0
        }
    },
    {
        "ID" : "14365",
        "course_id" : "843",
        "sec_id" : "1",
        "semester" : "Fall",
        "year" : 2010.0,
        "course" : {
            "course_id" : "843",
            "title" : "Environmental Law",
            "dept_name" : "Math",
            "credits" : 4.0
        }
    }
]

}

I want to query like the following SQL query.

SELECT name, title From instructor Natural join teaches Natural join course;

How I can query in mongodb?

Body:
You need to MongoDB's aggregation operator $reduce :

db.collection.aggregate([
  /** Using project stage we'll project only needed fields */
  {
    $project: {
      _id: 0, // _id is by default included - you need to exclude it
      name: 1,
      title: {
        $reduce: {
          input: "$teaches", // Iterate on objects of `teaches` array
          initialValue: [], // Initial value
          in: {
            $cond: [
              { $eq: ["$$this.course.dept_name", "$dept_name"] }, // condition to check
              {
                $concatArrays: ["$$value", ["$$this.course.title"]], // If condition is met push values to array
              },
              "$$value" // If not send same holding array back for this iteration
            ]
          }
        }
      }
    }
  }
]);

Test : mongoplayground

Test : $filter: mongoplayground

Note :

We've used $reduce to bring all title's from different objects in teaches array to an array. You can also use $filter to achieve similar thing. If in any case if your title is just a single element in array (no duplicate dept_name in teaches array) then you can use $unwind or $arrayElemAt to convert title array to string.


问:
Raku equivalent of Java StringBuffer/StringBuilder?
I need to create a big string out of a complex structure and the runtime is way too long.
Back in the Java times I solved similar problems using StringBuffer or StringBuilder which greatly reduce the number of intermediate String objects needed.

Is there something similar in Raku?

答:
Native string arrays pretty much allow you to do that.

```<code>my str @parts;
@parts.push("foo")
...
say @parts.join;
</code>```

Is that what you're looking for?

Additionally: on the MoarVM backend, when you concat strings, they are not actually concatenated in memory, but rather just "linked" together into a single virtual string.  Unfortunately, the moment you want to do a regular expression on a string, if does need to be flattened.  Which is one of the reasons regular expressions are relatively expensive.

Body:
Native string arrays pretty much allow you to do that.

my str @parts;
@parts.push("foo")
...
say @parts.join;

Is that what you're looking for?

Additionally: on the MoarVM backend, when you concat strings, they are not actually concatenated in memory, but rather just "linked" together into a single virtual string.  Unfortunately, the moment you want to do a regular expression on a string, if does need to be flattened.  Which is one of the reasons regular expressions are relatively expensive.


问:
Oracle partitioning recommendations
Due to being locked down by Corona, I don't have easy access to my more knowledgeable colleagues, so I'm hoping for a few possible recommendations here.

We do quarterly and yearly "freezes" of a number of statistical entities with a large number (1-200) of columns. Everyone then uses these "frozen" versions as a common basis for all statistical releases in Denmark. Currently, we simply create a new table for each version.
There's a demand to test if we can consolidate these several hundred tables to 26 entity-based tables to make programming against them easier, while not harming performance too much.

A "freeze" is approximately 1 million rows and consists of: Year + Period + Type + Version.
For example:

2018_21_P_V1 = Preliminary Data for 2018 first quarter version 1

2019_41_F_V2 = Final Data for 2019 yearly version 2

I am simply not very experienced in the world of partitions. My initial thought was to partition on Year + Period and Subpartiton on Type + Version, but I am no longer sure this is the right approach, nor do I have a clear picture of which partitioning type would solve the problem best.

I am hoping someone can recommend an approach as it would help me tremendously and save me a lot of time "brute force" testing a lot of different combinations.

答:
Based on your current situation which you explained I highly recommend that "USE THE PARTITIONING". No doubt.
It's highly effective and easy to use. You can read Oracle documentation about partitioning or search on the web for that to understand how to start.
In general, when you partition a table, Oracle looks at each partition as a separate table so don't worry about the speed of fetching data.
The most important step is to choose the best field(s) to establish your partitions based on. I used the date format (20190506) in number or int data type for my daily basis. Or (201907) for a monthly basis. You should design and test it.
 The next is to decide about the sub-partitions. In some cases, you don't really need one. It depends on your data structure and your expectations from the data. What do you want to do with the data? Which fields are more important? (used in where clause, ...)
Then make some index(es) for each partition. Very important.
Another important point is that using partitions may have some changes in the way you code in pl/sql. For example, you can not use 2 or more partitions in a single query at the same time. You should select and fetch data from different partitions one by one.
And don't worry about 1 million records. I used partitioning for tables way larger than this and it works fine.
Goodluck </p>

Title: Oracle partitioning recommendations


问:
Always show scrollbar - Flutter
I have a long text and I need to show the scrollbar by default when the user enters my page.

Currently, the bars not shown until the user click over the text and this, not good behavior because the user could leave the page without notice that there is some unread text.

My code:

```<code>    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(15.0),
        child: Center(
          child: Column(
            children: <Widget>[
              Image.asset(
                "assets/images/logo.png",
                height: 200.0,
              ),
              SizedBox(
                height: 40,
              ),
              Expanded(
                child: Scrollbar(
                  child: SingleChildScrollView(
                    child: Text("Long Text Here ...",
                      textDirection: TextDirection.rtl,
                      style: TextStyle(fontSize: 17.2),
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: 50,
              ),
              Row(
                children: <Widget>[
                  Expanded(
                    child: RaisedButton(
                      child: Text("Continue"),
                      onPressed: () {
                        MaterialPageRoute route = MaterialPageRoute(
                            builder: (BuildContext context) => MainPage());
                        Navigator.of(context).push(route);
                      },
                    ),
                  ),
                  SizedBox(
                    width: 20.0,
                  ),
                  RaisedButton(
                    child: Text("Close"),
                    onPressed: () {
                      exit(0);
                    },
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }```
```

答:
Updated Answer April 2023

As of v2.9.0-1.0.pre, isAlwaysShown is deprecated and you should use thumbVisibility instead. Check jayjw's more complete answer: https://stackoverflow.com/a/71357052/9777674

Original Answer June 2020

As of Flutter version 1.17, on Scrollbar you can set isAlwaysShown to true, but you must set the same controller for your Scrollbar and your SingleChildScrollView (and that applies to any other scrollable Widget as well).

Have in mind that, for the Scrollbar to be visible, there must be enough items to scroll. If there are not, the Scrollbar won't be shown.

Full working example:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: MyWidget(),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(15.0),
        child: Center(
          child: Column(
            children: <Widget>[
              // ...
              Expanded(
                child: Scrollbar(
                  controller: _scrollController, // <---- Here, the controller
                  isAlwaysShown: true, // <---- Required
                  child: SingleChildScrollView(
                    controller: _scrollController, // <---- Same as the Scrollbar controller
                    child: Text(
                      "Long Text Here ...",
                      textDirection: TextDirection.rtl,
                      style: TextStyle(fontSize: 17.2),
                    ),
                  ),
                ),
              ),
              // ...
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Title: Always show scrollbar - Flutter

Body:
I have a long text and I need to show the scrollbar by default when the user enters my page.

Currently, the bars not shown until the user click over the text and this, not good behavior because the user could leave the page without notice that there is some unread text.

My code:

    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(15.0),
        child: Center(
          child: Column(
            children: <Widget>[
              Image.asset(
                "assets/images/logo.png",
                height: 200.0,
              ),
              SizedBox(
                height: 40,
              ),
              Expanded(
                child: Scrollbar(
                  child: SingleChildScrollView(
                    child: Text("Long Text Here ...",
                      textDirection: TextDirection.rtl,
                      style: TextStyle(fontSize: 17.2),
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: 50,
              ),
              Row(
                children: <Widget>[
                  Expanded(
                    child: RaisedButton(
                      child: Text("Continue"),
                      onPressed: () {
                        MaterialPageRoute route = MaterialPageRoute(
                            builder: (BuildContext context) => MainPage());
                        Navigator.of(context).push(route);
                      },
                    ),
                  ),
                  SizedBox(
                    width: 20.0,
                  ),
                  RaisedButton(
                    child: Text("Close"),
                    onPressed: () {
                      exit(0);
                    },
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }```

Body:
Updated Answer April 2023

As of v2.9.0-1.0.pre, isAlwaysShown is deprecated and you should use thumbVisibility instead. Check jayjw's more complete answer: https://stackoverflow.com/a/71357052/9777674

Original Answer June 2020

As of Flutter version 1.17, on Scrollbar you can set isAlwaysShown to true, but you must set the same controller for your Scrollbar and your SingleChildScrollView (and that applies to any other scrollable Widget as well).

Have in mind that, for the Scrollbar to be visible, there must be enough items to scroll. If there are not, the Scrollbar won't be shown.

Full working example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: MyWidget(),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(15.0),
        child: Center(
          child: Column(
            children: <Widget>[
              // ...
              Expanded(
                child: Scrollbar(
                  controller: _scrollController, // <---- Here, the controller
                  isAlwaysShown: true, // <---- Required
                  child: SingleChildScrollView(
                    controller: _scrollController, // <---- Same as the Scrollbar controller
                    child: Text(
                      "Long Text Here ...",
                      textDirection: TextDirection.rtl,
                      style: TextStyle(fontSize: 17.2),
                    ),
                  ),
                ),
              ),
              // ...
            ],
          ),
        ),
      ),
    );
  }
}


问:
How to get String response from JSONObject in Volley
I have created JSONRequest by using volley, It successfully hits the service, I checked the service end, It receives the data, and send "Success" in return.

The problem is that, Service returns String in output, and Volley excepts some JSON Data in output. So it executes  the onError Method, instead of onResponse.

Kindly guide me how to make it accept string response, or is it not possible when you are using JSONObjectas request.

```<code>    Request<JSONObject> jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://192.168.0.101:8888/api/services/mytest",
            jsonParent, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d("Success", response.toString());
            deleteFile();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error", error.toString());
            deleteFile();
        }

    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    requestQueue.add(jsonObjectRequest);
</code>```

答:
For those who still need to send raw Json and receive a String as response:

By default, the body consists of the request parameters in application/x-www-form-urlencoded; charset=UTF-8 format for StringRequest. When overriding getBody(), as Nayan suggested correctly, consider overriding getBodyContentType() as well to match the new body format. For Json it should be
application/json.

```<code>String url = "www.google.com";

HashMap<String, Object> params = new HashMap<>();
params.put("key1", "Android");
params.put("isCool", true);

StringRequest request = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>() {
            public void onResponse(String response) {

            }
        },
        new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {

            }
        }
    ) {
        public byte[] getBody() {
            return new JSONObject(params).toString().getBytes();
        }
        public String getBodyContentType() {
            return "application/json";
        }
    };

Volley.newRequestQueue(this).add(request);
</code>```

Body:
I have created JSONRequest by using volley, It successfully hits the service, I checked the service end, It receives the data, and send "Success" in return.

The problem is that, Service returns String in output, and Volley excepts some JSON Data in output. So it executes  the onError Method, instead of onResponse.

Kindly guide me how to make it accept string response, or is it not possible when you are using JSONObjectas request.

    Request<JSONObject> jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://192.168.0.101:8888/api/services/mytest",
            jsonParent, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d("Success", response.toString());
            deleteFile();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error", error.toString());
            deleteFile();
        }

    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    requestQueue.add(jsonObjectRequest);

Body:
For those who still need to send raw Json and receive a String as response:

By default, the body consists of the request parameters in application/x-www-form-urlencoded; charset=UTF-8 format for StringRequest. When overriding getBody(), as Nayan suggested correctly, consider overriding getBodyContentType() as well to match the new body format. For Json it should be
application/json.

String url = "www.google.com";

HashMap<String, Object> params = new HashMap<>();
params.put("key1", "Android");
params.put("isCool", true);

StringRequest request = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>() {
            public void onResponse(String response) {

            }
        },
        new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {

            }
        }
    ) {
        public byte[] getBody() {
            return new JSONObject(params).toString().getBytes();
        }
        public String getBodyContentType() {
            return "application/json";
        }
    };

Volley.newRequestQueue(this).add(request);


问:
Dynamic Dates SQL Server
I have the below data in SQL.

I need to figure out a way dynamically to get the next dates based the 2 values below. The remaining doses tells me how many dates I will need to find and RXDAYS tells me the increments in which to look for the dates

```<code>Date Shipped    Remaining Doses RXDAYS
2019-06-05      2               30
</code>```

So based on the above I would find the date 30 days after 2019-06-05 and get 2019-07-05 and 30 days after that I would get 2019-08-04.

Is there a way to do this?

答:
Another approach is to make use of a numbers table (or create your own on the fly if you don't already have one). Assuming you can't ever supply more than 255 doses:

```<code>DECLARE @Doses table
(
    RowID          int IDENTITY(1,1),
    DateShipped    date,
    RemainingDoses tinyint,
    RXDays         tinyint
);

INSERT @Doses(DateShipped, RemainingDoses, RXDays)
  VALUES('20190605',2,30),('20190704',3,24);

-- pseudo Numbers table
DECLARE @num table(n tinyint);

INSERT @num(n) SELECT TOP (256)
       row_number() OVER (ORDER BY (SELECT NULL)) - 1
  FROM sys.all_columns;

SELECT d.RowID, d.DateShipped, d.RemainingDoses, d.RXDays,
    SubsequentShipdate = DATEADD(DAY, n.n*d.RXDays, d.DateShipped)
  FROM @Doses AS d
  INNER JOIN @num AS n
  ON n.n <= d.RemainingDoses
  ORDER BY d.RowID, SubsequentShipdate;
</code>```

Results:

If you only want the "next" dates and not include the original row, just add:

```<code>AND n.n > 0
</code>```

Or, don't include 0 in the numbers table (though it can be useful):

```<code>INSERT @num(n) SELECT TOP (255)
       row_number() OVER (ORDER BY (SELECT NULL))
</code>```

Title: Dynamic Dates SQL Server

Body:
I have the below data in SQL.

I need to figure out a way dynamically to get the next dates based the 2 values below. The remaining doses tells me how many dates I will need to find and RXDAYS tells me the increments in which to look for the dates

Date Shipped    Remaining Doses RXDAYS
2019-06-05      2               30

So based on the above I would find the date 30 days after 2019-06-05 and get 2019-07-05 and 30 days after that I would get 2019-08-04.

Is there a way to do this?

Body:
Another approach is to make use of a numbers table (or create your own on the fly if you don't already have one). Assuming you can't ever supply more than 255 doses:

DECLARE @Doses table
(
    RowID          int IDENTITY(1,1),
    DateShipped    date,
    RemainingDoses tinyint,
    RXDays         tinyint
);

INSERT @Doses(DateShipped, RemainingDoses, RXDays)
  VALUES('20190605',2,30),('20190704',3,24);

-- pseudo Numbers table
DECLARE @num table(n tinyint);

INSERT @num(n) SELECT TOP (256)
       row_number() OVER (ORDER BY (SELECT NULL)) - 1
  FROM sys.all_columns;

SELECT d.RowID, d.DateShipped, d.RemainingDoses, d.RXDays,
    SubsequentShipdate = DATEADD(DAY, n.n*d.RXDays, d.DateShipped)
  FROM @Doses AS d
  INNER JOIN @num AS n
  ON n.n <= d.RemainingDoses
  ORDER BY d.RowID, SubsequentShipdate;

Results:

If you only want the "next" dates and not include the original row, just add:

AND n.n > 0

Or, don't include 0 in the numbers table (though it can be useful):

INSERT @num(n) SELECT TOP (255)
       row_number() OVER (ORDER BY (SELECT NULL))


问:
Retrieve first non-NA value from a group of columns
I'm a pretty new coder so if you guys could help me that'd be great.

Let's say I have one dataframe:

Can I combine "Number" and "Number 2" in a way where "Number" takes precedence unless there is no value(NaN). When "Number" is NaN, then we use the entry in "Number 2"

It should look like this

In other words, I want to combine "Number" and "Number 2" where if "Number" is NaN, then use "Number 2"'s entry. If "Number" has an entry, keep it for the merged entry. This is similar to left merge for merging two data frames.

Btw, I'm using python and pandas.

Update: trying to use np.where

Output without np.where:

Output with np.where:

答:
Or you can use apply:

```<code>df['Number'] = df.apply(lambda row: row['Number'] if not pd.isnull(row['Number']) else row['Number2'], axis=1)
</code>```

Just need to drop the Number2 column then

Body:
Or you can use apply:

df['Number'] = df.apply(lambda row: row['Number'] if not pd.isnull(row['Number']) else row['Number2'], axis=1)

Just need to drop the Number2 column then


问:
Firebase authentication issue - An internal error has occurred, print and inspect the error details for more information
I have used Firebase authentication to receive an OTP for the verification of the user. For that, I have used following method,

```<code>        PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
      if let error = error {
        showAlert(error.localizedDescription)
        return
      }

      print(verificationID)
    }
</code>```

Now, the issue is whenever we test release build from test flight in our devices, we are successfully authenticated but when we submit same build for the review team of Apple, they are facing following error,

An internal error has occurred, print and inspect the error details for more information.

Kindly help me how to regenerate above issue from my side, and solve it.

答: Check authentication OTP service enabled for other region or not in firebase.</p>

Body:
I have used Firebase authentication to receive an OTP for the verification of the user. For that, I have used following method,

        PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
      if let error = error {
        showAlert(error.localizedDescription)
        return
      }

      print(verificationID)
    }

Now, the issue is whenever we test release build from test flight in our devices, we are successfully authenticated but when we submit same build for the review team of Apple, they are facing following error,

An internal error has occurred, print and inspect the error details for more information.

Kindly help me how to regenerate above issue from my side, and solve it.


问:
How do you toggle all dimensions in a Flot chart at once?
From the Flotcharts example: https://www.flotcharts.org/flot/examples/series-toggle/index.html

I'd like to toggle on/off all flot series at once (i.e. Select All / Select None).

Toggling the checkboxes themselves is easy enough:

```<code>$('input:checkbox').addAttr('checked');    // Select All
$('input:checkbox').removeAttr('checked'); // Select None
</code>```

But how can I also trigger the dimensions to change?

Here's a jsfiddle of the flotcharts example:
https://jsfiddle.net/uzc5rqow/

答: I understand that "dimensions" refers to the axes. In your code, it is simple, you just need to call plotAccordingToChoices. I have forked your fiddle to show how to add all ticks with a button ( https://jsfiddle.net/Lk4oqvm5/ ). In the opposite case, when you uncheck every box, you need to decide which behavior you want. With no data, the graph cannot calculate the dimensions (if you manually uncheck every box, you will see that the last line does not disappear).

Body:
From the Flotcharts example: https://www.flotcharts.org/flot/examples/series-toggle/index.html

I'd like to toggle on/off all flot series at once (i.e. Select All / Select None).

Toggling the checkboxes themselves is easy enough:

$('input:checkbox').addAttr('checked');    // Select All
$('input:checkbox').removeAttr('checked'); // Select None

But how can I also trigger the dimensions to change?

Here's a jsfiddle of the flotcharts example:
https://jsfiddle.net/uzc5rqow/


问:
js array sort nor working for custom logic
I have an Issue in array sort. I have custom logic in displaying the array. The object has a code column and has a code ('A' or 'B' or 'C'). I have to sort in records to display first 'B', 'A' and last 'C'.

My code is in slackblitz.

Here is code

```<code>list.sort(function (el1, el2) {
  if (el1.codeNumber > el2.codeNumber) {
    return 1;
  }
  if (el1.codeNumber < el2.codeNumber) {
    return -1;
  }

  return 0;
});
</code>```

答:
You could simplify the code by using an object for getting the wanted order of an item with a certain code.

const
    list = [{ name: 'Bala', age: 21, code: 'A' }, { name: 'Bala', age: 22, code: 'A' }, { name: 'Bala', age: 23, code: 'C' }, { name: 'Bala', age: 24, code: 'A' }, { name: 'Bala', age: 25, code: 'B' }, { name: 'Bala', age: 26, code: 'B' }, { name: 'Bala', age: 27, code: 'B' }, { name: 'Bala', age: 28, code: 'A' }, { name: 'Bala', age: 29, code: 'B' }, { name: 'Bala', age: 30, code: 'C' }, { name: 'Bala', age: 31, code: 'C' }, { name: 'Bala', age: 31, code: 'C' }, { name: 'Bala', age: 28, code: 'A' }],
    order = { B: 1, A: 2, C: 3 };

list.sort((a, b) => order[a.code] - order[b.code]);

console.log(list);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an Issue in array sort. I have custom logic in displaying the array. The object has a code column and has a code ('A' or 'B' or 'C'). I have to sort in records to display first 'B', 'A' and last 'C'.

My code is in slackblitz.

Here is code

list.sort(function (el1, el2) {
  if (el1.codeNumber > el2.codeNumber) {
    return 1;
  }
  if (el1.codeNumber < el2.codeNumber) {
    return -1;
  }

  return 0;
});

Body:
You could simplify the code by using an object for getting the wanted order of an item with a certain code.

const
    list = [{ name: 'Bala', age: 21, code: 'A' }, { name: 'Bala', age: 22, code: 'A' }, { name: 'Bala', age: 23, code: 'C' }, { name: 'Bala', age: 24, code: 'A' }, { name: 'Bala', age: 25, code: 'B' }, { name: 'Bala', age: 26, code: 'B' }, { name: 'Bala', age: 27, code: 'B' }, { name: 'Bala', age: 28, code: 'A' }, { name: 'Bala', age: 29, code: 'B' }, { name: 'Bala', age: 30, code: 'C' }, { name: 'Bala', age: 31, code: 'C' }, { name: 'Bala', age: 31, code: 'C' }, { name: 'Bala', age: 28, code: 'A' }],
    order = { B: 1, A: 2, C: 3 };

list.sort((a, b) => order[a.code] - order[b.code]);

console.log(list);

.as-console-wrapper { max-height: 100% !important; top: 0; }