问:
What am I doing wrong to find element occurring most in array?
I am trying to debug one online coding platform problem. The problem I am facing is to return element occurring most often in array. I am interested in correcting my current code than trying other methods.

```<code>function findMostOccured(M, A) { //value of elements in A should not be greater than M
    var N = A.length;
    var count = new Array(M + 1);
    var i;
    for (i = 0; i <= M; i++)
        count[i] = 0;
    var maxOccurence = 1;
    var index = -1;
    for (i = 0; i < N; i++) {
        if (count[A[i]] > 0) {
            var tmp = count[A[i]];
            if (tmp > maxOccurence) {
                maxOccurence = tmp;
                index = i;
            }
            count[A[i]] = tmp + 1;
        } else {
            count[A[i]] = 1;
        }
    }
    return A[index];
}
</code>```

Given M = 3 and A = [1, 2, 3, 3, 1, 3, 1]. It should return 3 or 1.

答:
```<code>var arr = [1, 2, 3, 3, 1, 3, 1];
var M = 3;

function findMostOccured(M, arr) {
  var obj = {};
  var result = [];
  for (let i = 0; i < arr.length; i++) {
    if (obj[arr[i]]) {
      obj[arr[i]] = obj[arr[i]] + 1;
    } else {
      obj[arr[i]] = 1;
    }
  }

  for (var key in obj) {
    if (obj[key] === M) {
      result.push(parseInt(key));
    }
  }

  return result;
}

console.log(findMostOccured(3, arr));
</code>```

Body:
I am trying to debug one online coding platform problem. The problem I am facing is to return element occurring most often in array. I am interested in correcting my current code than trying other methods.

function findMostOccured(M, A) { //value of elements in A should not be greater than M
    var N = A.length;
    var count = new Array(M + 1);
    var i;
    for (i = 0; i <= M; i++)
        count[i] = 0;
    var maxOccurence = 1;
    var index = -1;
    for (i = 0; i < N; i++) {
        if (count[A[i]] > 0) {
            var tmp = count[A[i]];
            if (tmp > maxOccurence) {
                maxOccurence = tmp;
                index = i;
            }
            count[A[i]] = tmp + 1;
        } else {
            count[A[i]] = 1;
        }
    }
    return A[index];
}

Given M = 3 and A = [1, 2, 3, 3, 1, 3, 1]. It should return 3 or 1.


来源: stackexchange

问:
Javascript RegExp Matching weirdness
I have a RegExp:

/.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?/gi

and some text "Champion"

somehow, this is coming back as a match, am I crazy?

```<code>0: "pio"
1: "i"
index: 4
input: "Champion"
length: 2
</code>```

the loop is here:

```<code>// contruct the pattern, dynamically
var someText = "Champion";
var phrase = ".?(NCAA|Division|I|Basketball|Champions,|1939-2011).?";
var pat = new RegExp(phrase, "gi"); // <- ends up being
var result;

while( result = pat.exec(someText) ) {
     // do stuff!
}
</code>```

There has to be something wrong with my RegExp, right?

EDIT:
The .? thing was just a quick and dirty attempt to say that I'd like to match one of those words AND/OR one of those words with a single char on either side. ex:

```<code>\sNCAA\s
NCAA
NCAA\s
\sNCAA
</code>```

GOAL:
I'm trying to do some simple hit highlighting based on some search words. I've got a function that gets all of the text nodes on a page, and I'd like to go through them all and highlight any matches to any of the terms in my phrase variable.

I think that I just need to rework how I am building my RegExp.

答:
Add start (^) and end ($) anchors to the regexp.

```<code>/^.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?$/gi
</code>```

Without the anchors, the regexp's match can start and end anywhere in the string, which is why

```<code>/.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?/gi.exec('Champion')
</code>```

can match pio and i: because it's actually matching around the (case-insensitive) I. If you leave the anchors off, but remove the ...|I|..., the regex won't match 'Champion':

```<code>> /.?(NCAA|Division|Basketball|Champions,|1939-2011).?/gi.exec('Champion')
null
</code>```

ContentLicense: CC BY-SA 3.0

Title: Javascript RegExp Matching weirdness

Body:
I have a RegExp:

/.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?/gi

and some text "Champion"

somehow, this is coming back as a match, am I crazy?

0: "pio"
1: "i"
index: 4
input: "Champion"
length: 2

the loop is here:

// contruct the pattern, dynamically
var someText = "Champion";
var phrase = ".?(NCAA|Division|I|Basketball|Champions,|1939-2011).?";
var pat = new RegExp(phrase, "gi"); // <- ends up being
var result;

while( result = pat.exec(someText) ) {
     // do stuff!
}

There has to be something wrong with my RegExp, right?

EDIT:
The .? thing was just a quick and dirty attempt to say that I'd like to match one of those words AND/OR one of those words with a single char on either side. ex:

\sNCAA\s
NCAA
NCAA\s
\sNCAA

GOAL:
I'm trying to do some simple hit highlighting based on some search words. I've got a function that gets all of the text nodes on a page, and I'd like to go through them all and highlight any matches to any of the terms in my phrase variable.

I think that I just need to rework how I am building my RegExp.

Body:
Add start (^) and end ($) anchors to the regexp.

/^.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?$/gi

Without the anchors, the regexp's match can start and end anywhere in the string, which is why

/.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?/gi.exec('Champion')

can match pio and i: because it's actually matching around the (case-insensitive) I. If you leave the anchors off, but remove the ...|I|..., the regex won't match 'Champion':

> /.?(NCAA|Division|Basketball|Champions,|1939-2011).?/gi.exec('Champion')
null


问:
How to space two buttons
I am trying two put space between these two buttons

Tried style="margin-right: but it pushed the button down instead of keeping it even with the other button

<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

>>>Click Here to get Started Now<<<

>>>Schedule call and LEARN MORE <<<

```

答:
You can simply add a Padding-Right so there is a space between the fields you want.</p>

```<code><html>
    <head>
        <title>W3.CSS</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    </head>
    <body>
        <div class="w3-container">
            <div class="w3-show-inline-block">
                <div class="w3-bar" style="padding-right: 200px;">
                    <p style="text-align: left;"><a class="global-btn" style="margin-top: 0;" href="https://queencitylocal.com/contact/">>>>Click Here to get Started Now<<<</a></p>
                </div>
            </div>
            <div class="w3-show-inline-block">
                <div class="w3-bar">
                    <p style="text-align: right;"><a class="global-btn" style="margin-top: 0;" href="https://queencitylocal.com/contact/">>>>Schedule call and LEARN MORE <<<</a></p>
                </div>
            </div>
        </div>
    </body>
</html>
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to space two buttons

Body:
You can simply add a Padding-Right so there is a space between the fields you want.

<html>
    <head>
        <title>W3.CSS</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    </head>
    <body>
        <div class="w3-container">
            <div class="w3-show-inline-block">
                <div class="w3-bar" style="padding-right: 200px;">
                    <p style="text-align: left;"><a class="global-btn" style="margin-top: 0;" href="https://queencitylocal.com/contact/">&gt;&gt;&gt;Click Here to get Started Now&lt;&lt;&lt;</a></p>
                </div>
            </div>
            <div class="w3-show-inline-block">
                <div class="w3-bar">
                    <p style="text-align: right;"><a class="global-btn" style="margin-top: 0;" href="https://queencitylocal.com/contact/">&gt;&gt;&gt;Schedule call and LEARN MORE &lt;&lt;&lt;</a></p>
                </div>
            </div>
        </div>
    </body>
</html>


问:
BOUNCE animation does not work on the map
As the title suggests, the BOUNCE animation doesn't work on the map, but I'm sure it has to work this way. Can you help me figure out where I'm wrong? This is the piece of code I use to add markers to the map

```<code>this.addMarker = function(lat, lng, url, title, icon, shadow, body, full_address, animation) {
        if(lat == 0.0) return;

    var latLng = new google.maps.LatLng(lat, lng);
    var zIndex = 99999 + this.numMarkers;

    var markerOptions = {
        position: latLng,
        map: this.map,
        linkURL: '',
        zIndex: zIndex,
       // animation: "",//google.maps.Animation.BOUNCE,
        title: title,
        full_address: full_address
    };
    google.maps.event.addListener(markerOptions, "mouseover", up)

    function up(){
        if(typeof animation == "undefined"){
            markerOptions.animation = google.maps.Animation.BOUNCE;
        } else {
            markerOptions.animation = null;
        }
    }
    if(typeof icon !== "undefined" && icon.length > 0) markerOptions.icon = icon;
        else if(this.icon) markerOptions.icon = this.icon;

    // console.log(markerOptions);

    if(typeof shadow !== "undefined" && shadow.length > 0) markerOptions.shadow = shadow;
        else if(this.shadow.length > 0) markerOptions.shadow = this.shadow;

    var marker = new google.maps.Marker(markerOptions);

    var infowindow = new google.maps.InfoWindow({
        content: '<div class="gmaps-box" style="width: 100%;"><h5>'+title+'</h5><p>'+body+'</p></div>'
    });

    if(url.length > 0) marker.linkURL = url;
    if(this.hoverBox) marker.hoverBoxTitle = title;
        else marker.setTitle(title);

    this.markers[this.numMarkers] = marker;
    this.numMarkers++;

    if(marker.linkURL.length > 0) {
        google.maps.event.addListener(marker, 'click', function(e) {
            // window.location.href = marker.linkURL;
            infowindow.open(this.map, marker);

        });
    }
    if(markerOptions.icon !== "undefined" && this.iconHover) {
        var iconHover = this.iconHover;
        google.maps.event.addListener(marker, 'mouseover', function(e) {
            marker.setIcon(iconHover);
        });
        google.maps.event.addListener(marker, 'mouseout', function(e) {
            marker.setIcon(markerOptions.icon);
        });
    }

    if(this.hoverBox) {

        var $hoverBox = this.hoverBox;
        var offsetTop = this.hoverBoxOffsetTop;
        var offsetLeft = this.hoverBoxOffsetLeft;

        var mouseMove = function(e) {
            $hoverBox.css({
                'top': e.pageY + offsetTop,
                'left': e.pageX + offsetLeft
            });
        };

        // console.log($hoverBox);

        google.maps.event.addListener(marker, 'mouseover', function(e) {
            this._currentURL = url;
            $hoverBox.html("<span>" + marker.hoverBoxTitle + "</span>")
                .css('top', '0px')
                .css('left', '0px')
                .css('display', 'block')
                .css('width', 'auto')
                .css('z-index', 9999);
            $hoverBox.show();

            $(document).mousemove(mouseMove);
        });

        google.maps.event.addListener(marker, 'mouseout', function(e) {
            $hoverBox.hide();
            $(document).unbind("mousemove", mouseMove);
        });

    }
}
</code>```

The result should look like this: https://jsfiddle.net/api/post/library/pure/

答:
To keep things simple and not worrying about scope, instead of calling up in addEventListener, you can try calling the function itself:

```<code>google.maps.event.addListener(markerOptions, "mouseover", function(){
        if(typeof animation == "undefined"){
            markerOptions.animation = google.maps.Animation.BOUNCE;
        } else {
            markerOptions.animation = null;
        }
    });
</code>```

Body:
As the title suggests, the BOUNCE animation doesn't work on the map, but I'm sure it has to work this way. Can you help me figure out where I'm wrong? This is the piece of code I use to add markers to the map

this.addMarker = function(lat, lng, url, title, icon, shadow, body, full_address, animation) {
        if(lat == 0.0) return;

    var latLng = new google.maps.LatLng(lat, lng);
    var zIndex = 99999 + this.numMarkers;

    var markerOptions = {
        position: latLng,
        map: this.map,
        linkURL: '',
        zIndex: zIndex,
       // animation: "",//google.maps.Animation.BOUNCE,
        title: title,
        full_address: full_address
    };
    google.maps.event.addListener(markerOptions, "mouseover", up)

    function up(){
        if(typeof animation == "undefined"){
            markerOptions.animation = google.maps.Animation.BOUNCE;
        } else {
            markerOptions.animation = null;
        }
    }
    if(typeof icon !== "undefined" && icon.length > 0) markerOptions.icon = icon;
        else if(this.icon) markerOptions.icon = this.icon;

    // console.log(markerOptions);

    if(typeof shadow !== "undefined" && shadow.length > 0) markerOptions.shadow = shadow;
        else if(this.shadow.length > 0) markerOptions.shadow = this.shadow;

    var marker = new google.maps.Marker(markerOptions);

    var infowindow = new google.maps.InfoWindow({
        content: '

'+title+'

'+body+'

'
    });

    if(url.length > 0) marker.linkURL = url;
    if(this.hoverBox) marker.hoverBoxTitle = title;
        else marker.setTitle(title);

    this.markers[this.numMarkers] = marker;
    this.numMarkers++;

    if(marker.linkURL.length > 0) {
        google.maps.event.addListener(marker, 'click', function(e) {
            // window.location.href = marker.linkURL;
            infowindow.open(this.map, marker);

        });
    }
    if(markerOptions.icon !== "undefined" && this.iconHover) {
        var iconHover = this.iconHover;
        google.maps.event.addListener(marker, 'mouseover', function(e) {
            marker.setIcon(iconHover);
        });
        google.maps.event.addListener(marker, 'mouseout', function(e) {
            marker.setIcon(markerOptions.icon);
        });
    }

    if(this.hoverBox) {

        var $hoverBox = this.hoverBox;
        var offsetTop = this.hoverBoxOffsetTop;
        var offsetLeft = this.hoverBoxOffsetLeft;

        var mouseMove = function(e) {
            $hoverBox.css({
                'top': e.pageY + offsetTop,
                'left': e.pageX + offsetLeft
            });
        };

        // console.log($hoverBox);

        google.maps.event.addListener(marker, 'mouseover', function(e) {
            this._currentURL = url;
            $hoverBox.html("" + marker.hoverBoxTitle + "")
                .css('top', '0px')
                .css('left', '0px')
                .css('display', 'block')
                .css('width', 'auto')
                .css('z-index', 9999);
            $hoverBox.show();

            $(document).mousemove(mouseMove);
        });

        google.maps.event.addListener(marker, 'mouseout', function(e) {
            $hoverBox.hide();
            $(document).unbind("mousemove", mouseMove);
        });

    }
}

The result should look like this: https://jsfiddle.net/api/post/library/pure/

Body:
To keep things simple and not worrying about scope, instead of calling up in addEventListener, you can try calling the function itself:

google.maps.event.addListener(markerOptions, "mouseover", function(){
        if(typeof animation == "undefined"){
            markerOptions.animation = google.maps.Animation.BOUNCE;
        } else {
            markerOptions.animation = null;
        }
    });


问:
Get a single compare function to order both ASC and DESC using Array.sort()?
I need to order an array of objects by the property price.

Right now I have the following, which works as intended:

```<code>function orderByPriceASC(a,b) {
    return(
      a.price < b.price ? -1
      : a.price > b.price ? 1
        : 0
    );
  }

  function orderByPriceDESC(a,b) {
    return(
      a.price < b.price ? 1
      : a.price > b.price ? -1
        : 0
    );
  }

  function sortByPrice(order) {
    setProductList((prevState) => {
      const aux = Array.from(prevState);
      order === 'asc' ? aux.sort(orderByPriceASC) : aux.sort(orderByPriceDESC);
      return aux;
    });
  }
</code>```

But can is there a way that I can structure this so I can get a single compare function that works for both ASC and DESC order?

Something like:

```<code>function orderByPrice(a,b,order) {
    return(
      a.price < b.price ?
        order === 'asc' ? -1 : 1
      : a.price > b.price ? 1
        order === 'asc' ? 1 : -1
        : 0
    );
  }
</code>```

The problem is that I would have to send that extra parameter down to the Array.sort method which I don't think it's possible. Maybe with some wrapper function.

How can this be implemented?

答:
You could just do this:

```<code>function flip(f) {
    return function (a, b) {
        return f(b, a);
    };
}

function orderByPriceASC(a,b) {
    return (
        a.price < b.price ? -1 :
        a.price > b.price ? 1 :
        0
    );
}

function sortByPrice(order) {
    setProductList((prevState) => {
        const aux = Array.from(prevState);
        aux.sort(order === 'asc' ? orderByPriceASC : flip(orderByPriceASC));
        return aux;
    });
}
</code>```

This way you don't need a separate orderByPriceDESC function and you don't have to add any extra parameters either.

Body:
I need to order an array of objects by the property price.

Right now I have the following, which works as intended:

function orderByPriceASC(a,b) {
    return(
      a.price  b.price ? 1
        : 0
    );
  }

  function orderByPriceDESC(a,b) {
    return(
      a.price  b.price ? -1
        : 0
    );
  }

  function sortByPrice(order) {
    setProductList((prevState) => {
      const aux = Array.from(prevState);
      order === 'asc' ? aux.sort(orderByPriceASC) : aux.sort(orderByPriceDESC);
      return aux;
    });
  }

But can is there a way that I can structure this so I can get a single compare function that works for both ASC and DESC order?

Something like:

function orderByPrice(a,b,order) {
    return(
      a.price  b.price ? 1
        order === 'asc' ? 1 : -1
        : 0
    );
  }

The problem is that I would have to send that extra parameter down to the Array.sort method which I don't think it's possible. Maybe with some wrapper function.

How can this be implemented?

Body:
You could just do this:

function flip(f) {
    return function (a, b) {
        return f(b, a);
    };
}

function orderByPriceASC(a,b) {
    return (
        a.price < b.price ? -1 :
        a.price > b.price ? 1 :
        0
    );
}

function sortByPrice(order) {
    setProductList((prevState) => {
        const aux = Array.from(prevState);
        aux.sort(order === 'asc' ? orderByPriceASC : flip(orderByPriceASC));
        return aux;
    });
}

This way you don't need a separate orderByPriceDESC function and you don't have to add any extra parameters either.


问:
df.apply(sorted, axis=1) removes column names?
Working through Pandas Cookbook.  Counting the Total Number of Flights Between Cities.

```<code>import pandas as pd
import numpy as np
# import matplotlib.pyplot as plt

print('NumPy: {}'.format(np.__version__))
print('Pandas: {}'.format(pd.__version__))
print('-----')

desired_width = 320
pd.set_option('display.width', desired_width)
pd.options.display.max_rows = 50
pd.options.display.max_columns = 14
# pd.options.display.float_format = '{:,.2f}'.format

file = "e:\\packt\\data_analysis_and_exploration_with_pandas\\section07\\data\\flights.csv"
flights = pd.read_csv(file)
print(flights.head(10))
print()

# This returns the total number of rows for each group.
flights_ct = flights.groupby(['ORG_AIR', 'DEST_AIR']).size()
print(flights_ct.head(10))
print()

# Get the number of flights between Atlanta and Houston in both directions.
print(flights_ct.loc[[('ATL', 'IAH'), ('IAH', 'ATL')]])
print()

# Sort the origin and destination cities:
# flights_sort = flights.sort_values(by=['ORG_AIR', 'DEST_AIR'], axis=1)
flights_sort = flights[['ORG_AIR', 'DEST_AIR']].apply(sorted, axis=1)
print(flights_sort.head(10))
print()

# Passing just the first row.
print(sorted(flights.loc[0, ['ORG_AIR', 'DEST_AIR']]))
print()

# Once each row is independently sorted, the column name are no longer correct.
# We will rename them to something generic, then again find the total number of flights between all cities.
rename_dict = {'ORG_AIR': 'AIR1', 'DEST_AIR': 'AIR2'}
flights_sort = flights_sort.rename(columns=rename_dict)
flights_ct2 = flights_sort.groupby(['AIR1', 'AIR2']).size()
print(flights_ct2.head(10))
print()
</code>```

When I get to this line of code my output differs from the authors:

```<code>```flights_sort = flights[['ORG_AIR', 'DEST_AIR']].apply(sorted, axis=1)```
</code>```

My output does not contain any column names.  As a result, when I get to:

```<code>```flights_ct2 = flights_sort.groupby(['AIR1', 'AIR2']).size()```
</code>```

it throws a KeyError.  This makes sense, as I am trying to rename columns when no column names exist.

My question is, why are the column names gone?  All other output matches the authors output exactly:

```<code>Connected to pydev debugger (build 191.7141.48)
NumPy: 1.16.3
Pandas: 0.24.2
-----
   MONTH  DAY  WEEKDAY AIRLINE ORG_AIR DEST_AIR  SCHED_DEP  DEP_DELAY  AIR_TIME  DIST  SCHED_ARR  ARR_DELAY  DIVERTED  CANCELLED
0      1    1        4      WN     LAX      SLC       1625       58.0      94.0   590       1905       65.0         0          0
1      1    1        4      UA     DEN      IAD        823        7.0     154.0  1452       1333      -13.0         0          0
2      1    1        4      MQ     DFW      VPS       1305       36.0      85.0   641       1453       35.0         0          0
3      1    1        4      AA     DFW      DCA       1555        7.0     126.0  1192       1935       -7.0         0          0
4      1    1        4      WN     LAX      MCI       1720       48.0     166.0  1363       2225       39.0         0          0
5      1    1        4      UA     IAH      SAN       1450        1.0     178.0  1303       1620      -14.0         0          0
6      1    1        4      AA     DFW      MSY       1250       84.0      64.0   447       1410       83.0         0          0
7      1    1        4      F9     SFO      PHX       1020       -7.0      91.0   651       1315       -6.0         0          0
8      1    1        4      AA     ORD      STL       1845       -5.0      44.0   258       1950       -5.0         0          0
9      1    1        4      UA     IAH      SJC        925        3.0     215.0  1608       1136      -14.0         0          0

ORG_AIR  DEST_AIR
ATL      ABE         31
         ABQ         16
         ABY         19
         ACY          6
         AEX         40
         AGS         83
         ALB         33
         ANC          2
         ASE          1
         ATW         10
dtype: int64

ORG_AIR  DEST_AIR
ATL      IAH         121
IAH      ATL         148
dtype: int64

*** No columns names ***  Why?

0    [LAX, SLC]
1    [DEN, IAD]
2    [DFW, VPS]
3    [DCA, DFW]
4    [LAX, MCI]
5    [IAH, SAN]
6    [DFW, MSY]
7    [PHX, SFO]
8    [ORD, STL]
9    [IAH, SJC]
dtype: object
</code>```

The author's output. Note the columns names are present.

答:
A final note.  I just applied @AndyHayden numpy based solution from above.

```<code>flights_sort = flights[["ORG_AIR", "DEST_AIR"]].values
flights_sort.sort(axis=1)
flights[["ORG_AIR", "DEST_AIR"]] = flights_sort
</code>```

All I can say is … Wow.  What an enormous performance difference.  I get the exact same
correct answer and I get it as soon as I click the mouse as compared to the pandas lambda solution also provided by @AndyHayden which takes about 20 seconds to perform the sort.  That dataset is 58,000+ rows.  The numpy solution returns the sort instantly.

Body:
Working through Pandas Cookbook.  Counting the Total Number of Flights Between Cities.

import pandas as pd
import numpy as np
# import matplotlib.pyplot as plt

print('NumPy: {}'.format(np.__version__))
print('Pandas: {}'.format(pd.__version__))
print('-----')

desired_width = 320
pd.set_option('display.width', desired_width)
pd.options.display.max_rows = 50
pd.options.display.max_columns = 14
# pd.options.display.float_format = '{:,.2f}'.format

file = "e:\\packt\\data_analysis_and_exploration_with_pandas\\section07\\data\\flights.csv"
flights = pd.read_csv(file)
print(flights.head(10))
print()

# This returns the total number of rows for each group.
flights_ct = flights.groupby(['ORG_AIR', 'DEST_AIR']).size()
print(flights_ct.head(10))
print()

# Get the number of flights between Atlanta and Houston in both directions.
print(flights_ct.loc[[('ATL', 'IAH'), ('IAH', 'ATL')]])
print()

# Sort the origin and destination cities:
# flights_sort = flights.sort_values(by=['ORG_AIR', 'DEST_AIR'], axis=1)
flights_sort = flights[['ORG_AIR', 'DEST_AIR']].apply(sorted, axis=1)
print(flights_sort.head(10))
print()

# Passing just the first row.
print(sorted(flights.loc[0, ['ORG_AIR', 'DEST_AIR']]))
print()

# Once each row is independently sorted, the column name are no longer correct.
# We will rename them to something generic, then again find the total number of flights between all cities.
rename_dict = {'ORG_AIR': 'AIR1', 'DEST_AIR': 'AIR2'}
flights_sort = flights_sort.rename(columns=rename_dict)
flights_ct2 = flights_sort.groupby(['AIR1', 'AIR2']).size()
print(flights_ct2.head(10))
print()

When I get to this line of code my output differs from the authors:

```flights_sort = flights[['ORG_AIR', 'DEST_AIR']].apply(sorted, axis=1)```

My output does not contain any column names.  As a result, when I get to:

```flights_ct2 = flights_sort.groupby(['AIR1', 'AIR2']).size()```

it throws a KeyError.  This makes sense, as I am trying to rename columns when no column names exist.

My question is, why are the column names gone?  All other output matches the authors output exactly:

Connected to pydev debugger (build 191.7141.48)
NumPy: 1.16.3
Pandas: 0.24.2
-----
   MONTH  DAY  WEEKDAY AIRLINE ORG_AIR DEST_AIR  SCHED_DEP  DEP_DELAY  AIR_TIME  DIST  SCHED_ARR  ARR_DELAY  DIVERTED  CANCELLED
0      1    1        4      WN     LAX      SLC       1625       58.0      94.0   590       1905       65.0         0          0
1      1    1        4      UA     DEN      IAD        823        7.0     154.0  1452       1333      -13.0         0          0
2      1    1        4      MQ     DFW      VPS       1305       36.0      85.0   641       1453       35.0         0          0
3      1    1        4      AA     DFW      DCA       1555        7.0     126.0  1192       1935       -7.0         0          0
4      1    1        4      WN     LAX      MCI       1720       48.0     166.0  1363       2225       39.0         0          0
5      1    1        4      UA     IAH      SAN       1450        1.0     178.0  1303       1620      -14.0         0          0
6      1    1        4      AA     DFW      MSY       1250       84.0      64.0   447       1410       83.0         0          0
7      1    1        4      F9     SFO      PHX       1020       -7.0      91.0   651       1315       -6.0         0          0
8      1    1        4      AA     ORD      STL       1845       -5.0      44.0   258       1950       -5.0         0          0
9      1    1        4      UA     IAH      SJC        925        3.0     215.0  1608       1136      -14.0         0          0

ORG_AIR  DEST_AIR
ATL      ABE         31
         ABQ         16
         ABY         19
         ACY          6
         AEX         40
         AGS         83
         ALB         33
         ANC          2
         ASE          1
         ATW         10
dtype: int64

ORG_AIR  DEST_AIR
ATL      IAH         121
IAH      ATL         148
dtype: int64

*** No columns names ***  Why?

0    [LAX, SLC]
1    [DEN, IAD]
2    [DFW, VPS]
3    [DCA, DFW]
4    [LAX, MCI]
5    [IAH, SAN]
6    [DFW, MSY]
7    [PHX, SFO]
8    [ORD, STL]
9    [IAH, SJC]
dtype: object

The author's output. Note the columns names are present.

Body:
A final note.  I just applied @AndyHayden numpy based solution from above.

flights_sort = flights[["ORG_AIR", "DEST_AIR"]].values
flights_sort.sort(axis=1)
flights[["ORG_AIR", "DEST_AIR"]] = flights_sort

All I can say is … Wow.  What an enormous performance difference.  I get the exact same
correct answer and I get it as soon as I click the mouse as compared to the pandas lambda solution also provided by @AndyHayden which takes about 20 seconds to perform the sort.  That dataset is 58,000+ rows.  The numpy solution returns the sort instantly.


问:
Create new columns with quantiles from a group in r
I want to include new columns with quantile 1 y 3 by group

I have this dataframe:

```<code>d <- data.frame(date = c("2017-02-23", "2017-02-22", "2017-02-23", "2017-02-23","2018-02-22", "2018-02-22"),
var1 = c(1,3,6,7,8,5),
var2 = c(1,3,18,15,25,5))
</code>```

and I would like to have two new columns Q1var1, Q1var2, Q1var1 and Q1var2 like:

```<code>d = d %>% group_by(date) %>% mutate(Q1var1 = quantile(var1,prob = 0.25,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q1var2 = quantile(var1,prob = 0.25,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q3var1 = quantile(var1,prob = 0.75,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q3var2 = quantile(var1,prob = 0.75,na.rm = TRUE))
</code>```

but in a faster way

答:
Here's a base solution in case that's your jam. First, I define the data frame.

# Original data frame
d <- data.frame(date = c("2017-02-23", "2017-02-22", "2017-02-23", "2017-02-23","2018-02-22", "2018-02-22"),
                var1 = c(1,3,6,7,8,5),
                var2 = c(1,3,18,15,25,5))
```

<p>Next, I define a function that calculates the quantiles and binds them to the original data.</p>

<pre class="lang-r prettyprint-override"><code># Function to calculate quantiles
foo <- function(x){
  q <- quantile(x, prob = c(0.25, 0.75), na.rm = TRUE)
  data.frame(x, q25 = q[1], q75 = q[2], row.names = NULL)
}
</code>```

I apply the function to each variable for each date, then rbind the results into a single data frame.

# The horror...
d2 <- do.call(rbind, lapply(levels(d$date),
                            function(x) data.frame(date = x, lapply(d[d$date == x, names(d) != "date"], foo))))
```

<p>This gives the following.</p>

<pre class="lang-r prettyprint-override"><code># print results
d2
#>         date var1.x var1.q25 var1.q75 var2.x var2.q25 var2.q75
#> 1 2017-02-22      3     3.00     3.00      3        3      3.0
#> 2 2017-02-23      1     3.50     6.50      1        8     16.5
#> 3 2017-02-23      6     3.50     6.50     18        8     16.5
#> 4 2017-02-23      7     3.50     6.50     15        8     16.5
#> 5 2018-02-22      8     5.75     7.25     25       10     20.0
#> 6 2018-02-22      5     5.75     7.25      5       10     20.0
</code>```

Created on 2019-05-29 by the reprex package (v0.3.0)

An issue with this approach, unlike @akrun's (better) solutions, is that it reorders your data frame.

Body:
I want to include new columns with quantile 1 y 3 by group

I have this dataframe:

d <- data.frame(date = c("2017-02-23", "2017-02-22", "2017-02-23", "2017-02-23","2018-02-22", "2018-02-22"),
var1 = c(1,3,6,7,8,5),
var2 = c(1,3,18,15,25,5))

and I would like to have two new columns Q1var1, Q1var2, Q1var1 and Q1var2 like:

d = d %>% group_by(date) %>% mutate(Q1var1 = quantile(var1,prob = 0.25,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q1var2 = quantile(var1,prob = 0.25,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q3var1 = quantile(var1,prob = 0.75,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q3var2 = quantile(var1,prob = 0.75,na.rm = TRUE))

but in a faster way

Body:
Here's a base solution in case that's your jam. First, I define the data frame.

# Original data frame
d <- data.frame(date = c("2017-02-23", "2017-02-22", "2017-02-23", "2017-02-23","2018-02-22", "2018-02-22"),
                var1 = c(1,3,6,7,8,5),
                var2 = c(1,3,18,15,25,5))

Next, I define a function that calculates the quantiles and binds them to the original data.

# Function to calculate quantiles
foo <- function(x){
  q <- quantile(x, prob = c(0.25, 0.75), na.rm = TRUE)
  data.frame(x, q25 = q[1], q75 = q[2], row.names = NULL)
}

I apply the function to each variable for each date, then rbind the results into a single data frame.

# The horror...
d2 <- do.call(rbind, lapply(levels(d$date),
                            function(x) data.frame(date = x, lapply(d[d$date == x, names(d) != "date"], foo))))

This gives the following.

# print results
d2
#>         date var1.x var1.q25 var1.q75 var2.x var2.q25 var2.q75
#> 1 2017-02-22      3     3.00     3.00      3        3      3.0
#> 2 2017-02-23      1     3.50     6.50      1        8     16.5
#> 3 2017-02-23      6     3.50     6.50     18        8     16.5
#> 4 2017-02-23      7     3.50     6.50     15        8     16.5
#> 5 2018-02-22      8     5.75     7.25     25       10     20.0
#> 6 2018-02-22      5     5.75     7.25      5       10     20.0

Created on 2019-05-29 by the reprex package (v0.3.0)

An issue with this approach, unlike @akrun's (better) solutions, is that it reorders your data frame.


问:
Font is not available to the JVM with Jasper Reports
I'm trying to generate report with DynamicJasper, but I'm getting the following error:

```<code>net.sf.jasperreports.engine.util.JRFontNotFoundException:
                                 Font 'Arial' is not available to the JVM.
</code>```

msttcorefonts is installed, but I guess the JVM is not using any fonts from it.

I'm using Ubuntu 10.04.

How can I fix this?

答:
If you are using maven in your project, you can just add the jasper-fonts dependency to pom.xml:

```<code><dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports-fonts</artifactId>
    <version>6.8.1</version>
</dependency>
</code>```

Installing the missing font on the system may be a working solution but not for me, I didn't want to have to install the missing fonts after each deployment in a new server, instead I opted for embedding the font with the application.

Regards.

Body:
I'm trying to generate report with DynamicJasper, but I'm getting the following error:

net.sf.jasperreports.engine.util.JRFontNotFoundException:
                                 Font 'Arial' is not available to the JVM.

msttcorefonts is installed, but I guess the JVM is not using any fonts from it.

I'm using Ubuntu 10.04.

How can I fix this?

Body:
If you are using maven in your project, you can just add the jasper-fonts dependency to pom.xml:

<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports-fonts</artifactId>
    <version>6.8.1</version>
</dependency>

Installing the missing font on the system may be a working solution but not for me, I didn't want to have to install the missing fonts after each deployment in a new server, instead I opted for embedding the font with the application.

Regards.


问:
Is there a way to skip error "filename is not found" and move to the next file
Is there a way to skip error "filename is not found" and move to the next file?

```<code>Sub CopyDataAndMoveDown()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        Call MoveBelow
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(4, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

Sub MoveBelow ()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        ' At this point when the macro meet again a empty cell
        ' it should keep moving from the same counted X
        ' but start the paste operation from 24 rows below.
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(28, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub
</code>```

So when the macro is copying / pasting data from Sheet 1 to Sheet 2 and meets an empty cell it should keep going, copying next available data, but paste it 24 rows below.

--------Below the old question.

I have a VBA which is opening and closing file for that INDEX function get data. My problem is that. VBA is getting the filename from reference cell which contain the full path. But some of the reference cells are blanks/zeros and then the running VBA stops and give me error "filename is not found". Is there a way to skip that and move to next step?

```<code>Sub HaeReseptiTiedot()

Dim myfile As String
Dim myfile1 As String
Dim myfile2 As String
Dim myfile3 As String
Dim myfile4 As String
Dim myfile5 As String
Dim myfile6 As String
Dim myfile7 As String
Dim myfile8 As String
Dim myfile9 As String

myfile = Cells(19, 4).Value
myfile1 = Cells(19, 9).Value
myfile2 = Cells(19, 14).Value
myfile3 = Cells(19, 19).Value
myfile4 = Cells(19, 24).Value
myfile5 = Cells(19, 29).Value
myfile6 = Cells(19, 34).Value
myfile7 = Cells(19, 39).Value
myfile8 = Cells(19, 44).Value
myfile9 = Cells(19, 49).Value

Application.ScreenUpdating = False

Workbooks.Open Filename:=myfile, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("D16:G30").Select
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Workbooks.Open Filename:=myfile1, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("I16:L30").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("G4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
</code>```

答:
Here is a function that can check if a file exists:</p>

```<code>'********************************************************************************************************************************
' To check if a particular file exists
' Set excelFile = False, if it is not an Excel file that is being checked
'********************************************************************************************************************************
Public Function isAnExistingFile(ByVal fileNameStr As Variant, Optional ByVal excelFile As Boolean = True) As Boolean
Dim wb As Workbook

isAnExistingFile = True
Err.Clear
On Error GoTo errHandler
If Not VarType(fileNameStr) = vbString Then
    isAnExistingFile = False
ElseIf Len(fileNameStr) = 0 Then
    isAnExistingFile = False
ElseIf Len(Dir(fileNameStr)) = 0 Then
    isAnExistingFile = False
ElseIf ((GetAttr(fileNameStr) And vbDirectory) <> vbDirectory) = False Then
    isAnExistingFile = False
Else
    If excelFile Then
        On Error Resume Next
        Set wb = Application.Workbooks.Open(Filename:=fileNameStr, UpdateLinks:=0, ReadOnly:=True)
        If wb Is Nothing Then isAnExistingFile = False
        If Not wb Is Nothing Then
            wb.Close False
            Set wb = Nothing
        End If
        GoTo Out
    End If
End If

errHandler:
If Not Err.Number = 0 Then isAnExistingFile = False

Out:
Err.Clear: On Error GoTo 0

End Function
</code>```

Body:
Is there a way to skip error "filename is not found" and move to the next file?

Sub CopyDataAndMoveDown()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        Call MoveBelow
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(4, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

Sub MoveBelow ()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        ' At this point when the macro meet again a empty cell
        ' it should keep moving from the same counted X
        ' but start the paste operation from 24 rows below.
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(28, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

So when the macro is copying / pasting data from Sheet 1 to Sheet 2 and meets an empty cell it should keep going, copying next available data, but paste it 24 rows below.

--------Below the old question.

I have a VBA which is opening and closing file for that INDEX function get data. My problem is that. VBA is getting the filename from reference cell which contain the full path. But some of the reference cells are blanks/zeros and then the running VBA stops and give me error "filename is not found". Is there a way to skip that and move to next step?

Sub HaeReseptiTiedot()

Dim myfile As String
Dim myfile1 As String
Dim myfile2 As String
Dim myfile3 As String
Dim myfile4 As String
Dim myfile5 As String
Dim myfile6 As String
Dim myfile7 As String
Dim myfile8 As String
Dim myfile9 As String

myfile = Cells(19, 4).Value
myfile1 = Cells(19, 9).Value
myfile2 = Cells(19, 14).Value
myfile3 = Cells(19, 19).Value
myfile4 = Cells(19, 24).Value
myfile5 = Cells(19, 29).Value
myfile6 = Cells(19, 34).Value
myfile7 = Cells(19, 39).Value
myfile8 = Cells(19, 44).Value
myfile9 = Cells(19, 49).Value

Application.ScreenUpdating = False

Workbooks.Open Filename:=myfile, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("D16:G30").Select
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Workbooks.Open Filename:=myfile1, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("I16:L30").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("G4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Body:
Here is a function that can check if a file exists:

'********************************************************************************************************************************
' To check if a particular file exists
' Set excelFile = False, if it is not an Excel file that is being checked
'********************************************************************************************************************************
Public Function isAnExistingFile(ByVal fileNameStr As Variant, Optional ByVal excelFile As Boolean = True) As Boolean
Dim wb As Workbook

isAnExistingFile = True
Err.Clear
On Error GoTo errHandler
If Not VarType(fileNameStr) = vbString Then
    isAnExistingFile = False
ElseIf Len(fileNameStr) = 0 Then
    isAnExistingFile = False
ElseIf Len(Dir(fileNameStr)) = 0 Then
    isAnExistingFile = False
ElseIf ((GetAttr(fileNameStr) And vbDirectory) <> vbDirectory) = False Then
    isAnExistingFile = False
Else
    If excelFile Then
        On Error Resume Next
        Set wb = Application.Workbooks.Open(Filename:=fileNameStr, UpdateLinks:=0, ReadOnly:=True)
        If wb Is Nothing Then isAnExistingFile = False
        If Not wb Is Nothing Then
            wb.Close False
            Set wb = Nothing
        End If
        GoTo Out
    End If
End If

errHandler:
If Not Err.Number = 0 Then isAnExistingFile = False

Out:
Err.Clear: On Error GoTo 0

End Function


问:
Returning an output value via C# WCF service
I'm looking to return a string value to the client via my HTTP post service on WCF.

I can return a status code okay via the following:

WebOperationContext.Current.OutgoingResponse.StatusCode
  = HttpStatusCode.OK;

... however I'm not entirely sure how to return a string value to the client.

Any pointers would be much appreciated.

Thanks

Nick

```<code>namespace TextWCF
{
[ServiceContract]
public interface IShortMessageService
{
    [WebInvoke(UriTemplate = "invoke", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    [OperationContract]
    void PostSMS(Stream input);

}
}

[OperationBehavior]
    public void PostSMS(Stream input)
    {

        StreamReader sr = new StreamReader(input);
        string s = sr.ReadToEnd();
        sr.Dispose();
        NameValueCollection qs = HttpUtility.ParseQueryString(s);

        string user = Convert.ToString(qs["user"]);
        string password = qs["password"];
        string api_id = qs["api_id"];
        string to = qs["to"];
        string text = qs["text"];
        string from = qs["from"];

        WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
        WebOperationContext.Current.OutgoingResponse. = HttpStatusCode.OK;
    }
</code>```

答:
You need to have your method actually return something as Neil pointed out.

So just change your method signature to look like

```<code>namespace TextWCF
{
[ServiceContract]
public interface IShortMessageService
{
    [WebInvoke(UriTemplate = "invoke", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    [OperationContract]
    string PostSMS(Stream input);

}
}

[OperationBehavior]
    public string PostSMS(Stream input)
    {

        StreamReader sr = new StreamReader(input);
        string s = sr.ReadToEnd();
        sr.Dispose();
        NameValueCollection qs = HttpUtility.ParseQueryString(s);

        string user = Convert.ToString(qs["user"]);
        string password = qs["password"];
        string api_id = qs["api_id"];
        string to = qs["to"];
        string text = qs["text"];
        string from = qs["from"];

        WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
        WebOperationContext.Current.OutgoingResponse. = HttpStatusCode.OK;

        return "Some String";
    }
</code>```

Body:
I'm looking to return a string value to the client via my HTTP post service on WCF.

I can return a status code okay via the following:

WebOperationContext.Current.OutgoingResponse.StatusCode
  = HttpStatusCode.OK;

... however I'm not entirely sure how to return a string value to the client.

Any pointers would be much appreciated.

Thanks

Nick

namespace TextWCF
{
[ServiceContract]
public interface IShortMessageService
{
    [WebInvoke(UriTemplate = "invoke", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    [OperationContract]
    void PostSMS(Stream input);

}
}

[OperationBehavior]
    public void PostSMS(Stream input)
    {

        StreamReader sr = new StreamReader(input);
        string s = sr.ReadToEnd();
        sr.Dispose();
        NameValueCollection qs = HttpUtility.ParseQueryString(s);

        string user = Convert.ToString(qs["user"]);
        string password = qs["password"];
        string api_id = qs["api_id"];
        string to = qs["to"];
        string text = qs["text"];
        string from = qs["from"];

        WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
        WebOperationContext.Current.OutgoingResponse. = HttpStatusCode.OK;
    }

Body:
You need to have your method actually return something as Neil pointed out.

So just change your method signature to look like

namespace TextWCF
{
[ServiceContract]
public interface IShortMessageService
{
    [WebInvoke(UriTemplate = "invoke", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    [OperationContract]
    string PostSMS(Stream input);

}
}

[OperationBehavior]
    public string PostSMS(Stream input)
    {

        StreamReader sr = new StreamReader(input);
        string s = sr.ReadToEnd();
        sr.Dispose();
        NameValueCollection qs = HttpUtility.ParseQueryString(s);

        string user = Convert.ToString(qs["user"]);
        string password = qs["password"];
        string api_id = qs["api_id"];
        string to = qs["to"];
        string text = qs["text"];
        string from = qs["from"];

        WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
        WebOperationContext.Current.OutgoingResponse. = HttpStatusCode.OK;

        return "Some String";
    }


问:
React jest how to test Redirect based on localStorage item
I have a component which checks for a local-storage key and based on that it decides whether to render component or redirect to login screen.

I want to test this case using jest and enzyme but i am not able to force code to use mock localstorage and not actual browser locastorage.

Right now code it trying to read localstorage and it always gets null value.

I have already spent 2-3 hours and followed many stackobverflow question but most of them are trying to mock localstorage and checking if it sets and reads values from fake localstorage.

I think my case is different because i want to fake localstorage but that output should affect component decision.

Below is my component code

```<code>        // Below console.log prints null when i run test, which i think should print { "googleId" : null} , isnt it ?
        console.log(localStorage.getItem("auth"));
        let storageUser = JSON.parse(localStorage.getItem("auth"));
        if (!storageUser || !storageUser.googleId){
            return <Redirect to="/login" />
        }

        return (
            <Home user  = {user} />
        )
    }
</code>```

and my test code

```<code>it("Renders Home page if googleId is set in localStorage", () => {
    const localStorage = jest.fn();
    global.localStorage.getItem = key => '{ "googleId" : null}';

    // Below code prints { "googleId" : null}
    console.log(localStorage.getItem("auth"));

    expect(wrapper.find(Home).length).toEqual(1);
});
</code>```

答:
I'd recommend using jest-localstorage-mock - the setup process shouldn't be tough.

By including the package in your tests, you have access to a mocked LS that can be manipulated with ease, for instance:

```<code>localStorage.__STORE__["auth"] = your_desired_object;
</code>```

Here is a brief example that might fit your issue - and also it's a demonstration of testing the different conditionals in cases like this:

beforeEach(() => {
   // According to the documentation: "values stored in tests will also be available in other tests unless you run"
   localStorage.clear();
});

describe("when `auth` does not exist in the localStorage", () => {
   it("redirects the user to the `login` page", () => {
      // ...
   });
});

describe("when `auth` exists in the localStorage", () => {
   describe("when `googleId` is not defined", () => {
      it("redirects the user to the `login` page", () => {
         // ...
      });
   });

   describe("when `googleId` is defined", () => {
      it("renders `Home`", () => {
        // Ensures if the `Home` page is rendered if the last circumstance occurs.
      });
   });
});
```

Body:
I have a component which checks for a local-storage key and based on that it decides whether to render component or redirect to login screen.

I want to test this case using jest and enzyme but i am not able to force code to use mock localstorage and not actual browser locastorage.

Right now code it trying to read localstorage and it always gets null value.

I have already spent 2-3 hours and followed many stackobverflow question but most of them are trying to mock localstorage and checking if it sets and reads values from fake localstorage.

I think my case is different because i want to fake localstorage but that output should affect component decision.

Below is my component code

        // Below console.log prints null when i run test, which i think should print { "googleId" : null} , isnt it ?
        console.log(localStorage.getItem("auth"));
        let storageUser = JSON.parse(localStorage.getItem("auth"));
        if (!storageUser || !storageUser.googleId){
            return <Redirect to="/login" />
        }

        return (
            <Home user  = {user} />
        )
    }

and my test code

it("Renders Home page if googleId is set in localStorage", () => {
    const localStorage = jest.fn();
    global.localStorage.getItem = key => '{ "googleId" : null}';

    // Below code prints { "googleId" : null}
    console.log(localStorage.getItem("auth"));

    expect(wrapper.find(Home).length).toEqual(1);
});

Body:
I'd recommend using jest-localstorage-mock - the setup process shouldn't be tough.

By including the package in your tests, you have access to a mocked LS that can be manipulated with ease, for instance:

localStorage.__STORE__["auth"] = your_desired_object;

Here is a brief example that might fit your issue - and also it's a demonstration of testing the different conditionals in cases like this:

beforeEach(() => {
   // According to the documentation: "values stored in tests will also be available in other tests unless you run"
   localStorage.clear();
});

describe("when `auth` does not exist in the localStorage", () => {
   it("redirects the user to the `login` page", () => {
      // ...
   });
});

describe("when `auth` exists in the localStorage", () => {
   describe("when `googleId` is not defined", () => {
      it("redirects the user to the `login` page", () => {
         // ...
      });
   });

   describe("when `googleId` is defined", () => {
      it("renders `Home`", () => {
        // Ensures if the `Home` page is rendered if the last circumstance occurs.
      });
   });
});


问:
PUT, DELETE, methods not working, showing error "Http failure during parsing for "
I have published angular 7 with entity framework core application on server but only http POST method is working other http methods like DELETE and PUTthrow below error:

Http failure during parsing for " and "Unexpected token < in JSON at position 0

Previously it was working on another server where i published but when I published same application to new server then DELETE and PUT methods throw error.

1) I tried given possible solutions like putting "responseType": 'text' in header

2) Putting "Access-Control-Allow-Methods": "GET, PUT, POST, DELETE, OPTIONS" in header but nothing has solved the problem

答: Check your Allowed Verbs on your server. Typically only GET and POST are allowed by default. Especially with IIS, DELETE and PUT are not enabled.</p>


问:
Array of greater elements
I'd like to create a method that recieves an array and a value to compare. It should return the numbers which are greater than the value compared in the form of an array.

For instance, greaterThan([3, 4, 5, 6], 4]) should return [5, 6] and greaterThan([3, 4, 5, 6], 5]) should return [6].

Since the length of the result array is dynamic, I've incremented the size each time it finds a larger element.

```<code>static String greaterThan(int[] vectorCompare, int valueCompare)
{
    Arrays.sort(vectorCompare);         // make it faster

    int size = 0;

    int[] result = new int[size];

    for (int value : vectorCompare)
    {
        if (valueCompare < value)
        {
            size++;
        }
    }

    int[] resultCopy = Arrays.copyOf(result, size);

    // what to do next?

    return Arrays.toString(resultCopy);

}
</code>```

Any tips for me? I thought of using ArrayList but I'm kinda stuck.

答:
This is about as simple as it can get. This works with arrays.

   public static int[] greaterThan(int[] numbs, int max) {
      return Arrays.stream(numbs).parallel().filter(a -> a > max).toArray();
   }
```

<p>You can also do the same for a List.</p>

<pre class="lang-java prettyprint-override"><code>   public static List<Integer> greaterThan(List<Integer> numbs, int max) {
      return numbs.parallelstream().filter(a -> a > max).collect(Collectors.toList());
   }
</code>```

In both cases, the List or array is turned into parallel streams of values. Those are filtered to allow only those that are greater than max thru the pipeline.  Then they are collected into a List or an array and returned.  This particular task is suited to parallel operations in multiple threads and will speed up execution, especially if your PC has multiple cores.

Even if you're new at Java, lambdas and streams are important features of the language and should be learned.

Title: Array of greater elements

Body:
I'd like to create a method that recieves an array and a value to compare. It should return the numbers which are greater than the value compared in the form of an array.

For instance, greaterThan([3, 4, 5, 6], 4]) should return [5, 6] and greaterThan([3, 4, 5, 6], 5]) should return [6].

Since the length of the result array is dynamic, I've incremented the size each time it finds a larger element.

static String greaterThan(int[] vectorCompare, int valueCompare)
{
    Arrays.sort(vectorCompare);         // make it faster

    int size = 0;

    int[] result = new int[size];

    for (int value : vectorCompare)
    {
        if (valueCompare < value)
        {
            size++;
        }
    }

    int[] resultCopy = Arrays.copyOf(result, size);

    // what to do next?

    return Arrays.toString(resultCopy);

}

Any tips for me? I thought of using ArrayList but I'm kinda stuck.

Body:
This is about as simple as it can get. This works with arrays.

   public static int[] greaterThan(int[] numbs, int max) {
      return Arrays.stream(numbs).parallel().filter(a -> a > max).toArray();
   }

You can also do the same for a List.

   public static List<Integer> greaterThan(List<Integer> numbs, int max) {
      return numbs.parallelstream().filter(a -> a > max).collect(Collectors.toList());
   }

In both cases, the List or array is turned into parallel streams of values. Those are filtered to allow only those that are greater than max thru the pipeline.  Then they are collected into a List or an array and returned.  This particular task is suited to parallel operations in multiple threads and will speed up execution, especially if your PC has multiple cores.

Even if you're new at Java, lambdas and streams are important features of the language and should be learned.


问:
Pick email address from .To
My code will take the email address from the .To property, and send another email.

When the address is autocompleted, it has John Smith instead of john.smith@email.dot. The .To is empty for VBA code.

Is it possible to bypass it?

```<code>Dim objMail As Outlook.MailItem
Dim objNewMail1 As Outlook.MailItem
Dim strTo As String

strTo = objMail.To

Set objNewMail1 = Application.CreateItem(olMailItem)

With objNewMail1
    .To = strTo
    .Send
End With
</code>```

答:
Do not use the To / CC / BCC properties - they, generally, include only the display names, not email addresses.

Loop through all recipients in the MailItem.Recipients collection and use the Recipient.Address property - keep in mind you might have an EX type address, nit SMTP in case of Exchange, you might have to use Recipient.AddressEntry.GetExchangeUser().PrimarySmtpAddress (GetExchangeUser will return null for the non-Exchange address entries).

The recipient kind (olTo / olCC / olBCC) is stored in the Recipient.Type property.

```<code>   dim recip, newRecip
   ...
   With objNewMail1
        for each recip in objMail.Recipients
          set newRecip = .Recipients.Add(recip.Address)
          newRecip.Type = recip.Type
        next
        .Send
    End With
</code>```

Title: Pick email address from .To

Body:
My code will take the email address from the .To property, and send another email.

When the address is autocompleted, it has John Smith instead of john.smith@email.dot. The .To is empty for VBA code.

Is it possible to bypass it?

Dim objMail As Outlook.MailItem
Dim objNewMail1 As Outlook.MailItem
Dim strTo As String

strTo = objMail.To

Set objNewMail1 = Application.CreateItem(olMailItem)

With objNewMail1
    .To = strTo
    .Send
End With

Body:
Do not use the To / CC / BCC properties - they, generally, include only the display names, not email addresses.

Loop through all recipients in the MailItem.Recipients collection and use the Recipient.Address property - keep in mind you might have an EX type address, nit SMTP in case of Exchange, you might have to use Recipient.AddressEntry.GetExchangeUser().PrimarySmtpAddress (GetExchangeUser will return null for the non-Exchange address entries).

The recipient kind (olTo / olCC / olBCC) is stored in the Recipient.Type property.

   dim recip, newRecip
   ...
   With objNewMail1
        for each recip in objMail.Recipients
          set newRecip = .Recipients.Add(recip.Address)
          newRecip.Type = recip.Type
        next
        .Send
    End With


问:
Numpy: division by zero error, but mathematically function is apparently defined
I'm testing out some functions to fit with data, and one of them (in 2-D) is

```<code>f(x) = (1/(1-x)) / (1 + 1/(1-x))
</code>```

Which, according to Wolfram and the Google plotters, gives you the result

```<code>f(1) = 1
</code>```

I've tried to get this to work without hard coding the case

```<code>if x == 1:
    return 1
</code>```

but I end up with a nan and a RunTimeWarning informing me that I have indeed divided by zero.

import numpy as np

def f(x):
    return 1/(1-x) / (1 + 1/(1-x))

x_range = np.linspace(0, 1, 50)
y = f(x_range)
print(y)
```

Is there a more elegant solution than to simply introduce a hard-coded if?

答:
Is there a reason to keep it in this form, you can simplify it to:

```<code>def f(x):
    return 1/(2-x)
</code>```

Wolfram and Google probably to some sort of algebraic simplification too.

Body:
I'm testing out some functions to fit with data, and one of them (in 2-D) is

f(x) = (1/(1-x)) / (1 + 1/(1-x))

Which, according to Wolfram and the Google plotters, gives you the result

f(1) = 1

I've tried to get this to work without hard coding the case

if x == 1:
    return 1

but I end up with a nan and a RunTimeWarning informing me that I have indeed divided by zero.

import numpy as np

def f(x):
    return 1/(1-x) / (1 + 1/(1-x))

x_range = np.linspace(0, 1, 50)
y = f(x_range)
print(y)

Is there a more elegant solution than to simply introduce a hard-coded if?

Body:
Is there a reason to keep it in this form, you can simplify it to:

def f(x):
    return 1/(2-x)

Wolfram and Google probably to some sort of algebraic simplification too.


问:
DispatchQueue and [weak self] workItems. Is [weak self] necessary?
I've got a custom class that uses a DispatchQueue.

```<code>class MyCustomClass {

    func fetch(fromURL url: URL) {
        DispatchQueue.global().async { [weak self] in
            // workItem stuff where self? is called
        }
    }

}
</code>```

Is the [weak self] necessary? The workItem closure references the instance of MyCustomClass, so I see that strong reference, but does the instance of MyCustomClass keep a reference to the enclosed workItem block that's passed to async()? It seems like it doesn't, so is [weak self] unnecessary in this case?

答:
but does the instance of MyCustomClass keep a reference to the enclosed workItem block that's passed to async()?

Not from this  example, no.

However, if the instance of MyCustomClass has a DispatchQueue that was used instead of the global queue, then that would strongly reference the work time until it's completed.

Body:
I've got a custom class that uses a DispatchQueue.

class MyCustomClass {

    func fetch(fromURL url: URL) {
        DispatchQueue.global().async { [weak self] in
            // workItem stuff where self? is called
        }
    }

}

Is the [weak self] necessary? The workItem closure references the instance of MyCustomClass, so I see that strong reference, but does the instance of MyCustomClass keep a reference to the enclosed workItem block that's passed to async()? It seems like it doesn't, so is [weak self] unnecessary in this case?


问:
Logging all HTTP requests using .htaccess and PHP
I need to put an php script on my website to log all HTTP requests. The access.log doesn't have enough info for my proposes.

My idea was to use an .htaccess on /www/ with a rewrite rule to every request pass trough a php script that would save in one log. (something like a print_r($_GLOBALS))

Do any of you guys know the better way of doing this?

答:
I know this is an old question. If you're on shared hosting, as you're suggesting, you may be limited to having to redirect all traffic through a script.

I had to do this once. For a WordPress site that was getting hacked, I needed to determine how it was being attacked. Like you said, I redirected all requests with an .htaccess file to a single PHP script that would render a simple "Site is under Maintenance" page, but that also would record that request – the post data, cookies, upload filenames – pretty much anything I wanted to observe.

Conveniently, though, the site was also under Cloudflare protection; thus by doing so, Cloudflare ended up seeing the 503 Unavailable on the maintenance page, and served cache instead, thus keeping the site up almost completely. Better, the maintenance page was still able to record requests.

My .htaccess file appeared something like the following:

```
RewriteEngine On
RewriteRule ^index-maintenance\.php$ - [L]
RewriteRule .* /index-maintenance.php [L]
```

Then, the index-maintenance.php file looked something like:

```
<?php
    $record = TRUE; // whether or not to record requests

    header('HTTP/1.1 503 Service Unavailable', TRUE, 503);
    header('Retry-After: 18000');

    if($record) {
        // Get remote IP
        // If the site uses cloudflare, the true remote IP is served
        // in the HTTP_CF_CONNECTING_IP server var:
        $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP'])
            ? $_SERVER['HTTP_CF_CONNECTING_IP']
            : $_SERVER['REMOTE_ADDR'];

        ob_start();

        // Request date / IP / URL
        echo date('Y-m-d H:i:s: ')
            . 'Remote IP: ' . $ip
            . ' - ' . $_SERVER['REQUEST_METHOD']
            . ' ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
            . "\r\n";

        // User agent
        echo $_SERVER['HTTP_USER_AGENT'] . "\r\n";

        // If you needed all headers:
        # foreach(getallheaders() as $header => $value)
        #   echo "$header: $value\r\n";

        // If you wanted raw request data vs. parsed POST data:
        # $postdata = file_get_contents('php://input');
        # if(strlen($postdata)) echo $postdata."\r\n";

        // Post data / Cookies / Files
        if(count($_POST) || count($_COOKIE)) {
            ob_start();

            echo "POST\n";
            var_dump($_POST);

            echo "COOKIES\n";
            var_dump($_COOKIE);

            echo "FILES\n";
            var_dump($_FILES);

            $postdata = ob_get_clean();
            echo str_replace("\n","\r\n",$postdata);
        }
        echo "\r\n";

        // usage of random character string discourages guessing
        // the url if the directory is web-accessible; but, if at
        // all possible, make it inaccessible:
        file_put_contents('../requests_n5io09d21mkp.log',ob_get_clean(),FILE_APPEND);
    }

    // then, a simple maintenance page:
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Site Under Maintenance</title>
    </head>
    <style type="text/css">
        body {
            margin: 0;
            width: 100vw;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .notice {
            color: #808080;
            font: bold 20px/1.6em sans-serif;
            text-align: center;
        }
    </style>
    <body>
        <p class="notice">
            We're sorry. The site is under maintenance.<br/>Please check back later.
        </p>
    </body>
</html>
```

Body:
I know this is an old question. If you're on shared hosting, as you're suggesting, you may be limited to having to redirect all traffic through a script.

I had to do this once. For a WordPress site that was getting hacked, I needed to determine how it was being attacked. Like you said, I redirected all requests with an .htaccess file to a single PHP script that would render a simple "Site is under Maintenance" page, but that also would record that request – the post data, cookies, upload filenames – pretty much anything I wanted to observe.

Conveniently, though, the site was also under Cloudflare protection; thus by doing so, Cloudflare ended up seeing the 503 Unavailable on the maintenance page, and served cache instead, thus keeping the site up almost completely. Better, the maintenance page was still able to record requests.

My .htaccess file appeared something like the following:

RewriteEngine On
RewriteRule ^index-maintenance\.php$ - [L]
RewriteRule .* /index-maintenance.php [L]

Then, the index-maintenance.php file looked something like:

<?php
    $record = TRUE; // whether or not to record requests

    header('HTTP/1.1 503 Service Unavailable', TRUE, 503);
    header('Retry-After: 18000');

    if($record) {
        // Get remote IP
        // If the site uses cloudflare, the true remote IP is served
        // in the HTTP_CF_CONNECTING_IP server var:
        $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP'])
            ? $_SERVER['HTTP_CF_CONNECTING_IP']
            : $_SERVER['REMOTE_ADDR'];

        ob_start();

        // Request date / IP / URL
        echo date('Y-m-d H:i:s: ')
            . 'Remote IP: ' . $ip
            . ' - ' . $_SERVER['REQUEST_METHOD']
            . ' ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
            . "\r\n";

        // User agent
        echo $_SERVER['HTTP_USER_AGENT'] . "\r\n";

        // If you needed all headers:
        # foreach(getallheaders() as $header => $value)
        #   echo "$header: $value\r\n";

        // If you wanted raw request data vs. parsed POST data:
        # $postdata = file_get_contents('php://input');
        # if(strlen($postdata)) echo $postdata."\r\n";

        // Post data / Cookies / Files
        if(count($_POST) || count($_COOKIE)) {
            ob_start();

            echo "POST\n";
            var_dump($_POST);

            echo "COOKIES\n";
            var_dump($_COOKIE);

            echo "FILES\n";
            var_dump($_FILES);

            $postdata = ob_get_clean();
            echo str_replace("\n","\r\n",$postdata);
        }
        echo "\r\n";

        // usage of random character string discourages guessing
        // the url if the directory is web-accessible; but, if at
        // all possible, make it inaccessible:
        file_put_contents('../requests_n5io09d21mkp.log',ob_get_clean(),FILE_APPEND);
    }

    // then, a simple maintenance page:
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Site Under Maintenance</title>
    </head>
    <style type="text/css">
        body {
            margin: 0;
            width: 100vw;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .notice {
            color: #808080;
            font: bold 20px/1.6em sans-serif;
            text-align: center;
        }
    </style>
    <body>
        <p class="notice">
            We're sorry. The site is under maintenance.<br/>Please check back later.
        </p>
    </body>
</html>


问:
Nested UITableViews: a way to scroll both the outer vertical UITableView and a child horizontal UITableView at the same time?
When you're working with an atypical nested UITableViews setup - where you have an outer vertical UITableView that hosts 90° rotated UITableViews (see: Looking for a UI library to present Data horizontaly in iOS ):
is there a way to make iOS process vertical and horizontal touches at the same time?

I found that iOS is very clever in processing touches:
horizontal touches make the relevant horizontal UITableView scroll, while a vertical swipe makes the outer UITableView scroll. Perfect.

Only, I'd love to be able to move my finger diagonally and see the outer UITableView and the inner UITableView scroll at the same time.

I tried a few approaches (playing with canCancelContentTouches, delaysContentTouches, and touch messages) but I haven't found a way to make this happen.

EDIT:
Here's a XCode4 project that shows this behavior: http://marcanton.io/other/stackoverflow/nestedtableviews.zip

EDIT:
I submitted this issue to Apple Developer Technical Support, here's their reply:

Thank you for writing to Apple
  Worldwide Developer Technical Support.
  I am responding to your inquiry
  concerning touch events in embedded
  UITableViews.

Typically this is an approach that is
  not recommended. The issue is that
  UITableView inherits from UIScrollView
  and as stated in the documentation for
  UIScrollView:

"Important: You should not embed
  UIWebView or UITableView objects in
  UIScrollView objects. If you do so,
  unexpected behavior can result because
  touch events for the two objects can
  be mixed up and wrongly handled."

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIScrollView_Class/Reference/UIScrollView.html%23//apple_ref/occ/cl/UIScrollView

So that this time, there is not a
  workaround for getting both to scroll
  at the same time.

I recommend that you file an
  enhancement request at
  http://developer.apple.com/bugreporter/
  detailing what you would like to see
  us add in a future release.

Still, I think that there has to be a way to enable this functionality, although I understand that this is not recommended. In fact, Apple does not even recommend hosting UITableViews inside another UITableView, but with the exception made above, it works quite beautifully.
I'll keep this question updated with our collective findings.

EDIT: There actually is a way, detailed here: http://marcanton.io/blog/nested-orthogonal-tableviews/

答: Interesting, I haven't played around with this kind of setup yet, but I would try to intercept touch events on the nested UITableViews and delegate any vertical movement to the outer UITableView - and vice-versa. </p>


问:
Parse query retreiving with certain conditions
I am making a query in a class my problem is that I have some license plates, here in Colombia licenses plates are as it follows ABC 123. I need my query to only return to me, in this case, the ones that end with 2

This is what i did following the documentation...

```<code>private void queryForPlaca(String terminaEn){

    ParseQuery<ParseObject> query = ParseQuery.getQuery("TestDrive");
    query.whereFullText("Placa", terminaEn);
    query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> objects, ParseException e) {
            for (ParseObject obj:objects
                 ) {
                listaDeVehiculos.add(obj);
            }
            ListaVehiculosPicoYPlacaAdapter adapter= new ListaVehiculosPicoYPlacaAdapter(getActivity(),listaDeVehiculos);
            listadoTestDrive.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    });
}
</code>```

terminaEn variable querys for the licenses places plates depending on the day selected in a calendar (in this case 2).
My problem is that not only my listaDeVehiculos is not returning any values and the other problem that I see is that it also returns values I don't need for example ABS 124, AXX 524, AEE 234 etc. How should i modify my query?.

答:
You won't be able to do that using text search, since MongoDB text search feature only matches complete terms. You will have to do that using regular expressions. Try the following:

```<code>private void queryForPlaca(String terminaEn){

    ParseQuery<ParseObject> query = ParseQuery.getQuery("TestDrive");
    query.whereMatches("Placa", terminaEn + "$");
    query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> objects, ParseException e) {
            for (ParseObject obj:objects) {
                listaDeVehiculos.add(obj);
            }
            ListaVehiculosPicoYPlacaAdapter adapter= new ListaVehiculosPicoYPlacaAdapter(getActivity(),listaDeVehiculos);
            listadoTestDrive.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    });
}
</code>```

Please have in mind that regular expressions are very expensive to the database, so it's important for you to create the appropriate index. A { Placa: 1 } index in the TestDrive collection should help you a lot. For your reference, please take a look here:
https://docs.parseplatform.org/android/guide/#regular-expressions

Body:
I am making a query in a class my problem is that I have some license plates, here in Colombia licenses plates are as it follows ABC 123. I need my query to only return to me, in this case, the ones that end with 2

This is what i did following the documentation...

private void queryForPlaca(String terminaEn){

    ParseQuery<ParseObject> query = ParseQuery.getQuery("TestDrive");
    query.whereFullText("Placa", terminaEn);
    query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> objects, ParseException e) {
            for (ParseObject obj:objects
                 ) {
                listaDeVehiculos.add(obj);
            }
            ListaVehiculosPicoYPlacaAdapter adapter= new ListaVehiculosPicoYPlacaAdapter(getActivity(),listaDeVehiculos);
            listadoTestDrive.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    });
}

terminaEn variable querys for the licenses places plates depending on the day selected in a calendar (in this case 2).
My problem is that not only my listaDeVehiculos is not returning any values and the other problem that I see is that it also returns values I don't need for example ABS 124, AXX 524, AEE 234 etc. How should i modify my query?.

Body:
You won't be able to do that using text search, since MongoDB text search feature only matches complete terms. You will have to do that using regular expressions. Try the following:

private void queryForPlaca(String terminaEn){

    ParseQuery<ParseObject> query = ParseQuery.getQuery("TestDrive");
    query.whereMatches("Placa", terminaEn + "$");
    query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> objects, ParseException e) {
            for (ParseObject obj:objects) {
                listaDeVehiculos.add(obj);
            }
            ListaVehiculosPicoYPlacaAdapter adapter= new ListaVehiculosPicoYPlacaAdapter(getActivity(),listaDeVehiculos);
            listadoTestDrive.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    });
}

Please have in mind that regular expressions are very expensive to the database, so it's important for you to create the appropriate index. A { Placa: 1 } index in the TestDrive collection should help you a lot. For your reference, please take a look here:
https://docs.parseplatform.org/android/guide/#regular-expressions


答:
No it's not needed the singleton DispatchQueue.global()

```<code>DispatchQueue.global().async
</code>```

doesn't hold a strong reference to  self , GCD doesn't cause retain cycles

Title: DispatchQueue and [weak self] workItems. Is [weak self] necessary?

Body:
No it's not needed the singleton DispatchQueue.global()

DispatchQueue.global().async

doesn't hold a strong reference to  self , GCD doesn't cause retain cycles


问:
Why does range(start, end) not include end?
```<code>>>> range(1,11)
</code>```

gives you

```<code>[1,2,3,4,5,6,7,8,9,10]
</code>```

Why not 1-11?

Did they just decide to do it like that at random or does it have some value I am not seeing?

答:
It's just more convenient to reason about in many cases.

Basically, we could think of a range as an interval between start and end. If start <= end, the length of the interval between them  is end - start. If len was actually defined as the length, you'd have:

```<code>len(range(start, end)) == start - end
</code>```

However, we count the integers included in the range instead of measuring the length of the interval. To keep the above property true, we should include one of the endpoints and exclude the other.

Adding the step parameter is like introducing a unit of length. In that case, you'd expect

```<code>len(range(start, end, step)) == (start - end) / step
</code>```

for length. To get the count, you just use integer division.

ContentLicense: CC BY-SA 2.5

Body:
>>> range(1,11)

gives you

[1,2,3,4,5,6,7,8,9,10]

Why not 1-11?

Did they just decide to do it like that at random or does it have some value I am not seeing?

Body:
It's just more convenient to reason about in many cases.

Basically, we could think of a range as an interval between start and end. If start <= end, the length of the interval between them  is end - start. If len was actually defined as the length, you'd have:

len(range(start, end)) == start - end

However, we count the integers included in the range instead of measuring the length of the interval. To keep the above property true, we should include one of the endpoints and exclude the other.

Adding the step parameter is like introducing a unit of length. In that case, you'd expect

len(range(start, end, step)) == (start - end) / step

for length. To get the count, you just use integer division.


问:
Swift package manager unable to compile ncurses installed through Homebrew
I'm trying to use ncurses in a library using Swift Package Manager and I'd like to use a specific version of ncurses, not the one included in OS X.
To do so I installed a more recent version (6.1) using Homebrew.
This is how my Package.swift looks like:

```<code>// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "NcursesExample",
    products: [
        .executable(name: "NcursesExample", targets: ["NcursesExample"]),
    ],
    dependencies: [
    ],
    targets: [
        .systemLibrary(name: "Cncurses"),
        .target(name: "NcursesExample", dependencies: ["Cncurses"]),
    ]
)
</code>```

Under the Sources directory I have a subdirectory for Cncurses containing a module.modulemap and shim.h files:

module.modulemap

```<code>module Cncurses {
  header "shim.h"
  link "ncurses"
  export *
}
</code>```

shim.h

```<code>#include "/usr/local/Cellar/ncurses/6.1/include/ncurses.h"
</code>```

However, when compiling I get several errors complaining about conflicting types, apparently because ncurses is also provided by the macOS SDK:

```<code>shim.h:1:10: note: in file included from shim.h:1:
#include "/usr/local/Cellar/ncurses/6.1/include/ncurses.h"
         ^
/usr/local/Cellar/ncurses/6.1/include/ncurses.h:60:10: error: 'ncursesw/ncurses_dll.h' file not found with <angled> include; use "quotes" instead
#include <ncursesw/ncurses_dll.h>
         ^
<module-includes>:1:9: note: in file included from <module-includes>:1:
#import "shim.h"
        ^
shim.h:1:10: note: in file included from shim.h:1:
#include "/usr/local/Cellar/ncurses/6.1/include/ncurses.h"
         ^
/usr/local/Cellar/ncurses/6.1/include/ncurses.h:674:45: error: conflicting types for 'keyname'
extern NCURSES_EXPORT(NCURSES_CONST char *) keyname (int);              /* implemented */
                                            ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/curses.h:598:45: note: previous declaration is here
extern NCURSES_EXPORT(NCURSES_CONST char *) keyname (int);              /* implemented */

...
</code>```

I'm trying to compile the package using:

swift build -Xcc -I/usr/local/Cellar/ncurses/6.1/include/ -Xlinker -L/usr/local/Cellar/ncurses/6.1/lib

I also went down the route of specifying the pkgConfig on the package definition, with the same result. Can someone help?

FYI It's worth mentioning that upon ncurses installation through Homebrew I get the following warning as ncurses is already provided by OS X:

```<code>ncurses is keg-only, which means it was not symlinked into /usr/local,
because macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have ncurses first in your PATH run:
  echo 'export PATH="/usr/local/opt/ncurses/bin:$PATH"' >> ~/.zshrc

For compilers to find ncurses you may need to set:
  export LDFLAGS="-L/usr/local/opt/ncurses/lib"
  export CPPFLAGS="-I/usr/local/opt/ncurses/include"

For pkg-config to find ncurses you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/ncurses/lib/pkgconfig"
</code>```

Pkgconfig for ncurses looks like this

```<code># pkg-config file generated by gen-pkgconfig
# vile:makemode

prefix=/usr/local/Cellar/ncurses/6.1
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include/ncursesw
abi_version=6
major_version=6
version=6.1.20180127

Name: ncursesw
Description: ncurses 6.1 library
Version: ${version}
URL: https://invisible-island.net/ncurses
Requires.private:
Libs:  -L${libdir} -lncursesw
Libs.private:
Cflags:  -D_DARWIN_C_SOURCE -I/usr/local/Cellar/ncurses/6.1/include -I${includedir}
</code>```

答:
I'm not too well-versed in this subject, but it seems like you may want to look into adding a build script for this to your project. In Xcode, under the selected project, go to Build Phases > New Run Script Phase

In that script add your flags:

```<code>export LDFLAGS="-L/usr/local/opt/ncurses/lib"
export CPPFLAGS="-I/usr/local/opt/ncurses/include"
</code>```

The build script should run on install. I'm not sure if you need the pkg-config flag here. Hope this helps point you somewhere in the right direction.

Body:
I'm trying to use ncurses in a library using Swift Package Manager and I'd like to use a specific version of ncurses, not the one included in OS X.
To do so I installed a more recent version (6.1) using Homebrew.
This is how my Package.swift looks like:

// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "NcursesExample",
    products: [
        .executable(name: "NcursesExample", targets: ["NcursesExample"]),
    ],
    dependencies: [
    ],
    targets: [
        .systemLibrary(name: "Cncurses"),
        .target(name: "NcursesExample", dependencies: ["Cncurses"]),
    ]
)

Under the Sources directory I have a subdirectory for Cncurses containing a module.modulemap and shim.h files:

module.modulemap

module Cncurses {
  header "shim.h"
  link "ncurses"
  export *
}

shim.h

#include "/usr/local/Cellar/ncurses/6.1/include/ncurses.h"

However, when compiling I get several errors complaining about conflicting types, apparently because ncurses is also provided by the macOS SDK:

shim.h:1:10: note: in file included from shim.h:1:
#include "/usr/local/Cellar/ncurses/6.1/include/ncurses.h"
         ^
/usr/local/Cellar/ncurses/6.1/include/ncurses.h:60:10: error: 'ncursesw/ncurses_dll.h' file not found with <angled> include; use "quotes" instead
#include <ncursesw/ncurses_dll.h>
         ^
<module-includes>:1:9: note: in file included from <module-includes>:1:
#import "shim.h"
        ^
shim.h:1:10: note: in file included from shim.h:1:
#include "/usr/local/Cellar/ncurses/6.1/include/ncurses.h"
         ^
/usr/local/Cellar/ncurses/6.1/include/ncurses.h:674:45: error: conflicting types for 'keyname'
extern NCURSES_EXPORT(NCURSES_CONST char *) keyname (int);              /* implemented */
                                            ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/curses.h:598:45: note: previous declaration is here
extern NCURSES_EXPORT(NCURSES_CONST char *) keyname (int);              /* implemented */

...

I'm trying to compile the package using:

swift build -Xcc -I/usr/local/Cellar/ncurses/6.1/include/ -Xlinker -L/usr/local/Cellar/ncurses/6.1/lib

I also went down the route of specifying the pkgConfig on the package definition, with the same result. Can someone help?

FYI It's worth mentioning that upon ncurses installation through Homebrew I get the following warning as ncurses is already provided by OS X:

ncurses is keg-only, which means it was not symlinked into /usr/local,
because macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have ncurses first in your PATH run:
  echo 'export PATH="/usr/local/opt/ncurses/bin:$PATH"' >> ~/.zshrc

For compilers to find ncurses you may need to set:
  export LDFLAGS="-L/usr/local/opt/ncurses/lib"
  export CPPFLAGS="-I/usr/local/opt/ncurses/include"

For pkg-config to find ncurses you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/ncurses/lib/pkgconfig"

Pkgconfig for ncurses looks like this

# pkg-config file generated by gen-pkgconfig
# vile:makemode

prefix=/usr/local/Cellar/ncurses/6.1
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include/ncursesw
abi_version=6
major_version=6
version=6.1.20180127

Name: ncursesw
Description: ncurses 6.1 library
Version: ${version}
URL: https://invisible-island.net/ncurses
Requires.private:
Libs:  -L${libdir} -lncursesw
Libs.private:
Cflags:  -D_DARWIN_C_SOURCE -I/usr/local/Cellar/ncurses/6.1/include -I${includedir}

Body:
I'm not too well-versed in this subject, but it seems like you may want to look into adding a build script for this to your project. In Xcode, under the selected project, go to Build Phases > New Run Script Phase

In that script add your flags:

export LDFLAGS="-L/usr/local/opt/ncurses/lib"
export CPPFLAGS="-I/usr/local/opt/ncurses/include"

The build script should run on install. I'm not sure if you need the pkg-config flag here. Hope this helps point you somewhere in the right direction.


问:
Make flow assume that a particular key does exist in a Map
Due to the way you're iterating over something, you may know that a key always exists in a Map but flow may not know.

Currently, how I'm getting rid of it is to check if the result returned from get() is not undefined.

I don't want to add those spurious checks though, and instead I want to tell the typesystem that it can assume that that key exists. Telling this to the typesystem also conveys more information (this key definitely exists) about the program to a future reader than a spurious check (this key may or may not exist, and if doesn't exist then we're ignoring that case)

So I want to be able to do the following by preferably adding something on or before line 3 instead of an if check.

```<code>1. let score:Map<string, number> = new Map()
2. initialize(score); // some magic initilization of the map that flow doesn't understand
3. score.get("hello");
</code>```

答:
I wouldn't recommend doing this but you could extend the Map class to define your own class that defines get,

```<code>declare class MyMap<K, V> extends Map<K,V> {
    get(key: 'hello'): V;
    get(key: K): V | void;
}
</code>```

so that (new myMap()).get('hello') has type V instead of V | void. For example,

```<code>const myMap: MyMap<string, number> = new MyMap();
const n: number = myMap.get('hello');
const o: number = myMap.get('not hello'); // error
const p: number | void = myMap.get('not hello');
</code>```

Try Flow

You'll need to change your code so that initialize returns a MyMap instead of modifying the passed in Map. Note that although this will pass Flow, it may still break during running. As you can see in the example above, even though I have created a new MyMap(), I have not added the key 'hello' and so n isn't really a number.

Body:
Due to the way you're iterating over something, you may know that a key always exists in a Map but flow may not know.

Currently, how I'm getting rid of it is to check if the result returned from get() is not undefined.

I don't want to add those spurious checks though, and instead I want to tell the typesystem that it can assume that that key exists. Telling this to the typesystem also conveys more information (this key definitely exists) about the program to a future reader than a spurious check (this key may or may not exist, and if doesn't exist then we're ignoring that case)

So I want to be able to do the following by preferably adding something on or before line 3 instead of an if check.

1. let score:Map<string, number> = new Map()
2. initialize(score); // some magic initilization of the map that flow doesn't understand
3. score.get("hello");

Body:
I wouldn't recommend doing this but you could extend the Map class to define your own class that defines get,

declare class MyMap<K, V> extends Map<K,V> {
    get(key: 'hello'): V;
    get(key: K): V | void;
}

so that (new myMap()).get('hello') has type V instead of V | void. For example,

const myMap: MyMap<string, number> = new MyMap();
const n: number = myMap.get('hello');
const o: number = myMap.get('not hello'); // error
const p: number | void = myMap.get('not hello');

Try Flow

You'll need to change your code so that initialize returns a MyMap instead of modifying the passed in Map. Note that although this will pass Flow, it may still break during running. As you can see in the example above, even though I have created a new MyMap(), I have not added the key 'hello' and so n isn't really a number.