问:
CakePHP Method Will Not Process Data AT ALL
I have a problem my code below will not process at all. It will not save or delete. I get a success message but nothing will save nor will nothing delete. I thought the method was a reserved keyword but then I tried to rename it and it still didn't work. Any insight would be enormously appreciated as this has stumped me.</p>

```<code>function approve() {
    $this->set('title', 'Approve Article');
    if ($this->RequestHandler->isPost() || $this->RequestHandler->isPut()) {
        if (empty($this->data['Article']['id'])) {
            $this->Session->setFlash('No article was passed.', 'message_error');
        } else {
            $this->Article->set($this->data);
            if ($this->Article->validates()) {
                if ($this->data['Article']['approved']) {
                    $this->data['Article']['content'] = $this->Safe->filter($this->data['Article']['content']);
                    $role = $this->Auth->user('role');
                    if ($role == 'Admin')
                        $this->Article->set('updated', strtotime($this->data['Article']['updated']));
                    else
                        $this->Article->set('updated', time());
                    $this->Article->set('updated', time());
                    $this->Article->save();
                    // Status
                    $status['Status']['type'] = 'Gain';
                    $status['Status']['amount'] = 20;
                    $status['Status']['created'] = time();
                    $this->Status->add($this->data['Article']['account_id'], $status);
                    $this->Session->setFlash('The article was approved and status was added.', 'message_success');
                } else {
                    $this->Article->delete($this->data['Article']['id']);
                    $this->Session->setFlash('The article was unapproved and deleted.', 'message_error');
                }
            } else {
                $this->Session->setFlash('Form Errors', 'message_error');
            }
        }
    }
    $unapproved_articles = $this->Article->find('count', array('conditions' => array('Article.approved =' => 0)));
    if ($unapproved_articles == 0) {
        $this->Session->setFlash('There are no unapproved articles.', 'message_success');
    } else {
        $article = $this->Article->find('first', array('order' => array('Article.created DESC')));
        $article['Article']['updated'] = date('d M Y', $article['Article']['updated']);
        $this->set('article', $article);
        $this->set('categories', $this->Category->dropdown());
        $this->set('accounts', $this->Account->dropdown());
    }
}
</code>```

答:
I think you need

```<code>$this->Article->save($this->data)
</code>```

You should also check that there are no callbacks that are preventing it from being saved in the model code. Make sure that you turn on debug to level 2 in the app/config/core.php file and look at the sql queries that get output before redirecting.

ContentLicense: CC BY-SA 2.5

Body:
I have a problem my code below will not process at all. It will not save or delete. I get a success message but nothing will save nor will nothing delete. I thought the method was a reserved keyword but then I tried to rename it and it still didn't work. Any insight would be enormously appreciated as this has stumped me.

function approve() {
    $this->set('title', 'Approve Article');
    if ($this->RequestHandler->isPost() || $this->RequestHandler->isPut()) {
        if (empty($this->data['Article']['id'])) {
            $this->Session->setFlash('No article was passed.', 'message_error');
        } else {
            $this->Article->set($this->data);
            if ($this->Article->validates()) {
                if ($this->data['Article']['approved']) {
                    $this->data['Article']['content'] = $this->Safe->filter($this->data['Article']['content']);
                    $role = $this->Auth->user('role');
                    if ($role == 'Admin')
                        $this->Article->set('updated', strtotime($this->data['Article']['updated']));
                    else
                        $this->Article->set('updated', time());
                    $this->Article->set('updated', time());
                    $this->Article->save();
                    // Status
                    $status['Status']['type'] = 'Gain';
                    $status['Status']['amount'] = 20;
                    $status['Status']['created'] = time();
                    $this->Status->add($this->data['Article']['account_id'], $status);
                    $this->Session->setFlash('The article was approved and status was added.', 'message_success');
                } else {
                    $this->Article->delete($this->data['Article']['id']);
                    $this->Session->setFlash('The article was unapproved and deleted.', 'message_error');
                }
            } else {
                $this->Session->setFlash('Form Errors', 'message_error');
            }
        }
    }
    $unapproved_articles = $this->Article->find('count', array('conditions' => array('Article.approved =' => 0)));
    if ($unapproved_articles == 0) {
        $this->Session->setFlash('There are no unapproved articles.', 'message_success');
    } else {
        $article = $this->Article->find('first', array('order' => array('Article.created DESC')));
        $article['Article']['updated'] = date('d M Y', $article['Article']['updated']);
        $this->set('article', $article);
        $this->set('categories', $this->Category->dropdown());
        $this->set('accounts', $this->Account->dropdown());
    }
}

Body:
I think you need

$this->Article->save($this->data)

You should also check that there are no callbacks that are preventing it from being saved in the model code. Make sure that you turn on debug to level 2 in the app/config/core.php file and look at the sql queries that get output before redirecting.


来源: stackexchange

问:
calculate angle between 2 vectors return value in degrees between 0 and 360
Hey I have the following code that calculates the angle in degrees:

```<code>var angleDeg = Math.atan2(mouse.y - base.y, mouse.x - base.x) * 180 / Math.PI;
console.log(angleDeg);
</code>```

but at the moment i get the angle between 0 and 180 degrees positive and negative. with 0 deg at the right see image. But i want the returned angles to be between 0 and 360 all positive. with the 0 deg at the top. see image.

How do i update my function so this works? I write this in javascript.
So in the end i want the angle values to be returned as the pink in the image. Any help is greatly appreciated!!!

hopefully this is clear if not pls let me know so i can update my question.

答:
You need to "rotate" your mouse.x and mouse.y coordinates about 90° (=swap y, x with -x, y) and add an offset of 180° (= Math.PI):

let base = {x: 100, y: 100};

document.addEventListener('mousemove', event => {
  let angle = Math.PI + Math.atan2(-event.x + base.x, event.y - base.y);
  console.log(angle * 180 / Math.PI);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="position: absolute; top: 100px; left: 100px">x</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
Hey I have the following code that calculates the angle in degrees:

var angleDeg = Math.atan2(mouse.y - base.y, mouse.x - base.x) * 180 / Math.PI;
console.log(angleDeg);

but at the moment i get the angle between 0 and 180 degrees positive and negative. with 0 deg at the right see image. But i want the returned angles to be between 0 and 360 all positive. with the 0 deg at the top. see image.

How do i update my function so this works? I write this in javascript.
So in the end i want the angle values to be returned as the pink in the image. Any help is greatly appreciated!!!

hopefully this is clear if not pls let me know so i can update my question.

Body:
You need to "rotate" your mouse.x and mouse.y coordinates about 90° (=swap y, x with -x, y) and add an offset of 180° (= Math.PI):

let base = {x: 100, y: 100};

document.addEventListener('mousemove', event => {
  let angle = Math.PI + Math.atan2(-event.x + base.x, event.y - base.y);
  console.log(angle * 180 / Math.PI);
});

<div style="position: absolute; top: 100px; left: 100px">x</div>


问:
NameError: name 'glob' is not defined
```<code>#coding=utf
import glob
glob.glob('/pycharm/*')
</code>```

I used to the python3.5 version ,
TypeError: 'module' object is not callable

```<code>#coding=utf
from glob import *
glob('/pycharm/*')
</code>```

It has another error,
NameError: name 'glob' is not defined

答:
Please check if "glob" is used as a variable in the code, before the import statement is called.

if "glob" is used as a variable, the original meaning of the module will change, giving the mentioned errors.

Title: NameError: name 'glob' is not defined

Body:
#coding=utf
import glob
glob.glob('/pycharm/*')

I used to the python3.5 version ,
TypeError: 'module' object is not callable

#coding=utf
from glob import *
glob('/pycharm/*')

It has another error,
NameError: name 'glob' is not defined


问:
OPC UA server client on raspberry pi2
Can anyone help me on how to install OPCUA server and client on raspberry pi 2. It is better if anyone could help me with command line.</p>

答:
You can use "freeopcua" pure Python OPC-UA client and server library.
Project home page: http://freeopcua.github.io/

Installation is quite easy but not very fast.
In my case it was enough to do following installations steps:

```<code>apt-get update
apt-get install libxml2-dev libxmlsec1-dev libffi-dev
pip install cryptography
pip install freeopcua
</code>```

Some examples.
Example client and server code in short form can be found here

Title: OPC UA server client on raspberry pi2

Body:
You can use "freeopcua" pure Python OPC-UA client and server library.
Project home page: http://freeopcua.github.io/

Installation is quite easy but not very fast.
In my case it was enough to do following installations steps:

apt-get update
apt-get install libxml2-dev libxmlsec1-dev libffi-dev
pip install cryptography
pip install freeopcua

Some examples.
Example client and server code in short form can be found here

ContentLicense: CC BY-SA 4.0


问:
Creating class with variables vs passing variables as parameters into a method

Which is a better way to do this, in terms of performance or other factors?

Say I am creating a class with jut one method in it that takes 2 values and adds them together.

Is it better to have 2 instance variables to store the 2 values then have a method which uses these, or is it better to just pass the variables in as parameters when calling the method?

Note: this class is only ever created just to use this method.

public class MyClass {
    int value1;
    int value2;

public MyClass(int value1, int value2){
    this.value1 = value1;
    this.value2 = value2;
}

public int MyMethod(){
    return value1 + value2;
}
```

<p>or this way:</p>

<pre class="lang-java prettyprint-override"><code>public class MyClass {

public MyClass(){

}

public int MyMethod(int value1, int value2){
    return value1 + value2;
}
</code>```

Or would it be better to just use a static method, so I don't need to create an object every time I use the method?

答:
Which is a better way to do this, in terms of performance or other
  factors?

These ways have no relation with performance. These are way of designing.

The first form (storing the arguments as fields):

```<code>public MyClass(int value1, int value2){
    this.value1 = value1;
    this.value2 = value2;
}

public int myMethod(){
    return value1 + value2;
}
</code>```

makes sense if you want to save the passed information in the class in order to be able to invoke myMethod() when you want (the creation of the object and the computation may be differed in the time) but also to use value1 and value2 later in another methods of the instance.

The second form (using only the arguments) makes sense if you want only compute the result :

```<code>public int myMethod(int value1, int value2){
    return value1 + value2;
}
</code>```

Use one or the other one according to your need.

Body:
Which is a better way to do this, in terms of performance or other factors?

Say I am creating a class with jut one method in it that takes 2 values and adds them together.

Is it better to have 2 instance variables to store the 2 values then have a method which uses these, or is it better to just pass the variables in as parameters when calling the method?

Note: this class is only ever created just to use this method.

public class MyClass {
    int value1;
    int value2;

public MyClass(int value1, int value2){
    this.value1 = value1;
    this.value2 = value2;
}

public int MyMethod(){
    return value1 + value2;
}

or this way:

public class MyClass {

public MyClass(){

}

public int MyMethod(int value1, int value2){
    return value1 + value2;
}

Or would it be better to just use a static method, so I don't need to create an object every time I use the method?

Body:
Which is a better way to do this, in terms of performance or other
  factors?

These ways have no relation with performance. These are way of designing.

The first form (storing the arguments as fields):

public MyClass(int value1, int value2){
    this.value1 = value1;
    this.value2 = value2;
}

public int myMethod(){
    return value1 + value2;
}

makes sense if you want to save the passed information in the class in order to be able to invoke myMethod() when you want (the creation of the object and the computation may be differed in the time) but also to use value1 and value2 later in another methods of the instance.

The second form (using only the arguments) makes sense if you want only compute the result :

public int myMethod(int value1, int value2){
    return value1 + value2;
}

Use one or the other one according to your need.


问:
Use a recursive query in a PostgreSQL function
I have a table folder with (id, name, parent_id ) columns. The folder which is parent it's parent_id = -1. I need to get top level parent Id of  each folder. The following query works fine, but it doesn't work with spring data jpa.

```<code>WITH RECURSIVE nodes_cte AS (
SELECT tn.id, tn.parent_id, tn.name, tn.id top_id
FROM folder AS tn
WHERE tn.parent_id =-1
UNION ALL
SELECT c.id, c.parent_id, c.name, p.top_id
FROM nodes_cte AS p, folder AS c
WHERE c.parent_id = p.id
)
SELECT distinct * FROM nodes_cte
</code>```

How can I create postgresql function which will return same result as above query?

答:
Create an SQL function returning a table:

```<code>CREATE OR REPLACE FUNCTION my_function()
RETURNS TABLE (id int, parent_id int, name text, top_id int)
LANGUAGE SQL AS $$
    WITH RECURSIVE nodes_cte AS (
    SELECT tn.id, tn.parent_id, tn.name, tn.id top_id
    FROM folder AS tn
    WHERE tn.parent_id =-1
    UNION ALL
    SELECT c.id, c.parent_id, c.name, p.top_id
    FROM nodes_cte AS p, folder AS c
    WHERE c.parent_id = p.id
    )
    SELECT distinct * FROM nodes_cte
$$;

--use:
SELECT *
FROM my_function();
</code>```

Note, the name column in a returned table should have the same type as in the table folder.

Body:
I have a table folder with (id, name, parent_id ) columns. The folder which is parent it's parent_id = -1. I need to get top level parent Id of  each folder. The following query works fine, but it doesn't work with spring data jpa.

WITH RECURSIVE nodes_cte AS (
SELECT tn.id, tn.parent_id, tn.name, tn.id top_id
FROM folder AS tn
WHERE tn.parent_id =-1
UNION ALL
SELECT c.id, c.parent_id, c.name, p.top_id
FROM nodes_cte AS p, folder AS c
WHERE c.parent_id = p.id
)
SELECT distinct * FROM nodes_cte

How can I create postgresql function which will return same result as above query?

Body:
Create an SQL function returning a table:

CREATE OR REPLACE FUNCTION my_function()
RETURNS TABLE (id int, parent_id int, name text, top_id int)
LANGUAGE SQL AS $$
    WITH RECURSIVE nodes_cte AS (
    SELECT tn.id, tn.parent_id, tn.name, tn.id top_id
    FROM folder AS tn
    WHERE tn.parent_id =-1
    UNION ALL
    SELECT c.id, c.parent_id, c.name, p.top_id
    FROM nodes_cte AS p, folder AS c
    WHERE c.parent_id = p.id
    )
    SELECT distinct * FROM nodes_cte
$$;

--use:
SELECT *
FROM my_function();

Note, the name column in a returned table should have the same type as in the table folder.


问:
Key Value Pair in C Language
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

```<code>struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";
</code>```

But I don't know how to access these values from this structure. Can someone enlight on this ?

答:
"I have to store 30 key/value pair"

Create an array of struct e.g., key_value.

```<code>struct key_value
{
    int key;
    char* value;
};

struct key_value kv[30];

kv[0].key = 1;
kv[0].value = "foo";

printf("%s", kv[0].value);
</code>```

You can loop through to assign values to keys and values.
Access to whatever is in kv is simple.

```<code>int i = kv[0].key`;// copy value of k[0].key to i
char *v = kv[0].value; // copy value of k[0].value to v;
</code>```

Title: Key Value Pair in C Language

Body:
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";

But I don't know how to access these values from this structure. Can someone enlight on this ?

Body:
"I have to store 30 key/value pair"

Create an array of struct e.g., key_value.

struct key_value
{
    int key;
    char* value;
};

struct key_value kv[30];

kv[0].key = 1;
kv[0].value = "foo";

printf("%s", kv[0].value);

You can loop through to assign values to keys and values.
Access to whatever is in kv is simple.

int i = kv[0].key`;// copy value of k[0].key to i
char *v = kv[0].value; // copy value of k[0].value to v;


问:
Can't retrive the good information from JSON on C#
I'm trying to get information from the Google API (YT). I need to take the videoId from the API of Google.

So I download the JSON page and trying to deserialize my result but he doesn't works.

This is the JSON result

```<code>    {
   "kind": "youtube#playlistItemListResponse",
   "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/E6IhaTG5XEbqo_uSYhCcIvQhtwY\"",
   "nextPageToken": "CDIQAA",
   "pageInfo": {
   "totalResults": 180,
   "resultsPerPage": 50
   },
  "items": [
  {
   "kind": "youtube#playlistItem",
   "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/0cAZGJiF62yaNO7GwJlJBsc7DqY\"",
   "id": "UExNQzlLTmtJbmNLdFB6Z1ktNXJtaHZqN2ZheDhmZHhvai41RDlFNzlCQjE5NzcyQTYx",
   "snippet": {
    "publishedAt": "2016-05-19T13:47:40.000Z",
    "channelId": "UCs72iRpTEuwV3y6pdWYLgiw",
    "title": "Katy Perry - Dark Horse (Official) ft. Juicy J",
    "description": "Bla bla bla",
    },
    "channelTitle": "#RedMusic: Just Hits",
    "playlistId": "PLMC9KNkIncKtPzgY-5rmhvj7fax8fdxoj",
    "position": 0,
    "resourceId": {
     "kind": "youtube#video",
     "videoId": "0KSOMA3QBU0"
    }
   }
  },
</code>```

And this is my code for taking the videoId

```<code>JObject jObj = (JObject)JsonConvert.DeserializeObject(x.Result);
foreach (var item in jObj["items"])
{
  string title = item["videoId"].ToString();
}
</code>```

And when I'm start my app I have an error with System.NullReferenceException.

Where is my problem ?

Thanks

答:
```<code>JObject jObj = (JObject)JsonConvert.DeserializeObject(json);
foreach (var item in jObj["items"])
{
    string title = item["resourceId"]["videoId"].ToString();
}
</code>```

You are missing ["resourceId"].

Body:
I'm trying to get information from the Google API (YT). I need to take the videoId from the API of Google.

So I download the JSON page and trying to deserialize my result but he doesn't works.

This is the JSON result

    {
   "kind": "youtube#playlistItemListResponse",
   "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/E6IhaTG5XEbqo_uSYhCcIvQhtwY\"",
   "nextPageToken": "CDIQAA",
   "pageInfo": {
   "totalResults": 180,
   "resultsPerPage": 50
   },
  "items": [
  {
   "kind": "youtube#playlistItem",
   "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/0cAZGJiF62yaNO7GwJlJBsc7DqY\"",
   "id": "UExNQzlLTmtJbmNLdFB6Z1ktNXJtaHZqN2ZheDhmZHhvai41RDlFNzlCQjE5NzcyQTYx",
   "snippet": {
    "publishedAt": "2016-05-19T13:47:40.000Z",
    "channelId": "UCs72iRpTEuwV3y6pdWYLgiw",
    "title": "Katy Perry - Dark Horse (Official) ft. Juicy J",
    "description": "Bla bla bla",
    },
    "channelTitle": "#RedMusic: Just Hits",
    "playlistId": "PLMC9KNkIncKtPzgY-5rmhvj7fax8fdxoj",
    "position": 0,
    "resourceId": {
     "kind": "youtube#video",
     "videoId": "0KSOMA3QBU0"
    }
   }
  },

And this is my code for taking the videoId

JObject jObj = (JObject)JsonConvert.DeserializeObject(x.Result);
foreach (var item in jObj["items"])
{
  string title = item["videoId"].ToString();
}

And when I'm start my app I have an error with System.NullReferenceException.

Where is my problem ?

Thanks

Body:
JObject jObj = (JObject)JsonConvert.DeserializeObject(json);
foreach (var item in jObj["items"])
{
    string title = item["resourceId"]["videoId"].ToString();
}

You are missing ["resourceId"].


问:
Write custom query in mongodb repository
I am writing custom query in mongo repository like this :

```<code>public interface AuthenticationTokenRepository extends MongoRepository<AuthenticationToken, String>
{

    AuthenticationToken save(AuthenticationToken token);

    AuthenticationToken findByToken(String token);

    @Query("{'user.username' : ?0}")
    AuthenticationToken findByUserId(String username);
}
</code>```

But when i tried to findout AuthenticationToken by id then it is not working.

```<code>@Query("{'user._id' : ?0}")
        AuthenticationToken findByUserId(String userId);
</code>```

My data in authentication table is as following:

```<code>> db.authenticationToken.find().pretty()
{
    "_id" : ObjectId("5565b4d444ae3b1a9228be87"),
    "_class" : "com.samepinch.domain.user.AuthenticationToken",
    "token" : "545c1d10-d769-41cf-a47c-2d698ec4df72",
    "user" : {
        "_id" : ObjectId("5565b4d444ae3b1a9228be86"),
        "age" : 0,
        "username" : "dinesh.dhiman@oodlestechnologies.com",
        "firstName" : "Dinesh Dhiman",
        "email" : "dinesh.dhiman@oodlestechnologies.com",
        "gender" : "male",
        "createdDate" : ISODate("2015-05-27T12:13:08.562Z"),
        "updatedDate" : ISODate("2015-05-27T12:13:08.562Z")
    },
    "createdDate" : ISODate("2015-05-27T12:13:08.605Z"),
    "updatedDate" : ISODate("2015-05-27T12:13:26.436Z")
}
</code>```

I want to fetch data on the basis of userId. Can anyone help me.

答:
In some versions of Spring you must use ObjectId class instead of String.
 So you can try something like this

```<code>@Query("{'user._id' : ?0}")
    AuthenticationToken findByUserId(ObjectId objectId);
</code>```

If you want to use this query in code, it will look something like this

```<code>String userId = "someUserId";
repository.findByUserId(new ObjectId(userId));
</code>```

Body:
I am writing custom query in mongo repository like this :

public interface AuthenticationTokenRepository extends MongoRepository<AuthenticationToken, String>
{

    AuthenticationToken save(AuthenticationToken token);

    AuthenticationToken findByToken(String token);

    @Query("{'user.username' : ?0}")
    AuthenticationToken findByUserId(String username);
}

But when i tried to findout AuthenticationToken by id then it is not working.

@Query("{'user._id' : ?0}")
        AuthenticationToken findByUserId(String userId);

My data in authentication table is as following:

> db.authenticationToken.find().pretty()
{
    "_id" : ObjectId("5565b4d444ae3b1a9228be87"),
    "_class" : "com.samepinch.domain.user.AuthenticationToken",
    "token" : "545c1d10-d769-41cf-a47c-2d698ec4df72",
    "user" : {
        "_id" : ObjectId("5565b4d444ae3b1a9228be86"),
        "age" : 0,
        "username" : "dinesh.dhiman@oodlestechnologies.com",
        "firstName" : "Dinesh Dhiman",
        "email" : "dinesh.dhiman@oodlestechnologies.com",
        "gender" : "male",
        "createdDate" : ISODate("2015-05-27T12:13:08.562Z"),
        "updatedDate" : ISODate("2015-05-27T12:13:08.562Z")
    },
    "createdDate" : ISODate("2015-05-27T12:13:08.605Z"),
    "updatedDate" : ISODate("2015-05-27T12:13:26.436Z")
}

I want to fetch data on the basis of userId. Can anyone help me.

Body:
In some versions of Spring you must use ObjectId class instead of String.
 So you can try something like this

@Query("{'user._id' : ?0}")
    AuthenticationToken findByUserId(ObjectId objectId);

If you want to use this query in code, it will look something like this

String userId = "someUserId";
repository.findByUserId(new ObjectId(userId));


问:
Unit testing, how to make spring management services do not pollute the database
I'm trying to use the spring and junit test DAO method, I see some of the practice on the Internet is the use of spring statement-style transaction management (@Transactional) for business operations, said that after the test is completed, the spring will let the test method back Roll, so as to achieve the purpose of testing.

Then I follow this approach to add the operation of the method of dao tested and found that the transaction submitted, the rollback is not successful, the database I came out of the test data. At first I thought it was spring did not roll back, but behind the observation console print information found to have rollback information, but why would fail, do not know. I found some related programs, but I found that did not solve my problem. Very troubled, hope to get your help!

The following is my code and file configuration

DAOImpl's addUser () method

```<code>@Override
public void addUser(User u) {
    Session session = sessionFactory.openSession();
    Transaction tc = session.getTransaction();
    try {
        tc.begin();
        session.save(u);
        tc.commit();
    }catch(Exception e){
        tc.rollback();
        e.printStackTrace();
    }
    return ;
}
</code>```

Daos.xml file configuration

```<code><bean id="txManager"

    class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="mySessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
</code>```

Test class

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/services.xml"})
@Transactional(transactionManager = "txManager")
@Rollback(true)
 public class UserServiceImplTest {
    @Autowired
    UserDAO userDAO;

    @Test
    public void testAddUse(){
        User u = new User();
        u.setLevel(3);
        u.setName("ab11");
        u.setPassword("hh");
        userDAO.addUser(u);
        Assert.assertEquals(u.getName(), userDAO.getUserList().get(userDAO.getUserList().size()-1).getName());
    }
</code>```

Some of the console prints information

```<code>INFO: Using DataSource [org.apache.commons.dbcp2.BasicDataSource@498d318c] of Hibernate SessionFactory for HibernateTransactionManager
    JUNE 02, 2017 4:46:19 afternoon org.springframework.test.context.transaction.TransactionContext startTransaction
INFO: Began transaction (1) for test context [DefaultTestContext@52d6cd34 testClass = UserServiceImplTest, testInstance = com.dxzh.mall.serviceImpl.test.UserServiceImplTest@715d6168, testMethod = testAddUse@UserServiceImplTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@75798d03 testClass = UserServiceImplTest, locations = '{classpath:/services.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.hibernate5.HibernateTransactionManager@c6634d]; rollback [true]
    Fri Jun 02 16:46:19 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Hibernate: insert into user (name, password, level) values (?, ?, ?)
    JUNE 02, 2017 4:46:19 afternoon org.springframework.test.context.transaction.TransactionContext endTransaction
INFO: Rolled back transaction for test context [DefaultTestContext@52d6cd34 testClass = UserServiceImplTest, testInstance = com.dxzh.mall.serviceImpl.test.UserServiceImplTest@715d6168, testMethod = testAddUse@UserServiceImplTest, testException = java.lang.RuntimeException, mergedContextConfiguration = [MergedContextConfiguration@75798d03 testClass = UserServiceImplTest, locations = '{classpath:/services.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]].
    JUNE 02, 2017 4:46:19 afternoon org.springframework.context.support.GenericApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext@3ffc5af1: startup date [Fri Jun 02 16:46:13 CST 2017]; root of context hierarchy
</code>```

答:
Sadly, you are mixing a pair of concepts here.

Your production code manages the transaction DIRECTLY, while your test code uses AOP (aspect oriented programming) spring annotations.

Since your production code manages the transaction, the AOP annotations in your test code are totally useless: the transaction witch rules is the one inside your production code.

The solution: use AOP in your production code also. Let the robust and well tested Spring transaction mechanism to manage the transaction and forget about managing it yourself. Something like this:

```<code>@Override
@Transactional(transactionManager = "txManager")
public void addUser(User u) {
    // only your bussiness logic here
}
</code>```

More info: here (example) and here(Spring manal)

This wikipedia article explains quite well different software testing approaches. Yours falls under the category integration test

Body:
I'm trying to use the spring and junit test DAO method, I see some of the practice on the Internet is the use of spring statement-style transaction management (@Transactional) for business operations, said that after the test is completed, the spring will let the test method back Roll, so as to achieve the purpose of testing.

Then I follow this approach to add the operation of the method of dao tested and found that the transaction submitted, the rollback is not successful, the database I came out of the test data. At first I thought it was spring did not roll back, but behind the observation console print information found to have rollback information, but why would fail, do not know. I found some related programs, but I found that did not solve my problem. Very troubled, hope to get your help!

The following is my code and file configuration

DAOImpl's addUser () method

@Override
public void addUser(User u) {
    Session session = sessionFactory.openSession();
    Transaction tc = session.getTransaction();
    try {
        tc.begin();
        session.save(u);
        tc.commit();
    }catch(Exception e){
        tc.rollback();
        e.printStackTrace();
    }
    return ;
}

Daos.xml file configuration

<bean id="txManager"

    class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="mySessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />

Test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/services.xml"})
@Transactional(transactionManager = "txManager")
@Rollback(true)
 public class UserServiceImplTest {
    @Autowired
    UserDAO userDAO;

    @Test
    public void testAddUse(){
        User u = new User();
        u.setLevel(3);
        u.setName("ab11");
        u.setPassword("hh");
        userDAO.addUser(u);
        Assert.assertEquals(u.getName(), userDAO.getUserList().get(userDAO.getUserList().size()-1).getName());
    }

Some of the console prints information

INFO: Using DataSource [org.apache.commons.dbcp2.BasicDataSource@498d318c] of Hibernate SessionFactory for HibernateTransactionManager
    JUNE 02, 2017 4:46:19 afternoon org.springframework.test.context.transaction.TransactionContext startTransaction
INFO: Began transaction (1) for test context [DefaultTestContext@52d6cd34 testClass = UserServiceImplTest, testInstance = com.dxzh.mall.serviceImpl.test.UserServiceImplTest@715d6168, testMethod = testAddUse@UserServiceImplTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@75798d03 testClass = UserServiceImplTest, locations = '{classpath:/services.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.hibernate5.HibernateTransactionManager@c6634d]; rollback [true]
    Fri Jun 02 16:46:19 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Hibernate: insert into user (name, password, level) values (?, ?, ?)
    JUNE 02, 2017 4:46:19 afternoon org.springframework.test.context.transaction.TransactionContext endTransaction
INFO: Rolled back transaction for test context [DefaultTestContext@52d6cd34 testClass = UserServiceImplTest, testInstance = com.dxzh.mall.serviceImpl.test.UserServiceImplTest@715d6168, testMethod = testAddUse@UserServiceImplTest, testException = java.lang.RuntimeException, mergedContextConfiguration = [MergedContextConfiguration@75798d03 testClass = UserServiceImplTest, locations = '{classpath:/services.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]].
    JUNE 02, 2017 4:46:19 afternoon org.springframework.context.support.GenericApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext@3ffc5af1: startup date [Fri Jun 02 16:46:13 CST 2017]; root of context hierarchy

Body:
Sadly, you are mixing a pair of concepts here.

Your production code manages the transaction DIRECTLY, while your test code uses AOP (aspect oriented programming) spring annotations.

Since your production code manages the transaction, the AOP annotations in your test code are totally useless: the transaction witch rules is the one inside your production code.

The solution: use AOP in your production code also. Let the robust and well tested Spring transaction mechanism to manage the transaction and forget about managing it yourself. Something like this:

@Override
@Transactional(transactionManager = "txManager")
public void addUser(User u) {
    // only your bussiness logic here
}

More info: here (example) and here(Spring manal)

This wikipedia article explains quite well different software testing approaches. Yours falls under the category integration test


问:
What is the difference between interfaces with function properties like "f()" and "f: () =>"?
Consider next A and B interfaces:

```<code>interface A {f(): number}
interface B {f: () => number}
</code>```

I've tried next things:

```<code>var a: A = {f: function() {return 1}}
var a: A = {f: () => 1}
var b: B = {f: function() {return 1}}
var b: B = {f: () => 1}
</code>```

Looks like the same.

答:
This:

```<code>interface A { f(): number }
</code>```

Is the notation for declaring a method, and this:

```<code>interface B { f: () => number }
</code>```

Is how to declare a property of a function type.

While there's no real difference when it comes to interfaces it makes more sense in a class:

```<code>class MyClass {
    fn1() {
        return 0;
    }

    fn2 = () => {
        return 0;
    }

    fn3 = function () {
        return 0;
    }
}
</code>```

Compiles to:

```<code>var MyClass = (function () {
    function MyClass() {
        this.fn2 = function () {
            return 0;
        };
        this.fn3 = function () {
            return 0;
        };
    }
    MyClass.prototype.fn1 = function () {
        return 0;
    };
    return MyClass;
}());
</code>```

As you can see only fn1 is a method attached to the prototype, while the other two are just properties (assigned in the constructor).

Body:
Consider next A and B interfaces:

interface A {f(): number}
interface B {f: () => number}

I've tried next things:

var a: A = {f: function() {return 1}}
var a: A = {f: () => 1}
var b: B = {f: function() {return 1}}
var b: B = {f: () => 1}

Looks like the same.

Body:
This:

interface A { f(): number }

Is the notation for declaring a method, and this:

interface B { f: () => number }

Is how to declare a property of a function type.

While there's no real difference when it comes to interfaces it makes more sense in a class:

class MyClass {
    fn1() {
        return 0;
    }

    fn2 = () => {
        return 0;
    }

    fn3 = function () {
        return 0;
    }
}

Compiles to:

var MyClass = (function () {
    function MyClass() {
        this.fn2 = function () {
            return 0;
        };
        this.fn3 = function () {
            return 0;
        };
    }
    MyClass.prototype.fn1 = function () {
        return 0;
    };
    return MyClass;
}());

As you can see only fn1 is a method attached to the prototype, while the other two are just properties (assigned in the constructor).


问:
PHP count cell data based on name
I've been doing a manual report for a while  on some data from a form and it's got quite excessive with the amount of data i'm getting now, it was 50 entries at first and now its over 500 so I need to find an easier way to manage it. I thought that a PHP program may make this easier.

Basically i have data like below, I need to sort by user and count how many leads each user has.

Columns

Username | Lead Source

Pete M, Lead 1

Fiona L, Lead 2

bare in mind that this csv file is quite large, I was wondering if anyone had a easier way to resolve this than me doing a manual excel formula.

many thanks,

答: Using Pivot tables is easier and more quicker</p>

Title: PHP count cell data based on name


问:
Mathjax not rendering TEX formulas dynamically from PHP/Ajax

var questions = {"ques_id":"1","question":"
\\\\(x = {-b \\\\pm \\\\sqrt{b^2-4ac} \\\\over 2a}\\\\)<\/span>   Test Question new with mathjax<\/p>","ques_type":"text_based_questions","correctAnswer":3,"choices":[{"option_id":"1","value":"Option A"},{"option_id":"2","value":"Option B"},{"option_id":"3","value":"Option C"},{"option_id":"4","value":"OPtion D"}]};

$('#test-question').html(questions.question);
MathJax.Hub.Queue(["Typeset",MathJax.Hub, 'test-question']);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        showProcessingMessages: false,
        tex2jax: { inlineMath: [['$','$'],['\\(','\\)']] }
      });
    </script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_HTMLorMML">
    </script>
    </head>
 <body>
    <h5 class="border-bottom">Instructions: Read the question, work out your answer and select the best option.</h5>
    <p><span class="math-tex">\( \left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right) \)</span></p>
  <div class="question" id="test-question"></div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
  </body>
</html></code>```

I'm getting the following question from Ajax request

MathJax is configured properly but the question coming from the JSON is not rendered by MathJax. The question are saved in MySQL database and are fetched by ajax request.

I tried everything but it still not working. Please help

答: From Json it added double slash. Plz remove that it will solve your problem.</p>

Body:
var questions = {"ques_id":"1","question":"
\\\\(x = {-b \\\\pm \\\\sqrt{b^2-4ac} \\\\over 2a}\\\\)<\/span>   Test Question new with mathjax<\/p>","ques_type":"text_based_questions","correctAnswer":3,"choices":[{"option_id":"1","value":"Option A"},{"option_id":"2","value":"Option B"},{"option_id":"3","value":"Option C"},{"option_id":"4","value":"OPtion D"}]};

$('#test-question').html(questions.question);
MathJax.Hub.Queue(["Typeset",MathJax.Hub, 'test-question']);

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">

Instructions: Read the question, work out your answer and select the best option.

\( \left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right) \)

I'm getting the following question from Ajax request

MathJax is configured properly but the question coming from the JSON is not rendered by MathJax. The question are saved in MySQL database and are fetched by ajax request.

I tried everything but it still not working. Please help


答:
This is easiest to compute if you make a chart of the values you have and what you expect instead.

Have -> Want

-180 -> 270

-90 -> 0

0 -> 90

90 -> 180

180 -> 270

We see that this can be split into two cases:

[-180, -90)

and

[-90, 180]

Case 1

[-180, -90) -> [270, 360)

The rule is simply +450

Case 2

[-90, 180] -> [0, 270]

This one is just +90

So we get our code

```<code>sanitize(angle){ // expecting angle within [-180, 180]
    if(angle < -90){
        return angle + 450;
    } else {
        return angle + 90;
    }
}
</code>```

Title: calculate angle between 2 vectors return value in degrees between 0 and 360

Body:
Hey I have the following code that calculates the angle in degrees:

var angleDeg = Math.atan2(mouse.y - base.y, mouse.x - base.x) * 180 / Math.PI;
console.log(angleDeg);

but at the moment i get the angle between 0 and 180 degrees positive and negative. with 0 deg at the right see image. But i want the returned angles to be between 0 and 360 all positive. with the 0 deg at the top. see image.

How do i update my function so this works? I write this in javascript.
So in the end i want the angle values to be returned as the pink in the image. Any help is greatly appreciated!!!

hopefully this is clear if not pls let me know so i can update my question.

Body:
This is easiest to compute if you make a chart of the values you have and what you expect instead.

Have -> Want

-180 -> 270

-90 -> 0

0 -> 90

90 -> 180

180 -> 270

We see that this can be split into two cases:

[-180, -90)

and

[-90, 180]

Case 1

[-180, -90) -> [270, 360)

The rule is simply +450

Case 2

[-90, 180] -> [0, 270]

This one is just +90

So we get our code

sanitize(angle){ // expecting angle within [-180, 180]
    if(angle < -90){
        return angle + 450;
    } else {
        return angle + 90;
    }
}


问:
Casting hex string to signed int results in different values in different platforms
I am dealing with an edge case in a program that I want to be multi-platform. Here is the extract of the problem:

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

void print_bits(size_t const size, void const * const ptr){
    unsigned char *b = (unsigned char*) ptr;
    unsigned char byte;
    int i, j;

    for (i=size-1;i>=0;i--)
    {
        for (j=7;j>=0;j--)
        {
            byte = (b[i] >> j) & 1;
            printf("%u", byte);
        }
    }
    puts("");
}

int main() {

char* ascii = "0x80000000";
int myint = strtol(ascii, NULL, 16);

printf("%s to signed int is %d and bits are:\t", ascii, myint);
print_bits(sizeof myint, &myint);

return 0;
}
</code>```

So when I compile with GCC on Linux I get this output:

```<code>0x80000000 to signed int is -2147483648 and bits are:   10000000000000000000000000000000
</code>```

On a Windows, using MSVC and MinGW I get:

```<code>0x80000000 to signed int is 2147483647 and bits are:    01111111111111111111111111111111
</code>```

I think the GCC outputs the correct expected values. My question is, where does this difference come from and how to make sure that on all compilers I get the correct result?

UPDATE

The reason behind this code is, I have to check if the MSB (bit #31) of the HEX value is 0 or 1. Then, I have to get the unsigned integer value of the next 7 bits (#30 to #24) result (in case of 0x80000000these 7 bits should result in 0:

```<code>    int msb_is_set = myint & 1;
    uint8_t next_7_bits;

next_7_bits = myint >> 24; //fine on GCC, outputs 0 for the next 7 bits
#ifdef WIN32 //If I do not do this, next_7_bit will be 127 on Windows instead of 0
    if(msb_is_set )
        next_7_bits = myint >> 1;
#endif
</code>```

P.S. This is on the same machine (i5 64bit)

答:
This is about your update. Although I'm not sure what your intention is, let's first point out some mistakes:

```<code>#ifdef WIN32
</code>```

The macro always defined when targeting win32 is _WIN32, not WIN32.

Then you have another #ifdef checking for GCC, but this will not do what you expect: GCC also exists on win32 and it uses the same data model as MSVC. IOW, you can have both defined, __GCC__ and _WIN32.

You say you want to know whether the MSB is set. Then just make sure to convert your string to an unsigned int and directly check this bit:

```<code>#include <limits.h>
// [...]
unsigned int myint = strtoul(ascii, NULL, 16); // <- strtoul(), not strtol()!
unsigned int msb = 1U << (sizeof(unsigned int) * CHAR_BIT - 1);
if (myint & msb)
{
    // msb is set
}
</code>```

Btw, see this answer for a really portable way to get the number of bits in an integer type. sizeof() * CHAR_BIT will fail on a platform with padding bits.

Body:
I am dealing with an edge case in a program that I want to be multi-platform. Here is the extract of the problem:

#include <stdio.h>
#include <string.h>

void print_bits(size_t const size, void const * const ptr){
    unsigned char *b = (unsigned char*) ptr;
    unsigned char byte;
    int i, j;

    for (i=size-1;i>=0;i--)
    {
        for (j=7;j>=0;j--)
        {
            byte = (b[i] >> j) & 1;
            printf("%u", byte);
        }
    }
    puts("");
}

int main() {

char* ascii = "0x80000000";
int myint = strtol(ascii, NULL, 16);

printf("%s to signed int is %d and bits are:\t", ascii, myint);
print_bits(sizeof myint, &myint);

return 0;
}

So when I compile with GCC on Linux I get this output:

0x80000000 to signed int is -2147483648 and bits are:   10000000000000000000000000000000

On a Windows, using MSVC and MinGW I get:

0x80000000 to signed int is 2147483647 and bits are:    01111111111111111111111111111111

I think the GCC outputs the correct expected values. My question is, where does this difference come from and how to make sure that on all compilers I get the correct result?

UPDATE

The reason behind this code is, I have to check if the MSB (bit #31) of the HEX value is 0 or 1. Then, I have to get the unsigned integer value of the next 7 bits (#30 to #24) result (in case of 0x80000000these 7 bits should result in 0:

    int msb_is_set = myint & 1;
    uint8_t next_7_bits;

next_7_bits = myint >> 24; //fine on GCC, outputs 0 for the next 7 bits
#ifdef WIN32 //If I do not do this, next_7_bit will be 127 on Windows instead of 0
    if(msb_is_set )
        next_7_bits = myint >> 1;
#endif

P.S. This is on the same machine (i5 64bit)

Body:
This is about your update. Although I'm not sure what your intention is, let's first point out some mistakes:

#ifdef WIN32

The macro always defined when targeting win32 is _WIN32, not WIN32.

Then you have another #ifdef checking for GCC, but this will not do what you expect: GCC also exists on win32 and it uses the same data model as MSVC. IOW, you can have both defined, __GCC__ and _WIN32.

You say you want to know whether the MSB is set. Then just make sure to convert your string to an unsigned int and directly check this bit:

#include <limits.h>
// [...]
unsigned int myint = strtoul(ascii, NULL, 16); // <- strtoul(), not strtol()!
unsigned int msb = 1U << (sizeof(unsigned int) * CHAR_BIT - 1);
if (myint & msb)
{
    // msb is set
}

Btw, see this answer for a really portable way to get the number of bits in an integer type. sizeof() * CHAR_BIT will fail on a platform with padding bits.


问:
Spark SQL long double values are coming with Exponential
I have a amount value, which we are reading from a file and trying to print on the console.

When we try to print, it is showing as Exponential and another issue is when we try to cast it is coming as null.

Input value:

```<code>{"amt":987654321111.0}
</code>```

Sample Code:

```<code>df.show();
df.registerTempTable("input");
DataFrame outputDF = sqlContext.sql("select cast(amt as decimal) from input");
outputDF.show();
</code>```

Output:

```<code>+----------------+
|             amt|
+----------------+
|9.87654321111E11|
+----------------+

root
 |-- amt: double (nullable = true)

root
 |-- amt: decimal(10,0) (nullable = true)

+----+
| amt|
+----+
|null|
+----+
</code>```

答:
Solved the issue using StructType createDecimalType method.

```<code>StructType schema = new StructType().add("amt", DataTypes.createDecimalType(38,10));

DataFrame df = sqlContext.read().schema(schema).json("test.json");
</code>```

Body:
I have a amount value, which we are reading from a file and trying to print on the console.

When we try to print, it is showing as Exponential and another issue is when we try to cast it is coming as null.

Input value:

{"amt":987654321111.0}

Sample Code:

df.show();
df.registerTempTable("input");
DataFrame outputDF = sqlContext.sql("select cast(amt as decimal) from input");
outputDF.show();

Output:

+----------------+
|             amt|
+----------------+
|9.87654321111E11|
+----------------+

root
 |-- amt: double (nullable = true)

root
 |-- amt: decimal(10,0) (nullable = true)

+----+
| amt|
+----+
|null|
+----+

Body:
Solved the issue using StructType createDecimalType method.

StructType schema = new StructType().add("amt", DataTypes.createDecimalType(38,10));

DataFrame df = sqlContext.read().schema(schema).json("test.json");


问:
Automapper cannot convert to a type
I am getting "Cannot Convert type 'PlanEntity' to 'TDestination'" compile time error while mocking my auto mapper in Unit Tests.

```<code>public TDestination Map<TSource, TDestination>(TSource source) where TDestination : class
            {
                var value = source as PlanEntity;
                if (value != null)
                {
                    return (TDestination)value;
                }

                return null;

            }
</code>```

However when I map IEnumerable it is running just fine.

```<code>public TDestination Map<TDestination>(object source) where TDestination : class
            {
                var value = source as IEnumerable<PlanEntity>;

                if (value != null)
                {
                    var results = value.Select(i =>
                        new PlanModel
                        {
                            Id = i.Id,
                            Name = i.Name
                        });

                    return (TDestination)results;
                }

                return null;
            }
</code>```

I have also tried doing this but it is giving the same error.

```<code>public TDestination Map<TSource, TDestination>(TSource source) where TDestination : class
            {
                var value = source as PlanEntity;
                if (value != null)
                {
                    var planModel = new PlanModel
                    {
                        Id = value.Id,
                        Name = value.Name
                    };
                    return (TDestination)planModel;
                }

                return null;

            }
</code>```

There are three overrides in my mockMapper class.

```<code>TDestination Map<TSource, TDestination>(TSource source) where TDestination : class;
TDestination Map<TSource, TDestination>(TSource source, TDestination destination) where TDestination : class;
TDestination Map<TDestination>(object source) where TDestination : class;
</code>```

Can anyone help me out with this ?

答:
var value = source as PlanEntity is assigning the source to the 'value' variable. However, you later try to cast this to the destination type - return (TDestination)value; These types will be different, causing your error.

In your first code block, you would need to add the following to make it equivalent to the second code block:

```<code>var planModel = new PlanModel() { Id = value.Id };
return (TDestination)planModel;
</code>```

Title: Automapper cannot convert to a type

Body:
I am getting "Cannot Convert type 'PlanEntity' to 'TDestination'" compile time error while mocking my auto mapper in Unit Tests.

public TDestination Map<TSource, TDestination>(TSource source) where TDestination : class
            {
                var value = source as PlanEntity;
                if (value != null)
                {
                    return (TDestination)value;
                }

                return null;

            }

However when I map IEnumerable it is running just fine.

public TDestination Map<TDestination>(object source) where TDestination : class
            {
                var value = source as IEnumerable<PlanEntity>;

                if (value != null)
                {
                    var results = value.Select(i =>
                        new PlanModel
                        {
                            Id = i.Id,
                            Name = i.Name
                        });

                    return (TDestination)results;
                }

                return null;
            }

I have also tried doing this but it is giving the same error.

public TDestination Map<TSource, TDestination>(TSource source) where TDestination : class
            {
                var value = source as PlanEntity;
                if (value != null)
                {
                    var planModel = new PlanModel
                    {
                        Id = value.Id,
                        Name = value.Name
                    };
                    return (TDestination)planModel;
                }

                return null;

            }

There are three overrides in my mockMapper class.

TDestination Map<TSource, TDestination>(TSource source) where TDestination : class;
TDestination Map<TSource, TDestination>(TSource source, TDestination destination) where TDestination : class;
TDestination Map<TDestination>(object source) where TDestination : class;

Can anyone help me out with this ?

Body:
var value = source as PlanEntity is assigning the source to the 'value' variable. However, you later try to cast this to the destination type - return (TDestination)value; These types will be different, causing your error.

In your first code block, you would need to add the following to make it equivalent to the second code block:

var planModel = new PlanModel() { Id = value.Id };
return (TDestination)planModel;


问:
Ajax $.getJSON method to return html and json together
Is there a way to fetch html data and json data together from the server using ajax getjson or any other method.

For example,

Fetch.php  contains following:

```<code>$count=$conn->rowCount();
while($fetch=$query->fetch()) {
echo "This is data";
}

$array=array("itemcount" => $count);
echo json_encode($array);
</code>```

What I want from above fetch.php file is to return html data as well as $count value.

```<code>$.getJSON( 'fetch.php', {'id': uid}, function(data){
    $('#results').append(data);
   $('#offset').(data.itemcount);
}
</code>```

But this is not working. It seems getjson method is not designed to display html data. Then at the same time I could not display json with $.POST method either.  What is the solution to this problem then?

Thanks
Nikhil

答:
```<code>$count=$conn->rowCount();
while($fetch=$query->fetch()) {
$msg = "This is data";
}

$array=array("msg" => $msg , "itemcount" => $count);
echo json_encode($array);
</code>```

Body:
Is there a way to fetch html data and json data together from the server using ajax getjson or any other method.

For example,

Fetch.php  contains following:

$count=$conn->rowCount();
while($fetch=$query->fetch()) {
echo "This is data";
}

$array=array("itemcount" => $count);
echo json_encode($array);

What I want from above fetch.php file is to return html data as well as $count value.

$.getJSON( 'fetch.php', {'id': uid}, function(data){
    $('#results').append(data);
   $('#offset').(data.itemcount);
}

But this is not working. It seems getjson method is not designed to display html data. Then at the same time I could not display json with $.POST method either.  What is the solution to this problem then?

Thanks
Nikhil


问:
Fullscreen API not working if triggered with F11
I implemented a fullscreen toggling feature for my application and it is actually working fine, tested on newest Chrome, Firefox, IE and Opera. I have one method for activating and one for deactivating fullscreen mode:

```<code>  public deactivateFullscreen(element) {
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.webkitRequestFullscreen) {
      document.webkitCancelFullScreen();
    } else if (element.mozRequestFullScreen) {
      document.mozCancelFullScreen();
    }else if(element.msRequestFullscreen){
      document.msExitFullscreen();
    }
  }

  public activateFullscreen(element) {
    if (element.requestFullScreen) {
      element.requestFullScreen();
    } else if (element.webkitRequestFullScreen) {
      element.webkitRequestFullScreen();
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    }else if(element.msRequestFullscreen){
      element.msRequestFullscreen();
    }
  }
</code>```

So when triggered from UI they both work fine. The only problem is once I enter fullscreen mode using F11 I cannot exit it using the deactivateFullscreen function. As far as I understand it for the browser no flag is set once I hit F11. I tried to test it using the following method:

```<code>  public isFullscreen(element) {
    if(element.webkitIsFullScreen || element.mozFullscreen || element.msFullscreenElement || element.fullscreenElement || element.fullscreen || element.webkitFullscreenElement || element.mozFullScreenElement){
      return true;
    }
    return false;
  }
</code>```

This always returns false, no matter whether I am in fullscreen or not. Is there any other way to detect if I the browser is currently in fullscreen mode? Or am I missing on some concept here?

Another thing I tried is to catch the keydown event for F11 and prevent its default action.

```<code>$document.on('keydown',this.fsHandle);

  public fsHandle(event:KeyboardEvent){
    if(event.keyCode == 122){
      event.preventDefault();
      this._isFullscreen = !this._isFullscreen;
    }
  }
</code>```

Using this method I expected to supress any F11 events in order to process the fullscreen toggling manually via code. Unfortunately this also does not work. The reason seems a little odd, the keydown-event is simply not triggered while I am already in fullscreen. Hence I can supress the event outside the fullscreen mode but not once I entered it.

Update:
Some research showed that security concerns of browser vendors are the reason for this behaviour. Still there has to be a way to handle this kind of features.

答:
It seems impossible as of now.

See this question that was asking exact same thing.
But it's an evolving situation that deserves being revisited from time to time, so here are some details I gathered.

One comment there said:

This fullscreen window mode is OS dependent, only at an app level, and not tied to any API available to us poor web-devs. [...] You won't find any cross-browser/cross-OS hack (I don't even know any for my own browser/OS). The only way you could get something would be through [a] more powerful API, giving you an application access to the browser's window.

The API that allows to programmatically control fullscreen state is defined in  fullscreen spec, and I was hoping it would shed light on the issue. Browsers do not fully implement it yet (e.g. document.exitFullscreen() is not implemented in Chrome and document.webkitExitFullscreen() does not return a Promise), but it gives hints about where things are going. Unfortunately it does not mention the pre-existing full-screen browser feature (the one triggered by F11), so it's difficult to say how this would evolve.

For now, F11-fullscreen and programmatic-fullscreen are 2 different things, although not entirely isolated from one another. Also, on macOS for example, browser's "full screen" feature is completely different, as it does take the whole screen but can still leave address bar and/or tabs shown.

If you check this demo page for a library that wraps browser-specific implementations, you can see that:

When programmatically setting body or any element fullscreen, the browser applies special CSS rules (e.g. background becomes black).

This does not happen with F11-fullscreen

This also does not happen with programmatic fullscreen on document (document.documentElement), so that's the closest you can get from F11-fullscreen.

But that does not make F11-FS and programmatic-FS-on-doc-element equivalent:

animated transitions are different (and actually a bit clunky for example on Firefox and programmatic-fullscreen on document element, as it fades to black in anticipation of black background, but there is no black background when fullscreened element is document, as stated above)

When F11-fullscreened, document.documentElement === (document.msFullscreenElement || document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement) is false, but true when programmatic-fullscreen-on-document-element (verified on Chrome & Firefox & IE11)

F11 key can exit programmatic-fullscreen, but programmatic-exitFullscreen cannot exit F11-fullscreen. Which is the problem you are running into. Also, Esc key cannot exit F11-fullscreen, but does exit programmatic-fullscreen.

So, what should we do then?

Since there are 2 different features, maybe it's OK to leave them be: if users enter F11-fullscreen, they will know how to exit by just pressing the same key again. If they enter programmatic-fullscreen with your UI controls, make sure you make it as obvious how to exit. It might be (understandably) frustrating as a dev not to be able to control both 100%, but in practice users will probably be fine, as they will use one or the other.

Body:
I implemented a fullscreen toggling feature for my application and it is actually working fine, tested on newest Chrome, Firefox, IE and Opera. I have one method for activating and one for deactivating fullscreen mode:

  public deactivateFullscreen(element) {
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.webkitRequestFullscreen) {
      document.webkitCancelFullScreen();
    } else if (element.mozRequestFullScreen) {
      document.mozCancelFullScreen();
    }else if(element.msRequestFullscreen){
      document.msExitFullscreen();
    }
  }

  public activateFullscreen(element) {
    if (element.requestFullScreen) {
      element.requestFullScreen();
    } else if (element.webkitRequestFullScreen) {
      element.webkitRequestFullScreen();
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    }else if(element.msRequestFullscreen){
      element.msRequestFullscreen();
    }
  }

So when triggered from UI they both work fine. The only problem is once I enter fullscreen mode using F11 I cannot exit it using the deactivateFullscreen function. As far as I understand it for the browser no flag is set once I hit F11. I tried to test it using the following method:

  public isFullscreen(element) {
    if(element.webkitIsFullScreen || element.mozFullscreen || element.msFullscreenElement || element.fullscreenElement || element.fullscreen || element.webkitFullscreenElement || element.mozFullScreenElement){
      return true;
    }
    return false;
  }

This always returns false, no matter whether I am in fullscreen or not. Is there any other way to detect if I the browser is currently in fullscreen mode? Or am I missing on some concept here?

Another thing I tried is to catch the keydown event for F11 and prevent its default action.

$document.on('keydown',this.fsHandle);

  public fsHandle(event:KeyboardEvent){
    if(event.keyCode == 122){
      event.preventDefault();
      this._isFullscreen = !this._isFullscreen;
    }
  }

Using this method I expected to supress any F11 events in order to process the fullscreen toggling manually via code. Unfortunately this also does not work. The reason seems a little odd, the keydown-event is simply not triggered while I am already in fullscreen. Hence I can supress the event outside the fullscreen mode but not once I entered it.

Update:
Some research showed that security concerns of browser vendors are the reason for this behaviour. Still there has to be a way to handle this kind of features.


问:
How do I call Visual Studio 2017 RC's version of MSBuild from a BAT file?
Earlier versions of MSBuild could be found here: %programfiles(x86)%\msbuild\<version>\bin\msbuild.exe.

But for Visual Studio 2017RC the path is %programfiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\msbuild.exe. The type of install: enteprise, community or professional, seems to be part of the path. And that makes it difficult to specify the correct path to msbuild in a BAT file that should work on many different computers with different versions of Visual Studio 2017.

What is the best way to call Visual Studio 2017 RC's version of Msbuild from a bat file?  Or from PowerShell?

答:
Simplest way...

Install the Build Tools https://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=BuildTools&rel=15

Profit; the build tools will install to a separate location thats standard across everywhere you install it regardless of your VS SKU (professional / enterprise / community all install to different paths)

New location C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\msbuild.exe


问:
How to draw a circle with OpenGL(LWJGL specifically) using VBOs
I am currently learning LWJGL(LightWeight Java Game Library), the OpenGL-Java port, and am trying to figure out how to draw a circle using VBOs.

When I search for code samples concerning my problem (I search OpenGL b/c the syntax of OpenGL & LWJGL are quite similar), all I find is people using glBegin(GL_QUADS) and such, which I don't like due to its poor performance and its insufficiency. I know it uses thing like Math.PI and such(I've taken Geometry, the math is not the hard part in my opinion).

I want to know how I would get the X and Y values I receive from using Math.cos & Math.sin into the VBO, b/c when using glDrawArrays, you have to specify the number of vertices.

答:
//You Can use this small glBegin() code and convert into VBO</p>

```<code>double k=0;
    glBegin(GL_POINTS);
    for(k=0;k<=360;k+=0.1){
    glVertex2f((float)(x+r*Math.cos(Math.toRadians(k))),(float)(y-r*Math.sin(Math.toRadians(k))));
    }
    glEnd();
</code>```

Body:
//You Can use this small glBegin() code and convert into VBO

double k=0;
    glBegin(GL_POINTS);
    for(k=0;k<=360;k+=0.1){
    glVertex2f((float)(x+r*Math.cos(Math.toRadians(k))),(float)(y-r*Math.sin(Math.toRadians(k))));
    }
    glEnd();


问:
MySQL round() not working as expected with sum()
I'm using the following query;

```<code>select round(sum(quantity * calories)) as calories
from tableName;
</code>```

where quantity and calories are of type double and having the values 1.00 & 110.50 respectively. I'm expecting an output of 111, but the above query is instead giving me 110. But if I execute a simple query like the below,

```<code>select round (110.50);
</code>```

It's giving me 111 as the output. I went through this Link, and used a query like the following;

```<code>select round(sum(cast(quantity * calories as char))) as calories
from tableName;
</code>```

but this one also not working for me and giving 110 as output. Can someone tell how to arrive at the desired output of 111?

答:
TRY:::</p>

```<code>SELECT ROUND ( CAST ( SUM (quantity * calories) AS DECIMAL(10,4))) AS calories
FROM tableName;
</code>```

Body:
I'm using the following query;

select round(sum(quantity * calories)) as calories
from tableName;

where quantity and calories are of type double and having the values 1.00 & 110.50 respectively. I'm expecting an output of 111, but the above query is instead giving me 110. But if I execute a simple query like the below,

select round (110.50);

It's giving me 111 as the output. I went through this Link, and used a query like the following;

select round(sum(cast(quantity * calories as char))) as calories
from tableName;

but this one also not working for me and giving 110 as output. Can someone tell how to arrive at the desired output of 111?

Body:
TRY:::

SELECT ROUND ( CAST ( SUM (quantity * calories) AS DECIMAL(10,4))) AS calories
FROM tableName;


问:
What is HibernateTemplate class?
I am new in Hibernate currently want to implement the Hibernate Template  classes , any one please tell me about the Hibernate Template classes.

xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/test" />
        <property name="username" value="root" />
        <property name="password" value="mnrpass" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>employee.hbm.xml</value>
            </list>
        </property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </bean>
    <bean id="springHibernateExample" class="com.javarticles.spring.hibernate.SpringHibernateExample">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>
</code>```

答:
HibernateTemplate is a helper class that is used to simplify the data access code. This class supports automatically converts HibernateExceptions which is a checked exception into DataAccessExceptions which is an unchecked exception. HibernateTemplate is typically used to implement data access or business logic services. The central method is execute(), that supports the Hibernate code that implements HibernateCallback interface.
Define HibernateTemplate.

org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

HibernateTemplate benefits :

HibernateTemplate simplifies interactions with Hibernate Session.

The functions that are common are simplified to single method calls.

The sessions get automatically closed.

The exceptions get automatically caught and are converted to runtime exceptions.

Visit this link for the proper example

http://www.javarticles.com/2015/04/spring-hibernatetempate-example.html

Title: What is HibernateTemplate class?

Body:
I am new in Hibernate currently want to implement the Hibernate Template  classes , any one please tell me about the Hibernate Template classes.

xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/test" />
        <property name="username" value="root" />
        <property name="password" value="mnrpass" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>employee.hbm.xml</value>
            </list>
        </property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </bean>
    <bean id="springHibernateExample" class="com.javarticles.spring.hibernate.SpringHibernateExample">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>


问:
jQuery UI sortable border bottom on drag
I have a working jQuery UI sortable. Around every item is a border but to prevent a double border between the items I've removed the border bottom on the items. Instead I added a border bottom on the container.

http://jsfiddle.net/6oxdwb6g/1/

While it looks correct it first sight, it does not work well when starting to drag the elements. At that point it shows that the item has no border bottom. How can I both have a border around the item on drag and at the same time prevent a double border when not dragging?

html

```<code><ul id="sortable">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
</code>```

css

```<code>#sortable {
    list-style-type: none;
    margin: 20px;
    padding: 0;
    border-bottom: 1px solid #ddd;
}

#sortable li {
    border: 1px solid #ddd;
    border-bottom: none;
    padding: 20px;
}
</code>```

js

```<code>$(function() {
  $( "#sortable" ).sortable();
 });
</code>```

答:
I found the solution myself. Keeping border only to the li element and add a negative margin to it did the trick.

http://jsfiddle.net/6oxdwb6g/2/

```<code>#sortable {
    list-style-type: none;
    margin: 20px;
    padding: 0;
}

#sortable li {
    border: 1px solid #ddd;
    padding: 20px;
    margin-bottom: -1px;
}
</code>```

Body:
I have a working jQuery UI sortable. Around every item is a border but to prevent a double border between the items I've removed the border bottom on the items. Instead I added a border bottom on the container.

http://jsfiddle.net/6oxdwb6g/1/

While it looks correct it first sight, it does not work well when starting to drag the elements. At that point it shows that the item has no border bottom. How can I both have a border around the item on drag and at the same time prevent a double border when not dragging?

html

1

2

3

css

#sortable {
    list-style-type: none;
    margin: 20px;
    padding: 0;
    border-bottom: 1px solid #ddd;
}

#sortable li {
    border: 1px solid #ddd;
    border-bottom: none;
    padding: 20px;
}

js

$(function() {
  $( "#sortable" ).sortable();
 });

Body:
I found the solution myself. Keeping border only to the li element and add a negative margin to it did the trick.

http://jsfiddle.net/6oxdwb6g/2/

#sortable {
    list-style-type: none;
    margin: 20px;
    padding: 0;
}

#sortable li {
    border: 1px solid #ddd;
    padding: 20px;
    margin-bottom: -1px;
}


问:
How to change the Keyboard layout on Solaris
I am running a machine with SunOS and NO graphical enviroment. Does someone know how to change the keyboard layout from the console??

Thanks

答: have a look at the loadkeys command</p>

Body: have a look at the loadkeys command

OwnerDisplayName: howlingmadhowie


问:
BigQuery: Querying with standard sql
I have this table:

```<code>client_id   session_id  time    action  transaction_id
------------------------------------------------------
1   1   15:01   view    NULL
1   1   15:02   basket  NULL
1   1   15:03   basket  NULL
1   1   15:04   purchase    1
1   2   15:05   basket  NULL
1   2   15:06   purchase    2
1   2   15:07   view    NULL
</code>```

And I want inside the session, for all the previous actions to register the transaction_id that occur for the first time (therefore at 15:03 transaction_id = NULL)

```<code>session_id  time    transaction_id
------------------------------------
1   15:01   1
1   15:02   1
1   15:03   NULL
1   15:04   1
2   15:05   2
2   15:06   2
2   15:07   NULL
</code>```

答:
Hmmm . . . assuming that there is only one transaction id per session, then you can use window functions:</p>

```<code>select t.*,
       (case when row_number() over (partition by client_id, session_id, action
                                     order by time) = 1
             then max(transactc
ion_id) over (partition by client_id, session_id)
        end) as new_transaction_id
from t
</code>```

Title: BigQuery: Querying with standard sql

Body:
I have this table:

client_id   session_id  time    action  transaction_id
------------------------------------------------------
1   1   15:01   view    NULL
1   1   15:02   basket  NULL
1   1   15:03   basket  NULL
1   1   15:04   purchase    1
1   2   15:05   basket  NULL
1   2   15:06   purchase    2
1   2   15:07   view    NULL

And I want inside the session, for all the previous actions to register the transaction_id that occur for the first time (therefore at 15:03 transaction_id = NULL)

session_id  time    transaction_id
------------------------------------
1   15:01   1
1   15:02   1
1   15:03   NULL
1   15:04   1
2   15:05   2
2   15:06   2
2   15:07   NULL

Body:
Hmmm . . . assuming that there is only one transaction id per session, then you can use window functions:

select t.*,
       (case when row_number() over (partition by client_id, session_id, action
                                     order by time) = 1
             then max(transactc
ion_id) over (partition by client_id, session_id)
        end) as new_transaction_id
from t


问:
Key Value Pair in C Language
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

```<code>struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";
</code>```

But I don't know how to access these values from this structure. Can someone enlight on this ?

答:
Here is an example:</p>

```<code>#include <stdio.h>
#include <stdlib.h>
struct key_value
{
    int key;
    char* value;
};

int main(void)
{
    int number_of_keys = 2;
    struct key_value *kv = malloc(sizeof(struct key_value) * number_of_keys);
    if (kv == NULL) {
        perror("Malloc");
        exit(EXIT_FAILURE);
    }

    kv[0].key = 8;
    kv[0].value = "Test 8 key!";

    kv[1].key = 6;
    kv[1].value = "Test 6 key!";

    printf("Key = %d\nKey value = %s\n", kv[0].key, kv[0].value);
    printf("Key = %d\nKey value = %s\n", kv[1].key, kv[1].value);

    free(kv);
    return 0;
}
</code>```

Title: Key Value Pair in C Language

Body:
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";

But I don't know how to access these values from this structure. Can someone enlight on this ?

Body:
Here is an example:

#include <stdio.h>
#include <stdlib.h>
struct key_value
{
    int key;
    char* value;
};

int main(void)
{
    int number_of_keys = 2;
    struct key_value *kv = malloc(sizeof(struct key_value) * number_of_keys);
    if (kv == NULL) {
        perror("Malloc");
        exit(EXIT_FAILURE);
    }

    kv[0].key = 8;
    kv[0].value = "Test 8 key!";

    kv[1].key = 6;
    kv[1].value = "Test 6 key!";

    printf("Key = %d\nKey value = %s\n", kv[0].key, kv[0].value);
    printf("Key = %d\nKey value = %s\n", kv[1].key, kv[1].value);

    free(kv);
    return 0;
}


问:
Swift 3- How to get button in UICollectionViewCell work
I am trying to implement an Edit button inside a cell.

Please refer to image:

What I done so far:

MainController:

```<code>class MainController: UICollectionViewController, UICollectionViewDelegateFlowLayout  {
  let imgCellId = "imgCellId"

  override func viewDidLoad() {
    collectionView?.backgroundColor = .white
    collectionView?.register(ImgItemCell.self, forCellWithReuseIdentifier: imgCellId)
  }

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
      cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

      return cell
  }

  func buttonPressed(){
    print("buttonPressed !")
  }

}
</code>```

ImgItemCell:

```<code>import Material

class ImgItemCell: UICollectionViewCell{

   override init(frame: CGRect){
       super.init(frame: frame)

       setupViews()
   }
   ...
   let editButton: RaisedButton = {
       let button = RaisedButton(title: "Edit", titleColor: .black) return button
   }()

  func setupViews(){
     ...
     addSubview(editButton)
     ...
  }

}
</code>```

Result: The button is not clickable. No log is printed when clicking on the button.

In android, I have done this by OnClickListener of button to perform action for each row. How can I do the same in Swift 3?

Solution: (it's working for me)

Hi all thank you for all suggestions, they’re more less the hint for me to come to the solution.

The root cause of my problem is view hierarchy (as @DatForis pointed out)

Explanation: I want a cell contains image and a layout of buttons so that I had view hierarchy as below

```<code>override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
    buttonLayout.addSubView(buttonList)
            buttonList.addSubview(editButton)
            buttonList.addSubview(shareButton)
  }
</code>```

this hierarchy somehow blocked the click event of button.

Therefore, I changed a bit in hierarchy

```<code>  override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
            buttonLayout.addSubview(editButton)
            buttonLayout.addSubview(shareButton)
   }
</code>```

and BAM ! it worked like a charm.

In fact, I need a proper explanation about why the hierarchy impact to children view.

By the way, I think most replies here are workable solution, but I selected @DonMag as final answer, because it’s clean and clear with a cool callback to Controller.

But again, my root problem is from view hierarchy.

答:
How your buttonpress method will know,you are selecting which cell button.So you can differentiate with tag

Add in cellForItemAtindexPath

```<code>ButtonObject.tag = indexPath.item
</code>```

and

```<code>func buttonPressed(_ sender: UIButton)
    {
        print("buttonPressed ! \(sender.tag)")
    }
</code>```

Body:
I am trying to implement an Edit button inside a cell.

Please refer to image:

What I done so far:

MainController:

class MainController: UICollectionViewController, UICollectionViewDelegateFlowLayout  {
  let imgCellId = "imgCellId"

  override func viewDidLoad() {
    collectionView?.backgroundColor = .white
    collectionView?.register(ImgItemCell.self, forCellWithReuseIdentifier: imgCellId)
  }

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
      cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

      return cell
  }

  func buttonPressed(){
    print("buttonPressed !")
  }

}

ImgItemCell:

import Material

class ImgItemCell: UICollectionViewCell{

   override init(frame: CGRect){
       super.init(frame: frame)

       setupViews()
   }
   ...
   let editButton: RaisedButton = {
       let button = RaisedButton(title: "Edit", titleColor: .black) return button
   }()

  func setupViews(){
     ...
     addSubview(editButton)
     ...
  }

}

Result: The button is not clickable. No log is printed when clicking on the button.

In android, I have done this by OnClickListener of button to perform action for each row. How can I do the same in Swift 3?

Solution: (it's working for me)

Hi all thank you for all suggestions, they’re more less the hint for me to come to the solution.

The root cause of my problem is view hierarchy (as @DatForis pointed out)

Explanation: I want a cell contains image and a layout of buttons so that I had view hierarchy as below

override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
    buttonLayout.addSubView(buttonList)
            buttonList.addSubview(editButton)
            buttonList.addSubview(shareButton)
  }

this hierarchy somehow blocked the click event of button.

Therefore, I changed a bit in hierarchy

  override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
            buttonLayout.addSubview(editButton)
            buttonLayout.addSubview(shareButton)
   }

and BAM ! it worked like a charm.

In fact, I need a proper explanation about why the hierarchy impact to children view.

By the way, I think most replies here are workable solution, but I selected @DonMag as final answer, because it’s clean and clear with a cool callback to Controller.

But again, my root problem is from view hierarchy.

Body:
How your buttonpress method will know,you are selecting which cell button.So you can differentiate with tag

Add in cellForItemAtindexPath

ButtonObject.tag = indexPath.item

and

func buttonPressed(_ sender: UIButton)
    {
        print("buttonPressed ! \(sender.tag)")
    }


问:
CMake dependency conflict with same header file names
I am stuck in CMake dependency issue. CMake does not rebuild the program when I modified the CXX header files.

My file structure is as such

```<code>$ tree
.
├── a
│   ├── a.h
│   └── c.h
├── b
│   ├── b.h
│   └── c.h
├── CMakeLists.txt
└── main.cxx
</code>```

File contents:

a.h

```<code>$ cat a/a.h
#include "c.h"
</code>```

b.h

```<code>$ cat b/b.h
#include "c.h"
</code>```

main.cxx

```<code>$ cat main.cxx
#include "a/a.h"
#include "b/b.h"
int main()
{
}
</code>```

CMake depend.internal

```<code>$ cat CMakeFiles/hello.dir/depend.internal
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.7

CMakeFiles/hello.dir/main.cxx.o
 /proj/mtk09331/work/tmp/cmake/a/a.h
 /proj/mtk09331/work/tmp/cmake/a/c.h
 /proj/mtk09331/work/tmp/cmake/b/b.h
 /proj/mtk09331/work/tmp/cmake/main.cxx
</code>```

CMakeLists.txt:

```<code>$ cat CMakeLists.txt
add_executable(hello main.cxx)
</code>```

As you can see, b/c.h does not exist in the dependency list.
Therefore, CMake won't rebuild the program if I modified b/c.h.

Does cmake not allow the same header file names?
Altough it works with renaming the header files.
But I would like to find a "correct" way to prevents this.

Thanks in advance

答:
As @MABVT notes in the comment, CMake is unrelated here: the question is about proper projects' organization.

From the point of projects' organization, headers for every project can be devided into two parts:

private headers, which are used only for compile the project itself,

public headers, which are used by the outer world (by other projects).

Naming and organization of private headers are fully up to the project's author.

But for scalable projects naming and organization of their public headers should follow several rules:

Name of the public header should be unique among all projects.

Usually this is achived by moving these headers into the directory contained the name of the project.

Public header shouldn't include private header.

Public header should include other public header using only its unique name.

As you can see, headers a/a.h and b/b.h are public in your case.

But for headers a/c.h and b/c.h you should decide, whether they are public or private.

If you want to make a/c.h private, then public header a/a.h cannot include it (rule 2).

If you want to make a/c.h public, then public header a/a.h should include it using its unique name, that is #include  (rule 3).

Body:
I am stuck in CMake dependency issue. CMake does not rebuild the program when I modified the CXX header files.

My file structure is as such

$ tree
.
├── a
│   ├── a.h
│   └── c.h
├── b
│   ├── b.h
│   └── c.h
├── CMakeLists.txt
└── main.cxx

File contents:

a.h

$ cat a/a.h
#include "c.h"

b.h

$ cat b/b.h
#include "c.h"

main.cxx

$ cat main.cxx
#include "a/a.h"
#include "b/b.h"
int main()
{
}

CMake depend.internal

$ cat CMakeFiles/hello.dir/depend.internal
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.7

CMakeFiles/hello.dir/main.cxx.o
 /proj/mtk09331/work/tmp/cmake/a/a.h
 /proj/mtk09331/work/tmp/cmake/a/c.h
 /proj/mtk09331/work/tmp/cmake/b/b.h
 /proj/mtk09331/work/tmp/cmake/main.cxx

CMakeLists.txt:

$ cat CMakeLists.txt
add_executable(hello main.cxx)

As you can see, b/c.h does not exist in the dependency list.
Therefore, CMake won't rebuild the program if I modified b/c.h.

Does cmake not allow the same header file names?
Altough it works with renaming the header files.
But I would like to find a "correct" way to prevents this.

Thanks in advance

Body:
As @MABVT notes in the comment, CMake is unrelated here: the question is about proper projects' organization.

From the point of projects' organization, headers for every project can be devided into two parts:

private headers, which are used only for compile the project itself,

public headers, which are used by the outer world (by other projects).

Naming and organization of private headers are fully up to the project's author.

But for scalable projects naming and organization of their public headers should follow several rules:

Name of the public header should be unique among all projects.

Usually this is achived by moving these headers into the directory contained the name of the project.

Public header shouldn't include private header.

Public header should include other public header using only its unique name.

As you can see, headers a/a.h and b/b.h are public in your case.

But for headers a/c.h and b/c.h you should decide, whether they are public or private.

If you want to make a/c.h private, then public header a/a.h cannot include it (rule 2).

If you want to make a/c.h public, then public header a/a.h should include it using its unique name, that is #include <a/c.h> (rule 3).


问:
C# - FrameworkElement.FindName returns null
I spent the past one hour trying to figure this out. I have a CheckBox inside DataGrid as follows:

```<code><DataGridTemplateColumn>
    <DataGridTemplateColumn.Header>
        <CheckBox Name="chkall" Content="Select All" Checked="chkall_Checked" Unchecked="chkall_Unchecked"/>
    </DataGridTemplateColumn.Header>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Tag="{Binding Path=id}" x:Name="chksingle"  Checked="chksingle_Checked" Unchecked="chksingle_Unchecked"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</code>```

As you can see I am trying to check and uncheck the CheckBoxes inside DataGrid rows when the CheckBox in the header is checked or unchecked. This is the code where I am trying to retrieve the CheckBox and mark it as checked:

```<code>private void chkall_Checked(object sender, RoutedEventArgs e)
{
    foreach (var r in userDG.Items)
    {
        DataGridRow row =(DataGridRow)userDG.ItemContainerGenerator.ContainerFromItem(r);
        FrameworkElement FW_element = userDG.Columns[0].GetCellContent(row);
        FW_element.ApplyTemplate();
        var checkbox = FW_element.FindName("chksingle") as CheckBox;
        checkbox.IsChecked = false;
    }
}
</code>```

I have already tried RegisterName() method and I've tried VisualTreeHelper but nothing works.

This line always returns null:

```<code>var checkbox = FW_element.FindName("chksingle") as CheckBox;
</code>```

Here is a WPF visualizer screenshot for my FrameworkElement where I can clearly see the checkbox I am trying to find:

Please tell me what am I doing wrong? Thank you.

答:
Try this:</p>

```<code>FrameworkElement FW_element = userDG.Columns[0].GetCellContent(row);
CheckBox checkbox = VisualTreeHelper.GetChild(FW_element, 0) as CheckBox;
</code>```

Body:
I spent the past one hour trying to figure this out. I have a CheckBox inside DataGrid as follows:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.Header>
        <CheckBox Name="chkall" Content="Select All" Checked="chkall_Checked" Unchecked="chkall_Unchecked"/>
    </DataGridTemplateColumn.Header>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Tag="{Binding Path=id}" x:Name="chksingle"  Checked="chksingle_Checked" Unchecked="chksingle_Unchecked"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

As you can see I am trying to check and uncheck the CheckBoxes inside DataGrid rows when the CheckBox in the header is checked or unchecked. This is the code where I am trying to retrieve the CheckBox and mark it as checked:

private void chkall_Checked(object sender, RoutedEventArgs e)
{
    foreach (var r in userDG.Items)
    {
        DataGridRow row =(DataGridRow)userDG.ItemContainerGenerator.ContainerFromItem(r);
        FrameworkElement FW_element = userDG.Columns[0].GetCellContent(row);
        FW_element.ApplyTemplate();
        var checkbox = FW_element.FindName("chksingle") as CheckBox;
        checkbox.IsChecked = false;
    }
}

I have already tried RegisterName() method and I've tried VisualTreeHelper but nothing works.

This line always returns null:

var checkbox = FW_element.FindName("chksingle") as CheckBox;

Here is a WPF visualizer screenshot for my FrameworkElement where I can clearly see the checkbox I am trying to find:

Please tell me what am I doing wrong? Thank you.

Body:
Try this:

FrameworkElement FW_element = userDG.Columns[0].GetCellContent(row);
CheckBox checkbox = VisualTreeHelper.GetChild(FW_element, 0) as CheckBox;


问:
Problems with Android Dialog and sliding out keyboard
My Android application puts up a Dialog with and Edit Text field. If the dialog is displayed with the slide out keyboard closed and then the keyboard is opened, the dialog box (sometimes) disappears. The application goes off into never-never land. I am using a LG Alley.

Is there an event for opening a keyboard slider? An event I can capture and gain control over this situation? Any advice as to how to deal with this?

答:
I think you're possibly seeing the result of a 'configuration change' - see Handling Runtime Changes.

Things like a change in device orientation or opening/closing a 'hard' keyboard cause the currently running Activity to be destroyed and re-created and you need to restore things to the way they were before the change.

Not so much listening for an event but more a case of being able to 'retrace your steps' from the start.