问:
Get attribute or elements from page by script in nightwatch
I need a check that class elements was ui-state-active.

```<code>class="ui-state-default ui-state-active" href="#">15</a>
</code>```

I am trying to using all methods and don't undestand how to write a code:

```<code>.perform(function () {
    var arrAttr = [];
    var arrCssProp = [];
    var arrValue= [];
    for (i = 1; i < 8; i++) {
      for (j = 1; j < 7; j++) {
        browser.useXpath();
        browser.getCssProperty('//*[@id="ui-datepicker-div"]/table/tbody/tr[' + i + ']/td[' + j + ']', '.ui-state-default', function (result) {
          arrCssProp[j, i] = result.value;
        });
        browser.getAttribute('//*[@id="ui-datepicker-div"]/table/tbody/tr[' + i + ']/td[' + j + ']', '.ui-state-default', function (result) {
          arrAttr[j, i] = result.value;
        });
        browser.getValue('//*[@id="ui-datepicker-div"]/table/tbody/tr[' + i + ']/td[' + j + ']', '.ui-state-default', function (result) {
          arrValue[j, i] = result.value;
        });
        browser.useCss();
        writeLogLine('arrAttr:' + i + "|" + j + ' :' + arrAttr);
        console.log('arrAttr:' + i + "|" + j + ' :' + arrAttr);
        writeLogLine('arrCssProp:' + i + "|" + j + ' :' + arrCssProp);
        console.log('arrCssProp:' + i + "|" + j + ' :' + arrCssProp);
        writeLogLine('arrValue:' + i + "|" + j + ' :' + arrValue);
        console.log('arrValue:' + i + "|" + j + ' :' + arrValue);
      }
    }
  })
</code>```

答:
Like in Rohit's example, if you want to use an attribute value, all the commands that rely on it need to be inside the callback. Doing arrCssProp[j, i] = result.value; won't work, since that value will disappear as soon as you exit the callback.

For more info, check out https://github.com/nightwatchjs/nightwatch/wiki/Understanding-the-Command-Queue

Body:
I need a check that class elements was ui-state-active.

class="ui-state-default ui-state-active" href="#">15

I am trying to using all methods and don't undestand how to write a code:

.perform(function () {
    var arrAttr = [];
    var arrCssProp = [];
    var arrValue= [];
    for (i = 1; i < 8; i++) {
      for (j = 1; j < 7; j++) {
        browser.useXpath();
        browser.getCssProperty('//*[@id="ui-datepicker-div"]/table/tbody/tr[' + i + ']/td[' + j + ']', '.ui-state-default', function (result) {
          arrCssProp[j, i] = result.value;
        });
        browser.getAttribute('//*[@id="ui-datepicker-div"]/table/tbody/tr[' + i + ']/td[' + j + ']', '.ui-state-default', function (result) {
          arrAttr[j, i] = result.value;
        });
        browser.getValue('//*[@id="ui-datepicker-div"]/table/tbody/tr[' + i + ']/td[' + j + ']', '.ui-state-default', function (result) {
          arrValue[j, i] = result.value;
        });
        browser.useCss();
        writeLogLine('arrAttr:' + i + "|" + j + ' :' + arrAttr);
        console.log('arrAttr:' + i + "|" + j + ' :' + arrAttr);
        writeLogLine('arrCssProp:' + i + "|" + j + ' :' + arrCssProp);
        console.log('arrCssProp:' + i + "|" + j + ' :' + arrCssProp);
        writeLogLine('arrValue:' + i + "|" + j + ' :' + arrValue);
        console.log('arrValue:' + i + "|" + j + ' :' + arrValue);
      }
    }
  })


来源: stackexchange

问:
Download file and converter to type doc or pdf
I have a URL that returns a .dat file, I would like to download it but converted to a .pdf or .doc extension, could someone help me?

I'm doing in typescript

URL: http://172.17.0.53:8060/leisarq/\originais\0000000\0000000000353.dat

答:
Assuming that you just want to grab the file, change the extension on the fly and save it, you can use the file-saver helper (more details here: https://www.npmjs.com/package/file-saver)

I've prepared you a simple example here:

https://stackblitz.com/edit/angular-za1kbf

The idea is quite simple, just get the original file using Angular's http.get()
and finally, trigger a download on the client-side using the file-saver utility.

```<code>download() {
  return this.http.get("https://i.ibb.co/n3Y038T/a52b055eafb69acd427c99c25bc0fd02.jpg", {
      responseType: "blob"
    }).subscribe((response)=>{
     saveAs(response, "new-image.png");
  });
}
</code>```

Maybe is worth to mention that this only changes the extension, the file are still a JPG (but with .PNG extension)

ContentLicense: CC BY-SA 4.0

Body:
Assuming that you just want to grab the file, change the extension on the fly and save it, you can use the file-saver helper (more details here: https://www.npmjs.com/package/file-saver)

I've prepared you a simple example here:

https://stackblitz.com/edit/angular-za1kbf

The idea is quite simple, just get the original file using Angular's http.get()
and finally, trigger a download on the client-side using the file-saver utility.

download() {
  return this.http.get("https://i.ibb.co/n3Y038T/a52b055eafb69acd427c99c25bc0fd02.jpg", {
      responseType: "blob"
    }).subscribe((response)=>{
     saveAs(response, "new-image.png");
  });
}

Maybe is worth to mention that this only changes the extension, the file are still a JPG (but with .PNG extension)


问:
How do I write to a conditional output
In my code I have defined a conditional output:

```<code>class EccGenerate[D <: Data](data: D, doubleBit : Boolean = true) extends Module {
  val eccBits = calcCodeBits(data.getWidth)

  val io = IO(new Bundle {
    val in = Input(data.cloneType)
    val out = Output(UInt(eccBits.W))
    val par = if (doubleBit) Some(Output(Bool())) else None
  })
</code>```

Trying to use the := operator on the par output fails, because it is not always an output.  When using conditional inputs, I would use io.par.get() to retrieve the current value of the input, is there a corresponding primitive, operator or function call I can use to set the value of a conditional output?

答:
The issue is that you can't connect to par because it's type is Option[Bool] and := isn't define for Option. You need to unpack it and assign to the Bool inside if the option contains something.

The functional programming way of doing this would be:

io.par.foreach(_ := foo)
```

<p>You can also be more verbose about it if you want:</p>

<pre class="lang-scala prettyprint-override"><code>io.par match {
  case Some(a) => a := foo
  case None    =>
}
</code>```

An if statement would also work:

if (par.nonEmpty) {
  io.par.get := foo
}
```

Title: How do I write to a conditional output

Body:
In my code I have defined a conditional output:

class EccGenerate[D <: Data](data: D, doubleBit : Boolean = true) extends Module {
  val eccBits = calcCodeBits(data.getWidth)

  val io = IO(new Bundle {
    val in = Input(data.cloneType)
    val out = Output(UInt(eccBits.W))
    val par = if (doubleBit) Some(Output(Bool())) else None
  })

Trying to use the := operator on the par output fails, because it is not always an output.  When using conditional inputs, I would use io.par.get() to retrieve the current value of the input, is there a corresponding primitive, operator or function call I can use to set the value of a conditional output?

Body:
The issue is that you can't connect to par because it's type is Option[Bool] and := isn't define for Option. You need to unpack it and assign to the Bool inside if the option contains something.

The functional programming way of doing this would be:

io.par.foreach(_ := foo)

You can also be more verbose about it if you want:

io.par match {
  case Some(a) => a := foo
  case None    =>
}

An if statement would also work:

if (par.nonEmpty) {
  io.par.get := foo
}


问:
H2 Driver not found when configuring JOOQ Codegen through gradle
I am trying to configure a project using h2, jooq and flyway. However, once the nu.studer.jooq plugin generates the config.xml it's unable to find the org.h2.driver I have the depedency in my build.gradle which is shown below along with the error I keep getting.

```<code>plugins {
    id 'java'
    id 'application'
    id 'org.springframework.boot' version '2.2.4.RELEASE'
    id 'nu.studer.jooq' version '4.0'
    id 'org.flywaydb.flyway' version '6.2.3'
}
ext['jooq.version'] = '3.12.3'
sourceCompatibility = 11.0

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.2.4.RELEASE'
    implementation group: 'org.jooq', name: 'jooq', version: '3.12.3'
    implementation group: 'com.h2database', name: 'h2', version: '1.4.199'

}

application {
    mainClassName = 'exampleapp.App'
}

jooq {
    version = '3.12.3'
    edition = 'OSS'
    sample(sourceSets.main) {
        jdbc {
            driver = 'org.h2.Driver'
            url = 'jdbc:h2:~/test'
            user = 'sa'
            password = ''
            schema = 'public'
        }
        generator {
            name = 'org.jooq.util.DefaultGenerator'
            strategy {
                name = 'org.jooq.util.DefaultGeneratorStrategy'
            }
            database {
                name = 'org.jooq.meta.h2.H2Database'
            }
            generate {
                relations = true
                deprecated = false
                records = true
                immutablePojos = true
                fluentSetters = true
            }
            target {
                packageName = 'generated.jooq'
                directory = '$projectDir/src/generated/jooq'
            }
        }
    }
}

flyway {
    url = 'jdbc:h2:~/test'
    user = 'sa'
    password = ''
    schemas = ['public']
}

generateSampleJooqSchemaSource.dependsOn flywayMigrate
</code>```

The error I receive when I run gradle clean build is as follows:

```<code>java.lang.ClassNotFoundException: org.h2.Driver
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        at org.jooq.codegen.GenerationTool.loadClass0(GenerationTool.java:925)
        at org.jooq.codegen.GenerationTool.loadClass(GenerationTool.java:869)
        at org.jooq.codegen.GenerationTool.run0(GenerationTool.java:334)
        at org.jooq.codegen.GenerationTool.run(GenerationTool.java:221)
        at org.jooq.codegen.GenerationTool.generate(GenerationTool.java:216)
        at org.jooq.codegen.GenerationTool.main(GenerationTool.java:188)
</code>```

Not sure why it can't find h2 in the classpath, any ideas?

答:
Figured it out, I needed to add

```<code>jooqRuntime {
    dependecies: 'com.h2database:h2:1.4.199'
}
</code>```

To allow the task to find org.h2.Driver in the classpath

Body:
I am trying to configure a project using h2, jooq and flyway. However, once the nu.studer.jooq plugin generates the config.xml it's unable to find the org.h2.driver I have the depedency in my build.gradle which is shown below along with the error I keep getting.

plugins {
    id 'java'
    id 'application'
    id 'org.springframework.boot' version '2.2.4.RELEASE'
    id 'nu.studer.jooq' version '4.0'
    id 'org.flywaydb.flyway' version '6.2.3'
}
ext['jooq.version'] = '3.12.3'
sourceCompatibility = 11.0

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.2.4.RELEASE'
    implementation group: 'org.jooq', name: 'jooq', version: '3.12.3'
    implementation group: 'com.h2database', name: 'h2', version: '1.4.199'

}

application {
    mainClassName = 'exampleapp.App'
}

jooq {
    version = '3.12.3'
    edition = 'OSS'
    sample(sourceSets.main) {
        jdbc {
            driver = 'org.h2.Driver'
            url = 'jdbc:h2:~/test'
            user = 'sa'
            password = ''
            schema = 'public'
        }
        generator {
            name = 'org.jooq.util.DefaultGenerator'
            strategy {
                name = 'org.jooq.util.DefaultGeneratorStrategy'
            }
            database {
                name = 'org.jooq.meta.h2.H2Database'
            }
            generate {
                relations = true
                deprecated = false
                records = true
                immutablePojos = true
                fluentSetters = true
            }
            target {
                packageName = 'generated.jooq'
                directory = '$projectDir/src/generated/jooq'
            }
        }
    }
}

flyway {
    url = 'jdbc:h2:~/test'
    user = 'sa'
    password = ''
    schemas = ['public']
}

generateSampleJooqSchemaSource.dependsOn flywayMigrate

The error I receive when I run gradle clean build is as follows:

java.lang.ClassNotFoundException: org.h2.Driver
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        at org.jooq.codegen.GenerationTool.loadClass0(GenerationTool.java:925)
        at org.jooq.codegen.GenerationTool.loadClass(GenerationTool.java:869)
        at org.jooq.codegen.GenerationTool.run0(GenerationTool.java:334)
        at org.jooq.codegen.GenerationTool.run(GenerationTool.java:221)
        at org.jooq.codegen.GenerationTool.generate(GenerationTool.java:216)
        at org.jooq.codegen.GenerationTool.main(GenerationTool.java:188)

Not sure why it can't find h2 in the classpath, any ideas?

Body:
Figured it out, I needed to add

jooqRuntime {
    dependecies: 'com.h2database:h2:1.4.199'
}

To allow the task to find org.h2.Driver in the classpath


问:
Where is vogue (the nodeJS module), so that I can add it to PATH?
I have been following the instructions at http://aboutcode.net/vogue/ - installed nodeJS and npm, with no errors - but when it comes to the step:

$ vogue path/to/website

I get:

-bash: vogue: command not found

How do I find vogue to add it to PATH? I have tried:

find /usr -name vogue -type f

find / -name vogue -type f

...with no joy.

答:
If you install anything via NPM all bin's are in this hidden folder: /node_modules/.bin/
The /node_modules folder gets created relative, from where you run NPM.</p>

ContentLicense: CC BY-SA 3.0


问:
EOFException when reading files with ObjectInputStream
I basically have a similar problem as stated here: EOFexception in Java when reading objectinputstream, but I don't find an answer with clean code.

The answer states that the ObjectInputStream#readObject will throw the exception when the reader reachs the End Of File. After looking in the web for a solution, I haven't found a solution. Could be a good and clean solution for this case?

Note: I have tried this (but it looks ugly and is not clean code). I'm looking for a better solution:

```<code>ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
try {
    Object o;
    while ((o = ois.readObject()) != null) {
        if (o instanceof MyClass) {
            MyClass m = (MyClass)o;
            //use the object...
        }
    }
} catch (EOFException eofex) {
    //do nothing
}  catch (IOException ioex) {
    throw ioex;
    //I have another try/catch block outside to control the life of the ObjectInputStream
}
//later in the code...
ois.close();
</code>```

答: I encountered this error because I had forgot to close an ObjectOutputStream in the code that wrote the data. Once I wrote the data again with code that closed the output stream the data was able to be read in fine.</p>

Body:
I basically have a similar problem as stated here: EOFexception in Java when reading objectinputstream, but I don't find an answer with clean code.

The answer states that the ObjectInputStream#readObject will throw the exception when the reader reachs the End Of File. After looking in the web for a solution, I haven't found a solution. Could be a good and clean solution for this case?

Note: I have tried this (but it looks ugly and is not clean code). I'm looking for a better solution:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
try {
    Object o;
    while ((o = ois.readObject()) != null) {
        if (o instanceof MyClass) {
            MyClass m = (MyClass)o;
            //use the object...
        }
    }
} catch (EOFException eofex) {
    //do nothing
}  catch (IOException ioex) {
    throw ioex;
    //I have another try/catch block outside to control the life of the ObjectInputStream
}
//later in the code...
ois.close();


问:
What is the best way to create a superuser in flask
I am working on a flask application which I need to create different types of user roles using a superuser. What is the best way to create a superuser? Some of ways that I am thinking is:

Create a custom command and execute the command in production.

```<code>import click
from flask import Flask

app = Flask(__name__)

@app.cli.command("create-superuser")
@click.argument("name")
def create_superuser(name):
    ...
</code>```

Create a function and execute before first request.

```<code>@app.before_first_request
def init_db():
    db.create_all()
    insert_superuser()
</code>```

Or just sql insert a superuser in the database.

If I am doing this wrong or this is a bad practice to do in production please tell me. I am still new to this.

答:
There are several options here-

Have a CLI command for adding the user, like you are doing. I find that most projects go this route, and that it works pretty well as long as you can run the CLI on a system with the appropriate config. Generally speaking it might make sense to expand that CLI to also include things like password resets.

Have a "First run" most where the application displays a form asking for information. This is how things like Github Enterprise or Wordpress tend to work, but there is a small threat where a user who knows you are deploying can beat you to the web interface. This can be mitigated by having the first run script log a URL with a security token in it, so only someone with access to the logs can start the configuration project. If you're not deploying to customers though this is more complicated than needed.

Have users get created based off of environmental variables. This route is particularly useful for when you're creating developer environments, as it means the devs don't have to run through extra steps when getting setup. It is a bad idea to do in production though.

I hope that helps!

Body:
I am working on a flask application which I need to create different types of user roles using a superuser. What is the best way to create a superuser? Some of ways that I am thinking is:

Create a custom command and execute the command in production.

import click
from flask import Flask

app = Flask(__name__)

@app.cli.command("create-superuser")
@click.argument("name")
def create_superuser(name):
    ...

Create a function and execute before first request.

@app.before_first_request
def init_db():
    db.create_all()
    insert_superuser()

Or just sql insert a superuser in the database.

If I am doing this wrong or this is a bad practice to do in production please tell me. I am still new to this.


问:
Not able to Update password and useraccountcontrol in AD using Spring LDAP
I am new to Spring LDAP and Active directory and facing issue while updating password for new created user in AD.

Using SPRING LDAP I have first created User in AD successfully and then tried to update password and useraccountcontrol of user when I getting below exception.
We have been trying for last 1 week and not able to resolve. Any help/direction is highly appreciated.

I have been through many blogs and  tried as mentioned in below two blogs but still blocked and getting same exception:

How do I resolve "WILL_NOT_PERFORM" MS AD reply when trying to change password in scala w/ the unboundid LDAP SDK?

Adding a user with a password in Active Directory LDAP

Stacktrace:

```<code>16:43:56,991 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)  INFO [http-localhost-127.0.0.1-8080-1] (HelperDao.java:26) - HelperDao.getNextUserId(): entry

16:43:57,007 INFO  [stdout] (http-localhost-127.0.0.1-8080-1) Hibernate:   SELECT LTRIM(TO_CHAR( IP_USER_XDUSERID_SEQ.nextval, '000000000000000000000000000')) ID from dual

16:43:57,164 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)  INFO [http-localhost-127.0.0.1-8080-1] (HelperDao.java:30) - HelperDao.getNextUserId(): exit

16:47:17,051 INFO  [stdout] (http-localhost-127.0.0.1-8080-1) 16:47:17.051 [http-localhost-127.0.0.1-8080-1] ERROR com.st.liotroevo.web.dao.UserADRepository - catching

16:47:17,051 INFO  [stdout] (http-localhost-127.0.0.1-8080-1) javax.naming.OperationNotSupportedException: [LDAP: error code 53 - 0000200D: SvcErr: DSID-031A0FC0, problem 5003 (WILL_NOT_PERFORM), data 0
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3160) ~[?:1.7.0_45]
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:3033) ~[?:1.7.0_45]
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2840) ~[?:1.7.0_45]
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.ldap.LdapCtx.c_modifyAttributes(LdapCtx.java:1478) ~[?:1.7.0_45]
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_modifyAttributes(ComponentDirContext.java:273) ~[?:?]
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.modifyAttributes(PartialCompositeDirContext.java:190) ~[?:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.modifyAttributes(PartialCompositeDirContext.java:179) ~[?:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at javax.naming.directory.InitialDirContext.modifyAttributes(InitialDirContext.java:167) ~[?:1.7.0_45]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_45]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_45]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_45]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_45]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.springframework.transaction.compensating.support.CompensatingTransactionUtils.performOperation(CompensatingTransactionUtils.java:69) ~[spring-ldap-core-2.0.2.RELEASE.jar:2.0.2.RELEASE]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.springframework.ldap.transaction.compensating.manager.TransactionAwareDirContextInvocationHandler.invoke(TransactionAwareDirContextInvocationHandler.java:85) ~[spring-ldap-core-2.0.2.RELEASE.jar:2.0.2.RELEASE]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.proxy.$Proxy69.modifyAttributes(Unknown Source) ~[?:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.st.liotroevo.web.dao.UserADRepository.update(UserADRepository.java:104) [classes:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.st.liotroevo.web.service.UserService.updateUser(UserService.java:92) [classes:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.st.liotroevo.web.service.serviceImpl.IPRegistrationServiceImpl.createUser(IPRegistrationServiceImpl.java:72) [classes:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_45]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_45]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_45]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_45]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.jboss.ws.common.invocation.AbstractInvocationHandlerJSE.invoke(AbstractInvocationHandlerJSE.java:111) [jbossws-common-2.0.2.GA.jar!/:2.0.2.GA]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.jboss.wsf.stack.cxf.JBossWSInvoker._invokeInternal(JBossWSInvoker.java:181) [jbossws-cxf-server-4.0.2.GA.jar!/:4.0.2.GA]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.jboss.wsf.stack.cxf.JBossWSInvoker.invoke(JBossWSInvoker.java:127) [jbossws-cxf-server-4.0.2.GA.jar!/:4.0.2.GA]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58) [cxf-rt-core-2.4.6.jar!/:2.4.6]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [?:1.7.0_45]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at java.util.concurrent.FutureTask.run(FutureTask.java:262) [?:1.7.0_45]
</code>```

Below is the code snippet:

```<code>ldap.url=ldaps://url:636
ldap.userDn=CN=IP User,OU=AdminAccounts,DC=stp-qa,DC=st,DC=com
ldap.password=dummyPass
ldap.base=OU=ST,OU=People,DC=stp-qa,DC=st,DC=com
ldap.clean=false

@Entry(objectClasses = {  "top", "person", "organizationalPerson","user","st-individualpassportuser"})
public final class User {

    @Id
    private Name dn;

    @Attribute(name = "mail")
    private String email;

    @Attribute(name = "cn")
    @DnAttribute(value="cn",index=0)
    private String fullName;

    @Attribute(name = "givenName")
    private String firstName;

    @Attribute(name = "sn")
    private String lastName;

    @Attribute(name = "st-AccValidationStatus")
    private String accountStatus;

    @Attribute(name = "st-entryStatus")
    private String validationStatus;

    @Attribute(name = "whenCreated")
    private String creationDate;

    @Attribute(name = "st-ValidatedOn")
    private String validationDate;

    @Attribute(name = "st-ValidatedBy")
    private String validatedBy;

    @Attribute(name = "st-currentLogon")
    private String lastLogon;

    @Attribute(name = "st-loginRedirectURL")
    private String loginRedirectUrl;

    @Attribute(name = "st-jvCompany")
    private String jvCode;

    @Attribute(name = "sAMAccountName")
    private String samAccount;

    @Attribute(name = "st-userSpecifedCompany")
    private String employerName;

    @Attribute(name = "postalCode")
    private String zipCode;

    @Attribute(name="st-xduserid")
    private String xdUserId;

    @Attribute(name="st-Logincount")
    private String loginCount;

    @Attribute(name="unicodePwd")
    private byte[] unicodePassword;

    @Attribute(name="userAccountControl")
    private String userAccountControl;

    @Attribute(name="st-AccLastValidated")
    private String userAccLastValidated;

    @Attribute(name="st-secretQuestion")
    private String userSecretQuestion;

    @Attribute(name="st-secretAnswer")
    private String userAnswerToSecretQuestion;
    }
</code>```

Java Class for Password computation:

```<code>/**
 * Add unicode Password to userObject.
 * Ldap does not allow to set password/userAccountControl during creation of user by design, So need to update user after creation in AD with password and userAccountControl.
 * @param password
 */
private void addPasswordToUserProfile(String password) {

    String newQuotedPassword = "\"" +  password + "\"";
    try {
        byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
            int UF_NORMAL_ACCOUNT = 0x0200;
            int UF_PASSWORD_EXPIRED = 0x800000;
            adUserBean.setUserAccountControl(Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWORD_EXPIRED));
            adUserBean.setUnicodePassword(newUnicodePassword);
    } catch (UnsupportedEncodingException e) {
        logger.catching(e);
    }
}
</code>```

Repository.Java

```<code>@Repository
public class UserADRepository {

    @Autowired
    private LdapTemplate ldapTemplate;

    public User create(User user) {
        ldapTemplate.create(user);
        return user;
    }

    public User findByFullName(String fullName) {
        return ldapTemplate.findOne(
                LdapQueryBuilder.query().where("cn").is(fullName), User.class);
    }

    /**
     * Find user in LDAP based on User SamAccountName
     * @param samAccount
     * @return
     */
    public User findBySamAccountName(String samAccount) {
        User usr = null;
        try {
            usr = ldapTemplate.findOne(
                    LdapQueryBuilder.query().where("sAMAccountName")
                            .is(samAccount), User.class);
        } catch (EmptyResultDataAccessException emptyException) {
            return usr;
        }
        return usr;
    }

/**
 * Find user in LDAP based on User DN (distinguisedName)
 * @param dn
 * @return
 */
    public User findByDn(Name dn) {
        User usr = null;
        try {
            usr = ldapTemplate.findByDn(dn, User.class);
        } catch (NameNotFoundException e) {
            return usr;
        }
        return usr;
    }

    /**
     * Update user in AD
     * @param User
     */
    public void update(User User) {
        ldapTemplate.update(User);
    }

    public void delete(User User) {
        ldapTemplate.delete(User);
    }
</code>```

Thanks in advance for kind help or direction to resolve this issue.

答:
In addition to aalmero answer, it seems like Spring Ldap repository can't save unicodePwd.

But you can use LdapTemplate for it:

```<code>    UserAd userAd = new UserAd();
    // set your stuff
    userAdRepository.save(userAd);

    ModificationItem[] mods = new ModificationItem[1];
    mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", encodePassword("password-respecting-policies")));

    ldapTemplate.modifyAttributes(userAd.getDn(), mods);
</code>```

Body:
I am new to Spring LDAP and Active directory and facing issue while updating password for new created user in AD.

Using SPRING LDAP I have first created User in AD successfully and then tried to update password and useraccountcontrol of user when I getting below exception.
We have been trying for last 1 week and not able to resolve. Any help/direction is highly appreciated.

I have been through many blogs and  tried as mentioned in below two blogs but still blocked and getting same exception:

How do I resolve "WILL_NOT_PERFORM" MS AD reply when trying to change password in scala w/ the unboundid LDAP SDK?

Adding a user with a password in Active Directory LDAP

Stacktrace:

16:43:56,991 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)  INFO [http-localhost-127.0.0.1-8080-1] (HelperDao.java:26) - HelperDao.getNextUserId(): entry

16:43:57,007 INFO  [stdout] (http-localhost-127.0.0.1-8080-1) Hibernate:   SELECT LTRIM(TO_CHAR( IP_USER_XDUSERID_SEQ.nextval, '000000000000000000000000000')) ID from dual

16:43:57,164 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)  INFO [http-localhost-127.0.0.1-8080-1] (HelperDao.java:30) - HelperDao.getNextUserId(): exit

16:47:17,051 INFO  [stdout] (http-localhost-127.0.0.1-8080-1) 16:47:17.051 [http-localhost-127.0.0.1-8080-1] ERROR com.st.liotroevo.web.dao.UserADRepository - catching

16:47:17,051 INFO  [stdout] (http-localhost-127.0.0.1-8080-1) javax.naming.OperationNotSupportedException: [LDAP: error code 53 - 0000200D: SvcErr: DSID-031A0FC0, problem 5003 (WILL_NOT_PERFORM), data 0
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3160) ~[?:1.7.0_45]
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:3033) ~[?:1.7.0_45]
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2840) ~[?:1.7.0_45]
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.ldap.LdapCtx.c_modifyAttributes(LdapCtx.java:1478) ~[?:1.7.0_45]
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_modifyAttributes(ComponentDirContext.java:273) ~[?:?]
16:47:17,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.modifyAttributes(PartialCompositeDirContext.java:190) ~[?:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.modifyAttributes(PartialCompositeDirContext.java:179) ~[?:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at javax.naming.directory.InitialDirContext.modifyAttributes(InitialDirContext.java:167) ~[?:1.7.0_45]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_45]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_45]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_45]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_45]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.springframework.transaction.compensating.support.CompensatingTransactionUtils.performOperation(CompensatingTransactionUtils.java:69) ~[spring-ldap-core-2.0.2.RELEASE.jar:2.0.2.RELEASE]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.springframework.ldap.transaction.compensating.manager.TransactionAwareDirContextInvocationHandler.invoke(TransactionAwareDirContextInvocationHandler.java:85) ~[spring-ldap-core-2.0.2.RELEASE.jar:2.0.2.RELEASE]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.sun.proxy.$Proxy69.modifyAttributes(Unknown Source) ~[?:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.st.liotroevo.web.dao.UserADRepository.update(UserADRepository.java:104) [classes:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.st.liotroevo.web.service.UserService.updateUser(UserService.java:92) [classes:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at com.st.liotroevo.web.service.serviceImpl.IPRegistrationServiceImpl.createUser(IPRegistrationServiceImpl.java:72) [classes:?]
16:47:17,099 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_45]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_45]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_45]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_45]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.jboss.ws.common.invocation.AbstractInvocationHandlerJSE.invoke(AbstractInvocationHandlerJSE.java:111) [jbossws-common-2.0.2.GA.jar!/:2.0.2.GA]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.jboss.wsf.stack.cxf.JBossWSInvoker._invokeInternal(JBossWSInvoker.java:181) [jbossws-cxf-server-4.0.2.GA.jar!/:4.0.2.GA]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.jboss.wsf.stack.cxf.JBossWSInvoker.invoke(JBossWSInvoker.java:127) [jbossws-cxf-server-4.0.2.GA.jar!/:4.0.2.GA]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58) [cxf-rt-core-2.4.6.jar!/:2.4.6]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [?:1.7.0_45]
16:47:17,115 INFO  [stdout] (http-localhost-127.0.0.1-8080-1)       at java.util.concurrent.FutureTask.run(FutureTask.java:262) [?:1.7.0_45]

Below is the code snippet:

ldap.url=ldaps://url:636
ldap.userDn=CN=IP User,OU=AdminAccounts,DC=stp-qa,DC=st,DC=com
ldap.password=dummyPass
ldap.base=OU=ST,OU=People,DC=stp-qa,DC=st,DC=com
ldap.clean=false

@Entry(objectClasses = {  "top", "person", "organizationalPerson","user","st-individualpassportuser"})
public final class User {

    @Id
    private Name dn;

    @Attribute(name = "mail")
    private String email;

    @Attribute(name = "cn")
    @DnAttribute(value="cn",index=0)
    private String fullName;

    @Attribute(name = "givenName")
    private String firstName;

    @Attribute(name = "sn")
    private String lastName;

    @Attribute(name = "st-AccValidationStatus")
    private String accountStatus;

    @Attribute(name = "st-entryStatus")
    private String validationStatus;

    @Attribute(name = "whenCreated")
    private String creationDate;

    @Attribute(name = "st-ValidatedOn")
    private String validationDate;

    @Attribute(name = "st-ValidatedBy")
    private String validatedBy;

    @Attribute(name = "st-currentLogon")
    private String lastLogon;

    @Attribute(name = "st-loginRedirectURL")
    private String loginRedirectUrl;

    @Attribute(name = "st-jvCompany")
    private String jvCode;

    @Attribute(name = "sAMAccountName")
    private String samAccount;

    @Attribute(name = "st-userSpecifedCompany")
    private String employerName;

    @Attribute(name = "postalCode")
    private String zipCode;

    @Attribute(name="st-xduserid")
    private String xdUserId;

    @Attribute(name="st-Logincount")
    private String loginCount;

    @Attribute(name="unicodePwd")
    private byte[] unicodePassword;

    @Attribute(name="userAccountControl")
    private String userAccountControl;

    @Attribute(name="st-AccLastValidated")
    private String userAccLastValidated;

    @Attribute(name="st-secretQuestion")
    private String userSecretQuestion;

    @Attribute(name="st-secretAnswer")
    private String userAnswerToSecretQuestion;
    }

Java Class for Password computation:

/**
 * Add unicode Password to userObject.
 * Ldap does not allow to set password/userAccountControl during creation of user by design, So need to update user after creation in AD with password and userAccountControl.
 * @param password
 */
private void addPasswordToUserProfile(String password) {

    String newQuotedPassword = "\"" +  password + "\"";
    try {
        byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
            int UF_NORMAL_ACCOUNT = 0x0200;
            int UF_PASSWORD_EXPIRED = 0x800000;
            adUserBean.setUserAccountControl(Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWORD_EXPIRED));
            adUserBean.setUnicodePassword(newUnicodePassword);
    } catch (UnsupportedEncodingException e) {
        logger.catching(e);
    }
}

Repository.Java

@Repository
public class UserADRepository {

    @Autowired
    private LdapTemplate ldapTemplate;

    public User create(User user) {
        ldapTemplate.create(user);
        return user;
    }

    public User findByFullName(String fullName) {
        return ldapTemplate.findOne(
                LdapQueryBuilder.query().where("cn").is(fullName), User.class);
    }

    /**
     * Find user in LDAP based on User SamAccountName
     * @param samAccount
     * @return
     */
    public User findBySamAccountName(String samAccount) {
        User usr = null;
        try {
            usr = ldapTemplate.findOne(
                    LdapQueryBuilder.query().where("sAMAccountName")
                            .is(samAccount), User.class);
        } catch (EmptyResultDataAccessException emptyException) {
            return usr;
        }
        return usr;
    }

/**
 * Find user in LDAP based on User DN (distinguisedName)
 * @param dn
 * @return
 */
    public User findByDn(Name dn) {
        User usr = null;
        try {
            usr = ldapTemplate.findByDn(dn, User.class);
        } catch (NameNotFoundException e) {
            return usr;
        }
        return usr;
    }

    /**
     * Update user in AD
     * @param User
     */
    public void update(User User) {
        ldapTemplate.update(User);
    }

    public void delete(User User) {
        ldapTemplate.delete(User);
    }

Thanks in advance for kind help or direction to resolve this issue.

Body:
In addition to aalmero answer, it seems like Spring Ldap repository can't save unicodePwd.

But you can use LdapTemplate for it:

    UserAd userAd = new UserAd();
    // set your stuff
    userAdRepository.save(userAd);

    ModificationItem[] mods = new ModificationItem[1];
    mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", encodePassword("password-respecting-policies")));

    ldapTemplate.modifyAttributes(userAd.getDn(), mods);


问:
dispay json data in ngfor loop in angular (data from firebase)
In my Angular code, I am getting data from a firebase database through an Http get request and when I try to display the result with an ngfor loop, I have an error message. This example was replicated from a tutorial and it worked for him. Where is the problem and how could I make it work? Thanks for helping!

I use a service to get data here is the code:

```<code>import {Http} from '@angular/http';
import { Injectable } from '@angular/core';
import {Response} from "@angular/http";
import {map} from 'rxjs/operators';

@Injectable()

export class ServerService {
constructor(private http:Http){}

StoreServers(servers:any[]){
return this.http.post('https://ng-http-a5718.firebaseio.com/data.json',servers);
}

GetServers(){
 return  this.http.get('https://ng-http-a5718.firebaseio.com/data.json').pipe(map(
  (res:Response) =>{
    const dataserver = res.json() as any[];
  for(const server of dataserver ){
    server.name='fetched_server'+server.name
  }
  return dataserver;
}
  )
 )
}

}
</code>```

Here is the .ts code of the component where I try to display the data:

```<code>import { Component } from '@angular/core';
import { ServerService } from './server.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private ServerService : ServerService){}

  servers = [
    {
      name: 'Testserver',
      capacity: 10,
      id: this.generateId()
    },
    {
      name: 'Liveserver',
      capacity: 100,
      id: this.generateId()
    }
  ];
  onAddServer(name: string) {
    this.servers.push({
      name: name,
      capacity: 50,
      id: this.generateId()
    });
  }
  private generateId() {
    return Math.round(Math.random() * 10000);
  }

  OnSave(){
    this.ServerService.StoreServers(this.servers).subscribe(
      (Response)=>(console.log(Response)),
      (Error)=>(console.log(Error))
      )
  }

  OnGet(){
    this.ServerService.GetServers().subscribe(
      (data) => { this.servers=data}
        ,
      (Error)=>{
        return (console.log(Error));
      }
      )
  }
}
</code>```

Here is the html code of the component where I try to display the data:

```<code><div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <input type="text" #serverName>
      <button class="btn btn-primary" (click)="onAddServer(serverName.value)">Add Server</button>
      <hr>
      <button class="btn btn-primary" (click)='OnSave()'>Save servers</button>
      <button class="btn btn-primary" (click)='OnGet()'>Get servers</button>
      <br>
      <ul class="list-group" *ngFor="let server of servers">
        <li class="list-group-item">{{ server.name }} (ID: {{ server.id }})</li>
      </ul>
    </div>
  </div>
</div>
</code>```

And finally here it is the error message I get:

enter image description here

答:
this.server expecting Array in onGet() method but getting Object from firebase with the unique key. so you can modify onGet() method in following:

OnGet(){
    this.ServerService.GetServers().subscribe(
      (data) => {
      const keys = Object.keys(data);
      const firstKey = keys[0];
      this.servers = data[firstKey]; // get the inside array

      }
        ,
      (Error)=>{
        return (console.log(Error));
      }
      )
  }```

Body:
In my Angular code, I am getting data from a firebase database through an Http get request and when I try to display the result with an ngfor loop, I have an error message. This example was replicated from a tutorial and it worked for him. Where is the problem and how could I make it work? Thanks for helping!

I use a service to get data here is the code:

import {Http} from '@angular/http';
import { Injectable } from '@angular/core';
import {Response} from "@angular/http";
import {map} from 'rxjs/operators';

@Injectable()

export class ServerService {
constructor(private http:Http){}

StoreServers(servers:any[]){
return this.http.post('https://ng-http-a5718.firebaseio.com/data.json',servers);
}

GetServers(){
 return  this.http.get('https://ng-http-a5718.firebaseio.com/data.json').pipe(map(
  (res:Response) =>{
    const dataserver = res.json() as any[];
  for(const server of dataserver ){
    server.name='fetched_server'+server.name
  }
  return dataserver;
}
  )
 )
}

}

Here is the .ts code of the component where I try to display the data:

import { Component } from '@angular/core';
import { ServerService } from './server.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private ServerService : ServerService){}

  servers = [
    {
      name: 'Testserver',
      capacity: 10,
      id: this.generateId()
    },
    {
      name: 'Liveserver',
      capacity: 100,
      id: this.generateId()
    }
  ];
  onAddServer(name: string) {
    this.servers.push({
      name: name,
      capacity: 50,
      id: this.generateId()
    });
  }
  private generateId() {
    return Math.round(Math.random() * 10000);
  }

  OnSave(){
    this.ServerService.StoreServers(this.servers).subscribe(
      (Response)=>(console.log(Response)),
      (Error)=>(console.log(Error))
      )
  }

  OnGet(){
    this.ServerService.GetServers().subscribe(
      (data) => { this.servers=data}
        ,
      (Error)=>{
        return (console.log(Error));
      }
      )
  }
}

Here is the html code of the component where I try to display the data:

      <input type="text" #serverName>
      <button class="btn btn-primary" (click)="onAddServer(serverName.value)">Add Server</button>

      <button class="btn btn-primary" (click)='OnSave()'>Save servers</button>
      <button class="btn btn-primary" (click)='OnGet()'>Get servers</button>

{{ server.name }} (ID: {{ server.id }})

And finally here it is the error message I get:

enter image description here


问:
How to maintain original dataframe index and keep order of input list when using isin()?
I have the following dataframe:
g= pd.DataFrame({'A':[1,2,42,5,7],'B':[5,6,7,3,2]})

```<code>    A  B
0   1  5
1   2  6
2  42  7
3   5  3
4   7  2
</code>```

am using the following list to filter the dataframe:

```<code>list_values = [5,7,1]
</code>```

and get the following output using:

```<code>indexes = g[g['A'].isin(list_values)].index.values
</code>```

output

```<code>array([0, 3, 4], dtype=int64)
</code>```

How do I change the code so that indexes is the following?

```<code>array([3, 4, 0], dtype=int64)
</code>```

Essentially, I am looking for a way to filter a DF with a list and return the original index values in the order of the filter list.

Thanks!

I looked at this but did not find what I was looking for:
Select rows of pandas dataframe from list, in order of list

答:
You can use an ordered CategoricalDtype to enforce a custom sorting order. After sorting you return all indices for 5, then 7, then 1.

```<code>import pandas as pd

my_cat = pd.CategoricalDtype(categories=list_values, ordered=True)
#CategoricalDtype(categories=[5, 7, 1], ordered=True)

g.loc[g['A'].isin(list_values), 'A'].astype(my_cat).sort_values().index
#Int64Index([3, 4, 0], dtype='int64')
</code>```

Body:
I have the following dataframe:
g= pd.DataFrame({'A':[1,2,42,5,7],'B':[5,6,7,3,2]})

    A  B
0   1  5
1   2  6
2  42  7
3   5  3
4   7  2

am using the following list to filter the dataframe:

list_values = [5,7,1]

and get the following output using:

indexes = g[g['A'].isin(list_values)].index.values

output

array([0, 3, 4], dtype=int64)

How do I change the code so that indexes is the following?

array([3, 4, 0], dtype=int64)

Essentially, I am looking for a way to filter a DF with a list and return the original index values in the order of the filter list.

Thanks!

I looked at this but did not find what I was looking for:
Select rows of pandas dataframe from list, in order of list

Body:
You can use an ordered CategoricalDtype to enforce a custom sorting order. After sorting you return all indices for 5, then 7, then 1.

import pandas as pd

my_cat = pd.CategoricalDtype(categories=list_values, ordered=True)
#CategoricalDtype(categories=[5, 7, 1], ordered=True)

g.loc[g['A'].isin(list_values), 'A'].astype(my_cat).sort_values().index
#Int64Index([3, 4, 0], dtype='int64')


答:
By the way, I'm sorry but you tagged your question flask_restful, and I really think everyone should use flask_restplus (being now flask_restx, forked due to change of maintainers).

I could change the tags, but I want to leave you the choice of doing it

This is what pleases you the most. There is no best way. It depends of your use-case. However, I dislike the 2nd method (before_first_request).

The custom command

If you want to put this task in the hand of a person, you can use this. People will come to someone that will add them or not on the admin side.

You can use the @app.before_request() decorator so that the action is performed each and every time, but do not set the database each and everytime you light up the app. Use a database, and it leads us to the 3rd one.

Superuser in database (password hashed with sha256).

Usually, if the system is in production, you don't want to mess with the admin too much.

There is another way : The JWT token.

Title: What is the best way to create a superuser in flask


问:
How indent this Objective-C code?
I have a simple question. How I indent a very long line. Let's use the traditional 80 caracters.
This is a line in my code:

```<code>    NSString *count = [[NSString alloc] initWithString: [sTemp substringFromIndex:[sTemp rangeOfString:@"count="].location + [sTemp rangeOfString:@"count="].length]];
</code>```

One solution was

```<code>    NSString *count = [[NSString alloc]                                 //line 1
                            initWithString: [sTemp substringFromIndex:
                                [sTemp rangeOfString:@"count="].location +
                                [sTemp rangeOfString:@"count="].length]];
</code>```

This is not the best sample, but the idea is:

Ok, the first line is the assignment and alloc thing.

The line 2 indent with a fell more right space. But, if the name of variable or type is very big, I will have the situation above. What I do?

```<code>NSStringWithVeryBigType *bigNameVariable = [NSStringWithVeryBigType alloc]
                  initWithString: [sTemp substringFromIndex:
</code>```

IN second line I create a new NSString. I can be confuse if the line 3 and 4 (in a bad situation, not this) is the main function creation, or is this new one. Have a good rule about it? And if it have a big name too, what to do again...

In other words, in a big assignment line, what rule I have to fallow?

答:
[sTemp rangeOfString:@"count="] is a potentially expensive operation, and you're doing it twice. You should cache the result in a local variable. Since you want to start your substring immediately after the found range, you can use NSMaxRange() to conveniently get that value. As well, use -copy instead of -initWithString: for NSString, as it can give you better performance with nearly identical semantics. So:

```<code>NSRange range = [sTemp rangeOfString:@"count="];
NSString *count = [[sTemp substringFromIndex:NSMaxRange(range)] copy];
</code>```

Title: How indent this Objective-C code?

Body:
I have a simple question. How I indent a very long line. Let's use the traditional 80 caracters.
This is a line in my code:

    NSString *count = [[NSString alloc] initWithString: [sTemp substringFromIndex:[sTemp rangeOfString:@"count="].location + [sTemp rangeOfString:@"count="].length]];

One solution was

    NSString *count = [[NSString alloc]                                 //line 1
                            initWithString: [sTemp substringFromIndex:
                                [sTemp rangeOfString:@"count="].location +
                                [sTemp rangeOfString:@"count="].length]];

This is not the best sample, but the idea is:

Ok, the first line is the assignment and alloc thing.

The line 2 indent with a fell more right space. But, if the name of variable or type is very big, I will have the situation above. What I do?

NSStringWithVeryBigType *bigNameVariable = [NSStringWithVeryBigType alloc]
                  initWithString: [sTemp substringFromIndex:

IN second line I create a new NSString. I can be confuse if the line 3 and 4 (in a bad situation, not this) is the main function creation, or is this new one. Have a good rule about it? And if it have a big name too, what to do again...

In other words, in a big assignment line, what rule I have to fallow?

Body:
[sTemp rangeOfString:@"count="] is a potentially expensive operation, and you're doing it twice. You should cache the result in a local variable. Since you want to start your substring immediately after the found range, you can use NSMaxRange() to conveniently get that value. As well, use -copy instead of -initWithString: for NSString, as it can give you better performance with nearly identical semantics. So:

NSRange range = [sTemp rangeOfString:@"count="];
NSString *count = [[sTemp substringFromIndex:NSMaxRange(range)] copy];


问:
Tracking down the source of a dataformat error in a query
I have a query in Excel, retrieving data from a different workbook. Recently, however, the table the query writes data to has failed with the error DataFormat.Error: Invalid cell value '#N/A'..

Going through the steps of the query in the query editor, it looks like the error happens when some rows used to be sorted out:

I suspect the error is because of a change of some column header in the source file, but I am far from certain if this is actually the case.

Is there any way to track down a more detailed error description, e.g. to get to know what cells it is that has the invalid values? Is there some other way to get a better grip on what is causing the error?

答:
If you are sourcing from an Excel Spreadsheet, just after you import the data, before you even Promote Headers or Change Data types select all columns and delete errors.

That worked for me.


问:
Append a function and its arguments to a list without calling the function immediately
I want to do something like this:

lst = []
lst.append( func1(a, b, c, d) ) # do NOT execute function here/now
lst.append( func2(e, f) )       # do NOT execute function here/now
lst.append( func3(w, x, y) )    # do NOT execute function here/now

# ... later
for f in lst:
    result = f # execute function here/now
```

What is the simplest way to accomplish this in Python?

答:
You can use the func(*args) syntax to provide a tuple of positional arguments:

lst = []
lst.append( (func1, a, b, c, d) )
lst.append( (func2, e, f) )
lst.append( (func3, w, x, y) )

for func, *args in lst:
    result = func(*args)
```

<p>Alternatively, just guard each function call with a lambda:</p>

<pre class="lang-py prettyprint-override"><code>lst = []
lst.append(lambda: func1(a, b, c, d))
lst.append(lambda: func2(e, f))
lst.append(lambda: func3(w, x, y))

for f in lst:
    result = f()
</code>```

The second version is subject to some subtle bugs, because the argument names (e.g. a) aren't evaluated when the lambda is created, they're evaluated when the lambda is called - this means if a changes between the append and the call, these two solutions will give different results, and the first one is probably what you intended. So I'd recommend avoiding the second one, unless the arguments are just constants.

Body:
I want to do something like this:

lst = []
lst.append( func1(a, b, c, d) ) # do NOT execute function here/now
lst.append( func2(e, f) )       # do NOT execute function here/now
lst.append( func3(w, x, y) )    # do NOT execute function here/now

# ... later
for f in lst:
    result = f # execute function here/now

What is the simplest way to accomplish this in Python?

Body:
You can use the func(*args) syntax to provide a tuple of positional arguments:

lst = []
lst.append( (func1, a, b, c, d) )
lst.append( (func2, e, f) )
lst.append( (func3, w, x, y) )

for func, *args in lst:
    result = func(*args)

Alternatively, just guard each function call with a lambda:

lst = []
lst.append(lambda: func1(a, b, c, d))
lst.append(lambda: func2(e, f))
lst.append(lambda: func3(w, x, y))

for f in lst:
    result = f()

The second version is subject to some subtle bugs, because the argument names (e.g. a) aren't evaluated when the lambda is created, they're evaluated when the lambda is called - this means if a changes between the append and the call, these two solutions will give different results, and the first one is probably what you intended. So I'd recommend avoiding the second one, unless the arguments are just constants.


问:
Support for float128 (np.longdouble) in scipy.stats
I would like to make some probability computations with scipy.stats, and avoid under/overflows:
in addition to using the appropriate log-functions, I tried to increase the float precision using numpy.longdouble (float128 on Ubuntu).

However, the functions I tried failed, for example:

```<code>import numpy as np, scipy.stats as st
x = np.array([0.1, 0.2, 0.5], dtype=np.longdouble)
st.entropy(x)
st.gamma.pdf(x, 2)
</code>```

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-72225ce02b65> in <module>
----> 1 st.entropy(x)

~/.local/lib/python3.5/site-packages/scipy/stats/_distn_infrastructure.py in entropy(pk, qk, base, axis)
   2664     pk = 1.0*pk / np.sum(pk, axis=axis, keepdims=True)
   2665     if qk is None:
-> 2666         vec = entr(pk)
   2667     else:
   2668         qk = asarray(qk)

TypeError: ufunc 'entr' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
</code>```

Is there any support for long double precision in scipy.stats?
According to this documentation page, it does not seem so :-(

Details and versions

My problem is similar to this one, except that scipy.linalg.svd or mpmath.matrix work for me.

scipy version is 1.4.1, and numpy.show_config():

```<code>lapack_opt_info:
    libraries = ['openblas', 'openblas']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
    library_dirs = ['/usr/local/lib']
openblas_lapack_info:
    libraries = ['openblas', 'openblas']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
    library_dirs = ['/usr/local/lib']
openblas_info:
    libraries = ['openblas', 'openblas']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
    library_dirs = ['/usr/local/lib']
lapack_mkl_info:
  NOT AVAILABLE
blis_info:
  NOT AVAILABLE
blas_opt_info:
    libraries = ['openblas', 'openblas']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
    library_dirs = ['/usr/local/lib']
blas_mkl_info:
  NOT AVAILABLE
</code>```

答: Basically, no, there isn't. Select methods of specific distributions may or may not work, and it's not guaranteed.</p>

Body:
I would like to make some probability computations with scipy.stats, and avoid under/overflows:
in addition to using the appropriate log-functions, I tried to increase the float precision using numpy.longdouble (float128 on Ubuntu).

However, the functions I tried failed, for example:

import numpy as np, scipy.stats as st
x = np.array([0.1, 0.2, 0.5], dtype=np.longdouble)
st.entropy(x)
st.gamma.pdf(x, 2)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-72225ce02b65> in <module>
----> 1 st.entropy(x)

~/.local/lib/python3.5/site-packages/scipy/stats/_distn_infrastructure.py in entropy(pk, qk, base, axis)
   2664     pk = 1.0*pk / np.sum(pk, axis=axis, keepdims=True)
   2665     if qk is None:
-> 2666         vec = entr(pk)
   2667     else:
   2668         qk = asarray(qk)

TypeError: ufunc 'entr' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Is there any support for long double precision in scipy.stats?
According to this documentation page, it does not seem so :-(

Details and versions

My problem is similar to this one, except that scipy.linalg.svd or mpmath.matrix work for me.

scipy version is 1.4.1, and numpy.show_config():

lapack_opt_info:
    libraries = ['openblas', 'openblas']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
    library_dirs = ['/usr/local/lib']
openblas_lapack_info:
    libraries = ['openblas', 'openblas']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
    library_dirs = ['/usr/local/lib']
openblas_info:
    libraries = ['openblas', 'openblas']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
    library_dirs = ['/usr/local/lib']
lapack_mkl_info:
  NOT AVAILABLE
blis_info:
  NOT AVAILABLE
blas_opt_info:
    libraries = ['openblas', 'openblas']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
    library_dirs = ['/usr/local/lib']
blas_mkl_info:
  NOT AVAILABLE


答:
Try this:</p>

```<code>list.append( functools.partial(func1, a, b, c, d) )
</code>```

Title: Append a function and its arguments to a list without calling the function immediately

Body:
Try this:

list.append( functools.partial(func1, a, b, c, d) )


问:
signalling inside php
hi when implementing a connection that stays open for a long time ( comet ),
how would i implement signalling between php proses(outstanding requests)??

example timeline:

request 1 start

request 1 makes action

request 1 sleeps

request 2 start

request 2 makes action

request 2 notifies request 1 and go's to sleep

request 1 wakes up and sends the new data

request 1 sleeps agen

i was wandering if ther was a methode whitch use less(noting?) cpu prosessing

答:
I believe you would have to use pcntl_signal(), along with pcntl_fork(). The server would have to support forking though.

As for the cpu processing load use usleep() in the loop so that the processor has time to be used by other processes.

Title: signalling inside php


问:
Symfony 5 firewall with JWT blocks access to some routes without login
I'm using LexikJWTAuthenticationBundle to manage the token creation and all that jazz.

My security.yaml file looks like this(removed not relevant stuff):

```<code>security:
    encoders:
        App\Entity\User:
            algorithm: auto
    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        login:
            pattern:  ^/api/login
            stateless: true
            anonymous: true
            json_login:
                check_path: /api/login_check
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
        api:
            pattern:   ^/api
            stateless: true
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: lazy
            guard:
                authenticators:
                    - App\Security\LoginFormAuthenticator
            logout:
                path: logout
                target: /
                invalidate_session: true
            remember_me:
                secret:   '%kernel.secret%'
                lifetime: 604800 # 1 week in seconds
                path:     /
                always_remember_me: true

    access_control:
         - { path: ^/admin, roles: ROLE_ADMIN }
         - { path: ^/profile, roles: ROLE_USER }
         - { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/user, roles: ROLE_USER }
         - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }
</code>```

As far as JWT goes it works fine

Doing a simple curl

```<code>$ curl -X POST -H "Content-Type: application/json" http://localhost/api/\login_check -d '{"username":"someusername","password":"somepassword!"}'
</code>```

Returns a token:

```<code>  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100   910  100   852  100    58    376     25  0:00:02  0:00:02 --:--:-- 376
{"token":"6wvL6E..."}
</code>```

Problem is, every other route responds with a 302 the immediately redirects to /

```<code>Request URL: http://localhost/register
Request Method: GET
Status Code: 302 Found
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade
</code>```

It's pretty clear that I've missconfigured something somewhere. But I can't seem to find. As far as I'm concerned the configs seem to be good.

Perhaps somebody with a better eye(and better experience) than myself can give me a hand.

I can only assume JWT expects X route to have a token, but, I'm clearly whitelisting certain paths in access_control.

Removing the bundle and reverting any changes will make all routes behave as expected.

Upon further investigation it seems to collide with a custom LoginFormAuthenticator

```<code><?php

namespace App\Security;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;

class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
{
    use TargetPathTrait;

    private $entityManager;
    private $urlGenerator;
    private $csrfTokenManager;
    private $passwordEncoder;

    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->entityManager = $entityManager;
        $this->urlGenerator = $urlGenerator;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->passwordEncoder = $passwordEncoder;
    }

    public function supports(Request $request)
    {
        return 'login_user' === $request->attributes->get('_route') && $request->isMethod('POST');
    }

    public function getCredentials(Request $request)
    {
        $credentials = [
            'email' => $request->request->get('email'),
            'password' => $request->request->get('password'),
            'csrf_token' => $request->request->get('_csrf_token'),
        ];
        $request->getSession()->set(
            Security::LAST_USERNAME,
            $credentials['email']
        );

        return $credentials;
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $token = new CsrfToken('authenticate', $credentials['csrf_token']);
        if (!$this->csrfTokenManager->isTokenValid($token)) {
            throw new InvalidCsrfTokenException();
        }

        $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);

        if (!$user) {
            // fail authentication with a custom error
            throw new CustomUserMessageAuthenticationException('Email could not be found.');
        }

        return $user;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
    }

    /**
     * Used to upgrade (rehash) the user's password automatically over time.
     */
    public function getPassword($credentials): ?string
    {
        return $credentials['password'];
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }

        return new RedirectResponse($this->urlGenerator->generate('index', [], RouterInterface::ABSOLUTE_URL));
    }

    protected function getLoginUrl()
    {
        return $this->urlGenerator->generate('login_user');
    }
}
</code>```

Why exactly this happens I'm not sure since they guards are in separate firewalls with clearly distinct routes. Not even the same prefix as far as I can tell.

答:
So in your config you have the main firewall with the custom LoginFormAuthenticator, in which I do not see the whole point when you do not need an authenticator for the login when you are using LexikJWTAuthenticationBundle.

Also I noticed is that if you make a request for example to http://localhost/register it would use your LoginFormAuthenticator, which will not support the request because in its supports() function you declared to accept certain route.

```<code>return 'login_user' === $request->attributes->get('_route') ....
</code>```

Another thing you can troubleshoot is your onAuthenticationSuccess function, especially I have suspicion about this line.

```<code>return new RedirectResponse($this->urlGenerator->generate('index', [], RouterInterface::ABSOLUTE_URL));
</code>```

I would assume that you have a route,which is named index and has path "/" and if you use routes.yaml it would look something like this. (You have the same principle in the other types too)

```<code>index:
    path: /
    controller: App\Controller\ACMEController::fooFunction
</code>```

So basically you are telling your authenticator to redirect to "/". That would be my other guess.
I hope I was helpful.

Body:
I'm using LexikJWTAuthenticationBundle to manage the token creation and all that jazz.

My security.yaml file looks like this(removed not relevant stuff):

security:
    encoders:
        App\Entity\User:
            algorithm: auto
    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        login:
            pattern:  ^/api/login
            stateless: true
            anonymous: true
            json_login:
                check_path: /api/login_check
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
        api:
            pattern:   ^/api
            stateless: true
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: lazy
            guard:
                authenticators:
                    - App\Security\LoginFormAuthenticator
            logout:
                path: logout
                target: /
                invalidate_session: true
            remember_me:
                secret:   '%kernel.secret%'
                lifetime: 604800 # 1 week in seconds
                path:     /
                always_remember_me: true

    access_control:
         - { path: ^/admin, roles: ROLE_ADMIN }
         - { path: ^/profile, roles: ROLE_USER }
         - { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/user, roles: ROLE_USER }
         - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }

As far as JWT goes it works fine

Doing a simple curl

$ curl -X POST -H "Content-Type: application/json" http://localhost/api/\login_check -d '{"username":"someusername","password":"somepassword!"}'

Returns a token:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100   910  100   852  100    58    376     25  0:00:02  0:00:02 --:--:-- 376
{"token":"6wvL6E..."}

Problem is, every other route responds with a 302 the immediately redirects to /

Request URL: http://localhost/register
Request Method: GET
Status Code: 302 Found
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade

It's pretty clear that I've missconfigured something somewhere. But I can't seem to find. As far as I'm concerned the configs seem to be good.

Perhaps somebody with a better eye(and better experience) than myself can give me a hand.

I can only assume JWT expects X route to have a token, but, I'm clearly whitelisting certain paths in access_control.

Removing the bundle and reverting any changes will make all routes behave as expected.

Upon further investigation it seems to collide with a custom LoginFormAuthenticator

<?php

namespace App\Security;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;

class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
{
    use TargetPathTrait;

    private $entityManager;
    private $urlGenerator;
    private $csrfTokenManager;
    private $passwordEncoder;

    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->entityManager = $entityManager;
        $this->urlGenerator = $urlGenerator;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->passwordEncoder = $passwordEncoder;
    }

    public function supports(Request $request)
    {
        return 'login_user' === $request->attributes->get('_route') && $request->isMethod('POST');
    }

    public function getCredentials(Request $request)
    {
        $credentials = [
            'email' => $request->request->get('email'),
            'password' => $request->request->get('password'),
            'csrf_token' => $request->request->get('_csrf_token'),
        ];
        $request->getSession()->set(
            Security::LAST_USERNAME,
            $credentials['email']
        );

        return $credentials;
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $token = new CsrfToken('authenticate', $credentials['csrf_token']);
        if (!$this->csrfTokenManager->isTokenValid($token)) {
            throw new InvalidCsrfTokenException();
        }

        $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);

        if (!$user) {
            // fail authentication with a custom error
            throw new CustomUserMessageAuthenticationException('Email could not be found.');
        }

        return $user;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
    }

    /**
     * Used to upgrade (rehash) the user's password automatically over time.
     */
    public function getPassword($credentials): ?string
    {
        return $credentials['password'];
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }

        return new RedirectResponse($this->urlGenerator->generate('index', [], RouterInterface::ABSOLUTE_URL));
    }

    protected function getLoginUrl()
    {
        return $this->urlGenerator->generate('login_user');
    }
}

Why exactly this happens I'm not sure since they guards are in separate firewalls with clearly distinct routes. Not even the same prefix as far as I can tell.

Body:
So in your config you have the main firewall with the custom LoginFormAuthenticator, in which I do not see the whole point when you do not need an authenticator for the login when you are using LexikJWTAuthenticationBundle.

Also I noticed is that if you make a request for example to http://localhost/register it would use your LoginFormAuthenticator, which will not support the request because in its supports() function you declared to accept certain route.

return 'login_user' === $request->attributes->get('_route') ....

Another thing you can troubleshoot is your onAuthenticationSuccess function, especially I have suspicion about this line.

return new RedirectResponse($this->urlGenerator->generate('index', [], RouterInterface::ABSOLUTE_URL));

I would assume that you have a route,which is named index and has path "/" and if you use routes.yaml it would look something like this. (You have the same principle in the other types too)

index:
    path: /
    controller: App\Controller\ACMEController::fooFunction

So basically you are telling your authenticator to redirect to "/". That would be my other guess.
I hope I was helpful.