问:
Gauging a web browser's bandwidth
Is it possible to gauge a web browsers upload and/or download speed by monitoring normal http requests? Ideally a web application would be able to tell the speed of a client without any modifications and without client-side scripting like JavaScript/Java/Flash.  So even if a client was accessing the service with a library like Curl it would still work.  If this is possible, how?  If its not possible,  why?  How accurate can this method be?

(If it helps assume PHP/Apache,  but really this is a platform independent question.  Also being able to gauge the upload speed is more important to me.)

答:
Overview

You're asking for what is commonly called "passive" available bandwidth (ABW) measurement along a path (versus measuring a single link's ABW).  There are a number of different techniques1 that estimate bandwidth using passive observation, or low-bandwidth "Active" ABW probing techniques.  However, the most common algorithms used in production services are active ABW techniques; they observe packet streams from two different end-points.

I'm most familiar with yaz, which sends packets from one side and measures variation in delay on the other side.  The one-sided passive path ABW measurement techniques are considered more experimental; there aren't solid implementations of the algorithms AFAIK.

Discussion

The problem with the task you've asked for is that all non-intrusive2 ABW measurement techniques rely on timing.  Sadly, timing is a very tricky thing when working with http...

You have to deal with the reality of object caching (for instance, akamai) and http proxies (which terminate your TCP session prematurely and often spoof the web-server's IP address to the client).

You have to deal with web-hosts which may get intermittently slammed

Finally, active ABW techniques rely on a structured packet stream (wrt packet sizes and timing), unlike what you see in a standard http transfer.

Summary

In summary, unless you set up dedicated client / server / protocol just for ABW measurement, I think you'll be rather frustrated with the results.  You can keep your ABW socket connections on TCP/80, but the tools I have seen won't use http3.

Editorial note: My original answer suggested that ABW with http was possible.  On further reflection, I changed my mind.

END-NOTES:
---

See Sally Floyd's archive of end-to-end TCP/IP bandwidth estimation tools

The most common intrusive techniques (such as speedtest.net) use a flash or java applet in the browser to send & receive 3-5 parallel TCP streams to each endpoint for 20-30 seconds.  Add the streams' average throughput (not including lost packets requiring retransmission) over time, and you get that path's tx and rx ABW.  This is obviously pretty disruptive to VoIP calls, or any downloads in progress.  Disruptive meausurements are called bulk transfer capacity (BTC).  See RFC 3148: A Framework for Defining Empirical Bulk Transfer Capacity Metrics.  BTC measurements often use HTTP, but BTC doesn't seem to be what you're after.

That is good, since it removes the risk of in-line caching by denying http caches an object to cache; although some tools (like yaz) are udp-only.

Title: Gauging a web browser's bandwidth


来源: stackexchange

问:
How to implement method swizzling swift 3.0?
How can I implement method swizzling in Swift 3.0 ?

I've read nshipster article about it, but in this code's chunk

```<code>struct Static {
    static var token: dispatch_once_t = 0
}
</code>```

the compiler gives me an error

dispatch_once_t is unavailable in Swift: Use lazily initialized
  globals instead

答:
Try this framework: https://github.com/623637646/SwiftHook

```<code>let object = MyObject()
let token = try? hookBefore(object: object, selector: #selector(MyObject.noArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
object.noArgsNoReturnFunc()
token?.cancelHook() // cancel the hook
</code>```

It's very easy to hook methods in Swift.

ContentLicense: CC BY-SA 3.0

Body:
How can I implement method swizzling in Swift 3.0 ?

I've read nshipster article about it, but in this code's chunk

struct Static {
    static var token: dispatch_once_t = 0
}

the compiler gives me an error

dispatch_once_t is unavailable in Swift: Use lazily initialized
  globals instead

Body:
Try this framework: https://github.com/623637646/SwiftHook

let object = MyObject()
let token = try? hookBefore(object: object, selector: #selector(MyObject.noArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
object.noArgsNoReturnFunc()
token?.cancelHook() // cancel the hook

It's very easy to hook methods in Swift.

ContentLicense: CC BY-SA 4.0


问:
How to invoke ShutdownHook thread with a window close operation of DISPOSE_ON_CLOSE or EXIT_ON_CLOSE
Assuming that Runtime.getRuntime().addShutdownHook(new Thread() has been set up correctly, how can the ShutdownHook thread be invoked when a Java application window (JFrame) is closed (in this case the only window) and the dispose window default close operation is DISPOSE_ON_CLOSE or EXIT_ON_CLOSE?

Note that for a quit command handled with a System.exit(0) which is then fed through the ShutdownHook thread, the application terminates correctly as all the associated threads are terminated before the Java application exits. So I want to accomplish the same thing by making the closing of the JFrame window go through the ShutdownHook thread clean up.

答:
This works according to your spec.  If I close the frame by clicking the X button, the shutdown hook is invoked.

```<code>import javax.swing.*;

class ShutDownHookDemo {

    public static void endMessage() {
        // clean up threads here..
        System.out.println("Thanks for using the app.");
    }

    public static void main(String[] args) {
        Thread t = new Thread() {
            public void run() {
                endMessage();
            }
        };
        Runtime.getRuntime().addShutdownHook(t);

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300,300);

        f.setVisible(true);
    }
}
</code>```

Body:
This works according to your spec.  If I close the frame by clicking the X button, the shutdown hook is invoked.

import javax.swing.*;

class ShutDownHookDemo {

    public static void endMessage() {
        // clean up threads here..
        System.out.println("Thanks for using the app.");
    }

    public static void main(String[] args) {
        Thread t = new Thread() {
            public void run() {
                endMessage();
            }
        };
        Runtime.getRuntime().addShutdownHook(t);

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300,300);

        f.setVisible(true);
    }
}


问:
Carrying out a c++ 2d array
My array is supposed to accept 3 values for 3 salespersons, store and print the array but somehow I can't get it going. I'm not too familiar with c++ 2d arrays so this is a tad bit new to me. The code is supposed to accept user input, and then output the prices of the products into table like format.</p>

答:
I had to clean up a lot of code to get this to even begin to compile. There were many cases where the closing } of a block was not present. These mistakes are easy to make, but they're also easy to spot if you're disciplined about maintaining a consistent indentation style.

Once I indented the code it became fairly obvious where the errors were, but identifying these in the original is very hard.

Here's the cleaned up code:

```<code>#include <iostream>
#include <iomanip>

int main( ) {
  const int salesPersonCount =3, productCount = 3;

  int rows = 5, columns = 5;
  int sales[rows][columns];
  double total;

  for (int p = 1; p <= salesPersonCount; p++) {
    std::cout << "\n \n Information for SalesPsn"<< p <<" : \n \n";

    //Sales Person
    for (int m = 1; m <=productCount; m++) {
      //Product Number
      std::cout << "\n Please enter sales value of product "<< m << ":";

      std::cout << "\n ";

      for (int i=0;i<rows;i++) {
        for (int j=3;j<columns; j++) {
          std::cout << "\nThe 2-D Array is:\n";

          for (int i=0;i<2;i++) {
            for (int j=0;j<2;j++) {
              std::cout << "\t" << sales[i][j];
            }

            std::cout << "Sale " << std::setw (17) << "Salespsn1" << std::setw (22)<< "Salespsn2"
              << std::setw (27)<< "Salespsn3" << std::setw (32) << "Total" << std::endl;
          }

          std::cout << std::endl;
        }
      }
    }
  }

  return 0;
}
</code>```

Note this still has a lot of problems you're going to need to resolve, like how you're capturing sales and information into variables p and m which are also used for iterators, plus how nothing actually puts data into the sales structure, but at least you've got something you can fix.

My advice: When you get into a deep hole, stop digging. If you can't figure out what to do, clean up your code. I've solved many problems in the course of better organizing what I've done, in adding comments to parts that should work yet don't. There's no shame in being stuck, but if you're stuck because of a mess you didn't clean up that's on you.

Title: Carrying out a c++ 2d array

Body:
I had to clean up a lot of code to get this to even begin to compile. There were many cases where the closing } of a block was not present. These mistakes are easy to make, but they're also easy to spot if you're disciplined about maintaining a consistent indentation style.

Once I indented the code it became fairly obvious where the errors were, but identifying these in the original is very hard.

Here's the cleaned up code:

#include <iostream>
#include <iomanip>

int main( ) {
  const int salesPersonCount =3, productCount = 3;

  int rows = 5, columns = 5;
  int sales[rows][columns];
  double total;

  for (int p = 1; p <= salesPersonCount; p++) {
    std::cout << "\n \n Information for SalesPsn"<< p <<" : \n \n";

    //Sales Person
    for (int m = 1; m <=productCount; m++) {
      //Product Number
      std::cout << "\n Please enter sales value of product "<< m << ":";

      std::cout << "\n ";

      for (int i=0;i<rows;i++) {
        for (int j=3;j<columns; j++) {
          std::cout << "\nThe 2-D Array is:\n";

          for (int i=0;i<2;i++) {
            for (int j=0;j<2;j++) {
              std::cout << "\t" << sales[i][j];
            }

            std::cout << "Sale " << std::setw (17) << "Salespsn1" << std::setw (22)<< "Salespsn2"
              << std::setw (27)<< "Salespsn3" << std::setw (32) << "Total" << std::endl;
          }

          std::cout << std::endl;
        }
      }
    }
  }

  return 0;
}

Note this still has a lot of problems you're going to need to resolve, like how you're capturing sales and information into variables p and m which are also used for iterators, plus how nothing actually puts data into the sales structure, but at least you've got something you can fix.

My advice: When you get into a deep hole, stop digging. If you can't figure out what to do, clean up your code. I've solved many problems in the course of better organizing what I've done, in adding comments to parts that should work yet don't. There's no shame in being stuck, but if you're stuck because of a mess you didn't clean up that's on you.


问:
Not getting uploaded pictures on wordpress site hosted on AWS , when i restarting my ec2 instance
I hosted a word press site on my AWS environment using ec2 and RDS(MySQL) instances.
I stopped my ec2 instance, but when i restarted it, the images are not showing and also its taking a long time to load the content of word press too.

This happened earlier also but that time i thought might be due to latency issue, but its happening again and again.

I tried to restart the RDS instance too, but didn't get the solution.

Can anyone please help.

答:
Thanks for all the answers.
Actually the main problem was of the location of the pictures, I uploaded it from my local machine. This is what i think.
Solution- I copied the /var/www/html/uploads directory to S3 bucket.
And used the cloudfront CDN of AWS and used the source as the s3 bucket.
Now its working fine for me. Even after stopping the instance and restarting it, the site is getting up quickkly.

Thanks.


问:
How can my app users view a lot of images (and possible download them) without me having to rent a server
So, I now have an app, and the idea is the same as a wallpaper app, a lot of images people can download and use for themselves. There are a little over 200 images in the app right now, but I want to increase this number to a couple of thousand. The problem is, the size of the app will increase very rapidly, so the best idea (I think) is to use some sort of server. Google Photos and Firebase both have quota's, and I know I will reach those both very soon (with only 200 images and the active users I have right now, the limit would be reached very quickly). So, I need another way to let people view the images (my images, I do not just copy them from another site, or any other place online) and be able to download them to their phones, without it costing me money (sorry, Im very poor) or using a service that has a quota. So, I need my android app users to view and download a lot (2500+) of my images, without it costing me money.
Thanks!</p>

答:
Cloud storage is your best bet. This AWS project looks like it would be a good fit for your needs.

https://aws.amazon.com/blogs/mobile/store-your-photos-in-the-cloud-using-amazon-s3/


问:
how to make a video from extracted frames?
I extracted the video frames into a folder called "images". After getting images saved in my folder, I use the following code to create the video again. I get the video but the frames are ordered randomly, how can I arrange them in sequential order? thanks for the post

```<code>import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()
</code>```

please advise, how do I fix this? I'd like the videos to be at the same rate as the original video, and frames to be in sequential order.

答:
If your requirement needs you to store the frames, try this</p>

```<code>import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for i in range(len(images)):
    video.write(cv2.imread(os.path.join(image_folder, 'a'+str(i)+'.jpg')))

cv2.destroyAllWindows()
video.release()
</code>```

Body:
I extracted the video frames into a folder called "images". After getting images saved in my folder, I use the following code to create the video again. I get the video but the frames are ordered randomly, how can I arrange them in sequential order? thanks for the post

import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()

please advise, how do I fix this? I'd like the videos to be at the same rate as the original video, and frames to be in sequential order.

Body:
If your requirement needs you to store the frames, try this

import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for i in range(len(images)):
    video.write(cv2.imread(os.path.join(image_folder, 'a'+str(i)+'.jpg')))

cv2.destroyAllWindows()
video.release()


问:
How to redirect to newly created document page after submitting the form firestore for web
I want to redirect to the newly created document page after successfully creating the document. Below is my code for that

```<code>db.collection("problems").add({
                statement: statement,
                details: {
                    difficulty: difficulty,
                    type: type,
                    title: title
                },
                tags: tags,
                timestamp: {
                    created: firebase.firestore.Timestamp.now(),
                    modified: firebase.firestore.Timestamp.now()
                }
            })
            .then(function(docRef) {
                console.log("Document written with ID: ", docRef.id);
                var problemID;
                docRef.get()
                .then( (doc) => {
                    if(doc.exists) {
                        console.log(doc.data());
                        console.log(doc.id);
                        problemID = doc.id;
                        window.location.replace("/practice/problemID");
                    }
                })

            })
</code>```

But this does not work. Please tell me where I am wrong?

答:
You need to append the ID.

window.location.replace("/practice/"+problemID);

```<code>db.collection("problems").add({
                statement: statement,
                details: {
                    difficulty: difficulty,
                    type: type,
                    title: title
                },
                tags: tags,
                timestamp: {
                    created: firebase.firestore.Timestamp.now(),
                    modified: firebase.firestore.Timestamp.now()
                }
            })
            .then(function(docRef) {
                console.log("Document written with ID: ", docRef.id);
                var problemID;
                docRef.get()
                .then( (doc) => {
                    if(doc.exists) {
                        console.log(doc.data());
                        console.log(doc.id);
                        problemID = doc.id;
                        window.location.replace("/practice/"+problemID);
                    }
                })

            })
</code>```

Body:
I want to redirect to the newly created document page after successfully creating the document. Below is my code for that

db.collection("problems").add({
                statement: statement,
                details: {
                    difficulty: difficulty,
                    type: type,
                    title: title
                },
                tags: tags,
                timestamp: {
                    created: firebase.firestore.Timestamp.now(),
                    modified: firebase.firestore.Timestamp.now()
                }
            })
            .then(function(docRef) {
                console.log("Document written with ID: ", docRef.id);
                var problemID;
                docRef.get()
                .then( (doc) => {
                    if(doc.exists) {
                        console.log(doc.data());
                        console.log(doc.id);
                        problemID = doc.id;
                        window.location.replace("/practice/problemID");
                    }
                })

            })

But this does not work. Please tell me where I am wrong?

Body:
You need to append the ID.

window.location.replace("/practice/"+problemID);

db.collection("problems").add({
                statement: statement,
                details: {
                    difficulty: difficulty,
                    type: type,
                    title: title
                },
                tags: tags,
                timestamp: {
                    created: firebase.firestore.Timestamp.now(),
                    modified: firebase.firestore.Timestamp.now()
                }
            })
            .then(function(docRef) {
                console.log("Document written with ID: ", docRef.id);
                var problemID;
                docRef.get()
                .then( (doc) => {
                    if(doc.exists) {
                        console.log(doc.data());
                        console.log(doc.id);
                        problemID = doc.id;
                        window.location.replace("/practice/"+problemID);
                    }
                })

            })


问:
Is it possible to populate a spinner in android using a JSONArray?
Just as the title says.. Is it possible to do this?  Say I have a JSON array of something like this</p>

```<code>{
    "locations": [
      {
        "id": 1,
        "loc": "miami"
      },
      {
        "id": 2,
        "loc": "manhattan"
      },
      {
        "id": 3,
        "loc": "lasVegas"
      }
    ]
  }
</code>```

答: Sure, extend BaseAdapter and use the JSONArray as your backing model. However, it would be better (but by no means necessary) to convert it to a more "natural" representation in Java and use that instead.

Body:
Just as the title says.. Is it possible to do this?  Say I have a JSON array of something like this

{
    "locations": [
      {
        "id": 1,
        "loc": "miami"
      },
      {
        "id": 2,
        "loc": "manhattan"
      },
      {
        "id": 3,
        "loc": "lasVegas"
      }
    ]
  }


问:
How to write a query to convert nvarchar to date
I have a table with a single column that contains date and string values. How to write a query to convert a string to date value?

Table usercomment:

```<code>comment
----------
02/22/2020
03/22/2020
Nochange
04/22/2020
userreviw
</code>```

Desired output:

```<code>comment
-----------
2020-02-22
2020-03-22
Nochange
2020-04-22
userreviw
</code>```

答:
```<code>Select CASE
         ISDATE(myColumn) WHEN 1 THEN CONVERT(nvarchar(10), CONVERT(datetime, myColumn, 101), 120)
         ELSE myColumn
       end
From myTable
</code>```

Body:
I have a table with a single column that contains date and string values. How to write a query to convert a string to date value?

Table usercomment:

comment
----------
02/22/2020
03/22/2020
Nochange
04/22/2020
userreviw

Desired output:

comment
-----------
2020-02-22
2020-03-22
Nochange
2020-04-22
userreviw


问:
How to prevent form submitting on other button is clicked rather than submit button in JavaScript
There is two buttons with in form, one is for submit the form and other one is close button for hide the form. But the problem is that form is also submitted on close button click, i don't want this behavior and i also don't want to place the close button outside the form.</p>

```<code><form class="add_form" id="add_list_form">
  <input type="text" class="form-control" placeholder="Enter list title..." id="list_value" />
  <div class="mt-2">
    <button type="submit" class="btn btn-sm btn-success mr-1" id="add_list_btn">Add List</button>
    <button class="btn btn-sm btn-danger" id="close_btn">close</button>
  </div>
</form>
<script>
  const add_list_form = document.querySelector('#add_list_form');
  add_list_form.addEventListener('submit',(e)=>{ e.preventDefault();
  console.log('form is submitted..') })
<script>
</code>```

答:
add type="button" attribute in your close button tag, without specifying this type attribute, browser consider every button as submit button by default in the form element.

your close button element should look like this:

```<code><button type="button">close</button>
</code>```

Body:
There is two buttons with in form, one is for submit the form and other one is close button for hide the form. But the problem is that form is also submitted on close button click, i don't want this behavior and i also don't want to place the close button outside the form.

<form class="add_form" id="add_list_form">
  <input type="text" class="form-control" placeholder="Enter list title..." id="list_value" />

    <button type="submit" class="btn btn-sm btn-success mr-1" id="add_list_btn">Add List</button>
    <button class="btn btn-sm btn-danger" id="close_btn">close</button>

</form>

Body:
add type="button" attribute in your close button tag, without specifying this type attribute, browser consider every button as submit button by default in the form element.

your close button element should look like this:

<button type="button">close</button>


问:
Could someone explain what an SVN bisect algorithm is? Theoretically and through code snippet
I want to understand what an SVN bisect / git-bisect algorithm is..I have tried to search online resources but unable to get a good problem statement and solution.</p>

答:
Briefly, the idea of bisect is a binary search.

The idea of bisect is based on several assumptions:

There is a particular application behaviour (for simplicity, let's call it "defect") and you want to find its reason.

Code analysis and debugging needs too much efforts.

Building any version and running tests against it is much easier than code analysis and debugging.

You know some code revision in the past without this defect.

A straight forward approach is to build the previous revision and test if it has this defect. If has, then test one revision earlier. You continue until you find the revision that introduced this bug. You know all the changes in this commit. That's why it is easier to find what change exactly caused the defect. Also debugging can be much easier, because you can focus on (usually) a few changes.

But if the revision known to have no defect is 200 revisions in the past before the recent revision, you may need to repeat "build and test" procedure 200 times (if you have no luck).

Let's name the revision without defect R0, revision with defect R200.

Bisect allows to make it faster. You "tell" bisect what revision has defect and what revision has no defect. Then bisect calculate the number of commits between these revisions. In our case these are 200 commits. Bisect takes a revision that is 100 revisions before the revision with defect and checks it out. Means, it checks out revision R100. You build it and test. Then you "tell" bisect if this revision contains defect or not. If there is defect, then it means it was introduced between versions R0 and R100. If there is no defect, it means that defect was introduced later, after revision R100, between R100 and R200.

Suppose you told bisect there is defect in R100. Then bisect takes the middle of the range R0 - R100. This will be revision R50. Bisect checks it out. You build it and test and tell the result to bisect.

Suppose R50 has no defect. Means, it was introduced between revisions R50 and R 100. Bisect takes again the middle, revision R75. You build it and test.

Suppose R75 has defect. Means it was introduced between R50 and R75. Bisect checks out R63. Ans so on.

In total you need log(200) = 8 steps. If you would check every version, you would build and test up to 200 revisions, which would take much longer.

In case of Git, you first start bisect procedure with command

```<code>git bisect start
</code>```

Then you check out revision with defect and run command

```<code>git bisect bad
</code>```

Then you tell bisect what revision was without defect:

```<code>git bisect good R0
</code>```

By this command Git bisect will find the middle, R100, and check it out. You build and test it and, if it contains defect, run command

```<code>git bisect bad
</code>```

Otherwise command

```<code>git bisect good
</code>```

And thus continue until you the revision found that introduced the defect.

Body:
Briefly, the idea of bisect is a binary search.

The idea of bisect is based on several assumptions:

There is a particular application behaviour (for simplicity, let's call it "defect") and you want to find its reason.

Code analysis and debugging needs too much efforts.

Building any version and running tests against it is much easier than code analysis and debugging.

You know some code revision in the past without this defect.

A straight forward approach is to build the previous revision and test if it has this defect. If has, then test one revision earlier. You continue until you find the revision that introduced this bug. You know all the changes in this commit. That's why it is easier to find what change exactly caused the defect. Also debugging can be much easier, because you can focus on (usually) a few changes.

But if the revision known to have no defect is 200 revisions in the past before the recent revision, you may need to repeat "build and test" procedure 200 times (if you have no luck).

Let's name the revision without defect R0, revision with defect R200.

Bisect allows to make it faster. You "tell" bisect what revision has defect and what revision has no defect. Then bisect calculate the number of commits between these revisions. In our case these are 200 commits. Bisect takes a revision that is 100 revisions before the revision with defect and checks it out. Means, it checks out revision R100. You build it and test. Then you "tell" bisect if this revision contains defect or not. If there is defect, then it means it was introduced between versions R0 and R100. If there is no defect, it means that defect was introduced later, after revision R100, between R100 and R200.

Suppose you told bisect there is defect in R100. Then bisect takes the middle of the range R0 - R100. This will be revision R50. Bisect checks it out. You build it and test and tell the result to bisect.

Suppose R50 has no defect. Means, it was introduced between revisions R50 and R 100. Bisect takes again the middle, revision R75. You build it and test.

Suppose R75 has defect. Means it was introduced between R50 and R75. Bisect checks out R63. Ans so on.

In total you need log(200) = 8 steps. If you would check every version, you would build and test up to 200 revisions, which would take much longer.

In case of Git, you first start bisect procedure with command

git bisect start

Then you check out revision with defect and run command

git bisect bad

Then you tell bisect what revision was without defect:

git bisect good R0

By this command Git bisect will find the middle, R100, and check it out. You build and test it and, if it contains defect, run command

git bisect bad

Otherwise command

git bisect good

And thus continue until you the revision found that introduced the defect.


问:
How to retain function name from eslint Source Code?
I want to store implementations of Javascript methods in a database. To store the function as a JSON parsed string, I am using the SourceCode module from ESlint. In my code, I have something that looks like this:

 let r = require(file);
 mapObj.set(id, {
        id,
        fn: SourceCode.splitLines(r.toString()),
      });

```

<p>This works correctly for function declarations, ie: </p>

<pre class="lang-js prettyprint-override"><code>function foo() {}
</code>```

But for function expressions, ie: arrow functions, function expressions:

const foo = (a, b, c) => {}
const foo = function(a,b,c) {}
```

<p>it will not retain the function name and looks like this: </p>

``` "(a, b, c) => {",
 "  .....
  "}"
```

If this is a configuration from ESLint, I haven't been able to find it. Any help would be appreciated!

答:
If a function has a name, you can look for it in the .name property.

E.g.

```<code> let r = require(file);
 mapObj.set(id, {
        id,
        name: r.name,
        fn: SourceCode.splitLines(r.toString()),
      });
</code>```

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

const foo1 = (a, b, c) => {}
const foo2 = function(a,b,c) {}

console.log(foo1.name, foo1.toString());
console.log(foo2.name, foo2.toString());```

Body:
I want to store implementations of Javascript methods in a database. To store the function as a JSON parsed string, I am using the SourceCode module from ESlint. In my code, I have something that looks like this:

 let r = require(file);
 mapObj.set(id, {
        id,
        fn: SourceCode.splitLines(r.toString()),
      });

This works correctly for function declarations, ie:

function foo() {}

But for function expressions, ie: arrow functions, function expressions:

const foo = (a, b, c) => {}
const foo = function(a,b,c) {}

it will not retain the function name and looks like this:

 "(a, b, c) => {",
 "  .....
  "}"

If this is a configuration from ESLint, I haven't been able to find it. Any help would be appreciated!

Body:
If a function has a name, you can look for it in the .name property.

E.g.

 let r = require(file);
 mapObj.set(id, {
        id,
        name: r.name,
        fn: SourceCode.splitLines(r.toString()),
      });

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

const foo1 = (a, b, c) => {}
const foo2 = function(a,b,c) {}

console.log(foo1.name, foo1.toString());
console.log(foo2.name, foo2.toString());


问:
How to change the cursor to a pointer when I hover over a bar in a ChartJS bar chart?
Here is my chart creation

```<code>createChart = function (name, contributions, idArray) {
    globalIdArray = idArray;
    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: "bar",
        data: {
            labels: name,
            datasets: [{
                label: "Contributions",
                data: contributions,
                backgroundColor: [
                    'rgba(0, 255, 0, 0.2)',
                    'rgba(0, 255, 0, 0.2)',
                    'rgba(0, 255, 0, 0.2)',
                    'rgba(0, 255, 0, 0.2)',
                    'rgba(0, 255, 0, 0.2)'
                ]
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            },
            onClick: handleClick,
            onHover: handleHover
        }
    });
</code>```

This is the HTML, everything is JavaScript and resides inside the canvas element.

```<code><canvas chart-hover="onHover" id="myChart" width="200" height="200"></canvas>
</code>```

I made it so when I click on a bar they act as a "drill in" and take my a page with more details.  To do that I used this code:

```<code>function handleClick(e) {
            debugger;
            var activeElement = myChart.getElementAtEvent(e);
            var designerId = _idArray[activeElement[0]._index];
            window.location.href = "/Display/search/index?designerId=" + designerId;
        }
</code>```

I'd like to make it so my cursor changes to a pointer to let the user know they can click the bar (as it would normally change with a link).  I saw some examples of this on Stack Overflow but they were from the last year or two, the posts included comments asking for an updated version but no solutions.

Here is another post I saw which I believe is the same thing I am trying to accomplish but it didn't work for me.

How to change cursor style to pointer on hovering over points of the chart?

Does anyone know of how I can implement this, using the most recent live version of ChartJS?

答:
I needed the cursor to change only when over a bar or point on a line chart so came up with this simple solution. Place your function outside the chart declaration.</p>

```<code>var chart = new Chart(ctx, {
    data: {...},
    options: {
     onHover: graphHover
    }
});
function graphHover(e, array) {
    if(array.length > 0) {
        e.target.style.cursor = 'pointer';
    }else {
        e.target.style.cursor = '';
    }
}
</code>```

Body:
Here is my chart creation

createChart = function (name, contributions, idArray) {
    globalIdArray = idArray;
    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: "bar",
        data: {
            labels: name,
            datasets: [{
                label: "Contributions",
                data: contributions,
                backgroundColor: [
                    'rgba(0, 255, 0, 0.2)',
                    'rgba(0, 255, 0, 0.2)',
                    'rgba(0, 255, 0, 0.2)',
                    'rgba(0, 255, 0, 0.2)',
                    'rgba(0, 255, 0, 0.2)'
                ]
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            },
            onClick: handleClick,
            onHover: handleHover
        }
    });

This is the HTML, everything is JavaScript and resides inside the canvas element.

<canvas chart-hover="onHover" id="myChart" width="200" height="200"></canvas>

I made it so when I click on a bar they act as a "drill in" and take my a page with more details.  To do that I used this code:

function handleClick(e) {
            debugger;
            var activeElement = myChart.getElementAtEvent(e);
            var designerId = _idArray[activeElement[0]._index];
            window.location.href = "/Display/search/index?designerId=" + designerId;
        }

I'd like to make it so my cursor changes to a pointer to let the user know they can click the bar (as it would normally change with a link).  I saw some examples of this on Stack Overflow but they were from the last year or two, the posts included comments asking for an updated version but no solutions.

Here is another post I saw which I believe is the same thing I am trying to accomplish but it didn't work for me.

How to change cursor style to pointer on hovering over points of the chart?

Does anyone know of how I can implement this, using the most recent live version of ChartJS?

Body:
I needed the cursor to change only when over a bar or point on a line chart so came up with this simple solution. Place your function outside the chart declaration.

var chart = new Chart(ctx, {
    data: {...},
    options: {
     onHover: graphHover
    }
});
function graphHover(e, array) {
    if(array.length > 0) {
        e.target.style.cursor = 'pointer';
    }else {
        e.target.style.cursor = '';
    }
}


问:
Is it okay to create constant variables just for the sake of readability?
Imagine if I have this piece of code:

```<code>System.out.println("Is the product:\n"+
                    "1. National.\n"+
                    "2. International.");
int choice = input.nextInt(System.in);
if (choice == 1)
    (...)
else if (choice == 2)
    (...)
</code>```

So is it okay to do the following?

```<code>final int NATIONAL = 1;
final int INTERNATIONAL = 2;
System.out.println("Is the product:\n"+
                        "1. National.\n"+
                        "2. International.");
int choice = input.nextInt(System.in);
if (choice == NATIONAL)
    (...)
else if (choice == INTERNATIONAL)
    (...)
</code>```

I don't know, I just bought the Clean Code book by Uncle Bob and I started to question myself.

答:
when you want to Some variable(constants) or Code multiple, then you make constants for better readablity and understanding.
For Example -:
if (choice == NATIONAL)
    (...)
else if (choice == INTERNATIONAL)
    (...)

is right when you have to use INTERNATIONAL and NATIONAL multiple times

Body:
Imagine if I have this piece of code:

System.out.println("Is the product:\n"+
                    "1. National.\n"+
                    "2. International.");
int choice = input.nextInt(System.in);
if (choice == 1)
    (...)
else if (choice == 2)
    (...)

So is it okay to do the following?

final int NATIONAL = 1;
final int INTERNATIONAL = 2;
System.out.println("Is the product:\n"+
                        "1. National.\n"+
                        "2. International.");
int choice = input.nextInt(System.in);
if (choice == NATIONAL)
    (...)
else if (choice == INTERNATIONAL)
    (...)

I don't know, I just bought the Clean Code book by Uncle Bob and I started to question myself.


问:
Cannot understand how background-image url works in Gatsby.js
I am learning Gatsby. I have a component called Hero which is for displaying a banner for the blog I am building.

import React from 'react';
import styled from '@emotion/styled';
import { Link, graphql, useStaticQuery } from 'gatsby';

const ImageBackground = styled('div')`
  background-image: url('images/plans-background.jpg'); <--- this url doesn't make sense to me
  background-position: top 20% center;
  background-size: cover;
  /* background-color: red; */
`;

const Hero = () => {
  return (
    <ImageBackground>

Frontend Masster dsfsdfsd

        hello
        <Link to="/about">learn about me</Link>

    </ImageBackground>
  );
};

export default Hero;
```

<p>I'm using the screenshot to show the folder structure
<img src="https://i.stack.imgur.com/VEalL.png" alt="enter image description here"></p>

<p>according to the structure, in order to reach the background image I need a url like this</p>

````../../../static/images/plans-background.jpg`
```

<p>And that's what the IDE prompted me to type when trying to reach the image file. However this url doesn't work as expected. There's no background image showing. and I changed it to </p>

````images/plans-background.jpg`
```

The background image showed up magically.

So I don't understand why this url is working. Is it something special about the folder static or is Gatsby doing something behind the scene?

Also when I opened up the devtool to inspect the resources that got loaded, I didn't find this static file, neither the background image file.

I am really trying to understand how these pieces work together

答:
Yes, this is the expected behavior for your assets in /static, read more about it in the docs: Using the Static Folder.

However, adding your images there is not a best practice because they won't be optimized with Gatsby's build time image processing and gatsby-image.

The docs also have good resources for this: Using Gatsby Image to Prevent Image Bloat, or Working with images in Gatsby.

Body:
I am learning Gatsby. I have a component called Hero which is for displaying a banner for the blog I am building.

import React from 'react';
import styled from '@emotion/styled';
import { Link, graphql, useStaticQuery } from 'gatsby';

const ImageBackground = styled('div')`
  background-image: url('images/plans-background.jpg'); <--- this url doesn't make sense to me
  background-position: top 20% center;
  background-size: cover;
  /* background-color: red; */
`;

const Hero = () => {
  return (
    <ImageBackground>

Frontend Masster dsfsdfsd

        hello
        <Link to="/about">learn about me</Link>

    </ImageBackground>
  );
};

export default Hero;

I'm using the screenshot to show the folder structure

according to the structure, in order to reach the background image I need a url like this

`../../../static/images/plans-background.jpg`

And that's what the IDE prompted me to type when trying to reach the image file. However this url doesn't work as expected. There's no background image showing. and I changed it to

`images/plans-background.jpg`

The background image showed up magically.

So I don't understand why this url is working. Is it something special about the folder static or is Gatsby doing something behind the scene?

Also when I opened up the devtool to inspect the resources that got loaded, I didn't find this static file, neither the background image file.

I am really trying to understand how these pieces work together


答:
Try using TRY_CONVERT:

```<code>SELECT
    COALESCE(TRY_CONVERT(varchar(10),
                         TRY_CONVERT(datetime, col, 101),
                         120), col) AS col_as_date
FROM yourTable;
</code>```

The format mask 101 in the first call to TRY_CONVERT corresponds to the date format mm/dd/yyyy, which matches your data, when it has a valid date.  For invalid values, such as comment, TRY_CONVERT will return NULL.  Then, we call TRY_CONVERT with mask 120 to generate text dates in the format yyyy-mm-dd.

Title: How to write a query to convert nvarchar to date

Body:
Try using TRY_CONVERT:

SELECT
    COALESCE(TRY_CONVERT(varchar(10),
                         TRY_CONVERT(datetime, col, 101),
                         120), col) AS col_as_date
FROM yourTable;

The format mask 101 in the first call to TRY_CONVERT corresponds to the date format mm/dd/yyyy, which matches your data, when it has a valid date.  For invalid values, such as comment, TRY_CONVERT will return NULL.  Then, we call TRY_CONVERT with mask 120 to generate text dates in the format yyyy-mm-dd.


问:
Problem with System.Data with Sybase SQL Anywhere and Windows CE
I am moving a vb.net application from Oracle Lite to Sybase SQL anywhere.  I have made several code changes but have a specific error that is driving me mad.  All of this is in Visual Studio 2005.

When I compile the code it gives me the following error "Reference required to assembly 'System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' containing the base class 'System.Data.Common.DbCommand'. Add one to your project".

I have both System and System.Data added for the WindowsCE platform and these worked fine under the Oracle Lite system.  I have removed and re-added these files to the project.  Nothing seems to be working to get rid of the error.

The offending code is legion, one example is:

```<code>Public con As ULConnection
</code>```

Any thoughts here would be very helpful!

答: A public Key Token of b77a5c561934e089 indicates a full framework, not compact framework, assembly.  Something you're using (likely the version of SQL Anywhere you have) was built referencing the desktop System.Data assembly, which is not going to work on a device.  You need assemblies built specifically targeting the Compact Framework.

Body:
I am moving a vb.net application from Oracle Lite to Sybase SQL anywhere.  I have made several code changes but have a specific error that is driving me mad.  All of this is in Visual Studio 2005.

When I compile the code it gives me the following error "Reference required to assembly 'System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' containing the base class 'System.Data.Common.DbCommand'. Add one to your project".

I have both System and System.Data added for the WindowsCE platform and these worked fine under the Oracle Lite system.  I have removed and re-added these files to the project.  Nothing seems to be working to get rid of the error.

The offending code is legion, one example is:

Public con As ULConnection

Any thoughts here would be very helpful!


问:
Selecting up to second space / first two words in a text()
I am having trouble getting my head around how to achieve the following. I have gotten this far:

```<code>//*[@id="main"]/div[2]/section/div[2]/h1/span[1][starts-with(.,"IDENTIFIER")]/following::span[1]/text()
</code>```

This will return a response such as:

Foo1 Foo2 Foo3 Foo4

I am trying to make this return only Foo1 & Foo2, where Foo1 & Foo2 can be any length of characters and there may be any number of additional Foo's following them.

I have tried looking at

```<code>substring-before(//*[@id="main"]/div[2]/section/div[2]/h1/span[1][starts-with(.,"IDENTIFIER")]/following::span[1]/text(), ' ')
</code>```

To extract up to the first space however I have hit a wall in what I am doing wrong.

I am using the xpath within a Scrapy spider. Any help is appreciated

答:
Example with :

```<code><table>
<td>Pierre Paul Jacques Marie Maurice Jeanne</td>
</table>
</code>```

XPath expression :

```<code>substring(//td,1,string-length(substring-before(//td," "))+string-length(substring-before(substring-after(//td," ")," "))+1)
</code>```

Output :

```<code>Pierre Paul
</code>```

The XPath works in 3 steps. First we get the length of the second term with 3 functions (substring-after, substring-before, and string-length). Space is used as delimiter. Then we get the length of the first term with 2 functions (substring-before and string-length). Space is used as delimiter. Finally  we use susbstring to extract what we need. Syntax : fn(content of the element,starting position for the extraction (1), ending position (length of text1 + length of text2) + 1(space delimiter)).

You can replace //td with your XPath selector (remove the /text() at the end and try to find a shorter expression).

Body:
I am having trouble getting my head around how to achieve the following. I have gotten this far:

//*[@id="main"]/div[2]/section/div[2]/h1/span[1][starts-with(.,"IDENTIFIER")]/following::span[1]/text()

This will return a response such as:

Foo1 Foo2 Foo3 Foo4

I am trying to make this return only Foo1 & Foo2, where Foo1 & Foo2 can be any length of characters and there may be any number of additional Foo's following them.

I have tried looking at

substring-before(//*[@id="main"]/div[2]/section/div[2]/h1/span[1][starts-with(.,"IDENTIFIER")]/following::span[1]/text(), ' ')

To extract up to the first space however I have hit a wall in what I am doing wrong.

I am using the xpath within a Scrapy spider. Any help is appreciated

Body:
Example with :

<table>
<td>Pierre Paul Jacques Marie Maurice Jeanne</td>
</table>

XPath expression :

substring(//td,1,string-length(substring-before(//td," "))+string-length(substring-before(substring-after(//td," ")," "))+1)

Output :

Pierre Paul

The XPath works in 3 steps. First we get the length of the second term with 3 functions (substring-after, substring-before, and string-length). Space is used as delimiter. Then we get the length of the first term with 2 functions (substring-before and string-length). Space is used as delimiter. Finally  we use susbstring to extract what we need. Syntax : fn(content of the element,starting position for the extraction (1), ending position (length of text1 + length of text2) + 1(space delimiter)).

You can replace //td with your XPath selector (remove the /text() at the end and try to find a shorter expression).


问:
Why Am I Getting "Cannot read property of undefined error" When I Can Print the Undefined Variable?
I am trying to write a recursive function that reads a string with nested parentheses, and turns it into an array with nested arrays. For example:
(hello(hi)are(yo(u))) => ["hello",["hihow"],"are"["yo",["u"]]]

(you might ask why I'm putting a single item into an array. I am planning to divide up the strings by # separators but I will do that after I can at least nest the single strings)

My code so far:

 const preProcessString = element => {
    var elementComponents = [];
    var part = "";
    var rS;
    if (
      element.indexOf("(") < element.indexOf(")") &&
      element.indexOf("(") !== -1
    ) {
      part = element.slice(0, element.indexOf("("));
      elementComponents.push(part);
      rS = preProcessString(element.substr(element.indexOf("(") + 1));
      console.log(rS[0]);//Am able to print the exact value that is causing the error
      elementComponents.push(rS[0]);//Causing the "cannot read property of undefined error"
      element = rS[1];
    } else {
      part = element.slice(0, element.indexOf(")"));
      elementComponents.push(part);
      return [elementComponents, element.substr(element.indexOf(")") + 1)];
    }
};
console.log(preProcessString("(hello(hi)are(yo(u)))"));```
</div>
</div>
</p>

<p>I am getting this error:</p>

``` ParseStepFile.js:272 Uncaught TypeError: Cannot read property '0' of undefined
    at preProcessString (ParseStepFile.js:272)
```

But I am able to print the value (and the value is the expected value) of the "undefined" variable in console.log statement right before the error causing line.  How is this possible? What can I do to fix this? Any help is appreciated!

答:
The valid output your getting is from when you call the preProcessString here.

rS = preProcessString(element.substr(element.indexOf("(") + 1));
```

<p>The error is coming after this, and this rS is really undefined because you're not returning anything</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> const preProcessString = element => {
    var elementComponents = [];
    var part = "";
    var rS;
    if (
      element.indexOf("(") < element.indexOf(")") &&
      element.indexOf("(") !== -1
    ) {
      part = element.slice(0, element.indexOf("("));
      elementComponents.push(part);
      rS = preProcessString(element.substr(element.indexOf("(") + 1));
      console.log(rS[0]);//Am able to print the exact value that is causing the error
      elementComponents.push(rS[0]);//Causing the "cannot read property of undefined error"
      element = rS[1];
      console.log("As you can see, enters here and return nothing to your rS so the rS is undefined")
    } else {
      part = element.slice(0, element.indexOf(")"));
      elementComponents.push(part);
      return [elementComponents, element.substr(element.indexOf(")") + 1)];
    }
};
console.log(preProcessString("(hello(hi)are(yo(u)))"));</code>```

Body:
I am trying to write a recursive function that reads a string with nested parentheses, and turns it into an array with nested arrays. For example:
(hello(hi)are(yo(u))) => ["hello",["hihow"],"are"["yo",["u"]]]

(you might ask why I'm putting a single item into an array. I am planning to divide up the strings by # separators but I will do that after I can at least nest the single strings)

My code so far:

 const preProcessString = element => {
    var elementComponents = [];
    var part = "";
    var rS;
    if (
      element.indexOf("(") < element.indexOf(")") &&
      element.indexOf("(") !== -1
    ) {
      part = element.slice(0, element.indexOf("("));
      elementComponents.push(part);
      rS = preProcessString(element.substr(element.indexOf("(") + 1));
      console.log(rS[0]);//Am able to print the exact value that is causing the error
      elementComponents.push(rS[0]);//Causing the "cannot read property of undefined error"
      element = rS[1];
    } else {
      part = element.slice(0, element.indexOf(")"));
      elementComponents.push(part);
      return [elementComponents, element.substr(element.indexOf(")") + 1)];
    }
};
console.log(preProcessString("(hello(hi)are(yo(u)))"));

I am getting this error:

 ParseStepFile.js:272 Uncaught TypeError: Cannot read property '0' of undefined
    at preProcessString (ParseStepFile.js:272)

But I am able to print the value (and the value is the expected value) of the "undefined" variable in console.log statement right before the error causing line.  How is this possible? What can I do to fix this? Any help is appreciated!

Body:
The valid output your getting is from when you call the preProcessString here.

rS = preProcessString(element.substr(element.indexOf("(") + 1));

The error is coming after this, and this rS is really undefined because you're not returning anything

 const preProcessString = element => {
    var elementComponents = [];
    var part = "";
    var rS;
    if (
      element.indexOf("(") < element.indexOf(")") &&
      element.indexOf("(") !== -1
    ) {
      part = element.slice(0, element.indexOf("("));
      elementComponents.push(part);
      rS = preProcessString(element.substr(element.indexOf("(") + 1));
      console.log(rS[0]);//Am able to print the exact value that is causing the error
      elementComponents.push(rS[0]);//Causing the "cannot read property of undefined error"
      element = rS[1];
      console.log("As you can see, enters here and return nothing to your rS so the rS is undefined")
    } else {
      part = element.slice(0, element.indexOf(")"));
      elementComponents.push(part);
      return [elementComponents, element.substr(element.indexOf(")") + 1)];
    }
};
console.log(preProcessString("(hello(hi)are(yo(u)))"));


问:
how to implement csrf without csrf token in django
In django, if I want to use csrf token, I need to imbed a form with csrf token in django template. However as a backend-engineer I am co-working with a front-end engineer whose code is not available for me. So I caanot use the template. In this case, if I want still the csrf function. what should I do?</p>

答:
you should ask the coworker to embed the csrf token in the form he is sending you

you can get it from document.Cookies if he doesnt want to or cannot use the {% csrf %} tag


问:
Ordering Timestamps for ARIMA model predicion
Info:

I am trying to predict the price of Bitcoin,as a test and to make it easier, 1 day after my most current datetime in my data. So t = 05/27/2020, t + 1 = 05/28/2020.

So I loaded my data:

```<code>x = pd.read_csv('btcdata.csv', header=0, parse_dates=['Date'], index_col=0)
close = x.Close
</code>```

And this is how it looks like .head():

```<code>Date
2020-05-27    8854.32
2020-05-26    8844.42
2020-05-25    8899.31
2020-05-24    8715.73
2020-05-23    9181.76
</code>```

There is a little problem with this is and that the most recent date is located at the top, and the most oldest date is located at the bottom. Most dates are organized by the opposite, at least that's how the ARIMA model sees it.

So when I fit and predict using the model .forecast() , this was my output[0]:

```<code>[381.59648517]
</code>```

Which actually matches more to the .tail() of my data:

```<code>Date
2014-12-05    377.1
2014-12-04    377.1
2014-12-03    378.0
2014-12-02    378.0
2014-12-01    370.0
</code>```

Question/Problem:

How do I get around this, and order it in a way so that the ARIMA model knows which is my most recent date t and know to predict for t + 1

Also every time I fit my model, there were these two warnings. It may be relevant to the problem:

```<code>ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting.
ValueWarning: A date index has been provided, but it is not monotonic and so will be ignored when e.g. forecasting.
</code>```

答:
If the problem is simply that your data is not sorted correctly then this should work.

Data sorted by date:

```<code>prices = x.sort_index()
</code>```

Or, if you only want the 5 most recent data points:

```<code>latest_prices = x.sort_index().iloc[-5:]
</code>```

Body:
Info:

I am trying to predict the price of Bitcoin,as a test and to make it easier, 1 day after my most current datetime in my data. So t = 05/27/2020, t + 1 = 05/28/2020.

So I loaded my data:

x = pd.read_csv('btcdata.csv', header=0, parse_dates=['Date'], index_col=0)
close = x.Close

And this is how it looks like .head():

Date
2020-05-27    8854.32
2020-05-26    8844.42
2020-05-25    8899.31
2020-05-24    8715.73
2020-05-23    9181.76

There is a little problem with this is and that the most recent date is located at the top, and the most oldest date is located at the bottom. Most dates are organized by the opposite, at least that's how the ARIMA model sees it.

So when I fit and predict using the model .forecast() , this was my output[0]:

[381.59648517]

Which actually matches more to the .tail() of my data:

Date
2014-12-05    377.1
2014-12-04    377.1
2014-12-03    378.0
2014-12-02    378.0
2014-12-01    370.0

Question/Problem:

How do I get around this, and order it in a way so that the ARIMA model knows which is my most recent date t and know to predict for t + 1

Also every time I fit my model, there were these two warnings. It may be relevant to the problem:

ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting.
ValueWarning: A date index has been provided, but it is not monotonic and so will be ignored when e.g. forecasting.

Body:
If the problem is simply that your data is not sorted correctly then this should work.

Data sorted by date:

prices = x.sort_index()

Or, if you only want the 5 most recent data points:

latest_prices = x.sort_index().iloc[-5:]


问:
How can I line up my sliders horizontally without using absolute positioning? CSS troubles
I've run into a problem which is interrupting my ability to continue. I've got a simple full-width carousel/slider under my navbar, but because it's using absolute positioning it's messing up the flow of the rest of the page under it (divs hiding beneath it). I tried using a ghost div at a matching height to correct for the height of the area which was out of flow, but when it gets scaled down to the mobile sizes, it doesn't work with my responsive styling due to variable heights (where text determines height).

I'd like to find an alternative that doesn't require absolute positioning, if possible, as it will allow me to keep the rest of my work as-is and keep the responsive features working. Plus I'm just not a fan of absolute positioning unless absolutely necessary. ;)

Presently, I'm using absolute positioning and overflow:hidden; to line up the 4 div "sliders" next to each other.. using left:100%;, left:200%;, etc.

I'd like to find a way to line up the 4 divs (100% width each, totalling 400% width) side-by-side, with overflow hidden, so that my slider will still function the same, but without using absolute positioning. Preferably using only CSS.

Here are the relevant portions of CSS, and the HTML (not sure if it's all relevant):

/* SLIDER CONTAINER */

.css-slider-wrapper {
  overflow: hidden;
}

/* SLIDERS */

.slider {
  width: 100%;
  position: absolute;
  left: 0;
  top: 68px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  align-content: center;
  -webkit-transition: -webkit-transform 1600ms;
  transition: -webkit-transform 1600ms, transform 1600ms;
  -webkit-transform: scale(1);
  transform: scale(1);
}

.slide-1 {
  left: 0;
}

.slide-2 {
  left: 100%
}

.slide-3 {
  left: 200%
}

.slide-4 {
  left: 300%;
}

.slider {
  display: flex;
  justify-content: flex-start;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="css-slider-wrapper">
  <input type="radio" name="slider" class="slide-radio1" checked id="slider_1">
  <input type="radio" name="slider" class="slide-radio2" id="slider_2">
  <input type="radio" name="slider" class="slide-radio3" id="slider_3">
  <input type="radio" name="slider" class="slide-radio4" id="slider_4">

  <!-- Slider #1 -->
  <div class="slider slide-1">CONTENT</div>

  <!-- Slider #2 -->
  <div class="slider slide-2">CONTENT</div>

  <!-- Slider #3 -->
  <div class="slider slide-3">CONTENT</div>

  <!-- Slider #4 -->
  <div class="slider slide-4">CONTENT</div>

  <!-- Slider Pagination -->
  <div class="slider-pagination">
    <label for="slider_1" class="page1"></label>
    <label for="slider_2" class="page2"></label>
    <label for="slider_3" class="page3"></label>
    <label for="slider_4" class="page4"></label>
  </div>

</div></code>```

Thanks for your time and help!

答:
Wrap the sliders with a flexbox (.sliders-container), and set the flex of each slider to flex: 0 0 100vw; (don't grow, don't shrink, base size screen width.

body {
  margin: 0;
}

/* SLIDER CONTAINER */

.css-slider-wrapper {
  /** overflow: hidden; **/
}

.sliders-container {
  display: flex;
  height: 90vh;
}

/* SLIDERS */

.slider {
  display: flex;
  flex: 0 0 100vw;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  align-content: center;
  -webkit-transition: -webkit-transform 1600ms;
  transition: -webkit-transform 1600ms, transform 1600ms;
  -webkit-transform: scale(1);
  transform: scale(1);
}

.slide-1 {
  background: red;
}

.slide-2 {
  background: blue;
}

.slide-3 {
  background: green;
}

.slide-4 {
  background: yellow;
}

.slider {
  display: flex;
  justify-content: flex-start;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="css-slider-wrapper">
  <input type="radio" name="slider" class="slide-radio1" checked id="slider_1">
  <input type="radio" name="slider" class="slide-radio2" id="slider_2">
  <input type="radio" name="slider" class="slide-radio3" id="slider_3">
  <input type="radio" name="slider" class="slide-radio4" id="slider_4">

  <div class="sliders-container">
    <!-- Slider #1 -->
    <div class="slider slide-1">CONTENT</div>

    <!-- Slider #2 -->
    <div class="slider slide-2">CONTENT</div>

    <!-- Slider #3 -->
    <div class="slider slide-3">CONTENT</div>

    <!-- Slider #4 -->
    <div class="slider slide-4">CONTENT</div>
  </div>

  <!-- Slider Pagination -->
  <div class="slider-pagination">
    <label for="slider_1" class="page1"></label>
    <label for="slider_2" class="page2"></label>
    <label for="slider_3" class="page3"></label>
    <label for="slider_4" class="page4"></label>
  </div>

</div></code>```

Body:
I've run into a problem which is interrupting my ability to continue. I've got a simple full-width carousel/slider under my navbar, but because it's using absolute positioning it's messing up the flow of the rest of the page under it (divs hiding beneath it). I tried using a ghost div at a matching height to correct for the height of the area which was out of flow, but when it gets scaled down to the mobile sizes, it doesn't work with my responsive styling due to variable heights (where text determines height).

I'd like to find an alternative that doesn't require absolute positioning, if possible, as it will allow me to keep the rest of my work as-is and keep the responsive features working. Plus I'm just not a fan of absolute positioning unless absolutely necessary. ;)

Presently, I'm using absolute positioning and overflow:hidden; to line up the 4 div "sliders" next to each other.. using left:100%;, left:200%;, etc.

I'd like to find a way to line up the 4 divs (100% width each, totalling 400% width) side-by-side, with overflow hidden, so that my slider will still function the same, but without using absolute positioning. Preferably using only CSS.

Here are the relevant portions of CSS, and the HTML (not sure if it's all relevant):

/* SLIDER CONTAINER */

.css-slider-wrapper {
  overflow: hidden;
}

/* SLIDERS */

.slider {
  width: 100%;
  position: absolute;
  left: 0;
  top: 68px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  align-content: center;
  -webkit-transition: -webkit-transform 1600ms;
  transition: -webkit-transform 1600ms, transform 1600ms;
  -webkit-transform: scale(1);
  transform: scale(1);
}

.slide-1 {
  left: 0;
}

.slide-2 {
  left: 100%
}

.slide-3 {
  left: 200%
}

.slide-4 {
  left: 300%;
}

.slider {
  display: flex;
  justify-content: flex-start;
}

  <input type="radio" name="slider" class="slide-radio1" checked id="slider_1">
  <input type="radio" name="slider" class="slide-radio2" id="slider_2">
  <input type="radio" name="slider" class="slide-radio3" id="slider_3">
  <input type="radio" name="slider" class="slide-radio4" id="slider_4">

CONTENT

CONTENT

CONTENT

CONTENT

Thanks for your time and help!

Body:
Wrap the sliders with a flexbox (.sliders-container), and set the flex of each slider to flex: 0 0 100vw; (don't grow, don't shrink, base size screen width.

body {
  margin: 0;
}

/* SLIDER CONTAINER */

.css-slider-wrapper {
  /** overflow: hidden; **/
}

.sliders-container {
  display: flex;
  height: 90vh;
}

/* SLIDERS */

.slider {
  display: flex;
  flex: 0 0 100vw;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  align-content: center;
  -webkit-transition: -webkit-transform 1600ms;
  transition: -webkit-transform 1600ms, transform 1600ms;
  -webkit-transform: scale(1);
  transform: scale(1);
}

.slide-1 {
  background: red;
}

.slide-2 {
  background: blue;
}

.slide-3 {
  background: green;
}

.slide-4 {
  background: yellow;
}

.slider {
  display: flex;
  justify-content: flex-start;
}

<div class="css-slider-wrapper">
  <input type="radio" name="slider" class="slide-radio1" checked id="slider_1">
  <input type="radio" name="slider" class="slide-radio2" id="slider_2">
  <input type="radio" name="slider" class="slide-radio3" id="slider_3">
  <input type="radio" name="slider" class="slide-radio4" id="slider_4">

  <div class="sliders-container">
    <!-- Slider #1 -->
    <div class="slider slide-1">CONTENT</div>

    <!-- Slider #2 -->
    <div class="slider slide-2">CONTENT</div>

    <!-- Slider #3 -->
    <div class="slider slide-3">CONTENT</div>

    <!-- Slider #4 -->
    <div class="slider slide-4">CONTENT</div>
  </div>

  <!-- Slider Pagination -->
  <div class="slider-pagination">
    <label for="slider_1" class="page1"></label>
    <label for="slider_2" class="page2"></label>
    <label for="slider_3" class="page3"></label>
    <label for="slider_4" class="page4"></label>
  </div>

</div>


问:
React blank page after running npm run build because of react-router-dom
Here is my code for the index.js page:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Route, Switch} from "react-router-dom"
import './css/bootstrap.min.css';
import './css/style.css';

// Pages
import Library from './pages/Library.js'
import Register from './pages/Register.js'

ReactDOM.render(
  <div>
    <Router>
      <Switch>
        <Route exact path="/" component={Library}/>
        <Route exact path="/library" component={Library}/>
        <Route exact path="/register" component={Register}/>
      </Switch>
    </Router>
  </div>,
  document.getElementById('root')
)
</code>```

When I run npm start I get the application as desired. localhost:3000 and localhost:3000/library render the Library component, while localhost:3000/register renders the Register component.

When I run npm run build I get the build folder but when I enter the index.html page, it is blank.

This problem was introduced after I implemented the router. Previously the result of both npm start and npm run build were the same.

答:
Here is the link to the same issue you are facing on the official create-react-app github issues

It is marked as closed there, you can also read that for more info.

You should serve the build folder for example like

```<code>npx serve -s build
</code>```

Body:
Here is my code for the index.js page:

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Route, Switch} from "react-router-dom"
import './css/bootstrap.min.css';
import './css/style.css';

// Pages
import Library from './pages/Library.js'
import Register from './pages/Register.js'

ReactDOM.render(

    <Router>
      <Switch>
        <Route exact path="/" component={Library}/>
        <Route exact path="/library" component={Library}/>
        <Route exact path="/register" component={Register}/>
      </Switch>
    </Router>

,
  document.getElementById('root')
)

When I run npm start I get the application as desired. localhost:3000 and localhost:3000/library render the Library component, while localhost:3000/register renders the Register component.

When I run npm run build I get the build folder but when I enter the index.html page, it is blank.

This problem was introduced after I implemented the router. Previously the result of both npm start and npm run build were the same.

Body:
Here is the link to the same issue you are facing on the official create-react-app github issues

It is marked as closed there, you can also read that for more info.

You should serve the build folder for example like

npx serve -s build


问:
I can't connect to mysql DB connection refused
I have tried to connect to the DB mysql using php artisan migrate command and gives me this error

```<code>     Exception trace:
 1   PDOException::("SQLSTATE[HY000] [2002] Connection refused")
  /Users/hamad/Desktop/web/php/test/vendor/laravel/framework/srcIlluminate/Database/Connectors/Connector.php:70

 2   PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=laravel", "root", "", [])
  /Users/hamad/Desktop/web/php/test/vendor/laravel/framework/src/Illuminate/Database/Connectors/.Connector.php:70
</code>```

my set up in the env file is

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
</code>```

and in config /database.php is

```<code>'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'laravel'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => true,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],
</code>```

I have tried to use localhost instead of 127.0.0.1 but did not work

thanks for your help

答:
I changed from xampp to mamp program and worked fine
I think it is from the localserver and the port number
xampp using 192.168.64.2 as localserver
mamp uses 127.0.0.1 as localserver </p>

Body:
I have tried to connect to the DB mysql using php artisan migrate command and gives me this error

     Exception trace:
 1   PDOException::("SQLSTATE[HY000] [2002] Connection refused")
  /Users/hamad/Desktop/web/php/test/vendor/laravel/framework/srcIlluminate/Database/Connectors/Connector.php:70

 2   PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=laravel", "root", "", [])
  /Users/hamad/Desktop/web/php/test/vendor/laravel/framework/src/Illuminate/Database/Connectors/.Connector.php:70

my set up in the env file is

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

and in config /database.php is

'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'laravel'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => true,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],

I have tried to use localhost instead of 127.0.0.1 but did not work

thanks for your help


问:
How to fix PHP 7.2 Warning: count(): Parameter must be an array or an object that implements Countable in errors.php?
My script is-

```<code><?php  if (count($errors) > 0) : ?>
  <div class="error">
        <?php foreach ($errors as $error) : ?>
          <p><?php echo $error ?></p>
        <?php endforeach ?>
  </div>
<?php  endif ?>

</code>```

The error I get is Warning: count(): Parameter must be an array or an object that implements Countable.

I'm using PHP 7.2 on Apache2.

答:
As the error says, Parameter must be an array or an object that implements Countable, the $errors should be an array.

In your case, it might be empty. So before using count() you should always check it implements a Countable interface.

I assume you are trying to iterate an Array and for that I first check the $errors is an array using is_array().

<?php  if (is_array($errors) && count($errors) ) : ?>

        <?php foreach ($errors as $error) : ?>

<?php echo $error ?>

        <?php endforeach ?>

<?php  endif ?>
```

You may also need to look at is_countable(), link below:

PHP Official Documentation:

PHP count()

PHP is_countable()

PHP is_array()

Body:
My script is-

<?php  if (count($errors) > 0) : ?>

        <?php foreach ($errors as $error) : ?>

<?php echo $error ?>

        <?php endforeach ?>

<?php  endif ?>

The error I get is Warning: count(): Parameter must be an array or an object that implements Countable.

I'm using PHP 7.2 on Apache2.

Body:
As the error says, Parameter must be an array or an object that implements Countable, the $errors should be an array.

In your case, it might be empty. So before using count() you should always check it implements a Countable interface.

I assume you are trying to iterate an Array and for that I first check the $errors is an array using is_array().

<?php  if (is_array($errors) && count($errors) ) : ?>
  <div class="error">
        <?php foreach ($errors as $error) : ?>
          <p><?php echo $error ?></p>
        <?php endforeach ?>
  </div>
<?php  endif ?>

You may also need to look at is_countable(), link below:

PHP Official Documentation:

PHP count()

PHP is_countable()

PHP is_array()


问:
WPF render thread hangs
I'm experiencing a problem in a wpf app where the render thread stops rendering, but the UI thread and helper threads are still pumping messages.

It appears to be related to the corruption of the presentation font cache, however this seems unlikely, as the app recovers fine on reboot.

The render thread will occasionally hang, preventing drawing updates, but the UI thread is still pumping messages.

We have seen a similar issue (similar to here) that occured when applying a scale transform to a textblock that was solved by deleting the font cache, however this particular problem is not reliably repeatable.

What is the best way to diagnose the root cause of this problem?

I have open a bug with microsoft at connect, but it will not be considered unless others vote it up.

答:
I don't know why it happens, but I have experienced it before. It's easier to observe it in systems that target framework 4.0 and run on older machines (XP, Vista).

What I did to solve was:

Delete FontCache3.0.0.0.dat

Permanently disable the font cache service on the offending machine

Solution 1 worked in one XP machine. It also worked in a Vista machine, but after a while the problem showed up again.

To delete FontCache3.0.0.0.dat you will need to stop the "Windows Presentation Foundation Font Cache 3.0.0.0" service before you can delete that file. In Vista it is located under c:\windows\serviceprofiles\localservice\appdata\local. In XP it is under c:\windows\system32\documents and settings\localservice\local settings\application data (I might have mispelled some folder)

I have also found that disabling the system altogether (solution 2) did not affect the performance of my .net apps.

Title: WPF render thread hangs


问:
Set specific cells with values to trigger with google script one by one
Before VS After looks after running my current codeI'm trying to trigger an action that will allow me to send my current google script into an app.
I tried to look around google and came out with what I have now.

I have a drop-down list at column "K3:K100". There are two options (Slack & Not Yet).

I want my script to be able to run when I select "Slack" and will change to "slacked" once the script is done running while if any of the columns are selected as "Not Yet" it will not run or do anything. Currently, this code works but it turns the whole column of K3:K100 to "Slacked" including the column that are written "Not yet" selected. Please help! I'm new to this.

TLDR: I want K3 column when "Slack" selected turns to slacked with google script while K4 column will not turn to "Slacked" instead just be "not yet" when the drop list is selected as I have programmed the script to run based on "Slack".As of now, it overwrites everything on column K3:K100 to "Slacked" once the script is run. I want those that are currently selected as "Not Yet" to be as it is not overwritten.

```<code>function SendSlack(){

  // get information from the range of
  var depositid = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = depositid.getSheetByName("MYSHEETNAME");
  var lastrow = sheet.getLastRow();

  var range = sheet.getRange(2,1,lastrow-3,12).getValues();

  // create timestamp to mark when communication was sent
  var timestamp = new Date();

  // loop over range and send communication if "SLACK" option chosen
  for (var i = 0; i < range.length; i++)
  {SpreadsheetApp.getActiveSheet().getRange('K3:K100').setValue('Slacked'); // this makes it to "slacked when you press slacked and run script"
    if (range[i][10] == "Slack")
      sendToSlack(range[i]);

    };
  }
}
</code>```

答:
If I understand correctly, you probably want this.

```<code>const range = SpreadsheetApp.getActiveSheet().getRange("K3:K100").getValues()
for (var i = 0; i < range.length; i++) {
    if (range[i][10] == "Slack") {
        sendToSlack(range[i]);
        range.setValue("Slacked");
    }
}
</code>```

The setValue("Slacked") should be inside the if check. You don't need a case for "Not Yet" because it wouldn't do anything anyway. Notice I also put the range in a const outside the loop. Those get functions are costly.

Body:
Before VS After looks after running my current codeI'm trying to trigger an action that will allow me to send my current google script into an app.
I tried to look around google and came out with what I have now.

I have a drop-down list at column "K3:K100". There are two options (Slack & Not Yet).

I want my script to be able to run when I select "Slack" and will change to "slacked" once the script is done running while if any of the columns are selected as "Not Yet" it will not run or do anything. Currently, this code works but it turns the whole column of K3:K100 to "Slacked" including the column that are written "Not yet" selected. Please help! I'm new to this.

TLDR: I want K3 column when "Slack" selected turns to slacked with google script while K4 column will not turn to "Slacked" instead just be "not yet" when the drop list is selected as I have programmed the script to run based on "Slack".As of now, it overwrites everything on column K3:K100 to "Slacked" once the script is run. I want those that are currently selected as "Not Yet" to be as it is not overwritten.

function SendSlack(){

  // get information from the range of
  var depositid = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = depositid.getSheetByName("MYSHEETNAME");
  var lastrow = sheet.getLastRow();

  var range = sheet.getRange(2,1,lastrow-3,12).getValues();

  // create timestamp to mark when communication was sent
  var timestamp = new Date();

  // loop over range and send communication if "SLACK" option chosen
  for (var i = 0; i < range.length; i++)
  {SpreadsheetApp.getActiveSheet().getRange('K3:K100').setValue('Slacked'); // this makes it to "slacked when you press slacked and run script"
    if (range[i][10] == "Slack")
      sendToSlack(range[i]);

    };
  }
}

Body:
If I understand correctly, you probably want this.

const range = SpreadsheetApp.getActiveSheet().getRange("K3:K100").getValues()
for (var i = 0; i < range.length; i++) {
    if (range[i][10] == "Slack") {
        sendToSlack(range[i]);
        range.setValue("Slacked");
    }
}

The setValue("Slacked") should be inside the if check. You don't need a case for "Not Yet" because it wouldn't do anything anyway. Notice I also put the range in a const outside the loop. Those get functions are costly.


问:
vuex store doesn't update component
I'm new to vue, so I'm probably making a rookie error.

I have a root vue element - raptor.js:

```<code>const Component = {
el: '#app',
store,
data: {
    productList: store.state.productlist
},
beforeCreate: function () {
    return store.dispatch('getProductList', 'getTrendingBrands');
},
updated: function (){
    console.log(111);
    startSlider();
}
};
const vm = new Vue(Component);
</code>```

Using this template

```<code><div class="grid-module-single popular-products" id="app">
<div class="row">
    <div class="popular-items-slick col-xs-12">
        <div v-for="product in productList">
            ...
        </div>
    </div>
</div>
</code>```

My store is very simple store/index.js:

```<code>import Vue from 'vue';
import Vuex from 'vuex';
import model from '../../utilities/model';

Vue.use(Vuex);

export default new Vuex.Store({
state: {
    productlist: []
},
mutations: {
    setProductList(state, data) {
        state.productlist = data;
    }
},
actions: {
    getProductList({ commit }, action) {
        return model.products().then(data => commit('setProductList', data));
    }
}
});
</code>```

In my vuex devtool, I can see, that the store is being updated
https://www.screencast.com/t/UGbw7JyHS3

but my component is not being updated:
https://www.screencast.com/t/KhXQrePEd

Question:

I can see from the devtools, that my code is working. The store is being updated with data. My component is not being updated,however. I thought it was enough just to add this in the data property on the component:

```<code>data: {
    productList: store.state.productlist
}
</code>```

but apparently the data object doesn't seem to be automatically synced with the store. So either I'm doing a complete vue no-no somewhere, or I need to tweak the code a bit. Anyway can anyone help me in the right direction.

Thanks a lot.

答:
You are calling the store into the productList data property in the wrong way.

You can try it:

```<code>data: {
  productList: $store.state.productlist
}
</code>```

Otherwise you have to import store in each component that are using the store.

Title: vuex store doesn't update component

Body:
I'm new to vue, so I'm probably making a rookie error.

I have a root vue element - raptor.js:

const Component = {
el: '#app',
store,
data: {
    productList: store.state.productlist
},
beforeCreate: function () {
    return store.dispatch('getProductList', 'getTrendingBrands');
},
updated: function (){
    console.log(111);
    startSlider();
}
};
const vm = new Vue(Component);

Using this template

            ...

My store is very simple store/index.js:

import Vue from 'vue';
import Vuex from 'vuex';
import model from '../../utilities/model';

Vue.use(Vuex);

export default new Vuex.Store({
state: {
    productlist: []
},
mutations: {
    setProductList(state, data) {
        state.productlist = data;
    }
},
actions: {
    getProductList({ commit }, action) {
        return model.products().then(data => commit('setProductList', data));
    }
}
});

In my vuex devtool, I can see, that the store is being updated
https://www.screencast.com/t/UGbw7JyHS3

but my component is not being updated:
https://www.screencast.com/t/KhXQrePEd

Question:

I can see from the devtools, that my code is working. The store is being updated with data. My component is not being updated,however. I thought it was enough just to add this in the data property on the component:

data: {
    productList: store.state.productlist
}

but apparently the data object doesn't seem to be automatically synced with the store. So either I'm doing a complete vue no-no somewhere, or I need to tweak the code a bit. Anyway can anyone help me in the right direction.

Thanks a lot.

Body:
You are calling the store into the productList data property in the wrong way.

You can try it:

data: {
  productList: $store.state.productlist
}

Otherwise you have to import store in each component that are using the store.


问:
Is Broadcast variable in spark moved to each executor or each nodemanager in YARN?
In YARN how is broadcast variable distributed across nodes. I am confused if it goes to each executor in Nodemanager or only copy on each node manager in cluster.

Please let me know about it. Thanks in advance.

答:
Broadcast variables in Apache Spark is a mechanism for sharing variables across executors that are meant to be read-only.

In order to understand Broadcast variable behavior please understand how the Spark life cycle works

Spark driver is started by YARN

It creates DAG for the Job

Job contains of Mapping an reducing tasks

These mapping and reducing tasks are ran in an Executor (i.e. a separate JVM process with its own thread pool)

This executor get its own copy of Broadcast variable at the time of initialization. The broadcast variable is distributed by Spark, not Yarn.

Step 3 will be repeated task based on volume of data or if its a Spark streaming job but there will always be one copy of broadcast variable and stay with the executor till it goes down.

If by node manager you are referring to Spark Worker nodes then I don't think Spark Worker nodes needs broadcast variable so they might not keep any copy of it.

Node manager (i.e. Spark worker) is responsible for,
 - allocating the required resources
 - registering executor to the driver
 - maintaining the Driver - Executor communication


问:
Google Cloud Functions "trigger-bucket" is not working as expected
I made a simple Cloud Function, which is supposed to log details of file operations in a Cloud Storage bucket.

I deployed it with the following command: gcloud functions deploy bucket_logger --runtime=python37 --memory=256 --region=us-east1 --entry-point=bucket_logger_function --trigger-bucket=[BUCKET_NAME]

```<code>def bucket_logger_function(data, context):
    id = context.event_id
    type = context.event_type

    print('Event ID: ' + id)
    print('Event Type: ' + type)

    if type == 'google.storage.object.finalize':
            print('File created: ' + data['name'])
    elif type == 'google.storage.objects.delete':
            print('File deleted: ' + data['name'])
    elif type == 'google.storage.objects.metadataUpdate':
            print('Metadata updated: ' + data['name'])
    else:
            print('File archived: ' + data['name'])
</code>```

I expect the function to trigger whenever I upload, delete, archive and update the metadata of any object within my bucket, but it is only triggered when a file is uploaded.

What could I be missing? The documentation doesn't mention anything specific about this, it claims that the aforementioned operations would work.

答:
I tried the approach of enabling Pub/Sub notifications, I modified your code, but I'm missing the attribute section which should contain the contentType.

```<code>def bucket_logger_function(event, context):
    import base64
    import json

    # Print Event Type and Event ID
    print('Event ID: ' + context.event_id)
    print('Event Type: ' + context.event_type)

    # Print Attributes  <-- This is the part that fails
    attributes = base64.b64decode(event['attributes']).decode('utf-8')
    print(attributes['eventType'])

    # Print Payload
    payload = json.loads(base64.b64decode(event['data']).decode('utf-8'))
    print(payload['name'])
    print(payload['bucket'])
</code>```

I guess that if you get the hang of parsing the attributes you'd be good to go to apply some logic on the event type.

Body:
I made a simple Cloud Function, which is supposed to log details of file operations in a Cloud Storage bucket.

I deployed it with the following command: gcloud functions deploy bucket_logger --runtime=python37 --memory=256 --region=us-east1 --entry-point=bucket_logger_function --trigger-bucket=[BUCKET_NAME]

def bucket_logger_function(data, context):
    id = context.event_id
    type = context.event_type

    print('Event ID: ' + id)
    print('Event Type: ' + type)

    if type == 'google.storage.object.finalize':
            print('File created: ' + data['name'])
    elif type == 'google.storage.objects.delete':
            print('File deleted: ' + data['name'])
    elif type == 'google.storage.objects.metadataUpdate':
            print('Metadata updated: ' + data['name'])
    else:
            print('File archived: ' + data['name'])

I expect the function to trigger whenever I upload, delete, archive and update the metadata of any object within my bucket, but it is only triggered when a file is uploaded.

What could I be missing? The documentation doesn't mention anything specific about this, it claims that the aforementioned operations would work.

Body:
I tried the approach of enabling Pub/Sub notifications, I modified your code, but I'm missing the attribute section which should contain the contentType.

def bucket_logger_function(event, context):
    import base64
    import json

    # Print Event Type and Event ID
    print('Event ID: ' + context.event_id)
    print('Event Type: ' + context.event_type)

    # Print Attributes  <-- This is the part that fails
    attributes = base64.b64decode(event['attributes']).decode('utf-8')
    print(attributes['eventType'])

    # Print Payload
    payload = json.loads(base64.b64decode(event['data']).decode('utf-8'))
    print(payload['name'])
    print(payload['bucket'])

I guess that if you get the hang of parsing the attributes you'd be good to go to apply some logic on the event type.


问:
Android app crashing, but only on Samsung Galaxy
Several of my users are experiencing crashes, all with the same error (shown below). Strangely, they are all using variants of the Samsung Galaxy.

I read that it may be related to an Out-Of-Memory situation, but moved images to drawable-nodpi and enabled largeHeap. The error actually seems more frequent after this change!

My app has over 30 activities and 10 layouts, so I won`t share code.

If anyone could give me a clue about where to start looking, I would appreciate it. It would also be useful to hear some theories about why only Galaxies are doing this.

```<code>java.lang.IllegalStateException:
  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick (AppCompatViewInflater.java)
  at android.view.View.performClick (View.java:6261)
  at android.widget.TextView.performClick (TextView.java:11157)
  at android.view.View$PerformClick.run (View.java:23748)
  at android.os.Handler.handleCallback (Handler.java:751)
  at android.os.Handler.dispatchMessage (Handler.java:95)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)

Caused by: java.lang.reflect.InvocationTargetException:
  at java.lang.reflect.Method.invoke (Method.java)
</code>```

答:
Install Genymotion and clone Samsung Device on which your app is crashing and check logs..
I hope it helps</p>

Body:
Several of my users are experiencing crashes, all with the same error (shown below). Strangely, they are all using variants of the Samsung Galaxy.

I read that it may be related to an Out-Of-Memory situation, but moved images to drawable-nodpi and enabled largeHeap. The error actually seems more frequent after this change!

My app has over 30 activities and 10 layouts, so I won`t share code.

If anyone could give me a clue about where to start looking, I would appreciate it. It would also be useful to hear some theories about why only Galaxies are doing this.

java.lang.IllegalStateException:
  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick (AppCompatViewInflater.java)
  at android.view.View.performClick (View.java:6261)
  at android.widget.TextView.performClick (TextView.java:11157)
  at android.view.View$PerformClick.run (View.java:23748)
  at android.os.Handler.handleCallback (Handler.java:751)
  at android.os.Handler.dispatchMessage (Handler.java:95)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)

Caused by: java.lang.reflect.InvocationTargetException:
  at java.lang.reflect.Method.invoke (Method.java)


问:
Do I need Windows 10 Pro to run Docker? Error: Hardware assisted virtualization and data execution protection must be enabled in the BIOS
I just installed Docker after upgrading my Windows 10 Home x64 to the version 2004 with the OS build 19041.264 (I needed to upgrade because Docker required me to have an OS buld >19018). Now if I want to launch docker I get this error Hardware assisted virtualization and data execution protection must be enabled in the BIOS. I have already read this (it is old) question, but because they let me install docker on my windows 10 home I assume that I can somehow run it without hyper-v, cuz I can't download it.

答:
The Hyper-V role cannot be installed on Windows 10 Home. Hyper-V is used to run Linux kernel on Windows.

https://learn.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/enable-hyper-v

The alternative solution is you can use Virtual box instead of Microsoft native Hyper-V. Docker toolbox comes with Virtual box. You can get details installation steps from below link.

https://docs.docker.com/toolbox/toolbox_install_windows/