问:
angularJs sorting code doesn't work
I totally cant understand, why my sorting code doesn't work.
I want just add a sorting method "sortFlag" to my app, and it doesn't work in a right way.

Here is code:

```<code>var App2 = angular.module('App2',[
    //submodules
]);

    App2.controller('MainController', ['$scope', '$http', function($scope, $http){
        $http.get('https://api.myjson.com/bins/14fug5')
        .success(function(datas){
            $scope.datas_1 = datas
            console.log($scope.datas_1.schema);

        });
        $http.get('https://api.myjson.com/bins/q80it')
        .success(function(datas){
            $scope.datas_2 = datas
        });

        // $scope.predicate = '';
        // $scope.reverse = true;
        // $scope.order = function(predicate) {
        //     $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
        //     $scope.predicate = predicate;
        // };

        $scope.sortFlag = 'id';
        $scope.sortTable = function(flag){
            $scope.sortFlag = flag;
        }

    }]);
</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>angular example 2</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">

    <form>

                <input type="text" class="form-control" placeholder="Search" ng-model="searchFish">

    </form>

    выберите данные:
    данные1
    <input
        name="content"
        type="radio"
        ng-model="content"
        ng-init="content='first'"
        value="first"
    />
    данные2
    <input
        name="content"
        type="radio"
        ng-model="content"
        value="second"
    />

            <button href="#"
                    ng-click="sortTable('{{key}}')">

                {{value}}
            </button>

        {{data.id}}
        {{data.name}}
        {{data.price}}
        {{data.quantity}}

            <button href="#" ng-click="order('{{key}}')">{{value}}</button>

        {{data.id}}
        {{data.name}}
        {{data.price}}
        {{data.quantity}}

```

if you have any idea, please help me with this stuff.

答:
I am not sure that the orderBy can take a scope variable to use a sorting field. You should use a function instead.

controller :

```<code>$scope.dynamicOrderFunction = function() {
    return '-' + $scope.sortFlag;
}
</code>```

You can change the - sign with a plus sign depending on the direction of your sorting.

template:

```<code><tr ng-repeat="data in datas_2.data | orderBy: dynamicOrderFunction">
    <td>{{data.id}}</td>
    <td>{{data.name}}</td>
    <td>{{data.price}}</td>
    <td>{{data.quantity}}</td>
</tr>
</code>```

Title: angularJs sorting code doesn't work

Body:
I totally cant understand, why my sorting code doesn't work.
I want just add a sorting method "sortFlag" to my app, and it doesn't work in a right way.

Here is code:

var App2 = angular.module('App2',[
    //submodules
]);

    App2.controller('MainController', ['$scope', '$http', function($scope, $http){
        $http.get('https://api.myjson.com/bins/14fug5')
        .success(function(datas){
            $scope.datas_1 = datas
            console.log($scope.datas_1.schema);

        });
        $http.get('https://api.myjson.com/bins/q80it')
        .success(function(datas){
            $scope.datas_2 = datas
        });

        // $scope.predicate = '';
        // $scope.reverse = true;
        // $scope.order = function(predicate) {
        //     $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
        //     $scope.predicate = predicate;
        // };

        $scope.sortFlag = 'id';
        $scope.sortTable = function(flag){
            $scope.sortFlag = flag;
        }

    }]);

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>angular example 2</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">

    <form>

                <input type="text" class="form-control" placeholder="Search" ng-model="searchFish">

    </form>

    выберите данные:
    данные1
    <input
        name="content"
        type="radio"
        ng-model="content"
        ng-init="content='first'"
        value="first"
    />
    данные2
    <input
        name="content"
        type="radio"
        ng-model="content"
        value="second"
    />

            <button href="#"
                    ng-click="sortTable('{{key}}')">

                {{value}}
            </button>

        {{data.id}}
        {{data.name}}
        {{data.price}}
        {{data.quantity}}

            <button href="#" ng-click="order('{{key}}')">{{value}}</button>

        {{data.id}}
        {{data.name}}
        {{data.price}}
        {{data.quantity}}

if you have any idea, please help me with this stuff.

Body:
I am not sure that the orderBy can take a scope variable to use a sorting field. You should use a function instead.

controller :

$scope.dynamicOrderFunction = function() {
    return '-' + $scope.sortFlag;
}

You can change the - sign with a plus sign depending on the direction of your sorting.

template:

<tr ng-repeat="data in datas_2.data | orderBy: dynamicOrderFunction">
    <td>{{data.id}}</td>
    <td>{{data.name}}</td>
    <td>{{data.price}}</td>
    <td>{{data.quantity}}</td>
</tr>


来源: stackexchange

问:
Android onListItemClick after disconecting udb does not work
story:
I have todo list app with 2 fragments.
In landscape I can see both fragments (list and details).
When i push on list item display fragments is showing its details.
This works when phone is connected with usb to pc or in wifi debbuging.

Problem starts when disconnecting phone from usb.
When I run app on phone, onListItemClick method is not switching details fragment.
How can I see where is the problem if I can not debug it?

Here is that method:

```<code>@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    TodoItem todoItem = (TodoItem) l.getAdapter().getItem(position);
    showDetails(todoItem.getId());
}
</code>```

P.S. Portrait mode working fine.

Maybe You guys have some ideas...

答: ok, found out that problem was in bundle, it was not initialized correctly.</p>

ContentLicense: CC BY-SA 3.0

Body:
story:
I have todo list app with 2 fragments.
In landscape I can see both fragments (list and details).
When i push on list item display fragments is showing its details.
This works when phone is connected with usb to pc or in wifi debbuging.

Problem starts when disconnecting phone from usb.
When I run app on phone, onListItemClick method is not switching details fragment.
How can I see where is the problem if I can not debug it?

Here is that method:

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    TodoItem todoItem = (TodoItem) l.getAdapter().getItem(position);
    showDetails(todoItem.getId());
}

P.S. Portrait mode working fine.

Maybe You guys have some ideas...


问:
Prevent robots from coping images from a website
I have a website created in PHP technology and i want to prevent robots from coping images from the website.What is the best way to prevent robots from coping images from a website?

Please make sure it doesn't harm SEO.
Please make sure this does not influence spyders and crawlers from indexing the site.

答:
As others have said, first tell bots they can't access the images with robots.txt if possible. Well-behaved bots will obey that.

Do a search for "prevent hotlinking". The standard method is to block requests to image files without a referrer within your domain, using a mod_rewrite rule. That'll stop most bots.

You can match the user-agent strings of hundreds of common crawlers using get_browser and a recent browscap.ini file. This is not commonly available on shared hosting, but if you read the comments in the manual, you should find a get_browsers implementation that you can run from your own code.

All of these will effect SEO since the major search engines all have image searches. It'll also effect the new Google Web Previews that show a screenshot of the webpage when hovering over a search result, since you'll be blocking the bot from seeing the images on your page when creating the screenshot.

ContentLicense: CC BY-SA 2.5


问:
Without using for each loop container in ssis , I have to dump one folder that contains several files in it
There is one folder that contains 4 csv files , I have to dump it to sql server without using foreach loop container. How to do that?</p>

答:
Easiest answer. Create a dataflow for each csv file.

My guess is that the files aren't the same if you aren't using a foreach.


问:
Remove quotes between letters
In golang, how can I remove quotes between two letters, like that:

```<code>import (
    "testing"
)

func TestRemoveQuotes(t *testing.T) {
    var a = "bus\"zipcode"
    var mockResult = "bus zipcode"
    a = RemoveQuotes(a)

    if a != mockResult {
        t.Error("Error or TestRemoveQuotes: ", a)
    }
}
</code>```

Function:

```<code>import (
    "fmt"
    "strings"
)

func RemoveQuotes(s string) string {
    s = strings.Replace(s, "\"", "", -1) //here I removed all quotes. I'd like to remove only quotes between letters

    fmt.Println(s)

    return s
}
</code>```

For example:

"bus"zipcode" = "bus zipcode"

答:
You may use a simple \b"\b regex that matches a double quote only when preceded and followed with word boundaries:

```<code>package main

import (
    "fmt"
    "regexp"
)

func main() {
    var a = "\"test1\",\"test2\",\"tes\"t3\""
    fmt.Println(RemoveQuotes(a))
}

func RemoveQuotes(s string) string {
    re := regexp.MustCompile(`\b"\b`)
    return re.ReplaceAllString(s, "")
}
</code>```

See the Go demo printing "test1","test2","test3".

Also, see the online regex demo.

Title: Remove quotes between letters

Body:
In golang, how can I remove quotes between two letters, like that:

import (
    "testing"
)

func TestRemoveQuotes(t *testing.T) {
    var a = "bus\"zipcode"
    var mockResult = "bus zipcode"
    a = RemoveQuotes(a)

    if a != mockResult {
        t.Error("Error or TestRemoveQuotes: ", a)
    }
}

Function:

import (
    "fmt"
    "strings"
)

func RemoveQuotes(s string) string {
    s = strings.Replace(s, "\"", "", -1) //here I removed all quotes. I'd like to remove only quotes between letters

    fmt.Println(s)

    return s
}

For example:

"bus"zipcode" = "bus zipcode"

Body:
You may use a simple \b"\b regex that matches a double quote only when preceded and followed with word boundaries:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    var a = "\"test1\",\"test2\",\"tes\"t3\""
    fmt.Println(RemoveQuotes(a))
}

func RemoveQuotes(s string) string {
    re := regexp.MustCompile(`\b"\b`)
    return re.ReplaceAllString(s, "")
}

See the Go demo printing "test1","test2","test3".

Also, see the online regex demo.


问:
jekyll page build failure
I'm new to web development, so please bear with me.

I'm trying to create a website for a group project using Github Pages, and I have forked this repository. I've made several changes, and the website was up and running. Today I updated some images and the website wouldn't build anymore. I tried reverting to the previous commit, but it wouldn't build either. I read the troubleshooting page, to no avail. I don't have any idea of what to do anymore, please help.

the error:

The page build failed with the following error:

Page build failed. For more information, see help[dot]github.com/articles/troubleshooting-github-pages-build-failures.

For information on troubleshooting Jekyll see:

help[dot]github.com/articles/troubleshooting-jekyll-builds

If you have any questions you can contact us by replying to this email.

I'm using the web interface of github (not ideal, I know). the repository is here.

答:
As you (and myself) discovered, GitHub suffered a major outage.

As a sidenote, all Jekyll pages require "Front Matter" if it's not included it won't build properly. It looks like below:

```<code>---
layout: Template
title: Web Development Page
---
</code>```

More info here: https://jekyllrb.com/docs/frontmatter/

Title: jekyll page build failure

Body:
As you (and myself) discovered, GitHub suffered a major outage.

As a sidenote, all Jekyll pages require "Front Matter" if it's not included it won't build properly. It looks like below:

---
layout: Template
title: Web Development Page
---

More info here: https://jekyllrb.com/docs/frontmatter/


问:
What logical Law is this?
p∧(~q∨s)⟺(~q∨s)∧p

What Logical law is being represented here? I think it is associative, but the q, and s should be swapped on the other end of the proposition to make that true so I'm stuck.

答:
That is called commutativity

```<code>a∧b = b∧a
</code>```

for logical expressions a,b.

Title: What logical Law is this?

Body:
That is called commutativity

a∧b = b∧a

for logical expressions a,b.


问:
Static variables in PHP
I have found different information regarding static variables in PHP but nothing that actually explains what it is and how it really works.

I have read that when used within a class that a static property cannot be used by any object instantiated by that class and that a static method can be used by an object instantiated by the class?

However, I have been trying to research what a static variable does within a function that is not in a class. Also, does a static variable within a function work somewhat like closure in javascript or am I totally off in this assumption?

答:
```<code>class Student {
static $total_student = 0;
static  function add_student(){
    return Student::$total_student++;
}
}
</code>```

First: for the add_student function, the best practice is to use static not public.
Second: in the add_student function, we are using Student::$total_student,not use $this->total_student. This is big different from normal variable.
Third:static variable are shared throughout the inheritance tree.

take below code to see what is the result:

```<code>class One {
static $foo ;
}
class Two extends One{}
class Three extends One{}
One::$foo = 1;
Two::$foo = 2;
Three::$foo = 3;
echo One::$foo;
echo Two::$foo;
echo Three::$foo;`
</code>```

Title: Static variables in PHP

Body:
class Student {
static $total_student = 0;
static  function add_student(){
    return Student::$total_student++;
}
}

First: for the add_student function, the best practice is to use static not public.
Second: in the add_student function, we are using Student::$total_student,not use $this->total_student. This is big different from normal variable.
Third:static variable are shared throughout the inheritance tree.

take below code to see what is the result:

class One {
static $foo ;
}
class Two extends One{}
class Three extends One{}
One::$foo = 1;
Two::$foo = 2;
Three::$foo = 3;
echo One::$foo;
echo Two::$foo;
echo Three::$foo;`


问:
Angular 2, C# MVC ApiController: Error on Get Request from C# Rest Api

i have problem with c# ApiController, i have some like this:

```<code>public class Heroes
{
    public int userId;
    public int id;
    public string title;
    public string body;
}

public class HeroesController : ApiController
{
    // ...

    // GET: api/Heroes/5
    public Heroes Get(int id)
    {
        Heroes u = new Heroes()
        {
            userId = 1, title = "some titile", body = "some body"
        };
        return u;
    }

    // ...
}

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Formatters.JsonFormatter.SupportedMediaTypes
            .Add(new MediaTypeHeaderValue("text/html"));

        config.Formatters.Remove(config.Formatters.XmlFormatter);
    }
}
</code>```

the result of Chrome extension Restlet Client is correctly (200 ok)

Request 'Get' is send on http://localhost:63854/api/Heroes/5

```<code>{
"userId": 1,
"id": 0,
"title": "some titile",
"body": "some body"
}
</code>```

but, when i send Get Request in angular i recive a error message

TypeError:
  WEBPACK_IMPORTED_MODULE_1_rxjs_Observable.Observable.throw is not a function

and (in angular) if i use outside rest api, some like this

https://jsonplaceholder.typicode.com/posts

its works correcty, retun result, and i don't have any error messages.

Where is mistakes in Rest Api in c# controller ?

I don't suspects that errors is on the angular side.

sorry for my bad English :c

答:
Try adding this import statement to the top of your client:</p>

```<code>import 'rxjs/add/observable/throw';
</code>```

Body:
i have problem with c# ApiController, i have some like this:

public class Heroes
{
    public int userId;
    public int id;
    public string title;
    public string body;
}

public class HeroesController : ApiController
{
    // ...

    // GET: api/Heroes/5
    public Heroes Get(int id)
    {
        Heroes u = new Heroes()
        {
            userId = 1, title = "some titile", body = "some body"
        };
        return u;
    }

    // ...
}

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Formatters.JsonFormatter.SupportedMediaTypes
            .Add(new MediaTypeHeaderValue("text/html"));

        config.Formatters.Remove(config.Formatters.XmlFormatter);
    }
}

the result of Chrome extension Restlet Client is correctly (200 ok)

Request 'Get' is send on http://localhost:63854/api/Heroes/5

{
"userId": 1,
"id": 0,
"title": "some titile",
"body": "some body"
}

but, when i send Get Request in angular i recive a error message

TypeError:
  WEBPACK_IMPORTED_MODULE_1_rxjs_Observable.Observable.throw is not a function

and (in angular) if i use outside rest api, some like this

https://jsonplaceholder.typicode.com/posts

its works correcty, retun result, and i don't have any error messages.

Where is mistakes in Rest Api in c# controller ?

I don't suspects that errors is on the angular side.

sorry for my bad English :c

Body:
Try adding this import statement to the top of your client:

import 'rxjs/add/observable/throw';


问:
Basic information about text editors and html output
I'm a brand-newbie to coding. I am looking for a text editor that displays HTML output (hopefully with troubleshooting error messages, like with compiled languages). Does that exist? Does Notepad ++ have this capability? </p>

<p>Also, if my question indicates that I am misunderstanding some basic significant aspect of the front-end design process, I am all ears. Please assume I know absolutely nothing about web development because I know absolutely nothing about web development. Thanks in advance. </p>

答: Note that text editors are not for displaying html output... The browser displays your html out. </p>

Body:
I'm a brand-newbie to coding. I am looking for a text editor that displays HTML output (hopefully with troubleshooting error messages, like with compiled languages). Does that exist? Does Notepad ++ have this capability?

Also, if my question indicates that I am misunderstanding some basic significant aspect of the front-end design process, I am all ears. Please assume I know absolutely nothing about web development because I know absolutely nothing about web development. Thanks in advance.


问:
How do I delete a specific row when I click a button using jquery?
I have a table of player data with a delete button next to each row.
When the button is clicked, it should delete that specific row instantly using jQuery. I have included my code thus far. I am really stuck when the button should be clicked. Should I use a header function?

index.php

```<code><!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/style.css"></link>
        <script src="js/jquery-1.11.3.min.js"></script>
        <script src="js/script.js"></script>
    </head>
<body>
    <!-- Create a table-->
    <table style width="800" border="1" cellpadding="1" cellspacing="1">
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <tr>
    <th>Player ID</th>
    <th>Player Name</th>
    <th>Player Position</th>
    <th>Delete</th>
    </tr>

    <?php
        require "php/conn.php";
        //Select query
        $res = $db -> query ("SELECT * FROM player");
        //Set pointer to 1
        $res -> data_seek(0);
        //Display data using while loop
        while ($row = $res -> fetch_assoc()) {
            // Write html code in php using this method
            echo "<div class = 'row'>";
            echo "<tr>";
            echo "<td>".$row['id']."</td>";
            echo "<td>".$row['surname']."</td>";
            echo "<td>".$row['position']."</td>";
            echo "<td><button id = 'dlt_btn' type='button'>Delete</button></td>";
            echo "</tr>";
            echo "</div>";

        }

    ?>

</body>
</code>```

script.js

```<code>$(document).ready(function () {

    $("#dlt_btn").click(function(){
        //Activate 'delete.php'
    });

});
</code>```

delete.php

```<code>?
</code>```

答:
index.php

```<code><!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/style.css"></link>
        <script src="js/jquery-1.11.3.min.js"></script>
        <script src="js/script.js"></script>
    </head>
<body>
    <!-- Create a table-->
    <table style width="800" border="1" cellpadding="1" cellspacing="1">
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <tr>
    <th>Player ID</th>
    <th>Player Name</th>
    <th>Player Position</th>
    <th>Delete</th>
    </tr>

    <?php
        require "php/conn.php";
        //Select query
        $res = $db -> query ("SELECT * FROM player");
        //Set pointer to 1
        $res -> data_seek(0);
        //Display data using while loop
        while ($row = $res -> fetch_assoc()) {
            // Write html code in php using this method
            echo "<div class = 'row'>";
            echo "<tr>";
            echo "<td>".$row['id']."</td>";
            $player_id = $row['id'];
            echo "<td>".$row['surname']."</td>";
            echo "<td>".$row['position']."</td>";
            echo "<td><button id = 'dlt_btn' value = ". $row['id'] . " type='button'>Delete</button></td>";
            echo "</tr>";
            echo "</div>";

        }

    ?>

</body>
</code>```

script.js

```<code>$(document).ready(function () {

    $("#dlt_btn").click(function () {
        // The '$.ajax' function is used to perform a asynchronous HTTP request
        $.ajax({
            url: 'delete.php',
            //The type of request to make, which can be either “POST” or “GET”
            type: 'post',
            //data: the data to be sent to the server when performing the Ajax request i.e. You are sending the 'id' of the friends_list to the 'likes.php' file.
            //'val' = returns or sets the value attribute of the #selected elements
            //$(selector).val() = Returns the value attribute
            //the 'id' refers to the 'id' variable in 'likes.php'
            //Follows a {key:value} format. E.g. id('KEY'): $("#id").val()} ('VALUE');
            //N.B! The key is the the field/column name in database, hence key = 'id'
            data: {id : $("#dlt_btn").val()},
            //success: A function to be called if the request succeeds
            success: function(result)
            {
                //Reload the current document:
                location.reload();
            }
        });
    });
});
</code>```

delete.php

```<code><?php
require "php/conn.php";
$player_id = $_POST['id'];

$stmt = $db -> prepare ("DELETE FROM player WHERE id = $player_id");
$stmt -> execute();

?>
</code>```

Body:
I have a table of player data with a delete button next to each row.
When the button is clicked, it should delete that specific row instantly using jQuery. I have included my code thus far. I am really stuck when the button should be clicked. Should I use a header function?

index.php

<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="css/style.css"></link>

    Player ID
    Player Name
    Player Position
    Delete

    <?php
        require "php/conn.php";
        //Select query
        $res = $db -> query ("SELECT * FROM player");
        //Set pointer to 1
        $res -> data_seek(0);
        //Display data using while loop
        while ($row = $res -> fetch_assoc()) {
            // Write html code in php using this method
            echo "
";
            echo "
";
            echo "".$row['id']."	";
            echo "".$row['surname']."	";
            echo "".$row['position']."	";
            echo "<button id = 'dlt_btn' type='button'>Delete</button>	";
            echo "
";
            echo "
";

        }

    ?>

script.js

$(document).ready(function () {

    $("#dlt_btn").click(function(){
        //Activate 'delete.php'
    });

});

delete.php

?

Body:
index.php

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/style.css"></link>
        <script src="js/jquery-1.11.3.min.js"></script>
        <script src="js/script.js"></script>
    </head>
<body>
    <!-- Create a table-->
    <table style width="800" border="1" cellpadding="1" cellspacing="1">
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <tr>
    <th>Player ID</th>
    <th>Player Name</th>
    <th>Player Position</th>
    <th>Delete</th>
    </tr>

    <?php
        require "php/conn.php";
        //Select query
        $res = $db -> query ("SELECT * FROM player");
        //Set pointer to 1
        $res -> data_seek(0);
        //Display data using while loop
        while ($row = $res -> fetch_assoc()) {
            // Write html code in php using this method
            echo "<div class = 'row'>";
            echo "<tr>";
            echo "<td>".$row['id']."</td>";
            $player_id = $row['id'];
            echo "<td>".$row['surname']."</td>";
            echo "<td>".$row['position']."</td>";
            echo "<td><button id = 'dlt_btn' value = ". $row['id'] . " type='button'>Delete</button></td>";
            echo "</tr>";
            echo "</div>";

        }

    ?>

</body>

script.js

$(document).ready(function () {

    $("#dlt_btn").click(function () {
        // The '$.ajax' function is used to perform a asynchronous HTTP request
        $.ajax({
            url: 'delete.php',
            //The type of request to make, which can be either “POST” or “GET”
            type: 'post',
            //data: the data to be sent to the server when performing the Ajax request i.e. You are sending the 'id' of the friends_list to the 'likes.php' file.
            //'val' = returns or sets the value attribute of the #selected elements
            //$(selector).val() = Returns the value attribute
            //the 'id' refers to the 'id' variable in 'likes.php'
            //Follows a {key:value} format. E.g. id('KEY'): $("#id").val()} ('VALUE');
            //N.B! The key is the the field/column name in database, hence key = 'id'
            data: {id : $("#dlt_btn").val()},
            //success: A function to be called if the request succeeds
            success: function(result)
            {
                //Reload the current document:
                location.reload();
            }
        });
    });
});

delete.php

<?php
require "php/conn.php";
$player_id = $_POST['id'];

$stmt = $db -> prepare ("DELETE FROM player WHERE id = $player_id");
$stmt -> execute();

?>


问:
Push Submodule to GitHub
I have a problem pushing all code to GitHub after installing a component using composer. Here's the current setup:

GitHub repository created.

Repository cloned on local and project files added.

There is one remote called "origin".

Component added using "composer require". Component installed successfully to project sub-folder.

Composer created a git submodule (in this sub-folder) with two remotes. (a) "origin" which points to the component author github url. (b) "composer" which points to the same url and does not have a push url.

Project pushed to GitHub successfully but does NOT push git submodule containing component files.

If I try to push component to project "origin" I get error "Updates were rejected because the remote contains work that you do not have locally".

How do I get this git submodule component code into my GitHub repo? The folder in GitHub is empty.

答:
Make sure you're properly added the files to the stage area and committed them. Then you could try to push again:

```<code>git add . #to add all files to stage
git commit -m "Your commit message here"
git push origin master #if master is your branch
</code>```

Once you've said that the repository in GitHub is empty, you could try a force push:

```<code>git push --force origin master
</code>```

Also, sometimes, there is a tiny delay between the push and the files become available in GitHub.

Additionally, you could verify if the changes were correctly sent to GitHub by checking the differences between branches:

```<code>git diff --name-status master..origin/master
</code>```

Title: Push Submodule to GitHub

Body:
Make sure you're properly added the files to the stage area and committed them. Then you could try to push again:

git add . #to add all files to stage
git commit -m "Your commit message here"
git push origin master #if master is your branch

Once you've said that the repository in GitHub is empty, you could try a force push:

git push --force origin master

Also, sometimes, there is a tiny delay between the push and the files become available in GitHub.

Additionally, you could verify if the changes were correctly sent to GitHub by checking the differences between branches:

git diff --name-status master..origin/master


问:
GWT including external javascript file from module's manifest
So I read the documentation about including an external Javascript file directly in the module manifest yourApplication.gwt.xml (http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html)

I have this javascript file called iscroll.js and stored in the war/ folder of the GWT project.

I added the line to the module's manifest of my GWT application:

```<code><script src="iscroll.js"/>
</code>```

Then from the onModuleLoad() method I call this native JSNI method:

```<code>private native void initJavascript() /*-{
  $wnd.myScroll = new iScroll('jokeWrapperLabel');
}-*/;
</code>```

Then when I run the code in the browser I keep getting "iScroll is undefined".

Any idea what am I doing wrong?

This is the output of the "iScroll is undefined error"

```<code>18:32:41.780 [ERROR] [jollyjokesprogwt] Unable to load module entry point class com.wanderlust.jollyjokespro.gwt.client.JollyJokesProGWT (see associated exception for details)
com.google.gwt.core.client.JavaScriptException: (ReferenceError): iScroll is not defined
 stack: ReferenceError: iScroll is not defined
    at [object Object].<anonymous> (unknown source)
    at __gwt_jsInvoke (http://127.0.0.1:8888/jollyjokesprogwt/hosted.html?jollyjokesprogwt:76:35)
    at http://127.0.0.1:8888/jollyjokesprogwt/hosted.html?jollyjokesprogwt:280:16
    at C (http://127.0.0.1:8888/jollyjokesprogwt/jollyjokesprogwt.nocache.js:2:148)
    at http://127.0.0.1:8888/jollyjokesprogwt/jollyjokesprogwt.nocache.js:8:593
 type: not_defined
 arguments: iScroll
 __gwt_ObjectId: 91
    at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:237)
    at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:126)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNativeVoid(ModuleSpace.java:289)
    at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeVoid(JavaScriptHost.java:107)
    at com.wanderlust.jollyjokespro.gwt.client.JollyJokesProGWT.initJavascript(JollyJokesProGWT.java)
    at com.wanderlust.jollyjokespro.gwt.client.JollyJokesProGWT.onModuleLoad(JollyJokesProGWT.java:228)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:396)
    at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:183)
    at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:510)
    at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:352)
    at java.lang.Thread.run(Unknown Source)
</code>```

答:
You need to place the JavaScript file in a public folder, see this stackoverflow answer on how that works: gwt and javascript files
and the call to iScroll(.. must be $wnd.iScroll(...


问:
How to sign URL Google Directions?
I have a function to retrieve Google Directions but I have a question about where to find the Google Crypto Key to sign my url. Where is this on the dashboard?

```<code>        public static void getDirections(Context context, String origin, String destination,
                                         final DirectionsListener listener)
                throws ExecutionException, InterruptedException {
            if (FrameworkUtils.isStringEmpty(origin) || FrameworkUtils.isStringEmpty(destination)) {
                return;
            }
            try {
                String url = String.format(GOOGLE_API_DIRECTIONS_URL, origin, destination,
                        ConfigurationManager.GOOGLE_CLIENT_KEY, KEY_TRAVEL_MODE_DRIVING);
                String signedUrl = UrlSigner.signURL(url);
                JsonRequest request = new JsonRequest(Method.GET, signedUrl, null, new JsonResponseListener() {
                    @Override
                    public void onResponse(JSONObject response, int resultCode) {
                        try {
                            JSONArray routesObject = response.getJSONArray(KEY_ROUTES);
                            JSONObject currentRoute = routesObject.getJSONObject(0);
                            JSONObject overViewPolyline = currentRoute.getJSONObject(KEY_OVERVIEW_POLYLINE);
                            String encodedPoints = overViewPolyline.getString(KEY_POINTS);
                            listener.onSuccess(decode(encodedPoints));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        // do nothing
                    }
                }, new ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        // do nothing
                    }

                    @Override
                    public void onErrorResponse(VolleyError error, int resultCode) {
                        // do nothing
                    }
                }, 45);
  VolleyClient.getInstance(context.getApplicationContext()).addRequest(request);
            } catch (IOException | InvalidKeyException | NoSuchAlgorithmException | URISyntaxException e) {
                e.printStackTrace();
            }
        }
</code>```

Here is my signURL function

```<code>public static String signURL(String inputUrl) throws IOException, InvalidKeyException, NoSuchAlgorithmException, URISyntaxException {
    URL url = new URL(inputUrl);
    String googleCryptoKey = ConfigurationManager.GOOGLE_CRYPTO_KEY;
    UrlSigner signer = new UrlSigner(googleCryptoKey);
    String request = signer.signRequest(url.getPath(), url.getQuery());
    return url.getProtocol() + "://" + url.getHost() + request;
}
</code>```

I created this code from the example, but I am unable to figure what the Google Crypto Key should be?

The dashboard has

API Key that I create

from AIM & Admin I can see a Project ID and Project Number

Can someone help with this?

答:
Client ID and Cryptographic key are used in the Premium plan license. If you don't have a Premium plan license and use a Standard plan, you have to apply an API key in your request and digital signature is not necessary.

https://developers.google.com/maps/documentation/directions/get-api-key#standard-auth

So you can simplify your code to apply an API key instead of client ID and remove the part that creates a digital signature.

If you would like to protect your API key you should set IP restrictions in developer console. Client ID and digital signature is used to protect requests issued  by Premium plan users.

Title: How to sign URL Google Directions?

Body:
I have a function to retrieve Google Directions but I have a question about where to find the Google Crypto Key to sign my url. Where is this on the dashboard?

        public static void getDirections(Context context, String origin, String destination,
                                         final DirectionsListener listener)
                throws ExecutionException, InterruptedException {
            if (FrameworkUtils.isStringEmpty(origin) || FrameworkUtils.isStringEmpty(destination)) {
                return;
            }
            try {
                String url = String.format(GOOGLE_API_DIRECTIONS_URL, origin, destination,
                        ConfigurationManager.GOOGLE_CLIENT_KEY, KEY_TRAVEL_MODE_DRIVING);
                String signedUrl = UrlSigner.signURL(url);
                JsonRequest request = new JsonRequest(Method.GET, signedUrl, null, new JsonResponseListener() {
                    @Override
                    public void onResponse(JSONObject response, int resultCode) {
                        try {
                            JSONArray routesObject = response.getJSONArray(KEY_ROUTES);
                            JSONObject currentRoute = routesObject.getJSONObject(0);
                            JSONObject overViewPolyline = currentRoute.getJSONObject(KEY_OVERVIEW_POLYLINE);
                            String encodedPoints = overViewPolyline.getString(KEY_POINTS);
                            listener.onSuccess(decode(encodedPoints));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        // do nothing
                    }
                }, new ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        // do nothing
                    }

                    @Override
                    public void onErrorResponse(VolleyError error, int resultCode) {
                        // do nothing
                    }
                }, 45);
  VolleyClient.getInstance(context.getApplicationContext()).addRequest(request);
            } catch (IOException | InvalidKeyException | NoSuchAlgorithmException | URISyntaxException e) {
                e.printStackTrace();
            }
        }

Here is my signURL function

public static String signURL(String inputUrl) throws IOException, InvalidKeyException, NoSuchAlgorithmException, URISyntaxException {
    URL url = new URL(inputUrl);
    String googleCryptoKey = ConfigurationManager.GOOGLE_CRYPTO_KEY;
    UrlSigner signer = new UrlSigner(googleCryptoKey);
    String request = signer.signRequest(url.getPath(), url.getQuery());
    return url.getProtocol() + "://" + url.getHost() + request;
}

I created this code from the example, but I am unable to figure what the Google Crypto Key should be?

The dashboard has

API Key that I create

from AIM & Admin I can see a Project ID and Project Number

Can someone help with this?


答:
You can use recursion to initialize the elements of a multidimensional array of any dimension.1

Code

```<code>def init(n, *rest)
  rest.empty? ? Array.new(n, 0) : Array.new(n) { init(*rest) }
end
</code>```

Examples

```<code>dims = [2, 3, 2]
a = init(*dims)
  #=> [[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]

a[0][0][0] = 1
a #=> [[[1, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]

dims = [2, 3, 2, 4, 2, 3]
a = init(*dims)

a.flatten.size
  #=> 288 (= 2*3*2*4*2*3)
a[0][0][0][0][0][0] = 1
a.flatten.count(1)
  #=> 1
</code>```

Explanation

The steps are as follows.

Suppose, as in the example,

```<code>dims = [2, 3, 2]
</code>```

Then

```<code>n, *rest = dims
  #=> [2, 3, 2]
n #=> 2
rest
  #=> [3, 2]
</code>```

As rest.empty? #=> false, the method returns

```<code>Array.new(2) { init(*[3, 2]) } # (1)
  #=> [[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]
</code>```

To obtain this result, we execute the block

```<code>{ init(*[3, 2]) }
</code>```

for each of the two elements of the array being constructed. This requires us to compute init([3, 2]) (same as { init(3, 2) }), which is done as follows.

```<code>n, *rest = [3, 2]
  #=> [3, 2]
n #=> 3
rest
  #=> [2]
</code>```

Again, as rest.empty? #=> false, we return

```<code>Array.new(3) { init(*[2]) } # (2)
  #=> [[0, 0], [0, 0], [0, 0]]
</code>```

to expression (1) above. For each of the 3 elements of this array we execute the block

```<code>{ init(*[2]) }
</code>```

This requires us to compute init([2]), which is done as follows.

```<code>n, *rest = [2]
  #=> [2]
n #=> 2
rest
  #=> []
</code>```

This time, since rest.empty? #=> true, we compute and return

```<code>Array.new(2, 0)
  #=> [0, 0]
</code>```

to expression (2) above.

1 Yes, there's no such thing as a "multidimensional array" in Ruby, but I expect readers to know what I mean. The alternative is something like "...of an array containing nested arrays of equal size with any number of levels of nesting", but even that is incomplete as it fails to exclude, for example, [[1, [2,3]], [4,5]]. It would be helpful if Ruby had a name for such objects.

Title: How to initialise a three dimensional ruby array

Body:
I want to initialise a three dimensional ruby array. For a two-dimensional array, I can do

a = Array.new(4){ Array.new(5, 0) }

so I have tried

a = Array.new(4) { Array.new(5, Array.new(6, 0)) }

but if I do a[1][2][3] = 5, it not only sets that element to 5, it sets the corresponding element to 5 in other sub arrays i.e.

[[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]],
 [[0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0]],
 [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]],
 [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]]

Body:
You can use recursion to initialize the elements of a multidimensional array of any dimension.1

Code

def init(n, *rest)
  rest.empty? ? Array.new(n, 0) : Array.new(n) { init(*rest) }
end

Examples

dims = [2, 3, 2]
a = init(*dims)
  #=> [[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]

a[0][0][0] = 1
a #=> [[[1, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]

dims = [2, 3, 2, 4, 2, 3]
a = init(*dims)

a.flatten.size
  #=> 288 (= 2*3*2*4*2*3)
a[0][0][0][0][0][0] = 1
a.flatten.count(1)
  #=> 1

Explanation

The steps are as follows.

Suppose, as in the example,

dims = [2, 3, 2]

Then

n, *rest = dims
  #=> [2, 3, 2]
n #=> 2
rest
  #=> [3, 2]

As rest.empty? #=> false, the method returns

Array.new(2) { init(*[3, 2]) } # (1)
  #=> [[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]

To obtain this result, we execute the block

{ init(*[3, 2]) }

for each of the two elements of the array being constructed. This requires us to compute init([3, 2]) (same as { init(3, 2) }), which is done as follows.

n, *rest = [3, 2]
  #=> [3, 2]
n #=> 3
rest
  #=> [2]

Again, as rest.empty? #=> false, we return

Array.new(3) { init(*[2]) } # (2)
  #=> [[0, 0], [0, 0], [0, 0]]

to expression (1) above. For each of the 3 elements of this array we execute the block

{ init(*[2]) }

This requires us to compute init([2]), which is done as follows.

n, *rest = [2]
  #=> [2]
n #=> 2
rest
  #=> []

This time, since rest.empty? #=> true, we compute and return

Array.new(2, 0)
  #=> [0, 0]

to expression (2) above.

1 Yes, there's no such thing as a "multidimensional array" in Ruby, but I expect readers to know what I mean. The alternative is something like "...of an array containing nested arrays of equal size with any number of levels of nesting", but even that is incomplete as it fails to exclude, for example, [[1, [2,3]], [4,5]]. It would be helpful if Ruby had a name for such objects.


问:
Can't get access token in Xcode Swift Facebook login SDK
I'm trying to test Facebook SDK login in my app but keep getting this error. I see a dialog which accepts my email and password to login and then tells me I have already accepted the app. I should see a message "Logged in but I only see the error below. How can I test the Facebook SDK in the Xcode iOS simulator. I tested this on an iPhone with an alert to display the access token but got the same result. It will always present "User cancelled login".

```<code>-canOpenURL: failed for URL: "fbauth2:/" - error: The operation couldn’t be completed. (OSStatus error -10814.) User cancelled login.
</code>```

Here is my code.

```<code>func signInWithFacebook(button: UIButton) {

    let loginManager = LoginManager()

    loginManager.logIn([ .publicProfile ], viewController: self) { loginResult in

        switch loginResult {

        case .failed(let error):

            let alertController: UIAlertController = UIAlertController(title: "Login error", message: error as? String, preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print(error)

        case .cancelled:

            let alertController: UIAlertController = UIAlertController(title: "Login cancelled", message: "User cancelled login", preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print("User cancelled login.")

        case .success(let grantedPermissions, let declinedPermissions, let accessToken):

            print(grantedPermissions)

            print(declinedPermissions)

            print(accessToken)

            let alertController: UIAlertController = UIAlertController(title: "Login success", message: String(describing: accessToken), preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print("Logged in")
        }
    }
}
</code>```

On the first pass, I got the Facebook login dialog but thereafter I just see a dialog saying I have already authorized my app with an OK button.

```<code>let accessToken = AccessToken.current
</code>```

in viewDidLoad() returns nil always. I need to get an accessToken so i can send it to an API and test the response.

答:
I needed to add this function in my AppDelegate.swift. It seems completely undocumented.</p>

```<code>func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

        return FBSDKApplicationDelegate.sharedInstance().application(application,
                                                                     open: url,
                                                                     sourceApplication: sourceApplication,
                                                                     annotation: annotation)
}
</code>```

Body:
I'm trying to test Facebook SDK login in my app but keep getting this error. I see a dialog which accepts my email and password to login and then tells me I have already accepted the app. I should see a message "Logged in but I only see the error below. How can I test the Facebook SDK in the Xcode iOS simulator. I tested this on an iPhone with an alert to display the access token but got the same result. It will always present "User cancelled login".

-canOpenURL: failed for URL: "fbauth2:/" - error: The operation couldn’t be completed. (OSStatus error -10814.) User cancelled login.

Here is my code.

func signInWithFacebook(button: UIButton) {

    let loginManager = LoginManager()

    loginManager.logIn([ .publicProfile ], viewController: self) { loginResult in

        switch loginResult {

        case .failed(let error):

            let alertController: UIAlertController = UIAlertController(title: "Login error", message: error as? String, preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print(error)

        case .cancelled:

            let alertController: UIAlertController = UIAlertController(title: "Login cancelled", message: "User cancelled login", preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print("User cancelled login.")

        case .success(let grantedPermissions, let declinedPermissions, let accessToken):

            print(grantedPermissions)

            print(declinedPermissions)

            print(accessToken)

            let alertController: UIAlertController = UIAlertController(title: "Login success", message: String(describing: accessToken), preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print("Logged in")
        }
    }
}

On the first pass, I got the Facebook login dialog but thereafter I just see a dialog saying I have already authorized my app with an OK button.

let accessToken = AccessToken.current

in viewDidLoad() returns nil always. I need to get an accessToken so i can send it to an API and test the response.

Body:
I needed to add this function in my AppDelegate.swift. It seems completely undocumented.

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

        return FBSDKApplicationDelegate.sharedInstance().application(application,
                                                                     open: url,
                                                                     sourceApplication: sourceApplication,
                                                                     annotation: annotation)
}


问:
php query in database doesn't work
Hello guys i tried to add into database some values and it's not working.I tried everything but no.
What should i do? the name of the table is "credit".
Can you help me to rezolv this problem?</p>

```<code><tr>
    <td><input class="form-control" placeholder="nr" name="nr" type="text" autofocus></td>
    <td><input class="form-control" placeholder="suma" name="suma" type="text" autofocus></td>
    <td><input class="form-control" placeholder="rate" name="rate" type="text" autofocus></td>
    <td><input class="form-control" placeholder="dobanda" name="dobanda" type="text" autofocus></td>
    <td><button class="btn btn-success" value="adaugare">Adaugare credit</button></a></td>
</tr>
</table>
</div>
</div>

<?php if(isset($_POST['adaugare']))
    {
        $nr=$_POST['nr'];
        $suma=$_POST['suma'];
        $rate=$_POST['rate'];
        $dobanda=$_POST['dobanda'];

        if($nr=='')
        {

            echo"<script>alert('Introdu numar')</script>";
            exit();
        }

        if($suma=='')
        {

            echo"<script>alert('Introdu suma')</script>";
            exit();
        }
        if($rate=='')
        {
            echo"<script>alert('Introdu rate')</script>";
            exit();
        }
        if($dobanda=='')
        {
            echo"<script>alert('Introdu dobanda')</script>";
            exit();
        }
        $id=$_SESSION['id'];
        $insert_credit="insert into credit VALUE ('$nr','$id','$suma','$rate','$dobanda')";
        mysqli_query($dbcon,$insert_credit);

    }
</code>```

答:
1) I can't see you establishing your    connection to the databse

2) Change your button to a submit button
    and wrap your for-tabel in a <form></form>

3) Your SQL query has a syntax error Wich should have been displayed if not for 1.

*4) I would not use mysql
i I find it simple to use PDO and it's allso safer

Title: php query in database doesn't work

Body:
Hello guys i tried to add into database some values and it's not working.I tried everything but no.
What should i do? the name of the table is "credit".
Can you help me to rezolv this problem?

    <input class="form-control" placeholder="nr" name="nr" type="text" autofocus>
    <input class="form-control" placeholder="suma" name="suma" type="text" autofocus>
    <input class="form-control" placeholder="rate" name="rate" type="text" autofocus>
    <input class="form-control" placeholder="dobanda" name="dobanda" type="text" autofocus>
    <button class="btn btn-success" value="adaugare">Adaugare credit</button>

<?php if(isset($_POST['adaugare']))
    {
        $nr=$_POST['nr'];
        $suma=$_POST['suma'];
        $rate=$_POST['rate'];
        $dobanda=$_POST['dobanda'];

        if($nr=='')
        {

            echo"";
            exit();
        }

        if($suma=='')
        {

            echo"";
            exit();
        }
        if($rate=='')
        {
            echo"";
            exit();
        }
        if($dobanda=='')
        {
            echo"";
            exit();
        }
        $id=$_SESSION['id'];
        $insert_credit="insert into credit VALUE ('$nr','$id','$suma','$rate','$dobanda')";
        mysqli_query($dbcon,$insert_credit);

    }


问:
Linux system call getifaddr c++
in my c++ application I've wrriten this code:

```<code>struct ifaddrs *ifap;

if (0 != getifaddrs(&ifap)) {
    error = errno;
    return -1;
}

addresses.clear();
for (struct ifaddrs *ifa = ifap; ifa; ifa = ifa->ifa_next) {
    sockaddr *s=ifa->ifa_addr;
    PRINT(" LocalIP sockaddr %u.%u.%u.%u \n",s->sa_data[2],s->sa_data[3],s->sa_data[4],s->sa_data[5]);}
</code>```

when I debug the print I see that when I have static ip like 10.0.0.12 it prints it correct. but ip from DHCP like 192.168.14.12 it prints it "-64.-88.14.12"

how can I solve this issue?

10x

答: Seems like it's trying to print bytes as signed. Try using %u instead of %d inside IP address.</p>

Title: Linux system call getifaddr c++

Body:
in my c++ application I've wrriten this code:

struct ifaddrs *ifap;

if (0 != getifaddrs(&ifap)) {
    error = errno;
    return -1;
}

addresses.clear();
for (struct ifaddrs *ifa = ifap; ifa; ifa = ifa->ifa_next) {
    sockaddr *s=ifa->ifa_addr;
    PRINT(" LocalIP sockaddr %u.%u.%u.%u \n",s->sa_data[2],s->sa_data[3],s->sa_data[4],s->sa_data[5]);}

when I debug the print I see that when I have static ip like 10.0.0.12 it prints it correct. but ip from DHCP like 192.168.14.12 it prints it "-64.-88.14.12"

how can I solve this issue?

10x


问:
Notification Email Entry Won't Work For Date Box Value
So I am using the following in the onValueEdit field of an entry form

```<code>var widgets = widget.root.descendants;
var to = 'xxxx@yyy.com';
var subject = 'Delivery Date Change For: ' + widgets.ProjectName.value;
var msg = "The Delivery Date for [ " + widgets.UsersPosition.value + " ] on [ " + widgets.ProjectName.value + " ] has been changed;
sendMessage(to, subject, msg);
</code>```

So when a user changes a Delivery Date (by adjusting a Date Box) a notification email is sent out. I would like to add the actual in the Date Box but when I add " + widgets.DeliveryDate.value + " it says it is unrecognized.

Since the DeliveryDate is a Date Box, do I need something different? widgets.DeliveryDate.???

Thank you for any help.

答:
"value" property is the one you need. Please note that it's JavaScript Date object so in some cases you need to convert it. But code you provided looks good to me.

What do you mean by "unrecognized"? Could you provide error details?

BTW: it's better to use Server Script to generate email message.

Body:
So I am using the following in the onValueEdit field of an entry form

var widgets = widget.root.descendants;
var to = 'xxxx@yyy.com';
var subject = 'Delivery Date Change For: ' + widgets.ProjectName.value;
var msg = "The Delivery Date for [ " + widgets.UsersPosition.value + " ] on [ " + widgets.ProjectName.value + " ] has been changed;
sendMessage(to, subject, msg);

So when a user changes a Delivery Date (by adjusting a Date Box) a notification email is sent out. I would like to add the actual in the Date Box but when I add " + widgets.DeliveryDate.value + " it says it is unrecognized.

Since the DeliveryDate is a Date Box, do I need something different? widgets.DeliveryDate.???

Thank you for any help.


问:
Python/PyQt/Qt QMenu QAction syntax
I have a syntax/understanding problem in an application using Python 3, PyQt5 and Qt5.  I am unsure which of these is causing the problem.

I am charged with porting a GUI application which worked under Windows to Linux, with newer versions of libraries.  I do not have access to the original running under Windows.

In several places I see:

```<code>menu = QMenu(self)
action = menu.addAction("Some string")
action.triggered[()].connect(self.handler)
</code>```

I presume this used to work.  I am porting to Python 3.5, PyQt 5.7 & Qt 5.7.  I have reason to believe the code was written for earlier versions of each of these.

Executing it now generates a 'there is no matching overloaded signal' error, on the action.triggered[()] segment.

By guesswork and looking at a couple of examples I found somewhere, I have changed the last line to:

```<code>action.triggered.connect(self.handler)
</code>```

and it seems to work now.

Could someone explain what the original triggered[()] syntax meant/worked, and which "product" the evident change was in --- it would be nice to be able to read about where this got changed?  Is my replacement by simply triggered correct/same behaviour?

答:
The relevant change happened in PyQt-5.3. It is not entirely safe to simply remove the old syntax, as this could easily create a subtle bug in both current and future code.

The issue is that certain signals like triggered will always send a default boolean value unless you take steps to eliminate it. Qt defines these signals like this:

```<code>    triggered(bool checked = false)
</code>```

PyQt previously implemented this as two overloads:

```<code>    triggered(bool checked)
    triggered()
</code>```

and if you wanted to explicitly select the latter overload, you had to use the following slightly awkward sytax:

```<code>    triggered[()].connect(slot)
</code>```

But this is now no longer an option, as only the first overload is implemented. So to get exactly the same behaviour, it is necessary to either wrap the handler like this:

```<code>    triggered.connect(lambda checked: slot())
</code>```

or decorate it like this:

```<code>    @QtCore.pyqtSlot()
    def handleTriggered(self):
        pass
</code>```

Otherwise, it is quite easy to fall into a little trap. Imagine you have a method defined like this:

```<code>    def frobnicate(self, foobar=True):
        if foobar:
            # do something nice
        else:
            # empty my home directory without prompting
</code>```

Later on, you decide to hook this up to a button, like this:

```<code>    self.button.clicked.connect(self.frobnicate)
</code>```

Which all seems perfectly fine, until you find out that the clicked signal works just like triggered, and always sends False by default...

Of course, if you're absolutely certain that you will never connect slots which take arguments to signals like triggered and clicked, you could get away with connecting them all in the simplistic fashion shown above. But, really, that is just an accident waiting to happen...

Title: Python/PyQt/Qt QMenu QAction syntax

Body:
I have a syntax/understanding problem in an application using Python 3, PyQt5 and Qt5.  I am unsure which of these is causing the problem.

I am charged with porting a GUI application which worked under Windows to Linux, with newer versions of libraries.  I do not have access to the original running under Windows.

In several places I see:

menu = QMenu(self)
action = menu.addAction("Some string")
action.triggered[()].connect(self.handler)

I presume this used to work.  I am porting to Python 3.5, PyQt 5.7 & Qt 5.7.  I have reason to believe the code was written for earlier versions of each of these.

Executing it now generates a 'there is no matching overloaded signal' error, on the action.triggered[()] segment.

By guesswork and looking at a couple of examples I found somewhere, I have changed the last line to:

action.triggered.connect(self.handler)

and it seems to work now.

Could someone explain what the original triggered[()] syntax meant/worked, and which "product" the evident change was in --- it would be nice to be able to read about where this got changed?  Is my replacement by simply triggered correct/same behaviour?

Body:
The relevant change happened in PyQt-5.3. It is not entirely safe to simply remove the old syntax, as this could easily create a subtle bug in both current and future code.

The issue is that certain signals like triggered will always send a default boolean value unless you take steps to eliminate it. Qt defines these signals like this:

    triggered(bool checked = false)

PyQt previously implemented this as two overloads:

    triggered(bool checked)
    triggered()

and if you wanted to explicitly select the latter overload, you had to use the following slightly awkward sytax:

    triggered[()].connect(slot)

But this is now no longer an option, as only the first overload is implemented. So to get exactly the same behaviour, it is necessary to either wrap the handler like this:

    triggered.connect(lambda checked: slot())

or decorate it like this:

    @QtCore.pyqtSlot()
    def handleTriggered(self):
        pass

Otherwise, it is quite easy to fall into a little trap. Imagine you have a method defined like this:

    def frobnicate(self, foobar=True):
        if foobar:
            # do something nice
        else:
            # empty my home directory without prompting

Later on, you decide to hook this up to a button, like this:

    self.button.clicked.connect(self.frobnicate)

Which all seems perfectly fine, until you find out that the clicked signal works just like triggered, and always sends False by default...

Of course, if you're absolutely certain that you will never connect slots which take arguments to signals like triggered and clicked, you could get away with connecting them all in the simplistic fashion shown above. But, really, that is just an accident waiting to happen...


问:
Python changing units on a basemap
I am trying to plot precipitation data, from a netCDF4 file, on a basemap using python 3.6. The code that I am using has worked perfectly on a very similar data set. The only difference being that the previous precip data was in 'cm' while the data that I am currently trying to plot is in 'kg m-2 s-1'. The variables found in this file are time, time_bnds, lat, lat_bnds, lon, lon_bnds, and pr. pr is the precipitation variable and the one I an interested in plotting.

Here is my code

```<code>from mpl_toolkits.basemap import Basemap, cm
from netCDF4 import Dataset as NetCDFFile
import matplotlib.pyplot as plt

nc = NetCDFFile('filename.nc','r')

p = nc.variables['prc']
data = p[:,:,0]

fig = plt.figure(figsize=(8,8))
ax = fig.add_axes([0.1,0.1,0.8,0.8])

m = Basemap(projection='cyl',lon_0=180,lat_0=0,resolution='l')

m.drawcoastlines()
m.drawstates()
m.drawcountries()

ny = data.shape[0]; nx = data.shape[1]
lons, lats = m.makegrid(nx,ny)
x,y = m(lons, lats) # compute map proj coordinates.

cs=plt.contourf(x,-y,data*2592000,range(0,1000,10),cmap=cm.s3pcpn,latlon=True)

#data is multiplied by the amount of seconds in a month

cbar = m.colorbar(cs,location='bottom',pad="5%")
cbar.set_label('mm')

plt.show()
</code>```

If you want to try and run this code with the same file I am using it is a netCDF4 file was downloaded from CMIP5 website:  http://pcmdi9.llnl.gov/ My file name:(/data/CCSM4/pr_Amon_CCSM4_historical_r1i1p1_185001-200512.nc)
However the original data is in netCDF3_CLASSIC format so you have to change it to netCDF4.

答:
If the only change is in the units for how much precipitation, what about converting the data to cm, that way you know it will work and you are already familiar with how to interpret the data.  You could even write a function to convert it.

If you convert it, and it's in the same format you expect to work, yet it still doesn't work, you will have found that there is something else wrong with your data, so there's another plus in trying that approach.

Title: Python changing units on a basemap

Body:
I am trying to plot precipitation data, from a netCDF4 file, on a basemap using python 3.6. The code that I am using has worked perfectly on a very similar data set. The only difference being that the previous precip data was in 'cm' while the data that I am currently trying to plot is in 'kg m-2 s-1'. The variables found in this file are time, time_bnds, lat, lat_bnds, lon, lon_bnds, and pr. pr is the precipitation variable and the one I an interested in plotting.

Here is my code

from mpl_toolkits.basemap import Basemap, cm
from netCDF4 import Dataset as NetCDFFile
import matplotlib.pyplot as plt

nc = NetCDFFile('filename.nc','r')

p = nc.variables['prc']
data = p[:,:,0]

fig = plt.figure(figsize=(8,8))
ax = fig.add_axes([0.1,0.1,0.8,0.8])

m = Basemap(projection='cyl',lon_0=180,lat_0=0,resolution='l')

m.drawcoastlines()
m.drawstates()
m.drawcountries()

ny = data.shape[0]; nx = data.shape[1]
lons, lats = m.makegrid(nx,ny)
x,y = m(lons, lats) # compute map proj coordinates.

cs=plt.contourf(x,-y,data*2592000,range(0,1000,10),cmap=cm.s3pcpn,latlon=True)

#data is multiplied by the amount of seconds in a month

cbar = m.colorbar(cs,location='bottom',pad="5%")
cbar.set_label('mm')

plt.show()

If you want to try and run this code with the same file I am using it is a netCDF4 file was downloaded from CMIP5 website:  http://pcmdi9.llnl.gov/ My file name:(/data/CCSM4/pr_Amon_CCSM4_historical_r1i1p1_185001-200512.nc)
However the original data is in netCDF3_CLASSIC format so you have to change it to netCDF4.


问:
Populating HTML table with data from MySQL database using PHP
I have a table with structure as:

```<code>CREATE TABLE `lectures` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category` varchar(255) NOT NULL,
`semester` varchar(255) NOT NULL,
`course_no` varchar(255) NOT NULL,
`course_title` varchar(255) NOT NULL,
`faculty_name` varchar(216) NOT NULL,
`upload_file` varchar(255) NOT NULL,
`dateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1
</code>```

Now the scenario is, I have 3 things; semester, course and lecturer. There can be more than one semesters, each semester can have multiple courses and each course can be have many lecturers. Above DB table have all the data in it.
I want to populate data in HTML table whose structure can be as follows.

I want to populate data in above pic format. I can't figure out how to do that.

Any help appreciated.

答:
When you write the query, add an additional column say 'CourseClass'. Make the CourseClass equal to the name of the course.

Once you have a table with your data and the additional column, you can write jquery or js to merge the rows with similar values.

At the front-end, simply hide the extra column you added.

Alternatively, you can look this up. The person is trying to achieve something similar - html table span if the data is same

There is a JSFiddle link in there too.

Hope this helps!

Body:
I have a table with structure as:

CREATE TABLE `lectures` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category` varchar(255) NOT NULL,
`semester` varchar(255) NOT NULL,
`course_no` varchar(255) NOT NULL,
`course_title` varchar(255) NOT NULL,
`faculty_name` varchar(216) NOT NULL,
`upload_file` varchar(255) NOT NULL,
`dateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1

Now the scenario is, I have 3 things; semester, course and lecturer. There can be more than one semesters, each semester can have multiple courses and each course can be have many lecturers. Above DB table have all the data in it.
I want to populate data in HTML table whose structure can be as follows.

I want to populate data in above pic format. I can't figure out how to do that.

Any help appreciated.


问:
Possible to do .net programming with Visual Studio Community Mac?
https://www.visualstudio.com/vs/visual-studio-mac/

There's a screenshot from this webpage that looks like I can do .net programming with the Mac version of Visual Studio Community. However, it seemed like I could only do Android and iOS development after downloaded Visual Studio Mac.

Is there a way to do .net programming in Visual Studio Community Mac? I'd rather not have to use a VM to do .net programming.

Thanks in advance!

答:
Yes, you can use Visual Studio for Mac to develop .net (core) applications.

You will need to have the .net core SDK installed on your mac:

https://www.microsoft.com/net/core#macos

Don't expect a like-for-like experience between Windows based Visual Studio and Visual Studio for Mac.

A lot of things are missing, not to mention, it's only compatible with .net core.


问:
Angular: Global Error Handler working only once
I have a service which calls a REST API. The create operation POST the parameters, and then GET the created object by using the id returned in the HTTP header. When the object is returned, a Subject propagates the object to notify other components. You can notice that I don't call the catch operation. I did it on purpose so the global error handler manages the error It works as expected the first time, but the second time, the global error handler is not called.

In the Chrome console, I get an error after the first call but not after the second call in rxjs/Subscriber.js:

```<code>Subscriber.js:240 Uncaught
Response {_body: "{"message":"The query is not valid"}", status: 500, ok: false, statusText: "Internal Server Error", headers: Headers…}

SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            this.unsubscribe();
            throw err;
        }
    };
</code>```

The service:

```<code>@Injectable()
export class SystemService {

  private subject = new Subject<any>();

  constructor(private http: Http) {
  }

  create(system: SdqlSystem) {
    this.http.post(environment.apiEndpoint + 'systems', system)
      .flatMap(res => {
        const location = res.headers.get('Location');
        return this.http.get(location);
      })
      .map(res => res.json())
      .subscribe(data => this.subject.next(data));

  }

  get(id: string) {
    this.http.get(environment.apiEndpoint + 'systems/' + id)
      .map(res => res.json())
      .subscribe(data => this.subject.next(data));
  }

  systems(): Observable<any> {
    return this.subject.asObservable();
  }

}
</code>```

The call from a form:

```<code>onSubmit({value, valid}: { value: SdqlSystem, valid: boolean }) {
  this.systemService.create(value);
}
</code>```

The global error handler:

```<code>@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

  constructor(private logger: LoggingService, private notificationsService: NotificationsService) {
  }

  handleError(error: Response | any): void {
    console.log('***** HANDLE ERROR *****');
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || body.message || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    this.logger.error(errMsg);
    this.notificationsService.error('Error', errMsg);
    throw error;
  }

}
</code>```

答:
OP already resolved it, but I guess I'll answer in case someone else stumbles upon this problem:

Rethrowing the error in the GlobalErrorHandler leads to an uncaught exception where the browser stops execution. That's why it works only once.

The solution is simply to not rethrow in the ErrorHandler.

More detail: In this case there is no onError-function provided in subscribe(). That's why rxjs/Subscriber.js runs into the catch-part of __tryOrUnsub.
It tries to execute the onError-function but fails (because there is none) and therefore unsubscribes from the Observable and throws the error.
The GlobalErrorHandler picks it up, does logging and notification and then rethrows it.

At this point the error becomes an uncaught exception outside of Angular.
(the default ErrorHandler does not rethrow an error)

Note: this approach works for standard http-calls, because the Response-Observable only emits one value and then completes anyway.
If you have an Observable that needs to emit more than one value you will have to deal with the error differently because an Observable that emits an error will not emit any further values, as specified in the Observable-Contract:

OnError

    indicates that the Observable has terminated with a specified error condition and that it will be emitting no further items

Body:
I have a service which calls a REST API. The create operation POST the parameters, and then GET the created object by using the id returned in the HTTP header. When the object is returned, a Subject propagates the object to notify other components. You can notice that I don't call the catch operation. I did it on purpose so the global error handler manages the error It works as expected the first time, but the second time, the global error handler is not called.

In the Chrome console, I get an error after the first call but not after the second call in rxjs/Subscriber.js:

Subscriber.js:240 Uncaught
Response {_body: "{"message":"The query is not valid"}", status: 500, ok: false, statusText: "Internal Server Error", headers: Headers…}

SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            this.unsubscribe();
            throw err;
        }
    };

The service:

@Injectable()
export class SystemService {

  private subject = new Subject<any>();

  constructor(private http: Http) {
  }

  create(system: SdqlSystem) {
    this.http.post(environment.apiEndpoint + 'systems', system)
      .flatMap(res => {
        const location = res.headers.get('Location');
        return this.http.get(location);
      })
      .map(res => res.json())
      .subscribe(data => this.subject.next(data));

  }

  get(id: string) {
    this.http.get(environment.apiEndpoint + 'systems/' + id)
      .map(res => res.json())
      .subscribe(data => this.subject.next(data));
  }

  systems(): Observable<any> {
    return this.subject.asObservable();
  }

}

The call from a form:

onSubmit({value, valid}: { value: SdqlSystem, valid: boolean }) {
  this.systemService.create(value);
}

The global error handler:

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

  constructor(private logger: LoggingService, private notificationsService: NotificationsService) {
  }

  handleError(error: Response | any): void {
    console.log('***** HANDLE ERROR *****');
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || body.message || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    this.logger.error(errMsg);
    this.notificationsService.error('Error', errMsg);
    throw error;
  }

}


问:
angularJs sorting code doesn't work
I totally cant understand, why my sorting code doesn't work.
I want just add a sorting method "sortFlag" to my app, and it doesn't work in a right way.

Here is code:

```<code>var App2 = angular.module('App2',[
    //submodules
]);

    App2.controller('MainController', ['$scope', '$http', function($scope, $http){
        $http.get('https://api.myjson.com/bins/14fug5')
        .success(function(datas){
            $scope.datas_1 = datas
            console.log($scope.datas_1.schema);

        });
        $http.get('https://api.myjson.com/bins/q80it')
        .success(function(datas){
            $scope.datas_2 = datas
        });

        // $scope.predicate = '';
        // $scope.reverse = true;
        // $scope.order = function(predicate) {
        //     $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
        //     $scope.predicate = predicate;
        // };

        $scope.sortFlag = 'id';
        $scope.sortTable = function(flag){
            $scope.sortFlag = flag;
        }

    }]);
</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>angular example 2</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">

    <form>

                <input type="text" class="form-control" placeholder="Search" ng-model="searchFish">

    </form>

    выберите данные:
    данные1
    <input
        name="content"
        type="radio"
        ng-model="content"
        ng-init="content='first'"
        value="first"
    />
    данные2
    <input
        name="content"
        type="radio"
        ng-model="content"
        value="second"
    />

            <button href="#"
                    ng-click="sortTable('{{key}}')">

                {{value}}
            </button>

        {{data.id}}
        {{data.name}}
        {{data.price}}
        {{data.quantity}}

            <button href="#" ng-click="order('{{key}}')">{{value}}</button>

        {{data.id}}
        {{data.name}}
        {{data.price}}
        {{data.quantity}}

```

if you have any idea, please help me with this stuff.

答:
You should add another parameter "reverse" to your orderBy in ng-repeat something like this:

```<code><tr ng-repeat="data in datas_2.data | orderBy:sortFlag:reverse">
</code>```

And to your function in controller set the boolean value to that reverse parameter.

```<code>$scope.sortFlag = 'id';
$scopr.reverse = false;
$scope.sortTable = function(flag){
    $scope.reverse = ($scope.sortFlag === flag) ?
     !$scope.reverse : false;
    $scope.sortFlag = flag;
}
</code>```

This should solve your problem. Let me know if it doesn't work for you.

Title: angularJs sorting code doesn't work

Body:
I totally cant understand, why my sorting code doesn't work.
I want just add a sorting method "sortFlag" to my app, and it doesn't work in a right way.

Here is code:

var App2 = angular.module('App2',[
    //submodules
]);

    App2.controller('MainController', ['$scope', '$http', function($scope, $http){
        $http.get('https://api.myjson.com/bins/14fug5')
        .success(function(datas){
            $scope.datas_1 = datas
            console.log($scope.datas_1.schema);

        });
        $http.get('https://api.myjson.com/bins/q80it')
        .success(function(datas){
            $scope.datas_2 = datas
        });

        // $scope.predicate = '';
        // $scope.reverse = true;
        // $scope.order = function(predicate) {
        //     $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
        //     $scope.predicate = predicate;
        // };

        $scope.sortFlag = 'id';
        $scope.sortTable = function(flag){
            $scope.sortFlag = flag;
        }

    }]);

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>angular example 2</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">

    <form>

                <input type="text" class="form-control" placeholder="Search" ng-model="searchFish">

    </form>

    выберите данные:
    данные1
    <input
        name="content"
        type="radio"
        ng-model="content"
        ng-init="content='first'"
        value="first"
    />
    данные2
    <input
        name="content"
        type="radio"
        ng-model="content"
        value="second"
    />

            <button href="#"
                    ng-click="sortTable('{{key}}')">

                {{value}}
            </button>

        {{data.id}}
        {{data.name}}
        {{data.price}}
        {{data.quantity}}

            <button href="#" ng-click="order('{{key}}')">{{value}}</button>

        {{data.id}}
        {{data.name}}
        {{data.price}}
        {{data.quantity}}

if you have any idea, please help me with this stuff.

Body:
You should add another parameter "reverse" to your orderBy in ng-repeat something like this:

<tr ng-repeat="data in datas_2.data | orderBy:sortFlag:reverse">

And to your function in controller set the boolean value to that reverse parameter.

$scope.sortFlag = 'id';
$scopr.reverse = false;
$scope.sortTable = function(flag){
    $scope.reverse = ($scope.sortFlag === flag) ?
     !$scope.reverse : false;
    $scope.sortFlag = flag;
}

This should solve your problem. Let me know if it doesn't work for you.


问:
Spark Structtype for coalesce
I use Spark 2.0.1 Scala 2.11

How to provide a default value using coalesce for a column that's a StructType?

Say ...

val ss = new StructType().add("x", IntegerType).add("y", IntegerType)

val s = new StructType()
    .add("a", IntegerType)
    .add("b", ss)

val d = Seq( Row(1, Row(1,2)), Row(2, Row(2,3)), Row(2, null) )

val rd = sc.parallelize(d)
val df = spark.createDataFrame(rd, s)
```

<p>Now, <code>df.select($"b").show</code> results in</p>

<pre class="lang-scala prettyprint-override"><code>+-----+
| b   |
+-----+
|[1,2]|
|[2,3]|
| null|
+-----+
</code>```

My question is how can I provide a default value (say [0,0]) using coalesce?

Title: Spark Structtype for coalesce

Body:
I use Spark 2.0.1 Scala 2.11

How to provide a default value using coalesce for a column that's a StructType?

Say ...

val ss = new StructType().add("x", IntegerType).add("y", IntegerType)

val s = new StructType()
    .add("a", IntegerType)
    .add("b", ss)

val d = Seq( Row(1, Row(1,2)), Row(2, Row(2,3)), Row(2, null) )

val rd = sc.parallelize(d)
val df = spark.createDataFrame(rd, s)

Now, df.select($"b").show results in

+-----+
| b   |
+-----+
|[1,2]|
|[2,3]|
| null|
+-----+

My question is how can I provide a default value (say [0,0]) using coalesce?

Body:
You can use the struct function, passing two lit(0) values named to match the names of the struct you already have:

df.select(coalesce($"b", struct(lit(0).as("x"), lit(0).as("y"))))
  .show()

// +---------------------------------------+
// |coalesce(b, struct(0 AS `x`, 0 AS `y`))|
// +---------------------------------------+
// |                                  [1,2]|
// |                                  [2,3]|
// |                                  [0,0]|
// +---------------------------------------+


问:
Is kinit required while accessing a Kerberized service through Java code?
I have a java application which needs to access Hadoop cluster to fetch a file at regular intervals(say, every 24 hours).

Since Kerberos protocol is enabled for protection on that cluster, I am using loginUserFromKeytab() method of UserGroupInformation class : https://hadoop.apache.org/docs/r1.2.1/api/org/apache/hadoop/security/UserGroupInformation.html.

Now, I know that kinit command grants a ticket-granting ticket to access any Kerberized service and this ticket has to be refreshed periodically(through kinit command). Now, my question is, is it required to run kinit periodically(from code) in combination with the above Java API for the code to work? Or will running it once be sufficient? Or is it not required at all.

Thanks for reading.

答:
It's a long and complicated story. In short:

if you request explicitly the Hadoop auth library to create a private Kerberos ticket with loginUserFromKeytab(), then that ticket is not renewable; you must launch a background thread to call checkTGTAndReloginFromKeytab() from time to time, and it will re-create the ticket whenever it comes close to expiration

otherwise the UGI will implicitly read the shared ticket cache to get an existing ticket; and it will also implicitly launch a background thread to renew automatically that ticket (as long as it does not reach its end-of-renewal time -- at this point you are screwed)

Some recommended readings:

 - HBase Kerberos connection renewal strategy

 - Should I call ugi.checkTGTAndReloginFromKeytab() before every action on hadoop?

 - Auto renewal of Kerberos ticket not working from Java (i.e. there's a bug in the non-static methods of UGI)


问:
How do you string a variable together along with a string in PHP?
So I have a variable in PHP that I would like to print along with an html tag but I am very new to PHP and I can't seem to get the syntax right

My goal is to output/print the following

```<code><div class="post-block" style="background-image:url(Whatever image here);">
</code>```

My code is below:

```<code>    $feature_posts = the_sub_field('feature_image_post');

      if ( get_sub_field('post-feature') == "" )  {
        echo '<div class="post-block" style="background-image:url(' .$feature_posts");>';
        echo '</div>';
      }
</code>```

答:
You can make that.

```<code><?php for($i = 0; $i <= 100; $i++){ ?>
    <div class="post-block" style="background-image:url(<?php echo the_sub_field('feature_image_post') ?>);"></div>

<?php } ?>
</code>```

This a sample how you can do.

Body:
So I have a variable in PHP that I would like to print along with an html tag but I am very new to PHP and I can't seem to get the syntax right

My goal is to output/print the following

My code is below:

    $feature_posts = the_sub_field('feature_image_post');

      if ( get_sub_field('post-feature') == "" )  {
        echo '
';
        echo '
';
      }

Body:
You can make that.

<?php for($i = 0; $i <= 100; $i++){ ?>
    <div class="post-block" style="background-image:url(<?php echo the_sub_field('feature_image_post') ?>);"></div>

<?php } ?>

This a sample how you can do.


问:
Oracle Invalid Identifier Error: ORA-00904 In inserting subquery
I can't figure out what is the problem that is causing it. I have tried renaming "amount" I have tried changing what data type is transferred through, I tried just removing it, but then it says that End_Date is invalid once I do that. Here is the code.

```<code>INSERT INTO price
( price_id
, item_id
, price_type
, active_flag
, start_date
, end_date
, amount
, created_by
, creation_date
, last_updated_by
, last_updated)

(SELECT price_s1.nextval
,      il.Item_ID
,      il.Price_Type
,      il.Active_Flag
,      il.Start_Date
,      il.End_Date
,      il.amount
,      1
,      SYSDATE
,      1
,      SYSDATE
FROM    (SELECT i.item_id AS "Item_ID"
        , af.active_flag AS "Active_Flag"
        , cl.common_lookup_id AS "Price_Type"
        , cl.common_lookup_type AS "Price_Desc"
        ,    CASE
             WHEN (TRUNC(SYSDATE) - 30) > TRUNC(i.release_date) THEN TRUNC(i.release_date) + 31
             ELSE TRUNC(i.release_date)
             END AS "Start_Date"
        ,    CASE
             WHEN (TRUNC(SYSDATE)-30) > TRUNC(i.release_date) AND active_flag = 'N' THEN
             TRUNC(i.release_date) + 30
             ELSE
                null
             END AS "End_Date"
        ,    CASE
                 WHEN active_flag = 'N' AND cl.common_lookup_type = '1-DAY RENTAL' THEN 3
                 WHEN active_flag = 'N' AND cl.common_lookup_type = '3-DAY RENTAL' THEN 10
                 WHEN active_flag = 'N' AND cl.common_lookup_type = '5-DAY RENTAL' THEN 15
                 WHEN i.release_date+1 > (SYSDATE-1) AND cl.common_lookup_type = '1-DAY RENTAL' THEN 3
                 WHEN i.release_date+1 > (SYSDATE-1) AND cl.common_lookup_type = '3-DAY RENTAL' THEN 10
                 WHEN i.release_date+1 > (SYSDATE-1) AND cl.common_lookup_type = '5-DAY RENTAL' THEN 15
                 WHEN active_flag = 'Y' AND i.release_date +1 < (SYSDATE-1) THEN cl.common_lookup_code
             END AS "amount"

             FROM     item i CROSS JOIN
                (SELECT 'Y' AS active_flag FROM dual
                 UNION ALL
                 SELECT 'N' AS active_flag FROM dual) af CROSS JOIN
                (SELECT '1' AS rental_days FROM dual
                 UNION ALL
                 SELECT '3' AS rental_days FROM dual
                 UNION ALL
                 SELECT '5' AS rental_days FROM dual) dr INNER JOIN
                 common_lookup cl ON dr.rental_days = SUBSTR(cl.common_lookup_type,1,1)
        WHERE    cl.common_lookup_table = 'PRICE'
        AND      cl.common_lookup_column = 'PRICE_TYPE'
        AND NOT (active_flag ='N' AND (TRUNC(SYSDATE)-30) < TRUNC(i.release_date))
        ORDER BY 1, 2, 3) il);
</code>```

I get the error at

```<code>,      il.amount
</code>```

and this is what it says

```<code>Error report -
SQL Error: ORA-00904: "IL"."AMOUNT": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:
*Action:
</code>```

Any help would be appreciated, if you need more info, just ask. Thanks

答:
By using quotes for alias names you specify a particalur case sensitive name.

```<code>CASE ... END AS "amount"
</code>```

specifies the alias name to be "amount" in lowercase. If you want to access it, use excatly the same spelling. E.g. "Amount" would be invalid.

You are trying to access

```<code>il.amount
</code>```

and as there are no quotes, you say: "I don't care about upper/lower case". That works when accessing table and column names directly or when using an alias name without quotes. But as you used "amount" before, amount cannot be found (you were lucky if it would; I guess it could  happen with an alias name with all upper chars, as Oracle uses upper chars for its names internally, but you wouldn't want to rely on this).

I suggest you just remove the quotes. Try to avoid them whenever possible. Use names that work without quotes (which you are actually already doing; none of your alias names contains any blank, leading digit or whatever).

Body:
I can't figure out what is the problem that is causing it. I have tried renaming "amount" I have tried changing what data type is transferred through, I tried just removing it, but then it says that End_Date is invalid once I do that. Here is the code.

INSERT INTO price
( price_id
, item_id
, price_type
, active_flag
, start_date
, end_date
, amount
, created_by
, creation_date
, last_updated_by
, last_updated)

(SELECT price_s1.nextval
,      il.Item_ID
,      il.Price_Type
,      il.Active_Flag
,      il.Start_Date
,      il.End_Date
,      il.amount
,      1
,      SYSDATE
,      1
,      SYSDATE
FROM    (SELECT i.item_id AS "Item_ID"
        , af.active_flag AS "Active_Flag"
        , cl.common_lookup_id AS "Price_Type"
        , cl.common_lookup_type AS "Price_Desc"
        ,    CASE
             WHEN (TRUNC(SYSDATE) - 30) > TRUNC(i.release_date) THEN TRUNC(i.release_date) + 31
             ELSE TRUNC(i.release_date)
             END AS "Start_Date"
        ,    CASE
             WHEN (TRUNC(SYSDATE)-30) > TRUNC(i.release_date) AND active_flag = 'N' THEN
             TRUNC(i.release_date) + 30
             ELSE
                null
             END AS "End_Date"
        ,    CASE
                 WHEN active_flag = 'N' AND cl.common_lookup_type = '1-DAY RENTAL' THEN 3
                 WHEN active_flag = 'N' AND cl.common_lookup_type = '3-DAY RENTAL' THEN 10
                 WHEN active_flag = 'N' AND cl.common_lookup_type = '5-DAY RENTAL' THEN 15
                 WHEN i.release_date+1 > (SYSDATE-1) AND cl.common_lookup_type = '1-DAY RENTAL' THEN 3
                 WHEN i.release_date+1 > (SYSDATE-1) AND cl.common_lookup_type = '3-DAY RENTAL' THEN 10
                 WHEN i.release_date+1 > (SYSDATE-1) AND cl.common_lookup_type = '5-DAY RENTAL' THEN 15
                 WHEN active_flag = 'Y' AND i.release_date +1 < (SYSDATE-1) THEN cl.common_lookup_code
             END AS "amount"

             FROM     item i CROSS JOIN
                (SELECT 'Y' AS active_flag FROM dual
                 UNION ALL
                 SELECT 'N' AS active_flag FROM dual) af CROSS JOIN
                (SELECT '1' AS rental_days FROM dual
                 UNION ALL
                 SELECT '3' AS rental_days FROM dual
                 UNION ALL
                 SELECT '5' AS rental_days FROM dual) dr INNER JOIN
                 common_lookup cl ON dr.rental_days = SUBSTR(cl.common_lookup_type,1,1)
        WHERE    cl.common_lookup_table = 'PRICE'
        AND      cl.common_lookup_column = 'PRICE_TYPE'
        AND NOT (active_flag ='N' AND (TRUNC(SYSDATE)-30) < TRUNC(i.release_date))
        ORDER BY 1, 2, 3) il);

I get the error at

,      il.amount

and this is what it says

Error report -
SQL Error: ORA-00904: "IL"."AMOUNT": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:
*Action:

Any help would be appreciated, if you need more info, just ask. Thanks

Body:
By using quotes for alias names you specify a particalur case sensitive name.

CASE ... END AS "amount"

specifies the alias name to be "amount" in lowercase. If you want to access it, use excatly the same spelling. E.g. "Amount" would be invalid.

You are trying to access

il.amount

and as there are no quotes, you say: "I don't care about upper/lower case". That works when accessing table and column names directly or when using an alias name without quotes. But as you used "amount" before, amount cannot be found (you were lucky if it would; I guess it could  happen with an alias name with all upper chars, as Oracle uses upper chars for its names internally, but you wouldn't want to rely on this).

I suggest you just remove the quotes. Try to avoid them whenever possible. Use names that work without quotes (which you are actually already doing; none of your alias names contains any blank, leading digit or whatever).


问:
Plotting a graph with flot using sqlite db information
I'm trying to read data from the internal sqlite database, and plot a graph using flot based
on this data.

I have an activity which inserts data into the db, accesses the db and even returns an
array with the desired data.

I also have an activity which creates a webview, and adds a javascript interface to a class
so that I can use flot and javascript to create the graph.

Both of these activities function perfectly individually but my problem lies in getting the
array of db data to a javascript interface class so that it can be accessed from javascript.

I've tried to use "Bundle.getExtra()"..etc.. to send the array from one activity to the other, but when
I go to retrieve it in the js class it can only be retrieved from the onCreate method, and hence
cannot be accessed from a javascript interface.

This is driving me crazy, any help at all would be much appreciated.

Thank you,
D

答:
Note sure what you want, but here i go:

If you want to fill out some data from a query you could do it quick and easy by doing something like this in php:

```<code><?php
foreach($res in $query )
{
echo "var d1 = [[0, ". $res['xxx'] ."], [1, ". $res['yyy'] ."], [2, ". $res['zzz'] ."]];";
}
?>
</code>```

where you normally fill in the datavalues. You might even use Ajax, and then i recomend reading http://api.jquery.com/jQuery.get/

Body:
Note sure what you want, but here i go:

If you want to fill out some data from a query you could do it quick and easy by doing something like this in php:

<?php
foreach($res in $query )
{
echo "var d1 = [[0, ". $res['xxx'] ."], [1, ". $res['yyy'] ."], [2, ". $res['zzz'] ."]];";
}
?>

where you normally fill in the datavalues. You might even use Ajax, and then i recomend reading http://api.jquery.com/jQuery.get/


问:
Addition of two variables in selenium IDE
I have store one value in one variable and second in other, now i want to make addition of those two number.I am not able to do that, I have  tried below code but its not working</p>

```<code><tr>
    <td>store</td>
    <td>6</td>
    <td>w</td>
</tr>
<tr>
    <td>store</td>
    <td>6</td>
    <td>x</td>
</tr>
<tr>
    <td>store</td>
    <td>javascript{storedVars['w'] + storedVars['x']}</td>
    <td>z</td>
</tr>
<tr>
    <td>echo</td>
    <td>${z}</td>
    <td></td>
</tr>
</code>```

答:
Be sure to add quotes around the variables...

So:

```<code><tr>
    <td>storeEval</td>
    <td>"${w}"+"${x}"</td>
    <td>z</td>
</tr>
</code>```

You might see some annoying semi-colon related errors if you don't!
Cheers!

Body:
I have store one value in one variable and second in other, now i want to make addition of those two number.I am not able to do that, I have  tried below code but its not working

    store
    6
    w

    store
    6
    x

    store
    javascript{storedVars['w'] + storedVars['x']}
    z

    echo
    ${z}

Body:
Be sure to add quotes around the variables...

So:

<tr>
    <td>storeEval</td>
    <td>&quot;${w}&quot;+&quot;${x}&quot;</td>
    <td>z</td>
</tr>

You might see some annoying semi-colon related errors if you don't!
Cheers!