问:
Ranking user score in jQuery
I have an array which consists of 600 records in the format of:

```<code>[ Mac     14
  John    12
  abc     12
  bill    16  ]
</code>```

I am trying to create a ranking model for the above, in the sense the bill has rank1, mac as rank 2, john, abc as rank3 and push it back to the array. Example as

```<code>[ Mac     14  2
  John    12  3
  abc     12  3
  bill    16  1 ]
</code>```

Below is the code which i have tried:

```<code>    var items = data.d.results;

if(items.length > 0){
for (i = 0; i < items.length; i++) {
 playerDetails.push( items[i].Title , items[i].Points );
 }
 var scores = playerDetails.map(function(d) { return d[1]; }).sort().reverse();
   console.log(playerDetails);
</code>```

The initial playerdetails array contains the data in the format of:

```<code>{John, Nikhil C.,467},{Cule, Mac A.,341},{Pat, Ryan,465}

  [
      [0...99]: [
         [0...9]: [
            0: "{John, Nikhil C.",
            1: "467}",
            2: "{Cule, Mac A.",
            3: "341}",
            4: "{Pat, Ryan",
            5: "465}",

         ],
</code>```

Is this possible in jQuery? If yes, how to achieve it?
Thanks

答:
This is possible in javascript, no jQuery required.

This example introduces a new array of scores, for sorting purposes:

```<code>var data = [['Mac', 14],['John', 12],['abc',12],['bill',16]];

var scores = data.map(d => d[1]).sort().reverse();
data = data.map(d => d.concat([scores.indexOf(d[1])+1]));
</code>```

If you don't mind your entire dataset to be sorted based on score, you could do the manipulation entirely within the original data. You could then use the current posiiton in the iteration for rank, and only check for the corner case that the current item is ranking the same as the previous:

```<code>data
  .sort((a,b) => b[1] - a[1])
  .forEach((d,i,a) => d.push(i > 0 && a[i-1][1] == d[1] ? a[i-1][2] : i+1));
</code>```

Title: Ranking user score in jQuery

Body:
I have an array which consists of 600 records in the format of:

[ Mac     14
  John    12
  abc     12
  bill    16  ]

I am trying to create a ranking model for the above, in the sense the bill has rank1, mac as rank 2, john, abc as rank3 and push it back to the array. Example as

[ Mac     14  2
  John    12  3
  abc     12  3
  bill    16  1 ]

Below is the code which i have tried:

    var items = data.d.results;

if(items.length > 0){
for (i = 0; i < items.length; i++) {
 playerDetails.push( items[i].Title , items[i].Points );
 }
 var scores = playerDetails.map(function(d) { return d[1]; }).sort().reverse();
   console.log(playerDetails);

The initial playerdetails array contains the data in the format of:

{John, Nikhil C.,467},{Cule, Mac A.,341},{Pat, Ryan,465}

  [
      [0...99]: [
         [0...9]: [
            0: "{John, Nikhil C.",
            1: "467}",
            2: "{Cule, Mac A.",
            3: "341}",
            4: "{Pat, Ryan",
            5: "465}",

         ],

Is this possible in jQuery? If yes, how to achieve it?
Thanks

Body:
This is possible in javascript, no jQuery required.

This example introduces a new array of scores, for sorting purposes:

var data = [['Mac', 14],['John', 12],['abc',12],['bill',16]];

var scores = data.map(d => d[1]).sort().reverse();
data = data.map(d => d.concat([scores.indexOf(d[1])+1]));

If you don't mind your entire dataset to be sorted based on score, you could do the manipulation entirely within the original data. You could then use the current posiiton in the iteration for rank, and only check for the corner case that the current item is ranking the same as the previous:

data
  .sort((a,b) => b[1] - a[1])
  .forEach((d,i,a) => d.push(i > 0 && a[i-1][1] == d[1] ? a[i-1][2] : i+1));


来源: stackexchange

问:
iOS: Using Swift 4 when targeting iOS 9
Swift 4 is adding some really cool features, like strongly typed keypaths and JSON encoding/decoding using Codable.

I would like to use these new features while still targeting iOS 9 and above.

As far as I understand, Swift language version is not bound to a version of iOS, as opposite to Foundation framework, for example. However, I can't find any info if that's correct.

Can I use Swift 4 when targeting iOS older than 11?

答:
Yes, just like with Swift 1, Swift 2 and Swift 3, you can use Swift 4 with any version of iOS 7 and above.

See this similar question for Swift 3: Xcode 8 / Swift 3 and installing apps on iPhone 4 running iOS 7

See this similar question for Swift 2: Swift 2.0 minimum system version requirement (deployment target)

Note: as iOS 11 is dropping support for 32-bit, you will only be able to use iOS 11 from an arm64 slice (that is, from iPhone 5S and up). Source:

iOS 11 no longer supports armv7 or armv7s (32-bit). If an iOS target has an iOS Deployment
  Target of 11, then it will not build for 32-bit. iOS targets with an iOS Deployment Target earlier
  than 11 will still build for 32-bit by default. (32163517)

ContentLicense: CC BY-SA 3.0

Title: iOS: Using Swift 4 when targeting iOS 9


问:
GroupBy LINQ Query
I have the following structure of classes:

```<code>public partial class OrderOrderData
{
    public OrderOrderDataOfferOrder[] OfferOrder{get;set}
}

public partial class OrderOrderDataOfferOrder
{
    public OrderOrderDataOfferOrderQuestion[] Question{get;set}
}

public partial class OrderOrderDataOfferOrderQuestion
{
    public OrderOrderDataOfferOrderQuestionPrice Price{get;set;}
}
</code>```

Now I am trying to retrieve that OfferOrder whose Question.Price is not equal to null.

For Example I have Object A, B and C in OfferOrder. Question.Price of C is not equal to null hence my LINQ query should return OfferOrder C to pricedOfferOrder .

I tried to do it by GroupBy but found no luck. I'm trying something like this but still clueless as to how will I get to the Price after grouping by Question

```<code>OrderOrderData OrderData = order;
OfferOrder pricedOfferOrder = OrderData.OfferOrder.GroupBy(x=>x.Question)...
</code>```

答:
Simple Where method is sufficient here:</p>

```<code>OrderOrderData OrderData = order;

OfferOrder pricedOfferOrder = OrderData.OfferOrder
  .Where(d => d.Question.Any(e => e.Price != null));
</code>```

Title: GroupBy LINQ Query

Body:
I have the following structure of classes:

public partial class OrderOrderData
{
    public OrderOrderDataOfferOrder[] OfferOrder{get;set}
}

public partial class OrderOrderDataOfferOrder
{
    public OrderOrderDataOfferOrderQuestion[] Question{get;set}
}

public partial class OrderOrderDataOfferOrderQuestion
{
    public OrderOrderDataOfferOrderQuestionPrice Price{get;set;}
}

Now I am trying to retrieve that OfferOrder whose Question.Price is not equal to null.

For Example I have Object A, B and C in OfferOrder. Question.Price of C is not equal to null hence my LINQ query should return OfferOrder C to pricedOfferOrder .

I tried to do it by GroupBy but found no luck. I'm trying something like this but still clueless as to how will I get to the Price after grouping by Question

OrderOrderData OrderData = order;
OfferOrder pricedOfferOrder = OrderData.OfferOrder.GroupBy(x=>x.Question)...

Body:
Simple Where method is sufficient here:

OrderOrderData OrderData = order;

OfferOrder pricedOfferOrder = OrderData.OfferOrder
  .Where(d => d.Question.Any(e => e.Price != null));


答:
There isn't any need to use GroupBy in this case. You could try something like this:

```<code>var offerOrder = OrderData.OfferOrder
  .FirstOrDefault(oo => oo.Question.FirstOrDefault(q=>q.Price != null) != null );
</code>```

Essentially we use the FirstOrDefault method, which takes a predicate and provided that there is at least one item that fulfills this predicate this is the result of the query. Otherwise the default value is returned, which in out case is null. So we are looking for the first OfferOrder if there is any at all, whose Question array contains at least one Question (not null), whose Price is not null.

For further info regarding this method, please have a look here.

Title: GroupBy LINQ Query

Body:
There isn't any need to use GroupBy in this case. You could try something like this:

var offerOrder = OrderData.OfferOrder
  .FirstOrDefault(oo => oo.Question.FirstOrDefault(q=>q.Price != null) != null );

Essentially we use the FirstOrDefault method, which takes a predicate and provided that there is at least one item that fulfills this predicate this is the result of the query. Otherwise the default value is returned, which in out case is null. So we are looking for the first OfferOrder if there is any at all, whose Question array contains at least one Question (not null), whose Price is not null.

For further info regarding this method, please have a look here.


问:
Remove double quoted string from text file?
I'm working on some text files, i have to remove a specific string

```<code>ex: "1234_NAME=TRUE", (including double quotes and comma)
</code>```

Using Vim editor if i pass

```<code>:%s/"1234_NAME=TRUE",//g
</code>```

But In this way i will be doing manually. But i want to automate the job by using some script.

I tried using sed tool, but it failed.

```<code>sed 's/"1234_NAME=TRUE",//g' hello.txt
</code>```

I'm not expert on scripting. i know command is not correct. what is the solution for the above command.

And one more question:

Instead of passing file names manually, can we add a small loop which will take all text files in a directory one by one and remove the string.

Answer as suggested by @codeforester require some fix:

```<code>for file in *.txt
do
   [[ -f "$file" ]] || continue
</code>```

semicolon was the issue.

and Thanks to @SlePort for the answer.

Regards,

GBiradar

答:
Your command is correct.  To loop through your files, you can use a simple loop:

```<code>for file in *.txt; do          # assuming your files are have .txt extension, modify accordingly
  [[ -f "$file" ]] || continue # skip if not a regular file
  sed 's/"1234_NAME=TRUE",//g' "$file" > "$file.modified" && mv "$file.modified" "$file"
  # you can also use the `-i` flag to make a backup of the file and then overwrite the original
  # `-i ''` will skip the backup and just overwrite the file
  # sed -i .bak 's/"1234_NAME=TRUE",//g' "$file"
done
</code>```

Make sure you have a backup of your files before running the above code.

Body:
I'm working on some text files, i have to remove a specific string

ex: "1234_NAME=TRUE", (including double quotes and comma)

Using Vim editor if i pass

:%s/"1234_NAME=TRUE",//g

But In this way i will be doing manually. But i want to automate the job by using some script.

I tried using sed tool, but it failed.

sed 's/"1234_NAME=TRUE",//g' hello.txt

I'm not expert on scripting. i know command is not correct. what is the solution for the above command.

And one more question:

Instead of passing file names manually, can we add a small loop which will take all text files in a directory one by one and remove the string.

Answer as suggested by @codeforester require some fix:

for file in *.txt
do
   [[ -f "$file" ]] || continue

semicolon was the issue.

and Thanks to @SlePort for the answer.

Regards,

GBiradar

Body:
Your command is correct.  To loop through your files, you can use a simple loop:

for file in *.txt; do          # assuming your files are have .txt extension, modify accordingly
  [[ -f "$file" ]] || continue # skip if not a regular file
  sed 's/"1234_NAME=TRUE",//g' "$file" > "$file.modified" && mv "$file.modified" "$file"
  # you can also use the `-i` flag to make a backup of the file and then overwrite the original
  # `-i ''` will skip the backup and just overwrite the file
  # sed -i .bak 's/"1234_NAME=TRUE",//g' "$file"
done

Make sure you have a backup of your files before running the above code.


问:
Change not being triggered on page load
I have a page that I use to create production records for unique line, shift, and date combinations, as well as edit existing records.  I have two drop downs for the line and shift, and a jQuery date picker for the date.  When the line changes, the date picker gets disabled and the shift drop down gets reset.  I want to disable the date picker when creating a new shift (enabled after a shift is picked), but I haven't been able to figure out how to do it.  Here's my jQuery code:

```<code>$(document).ready(function() {
       $('#lineSel').on('change',function() {
           $('#shiftSel').find('option:first').attr('selected', 'selected');
           $('#datePicker').val('').datepicker('disable');
           console.log('Datepicker disabled');
       });

       $('#shiftSel').on('change',function() {
           $.ajax({
               url: '/api/Shifts/GetDates',
               data: { plantCd: '@Model.PlantCd',
                       lineId: $('#lineSel').val(),
                       shift: $('#shiftSel').val()
                    },
               success: function(e) {
                   var dates = e.toString().split(',');
                   $('#datePicker').datepicker('option', 'beforeShowDay', function(date) {
                        var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
                        return [dates.indexOf(string) == -1];
                   });
               }
            });
           $('#datePicker').datepicker('enable');
       });

       if ('@Model.Title' !== 'New Shift') {
           $('#shiftSel').change();
       }

       $('#lineSel').change();
});
</code>```

#lineSel is the drop down for the line, #shiftSel the drop down for the shift, and #datePicker the date picker.

After the page loads, if I change the line drop down, the date picker disables like it should.  However, $('#lineSel').change(); executes the on('change') code ('Datepicker disabled' shows up in browser dev tools console), but the the date picker does not get disabled.

I've tried calling $('#datePicker').datepicker('disable') in the ready function, adding .change() to the end of the event handler binding, using .change(function() instead of on('change', function()), and other suggestions from this question and this question.

Any ideas why the date picker doesn't get disabled on page load and what I can do fix it?  Using jQuery UI 1.11.2 in and ASP.NET MVC 5 application.

答: After playing around with @TetsuyaYamamoto's fiddle and trying different things, finally figured out how to get it working.  Replaced $('#lineSel').change() with $('#datePicker').prop('disabled', true) and that did the trick.  Thanks for the help.

Title: Change not being triggered on page load

Body:
I have a page that I use to create production records for unique line, shift, and date combinations, as well as edit existing records.  I have two drop downs for the line and shift, and a jQuery date picker for the date.  When the line changes, the date picker gets disabled and the shift drop down gets reset.  I want to disable the date picker when creating a new shift (enabled after a shift is picked), but I haven't been able to figure out how to do it.  Here's my jQuery code:

$(document).ready(function() {
       $('#lineSel').on('change',function() {
           $('#shiftSel').find('option:first').attr('selected', 'selected');
           $('#datePicker').val('').datepicker('disable');
           console.log('Datepicker disabled');
       });

       $('#shiftSel').on('change',function() {
           $.ajax({
               url: '/api/Shifts/GetDates',
               data: { plantCd: '@Model.PlantCd',
                       lineId: $('#lineSel').val(),
                       shift: $('#shiftSel').val()
                    },
               success: function(e) {
                   var dates = e.toString().split(',');
                   $('#datePicker').datepicker('option', 'beforeShowDay', function(date) {
                        var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
                        return [dates.indexOf(string) == -1];
                   });
               }
            });
           $('#datePicker').datepicker('enable');
       });

       if ('@Model.Title' !== 'New Shift') {
           $('#shiftSel').change();
       }

       $('#lineSel').change();
});

#lineSel is the drop down for the line, #shiftSel the drop down for the shift, and #datePicker the date picker.

After the page loads, if I change the line drop down, the date picker disables like it should.  However, $('#lineSel').change(); executes the on('change') code ('Datepicker disabled' shows up in browser dev tools console), but the the date picker does not get disabled.

I've tried calling $('#datePicker').datepicker('disable') in the ready function, adding .change() to the end of the event handler binding, using .change(function() instead of on('change', function()), and other suggestions from this question and this question.

Any ideas why the date picker doesn't get disabled on page load and what I can do fix it?  Using jQuery UI 1.11.2 in and ASP.NET MVC 5 application.


问:
I am creating a sample website. How do I check how it looks on mobile devices?
I have not launched the website yet. All the mobile testing websites I have found on the internet are asking for my URL. Is there any way to test a website that has not been launched yet?</p>

答:
You can use Chrome's responsive mode:

Go to DevTools (Ctrl+Shift+I)

Click the phone/tablet icon in topbar (2nd from the left) or Ctrl+Shift+M

Then you can resize website or select sample device from menu.


问:
Squeeze blank lines into one blank line in C
Hello to refer to the  same question but different code.

Replacing multiple new lines in a file with just one

```<code>int main(void){

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

void format(){
    int c;
    size_t nlines = 1;
    size_t nspace = 0;

    while (( c= getchar()) != EOF ){

        /*TABS*/
        if(c == '\t'){
            c = ' ';
        }
        /*SPACES*/
        if (c ==' '){
            if(nspace > 0){
                continue;
            }
            else{
                putchar(c);
                nspace++;
                nlines = 0;
            }
        }

        /*NEW LINE*/
        else if(c == '\n'){
            if(++nlines >2){
                continue;
            }
            else {
                nlines++;
                nspace = 0;
            }
            putchar(c);
        }
        else{
            putchar(c);
            nspace = 0;
            nlines = 0;
        }
    }
}
</code>```

I want to squeeze multiple blank lines into one blank line but it doesn't seem to work and on Cygwin terminal at the stdout, last line gives me extra blank line although the input doesn't have the blank line at the end.

For example

INPUT

```<code>Hello   Hi\n
\n
\n
Hey\t\tHola\n
</code>```

DESIRED OUTPUT

```<code>Hello Hi\n
\n
Hey Hola\n
</code>```

ACTUAL OUTPUT

```<code>Hello Hi\n
Hey Hola\n
</code>```

Please explain!

答:
Here's a variant of your code.  I eliminated the format() function (which is unusual for me since most programs on SO don't use enough functions) incorporating it directly into main().  The code treats spaces and newlines more symmetrically now, fixing the double increment problem also identified in paddy's answer.  It also only prints out a newline at the end if there wasn't already a newline at the end.  That normalizes files which do not end with a newline.  The initialization of nlines = 1; deals with multiple newlines at the start of the file — that was well done already.

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

int main(void)
{
    int c;
    size_t nlines = 1;
    size_t nspace = 0;

    while ((c = getchar()) != EOF)
    {
        if (c == '\t')
            c = ' ';
        if (c == ' ')
        {
            if (nspace < 1)
            {
                putchar(c);
                nspace++;
                nlines = 0;
            }
        }
        else if (c == '\n')
        {
            if (nlines < 2)
            {
                putchar(c);
                nlines++;
                nspace = 0;
            }
        }
        else
        {
            putchar(c);
            nspace = 0;
            nlines = 0;
        }
    }
    if (nlines == 0)
        putchar('\n');
    return 0;
}
</code>```

My testing uses some Bash-specific notations.  My program was sb73:
The last of test input does not include a final newline.  The outputs use ⌴ to indicate a newline in the output:

```<code>$ echo $'Hello   Hi\n\n\nHey\t\tHola\n' | sb73
Hello Hi⌴
⌴
Hey Hola
⌴
$
</code>```

and:

```<code>$ echo $'\n\nHello   Hi\n\n\n    Hey\t\tHola\n' | sb73
⌴
Hello Hi⌴
⌴
 Hey Hola⌴
⌴
$
</code>```

and:

```<code>$ printf '%s' $'\n\nHello   Hi\n\n\n    Hey\t\tHola' | sb73
⌴
Hello Hi⌴
⌴
 Hey Hola⌴
$
</code>```

Handling CRLF line endings

The comments identify that the code above doesn't work on a Cygwin terminal, and the plausible reason is that the data being modified has CRLF line endings.  There are various ways around this.  One is to find a way of forcing the standard input into text mode.  In text mode, CRLF line endings should be mapped to Unix-style '\n' (NL or LF only) endings on input, and Unix-style line ending should be mapped to CRLF line endings on output.

Alternatively, it would be possible simply to ignore CR characters:

```<code>--- sb73.c  2017-06-08 22:04:28.000000000 -0700
+++ sb47.c  2017-06-08 22:40:24.000000000 -0700
@@ -19,6 +19,8 @@
                 nlines = 0;
             }
         }
+        else if (c == '\r')
+            continue;    // Windows?
         else if (c == '\n')
         {
             if (nlines < 2)
</code>```

That's a 'unified diff' showing two extra lines in the code.  Or it is possible to handle CR not followed by LF as a regular character and yet handle CR followed by LF as a newline combination:

```<code>--- sb73.c  2017-06-08 22:04:28.000000000 -0700
+++ sb59.c  2017-06-08 22:42:43.000000000 -0700
@@ -19,6 +19,17 @@
                 nlines = 0;
             }
         }
+        else if (c == '\r')
+        {
+            if ((c = getchar()) == '\n')
+            {
+               ungetc(c, stdin);
+               continue;
+            }
+            putchar('\r');
+            nspace = 0;
+            nlines = 0;
+        }
         else if (c == '\n')
         {
             if (nlines < 2)
</code>```

There's probably a way to write a state machine that handles CR, but that would be more complex.

I have a utod program that converts Unix-style line endings to Windows-style; I used that in the pipeline to test the new variants of the code.

Body:
Hello to refer to the  same question but different code.

Replacing multiple new lines in a file with just one

int main(void){

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

void format(){
    int c;
    size_t nlines = 1;
    size_t nspace = 0;

    while (( c= getchar()) != EOF ){

        /*TABS*/
        if(c == '\t'){
            c = ' ';
        }
        /*SPACES*/
        if (c ==' '){
            if(nspace > 0){
                continue;
            }
            else{
                putchar(c);
                nspace++;
                nlines = 0;
            }
        }

        /*NEW LINE*/
        else if(c == '\n'){
            if(++nlines >2){
                continue;
            }
            else {
                nlines++;
                nspace = 0;
            }
            putchar(c);
        }
        else{
            putchar(c);
            nspace = 0;
            nlines = 0;
        }
    }
}

I want to squeeze multiple blank lines into one blank line but it doesn't seem to work and on Cygwin terminal at the stdout, last line gives me extra blank line although the input doesn't have the blank line at the end.

For example

INPUT

Hello   Hi\n
\n
\n
Hey\t\tHola\n

DESIRED OUTPUT

Hello Hi\n
\n
Hey Hola\n

ACTUAL OUTPUT

Hello Hi\n
Hey Hola\n

Please explain!

Body:
Here's a variant of your code.  I eliminated the format() function (which is unusual for me since most programs on SO don't use enough functions) incorporating it directly into main().  The code treats spaces and newlines more symmetrically now, fixing the double increment problem also identified in paddy's answer.  It also only prints out a newline at the end if there wasn't already a newline at the end.  That normalizes files which do not end with a newline.  The initialization of nlines = 1; deals with multiple newlines at the start of the file — that was well done already.

#include <stdio.h>

int main(void)
{
    int c;
    size_t nlines = 1;
    size_t nspace = 0;

    while ((c = getchar()) != EOF)
    {
        if (c == '\t')
            c = ' ';
        if (c == ' ')
        {
            if (nspace < 1)
            {
                putchar(c);
                nspace++;
                nlines = 0;
            }
        }
        else if (c == '\n')
        {
            if (nlines < 2)
            {
                putchar(c);
                nlines++;
                nspace = 0;
            }
        }
        else
        {
            putchar(c);
            nspace = 0;
            nlines = 0;
        }
    }
    if (nlines == 0)
        putchar('\n');
    return 0;
}

My testing uses some Bash-specific notations.  My program was sb73:
The last of test input does not include a final newline.  The outputs use ⌴ to indicate a newline in the output:

$ echo $'Hello   Hi\n\n\nHey\t\tHola\n' | sb73
Hello Hi⌴
⌴
Hey Hola
⌴
$

and:

$ echo $'\n\nHello   Hi\n\n\n    Hey\t\tHola\n' | sb73
⌴
Hello Hi⌴
⌴
 Hey Hola⌴
⌴
$

and:

$ printf '%s' $'\n\nHello   Hi\n\n\n    Hey\t\tHola' | sb73
⌴
Hello Hi⌴
⌴
 Hey Hola⌴
$

Handling CRLF line endings

The comments identify that the code above doesn't work on a Cygwin terminal, and the plausible reason is that the data being modified has CRLF line endings.  There are various ways around this.  One is to find a way of forcing the standard input into text mode.  In text mode, CRLF line endings should be mapped to Unix-style '\n' (NL or LF only) endings on input, and Unix-style line ending should be mapped to CRLF line endings on output.

Alternatively, it would be possible simply to ignore CR characters:

--- sb73.c  2017-06-08 22:04:28.000000000 -0700
+++ sb47.c  2017-06-08 22:40:24.000000000 -0700
@@ -19,6 +19,8 @@
                 nlines = 0;
             }
         }
+        else if (c == '\r')
+            continue;    // Windows?
         else if (c == '\n')
         {
             if (nlines < 2)

That's a 'unified diff' showing two extra lines in the code.  Or it is possible to handle CR not followed by LF as a regular character and yet handle CR followed by LF as a newline combination:

--- sb73.c  2017-06-08 22:04:28.000000000 -0700
+++ sb59.c  2017-06-08 22:42:43.000000000 -0700
@@ -19,6 +19,17 @@
                 nlines = 0;
             }
         }
+        else if (c == '\r')
+        {
+            if ((c = getchar()) == '\n')
+            {
+               ungetc(c, stdin);
+               continue;
+            }
+            putchar('\r');
+            nspace = 0;
+            nlines = 0;
+        }
         else if (c == '\n')
         {
             if (nlines < 2)

There's probably a way to write a state machine that handles CR, but that would be more complex.

I have a utod program that converts Unix-style line endings to Windows-style; I used that in the pipeline to test the new variants of the code.


问:
How to convert a image into formula using python
That might be a question that is a little... big. I was inspired by that, and wonder if I can do it in python:

Following its idea, I first got the edge of the image, take it as a matrix and evaluated the position of the points, then try to make it continuous, like that (apparently not beautiful... ):

(If I don't do that, plot them by line willbe like this:)

Then I make fft to the x and y coordinates, got that:

```<code>[ 92897.00000000    +0.j         -16312.65365042 -5708.43473681j
   6403.02886691-11902.98323505j ...
</code>```

I thought these number represents C_n below:

So I use these complex numbers, trying to construct an formula:

```<code>equ = ''
itera = 0
for comp in compList:  # compList is the list of the complex numbers
    mod = math.sqrt(comp.real**2 + comp.imag**2)
    arg = cmath.phase(comp)
    if not comp.imag == 0:
        equ += '+' + str(mod) + '*np.sin(' + str(itera*2) + '*t+' +\
            str(arg) + ')'
    else:
        equ += str(2 * comp.real)
    itera += 1
</code>```

Which gave me this:

```<code>185794.0+17282.618327763143*np.sin(2*t+-2.804972121911925)+13515.908721371954*np.sin(4*t+-1.0772633933209355)+11927.354784757847*np.sin(6*t+1.847507468889795)+...
</code>```

I do an eval() to it, thinking that'll be the formula, the total code is like this :

```<code>x, y = getBorder('target.png', maxRes = 256)
x, y = sortNearest(x, y, maxDistance = 15)

fx = np.fft.fft(x)
fy = np.fft.fft(y)

equaX = generateEqua(fx) #the codes beyond
equaY = generateEqua(fy)

t = np.linspace(0, len(x), 10000)
fsX = eval(equaX)
fsY = eval(equaY)

fig = plt.figure(figsize = (15, 15))
plt.plot(fsX, fsY, linewidth = 0.5)
plt.show()
</code>```

And that's what it gave: Apparently not what I want...

Here I am not asking for details, just wonder where might be incorrect, is my concept wrong?Lack something? Or I use some wrong options?

答:
If I am not totally wrong you should see, that if you scatterplot the image, that there are multiple y values for some x values. This would violate the basic principle of the Cartesian coordinate system.  Therefore you cannot deduce a single formula for the image.

When working with images you usually use a 2D array of the coordinates and then apply functions to each x-y coordinate.

Body:
That might be a question that is a little... big. I was inspired by that, and wonder if I can do it in python:

Following its idea, I first got the edge of the image, take it as a matrix and evaluated the position of the points, then try to make it continuous, like that (apparently not beautiful... ):

(If I don't do that, plot them by line willbe like this:)

Then I make fft to the x and y coordinates, got that:

[ 92897.00000000    +0.j         -16312.65365042 -5708.43473681j
   6403.02886691-11902.98323505j ...

I thought these number represents C_n below:

So I use these complex numbers, trying to construct an formula:

equ = ''
itera = 0
for comp in compList:  # compList is the list of the complex numbers
    mod = math.sqrt(comp.real**2 + comp.imag**2)
    arg = cmath.phase(comp)
    if not comp.imag == 0:
        equ += '+' + str(mod) + '*np.sin(' + str(itera*2) + '*t+' +\
            str(arg) + ')'
    else:
        equ += str(2 * comp.real)
    itera += 1

Which gave me this:

185794.0+17282.618327763143*np.sin(2*t+-2.804972121911925)+13515.908721371954*np.sin(4*t+-1.0772633933209355)+11927.354784757847*np.sin(6*t+1.847507468889795)+...

I do an eval() to it, thinking that'll be the formula, the total code is like this :

x, y = getBorder('target.png', maxRes = 256)
x, y = sortNearest(x, y, maxDistance = 15)

fx = np.fft.fft(x)
fy = np.fft.fft(y)

equaX = generateEqua(fx) #the codes beyond
equaY = generateEqua(fy)

t = np.linspace(0, len(x), 10000)
fsX = eval(equaX)
fsY = eval(equaY)

fig = plt.figure(figsize = (15, 15))
plt.plot(fsX, fsY, linewidth = 0.5)
plt.show()

And that's what it gave: Apparently not what I want...

Here I am not asking for details, just wonder where might be incorrect, is my concept wrong?Lack something? Or I use some wrong options?


问:
How to select an option in a jQuery ui selectmenu dynamically?
After changing a menu from a regular select to a jQuery selectmenu, I can no longer select options in it programatically.  Is there a way to do this?

The code to select is (assuming ListId is the actual Id of the list)

```<code>$('#ListId').val(value);
</code>```

The plugin is activited like this:

```<code>$("#ListId").selectmenu({ style: "dropdown", width:140 });
</code>```

Is there a way to select an item in the select menu?  Calling the same .val(value) function just selects the value in the hidden original select list, not the nicely styled jQuery selectmenu.

ContentLicense: CC BY-SA 2.5

Body:
After changing a menu from a regular select to a jQuery selectmenu, I can no longer select options in it programatically.  Is there a way to do this?

The code to select is (assuming ListId is the actual Id of the list)

$('#ListId').val(value);

The plugin is activited like this:

$("#ListId").selectmenu({ style: "dropdown", width:140 });

Is there a way to select an item in the select menu?  Calling the same .val(value) function just selects the value in the hidden original select list, not the nicely styled jQuery selectmenu.

Body: $('#ListId').selectmenu("value", value);


问:
How to unregister Spark UDF
I use Spark 1.6.0 with Java.

I'd like to unregister a Spark UDF. Is there a way like dropping a temporary table sqlContext.drop(TemporaryTableName)?

```<code>    sqlContext.udf().register("isNumeric", value -> {
        if(StringUtils.isNumeric((String)value)) {
            return 1;
        } else {
            return 0;
        }
    }, DataTypes.IntegerType);

sqlContext.functionRegistry().listFunction().toSet().toString()
</code>```

I tried to get all functions(including UDF we defined) from current sqlContext, and it works, but is there any way to unregister custom UDF 'isNumeric'

答:
the udf can be unregistered by executing the below SQL.

```<code>spark.sql("drop temporary function isNumeric")
</code>```

The below snippet shows creating a UDF and dropping of the UDF.

```<code>scala> spark.udf.register("test", (value: String) => value.toInt)
res16: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function1>,IntegerType,Some(List(StringType)))

scala> spark.catalog.listFunctions.filter(_.name == "test").collect
res17: Array[org.apache.spark.sql.catalog.Function] = Array(Function[name='test', className='null', isTemporary='true'])

scala> spark.sql("drop temporary function test")
res18: org.apache.spark.sql.DataFrame = []

scala> spark.catalog.listFunctions.filter(_.name == "test").collect
res19: Array[org.apache.spark.sql.catalog.Function] = Array()
</code>```

Spark 1.6v:

```<code>scala> sqlContext.sql("drop temporary function test")
{"level": "INFO ", "timestamp": "2017-06-09 05:43:44,650", "classname": "hive.ql.parse.ParseDriver", "body": "Parsing command: drop temporary function test"}
{"level": "INFO ", "timestamp": "2017-06-09 05:43:44,650", "classname": "hive.ql.parse.ParseDriver", "body": "Parse Completed"}
{"level": "INFO ", "timestamp": "2017-06-09 05:43:44,655", "classname": "hive.ql.parse.ParseDriver", "body": "Parsing command: drop temporary function test"}
{"level": "INFO ", "timestamp": "2017-06-09 05:43:44,656", "classname": "hive.ql.parse.ParseDriver", "body": "Parse Completed"}
res7: org.apache.spark.sql.DataFrame = [result: string]
</code>```

Title: How to unregister Spark UDF

Body:
I use Spark 1.6.0 with Java.

I'd like to unregister a Spark UDF. Is there a way like dropping a temporary table sqlContext.drop(TemporaryTableName)?

    sqlContext.udf().register("isNumeric", value -> {
        if(StringUtils.isNumeric((String)value)) {
            return 1;
        } else {
            return 0;
        }
    }, DataTypes.IntegerType);

sqlContext.functionRegistry().listFunction().toSet().toString()

I tried to get all functions(including UDF we defined) from current sqlContext, and it works, but is there any way to unregister custom UDF 'isNumeric'

Body:
the udf can be unregistered by executing the below SQL.

spark.sql("drop temporary function isNumeric")

The below snippet shows creating a UDF and dropping of the UDF.

scala> spark.udf.register("test", (value: String) => value.toInt)
res16: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function1>,IntegerType,Some(List(StringType)))

scala> spark.catalog.listFunctions.filter(_.name == "test").collect
res17: Array[org.apache.spark.sql.catalog.Function] = Array(Function[name='test', className='null', isTemporary='true'])

scala> spark.sql("drop temporary function test")
res18: org.apache.spark.sql.DataFrame = []

scala> spark.catalog.listFunctions.filter(_.name == "test").collect
res19: Array[org.apache.spark.sql.catalog.Function] = Array()

Spark 1.6v:

scala> sqlContext.sql("drop temporary function test")
{"level": "INFO ", "timestamp": "2017-06-09 05:43:44,650", "classname": "hive.ql.parse.ParseDriver", "body": "Parsing command: drop temporary function test"}
{"level": "INFO ", "timestamp": "2017-06-09 05:43:44,650", "classname": "hive.ql.parse.ParseDriver", "body": "Parse Completed"}
{"level": "INFO ", "timestamp": "2017-06-09 05:43:44,655", "classname": "hive.ql.parse.ParseDriver", "body": "Parsing command: drop temporary function test"}
{"level": "INFO ", "timestamp": "2017-06-09 05:43:44,656", "classname": "hive.ql.parse.ParseDriver", "body": "Parse Completed"}
res7: org.apache.spark.sql.DataFrame = [result: string]


问:
Supporting multiple size of screen
In my app i use Appbarlayout many times but the problem is when i run app in devices have resolution approx 480*720 the app bar layout cover whole screen

But in other high resolution devices it seems good

Not in appbarlayout also in navigation header height and other layout height.

How to fix this problem so that app seems good in low resolution as well as high resolution devices.

and also i want my app make tablet support. Tablets were so wide and looks weird in that also... Can some one help

Any answers will highly appreciated

答:
You can add your dimension under value folder. You need to create sub folder folder under VALUE section and put your dimensions under it. Please refer below links for more details it will solve your problem.

Different values folders in android

http://www.tothenew.com/blog/handle-multiple-screen-sizes-in-android/

https://developer.android.com/training/multiscreen/screensizes.html

https://developer.android.com/guide/practices/screens_support.html

Title: Supporting multiple size of screen


问:
Error: var is a reserved word - React native
I have made a simple ListView in React Native. I am getting an error as shown here. I searched the Internet but couldn't find relevant posts. The code is provided below.

```<code>import React, {Component} from "react";
import {StyleSheet, View, AppRegistry, ListView, Text} from "react-native";

class dhrumil extends Component{

constructor(props){
super(props);
this.state = {
var ds = new ListView.DataSource({rowsHasChanged : (r1,r2) => r1!==r2})
return {
dataSource: ds.cloneWithRows(["1","2","3","4","5"])
};
}
}

_renderer(rowData){
  return <Text>{rowData}</Text>;
}

render(){
return(
<ListView
dataSource = {() => this.state.dataSource}
renderRow = {() => this._renderer()}
/>
);

}

}
AppRegistry.registerComponent("dhrumil",()=>dhrumil);
</code>```

How do I solve it?

答:
You have written the wrong coding in constructor</p>

```<code>constructor(props) {
    super(props);
    var ds = new ListView.DataSource({rowsHasChanged : (r1,r2) => r1!==r2})
    this.state = {
        dataSource: ds.cloneWithRows(["1","2","3","4","5"])
    };
}
</code>```

Body:
I have made a simple ListView in React Native. I am getting an error as shown here. I searched the Internet but couldn't find relevant posts. The code is provided below.

import React, {Component} from "react";
import {StyleSheet, View, AppRegistry, ListView, Text} from "react-native";

class dhrumil extends Component{

constructor(props){
super(props);
this.state = {
var ds = new ListView.DataSource({rowsHasChanged : (r1,r2) => r1!==r2})
return {
dataSource: ds.cloneWithRows(["1","2","3","4","5"])
};
}
}

_renderer(rowData){
  return <Text>{rowData}</Text>;
}

render(){
return(
<ListView
dataSource = {() => this.state.dataSource}
renderRow = {() => this._renderer()}
/>
);

}

}
AppRegistry.registerComponent("dhrumil",()=>dhrumil);

How do I solve it?

Body:
You have written the wrong coding in constructor

constructor(props) {
    super(props);
    var ds = new ListView.DataSource({rowsHasChanged : (r1,r2) => r1!==r2})
    this.state = {
        dataSource: ds.cloneWithRows(["1","2","3","4","5"])
    };
}


问:
AWS API: how to cast dynamo result as class
So I have a model repository that utilizes the C# AWS SDK for Dynamo. Right now it's a bit ugly. What I'd like is to cast-out result items to my model. Going into Dynamo it's great. I just do some type reflection on my Poco classes and shove them in like so:

```<code>     var doc = new Document();
     foreach (PropertyInfo prop in model.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
     {
         var propName = (string)prop.Name;
         // dont add if value is null
         if (prop.GetValue(model, null) != null)
         {
             if (prop.PropertyType == typeof(string))
                 doc[propName] = (string)prop.GetValue(model, null);
             if (prop.PropertyType == typeof(List<string>))
                 doc[propName] = (List<string>)prop.GetValue(model, null);
             if (prop.PropertyType == typeof(float))
                 doc[propName] = (float)prop.GetValue(model, null);
         }
     }
</code>```

But here in the repo, I'd like to not have to write this ugly manual cast when retrieving items. Is there a AWS helper to make this less manual? I guess I could write the inverse of the above loop and get the attribute property names then test for null on each N, S, SS  type etc.

```<code>var request = new ScanRequest
            {
                TableName = TableName.User,
            };

            var response = client.Scan(request);
            var collection = (from item in response.ScanResult.Items
                from att in item
                select new User(att.Value.S, att.Value.N, att.Value.S, att.Value.N, att.Value.S, att.Value.S, att.Value.S, att.Value.S, att.Value.S,
                    att.Value.S, att.Value.S, att.Value.S, att.Value.S, att.Value.SS, att.Value.SS)).ToList();

            return collection.AsQueryable();
</code>```

答: From the aws Document result class, you can use the instance method: .ToJson(), then deserialise into your class.</p>

Body:
So I have a model repository that utilizes the C# AWS SDK for Dynamo. Right now it's a bit ugly. What I'd like is to cast-out result items to my model. Going into Dynamo it's great. I just do some type reflection on my Poco classes and shove them in like so:

     var doc = new Document();
     foreach (PropertyInfo prop in model.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
     {
         var propName = (string)prop.Name;
         // dont add if value is null
         if (prop.GetValue(model, null) != null)
         {
             if (prop.PropertyType == typeof(string))
                 doc[propName] = (string)prop.GetValue(model, null);
             if (prop.PropertyType == typeof(List<string>))
                 doc[propName] = (List<string>)prop.GetValue(model, null);
             if (prop.PropertyType == typeof(float))
                 doc[propName] = (float)prop.GetValue(model, null);
         }
     }

But here in the repo, I'd like to not have to write this ugly manual cast when retrieving items. Is there a AWS helper to make this less manual? I guess I could write the inverse of the above loop and get the attribute property names then test for null on each N, S, SS  type etc.

var request = new ScanRequest
            {
                TableName = TableName.User,
            };

            var response = client.Scan(request);
            var collection = (from item in response.ScanResult.Items
                from att in item
                select new User(att.Value.S, att.Value.N, att.Value.S, att.Value.N, att.Value.S, att.Value.S, att.Value.S, att.Value.S, att.Value.S,
                    att.Value.S, att.Value.S, att.Value.S, att.Value.S, att.Value.SS, att.Value.SS)).ToList();

            return collection.AsQueryable();


问:
Python: How to write to data in a form of table to a spreadsheet
I have a code that calculates a given function at different points, that is :

```<code>def f(x):
    return np.sin(x)
x=np.arange(-1,1,0.01)
print np.sin(x)
</code>```

I want to store the values to an excel sheet using this format:

Is there a simple way to do it without using the pandas DataFrame since it this package is now working on my laptop

答:
An easy way to do it is use the csv module to write to a csv file, which can then be read into excel.

An example would be:

```<code>import csv
import numpy as np

def f(val):
    return np.sin(val)

x = np.arange(-1, 1, 0.01)
y = f(x)

with open('outfile.csv', 'w') as fid:
    writer = csv.writer(fid)
    writer.writerow(['x'] + list(x))
    writer.writerow(['f(x)'] + list(y))
</code>```

On the other hand, if you really want to write to excel, you can use packages that handle excel files. You can refer to http://www.python-excel.org/ for a list of relevant packages that are not pandas

Body:
I have a code that calculates a given function at different points, that is :

def f(x):
    return np.sin(x)
x=np.arange(-1,1,0.01)
print np.sin(x)

I want to store the values to an excel sheet using this format:

Is there a simple way to do it without using the pandas DataFrame since it this package is now working on my laptop

Body:
An easy way to do it is use the csv module to write to a csv file, which can then be read into excel.

An example would be:

import csv
import numpy as np

def f(val):
    return np.sin(val)

x = np.arange(-1, 1, 0.01)
y = f(x)

with open('outfile.csv', 'w') as fid:
    writer = csv.writer(fid)
    writer.writerow(['x'] + list(x))
    writer.writerow(['f(x)'] + list(y))

On the other hand, if you really want to write to excel, you can use packages that handle excel files. You can refer to http://www.python-excel.org/ for a list of relevant packages that are not pandas


问:
Jmeter JSON PATH postprocessor
I have my JSON response code as

```<code><script type="text/javascript" id="RequestScript">
var contextpath = 'https://example.com/';
var JSONObject = null;
var XMLString ='';
var pswitchprofiles = new Object();

pswitchprofiles.WLDATAObject =
{
:   switchprofile:
:   {
:   :   totalRows:5,
:   :   moreRows:false,
:   :   rows:
:   :   [
:   :   :   {
:   :   :   :   id:'1f04b8c7788f47eaba507cd1f01bafd6',
:   :   :   :   ex:'N',
:   :   :   :   name:'Mahindra'
:   :   :   },
:   :   :   {
:   :   :   :   id:'a316419bf71f402cbc3a7af746d80626',
:   :   :   :   ex:'N',
:   :   :   :   name:'Toyota'
:   :   :   },
:   :   :   {
:   :   :   :   id:'1b8f642c00c6469cad1f73829d1b88df',
:   :   :   :   ex:'N',
:   :   :   :   name:'Renault'
:   :   :   },
:   :   :   {
:   :   :   :   id:'df989db921f84dfcac2fb1d4e72c18a3',
:   :   :   :   ex:'N',
:   :   :   :   name:'Huyndai'
:   :   :   },
:   :   :   {
:   :   :   :   id:'43B014C9BF0C1516E0530100007F2995',
:   :   :   :   ex:'N',
:   :   :   :   name:'Skoda'
:   :   :   }
:   :   ]
:   }
}
;
</script>
</code>```

I am trying to get the id for the corresponding name.
In JSON PATH postprocessor, if i give          $.switchprofile.rows[?(@.name == 'Renault')].id               in JSON path expressions, I am not able to get the correct id.

Please help me in getting it. Also, i am not sure if that response is actually JSON.
I am using jmeter 3.0

答:
When i use Regular expression extactor with expression id:'(\w*)',ex:'N',name:'Renault' i am able to get my id properly.

Thanks @Dmitri for your help.

Title: Jmeter JSON PATH postprocessor

Body:
I have my JSON response code as

I am trying to get the id for the corresponding name.
In JSON PATH postprocessor, if i give          $.switchprofile.rows[?(@.name == 'Renault')].id               in JSON path expressions, I am not able to get the correct id.

Please help me in getting it. Also, i am not sure if that response is actually JSON.
I am using jmeter 3.0


答:
You could try multiple extensions from chrome web store such as
https://chrome.google.com/webstore/detail/responsive-web-design-tes/objclahbaimlfnbjdeobicmmlnbhamkg?utm_source=chrome-ntp-icon if you are using chrome. Type "responsive" in search and you will get various extensions. You can also do ctrl+shift+m.

If using firefox you can do Ctrl+shift+m and you can view your website in responsive mode.

Also you can try resizing the browser as a third alternative.

Title: I am creating a sample website. How do I check how it looks on mobile devices?

Body: I have not launched the website yet. All the mobile testing websites I have found on the internet are asking for my URL. Is there any way to test a website that has not been launched yet?


问:
"Gradle files have changed since last project sync." message always shows up
I'm working on an Android Studio project of which I write while constantly move back and forth from laptop to desktop using usb stick. There has been no problem for couple of months I tried this since Android Studio went stable, until today this message keeps showing up no matter how many times I sync the gradle:

Gradle files have changed since last project sync. A project sync may be necessary for the IDE to work properly.

Gradle Console indicates that the build is successful. I also tried cleaning and rebuilding the project, even reinstalling Android Studio, still the message pops out.

What seems to be the problem? Is it not recommended to write a project on multiple Android Studios?

Here's a look of my build.gradle:

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

android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "com.simplifyinc.prodigy"
    minSdkVersion 16
    targetSdkVersion 21
    versionCode 1
    versionName "0.3.2"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'de.hdodenhof:circleimageview:1.2.1'
    compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
    compile 'net.the4thdimension:audio-wife:1.0.3'
    compile project('libraries:android-crop')
}
</code>```

答: this error happen when android studio 2.3.3 available and i ignore it, upgrade your android studio to 2.3.3</p>

Body:
I'm working on an Android Studio project of which I write while constantly move back and forth from laptop to desktop using usb stick. There has been no problem for couple of months I tried this since Android Studio went stable, until today this message keeps showing up no matter how many times I sync the gradle:

Gradle files have changed since last project sync. A project sync may be necessary for the IDE to work properly.

Gradle Console indicates that the build is successful. I also tried cleaning and rebuilding the project, even reinstalling Android Studio, still the message pops out.

What seems to be the problem? Is it not recommended to write a project on multiple Android Studios?

Here's a look of my build.gradle:

apply plugin: 'com.android.application'

android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "com.simplifyinc.prodigy"
    minSdkVersion 16
    targetSdkVersion 21
    versionCode 1
    versionName "0.3.2"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'de.hdodenhof:circleimageview:1.2.1'
    compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
    compile 'net.the4thdimension:audio-wife:1.0.3'
    compile project('libraries:android-crop')
}


问:
Expand/reshape dimension of column of Pandas Series
I want to expand a pandas series from one to three dimension. Below print(np.array(xs).shape) gives me an output of (2,) and I would like the shape of np.array(xs) to be (2,3,3), what should I do?

```<code>import pandas as pd
x = []
x.append(np.ones((3,3)))
x.append(np.zeros((3,3)))

xs = pd.Series(x)
print(np.array(xs).shape)
</code>```

Any reply is appreciated!

note: I know np.array(x) would give me the desired output and shape, however I am given xs in the first place. The expected output should be print(np.array(x)) whose shape is (2,3,3).

```<code>array([[[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]],

      [[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]]])
</code>```

答:
You can convert Series to list and then to array:

```<code>print (np.array(xs.tolist()))
[[[ 1.  1.  1.]
  [ 1.  1.  1.]
  [ 1.  1.  1.]]

 [[ 0.  0.  0.]
  [ 0.  0.  0.]
  [ 0.  0.  0.]]]

print (np.array(xs.tolist()).shape)
(2, 3, 3)
</code>```

Body:
I want to expand a pandas series from one to three dimension. Below print(np.array(xs).shape) gives me an output of (2,) and I would like the shape of np.array(xs) to be (2,3,3), what should I do?

import pandas as pd
x = []
x.append(np.ones((3,3)))
x.append(np.zeros((3,3)))

xs = pd.Series(x)
print(np.array(xs).shape)

Any reply is appreciated!

note: I know np.array(x) would give me the desired output and shape, however I am given xs in the first place. The expected output should be print(np.array(x)) whose shape is (2,3,3).

array([[[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]],

      [[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]]])

Body:
You can convert Series to list and then to array:

print (np.array(xs.tolist()))
[[[ 1.  1.  1.]
  [ 1.  1.  1.]
  [ 1.  1.  1.]]

 [[ 0.  0.  0.]
  [ 0.  0.  0.]
  [ 0.  0.  0.]]]

print (np.array(xs.tolist()).shape)
(2, 3, 3)


问:
Windows server 2012 R2 IIS Hosting application
Hello i am trying to host a site on my windows server 2012 R2 and trying to access from my static public ip address but it not happening not sure where am going wrong my steps to do it was.

Add Website from applications Pools -> Site Name(test.com)

Physical path (C:\test.com)

Ip address as my local static ip (192.168.1.6) Port (93)

Then Click OK

add inbound rule in windows firewall -> port ->93 TCP ->Allow All connections -> Domain private and public -> description done

added port forward tcp for ip address 192.168.1.6 port 93

7.browsing from public ip address: WITH PORT not working

Please let me know where am going wrong am new to this

答:
You did mistake on step #3, in your bindings you need to use your public static IP. So, your steps should be like that:

Add Website from applications Pools -> Site Name(test.com)

Physical path (C:\test.com)

Ip address of your public static IP (XXX.XXX.XXX.XXX) Port (93) or you can select 'All Unassigned' option

Then Click OK

add inbound rule in windows firewall -> port ->93 TCP ->Allow All connections -> Domain private and public -> description done

added port forward tcp for ip address 192.168.1.6 port 93 (in your router)

browsing from public ip address: WITH PORT not working

If it is still not working, you need to check if port is actually open and nothing is blocking your port.

Install telnet client

Execute on command prompt this command telnet XXX.XXX.XXX.XXX 93 where XXX is your public IP. Telnet should successfully create connection to this port


问:
Get Filename Without Extension in Python
If I have a filename like one of these:

```<code>1.1.1.1.1.jpg

1.1.jpg

1.jpg
</code>```

How could I get only the filename, without the extension? Would a regex be appropriate?

答:
No need for regex. os.path.splitext is your friend:

```<code>os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')
</code>```

Body:
If I have a filename like one of these:

1.1.1.1.1.jpg

1.1.jpg

1.jpg

How could I get only the filename, without the extension? Would a regex be appropriate?

Body:
No need for regex. os.path.splitext is your friend:

os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')


问:
PG::UndefinedTable: ERROR: relation "admins" does not exist
I am trying to run this [https://github.com/ttseng/Build-in-Progress-Web/wiki/1.-Running-Locally][1] and so I installed the required materials and when it comes to the database setup I get this !
I can't really understand what is it? and why I can't deploy this platform locally without the database migration.
There are always two pending migration

```<code>  20170606002857 AddDeviseToAdmins
  20170606130509 AddUserRefToGoals
` root@debian:/home/zeeroday/github/Build-in-Progress-Web# bundle exec rake db:drop
root@debian:/home/zeeroday/github/Build-in-Progress-Web# bundle exec rake db:setup
-- create_table("activities", {:force=>true})
   -> 0.1371s
-- add_index("activities", ["owner_id", "owner_type"], {:name=>"index_activities_on_owner_id_and_owner_type"})
   -> 0.0910s
-- add_index("activities", ["recipient_id", "recipient_type"], {:name=>"index_activities_on_recipient_id_and_recipient_type"})
   -> 0.0911s
-- add_index("activities", ["trackable_id", "trackable_type"], {:name=>"index_activities_on_trackable_id_and_trackable_type"})
   -> 0.0909s
-- create_table("admin_users", {:force=>true})
   -> 0.1411s
-- add_index("admin_users", ["email"], {:name=>"index_admin_users_on_email", :unique=>true})
   -> 0.0909s
-- add_index("admin_users", ["reset_password_token"], {:name=>"index_admin_users_on_reset_password_token", :unique=>true})
   -> 0.0910s
-- create_table("categories", {:force=>true})
   -> 0.0992s
-- create_table("categorizations", {:force=>true})
   -> 0.0908s
-- add_index("categorizations", ["category_id", "project_id"], {:name=>"index_categorizations_on_category_id_and_project_id", :unique=>true})
   -> 0.0910s
-- add_index("categorizations", ["category_id"], {:name=>"index_categorizations_on_category_id"})
   -> 0.0907s
-- add_index("categorizations", ["project_id"], {:name=>"index_categorizations_on_project_id"})
   -> 0.0910s
-- create_table("collectifies", {:force=>true})
   -> 0.0993s
-- add_index("collectifies", ["collection_id", "project_id"], {:name=>"index_collectifies_on_collection_id_and_project_id", :unique=>true})
   -> 0.0907s
-- add_index("collectifies", ["collection_id"], {:name=>"index_collectifies_on_collection_id"})
   -> 0.0910s
-- add_index("collectifies", ["project_id"], {:name=>"index_collectifies_on_project_id"})
   -> 0.0908s
-- create_table("collections", {:force=>true})
   -> 0.1238s
-- add_index("collections", ["slug"], {:name=>"index_collections_on_slug"})
   -> 0.0742s
-- create_table("comments", {:force=>true})
   -> 0.1249s
-- add_index("comments", ["commentable_id", "commentable_type"], {:name=>"index_comments_on_commentable_id_and_commentable_type"})
   -> 0.0825s
-- add_index("comments", ["user_id"], {:name=>"index_comments_on_user_id"})
   -> 0.0827s
-- create_table("decisions", {:force=>true})
   -> 0.0825s
-- create_table("delayed_jobs", {:force=>true})
   -> 0.1244s
-- add_index("delayed_jobs", ["priority", "run_at"], {:name=>"delayed_jobs_priority"})
   -> 0.0825s
-- create_table("design_files", {:force=>true})
   -> 0.0828s
-- create_table("edits", {:force=>true})
   -> 0.0826s
-- create_table("favorite_projects", {:force=>true})
   -> 0.0910s
-- create_table("follows", {:force=>true})
   -> 0.1492s
-- add_index("follows", ["followable_id", "followable_type"], {:name=>"fk_followables"})
   -> 0.0907s
-- add_index("follows", ["follower_id", "follower_type"], {:name=>"fk_follows"})
   -> 0.0827s
-- create_table("friendly_id_slugs", {:force=>true})
   -> 0.0827s
-- add_index("friendly_id_slugs", ["slug", "sluggable_type"], {:name=>"index_friendly_id_slugs_on_slug_and_sluggable_type", :unique=>true})
   -> 0.0826s
-- add_index("friendly_id_slugs", ["sluggable_id"], {:name=>"index_friendly_id_slugs_on_sluggable_id"})
   -> 0.0825s
-- add_index("friendly_id_slugs", ["sluggable_type"], {:name=>"index_friendly_id_slugs_on_sluggable_type"})
   -> 0.0826s
-- create_table("images", {:force=>true})
   -> 0.1241s
-- create_table("news", {:force=>true})
   -> 0.1822s
-- create_table("placements", {:force=>true})
   -> 0.0909s
-- create_table("projects", {:force=>true})
   -> 0.1740s
-- create_table("projects_users", {:id=>false, :force=>true})
   -> 0.0083s
-- add_index("projects_users", ["project_id", "user_id"], {:name=>"index_projects_users_on_project_id_and_user_id"})
   -> 0.0823s
-- create_table("questions", {:force=>true})
   -> 0.0911s
-- create_table("remarks", {:force=>true})
   -> 0.1241s
-- create_table("sessions", {:force=>true})
   -> 0.1324s
-- add_index("sessions", ["session_id"], {:name=>"index_sessions_on_session_id"})
   -> 0.0825s
-- add_index("sessions", ["updated_at"], {:name=>"index_sessions_on_updated_at"})
   -> 0.0827s
-- create_table("settings", {:force=>true})
   -> 0.1578s
-- add_index("settings", ["target_type", "target_id", "var"], {:name=>"index_settings_on_target_type_and_target_id_and_var", :unique=>true})
   -> 0.0820s
-- create_table("sounds", {:force=>true})
   -> 0.1573s
-- create_table("steps", {:force=>true})
   -> 0.1241s
-- add_index("steps", ["ancestry"], {:name=>"index_steps_on_ancestry"})
   -> 0.0825s
-- create_table("users", {:force=>true})
   -> 0.1492s
-- add_index("users", ["authentication_token"], {:name=>"index_users_on_authentication_token", :unique=>true})
   -> 0.0823s
-- add_index("users", ["confirmation_token"], {:name=>"index_users_on_confirmation_token", :unique=>true})
   -> 0.0826s
-- add_index("users", ["email"], {:name=>"index_users_on_email", :unique=>true})
   -> 0.0908s
-- add_index("users", ["reset_password_token"], {:name=>"index_users_on_reset_password_token", :unique=>true})
   -> 0.0827s
-- add_index("users", ["unlock_token"], {:name=>"index_users_on_unlock_token", :unique=>true})
   -> 0.0826s
-- create_table("versions", {:force=>true})
   -> 0.1491s
-- add_index("versions", ["item_type", "item_id"], {:name=>"index_versions_on_item_type_and_item_id"})
   -> 0.0825s
-- create_table("videos", {:force=>true})
   -> 0.1574s
-- initialize_schema_migrations_table()
   -> 0.1017s
-- assume_migrated_upto_version(20170605230006, ["/home/zeeroday/github/Build-in-Progress-Web/db/migrate"])
   -> 0.8765s
You have 2 pending migrations:
  20170606002857 AddDeviseToAdmins
  20170606130509 AddUserRefToGoals
Run `rake db:migrate` to update your database then try again.
`
</code>```

I tried many things related to the same error but always the same thing.
And before I had the same error but I created an admin user in the DB and so it migrate most of the database except the two above.

答:
PG::UndefinedTable: ERROR: relation “admins” does not exist

As the log says you have pending migrations. You should run rake db:migrate to resolve the issue.

Body:
I am trying to run this [https://github.com/ttseng/Build-in-Progress-Web/wiki/1.-Running-Locally][1] and so I installed the required materials and when it comes to the database setup I get this !
I can't really understand what is it? and why I can't deploy this platform locally without the database migration.
There are always two pending migration

  20170606002857 AddDeviseToAdmins
  20170606130509 AddUserRefToGoals
` root@debian:/home/zeeroday/github/Build-in-Progress-Web# bundle exec rake db:drop
root@debian:/home/zeeroday/github/Build-in-Progress-Web# bundle exec rake db:setup
-- create_table("activities", {:force=>true})
   -> 0.1371s
-- add_index("activities", ["owner_id", "owner_type"], {:name=>"index_activities_on_owner_id_and_owner_type"})
   -> 0.0910s
-- add_index("activities", ["recipient_id", "recipient_type"], {:name=>"index_activities_on_recipient_id_and_recipient_type"})
   -> 0.0911s
-- add_index("activities", ["trackable_id", "trackable_type"], {:name=>"index_activities_on_trackable_id_and_trackable_type"})
   -> 0.0909s
-- create_table("admin_users", {:force=>true})
   -> 0.1411s
-- add_index("admin_users", ["email"], {:name=>"index_admin_users_on_email", :unique=>true})
   -> 0.0909s
-- add_index("admin_users", ["reset_password_token"], {:name=>"index_admin_users_on_reset_password_token", :unique=>true})
   -> 0.0910s
-- create_table("categories", {:force=>true})
   -> 0.0992s
-- create_table("categorizations", {:force=>true})
   -> 0.0908s
-- add_index("categorizations", ["category_id", "project_id"], {:name=>"index_categorizations_on_category_id_and_project_id", :unique=>true})
   -> 0.0910s
-- add_index("categorizations", ["category_id"], {:name=>"index_categorizations_on_category_id"})
   -> 0.0907s
-- add_index("categorizations", ["project_id"], {:name=>"index_categorizations_on_project_id"})
   -> 0.0910s
-- create_table("collectifies", {:force=>true})
   -> 0.0993s
-- add_index("collectifies", ["collection_id", "project_id"], {:name=>"index_collectifies_on_collection_id_and_project_id", :unique=>true})
   -> 0.0907s
-- add_index("collectifies", ["collection_id"], {:name=>"index_collectifies_on_collection_id"})
   -> 0.0910s
-- add_index("collectifies", ["project_id"], {:name=>"index_collectifies_on_project_id"})
   -> 0.0908s
-- create_table("collections", {:force=>true})
   -> 0.1238s
-- add_index("collections", ["slug"], {:name=>"index_collections_on_slug"})
   -> 0.0742s
-- create_table("comments", {:force=>true})
   -> 0.1249s
-- add_index("comments", ["commentable_id", "commentable_type"], {:name=>"index_comments_on_commentable_id_and_commentable_type"})
   -> 0.0825s
-- add_index("comments", ["user_id"], {:name=>"index_comments_on_user_id"})
   -> 0.0827s
-- create_table("decisions", {:force=>true})
   -> 0.0825s
-- create_table("delayed_jobs", {:force=>true})
   -> 0.1244s
-- add_index("delayed_jobs", ["priority", "run_at"], {:name=>"delayed_jobs_priority"})
   -> 0.0825s
-- create_table("design_files", {:force=>true})
   -> 0.0828s
-- create_table("edits", {:force=>true})
   -> 0.0826s
-- create_table("favorite_projects", {:force=>true})
   -> 0.0910s
-- create_table("follows", {:force=>true})
   -> 0.1492s
-- add_index("follows", ["followable_id", "followable_type"], {:name=>"fk_followables"})
   -> 0.0907s
-- add_index("follows", ["follower_id", "follower_type"], {:name=>"fk_follows"})
   -> 0.0827s
-- create_table("friendly_id_slugs", {:force=>true})
   -> 0.0827s
-- add_index("friendly_id_slugs", ["slug", "sluggable_type"], {:name=>"index_friendly_id_slugs_on_slug_and_sluggable_type", :unique=>true})
   -> 0.0826s
-- add_index("friendly_id_slugs", ["sluggable_id"], {:name=>"index_friendly_id_slugs_on_sluggable_id"})
   -> 0.0825s
-- add_index("friendly_id_slugs", ["sluggable_type"], {:name=>"index_friendly_id_slugs_on_sluggable_type"})
   -> 0.0826s
-- create_table("images", {:force=>true})
   -> 0.1241s
-- create_table("news", {:force=>true})
   -> 0.1822s
-- create_table("placements", {:force=>true})
   -> 0.0909s
-- create_table("projects", {:force=>true})
   -> 0.1740s
-- create_table("projects_users", {:id=>false, :force=>true})
   -> 0.0083s
-- add_index("projects_users", ["project_id", "user_id"], {:name=>"index_projects_users_on_project_id_and_user_id"})
   -> 0.0823s
-- create_table("questions", {:force=>true})
   -> 0.0911s
-- create_table("remarks", {:force=>true})
   -> 0.1241s
-- create_table("sessions", {:force=>true})
   -> 0.1324s
-- add_index("sessions", ["session_id"], {:name=>"index_sessions_on_session_id"})
   -> 0.0825s
-- add_index("sessions", ["updated_at"], {:name=>"index_sessions_on_updated_at"})
   -> 0.0827s
-- create_table("settings", {:force=>true})
   -> 0.1578s
-- add_index("settings", ["target_type", "target_id", "var"], {:name=>"index_settings_on_target_type_and_target_id_and_var", :unique=>true})
   -> 0.0820s
-- create_table("sounds", {:force=>true})
   -> 0.1573s
-- create_table("steps", {:force=>true})
   -> 0.1241s
-- add_index("steps", ["ancestry"], {:name=>"index_steps_on_ancestry"})
   -> 0.0825s
-- create_table("users", {:force=>true})
   -> 0.1492s
-- add_index("users", ["authentication_token"], {:name=>"index_users_on_authentication_token", :unique=>true})
   -> 0.0823s
-- add_index("users", ["confirmation_token"], {:name=>"index_users_on_confirmation_token", :unique=>true})
   -> 0.0826s
-- add_index("users", ["email"], {:name=>"index_users_on_email", :unique=>true})
   -> 0.0908s
-- add_index("users", ["reset_password_token"], {:name=>"index_users_on_reset_password_token", :unique=>true})
   -> 0.0827s
-- add_index("users", ["unlock_token"], {:name=>"index_users_on_unlock_token", :unique=>true})
   -> 0.0826s
-- create_table("versions", {:force=>true})
   -> 0.1491s
-- add_index("versions", ["item_type", "item_id"], {:name=>"index_versions_on_item_type_and_item_id"})
   -> 0.0825s
-- create_table("videos", {:force=>true})
   -> 0.1574s
-- initialize_schema_migrations_table()
   -> 0.1017s
-- assume_migrated_upto_version(20170605230006, ["/home/zeeroday/github/Build-in-Progress-Web/db/migrate"])
   -> 0.8765s
You have 2 pending migrations:
  20170606002857 AddDeviseToAdmins
  20170606130509 AddUserRefToGoals
Run `rake db:migrate` to update your database then try again.
`

I tried many things related to the same error but always the same thing.
And before I had the same error but I created an admin user in the DB and so it migrate most of the database except the two above.


问:
What is the Complexity of Find() Function
I have two versions of find function, both of which search an integer value in an array and return its position if exists. Function find1() will search up to N elements in worst case on the other hand find2() function will search up to N/2 elements in worst case. Does it mean find2() functions complexity is reduced into O(N/2)?

I assume the array arr contains non-duplicating values.

Function: find1()

```<code>int find1(int value){
    for (int i = 0; i < N; i++){
        if (arr[i] == value){
            return i;
        }
    }
    return -1;
}
</code>```

Function: find2()

```<code>int find2(int value){
    for (int i = 0, j = N - 1; i <= j; i++, j--){
        if (arr[i] == value){
            return i;
        }
        if (arr[j] == value){
            return j;
        }
    }
    return -1;
}
</code>```

答:
To begin with, the first version does in the worst case n iterations, and, in each iteration, does a constant number of operations. The second version does in the worst case n / 2 iterations, and, in each iteration, also does a constant number of operations, but a larger constant. Thus, there is no reason to think that the first is O(n) and the second is O(n / 2).

In any case, O(n) = O(n / 2). By the definition of O, O(n) means that there is a constant c1 such that for every n > n1,

f(n) < c1 n.

Similarly, O(n / 2) means that there is a constant c2 such that for every n > n2,

f(n) < c2 n / 2 = (c2 / 2) n.

Since for any n > max(n1, n2) the inequality holds for c1 = c2 / 2, each of these two implies the other one.

Body:
I have two versions of find function, both of which search an integer value in an array and return its position if exists. Function find1() will search up to N elements in worst case on the other hand find2() function will search up to N/2 elements in worst case. Does it mean find2() functions complexity is reduced into O(N/2)?

I assume the array arr contains non-duplicating values.

Function: find1()

int find1(int value){
    for (int i = 0; i < N; i++){
        if (arr[i] == value){
            return i;
        }
    }
    return -1;
}

Function: find2()

int find2(int value){
    for (int i = 0, j = N - 1; i <= j; i++, j--){
        if (arr[i] == value){
            return i;
        }
        if (arr[j] == value){
            return j;
        }
    }
    return -1;
}


问:
IONIC: unable to load dynamic content in `ion-infinite-scroll`
I am new with ionic framework.Currently i am working on ionicsidemenu app.

I have 100 plus records i want to display 20 records at once.   When scroll down get next 20 records.   For this i am using ion-infinite-scroll but i am unable to understand how to call next 20 records. I am  using webservice for fetching records.

Please help me.

答:
use limitTo together with Infinite scrolling. AngularJS ng-repeat offers from version 1.1.4 the limitTo option. I slightly adapted the Infinite Scroll directive to make scrolling within a container possible that does not have height 100% of window.

```<code>   ng-repeat="item in items | orderBy:prop | filter:query | limitTo:limit"
</code>```

Notice that limit is a variable in the $scope, so changing it automatically adjusts the number of rendered items. And incrementing limit, only renders the added elements.

```<code><table>
    <tr ng-repeat="d in data | limitTo:totalDisplayed"><td>{{d}}</td></tr>
</table>
<button class="btn" ng-click="loadMore()">Load more</button>

//the controller
$scope.totalDisplayed = 20;

$scope.loadMore = function () {
  $scope.totalDisplayed += 20;
};

$scope.data = data;
</code>```

or try out this solution

```<code><body>
    <pane ng-controller="MainCtrl">
         <header-bar title="'Infinite Scroll Example'">
          </header-bar>
        <content has-header="true"  padding="true" on-infinite-scroll="addMoreItem">
          <div class=" list padding">
            <div ng-repeat="item in items | limitTo:numberOfItemsToDisplay" class="item" type="item-text-wrap">
              <h3>{{item}}</h3>
            </div>
          </div>
        </content>
    </pane>

  </body>
</code>```

js code

```<code>angular.module('myApp', ['ionic'])
  .controller('MainCtrl', function($scope) {
      $scope.numberOfItemsToDisplay = 20; // number of item to load each time
      $scope.items = getData();

      function getData() {
        var a = [];
        for (var i=1; i< 1000; i++) {
            a.push(i);
        }

        return a;
      }
      $scope.addMoreItem = function(done) {
        if ($scope.items.length > $scope.numberOfItemsToDisplay)
          $scope.numberOfItemsToDisplay += 20; // load 20 more items
        done(); // need to call this when finish loading more data
      }

    });
</code>```

while on scrolling will display 20 items.

Body:
use limitTo together with Infinite scrolling. AngularJS ng-repeat offers from version 1.1.4 the limitTo option. I slightly adapted the Infinite Scroll directive to make scrolling within a container possible that does not have height 100% of window.

   ng-repeat="item in items | orderBy:prop | filter:query | limitTo:limit"

Notice that limit is a variable in the $scope, so changing it automatically adjusts the number of rendered items. And incrementing limit, only renders the added elements.

<table>
    <tr ng-repeat="d in data | limitTo:totalDisplayed"><td>{{d}}</td></tr>
</table>
<button class="btn" ng-click="loadMore()">Load more</button>

//the controller
$scope.totalDisplayed = 20;

$scope.loadMore = function () {
  $scope.totalDisplayed += 20;
};

$scope.data = data;

or try out this solution

<body>
    <pane ng-controller="MainCtrl">
         <header-bar title="'Infinite Scroll Example'">
          </header-bar>
        <content has-header="true"  padding="true" on-infinite-scroll="addMoreItem">
          <div class=" list padding">
            <div ng-repeat="item in items | limitTo:numberOfItemsToDisplay" class="item" type="item-text-wrap">
              <h3>{{item}}</h3>
            </div>
          </div>
        </content>
    </pane>

  </body>

js code

angular.module('myApp', ['ionic'])
  .controller('MainCtrl', function($scope) {
      $scope.numberOfItemsToDisplay = 20; // number of item to load each time
      $scope.items = getData();

      function getData() {
        var a = [];
        for (var i=1; i< 1000; i++) {
            a.push(i);
        }

        return a;
      }
      $scope.addMoreItem = function(done) {
        if ($scope.items.length > $scope.numberOfItemsToDisplay)
          $scope.numberOfItemsToDisplay += 20; // load 20 more items
        done(); // need to call this when finish loading more data
      }

    });

while on scrolling will display 20 items.


问:
I am creating a sample website. How do I check how it looks on mobile devices?
I have not launched the website yet. All the mobile testing websites I have found on the internet are asking for my URL. Is there any way to test a website that has not been launched yet?</p>

答: If you are using Chrome then go through this. For Interner Explorer try this method.</p>


问:
Android Architecture component LiveData - how to bind broadcastReceivers to lifecycle
Using Android LiveData I'd like to be able to unregister and register many BroadcastReceivers in the onInactive() and onActive() call backs. So I want to do something like this:

```<code>public class BroadcastRecieverLiveData extends LiveData<BroadCastReciever> {
    private BroadcastReciever reciever;
    private Context context;

    public BroadcastRecieverLiveData(Context context) {
        this.context = context;
    }

    @Override
    protected void onActive() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("SOME_ACTION");
        filter.addAction("SOME_OTHER_ACTION");

        reciever = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //do something based on the intent's action
            }
        };
        registerReceiver(reciever, filter);
    }

    @Override
    protected void onInactive() {
        if (reciever != null) {
            context.unregisterReceiver(reciever);
        }
    }
}
</code>```

I was thinking this could be a design pattern to be clean up of code instead of relaying on onDestroy. What are your thoughts on using LiveData this way? There is an example of using it here

答:
I think for receivers, you should implement LifecycleObserver.
As per LiveData documentation from Google codelab,

Caution: Storing a reference to a Context or View in a ViewModel can
  result in memory leaks. Avoid fields that reference instances of the
  Context or View classes. The onCleared() method is useful to
  unsubscribe or clear references to other objects with a longer
  lifecycle, but not for clearing references to Context or View objects.

So, You should not do context intensive operation in LiveData.

Instead, take an example of below implementation,

```<code>import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.OnLifecycleEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class ReceiverManager implements LifecycleObserver {

    private final Context mContext;
    private final MyBrodacastReceiver myBrodacastReceiver;

    public ReceiverManager(LifecycleOwner lifecycleOwner,
                           Context context) {
        mContext = context;
        myBrodacastReceiver = new MyBrodacastReceiver();
        lifecycleOwner.getLifecycle().addObserver(this);

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void registerYourReceiver() {
        mContext.registerReceiver(myBrodacastReceiver, new IntentFilter());
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void unRegisterYourReceiver() {
        mContext.unregisterReceiver(myBrodacastReceiver);
    }

    private static class MyBrodacastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

        }
    }
}
</code>```

Thanks.

Body:
Using Android LiveData I'd like to be able to unregister and register many BroadcastReceivers in the onInactive() and onActive() call backs. So I want to do something like this:

public class BroadcastRecieverLiveData extends LiveData<BroadCastReciever> {
    private BroadcastReciever reciever;
    private Context context;

    public BroadcastRecieverLiveData(Context context) {
        this.context = context;
    }

    @Override
    protected void onActive() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("SOME_ACTION");
        filter.addAction("SOME_OTHER_ACTION");

        reciever = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //do something based on the intent's action
            }
        };
        registerReceiver(reciever, filter);
    }

    @Override
    protected void onInactive() {
        if (reciever != null) {
            context.unregisterReceiver(reciever);
        }
    }
}

I was thinking this could be a design pattern to be clean up of code instead of relaying on onDestroy. What are your thoughts on using LiveData this way? There is an example of using it here

Body:
I think for receivers, you should implement LifecycleObserver.
As per LiveData documentation from Google codelab,

Caution: Storing a reference to a Context or View in a ViewModel can
  result in memory leaks. Avoid fields that reference instances of the
  Context or View classes. The onCleared() method is useful to
  unsubscribe or clear references to other objects with a longer
  lifecycle, but not for clearing references to Context or View objects.

So, You should not do context intensive operation in LiveData.

Instead, take an example of below implementation,

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.OnLifecycleEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class ReceiverManager implements LifecycleObserver {

    private final Context mContext;
    private final MyBrodacastReceiver myBrodacastReceiver;

    public ReceiverManager(LifecycleOwner lifecycleOwner,
                           Context context) {
        mContext = context;
        myBrodacastReceiver = new MyBrodacastReceiver();
        lifecycleOwner.getLifecycle().addObserver(this);

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void registerYourReceiver() {
        mContext.registerReceiver(myBrodacastReceiver, new IntentFilter());
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void unRegisterYourReceiver() {
        mContext.unregisterReceiver(myBrodacastReceiver);
    }

    private static class MyBrodacastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

        }
    }
}

Thanks.


问:
boost::counting_iterator analogue in range-v3
I am wondering if range-v3 library has any view/utility providing the functionality similar to boost::counting_iterators?

I was looking for something of that kind, but seems there is nothing readily available. But the documentation is incomplete (at least the README suggests so) so maybe there is something I have overlooked.

UPD: what I am actually looking for is not just a range of integers like view::iota but rather a range view (wrapper) that accepts any Incrementable.
One such example is the following code from Boost.CountingIterator documentation:

```<code>int N = 7;
std::vector<int> numbers;
...
// the code below does what I am actually looking for
// I would like to use a single range instead of two separate iterators here
std::vector<std::vector<int>::iterator> pointers;
std::copy(boost::make_counting_iterator(numbers.begin()),
          boost::make_counting_iterator(numbers.end()),
          std::back_inserter(pointers));
</code>```

答:
I believe view::ints is what you're looking for. You can make an unbounded range, and truncate it with something like view::take:

```<code>using namespace ranges;
int x = accumulate(view::ints(0) | view::take(10), 0); // 45
</code>```

or you can make a bounded range (lower inclusive, upper exclusive)

```<code>int x = accumulate(view::ints(0, 10), 0);
</code>```

For your example, you can use view::iota instead.

```<code>copy(view::iota(numbers.begin(), numbers.end()), back_inserter(pointers));
</code>```

Body:
I am wondering if range-v3 library has any view/utility providing the functionality similar to boost::counting_iterators?

I was looking for something of that kind, but seems there is nothing readily available. But the documentation is incomplete (at least the README suggests so) so maybe there is something I have overlooked.

UPD: what I am actually looking for is not just a range of integers like view::iota but rather a range view (wrapper) that accepts any Incrementable.
One such example is the following code from Boost.CountingIterator documentation:

int N = 7;
std::vector<int> numbers;
...
// the code below does what I am actually looking for
// I would like to use a single range instead of two separate iterators here
std::vector<std::vector<int>::iterator> pointers;
std::copy(boost::make_counting_iterator(numbers.begin()),
          boost::make_counting_iterator(numbers.end()),
          std::back_inserter(pointers));

Body:
I believe view::ints is what you're looking for. You can make an unbounded range, and truncate it with something like view::take:

using namespace ranges;
int x = accumulate(view::ints(0) | view::take(10), 0); // 45

or you can make a bounded range (lower inclusive, upper exclusive)

int x = accumulate(view::ints(0, 10), 0);

For your example, you can use view::iota instead.

copy(view::iota(numbers.begin(), numbers.end()), back_inserter(pointers));


问:
Wait for tasks in Ada
I have a procedure with tasks in it.
I have to do something after the all of the tasks terminated.
How can I do that?</p>

答:
Declare the tasks in an inner block: the block won't exit until all the tasks are complete, ARM7.6.1(4)</p>
```<code>with Ada.Text_IO; use Ada.Text_IO;
procedure After_Tasks is
begin
   Put_Line ("at the start");

   declare
      task T1;
      task T2;
      task body T1 is
      begin
         delay 1.0;
         Put_Line ("t1 done");
      end T1;
      task body T2 is
      begin
         delay 2.0;
         Put_Line ("t2 done");
      end T2;
   begin
      null;
   end;        -- block here until T1 & T2 are completed

   Put_Line ("at the end");
end After_Tasks;
</code>```

Title: Wait for tasks in Ada

Body:
Declare the tasks in an inner block: the block won't exit until all the tasks are complete, ARM7.6.1(4)

with Ada.Text_IO; use Ada.Text_IO;
procedure After_Tasks is
begin
   Put_Line ("at the start");

   declare
      task T1;
      task T2;
      task body T1 is
      begin
         delay 1.0;
         Put_Line ("t1 done");
      end T1;
      task body T2 is
      begin
         delay 2.0;
         Put_Line ("t2 done");
      end T2;
   begin
      null;
   end;        -- block here until T1 & T2 are completed

   Put_Line ("at the end");
end After_Tasks;

ContentLicense: CC BY-SA 4.0


问:
Ember js service and filterBy
i have a service to manage all the errors and alerts in my app. and the code looks like this

Service

```<code>import Ember from 'ember';

export default Ember.Service.extend({
messages: null,

init() {
    this._super(...arguments);
    this.set('messages', []);
},

add: function (severity, msg, messageType) {
    if (severity === 'error') {severity = 'danger';}

    var msgObject ={
        severity: severity,
        messageType: messageType,
        msg: msg,
        msgId: new Date()
    };
    this.get('messages').pushObject(msgObject);
},

remove(msgId) {
    this.get('messages').removeObject(msgId);
},

empty() {
    this.get('messages').clear();
}
});
</code>```

Component

```<code>import Ember from 'ember';

export default Ember.Component.extend({
messageType:'global',
messageHandler: Ember.inject.service(),

messages: function(){
    return this.get('messageHandler.messages').filterBy('messageType',this.get('messageType'));
}.property('messageHandler.messages'),

actions : {
    dismissAllAlerts: function(){
        this.get('messageHandler').empty();
    },
    dismissAlert: function(msgId){
        this.get('messageHandler').remove(msgId);
    }
}
});
</code>```

Initializer

```<code>export function initialize(container, application) {
application.inject('component', 'messageHandler', 'service:message-handler');
}

export default {
name: 'message-handler',
initialize : initialize
};
</code>```

Template

```<code>import Ember from 'ember';

export default Ember.Component.extend({
messageType:'global',
messageHandler: Ember.inject.service(),

messages: function(){
    return this.get('messageHandler.messages');
}.property('messageHandler.messages'),

actions : {
    dismissAllAlerts: function(){
        this.get('messageHandler').empty();
    },
    dismissAlert: function(msgId){
        this.get('messageHandler').remove(msgId);
    }
}
});
</code>```

and whenever there is an error i will add it like this

```<code>this.get('messageHandler').add('error',"Unable to get ossoi details","global");
</code>```

my problem is the filterBy in the component is not working. if i remove the filterBy() it works and i can see the error in the template. am kinda new to ember so if anyone can help me figure out what am missing here or if there is a better way of doing this please let me know

答:
filterBy usage is good and it should be working well. but messages computed property will not be recomputed whenever you add/remove item from messageHandler.messages.

```<code>messages: Ember.computed('messageHandler.messages.[]', function() {
        return this.get('messageHandler.messages').filterBy('messageType', this.get('messageType'));
    }),
</code>```

In the above code I used messageHandler.messages.[] as dependant key for the messages computed property so that it will be called for add/remove items.

Refer:https://guides.emberjs.com/v2.13.0/object-model/computed-properties-and-aggregate-data/

Computed properties dependent on an array using the [] key will only
  update if items are added to or removed from the array, or if the
  array property is set to a different array.

Title: Ember js service and filterBy

Body:
i have a service to manage all the errors and alerts in my app. and the code looks like this

Service

import Ember from 'ember';

export default Ember.Service.extend({
messages: null,

init() {
    this._super(...arguments);
    this.set('messages', []);
},

add: function (severity, msg, messageType) {
    if (severity === 'error') {severity = 'danger';}

    var msgObject ={
        severity: severity,
        messageType: messageType,
        msg: msg,
        msgId: new Date()
    };
    this.get('messages').pushObject(msgObject);
},

remove(msgId) {
    this.get('messages').removeObject(msgId);
},

empty() {
    this.get('messages').clear();
}
});

Component

import Ember from 'ember';

export default Ember.Component.extend({
messageType:'global',
messageHandler: Ember.inject.service(),

messages: function(){
    return this.get('messageHandler.messages').filterBy('messageType',this.get('messageType'));
}.property('messageHandler.messages'),

actions : {
    dismissAllAlerts: function(){
        this.get('messageHandler').empty();
    },
    dismissAlert: function(msgId){
        this.get('messageHandler').remove(msgId);
    }
}
});

Initializer

export function initialize(container, application) {
application.inject('component', 'messageHandler', 'service:message-handler');
}

export default {
name: 'message-handler',
initialize : initialize
};

Template

import Ember from 'ember';

export default Ember.Component.extend({
messageType:'global',
messageHandler: Ember.inject.service(),

messages: function(){
    return this.get('messageHandler.messages');
}.property('messageHandler.messages'),

actions : {
    dismissAllAlerts: function(){
        this.get('messageHandler').empty();
    },
    dismissAlert: function(msgId){
        this.get('messageHandler').remove(msgId);
    }
}
});

and whenever there is an error i will add it like this

this.get('messageHandler').add('error',"Unable to get ossoi details","global");

my problem is the filterBy in the component is not working. if i remove the filterBy() it works and i can see the error in the template. am kinda new to ember so if anyone can help me figure out what am missing here or if there is a better way of doing this please let me know

Body:
filterBy usage is good and it should be working well. but messages computed property will not be recomputed whenever you add/remove item from messageHandler.messages.

messages: Ember.computed('messageHandler.messages.[]', function() {
        return this.get('messageHandler.messages').filterBy('messageType', this.get('messageType'));
    }),

In the above code I used messageHandler.messages.[] as dependant key for the messages computed property so that it will be called for add/remove items.

Refer:https://guides.emberjs.com/v2.13.0/object-model/computed-properties-and-aggregate-data/

Computed properties dependent on an array using the [] key will only
  update if items are added to or removed from the array, or if the
  array property is set to a different array.


问:
Magento Product Import - Beyond CSV/XLS
I want to move an entire catalog from one magento store to another store on another server.  I realize I can import via csv, but I also want to maintain product relationships, grouped product relationship, config product relationships and images.  The only way I can think to do this is to write my own script using the Magento API.   Is there another more straight forward way of doing this? </p>

答:
I just found this extension, we'll see if it does the job:

http://www.commerceextensions.com/magento-product-import-export.html

Title: Magento Product Import - Beyond CSV/XLS


问:
How can I edit on my server files without restarting nodejs when i want to see the changes?
I'm trying to setup my own nodejs server, but I'm having a problem. I can't figure out how to see changes to my application without restarting it. Is there a way to edit the application and see changes live with node.js?</p>

答:
You can also use the tool PM2. Which is a advanced production process tool for node js.
 http://pm2.keymetrics.io/</p>