问:
Converting given string to List<Class> in Java
I have a string discounts with value:

```<code>"[{\"startInterval\":0,\"endInterval\":3,\"discount\":1000.0},
 {\"startInterval\":3,\"endInterval\":6,\"discount\":750.0},
 {\"startInterval\":6,\"endInterval\":9,\"discount\":500.0},
 {\"startInterval\":9,\"endInterval\":12,\"discount\":10.0}]"
</code>```

My Discount class has model:

```<code>public class Discount  {

    private int startInterval;
    private int endInterval;
    private double discount;

    public Discount() {

    }

    public int getStartInterval() {
        return startInterval;
    }

    public void setStartInterval(int startInterval) {
        this.startInterval = startInterval;
    }

    public int getEndInterval() {
        return endInterval;
    }

    public void setEndInterval(int endInterval) {
        this.endInterval = endInterval;
    }

    public Double getDiscount() {
        return discount;
    }

    public void setDiscount(Double discount) {
        this.discount = discount;
    }

}
</code>```

I want to serialize the string to List<Discount>. How do I do that? I have tried converting the string to JSONArray (gson and json), but I'm getting some errors.

Note that:

```<code>[{"startInterval":0,"endInterval":3,"discount":1000.0},
 {"startInterval":3,"endInterval":6,"discount":750.0},
 {"startInterval":6,"endInterval":9,"discount":500.0},
 {"startInterval":9,"endInterval":12,"discount":10.0}]
</code>```

is stored in mysql db. I am fetching this into a string discounts, then trying to serialize it.

答:
With GSON:</p>

```<code>String json = /* your json */
Type type = new TypeToken<List<Discount>>().getType();
List<Discount> discounts = new Gson().fromJson(json , type);
</code>```

Body:
I have a string discounts with value:

"[{\"startInterval\":0,\"endInterval\":3,\"discount\":1000.0},
 {\"startInterval\":3,\"endInterval\":6,\"discount\":750.0},
 {\"startInterval\":6,\"endInterval\":9,\"discount\":500.0},
 {\"startInterval\":9,\"endInterval\":12,\"discount\":10.0}]"

My Discount class has model:

public class Discount  {

    private int startInterval;
    private int endInterval;
    private double discount;

    public Discount() {

    }

    public int getStartInterval() {
        return startInterval;
    }

    public void setStartInterval(int startInterval) {
        this.startInterval = startInterval;
    }

    public int getEndInterval() {
        return endInterval;
    }

    public void setEndInterval(int endInterval) {
        this.endInterval = endInterval;
    }

    public Double getDiscount() {
        return discount;
    }

    public void setDiscount(Double discount) {
        this.discount = discount;
    }

}

I want to serialize the string to List<Discount>. How do I do that? I have tried converting the string to JSONArray (gson and json), but I'm getting some errors.

Note that:

[{"startInterval":0,"endInterval":3,"discount":1000.0},
 {"startInterval":3,"endInterval":6,"discount":750.0},
 {"startInterval":6,"endInterval":9,"discount":500.0},
 {"startInterval":9,"endInterval":12,"discount":10.0}]

is stored in mysql db. I am fetching this into a string discounts, then trying to serialize it.

Body:
With GSON:

String json = /* your json */
Type type = new TypeToken<List<Discount>>().getType();
List<Discount> discounts = new Gson().fromJson(json , type);


来源: stackexchange

问:
How do you set the UserState in the RunWorkerCompletedEventArgs object?
HI all.
I have an array of BackgroundWorker objects running instances of a Worker class.  When I call the Worker class the object instance does it's thing and then runs out of code (the loop finishes).  I'm able to listen to the RunWorkerCompleted() event but when it calls the delegate that I've set up I need to know which of my Worker objects just completed.

I see a UserState property in the RunWorkerCompletedEventArgs that comes to my delegate but I have no idea how to set this in my Worker object as it's finishing.

Any ideas?

snippet from my WorkManager.cs class

```<code>public Worker AddWorker()
{
    Worker w = new Worker();

    _workers.Add(w.WorkerID,w);

    BackgroundWorker bg = new BackgroundWorker();
    _bgworkers.Add(bg);

    bg.DoWork += w.Start;
    bg.WorkerReportsProgress = true;
    bg.WorkerSupportsCancellation = true;
    bg.ProgressChanged += ProcessWorkerMessage;
    bg.RunWorkerCompleted += WorkerFinished;

    w.WorkManager = this;
    w.BackgroundWorker = bg;

    bg.RunWorkerAsync(w);

    return w;

}

public void WorkerFinished(object sender, RunWorkerCompletedEventArgs e)
{
    if (_onManagerEvent != null)
        _onManagerEvent(new ManagerEvent { EventDate = DateTime.Now, Message = "Worker ??? successfully ended." });
}
</code>```

So when my Worker object finishes the loop in its Start() method, what do I do to fill the userState property of the RunWorkerCompleteEventArgs object "e" that is passed to my WorkerFinished method()?

Thanks

答:
That UserState thing is a known bug in BackgroundWorker:

http://www.pluralsight-training.net/community/blogs/mike/archive/2005/10/21/15783.aspx (archive.org link…original link is dead)

What I've done in the past when I've been in your situation is either use RunWorkerCompletedEventArgs.Result (as Philip suggests), or, if possible, have my worker derive from BackgroundWorker (then I can add as much extra state as I want, and get the whole worker as the sender argument to the events raised by BackgroundWorker, while still being able to use Result for its intended purpose).

ContentLicense: CC BY-SA 2.5

Body:
HI all.
I have an array of BackgroundWorker objects running instances of a Worker class.  When I call the Worker class the object instance does it's thing and then runs out of code (the loop finishes).  I'm able to listen to the RunWorkerCompleted() event but when it calls the delegate that I've set up I need to know which of my Worker objects just completed.

I see a UserState property in the RunWorkerCompletedEventArgs that comes to my delegate but I have no idea how to set this in my Worker object as it's finishing.

Any ideas?

snippet from my WorkManager.cs class

public Worker AddWorker()
{
    Worker w = new Worker();

    _workers.Add(w.WorkerID,w);

    BackgroundWorker bg = new BackgroundWorker();
    _bgworkers.Add(bg);

    bg.DoWork += w.Start;
    bg.WorkerReportsProgress = true;
    bg.WorkerSupportsCancellation = true;
    bg.ProgressChanged += ProcessWorkerMessage;
    bg.RunWorkerCompleted += WorkerFinished;

    w.WorkManager = this;
    w.BackgroundWorker = bg;

    bg.RunWorkerAsync(w);

    return w;

}

public void WorkerFinished(object sender, RunWorkerCompletedEventArgs e)
{
    if (_onManagerEvent != null)
        _onManagerEvent(new ManagerEvent { EventDate = DateTime.Now, Message = "Worker ??? successfully ended." });
}

So when my Worker object finishes the loop in its Start() method, what do I do to fill the userState property of the RunWorkerCompleteEventArgs object "e" that is passed to my WorkerFinished method()?

Thanks

ContentLicense: CC BY-SA 3.0


问:
display bootstrap navbar using react.js
I have a very simple React.js project where I am trying to add a bootstrap navbar to the project, but I can't seem to figure out how to get the navbar to display on the page.  The navbar example I am referencing can be found here, http://codepen.io/zhaozhiming/pen/LNGyvR

The project looks like the following,

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <title>My super cool title.</title>
</head>
<body>
  <div id="root"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <script src="bundle.js" ></script>
</body>
</html>
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.js';

ReactDOM.render(<App />, document.getElementById('root'));
</code>```

App.js

```<code>import React, {PropTypes} from 'react';
import styles from './App.css';
import NavBarTest from './common/NavBar-test';

const App = () => {
  return (
    <div id="parent">
      <div>Hello, App!</div>
      <NavBarTest {...NavBarTest} />
    </div>
  )
}

export default App;
</code>```

Navbar-test.js

```<code>import React from 'react';

// create classes
var NavBar = React.createClass({
  render: function(){
    return(
      <nav className="navbar navbar-inverse">
        <div className="container-fluid">
          <div className="navbar-header">
            <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false">
              <span className="sr-only">Toggle navigation</span>
              <span className="icon-bar"></span>
              <span className="icon-bar"></span>
              <span className="icon-bar"></span>
            </button>
            <NavBrand linkTo={this.props.brand.linkTo} text={this.props.brand.text} />
          </div>
          <div className="collapse navbar-collapse" id="navbar-collapse">
            <NavMenu links={this.props.links} />
          </div>
        </div>
      </nav>
    );
  }
});

var NavBrand = React.createClass({
  render: function(){
    return (
      <a className="navbar-brand" href={this.props.linkTo}>{this.props.text}</a>
    );
  }
});

var NavMenu = React.createClass({
  render: function(){
    var links = this.props.links.map(function(link){
      if(link.dropdown) {
        return (
          <NavLinkDropdown links={link.links} text={link.text} active={link.active} />
        );
      }
      else {
        return (
          <NavLink linkTo={link.linkTo} text={link.text} active={link.active} />
        );
      }
    });
    return (
      <ul className="nav navbar-nav">
        {links}
      </ul>
    );
  }
});

var NavLinkDropdown = React.createClass({
  render: function(){
    var active = false;
    var links = this.props.links.map(function(link){
      if(link.active){
        active = true;
      }
      return (
        <NavLink linkTo={link.linkTo} text={link.text} active={link.active} />
      );
    });
    return (
      <li className={"dropdown " + (active ? "active" : "")}>
        <a href="#" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
          {this.props.text}
          <span className="caret"></span>
        </a>
        <ul className="dropdown-menu">
          {links}
        </ul>
      </li>
    );
  }
});

var NavLink = React.createClass({
  render: function(){
    return(
      <li className={(this.props.active ? "active" : "")}><a href={this.props.linkTo}>{this.props.text}</a></li>
    );
  }
});

// set data
var navbar = {};
navbar.brand =
  {linkTo: "#", text: "React Bootstrap Navbar"};
navbar.links = [
  {linkTo: "#", text: "Link 1"},
  {linkTo: "#", text: "Link 2"},
  {dropdown: true, text: "Dropdown", links: [
    {linkTo: "#", text: "Dropdown Link 1"},
    {linkTo: "#", text: "Dropdown Link 2", active: true}
  ]}
];

export default NavBar;
</code>```

Finally, the page appears to render, but I am seeing the following error / warning message in the browser console.  Any help on how I can get this navbar to display on the page would greatly be appreciated.

答:
If this is for learning then do go ahead and create them all! Else I will suggest using react-bootstrap

https://react-bootstrap.github.io/components/navbar/

Title: display bootstrap navbar using react.js

Body:
I have a very simple React.js project where I am trying to add a bootstrap navbar to the project, but I can't seem to figure out how to get the navbar to display on the page.  The navbar example I am referencing can be found here, http://codepen.io/zhaozhiming/pen/LNGyvR

The project looks like the following,

index.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <title>My super cool title.</title>

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.js';

ReactDOM.render(<App />, document.getElementById('root'));

App.js

import React, {PropTypes} from 'react';
import styles from './App.css';
import NavBarTest from './common/NavBar-test';

const App = () => {
  return (

Hello, App!

      <NavBarTest {...NavBarTest} />

  )
}

export default App;

Navbar-test.js

import React from 'react';

// create classes
var NavBar = React.createClass({
  render: function(){
    return(

            <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false">
              Toggle navigation

            </button>
            <NavBrand linkTo={this.props.brand.linkTo} text={this.props.brand.text} />

            <NavMenu links={this.props.links} />

    );
  }
});

var NavBrand = React.createClass({
  render: function(){
    return (
      {this.props.text}
    );
  }
});

var NavMenu = React.createClass({
  render: function(){
    var links = this.props.links.map(function(link){
      if(link.dropdown) {
        return (
          <NavLinkDropdown links={link.links} text={link.text} active={link.active} />
        );
      }
      else {
        return (
          <NavLink linkTo={link.linkTo} text={link.text} active={link.active} />
        );
      }
    });
    return (

        {links}

    );
  }
});

var NavLinkDropdown = React.createClass({
  render: function(){
    var active = false;
    var links = this.props.links.map(function(link){
      if(link.active){
        active = true;
      }
      return (
        <NavLink linkTo={link.linkTo} text={link.text} active={link.active} />
      );
    });
    return (

          {this.props.text}

          {links}

    );
  }
});

var NavLink = React.createClass({
  render: function(){
    return(

{this.props.text}

    );
  }
});

// set data
var navbar = {};
navbar.brand =
  {linkTo: "#", text: "React Bootstrap Navbar"};
navbar.links = [
  {linkTo: "#", text: "Link 1"},
  {linkTo: "#", text: "Link 2"},
  {dropdown: true, text: "Dropdown", links: [
    {linkTo: "#", text: "Dropdown Link 1"},
    {linkTo: "#", text: "Dropdown Link 2", active: true}
  ]}
];

export default NavBar;

Finally, the page appears to render, but I am seeing the following error / warning message in the browser console.  Any help on how I can get this navbar to display on the page would greatly be appreciated.


问:
Amazon SES messages to SNS and SQS optimization
I am using Amazon SES for a project and have set up a Receipt rule to send messages from SES to SNS. The SNS has my API end point as a subscriber but to ensure that I do not miss any message I have also set up an SQS Queue and have subscribed the queue to SNS topic.

With this set up I receive each SES email twice. (One from SNS and one with a poll in SQS). Is there a way to send only the failed SNS messages to SQS queue so that I don't have to check for duplicates always ?

Rule which sends SES messages to SNS:

SQS queue subscribed to SNS topic:

答:
Short answer, no.

If you've subscribed an SQS queue to an SNS topic, it'll receive all messages published to the latter. SNS doesn't know which messages were successfully processed by your API, so can't selectively send to SQS.


问:
Using recursive folder delete and folder delete causes stack overflow
I'm using PHP's CLI for creating a program. There's a folder named /compile which holds all of the compiled files after it's CLI call, this folder gets the constant __COMPILE__. I'm using this function and using the constant to use as the location: (Location: C:\Users\Jeklin\Documents\GitHub\spitfire-engine\compiled):

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65488 bytes) in C:\Users\Jeklin\Documents\GitHub\spitfire-engine\sys\compiler\Launcher.compiler.php on line 66

This is the function I'm using:

```<code>/*59*/    public function p_sweep_compile_dir()
/*60*/      { $dir = __COMPILE__;
/*61*/        if (is_dir($dir)) {
/*62*/          $objects = scandir($dir);
/*63*/          foreach ($objects as $object) {
/*64*/            if ($object != "." && $object != "..") {
/*65*/              if (filetype($dir."/".$object) == "dir")
/*66*/                 $this->p_sweep_compile_dir($dir."/".$object);
/*67*/              else unlink   ($dir."/".$object);
/*68*/            }
/*69*/          }
/*70*/          reset($objects);
/*71*/          rmdir($dir);
/*72*/        } else die('tried to delete a non-folder from p_sweep_compile_dir');
/*73*/      }
</code>```

I can see that on line 66 that includes the recursion method to try to get deeper into the file structure, although the structure is very shallow, this is the __COMPILE__ directories setup:

```<code>|--compiled
     |---app
     |---public
     |---sys
     |index.html
</code>```

答:
Not sure who wrote that code but this would make more sense:

```<code>/*59*/    public function p_sweep_compile_dir($dir = null) // default $dir to null unless something is passed into it
/*60*/      { $dir = ($dir === null ? __COMPILE__ : $dir); // If $dir is null then use __COMPILE__ otherwise use the $dir value
/*61*/        if (is_dir($dir)) {
/*62*/          $objects = scandir($dir);
/*63*/          foreach ($objects as $object) {
/*64*/            if ($object != "." && $object != "..") {
/*65*/              if (filetype($dir."/".$object) == "dir")
/*66*/                 $this->p_sweep_compile_dir($dir."/".$object); // recurse self and provide deeper dir
/*67*/              else unlink   ($dir."/".$object);
/*68*/            }
/*69*/          }
/*70*/          reset($objects);
/*71*/          rmdir($dir);
/*72*/        } else die('tried to delete a non-folder from p_sweep_compile_dir');
/*73*/      }
</code>```

I have not tested this but in theory it should work.

See line #s 59, 60, and 66 for comments.

Side-note:

Assuming you have full control of this source code, for the love of all that is good in this world, please use opening and closing curly braces, ALWAYS. Some poor programmer is going to curse you for hours when they work on this after you stop working on it.

How I would write it:

```<code>public function p_sweep_compile_dir($dir = null) // default $dir to null unless something is passed into it
{
    $dir = ($dir === null ? __COMPILE__ : $dir); // If $dir is null then use __COMPILE__ otherwise use the $dir value

    if(is_dir($dir))
    {
        $objects = array_diff(scandir($dir), array('..', '.'));
        foreach ($objects as $object)
        {
            if(is_dir($dir."/".$object))
            {
                $this->p_sweep_compile_dir($dir."/".$object); // recurse self and provide deeper dir
            }
            else
            {
                unlink($dir."/".$object);
            }
        }
        unset($object, $objects); // forced memory management
        rmdir($dir);
    }
    else
    {
        die('tried to delete a non-folder from p_sweep_compile_dir');
    }

    unset($dir);
}
</code>```

Body:
I'm using PHP's CLI for creating a program. There's a folder named /compile which holds all of the compiled files after it's CLI call, this folder gets the constant __COMPILE__. I'm using this function and using the constant to use as the location: (Location: C:\Users\Jeklin\Documents\GitHub\spitfire-engine\compiled):

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65488 bytes) in C:\Users\Jeklin\Documents\GitHub\spitfire-engine\sys\compiler\Launcher.compiler.php on line 66

This is the function I'm using:

/*59*/    public function p_sweep_compile_dir()
/*60*/      { $dir = __COMPILE__;
/*61*/        if (is_dir($dir)) {
/*62*/          $objects = scandir($dir);
/*63*/          foreach ($objects as $object) {
/*64*/            if ($object != "." && $object != "..") {
/*65*/              if (filetype($dir."/".$object) == "dir")
/*66*/                 $this->p_sweep_compile_dir($dir."/".$object);
/*67*/              else unlink   ($dir."/".$object);
/*68*/            }
/*69*/          }
/*70*/          reset($objects);
/*71*/          rmdir($dir);
/*72*/        } else die('tried to delete a non-folder from p_sweep_compile_dir');
/*73*/      }

I can see that on line 66 that includes the recursion method to try to get deeper into the file structure, although the structure is very shallow, this is the __COMPILE__ directories setup:

|--compiled
     |---app
     |---public
     |---sys
     |index.html

Body:
Not sure who wrote that code but this would make more sense:

/*59*/    public function p_sweep_compile_dir($dir = null) // default $dir to null unless something is passed into it
/*60*/      { $dir = ($dir === null ? __COMPILE__ : $dir); // If $dir is null then use __COMPILE__ otherwise use the $dir value
/*61*/        if (is_dir($dir)) {
/*62*/          $objects = scandir($dir);
/*63*/          foreach ($objects as $object) {
/*64*/            if ($object != "." && $object != "..") {
/*65*/              if (filetype($dir."/".$object) == "dir")
/*66*/                 $this->p_sweep_compile_dir($dir."/".$object); // recurse self and provide deeper dir
/*67*/              else unlink   ($dir."/".$object);
/*68*/            }
/*69*/          }
/*70*/          reset($objects);
/*71*/          rmdir($dir);
/*72*/        } else die('tried to delete a non-folder from p_sweep_compile_dir');
/*73*/      }

I have not tested this but in theory it should work.

See line #s 59, 60, and 66 for comments.

Side-note:

Assuming you have full control of this source code, for the love of all that is good in this world, please use opening and closing curly braces, ALWAYS. Some poor programmer is going to curse you for hours when they work on this after you stop working on it.

How I would write it:

public function p_sweep_compile_dir($dir = null) // default $dir to null unless something is passed into it
{
    $dir = ($dir === null ? __COMPILE__ : $dir); // If $dir is null then use __COMPILE__ otherwise use the $dir value

    if(is_dir($dir))
    {
        $objects = array_diff(scandir($dir), array('..', '.'));
        foreach ($objects as $object)
        {
            if(is_dir($dir."/".$object))
            {
                $this->p_sweep_compile_dir($dir."/".$object); // recurse self and provide deeper dir
            }
            else
            {
                unlink($dir."/".$object);
            }
        }
        unset($object, $objects); // forced memory management
        rmdir($dir);
    }
    else
    {
        die('tried to delete a non-folder from p_sweep_compile_dir');
    }

    unset($dir);
}


问:
Django creating new project - access is denied
I'm trying to create a Django project with the command:

```<code>django-admin startproject mysite
</code>```

unfortunately, I get the error:

```<code>CommandError: [WinError 5] Access is denied: 'C\\Windows\\mysite'
</code>```

How can I resolve this error?

答:
Start the project in a different directory, for example in your home directory.

You likely don't have permission to create a subdirectory there, nor would you want to create a Django project under C:\Windows.

Body:
I'm trying to create a Django project with the command:

django-admin startproject mysite

unfortunately, I get the error:

CommandError: [WinError 5] Access is denied: 'C\\Windows\\mysite'

How can I resolve this error?


答:
Run this command as administrator.
In start menu right click on cmd and click on Run As Administrator.

Title: Django creating new project - access is denied


问:
Doctrine 2 Performance Answer
i have a question, i'm using doctrine for 4 years but i dont know if he load all data of a Entity (including relations) when we search the object e.g.:

```<code>$entity = $entityManager->find('Entity', $id);
</code>```

in this case, all relations attributes are setted?

i have a class with much attributes of relation (WITHOUT featch=eager), its cause overload?

Or doctrine knows that only relations is searched when you use a get method of attribute?

if you know a documentation, to clarify, please post a link

答:
Lazy loading is the default. The collection data is only retrieved from the database, at the time they are accessed for the first time.

If you want the data to be loaded directly, you need to JOIN the specific collection, and add it to the select clause. Or use the EAGER fetch mode like you mentioned.

From http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#entity-object-graph-traversal

[...] Instead of passing you back a real Author instance and a collection of comments Doctrine will create proxy instances for you. Only if you access these proxies for the first time they will go through the EntityManager and load their state from the database.

Also:

Traversing the object graph for parts that are lazy-loaded will easily trigger lots of SQL queries and will perform badly if used to heavily. Make sure to use DQL to fetch-join all the parts of the object-graph that you need as efficiently as possible.

Title: Doctrine 2 Performance Answer

Body:
i have a question, i'm using doctrine for 4 years but i dont know if he load all data of a Entity (including relations) when we search the object e.g.:

$entity = $entityManager->find('Entity', $id);

in this case, all relations attributes are setted?

i have a class with much attributes of relation (WITHOUT featch=eager), its cause overload?

Or doctrine knows that only relations is searched when you use a get method of attribute?

if you know a documentation, to clarify, please post a link


问:
MySQL, Concatenate two columns
There are two columns in a MySQL table: SUBJECT and YEAR.

I want to generate an alphanumeric unique number which holds the concatenated data from SUBJECT and YEAR.

How can I do this?  Is it possible to use a simple operator like +?

答:
You can use mysql built in CONCAT() for this.

```<code>SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;
</code>```

change field name as your requirement

then the result is

and if you want to concat same field using other field which same then

```<code>SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1
</code>```

then this is output

Title: MySQL, Concatenate two columns

Body:
You can use mysql built in CONCAT() for this.

SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;

change field name as your requirement

then the result is

and if you want to concat same field using other field which same then

SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1

then this is output

ContentLicense: CC BY-SA 4.0


问:
same fish and bash command for detecting python executable name
Within a Makefile I need to check whether python2 command exists and, if not, try with just python. Currently it works for bash/sh as follows:

```<code>PYTHON?=$(type -p python2 || echo python)
</code>```

(and then using $(PYTHON) within make tasks).

However it fails when using fish shell because it does not support || (but instead requires using or, which does not work in bash/sh):

```<code>foo@bar ~> echo $(type -p python2 || echo python)

Unsupported use of '||'. In fish, please use 'COMMAND; or COMMAND'.
fish: echo $(type -p python2 || echo python)
                              ^
</code>```

I can not figure out any approach that works for both bash/sh and fish. Any help please?

答:
OK, invalid. There were two issues, but were unrelated. In fact make uses  /bin/sh (unless SHELL variable is defined in the Makefile) to run like-shell commands within the Makefile itself.

It was failing due to another unrelated problem, sorry for the noise.

BTW:

https://www.gnu.org/software/make/manual/html_node/Choosing-the-Shell.html

The program used as the shell is taken from the variable SHELL. If this variable is not set in your makefile, the program /bin/sh is used as the shell.

Body:
Within a Makefile I need to check whether python2 command exists and, if not, try with just python. Currently it works for bash/sh as follows:

PYTHON?=$(type -p python2 || echo python)

(and then using $(PYTHON) within make tasks).

However it fails when using fish shell because it does not support || (but instead requires using or, which does not work in bash/sh):

foo@bar ~> echo $(type -p python2 || echo python)

Unsupported use of '||'. In fish, please use 'COMMAND; or COMMAND'.
fish: echo $(type -p python2 || echo python)
                              ^

I can not figure out any approach that works for both bash/sh and fish. Any help please?


问:
Draw Straight line between two points in vertical orientation using Opencv and C++
I have tried to draw a straight line using two reference points and I got some problems on vertical orientation.

That's the current source code:

```<code>cv::Mat img = cv::Mat::zeros(600,600,CV_8UC3);
cv::Point p1(306,41);
cv::Point p2(304,8);

cv::Point p(0,0), q(img.cols, img.rows);
if (p1.x != p2.x) {
    double m = (double) (p1.y - p2.y) / (double) (p1.x - p2.x);
    double b = p1.y - (m * p1.x);
    p.y = m * p.x + b;
    q.y = m * q.x + b;
} else {
    p.x = q.x = p2.x;
    p.y = 0;
    q.y = img.rows;
}

cv::circle(img, p1, 4, cv::Scalar(255,0,255), -1);
cv::circle(img, p2, 4, cv::Scalar(255,0,255), -1);
cv::line(img, p, q, cv::Scalar(0,0,255), 2);
</code>```

This is the following output:

What am I doing wrong?

答:
I had the same problem of you running on the 2.4.9 version. Given the Miki anwser it might have been fixed on newer versions.

The problem seems to happen when the line slope is too high and therefore the intersection with the y axis it is far away from the origin.

I tested the cited point,as well many others and the following function handled that problem. It basically computes the intersection of the computed line with the image borders and return collinear points in the image borders.

```<code>void getLinePointinImageBorder(const cv::Point& p1_in, const cv::Point& p2_in,
                               cv::Point& p1_out, cv::Point& p2_out,
                               int rows, int cols)
{
    double m = (double) (p1_in.y - p2_in.y) / (double) (p1_in.x - p2_in.x + std::numeric_limits<double>::epsilon());
    double b = p1_in.y - (m * p1_in.x);

    std::vector<cv::Point> border_point;
    double x,y;
    //test for the line y = 0
    y = 0;
    x = (y-b)/m;
    if(x > 0 && x < cols)
        border_point.push_back(cv::Point(x,y));

    //test for the line y = img.rows
    y = rows;
    x = (y-b)/m;
    if(x > 0 && x < cols)
        border_point.push_back(cv::Point(x,y));

    //check intersection with horizontal lines x = 0
    x = 0;
    y = m * x + b;
    if(y > 0 && y < rows)
        border_point.push_back(cv::Point(x,y));

    x = cols;
    y = m * x + b;
    if(y > 0 && y < rows)
        border_point.push_back(cv::Point(x,y));

    p1_out = border_point[0];
    p2_out = border_point[1];
}
</code>```

Body:
I have tried to draw a straight line using two reference points and I got some problems on vertical orientation.

That's the current source code:

cv::Mat img = cv::Mat::zeros(600,600,CV_8UC3);
cv::Point p1(306,41);
cv::Point p2(304,8);

cv::Point p(0,0), q(img.cols, img.rows);
if (p1.x != p2.x) {
    double m = (double) (p1.y - p2.y) / (double) (p1.x - p2.x);
    double b = p1.y - (m * p1.x);
    p.y = m * p.x + b;
    q.y = m * q.x + b;
} else {
    p.x = q.x = p2.x;
    p.y = 0;
    q.y = img.rows;
}

cv::circle(img, p1, 4, cv::Scalar(255,0,255), -1);
cv::circle(img, p2, 4, cv::Scalar(255,0,255), -1);
cv::line(img, p, q, cv::Scalar(0,0,255), 2);

This is the following output:

What am I doing wrong?

Body:
I had the same problem of you running on the 2.4.9 version. Given the Miki anwser it might have been fixed on newer versions.

The problem seems to happen when the line slope is too high and therefore the intersection with the y axis it is far away from the origin.

I tested the cited point,as well many others and the following function handled that problem. It basically computes the intersection of the computed line with the image borders and return collinear points in the image borders.

void getLinePointinImageBorder(const cv::Point& p1_in, const cv::Point& p2_in,
                               cv::Point& p1_out, cv::Point& p2_out,
                               int rows, int cols)
{
    double m = (double) (p1_in.y - p2_in.y) / (double) (p1_in.x - p2_in.x + std::numeric_limits<double>::epsilon());
    double b = p1_in.y - (m * p1_in.x);

    std::vector<cv::Point> border_point;
    double x,y;
    //test for the line y = 0
    y = 0;
    x = (y-b)/m;
    if(x > 0 && x < cols)
        border_point.push_back(cv::Point(x,y));

    //test for the line y = img.rows
    y = rows;
    x = (y-b)/m;
    if(x > 0 && x < cols)
        border_point.push_back(cv::Point(x,y));

    //check intersection with horizontal lines x = 0
    x = 0;
    y = m * x + b;
    if(y > 0 && y < rows)
        border_point.push_back(cv::Point(x,y));

    x = cols;
    y = m * x + b;
    if(y > 0 && y < rows)
        border_point.push_back(cv::Point(x,y));

    p1_out = border_point[0];
    p2_out = border_point[1];
}


问:
Check the open FD limit for a given process in Linux
I recently had a Linux process which “leaked” file descriptors: It opened them and didn't properly close some of them.

If I had monitored this, I could tell – in advance – that the process was reaching its limit.

Is there a nice, Bash or Python way to check the FD usage ratio for a given process in a Ubuntu Linux system?

EDIT:

I now know how to check how many open file descriptors are there; I only need to know how many file descriptors are allowed for a process. Some systems (like Amazon EC2) don't have the /proc/pid/limits file.

答:
In CentOS 6 and below (anything using GCC 3), you may find that adjusting the kernel limits does not resolve the issue. This is because there is a FD_SETSIZE value that is set at compile time in use by GCC. For this, you will need to increase the value and then re-compile the process.

Also, you may find that you are leaking file descriptors due to known issues in libpthread if you are using that library. This call was integrated into GCC in GCC 4 / CentOS7 / RHEL 7 and this seems to have fixed the threading issues.


问:
Visual Studio 2017 crash
We are running into a problem opening our MVC5 solution in Visual Studio 2017. It will show a message saying loading projects, followed by "Preparing solution" and then it just freezes. Some preliminary research has lead to suggestions like

Remove the hidden .vs folder

Repair installation by running as admin

Updating to the latest released VS build

Remove any node.js type folders that have deeply nested folder structure within the solution folder

However, none of these have worked. Has anyone else run into a similar problem using VS 2017 with their solution? There are no special commands on packages loaded on startup.

答: I installed visual studio enterprise 2017 version 15.0.0+26228.10. and productivity power tool extension. the studio keep crashing when load project. I uninstall everything and reinstall vs only, the crash problem disappeared. </p>

Title: Visual Studio 2017 crash


问:
django rest framework Serialization of foreign key
I just started to learn django rest framework and the following are files of my Topic app

======models.py=====

```<code>from django.contrib.auth.models import User
class Topic(models.Model):
    title = models.CharField(max_length=100,verbose_name="Topic Title")
    description = models.CharField(max_length=500, verbose_name="Topic Description")
    user = models.ForeignKey(to=User,related_name="user_topics")
</code>```

=====serializers.py=====

```<code>class TopicSerializer(ModelSerializer):
    class Meta:
        model = Topic
        fields = "__all__"
</code>```

=====views.py=====

```<code>class TopicViewSet(ModelViewSet):
    queryset = Topic.objects.all()
    serializer_class = TopicSerializer
</code>```

I'am able to create a "Topic" data using httpie as follows

```<code>http POST http://127.0.0.1:8989/api/v1/topics/ description="Learn Python" title="Python" user=1
</code>```

NOW my need is that the topic detail should have the "user" key expanded for the User - (While maintaining the same  "user" key to PASS user id to create a topic) ie.,

making a GET request to the detail should return the following

```<code>http GET http://127.0.0.1:8989/api/v1/topics/1/
=====
HTTP/1.0 200 OK

{
    "description": "Learn Python",
    "id": 1,
    "title": "Python",
    "user": { name:"blah blah"
        ...
        ...
     }
}
</code>```

AND

Making a post with user id in "user" key should create the "Topic" and should return the response with user expanded in "user" key ie.,

```<code>http POST http://127.0.0.1:8989/api/v1/topics/ description="Learn Python" title="Python" user=1
HTTP/1.0 201 Created
....

{
    "description": "Learn Python",
    "id": 1,
    "title": "Python",
    "user": { name:"blah blah", ...}
}
</code>```

What changes do i need to make, so that i will be able to use the SAME "user" key? for 3 following purpose

to make a POST with "user id" to create a Topic // user:1

The POST response returned while creating a Topic should have the user expanded in user key //user : { name:"blah blah", ...}

Also, to GET the detail expanded // user : { name:"blah blah", ...}

or
please suggest an better way of doing this.

答:
In ====serializers.py======= you can make these changes</p>

```<code>from rest_framework import serializers
from models import Topic

class TopicSerializer(ModelSerializer):
   title = serializers.CharField(max_length=100,verbose_name="Topic Title")
   description = serializers.CharField(max_length=500, verbose_name="Topic Description")
   user = serializers.PrimaryKeyRelatedField(queryset = User.objects.all(),related_name="user_topics")
   class Meta:
      model = Topic
      fields = "__all__"

  def create(self, validated_data):
      return Topic.objects.create(**validated_data)

  def update(self, instance, validated_data):
      instance.title = validated_data.get('title', instance. title)
      instance.description = validated_data.get('description', instance. description)
      instance.user = validated_data.get('user', instance. user)
      instance.save()
      return instance

 def delete(self, instance):
      instance.delete()
      return True
</code>```

Body:
I just started to learn django rest framework and the following are files of my Topic app

======models.py=====

from django.contrib.auth.models import User
class Topic(models.Model):
    title = models.CharField(max_length=100,verbose_name="Topic Title")
    description = models.CharField(max_length=500, verbose_name="Topic Description")
    user = models.ForeignKey(to=User,related_name="user_topics")

=====serializers.py=====

class TopicSerializer(ModelSerializer):
    class Meta:
        model = Topic
        fields = "__all__"

=====views.py=====

class TopicViewSet(ModelViewSet):
    queryset = Topic.objects.all()
    serializer_class = TopicSerializer

I'am able to create a "Topic" data using httpie as follows

http POST http://127.0.0.1:8989/api/v1/topics/ description="Learn Python" title="Python" user=1

NOW my need is that the topic detail should have the "user" key expanded for the User - (While maintaining the same  "user" key to PASS user id to create a topic) ie.,

making a GET request to the detail should return the following

http GET http://127.0.0.1:8989/api/v1/topics/1/
=====
HTTP/1.0 200 OK

{
    "description": "Learn Python",
    "id": 1,
    "title": "Python",
    "user": { name:"blah blah"
        ...
        ...
     }
}

AND

Making a post with user id in "user" key should create the "Topic" and should return the response with user expanded in "user" key ie.,

http POST http://127.0.0.1:8989/api/v1/topics/ description="Learn Python" title="Python" user=1
HTTP/1.0 201 Created
....

{
    "description": "Learn Python",
    "id": 1,
    "title": "Python",
    "user": { name:"blah blah", ...}
}

What changes do i need to make, so that i will be able to use the SAME "user" key? for 3 following purpose

to make a POST with "user id" to create a Topic // user:1

The POST response returned while creating a Topic should have the user expanded in user key //user : { name:"blah blah", ...}

Also, to GET the detail expanded // user : { name:"blah blah", ...}

or
please suggest an better way of doing this.

Body:
In ====serializers.py======= you can make these changes

from rest_framework import serializers
from models import Topic

class TopicSerializer(ModelSerializer):
   title = serializers.CharField(max_length=100,verbose_name="Topic Title")
   description = serializers.CharField(max_length=500, verbose_name="Topic Description")
   user = serializers.PrimaryKeyRelatedField(queryset = User.objects.all(),related_name="user_topics")
   class Meta:
      model = Topic
      fields = "__all__"

  def create(self, validated_data):
      return Topic.objects.create(**validated_data)

  def update(self, instance, validated_data):
      instance.title = validated_data.get('title', instance. title)
      instance.description = validated_data.get('description', instance. description)
      instance.user = validated_data.get('user', instance. user)
      instance.save()
      return instance

 def delete(self, instance):
      instance.delete()
      return True


问:
Parsing Openweather API Python
Okay, I've got a bit of a situation and I've hit a road block in understanding how to pull values out of JSON returned from an API. I have the following code:

```<code>import requests
import json

weather_results = []
key = 'somekey'
cities = ['sometown']

def weather_get(apikey, city):
    r = requests.get('http://api.openweathermap.org/data/2.5/weather?q={},canada&APPID={}'.format(city, apikey))
    return(r.text)
</code>```

This will return a long string of JSON formatted like so:

```<code>[u'{"coord":{"lon":-73.59,"lat":45.51},"weather":[{"id":521,"main":"Rain","description":"shower rain","icon":"09d"}],"base":"stations","main":{"temp":277.5,"pressure":1022,"humidity":55,"temp_min":277.15,"temp_max":278.15},"visibility":24140,"wind":{"speed":3.1,"deg":300},"clouds":{"all":90},"dt":1490810400,"sys":{"type":1,"id":3829,"message":0.0973,"country":"CA","sunrise":1490783901,"sunset":1490829598},"id":6077243,"name":"Montreal","cod":200}']
</code>```

Now, if I write a functon like so:

```<code>def get_temp_min(arg):
for items in arg:
    data = json.loads(items)
    for key, value in data['main'].items():
        if key=='temp_min':
            return(value)
</code>```

It will return back the following value, but if I try:

```<code>def get_weather_description(arg):
for items in arg:
    data = json.loads(items)
    for key, value in data['weather'].items():
      if key=='description':
          return(value)
</code>```

I'm not getting back the type of response that I'd want. I've tried something like this, to see if I could get deeper into the JSON:

```<code>def get_weather_description(arg):
for items in arg:
    data = json.loads(items)
    for key, value in data.items():
        if key=='weather':
            data2= value
            for items in data2:
                data3 = items
</code>```

But I feel like I'm not on the right track at the moment, if anyone could offer some advice, I'd really appreciate it.

答:
So, I've done a couple of things to make this better, I've implemented to @kiran.kodur's suggestion of

```<code>def weather_get(apikey, city):
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q={},canada&APPID={}'.format(city, apikey))
return(r.json())
</code>```

The 'return(r.json())' has made the code cleaner:

```<code>def get_temp(arg):
for items in arg:
    for key, value in items['main'].items():
        if key=='temp':
            return(value)
def get_pressure(arg):
    for items in arg:
        for key, value in items['main'].items():
            if key=='pressure':
                return(value)
def get_temp_min(arg):
    for items in arg:
        for key, value in items['main'].items():
            if key=='temp_min':
                return(value)
</code>```

It also turns out that I need to modify:

```<code>for key, value in data.items()
</code>```

To:

```<code>for key, value in items['weather'][0].items():
</code>```

I was able to return back what I needed with this.

Title: Parsing Openweather API Python

Body:
Okay, I've got a bit of a situation and I've hit a road block in understanding how to pull values out of JSON returned from an API. I have the following code:

import requests
import json

weather_results = []
key = 'somekey'
cities = ['sometown']

def weather_get(apikey, city):
    r = requests.get('http://api.openweathermap.org/data/2.5/weather?q={},canada&APPID={}'.format(city, apikey))
    return(r.text)

This will return a long string of JSON formatted like so:

[u'{"coord":{"lon":-73.59,"lat":45.51},"weather":[{"id":521,"main":"Rain","description":"shower rain","icon":"09d"}],"base":"stations","main":{"temp":277.5,"pressure":1022,"humidity":55,"temp_min":277.15,"temp_max":278.15},"visibility":24140,"wind":{"speed":3.1,"deg":300},"clouds":{"all":90},"dt":1490810400,"sys":{"type":1,"id":3829,"message":0.0973,"country":"CA","sunrise":1490783901,"sunset":1490829598},"id":6077243,"name":"Montreal","cod":200}']

Now, if I write a functon like so:

def get_temp_min(arg):
for items in arg:
    data = json.loads(items)
    for key, value in data['main'].items():
        if key=='temp_min':
            return(value)

It will return back the following value, but if I try:

def get_weather_description(arg):
for items in arg:
    data = json.loads(items)
    for key, value in data['weather'].items():
      if key=='description':
          return(value)

I'm not getting back the type of response that I'd want. I've tried something like this, to see if I could get deeper into the JSON:

def get_weather_description(arg):
for items in arg:
    data = json.loads(items)
    for key, value in data.items():
        if key=='weather':
            data2= value
            for items in data2:
                data3 = items

But I feel like I'm not on the right track at the moment, if anyone could offer some advice, I'd really appreciate it.

Body:
So, I've done a couple of things to make this better, I've implemented to @kiran.kodur's suggestion of

def weather_get(apikey, city):
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q={},canada&APPID={}'.format(city, apikey))
return(r.json())

The 'return(r.json())' has made the code cleaner:

def get_temp(arg):
for items in arg:
    for key, value in items['main'].items():
        if key=='temp':
            return(value)
def get_pressure(arg):
    for items in arg:
        for key, value in items['main'].items():
            if key=='pressure':
                return(value)
def get_temp_min(arg):
    for items in arg:
        for key, value in items['main'].items():
            if key=='temp_min':
                return(value)

It also turns out that I need to modify:

for key, value in data.items()

To:

for key, value in items['weather'][0].items():

I was able to return back what I needed with this.


问:
Make child div stretch across width of page
Suppose I have the following HTML code:

```<code><div id="container" style="width: 960px">
   <div id="help_panel" style="width: 100%; margin: 0 auto;">
     Content goes here.
   </div>
</div>
</code>```

If I want the help_panel div to stretch across the width of the page/broswer, even if the width of the page/browser is wider than 960px (which is the width set for the container div), is it possible to do it with the above structure?  I want to get the help panel div to expand beyond the width limits set in the container div if the page is wider than 960px.

I am curious if this can be accomplished with the above structure.  Or will I have to put the help_panel div outside of the container div to make it work?

Thanks!

答:
With current browsers (this question is dating a bit now), you can use the much simpler vw (viewport width) unit:

```<code>#help_panel {
  margin-left: calc(50% - 50vw);
  width: 100vw;
}
</code>```

(usage data: http://caniuse.com/#feat=viewport-units)

From my tests, this should not break your flow while being easy to use.

Body:
Suppose I have the following HTML code:

     Content goes here.

If I want the help_panel div to stretch across the width of the page/broswer, even if the width of the page/browser is wider than 960px (which is the width set for the container div), is it possible to do it with the above structure?  I want to get the help panel div to expand beyond the width limits set in the container div if the page is wider than 960px.

I am curious if this can be accomplished with the above structure.  Or will I have to put the help_panel div outside of the container div to make it work?

Thanks!

Body:
With current browsers (this question is dating a bit now), you can use the much simpler vw (viewport width) unit:

#help_panel {
  margin-left: calc(50% - 50vw);
  width: 100vw;
}

(usage data: http://caniuse.com/#feat=viewport-units)

From my tests, this should not break your flow while being easy to use.


问:
Count registers by day including zero
I have a table in a SQL Server database containing a register of each time a user downloads an image from my app so my table TBL_Downloads has the following structure:

```<code>UserID|  ImageID  | DownloadDate              |
------+-----------+---------------------------+
  292 |    782    |  02-01-2016 14:20:22.737  |
  292 |    783    |  02-01-2016 14:20:22.737  |
  292 |    784    |  02-02-2016 14:20:22.737  |
  292 |    785    |  02-04-2016 14:20:22.737  |
  292 |    786    |  02-05-2016 14:20:22.737  |
  292 |    787    |  02-06-2016 14:20:22.737  |
</code>```

In table there are shown only registers for 1 specific user even when there are several just to simplify the example.

What I would like to have is a result table containing the number of downloads made BY DAY in the last 30 days for a specific user including a zero for the days in which there was no download. I currently have the following query:

```<code>SELECT COUNT(*) AS Downloads
FROM TBL_Downloads
WHERE DownloadDate BETWEEN DATEADD(day, -30, GETDATE()) AND GETDATE()
  AND IdUser = 292
GROUP BY CAST(DownloadDate AS DATE)
</code>```

This returns a table with the sum, but only for days for which there is at least one entry of a download.

Do you have any idea how can I solve this?

答:
You can use group by to find count and generate dates using Common Table Expressions

```<code>--Final Query - For this query to execute you require #dates to be populated as below
select cte_start_date as [date], coalesce(cnt,0) as DownLoadCount from #dates d left join
(
    select userid,convert(date,DownloadDate) dt , count( convert(date,DownloadDate)) as cnt from #yourDownloads
    group by userid, convert(date,DownloadDate)
) a
on d.cte_start_date = a.dt
</code>```

Common Table Expression recursive query to populate date for that month

```<code>--Populuating dates
declare @start_date date = '02-01-2016'
declare @end_date date = eomonth('02-01-2016')
;WITH CTE AS
(
    SELECT @start_date AS cte_start_date
    UNION ALL
    SELECT DATEADD(DAY, 1, cte_start_date)
    FROM CTE
    WHERE DATEADD(DAY, 1, cte_start_date) <= @end_date
)
select * into #dates from cte
</code>```

Your Input table

```<code>create table #yourDownloads (UserId int, ImageId int, DownloadDate datetime)

insert into #yourDownloads
( UserID ,  ImageID , DownloadDate  ) values
 (  292 ,  782   ,'02-01-2016 14:20:22.737')
,(  292 ,  783   ,'02-01-2016 14:20:22.737')
,(  292 ,  784   ,'02-02-2016 14:20:22.737')
,(  292 ,  785   ,'02-04-2016 14:20:22.737')
,(  292 ,  786   ,'02-05-2016 14:20:22.737')
,(  292 ,  787   ,'02-06-2016 14:20:22.737')
</code>```

Title: Count registers by day including zero

Body:
I have a table in a SQL Server database containing a register of each time a user downloads an image from my app so my table TBL_Downloads has the following structure:

UserID|  ImageID  | DownloadDate              |
------+-----------+---------------------------+
  292 |    782    |  02-01-2016 14:20:22.737  |
  292 |    783    |  02-01-2016 14:20:22.737  |
  292 |    784    |  02-02-2016 14:20:22.737  |
  292 |    785    |  02-04-2016 14:20:22.737  |
  292 |    786    |  02-05-2016 14:20:22.737  |
  292 |    787    |  02-06-2016 14:20:22.737  |

In table there are shown only registers for 1 specific user even when there are several just to simplify the example.

What I would like to have is a result table containing the number of downloads made BY DAY in the last 30 days for a specific user including a zero for the days in which there was no download. I currently have the following query:

SELECT COUNT(*) AS Downloads
FROM TBL_Downloads
WHERE DownloadDate BETWEEN DATEADD(day, -30, GETDATE()) AND GETDATE()
  AND IdUser = 292
GROUP BY CAST(DownloadDate AS DATE)

This returns a table with the sum, but only for days for which there is at least one entry of a download.

Do you have any idea how can I solve this?

Body:
You can use group by to find count and generate dates using Common Table Expressions

--Final Query - For this query to execute you require #dates to be populated as below
select cte_start_date as [date], coalesce(cnt,0) as DownLoadCount from #dates d left join
(
    select userid,convert(date,DownloadDate) dt , count( convert(date,DownloadDate)) as cnt from #yourDownloads
    group by userid, convert(date,DownloadDate)
) a
on d.cte_start_date = a.dt

Common Table Expression recursive query to populate date for that month

--Populuating dates
declare @start_date date = '02-01-2016'
declare @end_date date = eomonth('02-01-2016')
;WITH CTE AS
(
    SELECT @start_date AS cte_start_date
    UNION ALL
    SELECT DATEADD(DAY, 1, cte_start_date)
    FROM CTE
    WHERE DATEADD(DAY, 1, cte_start_date) <= @end_date
)
select * into #dates from cte

Your Input table

create table #yourDownloads (UserId int, ImageId int, DownloadDate datetime)

insert into #yourDownloads
( UserID ,  ImageID , DownloadDate  ) values
 (  292 ,  782   ,'02-01-2016 14:20:22.737')
,(  292 ,  783   ,'02-01-2016 14:20:22.737')
,(  292 ,  784   ,'02-02-2016 14:20:22.737')
,(  292 ,  785   ,'02-04-2016 14:20:22.737')
,(  292 ,  786   ,'02-05-2016 14:20:22.737')
,(  292 ,  787   ,'02-06-2016 14:20:22.737')


问:
Magento 1.9 extend core class
I would like to extend core product class and add some functionality.

I made file app\code\local\ast\Catalog\etc\config.xml

```<code><?xml version="1.0"?>
<config>
    <modules>
         <ast_Catalog>
            <version>0.0.1</version>
        </ast_Catalog>
    </modules>
    <global>
        <models>
            <catalog>
                <rewrite>
                    <product>ast_Catalog_Model_Product</product>
                </rewrite>
            </catalog>
        </models>
   </global>
</config>
</code>```

second file app\etc\modules\ast_Catalog.xml

```<code><?xml version="1.0"?>
<config>
     <modules>
        <ast_Catalog>
            <active>true</active>
            <codePool>local</codePool>
        </ast_Catalog>
     </modules>
</config>
</code>```

and file Product.php in app\code\local\ast\Catalog\Model\

```<code>class ast_Catalog_Model_Product extends Mage_Catalog_Model_Product
{

    public function makeBlue()
    {
        echo 'makeBlue';
    }

}
</code>```

Now when I try to use my function makeBlue() in app\design\frontend\ast\default\template\catalog\product\view.phtml file

```<code><div class="product-shop">
 <?php
               ....
               echo 'hello';
               echo $this->makeBlue();
               ....
 ?>
</code>```

I have got error below:

```<code>Invalid method Mage_Catalog_Block_Product_View::makeBlue(Array
(
)
)

#0 I:\WWW\Sklep_www4\app\design\frontend\ast\default\template\catalog\product\view.phtml(45): Varien_Object->__call('makeBlue', Array)
.......
</code>```

What is wrong ?

答: You didn't respect the naming convention when creating your module. Module namespace and module name should start with an uppercase letter, try changing "ast" to "Ast" in xml, class names, and folder name</p>

Title: Magento 1.9 extend core class

Body:
I would like to extend core product class and add some functionality.

I made file app\code\local\ast\Catalog\etc\config.xml

<?xml version="1.0"?>
<config>
    <modules>
         <ast_Catalog>
            <version>0.0.1</version>
        </ast_Catalog>
    </modules>
    <global>
        <models>
            <catalog>
                <rewrite>
                    <product>ast_Catalog_Model_Product</product>
                </rewrite>
            </catalog>
        </models>
   </global>
</config>

second file app\etc\modules\ast_Catalog.xml

<?xml version="1.0"?>
<config>
     <modules>
        <ast_Catalog>
            <active>true</active>
            <codePool>local</codePool>
        </ast_Catalog>
     </modules>
</config>

and file Product.php in app\code\local\ast\Catalog\Model\

class ast_Catalog_Model_Product extends Mage_Catalog_Model_Product
{

    public function makeBlue()
    {
        echo 'makeBlue';
    }

}

Now when I try to use my function makeBlue() in app\design\frontend\ast\default\template\catalog\product\view.phtml file

 <?php
               ....
               echo 'hello';
               echo $this->makeBlue();
               ....
 ?>

I have got error below:

Invalid method Mage_Catalog_Block_Product_View::makeBlue(Array
(
)
)

#0 I:\WWW\Sklep_www4\app\design\frontend\ast\default\template\catalog\product\view.phtml(45): Varien_Object->__call('makeBlue', Array)
.......

What is wrong ?


问:
Snap.SVG s.node.offsetLeft [Top] is undefined?
In Snap.SVG I need the position of a SVG container left upper corner. I get the needed coordinates with

```<code>s.mousemove(moveFunc)
</code>```

but they are relative to the position of the html body. The html document is responsive. The result useing

s.node.offsetLeft

or

```<code>s.node.offsetTop
</code>```

is undefined. A SVG container with an ID and the use of

```<code>document.getElementByID('usedId').offsetLeft
</code>```

or other offset... give also 'undefined'. The results are independent of the browser. So far I couldn't find a usefull answer or example. I hope to get some help.

For completion to IAN's answer. The html body ist centered to the viewport of the browser and the contents are responsible. The SVG container should be centered in the body. The mousemove event gives me the correct coordinates relative to the viewport. If I want for example that a SVG grafic element will follow the mouse or be placed at the mousepointer I need the relative coordinates of the SVG container's upper left corner and not the absolut coordinates with x=0 and y=0. How can I get these coordinates? For a absolut positioned html element I can get the needed offsets but not for the SVG.

sorry, I tried a jsfiddle but unsuccessful. Here the the code I used:

```<code><!DOCTYPE html>
<html>
<head>
<script src="snap.svg-min.js"></script>
<title>Test.svg</title>
<style>
body {max-width:62em;margin:0 auto;overflow-y:scroll;}
main {background: #ddd;}
svg {background:#eee;border:1px dotted #3983ab;width:100%;height:auto;}
</style>
</head>
<body>
<main>
<h1>Test responsiv SVG</h1>
<div style="text-align: center">
<svg id="svgout" style="max-width:500px" viewBox="0 0 500 250" ></svg>
</div>
<script>
var s = Snap('#svgout');
var c1 = s.circle(0,0,10).attr({fill: '#00f'});
function mausPosi(event, x, y ) {
c1.attr({cx: x, cy: y});
mC.attr({'text': x+'/'+y});
oL.attr({'text': s.node.offsetLeft});
};
s.mousemove(mausPosi);
var oL = s.text(10,100, 'Offset...: ');
var mC = s.text(10,150, 'mouseCoord:');
</script>
</main>
</body>
</html>
</code>```

For the circle following the mousecurser in the correct way I have to substract the coordinates of the upper left corner of SVG. The mouse event return the coordinates inside the SVG relativ to the body (main). For the element (circle) the coordinates of the upper point ist (0/0).

Ian, I found jsfiddle.net/xJ4Lj/36/ (yours?) with s.node.offset... only working good if the SVG container remains left of the browsers viewport. The returned value in an additional text gives undefined.

答:
When there are differences from the screen coordinates to the svg element, we need to do a transformation on the points, to the svg coordinates space. We can find that out from the matrix given by element.getScreenCTM().

It's a little bit complex, so I typically use a plugin I made, just include that at the top before you create a Snap paper instance. Basically create an svg point, find the inverse matrix of the transformation from the screen to the svg paper, and then do a transformation on the points using that.

```<code>Snap.plugin( function( Snap, Element, Paper, global ) {

    Element.prototype.getCursorPoint = function( x, y ) {
            var pt = this.paper.node.createSVGPoint();
            pt.x = x; pt.y = y;
            return pt.matrixTransform( this.paper.node.getScreenCTM().inverse());
    }

});

...

function mausPosi(event, x, y ) {
    var cpt = s.getCursorPoint(x,y)
    c1.attr({cx: cpt.x, cy: cpt.y});
};
</code>```

jsfiddle

Body:
In Snap.SVG I need the position of a SVG container left upper corner. I get the needed coordinates with

s.mousemove(moveFunc)

but they are relative to the position of the html body. The html document is responsive. The result useing

s.node.offsetLeft

or

s.node.offsetTop

is undefined. A SVG container with an ID and the use of

document.getElementByID('usedId').offsetLeft

or other offset... give also 'undefined'. The results are independent of the browser. So far I couldn't find a usefull answer or example. I hope to get some help.

For completion to IAN's answer. The html body ist centered to the viewport of the browser and the contents are responsible. The SVG container should be centered in the body. The mousemove event gives me the correct coordinates relative to the viewport. If I want for example that a SVG grafic element will follow the mouse or be placed at the mousepointer I need the relative coordinates of the SVG container's upper left corner and not the absolut coordinates with x=0 and y=0. How can I get these coordinates? For a absolut positioned html element I can get the needed offsets but not for the SVG.

sorry, I tried a jsfiddle but unsuccessful. Here the the code I used:

<!DOCTYPE html>

<title>Test.svg</title>

Test responsiv SVG

<svg id="svgout" style="max-width:500px" viewBox="0 0 500 250" ></svg>

For the circle following the mousecurser in the correct way I have to substract the coordinates of the upper left corner of SVG. The mouse event return the coordinates inside the SVG relativ to the body (main). For the element (circle) the coordinates of the upper point ist (0/0).

Ian, I found jsfiddle.net/xJ4Lj/36/ (yours?) with s.node.offset... only working good if the SVG container remains left of the browsers viewport. The returned value in an additional text gives undefined.

Body:
When there are differences from the screen coordinates to the svg element, we need to do a transformation on the points, to the svg coordinates space. We can find that out from the matrix given by element.getScreenCTM().

It's a little bit complex, so I typically use a plugin I made, just include that at the top before you create a Snap paper instance. Basically create an svg point, find the inverse matrix of the transformation from the screen to the svg paper, and then do a transformation on the points using that.

Snap.plugin( function( Snap, Element, Paper, global ) {

    Element.prototype.getCursorPoint = function( x, y ) {
            var pt = this.paper.node.createSVGPoint();
            pt.x = x; pt.y = y;
            return pt.matrixTransform( this.paper.node.getScreenCTM().inverse());
    }

});

...

function mausPosi(event, x, y ) {
    var cpt = s.getCursorPoint(x,y)
    c1.attr({cx: cpt.x, cy: cpt.y});
};

jsfiddle


问:
ASP.NET MVC- functionalities of a view doesn't work unless I access it directly
I have a view with sidebar that contains a list of files, and a partial view contains a text area. I want to display the contents of a file once the user clicks on it (by refreshing the partial view). This is the script I'm using:

```<code> <script>
     $(document).ready(function () {
         $('.filelist').on('click', function (e) {
             var filePath = $(this).attr('value');    //value is attribute set in Html
             $('#partial').load('DevelopmentPartial', { path1: filePath });
         });
     });
</script>
</code>```

It was working correctly until yesterday, I started getting this error when redirecting to this view, but not if it was accessed directly:

The requested content appears to be script and will not be served by
  the static file handler

I was able to get rid of the error, but now the functionalities like displaying the contents of the files on-click doesn't work unless I access the
view directly, but if I redirect to it from another action method it doesn't!

This is my controller:

```<code> StudentsCodes modelSC;

    public DevelopmentController()
    {
        m4 = new MicroG4();
        modelSC = new StudentsCodes();
    }
    public ActionResult Index()
    {
        modelSC.Student = (Student)CurrentUser;
        var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
        modelSC.Instructor =(Instructor) user;
        //modelSC.path = "~/Content/" + CurrentUser.UserName + "/CompilerProject/src/Driver.java";
         return View(modelSC);
    }
    public PartialViewResult DevelopmentPartial(string path1)
    {
        modelSC.Student = (Student)CurrentUser;
        var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
        modelSC.Instructor = (Instructor)user;
        modelSC.path = path1;
        modelSC.code = "";
        if (modelSC.path == null)
        {
            modelSC.code = "";
        }
        else
        {
            try
            {
               modelSC.code = System.IO.File.ReadAllText(Server.MapPath(modelSC.path));
            }
            catch (Exception e)
            {
                modelSC.code = "";
            }
        }
        return PartialView(modelSC);

    }
</code>```

What am I doing wrong?

答:
I solved the problem by reordering the scripts in the main view as the following:

```<code>    <script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</code>```

The jquery.unobtrusive was the first. Then I updated the script that loads the partial view :

```<code><script type="text/javascript">
     $(document).ready(function () {
         $('.filelist').on('click', function (e) {
             e.preventDefault();
             alert('Im clicked on filePath = ' + $(this).attr('value'));
             var filePath = $(this).attr('value');    //value is attribute set in Html
             $('#partial').load('@Url.Action("DevelopmentPartial", "Development")', { path1: filePath });
         });
     });
</script>
</code>```

Body:
I have a view with sidebar that contains a list of files, and a partial view contains a text area. I want to display the contents of a file once the user clicks on it (by refreshing the partial view). This is the script I'm using:

It was working correctly until yesterday, I started getting this error when redirecting to this view, but not if it was accessed directly:

The requested content appears to be script and will not be served by
  the static file handler

I was able to get rid of the error, but now the functionalities like displaying the contents of the files on-click doesn't work unless I access the
view directly, but if I redirect to it from another action method it doesn't!

This is my controller:

 StudentsCodes modelSC;

    public DevelopmentController()
    {
        m4 = new MicroG4();
        modelSC = new StudentsCodes();
    }
    public ActionResult Index()
    {
        modelSC.Student = (Student)CurrentUser;
        var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
        modelSC.Instructor =(Instructor) user;
        //modelSC.path = "~/Content/" + CurrentUser.UserName + "/CompilerProject/src/Driver.java";
         return View(modelSC);
    }
    public PartialViewResult DevelopmentPartial(string path1)
    {
        modelSC.Student = (Student)CurrentUser;
        var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
        modelSC.Instructor = (Instructor)user;
        modelSC.path = path1;
        modelSC.code = "";
        if (modelSC.path == null)
        {
            modelSC.code = "";
        }
        else
        {
            try
            {
               modelSC.code = System.IO.File.ReadAllText(Server.MapPath(modelSC.path));
            }
            catch (Exception e)
            {
                modelSC.code = "";
            }
        }
        return PartialView(modelSC);

    }

What am I doing wrong?

Body:
I solved the problem by reordering the scripts in the main view as the following:

    <script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

The jquery.unobtrusive was the first. Then I updated the script that loads the partial view :

<script type="text/javascript">
     $(document).ready(function () {
         $('.filelist').on('click', function (e) {
             e.preventDefault();
             alert('Im clicked on filePath = ' + $(this).attr('value'));
             var filePath = $(this).attr('value');    //value is attribute set in Html
             $('#partial').load('@Url.Action("DevelopmentPartial", "Development")', { path1: filePath });
         });
     });
</script>


问:
Want to select button on website using excel vba
I want to use excel to navigate a webpage. yet the website doesn't use ID's like a normal site does (amazon,google,ect). the website is http://www.scoopmae.com/. how would i select the "book a demo" button. I would normally use getelementbyID, but i don't know the id. I've also tried tag and class but no luck.</p>

```<code>Sub scoop()
Set objie = CreateObject("InternetExplorer.Application")
objie.Top = 0
objie.Left = 0
objie.Width = 1600
objie.Height = 900
objie.Visible = True 'We can see IE

On Error Resume Next
objie.navigate ("http://scoopmae.com")
Do
DoEvents
Loop Until objue.readystate = 4

Application.Wait (Now + TimeValue("0:00:02"))
'MsgBox ("wait")
'click button
'objie.document.getElementsById("scoop-sort").Click

 x = objie.document.getElementsByClassName("a")
Cells(1, 2) = x
End Sub
</code>```

答:
I can access the button by doing this.

```<code>Sub test()

Dim oHtml As HTMLDocument
Dim oElement As Object

Set oHtml = New HTMLDocument

With CreateObject("WINHTTP.WinHTTPRequest.5.1")
    .Open "GET", "http://www.scoopmae.com/", False
    .send
    oHtml.body.innerHTML = .responseText
End With

Set mybtn = oHtml.getElementsByClassName("sf-button large orange default  dropshadow")(0).getElementsByTagName("span")

i = 0
For Each oElement In mybtn
    Debug.Print mybtn(i).innerText
    i = i + 1
Next oElement

End Sub
</code>```

Make certain that you go to Tools -> References and add a reference to the Microsoft HTML Object Library [MSHTML.TLB]
Thanks
Miguel

Body:
I want to use excel to navigate a webpage. yet the website doesn't use ID's like a normal site does (amazon,google,ect). the website is http://www.scoopmae.com/. how would i select the "book a demo" button. I would normally use getelementbyID, but i don't know the id. I've also tried tag and class but no luck.

Sub scoop()
Set objie = CreateObject("InternetExplorer.Application")
objie.Top = 0
objie.Left = 0
objie.Width = 1600
objie.Height = 900
objie.Visible = True 'We can see IE

On Error Resume Next
objie.navigate ("http://scoopmae.com")
Do
DoEvents
Loop Until objue.readystate = 4

Application.Wait (Now + TimeValue("0:00:02"))
'MsgBox ("wait")
'click button
'objie.document.getElementsById("scoop-sort").Click

 x = objie.document.getElementsByClassName("a")
Cells(1, 2) = x
End Sub

Body:
I can access the button by doing this.

Sub test()

Dim oHtml As HTMLDocument
Dim oElement As Object

Set oHtml = New HTMLDocument

With CreateObject("WINHTTP.WinHTTPRequest.5.1")
    .Open "GET", "http://www.scoopmae.com/", False
    .send
    oHtml.body.innerHTML = .responseText
End With

Set mybtn = oHtml.getElementsByClassName("sf-button large orange default  dropshadow")(0).getElementsByTagName("span")

i = 0
For Each oElement In mybtn
    Debug.Print mybtn(i).innerText
    i = i + 1
Next oElement

End Sub

Make certain that you go to Tools -> References and add a reference to the Microsoft HTML Object Library [MSHTML.TLB]
Thanks
Miguel


问:
Spring Data MongoDB eliminate POJO's
My system is a dynamic telemetry system.  We have hundreds of different spiders all sending telemetry back to the SpringBoot server, Everything is dynamic, driven by json files in Mongo, including the UI.  We don't build the UI, as opposed to individual teams can configure their own UI for their needs, all by editing json docs.

We have the majority of the UI running and i began the middleware piece.  We are using Spring Boot for the first time along with Spring Data Mongo with several MQ listeners for events.  The problem is Spring Data.  I started reading the docs on it and I realized the docs do not address using it without POJO's.  I have this wonderfully dynamic model that changes per user per minute if the telemetry spiders dictate, I couldn't shackle this to a POJO if I tried.  Is there a way to use Spring Data with a Map?

It seems from my experiments that the big issue is there is no way to tell the CRUD routines of the repository class what collection to query without a POJO.

Are my suspicions correct in that this won't work and am I better off ditching Spring Data and using the Mongo driver directly?

答:
I don't think you can do it without a pojo when using spring-data. The least you could do is this

```<code>public interface NoPojoRepository extends MongoRepository<DummyPojo, String> {
}
</code>```

and create a dummy pojo with just id and a Map.

```<code>@Data
public class DummyPojo {
  @Id
  private String id;
  private Map<String, Object> value;
}
</code>```

Since this value field is a map, you can store pretty much anything.

Title: Spring Data MongoDB eliminate POJO's

Body:
I don't think you can do it without a pojo when using spring-data. The least you could do is this

public interface NoPojoRepository extends MongoRepository<DummyPojo, String> {
}

and create a dummy pojo with just id and a Map.

@Data
public class DummyPojo {
  @Id
  private String id;
  private Map<String, Object> value;
}

Since this value field is a map, you can store pretty much anything.


问:
EJB annotation not working
I have a problem with my EJB annotations:

I have a DAO:

```<code>@Singleton
@Startup
public class CassandraDAO<T extends Serializable> extends AbstractDAO {

  @PersistenceContext(unitName = "JPAService", type = PersistenceContextType.EXTENDED)
  private EntityManager em;

  @PostConstruct
  public void init() {
    System.out.println("***************** init CassandraDAO ***************************");
  }

  @PreDestroy
  public void destroy() {
    System.out.println("***************** destroying CassandraDAO *************************");
    if (em.isOpen()) {
      em.close();
    }
  }

  @Override
  public EntityManager getManager() {
    return em;
  }

  @Override
  public void setManager(EntityManager em) {
    this.em = em;
  }
}
</code>```

And there are several DAOs that extends this DAO:

```<code>@Stateless
public class IOConfigurationDAO extends CassandraDAO<IOConfiguration> {
...
}
</code>```

And here is how I use the DAO:

```<code>public class AddAlertTest extends TestCase {
  @EJB
  private IOConfigurationDAO ioConfigurationDAO;
  public void test() {
      ioConfigurationDAO.getManager().getTransaction().begin();
      IOConfiguration ioConfig = new IOConfiguration("CH1");
      ioConfigurationDAO.getManager().persist(ioConfig);
      ioConfigurationDAO.getManager().getTransaction().commit();
      int oldSize = ioConfig.getAlerts() == null ? 0 : ioConfig.getAlerts().size();
      System.out.println("Created IO configuration with id " + ioConfig.getIoConfigurationId());

      ioConfigurationDAO.getManager().getTransaction().begin();
      Alert alert = ioConfigurationDAO.addAlert(ioConfig,
          Operators[(int) (Math.random() * Operators.length)], new Double(Math.random() * 100));
      ioConfigurationDAO.getManager().getTransaction().commit();
      int newSize = ioConfig.getAlerts().size();
      System.out.println("Created new Alert with id " + alert.getAlertId());
      System.out.println("Alert list: " + ioConfig.getAlerts());
      System.out.println("Alert is connected to " + alert.getIoConfiguration());

      assertEquals(oldSize + 1, newSize);
      assertNotNull(ioConfigurationDAO.getManager().find(Alert.class, alert.getAlertId()));

      ioConfigurationDAO.getManager().getTransaction().begin();
      ioConfigurationDAO.getManager().remove(ioConfig);
      ioConfigurationDAO.getManager().getTransaction().commit();
      System.out.println("Deleted IO configuration with id " + ioConfig.getIoConfigurationId());
  }
</code>```

But my IOConfigurationDAO is always null, so my persistenceContext annotation doesn't work at all. And there is nothing printed out in my console, so my postConstruct annotations doesn't work as well.

Here is my persistence.xml:

```<code><?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="JPAService">
        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
        <class>com.sensorhound.aigateway.domain.Alert</class>
        <class>com.sensorhound.aigateway.domain.DataSeriesMeta</class>
        <class>com.sensorhound.aigateway.domain.IOConfiguration</class>
        <class>com.sensorhound.aigateway.domain.NodeData</class>
        <properties>
            <property name="hibernate.transaction.jta.platform" value="JBossAS" />
            <property name="jboss.as.jpa.providerModule" value="org.hibernate:5.0" />
            <property name="hibernate.ogm.datastore.provider" value="cassandra_experimental"/>
            <property name="hibernate.ogm.datastore.host" value="127.0.0.1:9042"/>
            <property name="hibernate.ogm.datastore.database" value="dev"/>
            <property name="hibernate.hbm2ddl.auto" value="none"></property>
            <property name = "hibernate.show_sql" value = "true" />
            <property name = "hibernate.format_sql" value = "true" />
        </properties>
    </persistence-unit>
</persistence>
</code>```

I don't know what is wrong in my configuration. Someone please help me. If you need more information, I am willing to share.

Thanks!

答: I am not able to get EJB in my unit test to work. But I got my EJB working in the project. I just switch to stateful EJB since my DAO is making some modification in the database and copy the method I had in the DAO's parent class to the DAO. Thanks!</p>

Title: EJB annotation not working

Body:
I have a problem with my EJB annotations:

I have a DAO:

@Singleton
@Startup
public class CassandraDAO<T extends Serializable> extends AbstractDAO {

  @PersistenceContext(unitName = "JPAService", type = PersistenceContextType.EXTENDED)
  private EntityManager em;

  @PostConstruct
  public void init() {
    System.out.println("***************** init CassandraDAO ***************************");
  }

  @PreDestroy
  public void destroy() {
    System.out.println("***************** destroying CassandraDAO *************************");
    if (em.isOpen()) {
      em.close();
    }
  }

  @Override
  public EntityManager getManager() {
    return em;
  }

  @Override
  public void setManager(EntityManager em) {
    this.em = em;
  }
}

And there are several DAOs that extends this DAO:

@Stateless
public class IOConfigurationDAO extends CassandraDAO<IOConfiguration> {
...
}

And here is how I use the DAO:

public class AddAlertTest extends TestCase {
  @EJB
  private IOConfigurationDAO ioConfigurationDAO;
  public void test() {
      ioConfigurationDAO.getManager().getTransaction().begin();
      IOConfiguration ioConfig = new IOConfiguration("CH1");
      ioConfigurationDAO.getManager().persist(ioConfig);
      ioConfigurationDAO.getManager().getTransaction().commit();
      int oldSize = ioConfig.getAlerts() == null ? 0 : ioConfig.getAlerts().size();
      System.out.println("Created IO configuration with id " + ioConfig.getIoConfigurationId());

      ioConfigurationDAO.getManager().getTransaction().begin();
      Alert alert = ioConfigurationDAO.addAlert(ioConfig,
          Operators[(int) (Math.random() * Operators.length)], new Double(Math.random() * 100));
      ioConfigurationDAO.getManager().getTransaction().commit();
      int newSize = ioConfig.getAlerts().size();
      System.out.println("Created new Alert with id " + alert.getAlertId());
      System.out.println("Alert list: " + ioConfig.getAlerts());
      System.out.println("Alert is connected to " + alert.getIoConfiguration());

      assertEquals(oldSize + 1, newSize);
      assertNotNull(ioConfigurationDAO.getManager().find(Alert.class, alert.getAlertId()));

      ioConfigurationDAO.getManager().getTransaction().begin();
      ioConfigurationDAO.getManager().remove(ioConfig);
      ioConfigurationDAO.getManager().getTransaction().commit();
      System.out.println("Deleted IO configuration with id " + ioConfig.getIoConfigurationId());
  }

But my IOConfigurationDAO is always null, so my persistenceContext annotation doesn't work at all. And there is nothing printed out in my console, so my postConstruct annotations doesn't work as well.

Here is my persistence.xml:

<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="JPAService">
        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
        <class>com.sensorhound.aigateway.domain.Alert</class>
        <class>com.sensorhound.aigateway.domain.DataSeriesMeta</class>
        <class>com.sensorhound.aigateway.domain.IOConfiguration</class>
        <class>com.sensorhound.aigateway.domain.NodeData</class>
        <properties>
            <property name="hibernate.transaction.jta.platform" value="JBossAS" />
            <property name="jboss.as.jpa.providerModule" value="org.hibernate:5.0" />
            <property name="hibernate.ogm.datastore.provider" value="cassandra_experimental"/>
            <property name="hibernate.ogm.datastore.host" value="127.0.0.1:9042"/>
            <property name="hibernate.ogm.datastore.database" value="dev"/>
            <property name="hibernate.hbm2ddl.auto" value="none"></property>
            <property name = "hibernate.show_sql" value = "true" />
            <property name = "hibernate.format_sql" value = "true" />
        </properties>
    </persistence-unit>
</persistence>

I don't know what is wrong in my configuration. Someone please help me. If you need more information, I am willing to share.

Thanks!


问:
How to disassemble, modify and then reassemble a Linux executable?
Is there anyway this can be done? I've used objdump but that doesn't produce assembly output that will be accepted by any assembler that I know of. I'd like to be able to change instructions within an executable and then test it afterwards.</p>

答:
I don't think there is any reliable way to do this. Machine code formats are very complicated, more complicated than assembly files. It isn't really possible to take a compiled binary (say, in ELF format) and produce a source assembly program which will compile to the same (or similar-enough) binary. To gain an understanding of the differences, compare the output of GCC compiling direct to assembler (gcc -S) versus the output of objdump on the executable (objdump -D).

There are two major complications I can think of. Firstly, the machine code itself is not a 1-to-1 correspondence with assembly code, because of things like pointer offsets.

For example, consider the C code to Hello world:

```<code>int main()
{
    printf("Hello, world!\n");
    return 0;
}
</code>```

This compiles to the x86 assembly code:

```<code>.LC0:
    .string "hello"
    .text
<snip>
    movl    $.LC0, %eax
    movl    %eax, (%esp)
    call    printf
</code>```

Where .LCO is a named constant, and printf is a symbol in a shared library symbol table. Compare to the output of objdump:

```<code>80483cd:       b8 b0 84 04 08          mov    $0x80484b0,%eax
80483d2:       89 04 24                mov    %eax,(%esp)
80483d5:       e8 1a ff ff ff          call   80482f4 <printf@plt>
</code>```

Firstly, the constant .LC0 is now just some random offset in memory somewhere -- it would be difficult to create an assembly source file which contains this constant in the correct place, since the assembler and linker are free to choose locations for these constants.

Secondly, I'm not entirely sure about this (and it depends on things like position independent code), but I believe the reference to printf is not actually encoded at the pointer address in that code there at all, but the ELF headers contain a lookup table which dynamically replaces its address at runtime. Therefore, the disassembled code doesn't quite correspond to the source assembly code.

In summary, source assembly has symbols while compiled machine code has addresses which are difficult to reverse.

The second major complication is that an assembly source file can't contain all of the information that was present in the original ELF file headers, like which libraries to dynamically link against, and other metadata placed there by the original compiler. It would be difficult to reconstruct this.

Like I said, it's possible that a special tool can manipulate all of this information, but it is unlikely that one can simply produce assembly code which can be reassembled back to the executable.

If you are interested in modifying just a small section of the executable, I recommend a much more subtle approach than recompiling the whole application. Use objdump to get the assembly code for the function(s) you are interested in. Convert it to "source assembly syntax" by hand (and here, I wish there was a tool that actually produced disassembly in the same syntax as the input), and modify it as you wish. When you are done, recompile just those function(s) and use objdump to figure out the machine code for your modified program. Then, use a hex editor to manually paste the new machine code over the top of the corresponding part of the original program, taking care that your new code is precisely the same number of bytes as the old code (or all the offsets would be wrong). If the new code is shorter, you can pad it out using NOP instructions. If it is longer, you may be in trouble, and might have to create new functions and call them instead.

Body:
I don't think there is any reliable way to do this. Machine code formats are very complicated, more complicated than assembly files. It isn't really possible to take a compiled binary (say, in ELF format) and produce a source assembly program which will compile to the same (or similar-enough) binary. To gain an understanding of the differences, compare the output of GCC compiling direct to assembler (gcc -S) versus the output of objdump on the executable (objdump -D).

There are two major complications I can think of. Firstly, the machine code itself is not a 1-to-1 correspondence with assembly code, because of things like pointer offsets.

For example, consider the C code to Hello world:

int main()
{
    printf("Hello, world!\n");
    return 0;
}

This compiles to the x86 assembly code:

.LC0:
    .string "hello"
    .text
<snip>
    movl    $.LC0, %eax
    movl    %eax, (%esp)
    call    printf

Where .LCO is a named constant, and printf is a symbol in a shared library symbol table. Compare to the output of objdump:

80483cd:       b8 b0 84 04 08          mov    $0x80484b0,%eax
80483d2:       89 04 24                mov    %eax,(%esp)
80483d5:       e8 1a ff ff ff          call   80482f4 <printf@plt>

Firstly, the constant .LC0 is now just some random offset in memory somewhere -- it would be difficult to create an assembly source file which contains this constant in the correct place, since the assembler and linker are free to choose locations for these constants.

Secondly, I'm not entirely sure about this (and it depends on things like position independent code), but I believe the reference to printf is not actually encoded at the pointer address in that code there at all, but the ELF headers contain a lookup table which dynamically replaces its address at runtime. Therefore, the disassembled code doesn't quite correspond to the source assembly code.

In summary, source assembly has symbols while compiled machine code has addresses which are difficult to reverse.

The second major complication is that an assembly source file can't contain all of the information that was present in the original ELF file headers, like which libraries to dynamically link against, and other metadata placed there by the original compiler. It would be difficult to reconstruct this.

Like I said, it's possible that a special tool can manipulate all of this information, but it is unlikely that one can simply produce assembly code which can be reassembled back to the executable.

If you are interested in modifying just a small section of the executable, I recommend a much more subtle approach than recompiling the whole application. Use objdump to get the assembly code for the function(s) you are interested in. Convert it to "source assembly syntax" by hand (and here, I wish there was a tool that actually produced disassembly in the same syntax as the input), and modify it as you wish. When you are done, recompile just those function(s) and use objdump to figure out the machine code for your modified program. Then, use a hex editor to manually paste the new machine code over the top of the corresponding part of the original program, taking care that your new code is precisely the same number of bytes as the old code (or all the offsets would be wrong). If the new code is shorter, you can pad it out using NOP instructions. If it is longer, you may be in trouble, and might have to create new functions and call them instead.