问:
Recoding floats in a list
I have a list of floats, which looks like this:

```<code>predictions_dec = [13.0, 8.6, 4.9, -1.5, 6.2, 7.7, 2.0, 10.0, 7.7, 12.7,...]
</code>```

I want to clean this data, by giving number higher than 10.0 a 10.0 and numbers lower than 0.0 (so all negative numbers) a 0.0. I'm doing this with the following if statement:

```<code>predictions_clean = []
for pred in predictions_dec:
    if pred >= 10:
        predictions_clean.append(10.0)
    if pred <= 0:
        predictions_clean.append(0.0)
    else:
        predictions_clean.append(pred)
</code>```

This code seems to work, but the funny thing is that:

```<code>len(predictions_dec)
1222
len(predictions_clean)
1816
</code>```

My understanding of if statements is not that great. Where in the if statement am I doing something wrong?

答:
If your list is very large (and you thus want to avoid loops and if statements) you could also use NumPy and the mathematical trick to set every negative number to zero by:

```<code>A = .5*(A+np.abs(A))
</code>```

You could do the same to set everything larger that 10 to 10. Here is everything put together:

```<code>import numpy as np

A = np.array([13.0, 8.6, 4.9, -1.5, 6.2, 7.7, 2.0, 10.0, 7.7, 12.7])

# set all items <= 0 to 0.0
A = .5*(A+np.abs(A))
print(A)

# set all items >= 10 to 10.0
A = 10.-A
A = .5*(A+np.abs(A))
A = 10.-A
print(A)
</code>```

Edit

The suggestion by "tobias_k" is of course better then mine. But to put some science into it I considered a random list/array of length 1,000,000. I compared the above implementation to

```<code>A[A< 0.] =  0.
A[A>10.] = 10.
</code>```

and to the answer of "Miriam Farber". I found:

The approach with A[A<0.] = 0., by "tobias_k", to be the fasted.

My approach took about twice as much time.

The approach with if-statements and the for loop, by "Miriam Farber", took about 50 times as much time. (This also approximately holds from the min, max construction in an inline for-loop, which is a bit faster: 42 times as much time as the fastest option.)

Title: Recoding floats in a list

Body:
I have a list of floats, which looks like this:

predictions_dec = [13.0, 8.6, 4.9, -1.5, 6.2, 7.7, 2.0, 10.0, 7.7, 12.7,...]

I want to clean this data, by giving number higher than 10.0 a 10.0 and numbers lower than 0.0 (so all negative numbers) a 0.0. I'm doing this with the following if statement:

predictions_clean = []
for pred in predictions_dec:
    if pred >= 10:
        predictions_clean.append(10.0)
    if pred <= 0:
        predictions_clean.append(0.0)
    else:
        predictions_clean.append(pred)

This code seems to work, but the funny thing is that:

len(predictions_dec)
1222
len(predictions_clean)
1816

My understanding of if statements is not that great. Where in the if statement am I doing something wrong?

Body:
If your list is very large (and you thus want to avoid loops and if statements) you could also use NumPy and the mathematical trick to set every negative number to zero by:

A = .5*(A+np.abs(A))

You could do the same to set everything larger that 10 to 10. Here is everything put together:

import numpy as np

A = np.array([13.0, 8.6, 4.9, -1.5, 6.2, 7.7, 2.0, 10.0, 7.7, 12.7])

# set all items <= 0 to 0.0
A = .5*(A+np.abs(A))
print(A)

# set all items >= 10 to 10.0
A = 10.-A
A = .5*(A+np.abs(A))
A = 10.-A
print(A)

Edit

The suggestion by "tobias_k" is of course better then mine. But to put some science into it I considered a random list/array of length 1,000,000. I compared the above implementation to

A[A< 0.] =  0.
A[A>10.] = 10.

and to the answer of "Miriam Farber". I found:

The approach with A[A<0.] = 0., by "tobias_k", to be the fasted.

My approach took about twice as much time.

The approach with if-statements and the for loop, by "Miriam Farber", took about 50 times as much time. (This also approximately holds from the min, max construction in an inline for-loop, which is a bit faster: 42 times as much time as the fastest option.)


来源: stackexchange

问:
Import node module in angularjs
How can I import a module, e.g. pikaday from another one, e.g. handsontable in angularjs from the node_modules?

```<code>import {pikaday} from handsontable
</code>```

doesn't seem to work.

答:
If you using angular1, then you should also add them as dependencies:

angular.module('YourApp', ['ngHandsontable','pikaday']);

If you using angular2, then it should be like:

import { Pikaday } from 'picaday', you can Read more here

ContentLicense: CC BY-SA 3.0

Title: Import node module in angularjs

Body:
How can I import a module, e.g. pikaday from another one, e.g. handsontable in angularjs from the node_modules?

import {pikaday} from handsontable

doesn't seem to work.


问:
Sorting an array with multiple elements
I am making a to-do list in java for a class project. In the jList i display a date and a string that represent a date and what needs to be done on that day. I would also like to be able to sort these events by the dates on them, so the tasks that are due sooner appear first. I know how to sort a list of dates using bubble sort, but I do not know how to apply this to my list because each item contains a date AND a string. This is the code I have so far. Does anyone know how I will be able to sort the dates in order and keep the strings attached to their dates. Thanks. </p>

```<code>public class ToDoListManager {

    final int maxitems = 20;
    int items = 0;
    String[] toDoList = new String[20];
    Date[] Dates = new Date[20];

    String addItem(String toDo, Date date) {
        if (items == maxitems) {
            return ("No more Space");
        } else if (toDo.equalsIgnoreCase("") || (toDo == null) || (date == null)) {
            return ("All fields required");
        } else if (items < maxitems) {
            Dates[items] = date;
            SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
            toDoList[items] = "On " + dt1.format(date) + " " + toDo;
            items = items + 1;
            return (toDo + " Was Added to the List");
        }
        return null;
    }

    void Order(Date[] dates) {
        Date temp;
        boolean fixed = false;
        while (fixed == false) {
            fixed = true;
            for (int i = 0; i < dates.length - 1; i++) {
                if (dates[i].before(dates[i + 1])) {
                    temp = dates[i + 1];
                    dates[i + 1] = dates[i];
                    dates[i] = temp;
                    fixed = false;
                }
            }

        }
        System.out.println(dates);

    }

    String[] getItems() {
        String[] displayList = new String[items];
        for (int i = 0; i < items; i++) {
            displayList[i] = toDoList[i];

        }

        return displayList;

    }
}
</code>```

答:
Another way of doing this, as mentioned by Michael, is to have an object. That would store the variables you want, date and String. If you in the future want to add another variable you can easily just add this to the object, without editing the list you store the objects in. </p>

```<code>public class Todo {

private Date date;
private String info;

public Todo(Date date, String info){
    this.date = date;
    this.info = info;
}

public Date getDate() {
    return date;
}
public void setDate(Date date) {
    this.date = date;
}
public String getInfo() {
    return info;
}
public void setInfo(String info) {
    this.info = info;
}
}
</code>```

Title: Sorting an array with multiple elements

Body:
I am making a to-do list in java for a class project. In the jList i display a date and a string that represent a date and what needs to be done on that day. I would also like to be able to sort these events by the dates on them, so the tasks that are due sooner appear first. I know how to sort a list of dates using bubble sort, but I do not know how to apply this to my list because each item contains a date AND a string. This is the code I have so far. Does anyone know how I will be able to sort the dates in order and keep the strings attached to their dates. Thanks.

public class ToDoListManager {

    final int maxitems = 20;
    int items = 0;
    String[] toDoList = new String[20];
    Date[] Dates = new Date[20];

    String addItem(String toDo, Date date) {
        if (items == maxitems) {
            return ("No more Space");
        } else if (toDo.equalsIgnoreCase("") || (toDo == null) || (date == null)) {
            return ("All fields required");
        } else if (items < maxitems) {
            Dates[items] = date;
            SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
            toDoList[items] = "On " + dt1.format(date) + " " + toDo;
            items = items + 1;
            return (toDo + " Was Added to the List");
        }
        return null;
    }

    void Order(Date[] dates) {
        Date temp;
        boolean fixed = false;
        while (fixed == false) {
            fixed = true;
            for (int i = 0; i < dates.length - 1; i++) {
                if (dates[i].before(dates[i + 1])) {
                    temp = dates[i + 1];
                    dates[i + 1] = dates[i];
                    dates[i] = temp;
                    fixed = false;
                }
            }

        }
        System.out.println(dates);

    }

    String[] getItems() {
        String[] displayList = new String[items];
        for (int i = 0; i < items; i++) {
            displayList[i] = toDoList[i];

        }

        return displayList;

    }
}

Body:
Another way of doing this, as mentioned by Michael, is to have an object. That would store the variables you want, date and String. If you in the future want to add another variable you can easily just add this to the object, without editing the list you store the objects in.

public class Todo {

private Date date;
private String info;

public Todo(Date date, String info){
    this.date = date;
    this.info = info;
}

public Date getDate() {
    return date;
}
public void setDate(Date date) {
    this.date = date;
}
public String getInfo() {
    return info;
}
public void setInfo(String info) {
    this.info = info;
}
}


问:
Why there is no std::free overload for const void*?
I use an extern C function that returns dynamically allocated const char*.

I want to use unique_ptr<const char, decltype(std::free)> to manage it.

But there is no std::free(const void*) overload so I get invalid conversion from 'const void*' to 'void*' and have to use const_cast<char*>().

Is this just a Standard Library imperfection or there is something else behind it?

答:
std::free is inherited from the C standard library. C does not have overloading, so a const overload could not have been inherited.

While the C++ standard library has extended the inherited C library with some useful overloads, a const overload has not been added for free.

Either such an overload has never been considered, or it has not been considered necessary enough to warrant its addition to the standard. I have not come across any openly available proposal for such an addition -- although I haven't read all proposals there have ever been, nor have I attended any committee meetings or workshops, so  I cannot deny the possibility of the existence of such a document.

To work around the lack of such an overload, you can indeed use const_cast. In this context, it is completely safe.


问:
class httpresponse results in 405 - django
I am new to django and I am trying to understand class views.

In urls.py (main) I have:

```<code>from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('webapp.urls')),
]
</code>```

in webapp folder I have:

urls.py (webapp):

```<code>from django.conf.urls import url
from webapp.views import Firstapp

urlpatterns = [
    url(r'^whatever$', Firstapp.as_view()),

]
</code>```

views.py (webapp):

```<code>from django.shortcuts import render
from django.views import View
from django.http import HttpResponse

class Firstapp(View):

    def something(self):
        return HttpResponse('Yes it works!')
</code>```

As I have said, I am trying to use class views and I would appreciate if you could help me understand why class returns 405 error. Thank you. CMD returns 0 problems.

答:
Because you are subclassing View and the only method you define is called something.

View expects you to define a method for each valid http verb. (GET, POST, HEAD etc). Since Firstapp has no such method, View.dispatch will return a response with http status 405 (Method not allowed).

dispatch(request, *args, **kwargs)

The view part of the view – the
  method that accepts a request argument plus arguments, and returns a HTTP response.

The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated to get(), a POST to post(), and so on.

By default, a HEAD request will be delegated to get(). If you need to handle HEAD requests in a different way than GET, you can override the head() method. See Supporting other HTTP methods for an example.

To fix this, change your something method:

```<code>def get(self, request):
    return HttpResponse('Yes it works!')
</code>```

Body:
I am new to django and I am trying to understand class views.

In urls.py (main) I have:

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('webapp.urls')),
]

in webapp folder I have:

urls.py (webapp):

from django.conf.urls import url
from webapp.views import Firstapp

urlpatterns = [
    url(r'^whatever$', Firstapp.as_view()),

]

views.py (webapp):

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse

class Firstapp(View):

    def something(self):
        return HttpResponse('Yes it works!')

As I have said, I am trying to use class views and I would appreciate if you could help me understand why class returns 405 error. Thank you. CMD returns 0 problems.

Body:
Because you are subclassing View and the only method you define is called something.

View expects you to define a method for each valid http verb. (GET, POST, HEAD etc). Since Firstapp has no such method, View.dispatch will return a response with http status 405 (Method not allowed).

dispatch(request, *args, **kwargs)

The view part of the view – the
  method that accepts a request argument plus arguments, and returns a HTTP response.

The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated to get(), a POST to post(), and so on.

By default, a HEAD request will be delegated to get(). If you need to handle HEAD requests in a different way than GET, you can override the head() method. See Supporting other HTTP methods for an example.

To fix this, change your something method:

def get(self, request):
    return HttpResponse('Yes it works!')


问:
Github project pages
I have the below repository;

https://github.com/garfieldmoore/mychesscalculator/settings

I have configured github pages to point to mychessgrade.com

I have configured A records for the below;

@ 192.30.252.154
@ 192.30.252.153

www 192.30.252.154
www 192.30.252.154

However, when I browse to mychessgrade.com the browser reports the below error;

mychessgrade.com redirected you too many times

I've done this for my user pages and it's worked.

What have I done wrong?

答: There wasn't a problem after all - it was my DNS TTL that was confusing me.</p>

Title: Github project pages


问:
How do I create a doPost(e) function in Apps Script project to capture HTTP POST data from web service?
I'm trying to create a script to capture data via HTTP POST from Ejunkie. When someone makes a purchase on ejunkie, they can transmit all the order data via HTTP POST to a common notification url (documentation). I want to capture that data so I can get it into a Google Sheet.

So I've setup a sheet with a doPost(e) function like so:

```<code>// attempt 1
function doPost(e) {
  if(typeof e !== 'undefined')
  Logger.log(e.parameters);
}

// attempt 2
function doPost(e) {
  var data = JSON.stringify(e);
  Logger.log(data);
}
</code>```

which I've published as a Web App with access to anyone, and then entered this script URL as the common notification URL in ejunkie.

I've tried a couple of test transactions, but I'm getting nothing in the Logs.

Any ideas? Thanks in advance for any help.

Here's the ejunkie documentation on this subject.

答:
Instead of using Logger.log() as a way to notify yourself if your calls made it through, try sending an email to yourself instead. This is the snippet:

```<code>function doPost(e) {
  if(typeof e !== 'undefined')

  MailApp.sendEmail({
     to: "youremail@gmail.com",
     subject: "Call Sucessful",
     htmlBody: "I am your <br>" +
               "DATA"
    });
}
</code>```

Just allow the necessary permission if asked. If I'm not mistaken Logger.log is for script editor only and not for your production web apps.

Body:
I'm trying to create a script to capture data via HTTP POST from Ejunkie. When someone makes a purchase on ejunkie, they can transmit all the order data via HTTP POST to a common notification url (documentation). I want to capture that data so I can get it into a Google Sheet.

So I've setup a sheet with a doPost(e) function like so:

// attempt 1
function doPost(e) {
  if(typeof e !== 'undefined')
  Logger.log(e.parameters);
}

// attempt 2
function doPost(e) {
  var data = JSON.stringify(e);
  Logger.log(data);
}

which I've published as a Web App with access to anyone, and then entered this script URL as the common notification URL in ejunkie.

I've tried a couple of test transactions, but I'm getting nothing in the Logs.

Any ideas? Thanks in advance for any help.

Here's the ejunkie documentation on this subject.

Body:
Instead of using Logger.log() as a way to notify yourself if your calls made it through, try sending an email to yourself instead. This is the snippet:

function doPost(e) {
  if(typeof e !== 'undefined')

  MailApp.sendEmail({
     to: "youremail@gmail.com",
     subject: "Call Sucessful",
     htmlBody: "I am your <br>" +
               "DATA"
    });
}

Just allow the necessary permission if asked. If I'm not mistaken Logger.log is for script editor only and not for your production web apps.


问:
Remove all punctuation from string, except if it's between digits
I have a text that contains words and numbers. I'll give a representative example of the text:

```<code>string = "This is a 1example of the text. But, it only is 2.5 percent of all data"
</code>```

I'd like to convert it to something like:

```<code>"This is a  1 example of the text But it only is  2.5  percent of all data"
</code>```

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

```<code>item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item
</code>```

The result is :

```<code> >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"
</code>```

I'm almost there but can't figure out that last peace.

答:
Okay folks, here is an answer (the best ? I don't know but it seems to work) :</p>

```<code>item = "This is a 1example 2Ex of the text.But, it only is 2.5 percent of all data?"
#if there is two strings contatenated with the second starting with capital letter
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
#if a word starts with a digit like "1example"
item = ' '.join(re.split(r'(\d+)([A-Za-z]+)', item) )
#Magical line that removes punctuation apart from floats
item = re.sub('\S+', lambda m: re.match(r'^\W*(.*\w)\W*$', m.group()).group(1), item)
item = item.replace("  "," ")
print item
</code>```

Body:
I have a text that contains words and numbers. I'll give a representative example of the text:

string = "This is a 1example of the text. But, it only is 2.5 percent of all data"

I'd like to convert it to something like:

"This is a  1 example of the text But it only is  2.5  percent of all data"

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item

The result is :

 >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"

I'm almost there but can't figure out that last peace.

Body:
Okay folks, here is an answer (the best ? I don't know but it seems to work) :

item = "This is a 1example 2Ex of the text.But, it only is 2.5 percent of all data?"
#if there is two strings contatenated with the second starting with capital letter
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
#if a word starts with a digit like "1example"
item = ' '.join(re.split(r'(\d+)([A-Za-z]+)', item) )
#Magical line that removes punctuation apart from floats
item = re.sub('\S+', lambda m: re.match(r'^\W*(.*\w)\W*$', m.group()).group(1), item)
item = item.replace("  "," ")
print item


问:
Using T-SQL EXCEPT with DELETE / Optimizing a query
The following code removes records of tasks related to inactive projects from the table.

```<code>delete from [Deliverables] where
[Deliverables].[ProjectID] not in
(
select
[ProjectID] from [ActiveProjects]
)
</code>```

I've read somewhere that using NOT IN with subquery that returns a lot of values is not really the most efficient thing to do and it's better to use EXCEPT clause.

However, when I try to use the following code, I get an error (Incorrect syntax near the keyword 'except'.)

```<code>delete from [Deliverables]
except
select * from [Deliverables], [ActiveProjects]
where [Deliverables].[ProjectID] = [ActiveProjects].[ProjectID]
</code>```

How can I use EXCEPT with DELETE? If I can't, is there any way to optimize my query to execute faster?

答:
You can try as well not exists and script would look like:

```<code>delete from [Deliverables]
where not exists
    (select 1
        from [ActiveProjects]
        where [ActiveProjects].[ProjectID] = [Deliverables].[ProjectID])
</code>```

If there is a lot of data in [ActiveProjects] then it should be better solution, however it is all data dependent so please test efficiency before use.

Body:
The following code removes records of tasks related to inactive projects from the table.

delete from [Deliverables] where
[Deliverables].[ProjectID] not in
(
select
[ProjectID] from [ActiveProjects]
)

I've read somewhere that using NOT IN with subquery that returns a lot of values is not really the most efficient thing to do and it's better to use EXCEPT clause.

However, when I try to use the following code, I get an error (Incorrect syntax near the keyword 'except'.)

delete from [Deliverables]
except
select * from [Deliverables], [ActiveProjects]
where [Deliverables].[ProjectID] = [ActiveProjects].[ProjectID]

How can I use EXCEPT with DELETE? If I can't, is there any way to optimize my query to execute faster?

Body:
You can try as well not exists and script would look like:

delete from [Deliverables]
where not exists
    (select 1
        from [ActiveProjects]
        where [ActiveProjects].[ProjectID] = [Deliverables].[ProjectID])

If there is a lot of data in [ActiveProjects] then it should be better solution, however it is all data dependent so please test efficiency before use.


问:
Get coordinates of a particular section of the image
I want to add a text and link to both the sign boards here in this image (separately for both). I am trying to use the <map> <area> rule and I need to place the coordinates of the two rectangle boxes there so that once a user clicks on that board or text he will be redirected to some another page. Now the problem is that I am not sure from where to find the exact coordinates of the image here and how? If anyone can help then please help.

Here is the code I am using

```<code><img src="image link here" usemap="#mapname">
    <map name="mapname">
      <area shape="rect" coords="" href="http://www.google.com" alt="TEST">
    </map>
</code>```

答:
if you want to add text, then you better use real links and set them on top of your areas wich are quiet good rectangle.

example:

.map {
  position: relative;
}

.map img {
  display: block;
  width: 100%;
}

.map a {
  position: absolute;
  top: 48.6%;
  left: 9.118%;
  width: 19.8%;
  height: 19%;
  transform: rotate(-1.375deg);
  border-radius: 50% 50% 0px 0 / 0.25vw;
  transition: 0.5s;
  color:#3F4754;
  display:flex;
  align-items:center;
  justify-content:center;
  font-size:4vw;
  font-weight:bold;
  font-family:courier;
  font-variant:small-caps;
  text-decoration:none;
  text-shadow:-2px -2px 2px black
}

.map a + a {
  top: 48%;
  left: 70%;
  transform: rotate(3deg);
  transform-origin: bottom right
}

a:hover {
  color: white;
  background:linear-gradient(to bottom left, rgba(0, 0, 0, 0.5), transparent);
  text-shadow:2px 2px 2px black
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="map">
  <img src="https://i.stack.imgur.com/mDEuy.jpg" />
  hover me
  or me
</div></code>```

use your own style and ids or class

Body:
I want to add a text and link to both the sign boards here in this image (separately for both). I am trying to use the <map> <area> rule and I need to place the coordinates of the two rectangle boxes there so that once a user clicks on that board or text he will be redirected to some another page. Now the problem is that I am not sure from where to find the exact coordinates of the image here and how? If anyone can help then please help.

Here is the code I am using

    <map name="mapname">
      <area shape="rect" coords="" href="http://www.google.com" alt="TEST">
    </map>

Body:
if you want to add text, then you better use real links and set them on top of your areas wich are quiet good rectangle.

example:

.map {
  position: relative;
}

.map img {
  display: block;
  width: 100%;
}

.map a {
  position: absolute;
  top: 48.6%;
  left: 9.118%;
  width: 19.8%;
  height: 19%;
  transform: rotate(-1.375deg);
  border-radius: 50% 50% 0px 0 / 0.25vw;
  transition: 0.5s;
  color:#3F4754;
  display:flex;
  align-items:center;
  justify-content:center;
  font-size:4vw;
  font-weight:bold;
  font-family:courier;
  font-variant:small-caps;
  text-decoration:none;
  text-shadow:-2px -2px 2px black
}

.map a + a {
  top: 48%;
  left: 70%;
  transform: rotate(3deg);
  transform-origin: bottom right
}

a:hover {
  color: white;
  background:linear-gradient(to bottom left, rgba(0, 0, 0, 0.5), transparent);
  text-shadow:2px 2px 2px black
}

<div class="map">
  <img src="https://i.stack.imgur.com/mDEuy.jpg" />
  <a href="#1">hover me</a>
  <a href="#2">or me</a>
</div>

use your own style and ids or class


问:
How to retrieve the records based on a condition from a Hbase table?
I have a Hbase table: employeedetails with column families:cols-personaldetails: firstname, lastname, professionaldetails: cols-company, empid
and it has the following data in it.

```<code> 1    column=personaldetails:firstname, timestamp=1490959927100, value=Steven
 1    column=personaldetails:lastname, timestamp=1490959947478, value=Gerrard
 1    column=professionaldetails:company, timestamp=1490959968846, value=ABC
 1    column=professionaldetails:empid, timestamp=1490959978542, value=02429O
 2    column=personaldetails:firstname, timestamp=1490960007427, value=Sidhartha
 2    column=personaldetails:lastname, timestamp=1490960054615, value=Bobby
 2    column=professionaldetails:company, timestamp=1490960074243, value=DEF
 2    column=professionaldetails:empid, timestamp=1490960103882, value=02429N
 3    column=personaldetails:company, timestamp=1490960175772, value=WES
 3    column=personaldetails:empid, timestamp=1490960187863, value=987789
 3    column=personaldetails:firstname, timestamp=1490960128896, value=Sunny
 3    column=personaldetails:lastname, timestamp=1490960142031, value=Smith
</code>```

Is there a way to write a command to retrieve the records whose first name starts with 'S'.

答:
Use SingleColumnValueFilter

This filter takes a column family, a qualifier, a compare operator and a comparator as arguments.

If the specified column is not found, all the columns of that row
  will be emitted.

If the column is found and the comparison with the comparator
  returns true, all the columns of the row will be emitted.

If the column is found and the comparison with the comparator
  returns false, the row will not be emitted.

Syntax:

```<code>SingleColumnValueFilter (‘<family>’, ‘<qualifier>’, <compare operator>, ‘<comparator>’, <filterIfColumnMissing_boolean>, <latest_version_boolean>)
</code>```

Try:

```<code>scan 'employeedetails' ,{ FILTER => "SingleColumnValueFilter('personaldetails','firstname',=, 'binaryprefix:S', true, false)" }
</code>```

If the filterIfColumnMissing flag is set to true, the columns of the row will not be emitted if the specified column to check is not found in the row.

Let me know if this retrieves expected results.

Body:
I have a Hbase table: employeedetails with column families:cols-personaldetails: firstname, lastname, professionaldetails: cols-company, empid
and it has the following data in it.

 1    column=personaldetails:firstname, timestamp=1490959927100, value=Steven
 1    column=personaldetails:lastname, timestamp=1490959947478, value=Gerrard
 1    column=professionaldetails:company, timestamp=1490959968846, value=ABC
 1    column=professionaldetails:empid, timestamp=1490959978542, value=02429O
 2    column=personaldetails:firstname, timestamp=1490960007427, value=Sidhartha
 2    column=personaldetails:lastname, timestamp=1490960054615, value=Bobby
 2    column=professionaldetails:company, timestamp=1490960074243, value=DEF
 2    column=professionaldetails:empid, timestamp=1490960103882, value=02429N
 3    column=personaldetails:company, timestamp=1490960175772, value=WES
 3    column=personaldetails:empid, timestamp=1490960187863, value=987789
 3    column=personaldetails:firstname, timestamp=1490960128896, value=Sunny
 3    column=personaldetails:lastname, timestamp=1490960142031, value=Smith

Is there a way to write a command to retrieve the records whose first name starts with 'S'.

Body:
Use SingleColumnValueFilter

This filter takes a column family, a qualifier, a compare operator and a comparator as arguments.

If the specified column is not found, all the columns of that row
  will be emitted.

If the column is found and the comparison with the comparator
  returns true, all the columns of the row will be emitted.

If the column is found and the comparison with the comparator
  returns false, the row will not be emitted.

Syntax:

SingleColumnValueFilter (‘<family>’, ‘<qualifier>’, <compare operator>, ‘<comparator>’, <filterIfColumnMissing_boolean>, <latest_version_boolean>)

Try:

scan 'employeedetails' ,{ FILTER => "SingleColumnValueFilter('personaldetails','firstname',=, 'binaryprefix:S', true, false)" }

If the filterIfColumnMissing flag is set to true, the columns of the row will not be emitted if the specified column to check is not found in the row.

Let me know if this retrieves expected results.


问:
Angular : When to use "[]" in modules and controllers
I'm starting in Angular and i don't understand when to use or not [] when declaring (if it's called like this) modules and controllers.

So far, i understood that :

angular.module('app.prof', []).config(config); means i declare the module prof

while angular.module('app.prof').config(config); means i call it.

But i always end up having the [] in the controller and not in the module, and when i have two controllers i don't know what to do anymore.

I just want to understand Angular :(

Edit : adding more details

In my Angular project, i use the Fuse theme with a thing called Yeoman (if i understood well) so i never write

答:
In angular the "[]" is meant for injecting the external(angular) dependencies to you module and get access of it. refer the below example

```<code>angular.module('app.proof',['myservice']).controller(function(bootstrap,myservice){
 myservice.callmethod();});
</code>```

Hope This helps!

Body:
In angular the "[]" is meant for injecting the external(angular) dependencies to you module and get access of it. refer the below example

angular.module('app.proof',['myservice']).controller(function(bootstrap,myservice){
 myservice.callmethod();});

Hope This helps!


问:
Bootstrap place all div in single line
I am trying to place userlist in left side and searchbox and button in right side in same line

```<code><div class="row">
  <div class="col-md-4">
    <div class="user-title">User List-5</div>
  </div>
  <div class="col-md-8">
    <div class="input-group user-search-box col-md-6">
      <input type="text" class="form-control" placeholder="Search" aria-describedby="basic-addon2">
      <span class="input-group-addon input-search-custom-adon" ><i class="fa fa-search" aria-hidden="true"></i></span>
    </div>
    <div class="add-new-user col-md-6">
      <a class="btn  add-new-user" href="#" role="button">ADD NEW USER</a>
    </div>
  </div>
</div>
</code>```

i have tried by using float:left then add button will show first instead of search box
can any one help me

答:
Just force the float at left for the user box :

CSS:

.user-search-box{float:left !important}

Fiddle : http://www.bootply.com/9CEJvzG4y6

And :

You forgot to insert a .row after the col-md-8

Title: Bootstrap place all div in single line

Body:
I am trying to place userlist in left side and searchbox and button in right side in same line

User List-5

      <input type="text" class="form-control" placeholder="Search" aria-describedby="basic-addon2">

      ADD NEW USER

i have tried by using float:left then add button will show first instead of search box
can any one help me


问:
Hibernate 3 not auto creating tables
Here is my code:

hiberntae.cfg.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
  </session-factory>
</hibernate-configuration>
</code>```

pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>edu.bc.eagleapps</groupId>
    <artifactId>mavenproject1</artifactId>
    <version>1.2-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>mavenproject1</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <springframework.version>4.0.6.RELEASE</springframework.version>
        <hibernate.version>3.6.9.Final</hibernate.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.18.2-GA</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-base</artifactId>
            <version>2.6.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Model

```<code>package app.model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER_MASTER")
public class UserMaster {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column
private String id;

  @Column(length = 50, nullable = false, unique = true)
private String userid;

  @Column(length = 50, nullable = false, unique = true)
private String password;

public UserMaster() {}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getUserid() {
            return userid;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
</code>```

When I try to save user via controller, I get the following error:

```<code>org.hibernate.exception.SQLGrammarException: could not insert: [app.model.UserMaster]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at coolcook.dao.UserMasterDao.saveUser(UserMasterDao.java:23)
at coolcook.service.UserMasterServiceImpl.saveUser(UserMasterServiceImpl.java:16)
at coolcook.controller.UserController.registerUser(UserController.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
a

t java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'app.USER_MASTER' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
</code>```

the database "app" exists, but whenever I try to save user through controller, it gives me above error.

I search through several answers on SO and other sites but not successful. Any help will be appreciated!

Dao

```<code>   package coolcook.dao;

import coolcook.model.UserMaster;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class UserMasterDao {

    @Autowired
    private SessionFactory sessionFactory;

    public UserMaster saveUser(UserMaster user) {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
            tx = session.beginTransaction();
            session.save(user);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
            }
            return user;
        }

    }
</code>```

springmvc-servlet.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:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
                http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="app" />
    <!--<mvc:resources mapping="/views/**" location="/views/" />-->
    <mvc:default-servlet-handler />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
          p:url="jdbc:mysql://localhost:3306/app" p:username="root"
          p:password="root" />

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <value>app.model</value>
            </list>
        </property>

        <property name="configLocation">
            <value>WEB-INF/hibernate.cfg.xml</value>
        </property>

    </bean>

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:annotation-config />

       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name = "prefix" value = "/WEB-INF/views/" />
        <property name = "suffix" value = ".jsp" />
    </bean>

</beans>
</code>```

答:
dependancies can be a culprit as because of conflict. In my case, exclusion of dom4j solved the issue. Try updating jackson dependency in your pom.xml. It worked for me. </p>

```<code><dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-base</artifactId>
        <version>2.6.3</version>
        <exclusions>
          <exclusion>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
          </exclusion>
        </exclusions>
    </dependency>
</code>```

Title: Hibernate 3 not auto creating tables

Body:
Here is my code:

hiberntae.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
  </session-factory>
</hibernate-configuration>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>edu.bc.eagleapps</groupId>
    <artifactId>mavenproject1</artifactId>
    <version>1.2-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>mavenproject1</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <springframework.version>4.0.6.RELEASE</springframework.version>
        <hibernate.version>3.6.9.Final</hibernate.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.18.2-GA</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-base</artifactId>
            <version>2.6.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Model

package app.model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER_MASTER")
public class UserMaster {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column
private String id;

  @Column(length = 50, nullable = false, unique = true)
private String userid;

  @Column(length = 50, nullable = false, unique = true)
private String password;

public UserMaster() {}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getUserid() {
            return userid;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }

When I try to save user via controller, I get the following error:

org.hibernate.exception.SQLGrammarException: could not insert: [app.model.UserMaster]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at coolcook.dao.UserMasterDao.saveUser(UserMasterDao.java:23)
at coolcook.service.UserMasterServiceImpl.saveUser(UserMasterServiceImpl.java:16)
at coolcook.controller.UserController.registerUser(UserController.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
a

t java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'app.USER_MASTER' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)

the database "app" exists, but whenever I try to save user through controller, it gives me above error.

I search through several answers on SO and other sites but not successful. Any help will be appreciated!

Dao

   package coolcook.dao;

import coolcook.model.UserMaster;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class UserMasterDao {

    @Autowired
    private SessionFactory sessionFactory;

    public UserMaster saveUser(UserMaster user) {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
            tx = session.beginTransaction();
            session.save(user);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
            }
            return user;
        }

    }

springmvc-servlet.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:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
                http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="app" />

    <mvc:default-servlet-handler />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
          p:url="jdbc:mysql://localhost:3306/app" p:username="root"
          p:password="root" />

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <value>app.model</value>
            </list>
        </property>

        <property name="configLocation">
            <value>WEB-INF/hibernate.cfg.xml</value>
        </property>

    </bean>

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:annotation-config />

       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name = "prefix" value = "/WEB-INF/views/" />
        <property name = "suffix" value = ".jsp" />
    </bean>

</beans>

Body:
dependancies can be a culprit as because of conflict. In my case, exclusion of dom4j solved the issue. Try updating jackson dependency in your pom.xml. It worked for me.

<dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-base</artifactId>
        <version>2.6.3</version>
        <exclusions>
          <exclusion>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
          </exclusion>
        </exclusions>
    </dependency>


问:
Reading into hashmap in c++
I'm working on a markov chain and have created a 2d hashmap that calculates the weighted probabilities.  The output of this works fine.

I'm looking to find the best way to output the next value.  The way I have it at the moment isn't working properly.  Ent1.first is the incoming midiNote.  Ent2.first is the potential outgoing value and Ent2.second is the weighted probability.

When midiNotecomes in, I need to look into the table and find the weighted probabilities and using rand() pick the next value.  One problem is that I only need this to happen once, not for every time in the for loop.  Here is a snippet of my table calculation for simplicity's sake, but if you'd like me to post the entire code let me know.

```<code>void getCountTable(int midiNote) {
    for(auto const &ent1: cdf) {
        midiNote = ent1.first;
        for (auto const &ent2: ent1.second) {
            //console out all resulting note transition weights
            //std::cout << "Note: " << ent1.first << std::endl <<"Next note: " << ent2.first <<std::endl << "Weight: " << ent2.second << std::endl << std::endl;

            //TRYING TO FIGURE HOW TO HANDLE THIS.  JUST WANT TO HAPPEN ONCE FOR EACH INCOMING VALUE

            //psuedo-random values between 0-1
            float r = static_cast <float> (rand()) / static_cast<float> (RAND_MAX);

            //calculate next value
            if (r < ent2.second) {
                int output = ent2.first;
                std::cout << ent1.first << " " << output << std::endl;
            }
        }
    }
}
</code>```

答:
I've found there needs to be a comparison between the map and the incoming midi value.  Also changed the probabilities to the first entry in the second map and the resulting output as the second entry.  Modified some and provided all below.</p>

```<code>void nextNote(int midiNote){
float r = static_cast <float> (rand()) / static_cast<float> (RAND_MAX);
int output = 0;
float sum = 0;
for (auto const & ent1: cdf){
    if(ent1.first == midiNote){
        for (auto const & ent2: ent1.second){
            sum+= ent2.first;
            std::cout <<sum << std::endl;
            if(sum >= r){
                output = ent2.second;
                std::cout << output <<std::endl;
                break;
            }
        }
    }

}

}
</code>```

Title: Reading into hashmap in c++

Body:
I'm working on a markov chain and have created a 2d hashmap that calculates the weighted probabilities.  The output of this works fine.

I'm looking to find the best way to output the next value.  The way I have it at the moment isn't working properly.  Ent1.first is the incoming midiNote.  Ent2.first is the potential outgoing value and Ent2.second is the weighted probability.

When midiNotecomes in, I need to look into the table and find the weighted probabilities and using rand() pick the next value.  One problem is that I only need this to happen once, not for every time in the for loop.  Here is a snippet of my table calculation for simplicity's sake, but if you'd like me to post the entire code let me know.

void getCountTable(int midiNote) {
    for(auto const &ent1: cdf) {
        midiNote = ent1.first;
        for (auto const &ent2: ent1.second) {
            //console out all resulting note transition weights
            //std::cout << "Note: " << ent1.first << std::endl <<"Next note: " << ent2.first <<std::endl << "Weight: " << ent2.second << std::endl << std::endl;

            //TRYING TO FIGURE HOW TO HANDLE THIS.  JUST WANT TO HAPPEN ONCE FOR EACH INCOMING VALUE

            //psuedo-random values between 0-1
            float r = static_cast <float> (rand()) / static_cast<float> (RAND_MAX);

            //calculate next value
            if (r < ent2.second) {
                int output = ent2.first;
                std::cout << ent1.first << " " << output << std::endl;
            }
        }
    }
}

Body:
I've found there needs to be a comparison between the map and the incoming midi value.  Also changed the probabilities to the first entry in the second map and the resulting output as the second entry.  Modified some and provided all below.

void nextNote(int midiNote){
float r = static_cast <float> (rand()) / static_cast<float> (RAND_MAX);
int output = 0;
float sum = 0;
for (auto const & ent1: cdf){
    if(ent1.first == midiNote){
        for (auto const & ent2: ent1.second){
            sum+= ent2.first;
            std::cout <<sum << std::endl;
            if(sum >= r){
                output = ent2.second;
                std::cout << output <<std::endl;
                break;
            }
        }
    }

}

}


问:
How to invoke pandas str.split() and not python's built in str.split()
I am trying to locate all the rows of a dataframe whose one attribute (say id_proof) value matches to the second part of another column (say adr_proof) that starts with a fixed word (say PARENT) and also the corresponding values should match which are part of the same dataframe.

For example, in the dataframe :

```<code>import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT   B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)
</code>```

I am trying to achieve :

```<code>node1    node2    relation
  1        7      parent-child
  2        8      parent-child
  3        9      parent-child
  4       12      parent-child
  5       10      parent-child
  6       11      parent-child
</code>```

Below is my code. I am aware that my code is incomplete. I am stuck with the split() function. I am new to python and pandas and am not sure how to invoke pandas' split() function rather than python's built-in str.split() function. I have gone through this question

```<code>import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)

df_group_count = pd.DataFrame({'count' : main.groupby(['adr_proof']).size()}).reset_index()
adr_type = df_group_count['adr_proof']
adr_type_parent = adr_type.loc[adr_type.str.startswith('PARENT',na=False)]

df_j_ = pd.DataFrame()
for j in adr_type_parent:
    dfn_j = main.loc[(main['adr_proof'] == j)]
    adr_type_parent_type = j.split(' ',expand=True,n=1)
    res = main.loc[(main['id_proof'] == adr_type_parent_type[1]) & (main['id_value'] == dfn_j['adr_value'])]

res
</code>```

Please provide a way to achieve my goal. The output is another dataframe. Please excuse for bad code or any violations. A completely different approach is also appreciated. Thank You.

答:
After investigating this and also discussing about this in the #python channel on IRC network freenode.net, I have an answer for you. You can't overshadow str.split() of Python with the str.split() of the pandas library.

Also, the DataFrame object has no str.split(). I have read the whole API and also played with from ... import ... to somehow import str.split() from pandas and overshadow the str.split() of Python.

The DataFrame object you are using in your code has no str.split(). The only reason str.split() in your code doesn't throw an error is because it just so happens Python has str.split() built in and uses that.

The only pandas object I could find that has str.split() is the Series object, pandas.Series.str.split(). But you're not using the Series object, you are using the DataFrame object. I'm sorry, there's nothing to be done.

If you ask me, the structure of pandas is broken. You can't just import str.split(), because str is basically a StringMethods object and this object lives under the strings package, which lives in the core package, which lives in the pandas top-level package. It's a mess! I wasted 2 hours of my life to understand its package/module/object structure.

Also, pandas.Series.str.split() is basically pandas.core.series.Series.str.split(). I just gave up!

Try to import str.split() from pandas and you'll get a Nobel prize!

Body:
I am trying to locate all the rows of a dataframe whose one attribute (say id_proof) value matches to the second part of another column (say adr_proof) that starts with a fixed word (say PARENT) and also the corresponding values should match which are part of the same dataframe.

For example, in the dataframe :

import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT   B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)

I am trying to achieve :

node1    node2    relation
  1        7      parent-child
  2        8      parent-child
  3        9      parent-child
  4       12      parent-child
  5       10      parent-child
  6       11      parent-child

Below is my code. I am aware that my code is incomplete. I am stuck with the split() function. I am new to python and pandas and am not sure how to invoke pandas' split() function rather than python's built-in str.split() function. I have gone through this question

import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)

df_group_count = pd.DataFrame({'count' : main.groupby(['adr_proof']).size()}).reset_index()
adr_type = df_group_count['adr_proof']
adr_type_parent = adr_type.loc[adr_type.str.startswith('PARENT',na=False)]

df_j_ = pd.DataFrame()
for j in adr_type_parent:
    dfn_j = main.loc[(main['adr_proof'] == j)]
    adr_type_parent_type = j.split(' ',expand=True,n=1)
    res = main.loc[(main['id_proof'] == adr_type_parent_type[1]) & (main['id_value'] == dfn_j['adr_value'])]

res

Please provide a way to achieve my goal. The output is another dataframe. Please excuse for bad code or any violations. A completely different approach is also appreciated. Thank You.


问:
What automation approach is should I use to create and maintain many similar POCOs and DTOs?
I need to maintain several similar files, with similar contents, but with slight differences for each purpose, such as the

View (ASP.net, Xamarin.Forms, etc)

ViewModel (Per field validation)

Entity Framework Code first classes

NoSQL classes iOS CloudKit, Azure table

Some of those require special implementations (INotifyPropertyChanged, Rx), or others require to be inherited from an abstract class.

Question

Does any DTO automation (or schema description language) exist that allows for centralized management / property propagation of several similar files?

Perhaps I can extend visual studio to run a script in the background that will maintain the files, and alert me to any inconsistencies

答: Entity Framework already uses T4 templating for this purpose, and there's nothing preventing you from extending that mechanism to generate multiple copies of each class, each tailored to a specific purpose. You'd probably want to configure some rules and overrides for each type of code generation and perhaps for each entity type, but since it's just code you can basically do anything you want. </p>


问:
How to verify a text is present on a webpage for 'n' times
I wanted to verify a text in a webpage exist for  2 times or ‘n’ times. I have used “Page Should Contain” keyword but it says “Pass” when it identifies single occurrence. I don’t want to verify using locator.

Ex: I want to verify the text "Success" is available in a current webpage for 3 times using robot framework

Any inputs/suggesstions would be helpful.

答:
I thought the problem of not using locator sounds fun (the rationale behind the requirement still unclear, yet), so another solution - look in the source yourself:

```<code>${source}=    Page Source     # you have the whole html of the page here
${matches}=   Get Regexp Matches    ${source}   >.*\b(Success)\b.*<
${count}=     Get Length    ${matches}
</code>```

The first one gets the source, the second gets all non-overlapping (separate) occurrences of the target string, when it is (hopefully) inside a tag. The third line returns the count.

Disclaimer - please don't actually do that, unless you're 100% sure of the source and the structure. Use a locator.

Body:
I thought the problem of not using locator sounds fun (the rationale behind the requirement still unclear, yet), so another solution - look in the source yourself:

${source}=    Page Source     # you have the whole html of the page here
${matches}=   Get Regexp Matches    ${source}   >.*\b(Success)\b.*<
${count}=     Get Length    ${matches}

The first one gets the source, the second gets all non-overlapping (separate) occurrences of the target string, when it is (hopefully) inside a tag. The third line returns the count.

Disclaimer - please don't actually do that, unless you're 100% sure of the source and the structure. Use a locator.


答:
So when you create a module, you can add other modules as dependencies to it that you're planning to use:

```<code>var app = angular.module('myModule', ['Restangular', 'UserService', 'otherModule']);
</code>```

Then, when you create a controller, you can make services, factories, etc. available to the controller.

```<code>app.controller('MyNewController', ['$scope', '$http', 'restangular', function($scope, $http, restangular) {
    // Your code here
    $scope.name = "Daniel";
});
</code>```

Title: Angular : When to use "[]" in modules and controllers

Body:
I'm starting in Angular and i don't understand when to use or not [] when declaring (if it's called like this) modules and controllers.

So far, i understood that :

angular.module('app.prof', []).config(config); means i declare the module prof

while angular.module('app.prof').config(config); means i call it.

But i always end up having the [] in the controller and not in the module, and when i have two controllers i don't know what to do anymore.

I just want to understand Angular :(

Edit : adding more details

In my Angular project, i use the Fuse theme with a thing called Yeoman (if i understood well) so i never write

Body:
So when you create a module, you can add other modules as dependencies to it that you're planning to use:

var app = angular.module('myModule', ['Restangular', 'UserService', 'otherModule']);

Then, when you create a controller, you can make services, factories, etc. available to the controller.

app.controller('MyNewController', ['$scope', '$http', 'restangular', function($scope, $http, restangular) {
    // Your code here
    $scope.name = "Daniel";
});


问:
Symfony DomCrawler link contains searched HTML
This is a project that I do in my free time to help reduce my time spent doing repetitive clicking in my company, so I hope it is not offending or prohibited.

Page to be scraped

I only want the URI of the second link, because it is the exact search match. The first one contains also the -V1331 suffix.

Wrong:

```<code><a href="http://pdb2.turck.de/en/DE/products/0000000000011ba40002003a">
    <strong> Product BI1-EH04-AP6X-V1331</strong> (HTML, 48.7K)<br>
    Product <strong>BI1-EH04-AP6X-V1331</strong>
    Click to enlarge Inductive sensor Order number:  4608440 Smooth barrel, Ø 4 mm Stainless steel, 1.4427 SO DC 3-wire, 10…30 VDC NO contact, PNP
</a>
</code>```

Right:

```<code><a href="http://pdb2.turck.de/en/DE/products/000000000001ecee0003003a">
    <strong> Product BI1-EH04-AP6X</strong> (HTML, 48.6K)<br>
    Product <strong>BI1-EH04-AP6X</strong>
    Click to enlarge Inductive sensor Order number:  4609540 Smooth barrel, Ø 4 mm Stainless steel, 1.4427 SO DC 3-wire, 10…30 VDC NO contact, PNP output
</a>
</code>```

I have tried this:

```<code>$search = 'BI1-EH04-AP6X';
$crawler = Goutte::request('GET', 'http://www.turck.de/en/search.php?q_simple=' . $search);
return $crawler->selectLink(' Product ' . $search)->link()->getUri();
</code>```

However, this obviously fails because there is a lot of HTML inside the  element, thus no link is matched.

Please do not be confused with Laravel's Goutte facade, it is the Symfony Dom Crawler method.

How to obtain the URI of the second link? Is there a method that matches a link, if it contains search HTML snippet (in our case > Product BI1-EH04-AP6X<) ?

答:
I have found the answer by experimenting with the XPath helper extension and information from SO page mentioned below.

Locating the node by value containing whitespaces using XPath

```<code>$search = 'BI1-EH04-AP6X';
$crawler = Goutte::request('GET', 'http://www.turck.de/en/search.php?q_simple=' . $search);
$crawler->filterXPath('//strong[normalize-space(text())="' . $search . '"]')->each(function ($node) {
print $node->parents()->link()->getUri()."\n";
});
</code>```

It does need some more optimization, but for now it is allright.

Body:
This is a project that I do in my free time to help reduce my time spent doing repetitive clicking in my company, so I hope it is not offending or prohibited.

Page to be scraped

I only want the URI of the second link, because it is the exact search match. The first one contains also the -V1331 suffix.

Wrong:

     Product BI1-EH04-AP6X-V1331 (HTML, 48.7K)

    Product BI1-EH04-AP6X-V1331
    Click to enlarge Inductive sensor Order number:  4608440 Smooth barrel, Ø 4 mm Stainless steel, 1.4427 SO DC 3-wire, 10…30 VDC NO contact, PNP

Right:

     Product BI1-EH04-AP6X (HTML, 48.6K)

    Product BI1-EH04-AP6X
    Click to enlarge Inductive sensor Order number:  4609540 Smooth barrel, Ø 4 mm Stainless steel, 1.4427 SO DC 3-wire, 10…30 VDC NO contact, PNP output

I have tried this:

$search = 'BI1-EH04-AP6X';
$crawler = Goutte::request('GET', 'http://www.turck.de/en/search.php?q_simple=' . $search);
return $crawler->selectLink(' Product ' . $search)->link()->getUri();

However, this obviously fails because there is a lot of HTML inside the  element, thus no link is matched.

Please do not be confused with Laravel's Goutte facade, it is the Symfony Dom Crawler method.

How to obtain the URI of the second link? Is there a method that matches a link, if it contains search HTML snippet (in our case > Product BI1-EH04-AP6X<) ?

Body:
I have found the answer by experimenting with the XPath helper extension and information from SO page mentioned below.

Locating the node by value containing whitespaces using XPath

$search = 'BI1-EH04-AP6X';
$crawler = Goutte::request('GET', 'http://www.turck.de/en/search.php?q_simple=' . $search);
$crawler->filterXPath('//strong[normalize-space(text())="' . $search . '"]')->each(function ($node) {
print $node->parents()->link()->getUri()."\n";
});

It does need some more optimization, but for now it is allright.


答:
You can define your "groups" of classes configuration using JSON, XML or anything else.
Then you can use T4 templates to read this configuration and produce several similar classes for each group.

This will occur at save and\or build.

Title: What automation approach is should I use to create and maintain many similar POCOs and DTOs?

Body:
I need to maintain several similar files, with similar contents, but with slight differences for each purpose, such as the

View (ASP.net, Xamarin.Forms, etc)

ViewModel (Per field validation)

Entity Framework Code first classes

NoSQL classes iOS CloudKit, Azure table

Some of those require special implementations (INotifyPropertyChanged, Rx), or others require to be inherited from an abstract class.

Question

Does any DTO automation (or schema description language) exist that allows for centralized management / property propagation of several similar files?

Perhaps I can extend visual studio to run a script in the background that will maintain the files, and alert me to any inconsistencies


问:
sql normalisation
I have 4 tables, courts, divisions, addresses and telephone_numbers.

Each court may have one or more divisions, civil, criminal, family etc. Each of these combination's may have one or more addresses i.e. the civil division for a particular court may or may not be at a different physical address to the criminal court. The same applies to the telephone numbers, they may be the same for each division or address, or they may be different.

I have considered several approaches to this, but do not know the best to use?

a) I could have one big table, which would replicate much of the data many times.

b) I have considered holding the FK of the court in the division table, and the FK of the division in the address table. This means duplicating division values for each court in the division table. I'm then not sure what to do with the telephone table.

c) My final though was to have a single link table holding the FK's all all 4 other tables. This would mean no replication of data, but would mean a lot of joins to get anything meaningful out, and would probably be unwieldy to use.

I'm sure I'm overlooking the obvious here, but what is the best way to model these tables?

The tables will be accessed through CakePHP, but perhaps we'll leave that to one side for the moment.

答:
what you describe is a star schema and is the advised way to do it

```<code>court 1:m divisions
divisions 1:m addresses
address 1:m  telephone
</code>```

i think you should look at what queries you need to do to get the data out as you need it although just a description not sql would be the first step

ContentLicense: CC BY-SA 2.5

Title: sql normalisation

Body:
what you describe is a star schema and is the advised way to do it

court 1:m divisions
divisions 1:m addresses
address 1:m  telephone

i think you should look at what queries you need to do to get the data out as you need it although just a description not sql would be the first step


问:
Can anyone explain how you subtract and add in signed magnitude binary numbers, and not 2s complement?
I had a question on an exam that is the following:

Compute the following value for the 4-bit signed magnitude number below using binary subtraction or addition. Include the decimal answer.

a) 0011 – 1011

First off, how do I interpret these binary numbers? With or without twos complement? If I interpret it with twos complement, I see the decimal calculation

```<code>3 - (-5) = 8
</code>```

But this is wrong.

Apparently the correct answer is

```<code>3 - (-3) = 6
</code>```

So then I should interpret the second number as -3 and not -5? Is this what "signed magnitude number" means? I thought both -3 and -5 depending on interpretation were called signed.

So how do I know if I should interpret the second number as -3 or -5?

And, how do I do the operation? With or without the help of twos complement? Going with that the second number is indeed -3 and not -5, I have:

```<code>0011 = 3
1011 = -3

0011-1011
</code>```

How to do this? I learned in twos complement you should just invert the number and add one but if I do this to the second number and add them together I get:

0011
+ 0101
  = 1000

So 8 again and its wrong. The answer is 6.

I am extremely confused, I have no idea when to use twos complement, what "signed magnitude number" means and how to do this calculation.

Can anyone help?

答:
In signed Number, the first bit is the sign bit. 1 for negative and 0 for positive. (-43) encoded in an eight-bit byte is 10101011 while 43 is 00101011

So in your case 1011 is the negative of 0011 which is -3

0011 + 0011 = 6

Body:
I had a question on an exam that is the following:

Compute the following value for the 4-bit signed magnitude number below using binary subtraction or addition. Include the decimal answer.

a) 0011 – 1011

First off, how do I interpret these binary numbers? With or without twos complement? If I interpret it with twos complement, I see the decimal calculation

3 - (-5) = 8

But this is wrong.

Apparently the correct answer is

3 - (-3) = 6

So then I should interpret the second number as -3 and not -5? Is this what "signed magnitude number" means? I thought both -3 and -5 depending on interpretation were called signed.

So how do I know if I should interpret the second number as -3 or -5?

And, how do I do the operation? With or without the help of twos complement? Going with that the second number is indeed -3 and not -5, I have:

0011 = 3
1011 = -3

0011-1011

How to do this? I learned in twos complement you should just invert the number and add one but if I do this to the second number and add them together I get:

0011
+ 0101
  = 1000

So 8 again and its wrong. The answer is 6.

I am extremely confused, I have no idea when to use twos complement, what "signed magnitude number" means and how to do this calculation.

Can anyone help?

ContentLicense: CC BY-SA 4.0


问:
CSS: background-image rotate without transform: rotate()
I rotated the block that is given a background-image, I need the image not to be rotated but the block that is given the image to be rotated.

page link
What must I do?

Thank you.

CSS:

```<code>   .bg {
        background-image: url("http://bagrattam.com/sss/website/images/other/paint.png");
        background-repeat: no-repeat;
        background-size: cover;
        position: absolute;
        top: -50%;
        left: -10%;
        right: -10%;
        height: 170%;
        z-index: -1;
        transform: rotate(-10deg);
    }
</code>```

答:
Use a psuedo element, put the image in that and rotate it the other way

```<code>.bg:before {
  content: "";
  position: absolute;
  top: -50%;
  left: -10%;
  right: -10%;
  height: 170%;
  z-index: -1;
  background: url(http://bagrattam.com/website/images/other/paint.png') 0 0 repeat;
  -webkit-transform: rotate(-10deg);
  -moz-transform: rotate(-10deg);
  -ms-transform: rotate(-10deg);
  -o-transform: rotate(-10deg);
  transform: rotate(-10deg);
}
</code>```

Don't forget to set the main elements 'overflow:hidden' so it doesn't flow outside.

Body:
I rotated the block that is given a background-image, I need the image not to be rotated but the block that is given the image to be rotated.

page link
What must I do?

Thank you.

CSS:

   .bg {
        background-image: url("http://bagrattam.com/sss/website/images/other/paint.png");
        background-repeat: no-repeat;
        background-size: cover;
        position: absolute;
        top: -50%;
        left: -10%;
        right: -10%;
        height: 170%;
        z-index: -1;
        transform: rotate(-10deg);
    }

Body:
Use a psuedo element, put the image in that and rotate it the other way

.bg:before {
  content: "";
  position: absolute;
  top: -50%;
  left: -10%;
  right: -10%;
  height: 170%;
  z-index: -1;
  background: url(http://bagrattam.com/website/images/other/paint.png') 0 0 repeat;
  -webkit-transform: rotate(-10deg);
  -moz-transform: rotate(-10deg);
  -ms-transform: rotate(-10deg);
  -o-transform: rotate(-10deg);
  transform: rotate(-10deg);
}

Don't forget to set the main elements 'overflow:hidden' so it doesn't flow outside.


问:
How to get the valid part of a regex match
I want to test if a user string is "ok so far", in that it might not be valid as a whole but it is a subset of a valid one.

I have a regex say ^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]$
such that "1234-1234-5678-5678" is valid

"1234-12" or even "1"  does not match pattern but its a valid subset of a valid format, in other words the input is ok so far.

is there a neat way of doing this without making many many regexes,    its friday.

Body:
This regex will match key for key as you type, although it is a little cumbersome.

^([0-9]{1,4}|[0-9]{4}-[0-9]{0,4}|[0-9]{4}-[0-9]{4}-[0-9]{0,4}|[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{0,4})$

Here is a live example


问:
Why do I get a 403 Unauthorized when I try to create a topic on IBM Message Hub
I created a new instance of IBM Message Hub on Bluemix and can use the Kafka Java client to connect to it (from my laptop) and list topics.  What I cannot do is create a topic via the administrative REST APIs (linebreaks added for clarity):

```<code>curl -H "Content-Type: application/json"
    -H "X-Auth-Token: [value from 'password' field of credentials shown on Bluemix Service credentials]"
    -d "{ \"name\": \"topic1\" }"
    https://kafka-admin-prod01.messagehub.services.us-south.bluemix.net:443/admin/topics
</code>```

...which results in this:

```<code>{
    "error_code":403,
    "message":"Unauthorized"
}
</code>```

答: Well I'm an idiot.  The api_key from the Bluemix Service credentials was staring me in the face the whole time I was trying to use password.  Problem solved.

Body:
I created a new instance of IBM Message Hub on Bluemix and can use the Kafka Java client to connect to it (from my laptop) and list topics.  What I cannot do is create a topic via the administrative REST APIs (linebreaks added for clarity):

curl -H "Content-Type: application/json"
    -H "X-Auth-Token: [value from 'password' field of credentials shown on Bluemix Service credentials]"
    -d "{ \"name\": \"topic1\" }"
    https://kafka-admin-prod01.messagehub.services.us-south.bluemix.net:443/admin/topics

...which results in this:

{
    "error_code":403,
    "message":"Unauthorized"
}