问:
How to rows limit in table and doesnot allow duplicate rows
I am displaying the form details in table formate in same page. But when i am saving multiple times table rows also increasing, so i want display 3 row only remaining rows will be show in scroll or pagination. </p>

```<code><table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
    <th>Name</th>
    <th>Email</th>
    <th>Message</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<form id="localStorageTest" method="post" action="">
<label>Name:</label>
<input type="text" name="name" id="name" class="stored" value="" />

<label>Email:</label>
<input type="email" name="email" id="email" class="stored" value="" />

<label>Message:</label>
<textarea name="message" id="message" class="stored"></textarea>

 <button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;" id="savebutton"><i class="icon-check-sign" aria-hidden="false"></i> Save </button>
 </form>
</code>```

<p>And for example same mail id displaying second time it doesn't allow. </p>

```<code>$("button#savebutton").click(function() {
 var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
//---->Form validation goes here
var new_row = '<tr><td class="name">' + name + '</td><td class="email">' + email + '</td><td class="message">' + message + '</td></tr>';
$("table tbody").append(new_row);
 });
</code>```

答:
Here is the solution to your problem.

Disable Save button after appending the row.

Enable Save button when there is change in input/testarea.

Check out working code below.

$("button#savebutton").click(function() {
 var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
//---->Form validation goes here
var new_row = '
' + name + '	' + email + '	' + message + '
';
$("table tbody").append(new_row);

//disable the save button after appending row
$(this).prop("disabled",true);

});

//listen to change in input/textare and then enable the save button
$(document).on('change', 'input, textarea', function() {

  if($("button#savebutton").is(':disabled')){
    $("button#savebutton").prop("disabled",false);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
    <th>Name</th>
    <th>Email</th>
    <th>Message</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<form id="localStorageTest" method="post" action="">
<label>Name:</label>
<input type="text" name="name" id="name" class="stored" value="" />

<label>Email:</label>
<input type="email" name="email" id="email" class="stored" value="" />

<label>Message:</label>
<textarea name="message" id="message" class="stored"></textarea>

 <button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;" id="savebutton"><i class="icon-check-sign" aria-hidden="false"></i> Save </button>
 </form></code>```

Body:
I am displaying the form details in table formate in same page. But when i am saving multiple times table rows also increasing, so i want display 3 row only remaining rows will be show in scroll or pagination.

    Name
    Email
    Message

<form id="localStorageTest" method="post" action="">
Name:
<input type="text" name="name" id="name" class="stored" value="" />

Email:
<input type="email" name="email" id="email" class="stored" value="" />

Message:
<textarea name="message" id="message" class="stored"></textarea>

 <button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;" id="savebutton"> Save </button>
 </form>

And for example same mail id displaying second time it doesn't allow.

$("button#savebutton").click(function() {
 var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
//---->Form validation goes here
var new_row = '
' + name + '	' + email + '	' + message + '
';
$("table tbody").append(new_row);
 });

Body:
Here is the solution to your problem.

Disable Save button after appending the row.

Enable Save button when there is change in input/testarea.

Check out working code below.

$("button#savebutton").click(function() {
 var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
//---->Form validation goes here
var new_row = '<tr><td class="name">' + name + '</td><td class="email">' + email + '</td><td class="message">' + message + '</td></tr>';
$("table tbody").append(new_row);

//disable the save button after appending row
$(this).prop("disabled",true);

});

//listen to change in input/textare and then enable the save button
$(document).on('change', 'input, textarea', function() {

  if($("button#savebutton").is(':disabled')){
    $("button#savebutton").prop("disabled",false);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
    <th>Name</th>
    <th>Email</th>
    <th>Message</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<form id="localStorageTest" method="post" action="">
<label>Name:</label>
<input type="text" name="name" id="name" class="stored" value="" />

<label>Email:</label>
<input type="email" name="email" id="email" class="stored" value="" />

<label>Message:</label>
<textarea name="message" id="message" class="stored"></textarea>

 <button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;" id="savebutton"><i class="icon-check-sign" aria-hidden="false"></i> Save </button>
 </form>


来源: stackexchange

问:
how to implement clustering in Sequelize?
I have two mysql server both are (MASTER,MASTER). how could we implement clustering in sequelize. if one of sql server has stopped then all request goes to other mysql server without restarting node server.</p>

答:
They haven't implemented clustering feature or fallback. I have found a way around for the same.

```<code>var Sequelize = require("sequelize");

sequelize.connectionManager.connect = function(){
    return new Promise(function(resolve,reject){
       // create your connection and return its instance in promise
       resolve(connection);
    });
}

sequelize.connectionManager.disconnect = function(connection){
   // to disconnect the connection
   if (!connection._protocol._ended) {
       connection.release()
}
return Promise.resolve();

}
</code>```

I can share code if above code is not enough.

ContentLicense: CC BY-SA 3.0

Body:
They haven't implemented clustering feature or fallback. I have found a way around for the same.

var Sequelize = require("sequelize");

sequelize.connectionManager.connect = function(){
    return new Promise(function(resolve,reject){
       // create your connection and return its instance in promise
       resolve(connection);
    });
}

sequelize.connectionManager.disconnect = function(connection){
   // to disconnect the connection
   if (!connection._protocol._ended) {
       connection.release()
}
return Promise.resolve();

}

I can share code if above code is not enough.


问:
Ignore SIGINT in Python multiprocessing Subprocess
When I run the following code on OSX or Linux and then press ctrl+c a "graceful shutdown" is initiated. Which looks something like this:

```<code>$ python subprocess_test.py
Subprocess:  <MyProcess(MyProcess-1, started)>
^CMain: Graceful shutdown
Subprocess: shutdown
</code>```

However, when I run the some code on a Windows10 machine a KeyboardInterrupt is raised in line self.event.wait() preventing a graceful shutdown. I have tried different approaches as described here to prevent that the subprocess is receiving the signal.

What is the correct way to to get the same behavior on the different OS using Python 2.7?

```<code>import multiprocessing
import signal

class MyProcess(multiprocessing.Process):

    def __init__(self):
        super(MyProcess, self).__init__()
        self.event = multiprocessing.Event()

    def run(self):
        print "Subprocess: ", multiprocessing.current_process()
        self.event.wait()
        print "Subprocess: shutdown"

def sighandler(a,b,):
    print "Main: Graceful shutdown"
    p1.event.set()

def run():
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    global p1
    p1 = MyProcess()

    p1.start()

    signal.signal(signal.SIGINT, sighandler)
    p1.join()

if __name__ == '__main__':
    run()
</code>```

答:
Using win32api.SetConsoleCtrlHandler from pywin32 one can control how Windows the interrupts. Using SetConsoleCtrlHandler(None, True) causes the calling process to ignore CTRL+C input. With SetConsoleCtrlHandler(sighandler, True) a specific handler can be registered.

Putting it all together the issue is addressed like this:

```<code>import multiprocessing
import signal
import sys

class MyProcess(multiprocessing.Process):

    def __init__(self):
        super(MyProcess, self).__init__()
        self.event = multiprocessing.Event()

    def run(self):
        if sys.platform == "win32":
            import win32api # ignoring the signal
            win32api.SetConsoleCtrlHandler(None, True)

        print "Subprocess: ", multiprocessing.current_process()
        self.event.wait()
        print "Subprocess: shutdown"

def sighandler(a,b=None):
    print "Main: Graceful shutdown"
    p1.event.set()

def run():
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    global p1
    p1 = MyProcess()

    p1.start()

    if sys.platform == "win32":
        import win32api
        win32api.SetConsoleCtrlHandler(sighandler, True)
    else:
        signal.signal(signal.SIGINT, sighandler)

    p1.join()

if __name__ == '__main__':
    run()
</code>```

Body:
When I run the following code on OSX or Linux and then press ctrl+c a "graceful shutdown" is initiated. Which looks something like this:

$ python subprocess_test.py
Subprocess:  <MyProcess(MyProcess-1, started)>
^CMain: Graceful shutdown
Subprocess: shutdown

However, when I run the some code on a Windows10 machine a KeyboardInterrupt is raised in line self.event.wait() preventing a graceful shutdown. I have tried different approaches as described here to prevent that the subprocess is receiving the signal.

What is the correct way to to get the same behavior on the different OS using Python 2.7?

import multiprocessing
import signal

class MyProcess(multiprocessing.Process):

    def __init__(self):
        super(MyProcess, self).__init__()
        self.event = multiprocessing.Event()

    def run(self):
        print "Subprocess: ", multiprocessing.current_process()
        self.event.wait()
        print "Subprocess: shutdown"

def sighandler(a,b,):
    print "Main: Graceful shutdown"
    p1.event.set()

def run():
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    global p1
    p1 = MyProcess()

    p1.start()

    signal.signal(signal.SIGINT, sighandler)
    p1.join()

if __name__ == '__main__':
    run()

Body:
Using win32api.SetConsoleCtrlHandler from pywin32 one can control how Windows the interrupts. Using SetConsoleCtrlHandler(None, True) causes the calling process to ignore CTRL+C input. With SetConsoleCtrlHandler(sighandler, True) a specific handler can be registered.

Putting it all together the issue is addressed like this:

import multiprocessing
import signal
import sys

class MyProcess(multiprocessing.Process):

    def __init__(self):
        super(MyProcess, self).__init__()
        self.event = multiprocessing.Event()

    def run(self):
        if sys.platform == "win32":
            import win32api # ignoring the signal
            win32api.SetConsoleCtrlHandler(None, True)

        print "Subprocess: ", multiprocessing.current_process()
        self.event.wait()
        print "Subprocess: shutdown"

def sighandler(a,b=None):
    print "Main: Graceful shutdown"
    p1.event.set()

def run():
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    global p1
    p1 = MyProcess()

    p1.start()

    if sys.platform == "win32":
        import win32api
        win32api.SetConsoleCtrlHandler(sighandler, True)
    else:
        signal.signal(signal.SIGINT, sighandler)

    p1.join()

if __name__ == '__main__':
    run()


问:
How to make absolutely positioned element take full screen width when it is inside fixed width container?
Html:

```<code><div id='id1'>
  <div id='id2'>

  </div>
</div>
</code>```

Css:

```<code>#id1 {
  width: 300px;
  height: 200px;
  margin: 0 auto;
  background: red;
  position: relative;
}
#id2 {
  position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto;
  width: 100%; top: 20px; background: green; height: 30px;
}
</code>```

I want #id2 to take full screen width. I can specify left: -Npx and right: -Npx, but this will work only for some screen sizes.

id2 must not go beyond screen, so I can not specify left: -9999px;

Related fiddle: https://jsfiddle.net/aLubmd4a/

答:
```<code>#id2 {
    position: absolute;
    left: -100%;
    right: -100%;
    top: 20px;
    background: green;
    height: 30px;
}
</code>```

https://jsfiddle.net/aLubmd4a/1/

Body:
Html:

Css:

#id1 {
  width: 300px;
  height: 200px;
  margin: 0 auto;
  background: red;
  position: relative;
}
#id2 {
  position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto;
  width: 100%; top: 20px; background: green; height: 30px;
}

I want #id2 to take full screen width. I can specify left: -Npx and right: -Npx, but this will work only for some screen sizes.

id2 must not go beyond screen, so I can not specify left: -9999px;

Related fiddle: https://jsfiddle.net/aLubmd4a/

Body:
#id2 {
    position: absolute;
    left: -100%;
    right: -100%;
    top: 20px;
    background: green;
    height: 30px;
}

https://jsfiddle.net/aLubmd4a/1/


问:
Pymc3: how to defined an ordered vector of parameters
I'm trying to do an ordered logistic regression, one parameter of which is an ordered vector of cutpoints. I'm not sure how I can define them.

One very stupid way I have come up with is to just define each component of the vector manually, using one as the other's bound:

```<code>with pm.Model() as bound_model:
    a = pm.Normal('a', mu=0, sd=10)
    BoundedB = pm.Bound(pm.Normal, upper=a)
    b = BoundedB('b', mu=0, sd=10)
    BoundedC = pm.Bound(pm.Normal, upper=b)
    c = BoundedC('c', mu=0, sd=10)

    bound_trace = pm.sample(1000)
</code>```

This is hardly efficient and I'm not sure whether they will work as expected. Is there better way to do this?

答:
This is a missing feature in pymc3 I guess. I might write a pull request, but in the meantime you can use something like this:

```<code>class Ordered(pymc3.distributions.transforms.ElemwiseTransform):
    name = "ordered"

    def forward(self, x):
        out = tt.zeros(x.shape)
        out = tt.inc_subtensor(out[0], x[0])
        out = tt.inc_subtensor(out[1:], tt.log(x[1:] - x[:-1]))
        return out

    def backward(self, y):
        out = tt.zeros(y.shape)
        out = tt.inc_subtensor(out[0], y[0])
        out = tt.inc_subtensor(out[1:], tt.exp(y[1:]))
        return tt.cumsum(out)

    def jacobian_det(self, y):
        return tt.sum(y[1:])
</code>```

And use it like this:

```<code>N = 10
with pm.Model() as model:
    pm.Normal('y', mu=np.zeros(N), sd=1, shape=N,
              transform=Ordered(), testval=np.arange(N))
</code>```

Edit: A very short explanation about what is happening here:

We define a map from $R^n$ to the set of ordered sequences by

```<code>f(x_1) = x_1,\quad f(x_i) = f(x_{i - 1}) + exp(x_i)
</code>```

Since this is a nice bijective function, we can compute the probability density on $R^n$ by

```<code>P_{R^n}(x) = P_{ordered}(f(x)) \cdot |J_{f(x)}|
</code>```

where J is the jacobian of the transformation.

The sampler will only see the unconstrained values. This is pretty much how Bound is implemented in the first place.

If you want more details, you can have a look at the stan manual. It contains a nice description of these transforms, and the math is the same for pymc3 and stan.

Body:
I'm trying to do an ordered logistic regression, one parameter of which is an ordered vector of cutpoints. I'm not sure how I can define them.

One very stupid way I have come up with is to just define each component of the vector manually, using one as the other's bound:

with pm.Model() as bound_model:
    a = pm.Normal('a', mu=0, sd=10)
    BoundedB = pm.Bound(pm.Normal, upper=a)
    b = BoundedB('b', mu=0, sd=10)
    BoundedC = pm.Bound(pm.Normal, upper=b)
    c = BoundedC('c', mu=0, sd=10)

    bound_trace = pm.sample(1000)

This is hardly efficient and I'm not sure whether they will work as expected. Is there better way to do this?

Body:
This is a missing feature in pymc3 I guess. I might write a pull request, but in the meantime you can use something like this:

class Ordered(pymc3.distributions.transforms.ElemwiseTransform):
    name = "ordered"

    def forward(self, x):
        out = tt.zeros(x.shape)
        out = tt.inc_subtensor(out[0], x[0])
        out = tt.inc_subtensor(out[1:], tt.log(x[1:] - x[:-1]))
        return out

    def backward(self, y):
        out = tt.zeros(y.shape)
        out = tt.inc_subtensor(out[0], y[0])
        out = tt.inc_subtensor(out[1:], tt.exp(y[1:]))
        return tt.cumsum(out)

    def jacobian_det(self, y):
        return tt.sum(y[1:])

And use it like this:

N = 10
with pm.Model() as model:
    pm.Normal('y', mu=np.zeros(N), sd=1, shape=N,
              transform=Ordered(), testval=np.arange(N))

Edit: A very short explanation about what is happening here:

We define a map from $R^n$ to the set of ordered sequences by

f(x_1) = x_1,\quad f(x_i) = f(x_{i - 1}) + exp(x_i)

Since this is a nice bijective function, we can compute the probability density on $R^n$ by

P_{R^n}(x) = P_{ordered}(f(x)) \cdot |J_{f(x)}|

where J is the jacobian of the transformation.

The sampler will only see the unconstrained values. This is pretty much how Bound is implemented in the first place.

If you want more details, you can have a look at the stan manual. It contains a nice description of these transforms, and the math is the same for pymc3 and stan.


问:
Difference between ArrayList<String>() and mutableListOf<String>() in Kotlin
```<code>private val repositories = mutableListOf<String>()

private val repositories = ArrayList<String>()
</code>```

Both are mutable list, then what is the point of two keywords mutableListOf or ArrayList?

or is there any major difference?

答:
As you can see in sources:

```<code>public inline fun <T> mutableListOf(): MutableList<T> = ArrayList()
</code>```

So, there is no difference, just a convenience method.

Body:
private val repositories = mutableListOf<String>()

private val repositories = ArrayList<String>()

Both are mutable list, then what is the point of two keywords mutableListOf or ArrayList?

or is there any major difference?

Body:
As you can see in sources:

public inline fun <T> mutableListOf(): MutableList<T> = ArrayList()

So, there is no difference, just a convenience method.


问:
Overwrite CSS from another files
I've downloaded a big webtemplate with many different css and js files. Now my website looks good but there still some little things I want to change. Like the font-style, colors and other things.

Now my problem is that I'm not able to overwrite the css from another files.

I want to change the font-family of my webpage. Now the normal content inside my
 tags, the navbar and and and... they all got the new font-family. But every  tag still got the old font family. I tried it with:

```<code>font-family: 'Roboto', sans-serif !important;
</code>```

but this haven't changed a thing and I don't really want to overwrite the css files that came from the template.

is there a way that my custom.css gets more important then the other files? Or any other trick?

答: If you do not want to overwrite the css file, you have to find the class or the id of the elements you want to change in the css file of the template that you downloaded, then you can change it.</p>

Title: Overwrite CSS from another files

Body:
I've downloaded a big webtemplate with many different css and js files. Now my website looks good but there still some little things I want to change. Like the font-style, colors and other things.

Now my problem is that I'm not able to overwrite the css from another files.

I want to change the font-family of my webpage. Now the normal content inside my
 tags, the navbar and and and... they all got the new font-family. But every  tag still got the old font family. I tried it with:

font-family: 'Roboto', sans-serif !important;

but this haven't changed a thing and I don't really want to overwrite the css files that came from the template.

is there a way that my custom.css gets more important then the other files? Or any other trick?


问:
If IQueryable<T> inherits IEnumerable<T> , how come IQueryable<T> is LINQ to SQL?
IEnumerable<T> case is LINQ-to-object and IQueryable<T> is the interface that allows LINQ-to-SQL , however IQueryable<T> inherits IEnumerable<T> , so how is it possible to IQueryable<T> to filter rows in the Database while IEnumerable<T> filters objects in the memory ?

答:
You are mistaking inheritance and interface implementation.

IQueryable<T> inherits IEnumerable<T> but that is radically different from inheritance between classes where the derived class inherits the implementation of the base class. Interfaces are simply contracts, there is no actual code behind them:

```<code>public interface IFoo
{
    void Foo(); //its simply a contract, no implementation at all.
}

public interface IBar: IFoo
{
    void Bar();
}

public class Foo: IFoo
{
    void Foo() { //Foo's sepecific implementation goes here }
}

public class Bar : IBar
{
    void Foo() { //Bar's specific implementation goes here }
    void Bar() { //implementation goes here }
}
</code>```

The fact that Bar implements IFoo through IBar doesn't mean, in any way, that there is any relationship whatsoever between Foo and Bar.

Body:
You are mistaking inheritance and interface implementation.

IQueryable<T> inherits IEnumerable<T> but that is radically different from inheritance between classes where the derived class inherits the implementation of the base class. Interfaces are simply contracts, there is no actual code behind them:

public interface IFoo
{
    void Foo(); //its simply a contract, no implementation at all.
}

public interface IBar: IFoo
{
    void Bar();
}

public class Foo: IFoo
{
    void Foo() { //Foo's sepecific implementation goes here }
}

public class Bar : IBar
{
    void Foo() { //Bar's specific implementation goes here }
    void Bar() { //implementation goes here }
}

The fact that Bar implements IFoo through IBar doesn't mean, in any way, that there is any relationship whatsoever between Foo and Bar.


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
For me it was Pointers.

Whilst I won't even pretend to fully understand pointers it was the first time that I really got stuck with programming. After messing around with Visual Basic 6 and server-side scripting languages I moved onto C, picked up the bare basics, then met pointers.

During that lecture I can remember peoples reaction to pointers. Self-proclaimed programming gods cowered in fear, those that knew little started reading the job ads in the local papers. I actually remember one girl in my class saying "whaaa?"

Many programmers get a wake-up call when they hit pointers. The programming world has just introduced you to the world of Computing and if you've only really just met you'll find very little to talk about.

OwnerDisplayName: Michael Buen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Triptych

OwnerDisplayName: EnderMB


问:
How to handle external and internal event in j2me
i am developing game in j2me. In that i have to handle external and internal event.. I studied in some of websites that we can handle the event with the help of hidenotify() and shownotify().

But it dont know where to use these two methods? whether in hidenotify() in pauseApp() and shownotify() in startApp() or somewhere else..

Please anyone give me a clear idea about handling the event in mobile.

答:
In J2ME world, external events resemble the following:

In coming SMS message. This is used trigger application specific action caused by a message sent from a pre-defined and well known sender. This feature is known as "push".

Media card inserted and the application needs to recognize it and act upon it.

If the phone is NFC enabled, launching an application when the phone is taken to a card reader.

When a server is attempting to connect to the phone, launch the application and perform some specific action. This requires that phone is addressable on network; very few of them support it.

Launching the application at a specific time.

I hope you get the idea. Most of the above are achieved by making use Push Registry.

The events that you are talking about are the callbacks to application that AMS (Application Management Software) notifies before the component is being shown and before the component is being hidden.

And pauseApp will be called by AMS when the application is about to be paused; this typically happens when there is an incoming phone call, or the flip is closed (on a flip phone) etc.

Hope it answers your question.

OwnerDisplayName: Deepa


问:
NodeJS ways to increase server performance in case of large number of connections and bulk of data
I am in between building a web application for showing vehicles position in a map view, AngularJS as front end and Node.js as the server for real-time updating of the map. The events are coming from a middleware application to Node server, the server then has to apply some logic there to broadcast the data to the needed connected clients.

Coming to the question- the issue what I am currently facing is that, there comes around 20K vehicle data at a single time to the Node server, the Node server then has to decide to which connected clients should the data updated.This is achieving by looping each data against each connected client's map bounds.If the incoming data bounds are within the connected client's bounds that particular data will be emitted to that client. So this entire process will take more time if there have 1K clients and 20K data.

Are there any ways to reduce this server overload by using any node techniques?

What I have tried: I read through node clusters, but I think it deals with distributing connections across multiple workers. Is this a way for resolving my issue?

The sample code snippet is as follows:

Node server side logic

```<code>users // user array eg: array(userSocketId1,userSocketId2);

bounds //each user's bounds array eg:array({userSocketId1:boundsValue},{userSocketId2:boundsValue2});

app.post('/addObject',  (req, res) => {
 for (var k = 0; k < Object.keys(req.body).length; k++) {
  var point=[{'lat':req.body[k].lat,'lng':req.body[k].lng,'message':req.body[k].message,'id':req.body[k].id}];
  for (var i = 0; i < users.length; i++) {
    var userBounds  = bounds[users[i]];
    if(typeof userBounds!=='undefined'){
      var inbounds    = inBounds(point[0],userBounds); // check whether current vehicle's bounds within user's bounds
      var user        = users[i];
      if(inbounds){
      io.to(user).emit('updateMap', point); // send that vehicle data to one client say user
      }
    }
  }
}
res.send('Event received in Node Server');
});
</code>```

Client-side logic for plotting vehicle info to map

```<code> socket.on('updateMap', function(msg){
    L.marker([msg.lat, msg.lng]).addTo(map);
 });
</code>```

答:
First thing you can try is make the code asynchrnous, like using Promise.

Without any library, this should work better:

```<code>app.post('/addObject',  (req, res) => {
    Promise.all(Object.keys(req.body).map((k) => {
        let point=[
            {
                'lat':req.body[k].lat,
                'lng':req.body[k].lng,
                'message':req.body[k].message,
                'id':req.body[k].id
            }
        ];

        Promise.all(users.map((user) => {
            let userBounds = bounds[user];
            if(typeof userBounds!=='undefined'){
                let inbounds = inBounds(point[0], userBounds); // check whether current vehicle's bounds within user's bounds
                if(inbounds){
                    io.to(user).emit('updateMap', point); // send that vehicle data to one client say user
                }
            }
        }));
    })).then(() => {
        res.send('Event received in Node Server');
    }).catch((error) => {
        res.send(error);
    });
});
</code>```

Other advantages include not having to deal with indexes, easier to deal with errors.

It may not be enought, but you will not block each time you receive a request, and that is already a huge improvement.

Body:
I am in between building a web application for showing vehicles position in a map view, AngularJS as front end and Node.js as the server for real-time updating of the map. The events are coming from a middleware application to Node server, the server then has to apply some logic there to broadcast the data to the needed connected clients.

Coming to the question- the issue what I am currently facing is that, there comes around 20K vehicle data at a single time to the Node server, the Node server then has to decide to which connected clients should the data updated.This is achieving by looping each data against each connected client's map bounds.If the incoming data bounds are within the connected client's bounds that particular data will be emitted to that client. So this entire process will take more time if there have 1K clients and 20K data.

Are there any ways to reduce this server overload by using any node techniques?

What I have tried: I read through node clusters, but I think it deals with distributing connections across multiple workers. Is this a way for resolving my issue?

The sample code snippet is as follows:

Node server side logic

users // user array eg: array(userSocketId1,userSocketId2);

bounds //each user's bounds array eg:array({userSocketId1:boundsValue},{userSocketId2:boundsValue2});

app.post('/addObject',  (req, res) => {
 for (var k = 0; k < Object.keys(req.body).length; k++) {
  var point=[{'lat':req.body[k].lat,'lng':req.body[k].lng,'message':req.body[k].message,'id':req.body[k].id}];
  for (var i = 0; i < users.length; i++) {
    var userBounds  = bounds[users[i]];
    if(typeof userBounds!=='undefined'){
      var inbounds    = inBounds(point[0],userBounds); // check whether current vehicle's bounds within user's bounds
      var user        = users[i];
      if(inbounds){
      io.to(user).emit('updateMap', point); // send that vehicle data to one client say user
      }
    }
  }
}
res.send('Event received in Node Server');
});

Client-side logic for plotting vehicle info to map

 socket.on('updateMap', function(msg){
    L.marker([msg.lat, msg.lng]).addTo(map);
 });

Body:
First thing you can try is make the code asynchrnous, like using Promise.

Without any library, this should work better:

app.post('/addObject',  (req, res) => {
    Promise.all(Object.keys(req.body).map((k) => {
        let point=[
            {
                'lat':req.body[k].lat,
                'lng':req.body[k].lng,
                'message':req.body[k].message,
                'id':req.body[k].id
            }
        ];

        Promise.all(users.map((user) => {
            let userBounds = bounds[user];
            if(typeof userBounds!=='undefined'){
                let inbounds = inBounds(point[0], userBounds); // check whether current vehicle's bounds within user's bounds
                if(inbounds){
                    io.to(user).emit('updateMap', point); // send that vehicle data to one client say user
                }
            }
        }));
    })).then(() => {
        res.send('Event received in Node Server');
    }).catch((error) => {
        res.send(error);
    });
});

Other advantages include not having to deal with indexes, easier to deal with errors.

It may not be enought, but you will not block each time you receive a request, and that is already a huge improvement.


问:
How to retrieve date time from mysql in decending order?
I have made a simple blog and trying to retrieve the latest post to the top of the blog. the code i have typed already does the ordering for the specific day however when i try to add a another post the next day it goes to the bottom of the page and the ordering of the latest blog works on that specific day.

So what i want is ,my blog to compare all the dates and then post the latest one right at the top..
many thanks

答:
You should use order by

```<code>SELECT * FROM table_name WHERE your_condition ORDER BY your_date_column_name
</code>```

DESC

Body:
You should use order by

SELECT * FROM table_name WHERE your_condition ORDER BY your_date_column_name

DESC


问:
Show values in another value in sql
I want show value 1 by 'this i number one' in result of query sql. I'm looking for a statement like ALIAS but using for values, not column.
Ex:
id|
0|
1|
1|
When excute query results sholud be:
id|
this is number zero|
this is number one|
this is number one|

Thanks!

答:
Ex: i have table id that have 2 value 0,1. Can i using SELECT id FROM table WITH 0 AS zero AND 1 AS one;

I hope my result should be: id|zero|zero|one|...

If I correct understood, you need something like this:

```<code>with t(id) as (
    select 0
    union all
    select 1
    -- another values
)
select id as original_value,
CASE
    WHEN id = 0 THEN 'zero'
    WHEN id = 1 THEN 'one'
    -- another values
END as changed_value
from t
</code>```

Title: Show values in another value in sql

Body:
Ex: i have table id that have 2 value 0,1. Can i using SELECT id FROM table WITH 0 AS zero AND 1 AS one;

I hope my result should be: id|zero|zero|one|...

If I correct understood, you need something like this:

with t(id) as (
    select 0
    union all
    select 1
    -- another values
)
select id as original_value,
CASE
    WHEN id = 0 THEN 'zero'
    WHEN id = 1 THEN 'one'
    -- another values
END as changed_value
from t


问:
How to show console.log in mobile simulator for angular2
I want to debug javascript inside mobile phones.

So please provide some piece of code or library how to show console.log in android/iphone simulator. It's better to show it in phone screen.

I am using angular2 ionic2

答:
I recommend you a remote tool like jsconsole

(function(angular) {
  'use strict';
  angular.module('ngConsole', []).controller('consoleController', function($scope) {
    $scope.messages = [];
    $scope.log = function(msg) {
      $scope.messages.push({
        type: 'log',
        text: msg,
        date: new Date()
      });
    };
  });
})(window.angular);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example</title>
  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>

</head>

<body ng-app="ngConsole">
  <div ng-controller="consoleController">
    <ul>
      <li ng-repeat="msg in messages">
        [{{$index + 1}}] {{msg.type}} {{msg.text}} {{msg.date}}
      </li>
      <li ng-if="messages.length === 0">
        <i>no results messages...</i>
      </li>
    </ul>
    <button ng-click="log('ok')">click</button>
  </div>
</body>

</html></code>```

Body:
I recommend you a remote tool like jsconsole

(function(angular) {
  'use strict';
  angular.module('ngConsole', []).controller('consoleController', function($scope) {
    $scope.messages = [];
    $scope.log = function(msg) {
      $scope.messages.push({
        type: 'log',
        text: msg,
        date: new Date()
      });
    };
  });
})(window.angular);

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example</title>
  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>

</head>

<body ng-app="ngConsole">
  <div ng-controller="consoleController">
    <ul>
      <li ng-repeat="msg in messages">
        [{{$index + 1}}] {{msg.type}} {{msg.text}} {{msg.date}}
      </li>
      <li ng-if="messages.length === 0">
        <i>no results messages...</i>
      </li>
    </ul>
    <button ng-click="log('ok')">click</button>
  </div>
</body>

</html>


问:
Angular 2 unit test case is not working for services with external module configuration
If I create a module with services using @Inject method is not working with Angular 2 Testbed Unit test cases. It is throwing No Provider for AppService Error.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { AppService } from './app.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [
    {provide:'AppService',useClass:AppService}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }```
</div>
</div>
</p>

<ol start="2">
<li>app.component.ts</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component, Inject } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  constructor(@Inject('AppService') private appService) {}

  getName() {
    this.title = this.appService.getName();
  }

  setName(name) {
    this.appService.setName(name);
  }
}</code>```

app.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class AppService {
  private name = 'dummy';

  public getName() {
    return this.name;
  }

  public setName(name) {
    console.log("ser", name);
    this.name = name;
  }
}```
</div>
</div>
</p>

<ol start="4">
<li>app.component.spec.ts</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Injectable} from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

import { AppService } from './app.service';

describe('AppComponent', () => {

  let fixture, comp, appService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [
        AppComponent
      ],
      providers: [AppService]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.debugElement.componentInstance;
    appService = fixture.debugElement.injector.get(AppService);
  });

  it('should create the app', async(() => {
    expect(comp).toBeTruthy();
  }));

});</code>```

答:
try adding providers: [AppService] in @Component in app.component.ts as below</p>

```<code>@Component({
providers: [AppService],
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
</code>```

Body:
If I create a module with services using @Inject method is not working with Angular 2 Testbed Unit test cases. It is throwing No Provider for AppService Error.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { AppService } from './app.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [
    {provide:'AppService',useClass:AppService}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component, Inject } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  constructor(@Inject('AppService') private appService) {}

  getName() {
    this.title = this.appService.getName();
  }

  setName(name) {
    this.appService.setName(name);
  }
}

app.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class AppService {
  private name = 'dummy';

  public getName() {
    return this.name;
  }

  public setName(name) {
    console.log("ser", name);
    this.name = name;
  }
}

app.component.spec.ts

import { Injectable} from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

import { AppService } from './app.service';

describe('AppComponent', () => {

  let fixture, comp, appService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [
        AppComponent
      ],
      providers: [AppService]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.debugElement.componentInstance;
    appService = fixture.debugElement.injector.get(AppService);
  });

  it('should create the app', async(() => {
    expect(comp).toBeTruthy();
  }));

});

Body:
try adding providers: [AppService] in @Component in app.component.ts as below

@Component({
providers: [AppService],
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})


问:
MySQLSyntaxErrorException: Table XYZ doesn't exist
I am using JPA and c3p0 and attempting to query a table and getting back a stack trace claiming that the table doesn't exist. I can open a connection to the db in, for example, DbVisualizer, and see the table there. In fact, the debug statements from my app show it is able to make a connection and test its viability. But then it is not finding the table.

```<code>15:45:53.940 [http-8080-1] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtaining JDBC connection
15:45:53.940 [http-8080-1] DEBUG c.m.v.c.i.C3P0PooledConnectionPool - Testing PooledConnection [com.mchange.v2.c3p0.impl.NewPooledConnection@4d687dcd] on CHECKOUT.
15:45:53.949 [http-8080-1] DEBUG c.m.v.c.i.C3P0PooledConnectionPool - Test of PooledConnection [com.mchange.v2.c3p0.impl.NewPooledConnection@4d687dcd] on CHECKOUT has SUCCEEDED.
15:45:53.950 [http-8080-1] DEBUG c.m.v.resourcepool.BasicResourcePool - trace com.mchange.v2.resourcepool.BasicResourcePool@7930ebb [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@3e30e173)
15:45:53.950 [http-8080-1] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtained JDBC connection
15:45:53.966 [http-8080-1] DEBUG org.hibernate.SQL - select alert0_.rrdb_key as rrdb1_0_, alert0_.date as date0_, alert0_.hostname as hostname0_, alert0_.message as message0_, alert0_.program as program0_ from reportsDb.alerts alert0_ where (alert0_.message not like '%Anomolous%') and (alert0_.message not like '%Requeue%')
Hibernate: select alert0_.rrdb_key as rrdb1_0_, alert0_.date as date0_, alert0_.hostname as hostname0_, alert0_.message as message0_, alert0_.program as program0_ from reportsDb.alerts alert0_ where (alert0_.message not like '%Anomolous%') and (alert0_.message not like '%Requeue%')
15:45:54.013 [http-8080-1] DEBUG c.m.v2.c3p0.impl.NewPooledConnection - com.mchange.v2.c3p0.impl.NewPooledConnection@4d687dcd handling a throwable.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'reportsDb.alerts' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.6.0_45]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) ~[na:1.6.0_45]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) ~[na:1.6.0_45]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513) ~[na:1.6.0_45]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406) ~[mysql-connector-java-5.1.6.jar:na]
...
</code>```

Here is persistence.xml (in /src/main/resources/META-INF):

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" 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_1_0.xsd">
    <persistence-unit name="reportsDb" transaction-type="RESOURCE_LOCAL">
        <description>Hibernate</description>
        <class>com.pronto.mexp.common.entity.Alert</class>
    </persistence-unit>
</persistence>
</code>```

A subsection of applicationContext.xml:

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

    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>

    <bean id="reportsDbEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="reportsDbDataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true"/>
                <property name="generateDdl" value="false" />
                <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            </bean>
        </property>
        <property name="persistenceUnitName" value="reportsDb" />
        <property name="jpaDialect" ref="jpaDialect"/>
    </bean>

    <bean id="reportsDbDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <!--<property name="jdbcUrl" value="jdbc:mysql://devdbrw01:3306/mexp"/>-->
        <property name="jdbcUrl" value="jdbc:mysql://report101:3306/worker_events"/>
        <property name="user" value="********"/>
        <property name="password" value="********"/>
        <property name="acquireRetryDelay" value="1000"/>
        <property name="acquireRetryAttempts" value="4"/>
        <property name="breakAfterAcquireFailure" value="false"/>
        <property name="testConnectionOnCheckout" value="true"/>
        <property name="maxConnectionAge" value="14400"/>
        <property name="maxIdleTimeExcessConnections" value="1800"/>
    </bean>

    <!-- DAOs -->
    <bean id="genericReportsDbDAO" class="com.pronto.mexp.common.dal.GenericReportsDbJPADAOImpl"/>

    <bean id="alertJPADAO" class="com.pronto.mexp.dal.AlertJPADAOImpl" parent="genericReportsDbDAO"/>
</beans>
</code>```

The thing I find suspicious is the part of the hibernate query where it tries to query select ... from reportsDb.alerts alert0_ - how do I confirm that "reportsDb" actually stands for my data source that I spec'd in applicationContext.xml?

ETA:
The entity, Alert, looks like this:

```<code>@Entity
@Table(name = "alerts", catalog = "reportsDb")
public class Alert {

    int rrdbKey;
    String hostname = "";
    String message = "";
    String program = "";
    Date date = new Date();

    @javax.persistence.Column(name = "rrdb_key", nullable = false, insertable = false, updatable = false, length = 10, precision = 0)
    @Id
    public int getRrdbKey() {
        return rrdbKey;
    }

    public void setRrdbKey(int rrdbKey) {
        this.rrdbKey = rrdbKey;
    }

    @javax.persistence.Column(name = "hostname", nullable = false, insertable = false, updatable = false, length = 32, precision = 0)
    @Basic
    public String getHostname() {
        return hostname;
    }

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    @javax.persistence.Column(name = "message", nullable = false, insertable = false, updatable = false, length = 128, precision = 0)
    @Basic
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @javax.persistence.Column(name = "program", nullable = true, insertable = false, updatable = false, length = 40, precision = 0)
    @Basic
    public String getProgram() {
        return program;
    }

    public void setProgram(String program) {
        this.program = program;
    }

    @javax.persistence.Column(name = "date", nullable = false, insertable = false, updatable = false, length = 19, precision = 0)
    @Basic
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}
</code>```

答:
I had the same issue, my mysql db was on windows but i moved it to linux which resulted in the mysql syntax of not recognizing the table.
The cause was that mysql on windows is case insensitive and case sensitive on linux
I was able to resolve this by adding :

lower_case_table_names=1

in my.cnf.

Also make sure to include

[mysqld]

at the beginning of my.cnf to avoid another error

"MySQL my.cnf file - Found option without preceding group"

Body:
I am using JPA and c3p0 and attempting to query a table and getting back a stack trace claiming that the table doesn't exist. I can open a connection to the db in, for example, DbVisualizer, and see the table there. In fact, the debug statements from my app show it is able to make a connection and test its viability. But then it is not finding the table.

15:45:53.940 [http-8080-1] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtaining JDBC connection
15:45:53.940 [http-8080-1] DEBUG c.m.v.c.i.C3P0PooledConnectionPool - Testing PooledConnection [com.mchange.v2.c3p0.impl.NewPooledConnection@4d687dcd] on CHECKOUT.
15:45:53.949 [http-8080-1] DEBUG c.m.v.c.i.C3P0PooledConnectionPool - Test of PooledConnection [com.mchange.v2.c3p0.impl.NewPooledConnection@4d687dcd] on CHECKOUT has SUCCEEDED.
15:45:53.950 [http-8080-1] DEBUG c.m.v.resourcepool.BasicResourcePool - trace com.mchange.v2.resourcepool.BasicResourcePool@7930ebb [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@3e30e173)
15:45:53.950 [http-8080-1] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtained JDBC connection
15:45:53.966 [http-8080-1] DEBUG org.hibernate.SQL - select alert0_.rrdb_key as rrdb1_0_, alert0_.date as date0_, alert0_.hostname as hostname0_, alert0_.message as message0_, alert0_.program as program0_ from reportsDb.alerts alert0_ where (alert0_.message not like '%Anomolous%') and (alert0_.message not like '%Requeue%')
Hibernate: select alert0_.rrdb_key as rrdb1_0_, alert0_.date as date0_, alert0_.hostname as hostname0_, alert0_.message as message0_, alert0_.program as program0_ from reportsDb.alerts alert0_ where (alert0_.message not like '%Anomolous%') and (alert0_.message not like '%Requeue%')
15:45:54.013 [http-8080-1] DEBUG c.m.v2.c3p0.impl.NewPooledConnection - com.mchange.v2.c3p0.impl.NewPooledConnection@4d687dcd handling a throwable.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'reportsDb.alerts' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.6.0_45]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) ~[na:1.6.0_45]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) ~[na:1.6.0_45]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513) ~[na:1.6.0_45]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406) ~[mysql-connector-java-5.1.6.jar:na]
...

Here is persistence.xml (in /src/main/resources/META-INF):

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" 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_1_0.xsd">
    <persistence-unit name="reportsDb" transaction-type="RESOURCE_LOCAL">
        <description>Hibernate</description>
        <class>com.pronto.mexp.common.entity.Alert</class>
    </persistence-unit>
</persistence>

A subsection of applicationContext.xml:

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

    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>

    <bean id="reportsDbEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="reportsDbDataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true"/>
                <property name="generateDdl" value="false" />
                <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            </bean>
        </property>
        <property name="persistenceUnitName" value="reportsDb" />
        <property name="jpaDialect" ref="jpaDialect"/>
    </bean>

    <bean id="reportsDbDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>

        <property name="jdbcUrl" value="jdbc:mysql://report101:3306/worker_events"/>
        <property name="user" value="********"/>
        <property name="password" value="********"/>
        <property name="acquireRetryDelay" value="1000"/>
        <property name="acquireRetryAttempts" value="4"/>
        <property name="breakAfterAcquireFailure" value="false"/>
        <property name="testConnectionOnCheckout" value="true"/>
        <property name="maxConnectionAge" value="14400"/>
        <property name="maxIdleTimeExcessConnections" value="1800"/>
    </bean>

    <bean id="genericReportsDbDAO" class="com.pronto.mexp.common.dal.GenericReportsDbJPADAOImpl"/>

    <bean id="alertJPADAO" class="com.pronto.mexp.dal.AlertJPADAOImpl" parent="genericReportsDbDAO"/>
</beans>

The thing I find suspicious is the part of the hibernate query where it tries to query select ... from reportsDb.alerts alert0_ - how do I confirm that "reportsDb" actually stands for my data source that I spec'd in applicationContext.xml?

ETA:
The entity, Alert, looks like this:

@Entity
@Table(name = "alerts", catalog = "reportsDb")
public class Alert {

    int rrdbKey;
    String hostname = "";
    String message = "";
    String program = "";
    Date date = new Date();

    @javax.persistence.Column(name = "rrdb_key", nullable = false, insertable = false, updatable = false, length = 10, precision = 0)
    @Id
    public int getRrdbKey() {
        return rrdbKey;
    }

    public void setRrdbKey(int rrdbKey) {
        this.rrdbKey = rrdbKey;
    }

    @javax.persistence.Column(name = "hostname", nullable = false, insertable = false, updatable = false, length = 32, precision = 0)
    @Basic
    public String getHostname() {
        return hostname;
    }

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    @javax.persistence.Column(name = "message", nullable = false, insertable = false, updatable = false, length = 128, precision = 0)
    @Basic
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @javax.persistence.Column(name = "program", nullable = true, insertable = false, updatable = false, length = 40, precision = 0)
    @Basic
    public String getProgram() {
        return program;
    }

    public void setProgram(String program) {
        this.program = program;
    }

    @javax.persistence.Column(name = "date", nullable = false, insertable = false, updatable = false, length = 19, precision = 0)
    @Basic
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

ContentLicense: CC BY-SA 4.0


问:
Maintaining project with plugins in git
We are currently using SVN to develop an internal application that has most of its functionality in plugins. In our approach to switch git, this app is causing some headaches as to what the best practice is regarding handling this kind of project in git.

I.e. should we put every plugin into its own git repository? This would seem a logical choice as the plugins are mostly not depending on each other and rather stand-alone (just using the core app for framework functionality and management of common functions), often developed by different persons and occasionally deprecated. However there are now well over a dozen plugins with more to come and building the whole project would usually require checking out all (or most) of the plugins one by one. And there does not seem to be an easy way to check out ALL of them at once, i.e. there probably needs to be some kind of "list" out there so people know what to get and what not.

On the other hand, putting everything in one git repository seems to be not in the spirit of git, esp. as we would carry around old dead code and working on just one plugin would require checking out a lot of code (though then most developers working on it would check out everything anyway). Also branching would always branch everything (which makes for example cross-testing of branched features difficult if the plugins can't branch individually)

One idea is to use submodules, but I don't know whether the overhead (mental overhead, I mean) is bigger than the gain (or, whether we gain less than we lose with using the one-for-all approach).

How would/do you handle this kind of project in git?

答:
This kind of system (as in "collection of writable components") would be best managed with:

each plugin in its own repository

one parent project which would declare all the relevant plugins as submodules.

As detailed in "true nature of submodules", you can then modify any plugin directly from that one parent project.

(See also Duplicate submodules with Git if you have duplicate dependencies)
And recent Git releases comes with commands able to recursively checkout all the submodules of a parent project.

So when I check the parent project out and remember to call "git submodule init" for each plugin, I would have all projects on my desktop.

But you shouldn't have to remember to do anything beside git submodule update --init --recursive (just one command). As I said, it will recursively initialize all your submodules.

However submodules are pinned to versions, wouldn't this cause some more complicated workflow?

The principle of dependency management is to always reference a specific version (as opposed to reference "the latest code out there" for one component).

But that doesn't prevent you to:

work in that component (working from that specific version *as a starting point")

commit

push that one component to its remote repo

go up one level, back in the parent project

commit the parent project (in order to reference the new version of the submodule you just modified)

Again, true nature of submodules details that process.

Title: Maintaining project with plugins in git


问:
COMException with interopServices C# in Excel
I am facing a very annoying problem while installing my program on some machines, I have developed a C# application and everything goes OK and surely I tested it on another machines with no problem but when I am installing it on my client machine the following problem occurs:

System.Runtime.InteropServices.COMException (0x800A03EC): exception
  from HRESULT: 0x800A03EC
      at
  System.RuntimeType.ForwardCallToInvokeMember
  (String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
     at Microsoft.Office.Interop.Excel.Range.set__Default(Object RowIndex, Object ColumnIndex, Object )
      at SchoolMgmt.certificate_succession.sum_operation()

as the program communicates with Excel, Office Microsoft (I tried to install another Office version with no success).

I've searched a lot for a solution but nothing works as it's claimed the problem is just a permission issue in the following path

C:\Windows\ System32\config\SystemProfile

It is really driving me crazy why the program runs smoothly and successfuly on my testing machine but not on my client's !!

Any suggestion please.

答:
I got the same issue and after several trials I understood that some installed versions of Excel (2013) had set the options (general options) of compatibility with Excel 2003. In this case the new created file accepts only 255 columns and 65.535 rows. As my application was working on thousands of columns, excel was generating the error.
The easy solution was to change the general options and set the "saved file format" to ".xlsx" instead of ".xls"


问:
Class lables absent from Keras Predictions
I am trying to solve the Cats vs Dogs problem using Keras. Here is the model I am using.

```<code>from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
from keras import regularizers
from keras.utils import plot_model

img_width, img_height = 150, 150
train_data_dir = 'kateVSdoge/train'
validation_data_dir = 'kateVSdoge/validation'
nb_train_samples = 2000
nb_validation_samples = 800
epochs = 50
batch_size = 16
if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()

model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1,kernel_regularizer=regularizers.l2(0.01),
                activity_regularizer=regularizers.l1(0.01)))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

train_datagen = ImageDataGenerator(
                rescale=1. / 255,
                shear_range=0.2,
                zoom_range=0.2,
                horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
                    train_data_dir,
                    target_size=(img_width, img_height),
                    batch_size=batch_size,
                    class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
                        validation_data_dir,
                        target_size=(img_width, img_height),
                        batch_size=batch_size,
                        class_mode='binary',
                        )
xm=model.fit_generator(
                    train_generator,
                    steps_per_epoch=nb_train_samples // batch_size,
                    epochs=epochs,
                    validation_data=validation_generator,
                    validation_steps=nb_validation_samples // batch_size)

model.save_weights('first_try3.h5')
model_json=model.to_json()
with open("model3.json","w+") as json_file:
    json_file.write(model_json)
plot_model(model,to_file="model.jpeg")
</code>```

The model trains well accuracy at the end is 0.79-0.80. But when I try to load the model in a predictor script and predict using the model.predict_generator()  I seem to be doing something wrong as I cant get the class names in the prediction. I have tried .predict() and .predict_proba() without any success.

Here is the predictor script:

```<code>from keras.models import Sequential, model_from_json
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
import numpy as np

p_model = Sequential();
jsonfile = open('model3.json','r')
model_json = jsonfile.read()
p_model = model_from_json(model_json)
p_model.load_weights('first_try3.h5')
p_model.compile(loss='binary_crossentropy',
                optimizer='rmsprop',
                metrics=['accuracy'])

img = image.load_img('do.jpg', target_size=(150,150))
x=image.img_to_array(img)
x=x.reshape((1,)+x.shape)
test_datagen = ImageDataGenerator(rescale=1. /255)
m=test_datagen.flow(x,batch_size=1)

preds = p_model.predict_generator(m,1,verbose=1)
print preds
</code>```

Also I observed an Interesting thing , The image doesn't seem to rescale.
I printed out x and m.x , both the matrices seem to be equal and the values don't transform to be between 0 and 1.

Here is the output for a cat and a dog's picture respectively.

```<code>(myenv)link@zero-VirtualBox:~/myenv/keras_app$ python predictor.py
Using Theano backend.
1/1 [==============================] - 0s
[[ 0.29857877]]
(myenv)link@zero-VirtualBox:~/myenv/keras_app$ python predictor.py
Using Theano backend.
1/1 [==============================] - 0s
[[ 0.77536112]]
</code>```

I have used the advice given here https://stackoverflow.com/a/41833076/4159447 to introduce regularizers and rescale.

What am I doing wrong? All I want is to get the cat and dog labels against their scores.

答:
The only wrong thing is to expect class names from a classifier. The classifier doesn't know the class names, that is a post-processing step, something like:

```<code>preds = p_model.predict_generator(m,1,verbose=1)[0]

if preds > 0.5:
    output = "cat"
else:
   output = "dog"
</code>```

Note that 0.5 might not be the best threshold, you can also take the class with biggest probability (p vs 1 - p).

Body:
I am trying to solve the Cats vs Dogs problem using Keras. Here is the model I am using.

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
from keras import regularizers
from keras.utils import plot_model

img_width, img_height = 150, 150
train_data_dir = 'kateVSdoge/train'
validation_data_dir = 'kateVSdoge/validation'
nb_train_samples = 2000
nb_validation_samples = 800
epochs = 50
batch_size = 16
if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()

model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1,kernel_regularizer=regularizers.l2(0.01),
                activity_regularizer=regularizers.l1(0.01)))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

train_datagen = ImageDataGenerator(
                rescale=1. / 255,
                shear_range=0.2,
                zoom_range=0.2,
                horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
                    train_data_dir,
                    target_size=(img_width, img_height),
                    batch_size=batch_size,
                    class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
                        validation_data_dir,
                        target_size=(img_width, img_height),
                        batch_size=batch_size,
                        class_mode='binary',
                        )
xm=model.fit_generator(
                    train_generator,
                    steps_per_epoch=nb_train_samples // batch_size,
                    epochs=epochs,
                    validation_data=validation_generator,
                    validation_steps=nb_validation_samples // batch_size)

model.save_weights('first_try3.h5')
model_json=model.to_json()
with open("model3.json","w+") as json_file:
    json_file.write(model_json)
plot_model(model,to_file="model.jpeg")

The model trains well accuracy at the end is 0.79-0.80. But when I try to load the model in a predictor script and predict using the model.predict_generator()  I seem to be doing something wrong as I cant get the class names in the prediction. I have tried .predict() and .predict_proba() without any success.

Here is the predictor script:

from keras.models import Sequential, model_from_json
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
import numpy as np

p_model = Sequential();
jsonfile = open('model3.json','r')
model_json = jsonfile.read()
p_model = model_from_json(model_json)
p_model.load_weights('first_try3.h5')
p_model.compile(loss='binary_crossentropy',
                optimizer='rmsprop',
                metrics=['accuracy'])

img = image.load_img('do.jpg', target_size=(150,150))
x=image.img_to_array(img)
x=x.reshape((1,)+x.shape)
test_datagen = ImageDataGenerator(rescale=1. /255)
m=test_datagen.flow(x,batch_size=1)

preds = p_model.predict_generator(m,1,verbose=1)
print preds

Also I observed an Interesting thing , The image doesn't seem to rescale.
I printed out x and m.x , both the matrices seem to be equal and the values don't transform to be between 0 and 1.

Here is the output for a cat and a dog's picture respectively.

(myenv)link@zero-VirtualBox:~/myenv/keras_app$ python predictor.py
Using Theano backend.
1/1 [==============================] - 0s
[[ 0.29857877]]
(myenv)link@zero-VirtualBox:~/myenv/keras_app$ python predictor.py
Using Theano backend.
1/1 [==============================] - 0s
[[ 0.77536112]]

I have used the advice given here https://stackoverflow.com/a/41833076/4159447 to introduce regularizers and rescale.

What am I doing wrong? All I want is to get the cat and dog labels against their scores.

Body:
The only wrong thing is to expect class names from a classifier. The classifier doesn't know the class names, that is a post-processing step, something like:

preds = p_model.predict_generator(m,1,verbose=1)[0]

if preds > 0.5:
    output = "cat"
else:
   output = "dog"

Note that 0.5 might not be the best threshold, you can also take the class with biggest probability (p vs 1 - p).


问:
scipy.sparse : Set row to zeros
Suppose I have a matrix in the CSR format, what is the most efficient way to set a row (or rows) to zeros?

The following code runs quite slowly:

```<code>A = A.tolil()
A[indices, :] = 0
A = A.tocsr()
</code>```

I had to convert to scipy.sparse.lil_matrix because the CSR format seems to support neither fancy indexing nor setting values to slices.

答:
You can use matrix dot product to achieve that zeroing. Since the matrix we'll use is very sparse (diagonal with zeros for the rows/columns we which to zero out), multiplication should be efficient.

You'll need one of the following functions:

```<code>import scipy.sparse

def zero_rows(M, rows):
    diag = scipy.sparse.eye(M.shape[0]).tolil()
    for r in rows:
        diag[r, r] = 0
    return diag.dot(M)

def zero_columns(M, columns):
    diag = scipy.sparse.eye(M.shape[1]).tolil()
    for c in columns:
        diag[c, c] = 0
    return M.dot(diag)
</code>```

Usage example:

```<code>>>> A = scipy.sparse.csr_matrix([[1,0,3,4], [5,6,0,8], [9,10,11,0]])
>>> A
<3x4 sparse matrix of type '<class 'numpy.int64'>'
        with 9 stored elements in Compressed Sparse Row format>
>>> A.toarray()
array([[ 1,  0,  3,  4],
       [ 5,  6,  0,  8],
       [ 9, 10, 11,  0]], dtype=int64)

>>> B = zero_rows(A, [1])
>>> B
<3x4 sparse matrix of type '<class 'numpy.float64'>'
        with 6 stored elements in Compressed Sparse Row format>
>>> B.toarray()
array([[  1.,   0.,   3.,   4.],
       [  0.,   0.,   0.,   0.],
       [  9.,  10.,  11.,   0.]])

>>> C = zero_columns(A, [1, 3])
>>> C
<3x4 sparse matrix of type '<class 'numpy.float64'>'
        with 5 stored elements in Compressed Sparse Row format>
>>> C.toarray()
array([[  1.,   0.,   3.,   0.],
       [  5.,   0.,   0.,   0.],
       [  9.,   0.,  11.,   0.]])
</code>```

Title: scipy.sparse : Set row to zeros

Body:
Suppose I have a matrix in the CSR format, what is the most efficient way to set a row (or rows) to zeros?

The following code runs quite slowly:

A = A.tolil()
A[indices, :] = 0
A = A.tocsr()

I had to convert to scipy.sparse.lil_matrix because the CSR format seems to support neither fancy indexing nor setting values to slices.

Body:
You can use matrix dot product to achieve that zeroing. Since the matrix we'll use is very sparse (diagonal with zeros for the rows/columns we which to zero out), multiplication should be efficient.

You'll need one of the following functions:

import scipy.sparse

def zero_rows(M, rows):
    diag = scipy.sparse.eye(M.shape[0]).tolil()
    for r in rows:
        diag[r, r] = 0
    return diag.dot(M)

def zero_columns(M, columns):
    diag = scipy.sparse.eye(M.shape[1]).tolil()
    for c in columns:
        diag[c, c] = 0
    return M.dot(diag)

Usage example:

>>> A = scipy.sparse.csr_matrix([[1,0,3,4], [5,6,0,8], [9,10,11,0]])
>>> A
<3x4 sparse matrix of type '<class 'numpy.int64'>'
        with 9 stored elements in Compressed Sparse Row format>
>>> A.toarray()
array([[ 1,  0,  3,  4],
       [ 5,  6,  0,  8],
       [ 9, 10, 11,  0]], dtype=int64)

>>> B = zero_rows(A, [1])
>>> B
<3x4 sparse matrix of type '<class 'numpy.float64'>'
        with 6 stored elements in Compressed Sparse Row format>
>>> B.toarray()
array([[  1.,   0.,   3.,   4.],
       [  0.,   0.,   0.,   0.],
       [  9.,  10.,  11.,   0.]])

>>> C = zero_columns(A, [1, 3])
>>> C
<3x4 sparse matrix of type '<class 'numpy.float64'>'
        with 5 stored elements in Compressed Sparse Row format>
>>> C.toarray()
array([[  1.,   0.,   3.,   0.],
       [  5.,   0.,   0.,   0.],
       [  9.,   0.,  11.,   0.]])


问:
Can't use superclass in Repository implementation in PHP
I'm trying to implement very basic Repository pattern in PHP.

Let's assume I need a common interface to handle common Entity storage:

```<code><?php

interface IRepository
{
    public function persist(Entity $entity);
    // reduced code for brevity
}
</code>```

Now I build entities types hierarchy:

```<code><?php

abstract class Entity
{
    protected $id;

    protected function getId()
    {
        return $this->id;
    }
}
</code>```

Here's the Post class:

```<code><?php

class Post extends Entity
{
    private $title;

    private $body;
}
</code>```

Now I would like to use PDO-supported databases to store posts:

```<code><?php

use PDO;

abstract class DatabaseRepository implements IRepository
{
    protected $pdo;

    protected $statement;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }
}
</code>```

And now I try to implement IRepository interface

```<code><?php

class PostRepository extends DatabaseRepository
{

    // I have an error here
    //  Fatal error: Declaration of PostRepository::persist(Post $post) must be compatible with IRepository::persist(Entity $entity)
    public function persist(Post $post)
    {
    }
}
</code>```

As you can see this throws fatal error. Using type hinting in PostRepository::persist() I guarantee that I use Entity child object to fulfill IRepository requirements. So why this error is thrown?

答:
As I commented you are looking for generics.  For now it isn't possible like  JAVA or C# it is however in HHVM

For PHP the rfc is still in draft status.
https://wiki.php.net/rfc/generics

So if you really want to do it, you either create a more generic interface with some type checking or make Post a subclass of Entity or both a subclass of another parent (this however will generate strict warnings).

Body:
I'm trying to implement very basic Repository pattern in PHP.

Let's assume I need a common interface to handle common Entity storage:

<?php

interface IRepository
{
    public function persist(Entity $entity);
    // reduced code for brevity
}

Now I build entities types hierarchy:

<?php

abstract class Entity
{
    protected $id;

    protected function getId()
    {
        return $this->id;
    }
}

Here's the Post class:

<?php

class Post extends Entity
{
    private $title;

    private $body;
}

Now I would like to use PDO-supported databases to store posts:

<?php

use PDO;

abstract class DatabaseRepository implements IRepository
{
    protected $pdo;

    protected $statement;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }
}

And now I try to implement IRepository interface

<?php

class PostRepository extends DatabaseRepository
{

    // I have an error here
    //  Fatal error: Declaration of PostRepository::persist(Post $post) must be compatible with IRepository::persist(Entity $entity)
    public function persist(Post $post)
    {
    }
}

As you can see this throws fatal error. Using type hinting in PostRepository::persist() I guarantee that I use Entity child object to fulfill IRepository requirements. So why this error is thrown?


问:
pjsip2 issue during build
I'm trying to use pjsip library for sip telephony in an android device for different architectures on a MAC.

I have downloaded 2.5.5 from http://svn.pjsip.org/repos/pjproject/tags/2.5.5 which is build fine for armabi architectures with the corresponding libpjsua2.so.

I'm trying to build it for other architectures as well but with no much lack on it. I have followed the instructions from https://trac.pjsip.org/repos/wiki/Getting-Started/Android but I have different errors.

For instance having TARGET_ABI=armeabi-v7a ./configure-android --use-ndk-cflags I was getting at the beginning:

/Users/*****/Library/Android/sdk/ndk-bundle/samples/hello-jni: No such file or directory.  Stop.
configure-android error: failed to run ndk-build, check ANDROID_NDK_ROOT env var

I downloaded the samples from github (as suggested in Android NDK) and now I get another error:

Users/iu/Library/Android/sdk/ndk-bundle/build/core/build-local.mk:151:
  *** Android NDK: Aborting    .  Stop. ./configure-android: line 72: test: argument expected configure-android error: compiler not found,
  please check environment settings (TARGET_ABI, etc)

Any suggestions?
Thanks

答:
For Android, I suggest, you build pjsip 2.6.
And yes, build it on Linux.
It has fixed many SIGSEG errors that occurred in 5.x versions.
Since we switched to 2.6 the stability of our app increased significantly.

It may happen, that another build issue arises with 2.6 that correlates with libYUV if you compile together with openSSL.
If you do not need video, disable it in the build (config_site.h).

Title: pjsip2 issue during build


问:
Porting XML parsing from Java to Objective C
I am trying to port code written in Java to Objective C (for iPhone), but I'm kind of confused about a few lines of my code (mentioned below). How should I port this efficiently?

```<code>Namespace nmgrhistory=Namespace.getNamespace("history", "http://www.mywebsite.com/History.xsd");
        pEventEl.addContent(new Element("History",nmgrhistory));
        Namespace nmgrState=Namespace.getNamespace("state", "http://www.mywebsite.com/State.xsd");
        pEventEl.addContent(new Element("State",nmgrState));

        Iterator<Element> eld=(Iterator<Element>) pEventEl.getChild(
                pEventEl.getName() == "event"?  "./history:history/state:state" : "./state:state",pEventEl.getNamespace());
</code>```

I'm not very sure about the replacements for the classes Namespace, Iterator and Element.

Anybody having idea or having done this before, please enlighten me.

答:
Ok... So although these are not the actual replacements ... But basically what u need for parsing XML in Objecive - C is "NSXMLParser"

so u can say that NSXMLParser is the replacement for Namespace

And for "Iterator" NSXMLParserDelegate has a method named:-

```<code>– parser:didStartElement:namespaceURI:qualifiedName:attributes:
</code>```

OR

```<code>– parser:foundCharacters:
</code>```

Body:
I am trying to port code written in Java to Objective C (for iPhone), but I'm kind of confused about a few lines of my code (mentioned below). How should I port this efficiently?

Namespace nmgrhistory=Namespace.getNamespace("history", "http://www.mywebsite.com/History.xsd");
        pEventEl.addContent(new Element("History",nmgrhistory));
        Namespace nmgrState=Namespace.getNamespace("state", "http://www.mywebsite.com/State.xsd");
        pEventEl.addContent(new Element("State",nmgrState));

        Iterator<Element> eld=(Iterator<Element>) pEventEl.getChild(
                pEventEl.getName() == "event"?  "./history:history/state:state" : "./state:state",pEventEl.getNamespace());

I'm not very sure about the replacements for the classes Namespace, Iterator and Element.

Anybody having idea or having done this before, please enlighten me.

Body:
Ok... So although these are not the actual replacements ... But basically what u need for parsing XML in Objecive - C is "NSXMLParser"

so u can say that NSXMLParser is the replacement for Namespace

And for "Iterator" NSXMLParserDelegate has a method named:-

– parser:didStartElement:namespaceURI:qualifiedName:attributes:

OR

– parser:foundCharacters:


问:
EditText losing focus if I hit the record button
I'm trying to build chat interface . I've written code for recording voice with animation for the fab.my problem is when I press the button and my edittext is focused the edittext for no reason is losing focus which is hiding the autodetect words bar in the keyboard leaving the Fab above the keyboard with 1 cm . I know that this problem is due to the recycle view since when i just set the visibility of the recycler view to Gone the edittext don't lose focus when I try to record .I've tried also to change windowSoftInputMode.  Thanks for the help. </p>

```<code> <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        android:id="@+id/relativeLayout_chat_background"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"

        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android"

        >

    <com.example.fcb.insurance.customViews.holdingbutton.HoldingButtonLayout
        android:id="@+id/input_holder"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        app:hbl_cancel_icon="@drawable/ic_clear_white_24dp"
        app:hbl_color="@color/colorAccent"
        app:hbl_holding_view="@+id/start_record"
        app:hbl_icon="@drawable/ic_mic_white_24dp"
        app:hbl_radius="@dimen/activity_main_holding_button_radius"
        app:hbl_second_radius="@dimen/activity_main_holding_button_second_radius"
        android:layout_toLeftOf="@+id/sendMessage"
       android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:clipChildren="false"
        android:clipToPadding="false"        >

        <LinearLayout
            android:id="@+id/slide_to_cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|end"
            android:layout_marginEnd="@dimen/activity_main_slide_to_cancel_margin_right"
            android:layout_marginRight="@dimen/activity_main_slide_to_cancel_margin_right"
            android:gravity="center_vertical"
            android:visibility="invisible">

            <ImageView
                android:layout_width="@dimen/activity_main_slide_to_cancel_icon_size"
                android:layout_height="@dimen/activity_main_slide_to_cancel_icon_size"
                android:layout_marginEnd="@dimen/activity_main_slide_to_cancel_icon_margin_right"
                android:layout_marginRight="@dimen/activity_main_slide_to_cancel_icon_margin_right"
                android:scaleType="center"
                android:src="@drawable/ic_keyboard_arrow_left_black_24dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/label_slide_to_cancel"/>

            <TextView

                android:id="@+id/textView_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:textColor="@color/colorAccent"
                />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center_horizontal"

            android:minHeight="@dimen/activity_main_input_holder_min_height"
            android:orientation="horizontal"
            >

            <EditText
                android:id="@+id/editText_message"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/activity_main_input_margin_left"
                android:layout_marginStart="@dimen/activity_main_input_margin_left"
               android:paddingLeft="16dp"
                android:layout_weight="1"
                android:hint="@string/hint_type_your_message"
                android:paddingBottom="@dimen/activity_main_input_padding_vertical"
                android:paddingTop="@dimen/activity_main_input_padding_vertical"
                android:textSize="@dimen/activity_main_input_text_size"
                android:background="@drawable/chat_input_text"
                android:maxLines="6"
                android:scrollbarStyle="insideInset"
                android:scrollbars="vertical"
                android:layout_gravity="bottom"
                ></EditText>

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/start_record"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@style/Widget.AppCompat.Button.Borderless.Colored"
                android:src="@drawable/ic_mic_white_24dp"
                android:layout_marginLeft="10dp"
                android:layout_gravity="bottom"
                />

        </LinearLayout>

  </com.example.fcb.insurance.customViews.holdingbutton.HoldingButtonLayout>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/sendMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.Button.Borderless.Colored"
        android:src="@drawable/ic_send_white_24dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="10dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:visibility="gone"

        />
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView_chat_item_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/input_holder"
        android:layout_marginEnd="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginStart="5dp"
        android:clipToPadding="false"
        android:paddingTop="8dp"
        android:visibility="visible"
        app:layoutManager="LinearLayoutManager"
        tools:listitem="@layout/item_chat_list_out"

        />

    </RelativeLayout>
</code>```

答:
I figured out a solution . I wrapped the recyclerView with linearLayout and I disabled focus and blocked the descendants.</p>

```<code>   <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/input_holder"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:descendantFocusability="blocksDescendants"
    >
<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView_chat_item_list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginStart="5dp"
    android:clipToPadding="false"
    android:paddingTop="8dp"
    android:visibility="visible"
    app:layoutManager="LinearLayoutManager"
    tools:listitem="@layout/item_chat_list_out"

    />
</LinearLayout>
</code>```

Body:
I'm trying to build chat interface . I've written code for recording voice with animation for the fab.my problem is when I press the button and my edittext is focused the edittext for no reason is losing focus which is hiding the autodetect words bar in the keyboard leaving the Fab above the keyboard with 1 cm . I know that this problem is due to the recycle view since when i just set the visibility of the recycler view to Gone the edittext don't lose focus when I try to record .I've tried also to change windowSoftInputMode.  Thanks for the help.

 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        android:id="@+id/relativeLayout_chat_background"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"

        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android"

        >

    <com.example.fcb.insurance.customViews.holdingbutton.HoldingButtonLayout
        android:id="@+id/input_holder"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        app:hbl_cancel_icon="@drawable/ic_clear_white_24dp"
        app:hbl_color="@color/colorAccent"
        app:hbl_holding_view="@+id/start_record"
        app:hbl_icon="@drawable/ic_mic_white_24dp"
        app:hbl_radius="@dimen/activity_main_holding_button_radius"
        app:hbl_second_radius="@dimen/activity_main_holding_button_second_radius"
        android:layout_toLeftOf="@+id/sendMessage"
       android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:clipChildren="false"
        android:clipToPadding="false"        >

        <LinearLayout
            android:id="@+id/slide_to_cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|end"
            android:layout_marginEnd="@dimen/activity_main_slide_to_cancel_margin_right"
            android:layout_marginRight="@dimen/activity_main_slide_to_cancel_margin_right"
            android:gravity="center_vertical"
            android:visibility="invisible">

            <ImageView
                android:layout_width="@dimen/activity_main_slide_to_cancel_icon_size"
                android:layout_height="@dimen/activity_main_slide_to_cancel_icon_size"
                android:layout_marginEnd="@dimen/activity_main_slide_to_cancel_icon_margin_right"
                android:layout_marginRight="@dimen/activity_main_slide_to_cancel_icon_margin_right"
                android:scaleType="center"
                android:src="@drawable/ic_keyboard_arrow_left_black_24dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/label_slide_to_cancel"/>

            <TextView

                android:id="@+id/textView_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:textColor="@color/colorAccent"
                />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center_horizontal"

            android:minHeight="@dimen/activity_main_input_holder_min_height"
            android:orientation="horizontal"
            >

            <EditText
                android:id="@+id/editText_message"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/activity_main_input_margin_left"
                android:layout_marginStart="@dimen/activity_main_input_margin_left"
               android:paddingLeft="16dp"
                android:layout_weight="1"
                android:hint="@string/hint_type_your_message"
                android:paddingBottom="@dimen/activity_main_input_padding_vertical"
                android:paddingTop="@dimen/activity_main_input_padding_vertical"
                android:textSize="@dimen/activity_main_input_text_size"
                android:background="@drawable/chat_input_text"
                android:maxLines="6"
                android:scrollbarStyle="insideInset"
                android:scrollbars="vertical"
                android:layout_gravity="bottom"
                ></EditText>

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/start_record"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@style/Widget.AppCompat.Button.Borderless.Colored"
                android:src="@drawable/ic_mic_white_24dp"
                android:layout_marginLeft="10dp"
                android:layout_gravity="bottom"
                />

        </LinearLayout>

  </com.example.fcb.insurance.customViews.holdingbutton.HoldingButtonLayout>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/sendMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.Button.Borderless.Colored"
        android:src="@drawable/ic_send_white_24dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="10dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:visibility="gone"

        />
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView_chat_item_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/input_holder"
        android:layout_marginEnd="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginStart="5dp"
        android:clipToPadding="false"
        android:paddingTop="8dp"
        android:visibility="visible"
        app:layoutManager="LinearLayoutManager"
        tools:listitem="@layout/item_chat_list_out"

        />

    </RelativeLayout>

Body:
I figured out a solution . I wrapped the recyclerView with linearLayout and I disabled focus and blocked the descendants.

   <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/input_holder"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:descendantFocusability="blocksDescendants"
    >
<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView_chat_item_list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginStart="5dp"
    android:clipToPadding="false"
    android:paddingTop="8dp"
    android:visibility="visible"
    app:layoutManager="LinearLayoutManager"
    tools:listitem="@layout/item_chat_list_out"

    />
</LinearLayout>


问:
PageRank score computing
I'm currently working on the TextRank algorithm, which uses PageRank.
I was wondering how does PageRank take the edge weight into account when calculating the scores?

I'm working with Python to implement my textrank algorithm, can I use the pagerank Python function to compute the score of the nodes even though my graph is weighted (and the edge weight is important)?

答:
PageRank actually works using a Markov Chain.

You can find more details about it in this paper (the whole theory is way too long to be explained here).

Title: PageRank score computing