问:
Rest Webservice Basic Authorization
I am trying add basic authorization for my Rest webservice.    on weblogic i have created the same user under default security realm . when i executing my rest client without passing authorization it is returning HTTP 200 means application is consuming the request. however in case i pass authorization then it validates the username password. i want my service to work with authorization only. Can someone please let me know what i am missing or if i am doing anything wrong?
 in web.xml i have below:</p>

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
        <display-name>PP</display-name>
        <servlet>
            <servlet-name>jersey-servlet</servlet-name>
            <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
            <init-param>
                <param-name>com.sun.jersey.config.property.packages</param-name>
                <param-value>com.att.eddpp.preprocessing</param-value>
            </init-param>
            <init-param>
                <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
                <param-value>true</param-value>
            </init-param>
            <init-param>
            <param-name>wl-dispatch-policy</param-name>
            <param-value>PP-work-manager</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>jersey-servlet</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
        <security-constraint>
            <web-resource-collection>
                <web-resource-name>PP</web-resource-name>
                <url-pattern>/PP/*</url-pattern>
                <http-method>POST</http-method>

            </web-resource-collection>
        <auth-constraint>
        <role-name>PPRST</role-name>

        </auth-constraint>
        </security-constraint>
        <login-config>
                  <auth-method>BASIC</auth-method>
                  <realm-name>default</realm-name>
              </login-config>
               <security-role>
                   <role-name>PPRST</role-name>
               </security-role>

    </web-app>

    in weblogic.xml i have added

    <?xml version="1.0" encoding="UTF-8"?>
    <wls:weblogic-web-app
        xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.7/weblogic-web-app.xsd">
        <wls:weblogic-version>12.1.3</wls:weblogic-version>
        <wls:context-root>PP</wls:context-root>

        <wls:security-role-assignment>
             <wls:role-name>PPRST</wls:role-name>
             <wls:principal-name>PPRST</wls:principal-name>
         </wls:security-role-assignment>
    </wls:weblogic-web-app>
</code>```

答: Your constraint is for /PP/* but you jersey resource is under /* . I think that's the problem. </p>

Title: Rest Webservice Basic Authorization

Body:
I am trying add basic authorization for my Rest webservice.    on weblogic i have created the same user under default security realm . when i executing my rest client without passing authorization it is returning HTTP 200 means application is consuming the request. however in case i pass authorization then it validates the username password. i want my service to work with authorization only. Can someone please let me know what i am missing or if i am doing anything wrong?
 in web.xml i have below:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
        <display-name>PP</display-name>
        <servlet>
            <servlet-name>jersey-servlet</servlet-name>
            <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
            <init-param>
                <param-name>com.sun.jersey.config.property.packages</param-name>
                <param-value>com.att.eddpp.preprocessing</param-value>
            </init-param>
            <init-param>
                <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
                <param-value>true</param-value>
            </init-param>
            <init-param>
            <param-name>wl-dispatch-policy</param-name>
            <param-value>PP-work-manager</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>jersey-servlet</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
        <security-constraint>
            <web-resource-collection>
                <web-resource-name>PP</web-resource-name>
                <url-pattern>/PP/*</url-pattern>
                <http-method>POST</http-method>

            </web-resource-collection>
        <auth-constraint>
        <role-name>PPRST</role-name>

        </auth-constraint>
        </security-constraint>
        <login-config>
                  <auth-method>BASIC</auth-method>
                  <realm-name>default</realm-name>
              </login-config>
               <security-role>
                   <role-name>PPRST</role-name>
               </security-role>

    </web-app>

    in weblogic.xml i have added

    <?xml version="1.0" encoding="UTF-8"?>
    <wls:weblogic-web-app
        xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.7/weblogic-web-app.xsd">
        <wls:weblogic-version>12.1.3</wls:weblogic-version>
        <wls:context-root>PP</wls:context-root>

        <wls:security-role-assignment>
             <wls:role-name>PPRST</wls:role-name>
             <wls:principal-name>PPRST</wls:principal-name>
         </wls:security-role-assignment>
    </wls:weblogic-web-app>


来源: stackexchange

问:
select a button using selenium
how to select login button using selenium web driver

```<code><li id="buttons" class="greetings_fmt">
    <a href="#">
       <div class="user_btn log_in_icon">LOG IN</div>
    </a>
    <a href="#">
       <div class="user_btn sign_up_icon">SIGN UP</div>
    </a>
</li>
</code>```

tried with this code but not working

```<code>WebElement ele = driver.findElement(By.id("buttons"));
      List<WebElement> ele1 = ele.findElements(By.tagName("a"));
      for(WebElement e : ele1){
         e.click()

      }
</code>```

答:
You can use following xpath for user case:

Xpath=//*[contains(text(),'LOG IN')]

Hope it will work for you.

ContentLicense: CC BY-SA 3.0

Title: select a button using selenium

Body:
how to select login button using selenium web driver

LOG IN

SIGN UP

tried with this code but not working

WebElement ele = driver.findElement(By.id("buttons"));
      List<WebElement> ele1 = ele.findElements(By.tagName("a"));
      for(WebElement e : ele1){
         e.click()

      }


问:
Run script directly in 2 various browsers
I have created Ruby test script that use Selenium RC to test my web app directly in 2 browsers(IE, Firefox). My script runs - first on IE  then continue on Firefox and then should be continued and finished in already opened IE browser. My problem is: I can't continue(reconnect) to run my script in already opened IE browser. I use:

```<code>@browser = RSpecSeleniumHelper.connect_browser("URL")
</code>```

but it opens with new session (it needs to keep previous session).

答:
I'm also unsure why you need to switch back and forth in your browsers.

Regardless, I'm doing something similar, but instead I use a different library. I'm using the "Selenium" gem. (gem install selenium) and here's what I would do in your situation.

```<code>@ie_driver = Selenium::SeleniumDriver.new(rc_host, port, "*iexplore", url, 1000)
@ie_driver.start
@ie_driver.whatever //Test code
@ff_driver = Selenium::SeleniumDriver.new(rc_host, port, "*firefox", url, 1000)
@ff_driver.start
@ff_driver.whatever //Test code
@ff_driver.stop
@ie_driver.whatever //Continue test code with IE
@ie_driver.stop
</code>```

In summary, while I'm not really familiar with your selenium library, typically I would create 2 instances of the R/C driver, that way I won't have to interrupt the session.

OwnerDisplayName: NEO

Body:
I have created Ruby test script that use Selenium RC to test my web app directly in 2 browsers(IE, Firefox). My script runs - first on IE  then continue on Firefox and then should be continued and finished in already opened IE browser. My problem is: I can't continue(reconnect) to run my script in already opened IE browser. I use:

@browser = RSpecSeleniumHelper.connect_browser("URL")

but it opens with new session (it needs to keep previous session).

Body:
I'm also unsure why you need to switch back and forth in your browsers.

Regardless, I'm doing something similar, but instead I use a different library. I'm using the "Selenium" gem. (gem install selenium) and here's what I would do in your situation.

@ie_driver = Selenium::SeleniumDriver.new(rc_host, port, "*iexplore", url, 1000)
@ie_driver.start
@ie_driver.whatever //Test code
@ff_driver = Selenium::SeleniumDriver.new(rc_host, port, "*firefox", url, 1000)
@ff_driver.start
@ff_driver.whatever //Test code
@ff_driver.stop
@ie_driver.whatever //Continue test code with IE
@ie_driver.stop

In summary, while I'm not really familiar with your selenium library, typically I would create 2 instances of the R/C driver, that way I won't have to interrupt the session.

ContentLicense: CC BY-SA 2.5


问:
CSS placing an absolute div beside another div (pure CSS popover)
I have a sidebar with a user profile picture (pink color). When the viewer hover on the image, a div (blue color) appears and it contains user details. Basically, I want an absolute positioned div appear next to its sibling.

It is functionally a popover, but I want to do it with pure CSS, is it possible?

I am using boostrap 4, it will be nice if the suggestion can co-exists with Bootstrap CSS. It will be awesome if the div can have an arrow associate with it.

My code is:

```<code><div>
    <div><figure class="figure"><img ... /></figure></div>
    //css-popover
    <div class="css-popover">User detail: ... bla bla bla ...</div>
</div>
</code>```

I tried to search in Stackoverflow, most of the question is related to float div and makes it beside, but I want something absolute positioned, and display on top of the body.

Update:

Most of the suggestions provided fulfill part of the requests. The suggested .css-popover width and height are bounded by the parents, but I wish the popover dimension be independent from the parent, i.e. just "popup" and it doesn't "change" the layout beneath.

And when the popup appear, it doesn't change the parent height too. I wish the sidebar "icon" (light pink icons) stay in place whenever a popup appear.

If it is not possible with CSS, then I just go for JS solution...

You can try your luck here. https://jsfiddle.net/byanjiong/nohno2bd/13/

(Note: the user content is long, so it height usually will exceed the profile image's height)

Update 2:
Thanks to @Gezzasa, his solution is working. ^_^

Guy, this is the working example of pure CSS popover! Amazing!

https://jsfiddle.net/byanjiong/nohno2bd/15/

Thanks, guy...

答:
This is one pure CSS solution.. But i recomend using JS

body {
  margin: 0px;
}

.figure {
  height: 20px;
  width: 100px;
  background: pink;
  float: left;
  margin: 0px;
}

.figure+.css-popover {
  height: 50px;
  width: 0px;
  background: lightblue;
  transition: all 0.3s ease;
  float: left;
  position: relative;
  visibility: hidden;
  left: 5px;
  overflow: hidden;
  padding: 10px;
}

.figure+.css-popover::before {
  content: '';
  display: inline-block;
  height: 0px;
  width: 0px;
  border: 5px solid transparent;
  border-right: 5px solid lightblue;
  position: absolute;
  top: 5px;
  left: -10px;
}

.figure:hover+.css-popover,
.css-popover:hover {
  width: 100px;
  visibility: visible;
  overflow: visible;
}

.clearfic,
.clearfix:after,
.clearfix:before {
  content: "";
  clear: both;
  display: table;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="clearfix">
  <figure class="figure"></figure>
  <div class="css-popover">User detail: ... bla bla bla ...</div>
</div>
<div>Some content</div></code>```

EDIT : Added arrow

Body:
I have a sidebar with a user profile picture (pink color). When the viewer hover on the image, a div (blue color) appears and it contains user details. Basically, I want an absolute positioned div appear next to its sibling.

It is functionally a popover, but I want to do it with pure CSS, is it possible?

I am using boostrap 4, it will be nice if the suggestion can co-exists with Bootstrap CSS. It will be awesome if the div can have an arrow associate with it.

My code is:

    //css-popover

User detail: ... bla bla bla ...

I tried to search in Stackoverflow, most of the question is related to float div and makes it beside, but I want something absolute positioned, and display on top of the body.

Update:

Most of the suggestions provided fulfill part of the requests. The suggested .css-popover width and height are bounded by the parents, but I wish the popover dimension be independent from the parent, i.e. just "popup" and it doesn't "change" the layout beneath.

And when the popup appear, it doesn't change the parent height too. I wish the sidebar "icon" (light pink icons) stay in place whenever a popup appear.

If it is not possible with CSS, then I just go for JS solution...

You can try your luck here. https://jsfiddle.net/byanjiong/nohno2bd/13/

(Note: the user content is long, so it height usually will exceed the profile image's height)

Update 2:
Thanks to @Gezzasa, his solution is working. ^_^

Guy, this is the working example of pure CSS popover! Amazing!

https://jsfiddle.net/byanjiong/nohno2bd/15/

Thanks, guy...

Body:
This is one pure CSS solution.. But i recomend using JS

body {
  margin: 0px;
}

.figure {
  height: 20px;
  width: 100px;
  background: pink;
  float: left;
  margin: 0px;
}

.figure+.css-popover {
  height: 50px;
  width: 0px;
  background: lightblue;
  transition: all 0.3s ease;
  float: left;
  position: relative;
  visibility: hidden;
  left: 5px;
  overflow: hidden;
  padding: 10px;
}

.figure+.css-popover::before {
  content: '';
  display: inline-block;
  height: 0px;
  width: 0px;
  border: 5px solid transparent;
  border-right: 5px solid lightblue;
  position: absolute;
  top: 5px;
  left: -10px;
}

.figure:hover+.css-popover,
.css-popover:hover {
  width: 100px;
  visibility: visible;
  overflow: visible;
}

.clearfic,
.clearfix:after,
.clearfix:before {
  content: "";
  clear: both;
  display: table;
}

<div class="clearfix">
  <figure class="figure"></figure>
  <div class="css-popover">User detail: ... bla bla bla ...</div>
</div>
<div>Some content</div>

EDIT : Added arrow


问:
How to accept user input for a constant and use writeprocessmemory?
How do I use WriteProcessMemory to change ammo of my current ammo address? I know how to read it I just don't know how to write it. Is SetAmmo . I thought i'm doing everything wright?

Code:

```<code>#include <iostream>
#include <math.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <Windows.h>
using namespace std;

 DWORD pid;
 DWORD Ammo = 0x07823C5EC;
 int MyAmmo;
 int SetAmmo = 1;
int main(){

    HWND hwnd = FindWindowA(0, ("Garry's Mod"));

    GetWindowThreadProcessId(hwnd, &pid);
    HANDLE pHandle = OpenProcess(PROCESS_VM_READ, FALSE, pid);

    ReadProcessMemory(pHandle, (LPVOID)Ammo, &MyAmmo, sizeof(MyAmmo), 0);
    cout<<"Current Ammo = "<<MyAmmo<<endl;

    WriteProcessMemory(pHandle, (LPVOID)Ammo, &SetAmmo, sizeof(SetAmmo), 0);
    system("Pause");
    return 0;
}
</code>```

答:
you open the process with read access:

```<code>HANDLE pHandle = OpenProcess(PROCESS_VM_READ, FALSE, pid);
</code>```

try:

```<code>HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
</code>```

Body:
How do I use WriteProcessMemory to change ammo of my current ammo address? I know how to read it I just don't know how to write it. Is SetAmmo . I thought i'm doing everything wright?

Code:

#include <iostream>
#include <math.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <Windows.h>
using namespace std;

 DWORD pid;
 DWORD Ammo = 0x07823C5EC;
 int MyAmmo;
 int SetAmmo = 1;
int main(){

    HWND hwnd = FindWindowA(0, ("Garry's Mod"));

    GetWindowThreadProcessId(hwnd, &pid);
    HANDLE pHandle = OpenProcess(PROCESS_VM_READ, FALSE, pid);

    ReadProcessMemory(pHandle, (LPVOID)Ammo, &MyAmmo, sizeof(MyAmmo), 0);
    cout<<"Current Ammo = "<<MyAmmo<<endl;

    WriteProcessMemory(pHandle, (LPVOID)Ammo, &SetAmmo, sizeof(SetAmmo), 0);
    system("Pause");
    return 0;
}

Body:
you open the process with read access:

HANDLE pHandle = OpenProcess(PROCESS_VM_READ, FALSE, pid);

try:

HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);


问:
How can I remove "m" prefix from greenDAO's generated getters and setters?
GreenDAO is searching for getters and setters with the "m" prefix included in the name in its generated classes.

For example, I've set the entity to not generate any getters and setters but it still looks for, let's say, getMDate() for my private Date mDate, instead of my manually created getDate() method. Same goes for setters.

This is just breaking my adherence to the Android Code Style Guidelines.

Is there any way to configure greenDAO to use the code style standards that I've set out in Android Studio when it generates code?

EDIT: Just to make things clearer, I've added some code to get my point across. I wrote the above question half knocked out on antihistamines due to having chronic hayfever while I was trying to work and just wanted to get to sleep so I apologise if it wasn't enough to work with.

```<code>@Entity(generateConstructors = false, generateGettersSetters = false)
public class Day {

    @Id
    private long mId;

    @Unique
    @NotNull
    private Date mDate;

    @ToMany(referencedJoinProperty = "mDayId")
    private List<Goal> mGoals;

    public Day(long id) {
        this.mId = id;

        mGoals = new ArrayList<Goal>();
    }

    public Day(long id, Date date) {
        this.mId = id;
        this.mDate = date;
    }

    public long getId() {
        return mId;
    }

    public void setId(long id) {
        mId = id;
    }

    public Date getDate() {
        return mDate;
    }

    public void setDate(Date date) {
        mDate = date;
    }

    public List<Goal> getGoals() {
        return mGoals;
    }

    public void setGoals(List<Goal> goals) {
        mGoals = goals;
    }
}
</code>```

Above is my Day class. As you can see I've disabled generation of the getters and setters in the @Entity annotation, and put my own in there. I've set up Android Studio to take the "m" into consideration when I use alt+enter to create getters and setters for each of my fields.

```<code>public Date getMDate() {
    return mDate;
}

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

Here is an example of the getters and setters that greenDAO generates for my code given the field private Date mDate. This is breaking the code style guidelines in that the local variables include the "m" prefix and also that the method names include it as well (maybe a bit of a nit-pick there, but you can set up Android Studio so it doesn't do that which makes me think it shouldn't be like that).

With my getters and setters there, greenDAO still thinks the getters and setters are missing, which results in them being added twice. Once as the ones I put in, and another as what you see above. This also results in the generation of the code below.

```<code>@Override
protected final void bindValues(DatabaseStatement stmt, Day entity) {
    stmt.clearBindings();
    stmt.bindLong(1, entity.getMId());
    stmt.bindLong(2, entity.getMDate().getTime());
}

@Override
protected final void bindValues(SQLiteStatement stmt, Day entity) {
    stmt.clearBindings();
    stmt.bindLong(1, entity.getMId());
    stmt.bindLong(2, entity.getMDate().getTime());
}
</code>```

Here is some of the code from the class DayDao which is generated from greenDAO. It's still using the names for the getters (and also setters) that it would have used to generate its own getters and setters (getMDate() instead of getDate()) if I didn't disable their generation on the Day entity class. I can't change this code because it just switches back the next time I build the project, and there is my problem.

My question is: how can I get greenDAO to take the "m" prefix thing into consideration when it generates its code and get it to use the getters and setters that I have set out myself? Or even get it to generate getters and setters itself without the "m" being included in the name and local variables?

答:
The solution that I decided to use for this ended up being rather disappointing.

It involved just making my properties all public instead of private. Still conforming to the code style, these properties would no longer use the m prefix ... or any prefix, for that matter. It's not a very satisfactory solution as now my data can be accessed and set directly, just for a simple naming convention to be conformed to.

I (personally) disagree with people saying that using naming conventions hurts readability. If you structure your code well enough and give enough of a description in Javadoc comments and the like, you'll know exactly what something is doing. Having said that, if using the conventions is going to create such code as in my question above, then I guess that this is a situation where it does, and a reason not to use the code style in my other projects and still stick to the access that I want for my data.

Body:
GreenDAO is searching for getters and setters with the "m" prefix included in the name in its generated classes.

For example, I've set the entity to not generate any getters and setters but it still looks for, let's say, getMDate() for my private Date mDate, instead of my manually created getDate() method. Same goes for setters.

This is just breaking my adherence to the Android Code Style Guidelines.

Is there any way to configure greenDAO to use the code style standards that I've set out in Android Studio when it generates code?

EDIT: Just to make things clearer, I've added some code to get my point across. I wrote the above question half knocked out on antihistamines due to having chronic hayfever while I was trying to work and just wanted to get to sleep so I apologise if it wasn't enough to work with.

@Entity(generateConstructors = false, generateGettersSetters = false)
public class Day {

    @Id
    private long mId;

    @Unique
    @NotNull
    private Date mDate;

    @ToMany(referencedJoinProperty = "mDayId")
    private List<Goal> mGoals;

    public Day(long id) {
        this.mId = id;

        mGoals = new ArrayList<Goal>();
    }

    public Day(long id, Date date) {
        this.mId = id;
        this.mDate = date;
    }

    public long getId() {
        return mId;
    }

    public void setId(long id) {
        mId = id;
    }

    public Date getDate() {
        return mDate;
    }

    public void setDate(Date date) {
        mDate = date;
    }

    public List<Goal> getGoals() {
        return mGoals;
    }

    public void setGoals(List<Goal> goals) {
        mGoals = goals;
    }
}

Above is my Day class. As you can see I've disabled generation of the getters and setters in the @Entity annotation, and put my own in there. I've set up Android Studio to take the "m" into consideration when I use alt+enter to create getters and setters for each of my fields.

public Date getMDate() {
    return mDate;
}

public void setMDate(Date mDate) {
    this.mDate = mDate;
}

Here is an example of the getters and setters that greenDAO generates for my code given the field private Date mDate. This is breaking the code style guidelines in that the local variables include the "m" prefix and also that the method names include it as well (maybe a bit of a nit-pick there, but you can set up Android Studio so it doesn't do that which makes me think it shouldn't be like that).

With my getters and setters there, greenDAO still thinks the getters and setters are missing, which results in them being added twice. Once as the ones I put in, and another as what you see above. This also results in the generation of the code below.

@Override
protected final void bindValues(DatabaseStatement stmt, Day entity) {
    stmt.clearBindings();
    stmt.bindLong(1, entity.getMId());
    stmt.bindLong(2, entity.getMDate().getTime());
}

@Override
protected final void bindValues(SQLiteStatement stmt, Day entity) {
    stmt.clearBindings();
    stmt.bindLong(1, entity.getMId());
    stmt.bindLong(2, entity.getMDate().getTime());
}

Here is some of the code from the class DayDao which is generated from greenDAO. It's still using the names for the getters (and also setters) that it would have used to generate its own getters and setters (getMDate() instead of getDate()) if I didn't disable their generation on the Day entity class. I can't change this code because it just switches back the next time I build the project, and there is my problem.

My question is: how can I get greenDAO to take the "m" prefix thing into consideration when it generates its code and get it to use the getters and setters that I have set out myself? Or even get it to generate getters and setters itself without the "m" being included in the name and local variables?


问:
Move view with keyboard using Swift
I have an app that has a text field on the lower half of the view.
This means that when I go to type in the text field the keyboard covers the textfield.

How would I go about moving the view upwards while typing so I can see what i'm typing and then moving it back down to its original place when the keyboard disappears?

I've looked everywhere but all the solutions appear to be in Obj-C which I can't quite convert just yet.

Any help would be greatly appreciated.

答:
For Swift 3

```<code>func textFieldDidBeginEditing(_ textField: UITextField) { // became first responder

    //move textfields up
    let myScreenRect: CGRect = UIScreen.main.bounds
    let keyboardHeight : CGFloat = 216

    UIView.beginAnimations( "animateView", context: nil)
    var movementDuration:TimeInterval = 0.35
    var needToMove: CGFloat = 0

    var frame : CGRect = self.view.frame
    if (textField.frame.origin.y + textField.frame.size.height + UIApplication.shared.statusBarFrame.size.height > (myScreenRect.size.height - keyboardHeight - 30)) {
        needToMove = (textField.frame.origin.y + textField.frame.size.height + UIApplication.shared.statusBarFrame.size.height) - (myScreenRect.size.height - keyboardHeight - 30);
    }

    frame.origin.y = -needToMove
    self.view.frame = frame
    UIView.commitAnimations()
}

func textFieldDidEndEditing(_ textField: UITextField) {
    //move textfields back down
    UIView.beginAnimations( "animateView", context: nil)
    var movementDuration:TimeInterval = 0.35
    var frame : CGRect = self.view.frame
    frame.origin.y = 0
    self.view.frame = frame
    UIView.commitAnimations()
}
</code>```

Title: Move view with keyboard using Swift

Body:
For Swift 3

func textFieldDidBeginEditing(_ textField: UITextField) { // became first responder

    //move textfields up
    let myScreenRect: CGRect = UIScreen.main.bounds
    let keyboardHeight : CGFloat = 216

    UIView.beginAnimations( "animateView", context: nil)
    var movementDuration:TimeInterval = 0.35
    var needToMove: CGFloat = 0

    var frame : CGRect = self.view.frame
    if (textField.frame.origin.y + textField.frame.size.height + UIApplication.shared.statusBarFrame.size.height > (myScreenRect.size.height - keyboardHeight - 30)) {
        needToMove = (textField.frame.origin.y + textField.frame.size.height + UIApplication.shared.statusBarFrame.size.height) - (myScreenRect.size.height - keyboardHeight - 30);
    }

    frame.origin.y = -needToMove
    self.view.frame = frame
    UIView.commitAnimations()
}

func textFieldDidEndEditing(_ textField: UITextField) {
    //move textfields back down
    UIView.beginAnimations( "animateView", context: nil)
    var movementDuration:TimeInterval = 0.35
    var frame : CGRect = self.view.frame
    frame.origin.y = 0
    self.view.frame = frame
    UIView.commitAnimations()
}


问:
Michael Hartl ch9 : how to sign up
I’ve completed Michael Hartl ch 9 and have no error in testing.
But I could not  sign up...

It returns error as below even so previously I be able to sign up..login works fine.

How to fix it and be able to sign up?

Should I  merge  sign up branch? But doing that I could loose all changes..  Could something be done about sign up form this more advance branch?

Error:

No route matches [POST] "/signup"

routes.rb:

```<code>Rails.application.routes.draw do
  root   'static_pages#home'

  get    '/help',    to: 'static_pages#help'
  get    '/about',   to: 'static_pages#about'
  get    '/contact', to: 'static_pages#contact'
  get    '/signup',  to: 'users#new'
  get    '/login',   to: 'sessions#new'
  post   '/login',   to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'

  resources :users
end
</code>```

thanks.

Thanks everybody for answers.
It works now.
One more question related.
When users sign up - they could directly participate in website. It is no good since they need to get confirmation by email and only that they could participate.

How it could be implemented?

I think it is in the solutions Michael Hartl and I even implemented it for Rails 4, but could not remember what need to change..
What files need to be changed to allow users participate in website only after getting confirmation by email.
thanks.

答:
No route matches [POST] "/signup"

You should have post '/signup', to: 'users#create' in your routes.

Title: Michael Hartl ch9 : how to sign up

Body:
I’ve completed Michael Hartl ch 9 and have no error in testing.
But I could not  sign up...

It returns error as below even so previously I be able to sign up..login works fine.

How to fix it and be able to sign up?

Should I  merge  sign up branch? But doing that I could loose all changes..  Could something be done about sign up form this more advance branch?

Error:

No route matches [POST] "/signup"

routes.rb:

Rails.application.routes.draw do
  root   'static_pages#home'

  get    '/help',    to: 'static_pages#help'
  get    '/about',   to: 'static_pages#about'
  get    '/contact', to: 'static_pages#contact'
  get    '/signup',  to: 'users#new'
  get    '/login',   to: 'sessions#new'
  post   '/login',   to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'

  resources :users
end

thanks.

Thanks everybody for answers.
It works now.
One more question related.
When users sign up - they could directly participate in website. It is no good since they need to get confirmation by email and only that they could participate.

How it could be implemented?

I think it is in the solutions Michael Hartl and I even implemented it for Rails 4, but could not remember what need to change..
What files need to be changed to allow users participate in website only after getting confirmation by email.
thanks.


问:
c# send uploaded file through email daily using asp.net web application
I just want to know, how to make a web-application which takes input of Excel files from user and send an email daily if that excel file has any new data available.

Should I use web service (with installation of that service in local computer) ? and yes then how to add Upload User-Interface. or Should I use only a web application and Should I add web-service in that application ?

Pls give way to come out of this problem.

Thankyou.

答:
No need of installations to the user computer. You need a simple Web Application and a web server, of course. There are many tutorials about getting started with web applications here are some links:

ASP.NET WebForms - obsolete, yet powerful web app paradigm.
However, I do recommend the next option, especially if you don't have any previous experience with desktop applications.

ASP.NET MVC - this is the modern way of building web applications.

Once you made your mind about what technology to use, you gonna need so called SMTP server; usually the ISP provides one for you and you gonna need to add a configuration to the web.config, such as:

```<code><system.net>
    <mailSettings>
        <smtp deliveryMethod="Network">
            <network host="*SMTP server IP address*" port="25" />
        </smtp>
    </mailSettings>
</system.net>
</code>```

You can take a look at this SO post for details on how to accomplish this in ASP.NET MVC.

Body:
No need of installations to the user computer. You need a simple Web Application and a web server, of course. There are many tutorials about getting started with web applications here are some links:

ASP.NET WebForms - obsolete, yet powerful web app paradigm.
However, I do recommend the next option, especially if you don't have any previous experience with desktop applications.

ASP.NET MVC - this is the modern way of building web applications.

Once you made your mind about what technology to use, you gonna need so called SMTP server; usually the ISP provides one for you and you gonna need to add a configuration to the web.config, such as:

<system.net>
    <mailSettings>
        <smtp deliveryMethod="Network">
            <network host="*SMTP server IP address*" port="25" />
        </smtp>
    </mailSettings>
</system.net>

You can take a look at this SO post for details on how to accomplish this in ASP.NET MVC.


答:
You need to add

```<code>  post '/signup',  to: 'users#create'
</code>```

And write create method in

```<code>class UsersController < ApplicationController
  def create
    # Create User with signup parameterss
  end
end
</code>```

Title: Michael Hartl ch9 : how to sign up

Body:
You need to add

  post '/signup',  to: 'users#create'

And write create method in

class UsersController < ApplicationController
  def create
    # Create User with signup parameterss
  end
end


问:
Execute a python file c#
I have a python converter that works calling it with some parameters from cmd. I want to create an exe that automatically calls it with the needed parameters, which are the model I want to convert and the name of the model that it will be created.
The code is:</p>

```<code>blender -b -P dae-obj.py -- file.dae file.obj
</code>```

答:
Have you tried using IronPython? I see you wish to use C# along with python. In case your primary application is in C# and you wish to leverage some of the features of python, you can use IronPython to create an environment where a python code can be executed and it can interact with the C# application as well.
I hope this link will be able to solve some of the problems. They have explained it well with code</p>

Title: Execute a python file c#

Body:
I have a python converter that works calling it with some parameters from cmd. I want to create an exe that automatically calls it with the needed parameters, which are the model I want to convert and the name of the model that it will be created.
The code is:

blender -b -P dae-obj.py -- file.dae file.obj


问:
Bind to DropDownList in MVC 2
Ok I know I'm missing something real simple here so maybe an extra set of eyes will help. I have a POCO class (State) in my DAL, and in my MVC application I'm trying to bind that to a DropDownList, but when it loads all I get is WeddingPhotographer.Models.BusinessObjects.State in my DropDownList 50 times. Here's the code from the POCO class:

```<code>public partial class State
{
    public virtual int Key
    {
        get;
        set;
    }

    public virtual string StateAbbreviation
    {
        get;
        set;
    }

    public virtual string StateName
    {
        get;
        set;
    }

}
</code>```

Here's the code from my business Object (use term lightly)

```<code>public class State
{
    public int Key { get; set; }
    public string StateName { get; set; }
    public string StateAbbreviation { get; set; }
}

public class StateList
{
    private static IRepository<WeddingPhotographer.Data.Model.State> states = ObjectFactory.GetInstance<IRepository<WeddingPhotographer.Data.Model.State>>();
    static readonly IList<State> stateList = new List<State>();

    public static IEnumerable<State> States
    {
        get
        {
            foreach (WeddingPhotographer.Data.Model.State s in states.GetAll())
            {
                stateList.Add(new State
                {
                    Key = s.Key,
                    StateName = s.StateName,
                    StateAbbreviation = s.StateAbbreviation
                });
            }
            return stateList;
        }
    }
}
</code>```

Then my states DropDownList control

```<code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<WeddingPhotographer.Models.BusinessObjects.State>" %>
<%: Html.DropDownList("StatesDropDown", new SelectList(WeddingPhotographer.Helpers.StateList.States,Model))%>
</code>```

And finally how I'm loading it

```<code><div class="editor-field">
    <% Html.RenderPartial("StatesDropDown"); %>
    <%= Html.ValidationMessageFor(m => m.State) %>
</div>
</code>```

I know I'm missing something simple here (relatively new to MVC so still trying to get things right)

答:
I took @SyntaxC4's advice and went back to using IEnumerable but was getting a NullReferenceException whenever I would try to load the DropDownList in my View. I changed my DropDownList control to look like this and it now works perfectly

```<code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<WeddingPhotographer.Models.BusinessObjects.State>" %>
<%: Html.DropDownList("StatesDropDown", new SelectList(WeddingPhotographer.Helpers.StateList.States, "Key", "StateAbbreviation"))%>
</code>```

Thanks @SyntaxC4 and @BenAlabaster for your help in email as well

Title: Bind to DropDownList in MVC 2

Body:
Ok I know I'm missing something real simple here so maybe an extra set of eyes will help. I have a POCO class (State) in my DAL, and in my MVC application I'm trying to bind that to a DropDownList, but when it loads all I get is WeddingPhotographer.Models.BusinessObjects.State in my DropDownList 50 times. Here's the code from the POCO class:

public partial class State
{
    public virtual int Key
    {
        get;
        set;
    }

    public virtual string StateAbbreviation
    {
        get;
        set;
    }

    public virtual string StateName
    {
        get;
        set;
    }

}

Here's the code from my business Object (use term lightly)

public class State
{
    public int Key { get; set; }
    public string StateName { get; set; }
    public string StateAbbreviation { get; set; }
}

public class StateList
{
    private static IRepository<WeddingPhotographer.Data.Model.State> states = ObjectFactory.GetInstance<IRepository<WeddingPhotographer.Data.Model.State>>();
    static readonly IList<State> stateList = new List<State>();

    public static IEnumerable<State> States
    {
        get
        {
            foreach (WeddingPhotographer.Data.Model.State s in states.GetAll())
            {
                stateList.Add(new State
                {
                    Key = s.Key,
                    StateName = s.StateName,
                    StateAbbreviation = s.StateAbbreviation
                });
            }
            return stateList;
        }
    }
}

Then my states DropDownList control

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<WeddingPhotographer.Models.BusinessObjects.State>" %>
<%: Html.DropDownList("StatesDropDown", new SelectList(WeddingPhotographer.Helpers.StateList.States,Model))%>

And finally how I'm loading it

    <% Html.RenderPartial("StatesDropDown"); %>
    <%= Html.ValidationMessageFor(m => m.State) %>

I know I'm missing something simple here (relatively new to MVC so still trying to get things right)

Body:
I took @SyntaxC4's advice and went back to using IEnumerable but was getting a NullReferenceException whenever I would try to load the DropDownList in my View. I changed my DropDownList control to look like this and it now works perfectly

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<WeddingPhotographer.Models.BusinessObjects.State>" %>
<%: Html.DropDownList("StatesDropDown", new SelectList(WeddingPhotographer.Helpers.StateList.States, "Key", "StateAbbreviation"))%>

Thanks @SyntaxC4 and @BenAlabaster for your help in email as well


问:
Operands mismatch for mul when inserting asm into c
I'm trying to make an assembly insert into C code. However when I try to multiply two registers inside it I get an error calling for operands mismatch. I tried "mul %%bl, %%cl\n" (double %% because it's in C code). From my past experience with asm I think this should work. I also tried "mul %%cl\n" (moving bl to al first), but in this case I get tons of errors from linker

```<code>zad3:(.rodata+0x4): multiple definition of `len'
/tmp/ccJxYyIp.o:(.rodata+0x0): first defined here
zad3: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here
zad3: In function `data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.data+0x0): first defined here
zad3: In function `data_start':
(.data+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-linux-gnu/5/crtbegin.o:(.data+0x0): first defined here
zad3:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here
zad3: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: (.text+0x0): first defined here
zad3: In function `data_start':
(.data+0x10): multiple definition of `str'
/tmp/ccJxYyIp.o:(.data+0x0): first defined here
/usr/bin/ld: Warning: size of symbol `str' changed from 4 in   /tmp/ccJxYyIp.o to 9 in zad3
zad3: In function `main':
(.text+0xf6): multiple definition of `main'
/tmp/ccJxYyIp.o:zad3.c:(.text+0x0): first defined here
zad3: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o:(.init+0x0): first defined here
/usr/lib/gcc/x86_64-linux-gnu/5/crtend.o:(.tm_clone_table+0x0): multiple definition of `__TMC_END__'
zad3:(.data+0x20): first defined here
/usr/bin/ld: error in zad3(.eh_frame); no .eh_frame_hdr table will be created.
collect2: error: ld returned 1 exit status
</code>```

From what I understand, it tells me I defined len and a few other variables a few times, but I cannot see this multiple definition.
The goal of my program is to take a string of numbers and count sum of them but using 2 as a base. So let's say string is 293, then I want to count 2*2^2+9*2^1+3*2^0
Code:

```<code>#include <stdio.h>
char str[] = "543";
const int len = 3;

int main(void)
{
asm(
"mov $0, %%rbx \n"
"mov $1, %%rcx \n"

"potega: \n"
"shl $1, %%cl \n"
"inc %%rbx \n"
"cmp len, %%ebx \n"
"jl potega \n"

"mov $0, %%rbx \n"

"petla: \n"
"mov (%0, %%rbx, 1), %%al \n"

"sub $48, %%al \n"

"mul %%al, %%cl \n"
"shr $1, %%cl \n"

"add $48, %%al \n"

"mov %%al, (%0, %%rbx, 1) \n"

"inc %%rbx \n"
"cmp len, %%ebx \n"
"jl petla \n"

:"r"(&str)
:"%rax", "%rbx", "%rcx"
);
printf("Wynik: %s\n", str);
return 0;
}
</code>```

答:
As somebody pointed out - yes it's a student exercise.
When it comes to my original problem, when I removed line add $48,%%al \n" it worked. I also switched to mul %%cl.

When it comes to rest of problems, you pointed out, I talked with my professor and she slightly changed her mind (or I got the assgment wrong the first time - whatever you find more possible) and now she wanted me to return an argument from the inline function and  said the intiger type was good. It resulted in me writing such piece of code (which actually does what I wanted)

example: "543" -> 5*(2^2)+4*(2^1)+3*(2^0)=31

```<code>#include <stdio.h>
char str[] = "543";
const int len = 3;
int len1 = 2;
int result;

int main(){
asm(
    "mov $0, %%rbx\n"
    "mov $1, %%rcx\n"
    "mov $0, %%rdx\n"

    "potega: \n"
    "inc %%rbx\n"
    "shl $1, %%cl\n"
    "cmp len1, %%ebx \n"
    "jl potega\n"

    "mov $0, %%rbx\n"

    "petla:\n"
    "mov (%0, %%rbx, 1), %%al\n"
    "sub $48, %%al\n"
    "mul %%cl\n"
    "shr $1, %%cl\n"
    "add %%al, %%dl\n"
    "inc %%rbx\n"
    "cmp len, %%ebx\n"
    "jl petla\n"

    "movl %%edx, result\n"

    ://"=r"(result)

    :"r"(&str), "r"(&result)

    :"%rax", "%rbx", "%rcx", "%rdx"

);
printf("Wynik: %d\n", result);
return 0;
}
</code>```

Also - I do realise, that normally you return variables the way it's showed in comment, but it didn't work, so by my professor's suggestion I wrote the program this way.

Thanks everybody for help!

Body:
I'm trying to make an assembly insert into C code. However when I try to multiply two registers inside it I get an error calling for operands mismatch. I tried "mul %%bl, %%cl\n" (double %% because it's in C code). From my past experience with asm I think this should work. I also tried "mul %%cl\n" (moving bl to al first), but in this case I get tons of errors from linker

zad3:(.rodata+0x4): multiple definition of `len'
/tmp/ccJxYyIp.o:(.rodata+0x0): first defined here
zad3: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here
zad3: In function `data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.data+0x0): first defined here
zad3: In function `data_start':
(.data+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-linux-gnu/5/crtbegin.o:(.data+0x0): first defined here
zad3:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here
zad3: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: (.text+0x0): first defined here
zad3: In function `data_start':
(.data+0x10): multiple definition of `str'
/tmp/ccJxYyIp.o:(.data+0x0): first defined here
/usr/bin/ld: Warning: size of symbol `str' changed from 4 in   /tmp/ccJxYyIp.o to 9 in zad3
zad3: In function `main':
(.text+0xf6): multiple definition of `main'
/tmp/ccJxYyIp.o:zad3.c:(.text+0x0): first defined here
zad3: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o:(.init+0x0): first defined here
/usr/lib/gcc/x86_64-linux-gnu/5/crtend.o:(.tm_clone_table+0x0): multiple definition of `__TMC_END__'
zad3:(.data+0x20): first defined here
/usr/bin/ld: error in zad3(.eh_frame); no .eh_frame_hdr table will be created.
collect2: error: ld returned 1 exit status

From what I understand, it tells me I defined len and a few other variables a few times, but I cannot see this multiple definition.
The goal of my program is to take a string of numbers and count sum of them but using 2 as a base. So let's say string is 293, then I want to count 2*2^2+9*2^1+3*2^0
Code:

#include <stdio.h>
char str[] = "543";
const int len = 3;

int main(void)
{
asm(
"mov $0, %%rbx \n"
"mov $1, %%rcx \n"

"potega: \n"
"shl $1, %%cl \n"
"inc %%rbx \n"
"cmp len, %%ebx \n"
"jl potega \n"

"mov $0, %%rbx \n"

"petla: \n"
"mov (%0, %%rbx, 1), %%al \n"

"sub $48, %%al \n"

"mul %%al, %%cl \n"
"shr $1, %%cl \n"

"add $48, %%al \n"

"mov %%al, (%0, %%rbx, 1) \n"

"inc %%rbx \n"
"cmp len, %%ebx \n"
"jl petla \n"

:"r"(&str)
:"%rax", "%rbx", "%rcx"
);
printf("Wynik: %s\n", str);
return 0;
}

Body:
As somebody pointed out - yes it's a student exercise.
When it comes to my original problem, when I removed line add $48,%%al \n" it worked. I also switched to mul %%cl.

When it comes to rest of problems, you pointed out, I talked with my professor and she slightly changed her mind (or I got the assgment wrong the first time - whatever you find more possible) and now she wanted me to return an argument from the inline function and  said the intiger type was good. It resulted in me writing such piece of code (which actually does what I wanted)

example: "543" -> 5*(2^2)+4*(2^1)+3*(2^0)=31

#include <stdio.h>
char str[] = "543";
const int len = 3;
int len1 = 2;
int result;

int main(){
asm(
    "mov $0, %%rbx\n"
    "mov $1, %%rcx\n"
    "mov $0, %%rdx\n"

    "potega: \n"
    "inc %%rbx\n"
    "shl $1, %%cl\n"
    "cmp len1, %%ebx \n"
    "jl potega\n"

    "mov $0, %%rbx\n"

    "petla:\n"
    "mov (%0, %%rbx, 1), %%al\n"
    "sub $48, %%al\n"
    "mul %%cl\n"
    "shr $1, %%cl\n"
    "add %%al, %%dl\n"
    "inc %%rbx\n"
    "cmp len, %%ebx\n"
    "jl petla\n"

    "movl %%edx, result\n"

    ://"=r"(result)

    :"r"(&str), "r"(&result)

    :"%rax", "%rbx", "%rcx", "%rdx"

);
printf("Wynik: %d\n", result);
return 0;
}

Also - I do realise, that normally you return variables the way it's showed in comment, but it didn't work, so by my professor's suggestion I wrote the program this way.

Thanks everybody for help!


问:
Call Procedure / Function JPA Hibernate
Hey guys I have a procedure in postgres SQL and I'm trying call it using jpa hibernate, but I'm getting error.

```<code>    select * from myprocedure(2016, 3, 0, 0,0)
AS f(descricao varchar, itens integer, quantidade bigint, valor numeric)
</code>```

and here what im trying do in java.

```<code>StringBuilder sb = new StringBuilder();
            sb.append(" SELECT * ");
            sb.append(" FROM myprocedure( ");
            sb.append(" :ano , ");
            if (Util.isNotNull(mes)) {
                sb.append(":mes , ");
            }
            sb.append(" :codNre , ");
            sb.append(" :codMun , ");
            sb.append(" 0) ");
            sb.append(" AS f(descricao varchar, itens integer, quantidade bigint, valor numeric) ");

            TypedQuery<Tuple> query = em.createQuery(sb.toString(), Tuple.class);

            query.setParameter("ano", ano);
            if (Util.isNotNull(mes)) {
                query.setParameter("mes", mes);
            }
            query.setParameter("codNre", codNre);
            query.setParameter("codMun", codMun);

            List<ResumoDistribuicaoMerendaDTO> listaRetorno = new ArrayList<ResumoDistribuicaoMerendaDTO>();

            List<Tuple> results = query.getResultList();
            for (Tuple result : results) {
                ResumoDistribuicaoMerendaDTO resumoMerenda = new ResumoDistribuicaoMerendaDTO();
                resumoMerenda.setDescricaoAlimento(result.get(0).toString());
                resumoMerenda.setItens(Integer.valueOf(result.get(1).toString()));
                resumoMerenda
                        .setQuantidade(result.get(2) == null ? new Long(0) : Long.parseLong(result.get(2).toString()));
                resumoMerenda.setValor(result.get(3) == null ? new BigDecimal(0)
                        : BigDecimal.valueOf(Double.parseDouble(result.get(3).toString())));

                listaRetorno.add(resumoMerenda);
            }
</code>```

and the exception:

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: * near line 1, column 9 [ SELECT *  FROM myprocedure(  :ano , :mes ,  :codNre ,  :codMun ,  0)  AS f(descricao varchar, itens integer, quantidade bigint, valor numeric) ]

I already try replace the * for f but not working =\

答:
You cannot use PostgreSQL's SQL in createQuery(). The createQuery command accepts only Java Persistence Query Language (JPQL) which will not know the myprocedure defined in your database.

You will either have to use em.createNativeQuery(...) for that (check documentation here) or use something like this

Title: Call Procedure / Function JPA Hibernate

Body:
Hey guys I have a procedure in postgres SQL and I'm trying call it using jpa hibernate, but I'm getting error.

    select * from myprocedure(2016, 3, 0, 0,0)
AS f(descricao varchar, itens integer, quantidade bigint, valor numeric)

and here what im trying do in java.

StringBuilder sb = new StringBuilder();
            sb.append(" SELECT * ");
            sb.append(" FROM myprocedure( ");
            sb.append(" :ano , ");
            if (Util.isNotNull(mes)) {
                sb.append(":mes , ");
            }
            sb.append(" :codNre , ");
            sb.append(" :codMun , ");
            sb.append(" 0) ");
            sb.append(" AS f(descricao varchar, itens integer, quantidade bigint, valor numeric) ");

            TypedQuery<Tuple> query = em.createQuery(sb.toString(), Tuple.class);

            query.setParameter("ano", ano);
            if (Util.isNotNull(mes)) {
                query.setParameter("mes", mes);
            }
            query.setParameter("codNre", codNre);
            query.setParameter("codMun", codMun);

            List<ResumoDistribuicaoMerendaDTO> listaRetorno = new ArrayList<ResumoDistribuicaoMerendaDTO>();

            List<Tuple> results = query.getResultList();
            for (Tuple result : results) {
                ResumoDistribuicaoMerendaDTO resumoMerenda = new ResumoDistribuicaoMerendaDTO();
                resumoMerenda.setDescricaoAlimento(result.get(0).toString());
                resumoMerenda.setItens(Integer.valueOf(result.get(1).toString()));
                resumoMerenda
                        .setQuantidade(result.get(2) == null ? new Long(0) : Long.parseLong(result.get(2).toString()));
                resumoMerenda.setValor(result.get(3) == null ? new BigDecimal(0)
                        : BigDecimal.valueOf(Double.parseDouble(result.get(3).toString())));

                listaRetorno.add(resumoMerenda);
            }

and the exception:

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: * near line 1, column 9 [ SELECT *  FROM myprocedure(  :ano , :mes ,  :codNre ,  :codMun ,  0)  AS f(descricao varchar, itens integer, quantidade bigint, valor numeric) ]

I already try replace the * for f but not working =\


问:
What is the default Celery log level if none is specified?
According to the Celery documentation, the -l/--loglevel command line option can be used for:

-l, --loglevel

Logging level, choose between DEBUG, INFO, WARNING, ERROR, CRITICAL, or FATAL.

If this option is not used and therefore no log level is specified, what is the log level used by Celery by default?

答: Default log level in Celery is WARNING due implementation here. That level is set during initialization of the Logging instance.


问:
how to dry run neo4j cypher queries
I was trying to write a query in neo4j browser to make some data changes. However, I don't have confidence if it will work or not. So I was wondering if there is any way I can dry run the queries before I actually run it. Or is there any way I can revert a wrong query?

The idea here is like the powershell whatif commands to avoid accidents: http://www.computerperformance.co.uk/powershell/powershell_whatif_confirm.htm

Thanks

答:
You can prepend your statement with EXPLAIN. This will profile your query without actually running it.

Check this link for more info on profiling:
https://neo4j.com/docs/developer-manual/current/cypher/query-tuning/how-do-i-profile-a-query/

Title: how to dry run neo4j cypher queries


问:
Change npm registry by project
Is it possible to set registry for a specific project only.

I've installed verdaccio for publishing private enterprise modules.
I'd like to not use systematically this registry for other projects.

Each time i switch project i have to reset the registry manually.

答:
Yes you can, set in your package.json this using your verdaccio domain.

```<code>  "publishConfig": {
     "registry": "http:///localhost:4873"
   },
</code>```

Title: Change npm registry by project

Body:
Yes you can, set in your package.json this using your verdaccio domain.

  "publishConfig": {
     "registry": "http:///localhost:4873"
   },


问:
JDBC with Apache Derby throwing java.sql.SQLNonTransientConnectionException: No current connection
I'm working in a desktop application where I need to connect to a database to retrieve some data and generate a report. For testing purposes, I created a test DB in Derby with the tables I need and some dummy data in them.

As it is a small app, I decided to work with plain JDBC to make it as lightweight as it can be.

I'm using TDD for developing. I've already tested the method for loading the connection properties from a file and the method for creating a connection to the DB. I got stuck when trying to query the data and populate the objects mapped to that data. This is my code:

```<code>public class JdbcManager {

    static final String JDBC_DRIVER_PROPERTY = "jdbc.driver";
    static final String JDBC_URL_PROPERTY = "jdbc.url";
    static final String JDBC_USER_PROPERTY = "jdbc.username";
    static final String JDBC_PASSWORD_PROPERTY = "jdbc.password";
    static String PROPERTIES_FILE_PATH = "src/main/resources/connection.properties";
    String queryCareers = "SELECT career, name FROM db_career”;

    private static final Logger LOG = Logger.getLogger(JdbcManager.class.getName());

    public List<Career> getCareerList() {
        List<Career> result = new ArrayList<>();
        Career item;
        Connection connection = createConnection(PROPERTIES_FILE_PATH);
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(queryCareers);

            while (rs.next()) {
                item = new Career(rs.getString("Career"), rs.getString("name"));
                result.add(item);
            }
        } catch (SQLException ex) {
            LOG.log(Level.SEVERE, “Error retrieving Career data”, ex);
        }

        return result;
    }

    // This method is working correctly according to my tests
    Connection createConnection(String configFilePath) {
        Properties connectionProperties = loadPropertiesFromFile(configFilePath);
        try {
            Class driverClass = Class.forName(connectionProperties.getProperty(JDBC_DRIVER_PROPERTY));
            LOG.log(Level.INFO, "Driver loaded: {0}", driverClass);
        } catch (ClassNotFoundException ex) {
            LOG.log(Level.SEVERE, "Driver not found”, ex);
        }

        try (Connection connection = DriverManager.getConnection(
                connectionProperties.getProperty(JDBC_URL_PROPERTY),
                connectionProperties.getProperty(JDBC_USER_PROPERTY),
                connectionProperties.getProperty(JDBC_PASSWORD_PROPERTY))) {
            LOG.log(Level.INFO, “Connection created: {0}", connection);
            return connection;
        } catch (SQLException ex) {
            LOG.log(Level.SEVERE, “Unable to connect to DB”, ex);
            return null;
        }
    }

    // This method is working correctly according to my tests
    Properties loadPropertiesFromFile(String configFilePath) {
        File configFile = new File(configFilePath);
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(configFile));
            LOG.log(Level.INFO, “Properties loaded: {0}", properties);
        } catch (FileNotFoundException ex) {
            LOG.log(Level.SEVERE, "File not found", ex);
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "Error reading the file", ex);
        }

        return properties;
    }

}
</code>```

Then I have the failing test:

```<code>@Test
public void testGetCareerList() {
    logger.log(Level.INFO, "testGetCareerList():");
    List<Career> expectedResult = Arrays.asList(
            new Career("LGU", “Some dummy name 1”),
            new Career("TSGU", "Some dummy name 2”));

    // Change the location of the properties file to the testing one
    GestorJdbc.PROPERTIES_FILE_PATH = "src/test/resources/connectionTest.properties";

    List<Career> actualResult = jdbcManager.getCareerList();
    assertEquals(expectedResult, actualResult);
}
</code>```

And finally the stacktrace when I execute the test:

```<code>-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running ar.edu.unt.jdbc.JdbcManagerTest
jun 06, 2017 7:57:24 PM ar.edu.unt.jdbc.JdbcManagerTest testGetCareerList
INFO: testGetCareerList():
jun 06, 2017 7:57:24 PM ar.edu.unt.jdbc.JdbcManager loadPropertiesFromFile
INFO: Properties loaded: {jdbc.url=jdbc:derby://localhost:1527/siu_test, jdbc.username=dba, jdbc.driver=org.apache.derby.jdbc.ClientDriver, jdbc.password=dba}
jun 06, 2017 7:57:24 PM ar.edu.unt.jdbc.JdbcManager createConnection
INFO: Driver loaded: class org.apache.derby.jdbc.ClientDriver
jun 06, 2017 7:57:26 PM ar.edu.unt.jdbc.JdbcManager createConnection
INFO: Connection created: org.apache.derby.client.net.NetConnection40@dc24521
jun 06, 2017 7:57:26 PM ar.edu.unt.jdbc.JdbcManager getCareerList
SEVERE: Error retrieving Career data
java.sql.SQLNonTransientConnectionException: No current connection.
    at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
    at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
    at org.apache.derby.client.am.Connection.createStatement(Unknown Source)
    at ar.edu.unt.jdbc.JdbcManager.getCareerList(JdbcManager.java:49)
    at ar.edu.unt.jdbc.JdbcManagerTest.testGetCareerList(JdbcManagerTest.java:71)
    ...
</code>```

I'm working with Netbeans where I have a running Derby DB where I can connect to (as I said, the connection works fine). As you can see by the stacktrace, the Exception is thrown in createStatement() but I cannot find the reason.

I've been diving in blogs and post but nothing worked for me. There was a post in some other forum where a user solved his problem by calling Thread.isInterrupted() because createStatement() is synchronized but didn't work for me as I'm using a single thread for my whole application (in fact, it must be an old post as the method seems not to be available in Java 8, just a similar method called Thread.interrupted() or something like that).

If you need more info on my application, let me know in your comments. Any help and/or guidance is appreciated.

答:
Your method createConnection is returning a closed connection. You are using a try-with-resources statement to create your connection. This means this connection will be automatically closed at exit of that block, no matter how it is exited (by exception, by return or just end of block).

When you subsequently try to create a statement, the driver reports that you don't have a connection (although the error message itself could be a little more clear).

In short, you should change createConnection to:

```<code>Connection createConnection(String configFilePath) {
    Properties connectionProperties = loadPropertiesFromFile(configFilePath);
    try {
        Class driverClass = Class.forName(connectionProperties.getProperty(JDBC_DRIVER_PROPERTY));
        LOG.log(Level.INFO, "Driver loaded: {0}", driverClass);
    } catch (ClassNotFoundException ex) {
        LOG.log(Level.SEVERE, "Driver not found”, ex);
    }

    try {
        Connection connection = DriverManager.getConnection(
            connectionProperties.getProperty(JDBC_URL_PROPERTY),
            connectionProperties.getProperty(JDBC_USER_PROPERTY),
            connectionProperties.getProperty(JDBC_PASSWORD_PROPERTY))
        LOG.log(Level.INFO, “Connection created: {0}", connection);
        return connection;
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, “Unable to connect to DB”, ex);
        return null;
    }
}
</code>```

BTW: returning null on exceptions is really asking for NullPointerException elsewhere. Consider just throwing the SQLException or creating your own exception.

On the other hand, in getCareerList you are not using try-with-resource, while you should, because once you fixed the problem with createConnection, you will be leaking resources by not closing them correctly in getCareerList. Change it to:

```<code>try (Connection connection = createConnection(PROPERTIES_FILE_PATH);
     Statement stmt = connection.createStatement();
     ResultSet rs = stmt.executeQuery(queryCareers)) {

    //... rest
} catch (SQLException e) {
    //... rest
}
</code>```

With this the result set, statement and connection will always be correctly closed.

Body:
I'm working in a desktop application where I need to connect to a database to retrieve some data and generate a report. For testing purposes, I created a test DB in Derby with the tables I need and some dummy data in them.

As it is a small app, I decided to work with plain JDBC to make it as lightweight as it can be.

I'm using TDD for developing. I've already tested the method for loading the connection properties from a file and the method for creating a connection to the DB. I got stuck when trying to query the data and populate the objects mapped to that data. This is my code:

public class JdbcManager {

    static final String JDBC_DRIVER_PROPERTY = "jdbc.driver";
    static final String JDBC_URL_PROPERTY = "jdbc.url";
    static final String JDBC_USER_PROPERTY = "jdbc.username";
    static final String JDBC_PASSWORD_PROPERTY = "jdbc.password";
    static String PROPERTIES_FILE_PATH = "src/main/resources/connection.properties";
    String queryCareers = "SELECT career, name FROM db_career”;

    private static final Logger LOG = Logger.getLogger(JdbcManager.class.getName());

    public List<Career> getCareerList() {
        List<Career> result = new ArrayList<>();
        Career item;
        Connection connection = createConnection(PROPERTIES_FILE_PATH);
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(queryCareers);

            while (rs.next()) {
                item = new Career(rs.getString("Career"), rs.getString("name"));
                result.add(item);
            }
        } catch (SQLException ex) {
            LOG.log(Level.SEVERE, “Error retrieving Career data”, ex);
        }

        return result;
    }

    // This method is working correctly according to my tests
    Connection createConnection(String configFilePath) {
        Properties connectionProperties = loadPropertiesFromFile(configFilePath);
        try {
            Class driverClass = Class.forName(connectionProperties.getProperty(JDBC_DRIVER_PROPERTY));
            LOG.log(Level.INFO, "Driver loaded: {0}", driverClass);
        } catch (ClassNotFoundException ex) {
            LOG.log(Level.SEVERE, "Driver not found”, ex);
        }

        try (Connection connection = DriverManager.getConnection(
                connectionProperties.getProperty(JDBC_URL_PROPERTY),
                connectionProperties.getProperty(JDBC_USER_PROPERTY),
                connectionProperties.getProperty(JDBC_PASSWORD_PROPERTY))) {
            LOG.log(Level.INFO, “Connection created: {0}", connection);
            return connection;
        } catch (SQLException ex) {
            LOG.log(Level.SEVERE, “Unable to connect to DB”, ex);
            return null;
        }
    }

    // This method is working correctly according to my tests
    Properties loadPropertiesFromFile(String configFilePath) {
        File configFile = new File(configFilePath);
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(configFile));
            LOG.log(Level.INFO, “Properties loaded: {0}", properties);
        } catch (FileNotFoundException ex) {
            LOG.log(Level.SEVERE, "File not found", ex);
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "Error reading the file", ex);
        }

        return properties;
    }

}

Then I have the failing test:

@Test
public void testGetCareerList() {
    logger.log(Level.INFO, "testGetCareerList():");
    List<Career> expectedResult = Arrays.asList(
            new Career("LGU", “Some dummy name 1”),
            new Career("TSGU", "Some dummy name 2”));

    // Change the location of the properties file to the testing one
    GestorJdbc.PROPERTIES_FILE_PATH = "src/test/resources/connectionTest.properties";

    List<Career> actualResult = jdbcManager.getCareerList();
    assertEquals(expectedResult, actualResult);
}

And finally the stacktrace when I execute the test:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running ar.edu.unt.jdbc.JdbcManagerTest
jun 06, 2017 7:57:24 PM ar.edu.unt.jdbc.JdbcManagerTest testGetCareerList
INFO: testGetCareerList():
jun 06, 2017 7:57:24 PM ar.edu.unt.jdbc.JdbcManager loadPropertiesFromFile
INFO: Properties loaded: {jdbc.url=jdbc:derby://localhost:1527/siu_test, jdbc.username=dba, jdbc.driver=org.apache.derby.jdbc.ClientDriver, jdbc.password=dba}
jun 06, 2017 7:57:24 PM ar.edu.unt.jdbc.JdbcManager createConnection
INFO: Driver loaded: class org.apache.derby.jdbc.ClientDriver
jun 06, 2017 7:57:26 PM ar.edu.unt.jdbc.JdbcManager createConnection
INFO: Connection created: org.apache.derby.client.net.NetConnection40@dc24521
jun 06, 2017 7:57:26 PM ar.edu.unt.jdbc.JdbcManager getCareerList
SEVERE: Error retrieving Career data
java.sql.SQLNonTransientConnectionException: No current connection.
    at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
    at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
    at org.apache.derby.client.am.Connection.createStatement(Unknown Source)
    at ar.edu.unt.jdbc.JdbcManager.getCareerList(JdbcManager.java:49)
    at ar.edu.unt.jdbc.JdbcManagerTest.testGetCareerList(JdbcManagerTest.java:71)
    ...

I'm working with Netbeans where I have a running Derby DB where I can connect to (as I said, the connection works fine). As you can see by the stacktrace, the Exception is thrown in createStatement() but I cannot find the reason.

I've been diving in blogs and post but nothing worked for me. There was a post in some other forum where a user solved his problem by calling Thread.isInterrupted() because createStatement() is synchronized but didn't work for me as I'm using a single thread for my whole application (in fact, it must be an old post as the method seems not to be available in Java 8, just a similar method called Thread.interrupted() or something like that).

If you need more info on my application, let me know in your comments. Any help and/or guidance is appreciated.

Body:
Your method createConnection is returning a closed connection. You are using a try-with-resources statement to create your connection. This means this connection will be automatically closed at exit of that block, no matter how it is exited (by exception, by return or just end of block).

When you subsequently try to create a statement, the driver reports that you don't have a connection (although the error message itself could be a little more clear).

In short, you should change createConnection to:

Connection createConnection(String configFilePath) {
    Properties connectionProperties = loadPropertiesFromFile(configFilePath);
    try {
        Class driverClass = Class.forName(connectionProperties.getProperty(JDBC_DRIVER_PROPERTY));
        LOG.log(Level.INFO, "Driver loaded: {0}", driverClass);
    } catch (ClassNotFoundException ex) {
        LOG.log(Level.SEVERE, "Driver not found”, ex);
    }

    try {
        Connection connection = DriverManager.getConnection(
            connectionProperties.getProperty(JDBC_URL_PROPERTY),
            connectionProperties.getProperty(JDBC_USER_PROPERTY),
            connectionProperties.getProperty(JDBC_PASSWORD_PROPERTY))
        LOG.log(Level.INFO, “Connection created: {0}", connection);
        return connection;
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, “Unable to connect to DB”, ex);
        return null;
    }
}

BTW: returning null on exceptions is really asking for NullPointerException elsewhere. Consider just throwing the SQLException or creating your own exception.

On the other hand, in getCareerList you are not using try-with-resource, while you should, because once you fixed the problem with createConnection, you will be leaking resources by not closing them correctly in getCareerList. Change it to:

try (Connection connection = createConnection(PROPERTIES_FILE_PATH);
     Statement stmt = connection.createStatement();
     ResultSet rs = stmt.executeQuery(queryCareers)) {

    //... rest
} catch (SQLException e) {
    //... rest
}

With this the result set, statement and connection will always be correctly closed.


问:
How can I get get params in url via slashes in Yii2?
I want to build url with get params via slashes.

For exapmle, I want this code:

```<code>Url::to(['/controller/action',
    'filter' => 'filter,
    'param1' => 'value1',
    'param2' => 'value2' ...]);
</code>```

to generate url:
//path.to.site/controller/action/filter/param1/value1/param2/value2...

Is there a way to make this via defaut urlManager?

答:
```<code>use Yii;
use yii\web\UrlRuleInterface;

class SearchUrlRule implements UrlRuleInterface
{

    public function parseRequest($manager, $request)
    {
        $pathInfo = $request->getPathInfo();

        if (strpos($pathInfo, 'somepath') !== 0) {
            return false;
        }

        $parameters = explode('/', $pathInfo);

        if ($parameters[1] !== 'f') {
            return false;
        }

        $route = 'controller/action';

        $params = [
            'filter' => 'f'
        ];
        $count = count($parameters);
        $i = 2;
        var_dump($parameters);
        while (($i + 1) < $count) {
            $params[$parameters[$i]] = $parameters[$i + 1];
            $i = $i + 2;
        }

        Yii::trace("Request parsed with URL rule: action/controller", __METHOD__);

        return [$route, $params];
    }

    public function createUrl($manager, $route, $params)
    {
        if ($route !== 'controller/action') {
            return false;
        }

        if ($params['filter'] !== 'f') {
            return false;
        }
        unset($params['filter']);

        //If a parameter is defined and not empty - add it to the URL
        $url = 'somepath/f/';

        foreach ($params as $k => $param) {
            $url .= "$k/" . $param;
        }

        return $url;
    }
}
</code>```

Here is code, that solved my problem. And in config:

```<code>        'rules' => [
            ...
            ['class' => 'frontend\components\SearchUrlRule'],
            ...
</code>```

Body:
I want to build url with get params via slashes.

For exapmle, I want this code:

Url::to(['/controller/action',
    'filter' => 'filter,
    'param1' => 'value1',
    'param2' => 'value2' ...]);

to generate url:
//path.to.site/controller/action/filter/param1/value1/param2/value2...

Is there a way to make this via defaut urlManager?

Body:
use Yii;
use yii\web\UrlRuleInterface;

class SearchUrlRule implements UrlRuleInterface
{

    public function parseRequest($manager, $request)
    {
        $pathInfo = $request->getPathInfo();

        if (strpos($pathInfo, 'somepath') !== 0) {
            return false;
        }

        $parameters = explode('/', $pathInfo);

        if ($parameters[1] !== 'f') {
            return false;
        }

        $route = 'controller/action';

        $params = [
            'filter' => 'f'
        ];
        $count = count($parameters);
        $i = 2;
        var_dump($parameters);
        while (($i + 1) < $count) {
            $params[$parameters[$i]] = $parameters[$i + 1];
            $i = $i + 2;
        }

        Yii::trace("Request parsed with URL rule: action/controller", __METHOD__);

        return [$route, $params];
    }

    public function createUrl($manager, $route, $params)
    {
        if ($route !== 'controller/action') {
            return false;
        }

        if ($params['filter'] !== 'f') {
            return false;
        }
        unset($params['filter']);

        //If a parameter is defined and not empty - add it to the URL
        $url = 'somepath/f/';

        foreach ($params as $k => $param) {
            $url .= "$k/" . $param;
        }

        return $url;
    }
}

Here is code, that solved my problem. And in config:

        'rules' => [
            ...
            ['class' => 'frontend\components\SearchUrlRule'],
            ...


问:
Getting world position to canvas position for Screen Space - Camera canvas
I'm trying to make a text display over a cube in Unity UI when I freely move my camera. The canvas is set to Screen Space - Camera mode and I set the camera property in the inspector. I have also attached a mouse move script to the camera.

My problem is that the text is barely moving and seems to ignore the position of the cube relative to the camera's viewport. Here is my code:

```<code>public class UpdateUiMarker : MonoBehaviour {

    public RectTransform element;
    public Transform cube;

    public RectTransform canvas;

    // Update is called once per frame
    void LateUpdate () {
        Vector2 screenPos = Camera.main.WorldToScreenPoint(cube.position);
        Vector2 localPos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, screenPos, Camera.main, out localPos);
        element.localPosition = localPos;
    }
}
</code>```

答:
```<code>void LateUpdate () {
        element.anchoredPosition = Input.mousePosition;
    }
</code>```

And set anchors of element to Vector2.zero for min and max.

Body:
I'm trying to make a text display over a cube in Unity UI when I freely move my camera. The canvas is set to Screen Space - Camera mode and I set the camera property in the inspector. I have also attached a mouse move script to the camera.

My problem is that the text is barely moving and seems to ignore the position of the cube relative to the camera's viewport. Here is my code:

public class UpdateUiMarker : MonoBehaviour {

    public RectTransform element;
    public Transform cube;

    public RectTransform canvas;

    // Update is called once per frame
    void LateUpdate () {
        Vector2 screenPos = Camera.main.WorldToScreenPoint(cube.position);
        Vector2 localPos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, screenPos, Camera.main, out localPos);
        element.localPosition = localPos;
    }
}

Body:
void LateUpdate () {
        element.anchoredPosition = Input.mousePosition;
    }

And set anchors of element to Vector2.zero for min and max.


问:
Recompile Linux Kernel not to use specific CPU register
I'm doing an experiment that write the index of loop into a CPU register R11, then building it with gcc -ffixed-r11 try to let compiler know do not use that reg, and finally using perf to measure it.

But when I check the report (using perf script), the R11 value of most record entry is not what I expected, it supposed to be the number sequence like 1..2..3 or 1..4..7, etc. But actually it just a few fixed value. (possibly affected by system call overwriting?)

How can I let perf records the value I set to the register in my program? Or I must to recompile the whole kernel with -ffixed-r11 to achieve?

Thanks everyone.

答:
If you need cycle accurate profile of to the metal CPU activity then perf is not the right tool, as it is at best an approximation due to the fact it only samples the program at select points. See this video on perf by Clang developer Chandler Carruth. </p>

<p>Instead, you should single step through the program in order to monitor exactly what is happening to the registers. Or you could program your system bare metal without an OS, but that is probably outside the scope here. </p>

Body:
If you need cycle accurate profile of to the metal CPU activity then perf is not the right tool, as it is at best an approximation due to the fact it only samples the program at select points. See this video on perf by Clang developer Chandler Carruth.

Instead, you should single step through the program in order to monitor exactly what is happening to the registers. Or you could program your system bare metal without an OS, but that is probably outside the scope here.


问:
How to delete duplicate entries?
I have to add a unique constraint to an existing table. This is fine except that the table has millions of rows already, and many of the rows violate the unique constraint I need to add.

What is the fastest approach to removing the offending rows? I have an SQL statement which finds the duplicates and deletes them, but it is taking forever to run. Is there another way to solve this problem? Maybe backing up the table, then restoring after the constraint is added?

答:
Some of these approaches seem a little complicated, and I generally do this as:

Given table table, want to unique it on (field1, field2) keeping the row with the max field3:

```<code>DELETE FROM table USING table alias
  WHERE table.field1 = alias.field1 AND table.field2 = alias.field2 AND
    table.max_field < alias.max_field
</code>```

For example, I have a table, user_accounts, and I want to add a unique constraint on email, but I have some duplicates. Say also that I want to keep the most recently created one (max id among duplicates).

```<code>DELETE FROM user_accounts USING user_accounts ua2
  WHERE user_accounts.email = ua2.email AND user_account.id < ua2.id;
</code>```

Note - USING is not standard SQL, it is a PostgreSQL extension (but a very useful one), but the original question specifically mentions PostgreSQL.

Title: How to delete duplicate entries?

Body:
Some of these approaches seem a little complicated, and I generally do this as:

Given table table, want to unique it on (field1, field2) keeping the row with the max field3:

DELETE FROM table USING table alias
  WHERE table.field1 = alias.field1 AND table.field2 = alias.field2 AND
    table.max_field < alias.max_field

For example, I have a table, user_accounts, and I want to add a unique constraint on email, but I have some duplicates. Say also that I want to keep the most recently created one (max id among duplicates).

DELETE FROM user_accounts USING user_accounts ua2
  WHERE user_accounts.email = ua2.email AND user_account.id < ua2.id;

Note - USING is not standard SQL, it is a PostgreSQL extension (but a very useful one), but the original question specifically mentions PostgreSQL.


问:
Docker1.12 Worker not able to join in cluster(Swarm: Pending)
Manager Version Docker version 1.12.0-rc5, build a3f2063,

Worker version Docker version 1.12.0-rc5, build a3f2063.

Created Swarm manger:

```<code>docker swarm init --advertise-addr "172.25.30.2:4243"

    Swarm initialized: current node (3kmewyb10p8xj3ke5rpjyw4s8) is now a manager.

    To add a worker to this swarm, run the following command:
        docker swarm join \
        --token SWMTKN-1-5lwzvv7au6hosiqqmdwmcxvmlmhtz4ts04jsg06284fq3posn0-enq26dqnwma38ij48hymtnioq \
        172.25.30.2:4243

    To add a manager to this swarm, run the following command:
        docker swarm join \
        --token SWMTKN-1-5lwzvv7au6hosiqqmdwmcxvmlmhtz4ts04jsg06284fq3posn0-85cwe5pf779qw0knjn6wxdbim \
        172.25.30.2:4243
</code>```

Then created worker

```<code>docker swarm join --token SWMTKN-1-5lwzvv7au6hosiqqmdwmcxvmlmhtz4ts04jsg06284fq3posn0-enq26dqnwma38ij48hymtnioq 172.25.30.2:4243
    Error response from daemon: Timeout was reached before node was joined. Attempt to join the cluster will continue in the background. Use "docker info" command to see the current swarm status of your node.
</code>```

I have checked logs in worker

```<code>time="2016-08-01T00:22:47.449844174-07:00" level=warning msg="failed to retrieve remote root CA certificate: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:22:47.449962215-07:00" level=warning msg="failed to retrieve remote root CA certificate: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:22:47.450025342-07:00" level=warning msg="failed to retrieve remote root CA certificate: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:22:47.450081950-07:00" level=warning msg="failed to retrieve remote root CA certificate: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:22:47.450142443-07:00" level=warning msg="failed to retrieve remote root CA certificate: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:22:47.450202836-07:00" level=error msg="cluster exited with error: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:23:31.351868722-07:00" level=error msg="Handler for POST /v1.24/swarm/join returned error: Timeout was reached before node was joined. Attempt to join the cluster will continue in the background. Use \"docker info\" command to see the current swarm status of your node."
</code>```

In docker info, I saw "Swarm: Pending"

I did docker swarm update also!. Still, the worker was not able to join the cluster. So, how can I reslove

UPDATE-1

Uninstalled & removed config files and then install docker 1.12 again with version Docker version 1.12.0, build 8eab29e.

Still facing the same problem(Not able to join and "Swarm:Pending" in docker info) with DIFFERENT error in /var/logs/upstat/docker.logs

```<code>time="2016-08-01T11:22:08.629760770-07:00" level=error msg="Handler for POST /v1.24/swarm/join returned error: Timeout was reached before node was joined. Attempt to join the cluster will continue in the background. Use \"docker info\" command to see the current swarm status of your node."
</code>```

Thanks.

答: I was facing similar issue, While in my case port was getting blocked due to firewall rule.</p>

Body:
Manager Version Docker version 1.12.0-rc5, build a3f2063,

Worker version Docker version 1.12.0-rc5, build a3f2063.

Created Swarm manger:

docker swarm init --advertise-addr "172.25.30.2:4243"

    Swarm initialized: current node (3kmewyb10p8xj3ke5rpjyw4s8) is now a manager.

    To add a worker to this swarm, run the following command:
        docker swarm join \
        --token SWMTKN-1-5lwzvv7au6hosiqqmdwmcxvmlmhtz4ts04jsg06284fq3posn0-enq26dqnwma38ij48hymtnioq \
        172.25.30.2:4243

    To add a manager to this swarm, run the following command:
        docker swarm join \
        --token SWMTKN-1-5lwzvv7au6hosiqqmdwmcxvmlmhtz4ts04jsg06284fq3posn0-85cwe5pf779qw0knjn6wxdbim \
        172.25.30.2:4243

Then created worker

docker swarm join --token SWMTKN-1-5lwzvv7au6hosiqqmdwmcxvmlmhtz4ts04jsg06284fq3posn0-enq26dqnwma38ij48hymtnioq 172.25.30.2:4243
    Error response from daemon: Timeout was reached before node was joined. Attempt to join the cluster will continue in the background. Use "docker info" command to see the current swarm status of your node.

I have checked logs in worker

time="2016-08-01T00:22:47.449844174-07:00" level=warning msg="failed to retrieve remote root CA certificate: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:22:47.449962215-07:00" level=warning msg="failed to retrieve remote root CA certificate: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:22:47.450025342-07:00" level=warning msg="failed to retrieve remote root CA certificate: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:22:47.450081950-07:00" level=warning msg="failed to retrieve remote root CA certificate: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:22:47.450142443-07:00" level=warning msg="failed to retrieve remote root CA certificate: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:22:47.450202836-07:00" level=error msg="cluster exited with error: rpc error: code = 1 desc = context canceled"
time="2016-08-01T00:23:31.351868722-07:00" level=error msg="Handler for POST /v1.24/swarm/join returned error: Timeout was reached before node was joined. Attempt to join the cluster will continue in the background. Use \"docker info\" command to see the current swarm status of your node."

In docker info, I saw "Swarm: Pending"

I did docker swarm update also!. Still, the worker was not able to join the cluster. So, how can I reslove

UPDATE-1

Uninstalled & removed config files and then install docker 1.12 again with version Docker version 1.12.0, build 8eab29e.

Still facing the same problem(Not able to join and "Swarm:Pending" in docker info) with DIFFERENT error in /var/logs/upstat/docker.logs

time="2016-08-01T11:22:08.629760770-07:00" level=error msg="Handler for POST /v1.24/swarm/join returned error: Timeout was reached before node was joined. Attempt to join the cluster will continue in the background. Use \"docker info\" command to see the current swarm status of your node."

Thanks.


问:
9-patch image error in Android
Whenever I try to add a 9-patch image to the \drawable folder in my project, I get the same error:

```<code>ERROR: 9-patch image C:\...\res\drawable\appwidget.9.png malformed.
Frame pixels must be either solid or transparent (not intermediate alphas).
Found at pixel #3 along top edge. Failure processing PNG image
C:\...\res\drawable\appwidget.9.png
</code>```

The weird thing in this example is that I've got this image from the "android-g1-icon" images found in the SDK resources, so it is supposed to be OK. The same happened with any 9-patch image I've tried so far. What could be wrong?

答:
I found the issue is about *.9.png files. Open and check all your 9-Patch files, make sure that all files have black 1 pixel wide border, if don't have, just click the white place and add it, then save it.

It's the only solution to my problem.

Title: 9-patch image error in Android

Body:
Whenever I try to add a 9-patch image to the \drawable folder in my project, I get the same error:

ERROR: 9-patch image C:\...\res\drawable\appwidget.9.png malformed.
Frame pixels must be either solid or transparent (not intermediate alphas).
Found at pixel #3 along top edge. Failure processing PNG image
C:\...\res\drawable\appwidget.9.png

The weird thing in this example is that I've got this image from the "android-g1-icon" images found in the SDK resources, so it is supposed to be OK. The same happened with any 9-patch image I've tried so far. What could be wrong?


问:
Login with google BAD_AUTHENTICATION issue
```<code>E/Auth: [GoogleAccountDataServiceImpl] getToken() -> BAD_AUTHENTICATION. Account: <ELLIDED:652354120>, App: com.google.android.apps.maps, Service: oauth2:https://www.googleapis.com/auth/mobilemaps.firstparty
                                           efl: Long live credential not available.
                                               at efm.b(:com.google.android.gms:3117)
                                               at efm.a(:com.google.android.gms:119)
                                               at edt.a(:com.google.android.gms:437)
                                               at eds.a(:com.google.android.gms:31404)
                                               at eds.a(:com.google.android.gms:297)
                                               at flg.a(:com.google.android.gms:1189)
                                               at flf.a(:com.google.android.gms:480)
                                               at flf.a(:com.google.android.gms:185)
                                               at eaa.a(:com.google.android.gms:370)
                                               at eaa.a(:com.google.android.gms:225)
                                               at bwf.onTransact(:com.google.android.gms:137)
                                               at android.os.Binder.transact(Binder.java:380)
                                               at byl.onTransact(:com.google.android.gms:35)
                                               at android.os.Binder.execTransact(Binder.java:446)
</code>```

I have added SHA1 to signed apk and replaced google-services.json with new one. After release on app store getting this issue when going to login with google.

答:
By enrolling Your application (“app”) in Google Play App Signing (GPAS) service,You consent to be bound by these terms,

Key Generation and Storage

1.1. GPAS is an optional service that provides a secure means of handling
  Your app signing key.

1.2. By enrolling Your existing app in GPAS, You agree to give Your
  existing app’s signing key to Google and to secure or delete Your copy(ies)
  of the key. For new apps, Google will generate a new app signing key for
  Your app.

1.3. You will have the ability to download and review any APKs you publish
  that are signed by Google.

You need to add SHA-1 fingerprint from App signing certificate to your fire base console also, this is the new update from google effective as of May 17th 2017.

Body:
E/Auth: [GoogleAccountDataServiceImpl] getToken() -> BAD_AUTHENTICATION. Account: <ELLIDED:652354120>, App: com.google.android.apps.maps, Service: oauth2:https://www.googleapis.com/auth/mobilemaps.firstparty
                                           efl: Long live credential not available.
                                               at efm.b(:com.google.android.gms:3117)
                                               at efm.a(:com.google.android.gms:119)
                                               at edt.a(:com.google.android.gms:437)
                                               at eds.a(:com.google.android.gms:31404)
                                               at eds.a(:com.google.android.gms:297)
                                               at flg.a(:com.google.android.gms:1189)
                                               at flf.a(:com.google.android.gms:480)
                                               at flf.a(:com.google.android.gms:185)
                                               at eaa.a(:com.google.android.gms:370)
                                               at eaa.a(:com.google.android.gms:225)
                                               at bwf.onTransact(:com.google.android.gms:137)
                                               at android.os.Binder.transact(Binder.java:380)
                                               at byl.onTransact(:com.google.android.gms:35)
                                               at android.os.Binder.execTransact(Binder.java:446)

I have added SHA1 to signed apk and replaced google-services.json with new one. After release on app store getting this issue when going to login with google.


问:
How to fetch data from SQL database using TruClient protocol
During my load test, I would like to fetch values from an SQL database. How can I achieve this on load runner TrueClient protocol using JavaScript?

This would be great help…

答:
Important: This will only work in TruClient (IE) and not in TruClient (Firefox).

Enter a new "Eveluate Javascript" step, and edit the javasctipt like so:

```<code>var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   // Here you should get the value from the 1st cell, 1st column
   var value = rs.fields(1);
   rs.movenext;
}

rs.close;
connection.close;
</code>```

Body:
Important: This will only work in TruClient (IE) and not in TruClient (Firefox).

Enter a new "Eveluate Javascript" step, and edit the javasctipt like so:

var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   // Here you should get the value from the 1st cell, 1st column
   var value = rs.fields(1);
   rs.movenext;
}

rs.close;
connection.close;