问:
Configure WSO2 Identity Server with Active Directory?
I am trying to stand up WSO2 Identity Server 5.0.0 with Active Directory as the primary user store.  I have connectivity, LDAPS, working database, etc. and can login to the admin console as the admin user I have chosen, and can successfully search for AD users and see roles.

However, if I try to show the details of a user, or change their password, I receive errors.  For example, when attempting to change password, I see in the logs:

```<code>TID: [0] [IS] [2016-04-15 16:14:15,135] ERROR
{org.wso2.carbon.user.mgt.ui.UserAdminClient} -  User testuser does
not exisit in the user store
{org.wso2.carbon.user.mgt.ui.UserAdminClient}
org.wso2.carbon.user.mgt.stub.UserAdminUserAdminException:
UserAdminUserAdminException
</code>```

but I have looked up this user and clicked the "change password" link in the resulting display, so it was able to at least find that user in the search.

I suspect that the AD roles of the user that I have configured for the LDAP connection are not sufficient to perform these tasks, but am unsure.  Am I on the right trail, and if so, what are the requirements for this user?  Or, is there something else to troubleshoot related to these errors?

UPDATE 4/18/2016:
OK when I added the debug suggested in an answer (log4j.logger.org.wso2.carbon.user.core=DEBUG), I noticed that the tool was searching for the user by CN and not finding it:

```<code>TID: [0] [IS] [2016-04-18 10:19:42,394] DEBUG {org.wso2.carbon.identity.mgt.IdentityMgtEventListener} -  Pre update credential by admin is called in IdentityMgtEventListener {org.wso2.carbon.identity.mgt.IdentityMgtEventListener}
TID: [0] [IS] [2016-04-18 10:19:42,394] DEBUG {org.wso2.carbon.identity.mgt.IdentityMgtEventListener} -  Updating credentials of user astudent16 by admin with a non-empty password {org.wso2.carbon.identity.mgt.IdentityMgtEventListener}
TID: [0] [IS] [2016-04-18 10:19:42,394] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Searching for user astudent16 {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:19:42,409] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Searching for user with SearchFilter: (&(objectClass=user)(cn=astudent16)) in SearchBase:  {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:19:42,472] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Name in space for astudent16 is null {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:19:42,472] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  User: astudent16 exist: false {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:19:42,487] ERROR {org.wso2.carbon.user.mgt.ui.UserAdminClient} -  User astudent16 does not exisit in the user store {org.wso2.carbon.user.mgt.ui.UserAdminClient}
org.wso2.carbon.user.mgt.stub.UserAdminUserAdminException: UserAdminUserAdminException
</code>```

I referred back to documentation, and the vendor documentation suggests that for Active Directory, the UserNameAttribute in user-mgt.xml be set to CN - we had this set to sAMAccountName.

So, we changed to CN, and now the error is different:

```<code>TID: [0] [IS] [2016-04-18 10:30:46,338] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Searching for user A Student16 {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:30:46,354] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Searching for user with SearchFilter: (&(objectClass=user)(cn=A Student16)) in SearchBase:  {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:30:46,354] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Name in space for A Student16 is CN=A Student16,OU=2016,OU=Students,OU=Accounts,DC=some,DC=org {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:30:46,354] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  User: A Student16 exist: true {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:30:46,463] DEBUG {org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager} -  value after escaping special characters in A Student16 : A Student16 {org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager}
TID: [0] [IS] [2016-04-18 10:30:46,463] DEBUG {org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager} -  Can not access the directory service for user : A Student16 {org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager}
javax.naming.NameNotFoundException: [LDAP: error code 32 - 0000208D: NameErr: DSID-03100238, problem 2001 (NO_OBJECT), data 0, best match of:
    'DC=some,DC=org'
 ]; remaining name 'CN=A Student16'
    at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3112)
</code>```

答:
I think I am having the same problem you are. I was able to get the password recovery to work for a user by changing the UserSearchBase so it fully referenced the OU for the user.

In our case we have users in:

```<code>OU=FacStaff,OU=People,DC=SomeCollege,DC=edu
OU=Students,OU=People,DC=SomeCollege,DC=edu
OU=Sysusers,OU=PrivUsers,DC=SomeCollege,DC=edu
</code>```

By specifying the full OU, the password recovery works for users in that OU, but users in any other OU cannot even log in.

I want to have my UserSearchBase set to DC=SomeCollege,DC=edu so it can search our whole tree, and this does work for authentication, but not anything where it has to write to Active Directory.

I can replicate the error by doing an ldapmodify with an ldif that leaves out part of the DN for a user, so I suspect the problem lies in the updateCredentialByAdmin function in that it is attempting to use the CN and UserSearchBase where it should be using the full DN.

I have also tried using multiple UserSearchBase entries, separating them with the hash character.  Again, it works for authentication, but not updates.

Body:
I am trying to stand up WSO2 Identity Server 5.0.0 with Active Directory as the primary user store.  I have connectivity, LDAPS, working database, etc. and can login to the admin console as the admin user I have chosen, and can successfully search for AD users and see roles.

However, if I try to show the details of a user, or change their password, I receive errors.  For example, when attempting to change password, I see in the logs:

TID: [0] [IS] [2016-04-15 16:14:15,135] ERROR
{org.wso2.carbon.user.mgt.ui.UserAdminClient} -  User testuser does
not exisit in the user store
{org.wso2.carbon.user.mgt.ui.UserAdminClient}
org.wso2.carbon.user.mgt.stub.UserAdminUserAdminException:
UserAdminUserAdminException

but I have looked up this user and clicked the "change password" link in the resulting display, so it was able to at least find that user in the search.

I suspect that the AD roles of the user that I have configured for the LDAP connection are not sufficient to perform these tasks, but am unsure.  Am I on the right trail, and if so, what are the requirements for this user?  Or, is there something else to troubleshoot related to these errors?

UPDATE 4/18/2016:
OK when I added the debug suggested in an answer (log4j.logger.org.wso2.carbon.user.core=DEBUG), I noticed that the tool was searching for the user by CN and not finding it:

TID: [0] [IS] [2016-04-18 10:19:42,394] DEBUG {org.wso2.carbon.identity.mgt.IdentityMgtEventListener} -  Pre update credential by admin is called in IdentityMgtEventListener {org.wso2.carbon.identity.mgt.IdentityMgtEventListener}
TID: [0] [IS] [2016-04-18 10:19:42,394] DEBUG {org.wso2.carbon.identity.mgt.IdentityMgtEventListener} -  Updating credentials of user astudent16 by admin with a non-empty password {org.wso2.carbon.identity.mgt.IdentityMgtEventListener}
TID: [0] [IS] [2016-04-18 10:19:42,394] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Searching for user astudent16 {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:19:42,409] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Searching for user with SearchFilter: (&(objectClass=user)(cn=astudent16)) in SearchBase:  {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:19:42,472] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Name in space for astudent16 is null {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:19:42,472] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  User: astudent16 exist: false {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:19:42,487] ERROR {org.wso2.carbon.user.mgt.ui.UserAdminClient} -  User astudent16 does not exisit in the user store {org.wso2.carbon.user.mgt.ui.UserAdminClient}
org.wso2.carbon.user.mgt.stub.UserAdminUserAdminException: UserAdminUserAdminException

I referred back to documentation, and the vendor documentation suggests that for Active Directory, the UserNameAttribute in user-mgt.xml be set to CN - we had this set to sAMAccountName.

So, we changed to CN, and now the error is different:

TID: [0] [IS] [2016-04-18 10:30:46,338] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Searching for user A Student16 {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:30:46,354] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Searching for user with SearchFilter: (&(objectClass=user)(cn=A Student16)) in SearchBase:  {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:30:46,354] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Name in space for A Student16 is CN=A Student16,OU=2016,OU=Students,OU=Accounts,DC=some,DC=org {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:30:46,354] DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  User: A Student16 exist: true {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
TID: [0] [IS] [2016-04-18 10:30:46,463] DEBUG {org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager} -  value after escaping special characters in A Student16 : A Student16 {org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager}
TID: [0] [IS] [2016-04-18 10:30:46,463] DEBUG {org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager} -  Can not access the directory service for user : A Student16 {org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager}
javax.naming.NameNotFoundException: [LDAP: error code 32 - 0000208D: NameErr: DSID-03100238, problem 2001 (NO_OBJECT), data 0, best match of:
    'DC=some,DC=org'
 ]; remaining name 'CN=A Student16'
    at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3112)

Body:
I think I am having the same problem you are. I was able to get the password recovery to work for a user by changing the UserSearchBase so it fully referenced the OU for the user.

In our case we have users in:

OU=FacStaff,OU=People,DC=SomeCollege,DC=edu
OU=Students,OU=People,DC=SomeCollege,DC=edu
OU=Sysusers,OU=PrivUsers,DC=SomeCollege,DC=edu

By specifying the full OU, the password recovery works for users in that OU, but users in any other OU cannot even log in.

I want to have my UserSearchBase set to DC=SomeCollege,DC=edu so it can search our whole tree, and this does work for authentication, but not anything where it has to write to Active Directory.

I can replicate the error by doing an ldapmodify with an ldif that leaves out part of the DN for a user, so I suspect the problem lies in the updateCredentialByAdmin function in that it is attempting to use the CN and UserSearchBase where it should be using the full DN.

I have also tried using multiple UserSearchBase entries, separating them with the hash character.  Again, it works for authentication, but not updates.


来源: stackexchange

问:
how to move x labels to be over facet labels in ggplot in R
I would like to move the facet labels (3, 4, 5) to underneath the x values (4, 6, 8).
My current code:

```<code>library(ggplot2)
ggplot(mtcars) + aes(factor(cyl), wt) +
geom_bar(stat = "summary", fun.y = "mean") +
facet_grid(~gear, switch = "x")
</code>```

currently, it looks like this:

I'm looking for something that looks like this:

答:
```<code>library(ggplot2)
ggplot(mtcars) + aes(factor(cyl), wt) +
geom_bar(stat = "summary", fun.y = "mean") +
facet_grid(~gear, switch = "x") +
theme(strip.placement = "outside")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to move the facet labels (3, 4, 5) to underneath the x values (4, 6, 8).
My current code:

library(ggplot2)
ggplot(mtcars) + aes(factor(cyl), wt) +
geom_bar(stat = "summary", fun.y = "mean") +
facet_grid(~gear, switch = "x")

currently, it looks like this:

I'm looking for something that looks like this:


问:
Modal/Dialog is opening at the bottom of the screen, and not behaving properly
Like the question says, my dialog is popping up on the bottom of the screen, rather than in the middle.  It also does not close on click, but rather whenever I hit escape.  The rest of the page is also not disabled or grayed out, so I can stack them up (see below).

I'm using basically the exact same code as in the example

```<code>import {Component} from '@angular/core';
import {MdDialog, MdDialogRef} from '@angular/material';

@Component({
    selector: 'dialog-overview-example',
    template: '<button md-button (click)="openDialog()">Open dialog</button>'
})
export class DialogOverviewExample {
    constructor(public dialog: MdDialog) {}

    public openDialog(): void {
        this.dialog.open(BasicDialog);
    }
}

@Component({
    selector: 'dialog-overview-example-dialog',
    template: "<p> Hi, I'm a dialog! </p>",
})
export class BasicDialog {}
</code>```

I think my imports are correct, but here they are:

```<code>imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(ROUTES, {useHash: true}),
    MdDialogModule,
    BrowserAnimationsModule,
    ReactiveFormsModule,
    FormsModule,
    CommonModule
],
</code>```

Note that there is no error or warning in the console, and I have tried disabling css.

Anyone seen this before?

答:
in the index.html add the following link to angular material</p>

```<code><link href="https://unpkg.com/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
</code>```

Body:
Like the question says, my dialog is popping up on the bottom of the screen, rather than in the middle.  It also does not close on click, but rather whenever I hit escape.  The rest of the page is also not disabled or grayed out, so I can stack them up (see below).

I'm using basically the exact same code as in the example

import {Component} from '@angular/core';
import {MdDialog, MdDialogRef} from '@angular/material';

@Component({
    selector: 'dialog-overview-example',
    template: '<button md-button (click)="openDialog()">Open dialog</button>'
})
export class DialogOverviewExample {
    constructor(public dialog: MdDialog) {}

    public openDialog(): void {
        this.dialog.open(BasicDialog);
    }
}

@Component({
    selector: 'dialog-overview-example-dialog',
    template: "
 Hi, I'm a dialog!
",
})
export class BasicDialog {}

I think my imports are correct, but here they are:

imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(ROUTES, {useHash: true}),
    MdDialogModule,
    BrowserAnimationsModule,
    ReactiveFormsModule,
    FormsModule,
    CommonModule
],

Note that there is no error or warning in the console, and I have tried disabling css.

Anyone seen this before?

Body:
in the index.html add the following link to angular material

<link href="https://unpkg.com/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">


问:
Un-expected output from is_numeric / foreach routine
Ref: http://php.net/manual/en/function.is-numeric.php.

Example #1 is_numeric().

Why does the Example #1 routine output 1337 4 times instead of 1 time?  My expectation is the routine would ouput the other 3 numeric values that follow 1337.  Even if I re-arrange the order of the elements it still outputs 1337 4 times.  I understand hex and binary values are not allowed, but why does the routine output 1337 for those values.  Also, if I change 1337 to 01337 the ouput is 735.

Why these confusing outputs?

```<code><?php
$tests = array(
    "42", 1337, 0x539, 02471, 0b10100111001, 1238.443e2, "not numeric",
    array(), 9.1, null
);

foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo var_export($element, true) . " is numeric", PHP_EOL;
    } else {
        echo var_export($element, true) . " is NOT numeric", PHP_EOL;
    }
}
?>

Output:
'42' is numeric
1337 is numeric
1337 is numeric
1337 is numeric
1337 is numeric
123844.300000000002910383045673370361328125 is numeric
'not numeric' is NOT numeric
array () is NOT numeric
9.0999999999999996447286321199499070644378662109375 is numeric
NULL is NOT numeric
</code>```

答:
Because that is your values.

For example, if you start a number with a zero, it is means, this number is in octal number system. 02471 = 1337 in decimal number system. The other is the hexa, the remaining the binary.

Body:
Ref: http://php.net/manual/en/function.is-numeric.php.

Example #1 is_numeric().

Why does the Example #1 routine output 1337 4 times instead of 1 time?  My expectation is the routine would ouput the other 3 numeric values that follow 1337.  Even if I re-arrange the order of the elements it still outputs 1337 4 times.  I understand hex and binary values are not allowed, but why does the routine output 1337 for those values.  Also, if I change 1337 to 01337 the ouput is 735.

Why these confusing outputs?

<?php
$tests = array(
    "42", 1337, 0x539, 02471, 0b10100111001, 1238.443e2, "not numeric",
    array(), 9.1, null
);

foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo var_export($element, true) . " is numeric", PHP_EOL;
    } else {
        echo var_export($element, true) . " is NOT numeric", PHP_EOL;
    }
}
?>

Output:
'42' is numeric
1337 is numeric
1337 is numeric
1337 is numeric
1337 is numeric
123844.300000000002910383045673370361328125 is numeric
'not numeric' is NOT numeric
array () is NOT numeric
9.0999999999999996447286321199499070644378662109375 is numeric
NULL is NOT numeric


问:
Syntax error on multiple join statement

Hello, I'm getting a syntax error on this sql statement, can anyone advise thanks

```<code>String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
    "FROM tblStudent LEFT JOIN tblSchool " +
    "ON (tblStudent.schoolID = tblSchool.schoolID) " +
    "LEFT JOIN tblAgents " +
    "ON (tblStudent.agentID = tblAgents.agentID) " +
    "WHERE tblStudent.StudentID='" + studentID + "'";
</code>```

I was hoping that I could do multiple joins

But I am getting a syntax error.

答:
I believe your final SQL should look like this:

```<code>SELECT tblStudent.*
    ,tblSchool.*
    ,tblAgents.*
FROM tblSchool
RIGHT JOIN (
    tblAgents RIGHT JOIN tblStudent ON tblAgents.agentID = tblStudent.agentID
    ) ON tblSchool.schoolID = tblStudent.schoolID
WHERE tblStudent.StudentID=111;
</code>```

So, the VBA code for creating this SQL should be

```<code>Dim sql As String

sql = "SELECT tblStudent.* ,tblSchool.* ,tblAgents.* " & _
    "FROM tblSchool RIGHT JOIN (" & _
    "tblAgents RIGHT JOIN tblStudent ON tblAgents.agentID = tblStudent.agentID" & _
    ") ON tblSchool.schoolID = tblStudent.schoolID " & _
    "WHERE tblStudent.StudentID=" & studentID
</code>```

Here I assume that studentID is numeric field. Also I would recommend to do not use * for selecting the data from more than one table, otherwise column names may be unpredictable and as mentioned in comments, it will require additional resources, which won't be used.

Title: Syntax error on multiple join statement

Body:
Hello, I'm getting a syntax error on this sql statement, can anyone advise thanks

String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
    "FROM tblStudent LEFT JOIN tblSchool " +
    "ON (tblStudent.schoolID = tblSchool.schoolID) " +
    "LEFT JOIN tblAgents " +
    "ON (tblStudent.agentID = tblAgents.agentID) " +
    "WHERE tblStudent.StudentID='" + studentID + "'";

I was hoping that I could do multiple joins

But I am getting a syntax error.

Body:
I believe your final SQL should look like this:

SELECT tblStudent.*
    ,tblSchool.*
    ,tblAgents.*
FROM tblSchool
RIGHT JOIN (
    tblAgents RIGHT JOIN tblStudent ON tblAgents.agentID = tblStudent.agentID
    ) ON tblSchool.schoolID = tblStudent.schoolID
WHERE tblStudent.StudentID=111;

So, the VBA code for creating this SQL should be

Dim sql As String

sql = "SELECT tblStudent.* ,tblSchool.* ,tblAgents.* " & _
    "FROM tblSchool RIGHT JOIN (" & _
    "tblAgents RIGHT JOIN tblStudent ON tblAgents.agentID = tblStudent.agentID" & _
    ") ON tblSchool.schoolID = tblStudent.schoolID " & _
    "WHERE tblStudent.StudentID=" & studentID

Here I assume that studentID is numeric field. Also I would recommend to do not use * for selecting the data from more than one table, otherwise column names may be unpredictable and as mentioned in comments, it will require additional resources, which won't be used.


问:
Parse usable Street Address, City, State, Zip from a string
Problem: I have an address field from an Access database which has been converted to SQL Server 2005. This field has everything all in one field. I need to parse out the address's individual sections into their appropriate fields in a normalized table. I need to do this for approximately 4,000 records, and it needs to be repeatable.

Assumptions:

Assume an address in the US (for now)

assume that the input string will sometimes contain an addressee (the person being addressed) and/or a second street address (i.e. Suite B)

states may be abbreviated

zip code could be standard 5 digits or zip+4

there are typos in some instances

UPDATE: In response to the questions posed, standards were not universally followed; I need need to store the individual values, not just geocode and errors means typo (corrected above)

Sample Data:

A. P. Croll & Son  2299 Lewes-Georgetown Hwy, Georgetown, DE 19947

11522 Shawnee Road, Greenwood DE  19950

144 Kings Highway, S.W. Dover, DE  19901

Intergrated Const. Services 2 Penns Way Suite 405 New Castle, DE  19720

Humes Realty 33 Bridle Ridge Court, Lewes, DE  19958

Nichols Excavation 2742 Pulaski Hwy Newark, DE  19711

2284 Bryn Zion Road, Smyrna, DE  19904

VEI Dover Crossroads, LLC  1500 Serpentine Road, Suite 100 Baltimore MD  21

580 North Dupont Highway Dover, DE  19901

P.O. Box 778 Dover, DE  19903

答: Since there is chance of error in word, think about using SOUNDEX combined with LCS algorithm to compare strings, this will help a lot !</p>

OwnerDisplayName: Rob Allen

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Remou

ContentLicense: CC BY-SA 2.5


问:
Garbage Collector overhead limit exceeded Caused By Array Creation

Hello,

My program spent a lot of Time creating Object in the Heap Memory , so at certain  Time i get this Error:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded

I can't Put my Full Application in this discussion So i created A prototype to explain what My program is doing.

The part of my program that deal with Creating Object looks as Follows:

```<code>**The Calling Program :**

public class Example {

public static void main(String[] args) {
        ArrayList list = new ArrayList();
        for (int i = 0; i < 5000; i++) {
            for (int j = 0; j < 5000; j++) {
                if (i==j)
                    continue;
                int weight = new Random().nextInt();
                Edge edge = new Edge(new Vertex(i+""), new Vertex(j+""),weight);
                list.add(edge);
            }
        }
  }
</code>```

}

The Class Vertex :

```<code>public class Vertex {
    private String sequence ;

    public Vertex() {
    }

    public Vertex(String seq) {
        this.sequence = seq;
    }

}
</code>```

The Class Edge :

```<code>public class Edge {

    private Vertex source;
    private Vertex destination;
    private int weight;

    public Edge() {

    }

    public Edge(Vertex source, Vertex destination, int weight) {
        int[][] array = new int[500][500];
        //here i need the array to do some calculation
        anotherClass.someCalculation(array,source,destination);
        this.source = source;
        this.destination = destination;
        this.weight = weight;

    }
}
</code>```

So as you can see:

I have 5000 Vertices , i need To create 5000*5000 Edges , each edge has An array of length 500*500.

For this reason the memory allocated in the Heap Memory end at certain time,the problem as i understood from many disctions I read is that there is no guaranty that the Garbage Collector Will free memory.

So what are the solution for this problem ? normally I don't Need The Edge's Array after constructing the Edge;the array is only needed during the construction of The Edges.

Another question : How can I minimize the Memory Utilisation in my Program ? I tried To turn the int array to char array but it didn't help.

Many Thanks

答:
Your program actually creates 2 * 5000 * 5000 vertices, i.e. a pair for each iteration of the inner (j) loop. I think that you need to first create 5k vertices and keep references to them in an array for when you are creating your edges.

I assume that the "array" variable is only needed for the calculation. If that is true, then use a local variable instead of a instance variable.  That way you don't keep 5k instances of that array--just one while you complete your calculation--reducing the memory usage.

Redefinition of the Edge class:

```<code>public class Edge {

private Vertex source;
private Vertex destination;
private int weight;
//private int  [][] array;  // don't keep an instance copy of this array if
                            // if it is not needed beyond the calculation.

public Edge() {

}

public Edge(Vertex source, Vertex destination, int weight) {
    int[][] array = new int[500][500];  // array will gc eligible after
                                        // constructor completes
    //here i need the array to do some calculation
    anotherClass.someCalculation(array,source,destination);
    this.source = source;
    this.destination = destination;
    this.weight = weight;

}
</code>```

}

Body:
Hello,

My program spent a lot of Time creating Object in the Heap Memory , so at certain  Time i get this Error:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded

I can't Put my Full Application in this discussion So i created A prototype to explain what My program is doing.

The part of my program that deal with Creating Object looks as Follows:

**The Calling Program :**

public class Example {

public static void main(String[] args) {
        ArrayList list = new ArrayList();
        for (int i = 0; i < 5000; i++) {
            for (int j = 0; j < 5000; j++) {
                if (i==j)
                    continue;
                int weight = new Random().nextInt();
                Edge edge = new Edge(new Vertex(i+""), new Vertex(j+""),weight);
                list.add(edge);
            }
        }
  }

}

The Class Vertex :

public class Vertex {
    private String sequence ;

    public Vertex() {
    }

    public Vertex(String seq) {
        this.sequence = seq;
    }

}

The Class Edge :

public class Edge {

    private Vertex source;
    private Vertex destination;
    private int weight;

    public Edge() {

    }

    public Edge(Vertex source, Vertex destination, int weight) {
        int[][] array = new int[500][500];
        //here i need the array to do some calculation
        anotherClass.someCalculation(array,source,destination);
        this.source = source;
        this.destination = destination;
        this.weight = weight;

    }
}

So as you can see:

I have 5000 Vertices , i need To create 5000*5000 Edges , each edge has An array of length 500*500.

For this reason the memory allocated in the Heap Memory end at certain time,the problem as i understood from many disctions I read is that there is no guaranty that the Garbage Collector Will free memory.

So what are the solution for this problem ? normally I don't Need The Edge's Array after constructing the Edge;the array is only needed during the construction of The Edges.

Another question : How can I minimize the Memory Utilisation in my Program ? I tried To turn the int array to char array but it didn't help.

Many Thanks

Body:
Your program actually creates 2 * 5000 * 5000 vertices, i.e. a pair for each iteration of the inner (j) loop. I think that you need to first create 5k vertices and keep references to them in an array for when you are creating your edges.

I assume that the "array" variable is only needed for the calculation. If that is true, then use a local variable instead of a instance variable.  That way you don't keep 5k instances of that array--just one while you complete your calculation--reducing the memory usage.

Redefinition of the Edge class:

public class Edge {

private Vertex source;
private Vertex destination;
private int weight;
//private int  [][] array;  // don't keep an instance copy of this array if
                            // if it is not needed beyond the calculation.

public Edge() {

}

public Edge(Vertex source, Vertex destination, int weight) {
    int[][] array = new int[500][500];  // array will gc eligible after
                                        // constructor completes
    //here i need the array to do some calculation
    anotherClass.someCalculation(array,source,destination);
    this.source = source;
    this.destination = destination;
    this.weight = weight;

}

}


问:
Telephony Manager getCi() for LTE help needed
I am very new to Android coding and have been having lots of fun till now. I am stuck with an issue using the telephony manager, specifically for LTE. My getCi() method returns a value, which is correct, but not in the format in which I need it to be. For example, the value returned is 25605. What code can I use to take this number and create the correct Node B ID and Cell ID value which is what I want my app to display?

```<code>TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);

    List<CellInfo> cellInfos = tm.getAllCellInfo();

    for(CellInfo cellInfo : cellInfos)
    {
        //CellInfoWcdma cellInfoWcdma = (CellInfoWcdma) cellInfo;
        CellInfoLte cellInfoLte = (CellInfoLte)cellInfo;
        //CellInfoGsm cellInfoGsm = (CellInfoGsm)cellInfo;

        //CellIdentityWcdma cellIdentityWcdma = cellInfoWcdma.getCellIdentity();
        //CellSignalStrengthWcdma cellSignalStrengthWcdma = cellInfoWcdma.getCellSignalStrength();
        CellIdentityLte cellIdentityLte = cellInfoLte.getCellIdentity();
        CellSignalStrengthLte cellSignalStrengthLte = cellInfoLte.getCellSignalStrength();

        netId = cellIdentityLte.getCi();
        netId2 = cellSignalStrengthLte.getLevel();
        //netId = cellIdentityWcdma.getCid() & 0xffff;
        //netId2 = cellSignalStrengthWcdma.getAsuLevel();
        //netId3 = netId2*2 -113;
</code>```

nter code here

答:
The value of cellIdentityLte.getCi() you have to convert to HEX.

Then the last two symbols you convert to DEC and this is the Local Cell ID.

The rest (except the last two symbols) you convert to DEC and this is the eNodeB.

I don't know Java, but here it is with Excel formulas. I think you'll get the logic

```<code>eNodeB =HEX2DEC(LEFT(DEC2HEX(E2),LEN(DEC2HEX(E2))-2))
Local_Cell_ID =HEX2DEC(RIGHT(DEC2HEX(E2),2))
</code>```

where E2 is the output of cellIdentityLte.getCi()

I have tested this and checked the cell configuration. The values are the same.

Body:
I am very new to Android coding and have been having lots of fun till now. I am stuck with an issue using the telephony manager, specifically for LTE. My getCi() method returns a value, which is correct, but not in the format in which I need it to be. For example, the value returned is 25605. What code can I use to take this number and create the correct Node B ID and Cell ID value which is what I want my app to display?

TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);

    List<CellInfo> cellInfos = tm.getAllCellInfo();

    for(CellInfo cellInfo : cellInfos)
    {
        //CellInfoWcdma cellInfoWcdma = (CellInfoWcdma) cellInfo;
        CellInfoLte cellInfoLte = (CellInfoLte)cellInfo;
        //CellInfoGsm cellInfoGsm = (CellInfoGsm)cellInfo;

        //CellIdentityWcdma cellIdentityWcdma = cellInfoWcdma.getCellIdentity();
        //CellSignalStrengthWcdma cellSignalStrengthWcdma = cellInfoWcdma.getCellSignalStrength();
        CellIdentityLte cellIdentityLte = cellInfoLte.getCellIdentity();
        CellSignalStrengthLte cellSignalStrengthLte = cellInfoLte.getCellSignalStrength();

        netId = cellIdentityLte.getCi();
        netId2 = cellSignalStrengthLte.getLevel();
        //netId = cellIdentityWcdma.getCid() & 0xffff;
        //netId2 = cellSignalStrengthWcdma.getAsuLevel();
        //netId3 = netId2*2 -113;

nter code here

Body:
The value of cellIdentityLte.getCi() you have to convert to HEX.

Then the last two symbols you convert to DEC and this is the Local Cell ID.

The rest (except the last two symbols) you convert to DEC and this is the eNodeB.

I don't know Java, but here it is with Excel formulas. I think you'll get the logic

eNodeB =HEX2DEC(LEFT(DEC2HEX(E2),LEN(DEC2HEX(E2))-2))
Local_Cell_ID =HEX2DEC(RIGHT(DEC2HEX(E2),2))

where E2 is the output of cellIdentityLte.getCi()

I have tested this and checked the cell configuration. The values are the same.


问:
Passing String Arrays to Functions?

I'm not sure what I'm doing wrong. I'm trying to pass the array people to the function getInformation and have it so stuff (eventually it will ask for the names of people and their salaries but I can't seem to get the function to take the array as a parameter?

```<code>using System;

class SalesPeeps {

    string[] people = new string[8];
    double[] salaries = new double[8];

    static void Main() {

        getInformation(people);

    }

    static void getInformation(string[] arr) {

        int i = 0;

        do {

            Console.WriteLine("Please input a the sales person's last name.");
            i++;

        } while (i < people.Length);

    }
}
</code>```

答:
1) string[] people = new string[8];
is a field - not local variable. so when you say people - you are actually mean this.people but in static method there is no this.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members

2) getInformation method use arr array as a parameter but do not reference to it. You can use people and make it static this will also fix problem from point 1.

I think this can be corrected this way:

```<code>class SalesPeeps
{

    static string[] people = new string[8];
    static double[] salaries = new double[8];

    static void Main()
    {
        getInformation();
    }

    static void getInformation()
    {
        int i = 0;
        do
        {

            Console.WriteLine("Please input a the sales person's last name.");
            i++;

        } while (i < people.Length);

    }
}
</code>```

Title: Passing String Arrays to Functions?

Body:
I'm not sure what I'm doing wrong. I'm trying to pass the array people to the function getInformation and have it so stuff (eventually it will ask for the names of people and their salaries but I can't seem to get the function to take the array as a parameter?

using System;

class SalesPeeps {

    string[] people = new string[8];
    double[] salaries = new double[8];

    static void Main() {

        getInformation(people);

    }

    static void getInformation(string[] arr) {

        int i = 0;

        do {

            Console.WriteLine("Please input a the sales person's last name.");
            i++;

        } while (i < people.Length);

    }
}

Body:
1) string[] people = new string[8];
is a field - not local variable. so when you say people - you are actually mean this.people but in static method there is no this.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members

2) getInformation method use arr array as a parameter but do not reference to it. You can use people and make it static this will also fix problem from point 1.

I think this can be corrected this way:

class SalesPeeps
{

    static string[] people = new string[8];
    static double[] salaries = new double[8];

    static void Main()
    {
        getInformation();
    }

    static void getInformation()
    {
        int i = 0;
        do
        {

            Console.WriteLine("Please input a the sales person's last name.");
            i++;

        } while (i < people.Length);

    }
}


问:
Pandas merge issue on key of object type containing number and string values
I have two dataframes df1 and df2 as shown below:-

```<code>df1 = pd.DataFrame({'x': [1, '3', 5,'t','m','u'],'y':[2, 4, 6, 4, 4, 8]})

df2 = pd.DataFrame({'x': [1, 3, '4','t'],'z':[2, 4, 6,7]})
</code>```

I am trying to merge(left join) the two data frames as:-

```<code>df=pd.merge(df1, df2, how='left', on='x')
</code>```

the output is:-

```<code>df
Out[25]:
   x  y    z
0  1  2  2.0
1  3  4  NaN
2  5  6  NaN
3  t  4  7.0
4  m  4  NaN
5  u  8  NaN
</code>```

Clearly for second row above i.e for x=3, I would like to have z=4 instead of NaN.Is there an option to define data type of the key during merge or any other workaround where I can change the dtype of the keys to string in both data frames and get the desired output.

答:
Your df1 and df2 ,have different dtype for 3 one is numeric another is str, so we convert them all to string they can get match</p>

```<code>df=pd.merge(df1.astype(str), df2.astype(str), how='left', on='x')
df
Out[914]:
   x  y    z
0  1  2    2
1  3  4    4
2  5  6  NaN
3  t  4    7
4  m  4  NaN
5  u  8  NaN
</code>```

Body:
I have two dataframes df1 and df2 as shown below:-

df1 = pd.DataFrame({'x': [1, '3', 5,'t','m','u'],'y':[2, 4, 6, 4, 4, 8]})

df2 = pd.DataFrame({'x': [1, 3, '4','t'],'z':[2, 4, 6,7]})

I am trying to merge(left join) the two data frames as:-

df=pd.merge(df1, df2, how='left', on='x')

the output is:-

df
Out[25]:
   x  y    z
0  1  2  2.0
1  3  4  NaN
2  5  6  NaN
3  t  4  7.0
4  m  4  NaN
5  u  8  NaN

Clearly for second row above i.e for x=3, I would like to have z=4 instead of NaN.Is there an option to define data type of the key during merge or any other workaround where I can change the dtype of the keys to string in both data frames and get the desired output.

Body:
Your df1 and df2 ,have different dtype for 3 one is numeric another is str, so we convert them all to string they can get match

df=pd.merge(df1.astype(str), df2.astype(str), how='left', on='x')
df
Out[914]:
   x  y    z
0  1  2    2
1  3  4    4
2  5  6  NaN
3  t  4    7
4  m  4  NaN
5  u  8  NaN


问:
Get form data in React
I have a simple form in my render function, like so:

```<code>render : function() {
      return (
        <form>
          <input type="text" name="email" placeholder="Email" />
          <input type="password" name="password" placeholder="Password" />
          <button type="button" onClick={this.handleLogin}>Login</button>
        </form>
      );
    },
handleLogin: function() {
   // How can I access email and password here?
}
</code>```

What should I write in my handleLogin: function() { ... } to access Email and Password fields?

答:
There are a few ways to do this:

1) Get values from array of form elements by index

```<code>handleSubmit = (event) => {
  event.preventDefault();
  console.log(event.target[0].value)
}
</code>```

2) Using name attribute in html

```<code>handleSubmit = (event) => {
  event.preventDefault();
  console.log(event.target.elements.username.value) // from elements property
  console.log(event.target.username.value)          // or directly
}

<input type="text" name="username"/>
</code>```

3) Using refs

```<code>handleSubmit = (event) => {
  console.log(this.inputNode.value)
}

<input type="text" name="username" ref={node => (this.inputNode = node)}/>
</code>```

Full example

```<code>class NameForm extends React.Component {
  handleSubmit = (event) => {
    event.preventDefault()
    console.log(event.target[0].value)
    console.log(event.target.elements.username.value)
    console.log(event.target.username.value)
    console.log(this.inputNode.value)
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input
            type="text"
            name="username"
            ref={node => (this.inputNode = node)}
          />
        </label>
        <button type="submit">Submit</button>
      </form>
    )
  }
}
</code>```

Title: Get form data in React

Body:
I have a simple form in my render function, like so:

render : function() {
      return (
        <form>
          <input type="text" name="email" placeholder="Email" />
          <input type="password" name="password" placeholder="Password" />
          <button type="button" onClick={this.handleLogin}>Login</button>
        </form>
      );
    },
handleLogin: function() {
   // How can I access email and password here?
}

What should I write in my handleLogin: function() { ... } to access Email and Password fields?

Body:
There are a few ways to do this:

1) Get values from array of form elements by index

handleSubmit = (event) => {
  event.preventDefault();
  console.log(event.target[0].value)
}

2) Using name attribute in html

handleSubmit = (event) => {
  event.preventDefault();
  console.log(event.target.elements.username.value) // from elements property
  console.log(event.target.username.value)          // or directly
}

<input type="text" name="username"/>

3) Using refs

handleSubmit = (event) => {
  console.log(this.inputNode.value)
}

<input type="text" name="username" ref={node => (this.inputNode = node)}/>

Full example

class NameForm extends React.Component {
  handleSubmit = (event) => {
    event.preventDefault()
    console.log(event.target[0].value)
    console.log(event.target.elements.username.value)
    console.log(event.target.username.value)
    console.log(this.inputNode.value)
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input
            type="text"
            name="username"
            ref={node => (this.inputNode = node)}
          />
        </label>
        <button type="submit">Submit</button>
      </form>
    )
  }
}


问:
Python string join performance
There are a lot of articles around the web concerning Python performance. The first thing you read is concatenating strings should not be done using '+'; avoid s1 + s2 + s3, and instead use str.join

I tried the following: concatenating two strings as part of a directory path: three approaches:

'+' which I should not do

str.join

os.path.join

Here is my code:

```<code>import os, time

s1 = '/part/one/of/dir'
s2 = 'part/two/of/dir'
N = 10000

t = time.clock()
for i in xrange(N):
    s = s1 + os.sep + s2
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.sep.join((s1, s2))
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.path.join(s1, s2)
print time.clock() - t
</code>```

Here the results (Python 2.5 on Windows XP):

0.0182201927899
0.0262544541275
0.120238186697
```

Shouldn't it be exactly the other way around?

答:
Most of the performance issues with string concatenation are ones of asymptotic performance, so the differences become most significant when you are concatenating many long strings.

In your sample, you are performing the same concatenation many times. You aren't building up any long string, and it may be that the Python interpreter is optimizing your loops. This would explain why the time increases when you move to str.join and path.join - they are more complex functions that are not as easily reduced. (os.path.join does a lot of checking on the strings to see if they need to be rewritten in any way before they are concatenated. This sacrifices some performance for the sake of portability.)

By the way, since file paths are not usually very long, you almost certainly want to use os.path.join for the sake of the portability. If the performance of the concatenation is a problem, you're doing something very odd with your filesystem.

OwnerDisplayName: Danny

Title: Python string join performance

Body:
There are a lot of articles around the web concerning Python performance. The first thing you read is concatenating strings should not be done using '+'; avoid s1 + s2 + s3, and instead use str.join

I tried the following: concatenating two strings as part of a directory path: three approaches:

'+' which I should not do

str.join

os.path.join

Here is my code:

import os, time

s1 = '/part/one/of/dir'
s2 = 'part/two/of/dir'
N = 10000

t = time.clock()
for i in xrange(N):
    s = s1 + os.sep + s2
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.sep.join((s1, s2))
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.path.join(s1, s2)
print time.clock() - t

Here the results (Python 2.5 on Windows XP):

0.0182201927899
0.0262544541275
0.120238186697

Shouldn't it be exactly the other way around?

LastEditorDisplayName: Danny


问:
How to keep up to date with Facebook APIs?
Somehow I have the feeling that I am not the only one scratching my head with FB documentation. There seems to be quite a lot of overlapping features in APIs and I cannot tell whether something is going to be deprecated or not.

How can I find the current best practices? And any recommendations of FB technology blogs etc?

答:
Just found this:

http://developers.facebook.com/roadmap


问:
Jersey restful web service - File upload with multiple object
I'm new to web service and I'm developing a document management system and trying to save the file and multiple object using Jersey restful web service.

```<code>import java.awt.Image;
import java.io.InputStream;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sasianet.dmsservice.data.dao.UserDocumentDao;
import com.sasianet.dmsservice.data.entity.UserDocument;
import com.sasianet.dmsservice.data.entity.UserDocumentAttachment;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("/userDocument")
public class UserDocumentService {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<UserDocument> findAll(){
        List<UserDocument> userDocuments = null;
        try{
            UserDocumentDao udo = new UserDocumentDao();
            userDocuments = udo.findAll();
        }catch(Exception e){
            e.printStackTrace();
        }
        return userDocuments;
    }

    @POST
    @Path("/post/test")
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    public Response uploadFileWithData(
            @FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition cdh,
            @FormDataParam("userDoc") UserDocument userDocument,
            @FormDataParam("attachment") UserDocumentAttachment userDocumentAttachment) throws Exception{

        Image img = ImageIO.read(fileInputStream);
        JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(img)));
        System.out.println(cdh.getName());
        System.out.println(userDocument.getDescription());
        System.out.println(userDocumentAttachment.getAttachmentName());

        return Response.ok("Cool Tools!").build();
    }
}
</code>```

My web.xml

```<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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" metadata-complete="true" version="3.0">
    <display-name>DMSService</display-name>
    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.sasianet.dmsservice, com.fasterxml.jackson.jaxrs.json,com.jersey.jaxb</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>jersey.media.type.mappings</param-name>
        <param-value>json : application/json, xml : application/xml</param-value>
    </context-param>

</web-app>
</code>```

Once run this service,  I faced the following error

```<code>org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type public javax.ws.rs.core.Response com.sasianet.dmsservice.service.UserDocumentService.uploadFileWithData(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition,com.sasianet.dmsservice.data.entity.UserDocument) throws java.lang.Exception at index 0.; source='ResourceMethod{httpMethod=POST, consumedTypes=[multipart/form-data], producedTypes=[], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class com.sasianet.dmsservice.service.UserDocumentService, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@53d69bbb]}, definitionMethod=public javax.ws.rs.core.Response com.sasianet.dmsservice.service.UserDocumentService.uploadFileWithData(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition,com.sasianet.dmsservice.data.entity.UserDocument) throws java.lang.Exception, parameters=[Parameter [type=class java.io.InputStream, source=file, defaultValue=null], Parameter [type=class com.sun.jersey.core.header.FormDataContentDisposition, source=file, defaultValue=null], Parameter [type=class com.sasianet.dmsservice.data.entity.UserDocument, source=emp, defaultValue=null]], responseType=class javax.ws.rs.core.Response}, nameBindings=[]}', [WARNING] A resource, Resource{"/file", 0 child resources, 0 resource methods, 0 sub-resource locator, 0 method handler classes, 0 method handler instances}, with path "/file" is empty. It has no resource (or sub resource) methods neither sub resource locators defined.; source='Resource{"/file", 0 child resources, 0 resource methods, 0 sub-resource locator, 0 method handler classes, 0 method handler instances}']
</code>```

Project libraries are

So, I cant find any solution to this and is there any different way to upload file with multiple object with one rest call.

Please guide me on this.

答:
You're using the wrong version multipart dependency. Anytime you see com.sun.jersey in the package, that is for Jersey 1.x, and you should not use it for a 2.x project. You will need to switch versions and then register the MultiPartFeature. For more information, see MULTIPART_FORM_DATA: No injection source found for a parameter of type public javax.ws.rs.core.Response

Unless the client is able to set the Content-Type for each body part (some clients can't), you will need to tweak the method a little bit, in order to get the result an object. For example

```<code>public Response post(@FormDataParam("doc") FormDataBodyPart docpart) {
    docpart.setMediaType(MediaType.APPLICATION_JSON_TYPE);
    UserDocument doc = docpart.getValueAs(UserDocument.class);
}
</code>```

For the InputStream parameter, you don't need to do this. For more detail, see File upload along with other object in Jersey restful web service

Body:
I'm new to web service and I'm developing a document management system and trying to save the file and multiple object using Jersey restful web service.

import java.awt.Image;
import java.io.InputStream;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sasianet.dmsservice.data.dao.UserDocumentDao;
import com.sasianet.dmsservice.data.entity.UserDocument;
import com.sasianet.dmsservice.data.entity.UserDocumentAttachment;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("/userDocument")
public class UserDocumentService {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<UserDocument> findAll(){
        List<UserDocument> userDocuments = null;
        try{
            UserDocumentDao udo = new UserDocumentDao();
            userDocuments = udo.findAll();
        }catch(Exception e){
            e.printStackTrace();
        }
        return userDocuments;
    }

    @POST
    @Path("/post/test")
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    public Response uploadFileWithData(
            @FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition cdh,
            @FormDataParam("userDoc") UserDocument userDocument,
            @FormDataParam("attachment") UserDocumentAttachment userDocumentAttachment) throws Exception{

        Image img = ImageIO.read(fileInputStream);
        JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(img)));
        System.out.println(cdh.getName());
        System.out.println(userDocument.getDescription());
        System.out.println(userDocumentAttachment.getAttachmentName());

        return Response.ok("Cool Tools!").build();
    }
}

My web.xml

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" metadata-complete="true" version="3.0">
    <display-name>DMSService</display-name>
    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.sasianet.dmsservice, com.fasterxml.jackson.jaxrs.json,com.jersey.jaxb</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>jersey.media.type.mappings</param-name>
        <param-value>json : application/json, xml : application/xml</param-value>
    </context-param>

</web-app>

Once run this service,  I faced the following error

org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type public javax.ws.rs.core.Response com.sasianet.dmsservice.service.UserDocumentService.uploadFileWithData(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition,com.sasianet.dmsservice.data.entity.UserDocument) throws java.lang.Exception at index 0.; source='ResourceMethod{httpMethod=POST, consumedTypes=[multipart/form-data], producedTypes=[], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class com.sasianet.dmsservice.service.UserDocumentService, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@53d69bbb]}, definitionMethod=public javax.ws.rs.core.Response com.sasianet.dmsservice.service.UserDocumentService.uploadFileWithData(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition,com.sasianet.dmsservice.data.entity.UserDocument) throws java.lang.Exception, parameters=[Parameter [type=class java.io.InputStream, source=file, defaultValue=null], Parameter [type=class com.sun.jersey.core.header.FormDataContentDisposition, source=file, defaultValue=null], Parameter [type=class com.sasianet.dmsservice.data.entity.UserDocument, source=emp, defaultValue=null]], responseType=class javax.ws.rs.core.Response}, nameBindings=[]}', [WARNING] A resource, Resource{"/file", 0 child resources, 0 resource methods, 0 sub-resource locator, 0 method handler classes, 0 method handler instances}, with path "/file" is empty. It has no resource (or sub resource) methods neither sub resource locators defined.; source='Resource{"/file", 0 child resources, 0 resource methods, 0 sub-resource locator, 0 method handler classes, 0 method handler instances}']

Project libraries are

So, I cant find any solution to this and is there any different way to upload file with multiple object with one rest call.

Please guide me on this.

Body:
You're using the wrong version multipart dependency. Anytime you see com.sun.jersey in the package, that is for Jersey 1.x, and you should not use it for a 2.x project. You will need to switch versions and then register the MultiPartFeature. For more information, see MULTIPART_FORM_DATA: No injection source found for a parameter of type public javax.ws.rs.core.Response

Unless the client is able to set the Content-Type for each body part (some clients can't), you will need to tweak the method a little bit, in order to get the result an object. For example

public Response post(@FormDataParam("doc") FormDataBodyPart docpart) {
    docpart.setMediaType(MediaType.APPLICATION_JSON_TYPE);
    UserDocument doc = docpart.getValueAs(UserDocument.class);
}

For the InputStream parameter, you don't need to do this. For more detail, see File upload along with other object in Jersey restful web service


问:
Why during conversion YUV_420_888 to RGBA_8888 in Android NDK image rotate 90 degree?
I'm making a conversion in the native method from imagereader to yug format to Rgba format through this method in NDK:

```<code>size_t bufferSize = buffer.width * buffer.height * (size_t)4;
uint8_t * outPtr = reinterpret_cast<uint8_t *>(buffer.bits);
for (size_t y = 0; y < srcHeight; y++)
{
    uint8_t * Y_rowPtr = srcYPtr + y * Y_rowStride;
    uint8_t * U_rowPtr = srcUPtr + (y >> 1) * U_rowStride;
    uint8_t * V_rowPtr = srcVPtr + (y >> 1) * V_rowStride;

    for (size_t x = 0; x < srcWidth; x++)
    {
        uint8_t Y = Y_rowPtr[x];
        uint8_t U = U_rowPtr[(x >> 1)];
        uint8_t V = V_rowPtr[(x >> 1)];

        double R = (Y + (V - 128) * 1.40625);
        double G = (Y - (U - 128) * 0.34375 - (V - 128) * 0.71875);
        double B = (Y + (U - 128) * 1.765625);

        *(outPtr + (--bufferSize)) = 255; // gamma for RGBA_8888
        *(outPtr + (--bufferSize)) = (uint8_t) (B > 255 ? 255 : (B < 0 ? 0 : B));
        *(outPtr + (--bufferSize)) = (uint8_t) (G > 255 ? 255 : (G < 0 ? 0 : G));
        *(outPtr + (--bufferSize)) = (uint8_t) (R > 255 ? 255 : (R < 0 ? 0 : R));

    }
}
</code>```

Why is the image rotated 90 degrees?

UPDATE:

I use this conversion:
https://www.fourcc.org/fccyvrgb.php
but the image remains rotated from the original of 90.

UPDATE2:

```<code>       @Override
    public void onImageAvailable(ImageReader reader) {
        // ottiene il nuovo frame
        Image image = reader.acquireNextImage();

        if (image == null) {
            return;
        }

        //preparazione per RGBA output
        Image.Plane Y_plane = image.getPlanes()[0];
        int Y_rowStride = Y_plane.getRowStride();
        Image.Plane U_plane = image.getPlanes()[1];
        int UV_rowStride = U_plane.getRowStride();  //nelle immagini YUV, uPlane.getRowStride() == vPlane.getRowStride()
        Image.Plane V_plane = image.getPlanes()[2];
        JNIUtils.RGBADisplay(image.getWidth(), image.getHeight(), Y_rowStride, Y_plane.getBuffer(), UV_rowStride, U_plane.getBuffer(), UV_rowStride, V_plane.getBuffer(), surface);

        image.close();
    }
</code>```

UPDATE 3: Code into native.cpp

```<code>Java_com_ndkvideoimagecapture_JNIUtils_RGBADisplay(
    JNIEnv *env, //env per consentire il passaggio di dati per riferimento
    jobject obj,
    jint srcWidth,
    jint srcHeight,
    jint Y_rowStride,
    jobject Y_Buffer,
    jint U_rowStride,
    jobject U_Buffer,
    jint V_rowStride,
    jobject V_Buffer,
    jobject surface) {

uint8_t *srcYPtr = reinterpret_cast<uint8_t *>(env->GetDirectBufferAddress(Y_Buffer));
uint8_t *srcUPtr = reinterpret_cast<uint8_t *>(env->GetDirectBufferAddress(U_Buffer));
uint8_t *srcVPtr = reinterpret_cast<uint8_t *>(env->GetDirectBufferAddress(V_Buffer));

ANativeWindow *window = ANativeWindow_fromSurface(env, surface);
ANativeWindow_acquire(window);
ANativeWindow_Buffer buffer;

ANativeWindow_setBuffersGeometry(window, srcWidth, srcHeight, WINDOW_FORMAT_RGBA_8888);

if (int32_t err = ANativeWindow_lock(window, &buffer, NULL)) {
    LOGE("ANativeWindow_lock failed with error code: %d\n", err);
    ANativeWindow_release(window);
}

    size_t bufferSize = buffer.width * buffer.height * (size_t)4;
uint8_t * outPtr = reinterpret_cast<uint8_t *>(buffer.bits);
for (size_t y = 0; y < srcHeight; y++)
{
    uint8_t * Y_rowPtr = srcYPtr + y * Y_rowStride;
    uint8_t * U_rowPtr = srcUPtr + (y >> 1) * U_rowStride;
    uint8_t * V_rowPtr = srcVPtr + (y >> 1) * V_rowStride;

    for (size_t x = 0; x < srcWidth; x++)
    {
        uint8_t Y = Y_rowPtr[x];
        uint8_t U = U_rowPtr[(x >> 1)];
        uint8_t V = V_rowPtr[(x >> 1)];

        double R = (Y + (V - 128) * 1.40625);
        double G = (Y - (U - 128) * 0.34375 - (V - 128) * 0.71875);
        double B = (Y + (U - 128) * 1.765625);

        *(outPtr + (--bufferSize)) = 255; // gamma for RGBA_8888
        *(outPtr + (--bufferSize)) = (uint8_t) (B > 255 ? 255 : (B < 0 ? 0 : B));
        *(outPtr + (--bufferSize)) = (uint8_t) (G > 255 ? 255 : (G < 0 ? 0 : G));
        *(outPtr + (--bufferSize)) = (uint8_t) (R > 255 ? 255 : (R < 0 ? 0 : R));

    }
}

ANativeWindow_unlockAndPost(window);
ANativeWindow_release(window);
}
</code>```

答:
I suggest that you read this related discussion (there are nice screenshots, too, don't miss them).

TL;NR: ImageReader always returns a landscape image, same as onPreviewFrame().

If you connect your camera to a surface of texture, display will be much more efficient than YUV➤RGB conversion that your program can perform, but I understand that there are many situations when you need the RGB data for image processing, and sometimes you want the result of image processing to be displayed as live preview.

This, essentially, is the way OpenCV handles the Android camera and live preview (unfortunately official OpenCV does not use camera2 API, but I have found one tutorial that shows how this can be done).

I strongly suggest to use Renderscript for YUV➤RGB conversion. It's not only much faster, it also gives a significant battery save over doing it in CPU.

An entirely different issue with your code is that it assumes that the display window aspect ratio is same as the image that you receive from the camera, doesn't it?

You should not rely on this. Even after you fix 90° rotation (if the window is portrait), you can see the image distorted. This is not special for camera2, same can happen with the deprecated camera API.

In your case, though, the solution can be different. Instead of tuning the geometry of the window you use to display the live preview, you can skip some input pixels to keep the aspect ratio correct.

In the nutshell, you need

```<code>float srcAspectRatio = (float)srcWidth/srcHeight;
float outAspectRatio = (float)buffer.width/buffer.height;

int clippedSrcWidth =  outAspectRatio > srcAspectRatio ? srcWidth : (int)(0.5 + srcHeight*outAspectRatio);
int clippedSrcHeight = outAspectRatio < srcAspectRatio ? srcHeight : (int)(0.5 + srcWidth/outAspectRatio);

ANativeWindow_setBuffersGeometry(window, clippedSrcWidth, clippedSrcHeight, WINDOW_FORMAT_RGBA_8888);
</code>```

and

```<code>for (size_t y = (srcHeight-clippedSrcHeight)/2; y < srcHeight - (srcHeight-clippedSrcHeight)/2; y++)
</code>```

and so on.

And using the back counter to access pixels of the outPtr, you probably perform mirroring expected for the front-facing camera, don't you?

Body:
I'm making a conversion in the native method from imagereader to yug format to Rgba format through this method in NDK:

size_t bufferSize = buffer.width * buffer.height * (size_t)4;
uint8_t * outPtr = reinterpret_cast<uint8_t *>(buffer.bits);
for (size_t y = 0; y < srcHeight; y++)
{
    uint8_t * Y_rowPtr = srcYPtr + y * Y_rowStride;
    uint8_t * U_rowPtr = srcUPtr + (y >> 1) * U_rowStride;
    uint8_t * V_rowPtr = srcVPtr + (y >> 1) * V_rowStride;

    for (size_t x = 0; x < srcWidth; x++)
    {
        uint8_t Y = Y_rowPtr[x];
        uint8_t U = U_rowPtr[(x >> 1)];
        uint8_t V = V_rowPtr[(x >> 1)];

        double R = (Y + (V - 128) * 1.40625);
        double G = (Y - (U - 128) * 0.34375 - (V - 128) * 0.71875);
        double B = (Y + (U - 128) * 1.765625);

        *(outPtr + (--bufferSize)) = 255; // gamma for RGBA_8888
        *(outPtr + (--bufferSize)) = (uint8_t) (B > 255 ? 255 : (B < 0 ? 0 : B));
        *(outPtr + (--bufferSize)) = (uint8_t) (G > 255 ? 255 : (G < 0 ? 0 : G));
        *(outPtr + (--bufferSize)) = (uint8_t) (R > 255 ? 255 : (R < 0 ? 0 : R));

    }
}

Why is the image rotated 90 degrees?

UPDATE:

I use this conversion:
https://www.fourcc.org/fccyvrgb.php
but the image remains rotated from the original of 90.

UPDATE2:

       @Override
    public void onImageAvailable(ImageReader reader) {
        // ottiene il nuovo frame
        Image image = reader.acquireNextImage();

        if (image == null) {
            return;
        }

        //preparazione per RGBA output
        Image.Plane Y_plane = image.getPlanes()[0];
        int Y_rowStride = Y_plane.getRowStride();
        Image.Plane U_plane = image.getPlanes()[1];
        int UV_rowStride = U_plane.getRowStride();  //nelle immagini YUV, uPlane.getRowStride() == vPlane.getRowStride()
        Image.Plane V_plane = image.getPlanes()[2];
        JNIUtils.RGBADisplay(image.getWidth(), image.getHeight(), Y_rowStride, Y_plane.getBuffer(), UV_rowStride, U_plane.getBuffer(), UV_rowStride, V_plane.getBuffer(), surface);

        image.close();
    }

UPDATE 3: Code into native.cpp

Java_com_ndkvideoimagecapture_JNIUtils_RGBADisplay(
    JNIEnv *env, //env per consentire il passaggio di dati per riferimento
    jobject obj,
    jint srcWidth,
    jint srcHeight,
    jint Y_rowStride,
    jobject Y_Buffer,
    jint U_rowStride,
    jobject U_Buffer,
    jint V_rowStride,
    jobject V_Buffer,
    jobject surface) {

uint8_t *srcYPtr = reinterpret_cast<uint8_t *>(env->GetDirectBufferAddress(Y_Buffer));
uint8_t *srcUPtr = reinterpret_cast<uint8_t *>(env->GetDirectBufferAddress(U_Buffer));
uint8_t *srcVPtr = reinterpret_cast<uint8_t *>(env->GetDirectBufferAddress(V_Buffer));

ANativeWindow *window = ANativeWindow_fromSurface(env, surface);
ANativeWindow_acquire(window);
ANativeWindow_Buffer buffer;

ANativeWindow_setBuffersGeometry(window, srcWidth, srcHeight, WINDOW_FORMAT_RGBA_8888);

if (int32_t err = ANativeWindow_lock(window, &buffer, NULL)) {
    LOGE("ANativeWindow_lock failed with error code: %d\n", err);
    ANativeWindow_release(window);
}

    size_t bufferSize = buffer.width * buffer.height * (size_t)4;
uint8_t * outPtr = reinterpret_cast<uint8_t *>(buffer.bits);
for (size_t y = 0; y < srcHeight; y++)
{
    uint8_t * Y_rowPtr = srcYPtr + y * Y_rowStride;
    uint8_t * U_rowPtr = srcUPtr + (y >> 1) * U_rowStride;
    uint8_t * V_rowPtr = srcVPtr + (y >> 1) * V_rowStride;

    for (size_t x = 0; x < srcWidth; x++)
    {
        uint8_t Y = Y_rowPtr[x];
        uint8_t U = U_rowPtr[(x >> 1)];
        uint8_t V = V_rowPtr[(x >> 1)];

        double R = (Y + (V - 128) * 1.40625);
        double G = (Y - (U - 128) * 0.34375 - (V - 128) * 0.71875);
        double B = (Y + (U - 128) * 1.765625);

        *(outPtr + (--bufferSize)) = 255; // gamma for RGBA_8888
        *(outPtr + (--bufferSize)) = (uint8_t) (B > 255 ? 255 : (B < 0 ? 0 : B));
        *(outPtr + (--bufferSize)) = (uint8_t) (G > 255 ? 255 : (G < 0 ? 0 : G));
        *(outPtr + (--bufferSize)) = (uint8_t) (R > 255 ? 255 : (R < 0 ? 0 : R));

    }
}

ANativeWindow_unlockAndPost(window);
ANativeWindow_release(window);
}

Body:
I suggest that you read this related discussion (there are nice screenshots, too, don't miss them).

TL;NR: ImageReader always returns a landscape image, same as onPreviewFrame().

If you connect your camera to a surface of texture, display will be much more efficient than YUV➤RGB conversion that your program can perform, but I understand that there are many situations when you need the RGB data for image processing, and sometimes you want the result of image processing to be displayed as live preview.

This, essentially, is the way OpenCV handles the Android camera and live preview (unfortunately official OpenCV does not use camera2 API, but I have found one tutorial that shows how this can be done).

I strongly suggest to use Renderscript for YUV➤RGB conversion. It's not only much faster, it also gives a significant battery save over doing it in CPU.

An entirely different issue with your code is that it assumes that the display window aspect ratio is same as the image that you receive from the camera, doesn't it?

You should not rely on this. Even after you fix 90° rotation (if the window is portrait), you can see the image distorted. This is not special for camera2, same can happen with the deprecated camera API.

In your case, though, the solution can be different. Instead of tuning the geometry of the window you use to display the live preview, you can skip some input pixels to keep the aspect ratio correct.

In the nutshell, you need

float srcAspectRatio = (float)srcWidth/srcHeight;
float outAspectRatio = (float)buffer.width/buffer.height;

int clippedSrcWidth =  outAspectRatio > srcAspectRatio ? srcWidth : (int)(0.5 + srcHeight*outAspectRatio);
int clippedSrcHeight = outAspectRatio < srcAspectRatio ? srcHeight : (int)(0.5 + srcWidth/outAspectRatio);

ANativeWindow_setBuffersGeometry(window, clippedSrcWidth, clippedSrcHeight, WINDOW_FORMAT_RGBA_8888);

and

for (size_t y = (srcHeight-clippedSrcHeight)/2; y < srcHeight - (srcHeight-clippedSrcHeight)/2; y++)

and so on.

And using the back counter to access pixels of the outPtr, you probably perform mirroring expected for the front-facing camera, don't you?


问:
Supertypes of the following classes cannot be resolved
I have android app in kotlin which is giving me this error.

Error: Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath:
      class com.google.firebase.auth.FirebaseAuth, unresolved supertypes: com.google.android.gms.internal.aad

and this

Error:Execution failed for task ':app:compileDebugKotlin'.

Compilation error. See log for more details

this is my app module

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "appname"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

     implementation 'com.android.support:appcompat-v7:26.1.0'
     implementation 'com.android.support:animated-vector-drawable:26.1.0'
    implementation 'com.android.support:mediarouter-v7:26.1.0'
   implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'

    implementation 'com.firebaseui:firebase-ui-database:3.0.0'

    //noinspection GradleCompatible,GradleCompatible
    implementation 'com.google.android.gms:play-services:11.0.4'
    implementation 'com.google.firebase:firebase-auth:11.0.4'
    implementation 'com.google.firebase:firebase-database:11.0.4'
    implementation 'com.google.firebase:firebase-storage:11.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

}

 repositories {
    mavenCentral()
}
apply plugin: 'com.google.gms.google-services'
</code>```

and my project gradle is this

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.51'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.0'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

I have firebase.auth implementation but still, it's showing me the error.

答:
i see at least 2 problems in your gradle file:

You have a duplicated entry for "kotlin-stdlib-jre7" (one implementation and one compile). Remove the last one:

```<code>compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
</code>```

Not using the latest versions of firebase & google play services: update to firebase 11.6.2

Body:
I have android app in kotlin which is giving me this error.

Error: Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath:
      class com.google.firebase.auth.FirebaseAuth, unresolved supertypes: com.google.android.gms.internal.aad

and this

Error:Execution failed for task ':app:compileDebugKotlin'.

Compilation error. See log for more details

this is my app module

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "appname"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

     implementation 'com.android.support:appcompat-v7:26.1.0'
     implementation 'com.android.support:animated-vector-drawable:26.1.0'
    implementation 'com.android.support:mediarouter-v7:26.1.0'
   implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'

    implementation 'com.firebaseui:firebase-ui-database:3.0.0'

    //noinspection GradleCompatible,GradleCompatible
    implementation 'com.google.android.gms:play-services:11.0.4'
    implementation 'com.google.firebase:firebase-auth:11.0.4'
    implementation 'com.google.firebase:firebase-database:11.0.4'
    implementation 'com.google.firebase:firebase-storage:11.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

}

 repositories {
    mavenCentral()
}
apply plugin: 'com.google.gms.google-services'

and my project gradle is this

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.51'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.0'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I have firebase.auth implementation but still, it's showing me the error.

Body:
i see at least 2 problems in your gradle file:

You have a duplicated entry for "kotlin-stdlib-jre7" (one implementation and one compile). Remove the last one:

compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

Not using the latest versions of firebase & google play services: update to firebase 11.6.2


问:
`mmap()` manual concurrent prefaulting / paging
I'm trying to fine tune mmap() to perform fast writes or reads (generally not both) of a potentially very large file. The writes and reads will be mostly sequential on one pass and then likely very sparse on future passes. No region of memory needs to be accessed more than once.

In other words, think of it as a file transfer with some lossiness that gets fixed asynchronously.

It appears, as expected, that the main limitation of mmap()'s performance seems to be the number of minor page faults it generates on large files. Furthermore, I suspect the laziness of the Linux kernel's page-to-disk is causing some performance issues. Namely, any test programs that end up performing huge writes to mmaped memory seem to take a long time after performing all writes to terminate/munmap memory.

I was hoping to offset the cost of these faults by concurrently prefaulting pages while performing the almost-sequential access and paging out pages that I won't need again. But I have three main questions regarding this approach and my understanding of the problem:

Is there a straightforward (preferably POSIX [or at least OSX] compatible) way of performing a partial prefault? I am aware of the MAP_POPULATE flag, but this seems to attempt loading the entire file into memory, which is intolerable in many cases. Also, this seems to cause the mmap() call to block until prefaulting is complete, which is also intolerable.  My idea for a manual alternative was to spawn a thread simply to try reading the next  N pages in memory to force a prefetch. But it might be that madvise with MADV_SEQUENTIAL already does this, in effect.

msync() can be used to flush changes to the disk. However, is it actually useful to do this periodically? My idea is that it might be useful if the program is frequently in an "Idle" state of disk IO and can afford to squeeze in some disk writebacks. Then again, the kernel might very well be handling this itself better than the ever application could.

Is my understanding of disk IO accurate? My assumption is that prefaulting and reading/writing pages can be done concurrently by different threads or processes; if I am wrong about this, then manual  prefaulting would not be useful at all. Similarly, if an msync() call blocks all disk IO, both to the filesystem cache and to the raw filesystem, then there also isn't as much of an incentive to use it over flushing the entire disk cache at the program's termination.

答:
It appears, as expected, that the main limitation of mmap()'s performance seems to be the number of minor page faults it generates on large files.

That's not particularly surprising, I agree.  But this is a cost that cannot be avoided, at least for the pages corresponding to regions of the mapped file that you actually access.

Furthermore, I suspect the laziness of the Linux kernel's page-to-disk is causing some performance issues. Namely, any test programs that end up performing huge writes to mmaped memory seem to take a long time after performing all writes to terminate/munmap memory.

That's plausible.  Again, this is an unavoidable cost, at least for dirty pages, but you can exercise some influence over when those costs are incurred.

I was hoping to offset the cost of these faults by concurrently
  prefaulting pages while performing the almost-sequential access and
  paging out pages that I won't need again. But I have three main
  questions regarding this approach and my understanding of the problem:

Is there a straightforward (preferably POSIX [or at least OSX] compatible) way of performing a partial prefault? I am aware of the
  MAP_POPULATE flag, but this seems to attempt loading the entire file
  into memory,

Yes, that's consistent with its documentation.

which is intolerable in many cases. Also, this seems to
  cause the mmap() call to block until prefaulting is complete,

That's also as documented.

which
  is also intolerable. My idea for a manual alternative was to spawn a
  thread simply to try reading the next N pages in memory to force a
  prefetch.

Unless there's a delay between when you initially mmap() the file and when you want to start accessing the mapping, it's not clear to me why you would expect that to provide any improvement.

But it might be that madvise with MADV_SEQUENTIAL already
  does this, in effect.

If you want POSIX compatibility, then you're looking for posix_madvise().  I would indeed recommend using this function instead of trying to roll your own userspace alternative.  In particular, if you use posix_madvise() to assert POSIX_MADV_SEQUENTIAL on some or all of the mapped region, then it is reasonable to hope that the kernel will read ahead to load pages before they are needed.  Additionally, if you advise with POSIX_MADV_DONTNEED then you might, at the kernel's discretion, get earlier sync to disk and overall less memory use.  There is other advice you can pass by this mechanism, too, if it is useful.

msync() can be used to flush changes to the disk. However, is it actually useful to do this periodically? My idea is that it might
  be useful if the program is frequently in an "Idle" state of disk IO
  and can afford to squeeze in some disk writebacks. Then again, the
  kernel might very well be handling this itself better than the ever
  application could.

This is something to test.  Note that msync() supports asynchronous syncing, however, so you don't need I/O idleness.  Thus, when you're sure you're done with a given page you could consider msync()ing it with flag MS_ASYNC to request that the kernel schedule a sync.  This might reduce the delay incurred when you unmap the file.  You'll have to experiment with combining it with posix_madvise(..., ..., POSIX_MADV_DONTNEED); they might or might not complement each other.

Is my understanding of disk IO accurate? My assumption is that prefaulting and reading/writing pages can be done concurrently by
  different threads or processes; if I am wrong about this, then manual
  prefaulting would not be useful at all.

It should be possible for one thread to prefault pages (by accessing them), while another reads or writes others that have already been faulted in, but it's unclear to me why you expect such a prefaulting thread to be able to run ahead of the one(s) doing the reads and writes.  If it has any effect at all (i.e. if the kernel does not prefault on its own) then I would expect prefaulting a page to be more expensive than reading or writing each byte in it once.

Similarly, if an msync()
  call blocks all disk IO, both to the filesystem cache and to the raw
  filesystem, then there also isn't as much of an incentive to use it
  over flushing the entire disk cache at the program's termination.

There is a minimum number of disk reads and writes that will need to be performed on behalf of your program.  For any given mmapped file, they will all be performed on the same I/O device, and therefore they will all be serialized with respect to one another.  If you are I/O bound then to a first approximation, the order in which those I/O operations are performed does not matter for overall runtime.

Thus, if the runtime is what you're concerned with, then probably neither posix_madvise() nor msync() will be of much help unless your program spends a significant fraction of its runtime on tasks that are independent of accessing the mmapped file.  If you do find yourself not wholly I/O bound  then my suggestion would be to see first what posix_madvise() can do for you, and to try asynchronous msync() if you need more.  I'm inclined to doubt that userspace prefaulting or synchronous msync() would provide a win, but in optimization, it's always better to test than to (only) predict.


问:
MVC 3 Install problem
Somebody allready installed MVC 3? I have Windows 7 + VS 2010. Trying to install with Web Platform Installer,- its show me "OK" but there isn't Web MVC3 Application in New Project template =\</p>

答:
Somebody allready installed MVC 3?

Yes.

Try downloading the installer and running it locally. Make sure you have removed any previous RC versions you might have installed. The new project template shows when creating a new Web Application (not Web Site).

Title: MVC 3 Install problem