问:
jQuery not recognizing Symfony JSON?
I'm trying to get my JSON data from Symfony but it doesn't seem to be working right. Below is the snippet of symfony code:

```<code>$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
return $this->renderPartial('listJsonResponse',
array('jsonSlots' => json_encode($this->jsonQuery)));
</code>```

The above works fine and hits the partial. All that is in my partial is this:

```<code><?php echo $jsonSlots ?>
</code>```

Now according to Firebug this gets populated properly. Below is a copy of the response

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

Note if I take out the Content/Type header it changes slightly. I get the same response tab as above but also an html tab with the above parsed into html. Which shows like this:

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

I know the JSON function is hitting, but it isn't parsing the success function and alerting me any sort of data. the JavasScript is shown below and is wrapped in a jquery ready tag

```<code>$.getJSON('/frontend_dev.php/module/listJSONSlots', function(data) {
    alert(data);
});
</code>```

Any ideas why I can't get to the alert?

答:
Try json_encode($input, true) to force it to encode as an object.

Technically JSON's top-level container must be an object (enclosed with {}) and not an array (enclosed with []).

The value of a property on a JSON object can be an array, but an array is not a JSON object.

Title: jQuery not recognizing Symfony JSON?

Body:
I'm trying to get my JSON data from Symfony but it doesn't seem to be working right. Below is the snippet of symfony code:

$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
return $this->renderPartial('listJsonResponse',
array('jsonSlots' => json_encode($this->jsonQuery)));

The above works fine and hits the partial. All that is in my partial is this:

<?php echo $jsonSlots ?>

Now according to Firebug this gets populated properly. Below is a copy of the response

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

Note if I take out the Content/Type header it changes slightly. I get the same response tab as above but also an html tab with the above parsed into html. Which shows like this:

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

I know the JSON function is hitting, but it isn't parsing the success function and alerting me any sort of data. the JavasScript is shown below and is wrapped in a jquery ready tag

$.getJSON('/frontend_dev.php/module/listJSONSlots', function(data) {
    alert(data);
});

Any ideas why I can't get to the alert?


来源: stackexchange

问:
How to instantiate RealmQuery object in Realm Android [4.2.0]
In order to write less code when reading from realm database, I was creating RealmQuery objects and then pass them to a static method which could further handle sorting/finding results/copying results to list and closing realm instance like this

```<code>RealmQuery query = RealmQuery.createQuery(realm, Section.class)
                .equalTo(Section.TENT_ID_FIELD, mVisit.tentID);
</code>```

However, since the recent updates, RealmQuery.createQuery is set to package-private, and I couldn't find a public method which returns RealmQuery. Is it still possible to create these query objects because it would be really helpful?

答:
OK, just realized it's pretty straightforward, just replace

```<code>RealmQuery query = RealmQuery.createQuery(realm, Section.class)
                .equalTo(Section.TENT_ID_FIELD, mVisit.tentID);
</code>```

with

```<code>RealmQuery query = realm.where(Section.class)
                .equalTo(Section.TENT_ID_FIELD, mVisit.tentID);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In order to write less code when reading from realm database, I was creating RealmQuery objects and then pass them to a static method which could further handle sorting/finding results/copying results to list and closing realm instance like this

RealmQuery query = RealmQuery.createQuery(realm, Section.class)
                .equalTo(Section.TENT_ID_FIELD, mVisit.tentID);

However, since the recent updates, RealmQuery.createQuery is set to package-private, and I couldn't find a public method which returns RealmQuery. Is it still possible to create these query objects because it would be really helpful?

Body:
OK, just realized it's pretty straightforward, just replace

RealmQuery query = RealmQuery.createQuery(realm, Section.class)
                .equalTo(Section.TENT_ID_FIELD, mVisit.tentID);

with

RealmQuery query = realm.where(Section.class)
                .equalTo(Section.TENT_ID_FIELD, mVisit.tentID);


问:
How to hide certain columns (from a table) on mobile?
I am having great problems with using tables - they look perfect on a desktop - but not on mobile.
So here's a break up of what I want to do:

If @media screen is 600px then the number of columns = 3& the number of rows = 3

if @media screen is 460px or less then columnCount = 2, rowCount = 4

and columnCount = 4, rowCount =4 on desktop

How can I achieve this?

答:
Hiding the second column in a table on a screen narrower than 600 pixels and additionally hiding the third column on a screen narrower than 460 pixels, goes like this:

```<code>@media screen and (max-width: 600px) {
    tr > *:nth-child(2) {
        display: none;
    }
}

@media screen and (max-width: 460px) {
    tr > *:nth-child(3) {
        display: none;
    }
}
</code>```

Change the column numbers to your liking (the 2 and the 3).

WARNING: I do not think this is a good solution, as a truly responsive table shows all content on all screen sizes. In general I think that content on mobile and desktop should be the same. This answer is only added to meet the exact requirements of the OP.

Body:
Hiding the second column in a table on a screen narrower than 600 pixels and additionally hiding the third column on a screen narrower than 460 pixels, goes like this:

@media screen and (max-width: 600px) {
    tr > *:nth-child(2) {
        display: none;
    }
}

@media screen and (max-width: 460px) {
    tr > *:nth-child(3) {
        display: none;
    }
}

Change the column numbers to your liking (the 2 and the 3).

WARNING: I do not think this is a good solution, as a truly responsive table shows all content on all screen sizes. In general I think that content on mobile and desktop should be the same. This answer is only added to meet the exact requirements of the OP.


问:
Meteor MongoDB return single object
```<code>{
    "_id" : "R9zbu8oTWwgxT5eCR",
    "practiceSetup" : {
        "operatoriesSettings" : [
            {
                "name" : "Operatory 1",
                "description" : "Room 1",
                "status" : true
            },
                            {
                "name" : "Operatory 2",
                "description" : "Room B",
                "status" : true
            }
        ],

}
</code>```

I'm trying to lookup object that has name "Operatory 1" and only return that object.

Here is what I have tried,

```<code>Practice.findOne({ _id: 'R9zbu8oTWwgxT5eCR' }, { "$elemMatch": { "practiceSetup.operatoriesSettings": { "name": "Operatory 1" } } } );
</code>```

However this will return the whole document, not that particular object, not sure what I'm doing wrong here.

答:
That's how $elemMatch projection works:

The $elemMatch operator limits the contents of an  field from the query results to contain only the first element matching the $elemMatch condition.

If you only need that specific subdocument, you get it using JS:

const doc = Practice.findOne(
  { _id: 'R9zbu8oTWwgxT5eCR' },
  {
    $elemMatch: {
      'practiceSetup.operatoriesSettings': {
        name: 'Operatory 1'
      }
    }
  }
);

const operator1 = doc.practiceSetup.operatoriesSettings[0];
```

Title: Meteor MongoDB return single object

Body:
{
    "_id" : "R9zbu8oTWwgxT5eCR",
    "practiceSetup" : {
        "operatoriesSettings" : [
            {
                "name" : "Operatory 1",
                "description" : "Room 1",
                "status" : true
            },
                            {
                "name" : "Operatory 2",
                "description" : "Room B",
                "status" : true
            }
        ],

}

I'm trying to lookup object that has name "Operatory 1" and only return that object.

Here is what I have tried,

Practice.findOne({ _id: 'R9zbu8oTWwgxT5eCR' }, { "$elemMatch": { "practiceSetup.operatoriesSettings": { "name": "Operatory 1" } } } );

However this will return the whole document, not that particular object, not sure what I'm doing wrong here.


问:
Does LINQ new up memory when creating returns
Does LINQ actually perform a deep copy of the results to a different list/array/etc, or does it simply give me a list/array/etc. composed of references to the original?</p>

答:
Does LINQ actually perform a deep copy of the results to a different list/array/etc, or does it simply give me a list/array/etc. composed of references to the original?

From Enumerable.ToArray.  (Similiar text found at Enumerable.ToList)

The ToArray(IEnumerable) method forces immediate query evaluation and returns an array that contains the query results. You can append this method to your query in order to obtain a cached copy of the query results.

Well, that certainly looks confusing.

returns an array that contains the query results

obtain a cached copy of the query results

From the first sentence, it is clear that no copies of items in the query are made.

From the second sentence, you get a copy of the query results as a whole, but that is a shallow copy since no copies of items in the query are made.

ContentLicense: CC BY-SA 2.5


问:
VBA Applying code for multiple locations
Hello I have a macro that copies files from specific folders to a single folder and I am wondering whether the code I have can be altered to pull multiple files from multiple specified folders within one loop, as now I have to create a new module for every single folder path/file.

I have the following code:

```<code>Sub SmplAPP()
    Dim FSO As Object
    Dim FrFldr As String
    Dim ToFldr As String
    Dim myVal1 As Variant
    Dim myValn As String

        myVal1 = InputBox("Please enter today's date in mm-dd format")
        myValn = Replace(myVal1, "-", "\")
        Range("I1").Value = myValn

        FrFldr = "\\xxxf003\sample_data\SAMPLE_REPORTS\APPS\Reports\Regional\SAMPLE_APPLICATION\2017\" & myValn
        ToFldr = "C:\Users\sample\Desktop\logs_to_upload"

            If Right(FrFldr, 1) = "\" Then
                FrFldr = Left(FrFldr, Len(FrFldr) - 1)
            End If

            If Right(ToFldr, 1) = "\" Then
                ToFldr = Left(ToFldr, Len(ToFldr) - 1)
            End If

        Set FSO = CreateObject("scripting.filesystemobject")

            If FSO.FolderExists(FrFldr) = False Then
                MsgBox FrFldr & " doesn't exist"
                Exit Sub
            End If

        FSO.CopyFolder Source:=FrFldr, Destination:=ToFldr

Call NextApp

    End Sub
</code>```

Any help would be greatly appreciated!

答:
If you want copy from different folder, you may use collection. I have amended your subroutine:</p>

```<code>Sub SmplAPP()
    Dim FSO As Object
    Dim collFrFldr As New Collection
    Dim FrFldr As Variant
    Dim ToFldr As String
    Dim myVal1 As Variant
    Dim myValn As String

        myVal1 = InputBox("Please enter today's date in mm-dd format")
        myValn = Replace(myVal1, "-", "\")
        Range("I1").Value = myValn

        collFrFldr.Add "\\xxxf003\sample_data\SAMPLE_REPORTS\APPS\Reports\Regional\SAMPLE_APPLICATION\2017\" & myValn
        collFrFldr.Add "\\another folder"
        collFrFldr.Add "\\yet another folder"

        ToFldr = "c:\Users\u195567\test\"

        If Right(ToFldr, 1) = "\" Then
            ToFldr = Left(ToFldr, Len(ToFldr) - 1)
        End If

        Set FSO = CreateObject("scripting.filesystemobject")

        For Each FrFldr In collFrFldr
            If Right(FrFldr, 1) = "\" Then
                FrFldr = Left(FrFldr, Len(FrFldr) - 1)
            End If

            If FSO.FolderExists(FrFldr) = False Then
                MsgBox FrFldr & " doesn't exist"
                Exit Sub
            End If

        FSO.CopyFolder Source:=FrFldr, Destination:=ToFldr
        Next FrFldr

    Call NextApp

End Sub
</code>```

Body:
Hello I have a macro that copies files from specific folders to a single folder and I am wondering whether the code I have can be altered to pull multiple files from multiple specified folders within one loop, as now I have to create a new module for every single folder path/file.

I have the following code:

Sub SmplAPP()
    Dim FSO As Object
    Dim FrFldr As String
    Dim ToFldr As String
    Dim myVal1 As Variant
    Dim myValn As String

        myVal1 = InputBox("Please enter today's date in mm-dd format")
        myValn = Replace(myVal1, "-", "\")
        Range("I1").Value = myValn

        FrFldr = "\\xxxf003\sample_data\SAMPLE_REPORTS\APPS\Reports\Regional\SAMPLE_APPLICATION\2017\" & myValn
        ToFldr = "C:\Users\sample\Desktop\logs_to_upload"

            If Right(FrFldr, 1) = "\" Then
                FrFldr = Left(FrFldr, Len(FrFldr) - 1)
            End If

            If Right(ToFldr, 1) = "\" Then
                ToFldr = Left(ToFldr, Len(ToFldr) - 1)
            End If

        Set FSO = CreateObject("scripting.filesystemobject")

            If FSO.FolderExists(FrFldr) = False Then
                MsgBox FrFldr & " doesn't exist"
                Exit Sub
            End If

        FSO.CopyFolder Source:=FrFldr, Destination:=ToFldr

Call NextApp

    End Sub

Any help would be greatly appreciated!

Body:
If you want copy from different folder, you may use collection. I have amended your subroutine:

Sub SmplAPP()
    Dim FSO As Object
    Dim collFrFldr As New Collection
    Dim FrFldr As Variant
    Dim ToFldr As String
    Dim myVal1 As Variant
    Dim myValn As String

        myVal1 = InputBox("Please enter today's date in mm-dd format")
        myValn = Replace(myVal1, "-", "\")
        Range("I1").Value = myValn

        collFrFldr.Add "\\xxxf003\sample_data\SAMPLE_REPORTS\APPS\Reports\Regional\SAMPLE_APPLICATION\2017\" & myValn
        collFrFldr.Add "\\another folder"
        collFrFldr.Add "\\yet another folder"

        ToFldr = "c:\Users\u195567\test\"

        If Right(ToFldr, 1) = "\" Then
            ToFldr = Left(ToFldr, Len(ToFldr) - 1)
        End If

        Set FSO = CreateObject("scripting.filesystemobject")

        For Each FrFldr In collFrFldr
            If Right(FrFldr, 1) = "\" Then
                FrFldr = Left(FrFldr, Len(FrFldr) - 1)
            End If

            If FSO.FolderExists(FrFldr) = False Then
                MsgBox FrFldr & " doesn't exist"
                Exit Sub
            End If

        FSO.CopyFolder Source:=FrFldr, Destination:=ToFldr
        Next FrFldr

    Call NextApp

End Sub


问:
Auto-updating time for chatting
How can we get time?

For instance:

1 min ago

1 sec ago

today

yesterday

tuesday

before 7 days (1 week ago) it must show the date.

答:
I've done a similar thing using the DateUtils.getRelativeTimeSpanString().

It will return at date once it's > 1 week

```<code>public String timeSinceNow(Date date) {
    long test = date.getTime();
    String result = "";

    long millis = System.currentTimeMillis();

    long milliseconds = (millis - test);
    long minutes = 0;
    long hours = 0;
    long days = 0;

    days = (int) (milliseconds / (1000 * 60 * 60 * 24));
    hours = (int) ((milliseconds - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
    minutes = (int) (milliseconds - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);

    if (days > 0 || hours > 0 || minutes > 0) {
        if (hours > 0) {
            if (minutes > 0) {
                if (days == 0) {
                    if (hours == 0) {
                        if (minutes < 3) {
                            result = "Now";
                        } else {
                            result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
                        }
                    } else {
                        result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
                    }
                }
                else{
                        result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
                    }

            }else{
                result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
            }
        }else{
            result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
        }
    } else {
        result = "Now";
    }

    return result;
}
</code>```

This will return a String with the difference between "Now" and the date you pass as a parameter

Title: Auto-updating time for chatting

Body:
I've done a similar thing using the DateUtils.getRelativeTimeSpanString().

It will return at date once it's > 1 week

public String timeSinceNow(Date date) {
    long test = date.getTime();
    String result = "";

    long millis = System.currentTimeMillis();

    long milliseconds = (millis - test);
    long minutes = 0;
    long hours = 0;
    long days = 0;

    days = (int) (milliseconds / (1000 * 60 * 60 * 24));
    hours = (int) ((milliseconds - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
    minutes = (int) (milliseconds - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);

    if (days > 0 || hours > 0 || minutes > 0) {
        if (hours > 0) {
            if (minutes > 0) {
                if (days == 0) {
                    if (hours == 0) {
                        if (minutes < 3) {
                            result = "Now";
                        } else {
                            result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
                        }
                    } else {
                        result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
                    }
                }
                else{
                        result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
                    }

            }else{
                result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
            }
        }else{
            result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
        }
    } else {
        result = "Now";
    }

    return result;
}

This will return a String with the difference between "Now" and the date you pass as a parameter


问:
startForeground fail after upgrade to Android 8.1
After upgrading my phone to 8.1 Developer Preview my background service no longer starts up properly.

In my long-running service I've implemented a startForeground method to start the ongoing notification which is called in on create.

```<code>@TargetApi(Build.VERSION_CODES.O)
private fun startForeground() {
    // Safe call, handled by compat lib.
    val notificationBuilder = NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)

    val notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .build()
    startForeground(101, notification)
}
</code>```

Error message:

```<code>11-28 11:47:53.349 24704-24704/$PACKAGE_NAMEE/AndroidRuntime: FATAL EXCEPTION: main
    Process: $PACKAGE_NAME, PID: 24704
    android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=My channel pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>```

invalid channel for service notification, apparently my old channel the DEFAULT_CHANNEL_ID is no longer appropriate for API 27 I assume. What would be the proper channel? I've tried to look through the documentation

答:
Works properly on Andorid 8.1:

Updated sample (without any deprecated code):

```<code>public NotificationBattery(Context context) {
    this.mCtx = context;

    mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setContentTitle(context.getString(R.string.notification_title_battery))
            .setSmallIcon(R.drawable.ic_launcher)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setChannelId(CHANNEL_ID)
            .setOnlyAlertOnce(true)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setWhen(System.currentTimeMillis() + 500)
            .setGroup(GROUP)
            .setOngoing(true);

    mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_view_battery);

    initBatteryNotificationIntent();

    mBuilder.setContent(mRemoteViews);

    mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (AesPrefs.getBooleanRes(R.string.SHOW_BATTERY_NOTIFICATION, true)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, context.getString(R.string.notification_title_battery),
                    NotificationManager.IMPORTANCE_DEFAULT);
            channel.setShowBadge(false);
            channel.setSound(null, null);
            mNotificationManager.createNotificationChannel(channel);
        }
    } else {
        mNotificationManager.cancel(Const.NOTIFICATION_CLIPBOARD);
    }
}
</code>```

Old snipped (it's a different app - not related to the code above):

```<code>@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
    Log.d(TAG, "onStartCommand");

    String CHANNEL_ONE_ID = "com.kjtech.app.N1";
    String CHANNEL_ONE_NAME = "Channel One";
    NotificationChannel notificationChannel = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                CHANNEL_ONE_NAME, IMPORTANCE_HIGH);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setShowBadge(true);
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.createNotificationChannel(notificationChannel);
    }

    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    Notification notification = new Notification.Builder(getApplicationContext())
            .setChannelId(CHANNEL_ONE_ID)
            .setContentTitle(getString(R.string.obd_service_notification_title))
            .setContentText(getString(R.string.service_notification_content))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(icon)
            .build();

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startForeground(START_FOREGROUND_ID, notification);

    return START_STICKY;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
After upgrading my phone to 8.1 Developer Preview my background service no longer starts up properly.

In my long-running service I've implemented a startForeground method to start the ongoing notification which is called in on create.

@TargetApi(Build.VERSION_CODES.O)
private fun startForeground() {
    // Safe call, handled by compat lib.
    val notificationBuilder = NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)

    val notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .build()
    startForeground(101, notification)
}

Error message:

11-28 11:47:53.349 24704-24704/$PACKAGE_NAMEE/AndroidRuntime: FATAL EXCEPTION: main
    Process: $PACKAGE_NAME, PID: 24704
    android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=My channel pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

invalid channel for service notification, apparently my old channel the DEFAULT_CHANNEL_ID is no longer appropriate for API 27 I assume. What would be the proper channel? I've tried to look through the documentation

Body:
Works properly on Andorid 8.1:

Updated sample (without any deprecated code):

public NotificationBattery(Context context) {
    this.mCtx = context;

    mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setContentTitle(context.getString(R.string.notification_title_battery))
            .setSmallIcon(R.drawable.ic_launcher)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setChannelId(CHANNEL_ID)
            .setOnlyAlertOnce(true)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setWhen(System.currentTimeMillis() + 500)
            .setGroup(GROUP)
            .setOngoing(true);

    mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_view_battery);

    initBatteryNotificationIntent();

    mBuilder.setContent(mRemoteViews);

    mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (AesPrefs.getBooleanRes(R.string.SHOW_BATTERY_NOTIFICATION, true)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, context.getString(R.string.notification_title_battery),
                    NotificationManager.IMPORTANCE_DEFAULT);
            channel.setShowBadge(false);
            channel.setSound(null, null);
            mNotificationManager.createNotificationChannel(channel);
        }
    } else {
        mNotificationManager.cancel(Const.NOTIFICATION_CLIPBOARD);
    }
}

Old snipped (it's a different app - not related to the code above):

@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
    Log.d(TAG, "onStartCommand");

    String CHANNEL_ONE_ID = "com.kjtech.app.N1";
    String CHANNEL_ONE_NAME = "Channel One";
    NotificationChannel notificationChannel = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                CHANNEL_ONE_NAME, IMPORTANCE_HIGH);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setShowBadge(true);
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.createNotificationChannel(notificationChannel);
    }

    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    Notification notification = new Notification.Builder(getApplicationContext())
            .setChannelId(CHANNEL_ONE_ID)
            .setContentTitle(getString(R.string.obd_service_notification_title))
            .setContentText(getString(R.string.service_notification_content))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(icon)
            .build();

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startForeground(START_FOREGROUND_ID, notification);

    return START_STICKY;
}


问:
adding print button using jQuery in mobile view. but is not working
I'm try to print content in view of website. but is not working.
screenshot

function myFunction(){
  window.print();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Click the button to print the current page.</p>
<button onclick="myFunction()">Print this page</button></code>```

答:
Try This Code

$(function () {
  $("#btnPrint").click(function () {
    var contents = $("#dvContents").html();
    var frame1 = $('');
    frame1[0].name = "frame1";
    frame1.css({ "position": "absolute", "top": "-1000000px" });
    $("body").append(frame1);
    var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
    frameDoc.document.open();
    //Create a new HTML document.
    frameDoc.document.write('<title>DIV Contents</title>');
    frameDoc.document.write('');
    //Append the external CSS file.
    frameDoc.document.write('<link href="style.css" rel="stylesheet" type="text/css" />');
    //Append the DIV contents.
    frameDoc.document.write(contents);
    frameDoc.document.write('');
    frameDoc.document.close();
    setTimeout(function () {
      window.frames["frame1"].focus();
      window.frames["frame1"].print();
      frame1.remove();
    }, 500);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dvContents">
  <div class="clear"></div>
  <hr />
  <div class="contents">
    <span class="label">Hello,
      <br />
      This is <span class="name">Karan Mehta</span>.<br />
      Hoping that you are enjoying This!
    </span>
  </div>
</div>
<br />
<input type="button" id="btnPrint" value="Print" /></code>```

Body:
I'm try to print content in view of website. but is not working.
screenshot

function myFunction(){
  window.print();
}

Click the button to print the current page.

<button onclick="myFunction()">Print this page</button>

Body:
Try This Code

$(function () {
  $("#btnPrint").click(function () {
    var contents = $("#dvContents").html();
    var frame1 = $('<iframe />');
    frame1[0].name = "frame1";
    frame1.css({ "position": "absolute", "top": "-1000000px" });
    $("body").append(frame1);
    var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
    frameDoc.document.open();
    //Create a new HTML document.
    frameDoc.document.write('<html><head><title>DIV Contents</title>');
    frameDoc.document.write('</head><body>');
    //Append the external CSS file.
    frameDoc.document.write('<link href="style.css" rel="stylesheet" type="text/css" />');
    //Append the DIV contents.
    frameDoc.document.write(contents);
    frameDoc.document.write('</body></html>');
    frameDoc.document.close();
    setTimeout(function () {
      window.frames["frame1"].focus();
      window.frames["frame1"].print();
      frame1.remove();
    }, 500);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dvContents">
  <div class="clear"></div>
  <hr />
  <div class="contents">
    <span class="label">Hello,
      <br />
      This is <span class="name">Karan Mehta</span>.<br />
      Hoping that you are enjoying This!
    </span>
  </div>
</div>
<br />
<input type="button" id="btnPrint" value="Print" />


问:
Getting the highest value of a column in MongoDB
I've been for some help on getting the highest value on a column for a mongo document. I can sort it and get the top/bottom, but I'm pretty sure there is a better way to do it.

I tried the following (and different combinations):

```<code>transactions.find("id" => x).max({"sellprice" => 0})
</code>```

But it keeps throwing errors. What's a good way to do it besides sorting and getting the top/bottom?

Thank you!

答:
max() does not work the way you would expect it to in SQL for Mongo.  This is perhaps going to change in future versions but as of now, max,min are to be used with indexed keys primarily internally for sharding.

see http://www.mongodb.org/display/DOCS/min+and+max+Query+Specifiers

Unfortunately for now the only way to get the max value is to sort the collection desc on that value and take the first.

```<code>transactions.find("id" => x).sort({"sellprice" => -1}).limit(1).first()
</code>```

Body:
I've been for some help on getting the highest value on a column for a mongo document. I can sort it and get the top/bottom, but I'm pretty sure there is a better way to do it.

I tried the following (and different combinations):

transactions.find("id" => x).max({"sellprice" => 0})

But it keeps throwing errors. What's a good way to do it besides sorting and getting the top/bottom?

Thank you!

Body:
max() does not work the way you would expect it to in SQL for Mongo.  This is perhaps going to change in future versions but as of now, max,min are to be used with indexed keys primarily internally for sharding.

see http://www.mongodb.org/display/DOCS/min+and+max+Query+Specifiers

Unfortunately for now the only way to get the max value is to sort the collection desc on that value and take the first.

transactions.find("id" => x).sort({"sellprice" => -1}).limit(1).first()


问:
Load specific values to Combo Box from a table
I'm stuck in a project developed by another person which I cannot understand some code blocks.
This is the code block.

```<code> int outCount = 0;

                object obj = storeBO.FillStoreDDLWithLogicalQtyByItemID(cmbItem.SelectedItem.Value.CToInt(), out outCount);
            this.cmbStore.Items.Clear();

            if (outCount != 0)
            {
                support.LoadAllToComboBox(cmbStore, obj, "StoreID", "StoreName");
                lblStoreMsg.Text = "";
            }
            else
            {
                support.LoadAllToComboBox(cmbStore, null, null, null);
                lblStoreMsg.Text = Resources.Resource1.msgStoresNotFound;
                return;
            }
</code>```

cmbStore is id of Combo box

And definition of "LoadAllToComboBox" is below.

```<code>public void LoadAllToComboBox(AjaxControlToolkit.ComboBox cmb, object dataSource, string dataValueField, string dataTextField)
        {
            try
            {
                cmb.Items.Clear();
                cmb.SelectedValue = null;

                cmb.DataSource = dataSource;
                cmb.DataValueField = dataValueField;
                cmb.DataTextField = dataTextField;
                cmb.DataBind();
                cmb.Items.Add(new ListItem("Select", "Select"));
                cmb.SelectedValue = "Select";

            }
            catch (Exception exception)
            {

                throw exception;
            }

        }
</code>```

Please someone help me to understand this two code blocks. It will be great, if someone can explain these two code blocks to me.

Specially, I want to know this DataBind is binding to where.(through which one I can reach the LINQ code)

答:
Its easy to understand here ...

LoadAllToComboBox is common function in you application which allows to load value to comobo boxes in your application

DataBind() method in asp.net used to bind server control with the datasoruce which is in your code "dataSource"

there is no linq used in this code it just normal binding used

I suggest you google out DataBinding in Asp.net Application, you will get answer

Body:
I'm stuck in a project developed by another person which I cannot understand some code blocks.
This is the code block.

 int outCount = 0;

                object obj = storeBO.FillStoreDDLWithLogicalQtyByItemID(cmbItem.SelectedItem.Value.CToInt(), out outCount);
            this.cmbStore.Items.Clear();

            if (outCount != 0)
            {
                support.LoadAllToComboBox(cmbStore, obj, "StoreID", "StoreName");
                lblStoreMsg.Text = "";
            }
            else
            {
                support.LoadAllToComboBox(cmbStore, null, null, null);
                lblStoreMsg.Text = Resources.Resource1.msgStoresNotFound;
                return;
            }

cmbStore is id of Combo box

And definition of "LoadAllToComboBox" is below.

public void LoadAllToComboBox(AjaxControlToolkit.ComboBox cmb, object dataSource, string dataValueField, string dataTextField)
        {
            try
            {
                cmb.Items.Clear();
                cmb.SelectedValue = null;

                cmb.DataSource = dataSource;
                cmb.DataValueField = dataValueField;
                cmb.DataTextField = dataTextField;
                cmb.DataBind();
                cmb.Items.Add(new ListItem("Select", "Select"));
                cmb.SelectedValue = "Select";

            }
            catch (Exception exception)
            {

                throw exception;
            }

        }

Please someone help me to understand this two code blocks. It will be great, if someone can explain these two code blocks to me.

Specially, I want to know this DataBind is binding to where.(through which one I can reach the LINQ code)


问:
Is X day 0-14 days away?
I have an array of holidays. How can I detect if there's an upcoming holiday in 0-14 days? Is there a better way to store the holiday?</p>

```<code>var holidays = ["Tue Jul 04 2017", "Mon Sep 04 2017", "Mon Oct 09 2017", "Fri Nov 10 2017", "Thu Nov 23 2017", "Mon Dec 25 2017", "Mon Jan 01 2018", "Mon Jan 15 2018"];

if(holiday ???) console.log("Today is a holiday, or there is one soon.");
</code>```

答:
The basic code would look something like this.

```<code>var holidays = ["Tue Jul 04 2017", "Mon Sep 04 2017", "Mon Oct 09 2017", "Fri Nov 10 2017", "Thu Nov 23 2017", "Mon Dec 25 2017", "Mon Jan 01 2018", "Mon Jan 15 2018"];
var today = new Date();

for(var i = 0; i < holidays.length; i++) {
    date = new Date(holidays[i]);
    if(compareDate(today, date) {
        console.log("..");
    }
}
</code>```

The compareDate function would use the .fullYear(), .getMonth() and .getDate() methods to compare the year, month and day.

Hope this helps!

P.S.: You can also use momentjs to compare dates and easily make calculations using dates.

Title: Is X day 0-14 days away?

Body:
I have an array of holidays. How can I detect if there's an upcoming holiday in 0-14 days? Is there a better way to store the holiday?

var holidays = ["Tue Jul 04 2017", "Mon Sep 04 2017", "Mon Oct 09 2017", "Fri Nov 10 2017", "Thu Nov 23 2017", "Mon Dec 25 2017", "Mon Jan 01 2018", "Mon Jan 15 2018"];

if(holiday ???) console.log("Today is a holiday, or there is one soon.");

Body:
The basic code would look something like this.

var holidays = ["Tue Jul 04 2017", "Mon Sep 04 2017", "Mon Oct 09 2017", "Fri Nov 10 2017", "Thu Nov 23 2017", "Mon Dec 25 2017", "Mon Jan 01 2018", "Mon Jan 15 2018"];
var today = new Date();

for(var i = 0; i < holidays.length; i++) {
    date = new Date(holidays[i]);
    if(compareDate(today, date) {
        console.log("..");
    }
}

The compareDate function would use the .fullYear(), .getMonth() and .getDate() methods to compare the year, month and day.

Hope this helps!

P.S.: You can also use momentjs to compare dates and easily make calculations using dates.


问:
What is nextTick and what does it do in Vue.js?
I read the docs, but I still can't understand it.

I know what data, computed, watch, methods do, but what is nextTick() used for in Vue.js?

答:
Next Tick basically allows you to run some code, after the vue has re-rendered the component when you have made some changes to the a reactive property (data).

// modify data
vm.msg = 'Hello'
// DOM not updated yet
Vue.nextTick(function () {
   // this function is called when vue has re-rendered the component.
})

// usage as a promise (2.1.0+, see note below)
Vue.nextTick()
   .then(function () {
       // this function is called when vue has re-rendered the component.
    })
```

From the Vue.js Documentation:

Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update.

Read more about it, here.

Body:
Next Tick basically allows you to run some code, after the vue has re-rendered the component when you have made some changes to the a reactive property (data).

// modify data
vm.msg = 'Hello'
// DOM not updated yet
Vue.nextTick(function () {
   // this function is called when vue has re-rendered the component.
})

// usage as a promise (2.1.0+, see note below)
Vue.nextTick()
   .then(function () {
       // this function is called when vue has re-rendered the component.
    })

From the Vue.js Documentation:

Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update.

Read more about it, here.


问:
how to marry laravel and angularjs routing
I have an angularjs (version 5) app running in laravels public folder.
angularjs should serve the ui aka frontend. whilst laravels "only" route is the backend api access to the data(base) serving the ui at /api/....
How do I marry both?

My angularjs app resides in /public/ui/ so I currently just have a route in laravel like so:

```<code>Route::get('/', function () {
    return Redirect::to('/ui/dist');
});
</code>```

This works partially. It works from within the angularjs app like expected. But when I call anuglarjs routes they will fail to display because of course they don't exist in laravel.
Going with the angularjs tutorial for example:
If I call /ui/dist/heroes it will display a 404 instead of the angularjs app.

Note: Laravels public folder is symlinked to the webroot.

Edit:
I redirect to /ui/dist as I use angulars builder to build its files and these are reflected in the index.html also generated with the builder.
The index.html looks like this:

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Ui</title>
    <base href="./">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link href="styles.5cf98968a6d57e778c48.bundle.css" rel="stylesheet"/><!-- the hash changes on every build -->
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="inline.2379cc013d19d70a8003.bundle.js"></script> <!-- the hash changes on every build -->
<script type="text/javascript" src="polyfills.ad37cd45a71cb38eee76.bundle.js"></script> <!-- the hash changes on every build -->
<script type="text/javascript" src="main.99c0191843a51dda5d54.bundle.js"></script> <!-- the hash changes on every build -->
</body>
</html>
</code>```

答:
Here is how you can integrate laravel and angular routing.

In your routes.php, add this route:

```<code>Route::get('{slug}', function () {
    return view('index');
}); // this will ensure all routes will serve index.php file

Route::get('/', function () {
    return view('index');
});
</code>```

In your index.php of laravel view, add all necessary angular js config and controller like normally you do with angular projects.

Note: for each $http request urls you have to define it in laravel route file.

Now when any url is hit, it will serve the index.php file and then angular routing will serve the correct file.

Body:
I have an angularjs (version 5) app running in laravels public folder.
angularjs should serve the ui aka frontend. whilst laravels "only" route is the backend api access to the data(base) serving the ui at /api/....
How do I marry both?

My angularjs app resides in /public/ui/ so I currently just have a route in laravel like so:

Route::get('/', function () {
    return Redirect::to('/ui/dist');
});

This works partially. It works from within the angularjs app like expected. But when I call anuglarjs routes they will fail to display because of course they don't exist in laravel.
Going with the angularjs tutorial for example:
If I call /ui/dist/heroes it will display a 404 instead of the angularjs app.

Note: Laravels public folder is symlinked to the webroot.

Edit:
I redirect to /ui/dist as I use angulars builder to build its files and these are reflected in the index.html also generated with the builder.
The index.html looks like this:

<!doctype html>

    <meta charset="utf-8">
    <title>Ui</title>
    <base href="./">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link href="styles.5cf98968a6d57e778c48.bundle.css" rel="stylesheet"/>

<app-root></app-root>

Body:
Here is how you can integrate laravel and angular routing.

In your routes.php, add this route:

Route::get('{slug}', function () {
    return view('index');
}); // this will ensure all routes will serve index.php file

Route::get('/', function () {
    return view('index');
});

In your index.php of laravel view, add all necessary angular js config and controller like normally you do with angular projects.

Note: for each $http request urls you have to define it in laravel route file.

Now when any url is hit, it will serve the index.php file and then angular routing will serve the correct file.


问:
Nodejs telnet live response fetching
I am using Nodejs with Express. Is there any way to get all the response content from a request at the same time. I am using telnet to make the request, but am not getting all content at the same time. Instead, I am getting it part by part. I need to extract data from that response so I am trying to write all the contents to a file and then convert that xml file content to json.</p>

答:
I believe you use streams for that purposes.
So, most likely you have to use 'end' event to determine, that data fetching is finished.

Very sample code:

```<code>let data = ""

response.on('data', x => data += x)
response.on('end', () => firesomeCallback(data));
</code>```

Title: Nodejs telnet live response fetching

Body:
I believe you use streams for that purposes.
So, most likely you have to use 'end' event to determine, that data fetching is finished.

Very sample code:

let data = ""

response.on('data', x => data += x)
response.on('end', () => firesomeCallback(data));


问:
Get current screen width in xamarin forms
I am creating one Xamarin Forms project and I got stuck in finding the current screen width according to the different device.

I know how it can be done in android and ios but need a way to find the width in portable.

答:
Common code (in App.xaml.cs)

public static int ScreenHeight {get; set;}
public static int ScreenWidth {get; set;}
```
<p><strong>Android part (in MainActivity.cs, in the OnCreate method)</strong></p>
<pre class="lang-cs prettyprint-override"><code>App.ScreenHeight = (int) (Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density);
App.ScreenWidth = (int) (Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density);
</code>```

iOS part (in AppDelegate.cs, in the FinishedLaunching method)

App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height;
App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
```

So App.ScreenHeight and App.ScreenWidth will be initialized when the App will be launched, then you will be able to use them anywhere in the common code.

Body:
Common code (in App.xaml.cs)

public static int ScreenHeight {get; set;}
public static int ScreenWidth {get; set;}

Android part (in MainActivity.cs, in the OnCreate method)

App.ScreenHeight = (int) (Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density);
App.ScreenWidth = (int) (Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density);

iOS part (in AppDelegate.cs, in the FinishedLaunching method)

App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height;
App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;

So App.ScreenHeight and App.ScreenWidth will be initialized when the App will be launched, then you will be able to use them anywhere in the common code.


问:
Javascript document write
How do I get this javascript to populate the textarea?

```<code><body onload="form1.submit();"><div align="center">Loading...</div>
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery.wordstats.js"></script> <!-- core code -->
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery.wordstats.en.js"></script> <!-- English stop words -->
<script type="text/javascript">
        $(function() {
            var count = 20;
            $.extend($.wordStats.stopWords, {'retrieved': true, '2007': true});
            $.wordStats.computeTopWords(count);
            var msgcounttext1 = '<%=completehtml%>'
            for(var i = 0, j = $.wordStats.topWords.length; i < j && i <= count; i++) {
               msg += $.wordStats.topWords[i].substring(1) + ', ';
            }
            {
            document.form1.textarea.value = document.write(msgcounttext);
            }
            $.wordStats.clear();
        });
        </script>
<div id="content" class="hidden"><%=completehtml%>
    <form id="form1" name="form1" method="post" action="test.asp">
        <textarea name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </form>
  </div>
</body>
</code>```

Thanks

答:
The document.write method isn't used that way, you can just assign the value to the property. You can also use the jQuery val method to set the text.

Besides, you use three different variables in the code, which I think should be the same:

```<code>var msg = '<%=completehtml%>';
for(var i = 0, j = $.wordStats.topWords.length; i < j && i <= count; i++) {
  msg += $.wordStats.topWords[i].substring(1) + ', ';
}
$('#textarea').val(msg);
</code>```

Title: Javascript document write

Body:
How do I get this javascript to populate the textarea?

Loading...

<%=completehtml%>
    <form id="form1" name="form1" method="post" action="test.asp">
        <textarea name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </form>

Thanks

Body:
The document.write method isn't used that way, you can just assign the value to the property. You can also use the jQuery val method to set the text.

Besides, you use three different variables in the code, which I think should be the same:

var msg = '<%=completehtml%>';
for(var i = 0, j = $.wordStats.topWords.length; i < j && i <= count; i++) {
  msg += $.wordStats.topWords[i].substring(1) + ', ';
}
$('#textarea').val(msg);


问:
UWP Designer Stopped Working
So I have been working on this UWP project (visual studio 2017) for months and just recently the designer stopped working (it shows Loading desinger... You can continue working while the designer is loading in the background.) I have tried getting an earlier, working version of the project, but this did nothing to resolve the issue. One thing that did help was I made a in place copy of the folder containing the solution/projects. Opening this solution (with identical code) works as intended. So is there some temp files or something that is stopping the original version from working properly? I guess a solution I could use is to just work off the new copied directory, but if another solution is available I'd rather use that since this may happen again. Not sure why it happened in the first place honestly. Any information and/or help is greatly appreciated.</p>

答:
If your app is targeting the Fall Creators Update (16299), then Visual Studio will use the new XAML Designer, which although usually being more precise with its presentation is still more buggy and I find it more often not working than working. But it is a work in progress and I am actually extremely happy it is being improved :-) .

In any case, I think you can delete the temporary files and folders for the project like bin, obj, .suo, etc. and then Clean the solution and Rebuild all. If the copy-paste approach works, I suspect there is a stuck temporary file that causes this.

Title: UWP Designer Stopped Working


问:
How to set c++ compiler on OS X with bazel?
How can you tell bazel to use a different C++ compiler on OS X?

```<code>bazel build --action_env CC=/path/to/compiler //:target
</code>```

works on linux.

But -s shows that bazel always runs with external/local_config_cc/wrapped_clang (clang) on OSX regardless of what CC is.

答:
CC correctly works only when you use the C++-only toolchain. If you have Xcode installed, bazel will detect this and automatically pick a different toolchain, the one that supports both C++ and ObjC. This toolchain can only use Xcode-provided clang.

This is unfortunate and I propose two solutions:

File a feature request for bazel to make it possible to select which toolchain is used. This will allow you to tell bazel that even though you have Xcode installed, you want to use C++ only toolchain with a custom compiler. This is quite simple and doable in a short time.

File a feature request for bazel to make it possible to select which compiler is used with C++/ObjC toolchain. I cannot comment on viability of this, I know next to nothing about osx, and I have no idea if it makes any sense to compile ObjC with a compiler that is not provided with Xcode...

Body:
How can you tell bazel to use a different C++ compiler on OS X?

bazel build --action_env CC=/path/to/compiler //:target

works on linux.

But -s shows that bazel always runs with external/local_config_cc/wrapped_clang (clang) on OSX regardless of what CC is.


问:
Compress file on S3
I have a 17.7GB file on S3. It was generated as the output of a Hive query, and it isn't compressed.

I know that by compressing it, it'll be about 2.2GB (gzip). How can I download this file locally as quickly as possible when transfer is the bottleneck (250kB/s).

I've not found any straightforward way to compress the file on S3, or enable compression on transfer in s3cmd, boto, or related tools.

答:
Late answer but I found this working perfectly.

```<code>aws s3 sync s3://your-pics .

for file in "$(find . -name "*.jpg")"; do gzip "$file"; echo "$file";  done

aws s3 sync . s3://your-pics --content-encoding gzip --dryrun
</code>```

This will download all files in s3 bucket to the machine (or ec2 instance), compresses the image files and upload them back to s3 bucket.
Verify the data before removing dryrun flag.

Title: Compress file on S3

Body:
Late answer but I found this working perfectly.

aws s3 sync s3://your-pics .

for file in "$(find . -name "*.jpg")"; do gzip "$file"; echo "$file";  done

aws s3 sync . s3://your-pics --content-encoding gzip --dryrun

This will download all files in s3 bucket to the machine (or ec2 instance), compresses the image files and upload them back to s3 bucket.
Verify the data before removing dryrun flag.


问:
Ionic testing - asynchronous look for a change in ionViewDidLoad
I have troubles trying to test the value of a variable that change inside the ionViewDidLoad method

welcomepage.ts

```<code>@Component({...})
export class WelcomePage {

    test: number = 0;

    constructor(){}

    ionViewDidLoad(){
        this.test = 1;
    }

}
</code>```

welcomepage.spec.ts

```<code>    it('test should equal be equal to 1', () => {
        fixture.detectChanges();
        expect(component.test).toBe(1)
    });
</code>```

But this test is not succeeding. If I do the change inside the constructor function (this.test = 1) then it is working.

======== UPDATE ========

It seems that it is a problem with ionViewDidLoad function triggered by ionic, it is working as usual by running ionic but not in the test.

答:
It appears that ionic life-cycle events (ionViewDidEnter, ionViewDidLoad, ...) are not called during testing, by calling it manually it works :

```<code>it('test should equal be equal to 1', () => {
    component.ionViewDidLoad();
    fixture.detectChanges();
    expect(component.test).toBe(1)
});
</code>```

But then how are we sure that ionic really call ionViewDidLoad ?

Body:
I have troubles trying to test the value of a variable that change inside the ionViewDidLoad method

welcomepage.ts

@Component({...})
export class WelcomePage {

    test: number = 0;

    constructor(){}

    ionViewDidLoad(){
        this.test = 1;
    }

}

welcomepage.spec.ts

    it('test should equal be equal to 1', () => {
        fixture.detectChanges();
        expect(component.test).toBe(1)
    });

But this test is not succeeding. If I do the change inside the constructor function (this.test = 1) then it is working.

======== UPDATE ========

It seems that it is a problem with ionViewDidLoad function triggered by ionic, it is working as usual by running ionic but not in the test.

Body:
It appears that ionic life-cycle events (ionViewDidEnter, ionViewDidLoad, ...) are not called during testing, by calling it manually it works :

it('test should equal be equal to 1', () => {
    component.ionViewDidLoad();
    fixture.detectChanges();
    expect(component.test).toBe(1)
});

But then how are we sure that ionic really call ionViewDidLoad ?


问:
How to extract only words from a text file in F#?
I`m trying to extract only words from a text file that is very simple:

```<code>Please note that you still have an unclaimed iPhone 7.

We have repeatedly written to you regarding your delivery details. We do not understand why you have not yet confirmed your shipping information so we can send it to your home address.

Your special price for the brand new  iPhone 7 phone is only £3 with shipping.

We hope that you'll confirm your information this time.
</code>```

I have been using this function, but seems that it throws an Exception("No Overloads match for method Split"):

```<code>let wordSplit (text:string) =
  text.Split([|' ','\n','\t',',','.','/','\\','|',':',';'|])
  |> Array.toList
</code>```

答:
In F#, items in arrays or lists are separated by the ; (semicolon) character, not the , (comma). Your code is creating an array that contains one 10-item tuple. You should write the following if you want an array of ten items:

```<code>let wordSplit (text:string) =
  text.Split([|' ';'\n';'\t';',';'.';'/';'\\';'|';':';';'|])
  |> Array.toList
</code>```

If you also want to not get empty strings back as part of the split operation, then you want the version of String.Split that takes a StringSplitOptions parameter:

```<code>let wordSplit (text:string) =
  text.Split([|' ';'\n';'\t';',';'.';'/';'\\';'|';':';';'|], StringSplitOptions.RemoveEmptyEntries)
  |> Array.toList
</code>```

Note that StringSplitOptions is in the System namespace, so if you don't have an open System line at the top of your file, you'll need to add one.

Body:
I`m trying to extract only words from a text file that is very simple:

Please note that you still have an unclaimed iPhone 7.

We have repeatedly written to you regarding your delivery details. We do not understand why you have not yet confirmed your shipping information so we can send it to your home address.

Your special price for the brand new  iPhone 7 phone is only £3 with shipping.

We hope that you'll confirm your information this time.

I have been using this function, but seems that it throws an Exception("No Overloads match for method Split"):

let wordSplit (text:string) =
  text.Split([|' ','\n','\t',',','.','/','\\','|',':',';'|])
  |> Array.toList

Body:
In F#, items in arrays or lists are separated by the ; (semicolon) character, not the , (comma). Your code is creating an array that contains one 10-item tuple. You should write the following if you want an array of ten items:

let wordSplit (text:string) =
  text.Split([|' ';'\n';'\t';',';'.';'/';'\\';'|';':';';'|])
  |> Array.toList

If you also want to not get empty strings back as part of the split operation, then you want the version of String.Split that takes a StringSplitOptions parameter:

let wordSplit (text:string) =
  text.Split([|' ';'\n';'\t';',';'.';'/';'\\';'|';':';';'|], StringSplitOptions.RemoveEmptyEntries)
  |> Array.toList

Note that StringSplitOptions is in the System namespace, so if you don't have an open System line at the top of your file, you'll need to add one.


问:
Switch case pass multiple value
I have four dynamically inputs. User select how many wants.
In input he enter article ID and on success I send this in URL.
Url can have only two or three or four id

```<code>'http://someurl/' + ID + '/someParams'
example: 'http://someurl/991,992,993,994/someParams'
</code>```

I pass ID's from html to controller

```<code>$scope.submitChoice = function (name) {
    $scope.choices.forEach(function(choice, index){
        if(choice.name)
        {
            switch (index) {
                case 0:
                    var firstId = choice.name;
                    break;
                case 1:
                    var secondId = choice.name;
                    break;
                case 2:
                    var thirdId = choice.name;
                    break;
                case 3:
                    var fourthId = choice.name;
                    break;
            }
            console.log(firstId, secondId, thirdId, fourthId);
            $scope.getBenchIdForCompare(firstId, secondId, thirdId,fourthId);
        }
    })
}
</code>```

I use SWITCH CASE and INDEX because I need every of this ID set to unique var (because of another part of my app).
Problem is, when I submit entered ID in input, I get this in my console when I
    console.log(firstId, secondId, thirdId, fourthId);

console

```<code>991 undefined undefined undefined
undefined 992 undefined undefined
undefined undefined 993 undefined
undefined undefined undefined 994
</code>```

And I can not pass this to another function because I need to have 991 992 993 994

Is there another way to make this?

答:
You can use map instead and create an array. Once array is created, you can join them using join() method and you will get readymade comma separated string. This comma separated string can be added to get desired URL.

$scope.submitChoice = function(name) {
  var choices = $scope.choices.map(function(choice){
    return choice.name;
  });
  console.log(choices.join(','));
  $scope.getBenchIdForCompare(choices[0], choices[1], choices[2], choices[3]);
}
```

<p>ES6 version (using the spread operator):  </p>

```$scope.submitChoice = function(name) {
  let choices = $scope.choices.map(choice => choice.name)
  console.log(choices.join(','));
  $scope.getBenchIdForCompare(...choices);
}
```

Title: Switch case pass multiple value

Body:
I have four dynamically inputs. User select how many wants.
In input he enter article ID and on success I send this in URL.
Url can have only two or three or four id

'http://someurl/' + ID + '/someParams'
example: 'http://someurl/991,992,993,994/someParams'

I pass ID's from html to controller

$scope.submitChoice = function (name) {
    $scope.choices.forEach(function(choice, index){
        if(choice.name)
        {
            switch (index) {
                case 0:
                    var firstId = choice.name;
                    break;
                case 1:
                    var secondId = choice.name;
                    break;
                case 2:
                    var thirdId = choice.name;
                    break;
                case 3:
                    var fourthId = choice.name;
                    break;
            }
            console.log(firstId, secondId, thirdId, fourthId);
            $scope.getBenchIdForCompare(firstId, secondId, thirdId,fourthId);
        }
    })
}

I use SWITCH CASE and INDEX because I need every of this ID set to unique var (because of another part of my app).
Problem is, when I submit entered ID in input, I get this in my console when I
    console.log(firstId, secondId, thirdId, fourthId);

console

991 undefined undefined undefined
undefined 992 undefined undefined
undefined undefined 993 undefined
undefined undefined undefined 994

And I can not pass this to another function because I need to have 991 992 993 994

Is there another way to make this?

Body:
You can use map instead and create an array. Once array is created, you can join them using join() method and you will get readymade comma separated string. This comma separated string can be added to get desired URL.

$scope.submitChoice = function(name) {
  var choices = $scope.choices.map(function(choice){
    return choice.name;
  });
  console.log(choices.join(','));
  $scope.getBenchIdForCompare(choices[0], choices[1], choices[2], choices[3]);
}

ES6 version (using the spread operator):

$scope.submitChoice = function(name) {
  let choices = $scope.choices.map(choice => choice.name)
  console.log(choices.join(','));
  $scope.getBenchIdForCompare(...choices);
}


问:
Background Location Update issue When I minimized my app
When I Minimized my app background location is not updating when it opens it will be updating.

While updating location after few minutes app gets restarted.

```<code>public  void onLocationChanged(Location location) {

    ArrayList<Activity> activities = new ArrayList<Activity>();

    activities.add(StartTravel.StartTravelActivity);

    boolean isAppRunning = false;
    for (Activity activity : activities) {
        if (activity != null)
            isAppRunning = true;
    }
    if (isAppRunning) {
        startLocationUpdates();
    }
    if (!isAppRunning) {
        startLocationUpdates();
    }
    curLat = location.getLatitude();
    curLng = location.getLongitude();
    curLat1 = location.getLatitude();
    curLng1 = location.getLongitude();

    if (curLat != 0.0 && curLng != 0.0) {
        callWebservice();
    }
    Log.e("IN","Track Location :: " + curLat + curLng);
//  boolean isInserted1 = myDb.INSERT(String.format("%.6f",location.getLatitude()),String.format("%.6f",location.getLongitude()));
}
</code>```

答:
You need to move the location update code a Service. Activity is not meant for performing a long-running operations in the background.

Moreover, the problem emerge when you're creating a new object in your code with this:

```<code>public  void onLocationChanged(Location location) {
  ArrayList<Activity> activities = new ArrayList<Activity>();
  activities.add(StartTravel.StartTravelActivity);
}
</code>```

Creating object is expensive for Android. You're trying to allocate a new object each time the location changed. The memory used by the objects you've created is not yet reclaimed by garbage collector. So, it will get Out Of Memory error then killed by the system.

Body:
When I Minimized my app background location is not updating when it opens it will be updating.

While updating location after few minutes app gets restarted.

public  void onLocationChanged(Location location) {

    ArrayList<Activity> activities = new ArrayList<Activity>();

    activities.add(StartTravel.StartTravelActivity);

    boolean isAppRunning = false;
    for (Activity activity : activities) {
        if (activity != null)
            isAppRunning = true;
    }
    if (isAppRunning) {
        startLocationUpdates();
    }
    if (!isAppRunning) {
        startLocationUpdates();
    }
    curLat = location.getLatitude();
    curLng = location.getLongitude();
    curLat1 = location.getLatitude();
    curLng1 = location.getLongitude();

    if (curLat != 0.0 && curLng != 0.0) {
        callWebservice();
    }
    Log.e("IN","Track Location :: " + curLat + curLng);
//  boolean isInserted1 = myDb.INSERT(String.format("%.6f",location.getLatitude()),String.format("%.6f",location.getLongitude()));
}

Body:
You need to move the location update code a Service. Activity is not meant for performing a long-running operations in the background.

Moreover, the problem emerge when you're creating a new object in your code with this:

public  void onLocationChanged(Location location) {
  ArrayList<Activity> activities = new ArrayList<Activity>();
  activities.add(StartTravel.StartTravelActivity);
}

Creating object is expensive for Android. You're trying to allocate a new object each time the location changed. The memory used by the objects you've created is not yet reclaimed by garbage collector. So, it will get Out Of Memory error then killed by the system.


问:
MS Word VBA, trying to populate a combobox with data from an http call
I'm using the following code to populate a combobox in Word 2003.

```<code>Private Sub UserForm_Initialize()
ComboBox1.List = Array("Red", "Green", "Yellow", "Blue")
End Sub
</code>```

What I would like to do is get the data dynamically via an http call. This other function seems to work to get data via http

```<code>Dim MyRequest As Object

Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", _
"http://localhost:8500/test7.htm"

' Send Request.
MyRequest.Send

'And we get this response
MsgBox MyRequest.ResponseText
</code>```

test7.htm just contains

```<code>"Red", "Green", "Yellow", "Blue"
</code>```

I was hoping to combine the two but below doesn't work

```<code>Private Sub UserForm_Initialize()
Dim MyRequest As Object

Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", _
"http://localhost:8500/test7.htm"

' Send Request.
MyRequest.Send

ComboBox1.List = Array(MyRequest.ResponseText)
End Sub
</code>```

Any help for a VBA noob appreciated

答:
The response text should be a simple comma separated string, something like

Red,Green,Yellow,Blue

Thus you can use the following method for populating the ComboBox:

```<code>Private Sub populateComboBox(ByRef combo As ComboBox, ByRef html As String)
    Dim arrayValues() As String, index As Integer
    arrayValues = Split(Trim(html), ",")
    For index = LBound(arrayValues) To UBound(arrayValues)
        combo.AddItem (arrayValues(index))
    Next
End Sub
</code>```

For calling the method you can use the following sentence.

```<code>Call populateComboBox(Combo1, MyRequest.ResponseText)
</code>```

Body:
I'm using the following code to populate a combobox in Word 2003.

Private Sub UserForm_Initialize()
ComboBox1.List = Array("Red", "Green", "Yellow", "Blue")
End Sub

What I would like to do is get the data dynamically via an http call. This other function seems to work to get data via http

Dim MyRequest As Object

Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", _
"http://localhost:8500/test7.htm"

' Send Request.
MyRequest.Send

'And we get this response
MsgBox MyRequest.ResponseText

test7.htm just contains

"Red", "Green", "Yellow", "Blue"

I was hoping to combine the two but below doesn't work

Private Sub UserForm_Initialize()
Dim MyRequest As Object

Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", _
"http://localhost:8500/test7.htm"

' Send Request.
MyRequest.Send

ComboBox1.List = Array(MyRequest.ResponseText)
End Sub

Any help for a VBA noob appreciated

Body:
The response text should be a simple comma separated string, something like

Red,Green,Yellow,Blue

Thus you can use the following method for populating the ComboBox:

Private Sub populateComboBox(ByRef combo As ComboBox, ByRef html As String)
    Dim arrayValues() As String, index As Integer
    arrayValues = Split(Trim(html), ",")
    For index = LBound(arrayValues) To UBound(arrayValues)
        combo.AddItem (arrayValues(index))
    Next
End Sub

For calling the method you can use the following sentence.

Call populateComboBox(Combo1, MyRequest.ResponseText)