问:
mongodb collection fetch information with criteria
I'm facing the following issue:

I have this data in a collection in mongoDB

```<code>   { Node: '2', Type: 'temperature', Value: '25.9', _id: 5936f90c81c543363d42f598 },
   { Node: '3', Type: 'temperature', Value: '31.0', _id: 5936f90c81c543363d42f599 },
   { Node: '1', Type: 'humidity', Value: '45.2', _id: 5936f90c81c543363d42f59a },
   { Node: '2', Type: 'humidity', Value: '55.3', _id: 5936f90c81c543363d42f59b }
</code>```

I want to fetch it by type.

Can't find what I'm doing wrong in my code...

```<code>var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  if (err) throw err;
  var collection = db.collection('readings');
  collection.find({}).toArray(function(err, result) {
    if (err) throw err;
    //console.log(result); //mostrar os resultados
    var numTemps = 0;
    result.forEach(function(err,doc){
      if ("temperature" in result) {
        numTemps = numTemps + 1;
      };
    });
    var numHums = 0;
    result.forEach(function(err,doc){
      if ("humidity" in result) {
        numHums = numHums + 1;
      };
    });
    console.log("Temps: " + numTemps);
    console.log("Hums: " + numHums);
    db.close();
  });
});
</code>```

答:
Thank you all.

Managed to solve this with the following:

```<code>collection.find({}).toArray(function(err, result) {
if (err) throw err;
//console.log(result);
var numHums = 0;
var numTemps = 0;
var i = 0;
result.forEach(function(err,values){
  console.log(result[i].Type);
  if (result[i].Type == 'humidity') {
    numHums = numHums + 1;
  }
  if (result[i].Type == 'temperature') {
    numTemps = numTemps + 1;
  };
  i = i + 1;
});
console.log("Temps: " + numTemps);
console.log("Hums: " + numHums);
db.close();
});
</code>```

edit:

changed the foreach according to the suggestion of the users here:

```<code>result.forEach(function(values){
 console.log(values.Type);
 if (values.Type == 'humidity') {
  numHums = numHums + 1;
 }
 if (values.Type == 'temperature') {
  numTemps = numTemps + 1;
 };
});
</code>```

Body:
I'm facing the following issue:

I have this data in a collection in mongoDB

   { Node: '2', Type: 'temperature', Value: '25.9', _id: 5936f90c81c543363d42f598 },
   { Node: '3', Type: 'temperature', Value: '31.0', _id: 5936f90c81c543363d42f599 },
   { Node: '1', Type: 'humidity', Value: '45.2', _id: 5936f90c81c543363d42f59a },
   { Node: '2', Type: 'humidity', Value: '55.3', _id: 5936f90c81c543363d42f59b }

I want to fetch it by type.

Can't find what I'm doing wrong in my code...

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  if (err) throw err;
  var collection = db.collection('readings');
  collection.find({}).toArray(function(err, result) {
    if (err) throw err;
    //console.log(result); //mostrar os resultados
    var numTemps = 0;
    result.forEach(function(err,doc){
      if ("temperature" in result) {
        numTemps = numTemps + 1;
      };
    });
    var numHums = 0;
    result.forEach(function(err,doc){
      if ("humidity" in result) {
        numHums = numHums + 1;
      };
    });
    console.log("Temps: " + numTemps);
    console.log("Hums: " + numHums);
    db.close();
  });
});

Body:
Thank you all.

Managed to solve this with the following:

collection.find({}).toArray(function(err, result) {
if (err) throw err;
//console.log(result);
var numHums = 0;
var numTemps = 0;
var i = 0;
result.forEach(function(err,values){
  console.log(result[i].Type);
  if (result[i].Type == 'humidity') {
    numHums = numHums + 1;
  }
  if (result[i].Type == 'temperature') {
    numTemps = numTemps + 1;
  };
  i = i + 1;
});
console.log("Temps: " + numTemps);
console.log("Hums: " + numHums);
db.close();
});

edit:

changed the foreach according to the suggestion of the users here:

result.forEach(function(values){
 console.log(values.Type);
 if (values.Type == 'humidity') {
  numHums = numHums + 1;
 }
 if (values.Type == 'temperature') {
  numTemps = numTemps + 1;
 };
});


来源: stackexchange

问:
Git Errors/File not found
I have a working application. I deleted an html file from project, added changes to git and committed them. Then created another html of the same name in the same location, now my editor continues to throw an error 'Error: Cannot resolve 'file' or 'directory''

Will adding and committing to git help?

答:
I followed below steps to solve it - I think it was purely a Webstorm issue.

1) Deleted existing file (which was throwing the error: cannot resolve file)
2) Added same file
3) but this time under a different name

Seems weird but it solved it

ContentLicense: CC BY-SA 3.0

Title: Git Errors/File not found


问:
Why specify data types but not struct in function parameters? C++
Writing a function in C++, to my understanding, goes like this:

```<code> int  foo(int x)
    {
    //some code
    }
</code>```

First of all, int is the data type, why do we need to specify it?
Second of all if we have code like this:

```<code>  struct Monster
{
    std::string name;
    int health;

};
int printMonster(Monster myMonster)
    {

        std::cout << "This monster is named " << myMonster.name << " and has " << myMonster.health << " health" << std::endl;
        return 0;
</code>```

Why do we write the struct name, in this case "Monster" instead of struct?

答:
For the first question

First of all, int is the data type, why do we need to specify it?

In C/C++ you have to specify the data type for your variables. But you could also use the auto keyword like M.M suggested. You can use it, but I don't recommend using it cases like this.

For the second question

Why do we write the struct name, in this case "Monster" instead of struct?

Think about it like this. When you use the keywords struct or class, you are creating your own datatype. Monster is the datatype that you have created. Since C++ requires a data type for all variables, you write your datatype as Monster

Body:
Writing a function in C++, to my understanding, goes like this:

 int  foo(int x)
    {
    //some code
    }

First of all, int is the data type, why do we need to specify it?
Second of all if we have code like this:

  struct Monster
{
    std::string name;
    int health;

};
int printMonster(Monster myMonster)
    {

        std::cout << "This monster is named " << myMonster.name << " and has " << myMonster.health << " health" << std::endl;
        return 0;

Why do we write the struct name, in this case "Monster" instead of struct?


问:
Convert hours, mins, secs String to hours
I want to convert a time in the below format into hours.

My input which is a time format could be anything like

```<code>1 hour 30 mins 20 secs
2 hrs 10 mins
45 mins
</code>```

whereas my output will be:

```<code>1.505
2.167
0.75
</code>```

These are the hours.

Currently I am doing it manually by parsing the input string 1 hour 30 mins 20 secs, finding whether the word hour/hours/hrs/hr is present, then taking the preceding digits--the same for mins and secs. I use the formula to convert mins and secs to hours manually.

Is there any built-in provision that I can use in Java?

答:
Usually I wouldn't recommend Joda-Time (as it's being replaced by the new Java API's), but it's the only API I know with a good formatter/parser for periods.

You can use the PeriodFormatterBuilder class and use appendSuffix method to define the suffixes for singular and plural values for each field:

```<code>import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

// method to parse the period
public void getPeriod(String input) {
    PeriodFormatter formatter = new PeriodFormatterBuilder()
            // hours (singular and plural suffixes)
            .appendHours().appendSuffix("hour", "hours")
            // minutes
            .appendMinutes().appendSuffix("min", "mins")
            // seconds
            .appendSeconds().appendSuffix("sec", "secs")
            // create formatter
            .toFormatter();

    // remove spaces and change "hr" to "hour"
    Period p = formatter.parsePeriod(input.replaceAll(" ", "").replaceAll("hr", "hour"));

    double hours = p.getHours();
    hours += p.getMinutes() / 60d;
    hours += p.getSeconds() / 3600d;
    System.out.println(hours);
}

// tests
getPeriod("1 hour 30 mins 20 secs");
getPeriod("2 hrs 10 mins");
getPeriod("45 mins");
</code>```

Output:

1.5055555555555555

  2.1666666666666665

  0.75

Another way of creating the PeriodFormatter is using appendSuffix with regular expressions. It's useful when you have lots of different options for the suffix (like hour and hr for the hours field):

```<code>PeriodFormatter formatter = new PeriodFormatterBuilder()
    // hours (all possible suffixes for singular and plural)
    .appendHours()
    .appendSuffix(
        // regular expressions for singular and plural
        new String[] { "^1$", ".*", "^1$", ".*" },
        // possible suffixes for singular and plural
        new String[] { " hour", " hours", " hr", " hrs" })
    // optional space (if there are more fields)
    .appendSeparatorIfFieldsBefore(" ")
    // minutes
    .appendMinutes().appendSuffix(" min", " mins")
    // optional space (if there are more fields)
    .appendSeparatorIfFieldsBefore(" ")
    // seconds
    .appendSeconds().appendSuffix(" sec", " secs")
    // create formatter
    .toFormatter();
</code>```

Note that I've also added appendSeparatorIfFieldsBefore(" ") to indicate that it has a space before the next field.

The good thing about this version is that you don't need to pre-process the input:

```<code>// no need to call replaceAll (take input just as it is)
Period p = formatter.parsePeriod(input);
</code>```

The output is the same as above.

Java 8 date-time API

As stated in @assylian's answer, you can use the java.time.Duration class:

```<code>public void getDuration(String input) {
    // replace hour/min/secs strings for H, M and S
    String adjusted = input.replaceAll("\\s*(hour|hr)s?\\s*", "H");
    adjusted = adjusted.replaceAll("\\s*mins?\\s*", "M");
    adjusted = adjusted.replaceAll("\\s*secs?\\s*", "S");
    Duration d = Duration.parse("PT" + adjusted);

    double hours = d.toMillis() / 3600000d;
    System.out.println(hours);
}

//tests
getDuration("1 hour 30 mins 20 secs");
getDuration("2 hrs 10 mins");
getDuration("45 mins");
</code>```

The output is the same.

PS: if your Java version is <= 7, you can use the ThreeTen Backport. The class name and methods are the same, the only difference is the package name: org.threeten.bp instead of java.time.

Body:
I want to convert a time in the below format into hours.

My input which is a time format could be anything like

1 hour 30 mins 20 secs
2 hrs 10 mins
45 mins

whereas my output will be:

1.505
2.167
0.75

These are the hours.

Currently I am doing it manually by parsing the input string 1 hour 30 mins 20 secs, finding whether the word hour/hours/hrs/hr is present, then taking the preceding digits--the same for mins and secs. I use the formula to convert mins and secs to hours manually.

Is there any built-in provision that I can use in Java?

Body:
Usually I wouldn't recommend Joda-Time (as it's being replaced by the new Java API's), but it's the only API I know with a good formatter/parser for periods.

You can use the PeriodFormatterBuilder class and use appendSuffix method to define the suffixes for singular and plural values for each field:

import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

// method to parse the period
public void getPeriod(String input) {
    PeriodFormatter formatter = new PeriodFormatterBuilder()
            // hours (singular and plural suffixes)
            .appendHours().appendSuffix("hour", "hours")
            // minutes
            .appendMinutes().appendSuffix("min", "mins")
            // seconds
            .appendSeconds().appendSuffix("sec", "secs")
            // create formatter
            .toFormatter();

    // remove spaces and change "hr" to "hour"
    Period p = formatter.parsePeriod(input.replaceAll(" ", "").replaceAll("hr", "hour"));

    double hours = p.getHours();
    hours += p.getMinutes() / 60d;
    hours += p.getSeconds() / 3600d;
    System.out.println(hours);
}

// tests
getPeriod("1 hour 30 mins 20 secs");
getPeriod("2 hrs 10 mins");
getPeriod("45 mins");

Output:

1.5055555555555555

  2.1666666666666665

  0.75

Another way of creating the PeriodFormatter is using appendSuffix with regular expressions. It's useful when you have lots of different options for the suffix (like hour and hr for the hours field):

PeriodFormatter formatter = new PeriodFormatterBuilder()
    // hours (all possible suffixes for singular and plural)
    .appendHours()
    .appendSuffix(
        // regular expressions for singular and plural
        new String[] { "^1$", ".*", "^1$", ".*" },
        // possible suffixes for singular and plural
        new String[] { " hour", " hours", " hr", " hrs" })
    // optional space (if there are more fields)
    .appendSeparatorIfFieldsBefore(" ")
    // minutes
    .appendMinutes().appendSuffix(" min", " mins")
    // optional space (if there are more fields)
    .appendSeparatorIfFieldsBefore(" ")
    // seconds
    .appendSeconds().appendSuffix(" sec", " secs")
    // create formatter
    .toFormatter();

Note that I've also added appendSeparatorIfFieldsBefore(" ") to indicate that it has a space before the next field.

The good thing about this version is that you don't need to pre-process the input:

// no need to call replaceAll (take input just as it is)
Period p = formatter.parsePeriod(input);

The output is the same as above.

Java 8 date-time API

As stated in @assylian's answer, you can use the java.time.Duration class:

public void getDuration(String input) {
    // replace hour/min/secs strings for H, M and S
    String adjusted = input.replaceAll("\\s*(hour|hr)s?\\s*", "H");
    adjusted = adjusted.replaceAll("\\s*mins?\\s*", "M");
    adjusted = adjusted.replaceAll("\\s*secs?\\s*", "S");
    Duration d = Duration.parse("PT" + adjusted);

    double hours = d.toMillis() / 3600000d;
    System.out.println(hours);
}

//tests
getDuration("1 hour 30 mins 20 secs");
getDuration("2 hrs 10 mins");
getDuration("45 mins");

The output is the same.

PS: if your Java version is <= 7, you can use the ThreeTen Backport. The class name and methods are the same, the only difference is the package name: org.threeten.bp instead of java.time.


问:
Submit form after successful ajax call using jQuery in asp.net mvc 5
I have a form in an Asp.net MVC 5 project which has a Submit button. When the Submit button is clicked, I want to do the following:

Perform client=side validation using jQuery on various fields (required fields have been filled, email format is valid, etc...). That part is working fine.

Make an Ajax call that will perform some server side validation by calling an action from the controller and return a JSON response. The response contains a Success property and Errors property which contains a list of errors.

The Success property will return true if no error are found and the Errors property will be null. If errors are found the Success property is returns false and the Errors property contains a list of relevant errors.

I'm calling '\ApplicationForm\Validate' action from my ApplicationForm controller and this part is working fine.

When no errors are found in part 2, I want my form to be submitted as normal and call the '\ApplicationForm\Index' action so that my data can then be added to my database. I cannot get this part to work!!

The Submit button is defined as follows:

```<code><div class="form-group">
  <div>
    <input type="button" id="btnApply" value="Apply" class="btn btn-primary" />
  </div>
</div>
</code>```

My JavaScript code is defined as follows:

```<code>$('#AppllicationForm').submit(function () {
    if (!$(this).attr('validated')) {
        if ($(this).valid()) {
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        $('#ApplicationForm').attr('validated', true);
                        $('#ApplicationForm').attr('action', '/ApplicationForm/Index')
                            .submit();
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
        }
    }
    return false;
});
</code>```

The above is using a regular button but I've also tried to define its type as Submit but to no avail.

I know similar questions have been posted in the past but I cannot find one that has actually helped me out to find a resolution to my problem, so please bear with me and do not mark this question as a duplicate unless there is an actual question/answer with an actual resolution to my problem. Much appreciated!

The closest scenario I found to what I'm trying to achieve is can be found from this article on SO: Submit a form from inside an ajax success function that checks the values

I've been trying so many different things at this stage but nothing is working out. I either don't get the Index action to be called after the ValidateForm action, or either one or the other action is called or the only Index action is called or my model gets messed up, and the list goes on.

I'm clearly not doing this correctly or missing something but I'm at a complete stand still for now. I'm hoping that it will be something silly that I've missed and hopefully someone will clarify this for me.

Any help would be greatly appreciated.

答:
I thought I'd share my solution as I ended up hiring a freelancer to have a look at it as I was under time constraint and could not afford to spend any more time on this.

How did it fix it? He added a second ajax call from within the first one. The annoying (and costly!) part is that I did try this but I had one important missing line i.e. var formValidated = $('#AppllicationForm').serialize();.

After these changes were made, I just had to rejig some of my logic regarding which div should be displayed and/or hidden but bar that it was pretty standard stuff.

Here's the final code that worked as expected:

```<code>$('#AppllicationForm').submit(function () {
    if ($(this).valid()) {
        $.ajax({
            type: "POST",
            data: $(this).serialize(),
            url: "/ApplicationForm/ValidateForm",
            dataType: 'json',
            success: function (response) {
                if (response != null && response.success) {
                    var formValidated = $('#AppllicationForm').serialize();
                    $.ajax({
                        url: '/ApplicationForm/Index',
                        data: formValidated,
                        type: 'POST',
                        success: function (result) {
                            $('#mainDiv').hide();
                            $('#Congrats').show();
                        }
                    });
                    return true;
                }
                else if (response != null && !response.success) {
                    var errors = response['errors'];
                    displayValidationErrors(errors);
                    window.scrollTo(0, 0);
                }
                return false;
            },
            error: function (response) {
                $('validationSummary').hide();
                return false;
            }
        });
    }
    return false;
});
</code>```

Hope this helps others.

Body:
I have a form in an Asp.net MVC 5 project which has a Submit button. When the Submit button is clicked, I want to do the following:

Perform client=side validation using jQuery on various fields (required fields have been filled, email format is valid, etc...). That part is working fine.

Make an Ajax call that will perform some server side validation by calling an action from the controller and return a JSON response. The response contains a Success property and Errors property which contains a list of errors.

The Success property will return true if no error are found and the Errors property will be null. If errors are found the Success property is returns false and the Errors property contains a list of relevant errors.

I'm calling '\ApplicationForm\Validate' action from my ApplicationForm controller and this part is working fine.

When no errors are found in part 2, I want my form to be submitted as normal and call the '\ApplicationForm\Index' action so that my data can then be added to my database. I cannot get this part to work!!

The Submit button is defined as follows:

    <input type="button" id="btnApply" value="Apply" class="btn btn-primary" />

My JavaScript code is defined as follows:

$('#AppllicationForm').submit(function () {
    if (!$(this).attr('validated')) {
        if ($(this).valid()) {
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        $('#ApplicationForm').attr('validated', true);
                        $('#ApplicationForm').attr('action', '/ApplicationForm/Index')
                            .submit();
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
        }
    }
    return false;
});

The above is using a regular button but I've also tried to define its type as Submit but to no avail.

I know similar questions have been posted in the past but I cannot find one that has actually helped me out to find a resolution to my problem, so please bear with me and do not mark this question as a duplicate unless there is an actual question/answer with an actual resolution to my problem. Much appreciated!

The closest scenario I found to what I'm trying to achieve is can be found from this article on SO: Submit a form from inside an ajax success function that checks the values

I've been trying so many different things at this stage but nothing is working out. I either don't get the Index action to be called after the ValidateForm action, or either one or the other action is called or the only Index action is called or my model gets messed up, and the list goes on.

I'm clearly not doing this correctly or missing something but I'm at a complete stand still for now. I'm hoping that it will be something silly that I've missed and hopefully someone will clarify this for me.

Any help would be greatly appreciated.

Body:
I thought I'd share my solution as I ended up hiring a freelancer to have a look at it as I was under time constraint and could not afford to spend any more time on this.

How did it fix it? He added a second ajax call from within the first one. The annoying (and costly!) part is that I did try this but I had one important missing line i.e. var formValidated = $('#AppllicationForm').serialize();.

After these changes were made, I just had to rejig some of my logic regarding which div should be displayed and/or hidden but bar that it was pretty standard stuff.

Here's the final code that worked as expected:

$('#AppllicationForm').submit(function () {
    if ($(this).valid()) {
        $.ajax({
            type: "POST",
            data: $(this).serialize(),
            url: "/ApplicationForm/ValidateForm",
            dataType: 'json',
            success: function (response) {
                if (response != null && response.success) {
                    var formValidated = $('#AppllicationForm').serialize();
                    $.ajax({
                        url: '/ApplicationForm/Index',
                        data: formValidated,
                        type: 'POST',
                        success: function (result) {
                            $('#mainDiv').hide();
                            $('#Congrats').show();
                        }
                    });
                    return true;
                }
                else if (response != null && !response.success) {
                    var errors = response['errors'];
                    displayValidationErrors(errors);
                    window.scrollTo(0, 0);
                }
                return false;
            },
            error: function (response) {
                $('validationSummary').hide();
                return false;
            }
        });
    }
    return false;
});

Hope this helps others.


问:
How to consider few parameters in method
I have my own implementation of SimpleFileVisitor with a visitFile method.
I wonder how can i perform more precise search, if there are more than only one parameter. Here what i mean

```<code>public class SearchFileVisitor extends SimpleFileVisitor<Path>
{
    private String partOfName;
    private String partOfContent;
    private int minSize;
    private int maxSize;
    private List<Path> foundFiles = new ArrayList<>();

    public void setPartOfName(String partOfName)
    {
        this.partOfName = partOfName;
    }

    public void setPartOfContent(String partOfContent)
    {
        this.partOfContent = partOfContent;
    }

    public void setMinSize(int minSize)
    {
        this.minSize = minSize;
    }

    public void setMaxSize(int maxSize)
    {
        this.maxSize = maxSize;
    }

    public List<Path> getFoundFiles()
    {
        return foundFiles;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
    {
        if(partOfName != null && file.toString().contains(partOfName))
        {
           foundFiles.add(file);
        }
        else if(partOfContent != null)
            {
                try(Scanner scanner = new Scanner(file))
                {
                    while(scanner.hasNextLine())
                    {
                        String line = scanner.nextLine();
                        if(line.contains(partOfContent))
                        {
                            foundFiles.add(file);
                            break;
                        }
                    }
                }
            }
         else if(file.toFile().length() < maxSize)
         {
             foundFiles.add(file);
         }
         else if(file.toFile().length() > minSize)
         {
             foundFiles.add(file);
         }
        return super.visitFile(file, attrs);
    }
}
</code>```

The main method:

```<code>public static void main(String[] args) throws IOException
    {
        SearchFileVisitor searchFileVisitor = new SearchFileVisitor();

        searchFileVisitor.setPartOfName("John");
        searchFileVisitor.setPartOfContent("be or not to be?");
        searchFileVisitor.setMinSize(500);
        searchFileVisitor.setMaxSize(10000);

        Files.walkFileTree(Paths.get("D:/SecretFolder"), searchFileVisitor);

        List<Path> foundFiles = searchFileVisitor.getFoundFiles();
        for (Path file : foundFiles)
        {
            System.out.println(file);
        }
    }
</code>```

So, if i set only partOfName it should relay only on it. But if beside it i also set partOfContent and say maxSize, it simultaneously should relay on 3 parameters so far. And consequently if there are 4 par it should relay on four and add to the List, if the object satisfies all the criteria. How can i do that?(Without damn boolean flags)

答:
You should use Stream<Path> instead of FileVisitor<Path> like this.

```<code>static boolean contains(Path path, String partOfContent) {
    try (Scanner scanner = new Scanner(path)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.contains(partOfContent)) {
                return true;
            }
        }
    } catch (IOException e) {
        return false;
    }
    return false;
}

public static void main(String[] args) throws IOException {
    List<Path> results = Files.walk(Paths.get("D:/SecretFolder"))
        .filter(path -> Files.isRegularFile(path))
        .filter(path -> path.toString().contains("Jhon"))
        .filter(path -> contains(path, "be or not to be?"))
        .filter(path -> path.toFile().length() >= 500)
        .filter(path -> path.toFile().length() <= 10000)
        .collect(Collectors.toList());
    results.stream()
        .forEach(System.out::println);
}
</code>```

If you don't want to check minimum file size, delete the line .filter(path -> path.toFile().length() >= 500).

Body:
I have my own implementation of SimpleFileVisitor with a visitFile method.
I wonder how can i perform more precise search, if there are more than only one parameter. Here what i mean

public class SearchFileVisitor extends SimpleFileVisitor<Path>
{
    private String partOfName;
    private String partOfContent;
    private int minSize;
    private int maxSize;
    private List<Path> foundFiles = new ArrayList<>();

    public void setPartOfName(String partOfName)
    {
        this.partOfName = partOfName;
    }

    public void setPartOfContent(String partOfContent)
    {
        this.partOfContent = partOfContent;
    }

    public void setMinSize(int minSize)
    {
        this.minSize = minSize;
    }

    public void setMaxSize(int maxSize)
    {
        this.maxSize = maxSize;
    }

    public List<Path> getFoundFiles()
    {
        return foundFiles;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
    {
        if(partOfName != null && file.toString().contains(partOfName))
        {
           foundFiles.add(file);
        }
        else if(partOfContent != null)
            {
                try(Scanner scanner = new Scanner(file))
                {
                    while(scanner.hasNextLine())
                    {
                        String line = scanner.nextLine();
                        if(line.contains(partOfContent))
                        {
                            foundFiles.add(file);
                            break;
                        }
                    }
                }
            }
         else if(file.toFile().length() < maxSize)
         {
             foundFiles.add(file);
         }
         else if(file.toFile().length() > minSize)
         {
             foundFiles.add(file);
         }
        return super.visitFile(file, attrs);
    }
}

The main method:

public static void main(String[] args) throws IOException
    {
        SearchFileVisitor searchFileVisitor = new SearchFileVisitor();

        searchFileVisitor.setPartOfName("John");
        searchFileVisitor.setPartOfContent("be or not to be?");
        searchFileVisitor.setMinSize(500);
        searchFileVisitor.setMaxSize(10000);

        Files.walkFileTree(Paths.get("D:/SecretFolder"), searchFileVisitor);

        List<Path> foundFiles = searchFileVisitor.getFoundFiles();
        for (Path file : foundFiles)
        {
            System.out.println(file);
        }
    }

So, if i set only partOfName it should relay only on it. But if beside it i also set partOfContent and say maxSize, it simultaneously should relay on 3 parameters so far. And consequently if there are 4 par it should relay on four and add to the List, if the object satisfies all the criteria. How can i do that?(Without damn boolean flags)

Body:
You should use Stream<Path> instead of FileVisitor<Path> like this.

static boolean contains(Path path, String partOfContent) {
    try (Scanner scanner = new Scanner(path)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.contains(partOfContent)) {
                return true;
            }
        }
    } catch (IOException e) {
        return false;
    }
    return false;
}

public static void main(String[] args) throws IOException {
    List<Path> results = Files.walk(Paths.get("D:/SecretFolder"))
        .filter(path -> Files.isRegularFile(path))
        .filter(path -> path.toString().contains("Jhon"))
        .filter(path -> contains(path, "be or not to be?"))
        .filter(path -> path.toFile().length() >= 500)
        .filter(path -> path.toFile().length() <= 10000)
        .collect(Collectors.toList());
    results.stream()
        .forEach(System.out::println);
}

If you don't want to check minimum file size, delete the line .filter(path -> path.toFile().length() >= 500).


问:
How is a Realm sync effected by unchanged data?
If I call realm.create() and pass in a primary key for an entry that already exists, my understanding is that it does an update as opposed to an insert.

If I am using the realm server and one client calls a realm.create() on an existing entry and updates all the fields with the exact same data that was already in the row, will other clients see a need to sync that row, or since none of the data changed will they know to ignore it?

Is a sync needed flag generated on a row by diffing previous and current data, or by on some meta data based on when the entry was last edited regaurdless if the data changed?

I ask because I have a situation where one client could potentially call realm.create() on thousands of existing rows even though no data will have changed and I don't want my other clients to have to perform a huge sync as a result.

答:
Realm's sync is based off the actual database operations rather than the state. More specifically, the database maintains a transaction or operation log and the data sync is based off transmitting this data. For example, if you perform realm.create('Object', {foo:bar, id: 0}, true) which is an upsert operation for the Object with id:0, this will be written to the log and synchronized.

The result is that even if the upsert doesn't change any of the data, the operation must still be synced. The reasoning for this is that the sync uses operational transformation algorithms to automatically ensure that all changes across devices eventually become consistent. This works by ensuring eventually the server receives every operation.

As a result, you should be mindful of unnecessary operations if possible. Note the sync is highly optimized and by only syncing operations the data transfer is reduced compared to resending an entire object on each change.

Longer term we will be adding support for log compaction on the server. This will mean that clients will still always need to transmit their operations to the server, but the server could reduce operations needed to converge other clients (for example, collapsing multiple set operations down to the just the final set).


问:
Syntax highlighting richtextbox in C# on a single line only
I'm working on my own syntax highlighter using a Richtextbox. It's already working, but I've noticed that the typing slows down a lot when there's to many lines of code. This is because my syntax highlight function is coloring all the words in the entire Richtextbox on every change made to it. Here's a minimal example of the function to see how it works:

```<code>private void colorCode()
{
    // getting keywords/functions
    string keywords = @"\b(class|function)\b";
    MatchCollection keywordMatches = Regex.Matches(codeBox.Text, keywords);

    // saving the original caret position + forecolor
    int originalIndex = codeBox.SelectionStart;
    int originalLength = codeBox.SelectionLength;
    Color originalColor = Color.Black

    // focuses a label before highlighting (avoids blinking)
    titleLabel.Focus();;

    // removes any previous highlighting (so modified words won't remain highlighted)
    codeBox.SelectionStart = 0;
    codeBox.SelectionLength = codeBox.Text.Length;
    codeBox.SelectionColor = originalColor;

    foreach (Match m in keywordMatches)
    {
        codeBox.SelectionStart = m.Index;
        codeBox.SelectionLength = m.Length;
        codeBox.SelectionColor = Color.Blue;
    }

    // restoring the original colors, for further writing
    codeBox.SelectionStart = originalIndex;
    codeBox.SelectionLength = originalLength;
    codeBox.SelectionColor = originalColor;

    // giving back the focus
    codeBox.Focus();
}
</code>```

To solve the problem, I want to write a function that doesn't change the entire Richtextbox, but just the line of the cursor position instead. I realise this will still cause the same issue on minified code, but that's not a problem for me. The problem is, I can't seem to get it working. This is what I've got so far:

```<code>void changeLine(RichTextBox RTB, int line, Color clr, int curPos){
    string testWords = @"\b(test1|test2)\b";
    MatchCollection testwordMatches = Regex.Matches(RTB.Lines[line], testWords);

    foreach (Match m in testwordMatches)
    {
        //RTB.SelectionStart = m.Index;
        //RTB.SelectionLength = m.Length;
        RTB.SelectionColor = Color.Blue;
    }

    RTB.SelectionStart = curPos;
    RTB.SelectionColor = Color.Black;
}
</code>```

The problem is that it does the coloring when a word in testWords is found, but it colors the entire line instead of just the word. This is because I can't figure out a way of doing the selections right. So I'm hoping you guys can help me out with this.

Edit:

I'd like to add that I did thought about other solutions, like putting the lines in a List, or using a Stringbuilder. But those will turn the lines into strings and don't allow me to do color formatting like the Richtextbox does.

答:
Well, you obviously need language lexer and parser. This task is not solvable by using Regex. It's just doesn't capable to accomplish this because of some fundamental grammar rules (or "power levels" of grammars) (read about Thomsky hierarchy of grammars).

What you need is to use some grammar toolkit. For example ANTLR4 provide grammar lexer/parser generator and set of already predefined grammars.

For example, you can find a lot of user-written grammars in here (including latest C# syntax): https://github.com/antlr/grammars-v4

Then just generate parser/lexer by it and feed it your string. It will output full hierarchy with indexes and lengths of each token, and you can colorize them without jumping across entire rich box.

Also, consider to use some timeout between user input, so you don't colorize your output every symbol (just save color from previous token, and use it for some time, until you recolorize output, then refresh). This way it will go as smoothly as it is in Visual Studio.

Body:
I'm working on my own syntax highlighter using a Richtextbox. It's already working, but I've noticed that the typing slows down a lot when there's to many lines of code. This is because my syntax highlight function is coloring all the words in the entire Richtextbox on every change made to it. Here's a minimal example of the function to see how it works:

private void colorCode()
{
    // getting keywords/functions
    string keywords = @"\b(class|function)\b";
    MatchCollection keywordMatches = Regex.Matches(codeBox.Text, keywords);

    // saving the original caret position + forecolor
    int originalIndex = codeBox.SelectionStart;
    int originalLength = codeBox.SelectionLength;
    Color originalColor = Color.Black

    // focuses a label before highlighting (avoids blinking)
    titleLabel.Focus();;

    // removes any previous highlighting (so modified words won't remain highlighted)
    codeBox.SelectionStart = 0;
    codeBox.SelectionLength = codeBox.Text.Length;
    codeBox.SelectionColor = originalColor;

    foreach (Match m in keywordMatches)
    {
        codeBox.SelectionStart = m.Index;
        codeBox.SelectionLength = m.Length;
        codeBox.SelectionColor = Color.Blue;
    }

    // restoring the original colors, for further writing
    codeBox.SelectionStart = originalIndex;
    codeBox.SelectionLength = originalLength;
    codeBox.SelectionColor = originalColor;

    // giving back the focus
    codeBox.Focus();
}

To solve the problem, I want to write a function that doesn't change the entire Richtextbox, but just the line of the cursor position instead. I realise this will still cause the same issue on minified code, but that's not a problem for me. The problem is, I can't seem to get it working. This is what I've got so far:

void changeLine(RichTextBox RTB, int line, Color clr, int curPos){
    string testWords = @"\b(test1|test2)\b";
    MatchCollection testwordMatches = Regex.Matches(RTB.Lines[line], testWords);

    foreach (Match m in testwordMatches)
    {
        //RTB.SelectionStart = m.Index;
        //RTB.SelectionLength = m.Length;
        RTB.SelectionColor = Color.Blue;
    }

    RTB.SelectionStart = curPos;
    RTB.SelectionColor = Color.Black;
}

The problem is that it does the coloring when a word in testWords is found, but it colors the entire line instead of just the word. This is because I can't figure out a way of doing the selections right. So I'm hoping you guys can help me out with this.

Edit:

I'd like to add that I did thought about other solutions, like putting the lines in a List, or using a Stringbuilder. But those will turn the lines into strings and don't allow me to do color formatting like the Richtextbox does.


问:
C - Macro contradiction
I just started learning C and I am not sure about how everything works. Some of examples simply looks weird to me and I cannot predict what would it print. I am programming in GCC, I mean it is my compiler, so every code I test is in GCC.

I understood pointers etc how that all stuff work, but also as you know there are macros. Macros are very weird, and I discovered one example I have no explanation about. For example look at this code particular code:

```<code>#include <stdio.h>

int main(void){

  #define A 1

  if(A == 0){
    #define B 1
  }

  #ifdef B
    printf("B is defined, which means that A == 0.\n");
  #elif
    printf("B isn't defined, which means that A == 1.\n");
  #endif

  printf("Value of A is %d\n", A);

  return 0;
}
</code>```

What should it print? Well, I though it is easy to guess, but now I see that it is not very easy. The result is not what i thought is.

This was my reasoning: we firstly define A to be 1 and then if A is 0 then define B to be 1. So, if B is defined it means that A == 0 and otherwise A == 1. But, surprisingly it prints:

B is defined, which means that A == 0.

  Value of A is 1

What? It just printed a contradiction. I am not sure if this is some weird thing in GCC (because I have no visual studio or other compiler to test it). However, I am 99% sure I somehow misunderstood macros. I tried using variables instead of macros and it works properly.

Is it an issue, or did I simply misunderstand how macros work? Please keep in mind that I'm C beginner, so take it easy :).

Thank you in advance.

答:
Macros are part of the preprocessor before the code is actually compiled. The compiler will search the code for all preprocessor directives and modify the code accordingly. So when the compiler gets to if(A == 0) {#define B 1} it has already been expanded to if(0 == 1) { }.

Macros makes it easy to configure an aspect of your code or to replace magic numbers into meaningful defines. For example:

```<code>#define DO_HOUR_CALCULATION

#define NUMBER_OF_SECONDS_PER_MINUTE (60)
#define NUMBER_OF_SECONDS_PER_HOUR (NUMBER_OF_SECONDS_PER_MINUTE * 60)
...
#ifdef DO_HOUR_CALCULATION
int hours = time / NUMBER_OF_SECONDS_PER_HOUR;
int minutes = (time % NUMBER_OF_SECONDS_PER_HOUR) / NUMBER_OF_SECONDS_PER_MINUTE;
#endif // defined(DO_TIME_CALCULATION)
</code>```

Another use is to simplify a repeated or configurable task:

```<code>#define DEBUG

#ifdef DEBUG
#define DPRINTF(fmt, args...) printf(fmt, ## args)
#else
#define DPRINTF(args...)   do {} while (0)
#endif
...
ret = read(fd, p_buffer, buf_size);
DPRINTF("read(fd) returned %d\n", ret);
</code>```

Hope this helps you and happy coding!

Title: C - Macro contradiction

Body:
I just started learning C and I am not sure about how everything works. Some of examples simply looks weird to me and I cannot predict what would it print. I am programming in GCC, I mean it is my compiler, so every code I test is in GCC.

I understood pointers etc how that all stuff work, but also as you know there are macros. Macros are very weird, and I discovered one example I have no explanation about. For example look at this code particular code:

#include <stdio.h>

int main(void){

  #define A 1

  if(A == 0){
    #define B 1
  }

  #ifdef B
    printf("B is defined, which means that A == 0.\n");
  #elif
    printf("B isn't defined, which means that A == 1.\n");
  #endif

  printf("Value of A is %d\n", A);

  return 0;
}

What should it print? Well, I though it is easy to guess, but now I see that it is not very easy. The result is not what i thought is.

This was my reasoning: we firstly define A to be 1 and then if A is 0 then define B to be 1. So, if B is defined it means that A == 0 and otherwise A == 1. But, surprisingly it prints:

B is defined, which means that A == 0.

  Value of A is 1

What? It just printed a contradiction. I am not sure if this is some weird thing in GCC (because I have no visual studio or other compiler to test it). However, I am 99% sure I somehow misunderstood macros. I tried using variables instead of macros and it works properly.

Is it an issue, or did I simply misunderstand how macros work? Please keep in mind that I'm C beginner, so take it easy :).

Thank you in advance.

Body:
Macros are part of the preprocessor before the code is actually compiled. The compiler will search the code for all preprocessor directives and modify the code accordingly. So when the compiler gets to if(A == 0) {#define B 1} it has already been expanded to if(0 == 1) { }.

Macros makes it easy to configure an aspect of your code or to replace magic numbers into meaningful defines. For example:

#define DO_HOUR_CALCULATION

#define NUMBER_OF_SECONDS_PER_MINUTE (60)
#define NUMBER_OF_SECONDS_PER_HOUR (NUMBER_OF_SECONDS_PER_MINUTE * 60)
...
#ifdef DO_HOUR_CALCULATION
int hours = time / NUMBER_OF_SECONDS_PER_HOUR;
int minutes = (time % NUMBER_OF_SECONDS_PER_HOUR) / NUMBER_OF_SECONDS_PER_MINUTE;
#endif // defined(DO_TIME_CALCULATION)

Another use is to simplify a repeated or configurable task:

#define DEBUG

#ifdef DEBUG
#define DPRINTF(fmt, args...) printf(fmt, ## args)
#else
#define DPRINTF(args...)   do {} while (0)
#endif
...
ret = read(fd, p_buffer, buf_size);
DPRINTF("read(fd) returned %d\n", ret);

Hope this helps you and happy coding!


答:
The #define B 1 does not occur at run time.  It happens at compile time.  So #define B 1 is part of the compilation regardless of the result of A == 0, a run-time comparison

```<code>  if(A == 0){
    #define B 1
  }
</code>```

The following code

```<code>  #ifdef B
    printf("B is defined, which means that A == 0.\n");
  #elif
    printf("B isn't defined, which means that A == 1.\n");
  #endif
</code>```

is then the same as

```<code>  printf("B is defined, which means that A == 0.\n");
</code>```

Title: C - Macro contradiction

Body:
The #define B 1 does not occur at run time.  It happens at compile time.  So #define B 1 is part of the compilation regardless of the result of A == 0, a run-time comparison

  if(A == 0){
    #define B 1
  }

The following code

  #ifdef B
    printf("B is defined, which means that A == 0.\n");
  #elif
    printf("B isn't defined, which means that A == 1.\n");
  #endif

is then the same as

  printf("B is defined, which means that A == 0.\n");


问:
MongoDB: Unique Key in Embedded Document
Is it possible to set a unique key for a key in an embedded document?

I have a Users collection with the following sample documents:

```<code> {
       Name: "Bob",
       Items: [
           {
               Name: "Milk"
           },
           {
               Name: "Bread"
           }
       ]
    },
    {
       Name: "Jim"
    },
</code>```

Is there a way to create an index on the property Items.Name?

I got the following error when I tried to create an index:

```<code>> db.Users.ensureIndex({"Items.Name": 1}, {unique:true});
E11000 duplicate key error index: GroceryGuruApp.Users.$Items.Name_1  dup key: {
 : null }
</code>```

Any suggestions? Thank you!

答:
Unique indexes exist only across collection. To enforce uniqueness and other constraints across document you must do it in client code. (Probably virtual collections would allow that, you could vote for it.)

What are you trying to do in your case is to create index on key Items.Name which doesn't exist in any of the documents (it doesn't refer to embedded documents inside array Items), thus it's null and violates unique constraint across collection.

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to set a unique key for a key in an embedded document?

I have a Users collection with the following sample documents:

 {
       Name: "Bob",
       Items: [
           {
               Name: "Milk"
           },
           {
               Name: "Bread"
           }
       ]
    },
    {
       Name: "Jim"
    },

Is there a way to create an index on the property Items.Name?

I got the following error when I tried to create an index:

> db.Users.ensureIndex({"Items.Name": 1}, {unique:true});
E11000 duplicate key error index: GroceryGuruApp.Users.$Items.Name_1  dup key: {
 : null }

Any suggestions? Thank you!


问:
Using Google Closure's "compiler.jar" in Google App Engine
I am trying to use Google Closure Compiler API from my Java code. Function compile() receives the original source code, and returns the compiled source code in a String.

This code will run in Google App Engine, but when I deploy and run it I get an "server error". Without calling function below, I don't get any errors. At time of compilation I get warning "compiler.jar will not be available on server's classpath". Compiler.jar is the library I downloaded from Closure Compiler project website.

Any ideas of how to go around this?

Thanks a million,

```<code>import com.google.javascript.jscomp.*;

public static String compile(String code)
{
    com.google.javascript.jscomp.Compiler.setLoggingLevel(Level.INFO);
    com.google.javascript.jscomp.Compiler compiler = new com.google.javascript.jscomp.Compiler();

    CompilerOptions options = new CompilerOptions();
    CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

    JSSourceFile js = JSSourceFile.fromCode("input.js", code);

    WarningLevel.QUIET.setOptionsForWarningLevel(options);
    compiler.compile(null, js, options);

    return compiler.toSource();
}
</code>```

答:
try this:</p>

```<code>import com.google.javascript.jscomp.*;

public static String compile(String code)
{
    com.google.javascript.jscomp.Compiler.setLoggingLevel(Level.INFO);
    com.google.javascript.jscomp.Compiler compiler = new
    com.google.javascript.jscomp.Compiler();

    CompilerOptions options = new CompilerOptions();
    CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

    JSSourceFile js = JSSourceFile.fromCode("input.js", code);
    List<SourceFile> list = new ArrayList<SourceFile>();
    list.add(js);

    WarningLevel.QUIET.setOptionsForWarningLevel(options);
    compiler.compile(new ArrayList<SourceFile>(), list, options);

    return compiler.toSource();
 }
</code>```

Body:
I am trying to use Google Closure Compiler API from my Java code. Function compile() receives the original source code, and returns the compiled source code in a String.

This code will run in Google App Engine, but when I deploy and run it I get an "server error". Without calling function below, I don't get any errors. At time of compilation I get warning "compiler.jar will not be available on server's classpath". Compiler.jar is the library I downloaded from Closure Compiler project website.

Any ideas of how to go around this?

Thanks a million,

import com.google.javascript.jscomp.*;

public static String compile(String code)
{
    com.google.javascript.jscomp.Compiler.setLoggingLevel(Level.INFO);
    com.google.javascript.jscomp.Compiler compiler = new com.google.javascript.jscomp.Compiler();

    CompilerOptions options = new CompilerOptions();
    CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

    JSSourceFile js = JSSourceFile.fromCode("input.js", code);

    WarningLevel.QUIET.setOptionsForWarningLevel(options);
    compiler.compile(null, js, options);

    return compiler.toSource();
}

Body:
try this:

import com.google.javascript.jscomp.*;

public static String compile(String code)
{
    com.google.javascript.jscomp.Compiler.setLoggingLevel(Level.INFO);
    com.google.javascript.jscomp.Compiler compiler = new
    com.google.javascript.jscomp.Compiler();

    CompilerOptions options = new CompilerOptions();
    CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

    JSSourceFile js = JSSourceFile.fromCode("input.js", code);
    List<SourceFile> list = new ArrayList<SourceFile>();
    list.add(js);

    WarningLevel.QUIET.setOptionsForWarningLevel(options);
    compiler.compile(new ArrayList<SourceFile>(), list, options);

    return compiler.toSource();
 }


问:
When to use header('Content-Type: application/json') in PHP
I've been trying to figure out what's really the usage of header('Content-Type: application/json') in php scripts and I've found different questions and answers on stackoverflow about this subject but I still don't completely get it...

So here's the question : I've seen in some php projects this line of code, and I'm trying to understand

if this is used when another web page is calling this actual script (with ajax for example) so that the calling page can get a json from the php page

OR

if this script means that the php page is going to deal with json sent from another web page. Or maybe something else ???

Another thing that could help me if answered, lately I've been retrieving json from a resource (external url) with cURL and I had to put this header (Content-type:application/json) in the request. Did I send this header to the exertnal resource or was this MY header so that I can deal with the returned json ?

thanks

答:
In PHP, if you don't specify the Content-Type header in the script, it will default to whatever you've configured default-mimetype to be in your php.ini file which is usually text/html.

Calling header('Content-Type: application/json') will override that default setting so that the script will respond with that Content-Type when requested.

Also, when calling curl with a Content-type:application/json header, you're specifying the content type for your request body and not for the expected reponse.


问:
jQuery - How do I find an element with partial ID under a specific element
I have multiple records, each with the same fields, they all have the same name/id, plus the RecordID.  When I press cmdUpdate_xxx I detect which record div, assigning it to 'fldTarget'.  I know want to check each field (20, so don't want to do this manually) for validity.  I've tried

```<code>$('#RecordsWrapper')
    .on("click" , "[id*=cmdUpdate]", "input", function(e){
      fldTarget = $(this);
      fldAccountID = fldTarget.parent().find("#txtAccountID").prop("id");`
    })
</code>```

...but fldAccountID comes back as undefined.  How can I locate a sub element with an ID that contains 'txtAccountID' under 'Record001' div?

```<code><div id='RecordsWrapper'>
<div id='Record001'>
  <input type='text' id='txtAccount_001'>
  <input type='text' id='txtEntry_001'>
  <input type='text' id='txtValue_001'>
  <input type='submit' id='cmdUpdate_001'>
</div>
<div id='Record002'>
  <input type='text' id='txtAccount_002'>
  <input type='text' id='txtEntry_002'>
  <input type='text' id='txtValue_002'>
  <input type='submit' id='cmdUpdate_002'>
</div>
</div>
</code>```

答:
use attribute selector:

Attribute selectors

Attribute selectors select an element using the presence of a given attribute or attribute value.

REF: https://developer.mozilla.org/en/docs/Web/CSS/Attribute_selectors

REF (more example here): https://www.w3schools.com/css/css_attribute_selectors.asp

$('input[id^=txtEntry]').css('background', 'green');

$('#RecordsWrapper')
  .on("click", "input[id^=cmdUpdate]", "input", function(e) {
    fldTarget = $(this);
    fldAccountID = fldTarget.parent().find("input[id^=txtAccount]").prop("id");
    console.log('fldAccountID-->' + fldAccountID);
  })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input[id^=txtAccount] {
  background: red;
}</code>```

    <input type='text' id='txtAccount_001'>
    <input type='text' id='txtEntry_001'>
    <input type='text' id='txtValue_001'>
    <input type='submit' id='cmdUpdate_001'>

    <input type='text' id='txtAccount_002'>
    <input type='text' id='txtEntry_002'>
    <input type='text' id='txtValue_002'>
    <input type='submit' id='cmdUpdate_002'>

```

Body:
I have multiple records, each with the same fields, they all have the same name/id, plus the RecordID.  When I press cmdUpdate_xxx I detect which record div, assigning it to 'fldTarget'.  I know want to check each field (20, so don't want to do this manually) for validity.  I've tried

$('#RecordsWrapper')
    .on("click" , "[id*=cmdUpdate]", "input", function(e){
      fldTarget = $(this);
      fldAccountID = fldTarget.parent().find("#txtAccountID").prop("id");`
    })

...but fldAccountID comes back as undefined.  How can I locate a sub element with an ID that contains 'txtAccountID' under 'Record001' div?

  <input type='text' id='txtAccount_001'>
  <input type='text' id='txtEntry_001'>
  <input type='text' id='txtValue_001'>
  <input type='submit' id='cmdUpdate_001'>

  <input type='text' id='txtAccount_002'>
  <input type='text' id='txtEntry_002'>
  <input type='text' id='txtValue_002'>
  <input type='submit' id='cmdUpdate_002'>

Body:
use attribute selector:

Attribute selectors

Attribute selectors select an element using the presence of a given attribute or attribute value.

REF: https://developer.mozilla.org/en/docs/Web/CSS/Attribute_selectors

REF (more example here): https://www.w3schools.com/css/css_attribute_selectors.asp

$('input[id^=txtEntry]').css('background', 'green');

$('#RecordsWrapper')
  .on("click", "input[id^=cmdUpdate]", "input", function(e) {
    fldTarget = $(this);
    fldAccountID = fldTarget.parent().find("input[id^=txtAccount]").prop("id");
    console.log('fldAccountID-->' + fldAccountID);
  })

input[id^=txtAccount] {
  background: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='RecordsWrapper'>
  <div id='Record001'>
    <input type='text' id='txtAccount_001'>
    <input type='text' id='txtEntry_001'>
    <input type='text' id='txtValue_001'>
    <input type='submit' id='cmdUpdate_001'>
  </div>
  <div id='Record002'>
    <input type='text' id='txtAccount_002'>
    <input type='text' id='txtEntry_002'>
    <input type='text' id='txtValue_002'>
    <input type='submit' id='cmdUpdate_002'>
  </div>
</div>


问:
Executing wait-for-it.sh in python Docker container
I have a Python docker container that needs to wait until another container (postgres server) finishes setup.  I tried the standard wait-for-it.sh but several commands weren't included. I tried a basic sleep (again in an sh file) but now it's reporting exec: 300: not found when trying to finally execute the command I'm waiting on.

How do I get around this (preferably without changing the image, or having to extend an image.)

I know I could also just run a Python script, but ideally I'd like to use wait-for-it.sh to wait for the server to turn up rather than just sleep.

Dockerfile (for stuffer):

```<code> FROM python:2.7.13

 ADD ./stuff/bin /usr/local/bin/
 ADD ./stuff /usr/local/stuff
 WORKDIR /usr/local/bin

 COPY requirements.txt /opt/updater/requirements.txt
 COPY internal_requirements.txt /opt/stuff/internal_requirements.txt

 RUN pip install -r /opt/stuff/requirements.txt
 RUN pip install -r /opt/stuff/other_requirements.txt
</code>```

docker-compose.yml:

```<code> version: '3'
 services:
   local_db:
     build: ./local_db
     ports:
     - "localhost:5432:5432"

   stuffer:
     build: ./
     depends_on:
     - local_db
     command: ["./wait-for-postgres.sh", "-t", "300", "localhost:5432", "--", "python", "./stuffing.py", "--file", "./afile"]
</code>```

Script I want to use (but can't because no psql or exec):

```<code> #!/bin/bash
 # wait-for-postgres.sh

 set -e

 host="$1"
 shift
 cmd="$@"

 until psql -h "$host" -U "postgres" -c '\l'; do >&2 echo "Postgres is unavailable - sleeping"
   sleep 1
 done

 >&2 echo "Postgres is up - executing command"
 exec $cmd
</code>```

答: Sergey's comment. I had wrong argument order. This issue had nothing to do with docker and everything to do with my inability to read.</p>

Body:
I have a Python docker container that needs to wait until another container (postgres server) finishes setup.  I tried the standard wait-for-it.sh but several commands weren't included. I tried a basic sleep (again in an sh file) but now it's reporting exec: 300: not found when trying to finally execute the command I'm waiting on.

How do I get around this (preferably without changing the image, or having to extend an image.)

I know I could also just run a Python script, but ideally I'd like to use wait-for-it.sh to wait for the server to turn up rather than just sleep.

Dockerfile (for stuffer):

 FROM python:2.7.13

 ADD ./stuff/bin /usr/local/bin/
 ADD ./stuff /usr/local/stuff
 WORKDIR /usr/local/bin

 COPY requirements.txt /opt/updater/requirements.txt
 COPY internal_requirements.txt /opt/stuff/internal_requirements.txt

 RUN pip install -r /opt/stuff/requirements.txt
 RUN pip install -r /opt/stuff/other_requirements.txt

docker-compose.yml:

 version: '3'
 services:
   local_db:
     build: ./local_db
     ports:
     - "localhost:5432:5432"

   stuffer:
     build: ./
     depends_on:
     - local_db
     command: ["./wait-for-postgres.sh", "-t", "300", "localhost:5432", "--", "python", "./stuffing.py", "--file", "./afile"]

Script I want to use (but can't because no psql or exec):

 #!/bin/bash
 # wait-for-postgres.sh

 set -e

 host="$1"
 shift
 cmd="$@"

 until psql -h "$host" -U "postgres" -c '\l'; do >&2 echo "Postgres is unavailable - sleeping"
   sleep 1
 done

 >&2 echo "Postgres is up - executing command"
 exec $cmd


问:
Access 2007 Memo Field and C# Winform
Well I am stumped.  I have a access DB that I need to convert to using C# winforms.  Everything was fine until I started working with the Memo fields.  Everything is in HTML and the RichTextBox in C# wont accept the data.

How can I maintain the formatting in the access database and also edit and save back to access from c#?

Have been searching Google for the last 5 hours and not really coming up with much.  How can I display the memo in C# formatted and then save it back?

答: The RichTextBox is a control for editing RTF. So you would have to convert the memo HTML to RTF when loading and from RTF to HTML when saving. Alternatively you could edit the memo field using an WYSIWYG HTML editor control.</p>

Title: Access 2007 Memo Field and C# Winform


问:
How to detect windows 32bit or 64 bit using NSIS script?
I have written nsis script for java project.I have Batch file in my project.I have written batch file for commonly windows 32bit and 64 bit.After installing i have started batch file automatically using Exec command.Its woks fine in 32bit windows.but the same time this is not worked well in 64 bit.so i suspect that before installing  i should check whether windows is 32 bit or 64 bit version.please share your views how to check?

答:
Here's what I use most of the time without the need for x64.nsh

```<code>Var Bit
System::Call "kernel32::GetCurrentProcess()i.s"
System::Call "kernel32::IsWow64Process(is,*i.r0)"
StrCmpS $0 0 +3
StrCpy $Bit 64
Goto +2
StrCpy $Bit 32
</code>```

Now $Bit holds either 64 or 32 which can be used like this:

```<code>${If} $Bit == 64
     ...64-bit code..
${Else}
     ..32-bit code...
${EndIf}
</code>```

Or

```<code>StrCmpS $Bit 64 SixtyFour ThirtyTwo

SixtyFour:
    ...
    Goto End
ThirtyTwo:
    ...
End:
</code>```

I used StrCmpS as I believe it's a hair faster. Lol. Hope this helps! =)

Body:
Here's what I use most of the time without the need for x64.nsh

Var Bit
System::Call "kernel32::GetCurrentProcess()i.s"
System::Call "kernel32::IsWow64Process(is,*i.r0)"
StrCmpS $0 0 +3
StrCpy $Bit 64
Goto +2
StrCpy $Bit 32

Now $Bit holds either 64 or 32 which can be used like this:

${If} $Bit == 64
     ...64-bit code..
${Else}
     ..32-bit code...
${EndIf}

Or

StrCmpS $Bit 64 SixtyFour ThirtyTwo

SixtyFour:
    ...
    Goto End
ThirtyTwo:
    ...
End:

I used StrCmpS as I believe it's a hair faster. Lol. Hope this helps! =)


问:
Converting list of objects with map to array of primitives
I keep finding pieces of something I need to do, but I'm having trouble putting it all together. To start, here is my object, put simply:

```<code>Object1
    Object2
        Map<String, Double>
</code>```

What I need to do is, starting with a list of Object1, get a double[] for the values of the map given a specific key (all Objects in the list have the same N keys in the map).

Here was my starting attempt:

```<code>myList.stream().map(Object1::getObject2).map(Object2::getMyMap).map(m -> m.get(key).collect(Collectors.toCollection(ArrayList::new))
</code>```

I'm not sure how to get to the primitive array from here. If this is good so far, where do I go from here? If there a better way to do this whole thing, I'm open to suggestions. Any help is appreciated, thank you.

答:
Use .mapToDouble to make a DoubleStream:

```<code>myList.stream()
    .map(Object1::getObject2)
    .map(Object2::getMyMap)
    .mapToDouble(m -> m.get(key))  // or throw if key is not in map
    .toArray();
</code>```

Body:
I keep finding pieces of something I need to do, but I'm having trouble putting it all together. To start, here is my object, put simply:

Object1
    Object2
        Map<String, Double>

What I need to do is, starting with a list of Object1, get a double[] for the values of the map given a specific key (all Objects in the list have the same N keys in the map).

Here was my starting attempt:

myList.stream().map(Object1::getObject2).map(Object2::getMyMap).map(m -> m.get(key).collect(Collectors.toCollection(ArrayList::new))

I'm not sure how to get to the primitive array from here. If this is good so far, where do I go from here? If there a better way to do this whole thing, I'm open to suggestions. Any help is appreciated, thank you.

Body:
Use .mapToDouble to make a DoubleStream:

myList.stream()
    .map(Object1::getObject2)
    .map(Object2::getMyMap)
    .mapToDouble(m -> m.get(key))  // or throw if key is not in map
    .toArray();


问:
How can I preserve order with an EnumMap in java
I have an EnumMap that I'm using and I will need to keep the order of the items that I'm passing in. I know that when using a HashMap, I can initialize a LinkedHashMap in order to preserve order like so:

```<code>HashMap<String, List<String>> contentTypeToIdList = new LinkedHashMap<String, List<String>>();
</code>```

However, I'd like to use an EnumMap instead. How would I be able to do something like this:

```<code>EnumMap<ContentType, List<String>> contentTypeToIdList = new LinkedHashMap<ContentType, List<String>>();
</code>```

答:
As the API tells us:

Enum maps are maintained in the natural order of their keys (the order in which the enum constants are declared). This is reflected in the iterators returned by the collections views (keySet(), entrySet(), and values()).

This means it is internally sorted and simply not supposed to be ordered differently, e.g. insertion order as you need it.

Body:
I have an EnumMap that I'm using and I will need to keep the order of the items that I'm passing in. I know that when using a HashMap, I can initialize a LinkedHashMap in order to preserve order like so:

HashMap<String, List<String>> contentTypeToIdList = new LinkedHashMap<String, List<String>>();

However, I'd like to use an EnumMap instead. How would I be able to do something like this:

EnumMap<ContentType, List<String>> contentTypeToIdList = new LinkedHashMap<ContentType, List<String>>();


问:
android studio cannot find "Activity" symbol
I have tried to create and run hello world new app using Android studio.
however i cannot compile as it says it's cannot resolve Activity symbol.

and also other basic symbols in the black template.

I suggest adding/configuration the JDK.

I guess I'm doing this wrong, because I have tried to add the JDK and the problem re-occurred.

how to solve this?

UPDATE1

couldn't find external build

Android studio 0.2.6

答:
Make sure to import android.app.Activity.</p>

```<code>import android.app.Activity;
</code>```

Body:
Make sure to import android.app.Activity.

import android.app.Activity;


问:
The field 'usernameCanonical' is not mapped by Doctrine, so it cannot be validated for uniqueness
I am using FOSUserBundle in my Symfony 2.7 project. In the composer.json file the requirement is defined as "friendsofsymfony/user-bundle" : "~2.0@dev". Currently version/commit 45d6f40 (11/03/2015) is installed.

After using composer update the latest version 7abb0ff was installed. After this, I get the following exception when trying to create new users:

The field 'usernameCanonical' is not mapped by Doctrine, so it cannot be validated for uniqueness

Searching for solution for this problem brought up older issues dealing with the same exception (here and here). However I was not able to solve the problem with the solution discussed in these issues.

Issue 1565 proposes to use FOS\UserBundle\Entity\User as BaseUser; instead of FOS\UserBundle\Model\User as BaseUser;. But this solution seems not to be valid for version 2.x. The 2.x documentation says that you should extend from FOS\UserBundle\Model\User, which makes sense since there are no FOS\UserBundle\Entity\... classes anymore.

My User class looks like this:

```<code>namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * This class represents the User entity and extends the FOSBundle base user
 * Entity class to be able to use FOSUserBundle to manage the application users.
 *
 * @ORM\Entity(repositoryClass="AppBundle\Entity\UserRepository")
 * @ORM\Table(name="app_user") *
 * @ORM\HasLifecycleCallbacks()
 */
class User extends BaseUser {
    ...
}
</code>```

In Issue 1638 the solution was to use auto_mapping in the Doctrine configuration. I already did this.

So neither of the existing solutions worked for my. Additional all existing issues to this problem are quite old.

Of course I could simply downgrade back to version/commit 45d6f40. However I would prefer to solve the problem instead of ignoring it :-)

Any other idea how I can solve this?

PS: This is my composer show -i output:

```<code>doctrine/annotations                 v1.2.7             Docblock Annotations Parser
doctrine/cache                       v1.6.0             Caching library offering an object-oriented API for many cache backends
doctrine/collections                 v1.3.0             Collections Abstraction library
doctrine/common                      v2.6.1             Common Library for Doctrine projects
doctrine/dbal                        v2.4.5             Database Abstraction Layer
doctrine/doctrine-bundle             v1.2.0             Symfony DoctrineBundle
doctrine/inflector                   v1.0.1             Common String Manipulations with regard to casing and singular/plural rules.
doctrine/instantiator                1.0.5              A small, lightweight utility to instantiate objects in PHP without invoking their constructors
doctrine/lexer                       v1.0.1             Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.
doctrine/orm                         v2.4.8             Object-Relational-Mapper for PHP
friendsofsymfony/http-cache          1.4.0              Tools to manage cache invalidation
friendsofsymfony/http-cache-bundle   1.3.4              Set path based HTTP cache headers and send invalidation requests to your HTTP cache
friendsofsymfony/rest-bundle         1.4.2              This Bundle provides various tools to rapidly develop RESTful API's with Symfony2
friendsofsymfony/user-bundle         dev-master 7abb0ff Symfony FOSUserBundle
gremo/buzz-bundle                    v1.1.0             Symfony Bundle for using the lightweight Buzz HTTP client.
guzzle/guzzle                        v3.9.3             PHP HTTP client. This library is deprecated in favor of https://packagist.org/packages/guzzlehttp/guzzle
jdorn/sql-formatter                  v1.2.17            a PHP SQL highlighting library
jms/metadata                         1.5.1              Class/method/property metadata management in PHP
jms/parser-lib                       1.0.0              A library for easily creating recursive-descent parsers.
jms/serializer                       1.3.1              Library for (de-)serializing data of any complexity; supports XML, JSON, and YAML.
jms/serializer-bundle                1.1.0              Allows you to easily serialize, and deserialize data of any complexity
kriswallsmith/assetic                v1.3.2             Asset Management for PHP
kriswallsmith/buzz                   v0.15              Lightweight HTTP client
leafo/scssphp                        v0.6.6             scssphp is a compiler for SCSS written in PHP.
moontoast/math                       1.1.0              A mathematics library, providing functionality for large numbers
paragonie/random_compat              v2.0.2             PHP 5.x polyfill for random_bytes() and random_int() from PHP 7
phpcollection/phpcollection          0.5.0              General-Purpose Collection Library for PHP
phpoption/phpoption                  1.5.0              Option Type for PHP
psr/log                              1.0.0              Common interface for logging libraries
sensio/distribution-bundle           v2.3.22            The base bundle for the Symfony Distributions
sensio/framework-extra-bundle        v2.3.4             This bundle provides a way to configure your controllers with annotations
sensio/generator-bundle              v2.3.5             This bundle generates code for you
swiftmailer/swiftmailer              v5.4.3             Swiftmailer, free feature-rich PHP mailer
symfony/assetic-bundle               v2.7.1             Integrates Assetic into Symfony2
symfony/monolog-bundle               v2.8.2             Symfony MonologBundle
symfony/swiftmailer-bundle           v2.3.11            Symfony SwiftmailerBundle
symfony/symfony                      v2.7.7             The Symfony PHP framework
tfox/mpdf-port-bundle                1.3.1              A wrapper for mPDF class which allows to use mPDF in Symfony2 projects
twig/extensions                      v1.0.1             Common additional features for Twig that do not directly belong in core
twig/twig                            v1.25.0            Twig, the flexible, fast, and secure template language for PHP
willdurand/jsonp-callback-validator  v1.1.0             JSONP callback validator.
willdurand/negotiation               1.5.0              Content Negotiation tools for PHP provided as a standalone library.
</code>```

答:
Maybe this solve someone problems when you get the error

The field 'usernameCanonical' is not mapped by Doctrine, so it cannot be validated for uniqueness

One cause is using FOS\UserBundle\Model\User as BaseUser and running doctrine schema:update, if you did this you create a table on a database without several columns like username, usernameCanonical, password, etc.

When you want to access to any functionalities of this you get that message.

How to fix:

Dropping table fos_user on database

Change FOS\UserBundle\Model\User as BaseUser
to
FOS\UserBundle\Entity\User as BaseUser

Run php app/console doctrine:schema:update --force

Body:
I am using FOSUserBundle in my Symfony 2.7 project. In the composer.json file the requirement is defined as "friendsofsymfony/user-bundle" : "~2.0@dev". Currently version/commit 45d6f40 (11/03/2015) is installed.

After using composer update the latest version 7abb0ff was installed. After this, I get the following exception when trying to create new users:

The field 'usernameCanonical' is not mapped by Doctrine, so it cannot be validated for uniqueness

Searching for solution for this problem brought up older issues dealing with the same exception (here and here). However I was not able to solve the problem with the solution discussed in these issues.

Issue 1565 proposes to use FOS\UserBundle\Entity\User as BaseUser; instead of FOS\UserBundle\Model\User as BaseUser;. But this solution seems not to be valid for version 2.x. The 2.x documentation says that you should extend from FOS\UserBundle\Model\User, which makes sense since there are no FOS\UserBundle\Entity\... classes anymore.

My User class looks like this:

namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * This class represents the User entity and extends the FOSBundle base user
 * Entity class to be able to use FOSUserBundle to manage the application users.
 *
 * @ORM\Entity(repositoryClass="AppBundle\Entity\UserRepository")
 * @ORM\Table(name="app_user") *
 * @ORM\HasLifecycleCallbacks()
 */
class User extends BaseUser {
    ...
}

In Issue 1638 the solution was to use auto_mapping in the Doctrine configuration. I already did this.

So neither of the existing solutions worked for my. Additional all existing issues to this problem are quite old.

Of course I could simply downgrade back to version/commit 45d6f40. However I would prefer to solve the problem instead of ignoring it :-)

Any other idea how I can solve this?

PS: This is my composer show -i output:

doctrine/annotations                 v1.2.7             Docblock Annotations Parser
doctrine/cache                       v1.6.0             Caching library offering an object-oriented API for many cache backends
doctrine/collections                 v1.3.0             Collections Abstraction library
doctrine/common                      v2.6.1             Common Library for Doctrine projects
doctrine/dbal                        v2.4.5             Database Abstraction Layer
doctrine/doctrine-bundle             v1.2.0             Symfony DoctrineBundle
doctrine/inflector                   v1.0.1             Common String Manipulations with regard to casing and singular/plural rules.
doctrine/instantiator                1.0.5              A small, lightweight utility to instantiate objects in PHP without invoking their constructors
doctrine/lexer                       v1.0.1             Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.
doctrine/orm                         v2.4.8             Object-Relational-Mapper for PHP
friendsofsymfony/http-cache          1.4.0              Tools to manage cache invalidation
friendsofsymfony/http-cache-bundle   1.3.4              Set path based HTTP cache headers and send invalidation requests to your HTTP cache
friendsofsymfony/rest-bundle         1.4.2              This Bundle provides various tools to rapidly develop RESTful API's with Symfony2
friendsofsymfony/user-bundle         dev-master 7abb0ff Symfony FOSUserBundle
gremo/buzz-bundle                    v1.1.0             Symfony Bundle for using the lightweight Buzz HTTP client.
guzzle/guzzle                        v3.9.3             PHP HTTP client. This library is deprecated in favor of https://packagist.org/packages/guzzlehttp/guzzle
jdorn/sql-formatter                  v1.2.17            a PHP SQL highlighting library
jms/metadata                         1.5.1              Class/method/property metadata management in PHP
jms/parser-lib                       1.0.0              A library for easily creating recursive-descent parsers.
jms/serializer                       1.3.1              Library for (de-)serializing data of any complexity; supports XML, JSON, and YAML.
jms/serializer-bundle                1.1.0              Allows you to easily serialize, and deserialize data of any complexity
kriswallsmith/assetic                v1.3.2             Asset Management for PHP
kriswallsmith/buzz                   v0.15              Lightweight HTTP client
leafo/scssphp                        v0.6.6             scssphp is a compiler for SCSS written in PHP.
moontoast/math                       1.1.0              A mathematics library, providing functionality for large numbers
paragonie/random_compat              v2.0.2             PHP 5.x polyfill for random_bytes() and random_int() from PHP 7
phpcollection/phpcollection          0.5.0              General-Purpose Collection Library for PHP
phpoption/phpoption                  1.5.0              Option Type for PHP
psr/log                              1.0.0              Common interface for logging libraries
sensio/distribution-bundle           v2.3.22            The base bundle for the Symfony Distributions
sensio/framework-extra-bundle        v2.3.4             This bundle provides a way to configure your controllers with annotations
sensio/generator-bundle              v2.3.5             This bundle generates code for you
swiftmailer/swiftmailer              v5.4.3             Swiftmailer, free feature-rich PHP mailer
symfony/assetic-bundle               v2.7.1             Integrates Assetic into Symfony2
symfony/monolog-bundle               v2.8.2             Symfony MonologBundle
symfony/swiftmailer-bundle           v2.3.11            Symfony SwiftmailerBundle
symfony/symfony                      v2.7.7             The Symfony PHP framework
tfox/mpdf-port-bundle                1.3.1              A wrapper for mPDF class which allows to use mPDF in Symfony2 projects
twig/extensions                      v1.0.1             Common additional features for Twig that do not directly belong in core
twig/twig                            v1.25.0            Twig, the flexible, fast, and secure template language for PHP
willdurand/jsonp-callback-validator  v1.1.0             JSONP callback validator.
willdurand/negotiation               1.5.0              Content Negotiation tools for PHP provided as a standalone library.


问:
Apple ResearchKit cause Missing Info.plist key
I am doing a project using ResearchKit by Apple and my app is using it as a framework. I've already imported it into the same folder of my current project and everything built and runs just fine. To be specific I've added the framework into 3 places.

Embedded Binaries

Linked Frameworks and Libraries

Which should work fine as a normal procedure of linking frameworks. I end up getting this email from Apple Developer when I submit the app to Apple and I think that the problem is with ResearchKit info.plist itself. If anyone has the same problem it would be great to share how to solve the problem. My app didn't ask user for NSMotionUsageDescription, NSMicrophoneUsageDescription, NSHealthUpdateUsageDescription, and NSHealthShareUsageDescription. I think that is the work of ResearchKit.

Thank you for your help in advance! :)

答:
You should just add NSMicrophoneUsageDescription and other keys & values in to your plist file, and add the justification as to why your app would be using them. They won't be shown to the user until your app attempts to use those APIs. </p>

```<code><key>NSMicrophoneUsageDescription</key>
<string>Need microphone access for uploading videos</string>
</code>```

<p>Etc....Do this for each key. </p>

Body:
You should just add NSMicrophoneUsageDescription and other keys & values in to your plist file, and add the justification as to why your app would be using them. They won't be shown to the user until your app attempts to use those APIs.

<key>NSMicrophoneUsageDescription</key>
<string>Need microphone access for uploading videos</string>

Etc....Do this for each key.


问:
How can I convert an 2D int array into a 2D String array with Streams?
I am attempting to convert a 2D int array into a 2D String array with this code:

```<code>Arrays.stream(intArray).map(a ->
    Arrays.stream(a).map(i ->
        Integer.toString(i)).toArray()).toArray(String[][]::new);
</code>```

but I get the compile-time error cannot convert from String to int when doing Integer.toString(i). I thought it could be because I'm collecting the results of streaming an int array in a String array, but doesn't map create a new Collection?

答:
Arrays.stream on an int[] returns an IntStream, and to go from an int to a String or any other Object, you have to use the IntStream.mapToObj method, not the map method:

```<code>Arrays.stream(intArray).map(a ->
    Arrays.stream(a).mapToObj(i ->
        Integer.toString(i)).toArray(String[]::new)).toArray(String[][]::new);
</code>```

The map method of IntStream is only used to map from an int to an int.

Body:
I am attempting to convert a 2D int array into a 2D String array with this code:

Arrays.stream(intArray).map(a ->
    Arrays.stream(a).map(i ->
        Integer.toString(i)).toArray()).toArray(String[][]::new);

but I get the compile-time error cannot convert from String to int when doing Integer.toString(i). I thought it could be because I'm collecting the results of streaming an int array in a String array, but doesn't map create a new Collection?

Body:
Arrays.stream on an int[] returns an IntStream, and to go from an int to a String or any other Object, you have to use the IntStream.mapToObj method, not the map method:

Arrays.stream(intArray).map(a ->
    Arrays.stream(a).mapToObj(i ->
        Integer.toString(i)).toArray(String[]::new)).toArray(String[][]::new);

The map method of IntStream is only used to map from an int to an int.


问:
MySQL indexing for multiple count(*) queries
I'm lost regarding indexing.  I have a moderately complex web app that I'm building for a client and it has several count(*) queries that are all running very slow (0.3 seconds)

Here's a quick example

```<code>SELECT COUNT( * ) AS  `count`
FROM  `vehicles`
WHERE  `VehicleLocation_province` =  'Alberta'
AND  `default_image_URI` IS NOT NULL
AND  `default_image_URI` !=  ''
</code>```

Here's the explain..

```<code> 1 SIMPLE vehicles ref VehicleLocation_province,VehicleLocation_province_...     VehicleLocation_province 2 const 14128 Using where
</code>```

I can't even get this query to use a proper index, never mind some of the more complex queries such as

```<code>SELECT * , ( 6371 * ACOS( COS( RADIANS( 53.543564 ) ) * COS( RADIANS( lat ) ) * COS( RADIANS( lng ) - RADIANS( - 113.490456 ) ) + SIN( RADIANS( 53.543564 ) ) * SIN( RADIANS( lat ) ) ) ) AS  `distance`
FROM  `vehicles`
WHERE  `Make` =  'Pontiac'
AND  `BodyStyle` =  'Sedan'
AND  `VehiclePrice` >=  '1'
AND  `VehiclePrice` <=  '36000'
AND  `VehiclePrice` IS NOT NULL
AND  `default_image_URI` IS NOT NULL
AND  `default_image_URI` !=  ''
HAVING `distance` < 50
ORDER BY `VehicleReceivedDate` DESC LIMIT 25
</code>```

Explain

```<code>1 SIMPLE vehicles ref Make,BodyStyle,VehicleLocation_province_2 Make 99 const 5821 Using where; Using filesort
</code>```

I know I need to avoid temp tables and filesorts where possible... but how is this practically accomplished when several of these count(*) queries must be executed on each request with varying where parameters grouping and ordering?

答:
Well, the only way to get indexes speed up queries is to have indexes cover enough conditions that the selectivity becomes useful (or for RDBMS to be able to use indexes to calculate aggregates such as count).

Do not fail to realize that having index on (Make) and index on (BodyStyle) is not the same as having index on (Make, BodyStyle).

In your first query, when you need to count the records, the existence of index that covers default_image_URI and VehicleLocation_province should be enough for the mysql not to do a table scan, but retrieve the count from the index.

You can check this by creating an index (VehicleLocation_province, default_image_URI) and then running query and/or examining explain.

In the second query you have similar situation with query that has more conditions (which is good as long as they are all AND conditions) and it is not about counting records, but actually retrieving the data from the table and sorting.

Few notes here:

notice your conditions IS NOT NULL and !='' - if these conditions are commonly present in your queries then these suggest that your design is not proper, and that you have denormalised different entities into one table so now you have to sort them out each time you want to use the data (this is just an indication, and I assume that you apply these conditions a lot, which might not be true)

having said that, if you look at 2nd query and if Make and BodyStyle are covered with a composite index and have low selectivity the query will still perform fast

mysql has to choose one index to access the data and it will try to choose the index that returns least number of rows given statistics and available conditions (so that further conditions have to loop through least number of records) - if that index helps only with reducing the resultset the sorting will be done using a filesort. For index to be useful for both selecting rows and sorting it should have useful order or indexed columns, for example in the above query index on (Make, BodyStyle, VehicleReceivedDate) might do the trick

adding proper indexes on your table should help, but indexes can not fix problems with design

Body:
I'm lost regarding indexing.  I have a moderately complex web app that I'm building for a client and it has several count(*) queries that are all running very slow (0.3 seconds)

Here's a quick example

SELECT COUNT( * ) AS  `count`
FROM  `vehicles`
WHERE  `VehicleLocation_province` =  'Alberta'
AND  `default_image_URI` IS NOT NULL
AND  `default_image_URI` !=  ''

Here's the explain..

 1 SIMPLE vehicles ref VehicleLocation_province,VehicleLocation_province_...     VehicleLocation_province 2 const 14128 Using where

I can't even get this query to use a proper index, never mind some of the more complex queries such as

SELECT * , ( 6371 * ACOS( COS( RADIANS( 53.543564 ) ) * COS( RADIANS( lat ) ) * COS( RADIANS( lng ) - RADIANS( - 113.490456 ) ) + SIN( RADIANS( 53.543564 ) ) * SIN( RADIANS( lat ) ) ) ) AS  `distance`
FROM  `vehicles`
WHERE  `Make` =  'Pontiac'
AND  `BodyStyle` =  'Sedan'
AND  `VehiclePrice` >=  '1'
AND  `VehiclePrice` <=  '36000'
AND  `VehiclePrice` IS NOT NULL
AND  `default_image_URI` IS NOT NULL
AND  `default_image_URI` !=  ''
HAVING `distance` < 50
ORDER BY `VehicleReceivedDate` DESC LIMIT 25

Explain

1 SIMPLE vehicles ref Make,BodyStyle,VehicleLocation_province_2 Make 99 const 5821 Using where; Using filesort

I know I need to avoid temp tables and filesorts where possible... but how is this practically accomplished when several of these count(*) queries must be executed on each request with varying where parameters grouping and ordering?


问:
Angular 2 Observable.retryWhen doesn't include status in error
I am trying to get my code updated so that I am able to use refresh tokens to keep a user logged in. I intend to do this using the Observable.retryWhen method. However I am running into an issue where the error being passed to my retry method has a type of Subject instead of Response like I expected and have gotten in the past. This is an issue because I need to check if the status is a 401 and Subject doesn't include the status of the response. Also the catch works as expected passing a Response object to the handleError method.

http.service.ts

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { Http, Headers, RequestOptions, Response } from '@angular/http';

@Injectable()
export class HttpService {

  constructor(
    private http: Http
  ) { }

  public get(url: string, headers?: Headers): Observable<any> {
    return this.http.get(url, this.getHeaders(headers))
      .map(this.extractData)
      .retryWhen(this.handleRetry)
      .catch(this.handleError);
  }

  private handleRetry(error: Response): Observable<any> {
    if (error.status === 401) { // I can't get past here because error doesn't include status and is the wrong type.
      ...
    }
  }
}
</code>```

Error equals

```<code>Subject {
  closed: false
  hasError: false
  isStopped: false
  observers: Array(0)
  thrownError: null
  _isScalar: false
}
</code>```

While I expect error to equal something similar to:

```<code>Response {
  headers: Headers
  ok: false
  status: 401
  statusText: "OK"
  type: 2
  url: "..."
  _body: ""
}
</code>```

答:
The function passed to retryWhen does not receive an Error; it receives an Observable<Error> argument. That is why you are seeing a Subject.

The logic in your handleRetry function needs to be composed into an observable, from within which any effected errors can be inspected. mergeMap could be used to retry some errors and fail others. For example:

private handleRetry(errors: Observable<Response>): Observable<any> {

  return errors.mergeMap(error => {

    if (error.status === 401) {

      // Add an authorization header, perhaps.
      // ...
      // Emit anything (the error instance, for example) to retry:
      return Observable.of(error);

    } else {

      // Throw the error to give up retrying:
      return Observable.throw(error);
    }
  });
}
```

Body:
I am trying to get my code updated so that I am able to use refresh tokens to keep a user logged in. I intend to do this using the Observable.retryWhen method. However I am running into an issue where the error being passed to my retry method has a type of Subject instead of Response like I expected and have gotten in the past. This is an issue because I need to check if the status is a 401 and Subject doesn't include the status of the response. Also the catch works as expected passing a Response object to the handleError method.

http.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { Http, Headers, RequestOptions, Response } from '@angular/http';

@Injectable()
export class HttpService {

  constructor(
    private http: Http
  ) { }

  public get(url: string, headers?: Headers): Observable<any> {
    return this.http.get(url, this.getHeaders(headers))
      .map(this.extractData)
      .retryWhen(this.handleRetry)
      .catch(this.handleError);
  }

  private handleRetry(error: Response): Observable<any> {
    if (error.status === 401) { // I can't get past here because error doesn't include status and is the wrong type.
      ...
    }
  }
}

Error equals

Subject {
  closed: false
  hasError: false
  isStopped: false
  observers: Array(0)
  thrownError: null
  _isScalar: false
}

While I expect error to equal something similar to:

Response {
  headers: Headers
  ok: false
  status: 401
  statusText: "OK"
  type: 2
  url: "..."
  _body: ""
}