问:
Golang amazon s3 how can I upload images faster
I have some images that I am uploading to my s3 account using the official amazon s3 package . My images are typically around 250 - 350 KB so small images, however they take around 8 or 9 seconds to upload which seems excessive any suggestions on improving speed would be great. This is my code and if I take the resizing image code off it still takes a good 8 or 9 seconds still .</p>

```<code>      func UploadStreamImage(w http.ResponseWriter, r *http.Request) {

          r.ParseForm()
    var buff bytes.Buffer

    wg := sync.WaitGroup{}

    wg.Add(1)
    go func() {
        defer wg.Done()

        var buf bytes.Buffer
        sess, _ := session.NewSession(&aws.Config{
            Region:      aws.String("us-west-2"),
            Credentials: credentials.NewStaticCredentials(aws_access_key_id, aws_secret_access_key, ""),

        })

        svc := s3.New(sess)

        file, handler, err := r.FormFile("file")
        if err != nil {
            log_errors(" error on upload",err.Error(),w)
            fmt.Println("Error Uploading Image")
            return
        }
        defer file.Close()

        img,err := imaging.Decode(file)
        if err != nil {
            print("Imaging Open error")
            log_errors("Error decoding",err.Error(),w)
            return
        }

                imgSize,err := strconv.Atoi(r.FormValue("imgsize"))

        if err != nil {
            println("Error converting to integer")
            log_errors("Error converting to integer",err.Error(),w)
            return
        }

        b := img.Bounds()
        heightImg := b.Max.Y
        widthImg := b.Max.X

        // resize image
        height := int(float64(heightImg) * .23)
        width := int(float64(widthImg) * .23)

        if imgSize < 401 {
            height = int(float64(heightImg) * 1)
            width = int(float64(widthImg) * 1)

        } else if imgSize  >= 401 && imgSize < 900 {
               height = int(float64(heightImg) * .68)
               width = int(float64(widthImg) * .68)
               println("Middle Image")
                  } else if  imgSize  >= 900 && imgSize < 1300 {
            height = int(float64(heightImg) * .45)
            width = int(float64(widthImg) * .45)
           } else if  imgSize  >= 1301 && imgSize < 1700 {
            height = int(float64(heightImg) * .40)
            width = int(float64(widthImg) * .40)
        }

        new_img := imaging.Resize(img,width,height, imaging.Lanczos)
       // end resize

        err = imaging.Encode(&buf,new_img, imaging.JPEG)
        if err != nil {
            log.Println(err)
            log_errors(" error encoding file",err.Error(),w)
                        return
        }

        r := bytes.NewReader(buf.Bytes())

        read_file,err := ioutil.ReadAll(r)
        if err != nil {
            fmt.Println("Error Reading file")
            log_errors(" error reading file",err.Error(),w)
            return

        }

        file.Read(read_file)
        fileBytes := bytes.NewReader(read_file)
        fileSize, err := buff.ReadFrom(fileBytes)
        if err != nil {
            log_errors(" error fileSize",err.Error(),w)
            return
        }
        fileType := http.DetectContentType(read_file)
        path := handler.Filename
        params := &s3.PutObjectInput{
            Bucket: aws.String("bucket name"),
            Key: aws.String(path),
            Body: fileBytes,

            ContentLength: aws.Int64(fileSize),
            ContentType: aws.String(fileType),
        }

        resp, err := svc.PutObject(params)
        if err != nil {
            fmt.Printf("bad response: %s", err)
            log_errors("error in putObject",err.Error(),w)
            return
        }

        fmt.Println(w,"Done")

    }()
    wg.Wait()

}
</code>```

答:
Improving speed? this is subjective one; depends on many factors such as server uplink, client uplink, etc.

Instead, I will provide my inputs to improve your code snippets:

Let's start with sync.WaitGroup - I do not see a benefit as per your code flow, you just create and wait for goroutine to complete. Instead use without WaitGroup. Tip: Do not use feature for sake/buzz; use it when needed.

Do not create multiple bytes.Buffer and Reader, when you can accomplish without it. For e.g. getting fileSize after the resize, just do buf.Len().

If you want to offload the AWS upload then extract upload code part into separate func and call it as goroutine.

I have updated your code snippet (I have not tested your code, so please fix/improve it as required):

```<code>func UploadStreamImage(w http.ResponseWriter, r *http.Request) {
    file, handler, err := r.FormFile("file")
    if err != nil {
        log_errors(" error on upload", err.Error(), w)
        fmt.Println("Error Uploading Image")
        return
    }
    defer file.Close()

    // Suggestion: You can calculate the file size from bytes.
    // instead getting it from form; since after resize image will change
    imgSize, err := strconv.Atoi(r.FormValue("imgsize"))
    if err != nil {
        println("Error converting to integer")
        log_errors("Error converting to integer", err.Error(), w)
        return
    }

    img, err := imaging.Decode(file)
    if err != nil {
        print("Imaging Open error")
        log_errors("Error decoding", err.Error(), w)
        return
    }

    b := img.Bounds()
    heightImg := b.Max.Y
    widthImg := b.Max.X

    // resize image
    height := int(float64(heightImg) * .23)
    width := int(float64(widthImg) * .23)

    if imgSize < 401 {
        height = int(float64(heightImg) * 1)
        width = int(float64(widthImg) * 1)

    } else if imgSize >= 401 && imgSize < 900 {
        height = int(float64(heightImg) * .68)
        width = int(float64(widthImg) * .68)
        println("Middle Image")
    } else if imgSize >= 900 && imgSize < 1300 {
        height = int(float64(heightImg) * .45)
        width = int(float64(widthImg) * .45)
    } else if imgSize >= 1301 && imgSize < 1700 {
        height = int(float64(heightImg) * .40)
        width = int(float64(widthImg) * .40)
    }

    new_img := imaging.Resize(img, width, height, imaging.Lanczos)
    // end resize

    var buf bytes.Buffer
    err = imaging.Encode(&buf, new_img, imaging.JPEG)
    if err != nil {
        log.Println(err)
        log_errors(" error encoding file", err.Error(), w)
        return
    }

    fileType := http.DetectContentType(buf.Bytes())
    fileSize := buf.Len()
    path := handler.Filename
    params := &s3.PutObjectInput{
        Bucket: aws.String("bucket name"),
        Key:    aws.String(path),
        Body:   bytes.NewReader(buf.Bytes()),

        ContentLength: aws.Int64(fileSize),
        ContentType:   aws.String(fileType),
    }

    resp, err := svc.PutObject(params)
    if err != nil {
        fmt.Printf("bad response: %s", err)
        log_errors("error in putObject", err.Error(), w)
        return
    }

    fmt.Println("Done", resp)
}
</code>```

Body:
I have some images that I am uploading to my s3 account using the official amazon s3 package . My images are typically around 250 - 350 KB so small images, however they take around 8 or 9 seconds to upload which seems excessive any suggestions on improving speed would be great. This is my code and if I take the resizing image code off it still takes a good 8 or 9 seconds still .

      func UploadStreamImage(w http.ResponseWriter, r *http.Request) {

          r.ParseForm()
    var buff bytes.Buffer

    wg := sync.WaitGroup{}

    wg.Add(1)
    go func() {
        defer wg.Done()

        var buf bytes.Buffer
        sess, _ := session.NewSession(&aws.Config{
            Region:      aws.String("us-west-2"),
            Credentials: credentials.NewStaticCredentials(aws_access_key_id, aws_secret_access_key, ""),

        })

        svc := s3.New(sess)

        file, handler, err := r.FormFile("file")
        if err != nil {
            log_errors(" error on upload",err.Error(),w)
            fmt.Println("Error Uploading Image")
            return
        }
        defer file.Close()

        img,err := imaging.Decode(file)
        if err != nil {
            print("Imaging Open error")
            log_errors("Error decoding",err.Error(),w)
            return
        }

                imgSize,err := strconv.Atoi(r.FormValue("imgsize"))

        if err != nil {
            println("Error converting to integer")
            log_errors("Error converting to integer",err.Error(),w)
            return
        }

        b := img.Bounds()
        heightImg := b.Max.Y
        widthImg := b.Max.X

        // resize image
        height := int(float64(heightImg) * .23)
        width := int(float64(widthImg) * .23)

        if imgSize < 401 {
            height = int(float64(heightImg) * 1)
            width = int(float64(widthImg) * 1)

        } else if imgSize  >= 401 && imgSize < 900 {
               height = int(float64(heightImg) * .68)
               width = int(float64(widthImg) * .68)
               println("Middle Image")
                  } else if  imgSize  >= 900 && imgSize < 1300 {
            height = int(float64(heightImg) * .45)
            width = int(float64(widthImg) * .45)
           } else if  imgSize  >= 1301 && imgSize < 1700 {
            height = int(float64(heightImg) * .40)
            width = int(float64(widthImg) * .40)
        }

        new_img := imaging.Resize(img,width,height, imaging.Lanczos)
       // end resize

        err = imaging.Encode(&buf,new_img, imaging.JPEG)
        if err != nil {
            log.Println(err)
            log_errors(" error encoding file",err.Error(),w)
                        return
        }

        r := bytes.NewReader(buf.Bytes())

        read_file,err := ioutil.ReadAll(r)
        if err != nil {
            fmt.Println("Error Reading file")
            log_errors(" error reading file",err.Error(),w)
            return

        }

        file.Read(read_file)
        fileBytes := bytes.NewReader(read_file)
        fileSize, err := buff.ReadFrom(fileBytes)
        if err != nil {
            log_errors(" error fileSize",err.Error(),w)
            return
        }
        fileType := http.DetectContentType(read_file)
        path := handler.Filename
        params := &s3.PutObjectInput{
            Bucket: aws.String("bucket name"),
            Key: aws.String(path),
            Body: fileBytes,

            ContentLength: aws.Int64(fileSize),
            ContentType: aws.String(fileType),
        }

        resp, err := svc.PutObject(params)
        if err != nil {
            fmt.Printf("bad response: %s", err)
            log_errors("error in putObject",err.Error(),w)
            return
        }

        fmt.Println(w,"Done")

    }()
    wg.Wait()

}

Body:
Improving speed? this is subjective one; depends on many factors such as server uplink, client uplink, etc.

Instead, I will provide my inputs to improve your code snippets:

Let's start with sync.WaitGroup - I do not see a benefit as per your code flow, you just create and wait for goroutine to complete. Instead use without WaitGroup. Tip: Do not use feature for sake/buzz; use it when needed.

Do not create multiple bytes.Buffer and Reader, when you can accomplish without it. For e.g. getting fileSize after the resize, just do buf.Len().

If you want to offload the AWS upload then extract upload code part into separate func and call it as goroutine.

I have updated your code snippet (I have not tested your code, so please fix/improve it as required):

func UploadStreamImage(w http.ResponseWriter, r *http.Request) {
    file, handler, err := r.FormFile("file")
    if err != nil {
        log_errors(" error on upload", err.Error(), w)
        fmt.Println("Error Uploading Image")
        return
    }
    defer file.Close()

    // Suggestion: You can calculate the file size from bytes.
    // instead getting it from form; since after resize image will change
    imgSize, err := strconv.Atoi(r.FormValue("imgsize"))
    if err != nil {
        println("Error converting to integer")
        log_errors("Error converting to integer", err.Error(), w)
        return
    }

    img, err := imaging.Decode(file)
    if err != nil {
        print("Imaging Open error")
        log_errors("Error decoding", err.Error(), w)
        return
    }

    b := img.Bounds()
    heightImg := b.Max.Y
    widthImg := b.Max.X

    // resize image
    height := int(float64(heightImg) * .23)
    width := int(float64(widthImg) * .23)

    if imgSize < 401 {
        height = int(float64(heightImg) * 1)
        width = int(float64(widthImg) * 1)

    } else if imgSize >= 401 && imgSize < 900 {
        height = int(float64(heightImg) * .68)
        width = int(float64(widthImg) * .68)
        println("Middle Image")
    } else if imgSize >= 900 && imgSize < 1300 {
        height = int(float64(heightImg) * .45)
        width = int(float64(widthImg) * .45)
    } else if imgSize >= 1301 && imgSize < 1700 {
        height = int(float64(heightImg) * .40)
        width = int(float64(widthImg) * .40)
    }

    new_img := imaging.Resize(img, width, height, imaging.Lanczos)
    // end resize

    var buf bytes.Buffer
    err = imaging.Encode(&buf, new_img, imaging.JPEG)
    if err != nil {
        log.Println(err)
        log_errors(" error encoding file", err.Error(), w)
        return
    }

    fileType := http.DetectContentType(buf.Bytes())
    fileSize := buf.Len()
    path := handler.Filename
    params := &s3.PutObjectInput{
        Bucket: aws.String("bucket name"),
        Key:    aws.String(path),
        Body:   bytes.NewReader(buf.Bytes()),

        ContentLength: aws.Int64(fileSize),
        ContentType:   aws.String(fileType),
    }

    resp, err := svc.PutObject(params)
    if err != nil {
        fmt.Printf("bad response: %s", err)
        log_errors("error in putObject", err.Error(), w)
        return
    }

    fmt.Println("Done", resp)
}


来源: stackexchange

问:
Factory Pattern implementation in C#
I'm implementing a factory pattern that looks as follows.

```<code>public class FeedFactory
{
    #region Singleton Pattern
    //..
    #endregion

    private static Feed[] _factory = new Feed[(int)FeedType.Total];

    public void RegisterFeed(FeedType feedType,Feed feed)
    {
        if (_factory[(int)feedType] == null)
        {
            _factory[(int)feedType] = feed;
        }
        else
        {
            // already registered
        }
    }

    public Feed GetFeed(FeedType feedType)
    {
        return _factory[(int)feedType];
    }
}
</code>```

Here, Feed is an abstract class from which the different classes inherit. How can I register the different classes? Is it possible to do it from their constructor?

答: When you call the RegisterFeed method you need to pass a concrete instance of a Feed class. So it is the responsibility of the caller to provide the concrete implementation.

ContentLicense: CC BY-SA 2.5

Title: Factory Pattern implementation in C#

Body:
I'm implementing a factory pattern that looks as follows.

public class FeedFactory
{
    #region Singleton Pattern
    //..
    #endregion

    private static Feed[] _factory = new Feed[(int)FeedType.Total];

    public void RegisterFeed(FeedType feedType,Feed feed)
    {
        if (_factory[(int)feedType] == null)
        {
            _factory[(int)feedType] = feed;
        }
        else
        {
            // already registered
        }
    }

    public Feed GetFeed(FeedType feedType)
    {
        return _factory[(int)feedType];
    }
}

Here, Feed is an abstract class from which the different classes inherit. How can I register the different classes? Is it possible to do it from their constructor?


问:
Getting slope in R using Loops and conditionals
I am working on a data frame with x and y columns with values as rows.. I want to calculate the slope of x and y for every 2 rows and then using the calculated slope, record whether slope's "stability" is "high" or "low". You'll understand better after seeing the code. What is wrong with this code? When I input stability, R returns NULL.</p>

```<code>slope <- (acc$y[i+1] - acc$y[i]) / (acc$x[i+1] - acc$x[i])
stability <- c()
for (i in 1:nrow(acc)) {
  if (slope[i] > 0 & slope[i] < 0.8) {
    stability[i] <- "low"
  } else if (slope[i] >= 0.8 & slope[i] <= 1) {
    stability[i] <- "high"
  } else if (slope[i] > 1 & slope[i] < 1.2) {
    stability[i] <- "high"
  } else if (slope[i] >= 1.2) {
    stability[i] <- "low"
  } else if (slope[i] >= -1 & slope[i] <= -0.8) {
    stability[i] <- "high"
  } else if (slope[i] >= -0.8 & slope[i] <= 0) {
    stability[i] <- "low"
  } else if (slope[i] < -1 & slope[i] > -1.2) {
    stability[i] <- "high"
  } else
    stability[i] <- "low"
}
</code>```

答:
Modify your code as following:

```<code>    #slope <- (acc$y[i+1] - acc$y[i]) / (acc$x[i+1] - acc$x[i])
     stability <- as.vector(nrow(acc))
    n <- nrow(acc)-1
    for (i in 1:n) {
      slope <- (acc$y[i+1] - acc$y[i]) / (acc$x[i+1] - acc$x[i])

      if (slope > 0 && slope < 0.8) {
        stability[i] <- "low"
      } else if (slope >= 0.8 && slope <= 1) {
        stability[i] <- "high"
      } else if (slope > 1 && slope < 1.2) {
        stability[i] <- "high"
      } else if (slope >= 1.2) {
        stability[i] <- "low"
      } else if (slope >= -1 && slope <= -0.8) {
        stability[i] <- "high"
      } else if (slope >= -0.8 && slope <= 0) {
        stability[i] <- "low"
      } else if (slope < -1 && slope > -1.2) {
        stability[i] <- "high"
      } else
        stability[i] <- "low"
    }
</code>```

Try it Online

ContentLicense: CC BY-SA 3.0

Body:
I am working on a data frame with x and y columns with values as rows.. I want to calculate the slope of x and y for every 2 rows and then using the calculated slope, record whether slope's "stability" is "high" or "low". You'll understand better after seeing the code. What is wrong with this code? When I input stability, R returns NULL.

slope <- (acc$y[i+1] - acc$y[i]) / (acc$x[i+1] - acc$x[i])
stability <- c()
for (i in 1:nrow(acc)) {
  if (slope[i] > 0 & slope[i] < 0.8) {
    stability[i] <- "low"
  } else if (slope[i] >= 0.8 & slope[i] <= 1) {
    stability[i] <- "high"
  } else if (slope[i] > 1 & slope[i] < 1.2) {
    stability[i] <- "high"
  } else if (slope[i] >= 1.2) {
    stability[i] <- "low"
  } else if (slope[i] >= -1 & slope[i] <= -0.8) {
    stability[i] <- "high"
  } else if (slope[i] >= -0.8 & slope[i] <= 0) {
    stability[i] <- "low"
  } else if (slope[i] < -1 & slope[i] > -1.2) {
    stability[i] <- "high"
  } else
    stability[i] <- "low"
}

Body:
Modify your code as following:

    #slope <- (acc$y[i+1] - acc$y[i]) / (acc$x[i+1] - acc$x[i])
     stability <- as.vector(nrow(acc))
    n <- nrow(acc)-1
    for (i in 1:n) {
      slope <- (acc$y[i+1] - acc$y[i]) / (acc$x[i+1] - acc$x[i])

      if (slope > 0 && slope < 0.8) {
        stability[i] <- "low"
      } else if (slope >= 0.8 && slope <= 1) {
        stability[i] <- "high"
      } else if (slope > 1 && slope < 1.2) {
        stability[i] <- "high"
      } else if (slope >= 1.2) {
        stability[i] <- "low"
      } else if (slope >= -1 && slope <= -0.8) {
        stability[i] <- "high"
      } else if (slope >= -0.8 && slope <= 0) {
        stability[i] <- "low"
      } else if (slope < -1 && slope > -1.2) {
        stability[i] <- "high"
      } else
        stability[i] <- "low"
    }

Try it Online


问:
"Sending the email to the following server failed : webmail.company.com:465"
I use this code to send email </p>

```<code> Email email = new SimpleEmail();
            email.setDebug(true);
            email.setHostName("webmail.company.com");
            email.setSmtpPort(587);

            email.setAuthenticator(new DefaultAuthenticator("username@company.com", "*****"));
            email.setSSLOnConnect(true);
            try {
                email.setFrom("username@company.com");

                email.setSubject("TestMail");

                email.setMsg("Hi "+receiver.getSex()+" "+receiver.getName()+" "+editorBean.getValue());

                email.addTo(receiver.getEmail());
                email.send();
            } catch (EmailException ex) {
                Logger.getLogger(PersonBean.class.getName()).log(Level.SEVERE, null, ex);
                result += "exptions :" + ex.getMessage();
                return result;
            }
</code>```

<p>and I think that smtp port is not changing
"Sending the email to the following server failed : webmail.company.com:465"
what is the problem ? </p>

答:
Step1:

Change your settings in gmail account to allow less secure apps.
Go to https://myaccount.google.com/lesssecureapps and turn on Access for less secure apps

Step2:

In my case Avast Antivirus was causing the exception to be thrown when I was trying to send the email.

Avast shields control -> Disable for 10 minutes

(or)

Open Avast User Interface -> Settings -> Components -> MailShield(Customize) -> MainSettings - Uncheck the option 'Scan outbound mail (SMTP)'

Body:
I use this code to send email

 Email email = new SimpleEmail();
            email.setDebug(true);
            email.setHostName("webmail.company.com");
            email.setSmtpPort(587);

            email.setAuthenticator(new DefaultAuthenticator("username@company.com", "*****"));
            email.setSSLOnConnect(true);
            try {
                email.setFrom("username@company.com");

                email.setSubject("TestMail");

                email.setMsg("Hi "+receiver.getSex()+" "+receiver.getName()+" "+editorBean.getValue());

                email.addTo(receiver.getEmail());
                email.send();
            } catch (EmailException ex) {
                Logger.getLogger(PersonBean.class.getName()).log(Level.SEVERE, null, ex);
                result += "exptions :" + ex.getMessage();
                return result;
            }

and I think that smtp port is not changing
"Sending the email to the following server failed : webmail.company.com:465"
what is the problem ?


问:
What is the overhead cost of an empty vector?
What is the memory overhead of having an empty vector vs having a pointer to a vector?

Option A:

```<code>std::vector<int> v;
</code>```

Option B:

```<code>std::vector<int> *v = NULL;
</code>```

I believe that option B takes 1 32 bit pointer (assuming 32 bit here)
How much memory does the empty 'v' take up?

答:
In Visual Studio Community 2017 (Version 15.2), running this code:

```<code>#include <iostream>
#include <vector>

using namespace std;

void main()
{
    vector<float> test;
    vector<float>* test2 = &test;
    cout << sizeof(test) << "\n";
    cout << sizeof(test2) << "\n";

    cout << "\n";
    system("pause");
}
</code>```

Running in 32 bit (x86), I get 16 bytes for the vector and 4 bytes for the vector pointer.

Running in 64 bit (x64), I get 32 bytes for the vector and 8 bytes for the vector pointer.

LastEditorDisplayName: litb

Body:
What is the memory overhead of having an empty vector vs having a pointer to a vector?

Option A:

std::vector<int> v;

Option B:

std::vector<int> *v = NULL;

I believe that option B takes 1 32 bit pointer (assuming 32 bit here)
How much memory does the empty 'v' take up?

Body:
In Visual Studio Community 2017 (Version 15.2), running this code:

#include <iostream>
#include <vector>

using namespace std;

void main()
{
    vector<float> test;
    vector<float>* test2 = &test;
    cout << sizeof(test) << "\n";
    cout << sizeof(test2) << "\n";

    cout << "\n";
    system("pause");
}

Running in 32 bit (x86), I get 16 bytes for the vector and 4 bytes for the vector pointer.

Running in 64 bit (x64), I get 32 bytes for the vector and 8 bytes for the vector pointer.


问:
How to authenticate AAD token from PPE environment using OWIN?
I am using below code to authenticate AAD access token.

```<code>        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigSettings.MicrosoftAadTenant,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false,
                    ValidateIssuer = false
                }
            });
</code>```

The code works fine until I switched to use a token generated from PPE environment, whose Iss is "https://sts.windows-ppe.net/...". I pasted error message below. Do you know how to fix it?

Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationMiddleware
  Error: 0 : Authentication failed
  System.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException:
  IDX10500: Signature validation failed. Unable to resolve
  SecurityKeyIdentifier: 'SecurityKeyIdentifier
      (
      IsReadOnly = False,
      Count = 2,
      Clause[0] = X509ThumbprintKeyIdentifierClause(Hash = 0x871BE0E2BDD307841D01C8151AE2717D2DB9F376),
      Clause[1] = System.IdentityModel.Tokens.NamedKeySecurityKeyIdentifierClause
      ) ',

Thanks,

答: Ok, I find out why. Looking at Microsoft Owin source code at git repo, the login url is hard coded. There is no way to config it. I fix the issue by writing my own extension method.</p>

Body:
I am using below code to authenticate AAD access token.

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigSettings.MicrosoftAadTenant,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false,
                    ValidateIssuer = false
                }
            });

The code works fine until I switched to use a token generated from PPE environment, whose Iss is "https://sts.windows-ppe.net/...". I pasted error message below. Do you know how to fix it?

Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationMiddleware
  Error: 0 : Authentication failed
  System.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException:
  IDX10500: Signature validation failed. Unable to resolve
  SecurityKeyIdentifier: 'SecurityKeyIdentifier
      (
      IsReadOnly = False,
      Count = 2,
      Clause[0] = X509ThumbprintKeyIdentifierClause(Hash = 0x871BE0E2BDD307841D01C8151AE2717D2DB9F376),
      Clause[1] = System.IdentityModel.Tokens.NamedKeySecurityKeyIdentifierClause
      ) ',

Thanks,


问:
Realm migration inadequately documented. Can anyone clarify?
Performing migrations on a Realm database is poorly documented and the documentation seems to be out-of-date. There are two areas explaining how to migrate data:

-- The simple example on the Realm website:  https://realm.io/docs/swift/latest/

-- A more detailed example in the Github examples section:  https://github.com/realm/realm-cocoa/blob/master/examples/ios/swift-3.0/Migration/AppDelegate.swift

Neither of these examples adequately explain how to migrate data between schema versions. I've tried playing around with the examples and have yet to get any migrations working. As well, I've had problems with app crashes when upgrading to newer Realm versions without schema changes and data changes, which don't occur in the Simulator but occur when installing the app from TestFlight or the App Store.

Seems like the Realm documentation and examples detailing migrations are due for a refresh. My areas of interest are:

Upgrading to a newer Realm version without a schema change in the database. Unclear whether I should continue using the default.realm file generated with a previous version, or whether I need to re-generate the default.realm file using the newer Realm framework version.

Adding a new attribute to a Realm object.

New objects ("rows") added to an existing class without any schema change.

No schema changes to existing classes in the database, but addition of an entirely new class or classes.

Any combination of the above.

Thanks!

答:
Unfortunately, that doesn't work, at all. There is a block of code I had to add to iOS apps several months ago in order to get Realm to work, but it doesn't solve the migration problems I've experienced:

```<code>      config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("default-v1.realm")
  Realm.Configuration.defaultConfiguration = config

  // copy over old data files for migration
  //let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
  let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
  //print("Realm.Configuration.defaultConfiguration.fileURL! = \(defaultURL)")
  //let defaultParentURL = defaultURL.URLByDeletingLastPathComponent

  if let realmURL = bundleURL("default-v1") {
    do {
      //print("Bundle location for default.realm = \(realmURL)")
      let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
      let url = URL(fileURLWithPath: path)
      let filePath = url.appendingPathComponent("default-v1.realm").path
      let fileManager = FileManager.default
      if fileManager.fileExists(atPath: filePath) {

         print("FILE INSTALLED")
        print("Documents location for default.realm = \(filePath)")
      } else {
        //print("FILE NOT INSTALLED, COPYING default.realm from bundle to Documents directory.")
        try FileManager.default.copyItem(at: realmURL, to: defaultURL)
      }
    } catch {}
  }
</code>```

I suspect that a new default-v1.realm file may clobber an existing default-v1.realm file on a user's device, using this code with the "Nothing is needed" migration method.

Part of the confusion stems from the example migration code at https://github.com/realm/realm-cocoa/tree/master/examples/ios/swift-3.0/Migration where data from the v1 file is getting copied over to the v2 file. Regardless, I've tried the "Nothing is needed" code you've posted and the app doesn't find any Realm data then crashes.

It looks like I could splice the code you've posted into the code I've been using then perhaps that would solve the problem. Will look into that next week.

Thanks for your response!

Body:
Unfortunately, that doesn't work, at all. There is a block of code I had to add to iOS apps several months ago in order to get Realm to work, but it doesn't solve the migration problems I've experienced:

      config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("default-v1.realm")
  Realm.Configuration.defaultConfiguration = config

  // copy over old data files for migration
  //let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
  let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
  //print("Realm.Configuration.defaultConfiguration.fileURL! = \(defaultURL)")
  //let defaultParentURL = defaultURL.URLByDeletingLastPathComponent

  if let realmURL = bundleURL("default-v1") {
    do {
      //print("Bundle location for default.realm = \(realmURL)")
      let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
      let url = URL(fileURLWithPath: path)
      let filePath = url.appendingPathComponent("default-v1.realm").path
      let fileManager = FileManager.default
      if fileManager.fileExists(atPath: filePath) {

         print("FILE INSTALLED")
        print("Documents location for default.realm = \(filePath)")
      } else {
        //print("FILE NOT INSTALLED, COPYING default.realm from bundle to Documents directory.")
        try FileManager.default.copyItem(at: realmURL, to: defaultURL)
      }
    } catch {}
  }

I suspect that a new default-v1.realm file may clobber an existing default-v1.realm file on a user's device, using this code with the "Nothing is needed" migration method.

Part of the confusion stems from the example migration code at https://github.com/realm/realm-cocoa/tree/master/examples/ios/swift-3.0/Migration where data from the v1 file is getting copied over to the v2 file. Regardless, I've tried the "Nothing is needed" code you've posted and the app doesn't find any Realm data then crashes.

It looks like I could splice the code you've posted into the code I've been using then perhaps that would solve the problem. Will look into that next week.

Thanks for your response!


问:
d3.js passing in multiple functions on hover
I used a tutorial to get this function on mouseover:

```<code>function arcTween(outerRadius, delay) {
    return function () {
        d3.select(this).transition().delay(delay).attrTween("d", function (d) {
            var i = d3.interpolate(d.outerRadius, outerRadius);
            return function (t) { d.outerRadius = i(t); return arc(d); };
        });
    };
}
</code>```

And I add it to parts of a pie chart this way:

```<code>.on("mouseover", arcTween(outerRadius, 0, 0))
</code>```

However, I also have text tags added to svg for each slice in the pie chart, and want those to fade away if you are hovering over a different slice. So I gave those  tags IDs when I create them based on the index, then wrote these two methods:

```<code>function visibilityShow(dataSetSize) {
    for (var i = 0; i < dataSetSize; i++) {
        $("#" + i).show();
    }
}

function visibilityHide(index, dataSetSize) {
    for (var i = 0; i < dataSetSize; i++) {
        if (i === index) {
            $("#" + i).show();
        } else {
            $("#" + i).hide();
        }
    }
}
</code>```

Now these work in a vacuum, but when I try to put them on a mouseover event, it won't work. arcTween stops working, and "i" is always 0. These were what I tried:

Adding another .on("mouseover", ...)

```<code>        .on("mouseover", arcTween(outerRadius, 0))
        .on("mouseover", visibility(0, dataSet.length));
</code>```

and also tried passing in the index with:

```<code>        .on("mouseover", arcTween(outerRadius, 0))
        .on("mouseover", function (d, i) { return visibility(i, d.length) });
</code>```

But that always passes in i = 0 in addition to seemingly overwriting the arcTween() call.

I also tried

```<code>.on("mouseover", function (d, i) {
     return function {
          arcTween(outerRadius, 0);
          visibility(i, d.length);
     }
})
</code>```

Anyone have any advice? (I'm using v3 because all the tutorials online are outdated.)

Thanks!

EDIT: Code Snippet

// This data will be gathered from API calls eventually
dataDefault = [];
dataController = [{ "label": "Example 1", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
                  { "label": "Example 2", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
                  { "label": "Example 3", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
                  { "label": "Example 4", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
                  { "label": "Example 5", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] }];

var displaySize = 20;

// This is used to keep track of what data is showing
var mode = "Default";

// The amount of pixels the SVG will take up
var width = 600,
    height = 675;

// It's a donut, so it has an outer radius and an inner radius. 2r = width so r = width/2
var outerRadius = width / 2,
    innerRadius = outerRadius / 3;

// Default color function for deciding the colros of the donut slices
var color = d3.scale.category10();

// The pie function for deciding the size of the donut slices
var pie = d3.layout.pie()
    .value(function (d) { return d["value"]; });

// At first we use the default data to create the pie
var pieData = pie(dataDefault);

// Create an arc
var arc = d3.svg.arc()
    .innerRadius(innerRadius);

// Add an SVG tag to the document
var svg = d3.select("#graphs").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + outerRadius + "," + (outerRadius + 50) + ")");

// Append an link tag for each point of the data, then add an path tag inside each a tag
svg.selectAll("a")
    .data(pieData)
  .enter().append("a")
    .append("path")
    .each(function (d) { d.outerRadius = outerRadius - 20; })
    .attr("d", arc)
    .attr("fill", function (d, i) { return color(i); })
    .on("mouseover", arcTween(outerRadius, 0, 0))
    .on("mouseout", arcTween(outerRadius - 20, 150))
        .append("title")
        .text(function (d) { return d["value"] + " hits"; });

// Change the default data to the Apps data so it animates on load
changeToAPI("Controller", dataController);

// Function used to increase slice size on hover
function arcTween(outerRadius, delay) {
    return function () {
        d3.select(this).transition().delay(delay).attrTween("d", function (d) {
            var i = d3.interpolate(d.outerRadius, outerRadius);
            return function (t) { d.outerRadius = i(t); return arc(d); };
        });
    };
}

// Passes the color scale into the change function
function getColor(name) {
    // Get the remainder when / 3
    var bucket = hashify(name) % 4;

    // Setup the array of color functions
    var colors = [d3.scale.category10(), d3.scale.category20(), d3.scale.category20b(), d3.scale.category20c()];

    // Return the correct bucket
    return colors[bucket];
}

// Function used to swap the data being shown
function changeToAPI(name, dataSet) {
    // Don't update if the data is already showing

    // JavaScript doesn't short circuit?
    if (dataSet === null) {
        dataSet = [{ "label": "No data...", "value": 1 }];
        changeTo(name, dataSet);
    } else if (dataSet.length === 0) {
        dataSet = [{ "label": "No data...", "value": 1 }];
        changeTo(name, dataSet);
    } else {

        mode = name;

        // Get the new pie and color functions
        var newData = pie(dataSet);
        var newColor = getColor(name);

        // Remove the labels, titles, and tooltips
        svg.selectAll("text").remove();
        svg.selectAll("title").remove();
        // Line below fixes an error that doesn't cause issues, but makes the graph ugly :(
        svg.selectAll("a").remove();

        // Add the new slices if there are any
        var newSlices = svg.selectAll("a")
                            .data(newData);

        newSlices.enter()
            .append("a")
                .append("path")
                .style("cursor", "pointer");

        // Update the attributes of those slices and animate the transition
        newSlices.select("path")
                .each(function (d) { d.outerRadius = outerRadius - 20; })
                .transition()
                .attr("d", arc)
                .attr("fill", function (d, i) { return newColor(i); })
                .attr("title", function (d) { return d["value"]; });

        newSlices.selectAll("path")
                    .on("click", function (d) {
                        checkForChild(d["data"]["label"], d["data"]);
                    })
                    .on("mouseover.arcExpand", arcTween(outerRadius, 0))
                    .on("mouseover.textHide", function (d, i) {
                        visibilityHide(i, dataSet.length);
                    })
                    .on("mouseout.arcRetract", arcTween(outerRadius - 20, 150))
                    .on("mouseout.textShow", function (d, i) {
                        visibilityShow(dataSet.length);
                    });

        // Remove excess slices
        newSlices.exit().remove();

        // Add a title
        var title = svg.append("text")
            .attr("x", 0)
            .attr("y", -(outerRadius + 10))
            .style("text-anchor", "middle")
            .text("Distrubution of " + name + " Usage");

        // Add labels
        var labels = svg.selectAll(null)
            .data(newData)
            .enter()
                .append("text")
                .attr("fill", "white")
                .attr("id", function (d, i) { return i })
                .attr("transform", function (d) {
                    d.innerRadius = 0;
                    d.outerRadius = outerRadius;
                    return "translate(" + arc.centroid(d) + ")";
                })
                .attr("text-anchor", "middle")
                .text(function (d, i) {
                    return dataSet[i]["label"];
                });

        // Add tooltips
        svg.selectAll("path").data(newData).append("title").text(function (d) { return d["value"] + " hits"; });

        svg.append("circle")
        .attr("cx", 0)
        .attr("cy", 0)
        .attr("r", innerRadius)
        .style("fill", "white")
        .style("cursor", "pointer")
        .on("click", function () {
            changeToAPI("Controller", dataController);
        });

        // Adds back button if not at controller level
        if (dataSet !== dataController) {
            svg.append("text")
                .attr("x", 0)
                .attr("y", 12)
                .style("text-anchor", "middle")
                .style("color", "#efefef")
                .style("font-size", "40px")
                .text("Back");
        }
    }
}

function changeTo(name, dataSet) {
    // Don't update if the data is already showing

    // JavaScript doesn't short circuit?
    if (dataSet === null) {
        dataSet = [{ "label": "No data...", "value": 1 }];
    } else if (dataSet.length === 0) {
        dataSet = [{ "label": "No data...", "value": 1 }];
    }

    mode = name;

    // Get the new pie and color functions
    var newData = pie(dataSet);
    var newColor = getColor(name);

    // Remove the labels, titles, and tooltips
    svg.selectAll("text").remove();
    svg.selectAll("title").remove();
    // Line below fixes an error that doesn't cause issues, but makes the graph ugly :(
    //svg.selectAll("a").remove();

    // Add the new slices if there are any
    var newSlices = svg.selectAll("a")
                        .data(newData);

    newSlices.enter()
        .append("a")
            .append("path")
            .style("cursor", "pointer");

    // Update the attributes of those slices and animate the transition
    newSlices.select("path")
            .each(function (d) { d.outerRadius = outerRadius - 20; })
            .transition()
            .attr("fill", function (d, i) { return newColor(i); })
            .attr("d", arc)
            .attr("title", function (d) { return d["value"]; });

    newSlices.selectAll("path")
                .on("mouseover.arc", arcTween(outerRadius, 0))
                .on("mouseover.text", function (d, i) {
                    visibilityHide(i, dataSet.length);
                 })
                .on("mouseout.arc", arcTween(outerRadius - 20, 150))
                .on("mouseout.text", function (d, i) {
                    visibilityShow(dataSet.length);
                });

    // Remove excess slices
    newSlices.exit().remove();

    // Add a title
    svg.append("text")
        .attr("x", 0)
        .attr("y", -(outerRadius + 10))
        .style("text-anchor", "middle")
        .text(function (e) {
            var title = "Distrubution of " + name + " Usage";
            if (name === "Defualt") {
                title = "Loading..."
            }
            return title;
        });

    // Add labels
    svg.selectAll(null)
        .data(newData)
        .enter()
            .append("text")
            .attr("fill", "white")
            .attr("id", function (d, i) { return i })
            .attr("transform", function (d) {
                d.innerRadius = 0;
                d.outerRadius = outerRadius;
                return "translate(" + arc.centroid(d) + ")";
            })
            .attr("text-anchor", "middle")
            .text(function (d, i) {
                return dataSet[i]["label"];
            });

    // Add tooltips
    svg.selectAll("path").data(newData).append("title").text(function (d) { return d["value"] + " hits"; });
}

function checkForChild(name, dataSet) {
    if (dataSet.hasOwnProperty("child")) {
        if (dataSet["child"] !== null) {
            if (dataSet["child"].length !== 0) {
                changeToAPI(name, dataSet["child"]);
            }
        }
    }
}

// Hashcode generator for strings
function hashify(string) {
    var hash = 0;

    // Add the value of each char to the hash value
    for (var i = 0; i < string.length; i++) {
        hash += string.charCodeAt(i);
    }

    return hash;
}

function visibilityShow(dataSetSize) {
    for (var i = 0; i < dataSetSize; i++) {
        $("#" + i).show();
    }
}

function visibilityHide(index, dataSetSize) {
    for (var i = 0; i < dataSetSize; i++) {
        if (i === index) {
            $("#" + i).show();
        } else {
            $("#" + i).hide();
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: Arial;
    transition: all ease .5s;
    text-align: center;
    color: rgb(58,58,58);
}</code>```

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />

    <title>General Statistics</title>

```

答:
If you have more than one event listener of the same type in the same selection, you have to namespace your event listeners (but this probably won't fix your issue, please also read the Post Scriptum further down).

The problem right now, as @AndrewReid explained in his comment, is that the next event listener removes the previous one. According to the API:

If an event listener was already registered for the same type on the selected element, the existing listener is removed before the new listener is added.

Let's see it in the following demo.

Since you didn't provide your working code, I create a simple one here, with two event listeners: the first one increases the circle, and the second one fades out the text:

```<code>.on("mouseover", increaseCircle)//this one will not work!
.on("mouseover", fadeText)//only this one will work...
</code>```

You can see that only the last one works:

var svg = d3.select("svg");

var circle = svg.append("circle")
  .attr("r", 20)
  .attr("cx", 100)
  .attr("cy", 50)
  .attr("fill", "tan")
  .attr("stroke", "black")
  .on("mouseover", increaseCircle)
  .on("mouseover", fadeText)
  .on("mouseout", function() {
    circle.transition().duration(500).attr("r", 20);
    text.transition().duration(500).style("opacity", 1);
  })

var text = svg.append("text")
  .attr("y", 55)
  .attr("x", 150)
  .style("font-family", "helvetica")
  .text("Hover over the circle");

function increaseCircle() {
  circle.transition().duration(500).attr("r", 40)
}

function fadeText() {
  text.transition().duration(500).style("opacity", 0)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v3.js"></script>
<svg></svg></code>```

Solution:

There is a very simple solution, though. According to the same API:

To register multiple listeners for the same event type, the type may be followed by an optional namespace, such as "click.foo" and "click.bar"

Thus, in the above demo, we just need something like this:

```<code>.on("mouseover.circle", increaseCircle)
.on("mouseover.text", fadeText)
</code>```

Here is the demo, both event listeners work:

var svg = d3.select("svg");

var circle = svg.append("circle")
  .attr("r", 20)
  .attr("cx", 100)
  .attr("cy", 50)
  .attr("fill", "tan")
  .attr("stroke", "black")
  .on("mouseover.circle", increaseCircle)
  .on("mouseover.text", fadeText)
  .on("mouseout", function() {
    circle.transition().duration(500).attr("r", 20);
    text.transition().duration(500).style("opacity", 1);
  })

var text = svg.append("text")
  .attr("y", 55)
  .attr("x", 150)
  .style("font-family", "helvetica")
  .text("Hover over the circle");

function increaseCircle() {
  circle.transition().duration(500).attr("r", 40)
}

function fadeText() {
  text.transition().duration(500).style("opacity", 0)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v3.js"></script>
<svg></svg></code>```

Of course, a simple alternative to all this is just:

```<code>selection.on("mouseover", function(){
    foo();
    bar();
    baz();
    etc...
});
</code>```

PS: The above answer deals with the namespace issue. However, besides that issue, your code has a couple of problems, which we cannot test because you didn't provide a working demo.

First problem: when you do this...

```<code>.on("mouseover", arcTween(outerRadius, 0, 0))
</code>```

... you are calling arcTween immediately, and passing its value to the listener. You probably want:

```<code>.on("mouseover", function(){ arcTween(outerRadius, 0, 0)})
</code>```

Second, this is not correct:

```<code>.on("mouseover", function (d, i) {
    return function {
        arcTween(outerRadius, 0);
        visibility(i, d.length);
    }
})
</code>```

It should be just:

```<code>.on("mouseover", function (d, i) {
    arcTween(outerRadius, 0);
    visibility(i, d.length);
})
</code>```

Body:
I used a tutorial to get this function on mouseover:

function arcTween(outerRadius, delay) {
    return function () {
        d3.select(this).transition().delay(delay).attrTween("d", function (d) {
            var i = d3.interpolate(d.outerRadius, outerRadius);
            return function (t) { d.outerRadius = i(t); return arc(d); };
        });
    };
}

And I add it to parts of a pie chart this way:

.on("mouseover", arcTween(outerRadius, 0, 0))

However, I also have text tags added to svg for each slice in the pie chart, and want those to fade away if you are hovering over a different slice. So I gave those  tags IDs when I create them based on the index, then wrote these two methods:

function visibilityShow(dataSetSize) {
    for (var i = 0; i < dataSetSize; i++) {
        $("#" + i).show();
    }
}

function visibilityHide(index, dataSetSize) {
    for (var i = 0; i < dataSetSize; i++) {
        if (i === index) {
            $("#" + i).show();
        } else {
            $("#" + i).hide();
        }
    }
}

Now these work in a vacuum, but when I try to put them on a mouseover event, it won't work. arcTween stops working, and "i" is always 0. These were what I tried:

Adding another .on("mouseover", ...)

        .on("mouseover", arcTween(outerRadius, 0))
        .on("mouseover", visibility(0, dataSet.length));

and also tried passing in the index with:

        .on("mouseover", arcTween(outerRadius, 0))
        .on("mouseover", function (d, i) { return visibility(i, d.length) });

But that always passes in i = 0 in addition to seemingly overwriting the arcTween() call.

I also tried

.on("mouseover", function (d, i) {
     return function {
          arcTween(outerRadius, 0);
          visibility(i, d.length);
     }
})

Anyone have any advice? (I'm using v3 because all the tutorials online are outdated.)

Thanks!

EDIT: Code Snippet

// This data will be gathered from API calls eventually
dataDefault = [];
dataController = [{ "label": "Example 1", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
                  { "label": "Example 2", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
                  { "label": "Example 3", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
                  { "label": "Example 4", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] },
                  { "label": "Example 5", "value": 1, "child": [{ "label": "Child 1", "value": 1 }] }];

var displaySize = 20;

// This is used to keep track of what data is showing
var mode = "Default";

// The amount of pixels the SVG will take up
var width = 600,
    height = 675;

// It's a donut, so it has an outer radius and an inner radius. 2r = width so r = width/2
var outerRadius = width / 2,
    innerRadius = outerRadius / 3;

// Default color function for deciding the colros of the donut slices
var color = d3.scale.category10();

// The pie function for deciding the size of the donut slices
var pie = d3.layout.pie()
    .value(function (d) { return d["value"]; });

// At first we use the default data to create the pie
var pieData = pie(dataDefault);

// Create an arc
var arc = d3.svg.arc()
    .innerRadius(innerRadius);

// Add an SVG tag to the document
var svg = d3.select("#graphs").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + outerRadius + "," + (outerRadius + 50) + ")");

// Append an link tag for each point of the data, then add an path tag inside each a tag
svg.selectAll("a")
    .data(pieData)
  .enter().append("a")
    .append("path")
    .each(function (d) { d.outerRadius = outerRadius - 20; })
    .attr("d", arc)
    .attr("fill", function (d, i) { return color(i); })
    .on("mouseover", arcTween(outerRadius, 0, 0))
    .on("mouseout", arcTween(outerRadius - 20, 150))
        .append("title")
        .text(function (d) { return d["value"] + " hits"; });

// Change the default data to the Apps data so it animates on load
changeToAPI("Controller", dataController);

// Function used to increase slice size on hover
function arcTween(outerRadius, delay) {
    return function () {
        d3.select(this).transition().delay(delay).attrTween("d", function (d) {
            var i = d3.interpolate(d.outerRadius, outerRadius);
            return function (t) { d.outerRadius = i(t); return arc(d); };
        });
    };
}

// Passes the color scale into the change function
function getColor(name) {
    // Get the remainder when / 3
    var bucket = hashify(name) % 4;

    // Setup the array of color functions
    var colors = [d3.scale.category10(), d3.scale.category20(), d3.scale.category20b(), d3.scale.category20c()];

    // Return the correct bucket
    return colors[bucket];
}

// Function used to swap the data being shown
function changeToAPI(name, dataSet) {
    // Don't update if the data is already showing

    // JavaScript doesn't short circuit?
    if (dataSet === null) {
        dataSet = [{ "label": "No data...", "value": 1 }];
        changeTo(name, dataSet);
    } else if (dataSet.length === 0) {
        dataSet = [{ "label": "No data...", "value": 1 }];
        changeTo(name, dataSet);
    } else {

        mode = name;

        // Get the new pie and color functions
        var newData = pie(dataSet);
        var newColor = getColor(name);

        // Remove the labels, titles, and tooltips
        svg.selectAll("text").remove();
        svg.selectAll("title").remove();
        // Line below fixes an error that doesn't cause issues, but makes the graph ugly :(
        svg.selectAll("a").remove();

        // Add the new slices if there are any
        var newSlices = svg.selectAll("a")
                            .data(newData);

        newSlices.enter()
            .append("a")
                .append("path")
                .style("cursor", "pointer");

        // Update the attributes of those slices and animate the transition
        newSlices.select("path")
                .each(function (d) { d.outerRadius = outerRadius - 20; })
                .transition()
                .attr("d", arc)
                .attr("fill", function (d, i) { return newColor(i); })
                .attr("title", function (d) { return d["value"]; });

        newSlices.selectAll("path")
                    .on("click", function (d) {
                        checkForChild(d["data"]["label"], d["data"]);
                    })
                    .on("mouseover.arcExpand", arcTween(outerRadius, 0))
                    .on("mouseover.textHide", function (d, i) {
                        visibilityHide(i, dataSet.length);
                    })
                    .on("mouseout.arcRetract", arcTween(outerRadius - 20, 150))
                    .on("mouseout.textShow", function (d, i) {
                        visibilityShow(dataSet.length);
                    });

        // Remove excess slices
        newSlices.exit().remove();

        // Add a title
        var title = svg.append("text")
            .attr("x", 0)
            .attr("y", -(outerRadius + 10))
            .style("text-anchor", "middle")
            .text("Distrubution of " + name + " Usage");

        // Add labels
        var labels = svg.selectAll(null)
            .data(newData)
            .enter()
                .append("text")
                .attr("fill", "white")
                .attr("id", function (d, i) { return i })
                .attr("transform", function (d) {
                    d.innerRadius = 0;
                    d.outerRadius = outerRadius;
                    return "translate(" + arc.centroid(d) + ")";
                })
                .attr("text-anchor", "middle")
                .text(function (d, i) {
                    return dataSet[i]["label"];
                });

        // Add tooltips
        svg.selectAll("path").data(newData).append("title").text(function (d) { return d["value"] + " hits"; });

        svg.append("circle")
        .attr("cx", 0)
        .attr("cy", 0)
        .attr("r", innerRadius)
        .style("fill", "white")
        .style("cursor", "pointer")
        .on("click", function () {
            changeToAPI("Controller", dataController);
        });

        // Adds back button if not at controller level
        if (dataSet !== dataController) {
            svg.append("text")
                .attr("x", 0)
                .attr("y", 12)
                .style("text-anchor", "middle")
                .style("color", "#efefef")
                .style("font-size", "40px")
                .text("Back");
        }
    }
}

function changeTo(name, dataSet) {
    // Don't update if the data is already showing

    // JavaScript doesn't short circuit?
    if (dataSet === null) {
        dataSet = [{ "label": "No data...", "value": 1 }];
    } else if (dataSet.length === 0) {
        dataSet = [{ "label": "No data...", "value": 1 }];
    }

    mode = name;

    // Get the new pie and color functions
    var newData = pie(dataSet);
    var newColor = getColor(name);

    // Remove the labels, titles, and tooltips
    svg.selectAll("text").remove();
    svg.selectAll("title").remove();
    // Line below fixes an error that doesn't cause issues, but makes the graph ugly :(
    //svg.selectAll("a").remove();

    // Add the new slices if there are any
    var newSlices = svg.selectAll("a")
                        .data(newData);

    newSlices.enter()
        .append("a")
            .append("path")
            .style("cursor", "pointer");

    // Update the attributes of those slices and animate the transition
    newSlices.select("path")
            .each(function (d) { d.outerRadius = outerRadius - 20; })
            .transition()
            .attr("fill", function (d, i) { return newColor(i); })
            .attr("d", arc)
            .attr("title", function (d) { return d["value"]; });

    newSlices.selectAll("path")
                .on("mouseover.arc", arcTween(outerRadius, 0))
                .on("mouseover.text", function (d, i) {
                    visibilityHide(i, dataSet.length);
                 })
                .on("mouseout.arc", arcTween(outerRadius - 20, 150))
                .on("mouseout.text", function (d, i) {
                    visibilityShow(dataSet.length);
                });

    // Remove excess slices
    newSlices.exit().remove();

    // Add a title
    svg.append("text")
        .attr("x", 0)
        .attr("y", -(outerRadius + 10))
        .style("text-anchor", "middle")
        .text(function (e) {
            var title = "Distrubution of " + name + " Usage";
            if (name === "Defualt") {
                title = "Loading..."
            }
            return title;
        });

    // Add labels
    svg.selectAll(null)
        .data(newData)
        .enter()
            .append("text")
            .attr("fill", "white")
            .attr("id", function (d, i) { return i })
            .attr("transform", function (d) {
                d.innerRadius = 0;
                d.outerRadius = outerRadius;
                return "translate(" + arc.centroid(d) + ")";
            })
            .attr("text-anchor", "middle")
            .text(function (d, i) {
                return dataSet[i]["label"];
            });

    // Add tooltips
    svg.selectAll("path").data(newData).append("title").text(function (d) { return d["value"] + " hits"; });
}

function checkForChild(name, dataSet) {
    if (dataSet.hasOwnProperty("child")) {
        if (dataSet["child"] !== null) {
            if (dataSet["child"].length !== 0) {
                changeToAPI(name, dataSet["child"]);
            }
        }
    }
}

// Hashcode generator for strings
function hashify(string) {
    var hash = 0;

    // Add the value of each char to the hash value
    for (var i = 0; i < string.length; i++) {
        hash += string.charCodeAt(i);
    }

    return hash;
}

function visibilityShow(dataSetSize) {
    for (var i = 0; i < dataSetSize; i++) {
        $("#" + i).show();
    }
}

function visibilityHide(index, dataSetSize) {
    for (var i = 0; i < dataSetSize; i++) {
        if (i === index) {
            $("#" + i).show();
        } else {
            $("#" + i).hide();
        }
    }
}

body {
    font-family: Arial;
    transition: all ease .5s;
    text-align: center;
    color: rgb(58,58,58);
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />

    <title>General Statistics</title>

Body:
If you have more than one event listener of the same type in the same selection, you have to namespace your event listeners (but this probably won't fix your issue, please also read the Post Scriptum further down).

The problem right now, as @AndrewReid explained in his comment, is that the next event listener removes the previous one. According to the API:

If an event listener was already registered for the same type on the selected element, the existing listener is removed before the new listener is added.

Let's see it in the following demo.

Since you didn't provide your working code, I create a simple one here, with two event listeners: the first one increases the circle, and the second one fades out the text:

.on("mouseover", increaseCircle)//this one will not work!
.on("mouseover", fadeText)//only this one will work...

You can see that only the last one works:

var svg = d3.select("svg");

var circle = svg.append("circle")
  .attr("r", 20)
  .attr("cx", 100)
  .attr("cy", 50)
  .attr("fill", "tan")
  .attr("stroke", "black")
  .on("mouseover", increaseCircle)
  .on("mouseover", fadeText)
  .on("mouseout", function() {
    circle.transition().duration(500).attr("r", 20);
    text.transition().duration(500).style("opacity", 1);
  })

var text = svg.append("text")
  .attr("y", 55)
  .attr("x", 150)
  .style("font-family", "helvetica")
  .text("Hover over the circle");

function increaseCircle() {
  circle.transition().duration(500).attr("r", 40)
}

function fadeText() {
  text.transition().duration(500).style("opacity", 0)
}

<script src="https://d3js.org/d3.v3.js"></script>
<svg></svg>

Solution:

There is a very simple solution, though. According to the same API:

To register multiple listeners for the same event type, the type may be followed by an optional namespace, such as "click.foo" and "click.bar"

Thus, in the above demo, we just need something like this:

.on("mouseover.circle", increaseCircle)
.on("mouseover.text", fadeText)

Here is the demo, both event listeners work:

var svg = d3.select("svg");

var circle = svg.append("circle")
  .attr("r", 20)
  .attr("cx", 100)
  .attr("cy", 50)
  .attr("fill", "tan")
  .attr("stroke", "black")
  .on("mouseover.circle", increaseCircle)
  .on("mouseover.text", fadeText)
  .on("mouseout", function() {
    circle.transition().duration(500).attr("r", 20);
    text.transition().duration(500).style("opacity", 1);
  })

var text = svg.append("text")
  .attr("y", 55)
  .attr("x", 150)
  .style("font-family", "helvetica")
  .text("Hover over the circle");

function increaseCircle() {
  circle.transition().duration(500).attr("r", 40)
}

function fadeText() {
  text.transition().duration(500).style("opacity", 0)
}

<script src="https://d3js.org/d3.v3.js"></script>
<svg></svg>

Of course, a simple alternative to all this is just:

selection.on("mouseover", function(){
    foo();
    bar();
    baz();
    etc...
});

PS: The above answer deals with the namespace issue. However, besides that issue, your code has a couple of problems, which we cannot test because you didn't provide a working demo.

First problem: when you do this...

.on("mouseover", arcTween(outerRadius, 0, 0))

... you are calling arcTween immediately, and passing its value to the listener. You probably want:

.on("mouseover", function(){ arcTween(outerRadius, 0, 0)})

Second, this is not correct:

.on("mouseover", function (d, i) {
    return function {
        arcTween(outerRadius, 0);
        visibility(i, d.length);
    }
})

It should be just:

.on("mouseover", function (d, i) {
    arcTween(outerRadius, 0);
    visibility(i, d.length);
})


问:
Unmarshal and append to array go
I'm reading a number of JSON files from S3, and want to return them all as one large JSON array. I have a struct matching my JSON data, and a for loop iterating over all objects in my s3 bucket. Each time I read, I unmarshal to my struct array. I want to append to my struct array so that I can get all the JSON data rather than just one file's data. Is there anyway to do this in Golang?</p>

答:
Yes, you should create a temporary array to Unmarshal the contents of each JSON, then append the items to your final result array in order to return the whole collection as one item.

See here an example of doing that.

In your case input would come from each of the S3 files you mention. Also, you would probably put that unmarshal logic in its own function to be able to call it for each input JSON.

```<code>package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Record struct {
    Author string `json:"author"`
    Title  string `json:"title"`
}

func main() {
    var allRecords []Record

    input := []byte(`[{
      "author": "Nirvana",
      "title":  "Smells like teen spirit"
    }, {
      "author": "The Beatles",
      "title":  "Help"
    }]`)

    var tmpRecords []Record
    err := json.Unmarshal(input, &tmpRecords)
    if (err != nil) {
        log.Fatal(err)
    }

    allRecords = append(allRecords, tmpRecords...)

    fmt.Println("RECORDS:", allRecords)
}
</code>```

https://play.golang.org/p/ZZGhy4UNhP

Title: Unmarshal and append to array go

Body:
Yes, you should create a temporary array to Unmarshal the contents of each JSON, then append the items to your final result array in order to return the whole collection as one item.

See here an example of doing that.

In your case input would come from each of the S3 files you mention. Also, you would probably put that unmarshal logic in its own function to be able to call it for each input JSON.

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Record struct {
    Author string `json:"author"`
    Title  string `json:"title"`
}

func main() {
    var allRecords []Record

    input := []byte(`[{
      "author": "Nirvana",
      "title":  "Smells like teen spirit"
    }, {
      "author": "The Beatles",
      "title":  "Help"
    }]`)

    var tmpRecords []Record
    err := json.Unmarshal(input, &tmpRecords)
    if (err != nil) {
        log.Fatal(err)
    }

    allRecords = append(allRecords, tmpRecords...)

    fmt.Println("RECORDS:", allRecords)
}

https://play.golang.org/p/ZZGhy4UNhP


问:
node.js send http request with temporary /etc/hosts setting
/etc/hosts file allows us to specify an ip address for a domain.

For example, if the content of /etc/hosts file looks like this:

```<code>127.0.0.1 www.mydomain.com
</code>```

It means that www.mydomain.com represents 127.0.0.1 when you type www.mydomain.com in the browser URL bar.

Is it possible to specify a domain for an ip address when sending requests with http.get() without modifying /etc/hosts?

I work on a public ubuntu machine where many people get access to /etc/hosts file. So it's best not to modify /etc/hosts.

The options parameter does not support this feature.

And I don't want to use hostile because it changes /etc/hosts.

答:
You will probably need to use your own http.Agent or createConnection(). For example:

```<code>function customLookup(hostname, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = null;
  }
  // TODO: check `options` for options like `all` and `family`
  if (hostname.toLowerCase() === 'www.mydomain.com')
    return callback(null, '127.0.0.1');
  return dns.lookup(hostname, options, callback);
}

function createConnection(opts) {
  opts.lookup = customLookup;
  return net.createConnection(opts);
}

http.get({
  // ...
  createConnection
});
</code>```

Body:
/etc/hosts file allows us to specify an ip address for a domain.

For example, if the content of /etc/hosts file looks like this:

127.0.0.1 www.mydomain.com

It means that www.mydomain.com represents 127.0.0.1 when you type www.mydomain.com in the browser URL bar.

Is it possible to specify a domain for an ip address when sending requests with http.get() without modifying /etc/hosts?

I work on a public ubuntu machine where many people get access to /etc/hosts file. So it's best not to modify /etc/hosts.

The options parameter does not support this feature.

And I don't want to use hostile because it changes /etc/hosts.

Body:
You will probably need to use your own http.Agent or createConnection(). For example:

function customLookup(hostname, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = null;
  }
  // TODO: check `options` for options like `all` and `family`
  if (hostname.toLowerCase() === 'www.mydomain.com')
    return callback(null, '127.0.0.1');
  return dns.lookup(hostname, options, callback);
}

function createConnection(opts) {
  opts.lookup = customLookup;
  return net.createConnection(opts);
}

http.get({
  // ...
  createConnection
});


问:
JavaScript running pretty slow in specific computer
I writing a code that take a Black & White image and check the pixels  in an specific area (with an square shape) and finally retur the sum of how many of them are balck, each pixel of the area is read in a For loop like the next example:

```<code>    function is_box_black_corner(x,y,width,heigth){
    var counter=0;
    for (var i=x; i<(x+width); i++){
        for (var j=y; j<(y+heigth); j++){
            if(my_isblack(i,j)==1){
                counter++;
            }
        }
    }
</code>```

And as you can see inside the for loop a I call a function that verifies if the specific pixel is fairly black:

```<code>   function my_isblack(x,y){
        var p = ctx.getImageData(x, y, 1, 1).data;
        if(p[0]<50 && p[1]<50 && p[2]<50){
            return 1;
        }
        else{
            return 0;
        }
    }
</code>```

As you can imagine, this is a little bit computational expensive. but the problem is that with my computer, suddenly it got much slower than others (even with worst processors).  I already check the RAM memory and the processor and none of them were used more than 30%, and the processor before running the code is close to 0%.

And don’t know where else to look. I appreciate some help, also if somebody knows how to do this much faster it will be highly apreciated

答:
I will try wiht one call to getImageData as suggested by @ASDFGerte:

```<code>var x=10; var y=10; var width=50; var height=50;
var counter=0;
var image;
var p;   //global data

function init(){
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "black";
    ctx.fillRect(10, 10, 50, 50);      //this is just a black square

    image = ctx.getImageData(x, y, width, height);      //Load the image
    p = image.data;                                     //get the data of the image
    is_box_black_corner();
};

function is_box_black_corner(){
    for (var i=x; i<(x+width); i++){
        for (var j=y; j<(y+height); j++){
            if(my_isblack(i,j)==1){
            counter++;
            }
        }
    }
    console.log(counter);
};

function my_isblack(x,y){
    if(p[0]<50 && p[1]<50 && p[2]<50){  //check the global data
        return 1;
    }
    else{
        return 0;
    }
};
</code>```

Body:
I writing a code that take a Black & White image and check the pixels  in an specific area (with an square shape) and finally retur the sum of how many of them are balck, each pixel of the area is read in a For loop like the next example:

    function is_box_black_corner(x,y,width,heigth){
    var counter=0;
    for (var i=x; i<(x+width); i++){
        for (var j=y; j<(y+heigth); j++){
            if(my_isblack(i,j)==1){
                counter++;
            }
        }
    }

And as you can see inside the for loop a I call a function that verifies if the specific pixel is fairly black:

   function my_isblack(x,y){
        var p = ctx.getImageData(x, y, 1, 1).data;
        if(p[0]<50 && p[1]<50 && p[2]<50){
            return 1;
        }
        else{
            return 0;
        }
    }

As you can imagine, this is a little bit computational expensive. but the problem is that with my computer, suddenly it got much slower than others (even with worst processors).  I already check the RAM memory and the processor and none of them were used more than 30%, and the processor before running the code is close to 0%.

And don’t know where else to look. I appreciate some help, also if somebody knows how to do this much faster it will be highly apreciated

Body:
I will try wiht one call to getImageData as suggested by @ASDFGerte:

var x=10; var y=10; var width=50; var height=50;
var counter=0;
var image;
var p;   //global data

function init(){
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "black";
    ctx.fillRect(10, 10, 50, 50);      //this is just a black square

    image = ctx.getImageData(x, y, width, height);      //Load the image
    p = image.data;                                     //get the data of the image
    is_box_black_corner();
};

function is_box_black_corner(){
    for (var i=x; i<(x+width); i++){
        for (var j=y; j<(y+height); j++){
            if(my_isblack(i,j)==1){
            counter++;
            }
        }
    }
    console.log(counter);
};

function my_isblack(x,y){
    if(p[0]<50 && p[1]<50 && p[2]<50){  //check the global data
        return 1;
    }
    else{
        return 0;
    }
};


问:
Can recursion be used to guarantee an object gets saved to the DB in Ruby?
I am making payouts to my sub-merchants and wanted to know if I could use recursion to guarantee that when a payout is made to them, we save that data to our DB.

Example:

```<code>def make_payout
  result = object.process_payout_through_gateway
  if result.success?
    payout = Payout.new
    payout[:paid] = true
    save_payout(payout)
  end
end

def save_payout(payout)
  begin
    payout.save!
  rescue e
    save_payout(payout)
  end
end
</code>```

答:
The short answer is no. Unless the error is transient, retrying the save operation over and over again will not help you and in some cases it could even exacerbate the problem.

If you expect certain errors to routinely occur during normal operation, you can choose to selectively handle those errors by retrying the operation, for example. The keyword here is selectiveness - if you blindly rescue everything, you risk retrying the operation even when the error is caused by something you cannot routinely recover from, like a programming bug. Therefore, you should always specify a specific exception class that you would like to rescue:

```<code>begin
  payout.save!
rescue ExceptionThatHappensSometimesButIsNoBigDeal
  # ignore error + maybe log it, etc.
end
</code>```

Catching certain exceptions and retrying the operation later is a strategy frequently used when talking to non-critical external APIs, since those can have transient outages at any time. If you don't ignore these non-critical exceptions, they bubble up and bring down your app with them as well.

However, retrying failed operations that only touch systems which you have control over (such as saving to the local database) is usually counterproductive - if you silently ignore these errors, you risk not finding out about them in time.

Body:
I am making payouts to my sub-merchants and wanted to know if I could use recursion to guarantee that when a payout is made to them, we save that data to our DB.

Example:

def make_payout
  result = object.process_payout_through_gateway
  if result.success?
    payout = Payout.new
    payout[:paid] = true
    save_payout(payout)
  end
end

def save_payout(payout)
  begin
    payout.save!
  rescue e
    save_payout(payout)
  end
end

Body:
The short answer is no. Unless the error is transient, retrying the save operation over and over again will not help you and in some cases it could even exacerbate the problem.

If you expect certain errors to routinely occur during normal operation, you can choose to selectively handle those errors by retrying the operation, for example. The keyword here is selectiveness - if you blindly rescue everything, you risk retrying the operation even when the error is caused by something you cannot routinely recover from, like a programming bug. Therefore, you should always specify a specific exception class that you would like to rescue:

begin
  payout.save!
rescue ExceptionThatHappensSometimesButIsNoBigDeal
  # ignore error + maybe log it, etc.
end

Catching certain exceptions and retrying the operation later is a strategy frequently used when talking to non-critical external APIs, since those can have transient outages at any time. If you don't ignore these non-critical exceptions, they bubble up and bring down your app with them as well.

However, retrying failed operations that only touch systems which you have control over (such as saving to the local database) is usually counterproductive - if you silently ignore these errors, you risk not finding out about them in time.


问:
how to measure execution time in specific part of View
I want to calculate execution time in a specific part of View in MVC asp.net
for example

```<code><p>start time is A</p>

<br />

@for (int i = 0; i < 1000000; i++)
{

        if (@i % 100000 == 0)
        {
         <p>@i</p> <br />
        }

}
 <p>End time is B</p>
<p>execution time is: C</p>
</code>```

how to calculate A, B, C in above code ?

答:
What I would recommend you to do here is to create an instance of Stopwatch by Stopwatch.StartNew, execute your method or your code that you want to calculate execution time. Stop the Stopwatch where you think you method should be done with execution, and then get ElapsedMilliseconds like I will do in code below:

```<code>@{
  Stopwatch stopwatch = Stopwatch.StartNew();
  for (int i = 0; i < 1000000; i++)
  {
    if (i % 100000 == 0)
        {
             @Html.Raw("<p>" + i.ToString() + "</p> <br />");
        }

    }
   stopwatch.Stop();
   @Html.Raw("<p>Elapsed time is: " + stopwatch.ElapsedMilliseconds.ToString() + "</p>");
}
</code>```

And please, in case you might get an Error while you are trying to execute this code, be sure that you've included System.Diagnostics;

P.S If you don't like stopwatch.ElapsedMilliseconds you might check also for stopwatch.Elapsed to display elapsed time..

As I can see after Alexander's comment that you want start time, end time etc, what I suggest you to do here is to create a custom Stopwatch by inheriting System.Diagnostics.Stopwatchclass and extending it with a couple of DateTime properties.

And I will now show you how you might do it:

```<code>public class MyCustomStopWatch : Stopwatch
{

        public DateTime? StartAt { get; private set; }
        public DateTime? EndAt { get; private set; }

        public void Reset()
        {
            StartAt = null;
            EndAt = null;

            base.Reset();
        }

        public void Restart()
        {
            StartAt = DateTime.Now;
            EndAt = null;

            base.Restart();
        }

        //This is what is important to you right now, to get data about that when you code started, and when your code finished with executing
        public void Start()
        {
            StartAt = DateTime.Now;

            base.Start();
        }

        public void Stop()
        {
            EndAt = DateTime.Now;

            base.Stop();
        }

 }
</code>```

If you are wondering HOW COULD I USE THAT CODE?

DON'T WORRY, HERE IS AN EXAMPLE BASED ON YOUR QUESTION:

```<code>@{
      MyCustomStopwatch stopwatch = MyCustomStopwatch();
      for (int i = 0; i < 1000000; i++)
      {
        if (i % 100000 == 0)
            {
                 @Html.Raw("<p>" + i.ToString() + "</p> <br />");
            }

        }
       stopwatch.Stop();
       @Html.Raw(String.Format("<p>Stopwatch elapsed: {0}, StartAt: {1}, EndAt: {2} </p>", stopwatch.ElapsedMilliseconds.ToString(), stopwatch.StartAt.Value.ToString(), stopwatch.EndAt.Value.ToString());
    }
</code>```

Whatever I hope that you catch up the point and I hope that this helped you to solve your problem

Body:
I want to calculate execution time in a specific part of View in MVC asp.net
for example

start time is A

@for (int i = 0; i < 1000000; i++)
{

        if (@i % 100000 == 0)
        {

@i

        }

}

End time is B

execution time is: C

how to calculate A, B, C in above code ?

Body:
What I would recommend you to do here is to create an instance of Stopwatch by Stopwatch.StartNew, execute your method or your code that you want to calculate execution time. Stop the Stopwatch where you think you method should be done with execution, and then get ElapsedMilliseconds like I will do in code below:

@{
  Stopwatch stopwatch = Stopwatch.StartNew();
  for (int i = 0; i < 1000000; i++)
  {
    if (i % 100000 == 0)
        {
             @Html.Raw("<p>" + i.ToString() + "</p> <br />");
        }

    }
   stopwatch.Stop();
   @Html.Raw("<p>Elapsed time is: " + stopwatch.ElapsedMilliseconds.ToString() + "</p>");
}

And please, in case you might get an Error while you are trying to execute this code, be sure that you've included System.Diagnostics;

P.S If you don't like stopwatch.ElapsedMilliseconds you might check also for stopwatch.Elapsed to display elapsed time..

As I can see after Alexander's comment that you want start time, end time etc, what I suggest you to do here is to create a custom Stopwatch by inheriting System.Diagnostics.Stopwatchclass and extending it with a couple of DateTime properties.

And I will now show you how you might do it:

public class MyCustomStopWatch : Stopwatch
{

        public DateTime? StartAt { get; private set; }
        public DateTime? EndAt { get; private set; }

        public void Reset()
        {
            StartAt = null;
            EndAt = null;

            base.Reset();
        }

        public void Restart()
        {
            StartAt = DateTime.Now;
            EndAt = null;

            base.Restart();
        }

        //This is what is important to you right now, to get data about that when you code started, and when your code finished with executing
        public void Start()
        {
            StartAt = DateTime.Now;

            base.Start();
        }

        public void Stop()
        {
            EndAt = DateTime.Now;

            base.Stop();
        }

 }

If you are wondering HOW COULD I USE THAT CODE?

DON'T WORRY, HERE IS AN EXAMPLE BASED ON YOUR QUESTION:

@{
      MyCustomStopwatch stopwatch = MyCustomStopwatch();
      for (int i = 0; i < 1000000; i++)
      {
        if (i % 100000 == 0)
            {
                 @Html.Raw("<p>" + i.ToString() + "</p> <br />");
            }

        }
       stopwatch.Stop();
       @Html.Raw(String.Format("<p>Stopwatch elapsed: {0}, StartAt: {1}, EndAt: {2} </p>", stopwatch.ElapsedMilliseconds.ToString(), stopwatch.StartAt.Value.ToString(), stopwatch.EndAt.Value.ToString());
    }

Whatever I hope that you catch up the point and I hope that this helped you to solve your problem


问:
Modifying colors of geom_bar
I am having problems to group colors and present them in legend. The function takes in one level that is not within the data (3rd), and shows it in the legend, but does not do the same with 4th.

```<code>x <- structure(list(date = structure(c(1498521600, 1498525200, 1498528800,
1498532400, 1498536000, 1498539600, 1498543200, 1498546800, 1498550400,
1498554000, 1498557600, 1498561200, 1498564800, 1498568400, 1498572000,
1498575600, 1498579200, 1498582800), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), irish_rules_sensitive = c(0, 0, 0, 0, 0, 1,
2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("date", "irish_rules_sensitive"
), row.names = c(NA, -18L), class = c("tbl_df", "tbl", "data.frame"
))
color_var_sens <- vector(mode = "double",length = length(x$irish_rules_sensitive))
color_var_sens[color_var_sens== '0']<- NA
color_var_sens[x$irish_rules_sensitive>=1 & x$irish_rules_sensitive<=3] <- "#FFFF00"
color_var_sens[x$irish_rules_sensitive>=3 & x$irish_rules_sensitive<6] <- "#FFAA00"
color_var_sens[x$irish_rules_sensitive>=6 & x$irish_rules_sensitive<9] <- "#FF5500"
color_var_sens[x$irish_rules_sensitive>=12] <- "#FF0000"

p5 <- ggplot(x)+
  geom_col(aes(x = date, y = irish_rules_sensitive, color = color_var_sens, group = 1), size= 1)+
  scale_y_continuous(limits = c(0, 40) )+
  labs(x="", y="Accum. EBHours")+
  scale_color_identity("Modified Irish Rules", breaks= rev(levels(as.factor(color_var_sens)))[c(1,2,3,4)],
                       labels = c("Low ","Medium", "High", "Very High"),
                       guide = "legend",drop = FALSE)
p5 + guides(colour=guide_legend(override.aes=list(fill=c("#FFFF00","#FFAA00","#FF5500", "#FF0000" ))), size = "none")
</code>```

The weird thing is that this sometimes works and result should be something like this:

Error code:

```<code>    Error in `[[<-.data.frame`(`*tmp*`, v, value = c("#FFFF00", "#FFAA00",  :
  replacement has 4 rows, data has 3
</code>```

答:
The problem happens because color_var_sens is not a factor and the guide_legend tries do replace values that do not exist in color_car_sens. You should make it a factor. In that way you do not need theguide_legend:

```<code>color_var_sens <- factor(level=rev(c("#FFFF00","#FFAA00","#FF5500", "#FF0000" )), ordered=T)
color_var_sens[color_var_sens== '0']<- NA
color_var_sens[x$irish_rules_sensitive>=1 & x$irish_rules_sensitive<=3] <- "#FFFF00"
color_var_sens[x$irish_rules_sensitive>=3 & x$irish_rules_sensitive<6] <- "#FFAA00"
color_var_sens[x$irish_rules_sensitive>=6 & x$irish_rules_sensitive<9] <- "#FF5500"
color_var_sens[x$irish_rules_sensitive>=12] <- "#FF0000"

ggplot(x,aes(x = date, y = irish_rules_sensitive, fill = color_var_sens))+
  geom_col( size= 1)+
  scale_y_continuous(limits = c(0, 40) ) +
  labs(x="", y="Accum. EBHours") +
  scale_fill_identity("Modified Irish Rules", breaks= rev(levels(as.factor(color_var_sens))),
                       labels = c("Low ","Medium", "High", "Very High"),
                       guide = "legend",drop = FALSE)
</code>```

Title: Modifying colors of geom_bar

Body:
I am having problems to group colors and present them in legend. The function takes in one level that is not within the data (3rd), and shows it in the legend, but does not do the same with 4th.

x <- structure(list(date = structure(c(1498521600, 1498525200, 1498528800,
1498532400, 1498536000, 1498539600, 1498543200, 1498546800, 1498550400,
1498554000, 1498557600, 1498561200, 1498564800, 1498568400, 1498572000,
1498575600, 1498579200, 1498582800), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), irish_rules_sensitive = c(0, 0, 0, 0, 0, 1,
2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("date", "irish_rules_sensitive"
), row.names = c(NA, -18L), class = c("tbl_df", "tbl", "data.frame"
))
color_var_sens <- vector(mode = "double",length = length(x$irish_rules_sensitive))
color_var_sens[color_var_sens== '0']<- NA
color_var_sens[x$irish_rules_sensitive>=1 & x$irish_rules_sensitive<=3] <- "#FFFF00"
color_var_sens[x$irish_rules_sensitive>=3 & x$irish_rules_sensitive<6] <- "#FFAA00"
color_var_sens[x$irish_rules_sensitive>=6 & x$irish_rules_sensitive<9] <- "#FF5500"
color_var_sens[x$irish_rules_sensitive>=12] <- "#FF0000"

p5 <- ggplot(x)+
  geom_col(aes(x = date, y = irish_rules_sensitive, color = color_var_sens, group = 1), size= 1)+
  scale_y_continuous(limits = c(0, 40) )+
  labs(x="", y="Accum. EBHours")+
  scale_color_identity("Modified Irish Rules", breaks= rev(levels(as.factor(color_var_sens)))[c(1,2,3,4)],
                       labels = c("Low ","Medium", "High", "Very High"),
                       guide = "legend",drop = FALSE)
p5 + guides(colour=guide_legend(override.aes=list(fill=c("#FFFF00","#FFAA00","#FF5500", "#FF0000" ))), size = "none")

The weird thing is that this sometimes works and result should be something like this:

Error code:

    Error in `[[<-.data.frame`(`*tmp*`, v, value = c("#FFFF00", "#FFAA00",  :
  replacement has 4 rows, data has 3

Body:
The problem happens because color_var_sens is not a factor and the guide_legend tries do replace values that do not exist in color_car_sens. You should make it a factor. In that way you do not need theguide_legend:

color_var_sens <- factor(level=rev(c("#FFFF00","#FFAA00","#FF5500", "#FF0000" )), ordered=T)
color_var_sens[color_var_sens== '0']<- NA
color_var_sens[x$irish_rules_sensitive>=1 & x$irish_rules_sensitive<=3] <- "#FFFF00"
color_var_sens[x$irish_rules_sensitive>=3 & x$irish_rules_sensitive<6] <- "#FFAA00"
color_var_sens[x$irish_rules_sensitive>=6 & x$irish_rules_sensitive<9] <- "#FF5500"
color_var_sens[x$irish_rules_sensitive>=12] <- "#FF0000"

ggplot(x,aes(x = date, y = irish_rules_sensitive, fill = color_var_sens))+
  geom_col( size= 1)+
  scale_y_continuous(limits = c(0, 40) ) +
  labs(x="", y="Accum. EBHours") +
  scale_fill_identity("Modified Irish Rules", breaks= rev(levels(as.factor(color_var_sens))),
                       labels = c("Low ","Medium", "High", "Very High"),
                       guide = "legend",drop = FALSE)


问:
Write output out of grep into a file on Linux?
```<code>find . -name "*.php" | xargs grep -i -n "searchstring" >output.txt
</code>```

Here I am trying to write data into a file which is not happening...

答:
```<code>find . -name "*.php" -exec grep -i -n "function" {} \;  >output.txt
</code>```

But you won't know what file it came from. You might want:

```<code>find . -name "*.php" -exec grep -i -Hn "function" {} \;  >output.txt
</code>```

instead.

ContentLicense: CC BY-SA 4.0

Body:
find . -name "*.php" | xargs grep -i -n "searchstring" >output.txt

Here I am trying to write data into a file which is not happening...

Body:
find . -name "*.php" -exec grep -i -n "function" {} \;  >output.txt

But you won't know what file it came from. You might want:

find . -name "*.php" -exec grep -i -Hn "function" {} \;  >output.txt

instead.


问:
Install Scipy with MKL through PIP
I am using PIP to install Scipy with MKL to accelerate the performance. My OS is Ubuntu 64 bit. Using the solution from this question, I create a file .numpy-site.cfg

```<code>[mkl]
library_dirs=/opt/intel/composer_xe_2013_sp1/mkl/lib/intel64/
include_dirs=/opt/intel/mkl/include/
mkl_libs=mkl_intel_lp64,mkl_intel_thread,mkl_core,mkl_rt
lapack_libs=
</code>```

This file helps me to install Numpy with MKL successfully. However, using the same above file, installing Scipy prompts the error

```<code>ImportError: libmkl_rt.so: cannot open shared object file: No such file or directory
</code>```

I also use

```<code>export LD_LIBRARY_PATH=/opt/intel/composer_xe_2013_sp1/mkl/lib/intel64
</code>```

but the problem is still the same.

Anyone know how to fix this problem? I don't want to install Scipy manually so anyone give me some hints to fix it.

答:
If you are having trouble installing or running with specific version then first uninstall and then install

Step 1:

```<code>pip uninstall -v numpy
</code>```

Step 2: download the wheel file and install

```<code>pip install -U numpy-1.13.0+mkl-cp36-cp36m-win_amd64.whl
</code>```

In this example wheel file name is "numpy-1.13.0+mkl-cp36-cp36m-win_amd64.whl
"

Title: Install Scipy with MKL through PIP

Body:
I am using PIP to install Scipy with MKL to accelerate the performance. My OS is Ubuntu 64 bit. Using the solution from this question, I create a file .numpy-site.cfg

[mkl]
library_dirs=/opt/intel/composer_xe_2013_sp1/mkl/lib/intel64/
include_dirs=/opt/intel/mkl/include/
mkl_libs=mkl_intel_lp64,mkl_intel_thread,mkl_core,mkl_rt
lapack_libs=

This file helps me to install Numpy with MKL successfully. However, using the same above file, installing Scipy prompts the error

ImportError: libmkl_rt.so: cannot open shared object file: No such file or directory

I also use

export LD_LIBRARY_PATH=/opt/intel/composer_xe_2013_sp1/mkl/lib/intel64

but the problem is still the same.

Anyone know how to fix this problem? I don't want to install Scipy manually so anyone give me some hints to fix it.

Body:
If you are having trouble installing or running with specific version then first uninstall and then install

Step 1:

pip uninstall -v numpy

Step 2: download the wheel file and install

pip install -U numpy-1.13.0+mkl-cp36-cp36m-win_amd64.whl

In this example wheel file name is "numpy-1.13.0+mkl-cp36-cp36m-win_amd64.whl
"


问:
A CSS selector to get last visible div
A tricky CSS selector question, don't know if it's even possible.

Lets say this is the HTML layout:

```<code><div></div>
<div></div>
<div></div>
<div style="display:none"></div>
<div style="display:none"></div>
</code>```

I want to select the last div, which is displayed (ie. not display:none) which would be the third div in the given example.
Mind you, the number of divs on the real page can differ (even the display:none ones).

答:
If you can use inline styles, then you can do it purely with CSS.

I am using this for doing CSS on the next element when the previous one is visible:

```
div[style='display: block;'] + table {
  filter: blur(3px);
}
```

Title: A CSS selector to get last visible div

Body:
A tricky CSS selector question, don't know if it's even possible.

Lets say this is the HTML layout:

I want to select the last div, which is displayed (ie. not display:none) which would be the third div in the given example.
Mind you, the number of divs on the real page can differ (even the display:none ones).

Body:
If you can use inline styles, then you can do it purely with CSS.

I am using this for doing CSS on the next element when the previous one is visible:

div[style='display: block;'] + table {
  filter: blur(3px);
}


问:
threading.Timer join() quits immediately?
Since threading.Timer is a subclass of Thread, I would expect that the .join() in this script would cause the code to print "woof" once a second, continually:

```<code>import threading

def target_action(arg):
    print arg

def start_timer_proc(interval, arg):
    timer = threading.Timer(interval, target_action, [arg])
    timer.start()
    return timer

def main():
    timer = start_timer_proc(1.0, "woof")
    timer.join()
    print("...exiting")

main()
</code>```

Instead, it prints out "woof" once and then terminates (without any error message).  What am I missing?

答:
Here's what I really wanted (based loosely on https://stackoverflow.com/a/12435256/558639):

```<code>import threading

class IntervalTimer(threading.Thread):
    def __init__(self, target_action, interval, args=[]):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.target_action = target_action
        self.interval = interval
        self.args = args

    def start(self):
        while not self.event.wait(self.interval):
            self.target_action(*self.args)

def target_action(arg):
    print arg

def start_timer_proc(interval, arg):
    timer = IntervalTimer(target_action, interval, [arg])
    timer.start()
    return timer

def main():
    timer = start_timer_proc(1.0, "woof")
    print timer
    timer.join()
    print("...exiting")

main()
</code>```

Note that I didn't need to change my target_action() or start_timer_proc() methods, except to instantiate an IntervalTimer rather than a Timer.

Body:
Since threading.Timer is a subclass of Thread, I would expect that the .join() in this script would cause the code to print "woof" once a second, continually:

import threading

def target_action(arg):
    print arg

def start_timer_proc(interval, arg):
    timer = threading.Timer(interval, target_action, [arg])
    timer.start()
    return timer

def main():
    timer = start_timer_proc(1.0, "woof")
    timer.join()
    print("...exiting")

main()

Instead, it prints out "woof" once and then terminates (without any error message).  What am I missing?

Body:
Here's what I really wanted (based loosely on https://stackoverflow.com/a/12435256/558639):

import threading

class IntervalTimer(threading.Thread):
    def __init__(self, target_action, interval, args=[]):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.target_action = target_action
        self.interval = interval
        self.args = args

    def start(self):
        while not self.event.wait(self.interval):
            self.target_action(*self.args)

def target_action(arg):
    print arg

def start_timer_proc(interval, arg):
    timer = IntervalTimer(target_action, interval, [arg])
    timer.start()
    return timer

def main():
    timer = start_timer_proc(1.0, "woof")
    print timer
    timer.join()
    print("...exiting")

main()

Note that I didn't need to change my target_action() or start_timer_proc() methods, except to instantiate an IntervalTimer rather than a Timer.


问:
Adding textviews the the screen in a scrollview and I want to go down automatically
I am creating a bunch of textviews inside a scrollview. When I create a new textview, I want the scroll view to go to the bottom so that the user doesn't have to scroll down themselves. How could I do this, do I need to it in java or xml?</p>

答:
Depending on the effect you want you can try:

```<code>mScrollView.scrollTo (int x, int y)
</code>```

which will jump to the location you indicate or a smooth scroll

```<code>mScrollView.smoothScrollTo(int x, int y)
</code>```

or even

```<code>mScrollView.fullScroll(View.FOCUS_DOWN);
</code>```

where mScrollView is your scrollview

EDIT:

If you were to use a ListView as M.Palsish suggested you could call this on your listview:

```<code>private void scrollListViewToBottom() {
        mListView.post(new Runnable() {
            @Override
            public void run() {
                mListView.setSelection(mListView.getCount());
            }
        });
    }
</code>```

Body:
Depending on the effect you want you can try:

mScrollView.scrollTo (int x, int y)

which will jump to the location you indicate or a smooth scroll

mScrollView.smoothScrollTo(int x, int y)

or even

mScrollView.fullScroll(View.FOCUS_DOWN);

where mScrollView is your scrollview

EDIT:

If you were to use a ListView as M.Palsish suggested you could call this on your listview:

private void scrollListViewToBottom() {
        mListView.post(new Runnable() {
            @Override
            public void run() {
                mListView.setSelection(mListView.getCount());
            }
        });
    }