问:
Adding a string to a CSV file while monitoring existing string combinations in the CSV file
I'm trying to write a C# method that will add a set of strings to a CSV file. It will be like this,

```<code>public void StoreWords(string expectedValue, stringActualValue)
{
  ///Store expectedValue, actualValue, and a seed value per row in the
  /// .csv file. If the combination of the expectValue and actualValue
  ///does not exist in the .csv file, then initialize a seed value for that
  ///combination, otherwise increment the seed value for that combination
  }
</code>```

I'm getting stuck on opening a csv file and storing the combination of words. Any help would be appreciated.

答:
I think that code should meet your requirements:

```<code>private string FilePath { get; set; }

private string[] ReadFile()
{
    return File.ReadAllLines(FilePath);
}

public Dictionary<Tuple<string, string>, string> MakeOrIncSeedValuesFromCsv(string[] lines)
{
    var valuePairToSeedValue = new Dictionary<Tuple<string, string>, string>();

    var lines = ReadFile();
    for (int i = 0; i < lines.Length; i++)
    {
        var values = lines[i].Split(',');

        if (values.Length > 2)
        {
            var newSeedValue = IncSeedValue(lines[2]);
            var key = Tuple.Create<string, string>(values[0], values[1]);

            if (!valuePairToSeedValue.ContainsKey(key))
            {
                valuePairToSeedValue.Add(key, newSeedValue);
            }
            else
            {
                valuePairToSeedValue[key] = newSeedValue;
            }

        }
        else
        {
            var key = Tuple.Create<string, string>(values[0], values[1]);
            var seed = GetSeedValue(key);

            if (!valuePairToSeedValue.ContainsKey(key))
            {
                valuePairToSeedValue.Add(key, seed);
            }
            else
            {
                valuePairToSeedValue[key] = seed;
            }
        }
    }

    return valuePairToSeedValue;
}

private string GetSeedValue(Tuple<string, string> values)
{
    return // put your code here
}

private string IncSeedValue(string actualSeedValue)
{
    return // put your code here
}
</code>```

}

Body:
I'm trying to write a C# method that will add a set of strings to a CSV file. It will be like this,

public void StoreWords(string expectedValue, stringActualValue)
{
  ///Store expectedValue, actualValue, and a seed value per row in the
  /// .csv file. If the combination of the expectValue and actualValue
  ///does not exist in the .csv file, then initialize a seed value for that
  ///combination, otherwise increment the seed value for that combination
  }

I'm getting stuck on opening a csv file and storing the combination of words. Any help would be appreciated.

Body:
I think that code should meet your requirements:

private string FilePath { get; set; }

private string[] ReadFile()
{
    return File.ReadAllLines(FilePath);
}

public Dictionary<Tuple<string, string>, string> MakeOrIncSeedValuesFromCsv(string[] lines)
{
    var valuePairToSeedValue = new Dictionary<Tuple<string, string>, string>();

    var lines = ReadFile();
    for (int i = 0; i < lines.Length; i++)
    {
        var values = lines[i].Split(',');

        if (values.Length > 2)
        {
            var newSeedValue = IncSeedValue(lines[2]);
            var key = Tuple.Create<string, string>(values[0], values[1]);

            if (!valuePairToSeedValue.ContainsKey(key))
            {
                valuePairToSeedValue.Add(key, newSeedValue);
            }
            else
            {
                valuePairToSeedValue[key] = newSeedValue;
            }

        }
        else
        {
            var key = Tuple.Create<string, string>(values[0], values[1]);
            var seed = GetSeedValue(key);

            if (!valuePairToSeedValue.ContainsKey(key))
            {
                valuePairToSeedValue.Add(key, seed);
            }
            else
            {
                valuePairToSeedValue[key] = seed;
            }
        }
    }

    return valuePairToSeedValue;
}

private string GetSeedValue(Tuple<string, string> values)
{
    return // put your code here
}

private string IncSeedValue(string actualSeedValue)
{
    return // put your code here
}

}


来源: stackexchange

问:
Unsafe connection after changing rules in .htaccess
I'm trying to set rules to change the URL from page contact.php to contact but the website now show unsafe connection in the main page but not on other pages.

This is the rule i used:

```<code>RewriteRule ^contact(.[A-Za-z0-9-]+)/?$ contact.php?=$1
</code>```

While i still haven't set this clean URL yet, it's strange the website isn't using a secure connection anymore.

The link is here. Even if i clear the rule it is still unsecure and even if you write https:// in the URL, after navigating through other pages and back to the main page again it is not secure anymore.

Can you give me insight from this?

答:
I just checked your site. For every absolute URL you need to have https and not http as the protocol or use relative URLs.
So please check your HTML a-tags.
To also have the main site in https you should add another rewrite rule:

```<code>RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
</code>```

Another thing is to fix the current contact regex to:

```<code>RewriteRule ^contact([.A-Za-z0-9-]*)/?$ contact.php?=$1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to set rules to change the URL from page contact.php to contact but the website now show unsafe connection in the main page but not on other pages.

This is the rule i used:

RewriteRule ^contact(.[A-Za-z0-9-]+)/?$ contact.php?=$1

While i still haven't set this clean URL yet, it's strange the website isn't using a secure connection anymore.

The link is here. Even if i clear the rule it is still unsecure and even if you write https:// in the URL, after navigating through other pages and back to the main page again it is not secure anymore.

Can you give me insight from this?

Body:
I just checked your site. For every absolute URL you need to have https and not http as the protocol or use relative URLs.
So please check your HTML a-tags.
To also have the main site in https you should add another rewrite rule:

RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

Another thing is to fix the current contact regex to:

RewriteRule ^contact([.A-Za-z0-9-]*)/?$ contact.php?=$1


问:
How do I move items from a boost::variant to a multimap?
I'd like to improve the performance of PickPotatoes in the below code by using move instead of copy, but I can't figure out how to do that with insert and a boost::variant. In my actual use case, parsing the data takes about 75% of the time, and the real version of PickPotatoes takes about 25%, due to some slow copies. By improving PickPotatoes I should be able to get that down. Is it possible to move something out of a boost::variant and improve PickPotatoes?

```<code>#include <map>
#include "boost/variant.hpp"
#include <string>
#include <vector>
#include <functional>
struct tuber
{
    int z;
    std::vector<double> r;
};

int getZ(const tuber& t)
{
    return t.z;
}

boost::variant<std::string, tuber> GrowPotato()
{
    int z = std::rand() / (RAND_MAX / 10);
    if (z < 2)
    {
        return "BAD POTATO";
    }
    else
    {
        tuber ret;
        ret.z = z;
        ret.r.resize(10000);
        for (int i = 0;i < 10000;++i)
        {
            ret.r[i] = std::rand() / (RAND_MAX / 50);
        }
        return ret;
    }
}

std::vector<boost::variant<std::string,tuber>> GrowPotatoes(int n)
{

    std::vector<boost::variant<std::string, tuber>> ret;
    ret.resize(n);
    for (int i = 0; i < n; ++i)
    {
        ret[i] = GrowPotato();
    }

    return ret;
}

//could make this more efficient.
std::pair<std::vector<std::string>,std::multimap<int, tuber>> PickPotatoes(std::vector <boost::variant<std::string, tuber>> result)
{
    std::pair<std::vector<std::string>,std::multimap<int,tuber>> ret;
    int numTypTwo = 0;
    for (const auto& item : result)
    {
        numTypTwo += item.which();
    }
    ret.first.resize(result.size() - numTypTwo);
    int fstSpot = 0;
    for (int i = 0; i < result.size();++i)
    {
        if (result[i].which())
        {
            ret.second.insert(std::pair<int, tuber>(getZ(boost::get<tuber>(result[i])), boost::get<tuber>(result[i])));
        }
        else
        {
            ret.first[fstSpot++] = std::move(boost::get<std::string>(result[i]));
        }
    }
    return ret;
}
int main()
{
    std::srand(0);
    std::vector<boost::variant<std::string, tuber>>  q= GrowPotatoes(5000);
    std::pair<std::vector<std::string>, std::multimap<int, tuber>> z = PickPotatoes(q);
    return 0;
}
</code>```

答:
The simplest win would be to move the parameter value:

```<code>std::pair<std::vector<std::string>, std::multimap<int, tuber>> z = PickPotatoes(std::move(q));
</code>```

Indeed, it wins 14% of performance, roughly on my benchmarks. The rest heavily depends on what it all means, how it's going to be used.

Focus on reducing allocations (use a non-nodebased container if you can, e.g. boost::flat_multimap, sort explicitly, use string_view, parse into the desired datastructure instead of intermediate).

BONUS

I was able to shave off about 30% using:

```<code>std::pair<std::vector<std::string>, std::multimap<int, tuber> >
PickPotatoes(std::vector<boost::variant<std::string, tuber> >&& result) {

    std::pair<std::vector<std::string>, std::multimap<int, tuber> > ret;

    ret.first.reserve(result.size());

    struct Vis {
        using result_type = void;

        void operator()(std::string& s) const {
            first.emplace_back(std::move(s));
        }
        void operator()(tuber& tbr) const {
            second.emplace(tbr.z, std::move(tbr));
        }

        std::vector<std::string>& first;
        std::multimap<int, tuber>& second;
    } visitor { ret.first, ret.second };

    for (auto& element : result) {
        boost::apply_visitor(visitor, element);
    }

    return ret;
}
</code>```

Using emplace, avoiding repeated get<>, avoiding the loop to get the first size etc.

Body:
I'd like to improve the performance of PickPotatoes in the below code by using move instead of copy, but I can't figure out how to do that with insert and a boost::variant. In my actual use case, parsing the data takes about 75% of the time, and the real version of PickPotatoes takes about 25%, due to some slow copies. By improving PickPotatoes I should be able to get that down. Is it possible to move something out of a boost::variant and improve PickPotatoes?

#include <map>
#include "boost/variant.hpp"
#include <string>
#include <vector>
#include <functional>
struct tuber
{
    int z;
    std::vector<double> r;
};

int getZ(const tuber& t)
{
    return t.z;
}

boost::variant<std::string, tuber> GrowPotato()
{
    int z = std::rand() / (RAND_MAX / 10);
    if (z < 2)
    {
        return "BAD POTATO";
    }
    else
    {
        tuber ret;
        ret.z = z;
        ret.r.resize(10000);
        for (int i = 0;i < 10000;++i)
        {
            ret.r[i] = std::rand() / (RAND_MAX / 50);
        }
        return ret;
    }
}

std::vector<boost::variant<std::string,tuber>> GrowPotatoes(int n)
{

    std::vector<boost::variant<std::string, tuber>> ret;
    ret.resize(n);
    for (int i = 0; i < n; ++i)
    {
        ret[i] = GrowPotato();
    }

    return ret;
}

//could make this more efficient.
std::pair<std::vector<std::string>,std::multimap<int, tuber>> PickPotatoes(std::vector <boost::variant<std::string, tuber>> result)
{
    std::pair<std::vector<std::string>,std::multimap<int,tuber>> ret;
    int numTypTwo = 0;
    for (const auto& item : result)
    {
        numTypTwo += item.which();
    }
    ret.first.resize(result.size() - numTypTwo);
    int fstSpot = 0;
    for (int i = 0; i < result.size();++i)
    {
        if (result[i].which())
        {
            ret.second.insert(std::pair<int, tuber>(getZ(boost::get<tuber>(result[i])), boost::get<tuber>(result[i])));
        }
        else
        {
            ret.first[fstSpot++] = std::move(boost::get<std::string>(result[i]));
        }
    }
    return ret;
}
int main()
{
    std::srand(0);
    std::vector<boost::variant<std::string, tuber>>  q= GrowPotatoes(5000);
    std::pair<std::vector<std::string>, std::multimap<int, tuber>> z = PickPotatoes(q);
    return 0;
}

Body:
The simplest win would be to move the parameter value:

std::pair<std::vector<std::string>, std::multimap<int, tuber>> z = PickPotatoes(std::move(q));

Indeed, it wins 14% of performance, roughly on my benchmarks. The rest heavily depends on what it all means, how it's going to be used.

Focus on reducing allocations (use a non-nodebased container if you can, e.g. boost::flat_multimap, sort explicitly, use string_view, parse into the desired datastructure instead of intermediate).

BONUS

I was able to shave off about 30% using:

std::pair<std::vector<std::string>, std::multimap<int, tuber> >
PickPotatoes(std::vector<boost::variant<std::string, tuber> >&& result) {

    std::pair<std::vector<std::string>, std::multimap<int, tuber> > ret;

    ret.first.reserve(result.size());

    struct Vis {
        using result_type = void;

        void operator()(std::string& s) const {
            first.emplace_back(std::move(s));
        }
        void operator()(tuber& tbr) const {
            second.emplace(tbr.z, std::move(tbr));
        }

        std::vector<std::string>& first;
        std::multimap<int, tuber>& second;
    } visitor { ret.first, ret.second };

    for (auto& element : result) {
        boost::apply_visitor(visitor, element);
    }

    return ret;
}

Using emplace, avoiding repeated get<>, avoiding the loop to get the first size etc.


问:
how to keep records information when working in ML
I am basing this question on this one. The OP says 'This problem doesn't exist in ML as it uses DataFrame and I can simply add another column with the score to my original dataframe.' Can anyone tell me how to do this?
I have tried:

```<code>val labeledData = data1.select("labels","hash-tfidf").rdd.map { row =>
  LabeledPoint(row.getAs[Double]("labels"), row.getAs[org.apache.spark.ml.linalg.SparseVector]("hash-tfidf"))
}

val scoreDF = model.transform(labeledData.toDS)

val dfPredictions = data1.withColumn("prediction", scoreDF.col("prediction"))
</code>```

where data1 is my original dataframe with lots of columns.
This errors with:

```<code>org.apache.spark.sql.AnalysisException: resolved attribute(s) prediction#1458 missing from ....[loads of fields I think from data1]...
</code>```

What am I doing wrong?

答:
You don't need RDDs and you don't need LabeledPoint and you cannot add column from another DataFrame.

It is not clear what the model is, but I assume it's input column is features so you can either rename the column:

```<code>model.transform(data1.withColumnRenamed("hash-tfidf", "features"))
</code>```

or configure model to accept hash-tfidf as input.

Body:
I am basing this question on this one. The OP says 'This problem doesn't exist in ML as it uses DataFrame and I can simply add another column with the score to my original dataframe.' Can anyone tell me how to do this?
I have tried:

val labeledData = data1.select("labels","hash-tfidf").rdd.map { row =>
  LabeledPoint(row.getAs[Double]("labels"), row.getAs[org.apache.spark.ml.linalg.SparseVector]("hash-tfidf"))
}

val scoreDF = model.transform(labeledData.toDS)

val dfPredictions = data1.withColumn("prediction", scoreDF.col("prediction"))

where data1 is my original dataframe with lots of columns.
This errors with:

org.apache.spark.sql.AnalysisException: resolved attribute(s) prediction#1458 missing from ....[loads of fields I think from data1]...

What am I doing wrong?

Body:
You don't need RDDs and you don't need LabeledPoint and you cannot add column from another DataFrame.

It is not clear what the model is, but I assume it's input column is features so you can either rename the column:

model.transform(data1.withColumnRenamed("hash-tfidf", "features"))

or configure model to accept hash-tfidf as input.


问:
AWS ApiGateway Latency Issue
I am currently using AWS Lambda for my internal application to application calls using spring framework implemented with jrestless.

Application to application call is working perfect with decent latency(~10-15ms ideally)

But when I am trying to leverage same lambda function via API Gateway the latency shoots up to 700-800 ms. Even though my lambda function is taking same 10-15 ms.

Lambda Function Configurations:

```<code>VPC: open(no vpc)
Region: ap-south-1(Mumbai)
Memory: 1500 MB(Highest)
Timeout: 5 min(Highest)
</code>```

API Gateway Configurations:

```<code>Region: ap-south-a(Mumbai)
Request Integration: proxy+
Request Method: ANY
</code>```

No Authentication is being used and its an HTTPS call.

Has anyone faced a similar issue?

答:
If you are curious where the latency is introduced, API Gateway provides two CloudWatch metrics: Latency and IntegrationLatency. Latency is the total server-side latency recorded by API Gateway, and IntegrationLatency is only the latency of the backend request/response. The difference between these two metrics is the API Gateway server-side overhead. Any difference between client-side latency and the Latency metric will be network/TLS/connection latency.

We have recently launched the 'Regional' endpoint type which is an option for use cases where the client is in the same AWS region as the API itself. This should bring your latency down closer to what you get when calling Lambda directly.

Latency will generally improve with volume

Lambda itself will always have overhead, and they do not expose the server-side overhead (unlike API Gateway). The duration exposed by Lambda is only the function duration that you are billed for. It does not indicate the total latency.

Title: AWS ApiGateway Latency Issue

Body:
I am currently using AWS Lambda for my internal application to application calls using spring framework implemented with jrestless.

Application to application call is working perfect with decent latency(~10-15ms ideally)

But when I am trying to leverage same lambda function via API Gateway the latency shoots up to 700-800 ms. Even though my lambda function is taking same 10-15 ms.

Lambda Function Configurations:

VPC: open(no vpc)
Region: ap-south-1(Mumbai)
Memory: 1500 MB(Highest)
Timeout: 5 min(Highest)

API Gateway Configurations:

Region: ap-south-a(Mumbai)
Request Integration: proxy+
Request Method: ANY

No Authentication is being used and its an HTTPS call.

Has anyone faced a similar issue?


问:
Arguments passed into for loop in bash script
I am trying to pass the argument as max limit for the for loop like this:

```<code>#!/bin/bash

for i in {1..$1}
do
    echo $i
done
</code>```

This however returns {1..2} when called with argument 2, instead of executing the script and giving me

```<code>1
2
</code>```

答:
Variable substitutions are not done inside of curly braces. You can use fixed numbers but not variables.

Brace Expansion

A sequence expression takes the form {x..y}, where x and y are either integers or single characters. ...

Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result.  It is strictly textual.  Bash does  not  apply any syntactic interpretation to the context of the expansion or the text between the braces.

A  correctly-formed  brace  expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence expression.  Any incorrectly formed brace expansion is left unchanged.

Try one of these alternatives:

```<code>for ((i = 1; i <= $1; i++)); do
    echo $i
done

# Not recommended with large sequences.
for i in $(seq 1 $1); do
    echo $i
done
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to pass the argument as max limit for the for loop like this:

#!/bin/bash

for i in {1..$1}
do
    echo $i
done

This however returns {1..2} when called with argument 2, instead of executing the script and giving me

1
2

Body:
Variable substitutions are not done inside of curly braces. You can use fixed numbers but not variables.

Brace Expansion

A sequence expression takes the form {x..y}, where x and y are either integers or single characters. ...

Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result.  It is strictly textual.  Bash does  not  apply any syntactic interpretation to the context of the expansion or the text between the braces.

A  correctly-formed  brace  expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence expression.  Any incorrectly formed brace expansion is left unchanged.

Try one of these alternatives:

for ((i = 1; i <= $1; i++)); do
    echo $i
done

# Not recommended with large sequences.
for i in $(seq 1 $1); do
    echo $i
done


问:
Reset Video.js plugin to initial state
I'm using jquery ui tabs and video.js. I want to stop the video when I go to another tab and reset it when I come back to second tab.</p>

答:
```<code>player.reset();
</code>```

Life is simple.

Title: Reset Video.js plugin to initial state

Body:
player.reset();

Life is simple.


问:
Android Camera2: CONTROL_AF_STATE always 0 for CONTROL_AF_MODE_MACRO
I am trying to detect when camera has focused (or has stopped trying to) so I am calling result.get(CaptureResult.CONTROL_AF_STATE)in onCaptureCompleted method of callback.

It kind of works for mode AF_MODE_CONTINUOUS_PICTURE, camera reports CONTROL_AF_STATE 1 or 2 (CONTROL_AF_STATE_PASSIVE_SCAN or CONTROL_AF_STATE_PASSIVE_LOCKED), which is nice.

However when camera is switched to AF_MODE_MACRO, then reported CONTROL_AF_STATE is always 0 (INNACTIVE) no matter what happens. I was trying to refer to 1 but probably I do not get it right.

Further info: when changing modes between AF_MODE_MACRO and AF_MODE_CONTINUOUS_PICTURE I always start new capture session like this:

```<code>private void configCaptureSession(boolean macroModeNew) {
this.macroMode = macroModeNew;
try {
  // Wanna macro?
  if (macroMode) {
    LOGGER.d( "MACRO ON","");
    previewRequestBuilder.set(
            CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_MACRO);
    }

  else {
    // Continuous AF
    LOGGER.d( "MACRO OFF","");
    previewRequestBuilder.set(
            CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

  }

  // Finally, we start displaying the camera preview.
  previewRequest = previewRequestBuilder.build();
  LOGGER.d( "SETTING NEW SESSION","");

  captureSession.setRepeatingRequest(
      previewRequest, captureCallback, backgroundHandler);

} catch (final CameraAccessException e) {
  LOGGER.e(e, "Exception!");
}
</code>```

}

captureCallback:

```<code> private final CameraCaptureSession.CaptureCallback captureCallback =
  new CameraCaptureSession.CaptureCallback() {
    @Override
    public void onCaptureProgressed(
        final CameraCaptureSession session,
        final CaptureRequest request,
        final CaptureResult partialResult) {}

    @Override
    public void onCaptureCompleted(
        final CameraCaptureSession session,
        final CaptureRequest request,
        final TotalCaptureResult result) {

        afState = result.get(CaptureResult.CONTROL_AF_STATE);

        LOGGER.i("FOKKUS-MODE:"+result.get(CaptureResult.CONTROL_AF_MODE));
        LOGGER.i("FOKKUS:"+result.get(CaptureResult.CONTROL_AF_STATE));

    }

  };
</code>```

答:
Does your device list support for AF_MODE_MACRO in https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics.html#CONTROL_AF_AVAILABLE_MODES ?

If not, then this is expected as you're trying to use a non-supported focusing mode.

If it is supported, the next issue is that I don't see you issuing an AF trigger command anywhere.  Have you looked at the state transition tables for AF_STATE here:
https://developer.android.com/reference/android/hardware/camera2/CaptureResult.html#CONTROL_AF_STATE ?

For AF_AUTO and AF_MACRO, you have to trigger AF when you want a focus pass, and then wait for AF_STATE_FOCUSED_LOCKED or NOT_FOCUSED_LOCKED.

The continuous modes don't require a trigger to focus, which is why you're seeing something happening with them.

Body:
I am trying to detect when camera has focused (or has stopped trying to) so I am calling result.get(CaptureResult.CONTROL_AF_STATE)in onCaptureCompleted method of callback.

It kind of works for mode AF_MODE_CONTINUOUS_PICTURE, camera reports CONTROL_AF_STATE 1 or 2 (CONTROL_AF_STATE_PASSIVE_SCAN or CONTROL_AF_STATE_PASSIVE_LOCKED), which is nice.

However when camera is switched to AF_MODE_MACRO, then reported CONTROL_AF_STATE is always 0 (INNACTIVE) no matter what happens. I was trying to refer to 1 but probably I do not get it right.

Further info: when changing modes between AF_MODE_MACRO and AF_MODE_CONTINUOUS_PICTURE I always start new capture session like this:

private void configCaptureSession(boolean macroModeNew) {
this.macroMode = macroModeNew;
try {
  // Wanna macro?
  if (macroMode) {
    LOGGER.d( "MACRO ON","");
    previewRequestBuilder.set(
            CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_MACRO);
    }

  else {
    // Continuous AF
    LOGGER.d( "MACRO OFF","");
    previewRequestBuilder.set(
            CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

  }

  // Finally, we start displaying the camera preview.
  previewRequest = previewRequestBuilder.build();
  LOGGER.d( "SETTING NEW SESSION","");

  captureSession.setRepeatingRequest(
      previewRequest, captureCallback, backgroundHandler);

} catch (final CameraAccessException e) {
  LOGGER.e(e, "Exception!");
}

}

captureCallback:

 private final CameraCaptureSession.CaptureCallback captureCallback =
  new CameraCaptureSession.CaptureCallback() {
    @Override
    public void onCaptureProgressed(
        final CameraCaptureSession session,
        final CaptureRequest request,
        final CaptureResult partialResult) {}

    @Override
    public void onCaptureCompleted(
        final CameraCaptureSession session,
        final CaptureRequest request,
        final TotalCaptureResult result) {

        afState = result.get(CaptureResult.CONTROL_AF_STATE);

        LOGGER.i("FOKKUS-MODE:"+result.get(CaptureResult.CONTROL_AF_MODE));
        LOGGER.i("FOKKUS:"+result.get(CaptureResult.CONTROL_AF_STATE));

    }

  };


问:
Any JavaScript code coverage tools for client-server apps in Google Closure?
I'm trying to get code coverage for unit tests in a Google Closure client-server project. We have code coverage for the server side, and need client side coverage.

JSCover runs its own server. Our cleint side unit tests require running under our server to access specific services. I don't see a way to make them work together, but a suggestion on how to do so would be ideal.

istanbul supports a number of underlying frameworks, but Google Closure does not appear to be one of them. Is there an easy way to use istanbul with a Google Closure unit test?

Blanket does not seem to be supported any longer. Does anyone have any recent experience that indicates it might still work with Google Closure?

Are there other coverage tools that would work well with Google Closure in a client-server configuration?

答:
Istanbul works well with Google Closure and goog.testing.testSuite, although it is not obvious how to set it up. In general, follow the instructions for using Istanbul with IoT.js.

More specifically, here's an outline of how we instrumented our own Google Closure tests with Istanbul to generate code coverage information:

Install Node.js.

Using the Node.js package manager, install the Istanbul command line tool using the command npm install --save-dev nyc.

In our case, we use custom server code, so running our test suit under Node.js was not an option. I added a server-side call that accepted a file name and the contents of a file, and used this call to collect the code coverage statistics. If you don't need to use your own server code from your JavaScript tests, it is simpler to use Node.js as the server. See the link to using Istanbul with IoT.js (above) for some thoughts.

In each file for which code coverage is desired, run Istanbul's command line tool to instrument the file for coverage. The command will look something like nyc instrument myfile.js coverage_output_directory. This changes your .js files, so be sure to have a copy somewhere that you can use to restore the file. I used a Python script to find an instrument the various files.

In each Google Closure test file, add this to the end of the file:

```<code>window.onbeforeunload = function( event ) {
  /** @const {!FileUploadService} */
  var fileUploadService = new FileUploadService( "../.." );
  fileUploadService.upload( "coverage_output_directory.myfile.data", JSON.stringify( __coverage__ ) );
};
</code>```

Use a unique output file name for each test file. FileUploadService is the object we used to save result files on the server; you will need to replace this with your own service, or use the one in Node.js.

Run your tests.

Restore all changed files from your backups.

Use Istanbul and a report generator to create a code coverage report. For example, nyc report --reporter=lcov --temp-directory=coverage_output_directory. This uses the lcov report generator, which installs with Istanbul and creates a nice report.

Inspect the code coverage using a browser by loading coverage_output_directory/lcov-report/index.html.

Body:
Istanbul works well with Google Closure and goog.testing.testSuite, although it is not obvious how to set it up. In general, follow the instructions for using Istanbul with IoT.js.

More specifically, here's an outline of how we instrumented our own Google Closure tests with Istanbul to generate code coverage information:

Install Node.js.

Using the Node.js package manager, install the Istanbul command line tool using the command npm install --save-dev nyc.

In our case, we use custom server code, so running our test suit under Node.js was not an option. I added a server-side call that accepted a file name and the contents of a file, and used this call to collect the code coverage statistics. If you don't need to use your own server code from your JavaScript tests, it is simpler to use Node.js as the server. See the link to using Istanbul with IoT.js (above) for some thoughts.

In each file for which code coverage is desired, run Istanbul's command line tool to instrument the file for coverage. The command will look something like nyc instrument myfile.js coverage_output_directory. This changes your .js files, so be sure to have a copy somewhere that you can use to restore the file. I used a Python script to find an instrument the various files.

In each Google Closure test file, add this to the end of the file:

window.onbeforeunload = function( event ) {
  /** @const {!FileUploadService} */
  var fileUploadService = new FileUploadService( "../.." );
  fileUploadService.upload( "coverage_output_directory.myfile.data", JSON.stringify( __coverage__ ) );
};

Use a unique output file name for each test file. FileUploadService is the object we used to save result files on the server; you will need to replace this with your own service, or use the one in Node.js.

Run your tests.

Restore all changed files from your backups.

Use Istanbul and a report generator to create a code coverage report. For example, nyc report --reporter=lcov --temp-directory=coverage_output_directory. This uses the lcov report generator, which installs with Istanbul and creates a nice report.

Inspect the code coverage using a browser by loading coverage_output_directory/lcov-report/index.html.


问:
Seg fault when using strtok
I am trying to read each number from an input that looks like this:

```<code>179    2358 5197    867
5541    172 4294    1397
2637    136 3222    591
</code>```

... and get the min/max of each row going line by line and then getting each number in the line using strtok, but I get a seg fault error in the second while loop.

The code:

```<code>#include "header.h"
#include <string.h>

int main(void) {
  int8_t* line = malloc(sizeof(int8_t) * 75);
  int8_t* temp;

  int32_t minim, maxim;
  int32_t current;

  stdin = fopen("stdin", "r");
  while (fgets(line, 75 * sizeof(int8_t), stdin)) {
    printf("%s", line);
    temp = strtok(line," \n\t");
    maxim = minim = atoi(temp);

    while (temp != NULL) {
      current = atoi(temp);
      temp = strtok(NULL, " \n\t");

      if (current < minim)
        minim = current;
      if (current > maxim)
        maxim = current;

    }

    printf("\nMin and max: %d %d\n", minim, maxim);
  }

  printf("\n");
  return 0;
}
</code>```

The header:

```<code>#ifndef HEADER_H
# define HEADER_H

# include <stdio.h>
# include <stdlib.h>
# include <stdbool.h>

  typedef                   char  int8_t;
  typedef   signed     short int int16_t;
  typedef   signed           int int32_t;
  typedef   signed long long int int64_t;

  typedef unsigned          char  uint8_t;
  typedef unsigned     short int uint16_t;
  typedef unsigned           int uint32_t;
  typedef unsigned long long int uint64_t;

#endif
</code>```

I just don't get what it might be wrong. Thanks.

答:
OK, so...

Your  breaks on my compiler, as it redefines the identifiers int8_t et al. reserved by the standard. (Not quite correct of the compiler to complain, as the relevant headers were not included, but there you are.) If you define your own types, use your own identifiers. Or include <stdint.h> for the "real" intX_t types (yes I know a certain "big" compiler doesn't have that header).

The simplest thing, of course, is to use char * for strings instead of int8_t *. (The signed-ness of char is implementation-defined, and anyway a good compiler complains rather loudly about the many implicit casts not using char * involves.)

You use the exact-width type int32_t for your minim and maxim, but neglect to use the proper printf() width specifiers to go with that (PRId32, specified in <inttypes.h>). As I cannot see any specific need for exact-width types, I replaced them with plain int (for which a mere %d suffices).

Once you've done that, remove mention of sizeof( char ), as that is by definition 1.

Do check return values of functions. fopen() can fail. Make sure it didn't.

Don't "reuse" the stdin file descriptor. It's just confusing all around. Whether your stdin comes from the terminal or a file or a pipe is decided by how you call your executable. If you open a file, use a FILE * handle_name, not stdin. And besides, stdin is an open file descriptor (namely your program's standard input), so you would have to use freopen(), not fopen(), to have it properly receiving from a different source. The simplest thing is to actually use stdin as-is (which also gives you the greatest flexibility in using your program).

Do release resources you acquired. free() memory. fclose() files. Many operating systems protect you from this kind of negligence and clean up after you. Some don't.

And once you've fixed those problems you sneezed at in comments...

```<code>#include <stdlib.h>                           // <-- added
#include <stdio.h>                            // <-- added
#include <string.h>

int main() {
  char* line = malloc(75);                    // <-- turned to char *
  char* temp;                                 // <-- turned to char *

  int minim, maxim;                           // <-- turned to int
  int current;                                // <-- turned to int

  while (fgets(line, 75, stdin)) {            // <-- using stdin directly
    printf("%s", line);
    temp = strtok(line," \n\t");
    maxim = minim = atoi(temp);

    while (temp != NULL) {
      current = atoi(temp);
      temp = strtok(NULL, " \n\t");

      if (current < minim)
        minim = current;
      if (current > maxim)
        maxim = current;

    }

    printf("\nMin and max: %d %d\n", minim, maxim);
  }

  printf("\n");
  free( line );                                // <-- releasing memory
  return 0;
}
</code>```

...your program works:

```<code>./testme.exe < file.dat                      # feeding file.dat to stdin
179    2358 5197    867

Min and max: 179 5197
5541    172 4294    1397

Min and max: 172 5541
2637    136 3222    591

Min and max: 136 3222
</code>```

Lesson here: Code cleanly. Enable strictest compiler warnings, and heed them.

As for overwriting stdin with the results of fopen() as you did, the standard states (emphasis mine):

229) [...] [stderr, stdin, or stdout] need not be modifiable lvalues to which the value returned by the fopen function may be assigned.

Title: Seg fault when using strtok

Body:
I am trying to read each number from an input that looks like this:

179    2358 5197    867
5541    172 4294    1397
2637    136 3222    591

... and get the min/max of each row going line by line and then getting each number in the line using strtok, but I get a seg fault error in the second while loop.

The code:

#include "header.h"
#include <string.h>

int main(void) {
  int8_t* line = malloc(sizeof(int8_t) * 75);
  int8_t* temp;

  int32_t minim, maxim;
  int32_t current;

  stdin = fopen("stdin", "r");
  while (fgets(line, 75 * sizeof(int8_t), stdin)) {
    printf("%s", line);
    temp = strtok(line," \n\t");
    maxim = minim = atoi(temp);

    while (temp != NULL) {
      current = atoi(temp);
      temp = strtok(NULL, " \n\t");

      if (current < minim)
        minim = current;
      if (current > maxim)
        maxim = current;

    }

    printf("\nMin and max: %d %d\n", minim, maxim);
  }

  printf("\n");
  return 0;
}

The header:

#ifndef HEADER_H
# define HEADER_H

# include <stdio.h>
# include <stdlib.h>
# include <stdbool.h>

  typedef                   char  int8_t;
  typedef   signed     short int int16_t;
  typedef   signed           int int32_t;
  typedef   signed long long int int64_t;

  typedef unsigned          char  uint8_t;
  typedef unsigned     short int uint16_t;
  typedef unsigned           int uint32_t;
  typedef unsigned long long int uint64_t;

#endif

I just don't get what it might be wrong. Thanks.

Body:
OK, so...

Your <header.h> breaks on my compiler, as it redefines the identifiers int8_t et al. reserved by the standard. (Not quite correct of the compiler to complain, as the relevant headers were not included, but there you are.) If you define your own types, use your own identifiers. Or include <stdint.h> for the "real" intX_t types (yes I know a certain "big" compiler doesn't have that header).

The simplest thing, of course, is to use char * for strings instead of int8_t *. (The signed-ness of char is implementation-defined, and anyway a good compiler complains rather loudly about the many implicit casts not using char * involves.)

You use the exact-width type int32_t for your minim and maxim, but neglect to use the proper printf() width specifiers to go with that (PRId32, specified in <inttypes.h>). As I cannot see any specific need for exact-width types, I replaced them with plain int (for which a mere %d suffices).

Once you've done that, remove mention of sizeof( char ), as that is by definition 1.

Do check return values of functions. fopen() can fail. Make sure it didn't.

Don't "reuse" the stdin file descriptor. It's just confusing all around. Whether your stdin comes from the terminal or a file or a pipe is decided by how you call your executable. If you open a file, use a FILE * handle_name, not stdin. And besides, stdin is an open file descriptor (namely your program's standard input), so you would have to use freopen(), not fopen(), to have it properly receiving from a different source. The simplest thing is to actually use stdin as-is (which also gives you the greatest flexibility in using your program).

Do release resources you acquired. free() memory. fclose() files. Many operating systems protect you from this kind of negligence and clean up after you. Some don't.

And once you've fixed those problems you sneezed at in comments...

#include <stdlib.h>                           // <-- added
#include <stdio.h>                            // <-- added
#include <string.h>

int main() {
  char* line = malloc(75);                    // <-- turned to char *
  char* temp;                                 // <-- turned to char *

  int minim, maxim;                           // <-- turned to int
  int current;                                // <-- turned to int

  while (fgets(line, 75, stdin)) {            // <-- using stdin directly
    printf("%s", line);
    temp = strtok(line," \n\t");
    maxim = minim = atoi(temp);

    while (temp != NULL) {
      current = atoi(temp);
      temp = strtok(NULL, " \n\t");

      if (current < minim)
        minim = current;
      if (current > maxim)
        maxim = current;

    }

    printf("\nMin and max: %d %d\n", minim, maxim);
  }

  printf("\n");
  free( line );                                // <-- releasing memory
  return 0;
}

...your program works:

./testme.exe < file.dat                      # feeding file.dat to stdin
179    2358 5197    867

Min and max: 179 5197
5541    172 4294    1397

Min and max: 172 5541
2637    136 3222    591

Min and max: 136 3222

Lesson here: Code cleanly. Enable strictest compiler warnings, and heed them.

As for overwriting stdin with the results of fopen() as you did, the standard states (emphasis mine):

229) [...] [stderr, stdin, or stdout] need not be modifiable lvalues to which the value returned by the fopen function may be assigned.


问:
How to change Boolean true/false into strings
I'm currently working on a project involving validating credit cards, and I have this luhn algorithm:

```<code>export default function luhn(card: string): boolean {
return (
card.split('').reduceRight(function(prev: any, curr: any, idx) {
  prev = parseInt(prev, 10)
  if ((idx + 1) % 2 !== 0) {
    curr = (curr * 2)
      .toString()
      .split('')
      .reduce(function(p, c) {
        return (parseInt(p, 10) + parseInt(c, 10)) as any
      })
  }
  return prev + parseInt(curr, 10)
}, 0) %
  10 ===
0
)
}
</code>```

Notice the boolean in there? i'm using this as a module for my index.ts which looks like this:

```<code>import { createReadStream } from 'fs'
import { createInterface } from 'readline'
import { getCompanyName } from './cardType'
import cardValidator from './cardValidator'

const lineReader = createInterface({
input: createReadStream('data/input.txt')
})

lineReader.on('line', (creditCard: string) => {
  var company = `${getCompanyName(creditCard)}: ${creditCard} (${cardValidator(
creditCard
)})`

console.log(company)
})
</code>```

It currently outputs to the console something like this:

```<code>MasterCard: 5105105105105100 (true)
MasterCard: 5105105105105106 (false)
</code>```

I want the true/false to be valid/invalid I've looked into it a little bit(w3) but don't know how to integrate anything into my algorithm as it requires you to declare a variable for both  true and false. any suggestions/answers would be much appreciated

答:
You can simply use a ternary operator to include the strings you want directly in your output string:</p>

```<code>var company = `${getCompanyName(creditCard)}: ${creditCard} (${cardValidator(creditCard) ? "valid" : "invalid"})`
</code>```

Body:
I'm currently working on a project involving validating credit cards, and I have this luhn algorithm:

export default function luhn(card: string): boolean {
return (
card.split('').reduceRight(function(prev: any, curr: any, idx) {
  prev = parseInt(prev, 10)
  if ((idx + 1) % 2 !== 0) {
    curr = (curr * 2)
      .toString()
      .split('')
      .reduce(function(p, c) {
        return (parseInt(p, 10) + parseInt(c, 10)) as any
      })
  }
  return prev + parseInt(curr, 10)
}, 0) %
  10 ===
0
)
}

Notice the boolean in there? i'm using this as a module for my index.ts which looks like this:

import { createReadStream } from 'fs'
import { createInterface } from 'readline'
import { getCompanyName } from './cardType'
import cardValidator from './cardValidator'

const lineReader = createInterface({
input: createReadStream('data/input.txt')
})

lineReader.on('line', (creditCard: string) => {
  var company = `${getCompanyName(creditCard)}: ${creditCard} (${cardValidator(
creditCard
)})`

console.log(company)
})

It currently outputs to the console something like this:

MasterCard: 5105105105105100 (true)
MasterCard: 5105105105105106 (false)

I want the true/false to be valid/invalid I've looked into it a little bit(w3) but don't know how to integrate anything into my algorithm as it requires you to declare a variable for both  true and false. any suggestions/answers would be much appreciated

Body:
You can simply use a ternary operator to include the strings you want directly in your output string:

var company = `${getCompanyName(creditCard)}: ${creditCard} (${cardValidator(creditCard) ? "valid" : "invalid"})`


问:
How to call a controller function inside a view in laravel 5
In laravel 4 i just used a function

```<code>$varbl = App::make("ControllerName")->FunctionName($params);
</code>```

to call a controller function from a my balde template(view page).
Now i'm using Laravel 5 to do a new project and i tried this method to call a controller function from my blade template .But its not working and showing some errors.
Is there any method to call a controller function from a view page in Laravel 5?

答:
I like and favor Khan Shahrukh way, it is better to create a helpers files with all your functions, then add it to your composer.json file:

```<code>"autoload": {
    "files": [
        "app/Http/Helpers/helpers.php"
    ]
},
</code>```

You can select the path that suits you, then dump-autoload composer to make it includes the new file.

For usability and clean work, after that you will be able to invoke your function on any view file OR project parts : Controller, Model.

If you decided to go with the public static method  Don't forget to add this line at the very top of your view:

```<code>use \App\Http\Controllers\ControllerName;
</code>```

Body:
In laravel 4 i just used a function

$varbl = App::make("ControllerName")->FunctionName($params);

to call a controller function from a my balde template(view page).
Now i'm using Laravel 5 to do a new project and i tried this method to call a controller function from my blade template .But its not working and showing some errors.
Is there any method to call a controller function from a view page in Laravel 5?

Body:
I like and favor Khan Shahrukh way, it is better to create a helpers files with all your functions, then add it to your composer.json file:

"autoload": {
    "files": [
        "app/Http/Helpers/helpers.php"
    ]
},

You can select the path that suits you, then dump-autoload composer to make it includes the new file.

For usability and clean work, after that you will be able to invoke your function on any view file OR project parts : Controller, Model.

If you decided to go with the public static method  Don't forget to add this line at the very top of your view:

use \App\Http\Controllers\ControllerName;


问:
Using rel="noopener" in window.open()
So I know that I can apply rel="noopener in an a tag when using target="_blank". But I'm trying to pass it as an argument to window.open(), ie:

window.open('http://cats.com', '_blank', 'rel=noopener')

however it doesn't seem to be working the way that I expected, as the opener object still exists on the window after the user clicks on the link.

Is there something I'm missing? Or cannot it not be done the way that I'm intending?

I've found some great articles but they don't quite address my use case as far as I can tell.

https://developer.mozilla.org/en-US/docs/Web/API/Window/open
https://mathiasbynens.github.io/rel-noopener/

Much appreciated.

答:
This worked for me:</p>

```<code>const a = document.createElement("a")
a.href = args.url
a.target = "_blank"
a.rel = "noopener"
a.click()
</code>```

Title: Using rel="noopener" in window.open()

Body:
This worked for me:

const a = document.createElement("a")
a.href = args.url
a.target = "_blank"
a.rel = "noopener"
a.click()


问:
How is CIL used to make network / http requests?
I can see a list of CIL instructions here:

https://en.wikipedia.org/wiki/List_of_CIL_instructions

My understanding is that CIL is run in the CLR. However, I can't see how any of these instructions can be used to make a http request (which is obviously possible in the CLR).

None of the codes seem to be about getting outside information.

What am I missing?

答:
What am I missing?

Your chain of logic goes like this:

All CLR methods of all types are implemented with a sequence of CIL instructions

CIL instructions can only perform certain tasks

Some tasks require combinations of instructions not found in CIL.

Therefore some tasks are impossible in a CLR method.

You then note that the conclusion is wrong, and correctly note that one of the steps in that chain of logic must be wrong.

The wrong one is the first one. There is no requirement that a method be implemented by a hunk of CIL that is then jitted into native code. In particular a C# method marked with the extern modifier is implemented by transferring control to the (presumably unmanaged code) DLL mentioned in the declaration.  Thus, code written in other languages that does stuff outside of the management of the CLR can be called from a program running under the CLR.


问:
Special Copy Paste in VBA
This is a Copy Paste question using VBA. I basically want to grab a number from many different workbooks. My problem is this number is contantly updating so I don't think I can have the last vesion of the number without opening the workbooks.
The workbooks are big and take time to open and load data (taking data from an external source (bloomberg)).
My first clue was to open the workbooks, then let them charge then taking the data from it. My problem is, I need to set up a timer to do so(and let my workbook load) and during this timer my workbook cannot upload the datas so I end up with my old datas...

So the only solution I found was to do two different macros. One open all the workbook, then the second close and save it and grab the data from it...

Do you guys have any better idea?

My problem is, the workbooks are so big I need to open them 5 by 5 maximum and do it every time...

I copy paste you my code, I know it is very basic, if you think of any better code or way to make it work, please let me know.

```<code>Sub OpenWorkbooks()
workbooks.Open Filename :="C/.../file1.xlsx"
workbooks.Open Filename :="C/.../file2.xlsx"
workbooks.Open Filename :="C/.../file3.xlsx"
.
.
End sub
</code>```

Now the one to close and then copy paste the value as written by someone else.

```<code>Sub GetNumber()
Dim wWbPath As String, WbName As String
Dim WsName As String, CellRef As String
Dim Ret As String

Workbooks("file1").Close SaveChanges:=True

wbPath = "C:/etc...."

WbName = "file1.xlsx"
WsName = "Sheet1"
CellRef = "AD30"

arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)

Worksheets("Sheet1").Range("A1") = ExecuteExcel4Macro(arg)

End sub
</code>```

As said do you think there is a better way to do it? I wanted to do the whole steps for each file but I cannot since the timer stop the refresh of my spreadhseet and I need a timer since my worksheets needs time to load.
So 1 - Open all , 2- close all and save all and copy the numbers... But I need to do it by batch cause if I open all it crashes...

My other question is, how could I make the code better? Ultimately I would like to have in my open workbook a spreadsheet where I would have all the paths for each worbook to open and copy/paste. then I would like a macro which loop the path, open the workbook wait (but timer not working...) then copy paste and close.

The altrnative is always looping the paths but by blocks. I will put all my paths on cells A1:A10 and I could have a loops opening the path present in A1:A10, then a second macro closing and saving the workbook with the path in A1:A10

Any ideas are welcome,

Thank you

答:
You can achieve this in different ways. One is to store the values in a sheet or database and every time that you want to refresh and get new values compare the new value to the old value and if it was different (cell value updated for sure) then continue the code. Just to make the code get out of waiting you should set a max time like an expiration time. I would do an iteration of 20 times, each for 5 seconds. So basically you should have a setup like this in your code:

```<code>for i=1 to 20
    newHour = Hour(Now())
    newMinute = Minute(Now())
    newSecond = Second(Now()) + 5
    waitTime = TimeSerial(newHour, newMinute, newSecond)
    ' ~~> get new value here and compare it to the old value

next i

Application.Wait waitTime

if newValue<>oldValue then
    exit for
else
    'do nothing, just wait
end if
</code>```

or you can simply let Windows take the control, finish the task and continue:

```<code>'~~> your code here before refresh
Activeworkbook.RefreshAll
DoEvents
'~~> rest of your code here after refresh
</code>```

DoEvents let's Windows to momentarily take a break from Macro to process all pending events before returning to the macro. That means it will refresh your workbook from the external resource and then continue executing the rest of code.

If you are using Excel 2010 and higher, there is a control that may work better than DoEvents:

```<code> ThisWorkbook.RefreshAll 'or activeworkbook, choose as you need
 Application.CalculateUntilAsyncQueriesDone 'the code execution will halt here until the refresh job is done
</code>```

Title: Special Copy Paste in VBA

Body:
This is a Copy Paste question using VBA. I basically want to grab a number from many different workbooks. My problem is this number is contantly updating so I don't think I can have the last vesion of the number without opening the workbooks.
The workbooks are big and take time to open and load data (taking data from an external source (bloomberg)).
My first clue was to open the workbooks, then let them charge then taking the data from it. My problem is, I need to set up a timer to do so(and let my workbook load) and during this timer my workbook cannot upload the datas so I end up with my old datas...

So the only solution I found was to do two different macros. One open all the workbook, then the second close and save it and grab the data from it...

Do you guys have any better idea?

My problem is, the workbooks are so big I need to open them 5 by 5 maximum and do it every time...

I copy paste you my code, I know it is very basic, if you think of any better code or way to make it work, please let me know.

Sub OpenWorkbooks()
workbooks.Open Filename :="C/.../file1.xlsx"
workbooks.Open Filename :="C/.../file2.xlsx"
workbooks.Open Filename :="C/.../file3.xlsx"
.
.
End sub

Now the one to close and then copy paste the value as written by someone else.

Sub GetNumber()
Dim wWbPath As String, WbName As String
Dim WsName As String, CellRef As String
Dim Ret As String

Workbooks("file1").Close SaveChanges:=True

wbPath = "C:/etc...."

WbName = "file1.xlsx"
WsName = "Sheet1"
CellRef = "AD30"

arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)

Worksheets("Sheet1").Range("A1") = ExecuteExcel4Macro(arg)

End sub

As said do you think there is a better way to do it? I wanted to do the whole steps for each file but I cannot since the timer stop the refresh of my spreadhseet and I need a timer since my worksheets needs time to load.
So 1 - Open all , 2- close all and save all and copy the numbers... But I need to do it by batch cause if I open all it crashes...

My other question is, how could I make the code better? Ultimately I would like to have in my open workbook a spreadsheet where I would have all the paths for each worbook to open and copy/paste. then I would like a macro which loop the path, open the workbook wait (but timer not working...) then copy paste and close.

The altrnative is always looping the paths but by blocks. I will put all my paths on cells A1:A10 and I could have a loops opening the path present in A1:A10, then a second macro closing and saving the workbook with the path in A1:A10

Any ideas are welcome,

Thank you

Body:
You can achieve this in different ways. One is to store the values in a sheet or database and every time that you want to refresh and get new values compare the new value to the old value and if it was different (cell value updated for sure) then continue the code. Just to make the code get out of waiting you should set a max time like an expiration time. I would do an iteration of 20 times, each for 5 seconds. So basically you should have a setup like this in your code:

for i=1 to 20
    newHour = Hour(Now())
    newMinute = Minute(Now())
    newSecond = Second(Now()) + 5
    waitTime = TimeSerial(newHour, newMinute, newSecond)
    ' ~~> get new value here and compare it to the old value

next i

Application.Wait waitTime

if newValue<>oldValue then
    exit for
else
    'do nothing, just wait
end if

or you can simply let Windows take the control, finish the task and continue:

'~~> your code here before refresh
Activeworkbook.RefreshAll
DoEvents
'~~> rest of your code here after refresh

DoEvents let's Windows to momentarily take a break from Macro to process all pending events before returning to the macro. That means it will refresh your workbook from the external resource and then continue executing the rest of code.

If you are using Excel 2010 and higher, there is a control that may work better than DoEvents:

 ThisWorkbook.RefreshAll 'or activeworkbook, choose as you need
 Application.CalculateUntilAsyncQueriesDone 'the code execution will halt here until the refresh job is done


问:
Google Maps Api v2 Android Error loading map on Play Store
I am working with google maps API but when i upload my APK to Play Store my map doesn't load, when i run my app directly on my device it works perfect. When i generate my Signet APK and test it on my device (without Play Store, just sending my APK to my device and installing it manually) it works perfect, but if i publish the exactly same APK to Play Store it isnt visible after i downloaod it.

my app gradle

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "development.senseit.com.mapasinteca"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 102
        versionName "1.0.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    signingConfigs {
        release {
            storeFile file('C:\\Users\\jsalazar\\Desktop\\Certificados\\Android\\mapasInteca.jks')
            storePassword '****'
            keyAlias 'mapasinteca'
            keyPassword '****'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.release
        }
        release {
            signingConfig signingConfigs.release
        }
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.android.gms:play-services-maps:11.6.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
}
</code>```

My google API key is correct.
I have 2 finger print certificate added to google console, one for debug and one for release (i already trying removing the debug one).

答: I solved my problem adding one SHA-1 that i was missing, it was on Google Play Console (number 1 on image) i was only adding number 2

Body:
I am working with google maps API but when i upload my APK to Play Store my map doesn't load, when i run my app directly on my device it works perfect. When i generate my Signet APK and test it on my device (without Play Store, just sending my APK to my device and installing it manually) it works perfect, but if i publish the exactly same APK to Play Store it isnt visible after i downloaod it.

my app gradle

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "development.senseit.com.mapasinteca"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 102
        versionName "1.0.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    signingConfigs {
        release {
            storeFile file('C:\\Users\\jsalazar\\Desktop\\Certificados\\Android\\mapasInteca.jks')
            storePassword '****'
            keyAlias 'mapasinteca'
            keyPassword '****'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.release
        }
        release {
            signingConfig signingConfigs.release
        }
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.android.gms:play-services-maps:11.6.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
}

My google API key is correct.
I have 2 finger print certificate added to google console, one for debug and one for release (i already trying removing the debug one).


问:
Save an std::vector<int> to file
I noticed, that when using:

```<code>std::vector<int> v(100000);
...
std::ofstream outfile("outfile.dat", std::ios::out | std::ofstream::binary);
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(outfile));
outfile.close();
</code>```

my std::vector<int> is not serialized as raw bytes data (4 bytes per int) but as string, i.e. the string representation of each integer is saved to disk, which I don't want.

How to save a std::vector<int> as binary data?

(Note: I'd like to learn it with standard C++03, before learning new methods for it).

答:
To write binary data, use std::ostream::write() instead of std::ostream_iterator (which uses operator<< internally, thus formatted output), eg:

```<code>std::vector<int> v(100000);
...
std::ofstream outfile("outfile.dat", std::ofstream::binary);
outfile.write(reinterpret_cast<const char*>(v.data() /* or &v[0] pre-C++11 */), sizeof(int) * v.size());
outfile.close();
</code>```

Title: Save an std::vector<int> to file

Body:
I noticed, that when using:

std::vector<int> v(100000);
...
std::ofstream outfile("outfile.dat", std::ios::out | std::ofstream::binary);
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(outfile));
outfile.close();

my std::vector<int> is not serialized as raw bytes data (4 bytes per int) but as string, i.e. the string representation of each integer is saved to disk, which I don't want.

How to save a std::vector<int> as binary data?

(Note: I'd like to learn it with standard C++03, before learning new methods for it).

Body:
To write binary data, use std::ostream::write() instead of std::ostream_iterator (which uses operator<< internally, thus formatted output), eg:

std::vector<int> v(100000);
...
std::ofstream outfile("outfile.dat", std::ofstream::binary);
outfile.write(reinterpret_cast<const char*>(v.data() /* or &v[0] pre-C++11 */), sizeof(int) * v.size());
outfile.close();


问:
System.OutOfMemoryException with WCF during request
I have a server that is throwing an System.OutOfMemoryException, from what i can tell, during the transmission of data during a request.  From looking at this trace, is my assumption right?

```<code>System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
  at System.Net.Security.NegoState.ProcessAuthentication(LazyAsyncResult lazyResult)
  at System.Net.Security.NegotiateStream.AuthenticateAsServer(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
  at System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeAcceptor.OnAcceptUpgrade(Stream stream, SecurityMessageProperty& remoteSecurity)
  at System.ServiceModel.Channels.StreamSecurityUpgradeAcceptorBase.AcceptUpgrade(Stream stream)
  at System.ServiceModel.Channels.InitialServerConnectionReader.UpgradeConnection(IConnection connection, StreamUpgradeAcceptor upgradeAcceptor, IDefaultCommunicationTimeouts defaultTimeouts)
  at System.ServiceModel.Channels.ServerSessionPreambleConnectionReader.ServerFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
  at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
  at System.ServiceModel.Channels.CommunicationObject.Open()
  at System.ServiceModel.Dispatcher.ChannelHandler.OpenAndEnsurePump()
  at System.ServiceModel.Dispatcher.ChannelHandler.OpenAndEnsurePump(Object state)
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.OnSecurityContextCallback(Object o)
  at System.Security.SecurityContext.Run(SecurityContext securityContext, ContextCallback callback, Object state)
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke()
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks()
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state)
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
  at System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
  at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</code>```

I have maxArrayLength, and maxStringContentLength set really high in my config file.  Is it possible that one of these is extremely huge, and causing the channel to throw this error?  This is a .NET WCF service that is communicating locally through IPC with another process.

答:
Given that this is a production issue and its happening in different places sporadically I'm guessing you're having a high memory utilization issue. I would obtain a Memory dump of the system and use WinDbg to see what's causing this.

You can use proc dump  or Debug Diag to do this (but make sure you use the 32 or 64 bit one depending on which one you need).

If you've never done analysis on memory before (and its really not easy) then you might want to take a look at this article

Body:
I have a server that is throwing an System.OutOfMemoryException, from what i can tell, during the transmission of data during a request.  From looking at this trace, is my assumption right?

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
  at System.Net.Security.NegoState.ProcessAuthentication(LazyAsyncResult lazyResult)
  at System.Net.Security.NegotiateStream.AuthenticateAsServer(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
  at System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeAcceptor.OnAcceptUpgrade(Stream stream, SecurityMessageProperty& remoteSecurity)
  at System.ServiceModel.Channels.StreamSecurityUpgradeAcceptorBase.AcceptUpgrade(Stream stream)
  at System.ServiceModel.Channels.InitialServerConnectionReader.UpgradeConnection(IConnection connection, StreamUpgradeAcceptor upgradeAcceptor, IDefaultCommunicationTimeouts defaultTimeouts)
  at System.ServiceModel.Channels.ServerSessionPreambleConnectionReader.ServerFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
  at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
  at System.ServiceModel.Channels.CommunicationObject.Open()
  at System.ServiceModel.Dispatcher.ChannelHandler.OpenAndEnsurePump()
  at System.ServiceModel.Dispatcher.ChannelHandler.OpenAndEnsurePump(Object state)
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.OnSecurityContextCallback(Object o)
  at System.Security.SecurityContext.Run(SecurityContext securityContext, ContextCallback callback, Object state)
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke()
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks()
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state)
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
  at System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
  at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

I have maxArrayLength, and maxStringContentLength set really high in my config file.  Is it possible that one of these is extremely huge, and causing the channel to throw this error?  This is a .NET WCF service that is communicating locally through IPC with another process.


问:
ImportError: cannot import name 'load_entry_point' (PIP)
How can i fix it ?
Thank you for your helps.</p>

```<code>MacBook-Air:github synsx$ pip
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/bin/pip", line 6, in <module>
    from pkg_resources import load_entry_point
ImportError: cannot import name 'load_entry_point'
</code>```

答:
I had the same problem and fixed it by giving access permission to python package directory:</p>

```<code>sudo chmod -R a+rX /usr/lib/python3.6/site-packages
</code>```

Body:
How can i fix it ?
Thank you for your helps.

MacBook-Air:github synsx$ pip
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/bin/pip", line 6, in <module>
    from pkg_resources import load_entry_point
ImportError: cannot import name 'load_entry_point'

Body:
I had the same problem and fixed it by giving access permission to python package directory:

sudo chmod -R a+rX /usr/lib/python3.6/site-packages


问:
Use window.open but block use of window.opener
A while back I ran across an interesting security hole

```<code><a href="http://someurl.here" target="_blank">Link</a>
</code>```

Looks innocuous enough, but there's a hole because, by default, the page that's being opened is allowing the opened page to call back into it via window.opener. There are some restrictions, being cross-domain, but there's still some mischief that can be done

```<code>window.opener.location = 'http://gotcha.badstuff';
</code>```

Now, HTML has a workaround

```<code><a href="http://someurl.here" target="_blank" rel="noopener noreferrer">Link</a>
</code>```

That prevents the new window from having window.opener passed to it. That's fine and good for HTML, but what if you're using window.open?

```<code><button type="button" onclick="window.open('http://someurl.here', '_blank');">
    Click Me
</button>
</code>```

How would you block the use of window.opener being passed here?

Body:
A while back I ran across an interesting security hole

Link

Looks innocuous enough, but there's a hole because, by default, the page that's being opened is allowing the opened page to call back into it via window.opener. There are some restrictions, being cross-domain, but there's still some mischief that can be done

window.opener.location = 'http://gotcha.badstuff';

Now, HTML has a workaround

Link

That prevents the new window from having window.opener passed to it. That's fine and good for HTML, but what if you're using window.open?

<button type="button" onclick="window.open('http://someurl.here', '_blank');">
    Click Me
</button>

How would you block the use of window.opener being passed here?


问:
Making a "page change" in a single page web app over a WebSocket using php
I am trying to make a single page web app that runs over a websocket for all server request. After the user logs in, I want the page to change the html to display a dashboard (first page).

I have a template for the dashboard already build from a previous version. I need to find a way to input database info into template and send the page over the websocket as a string for the javascript to display.

I don't know how to fill the template using php classes without hard coding it into the class, then turning it into a string so I can send it. The dashboard is very complex and has dynamically built menus for each users per their settings and permissions.

Am I looking at this whole problem wrong? I have some experience with MVC from ruby on rails/node.js, but unfortunately this app is stuck using php. Can I use a framework with the socket? Should I have the JS load the template through https and send the data over the socket? (The JS guy would not like that).

I am running Ubuntu, apache2, php7, Ratchet WebSocket(wss), composer, and MySQL all on AWS.

答:
I would definitely let the frontend get the required data. You could use php as a backend to test the authentication, parse the request, get the data from the database and send it to the frontend. The frontend then would need to update the application using dom manipulation (think jQuery).

Or, php could send a generated view that would be shown in a div in the frontend.

In this setup, I would not recommend websockets, but just plain AJAX.

From what I gather from your question, you might be better of using a real SPA framework like AngularJS. It it just better in using the data you will get from the backend. You could then choose to use a PHP backend using AJAX or a Websocket backend like nodejs.


问:
d3 selection confusion with exit() and remove()
So I'm working through some d3 tutorials and learning a bit about why things work the way they do, and I've run into a peculiar instance of selection not behaving as expected. So I'm wondering if anyone can explain this to me.

```<code>var sales = [
    { product: 'Hoodie',  count: 7 },
    { product: 'Jacket',  count: 6 },
    { product: 'Snuggie', count: 9 },
];

var rects = svg.selectAll('rect')
  .data(sales).enter();

var maxCount = d3.max(sales, function(d, i) {
    return d.count;
});
var x = d3.scaleLinear()
    .range([0, 300])
    .domain([0, maxCount]);
var y = d3.scaleBand()
    .rangeRound([0, 75])
    .domain(sales.map(function(d, i) {
        return d.product;
    }));

rects.append('rect')
    .attr('x', x(0))
    .attr('y', function(d, i) {
        return y(d.product);
    })
    .attr('height', y.bandwidth())
    .attr('width', function(d, i) {
        return x(d.count);
    });
</code>```

This all works good and fine, generates 3 horizontal bars that correspond to the data in sales, but here's where I'm seeing the ambiguity:

```<code>sales.pop();

rects.data(sales).exit().remove();
</code>```

The last line is supposed to remove the bar that was popped, from the visual but it doesn't work. I think that there must be something going on with the d3 selection that I'm missing, because this does work:

```<code>d3.selectAll('rect').data(sales).exit().remove();
</code>```

Also when I break out the first one that doesn't work, it does appear to be selecting the correct element on exit, but just doesn't seem to be removing it. Anyway if anyone can explain what's going on here that would be very helpful, thanks!

Note: using d3 v4

答:
This is your rects selection:

```<code>var rects = svg.selectAll('rect')
    .data(sales).enter();
</code>```

So, when you do this:

```<code>rects.data(sales).exit().remove();
</code>```

You are effectively doing this:

```<code>svg.selectAll('rect')
    .data(sales)
    .enter()
    .data(sales)
    .exit()
    .remove();
</code>```

Thus, you are binding data, calling enter, binding data again and calling exit on top of all that! Wow!

Solution: just create a regular, old-fashioned "update" selection:

```<code>var rects = svg.selectAll('rect')
    .data(sales);
</code>```

Here is a basic demo with your code, calling exit after 2 seconds:

var svg = d3.select("svg")

var sales = [{
  product: 'Hoodie',
  count: 7
}, {
  product: 'Jacket',
  count: 6
}, {
  product: 'Snuggie',
  count: 9
}, ];

draw();

function draw() {

  var rects = svg.selectAll('rect')
    .data(sales);

  var maxCount = d3.max(sales, function(d, i) {
    return d.count;
  });
  var x = d3.scaleLinear()
    .range([0, 300])
    .domain([0, maxCount]);
  var y = d3.scaleBand()
    .rangeRound([0, 75])
    .domain(sales.map(function(d, i) {
      return d.product;
    }))
    .padding(.2);

  var rectsEnter = rects.enter().append('rect')
    .attr('x', x(0))
    .attr('y', function(d, i) {
      return y(d.product);
    })
    .attr('height', y.bandwidth())
    .attr('width', function(d, i) {
      return x(d.count);
    });

  rects.exit().remove();

}

d3.timeout(function() {
  sales.pop();
  draw()
}, 2000)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg></code>```

Body:
So I'm working through some d3 tutorials and learning a bit about why things work the way they do, and I've run into a peculiar instance of selection not behaving as expected. So I'm wondering if anyone can explain this to me.

var sales = [
    { product: 'Hoodie',  count: 7 },
    { product: 'Jacket',  count: 6 },
    { product: 'Snuggie', count: 9 },
];

var rects = svg.selectAll('rect')
  .data(sales).enter();

var maxCount = d3.max(sales, function(d, i) {
    return d.count;
});
var x = d3.scaleLinear()
    .range([0, 300])
    .domain([0, maxCount]);
var y = d3.scaleBand()
    .rangeRound([0, 75])
    .domain(sales.map(function(d, i) {
        return d.product;
    }));

rects.append('rect')
    .attr('x', x(0))
    .attr('y', function(d, i) {
        return y(d.product);
    })
    .attr('height', y.bandwidth())
    .attr('width', function(d, i) {
        return x(d.count);
    });

This all works good and fine, generates 3 horizontal bars that correspond to the data in sales, but here's where I'm seeing the ambiguity:

sales.pop();

rects.data(sales).exit().remove();

The last line is supposed to remove the bar that was popped, from the visual but it doesn't work. I think that there must be something going on with the d3 selection that I'm missing, because this does work:

d3.selectAll('rect').data(sales).exit().remove();

Also when I break out the first one that doesn't work, it does appear to be selecting the correct element on exit, but just doesn't seem to be removing it. Anyway if anyone can explain what's going on here that would be very helpful, thanks!

Note: using d3 v4

Body:
This is your rects selection:

var rects = svg.selectAll('rect')
    .data(sales).enter();

So, when you do this:

rects.data(sales).exit().remove();

You are effectively doing this:

svg.selectAll('rect')
    .data(sales)
    .enter()
    .data(sales)
    .exit()
    .remove();

Thus, you are binding data, calling enter, binding data again and calling exit on top of all that! Wow!

Solution: just create a regular, old-fashioned "update" selection:

var rects = svg.selectAll('rect')
    .data(sales);

Here is a basic demo with your code, calling exit after 2 seconds:

var svg = d3.select("svg")

var sales = [{
  product: 'Hoodie',
  count: 7
}, {
  product: 'Jacket',
  count: 6
}, {
  product: 'Snuggie',
  count: 9
}, ];

draw();

function draw() {

  var rects = svg.selectAll('rect')
    .data(sales);

  var maxCount = d3.max(sales, function(d, i) {
    return d.count;
  });
  var x = d3.scaleLinear()
    .range([0, 300])
    .domain([0, maxCount]);
  var y = d3.scaleBand()
    .rangeRound([0, 75])
    .domain(sales.map(function(d, i) {
      return d.product;
    }))
    .padding(.2);

  var rectsEnter = rects.enter().append('rect')
    .attr('x', x(0))
    .attr('y', function(d, i) {
      return y(d.product);
    })
    .attr('height', y.bandwidth())
    .attr('width', function(d, i) {
      return x(d.count);
    });

  rects.exit().remove();

}

d3.timeout(function() {
  sales.pop();
  draw()
}, 2000)

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


问:
C# to VB.net conversion
Can someone please help me convert this to VB.net:

```<code>HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];
</code>```

Thanks

答:
```<code>Dim jpeg_image_upload As HttpPostedFile = Request.Files("Filedata")
</code>```

Title: C# to VB.net conversion

Body:
Can someone please help me convert this to VB.net:

HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];

Thanks


问:
Modifying Info.plist's CFBundleVersion in Xcode 5 with Asset Library enabled
With Xcode 5's new Asset Library, adding images and organizing them has never been easier. However, it seems as if it has broken some scripts I use for creating builds.

I have a script within my Run Script Phase that sets the CFBundleVersion to be the current timestamp within the plist. In the script, I execute this statement:

```<code>/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $timestamp" $BUILT_PRODUCTS_DIR/$INFOPLIST_PATH
</code>```

However, when this gets executed, the following statement displays:

```<code>Set: Entry, ":CFBundleVersion", Does Not Exist
File Doesn't Exist, Will Create: /Users/SpacePyro/Library/DerivedData/BundleTest-duikdqngfmrovnagrcsvdcuxxstz/Build/Products/Debug-iphoneos/BundleTest.app/Info.plist
</code>```

It seems like this happens on clean builds. The plist doesn't seem to get generated until midway through the build, presumably due to the Asset Libraries.

I've also used this command, and while it doesn't throw the error, it still blows away my changes (assume INFO_PLIST="${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/Info"):

```<code>defaults write $INFO_PLIST CFBundleVersion $timestamp
</code>```

This used to not be the case when I started using the Asset Library to organize my app icons and splash images. Anyone know why this happens? And better yet, is there a workaround to add this value to the plist? I've already tried placing the script in a pre-action build phase, as well as the post-action build phase. I've also tried running the command after the build has completed, but when I try to codesign and package it up, it says that the signature is invalid due to plist modification.

If no reasonable solution exists, I guess I could always de-migrate from Asset Libraries until I can get my scripts to work.

答:
I had similar issue once, and here is what finally helped me out:

```<code>buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "${INFOPLIST_FILE}")
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "${INFOPLIST_FILE}"
</code>```

(Use INFOPLIST_FILE directly, not $BUILT_PRODUCTS_DIR/$INFOPLIST_PATH)

Hope this could be useful .

Body:
With Xcode 5's new Asset Library, adding images and organizing them has never been easier. However, it seems as if it has broken some scripts I use for creating builds.

I have a script within my Run Script Phase that sets the CFBundleVersion to be the current timestamp within the plist. In the script, I execute this statement:

/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $timestamp" $BUILT_PRODUCTS_DIR/$INFOPLIST_PATH

However, when this gets executed, the following statement displays:

Set: Entry, ":CFBundleVersion", Does Not Exist
File Doesn't Exist, Will Create: /Users/SpacePyro/Library/DerivedData/BundleTest-duikdqngfmrovnagrcsvdcuxxstz/Build/Products/Debug-iphoneos/BundleTest.app/Info.plist

It seems like this happens on clean builds. The plist doesn't seem to get generated until midway through the build, presumably due to the Asset Libraries.

I've also used this command, and while it doesn't throw the error, it still blows away my changes (assume INFO_PLIST="${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/Info"):

defaults write $INFO_PLIST CFBundleVersion $timestamp

This used to not be the case when I started using the Asset Library to organize my app icons and splash images. Anyone know why this happens? And better yet, is there a workaround to add this value to the plist? I've already tried placing the script in a pre-action build phase, as well as the post-action build phase. I've also tried running the command after the build has completed, but when I try to codesign and package it up, it says that the signature is invalid due to plist modification.

If no reasonable solution exists, I guess I could always de-migrate from Asset Libraries until I can get my scripts to work.

Body:
I had similar issue once, and here is what finally helped me out:

buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "${INFOPLIST_FILE}")
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "${INFOPLIST_FILE}"

(Use INFOPLIST_FILE directly, not $BUILT_PRODUCTS_DIR/$INFOPLIST_PATH)

Hope this could be useful .


问:
=LEFT(H2,5) To show data for all rows and stop at last row of data
Hi could someone enlighten me with some VBA code to insert formula =LEFT(H2,5) into column M and then stop at the last row of data.
The data it will be referencing will be inserted from the web so when i refresh the data pull the rows could be more or less so it can't be a fixed without using VB

Thanks
Rhys

答:
Would a while loop work for you?

```<code>Dim i As Integer
i = 2 'starting row number
While Cells(i, 1).Value <> "" 'Empty row
    Cells(i, 13).Formula = "=LEFT(H2,5)" 'replace this with something for that row, concatenating i to H will work i think.
    i = i + 1
Wend
</code>```

You'll also want to put this code to whenever the data is refreshed so it inserts the formula to all rows again.

Body:
Would a while loop work for you?

Dim i As Integer
i = 2 'starting row number
While Cells(i, 1).Value <> "" 'Empty row
    Cells(i, 13).Formula = "=LEFT(H2,5)" 'replace this with something for that row, concatenating i to H will work i think.
    i = i + 1
Wend

You'll also want to put this code to whenever the data is refreshed so it inserts the formula to all rows again.


问:
JavaFx: Sizing, when a Pane contains text
In JavaFX, I have a Label (or TextFlow) inside of an AnchorPane (or StackPane), inside of a container Pane.

The container Pane has infinite height, but its width is fixed to be anything I want.

I need:

1) The AnchorPane's width to fill all of the available space, but not greater than the label's width when it fits all in one line.

2) The Label to be multiline (wrap=true) and fill all of the available space.

3) The AnchorPane's height to be equal to the height of the Label.

The code setup:

```<code>Pane rootPane = new Pane();
rootPane.setBackground(new Background(new BackgroundFill(Color.FIREBRICK, CornerRadii.EMPTY, Insets.EMPTY)));
AnchorPane anchorPane = new AnchorPane();
anchorPane.setBackground(new Background(new BackgroundFill(Color.FORESTGREEN, CornerRadii.EMPTY, Insets.EMPTY)));
Label text = new Label("text text text text text text text text text text text");
anchorPane.getChildren().add(text);
rootPane.getChildren().add(anchorPane);
</code>```

Or, instead of a label I can have:

```<code>TextFlow text = new TextFlow(new Text("text text text text text text text text text text text"));
</code>```

I've wasted hours on this problem. This is so easy in HTML... How can I achieve this?

答:
Code

```<code>import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Pane rootPane = new Pane();

        Label text = new Label();
        text.setWrapText(true);
        text.setText("text text text text text text text text text text text");

        AnchorPane anchorPane = new AnchorPane();
        anchorPane.getChildren().add(text);
        anchorPane.setBackground(new Background(new BackgroundFill(Color.FORESTGREEN, CornerRadii.EMPTY, Insets.EMPTY)));

        rootPane.getChildren().add(anchorPane);
        rootPane.setBackground(new Background(new BackgroundFill(Color.FIREBRICK, CornerRadii.EMPTY, Insets.EMPTY)));

        primaryStage.setScene(new Scene(rootPane, 300, 275));
        primaryStage.show();

        rootPane.widthProperty().addListener(new ChangeListener<Number>() {

            private double textWidth;

            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {

                if(text.getWidth() > 0 && textWidth == 0) {
                    textWidth = text.getWidth();
                }

                if(textWidth > 0 && textWidth > rootPane.getWidth())
                {
                    text.setPrefWidth(rootPane.getWidth());
                }else
                {
                    text.setPrefWidth(Label.USE_COMPUTED_SIZE);
                }
            }
        });
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Result

Body:
In JavaFX, I have a Label (or TextFlow) inside of an AnchorPane (or StackPane), inside of a container Pane.

The container Pane has infinite height, but its width is fixed to be anything I want.

I need:

1) The AnchorPane's width to fill all of the available space, but not greater than the label's width when it fits all in one line.

2) The Label to be multiline (wrap=true) and fill all of the available space.

3) The AnchorPane's height to be equal to the height of the Label.

The code setup:

Pane rootPane = new Pane();
rootPane.setBackground(new Background(new BackgroundFill(Color.FIREBRICK, CornerRadii.EMPTY, Insets.EMPTY)));
AnchorPane anchorPane = new AnchorPane();
anchorPane.setBackground(new Background(new BackgroundFill(Color.FORESTGREEN, CornerRadii.EMPTY, Insets.EMPTY)));
Label text = new Label("text text text text text text text text text text text");
anchorPane.getChildren().add(text);
rootPane.getChildren().add(anchorPane);

Or, instead of a label I can have:

TextFlow text = new TextFlow(new Text("text text text text text text text text text text text"));

I've wasted hours on this problem. This is so easy in HTML... How can I achieve this?

Body:
Code

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Pane rootPane = new Pane();

        Label text = new Label();
        text.setWrapText(true);
        text.setText("text text text text text text text text text text text");

        AnchorPane anchorPane = new AnchorPane();
        anchorPane.getChildren().add(text);
        anchorPane.setBackground(new Background(new BackgroundFill(Color.FORESTGREEN, CornerRadii.EMPTY, Insets.EMPTY)));

        rootPane.getChildren().add(anchorPane);
        rootPane.setBackground(new Background(new BackgroundFill(Color.FIREBRICK, CornerRadii.EMPTY, Insets.EMPTY)));

        primaryStage.setScene(new Scene(rootPane, 300, 275));
        primaryStage.show();

        rootPane.widthProperty().addListener(new ChangeListener<Number>() {

            private double textWidth;

            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {

                if(text.getWidth() > 0 && textWidth == 0) {
                    textWidth = text.getWidth();
                }

                if(textWidth > 0 && textWidth > rootPane.getWidth())
                {
                    text.setPrefWidth(rootPane.getWidth());
                }else
                {
                    text.setPrefWidth(Label.USE_COMPUTED_SIZE);
                }
            }
        });
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Result


问:
iOS app - size of the app is too big after install SDK from POD
I want to add an 80 MB framework to my iOS App that is currently about 30 MB. Will the size of my app be 110 MB?

答:
Short answer:

You'll have to add the SDK and compile the code to see what your resulting size is.

Details:

When you build an app, the compiler rewrites it into machine-readable code, doing some further magic to optimize the end result. Because of this, the size of your code files, including SDK files, has no relationship whatsoever to the completed app executable's size.

For one example, your code may have tons of comments in it. However, the compiler wouldn't even look at those comments when producing the final app.

Additionally, an app compiled for debug will be larger than the same app compiled for release. That's because the compiler will leave some things in the debug version for troubleshooting that it does not include in a final release version.

As noted in some of the comments, when you submit your code to the Store, it may be further "trimmed", possibly ending up with an even smaller size. (In very simple terms, Apple has found a way to share common base code between apps on a device. The common code is removed from apps submitted to the store, since the apps can use that central base code instead. This results in smaller, faster apps.)

There are various things you can do to optimize an app into the smallest possible footprint, just as there are ways you can optimize an app to be faster or more responsive. Doing so, though, is totally dependent on the tools you're using, the statements you use, the way you import items, etc. You would have to consider these items individually. (For example, are you using the best structure for a task - array?, dictionary?, set? Are you using the most efficient method to perform a task? There's this whole "Big-O" thing... ;)

ContentLicense: CC BY-SA 4.0


问:
Serverless: Deploy to same api from different yml
I have api api.demo

It has following structure

```<code>api.demo
   /service1:
     GET /test1
     GET /test2
     ...
  /service2
     GET /test1
     GET /test2
     ...
</code>```

I have two separate folders service1, service2
Each one having its own serverless.yml file
When I deploy It creates tow separate api's in api gateway as below

```<code>api.demo(id1)
   /service1:
     GET /test1
     GET /test2
     ...
api.demo(id2)
   /service2
     GET /test1
     GET /test2
</code>```

How to update service2 to take same api endpoint api.demo(id1)?

How I can achieve this?
Any pointers would be helpful.

答:
Simply use a custom domain name: http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html

You can map base path to an API, so you could map /service1 to the first API and /service2 to the second API. Clients would be hitting a custom domain name rather than the default execute-api endpoint that we provide.

Body:
I have api api.demo

It has following structure

api.demo
   /service1:
     GET /test1
     GET /test2
     ...
  /service2
     GET /test1
     GET /test2
     ...

I have two separate folders service1, service2
Each one having its own serverless.yml file
When I deploy It creates tow separate api's in api gateway as below

api.demo(id1)
   /service1:
     GET /test1
     GET /test2
     ...
api.demo(id2)
   /service2
     GET /test1
     GET /test2

How to update service2 to take same api endpoint api.demo(id1)?

How I can achieve this?
Any pointers would be helpful.


答:
```<code>Dim x As Long

x = Application.CountA(ActiveSheet.Columns(13))

ActiveSheet.Cells(2, 13) = "=LEFT(H2,5)"

ActiveSheet.Cells(2, 13).Resize(x - 1).Formula = ActiveSheet.Cells(2, 13).Formula
</code>```

use excel function CountA to get the total number of row that you need to populate and assign that number to x

then put the actual formula on cells M2 then copy the formula until the last row using resize function

Title: =LEFT(H2,5) To show data for all rows and stop at last row of data

Body:
Hi could someone enlighten me with some VBA code to insert formula =LEFT(H2,5) into column M and then stop at the last row of data.
The data it will be referencing will be inserted from the web so when i refresh the data pull the rows could be more or less so it can't be a fixed without using VB

Thanks
Rhys

Body:
Dim x As Long

x = Application.CountA(ActiveSheet.Columns(13))

ActiveSheet.Cells(2, 13) = "=LEFT(H2,5)"

ActiveSheet.Cells(2, 13).Resize(x - 1).Formula = ActiveSheet.Cells(2, 13).Formula

use excel function CountA to get the total number of row that you need to populate and assign that number to x

then put the actual formula on cells M2 then copy the formula until the last row using resize function


答:
it will be:</p>

```<code>Dim jpeg_image_upload as HttpPostedFile
jpeg_image_upload = Request.Files("Filedata")
</code>```

Title: C# to VB.net conversion

Body:
it will be:

Dim jpeg_image_upload as HttpPostedFile
jpeg_image_upload = Request.Files("Filedata")