问:
Uncaught typeerror cannot read property 'image' of undefined with json data
I'm having an

```<code>Uncaught TypeError cannot read property 'image' of undefined
</code>```

error when calling some Json data. My js is the following:

```<code>$.getJSON('/js/data.json', function (json) {
    Object.keys(json).forEach(function (country) {
        $(".marker." + country.toLowerCase()).on("click", function () {
            $("#show").html(
                "Image: <img src=" + json[country][0].image + ">" +
                "| Description: <h1>" + json[country][0].description) + "</h1>";
        });
    });
});
</code>```

and my data.json the following:

```<code>{
    "france": {
        "image": "img/ausralia.jpg",
        "description": "number django 1"
    },
    "australia": {
        "image": "img/ausralia.jpg",
        "description": "number django 2"
    },
    "uk": {
        "image": "img/ausralia.jpg",
        "description": "number django 3"
    }
}
</code>```

ON click, no data are being display and I'm having that error being display in my console.

The weird thing is that If i call the data like this in my js, the error doesn't appear and everything works correctly. But I need to be able to call the data from an external file.

```<code>var json = {
    "France": [{
        "image": "img/ausralia.jpg",
        "description": "number django 1"
    }],
    "Australia": [{
        "image": "img/ausralia.jpg",
        "description": "number django 2"
    }],
    "uk": [{
        "image": "img/ausralia.jpg",
        "description": "number django 2ee"
    }]
}

Object.keys(json).forEach(function (country) {
    $(".marker." + country.toLowerCase()).on("click", function () {
        $("#show").html(
            "Image: <img src=" + json[country][0].image + ">" +
            "| Description: <h1>" + json[country][0].description) + "</h1>";
    });
});
</code>```

Any help will be amazing, I know there is post about this error, but I cant find any solution to make it work !

Hope it make sense , thanks for your time !

答:
Try this,</p>

```<code>Object.keys(json).forEach(function (country) {

    if(typeof json[country][0].image !== "undefined" && typeof json[country][0].description !== "undefined" ) {

        $(".marker." + country.toLowerCase()).on("click", function () {

            $("#show").html( "Image: <img src=" + json[country][0].image + ">" + "| Description: <h1>" + json[country][0].description) + "</h1>";

        });

    }

});
</code>```

Body:
I'm having an

Uncaught TypeError cannot read property 'image' of undefined

error when calling some Json data. My js is the following:

$.getJSON('/js/data.json', function (json) {
    Object.keys(json).forEach(function (country) {
        $(".marker." + country.toLowerCase()).on("click", function () {
            $("#show").html(
                "Image: " +
                "| Description:
" + json[country][0].description) + "
";
        });
    });
});

and my data.json the following:

{
    "france": {
        "image": "img/ausralia.jpg",
        "description": "number django 1"
    },
    "australia": {
        "image": "img/ausralia.jpg",
        "description": "number django 2"
    },
    "uk": {
        "image": "img/ausralia.jpg",
        "description": "number django 3"
    }
}

ON click, no data are being display and I'm having that error being display in my console.

The weird thing is that If i call the data like this in my js, the error doesn't appear and everything works correctly. But I need to be able to call the data from an external file.

var json = {
    "France": [{
        "image": "img/ausralia.jpg",
        "description": "number django 1"
    }],
    "Australia": [{
        "image": "img/ausralia.jpg",
        "description": "number django 2"
    }],
    "uk": [{
        "image": "img/ausralia.jpg",
        "description": "number django 2ee"
    }]
}

Object.keys(json).forEach(function (country) {
    $(".marker." + country.toLowerCase()).on("click", function () {
        $("#show").html(
            "Image: " +
            "| Description:
" + json[country][0].description) + "
";
    });
});

Any help will be amazing, I know there is post about this error, but I cant find any solution to make it work !

Hope it make sense , thanks for your time !

Body:
Try this,

Object.keys(json).forEach(function (country) {

    if(typeof json[country][0].image !== "undefined" && typeof json[country][0].description !== "undefined" ) {

        $(".marker." + country.toLowerCase()).on("click", function () {

            $("#show").html( "Image: <img src=" + json[country][0].image + ">" + "| Description: <h1>" + json[country][0].description) + "</h1>";

        });

    }

});


来源: stackexchange

问:
Cannot resolve function-like macro inside conditional compilation block
Consider the following - I want to check with #if #endif whether a
token is defined somewhere in the code.
I am using a CONCAT(input) macro that should glue the constant and changing parts of the token that I want to check.

Unfortunately, the approach presented below causes a compilation error:

error: missing binary operator before token "("

I have found the expressions that can be put inside a #if #endif block:

https://gcc.gnu.org/onlinedocs/cpp/If.html#If

And apparently it states that:

Macros. All macros in the expression are expanded before actual computation of the expression’s value begins.

It turns out that (CONCAT(test)) should be resolved, but it is not.

Is there any workaround allowing to resolve concatenated token names correctly in a conditional compilation block?

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

#define CONCAT(input) string##input
#define stringtest 1

int main(void)
{
    #if defined(CONCAT(test)) && (CONCAT(test)==1)
        printf("OK");
    #else
        printf("NOT");
    #endif

    return 0;
}
</code>```

答:
You can't do that. Only literals can be used.

You should check for macro directly:

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

#define CONCAT(input) string##input
#define stringtest 1

int main(void) {
    #if stringtest  == 1
        printf("OK");
    #else
        printf("NOT");
    #endif
    return 0;
}
</code>```

Since you don't need defined check, you can use like this:

```<code>#define CONCAT(input) string##input
#define stringtest 1

int main(void) {
    #if CONCAT(test) == 1
        printf("OK");
    #else
        printf("NOT");
    #endif
    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Consider the following - I want to check with #if #endif whether a
token is defined somewhere in the code.
I am using a CONCAT(input) macro that should glue the constant and changing parts of the token that I want to check.

Unfortunately, the approach presented below causes a compilation error:

error: missing binary operator before token "("

I have found the expressions that can be put inside a #if #endif block:

https://gcc.gnu.org/onlinedocs/cpp/If.html#If

And apparently it states that:

Macros. All macros in the expression are expanded before actual computation of the expression’s value begins.

It turns out that (CONCAT(test)) should be resolved, but it is not.

Is there any workaround allowing to resolve concatenated token names correctly in a conditional compilation block?

#include <stdio.h>

#define CONCAT(input) string##input
#define stringtest 1

int main(void)
{
    #if defined(CONCAT(test)) && (CONCAT(test)==1)
        printf("OK");
    #else
        printf("NOT");
    #endif

    return 0;
}

Body:
You can't do that. Only literals can be used.

You should check for macro directly:

#include <stdio.h>

#define CONCAT(input) string##input
#define stringtest 1

int main(void) {
    #if stringtest  == 1
        printf("OK");
    #else
        printf("NOT");
    #endif
    return 0;
}

Since you don't need defined check, you can use like this:

#define CONCAT(input) string##input
#define stringtest 1

int main(void) {
    #if CONCAT(test) == 1
        printf("OK");
    #else
        printf("NOT");
    #endif
    return 0;
}


问:
How to recursively filter an array if value exists on another array
I have two arrays.
The first one is the structure, an associative array that containts all elements inside categories. the name of the categories are keys inside this array. The categories can have different levels of depth:
check this example:

```<code>$structure = [
            'fruits'    => [
                'sweet' => [
                    'red' => [
                        'watermelon' =>['id' => 1],
                        'cherry' =>['id' => 2],
                        'litchi' =>['id' => 3]
                    ],
                    'white' => [
                        'coco' =>['id' => 13],
                        'lucuma' =>['id' => 14],
                    ]

                ],
                'sour'  => [
                    'lemon' =>['id' => 4],
                    'orange' =>['id' => 5],
                    'tangerine' =>['id' => 6]
                ],
            ],
            'colors'   => [
                'black' =>['id' => 7],
                'green' =>['id' => 8],
                'blue' => ['id' => 9]
            ],
            'names'   => [
                'jack' =>['id' => 10],
                'paul' =>['id' => 11],
                'peter' =>['id' => 12]
            ]
        ];
</code>```

I have a second array, with the elements that I want to search:

```<code>$results = ['coco', 'green','peter'];
</code>```

I need to write a function that gives an output array with the elements and the tree of categories where they belong. Something like this:

```<code>$resultsInStructure = [
            'fruits'    => [
                'sweet' => [
                    'white' => [
                        'coco' => ['id' => 13]
                    ]
                ]
            ],
            'colors'   => [
                'green' =>['id' => 8]
            ],
            'names'   => [
                'peter' =>['id' => 12]
            ]
        ];
</code>```

The function needs to be recursive, of course. Either walking the first of the second array, it's just that I can't manage to get it right... any help is appreciated !

答:
try this</p>

```<code>function walk($arr,$results)
{
    if (is_array($arr))
    {
        $arrFound = [];
        $arrTmpReturn = [];
        foreach($arr AS $key => $val)
        {
            if (in_array($key, $results))
            {
                $arrFound = array_merge($arrFound,[$key => $val]);
            }
            $arrReturn = walk($val,$results);
            if (!is_null($arrReturn))
            {
                $arrTmpReturn = array_merge($arrTmpReturn,[$key => $arrReturn]);
            }
        }
        if (count($arrFound) > 0)   return $arrFound;
        if (count($arrTmpReturn) > 0) return $arrTmpReturn;
    }
}

print_r(walk($structure,$results));
</code>```

Body:
I have two arrays.
The first one is the structure, an associative array that containts all elements inside categories. the name of the categories are keys inside this array. The categories can have different levels of depth:
check this example:

$structure = [
            'fruits'    => [
                'sweet' => [
                    'red' => [
                        'watermelon' =>['id' => 1],
                        'cherry' =>['id' => 2],
                        'litchi' =>['id' => 3]
                    ],
                    'white' => [
                        'coco' =>['id' => 13],
                        'lucuma' =>['id' => 14],
                    ]

                ],
                'sour'  => [
                    'lemon' =>['id' => 4],
                    'orange' =>['id' => 5],
                    'tangerine' =>['id' => 6]
                ],
            ],
            'colors'   => [
                'black' =>['id' => 7],
                'green' =>['id' => 8],
                'blue' => ['id' => 9]
            ],
            'names'   => [
                'jack' =>['id' => 10],
                'paul' =>['id' => 11],
                'peter' =>['id' => 12]
            ]
        ];

I have a second array, with the elements that I want to search:

$results = ['coco', 'green','peter'];

I need to write a function that gives an output array with the elements and the tree of categories where they belong. Something like this:

$resultsInStructure = [
            'fruits'    => [
                'sweet' => [
                    'white' => [
                        'coco' => ['id' => 13]
                    ]
                ]
            ],
            'colors'   => [
                'green' =>['id' => 8]
            ],
            'names'   => [
                'peter' =>['id' => 12]
            ]
        ];

The function needs to be recursive, of course. Either walking the first of the second array, it's just that I can't manage to get it right... any help is appreciated !

Body:
try this

function walk($arr,$results)
{
    if (is_array($arr))
    {
        $arrFound = [];
        $arrTmpReturn = [];
        foreach($arr AS $key => $val)
        {
            if (in_array($key, $results))
            {
                $arrFound = array_merge($arrFound,[$key => $val]);
            }
            $arrReturn = walk($val,$results);
            if (!is_null($arrReturn))
            {
                $arrTmpReturn = array_merge($arrTmpReturn,[$key => $arrReturn]);
            }
        }
        if (count($arrFound) > 0)   return $arrFound;
        if (count($arrTmpReturn) > 0) return $arrTmpReturn;
    }
}

print_r(walk($structure,$results));


问:
Monthly interval between two date
I have two dates like 2017-10-05 and 2018-02-20, my interval result should be:

```<code>2017-10-05
2017-10-31
2017-11-30
2017-12-31
2018-01-31
2018-02-20
2018-02-28
</code>```

Any suggestions to do this in C# using DateTime object?

UPDATE #1

The problem I mentioned first concerns is a real situation of a cash flow management, so I had to change dates specifications for the calculation of interest, dif and civ. This code i use for the purpose:

```<code>foreach (DataRow dr in DTFlussi.Rows)
{
    DateTime d1 = Convert.ToDateTime(DTFlussi.Rows[n]["data_scadenza"]).Date;
    DateTime d2 = Convert.ToDateTime(DTFlussi.Rows[n + 1]["data_scadenza"]).Date;
    int[] date = RecuperoDate(d1, d2);

    if (saldoConto > 0)
        InteressiAttivi(saldoConto, date, DTOneri, d1, d2);
    else if (saldoConto <= 0 && saldoConto >= (fidoConto * -1))
    {
        //esempio di interessi FIDO al 2%
        InteressiFido(saldoConto, date, tassoFIDO, DTOneri, d1, d2);
    }
    else if (saldoConto < 0 && saldoConto < (fidoConto * -1))
    {
        //esempio con interessi FIDO al 2% e interessi EXTRAFIDO al 4%
        InteressiExtraFido(saldoConto, fidoConto, date, tassoFIDO, tassoEXTRAFIDO, DTOneri, d1, d2);
    }
    catch (Exception)
    {

    }
    n++;
}
</code>```

The code for RecuperoDate is:

```<code>public int[] RecuperoDate(DateTime d1, DateTime d2)
{
    int[] diff = new int[2];

    //Gestione anno bisestile Febbrario
    int giorniFebbraio = 0;
    if (DateTime.IsLeapYear(d1.Year))
        giorniFebbraio = 29;
    else
        giorniFebbraio = 28;

    try
    {
        #region MESE 1

        if (d1.Date >= new DateTime(d1.Year, 1, 1) && d1.Date <= new DateTime(d1.Year, 1, 31) && d2.Date >= new DateTime(d1.Year, 1, 31))
        {
            DateTime Mese1 = new DateTime(d1.Year, 1, 31).Date;
            diff[0] = (int)(Mese1 - d1).TotalDays;
            diff[1] = (int)(d2 - Mese1).TotalDays;
        }

        #endregion

        //NOTE: incomplete code because is the same thing for the other months (February - December)
</code>```

This is necessary to obtain subsequent variations in the balance and at the end of the calculations this is what I want:

答:
```<code>var startDate = new DateTime(2017, 10, 5);
        var endDate = new DateTime(2018, 2, 20);

        var firstDayofMonth = new DateTime(startDate.Year, startDate.Month, 1).AddMonths(1);

        Console.WriteLine(startDate.ToShortDateString());

        while (true)
        {
            var dateToCompare = firstDayofMonth.AddDays(-1);

            //Last month
            if (dateToCompare >= endDate)
            {
                if (dateToCompare > endDate)
                {
                    Console.WriteLine(endDate.ToShortDateString());
                }
                Console.WriteLine(dateToCompare.ToShortDateString());
                break;
            }

            if (dateToCompare != startDate)
            {
                Console.WriteLine(dateToCompare.ToShortDateString());
            }

            firstDayofMonth = firstDayofMonth.AddMonths(1);
        }
</code>```

Title: Monthly interval between two date

Body:
I have two dates like 2017-10-05 and 2018-02-20, my interval result should be:

2017-10-05
2017-10-31
2017-11-30
2017-12-31
2018-01-31
2018-02-20
2018-02-28

Any suggestions to do this in C# using DateTime object?

UPDATE #1

The problem I mentioned first concerns is a real situation of a cash flow management, so I had to change dates specifications for the calculation of interest, dif and civ. This code i use for the purpose:

foreach (DataRow dr in DTFlussi.Rows)
{
    DateTime d1 = Convert.ToDateTime(DTFlussi.Rows[n]["data_scadenza"]).Date;
    DateTime d2 = Convert.ToDateTime(DTFlussi.Rows[n + 1]["data_scadenza"]).Date;
    int[] date = RecuperoDate(d1, d2);

    if (saldoConto > 0)
        InteressiAttivi(saldoConto, date, DTOneri, d1, d2);
    else if (saldoConto <= 0 && saldoConto >= (fidoConto * -1))
    {
        //esempio di interessi FIDO al 2%
        InteressiFido(saldoConto, date, tassoFIDO, DTOneri, d1, d2);
    }
    else if (saldoConto < 0 && saldoConto < (fidoConto * -1))
    {
        //esempio con interessi FIDO al 2% e interessi EXTRAFIDO al 4%
        InteressiExtraFido(saldoConto, fidoConto, date, tassoFIDO, tassoEXTRAFIDO, DTOneri, d1, d2);
    }
    catch (Exception)
    {

    }
    n++;
}

The code for RecuperoDate is:

public int[] RecuperoDate(DateTime d1, DateTime d2)
{
    int[] diff = new int[2];

    //Gestione anno bisestile Febbrario
    int giorniFebbraio = 0;
    if (DateTime.IsLeapYear(d1.Year))
        giorniFebbraio = 29;
    else
        giorniFebbraio = 28;

    try
    {
        #region MESE 1

        if (d1.Date >= new DateTime(d1.Year, 1, 1) && d1.Date <= new DateTime(d1.Year, 1, 31) && d2.Date >= new DateTime(d1.Year, 1, 31))
        {
            DateTime Mese1 = new DateTime(d1.Year, 1, 31).Date;
            diff[0] = (int)(Mese1 - d1).TotalDays;
            diff[1] = (int)(d2 - Mese1).TotalDays;
        }

        #endregion

        //NOTE: incomplete code because is the same thing for the other months (February - December)

This is necessary to obtain subsequent variations in the balance and at the end of the calculations this is what I want:


问:
improving search speed results - swift tableviewcontroller
I'm building personal weather app where the users can pick cities and show the weather temperature.

I'm using a search in this JSON file:

cities.json

I'm using the following code for the search:

searching extention:

```<code>extension SearchUI: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
    filterContentForSearchText(searchText: searchController.searchBar.text!)
}
</code>```

filtering function:

```<code>func filterContentForSearchText(searchText: String) {
    filteredCountries = countries.array!.filter { country in
        return country["name"].stringValue.lowercased().hasPrefix(searchText.lowercased())
    }
    tableView.reloadData()
}
</code>```

my cellForRowAt function:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell : UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "countryCell")

    var data: JSON

    if searchController.isActive && searchController.searchBar.text != "" {
        data = filteredCountries[indexPath.row]
    } else {
        data = countries[indexPath.row]
    }

    let countryName = data["country"].stringValue
    let countrycity = data["name"].stringValue
    //data1.append(data["name"].stringValue)
    cell?.textLabel?.text = countrycity
    cell?.detailTextLabel?.text = countryName

    return cell!
}
</code>```

the search process in my app is very slow and Im facing with a slow input by the keyboard during the filtering.

for notice:
countries - is a JSON object

thanks you all!

答:
parsing:</p>

```<code>countries = try! JSON(data: NSData(contentsOfFile: Bundle.main.path(forResource: "cities_with_countries", ofType: "json")!)! as Data)
</code>```

Body:
I'm building personal weather app where the users can pick cities and show the weather temperature.

I'm using a search in this JSON file:

cities.json

I'm using the following code for the search:

searching extention:

extension SearchUI: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
    filterContentForSearchText(searchText: searchController.searchBar.text!)
}

filtering function:

func filterContentForSearchText(searchText: String) {
    filteredCountries = countries.array!.filter { country in
        return country["name"].stringValue.lowercased().hasPrefix(searchText.lowercased())
    }
    tableView.reloadData()
}

my cellForRowAt function:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell : UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "countryCell")

    var data: JSON

    if searchController.isActive && searchController.searchBar.text != "" {
        data = filteredCountries[indexPath.row]
    } else {
        data = countries[indexPath.row]
    }

    let countryName = data["country"].stringValue
    let countrycity = data["name"].stringValue
    //data1.append(data["name"].stringValue)
    cell?.textLabel?.text = countrycity
    cell?.detailTextLabel?.text = countryName

    return cell!
}

the search process in my app is very slow and Im facing with a slow input by the keyboard during the filtering.

for notice:
countries - is a JSON object

thanks you all!

Body:
parsing:

countries = try! JSON(data: NSData(contentsOfFile: Bundle.main.path(forResource: "cities_with_countries", ofType: "json")!)! as Data)


问:
unable to split Firebase functions in multiple files
I'm working with firebase functions and arrived to hundreds of functions, and now it is very hard to manage it in single index.js file as shown in their lots of examples

I tried to split that functions in multiple files like:

```<code>--firebase.json
--functions
  --node_modules
  --index.js
  --package.json
  --app
    --groupFunctions.js
    --authFunctions.js
    --storageFunctions.js
</code>```

In this structure i divide my functions in three categories and put in that three files groupFunctions.js, authFunctions.js, and storageFunctions.js. I then tried to import thise files in index.js, but I don't know why it is not working for me.

Here is groupFunctions.js

```<code>var functions = require('firebase-functions');
module.exports = function(){
    exports.onGroupCreate = functions.database.ref('/groups/{groupId}')
        .onWrite(event => {
            console.log(`A group is created in database named:${event.params.groupId}.`);
            // some logic...
            //...
        })
}
</code>```

Here is index.js file:

```<code>var functions = require('firebase-functions');
module.exports = require("./app/groupFunctions")();
</code>```

My editor not giving any warning in this code. But when I deploy this code with firebase deploy --only functions, it does not deploy function. If some functions already exist on firebase console, it remove all functions on deploy.

here is deployment logs:

question is also asked on github

答:
You can pass the exports object to the function in groupFunctions.js, like this:

```<code>var functions = require('firebase-functions');

module.exports = function (e) {
    e.onGroupCreate = functions.database.ref('/groups/{groupId}')
        .onWrite(event => {
            console.log(`A group is created in database named:${event.params.groupId}.`);
            // some logic...
            //...
        })
}
</code>```

Now, in index.js:

```<code>var functions = require('firebase-functions');

require("./app/groupFunctions")(module.exports);
</code>```

The way it works is that modules.exports is a regular JavaScript object, so you can add new properties to that from wherever you want.

Body:
I'm working with firebase functions and arrived to hundreds of functions, and now it is very hard to manage it in single index.js file as shown in their lots of examples

I tried to split that functions in multiple files like:

--firebase.json
--functions
  --node_modules
  --index.js
  --package.json
  --app
    --groupFunctions.js
    --authFunctions.js
    --storageFunctions.js

In this structure i divide my functions in three categories and put in that three files groupFunctions.js, authFunctions.js, and storageFunctions.js. I then tried to import thise files in index.js, but I don't know why it is not working for me.

Here is groupFunctions.js

var functions = require('firebase-functions');
module.exports = function(){
    exports.onGroupCreate = functions.database.ref('/groups/{groupId}')
        .onWrite(event => {
            console.log(`A group is created in database named:${event.params.groupId}.`);
            // some logic...
            //...
        })
}

Here is index.js file:

var functions = require('firebase-functions');
module.exports = require("./app/groupFunctions")();

My editor not giving any warning in this code. But when I deploy this code with firebase deploy --only functions, it does not deploy function. If some functions already exist on firebase console, it remove all functions on deploy.

here is deployment logs:

question is also asked on github

Body:
You can pass the exports object to the function in groupFunctions.js, like this:

var functions = require('firebase-functions');

module.exports = function (e) {
    e.onGroupCreate = functions.database.ref('/groups/{groupId}')
        .onWrite(event => {
            console.log(`A group is created in database named:${event.params.groupId}.`);
            // some logic...
            //...
        })
}

Now, in index.js:

var functions = require('firebase-functions');

require("./app/groupFunctions")(module.exports);

The way it works is that modules.exports is a regular JavaScript object, so you can add new properties to that from wherever you want.


问:
Is Javaspaces supported on GWT?
Following a suggestion on a related post (see here), I was wondering if Javaspaces technology is supported on GWT?</p>

答:
Well, it depends on what you mean by "supported on GWT." GigaSpaces - built on JavaSpaces - can easily deploy GWT applications internally, and it's also easy for the server side of a GWT application to connect to a GigaSpace. (See http://openspaces.org/display/GDO/GoDo+-+Goods+Donation+System for an example of an application that does this - it was an OpenSpaces award winner.)

If you mean "direct from the client," well, it's likely to be POSSIBLE, but at that point you're not using the client side of GWT - you're using Java on the client.

ContentLicense: CC BY-SA 2.5

Title: Is Javaspaces supported on GWT?


问:
writing multiple returns to a file in python
I need to write the returns of each function in to a text file. I have used the code below. However, when I have multiple functions, this process of using file1.write() consumes a lot of time and lines. Is there any smarter method to write the outputs?

```<code>def function1():
    #some operation
    return "Status 1" + "\n\n"

def function2():
    #some operation
    return "Status 2" + "\n\n"

def function3():
    #some operation
    return "Status 1" + "\n\n"

if __name__ == '__main__':

    file1 = open("test.txt","w")

    output1 = function1()
    file1.write(output1)

    output2 = function2()
    file1.write(output2)

    output3 = function3()
    file1.write(output3)

    file1.close()
</code>```

I have modified the code since many are confused with my question.

答:
This code can be made shorter (and possibly clearer) by replacing everything below if by:

```<code>with open("text.txt","w") as file1:
    for func in (addition, subtraction, multiplication):
        file1.write(func(5,6))
</code>```

but this won't improve execution time.

Body:
I need to write the returns of each function in to a text file. I have used the code below. However, when I have multiple functions, this process of using file1.write() consumes a lot of time and lines. Is there any smarter method to write the outputs?

def function1():
    #some operation
    return "Status 1" + "\n\n"

def function2():
    #some operation
    return "Status 2" + "\n\n"

def function3():
    #some operation
    return "Status 1" + "\n\n"

if __name__ == '__main__':

    file1 = open("test.txt","w")

    output1 = function1()
    file1.write(output1)

    output2 = function2()
    file1.write(output2)

    output3 = function3()
    file1.write(output3)

    file1.close()

I have modified the code since many are confused with my question.

Body:
This code can be made shorter (and possibly clearer) by replacing everything below if by:

with open("text.txt","w") as file1:
    for func in (addition, subtraction, multiplication):
        file1.write(func(5,6))

but this won't improve execution time.


问:
py3.6 win10 - error installing virtualenv
Just installed Py3.6, made sur pip is installed and tried to install virtualenv with:

```<code>pip install virtualenv
</code>```

And this is the result:

```<code>pip install virtualenv
Collecting virtualenv
  Using cached virtualenv-15.1.0-py2.py3-none-any.whl
Installing collected packages: virtualenv
Exception:
Traceback (most recent call last):
  File "c:\program files\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "c:\program files\python36-32\lib\site-packages\pip\commands\install.py", line 342, in run
    prefix=options.prefix_path,
  File "c:\program files\python36-32\lib\site-packages\pip\req\req_set.py", line 784, in install
    **kwargs
  File "c:\program files\python36-32\lib\site-packages\pip\req\req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "c:\program files\python36-32\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "c:\program files\python36-32\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "c:\program files\python36-32\lib\site-packages\pip\wheel.py", line 323, in clobber
    shutil.copyfile(srcfile, destfile)
  File "c:\program files\python36-32\lib\shutil.py", line 115, in copyfile
    with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'c:\\program files\\python36-32\\Lib\\site-packages\\virtualenv.py'
</code>```

Same thing happened when I tried:

```<code>pip install virtualenvwrapper-win
</code>```

Any ideas?

答:
You need to run the command from a command prompt having admin privileges

On Windows 8 and 10 you can just press Windows+X and on the menu, choose "Command Prompt (Admin)"

This question is possibly a copy of this one.

Body:
Just installed Py3.6, made sur pip is installed and tried to install virtualenv with:

pip install virtualenv

And this is the result:

pip install virtualenv
Collecting virtualenv
  Using cached virtualenv-15.1.0-py2.py3-none-any.whl
Installing collected packages: virtualenv
Exception:
Traceback (most recent call last):
  File "c:\program files\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "c:\program files\python36-32\lib\site-packages\pip\commands\install.py", line 342, in run
    prefix=options.prefix_path,
  File "c:\program files\python36-32\lib\site-packages\pip\req\req_set.py", line 784, in install
    **kwargs
  File "c:\program files\python36-32\lib\site-packages\pip\req\req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "c:\program files\python36-32\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "c:\program files\python36-32\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "c:\program files\python36-32\lib\site-packages\pip\wheel.py", line 323, in clobber
    shutil.copyfile(srcfile, destfile)
  File "c:\program files\python36-32\lib\shutil.py", line 115, in copyfile
    with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'c:\\program files\\python36-32\\Lib\\site-packages\\virtualenv.py'

Same thing happened when I tried:

pip install virtualenvwrapper-win

Any ideas?


问:
How to get hover efect only on part of the element?
I have the below code:

.container {
 padding-top:20px;
}

.container:hover {
 background-color: red;
}

.text {
  padding-top: 20px;
}

.container:before {
content: 'before';
top: 5px;
position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <span class='text'>
    My text
  </span>
</div></code>```

I needed the 'before' as a title so inserted it as a pseudo, moved up and created palce for it by adding padding to the div. Now when I hover over the div the pseudo gets highlighted as well, which I don't want.

AS it's a skin for external app I have very limited possibilities to add elements to dom, which is what I guess should be done. How can I highlight only bottom part of the div without the pseudo? Maybe there's a better way to style the pseudo itself so that it doesn't get hovered over? Pure CSS appreciated.

答:
To prevent the background from covering the padding as well, add background-clip: content-box; to the .container:

.container {
  padding-top: 20px;
  background-clip: content-box;
}

.container:hover {
  background-color: red;
}

.text {
  padding-top: 20px;
}

.container:before {
  content: 'before';
  top: 5px;
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <span class='text'>
    My text
  </span>
</div></code>```

Or use margin-top: 20px; instead of the padding:

.container {
  margin-top: 20px;
}

.container:hover {
  background-color: red;
}

.text {
  padding-top: 20px;
}

.container:before {
  display: block;
  width: 100%;
  content: 'before';
  top: 5px;
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <span class='text'>
    My text
  </span>
</div></code>```

Body:
I have the below code:

.container {
 padding-top:20px;
}

.container:hover {
 background-color: red;
}

.text {
  padding-top: 20px;
}

.container:before {
content: 'before';
top: 5px;
position: absolute;
}

    My text

I needed the 'before' as a title so inserted it as a pseudo, moved up and created palce for it by adding padding to the div. Now when I hover over the div the pseudo gets highlighted as well, which I don't want.

AS it's a skin for external app I have very limited possibilities to add elements to dom, which is what I guess should be done. How can I highlight only bottom part of the div without the pseudo? Maybe there's a better way to style the pseudo itself so that it doesn't get hovered over? Pure CSS appreciated.

Body:
To prevent the background from covering the padding as well, add background-clip: content-box; to the .container:

.container {
  padding-top: 20px;
  background-clip: content-box;
}

.container:hover {
  background-color: red;
}

.text {
  padding-top: 20px;
}

.container:before {
  content: 'before';
  top: 5px;
  position: absolute;
}

<div class='container'>
  <span class='text'>
    My text
  </span>
</div>

Or use margin-top: 20px; instead of the padding:

.container {
  margin-top: 20px;
}

.container:hover {
  background-color: red;
}

.text {
  padding-top: 20px;
}

.container:before {
  display: block;
  width: 100%;
  content: 'before';
  top: 5px;
  position: absolute;
}

<div class='container'>
  <span class='text'>
    My text
  </span>
</div>


问:
passing functions as arguments in ruby
I'm trying to wrap my head around functional programming in ruby and there doesn't seem to be much good documentation out there.

Essentially, I'm trying to write a combine function that would have a Haskell type signature of:

```<code>[a] -> [a] -> (a -> a -> a) -> [a]
</code>```

So

```<code>combine([1,2,3], [2,3,4], plus_func) => [3,5,7]
combine([1,2,3], [2,3,4], multiply_func) => [2,6,12]
</code>```

etc.

I found some stuff about using zip and map but that feels really ugly to use.

What would be the most "ruby" way of implementing something like this?

答:
You can pass the name of the method as a symbol and use Object#send (or Object#__send__) to call it by name.  (Ruby doesn't really have functions, it has methods.)

You can pass a lambda or block which calls your desired method on your desired arguments.  Passing blocks is probably the preferred Ruby way, when it works (i.e. when you only have a single block to pass).

You retrieve Method objects directly via Object#method and then pass them around and call them, but I have little experience doing it this way and haven't seen it done much in practice.

OwnerDisplayName: Shalmanese

Title: passing functions as arguments in ruby

Body:
I'm trying to wrap my head around functional programming in ruby and there doesn't seem to be much good documentation out there.

Essentially, I'm trying to write a combine function that would have a Haskell type signature of:

[a] -> [a] -> (a -> a -> a) -> [a]

So

combine([1,2,3], [2,3,4], plus_func) => [3,5,7]
combine([1,2,3], [2,3,4], multiply_func) => [2,6,12]

etc.

I found some stuff about using zip and map but that feels really ugly to use.

What would be the most "ruby" way of implementing something like this?

OwnerDisplayName: Brian C.


问:
how to spread out buttons, they are currently stacked?
I have a bunch of buttons on my page, my html is like:

```<code><div>
  <input ..>
  <input ...>
</dvi>
</code>```

They are currently just stacking up on each other, I want them all on one horizontal line spread out.

I tried doing:

display:inline

on the outer div, but that didn't work.

答:
Just float them!</p>

```<code><div>
   <input style="float: right" />
   <input style="float: right" />
</div>
</code>```

Body:
I have a bunch of buttons on my page, my html is like:

  <input ..>
  <input ...>
</dvi>

They are currently just stacking up on each other, I want them all on one horizontal line spread out.

I tried doing:

display:inline

on the outer div, but that didn't work.

Body:
Just float them!

<div>
   <input style="float: right" />
   <input style="float: right" />
</div>


问:
DiscoveryClient.GetAsync fails “Issuer name does not match authority” when call passes through SSL-terminator
Our web applications are hosted behind an SSL-terminating cluster. I call DiscoveryClient.GetAsync

```<code>var discoveryClient = DiscoveryClient.GetAsync("https://ourcluster.net/identityserver").Result;
</code>```

And I get the following result:

Issuer name does not match authority: http://ourcluster.net/identityserver

I am assuming that the SSL-termination causes the IdentityServer endpoint to receive the request as http and thus it resolves its authority url accordingly.

Any suggestions on how to work around this?

-S

答:
We found an acceptable workaround by setting the IssuerUri in our application hosting the IdentityServer endpoints:

```<code>services.AddIdentityServer(options =>
{
    var issuerUri = Configuration["IdentityServer:IssuerUri"];
    if (!string.IsNullOrEmpty(issuerUri))
    {
        options.IssuerUri = issuerUri;
    }
});
</code>```

Thus the client applications get served the same issuerUri value from the JWT and from their own call to the IdentityServer endpoint.

-S

Body:
Our web applications are hosted behind an SSL-terminating cluster. I call DiscoveryClient.GetAsync

var discoveryClient = DiscoveryClient.GetAsync("https://ourcluster.net/identityserver").Result;

And I get the following result:

Issuer name does not match authority: http://ourcluster.net/identityserver

I am assuming that the SSL-termination causes the IdentityServer endpoint to receive the request as http and thus it resolves its authority url accordingly.

Any suggestions on how to work around this?

-S

Body:
We found an acceptable workaround by setting the IssuerUri in our application hosting the IdentityServer endpoints:

services.AddIdentityServer(options =>
{
    var issuerUri = Configuration["IdentityServer:IssuerUri"];
    if (!string.IsNullOrEmpty(issuerUri))
    {
        options.IssuerUri = issuerUri;
    }
});

Thus the client applications get served the same issuerUri value from the JWT and from their own call to the IdentityServer endpoint.

-S


问:
Group array of javascript objects based on value into there own sub array of objects
I have an array of Javascript objects like below.

```<code>        [{

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "40",
            "rate": "20",
            "amount": "200",
            "vat": "60",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "mike@test.com",
            "fn": "Mike",
            "sn": "Mann",
            "phone": "01233xxxxx",
            "hours": "50",
            "rate": "70",
            "amount": "500",
            "vat": "90",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "fred@test.com",
            "fn": "Fred",
            "sn": "Frogg",
            "phone": "01233xxxxx",
            "hours": "80",
            "rate": "90",
            "amount": "800",
            "vat": "100",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "90",
            "rate": "30",
            "amount": "900",
            "vat": "120",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        }]
</code>```

What I ideally want is to group those of the same value (email) into there own sub array of objects i.e if you look at the array above you will see I have 2 entries for the same person Alex McPherson. What I want to do is the below if possible move and combine into a sub array and the same for any other value that exists more than once.

```<code>    [[{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "40",
        "rate": "20",
        "amount": "200",
        "vat": "60",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    },{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "90",
        "rate": "30",
        "amount": "900",
        "vat": "120",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "mike@test.com",
        "fn": "Mike",
        "sn": "Mann",
        "phone": "01233xxxxx",
        "hours": "50",
        "rate": "70",
        "amount": "500",
        "vat": "90",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "fred@test.com",
        "fn": "Fred",
        "sn": "Frogg",
        "phone": "01233xxxxx",
        "hours": "80",
        "rate": "90",
        "amount": "800",
        "vat": "100",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }]]
</code>```

I can't seem to get my head around resorting the array.

答:
```<code>        let emails = [{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "40",
        "rate": "20",
        "amount": "200",
        "vat": "60",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    },
    {

        "email": "mike@test.com",
        "fn": "Mike",
        "sn": "Mann",
        "phone": "01233xxxxx",
        "hours": "50",
        "rate": "70",
        "amount": "500",
        "vat": "90",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    },
    {

        "email": "fred@test.com",
        "fn": "Fred",
        "sn": "Frogg",
        "phone": "01233xxxxx",
        "hours": "80",
        "rate": "90",
        "amount": "800",
        "vat": "100",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    },
    {

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "90",
        "rate": "30",
        "amount": "900",
        "vat": "120",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }];

    let emails_obj = [];
    let output_array = [];

    emails.forEach(function(obj) {
        if (emails_obj[obj.email] == undefined) {
            emails_obj[obj.email] = []
            emails_obj[obj.email].push(obj);
        } else {
            emails_obj[obj.email].push(obj);
        }
    })

    for (var key in emails_obj) {
        output_array.push(emails_obj[key]);
    }
    console.log(output_array);
</code>```

Body:
I have an array of Javascript objects like below.

        [{

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "40",
            "rate": "20",
            "amount": "200",
            "vat": "60",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "mike@test.com",
            "fn": "Mike",
            "sn": "Mann",
            "phone": "01233xxxxx",
            "hours": "50",
            "rate": "70",
            "amount": "500",
            "vat": "90",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "fred@test.com",
            "fn": "Fred",
            "sn": "Frogg",
            "phone": "01233xxxxx",
            "hours": "80",
            "rate": "90",
            "amount": "800",
            "vat": "100",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "90",
            "rate": "30",
            "amount": "900",
            "vat": "120",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        }]

What I ideally want is to group those of the same value (email) into there own sub array of objects i.e if you look at the array above you will see I have 2 entries for the same person Alex McPherson. What I want to do is the below if possible move and combine into a sub array and the same for any other value that exists more than once.

    [[{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "40",
        "rate": "20",
        "amount": "200",
        "vat": "60",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    },{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "90",
        "rate": "30",
        "amount": "900",
        "vat": "120",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "mike@test.com",
        "fn": "Mike",
        "sn": "Mann",
        "phone": "01233xxxxx",
        "hours": "50",
        "rate": "70",
        "amount": "500",
        "vat": "90",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "fred@test.com",
        "fn": "Fred",
        "sn": "Frogg",
        "phone": "01233xxxxx",
        "hours": "80",
        "rate": "90",
        "amount": "800",
        "vat": "100",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }]]

I can't seem to get my head around resorting the array.


问:
How to run sudo -u username command in Ansible?
I want to run a specific command as sudo -u username <command name> using Ansible.

I tried below task, but facing permissions issue.

```<code>---
-
  hosts: all
  become: yes
  vars_files:
    - vars.yml

  tasks:
    - name: "Create solr cores"
      shell: /opt/apps/solr/bin/solr create -c test10
      become_flags: '-u solr'
      register: core_one
#      changed_when: '"\"status\":0" in core_one.stdout'
</code>```

Could anyone suggest on this?

答:
```<code>remote_user: ansible
  tasks:
  - name: "Create solr cores"
     shell: /opt/apps/solr/bin/solr create -c test10
     become: yes
     become_user: solr
     register: core_one
</code>```

In above example ansible connects to remote machine using user 'ansible'. Now this ansible user should have permission to switch to another user. i.e it should have root privileges

What happens with above code:

```<code>* ssh connection is made via ansible user (ansible-play does it)
* It uses command "sudo su solr" internally
* Then execute the command which is mentioned in shell
</code>```

Body:
I want to run a specific command as sudo -u username <command name> using Ansible.

I tried below task, but facing permissions issue.

---
-
  hosts: all
  become: yes
  vars_files:
    - vars.yml

  tasks:
    - name: "Create solr cores"
      shell: /opt/apps/solr/bin/solr create -c test10
      become_flags: '-u solr'
      register: core_one
#      changed_when: '"\"status\":0" in core_one.stdout'

Could anyone suggest on this?

Body:
remote_user: ansible
  tasks:
  - name: "Create solr cores"
     shell: /opt/apps/solr/bin/solr create -c test10
     become: yes
     become_user: solr
     register: core_one

In above example ansible connects to remote machine using user 'ansible'. Now this ansible user should have permission to switch to another user. i.e it should have root privileges

What happens with above code:

* ssh connection is made via ansible user (ansible-play does it)
* It uses command "sudo su solr" internally
* Then execute the command which is mentioned in shell


问:
How is webservice different than a website
From what I have gathered from various sources:

A website provides and presents data

A webservice provides data and there is no presentation involved.

Both are called using an url.

But webservice does return data in forms like xml , json etc. How is it any different than a website then which is returning it in the form of an html?

答:
Website:

Website is a set of related web pages located under a single domain
name.

It serves the user html typically to be interpreted and displayed in
a web browser to a user.

This is the typical GET request over HTTP(S).

Web service

A web service is any piece of software that makes itself available
over the Internet and uses a standardized XML/JSON messaging system.

For example, a client invokes a web service by sending an XML/JSON
The message, then waits for a corresponding XML/JSON response.

The web service can respond to many different types of requests
(GET, PUT, POST, DELETE etc).

Interacting with a web service can result in changing data on a
remote location, getting information back regarding some data etc.

Furthermore, a web service can respond in many different ways,
serving data in text, XML or even an empty response. Requests to web services are usually obfuscated from the user.


问:
Unity3d cardboard. Reticle dot is missing
This will be my second question regarding my ongoing VR project.

I am making a photosphere cardboard app.

I have added a sphere and inside of it, I have placed the Main camera on 0,0,0 position.

Inside of the cube I have placed a 3d cube. If user gazes towards it for some specific seconds, the equirectangular textures on the sphere will change via script.

Now I am using the GvrReticlePointer in this project, and I can't seem to find the white dot anywhere except when it is on the 3d cube.
I would really like to know what is causing the reticle to disappear on the scene and how to fix it.

Thanks in advance.

答:
Answering this question myself!

Just use this shader. Works like a charm!

```<code>Shader "Custom/Equirectangular" {
Properties {
    _Color ("Main Color", Color) = (1,1,1,1)
    _MainTex ("Diffuse (RGB) Alpha (A)", 2D) = "gray" {}
}

SubShader{
    Pass {
    Cull Front
        Tags {"LightMode" = "Always"}

        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma fragmentoption ARB_precision_hint_fastest
            #pragma glsl
            #pragma target 3.0

            #include "UnityCG.cginc"

            struct appdata {
               float4 vertex : POSITION;
               float3 normal : NORMAL;
            };

            struct v2f
            {
                float4    pos : SV_POSITION;
                float3    normal : TEXCOORD0;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.normal = v.normal;
                return o;
            }

            sampler2D _MainTex;

            #define PI 3.141592653589793

            inline float2 RadialCoords(float3 a_coords)
            {
                float3 a_coords_n = normalize(a_coords);
                float lon = atan2(a_coords_n.z, a_coords_n.x);
                float lat = acos(a_coords_n.y);
                float2 sphereCoords = float2(lon, lat) * (1.0 / PI);
                //return float2(sphereCoords.x * 0.5 + 0.5, 1 - sphereCoords.y);
                return float2(1 - (sphereCoords.x * 0.5 + 0.5), 1 - sphereCoords.y);
            }

            float4 frag(v2f IN) : COLOR
            {
                float2 equiUV = RadialCoords(IN.normal);
                return tex2D(_MainTex, equiUV);
            }
        ENDCG
        }
    }
    FallBack "VertexLit"
}
</code>```

Body:
Answering this question myself!

Just use this shader. Works like a charm!

Shader "Custom/Equirectangular" {
Properties {
    _Color ("Main Color", Color) = (1,1,1,1)
    _MainTex ("Diffuse (RGB) Alpha (A)", 2D) = "gray" {}
}

SubShader{
    Pass {
    Cull Front
        Tags {"LightMode" = "Always"}

        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma fragmentoption ARB_precision_hint_fastest
            #pragma glsl
            #pragma target 3.0

            #include "UnityCG.cginc"

            struct appdata {
               float4 vertex : POSITION;
               float3 normal : NORMAL;
            };

            struct v2f
            {
                float4    pos : SV_POSITION;
                float3    normal : TEXCOORD0;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.normal = v.normal;
                return o;
            }

            sampler2D _MainTex;

            #define PI 3.141592653589793

            inline float2 RadialCoords(float3 a_coords)
            {
                float3 a_coords_n = normalize(a_coords);
                float lon = atan2(a_coords_n.z, a_coords_n.x);
                float lat = acos(a_coords_n.y);
                float2 sphereCoords = float2(lon, lat) * (1.0 / PI);
                //return float2(sphereCoords.x * 0.5 + 0.5, 1 - sphereCoords.y);
                return float2(1 - (sphereCoords.x * 0.5 + 0.5), 1 - sphereCoords.y);
            }

            float4 frag(v2f IN) : COLOR
            {
                float2 equiUV = RadialCoords(IN.normal);
                return tex2D(_MainTex, equiUV);
            }
        ENDCG
        }
    }
    FallBack "VertexLit"
}


问:
How to assign from a source array being a subset of the destination array?
Having two arrays like:

```<code>a = np.zeros((3, 4), dtype=int)
[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

b = np.ones((2, 3), dtype=int)
[[1 1 1]
 [1 1 1]]
</code>```

How to assign from a source array (b) to the entries in the destination array (a) that are present in source ?

The resulting array should then be:

```<code>[[1 1 1 0]
 [1 1 1 0]
 [0 0 0 0]]
</code>```

答:
Get the shape of array to be assigned and then slice the destination array and assign -

```<code>m,n = b.shape
a[:m,:n] = b
</code>```

Body:
Having two arrays like:

a = np.zeros((3, 4), dtype=int)
[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

b = np.ones((2, 3), dtype=int)
[[1 1 1]
 [1 1 1]]

How to assign from a source array (b) to the entries in the destination array (a) that are present in source ?

The resulting array should then be:

[[1 1 1 0]
 [1 1 1 0]
 [0 0 0 0]]

Body:
Get the shape of array to be assigned and then slice the destination array and assign -

m,n = b.shape
a[:m,:n] = b


问:
How to get text in angle brackets with lxml or bs
I want to extract text in angle brackets like:

```<code><p><verb></p>
</code>```

The result should be <verb>.

lxml and bs4 don't work on this situation and it seems they take <verb> as a html tag. They cannot parse the text from the angle brackets, and just return empty string.

So, any solutions? THX!

答:
How about this?

```<code>import re
my_str = "<p><verb></p>"
my_new_string = re.sub('[\<p\>|\<\/p\>]', '', my_str)
print my_new_string
</code>```

output: verb

Body:
I want to extract text in angle brackets like:

<verb>

The result should be <verb>.

lxml and bs4 don't work on this situation and it seems they take <verb> as a html tag. They cannot parse the text from the angle brackets, and just return empty string.

So, any solutions? THX!

Body:
How about this?

import re
my_str = "<p><verb></p>"
my_new_string = re.sub('[\<p\>|\<\/p\>]', '', my_str)
print my_new_string

output: verb


问:
How do I capture the yield value of a Redux-Saga `call` function?
I have a very simple function that returns an object:

```<code>export const fetchThing = (thingId) => ({
  description: "hi",
  thing: thingId
})
</code>```

I'll later expand this function to perform an async action but I'm trying to keep things simple to start with.

Using Redux-Saga I'm attempting to do the following:

```<code>export function* requestThingSaga({payload}) {
  const thing = yield call(fetchThing, payload.thingId)
  console.log(thing);
}
</code>```

But when I test the saga, I find that fetchThing is not called:

```<code>gen = requestThingSaga({payload: {thingId: 1 });
gen.next() // logs 'undefined'
</code>```

I can't understand what's going on. The docs for call say that a function with a normal return value can be used. I can't see why this wouldn't work. Any ideas?

答:
The whole point of redux-saga is about making effects "declarative". So you need an interpreter that will handle those effects. ReduxSaga middleware acts as such an interpreter that does actuall calls, awaiting promises etc. Otherwise it is just a declaration that (in this case) you want to call external function. So your test is kinda "testing effect interpreter" that only asserts something about which effect your saga returns w/o actually doing something "real".

```<code>gen = requestThingSaga({payload: {thingId: 1 });

// test by inspecting .value w/o actuall call
gen.next().value.should.be.deep.equal(call(fetchThing, 1))

// "interprete" call effect by passing a value back
gen.next({description: 'hi', thing: 1})
</code>```

BTW gen should be better named iter :) because it is Iterator not Generator.

Body:
I have a very simple function that returns an object:

export const fetchThing = (thingId) => ({
  description: "hi",
  thing: thingId
})

I'll later expand this function to perform an async action but I'm trying to keep things simple to start with.

Using Redux-Saga I'm attempting to do the following:

export function* requestThingSaga({payload}) {
  const thing = yield call(fetchThing, payload.thingId)
  console.log(thing);
}

But when I test the saga, I find that fetchThing is not called:

gen = requestThingSaga({payload: {thingId: 1 });
gen.next() // logs 'undefined'

I can't understand what's going on. The docs for call say that a function with a normal return value can be used. I can't see why this wouldn't work. Any ideas?

Body:
The whole point of redux-saga is about making effects "declarative". So you need an interpreter that will handle those effects. ReduxSaga middleware acts as such an interpreter that does actuall calls, awaiting promises etc. Otherwise it is just a declaration that (in this case) you want to call external function. So your test is kinda "testing effect interpreter" that only asserts something about which effect your saga returns w/o actually doing something "real".

gen = requestThingSaga({payload: {thingId: 1 });

// test by inspecting .value w/o actuall call
gen.next().value.should.be.deep.equal(call(fetchThing, 1))

// "interprete" call effect by passing a value back
gen.next({description: 'hi', thing: 1})

BTW gen should be better named iter :) because it is Iterator not Generator.


问:
Java Base64 MIME decoding/encoding throws away delimiters
I have a Base64-encoded string that looks like "data:image/png;base64,iVBORw0K". I'm trying to decode it back to binary and later encode it again into Base64 using java.util.Base64. Strangely, after decoding and encoding again, I would lose the delimiters and get back "dataimage/pngbase64iVBORw0I=".

This is how I do the decoding and encoding (written in Scala, but you get the idea):

```<code>import java.util.Base64

val b64mime = "data:image/png;base64,iVBORw0K"

val decoder = Base64.getMimeDecoder
val encoder = Base64.getMimeEncoder

println(encoder.encodeToString(decoder.decode(b64mime)))
</code>```

Here is an example: https://scalafiddle.io/sf/TJY7eeg/0

This also happens with javax.xml.bind.DatatypeConverter. What am I doing wrong? Is this the expected behavior?

答:
The string you are trying to deal with looks like an example of a "data:" URL as specified in RFC 2397

The correct way to deal with one of these is parse it into its components, and then decode only the component that is base64 encoded.  Here is the syntax

```<code>   dataurl    := "data:" [ mediatype ] [ ";base64" ] "," data
   mediatype  := [ type "/" subtype ] *( ";" parameter )
   data       := *urlchar
   parameter  := attribute "=" value
</code>```

So this says that everything up to the comma in your example is non-base64 data.  You cannot simply treat the whole string as base64 because it contains characters that are not valid in any standard variant of the base64 encoding scheme.

This Q&A talks about RFC 2397 parsers in Java:

Any RFC 2397 Data URI Parser for Java?

Body:
I have a Base64-encoded string that looks like "data:image/png;base64,iVBORw0K". I'm trying to decode it back to binary and later encode it again into Base64 using java.util.Base64. Strangely, after decoding and encoding again, I would lose the delimiters and get back "dataimage/pngbase64iVBORw0I=".

This is how I do the decoding and encoding (written in Scala, but you get the idea):

import java.util.Base64

val b64mime = "data:image/png;base64,iVBORw0K"

val decoder = Base64.getMimeDecoder
val encoder = Base64.getMimeEncoder

println(encoder.encodeToString(decoder.decode(b64mime)))

Here is an example: https://scalafiddle.io/sf/TJY7eeg/0

This also happens with javax.xml.bind.DatatypeConverter. What am I doing wrong? Is this the expected behavior?

Body:
The string you are trying to deal with looks like an example of a "data:" URL as specified in RFC 2397

The correct way to deal with one of these is parse it into its components, and then decode only the component that is base64 encoded.  Here is the syntax

   dataurl    := "data:" [ mediatype ] [ ";base64" ] "," data
   mediatype  := [ type "/" subtype ] *( ";" parameter )
   data       := *urlchar
   parameter  := attribute "=" value

So this says that everything up to the comma in your example is non-base64 data.  You cannot simply treat the whole string as base64 because it contains characters that are not valid in any standard variant of the base64 encoding scheme.

This Q&A talks about RFC 2397 parsers in Java:

Any RFC 2397 Data URI Parser for Java?


问:
Run Groovy Scripts in IntelliJ fails
I can't run or debug Groovy scripts in IntelliJ. I'm getting the error: Error: Could not find or load main class org.codehaus.groovy.tools.GroovyStarter. Running scripts from cmd works propertly (I'm using groovyc and groovy command).

```<code>import org.apache.pdfbox.pdmodel.PDDocument
import org.fit.pdfdom.PDFDomTree
import org.w3c.dom.Document

// load the PDF file using PDFBox
PDDocument pdf = PDDocument.load(new java.io.File("file.pdf"))
// create the DOM parser
PDFDomTree parser = new PDFDomTree()
// parse the file and get the DOM Document
Document dom = parser.createDOM(pdf)
</code>```

答:
Try to create you script not as Groovy class.
Use this way:</p>

```<code>Ctrl + Shift + A  -> Groovy Script  -> Set script name
</code>```

Title: Run Groovy Scripts in IntelliJ fails

Body:
I can't run or debug Groovy scripts in IntelliJ. I'm getting the error: Error: Could not find or load main class org.codehaus.groovy.tools.GroovyStarter. Running scripts from cmd works propertly (I'm using groovyc and groovy command).

import org.apache.pdfbox.pdmodel.PDDocument
import org.fit.pdfdom.PDFDomTree
import org.w3c.dom.Document

// load the PDF file using PDFBox
PDDocument pdf = PDDocument.load(new java.io.File("file.pdf"))
// create the DOM parser
PDFDomTree parser = new PDFDomTree()
// parse the file and get the DOM Document
Document dom = parser.createDOM(pdf)

Body:
Try to create you script not as Groovy class.
Use this way:

Ctrl + Shift + A  -> Groovy Script  -> Set script name


问:
Can't call method "capture2" on unblessed reference
```<code>if($var ==1){
    function($host);}
#OTHER PROCESSING
#***
#****
# ****
$hostForSsh =$host;
my $whatever ="xyz"
my $something= $ssh->capture2(qq(/user/somePlace $whatever) );#--line A
</code>```

The function above runs perfectly when value of $var passed is 1 but gives
Can't call method "capture2" on unblessed reference -->error on line A if $var =0.

答: Solved! Problem was in $ssh only! Actually, I forgot to pass the $ssh object in the particular function and i did not notice this as many arguments were being passed to the function.</p>

Body:
if($var ==1){
    function($host);}
#OTHER PROCESSING
#***
#****
# ****
$hostForSsh =$host;
my $whatever ="xyz"
my $something= $ssh->capture2(qq(/user/somePlace $whatever) );#--line A

The function above runs perfectly when value of $var passed is 1 but gives
Can't call method "capture2" on unblessed reference -->error on line A if $var =0.


问:
Ruby on Rails: Anything selected with 'joins' is readonly
So we're having some difficulty with the readonly? method in activerecord classes. It appears that anything fetched with a call to joins is being set to readonly and throws this error

```<code>ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord
</code>```

For instance:

```<code># fine
User.first.readonly?
User.first.save
# not fine
User.joins(:memberships).first.readonly?
# false
User.joins(:memberships).first.save
# ActiveRecord::ReadOnlyRecord
</code>```

According to the Rails documentation this will be set to false for "Records loaded through joins with piggy-back attributes."

As far as I'm aware, we're not including any piggy-back attributes here.

I can forcibly circumvent this restriction, but it feels like I'm hacking through the system unnecessarily.

```<code>user = User.joins(:memberships).first
User.instance_variable_set(:@readonly, false)
user.save
</code>```

Does anyone know why joins is returning readonly items? Can I prevent this? (I'm not trying to select any attributes from related objects).

I'm using Ruby on Rails version 3.2.22.5, It looks like this has been a change in behavior from an earlier version of Rails 3.

答:
Try using includes instead of joins, it's better and faster.

```<code>User.includes(:memberships).first
</code>```

Body:
So we're having some difficulty with the readonly? method in activerecord classes. It appears that anything fetched with a call to joins is being set to readonly and throws this error

ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord

For instance:

# fine
User.first.readonly?
User.first.save
# not fine
User.joins(:memberships).first.readonly?
# false
User.joins(:memberships).first.save
# ActiveRecord::ReadOnlyRecord

According to the Rails documentation this will be set to false for "Records loaded through joins with piggy-back attributes."

As far as I'm aware, we're not including any piggy-back attributes here.

I can forcibly circumvent this restriction, but it feels like I'm hacking through the system unnecessarily.

user = User.joins(:memberships).first
User.instance_variable_set(:@readonly, false)
user.save

Does anyone know why joins is returning readonly items? Can I prevent this? (I'm not trying to select any attributes from related objects).

I'm using Ruby on Rails version 3.2.22.5, It looks like this has been a change in behavior from an earlier version of Rails 3.

Body:
Try using includes instead of joins, it's better and faster.

User.includes(:memberships).first

ContentLicense: CC BY-SA 4.0


答:
You can simply obtain the shape of b like:

```<code>m,n = b.shape
</code>```

and then use slices to set the elements in a:

```<code>a[:m,:n] = b
</code>```

This generates:

```<code>>>> m,n = b.shape
>>> a[:m,:n] = b
>>> a
array([[1, 1, 1, 0],
       [1, 1, 1, 0],
       [0, 0, 0, 0]])
</code>```

In case a and b have the same but an arbitrary number of dimensions, we can use the following generator:

```<code>a[tuple(slice(mi) for mi in b.shape)] = b
</code>```

which results again in:

```<code>>>> a[tuple(slice(mi) for mi in b.shape)] = b
>>> a
array([[1, 1, 1, 0],
       [1, 1, 1, 0],
       [0, 0, 0, 0]])
</code>```

But this will also work for 3d, 4d, ... arrays.

Title: How to assign from a source array being a subset of the destination array?

Body:
You can simply obtain the shape of b like:

m,n = b.shape

and then use slices to set the elements in a:

a[:m,:n] = b

This generates:

>>> m,n = b.shape
>>> a[:m,:n] = b
>>> a
array([[1, 1, 1, 0],
       [1, 1, 1, 0],
       [0, 0, 0, 0]])

In case a and b have the same but an arbitrary number of dimensions, we can use the following generator:

a[tuple(slice(mi) for mi in b.shape)] = b

which results again in:

>>> a[tuple(slice(mi) for mi in b.shape)] = b
>>> a
array([[1, 1, 1, 0],
       [1, 1, 1, 0],
       [0, 0, 0, 0]])

But this will also work for 3d, 4d, ... arrays.


问:
CSS selectors for inner grid lines with variable items
I have a list view of data displayed as cards and I'm trying to get to a pure CSS solution where I'll have only inner border lines.

The cards will display a max of two per row and will wrap to the next line when there are more. We're using bootstrap col-md-6 to achieve this.

Here's an example of three data items displayed as cards and what I'm trying to achieve with the inner grid lines.

Notes:

If there are only two items then the bottom line shouldn't be visible

I thought I could use adapt the technique mentioned here by Lea Verou, but I haven't been able to get it to work.

Regardless of how many items there are none of the outer borders should ever show. This is especially so with the last 1 or two items depending on the total count of items

Here's an example of the HTML markup for an individual list item:

```<code><div class="col-md-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <a class="btn btn-link"><span class="glyphicon glyphicon-pencil"></span> edit</a>
        <a class="btn btn-link><span class="glyphicon glyphicon-remove"></span> delete</a>
    </div>
</div>
</code>```

I know to get the middle line I can use:
.col-md-6:nth-child(odd){
    border-right:1px solid gray;
}

The problem comes in with the bottom border, i.e. if you have a total of three data items then only the last one should have its bottom border set to 'none'. If there are four then the last two would need their bottom borders set to 'none'.

What's the best approach to getting this to work without the use of tables?

答:
Put a common class in every card. Here I assumed it as card

```<code>.card:nth-child(odd){
  border-right: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}
.card:nth-child(even){
  border-bottom: 1px solid #ddd;
}
</code>```

Body:
I have a list view of data displayed as cards and I'm trying to get to a pure CSS solution where I'll have only inner border lines.

The cards will display a max of two per row and will wrap to the next line when there are more. We're using bootstrap col-md-6 to achieve this.

Here's an example of three data items displayed as cards and what I'm trying to achieve with the inner grid lines.

Notes:

If there are only two items then the bottom line shouldn't be visible

I thought I could use adapt the technique mentioned here by Lea Verou, but I haven't been able to get it to work.

Regardless of how many items there are none of the outer borders should ever show. This is especially so with the last 1 or two items depending on the total count of items

Here's an example of the HTML markup for an individual list item:

        Name

Fund

        Tax Rate

1

        Amount

10

         edit
         delete

I know to get the middle line I can use:
.col-md-6:nth-child(odd){
    border-right:1px solid gray;
}

The problem comes in with the bottom border, i.e. if you have a total of three data items then only the last one should have its bottom border set to 'none'. If there are four then the last two would need their bottom borders set to 'none'.

What's the best approach to getting this to work without the use of tables?

Body:
Put a common class in every card. Here I assumed it as card

.card:nth-child(odd){
  border-right: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}
.card:nth-child(even){
  border-bottom: 1px solid #ddd;
}


问:
Retrieving the MethodInfo of of the correct overload of a generic method
I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func<T> parameter) using reflection. The problem however is that I can't find the correct parameter type to supply the Type.GetMethod(string, Type[]) method with.

Here is my class definition:

```<code>public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}
</code>```

And this is what I've come up with, unfortunately without succes:

```<code>[TestMethod]
public void Test1()
{
    Type parameterType = typeof(Func<>);

    var method = typeof(Foo).GetMethod("Bar", new Type[] { parameterType });

    Assert.IsNotNull(method); // Fails
}
</code>```

How can I get the MethodInfo of a generic method of which I know the parameters?

答:
I don't think you can do this directly using GetMethod. I suspect you'll have to iterate over all the methods called Bar, then:

Check that the method has one type parameter

Check that the method has one normal parameter

Use the type parameter to make a Func<T> (with typeof(Func<>).MakeGenericType) and check that the parameter type matches that.

LINQ is good for this sort of thing. Complete sample:

```<code>using System;
using System.Reflection;
using System.Linq;

public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}

class Test
{
    static void Main()
    {
        var methods = from method in typeof(Foo).GetMethods()
                      where method.Name == "Bar"
                      let typeArgs = method.GetGenericArguments()
                      where typeArgs.Length == 1
                      let parameters = method.GetParameters()
                      where parameters.Length == 1
                      where parameters[0].ParameterType ==
                            typeof(Func<>).MakeGenericType(typeArgs[0])
                      select method;

        Console.WriteLine("Matching methods...");
        foreach (var method in methods)
        {
            Console.WriteLine(method);
        }
    }
}
</code>```

Basically generics and reflection are really nasty in combination, I'm afraid :(

Body:
I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func<T> parameter) using reflection. The problem however is that I can't find the correct parameter type to supply the Type.GetMethod(string, Type[]) method with.

Here is my class definition:

public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}

And this is what I've come up with, unfortunately without succes:

[TestMethod]
public void Test1()
{
    Type parameterType = typeof(Func<>);

    var method = typeof(Foo).GetMethod("Bar", new Type[] { parameterType });

    Assert.IsNotNull(method); // Fails
}

How can I get the MethodInfo of a generic method of which I know the parameters?

Body:
I don't think you can do this directly using GetMethod. I suspect you'll have to iterate over all the methods called Bar, then:

Check that the method has one type parameter

Check that the method has one normal parameter

Use the type parameter to make a Func<T> (with typeof(Func<>).MakeGenericType) and check that the parameter type matches that.

LINQ is good for this sort of thing. Complete sample:

using System;
using System.Reflection;
using System.Linq;

public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}

class Test
{
    static void Main()
    {
        var methods = from method in typeof(Foo).GetMethods()
                      where method.Name == "Bar"
                      let typeArgs = method.GetGenericArguments()
                      where typeArgs.Length == 1
                      let parameters = method.GetParameters()
                      where parameters.Length == 1
                      where parameters[0].ParameterType ==
                            typeof(Func<>).MakeGenericType(typeArgs[0])
                      select method;

        Console.WriteLine("Matching methods...");
        foreach (var method in methods)
        {
            Console.WriteLine(method);
        }
    }
}

Basically generics and reflection are really nasty in combination, I'm afraid :(


问:
sqlsrv_connect not working with instance
I am trying to connect Mssql Server with Instance Name from PHP7 .My operating system Ubuntu 16.04 LTS. I connected different Mssql Server without Instance name on Ubuntu .I tested Mssql Server with Instance with Heidi Sql over another windows7 .It is working.

PHP Page::

```<code>$serverName = "10.10.0.1/Instance";
$connectionInfo = array( "Database"=>"Dbname", "UID"=>"user", "PWD"=>"pass");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
</code>```

答: I solved from MSSQL server side. In SQL-Server-Configuration-Manager > SQL-Server-Network-Configuration>Protocol-Name(TCP/IP) . TCP/IP status needs to be Enabled. And open Properties > IP Addresses > IP All > TCP Port needs to be 1433.

Body:
I am trying to connect Mssql Server with Instance Name from PHP7 .My operating system Ubuntu 16.04 LTS. I connected different Mssql Server without Instance name on Ubuntu .I tested Mssql Server with Instance with Heidi Sql over another windows7 .It is working.

PHP Page::

$serverName = "10.10.0.1/Instance";
$connectionInfo = array( "Database"=>"Dbname", "UID"=>"user", "PWD"=>"pass");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.
";
}else{
     echo "Connection could not be established.
";
     die( print_r( sqlsrv_errors(), true));
}


问:
Facebook Login not working in IOS SDK
I am struggling with the issue of Facebook login, Yesterday Facebook login working correctly but today when I run my app it's not working don't know why, why it's not working suddenly I already configured all things related to Facebook login in Facebook develop console everything is configured
Please help me out if you have any idea, I already enable Keychain sharing also.

Code for Facebook Login

```<code>@IBAction func onClickFacebookLoginAction(_ sender: Any) {

    var message = String()
    if Reachability.isConnectedToNetwork() == true{

        let loginView:FBSDKLoginManager = FBSDKLoginManager()
        loginView.loginBehavior = FBSDKLoginBehavior.web
        loginView.logIn(withReadPermissions: ["email","public_profile","user_friends"], from: self, handler: { (result, error) in
            if(error != nil){

                print("Error while try to login with facebook-\(error?.localizedDescription)")
            }else if (result?.isCancelled)!{

                print("User cancel the facebook login")
            }else{

                if result?.grantedPermissions != nil{
                    if (result?.grantedPermissions .contains("email"))!{
                        self.ShowProgressHUD()
                        self.fetchUserInfo()
                    }else{
                        message = message.appending("Facebook email permission error")
                        self.showAlertMessage(message: message, title: "")
                    }
                }
            }
        })
    }
}

func fetchUserInfo() -> Void {

    if (FBSDKAccessToken.current() != nil) {

        let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/me", parameters:["fields": "id, first_name, last_name, name, email, picture"])
        graphRequest.start(completionHandler: { (connection, result, error) in

            if(error != nil){

                self.showAlertMessage(message: (error?.localizedDescription)!, title: "")

            }
            else
            {
                 print("Result is:\(result)")
                self.dictionary = result as! [String : AnyObject]
                let name = self.dictionary["name"] as!String
                let email = self.dictionary["email"] as! String
                let token = FBSDKAccessToken.current().tokenString

                print("name is -\(name)")
                print("email is -\(email)")
                print("token is -\(token)")

                DispatchQueue.main.async {

                    let SelectionViewObj = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
                    self.navigationController?.pushViewController(SelectionViewObj, animated: true)
                }
            }
        })
    }
}
</code>```

答:
This is how I used to log in with Facebook,

```<code>@IBAction func act_loginFB(_ sender: UIButton) {
    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.logIn(withReadPermissions: ["public_profile", "email",], from: self) { (result, error) -> Void in
        if (error == nil){
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if(fbloginresult.grantedPermissions.contains("email"))
            {
                self.getFBUserData()
            }
        }
    }
}

func getFBUserData(){
    if((FBSDKAccessToken.current()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){
                //everything works print the user data
                print(result)
                let data: [String:AnyObject] = (result as? [String : AnyObject])!
                print(data)
                let email: String = data["email"]! as! String
                print(email)
            }
        })
    }
}
</code>```

Check you added the correct FacebookAppID and FacebookDisplayName in the info.plist

Title: Facebook Login not working in IOS SDK

Body:
I am struggling with the issue of Facebook login, Yesterday Facebook login working correctly but today when I run my app it's not working don't know why, why it's not working suddenly I already configured all things related to Facebook login in Facebook develop console everything is configured
Please help me out if you have any idea, I already enable Keychain sharing also.

Code for Facebook Login

@IBAction func onClickFacebookLoginAction(_ sender: Any) {

    var message = String()
    if Reachability.isConnectedToNetwork() == true{

        let loginView:FBSDKLoginManager = FBSDKLoginManager()
        loginView.loginBehavior = FBSDKLoginBehavior.web
        loginView.logIn(withReadPermissions: ["email","public_profile","user_friends"], from: self, handler: { (result, error) in
            if(error != nil){

                print("Error while try to login with facebook-\(error?.localizedDescription)")
            }else if (result?.isCancelled)!{

                print("User cancel the facebook login")
            }else{

                if result?.grantedPermissions != nil{
                    if (result?.grantedPermissions .contains("email"))!{
                        self.ShowProgressHUD()
                        self.fetchUserInfo()
                    }else{
                        message = message.appending("Facebook email permission error")
                        self.showAlertMessage(message: message, title: "")
                    }
                }
            }
        })
    }
}

func fetchUserInfo() -> Void {

    if (FBSDKAccessToken.current() != nil) {

        let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/me", parameters:["fields": "id, first_name, last_name, name, email, picture"])
        graphRequest.start(completionHandler: { (connection, result, error) in

            if(error != nil){

                self.showAlertMessage(message: (error?.localizedDescription)!, title: "")

            }
            else
            {
                 print("Result is:\(result)")
                self.dictionary = result as! [String : AnyObject]
                let name = self.dictionary["name"] as!String
                let email = self.dictionary["email"] as! String
                let token = FBSDKAccessToken.current().tokenString

                print("name is -\(name)")
                print("email is -\(email)")
                print("token is -\(token)")

                DispatchQueue.main.async {

                    let SelectionViewObj = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
                    self.navigationController?.pushViewController(SelectionViewObj, animated: true)
                }
            }
        })
    }
}

Body:
This is how I used to log in with Facebook,

@IBAction func act_loginFB(_ sender: UIButton) {
    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.logIn(withReadPermissions: ["public_profile", "email",], from: self) { (result, error) -> Void in
        if (error == nil){
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if(fbloginresult.grantedPermissions.contains("email"))
            {
                self.getFBUserData()
            }
        }
    }
}

func getFBUserData(){
    if((FBSDKAccessToken.current()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){
                //everything works print the user data
                print(result)
                let data: [String:AnyObject] = (result as? [String : AnyObject])!
                print(data)
                let email: String = data["email"]! as! String
                print(email)
            }
        })
    }
}

Check you added the correct FacebookAppID and FacebookDisplayName in the info.plist


问:
Nesting routes and dynamically routing in React-router v4
I have following routing configuration:

```<code>return (<div>
        <Router>
          <div>

            <Route path='/login' component={LoginPage}/>
            <EnsureLoggedInContainer>
              <Route path='/abc' component={abc} />
            </EnsureLoggedInContainer>
          </div>
        </Router>
      </div>
);
</code>```

The EnsureLoggedInContainer is:

```<code>import React from 'react';
import { connect } from "react-redux";

class EnsureLoggedInContainer extends React.Component
{
    componentDidMount() {
        if ( !this.props.isLoggedIn )
        {
            // this.props.history.push('/login');
            this.context.router.push('/contact');

        }
    }

    render() {
        // console.log(this.props);
        if ( this.props.isLoggedIn )
        {
            return this.props.children;
        }
        else
        {
            return null;
        }
    }

}
const mapStateToProps = (state,ownProps) => {
    return{
        isLoggedIn : state.isLoggedIn,
        // currentURL : this.props
    }
}

export default connect(mapStateToProps)(EnsureLoggedInContainer);
</code>```

But, the history push: this.props.history.push('/login'); isn't working. Here history is not present.

If I am using a configuration like this:

```<code><Route component={EnsureLoggedInContainer}>
              <Route path='/myjs' component={MyjsPage} />
            </Route>
</code>```

I am getting issue like:

```<code>Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored
</code>```

What's the best way of authentication in reactjs?

答:
From what I can see of your React Router Design, you seem to be using React router version 4

In that case you can specify the route in the Component Itself, and make use of withRouter to do a dynamic redirect like

```<code>return (<div>
        <Router>
          <div>

            <Route path='/login' component={LoginPage}/>
            <EnsureLoggedInContainer/>
          </div>
        </Router>
      </div>
);
</code>```

and

```<code>import React from 'react';
import { connect } from "react-redux";
import {withRouter} from "react-router";

class EnsureLoggedInContainer extends React.Component
{
    componentDidMount() {
        if ( !this.props.isLoggedIn )
        {
            this.props.history.push('/login');

        }
    }

    render() {
        // console.log(this.props);
        if ( this.props.isLoggedIn )
        {
            return <Route path='/abc' component={abc} />
        }
        else
        {
            return null;
        }
    }

}
const mapStateToProps = (state,ownProps) => {
    return{
        isLoggedIn : state.isLoggedIn,
        // currentURL : this.props
    }
}

export default connect(mapStateToProps)(withRouter(EnsureLoggedInContainer));
</code>```

Body:
I have following routing configuration:

return (

        <Router>

            <Route path='/login' component={LoginPage}/>
            <EnsureLoggedInContainer>
              <Route path='/abc' component={abc} />
            </EnsureLoggedInContainer>

        </Router>

);

The EnsureLoggedInContainer is:

import React from 'react';
import { connect } from "react-redux";

class EnsureLoggedInContainer extends React.Component
{
    componentDidMount() {
        if ( !this.props.isLoggedIn )
        {
            // this.props.history.push('/login');
            this.context.router.push('/contact');

        }
    }

    render() {
        // console.log(this.props);
        if ( this.props.isLoggedIn )
        {
            return this.props.children;
        }
        else
        {
            return null;
        }
    }

}
const mapStateToProps = (state,ownProps) => {
    return{
        isLoggedIn : state.isLoggedIn,
        // currentURL : this.props
    }
}

export default connect(mapStateToProps)(EnsureLoggedInContainer);

But, the history push: this.props.history.push('/login'); isn't working. Here history is not present.

If I am using a configuration like this:

<Route component={EnsureLoggedInContainer}>
              <Route path='/myjs' component={MyjsPage} />
            </Route>

I am getting issue like:

Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

What's the best way of authentication in reactjs?

Body:
From what I can see of your React Router Design, you seem to be using React router version 4

In that case you can specify the route in the Component Itself, and make use of withRouter to do a dynamic redirect like

return (<div>
        <Router>
          <div>

            <Route path='/login' component={LoginPage}/>
            <EnsureLoggedInContainer/>
          </div>
        </Router>
      </div>
);

and

import React from 'react';
import { connect } from "react-redux";
import {withRouter} from "react-router";

class EnsureLoggedInContainer extends React.Component
{
    componentDidMount() {
        if ( !this.props.isLoggedIn )
        {
            this.props.history.push('/login');

        }
    }

    render() {
        // console.log(this.props);
        if ( this.props.isLoggedIn )
        {
            return <Route path='/abc' component={abc} />
        }
        else
        {
            return null;
        }
    }

}
const mapStateToProps = (state,ownProps) => {
    return{
        isLoggedIn : state.isLoggedIn,
        // currentURL : this.props
    }
}

export default connect(mapStateToProps)(withRouter(EnsureLoggedInContainer));