问:
html/javascript page that files can be loaded to
I want to write a html file that can access files on my computer with gui like this one:

https://smallpdf.com/pdf-to-jpg

In the yellow box it says "choose file". you can click that and choose a file from your computers file system. I would like to do something similar and then be able to use the files in the html.

In particular I want the user to be able to choose a png and then convert it to a html canvas and then do stuff with that canvas. I want everything to be local, so nothing should be uploaded like the website i linked to does.

How does one do this?

Thanks

Sorry this wasn't clear, I want to have all the file processing handled by the html page not by some php on a server. I don't want there to be a server side component to this. If that is not possible please let me know, thanks again.

I want everything to be able to work off line so you could just have the html page, open it, and use it.

答:
You can achieve what you want through this code

```<code><form>
   <input type="file" name="pic" accept=".png" onchange="loadFile(event)">
   <img id="output"/>
</form>

<script>
  var loadFile = function(event) {
     var output = document.getElementById('output');
     output.src = URL.createObjectURL(event.target.files[0]);
  };
</script>
</code>```

As for the UI, it will be a css that you need to do on your own.

Body:
You can achieve what you want through this code

<form>
   <input type="file" name="pic" accept=".png" onchange="loadFile(event)">
   <img id="output"/>
</form>

<script>
  var loadFile = function(event) {
     var output = document.getElementById('output');
     output.src = URL.createObjectURL(event.target.files[0]);
  };
</script>

As for the UI, it will be a css that you need to do on your own.


来源: stackexchange

问:
Passing data through Intent and receiving it
I am trying to pass data through my Intent into the next activity so I can receive it and give a timer values.

```<code>Button TimerButton = (Button)findViewById(R.id.TimerActivityButton);
TimerButton.setOnClickListener(new View.OnClickListener(){
     public void onClick(View v)
     {
          Intent timer = new Intent (BeefActivity.this,TimerActivity.class);
          timer.putExtra("beefType", 5000);
          timer.putExtra("beefThickness", 5000);
          timer.putExtra("grillTime", 15000);
          startActivity(timer);
      }
});
</code>```

I have tried different methods of receiving the values, and I keep getting a force close or compiler errors. I know this is simple so can somebody please show me how to do this. Thank you in advance!

```<code>This is force closing
</code>```

I tried passing in int length = beefType and it force closed

I tried changing the -1 to 200, it still force closed

I put back int length = 20000 where it worked originally

Just having int beefType = getIntent().getIntExtra("beefType", -1); at the top of my class makes it force close. No compiler errors. I am stuck :-( Here is how my code looks

```<code>package com.android.project1;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class TimerActivity extends Activity {

    int beefType = getIntent().getIntExtra("beefType", 200);

  TextView timeDisplay;
  MyCount counter;
  int state = 0;
  int length = 20000;
  long startTime = 0;
  long currentTime = 0;
  long timeElapsed = 0;
  long timeRemaining = 0;
  long prevTimeRemaining = 0;
  Button control;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.timer);

    timeDisplay = (TextView) findViewById(R.id.timer);
    control = (Button) findViewById(R.id.control);
    counter = new MyCount(length, 100);
  }
  public String formatTime(long millis)
  {
      String output = "00:00:00";
      long seconds = millis / 1000;
      long minutes = seconds / 60;
      long hours = minutes / 60;

      seconds = seconds % 60;
      minutes = minutes % 60;
      hours = hours % 60;

      String secondsD = String.valueOf(seconds);
      String minutesD = String.valueOf(minutes);
      String hoursD = String.valueOf(hours);

      if (seconds < 10)
        secondsD = "0" + seconds;
      if (minutes < 10)
        minutesD = "0" + minutes;
      if (hours < 10)
        hoursD = "0" + hours;

      output = hoursD + " : " + minutesD + " : " + secondsD;
      return output;
    }
  public void control(View view) {
    switch (state) {
    case 0:
      startTime = System.currentTimeMillis();
      counter.start();
      control.setText(R.string.pause);
      state = 1;
      break;
    case 1:
      // Pause
      currentTime = System.currentTimeMillis();
      timeElapsed = currentTime - startTime;
      if (prevTimeRemaining == 0)
        timeRemaining = length - timeElapsed;
      else
        timeRemaining = prevTimeRemaining - timeElapsed;
      counter.cancel();
      timeDisplay.setText("Left: " + String.valueOf(formatTime(timeRemaining)));
      control.setText(R.string.resume);
      prevTimeRemaining = timeRemaining;

      // Resume
      counter = new MyCount(timeRemaining, 100);
      state = 0;
      break;
    case 2:
      prevTimeRemaining = 0;
      counter = new MyCount(length, 100);
      control.setText(R.string.start);
      timeDisplay.setText(R.string.timer);
      state = 0;
    }
  }

  public class MyCount extends CountDownTimer
  {

    public MyCount(long millisInFuture, long countDownInterval)
    {
      super(millisInFuture, countDownInterval);
    }
    public void onTick(long timeRemaining)
    {
        timeDisplay.setText("Left: " + formatTime(timeRemaining));
    }
    public void onFinish()
    {
      timeDisplay.setText("Finished!");
      state = 2;
      control.setText(R.string.restart);
    }
  }
}
</code>```

答:
```<code>int beefType = getIntent().getIntExtra("beefType", -1);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to pass data through my Intent into the next activity so I can receive it and give a timer values.

Button TimerButton = (Button)findViewById(R.id.TimerActivityButton);
TimerButton.setOnClickListener(new View.OnClickListener(){
     public void onClick(View v)
     {
          Intent timer = new Intent (BeefActivity.this,TimerActivity.class);
          timer.putExtra("beefType", 5000);
          timer.putExtra("beefThickness", 5000);
          timer.putExtra("grillTime", 15000);
          startActivity(timer);
      }
});

I have tried different methods of receiving the values, and I keep getting a force close or compiler errors. I know this is simple so can somebody please show me how to do this. Thank you in advance!

This is force closing

I tried passing in int length = beefType and it force closed

I tried changing the -1 to 200, it still force closed

I put back int length = 20000 where it worked originally

Just having int beefType = getIntent().getIntExtra("beefType", -1); at the top of my class makes it force close. No compiler errors. I am stuck :-( Here is how my code looks

package com.android.project1;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class TimerActivity extends Activity {

    int beefType = getIntent().getIntExtra("beefType", 200);

  TextView timeDisplay;
  MyCount counter;
  int state = 0;
  int length = 20000;
  long startTime = 0;
  long currentTime = 0;
  long timeElapsed = 0;
  long timeRemaining = 0;
  long prevTimeRemaining = 0;
  Button control;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.timer);

    timeDisplay = (TextView) findViewById(R.id.timer);
    control = (Button) findViewById(R.id.control);
    counter = new MyCount(length, 100);
  }
  public String formatTime(long millis)
  {
      String output = "00:00:00";
      long seconds = millis / 1000;
      long minutes = seconds / 60;
      long hours = minutes / 60;

      seconds = seconds % 60;
      minutes = minutes % 60;
      hours = hours % 60;

      String secondsD = String.valueOf(seconds);
      String minutesD = String.valueOf(minutes);
      String hoursD = String.valueOf(hours);

      if (seconds < 10)
        secondsD = "0" + seconds;
      if (minutes < 10)
        minutesD = "0" + minutes;
      if (hours < 10)
        hoursD = "0" + hours;

      output = hoursD + " : " + minutesD + " : " + secondsD;
      return output;
    }
  public void control(View view) {
    switch (state) {
    case 0:
      startTime = System.currentTimeMillis();
      counter.start();
      control.setText(R.string.pause);
      state = 1;
      break;
    case 1:
      // Pause
      currentTime = System.currentTimeMillis();
      timeElapsed = currentTime - startTime;
      if (prevTimeRemaining == 0)
        timeRemaining = length - timeElapsed;
      else
        timeRemaining = prevTimeRemaining - timeElapsed;
      counter.cancel();
      timeDisplay.setText("Left: " + String.valueOf(formatTime(timeRemaining)));
      control.setText(R.string.resume);
      prevTimeRemaining = timeRemaining;

      // Resume
      counter = new MyCount(timeRemaining, 100);
      state = 0;
      break;
    case 2:
      prevTimeRemaining = 0;
      counter = new MyCount(length, 100);
      control.setText(R.string.start);
      timeDisplay.setText(R.string.timer);
      state = 0;
    }
  }

  public class MyCount extends CountDownTimer
  {

    public MyCount(long millisInFuture, long countDownInterval)
    {
      super(millisInFuture, countDownInterval);
    }
    public void onTick(long timeRemaining)
    {
        timeDisplay.setText("Left: " + formatTime(timeRemaining));
    }
    public void onFinish()
    {
      timeDisplay.setText("Finished!");
      state = 2;
      control.setText(R.string.restart);
    }
  }
}


问:
macOS 10.12 and iOS 10 - Obscuring portions of a screenshot?
On both macOS and iOS, when a user takes a screenshot of a video file playing within iTunes / the TV app, the screenshot is obscured and the media player layer appears as a solid black box in the screenshot as shown here:

iOS:

macOS:

I have read in other posts that it is not possible to obscure/prevent the user from taking a screenshot on iOS devices; however, as shown in these images, Apple appears to be using some method to obscure the content of the video in the screenshot file.

In these cases, how is the app managing to obscure the video content within the screenshot?

答:
For MacOS it's pretty easy... set the window level to be above a certain point, for example in one of my apps where I disallow screenshots, I do this (in Objective-C):

```<code>windowLevel = CGShieldingWindowLevel();
[myWindowOutlet setLevel: windowLevel];
</code>```

For iOS it's trickier.  You can tell when a screenshot has been taken, but there's no official API to stop it from happening.  One person on Apple's developer forums suggested to call "touchesCancelled"

ContentLicense: CC BY-SA 3.0

Body:
For MacOS it's pretty easy... set the window level to be above a certain point, for example in one of my apps where I disallow screenshots, I do this (in Objective-C):

windowLevel = CGShieldingWindowLevel();
[myWindowOutlet setLevel: windowLevel];

For iOS it's trickier.  You can tell when a screenshot has been taken, but there's no official API to stop it from happening.  One person on Apple's developer forums suggested to call "touchesCancelled"


问:
How to compare all values in one vector to all values in another? (In minimal time)
I have the following r code:

```<code>list1 <- c(5, 6, 8, 10, 15, 26, 75)
list2 <- c(3, 6, 8, 10, 100, 42)

total <- length(list1)*length(list2)
  for(x in 1:length(list1)) {
    for(y in 1:length(list2)) {
      print(total - (x*y))
      if(list1[x]>list2[y]) {
        l1Bigger <- l1Bigger + 1
      } else if(list1[x]<list2[y]) {
        l2Bigger <- l2Bigger + 1
      } else {
        tie <- tie + 1
      }
    }
  }
  percents <- c(l1Bigger/total, l2Bigger/total, tie/total)
  return(percents)
</code>```

Basically, what I want my code to do is iterate through list1 and list2 and compare the values to figure out how often the values in list1 are greater than the values in list 2. My current method takes a lot of time, is there any way to reduce the amount of time this process takes?

Thank you!

答:
expand.grid is a natural way to do this sort of thing:

```<code>> x <- c(2,4,5,1,3)
> y <- c(1,6,2,3)
> g <- expand.grid(x,y)
> x.bigger <- sum(g$Var1 > g$Var2)
> y.bigger <- sum(g$Var1 < g$Var2)
> ties <- sum(g$Var1 == g$Var2)
> x.bigger
[1] 9
> y.bigger <- sum(g$Var1 < g$Var2)
> ties
[1] 3
</code>```

Of course, ties can just be computed via simple arithmetic from the other two values, but I wanted to show how you could get all three numbers directly.

Body:
I have the following r code:

list1 <- c(5, 6, 8, 10, 15, 26, 75)
list2 <- c(3, 6, 8, 10, 100, 42)

total <- length(list1)*length(list2)
  for(x in 1:length(list1)) {
    for(y in 1:length(list2)) {
      print(total - (x*y))
      if(list1[x]>list2[y]) {
        l1Bigger <- l1Bigger + 1
      } else if(list1[x]<list2[y]) {
        l2Bigger <- l2Bigger + 1
      } else {
        tie <- tie + 1
      }
    }
  }
  percents <- c(l1Bigger/total, l2Bigger/total, tie/total)
  return(percents)

Basically, what I want my code to do is iterate through list1 and list2 and compare the values to figure out how often the values in list1 are greater than the values in list 2. My current method takes a lot of time, is there any way to reduce the amount of time this process takes?

Thank you!

Body:
expand.grid is a natural way to do this sort of thing:

> x <- c(2,4,5,1,3)
> y <- c(1,6,2,3)
> g <- expand.grid(x,y)
> x.bigger <- sum(g$Var1 > g$Var2)
> y.bigger <- sum(g$Var1 < g$Var2)
> ties <- sum(g$Var1 == g$Var2)
> x.bigger
[1] 9
> y.bigger <- sum(g$Var1 < g$Var2)
> ties
[1] 3

Of course, ties can just be computed via simple arithmetic from the other two values, but I wanted to show how you could get all three numbers directly.


问:
javascript function call timing
I am trying to implement a for loop that iterates through a list and subsequently calls two functions, only if the first function results are found.

The issue is that the second function (search.similar) might be taking longer to fetch results.

With the code below, when I run, all of the appropriate output from (search.locate) is correct, but only the last element's results from myList are stored from the (search.similar) function.

ie.     all_results = [[cat_res1,mouse_res2],[dog_res1,mouse_res2],[mouse_res1,mouse_res2]]

How do I fix this to append the right results in the right order?

ie.     all_results = [[cat_res1,cat_res2],[dog_res1,dog_res2],[mouse_res1,mouse_res2]]

```<code>var search = require('./search');
var myList = ['cat','dog','mouse'];
var all_results = [];
for (i=0; i<myList.length; i++){
  /* locate function*/
  search.locate(myList[i], function (err, searchResult){
    if (err){
      console.log("Error");
      return;
    }

    if (!searchResult){
      console.log("Cannot find it");
      return;
    }

    /*similarity function*/
    /* seems to take longer*/
    search.similar(myList[i], function (err, similarResult){
      if (err){
        return;
      }

      if (!similarResult){
        return;
      }

      var res1 = searchResult.data;
      var res2 = similarResult.data;
      /* append results to array*/
      all_results.push([res1,res2]);
    }
  });
}
</code>```

答:
This is a good case for Promises (see Bluebird JS for example http://bluebirdjs.com/docs/getting-started.html) or you could do it with
 async.map().

This page talks about it well, too. http://promise-nuggets.github.io/articles/14-map-in-parallel.html

There are many Stack Overflows discussing Promises as well. Understanding JS Promises for example.

A rough example of how to write this with a Promise:

```<code>var search = require('./search');
var myList = ['cat','dog','mouse']
var all_results = []
var Promise = require('bluebird');
var locate = Promise.promisify(search.locate);
var similar = Promise.promisify(search.similar);

for (i = 0; i < myList.length; i++){
    // locate function
    locate(myList[i], function (err, searchResult) {
        if (err) {
            console.log("Error");
            return;
        }
        if (!searchResult){
            console.log("Cannot find it");
            return;
        }
    }).then(function(result) {
        //similarity function
        similar(myList[i], function (err, similarResult) {
            if (err){
                return;
            }
            if (!similarResult){
                return;
            }

            var res1 = searchResult.data
            var res2 = similarResult.data

            // append results to array
            all_results.push([res1,res2])
        }).finally(function() {
            // NOP
        });
    });
}
</code>```

Title: javascript function call timing

Body:
I am trying to implement a for loop that iterates through a list and subsequently calls two functions, only if the first function results are found.

The issue is that the second function (search.similar) might be taking longer to fetch results.

With the code below, when I run, all of the appropriate output from (search.locate) is correct, but only the last element's results from myList are stored from the (search.similar) function.

ie.     all_results = [[cat_res1,mouse_res2],[dog_res1,mouse_res2],[mouse_res1,mouse_res2]]

How do I fix this to append the right results in the right order?

ie.     all_results = [[cat_res1,cat_res2],[dog_res1,dog_res2],[mouse_res1,mouse_res2]]

var search = require('./search');
var myList = ['cat','dog','mouse'];
var all_results = [];
for (i=0; i<myList.length; i++){
  /* locate function*/
  search.locate(myList[i], function (err, searchResult){
    if (err){
      console.log("Error");
      return;
    }

    if (!searchResult){
      console.log("Cannot find it");
      return;
    }

    /*similarity function*/
    /* seems to take longer*/
    search.similar(myList[i], function (err, similarResult){
      if (err){
        return;
      }

      if (!similarResult){
        return;
      }

      var res1 = searchResult.data;
      var res2 = similarResult.data;
      /* append results to array*/
      all_results.push([res1,res2]);
    }
  });
}

Body:
This is a good case for Promises (see Bluebird JS for example http://bluebirdjs.com/docs/getting-started.html) or you could do it with
 async.map().

This page talks about it well, too. http://promise-nuggets.github.io/articles/14-map-in-parallel.html

There are many Stack Overflows discussing Promises as well. Understanding JS Promises for example.

A rough example of how to write this with a Promise:

var search = require('./search');
var myList = ['cat','dog','mouse']
var all_results = []
var Promise = require('bluebird');
var locate = Promise.promisify(search.locate);
var similar = Promise.promisify(search.similar);

for (i = 0; i < myList.length; i++){
    // locate function
    locate(myList[i], function (err, searchResult) {
        if (err) {
            console.log("Error");
            return;
        }
        if (!searchResult){
            console.log("Cannot find it");
            return;
        }
    }).then(function(result) {
        //similarity function
        similar(myList[i], function (err, similarResult) {
            if (err){
                return;
            }
            if (!similarResult){
                return;
            }

            var res1 = searchResult.data
            var res2 = similarResult.data

            // append results to array
            all_results.push([res1,res2])
        }).finally(function() {
            // NOP
        });
    });
}


问:
I am getting UnboundLocalError because I have the same variable inside functions and in main code
I am having a nightmare, I have created a code in Python to simulate a virtual queue.

The code is simplistic but should work, except for the reoccurring 'UnboundLocalError' I keep getting.

I think the issue is having 'aList' as a parameter for functions and having the variable in the main code as well as within def functions.

The code isn't that long and can be found on this link.

Please can somebody help? I've tried adding 'global aList' but it didn't solve it.

Thanks very much for any assistance.

Snapshot of code below :

```<code>def aRemove(aList):
    newlist = []
    for i in range(1,len(aList)):
        newlist.append(aList[i])
    aList = newlist
    return (aList)

user_request()
aList = ["mark","jon","peter"]
aList = (aRemove(aList))
print(aList)
</code>```

答:
The error in the code is not because of the code snippet you have added in the question but looking at your code provided in the link.

You are using aList inside function user_request() but it is not declared anywhere. What you can do something like this :

```<code>def user_request(aList):
    order = input("What would you like to do P | A | N | L | M | Q \n")
    while True:
        if order == 'P':
            aPrint()
        elif order == 'A':
            useradd = input("what would you like to add to the queue?")
            aAdd(useradd)
        elif order == 'N':
            aList = (aRemove(aList))   # aList used without passed
        elif order == 'L':
            aList = (aLeave(aList,input("What would you like to remove from the queue?")))
        elif order == 'M':
            aLocation()
        elif order == 'Q':
            aQuit()
</code>```

and replace the calling function like this :

```<code>user_request(aList)
</code>```

This shall resolve your error.

Note : Always read the line number in which error occur as that will help you in debugging the error faster and more efficiently.

Body:
I am having a nightmare, I have created a code in Python to simulate a virtual queue.

The code is simplistic but should work, except for the reoccurring 'UnboundLocalError' I keep getting.

I think the issue is having 'aList' as a parameter for functions and having the variable in the main code as well as within def functions.

The code isn't that long and can be found on this link.

Please can somebody help? I've tried adding 'global aList' but it didn't solve it.

Thanks very much for any assistance.

Snapshot of code below :

def aRemove(aList):
    newlist = []
    for i in range(1,len(aList)):
        newlist.append(aList[i])
    aList = newlist
    return (aList)

user_request()
aList = ["mark","jon","peter"]
aList = (aRemove(aList))
print(aList)

Body:
The error in the code is not because of the code snippet you have added in the question but looking at your code provided in the link.

You are using aList inside function user_request() but it is not declared anywhere. What you can do something like this :

def user_request(aList):
    order = input("What would you like to do P | A | N | L | M | Q \n")
    while True:
        if order == 'P':
            aPrint()
        elif order == 'A':
            useradd = input("what would you like to add to the queue?")
            aAdd(useradd)
        elif order == 'N':
            aList = (aRemove(aList))   # aList used without passed
        elif order == 'L':
            aList = (aLeave(aList,input("What would you like to remove from the queue?")))
        elif order == 'M':
            aLocation()
        elif order == 'Q':
            aQuit()

and replace the calling function like this :

user_request(aList)

This shall resolve your error.

Note : Always read the line number in which error occur as that will help you in debugging the error faster and more efficiently.


问:
Cannot open IE through selenium
I am trying to run my automation script in IE and have downloaded IE driver and giving that in path but some reason its not opening and getting error

org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session

I am setting path via batch file

```<code>java -jar selenium-server-standalone-2.53.1.jar -Dwebdriver.chrome.driver="chromedriver.exe" -Dwebdriver.ie.driver="IEDriverServer.exe"
</code>```

Here is the code creating the IEDriverInstance

```<code>else if (AutomationConstants.BROWSER_TYPE.equalsIgnoreCase("IE"))
{
    Browser ie = new IEBrowser();
    System.out.println(ie);

    try
    {
        webDriver = new RemoteWebDriver(new URL(SeleniumProperties.getHost()), ie.getCapabilities());
    } catch (MalformedURLException mue)
    {
        LOGGER.error(mue);
    }
}

private static final String NAME = "IE";
private static DesiredCapabilities capabilities;
static
{
    capabilities = new DesiredCapabilities();
    capabilities = DesiredCapabilities.internetExplorer();
    capabilities.setPlatform(Platform.WINDOWS);
    capabilities.setVersion("11");
    capabilities.setJavascriptEnabled(true);
    capabilities.setCapability("acceptSslCerts", true);
}
/** * */
public IEBrowser()
{
    super(NAME, capabilities);
}
</code>```

答:
please try below solution:

To work around the issue, create a DWORD value with the name iexplore.exe and the
value of 0 in the following key (for 32-bit Windows):

```<code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE
</code>```

For 64-bit Windows installations, the following key should be used:

```<code>HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE
</code>```

Title: Cannot open IE through selenium

Body:
I am trying to run my automation script in IE and have downloaded IE driver and giving that in path but some reason its not opening and getting error

org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session

I am setting path via batch file

java -jar selenium-server-standalone-2.53.1.jar -Dwebdriver.chrome.driver="chromedriver.exe" -Dwebdriver.ie.driver="IEDriverServer.exe"

Here is the code creating the IEDriverInstance

else if (AutomationConstants.BROWSER_TYPE.equalsIgnoreCase("IE"))
{
    Browser ie = new IEBrowser();
    System.out.println(ie);

    try
    {
        webDriver = new RemoteWebDriver(new URL(SeleniumProperties.getHost()), ie.getCapabilities());
    } catch (MalformedURLException mue)
    {
        LOGGER.error(mue);
    }
}

private static final String NAME = "IE";
private static DesiredCapabilities capabilities;
static
{
    capabilities = new DesiredCapabilities();
    capabilities = DesiredCapabilities.internetExplorer();
    capabilities.setPlatform(Platform.WINDOWS);
    capabilities.setVersion("11");
    capabilities.setJavascriptEnabled(true);
    capabilities.setCapability("acceptSslCerts", true);
}
/** * */
public IEBrowser()
{
    super(NAME, capabilities);
}

Body:
please try below solution:

To work around the issue, create a DWORD value with the name iexplore.exe and the
value of 0 in the following key (for 32-bit Windows):

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE

For 64-bit Windows installations, the following key should be used:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE


问:
R: polygon does not align with curves
I made the plot below in R. The edges of the polygon should align with the two curves as they are plotted using the same vectors. Yet, the polygon is slightly higher on the Y-axis relative to the curves. I cannot figure out why.

How do I get the outer edges of the polygon to align with the two curves?

Similarly, why does the polygon not extend all the way too the right end of the two curves? The curves are somewhat loner than the polygon.

I realize that I can plot the polygon with borders and not plot the two lines. That does not solve the underlying problem. Both the polygon and the two curves are plotted using the upper and lower vectors so I think they should align exactly. They do not.

```<code>lower <- qchisq(0.05,0:100)
upper <- qchisq(0.95,0:100)
df <- (0:100)

plot(df,upper, type='n', axes=F)
polygon(c(0,df,rev(df)), c(0,upper,rev(lower)), col='grey75',border=NA)
axis(1,pos=0)
axis(2,pos=0, las=1)
lines(upper, col='black')
lines(lower,col='black')
</code>```

答:
lines assumes the index is 1:length(x) (where x is the input) when you don't specify a second argument.

But in your case it's 0:100. Add df as the first argument to lines:

```<code>lines(df, upper, col='black')
lines(df, lower, col='black')
</code>```

Title: R: polygon does not align with curves

Body:
I made the plot below in R. The edges of the polygon should align with the two curves as they are plotted using the same vectors. Yet, the polygon is slightly higher on the Y-axis relative to the curves. I cannot figure out why.

How do I get the outer edges of the polygon to align with the two curves?

Similarly, why does the polygon not extend all the way too the right end of the two curves? The curves are somewhat loner than the polygon.

I realize that I can plot the polygon with borders and not plot the two lines. That does not solve the underlying problem. Both the polygon and the two curves are plotted using the upper and lower vectors so I think they should align exactly. They do not.

lower <- qchisq(0.05,0:100)
upper <- qchisq(0.95,0:100)
df <- (0:100)

plot(df,upper, type='n', axes=F)
polygon(c(0,df,rev(df)), c(0,upper,rev(lower)), col='grey75',border=NA)
axis(1,pos=0)
axis(2,pos=0, las=1)
lines(upper, col='black')
lines(lower,col='black')

Body:
lines assumes the index is 1:length(x) (where x is the input) when you don't specify a second argument.

But in your case it's 0:100. Add df as the first argument to lines:

lines(df, upper, col='black')
lines(df, lower, col='black')


问:
How to disable a click and re enable it later on with jQuery
I have a function that is triggered by a click. I want after I click it, disabling the click. So I made this

```<code>$('.item-blog').on('click', function(){

    $('.item-blog').off('click');

});
</code>```

and It's working perfectly.

But later on, at the end of all the events, within the last function, when I have resetted all the stuff and I have run all the code, I want to be able to re click the first function in order to fire the same events again. So I put this within the last function that resets everything.

```<code>$('.item-blog').on('click');
</code>```

But it is not working at all.

I even tried bind and unbind but every time I want to re enable the click, it is never working.

Some help?

Thank you very much

答:
Try removing the class instead... And add a temporary one.

;)

```<code>$(document).on('click','.item-blog', function(){
    $(this).removeClass("item-blog").addClass("item-blog-disabled");
});
</code>```

Then, later, you will only have to re-add the class using the item-blog-disabled class.

like:

```<code>$(document).find('.item-blog-disabled').removeClass("item-blog-disabled").addClass("item-blog");
</code>```

So now, the handler is binded to the document which delegates for .item-blog it has.

Giving you the opportunity to remove/add the handler on those elements using a simple class.

Body:
I have a function that is triggered by a click. I want after I click it, disabling the click. So I made this

$('.item-blog').on('click', function(){

    $('.item-blog').off('click');

});

and It's working perfectly.

But later on, at the end of all the events, within the last function, when I have resetted all the stuff and I have run all the code, I want to be able to re click the first function in order to fire the same events again. So I put this within the last function that resets everything.

$('.item-blog').on('click');

But it is not working at all.

I even tried bind and unbind but every time I want to re enable the click, it is never working.

Some help?

Thank you very much

Body:
Try removing the class instead... And add a temporary one.

;)

$(document).on('click','.item-blog', function(){
    $(this).removeClass("item-blog").addClass("item-blog-disabled");
});

Then, later, you will only have to re-add the class using the item-blog-disabled class.

like:

$(document).find('.item-blog-disabled').removeClass("item-blog-disabled").addClass("item-blog");

So now, the handler is binded to the document which delegates for .item-blog it has.

Giving you the opportunity to remove/add the handler on those elements using a simple class.


问:
How to show thumbnail image from Google Drive API
I got the thumbnailLink DoFu of my uploaded public file in Drive by following the Google Drive API Samples with Javascript. The image can be shown when opening the link on browsers. However, it cannot be shown on HTML image element.

I also tried to access this image via API key with "GET https://www.googleapis.com/drive/v3/files/{FILE_ID}?fields=contentHints%2Fthumbnail%2Fimage%2CthumbnailLink&key={YOUR_API_KEY}", and it can return me an object within a thumbnailLink. However, it cannot be shown on image element either.

How can I get the real image source link in order to show it on my web page?

答: I finally use this way to solve it. To get thumbnail link with scopes drive and drive.readonly , and set it to https://drive.google.com/thumbnail?authuser=0&sz=w320&id=[fileid]. It get let user get thumbnail image to private data when logging in.


问:
ec2 run scripts every boot
I have followed a few posts on here trying to run either a python or shell script on my ec2 instance after every boot not just the first boot.

I have tried the:

[scripts-user, always] to /etc/cloud/cloud.cfg file

Added script to ./scripts/per-boot folder

and

adding script to /etc/rc.local

Yes the permissions were changed to 755 for /etc/rc.local

I am attempting to pipe the output of the file into a file located in the /home/ubuntu/ directory and the file does not contain anything after boot.

If I run the scripts (.sh or .py) manually they work.

Any suggestions or request for additional info to help?

答:
So the current solution appears to be a method I wrote off in my initial question post as I may have not performed the setup exactly as outline in the link below...

This link -->
How do I make cloud-init startup scripts run every time my EC2 instance boots?

The link shows how to modify the /etc/cloud/cloud.cfg file to update scripts-user to [scripts-user, always]

Also that link says to add your *.sh file to /var/lib/cloud/scripts/per-boot directory.

Once you reboot your system your script should have executed and you can verify this in: sudo cat /var/log/cloud-init.log

if your script still fails to execute try to erase the instance state of your server with the following command: sudo rm -rf /var/lib/cloud/instance/*

--NOTE:--
It appears print commands from a python script do not pipe (>>) as expected but echo commands pipe easily

Fails to pipe
sudo python test.py >> log.txt

Pipes successfully
echo "HI" >> log.txt

Title: ec2 run scripts every boot


问:
Realm - Can't use object after having been deleted
I have a video player in my app. There is a list of videos in a collection view. If you tap on one of the cells, a new view controller appears to play the selected video. Also, you can cycle through all of the videos from the collection view in this new view controller because the entire list is passed.

The problem is:
When the user is in the PlayerVC, they can unfavorite a Video. If they do this, I delete the Video object from Realm. However, this causes a:

Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'

Basically, if a user is watching a video in PlayerVC and he unfavorites a video, I want them to still be able to watch the video for the time being. But when they leave the PlayerVC, the collection view in FavoritesVC should be updated and not show that Video any more.

When I delete a Video object I use Realm's delete method.

This is my code to hold a list of Video objects:

```<code>/// Model class that manages the ordering of `Video` objects.
final class FavoriteList: Object {
    // MARK: - Properties

    /// `objectId` is set to a static value so that only
    /// one `FavoriteList` object could be saved into Realm.
    dynamic var objectId = 0

    let videos = List<Video>()

    // MARK: - Realm Meta Information

    override class func primaryKey() -> String? {
        return "objectId"
    }
}
</code>```

This is my Video class which has an isFavorite property:

```<code>final class Video: Object {
    // MARK: - Properties

    dynamic var title = ""
    dynamic var descriptionText = ""
    dynamic var date = ""
    dynamic var videoId = ""
    dynamic var category = ""
    dynamic var duration = 0
    dynamic var fullURL = ""
    dynamic var creatorSite = ""
    dynamic var creatorName = ""
    dynamic var creatorURL = ""

    // MARK: FileManager Properties (Files are stored on disk for `Video` object).

    /*
        These are file names (e.g., myFile.mp4, myFile.jpg)
    */
    dynamic var previewLocalFileName: String?
    dynamic var stitchedImageLocalFileName: String?
    dynamic var placeholderLocalFileName: String?

    /*
        These are partial paths (e.g., bundleID/Feed/myFile.mp4,     bundleID/Favorites/myFile.mp4)
        They are used to build the full path/URL at runtime.
    */
    dynamic var previewLocalFilePath: String?
    dynamic var stitchedImageLocalFilePath: String?
    dynamic var placeholderLocalFilePath: String?

    // Other code...
}
</code>```

This is my code to show the Video objects in a collection view (Note: I use RealmCollectionChange to update the collection view for deleting  and inserting cells):

```<code>/// This view controller has a `collectioView` to show the favorites.
class FavoriteCollectionViewController: UIViewController {
    // MARK: Properties

    let favoriteList: FavoriteList = {
        let realm = try! Realm()
        return realm.objects(FavoriteList.self).first!
    }()

    // Realm notification token to update collection view.
    var notificationToken: NotificationToken?

    // MARK: Collection View

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return favoriteList.videos.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FavoritesCollectionViewCell.reuseIdentifier, for: indexPath) as! FavoritesCollectionViewCell
        cell.video = favoriteList.videos[indexPath.item]

        return cell
    }

    // I pass this lst forward to the PlayerVC
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let playerVC = self.storyboard?.instantiateViewController(withIdentifier: "PlayerViewController") as? PlayerViewController {
            // I pass the videos here.
            playerVC.videos = favoriteList.videos
            self.parent?.present(playerVC, animated: true, completion: nil)
        }
    }

    // MARK: Realm Notifications

    func updateUI(with changes: RealmCollectionChange<List<Video>>) {
        // This is code to update the collection view.
    }
}
</code>```

Finally, this is the code to allow the user to play and cycle between all Video objects:

```<code>/// This view controller uses `AVFoundation` to play the videos from `FavoriteCollectionViewController`.
class PlayerViewControllerr: UIViewController {

    /// This `videos` is passed from `FavoriteCollectionViewController`
    var videos = List<Video>()

    // HELP: The app crashes here if I unfavorite a `Video`.
    @IBAction func didToggleStarButton(_ sender: UIButton) {
        let realm = try! Realm()
        try! realm.write {
            let videoToDelete = videos[currentIndexInVideosList] /// Get the video that is currently playing
            realm.delete(videoToDelete)
        }
    }
}
</code>```

Ultimately I want the Video object that is unfavorited to be completely deleted from Realm. Just not sure how/when to do it in this case.

Any thoughts?

Update 1

An option to solve this is to:

Make an unmanaged copy of the Video copy, and use that one to power the UI of the view controller.

The way I see this possibly working is this:

The PlayerVC will receive two List, the original one saved in Realm and a copy of this List to power the UI. Let's call the lists favoriteList and copyList.

So inside of the didToggleStarButton we would do something like this:

Code:

```<code>/// This view controller uses `AVFoundation` to play the videos from `FavoriteCollectionViewController`.
class PlayerViewControllerr: UIViewController {

    /// A button to allow the user to favorite and unfavorite a `Video`
    @IBOutlet weak var starButton: UIButton!

    /// This is passed from `FavoriteCollectionViewController`
    var favoriteList: FavoriteList!

    /// A copy of the `FavoriteList` videos to power the UI.
    var copiedList: List<Video>!

    var currentIndexOfVideoInCopiedList: Int!

    override func viewDidLoad() {
        super viewDidLoad()

        // Make a copy of the favoriteList to power the UI.
        var copiedVideos = [Video]()

        for video in favoriteList.videos {
            let unmanagedVideo = Video(value: video)
            copiedVideos.append(unmanagedVideo)
        }

        self.copiedList.append(copiedVideos)
    }

    // HELP: The app crashes here if I unfavorite a `Video`.
    @IBAction func didToggleStarButton(_ sender: UIButton) {
        // Do the unfavoriting and favoriting here.

        // An example of unfavoriting:
        let realm = try! Realm()
        try! realm.write {
            let videoToDeleteFromFavoriteList = favoriteList.videos[currentIndexOfVideoInCopiedList] /// Get the video that is currently playing
            realm.delete(videoToDeleteFromOriginalList)
        }

        // Update star button to a new image depending on if the `Video` is favorited or not.
        starButton.isSelected = //... update based on if the `Video` in the `FavoriteList` or not.
    }
}
</code>```

Any thoughts?

答:
Here is the workaround solution. Check if it works.   </p>

```<code> class PlayerViewControllerr: UIViewController {

          var arrayForIndex = [Int]()
          var videos = List<Video>()

          @IBAction func didToggleStarButton(_ sender: UIButton) {
               self.arrayForIndex.append(currentIndexInVideosList)
           }

         @overide func viewWillDisappear(_ animated : Bool){
              super.viewWillDisappear(animated)
              for i in arrayForIndex{
                 let realm = try! Realm()
        try! realm.write {
            let videoToDelete = videos[i] /// Get the video that is currently playing
            realm.delete(videoToDelete)
        }
       }
        }
</code>```

Body:
I have a video player in my app. There is a list of videos in a collection view. If you tap on one of the cells, a new view controller appears to play the selected video. Also, you can cycle through all of the videos from the collection view in this new view controller because the entire list is passed.

The problem is:
When the user is in the PlayerVC, they can unfavorite a Video. If they do this, I delete the Video object from Realm. However, this causes a:

Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'

Basically, if a user is watching a video in PlayerVC and he unfavorites a video, I want them to still be able to watch the video for the time being. But when they leave the PlayerVC, the collection view in FavoritesVC should be updated and not show that Video any more.

When I delete a Video object I use Realm's delete method.

This is my code to hold a list of Video objects:

/// Model class that manages the ordering of `Video` objects.
final class FavoriteList: Object {
    // MARK: - Properties

    /// `objectId` is set to a static value so that only
    /// one `FavoriteList` object could be saved into Realm.
    dynamic var objectId = 0

    let videos = List<Video>()

    // MARK: - Realm Meta Information

    override class func primaryKey() -> String? {
        return "objectId"
    }
}

This is my Video class which has an isFavorite property:

final class Video: Object {
    // MARK: - Properties

    dynamic var title = ""
    dynamic var descriptionText = ""
    dynamic var date = ""
    dynamic var videoId = ""
    dynamic var category = ""
    dynamic var duration = 0
    dynamic var fullURL = ""
    dynamic var creatorSite = ""
    dynamic var creatorName = ""
    dynamic var creatorURL = ""

    // MARK: FileManager Properties (Files are stored on disk for `Video` object).

    /*
        These are file names (e.g., myFile.mp4, myFile.jpg)
    */
    dynamic var previewLocalFileName: String?
    dynamic var stitchedImageLocalFileName: String?
    dynamic var placeholderLocalFileName: String?

    /*
        These are partial paths (e.g., bundleID/Feed/myFile.mp4,     bundleID/Favorites/myFile.mp4)
        They are used to build the full path/URL at runtime.
    */
    dynamic var previewLocalFilePath: String?
    dynamic var stitchedImageLocalFilePath: String?
    dynamic var placeholderLocalFilePath: String?

    // Other code...
}

This is my code to show the Video objects in a collection view (Note: I use RealmCollectionChange to update the collection view for deleting  and inserting cells):

/// This view controller has a `collectioView` to show the favorites.
class FavoriteCollectionViewController: UIViewController {
    // MARK: Properties

    let favoriteList: FavoriteList = {
        let realm = try! Realm()
        return realm.objects(FavoriteList.self).first!
    }()

    // Realm notification token to update collection view.
    var notificationToken: NotificationToken?

    // MARK: Collection View

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return favoriteList.videos.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FavoritesCollectionViewCell.reuseIdentifier, for: indexPath) as! FavoritesCollectionViewCell
        cell.video = favoriteList.videos[indexPath.item]

        return cell
    }

    // I pass this lst forward to the PlayerVC
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let playerVC = self.storyboard?.instantiateViewController(withIdentifier: "PlayerViewController") as? PlayerViewController {
            // I pass the videos here.
            playerVC.videos = favoriteList.videos
            self.parent?.present(playerVC, animated: true, completion: nil)
        }
    }

    // MARK: Realm Notifications

    func updateUI(with changes: RealmCollectionChange<List<Video>>) {
        // This is code to update the collection view.
    }
}

Finally, this is the code to allow the user to play and cycle between all Video objects:

/// This view controller uses `AVFoundation` to play the videos from `FavoriteCollectionViewController`.
class PlayerViewControllerr: UIViewController {

    /// This `videos` is passed from `FavoriteCollectionViewController`
    var videos = List<Video>()

    // HELP: The app crashes here if I unfavorite a `Video`.
    @IBAction func didToggleStarButton(_ sender: UIButton) {
        let realm = try! Realm()
        try! realm.write {
            let videoToDelete = videos[currentIndexInVideosList] /// Get the video that is currently playing
            realm.delete(videoToDelete)
        }
    }
}

Ultimately I want the Video object that is unfavorited to be completely deleted from Realm. Just not sure how/when to do it in this case.

Any thoughts?

Update 1

An option to solve this is to:

Make an unmanaged copy of the Video copy, and use that one to power the UI of the view controller.

The way I see this possibly working is this:

The PlayerVC will receive two List, the original one saved in Realm and a copy of this List to power the UI. Let's call the lists favoriteList and copyList.

So inside of the didToggleStarButton we would do something like this:

Code:

/// This view controller uses `AVFoundation` to play the videos from `FavoriteCollectionViewController`.
class PlayerViewControllerr: UIViewController {

    /// A button to allow the user to favorite and unfavorite a `Video`
    @IBOutlet weak var starButton: UIButton!

    /// This is passed from `FavoriteCollectionViewController`
    var favoriteList: FavoriteList!

    /// A copy of the `FavoriteList` videos to power the UI.
    var copiedList: List<Video>!

    var currentIndexOfVideoInCopiedList: Int!

    override func viewDidLoad() {
        super viewDidLoad()

        // Make a copy of the favoriteList to power the UI.
        var copiedVideos = [Video]()

        for video in favoriteList.videos {
            let unmanagedVideo = Video(value: video)
            copiedVideos.append(unmanagedVideo)
        }

        self.copiedList.append(copiedVideos)
    }

    // HELP: The app crashes here if I unfavorite a `Video`.
    @IBAction func didToggleStarButton(_ sender: UIButton) {
        // Do the unfavoriting and favoriting here.

        // An example of unfavoriting:
        let realm = try! Realm()
        try! realm.write {
            let videoToDeleteFromFavoriteList = favoriteList.videos[currentIndexOfVideoInCopiedList] /// Get the video that is currently playing
            realm.delete(videoToDeleteFromOriginalList)
        }

        // Update star button to a new image depending on if the `Video` is favorited or not.
        starButton.isSelected = //... update based on if the `Video` in the `FavoriteList` or not.
    }
}

Any thoughts?

Body:
Here is the workaround solution. Check if it works.

 class PlayerViewControllerr: UIViewController {

          var arrayForIndex = [Int]()
          var videos = List<Video>()

          @IBAction func didToggleStarButton(_ sender: UIButton) {
               self.arrayForIndex.append(currentIndexInVideosList)
           }

         @overide func viewWillDisappear(_ animated : Bool){
              super.viewWillDisappear(animated)
              for i in arrayForIndex{
                 let realm = try! Realm()
        try! realm.write {
            let videoToDelete = videos[i] /// Get the video that is currently playing
            realm.delete(videoToDelete)
        }
       }
        }


问:
In Javascript, what is a sure way to loop through an array of 3 strings?
Something like this works, but looks a bit clumsy:

```<code>for (i in {foo: 1, bar: 1, wah: 1}) {  // loops through foo, bar, wah
  console.log(i + " haha");            // can view using Firebug or Chrome
}
</code>```

if using an array, I don't want to create any global temporary variable for the array...  Also, this has to work in any modern browser IE7 / FF / Chrome / Safari.  thanks.

答:
Okay I'm posting this cause I like strange code, so go easy on me...

If you absolutely do not want to create a temporary variable, global or local, and cannot use or add the forEach function (as in patrick dw's answer), you can drag out the dreaded with statement to do the job. It's not exactly pretty...

```<code>with(['foo', 'bar', 'wah'])
  while(valueOf().length)
    console.log(valueOf().shift())
</code>```

Look ma, no variables!

If you are okay with using lexically scoped variables, then you can do things a bit cleaner...

```<code>with({a: ['foo', 'bar', 'wah']})
  while(a.length)
    console.log(a.shift())
</code>```

You could do the same thing with a self-executing anonymous function, but with horrid syntax and (likely) lesser performance.

Regardless, I strongly recommend you use forEach if you can, or just...you know, local variables.

Body:
Something like this works, but looks a bit clumsy:

for (i in {foo: 1, bar: 1, wah: 1}) {  // loops through foo, bar, wah
  console.log(i + " haha");            // can view using Firebug or Chrome
}

if using an array, I don't want to create any global temporary variable for the array...  Also, this has to work in any modern browser IE7 / FF / Chrome / Safari.  thanks.

Body:
Okay I'm posting this cause I like strange code, so go easy on me...

If you absolutely do not want to create a temporary variable, global or local, and cannot use or add the forEach function (as in patrick dw's answer), you can drag out the dreaded with statement to do the job. It's not exactly pretty...

with(['foo', 'bar', 'wah'])
  while(valueOf().length)
    console.log(valueOf().shift())

Look ma, no variables!

If you are okay with using lexically scoped variables, then you can do things a bit cleaner...

with({a: ['foo', 'bar', 'wah']})
  while(a.length)
    console.log(a.shift())

You could do the same thing with a self-executing anonymous function, but with horrid syntax and (likely) lesser performance.

Regardless, I strongly recommend you use forEach if you can, or just...you know, local variables.


问:
Boost:asio time taken for socket read/write
I have the following code to measure the total time taken for a socket write from client to server. (assuming that the call back method invocation is done on successful write of the data to the destination socket (TCP-ACK received)) Does this ensure that - this time is the actual "network time" for the data transfer ? </p>

```<code>  void on_successful_read_from_client(const boost::system::error_code& error,
                              const size_t& bytes_transferred)
  {
     if (!error)
     {

      m_telnet_server_write_time = posix_time::microsec_clock::universal_time();
      async_write(telnet_server,
              boost::asio::buffer(data_from_device_,bytes_transferred),
              boost::bind(&bridge::on_successful_send_to_server,
                    shared_from_this(),
                    boost::asio::placeholders::error));

     }
     else
        close();
  }

  void on_successful_send_to_server(const boost::system::error_code& error)
  {
     if (!error)
     {
        posix_time::ptime now = posix_time::microsec_clock::universal_time();

        if ((now - m_telnet_server_write_time).total_milliseconds() > 0)
        {
            std::ostringstream log;
            log << "Time Taken for server write: " << (now - m_telnet_server_write_time).total_milliseconds() << " ms";

            write_log(log.str());
        }
</code>```

答:
it measures the time to put the data into send buffers in your network stack.
if you want to calculate the "network time", use icmp::socket, just like "ping" command does.

here is the example in boost documents
boost examples

search "ICMP" in this page

Body:
I have the following code to measure the total time taken for a socket write from client to server. (assuming that the call back method invocation is done on successful write of the data to the destination socket (TCP-ACK received)) Does this ensure that - this time is the actual "network time" for the data transfer ?

  void on_successful_read_from_client(const boost::system::error_code& error,
                              const size_t& bytes_transferred)
  {
     if (!error)
     {

      m_telnet_server_write_time = posix_time::microsec_clock::universal_time();
      async_write(telnet_server,
              boost::asio::buffer(data_from_device_,bytes_transferred),
              boost::bind(&bridge::on_successful_send_to_server,
                    shared_from_this(),
                    boost::asio::placeholders::error));

     }
     else
        close();
  }

  void on_successful_send_to_server(const boost::system::error_code& error)
  {
     if (!error)
     {
        posix_time::ptime now = posix_time::microsec_clock::universal_time();

        if ((now - m_telnet_server_write_time).total_milliseconds() > 0)
        {
            std::ostringstream log;
            log << "Time Taken for server write: " << (now - m_telnet_server_write_time).total_milliseconds() << " ms";

            write_log(log.str());
        }


问:
Task.WaitAll hangs in webapi call
Calling below webapi " Test " from client side (AngularJS). It executes Line1, Line2 and Line3 but it hangs at Line3 and never moved to Line4 and the same Line1, Line2 and Line3 executes fine if executed in unit test of unit test project. Can anyone help whats going wrong here?

```<code>    [Route("Test")]
    [HttpGet]
    public IHttpActionResult Test(string input)
    {

        var taskA = Dump(a, b); //Line1
        var taskB = Dump(c, d); //Line2
        Task.WaitAll(taskA, taskB); //Line3

        Line4;
        Line5;
        Line6;

        Ok(success);

    }
</code>```

Dump Method:

```<code>     public async Task Dump(string x, string y)
    {
        await Task.Run(() => methodToDump(x, y));
    }
</code>```

答:
You also need to change you Dump function to

```<code>public async Task Dump(string x, string y)
{
    await Task.Run(() => methodToDump(x, y)).ConfigureAwait(false);
}
</code>```

There is no code after await, so there is no need to force continuation on the captured SynchronizationContext

Title: Task.WaitAll hangs in webapi call

Body:
Calling below webapi " Test " from client side (AngularJS). It executes Line1, Line2 and Line3 but it hangs at Line3 and never moved to Line4 and the same Line1, Line2 and Line3 executes fine if executed in unit test of unit test project. Can anyone help whats going wrong here?

    [Route("Test")]
    [HttpGet]
    public IHttpActionResult Test(string input)
    {

        var taskA = Dump(a, b); //Line1
        var taskB = Dump(c, d); //Line2
        Task.WaitAll(taskA, taskB); //Line3

        Line4;
        Line5;
        Line6;

        Ok(success);

    }

Dump Method:

     public async Task Dump(string x, string y)
    {
        await Task.Run(() => methodToDump(x, y));
    }

Body:
You also need to change you Dump function to

public async Task Dump(string x, string y)
{
    await Task.Run(() => methodToDump(x, y)).ConfigureAwait(false);
}

There is no code after await, so there is no need to force continuation on the captured SynchronizationContext


问:
Variable appearing above html in php when using return
I am trying to put the variable $about inside of the html I am returning...however when I view the output, it puts $about above the html code...

```<code>function cc_shortcode( $atts ) {

 $other_page = 498;
 $about = the_field('cc_about_this_course', $other_page);

    extract( shortcode_atts( array(
        'id' => '',
    ), $atts) );
    $result = '<div class="main">
<div class="accordion">
<div class="accordion-section">

<a class="accordion-section-title active" href="#accordion-1">ABOUT THIS COURSE<i class="fa fa-arrow-down"></i></a>
<div id="accordion-1" class="accordion-section-content open" style="display: block;">
<p>' . $about . '</p>
</div>
</div>
';

    return $result;

}
</code>```

答:
https://www.advancedcustomfields.com/resources/the_field/

the_field used for displaying value from the current post that's why it display value..

solution to use get_field ; https://www.advancedcustomfields.com/resources/get_field/

if the there is not get_field.. (for common problems)... like this..

you can ob_start(); and ob_get_clean for you problem

```<code>function cc_shortcode( $atts ) {

     $other_page = 498;

ob_start();
the_field('cc_about_this_course', $other_page);
$about = ob_get_clean();

        extract( shortcode_atts( array(
            'id' => '',
        ), $atts) );
        $result = '<div class="main">
    <div class="accordion">
    <div class="accordion-section">

    <a class="accordion-section-title active" href="#accordion-1">ABOUT THIS COURSE<i class="fa fa-arrow-down"></i></a>
    <div id="accordion-1" class="accordion-section-content open" style="display: block;">
    <p>' . $about . '</p>
    </div>
    </div>
    ';

        return $result;

    }
</code>```

Body:
I am trying to put the variable $about inside of the html I am returning...however when I view the output, it puts $about above the html code...

function cc_shortcode( $atts ) {

 $other_page = 498;
 $about = the_field('cc_about_this_course', $other_page);

    extract( shortcode_atts( array(
        'id' => '',
    ), $atts) );
    $result = '

ABOUT THIS COURSE

' . $about . '

';

    return $result;

}

Body:
https://www.advancedcustomfields.com/resources/the_field/

the_field used for displaying value from the current post that's why it display value..

solution to use get_field ; https://www.advancedcustomfields.com/resources/get_field/

if the there is not get_field.. (for common problems)... like this..

you can ob_start(); and ob_get_clean for you problem

function cc_shortcode( $atts ) {

     $other_page = 498;

ob_start();
the_field('cc_about_this_course', $other_page);
$about = ob_get_clean();

        extract( shortcode_atts( array(
            'id' => '',
        ), $atts) );
        $result = '<div class="main">
    <div class="accordion">
    <div class="accordion-section">

    <a class="accordion-section-title active" href="#accordion-1">ABOUT THIS COURSE<i class="fa fa-arrow-down"></i></a>
    <div id="accordion-1" class="accordion-section-content open" style="display: block;">
    <p>' . $about . '</p>
    </div>
    </div>
    ';

        return $result;

    }


问:
How to read the rest of a sequence from new line and without the space? c++
So now looking at line 2, Cow- DNA Sequence; this continues on line 13 and 24 and ... I want to get this long sequence for each sequences ignoring the white space and new line in between.

This is the format of the file: 1

This is the code, which reads the first 10 sequences only

```<code>ifstream file ("txt");
string line;
vector <string> vec;
stringstream s;
string name;

string strip(string & s)
{
    size_t b = s.find_first_not_of(' ');
    size_t e = s.find_last_not_of(' ');
    if (b == string::npos) {
        return "";
    } else {
        return s.substr(b, e - b + 1);
    }
}

void getSequence(){
    int i;
    int row;
    int col;
    if (file.is_open())
    {
        file >> row >> col;
        for (i = 0; i < row; i++) {
            vec.push_back("");
        }
        i = 0;
        while (getline(file, line))
        {
            file >> name;
            if (line == " ")
            {
                continue;
            }

            vec[i % row] += strip(line);
            i++;
        }
    }
    else {
        cerr << "Error: file did not open!" << endl;
    }
    for (const string & v : vec) {
        cout << v << endl;
    }
}
</code>```

Thank you in advance for your help.

答:
Perhaps this will help a bit.  The idea is to read the row & col then read the header line for the number of rows.  After that repeatedly read the next chunk of lines and append each to the correct item assuming the lines are interleaved.</p>

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

struct Sequence
{
    std::string name;
    std::string data;
};
using SeqVec = std::vector<Sequence>;

bool readHeader(std::ifstream& f, SeqVec& v)
{
    for (size_t i = 0; i < v.size(); ++i)
    {
        if (!(f >> v[i].name >> v[i].data))
        {
            return false;
        }
    }
    return true;
}

int readChunk(std::ifstream& f, SeqVec& v)
{
    int linesRead = 0;
    std::string chunk;
    for (size_t i = 0; i < v.size(); ++i)
    {
        if(!(f >> chunk))
        {
            break;
        }
        v[i].data += chunk;
        ++linesRead;
    }
    return linesRead;
}

int main()
{
    std::vector<Sequence> v;

    const std::string filename = "test.txt";
    std::ifstream f(filename);
    if (!f)
    {
        return -1;
    }

    int row;
    int col;
    if (f >> row >> col)
    {
        v.resize(row);
        if (!readHeader(f, v))
        {
            return -1;
        }
        for (;;)
        {
            int linesRead = readChunk(f, v);
            if (linesRead == 0 && v[0].data.size() == col)
            {
                //If we read nothing and the lines are the correct length we're done.
                break;
            }
            else if (linesRead < v.size())
            {
                //partial read is an error.
                return -1;
            }
        }
    }

    for (auto& seq : v)
    {
        std::cout << seq.name << " : " << seq.data << "\n";
    }
    return 0;
}
</code>```

Body:
So now looking at line 2, Cow- DNA Sequence; this continues on line 13 and 24 and ... I want to get this long sequence for each sequences ignoring the white space and new line in between.

This is the format of the file: 1

This is the code, which reads the first 10 sequences only

ifstream file ("txt");
string line;
vector <string> vec;
stringstream s;
string name;

string strip(string & s)
{
    size_t b = s.find_first_not_of(' ');
    size_t e = s.find_last_not_of(' ');
    if (b == string::npos) {
        return "";
    } else {
        return s.substr(b, e - b + 1);
    }
}

void getSequence(){
    int i;
    int row;
    int col;
    if (file.is_open())
    {
        file >> row >> col;
        for (i = 0; i < row; i++) {
            vec.push_back("");
        }
        i = 0;
        while (getline(file, line))
        {
            file >> name;
            if (line == " ")
            {
                continue;
            }

            vec[i % row] += strip(line);
            i++;
        }
    }
    else {
        cerr << "Error: file did not open!" << endl;
    }
    for (const string & v : vec) {
        cout << v << endl;
    }
}

Thank you in advance for your help.

Body:
Perhaps this will help a bit.  The idea is to read the row & col then read the header line for the number of rows.  After that repeatedly read the next chunk of lines and append each to the correct item assuming the lines are interleaved.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

struct Sequence
{
    std::string name;
    std::string data;
};
using SeqVec = std::vector<Sequence>;

bool readHeader(std::ifstream& f, SeqVec& v)
{
    for (size_t i = 0; i < v.size(); ++i)
    {
        if (!(f >> v[i].name >> v[i].data))
        {
            return false;
        }
    }
    return true;
}

int readChunk(std::ifstream& f, SeqVec& v)
{
    int linesRead = 0;
    std::string chunk;
    for (size_t i = 0; i < v.size(); ++i)
    {
        if(!(f >> chunk))
        {
            break;
        }
        v[i].data += chunk;
        ++linesRead;
    }
    return linesRead;
}

int main()
{
    std::vector<Sequence> v;

    const std::string filename = "test.txt";
    std::ifstream f(filename);
    if (!f)
    {
        return -1;
    }

    int row;
    int col;
    if (f >> row >> col)
    {
        v.resize(row);
        if (!readHeader(f, v))
        {
            return -1;
        }
        for (;;)
        {
            int linesRead = readChunk(f, v);
            if (linesRead == 0 && v[0].data.size() == col)
            {
                //If we read nothing and the lines are the correct length we're done.
                break;
            }
            else if (linesRead < v.size())
            {
                //partial read is an error.
                return -1;
            }
        }
    }

    for (auto& seq : v)
    {
        std::cout << seq.name << " : " << seq.data << "\n";
    }
    return 0;
}


问:
best CMS for a custom and new employees?
we're moving to use an OPENSOURCE CMS system, for years we been using our own CMS, and it's time to move to OPENSOURCE. so which of Drupal, Joomla, WordPress is the best choice if

the team needs to learn it ...

supporting multi languages and RTL directions

easy to use ( for end users )

customization and templating

or if there are any other CMS that would make the process faster.

thanks all

答:
If you want to develop a robust application in a relatively quick fashion you should give Drupal a try. It's fantastic for intranet like systems. A lot of the more popular modules are very abstract and allow you to craft custom content to display in very custom ways easily.

I prefer it over WP and specially over Joomla!.


问:
HTML5: W3C vs WHATWG. Which gives the most authoritative spec?
I'm in halfway trough an html parser and found html5 defined explicitly the rules of thumb for parsing ill formed html. (And I used to infer them from DTDs, sigh)

I love that fact, but I know well that html5 isn't finalized yet (also I wonder if it ever will) and that it isn't developed by the W3C, but by the WHATWG.

Searching for the spec I need I'm presented with:

8.2 section of the W3C TR

http://www.w3.org/TR/html5/syntax.html#parsing

or

11.2 section of the WHATWG web-apps/current-work

http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html

If it wasn't for the section numbers I would induce those are simply the same. But the different numbering makes me wonder. Which version is, supposedly, the most authoritative?

WHATWG seems to have more sections, and to have been added to since W3C uploaded its candidate recommendation.

Will W3C update to the WHATWG version?

Or will they stick to their current candidate until it gets to the official recommendation status?

Which html5 spec are we poor devils supposed to follow, when in doubt?

答:
Biased answer from an editor of WHATWG HTML here. Hopefully the facts can speak for themselves though.

The WHATWG Living Standard should be considered authoritative. It is constantly worked on by a large community of contributors, including all browser vendors. No browser vendors implement according to W3C HTML; for some such as Firefox and Chrome this is a matter of publicly stated policy.

The WHATWG Living Standard is constantly receiving bug fixes and new features. For more information on this model of spec development, which more closely matches modern software development practices, see What does "Living Standard" mean?.

Unfortunately, the W3C sometimes copies and pastes our work onto their own website, and puts their own logo on it, and changes the names of the editors, and such. They do this for a variety of reasons, one of the largest of which is face-saving for the sake of their paying member companies (example of them stating this). What's worse, they like to release "versions" (like HTML "5.0", "5.1", etc.) which are just outdated versions missing modern bug fixes and features that clog up search result pages, causing confusion like this very question. We are currently tracking the confusion caused by these forks, of which HTML is only one.

You can track their progress on the copy-and-paste job in their issue tracker or in commits such as this one. It's a fun game to spot the bugs they introduce while doing this copy-and-paste job, as they generally do not read or understand the content they are copying, leading to widespread errors and inconsistencies.


问:
Dynamic variable to set OFFSET (mySQL, php)
Appreciate any help, what am I doing wrong? Undeclared variable: $offset </p>

```<code>$offset = 1;

$sql = 'SELECT * FROM links order by payout desc limit $offset, 1';
</code>```

答: One thing to mention, it seems you wrote variable inline in single quotes, variables can only be recognized in double quotes</p>

Body:
Appreciate any help, what am I doing wrong? Undeclared variable: $offset

$offset = 1;

$sql = 'SELECT * FROM links order by payout desc limit $offset, 1';


问:
How can I align these elements side by side?
I'm having difficulties in aligning these elements side by side, anyway this—

—is how it looks so far, but I want it look like this:

.reviewprofile {
  background-color: transparent;
  border: none;
  margin-top: 5em;
}

.reviewentry {
  display: inline-block;
  font-family: 'Abhaya Libre', Times, Serif;
  font-size: 0.8em;
  font-weight: 400;
  color: #5e5e5e;
  text-align: left;
  padding-left: 3.5em;
  margin: 0;
}

.commbutton button {
  float: left;
}

.starsrev {
  padding-left: 2.8em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="commsec">
  <div class="commbutton">
    <button class="reviewprofile"><img src="img/reviewprofile.png">  </button>
  </div>

  <div class="commentry">
    <p class="reviewentry">Cras ultricies dolor ac justo scelerisque, sit amet imperdiet<br> purus placerat.</p>
    <img class="starsrev" src="img/stars.png" alt="stars" />
  </div>
</div></code>```

答:
Please add under CSS & check

```<code>img {
    float: left;
}
</code>```

I didn't run the code.

ContentLicense: CC BY-SA 4.0

Body:
I'm having difficulties in aligning these elements side by side, anyway this—

—is how it looks so far, but I want it look like this:

.reviewprofile {
  background-color: transparent;
  border: none;
  margin-top: 5em;
}

.reviewentry {
  display: inline-block;
  font-family: 'Abhaya Libre', Times, Serif;
  font-size: 0.8em;
  font-weight: 400;
  color: #5e5e5e;
  text-align: left;
  padding-left: 3.5em;
  margin: 0;
}

.commbutton button {
  float: left;
}

.starsrev {
  padding-left: 2.8em;
}

    <button class="reviewprofile">  </button>

Cras ultricies dolor ac justo scelerisque, sit amet imperdiet
 purus placerat.

Body:
Please add under CSS & check

img {
    float: left;
}

I didn't run the code.


问:
R Error in x - y : non-conformable arrays
I'm trying to train a neural network in R with the following dataset (small part)

```<code>      Age   Salary Mortrate Clientrate Savrate PartialPrate
 [1,]  62 2381.140    0.047       7.05     3.1            0
 [2,]  52 1777.970    0.047       6.10     3.1            0
 [3,]  53 2701.210    0.047       6.40     3.1            0
 [4,]  52 4039.460    0.047       7.00     3.1            0
 [5,]  56  602.240    0.047       6.20     3.1            0
 [6,]  43 2951.090    0.047       6.80     3.1            0
 [7,]  49 4648.860    0.047       7.50     3.1            0
 [8,]  44 3304.110    0.047       7.10     3.1            0
 [9,]  56 1300.000    0.047       6.10     3.1            0
[10,]  50 1761.440    0.047       6.95     3.1            0
</code>```

If I try doing it for small set of data as above the code works, but if I take more data then the neuralnet() gives the error:

```<code>Neuralnet error Error in x - y : non-conformable arrays.
</code>```

What does this error mean and how do I fix it?

Code:

```<code>trainingsoutput <- AllData$PartialPrepay
trainingdata <- cbind(AllData$LEEFTIJD, AllData$MEDSAL2, AllData$rate5Y,
                      AllData$CRate, AllData$SavRate, trainingsoutput)
dimnames(trainingdata) <- list(NULL,
                               c("Age","Salary","Mortrate","Clientrate",
                                 "Savrate","PartialPrate"))

nn <- neuralnet(PartialPrate ~ Age + Salary + Mortrate + Clientrate + Savrate,
                data = trainingdata ,hidden=3, err.fct="sse", threshold=0.01)
</code>```

答:
Error message description:

The phrase Conformable arrays is linear algebra jargon for "arrays that can sensibly be operated on together".  The bare asterisk operator (as well as the ( + - and / ) operators in R do an Element-by-element, aka Element-wise multiplication.  They can be different orientations, but they must be the same length.

How to reproduce this error in R:

```<code>x = matrix(c(1, 2, 3))         #has dimension 3 1
y = matrix(c(1, 2))            #has dimension 2 1
e = x * y                      #Error in x * y : non-conformable arrays
e
</code>```

The asterisk operator between two matrices or vectors must be of compatible dimensions:

To fix the above, make sure the matrices are of compatible dimensions:

```<code>x = matrix(c(1, 2, 3))
y = matrix(c(c(1, 2, 3)))
e = x * y
e
</code>```

Prints:

```<code>     [,1]
[1,]    1
[2,]    4
[3,]    9
</code>```

Other ways to reproduce this error:

```<code>matrix(1,2,3)    + matrix(1,2)       #Error, non-conformable arrays
matrix(1:6)      / matrix(1:5)       #Error, non-conformable arrays
matrix(c(1,2))   / matrix(5)         #Error, non-conformable arrays
matrix(c(1,2,3)) * matrix(c(1,2))    #Error, non-conformable arrays
matrix(c(1,2))   * matrix(c(1))      #Error, non-conformable arrays
matrix(c(1,2))   * matrix(1)         #Error, non-conformable arrays
</code>```

Body:
I'm trying to train a neural network in R with the following dataset (small part)

      Age   Salary Mortrate Clientrate Savrate PartialPrate
 [1,]  62 2381.140    0.047       7.05     3.1            0
 [2,]  52 1777.970    0.047       6.10     3.1            0
 [3,]  53 2701.210    0.047       6.40     3.1            0
 [4,]  52 4039.460    0.047       7.00     3.1            0
 [5,]  56  602.240    0.047       6.20     3.1            0
 [6,]  43 2951.090    0.047       6.80     3.1            0
 [7,]  49 4648.860    0.047       7.50     3.1            0
 [8,]  44 3304.110    0.047       7.10     3.1            0
 [9,]  56 1300.000    0.047       6.10     3.1            0
[10,]  50 1761.440    0.047       6.95     3.1            0

If I try doing it for small set of data as above the code works, but if I take more data then the neuralnet() gives the error:

Neuralnet error Error in x - y : non-conformable arrays.

What does this error mean and how do I fix it?

Code:

trainingsoutput <- AllData$PartialPrepay
trainingdata <- cbind(AllData$LEEFTIJD, AllData$MEDSAL2, AllData$rate5Y,
                      AllData$CRate, AllData$SavRate, trainingsoutput)
dimnames(trainingdata) <- list(NULL,
                               c("Age","Salary","Mortrate","Clientrate",
                                 "Savrate","PartialPrate"))

nn <- neuralnet(PartialPrate ~ Age + Salary + Mortrate + Clientrate + Savrate,
                data = trainingdata ,hidden=3, err.fct="sse", threshold=0.01)

Body:
Error message description:

The phrase Conformable arrays is linear algebra jargon for "arrays that can sensibly be operated on together".  The bare asterisk operator (as well as the ( + - and / ) operators in R do an Element-by-element, aka Element-wise multiplication.  They can be different orientations, but they must be the same length.

How to reproduce this error in R:

x = matrix(c(1, 2, 3))         #has dimension 3 1
y = matrix(c(1, 2))            #has dimension 2 1
e = x * y                      #Error in x * y : non-conformable arrays
e

The asterisk operator between two matrices or vectors must be of compatible dimensions:

To fix the above, make sure the matrices are of compatible dimensions:

x = matrix(c(1, 2, 3))
y = matrix(c(c(1, 2, 3)))
e = x * y
e

Prints:

     [,1]
[1,]    1
[2,]    4
[3,]    9

Other ways to reproduce this error:

matrix(1,2,3)    + matrix(1,2)       #Error, non-conformable arrays
matrix(1:6)      / matrix(1:5)       #Error, non-conformable arrays
matrix(c(1,2))   / matrix(5)         #Error, non-conformable arrays
matrix(c(1,2,3)) * matrix(c(1,2))    #Error, non-conformable arrays
matrix(c(1,2))   * matrix(c(1))      #Error, non-conformable arrays
matrix(c(1,2))   * matrix(1)         #Error, non-conformable arrays


问:
How to create a library
I have some code which I want to organize into a class or library for other developers to use more easily on their website.

The way I use the class now is to instantiate an instance of it and start calling the functions I need as I need them.

```<code>$class_object = new MyClass();
$class_object->myFunction();
</code>```

Is this basically all I need to make a library, or do I need to make further changes to turn this into a library?

答:
As far as I know, yes.  But you do need to make your library compatible with the accepted autoloading standards.  That way developers can simply drop it into their system and start using it.

http://groups.google.com/group/php-standards/web/psr-0-final-proposal?pli=1

Title: How to create a library

Body:
I have some code which I want to organize into a class or library for other developers to use more easily on their website.

The way I use the class now is to instantiate an instance of it and start calling the functions I need as I need them.

$class_object = new MyClass();
$class_object->myFunction();

Is this basically all I need to make a library, or do I need to make further changes to turn this into a library?


问:
calculate similarity between two vectors
I have a matrix M which is a 29 x 18 double, something like this:

```<code>1   1   1 ...
2   1   1 ...
3   1   2 ...
2   2   2 ...
2   1   3 ...
3   1   3 ...
1   3   3 ...
...
</code>```

For each possible pair of two columns in M, I want to calculate the number of times the values of the same row between two columns are identical. Take column 1 and 2 for instance, the number of times values of the same row are identical is 2 since M(1,1) = M(1,2) and M(4,1) = M(4,2). This calculation is repeated 18 time for each column as each column is paired with each of the total number of columns, including itself. Thus, the output (called N) would be 18 x 18 matrix with the each value indicating how many instances the values of the same row from the original two corresponding columns are identical. Something like this

```<code>29 4 5 3 ...
4 29 6 0 ...
5 6 29 7 ...
...
</code>```

Since N(2,1) = 4, this would indicate that column 1 and column 2 matrix M have 4 matching values of the same row.

How do I do this?

答:
you can do a double for loop like that:</p>

```<code>result = zeros(18);
for i = 1:18
    for j = 1:18
        result(i,j) = nnz(M(:,i) == M(:,j));
    end
end
</code>```

Body:
I have a matrix M which is a 29 x 18 double, something like this:

1   1   1 ...
2   1   1 ...
3   1   2 ...
2   2   2 ...
2   1   3 ...
3   1   3 ...
1   3   3 ...
...

For each possible pair of two columns in M, I want to calculate the number of times the values of the same row between two columns are identical. Take column 1 and 2 for instance, the number of times values of the same row are identical is 2 since M(1,1) = M(1,2) and M(4,1) = M(4,2). This calculation is repeated 18 time for each column as each column is paired with each of the total number of columns, including itself. Thus, the output (called N) would be 18 x 18 matrix with the each value indicating how many instances the values of the same row from the original two corresponding columns are identical. Something like this

29 4 5 3 ...
4 29 6 0 ...
5 6 29 7 ...
...

Since N(2,1) = 4, this would indicate that column 1 and column 2 matrix M have 4 matching values of the same row.

How do I do this?

Body:
you can do a double for loop like that:

result = zeros(18);
for i = 1:18
    for j = 1:18
        result(i,j) = nnz(M(:,i) == M(:,j));
    end
end


答:
you can try floating them. thats what i usually do.</p>

```<code>.commbutton{
 float:left;
 }

 .commentry{
 float:left;
 }
</code>```

Title: How can I align these elements side by side?

Body:
you can try floating them. thats what i usually do.

.commbutton{
 float:left;
 }

 .commentry{
 float:left;
 }


问:
Deleting Blobs from azure storage mvc
When trying to delete, or copy a blob from my Azure storage, after successfully uploading it, I get the following 404 error. I cannot see why it is not finding the blob from my storage system, due to successfull upload and successfull downloading. Here is my code to delete that does not work;
I tried setting the "            CloudBlockBlob blob = container.GetBlockBlobReference(path);
" to a file I knew was there "2020Resume.pdf" and it still didnt work

```<code>// GET: DocumentUps/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            DocumentUps documentUps = db.DocumentUps.Find(id);
            Distributee distributees = db.Distributees.Find(id);
            if (documentUps == null)
            {
                return HttpNotFound();
            }
            return View(documentUps);
        }

        // POST: DocumentUps/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        DocumentUps documentUps = db.DocumentUps.Find(id);
        Distributee distributees = db.Distributees.Find(id);

        string attachmnt = documentUps.Attachment.ToString();
        if (attachmnt.Contains('.'))
            attachmnt = attachmnt.Substring(0, attachmnt.LastIndexOf('.'));

        var fileName = documentUps.DocumentId.ToString() + documentUps.RevisionId.ToString() + attachmnt;

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("filestorageideagen_AzureStorageConnectionString"));
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("documentuploader");
        CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
        blob.Delete();

        if (distributees != null)
        {
            db.Distributees.Remove(distributees);
        }
        db.DocumentUps.Remove(documentUps);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
</code>```

The error

```<code>Server Error in '/' Application.

The remote server returned an error: (404) Not Found.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (404) Not Found.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[WebException: The remote server returned an error: (404) Not Found.]
   System.Net.HttpWebRequest.GetResponse() +1399
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +1150

[StorageException: The remote server returned an error: (404) Not Found.]
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +4559
   Microsoft.WindowsAzure.Storage.Blob.CloudBlob.Delete(DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) +62
   Integrated_Project.Controllers.MyDocumentUpsController.DeleteConfirmed(Int32 id) +336
   lambda_method(Closure , ControllerBase , Object[] ) +97
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9765121
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</code>```

答:
There's an issue with the way you're creating an instance of CloudBlockBlob. The path should only include the file name and not the complete URL as the URL will be created automatically by the SDK. So if you do just the following, the error should go away:

```<code>            string path = "https://filestorageideagen.blob.core.windows.net/documentuploader/" + fileName;

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("filestorageideagen_AzureStorageConnectionString"));
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference("documentuploader");
            CloudBlockBlob blob = container.GetBlockBlobReference(fileName);//Changed path to fileName
            blob.Delete();
</code>```

Title: Deleting Blobs from azure storage mvc

Body:
When trying to delete, or copy a blob from my Azure storage, after successfully uploading it, I get the following 404 error. I cannot see why it is not finding the blob from my storage system, due to successfull upload and successfull downloading. Here is my code to delete that does not work;
I tried setting the "            CloudBlockBlob blob = container.GetBlockBlobReference(path);
" to a file I knew was there "2020Resume.pdf" and it still didnt work

// GET: DocumentUps/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            DocumentUps documentUps = db.DocumentUps.Find(id);
            Distributee distributees = db.Distributees.Find(id);
            if (documentUps == null)
            {
                return HttpNotFound();
            }
            return View(documentUps);
        }

        // POST: DocumentUps/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        DocumentUps documentUps = db.DocumentUps.Find(id);
        Distributee distributees = db.Distributees.Find(id);

        string attachmnt = documentUps.Attachment.ToString();
        if (attachmnt.Contains('.'))
            attachmnt = attachmnt.Substring(0, attachmnt.LastIndexOf('.'));

        var fileName = documentUps.DocumentId.ToString() + documentUps.RevisionId.ToString() + attachmnt;

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("filestorageideagen_AzureStorageConnectionString"));
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("documentuploader");
        CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
        blob.Delete();

        if (distributees != null)
        {
            db.Distributees.Remove(distributees);
        }
        db.DocumentUps.Remove(documentUps);
        db.SaveChanges();

        return RedirectToAction("Index");
    }

The error

Server Error in '/' Application.

The remote server returned an error: (404) Not Found.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (404) Not Found.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[WebException: The remote server returned an error: (404) Not Found.]
   System.Net.HttpWebRequest.GetResponse() +1399
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +1150

[StorageException: The remote server returned an error: (404) Not Found.]
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +4559
   Microsoft.WindowsAzure.Storage.Blob.CloudBlob.Delete(DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) +62
   Integrated_Project.Controllers.MyDocumentUpsController.DeleteConfirmed(Int32 id) +336
   lambda_method(Closure , ControllerBase , Object[] ) +97
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9765121
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Body:
There's an issue with the way you're creating an instance of CloudBlockBlob. The path should only include the file name and not the complete URL as the URL will be created automatically by the SDK. So if you do just the following, the error should go away:

            string path = "https://filestorageideagen.blob.core.windows.net/documentuploader/" + fileName;

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("filestorageideagen_AzureStorageConnectionString"));
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference("documentuploader");
            CloudBlockBlob blob = container.GetBlockBlobReference(fileName);//Changed path to fileName
            blob.Delete();