问:
Unable to merge dex error in android studio 3.0
I am looking for the answer that can help me to solve this problem. I am trying to solve this problem for last 2 days.But still, I didn't get the answer that can solve my problem. I have tried so many solutions which are given here.But no solution worked for me.
Please help me to solve this problem.Any help will be appreciated.

The actual problem is:

```<code>Error:Execution failed for task
':app:transformDexArchiveWithExternalLibsDexMergerForGlobalServerDebug'.
 java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
</code>```

this is occurring every time when I run my existing project on android studio 3.0

I have tried so many solutions for this like:

1- To add mutidexenabled true in gradle

2- To change the version of dependencies

3- To change the compile keyword with the implementation

4- To clean and rebuild the project

5- Delete the Gradle file(this was so difficult because when you again
  restarted the project no Gradle file will be auto-regenerated)  etc.

I am looking for the solutions which are other than those which are mentioned above. Please help me out. Please...

code of gradle file is given below:

```<code>apply plugin: 'com.android.application'
buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'io.fabric'

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }

    flatDir {
        dirs 'libs'
    }
}
repositories {
    maven { url 'http://clojars.org/repo' }
}

android {
    signingConfigs {
        config {
            keyAlias 'example'
            keyPassword 'example'
            storeFile file('/Users/standarduser/Documents/Android_Projects/example.jks')
            storePassword '@@@@@@@@'
        }
    }
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId 'com.example.example'
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 9  // both Latest
        versionName "2.0.7"
        multiDexEnabled true
        useLibrary 'org.apache.http.legacy'
        vectorDrawables.useSupportLibrary = true
        signingConfig signingConfigs.config
    }
    dexOptions {
        incremental = true
        preDexLibraries = false
        javaMaxHeapSize "4g"
    }
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
    android {
        packagingOptions
                {
                    exclude 'META-INF/DEPENDENCIES.txt'
                    exclude 'META-INF/LICENSE.txt'
                    exclude 'META-INF/NOTICE.txt'
                    exclude 'META-INF/NOTICE'
                    exclude 'META-INF/LICENSE'
                    exclude 'META-INF/DEPENDENCIES'
                    exclude 'META-INF/notice.txt'
                    exclude 'META-INF/license.txt'
                    exclude 'META-INF/dependencies.txt'
                    exclude 'META-INF/LGPL2.1'
                }
    }

    lintOptions{
        abortOnError false
    }
}

dependencies {
    compile files('libs/httpcore-4.4.1.jar')
    compile('com.twitter.sdk.android:twitter:2.1.1@aar') { //1.6.1@aar
        transitive = true;
    }
    compile('com.github.afollestad.material-dialogs:core:0.8.5.2@aar') {
        transitive = true
    }
    compile('io.socket:socket.io-client:0.8.2') { // 0.6.3
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
    testCompile 'junit:junit:4.12'
    compile 'com.writingminds:FFmpegAndroid:0.3.2'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'io.nlopez.smartlocation:library:3.2.9'
    //   compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.gms:play-services-appinvite:9.8.0'
    //9.0.1
    compile 'com.google.android.gms:play-services-gcm:9.8.0'
    compile 'com.google.android.gms:play-services-location:9.8.0'
    compile 'com.google.android.gms:play-services-places:9.8.0'
    compile 'com.google.android.gms:play-services-maps:9.8.0'
    compile 'com.google.android.gms:play-services-ads:9.8.0'
    compile 'com.google.android.gms:play-services-auth:9.8.0'
    compile 'com.google.android.gms:play-services-plus:9.8.0'
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:design:25.0.1'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.google.code.gson:gson:2.4'
    compile 'org.apache.httpcomponents:httpmime:4.3.5'
//    implementation 'org.apache.httpcomponents:httpmime:4.3.6'
//    implementation 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.facebook.android:facebook-android-sdk:4.23.0'
    compile 'com.pusher:pusher-java-client:1.1.2'
    compile 'com.android.support:recyclerview-v7:25.0.1'
    compile 'com.android.support:cardview-v7:25.0.1'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.6'
    compile 'com.amazonaws:aws-android-sdk-mobileanalytics:2.2.9'
    compile 'com.commit451:PhotoView:1.2.4'
    compile 'commons-lang:commons-lang:2.3'
    compile 'com.karumi:dexter:2.3.1'
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
    implementation 'com.android.support:multidex:1.0.2'
    compile 'org.ocpsoft.prettytime:prettytime:3.2.7.Final'
    compile 'com.koushikdutta.async:androidasync:2.+'
    compile 'com.soundcloud.android:android-crop:1.0.1@aar'
    compile 'net.danlew:android.joda:2.9.4.1'
    compile 'com.albinmathew:photo-crop-library:1.0.3'
    compile 'com.amazonaws:aws-android-sdk-core:2.2.+'
    compile 'com.amazonaws:aws-android-sdk-s3:2.2.+'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.wowza.gocoder.sdk.android:com.wowza.gocoder.sdk:1.0b7@aar'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.4@aar') {
        transitive = true;
    }
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    //    compile 'com.cocosw:bottomsheet:1.+@aar'
    compile project(':libbambuser7')
    compile 'com.squareup.okhttp:okhttp:2.0.0'
}

apply plugin: 'com.google.gms.google-services'
</code>```

答:
Try this

Use this

com.google.android.gms:play-services:11.6.0

```<code>com.google.android.gms:play-services-location:11.6.0
</code>```

Instead of this

com.google.android.gms:play-services:9.8.0

after  Sync ->  clean ->  rebuild

Body:
I am looking for the answer that can help me to solve this problem. I am trying to solve this problem for last 2 days.But still, I didn't get the answer that can solve my problem. I have tried so many solutions which are given here.But no solution worked for me.
Please help me to solve this problem.Any help will be appreciated.

The actual problem is:

Error:Execution failed for task
':app:transformDexArchiveWithExternalLibsDexMergerForGlobalServerDebug'.
 java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

this is occurring every time when I run my existing project on android studio 3.0

I have tried so many solutions for this like:

1- To add mutidexenabled true in gradle

2- To change the version of dependencies

3- To change the compile keyword with the implementation

4- To clean and rebuild the project

5- Delete the Gradle file(this was so difficult because when you again
  restarted the project no Gradle file will be auto-regenerated)  etc.

I am looking for the solutions which are other than those which are mentioned above. Please help me out. Please...

code of gradle file is given below:

apply plugin: 'com.android.application'
buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'io.fabric'

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }

    flatDir {
        dirs 'libs'
    }
}
repositories {
    maven { url 'http://clojars.org/repo' }
}

android {
    signingConfigs {
        config {
            keyAlias 'example'
            keyPassword 'example'
            storeFile file('/Users/standarduser/Documents/Android_Projects/example.jks')
            storePassword '@@@@@@@@'
        }
    }
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId 'com.example.example'
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 9  // both Latest
        versionName "2.0.7"
        multiDexEnabled true
        useLibrary 'org.apache.http.legacy'
        vectorDrawables.useSupportLibrary = true
        signingConfig signingConfigs.config
    }
    dexOptions {
        incremental = true
        preDexLibraries = false
        javaMaxHeapSize "4g"
    }
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
    android {
        packagingOptions
                {
                    exclude 'META-INF/DEPENDENCIES.txt'
                    exclude 'META-INF/LICENSE.txt'
                    exclude 'META-INF/NOTICE.txt'
                    exclude 'META-INF/NOTICE'
                    exclude 'META-INF/LICENSE'
                    exclude 'META-INF/DEPENDENCIES'
                    exclude 'META-INF/notice.txt'
                    exclude 'META-INF/license.txt'
                    exclude 'META-INF/dependencies.txt'
                    exclude 'META-INF/LGPL2.1'
                }
    }

    lintOptions{
        abortOnError false
    }
}

dependencies {
    compile files('libs/httpcore-4.4.1.jar')
    compile('com.twitter.sdk.android:twitter:2.1.1@aar') { //1.6.1@aar
        transitive = true;
    }
    compile('com.github.afollestad.material-dialogs:core:0.8.5.2@aar') {
        transitive = true
    }
    compile('io.socket:socket.io-client:0.8.2') { // 0.6.3
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
    testCompile 'junit:junit:4.12'
    compile 'com.writingminds:FFmpegAndroid:0.3.2'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'io.nlopez.smartlocation:library:3.2.9'
    //   compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.gms:play-services-appinvite:9.8.0'
    //9.0.1
    compile 'com.google.android.gms:play-services-gcm:9.8.0'
    compile 'com.google.android.gms:play-services-location:9.8.0'
    compile 'com.google.android.gms:play-services-places:9.8.0'
    compile 'com.google.android.gms:play-services-maps:9.8.0'
    compile 'com.google.android.gms:play-services-ads:9.8.0'
    compile 'com.google.android.gms:play-services-auth:9.8.0'
    compile 'com.google.android.gms:play-services-plus:9.8.0'
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:design:25.0.1'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.google.code.gson:gson:2.4'
    compile 'org.apache.httpcomponents:httpmime:4.3.5'
//    implementation 'org.apache.httpcomponents:httpmime:4.3.6'
//    implementation 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.facebook.android:facebook-android-sdk:4.23.0'
    compile 'com.pusher:pusher-java-client:1.1.2'
    compile 'com.android.support:recyclerview-v7:25.0.1'
    compile 'com.android.support:cardview-v7:25.0.1'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.6'
    compile 'com.amazonaws:aws-android-sdk-mobileanalytics:2.2.9'
    compile 'com.commit451:PhotoView:1.2.4'
    compile 'commons-lang:commons-lang:2.3'
    compile 'com.karumi:dexter:2.3.1'
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
    implementation 'com.android.support:multidex:1.0.2'
    compile 'org.ocpsoft.prettytime:prettytime:3.2.7.Final'
    compile 'com.koushikdutta.async:androidasync:2.+'
    compile 'com.soundcloud.android:android-crop:1.0.1@aar'
    compile 'net.danlew:android.joda:2.9.4.1'
    compile 'com.albinmathew:photo-crop-library:1.0.3'
    compile 'com.amazonaws:aws-android-sdk-core:2.2.+'
    compile 'com.amazonaws:aws-android-sdk-s3:2.2.+'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.wowza.gocoder.sdk.android:com.wowza.gocoder.sdk:1.0b7@aar'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.4@aar') {
        transitive = true;
    }
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    //    compile 'com.cocosw:bottomsheet:1.+@aar'
    compile project(':libbambuser7')
    compile 'com.squareup.okhttp:okhttp:2.0.0'
}

apply plugin: 'com.google.gms.google-services'

Body:
Try this

Use this

com.google.android.gms:play-services:11.6.0

com.google.android.gms:play-services-location:11.6.0

Instead of this

com.google.android.gms:play-services:9.8.0

after  Sync ->  clean ->  rebuild


来源: stackexchange

问:
How to fetch the Public IP of the newly launched machine using Terraform
I have created two instances (Instance-1 and Instance-2) in AWS using Terraform. I installed Ansible on Instance-1 in the same script and I want to push a playbook to Instance-2 from Instance-1.

I want to specify the public-IP, username and key path to the Ansible Host file inside Instance-1 where I installed Ansible.

How can I fetch the public-IP of Instance-2 for specifying the aforementioned attributes in the Ansible host file ?

答:
You can fetch the public_ip of the launched instances through terrraform using,

resource "aws_instance" "web" {

....

provisioner "local-exec" {

```<code>command = "echo ${aws_instance.web.public_ip} >> /path/to/save"
</code>```

}

https://www.terraform.io/docs/provisioners/local-exec.html

ContentLicense: CC BY-SA 3.0

Body:
You can fetch the public_ip of the launched instances through terrraform using,

resource "aws_instance" "web" {

....

provisioner "local-exec" {

command = "echo ${aws_instance.web.public_ip} >> /path/to/save"

}

https://www.terraform.io/docs/provisioners/local-exec.html


问:
Swagger node is taking URL phrase as parameter
I'm using swagger-node for REST APIs and I've found an absurd issue here.

Here's my one of GET requests:

```<code>GET: /students/{id}/{name}
</code>```

(id is number)

And now I wrote another request:

```<code>GET: /students/routeInfo/{id}
</code>```

But the 2nd request me following error:

Expected type is number, found type string. Which clearly means 2nd request is trying to "mask" 1st request. Which I think shouldn't be.

Am I doing something wrong or is there any other way to handle this?

答:
The exact same situation is described in the OpenAPI specification v3.0 document: section Path Templating Matching, 3rd example. It is called ambiguous matching, and "... it's up to the tooling to decide which path to use."  The tool, of course, being swagger-node.

It is weird though,  isn't it!

Body:
I'm using swagger-node for REST APIs and I've found an absurd issue here.

Here's my one of GET requests:

GET: /students/{id}/{name}

(id is number)

And now I wrote another request:

GET: /students/routeInfo/{id}

But the 2nd request me following error:

Expected type is number, found type string. Which clearly means 2nd request is trying to "mask" 1st request. Which I think shouldn't be.

Am I doing something wrong or is there any other way to handle this?


问:
How do you go from a sip.voidptr (QImage.constBits()) to a ctypes void or char pointer?
I'm using python and of course you can't loop through every pixel of a large image very quickly, so I defer to a C DLL.

I want to do something like this:

```<code>img = QImage("myimage.png").constBits()
imgPtr = c_void_p(img)
found = ctypesDLL.myImageSearchMethod(imgPtr, width, height)
</code>```

But this line
    imgPtr = c_void_p(img)
yelds

builtins.TypeError: cannot be converted to pointer

I don't need to modify the bits.  Please teach me your Jedi ways in this area.

答:
As stated here, sip.voidptr.__int__() method

returns the address as an integer

while c_void_p documentation says

The constructor accepts an optional integer initializer.

So you should be able to build a c_void_p passing the return value of sip.voidptr.__int__() method to its constructor:

```<code>imgPtr = c_void_p(img.__int__())
</code>```

I tested this solution this way:

```<code>from PyQt5 import QtGui
from ctypes import *

lib = CDLL("/usr/lib/libtestlib.so")

image = QtGui.QImage("so.png")
bits = image.constBits()
bytes = image.bytesPerLine()
lib.f(c_void_p(bits.__int__()), c_int(image.width()), c_int(image.height()), c_int(bytes))
</code>```

Which works fine with a function like:

```<code>#include <cstdio>
#include <QImage>
extern "C" {

    void f(unsigned char * c, int width, int height, int bpl)
    {
        printf("W:%d H:%d BPL:%d\n", width, height, bpl);
        QImage image(c, width, height, bpl, QImage::Format_RGB32);
        image.save("test.bmp");
    }
}
</code>```

Body:
I'm using python and of course you can't loop through every pixel of a large image very quickly, so I defer to a C DLL.

I want to do something like this:

img = QImage("myimage.png").constBits()
imgPtr = c_void_p(img)
found = ctypesDLL.myImageSearchMethod(imgPtr, width, height)

But this line
    imgPtr = c_void_p(img)
yelds

builtins.TypeError: cannot be converted to pointer

I don't need to modify the bits.  Please teach me your Jedi ways in this area.

Body:
As stated here, sip.voidptr.__int__() method

returns the address as an integer

while c_void_p documentation says

The constructor accepts an optional integer initializer.

So you should be able to build a c_void_p passing the return value of sip.voidptr.__int__() method to its constructor:

imgPtr = c_void_p(img.__int__())

I tested this solution this way:

from PyQt5 import QtGui
from ctypes import *

lib = CDLL("/usr/lib/libtestlib.so")

image = QtGui.QImage("so.png")
bits = image.constBits()
bytes = image.bytesPerLine()
lib.f(c_void_p(bits.__int__()), c_int(image.width()), c_int(image.height()), c_int(bytes))

Which works fine with a function like:

#include <cstdio>
#include <QImage>
extern "C" {

    void f(unsigned char * c, int width, int height, int bpl)
    {
        printf("W:%d H:%d BPL:%d\n", width, height, bpl);
        QImage image(c, width, height, bpl, QImage::Format_RGB32);
        image.save("test.bmp");
    }
}


问:
JSON array parsing with different types
I am using vk.com API and in one method in response I am getting something like this:

```<code>{
    "ts": 1691519416,
    "updates": [
        [
            6,
            2000000024,
            586731
        ],
        [
            4,
            586732,
            8243,
            2000000024,
            1512642885,
            "income message",
            {
                "from": "384574802"
            }
        ]
    ]
}
</code>```

The problem is I am using Gson and I don't know what type of array I need to use.

For now I have this:

```<code>public class Updates {
    public int ts;
    public Update[] updates;
}
</code>```

I don`t know what to put inside/instead of updates array.

Found a solution, thank you guys for answers. I just needed to use generics and a 2 dimensional array. The code of Updates class:

```<code>public class Updates {
    public int ts;
    public <?>[][] updates;
}
</code>```

答:
You can create your class like:

```<code>class Response
{
   Timestamp ts;
   Updates[] updates;
}
</code>```

And use GSON:

```<code>Response response = gson.fromJson(jsonString, Response.class);
</code>```

Title: JSON array parsing with different types

Body:
I am using vk.com API and in one method in response I am getting something like this:

{
    "ts": 1691519416,
    "updates": [
        [
            6,
            2000000024,
            586731
        ],
        [
            4,
            586732,
            8243,
            2000000024,
            1512642885,
            "income message",
            {
                "from": "384574802"
            }
        ]
    ]
}

The problem is I am using Gson and I don't know what type of array I need to use.

For now I have this:

public class Updates {
    public int ts;
    public Update[] updates;
}

I don`t know what to put inside/instead of updates array.

Found a solution, thank you guys for answers. I just needed to use generics and a 2 dimensional array. The code of Updates class:

public class Updates {
    public int ts;
    public <?>[][] updates;
}

Body:
You can create your class like:

class Response
{
   Timestamp ts;
   Updates[] updates;
}

And use GSON:

Response response = gson.fromJson(jsonString, Response.class);


问:
C# Making an Async Call Synchronously
I have a library that only allows for Async calls, my code needs to be synchronous. Will the following code work correctly? Can anyone foresee any problems with it?</p>

```<code>RestResponse<T> response = null;
bool executedCallBack = false;
client.ExecuteAsync(request, (RestResponse<T> aSyncResponse)=>{
    executedCallBack = true;
    response = aSyncResponse;
});

while (!executedCallBack){
    Thread.Sleep(100);
}
..continue execution synchronously
</code>```

答:
Don't poll.  Use the built-in synchronization facilities.

```<code>RestResponse<T> response = null;
var executedCallBack = new AutoResetEvent(false);
client.ExecuteAsync(request, (RestResponse<T> aSyncResponse)=>{
    response = aSyncResponse;
    executedCallBack.Set();
});

executedCallBack.WaitOne();
//continue execution synchronously
</code>```

As a side note, I had to switch the order of operations inside the callback.  Your example had a race condition, since the flag could allow the main thread to continue, and try to read the response, before the callback thread had written it.

ContentLicense: CC BY-SA 2.5

Title: C# Making an Async Call Synchronously

Body:
I have a library that only allows for Async calls, my code needs to be synchronous. Will the following code work correctly? Can anyone foresee any problems with it?

RestResponse<T> response = null;
bool executedCallBack = false;
client.ExecuteAsync(request, (RestResponse<T> aSyncResponse)=>{
    executedCallBack = true;
    response = aSyncResponse;
});

while (!executedCallBack){
    Thread.Sleep(100);
}
..continue execution synchronously

Body:
Don't poll.  Use the built-in synchronization facilities.

RestResponse<T> response = null;
var executedCallBack = new AutoResetEvent(false);
client.ExecuteAsync(request, (RestResponse<T> aSyncResponse)=>{
    response = aSyncResponse;
    executedCallBack.Set();
});

executedCallBack.WaitOne();
//continue execution synchronously

As a side note, I had to switch the order of operations inside the callback.  Your example had a race condition, since the flag could allow the main thread to continue, and try to read the response, before the callback thread had written it.


问:
In bash kill only first process in a pipeline
If I have a long-running command that periodically outputs some data, e.g. tail -F that I want to process with awk (or something else):

```<code>tail -F service.log | awk '{ ... } END { print ... }'
</code>```

How to kill the first process only (tail in this case) so that I could see the result of END {} block in awk? if I press Control+C the whole pipeline is stopped.

One way I've found to be working is to open a separate tab/window of term, grep PID of the first process and kill it from there, but it seems rather clumsy, is there another solution?

答:
Something like this, perhaps?</p>

```<code>tail -F service.log | (trap '' INT; awk '{ ... } END { print ...}')
</code>```

Body:
If I have a long-running command that periodically outputs some data, e.g. tail -F that I want to process with awk (or something else):

tail -F service.log | awk '{ ... } END { print ... }'

How to kill the first process only (tail in this case) so that I could see the result of END {} block in awk? if I press Control+C the whole pipeline is stopped.

One way I've found to be working is to open a separate tab/window of term, grep PID of the first process and kill it from there, but it seems rather clumsy, is there another solution?

Body:
Something like this, perhaps?

tail -F service.log | (trap '' INT; awk '{ ... } END { print ...}')


问:
How to reduce the battery power consumption?
In my application I'm using Google Maps and getting latlon from onLocationChanged(), while it's running in background and also getting that value using services.

Due to this, a lot of battery power is consumed by my application

How can I reduce my application power consuming?

答:
Here you go:

Use setPriority(LocationRequest.PRIORITY_LOW_POWER); in LocationRequest

See documentation Here:


问:
extract the text from doc file using python
```<code>import doc2txt
</code>```

I want to extract the string from the document file with Doc2txt it's give the following error.

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/doc2text/__init__.py", line 7, in <module>
    import PythonMagick
ImportError: No module named 'PythonMagick'
</code>```

答:
Open a terminal first, then:

```<code>sudo apt-get install python-magic
</code>```

or

```<code>pip3 install --user python-magic
</code>```

It will install what you need.

You can take a look here to see how use python-magic

Regards

Body:
import doc2txt

I want to extract the string from the document file with Doc2txt it's give the following error.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/doc2text/__init__.py", line 7, in <module>
    import PythonMagick
ImportError: No module named 'PythonMagick'

Body:
Open a terminal first, then:

sudo apt-get install python-magic

or

pip3 install --user python-magic

It will install what you need.

You can take a look here to see how use python-magic

Regards


问:
push Notification not working in ios ionic using FCM
i have setup all the steps for push notification using https://firebase.google.com/docs/cloud-messaging/ios/first-message#access_the_registration_token but i didn't get notification in ios App but working in Android App and also with http://pushtry.com .how to resolve this issue </p>

答:
I was facing the same problem and after searching for a day here are my conclusions:

Don't forget to allow for push notification in your App ID.Click on edit and then enable push notification.

Make sure your certificates you are using are correct because as you allow for push notification your previous profiles become invalid(In my case they were).So either edit the provision profiles and download again or create new ones.

3.I'll prefer using Apn-auth key as suggested on main firebase site instead of apns certificates.

4.One of the major point which I was missing was  the problem with xcode Enable push notification there in the xcode as well which
  are not enabled by default.

If your app is closing soon after opening your plist might be the cause Follow this answer for solution .

Last thing that really helped me fix the issue was a mac OS update.I was trying to build using xcode 7.2 which was quiet dumb part on my
  side.There when I tried to enable push notification.It made changes to
  my certificates and then I downloaded the provisional profile after
  editing them(So valid now) and then build and everything started
  working fine as hell.

ContentLicense: CC BY-SA 4.0


问:
How can I take a screenshot of an alert using Selenium webdriver in Ruby?
Hi I'm a new user of selenium. I'm trying to take a screenshot of an alert using selenium webdriver in ruby.

```<code>@driver.find_element(:name, "updateButton").click
@driver.save_screenshot "./#{Time.now.strftime("Alert_Screenshot___%d_%m_%Y__%H_%M_%S")}.png"
</code>```

Instead of taking a screenshot, this error is thown:

Selenium::WebDriver::Error::UnhandledAlertError

Of course I can accept the alert:

```<code>@driver.switch_to.alert.accept
</code>```

and then take a screenshot. But I want to know is there way to take the screenshot while the alert is being prompted?

答:
In your case you need to take screenshot for complete screen, not only the browser. So you can use xwd to take a screenshot of the root window:</p>

```<code>xwd -display :0 -root|xwdtopnm |pnmtopng > $1
</code>```

Body:
Hi I'm a new user of selenium. I'm trying to take a screenshot of an alert using selenium webdriver in ruby.

@driver.find_element(:name, "updateButton").click
@driver.save_screenshot "./#{Time.now.strftime("Alert_Screenshot___%d_%m_%Y__%H_%M_%S")}.png"

Instead of taking a screenshot, this error is thown:

Selenium::WebDriver::Error::UnhandledAlertError

Of course I can accept the alert:

@driver.switch_to.alert.accept

and then take a screenshot. But I want to know is there way to take the screenshot while the alert is being prompted?

Body:
In your case you need to take screenshot for complete screen, not only the browser. So you can use xwd to take a screenshot of the root window:

xwd -display :0 -root|xwdtopnm |pnmtopng > $1


问:
C++ - How can I avoid this header from appearing twice?
At: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

Under Header guards, there are those code snippets:

add.h:

```<code>#include "mymath.h"
int add(int x, int y);
</code>```

subtract.h:

```<code>#include "mymath.h"
int subtract(int x, int y);
</code>```

main.cpp:

```<code>#include "add.h"
#include "subtract.h"
</code>```

How can I avoid #include "mymath.h" from appearing twice in main.cpp?

Thanks.

答: You should put your header guards in any header, also in mymath.h.</p>

Body:
At: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

Under Header guards, there are those code snippets:

add.h:

#include "mymath.h"
int add(int x, int y);

subtract.h:

#include "mymath.h"
int subtract(int x, int y);

main.cpp:

#include "add.h"
#include "subtract.h"

How can I avoid #include "mymath.h" from appearing twice in main.cpp?

Thanks.


问:
Authenticate Devise User Before Accessing Omniauth Routes
I'm developing an app that utilizes devise for my user records and omniauth for records owned by the user, rather than using the typical omniauth + devise for user records. I'm trying to add devise's user authentication to the omniauth routes /auth/:provider so that non-registered visitors cannot access those routes and trigger the auth process for a specific provider.

I've been able to add authentication to the callbacks by using devise's authenticate_user! helper method in my Sessions controller, so I'm at least stopping non-registered visitors from being able to create records from the omniauth flow, but I'd like to have devise's user auth working in all phases of the omniauth flow.

Any ideas on how to add devise's user auth to the initial omniauth routes whether using something similar to my current solution or through my routes.rb file using devise's authenticate :user do?

答:
Add the devise autheticate_user! in application controller.
or use before filter to call it before omniauth authentication methods.


问:
Latest JxBrowser crashes on OSX
One of our users is reporting a consistent JxBrowser crash on Mac OS X 10.12.6

They are using JxBrowser v6.17, the Oracle jre1.8.0_152 and the latest webdrivers.

The full crash log is available here: https://github.com/zaproxy/zaproxy/issues/4126

Any suggestions?

答:
JxBrowser has two rendering modes: lightweight and heavyweight. In the heavyweight rendering mode we embed a native window into your Java application window and configure Chromium engine to render content into this native window using GPU. In order to embed the native window on Mac we have to initialize Chromium engine in Java process. JavaFX WebView is based on WebKit engine that is also initialized in Java process. The crash you see usually occurs when you mix both JxBrowser and JavaFX WebView in the same application. We do not recommend using JxBrowser in heavyweight mode and JavaFX WebView in the same application on Mac.

In case you have to use both JxBrowser and JavaFX WebView I recommend that you switch to the lightweight rendering mode in JxBrowser. To do that you need to start JxBrowser with the following VM parameter:

-Djxbrowser.ipc.external=true

This will force JxBrowser to initialize Chromium in a separate native process that will allow you to avoid conflicts between JxBrowser and WebView. It's not possible to use JxBrowser in the heavyweight rendering mode in this case.

If you need to use JxBrowser in heavyweight mode with JavaFX WebView in the same application you should make sure that the BrowserCore.initialize() method is invoked before creating any WebView instance.

Title: Latest JxBrowser crashes on OSX


问:
Php JSON encode array and unexpected token error in decoding
I got an array from an SQL query, encoded it and when I decode in javascript I receive the error

Unexpected token a in JSON at position 0

The var_dump of the array before the encode:

```<code>array(1) { [0]=> array(10) { ["order_id"]=> string(10) "1512642144"
["order_erp_id"]=> string(1) "0" ["order_type"]=> string(3) "web"
["order_date"]=> string(23) "2017-12-07 11:22:24.263" ["order_total"]=>
string(4) "0.00" ["order_desc1"]=> string(3) "web" ["order_desc2"]=>
string(4) "test" ["no_items"]=> string(1) "0" ["order_count"]=> int(1)
["item_arr"]=> string(0) "" } }
[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]
</code>```

then I  encode and send it with:

```<code>echo json_encode($order_item_arr);
</code>```

On the client side, I receive the data and before the decoding step I have this from the console.log(data); in javascript:

```<code>array(1) {
[0]=>
array(10) {
["order_id"]=>
string(10) "1512642144"
["order_erp_id"]=>
string(1) "0"
["order_type"]=>
string(3) "web"
["order_date"]=>
string(23) "2017-12-07 11:22:24.263"
["order_total"]=>
string(4) "0.00"
["order_desc1"]=>
string(3) "web"
["order_desc2"]=>
string(4) "test"
["no_items"]=>
string(1) "0"
["order_count"]=>
int(1)
["item_arr"]=>
string(0) ""
  }
}

[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]
</code>```

So it looks like quite ok, and when I decode it with JSON.parse(data); I have the error:

```<code>VM414:1 Uncaught SyntaxError: Unexpected token a in JSON at position 0
</code>```

答:
Don't output var_dump on your PHP page, it invalidates the json on that page. Remove the var_dump() and the errors will go away.

As you can see from:

Unexpected token a in JSON at position 0

That the error is occurring due to array(1) {, which is not a valid json. And is breaking the entire json data along with it.

So, just remove the var_dump().

Look at this:

```<code>array(1) {
[0]=>
array(10) {
["order_id"]=>
string(10) "1512642144"
["order_erp_id"]=>
string(1) "0"
["order_type"]=>
string(3) "web"
["order_date"]=>
string(23) "2017-12-07 11:22:24.263"
["order_total"]=>
string(4) "0.00"
["order_desc1"]=>
string(3) "web"
["order_desc2"]=>
string(4) "test"
["no_items"]=>
string(1) "0"
["order_count"]=>
int(1)
["item_arr"]=>
string(0) ""
  }
}
</code>```

Removing var_dump() will remove the above part and, only thing which will remain is the string below, which is valid json.

```<code>[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]
</code>```

Body:
I got an array from an SQL query, encoded it and when I decode in javascript I receive the error

Unexpected token a in JSON at position 0

The var_dump of the array before the encode:

array(1) { [0]=> array(10) { ["order_id"]=> string(10) "1512642144"
["order_erp_id"]=> string(1) "0" ["order_type"]=> string(3) "web"
["order_date"]=> string(23) "2017-12-07 11:22:24.263" ["order_total"]=>
string(4) "0.00" ["order_desc1"]=> string(3) "web" ["order_desc2"]=>
string(4) "test" ["no_items"]=> string(1) "0" ["order_count"]=> int(1)
["item_arr"]=> string(0) "" } }
[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]

then I  encode and send it with:

echo json_encode($order_item_arr);

On the client side, I receive the data and before the decoding step I have this from the console.log(data); in javascript:

array(1) {
[0]=>
array(10) {
["order_id"]=>
string(10) "1512642144"
["order_erp_id"]=>
string(1) "0"
["order_type"]=>
string(3) "web"
["order_date"]=>
string(23) "2017-12-07 11:22:24.263"
["order_total"]=>
string(4) "0.00"
["order_desc1"]=>
string(3) "web"
["order_desc2"]=>
string(4) "test"
["no_items"]=>
string(1) "0"
["order_count"]=>
int(1)
["item_arr"]=>
string(0) ""
  }
}

[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]

So it looks like quite ok, and when I decode it with JSON.parse(data); I have the error:

VM414:1 Uncaught SyntaxError: Unexpected token a in JSON at position 0

Body:
Don't output var_dump on your PHP page, it invalidates the json on that page. Remove the var_dump() and the errors will go away.

As you can see from:

Unexpected token a in JSON at position 0

That the error is occurring due to array(1) {, which is not a valid json. And is breaking the entire json data along with it.

So, just remove the var_dump().

Look at this:

array(1) {
[0]=>
array(10) {
["order_id"]=>
string(10) "1512642144"
["order_erp_id"]=>
string(1) "0"
["order_type"]=>
string(3) "web"
["order_date"]=>
string(23) "2017-12-07 11:22:24.263"
["order_total"]=>
string(4) "0.00"
["order_desc1"]=>
string(3) "web"
["order_desc2"]=>
string(4) "test"
["no_items"]=>
string(1) "0"
["order_count"]=>
int(1)
["item_arr"]=>
string(0) ""
  }
}

Removing var_dump() will remove the above part and, only thing which will remain is the string below, which is valid json.

[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]


问:
mysql query returns false, mysql insert works but echo statement doesn't show up
I am making a text-based online game, in my game, there is a battle system. After defeating the enemy you can be awarded a badge if you do not already have said badge. However, for some strange reason that I can not wrap my head around, the badge is added to the database as it should be (if the table row for the badge does not exist on the MySQL database) but the text that should accompany earning the badge shows up sometimes. I would say the echo shows 50% of the time or less. Here is my code:

```<code>$gettrainerbadge = mysqli_query($conn, "SELECT * FROM t_badges where
badge='$badge' AND trainer='$getuser3[username]'");
$gettrainerbadge2 = mysqli_fetch_assoc($gettrainerbadge);

if(!$gettrainerbadge2)
{
    //This echo shows up maybe 50% of the time the form is submitted.

    echo "<font face='verdana' size='2'><br><br><br><img src='images/badges/$get_gym_leader3[badge].png' style='padding: 10px;'><br>By defeating $getuser3[battle_trainer] you have also earned a(n) $get_gym_leader3[badge] Badge!";

    //This INSERT works as expected when the badge doesn't exist it adds the badge to the database if the badge already exists it does nothing

    $addbadge = "INSERT INTO t_badges (`trainer`, `badge`) VALUES ('$getuser3[username]', '$get_gym_leader3[badge]')";
    mysqli_query($conn, $addbadge);

}
</code>```

As I've said the echo statement works half the time, it should work every time and I can not figure out why the badge is being added but the text that accompanies it doesn't show. Any help is appreciated.

After playing with the code some more I've noticed that sometimes I can see a VERY fast flash of the page with the image of the badge, so I don't think the above code is to blame. I think it has to do with the following scripts I am using to submit the forms automatically without user feedback. I don't know why they would interfere with each other, but I'm almost certain that there is a double post submission going on somewhere. If anyone could help point out what I might be doing wrong here I would appreciate it.

```<code>if($get_remaining_opponents3 > '0')
{

print "<form action='index.php?action=battle' method='POST'
name='attackselect' id='attackselect' style='margin: 0px;'><td width='100%'
height='50px' style='background: #e6e6e6; border:2px solid #e6e6e6; border-
radius: 25px;'>

<center>

<font face='verdana' size='2'>

<label style='margin-top: 0px;' id='battle_text'>

<input type='radio' name='continue' value='continue' checked>

<i>Resuming battle ... (<span id='continue'> </span>)</i>
</input>
</label>
</form>
";
?>

<script>

var milisec= 0;
var seconds=4;

document.getElementById("continue").innerHTML ='4';
continue_battle() ;

function continue_battle(){
if (milisec<=0){
milisec=9;
seconds-=1;
}
if (seconds<=-1){
milisec=0;
seconds+=1;
}
else
{
milisec-=1;
document.getElementById("continue").innerHTML =seconds;
setTimeout("continue_battle()",100);
}
if(document.getElementById("continue").innerHTML == '0')
{
document.getElementById("attackselect").submit();
}
}
</script>

<?php
print "</form>";
}
else
{

print "<form action='index.php?action=battle' method='POST' name='victory'
id='victorious' style='margin: 0px;'><td width='100%' height='50px'
style='background: #e6e6e6; border:2px solid #e6e6e6; border-radius: 25px;'>

<center>

<font face='verdana' size='2'>

<label style='margin-top: 0px;' id='battle_text'>

<input type='radio' name='victory' value='$getuser3[opp_level]' checked>

<i>Resuming battle ... (<span id='victory'> </span>)</i>
</input>
</label>
</form>
";
?>

<script>

var milisec= 0;
var seconds=4;

document.getElementById("victory").innerHTML ='4';
victorious() ;

function victorious(){
if (milisec<=0){
milisec=9;
seconds-=1;
}
if (seconds<=-1){
milisec=0;
seconds+=1;
}
else
{
milisec-=1;
document.getElementById("victory").innerHTML =seconds;
setTimeout("victorious()",100);
}
if(document.getElementById("victory").innerHTML == '0')
{
document.getElementById("victorious").submit();
}
}
</script>

<?php
print "</form>";
}
</code>```

答:
```<code>$gettrainerbadge = mysqli_query($conn, "SELECT * FROM t_badges where badge='".$badge."' AND trainer='".$getuser3['username']."'");
$gettrainerbadge2 = mysqli_fetch_assoc($gettrainerbadge);

if(count($gettrainerbadge2) == 0)
{

     echo "<font face='verdana' size='2'><br><br><br><img src='images/badges/".$get_gym_leader3['badge'].".png' style='padding: 10px;'><br>By defeating ".$getuser3['battle_trainer']." you have also earned a(n) ".$get_gym_leader3[badge]." Badge!";

    //This INSERT works as expected when the badge doesn't exist it adds the badge to the database if the badge already exists it does nothing

    $addbadge = "INSERT INTO t_badges (`trainer`, `badge`) VALUES ('".$getuser3['username']."', '".$get_gym_leader3['badge']."')";
    mysqli_query($conn, $addbadge);

}
</code>```

Try using count variable i hope it should work for every match records.

Body:
I am making a text-based online game, in my game, there is a battle system. After defeating the enemy you can be awarded a badge if you do not already have said badge. However, for some strange reason that I can not wrap my head around, the badge is added to the database as it should be (if the table row for the badge does not exist on the MySQL database) but the text that should accompany earning the badge shows up sometimes. I would say the echo shows 50% of the time or less. Here is my code:

$gettrainerbadge = mysqli_query($conn, "SELECT * FROM t_badges where
badge='$badge' AND trainer='$getuser3[username]'");
$gettrainerbadge2 = mysqli_fetch_assoc($gettrainerbadge);

if(!$gettrainerbadge2)
{
    //This echo shows up maybe 50% of the time the form is submitted.

    echo "

By defeating $getuser3[battle_trainer] you have also earned a(n) $get_gym_leader3[badge] Badge!";

    //This INSERT works as expected when the badge doesn't exist it adds the badge to the database if the badge already exists it does nothing

    $addbadge = "INSERT INTO t_badges (`trainer`, `badge`) VALUES ('$getuser3[username]', '$get_gym_leader3[badge]')";
    mysqli_query($conn, $addbadge);

}

As I've said the echo statement works half the time, it should work every time and I can not figure out why the badge is being added but the text that accompanies it doesn't show. Any help is appreciated.

After playing with the code some more I've noticed that sometimes I can see a VERY fast flash of the page with the image of the badge, so I don't think the above code is to blame. I think it has to do with the following scripts I am using to submit the forms automatically without user feedback. I don't know why they would interfere with each other, but I'm almost certain that there is a double post submission going on somewhere. If anyone could help point out what I might be doing wrong here I would appreciate it.

if($get_remaining_opponents3 > '0')
{

print "<form action='index.php?action=battle' method='POST'
name='attackselect' id='attackselect' style='margin: 0px;'>

<input type='radio' name='continue' value='continue' checked>

Resuming battle ... ( )
</input>

</form>
";
?>

<?php
print "</form>";
}
else
{

print "<form action='index.php?action=battle' method='POST' name='victory'
id='victorious' style='margin: 0px;'>

<input type='radio' name='victory' value='$getuser3[opp_level]' checked>

Resuming battle ... ( )
</input>

</form>
";
?>

<?php
print "</form>";
}

Body:
$gettrainerbadge = mysqli_query($conn, "SELECT * FROM t_badges where badge='".$badge."' AND trainer='".$getuser3['username']."'");
$gettrainerbadge2 = mysqli_fetch_assoc($gettrainerbadge);

if(count($gettrainerbadge2) == 0)
{

     echo "<font face='verdana' size='2'><br><br><br><img src='images/badges/".$get_gym_leader3['badge'].".png' style='padding: 10px;'><br>By defeating ".$getuser3['battle_trainer']." you have also earned a(n) ".$get_gym_leader3[badge]." Badge!";

    //This INSERT works as expected when the badge doesn't exist it adds the badge to the database if the badge already exists it does nothing

    $addbadge = "INSERT INTO t_badges (`trainer`, `badge`) VALUES ('".$getuser3['username']."', '".$get_gym_leader3['badge']."')";
    mysqli_query($conn, $addbadge);

}

Try using count variable i hope it should work for every match records.


问:
slf4j log4j hello world problems
I tried searching for a solution to my error, however, due to similar questions being asked a lot, the swamp of results hasn't helped find an answer to my question.

I'm basically trying to get a simple "Hello World" in slf4j with log4j to work, so that I can later further customize it.

My Project is basically the maven hello world project, slightly adjusted:

App.java:

```<code>package xx.xxxx.logging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        System.out.println("Hello World!");

        LOGGER.info("Hello Logger!");
    }
}
</code>```

log4j2.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

        <Appenders>
                <Console name="STDOUT" target="System.out">
                        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
                </Console>
        </Appenders>

        <Loggers>
                <Root level="ALL">
                        <AppenderRef ref="STDOUT"/>
                </Root>
        </Loggers>

</Configuration>
</code>```

pom.xml:

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

  <groupId>xx.xxxx.logging</groupId>
  <artifactId>logging-test</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>

  <name>logging-test</name>

  <properties>
    <jdk.version>1.8</jdk.version>
    <java.version>1.8</java.version>

    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
    <sonar.java.source>${java.version}</sonar.java.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <version.sl4j>1.7.21</version.sl4j>
    <version.sl4j.log4j>2.0.1</version.sl4j.log4j>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${version.sl4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
  </dependencies>

</project>
</code>```

Trying to run App.java yields the following error:

```<code>2017-12-07 11:14:33,263 ERROR catching java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:133)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:744)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:683)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:675)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:349)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:150)
    at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:364)
    at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:422)
    at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:146)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:75)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:37)
    at org.apache.logging.log4j.LogManager.getContext(LogManager.java:263)
    at org.apache.logging.slf4j.Log4jLoggerFactory$PrivateManager.getContext(Log4jLoggerFactory.java:98)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getContext(Log4jLoggerFactory.java:84)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:44)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:358)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:383)
    at xx.xxxx.logging.App.<clinit>(App.java:8)
Caused by: java.lang.IllegalArgumentException: No enum constant org.apache.logging.log4j.core.appender.ConsoleAppender.Target.System.out
    at java.lang.Enum.valueOf(Enum.java:238)
    at org.apache.logging.log4j.core.appender.ConsoleAppender$Target.valueOf(ConsoleAppender.java:57)
    at org.apache.logging.log4j.core.appender.ConsoleAppender.createAppender(ConsoleAppender.java:98)
    ... 22 more

2017-12-07 11:14:33,268 ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.appender.ConsoleAppender for element Console.
2017-12-07 11:14:33,269 ERROR Null object returned for Console in Appenders.
2017-12-07 11:14:33,275 ERROR Unable to locate appender STDOUT for logger
Hello World!
</code>```

Any leads on how to fix this would be greatly appreciated.

答:
target="System.out" is obviously incorrect. It is related to ConsoleAppender.Target enum. I assume you want target="SYSTEM_OUT" as per https://logging.apache.org/log4j/2.x/log4j-core/apidocs/org/apache/logging/log4j/core/appender/ConsoleAppender.Target.html

Or just omit the attribute as by default it is SYSTEM_OUT already.

Title: slf4j log4j hello world problems

Body:
I tried searching for a solution to my error, however, due to similar questions being asked a lot, the swamp of results hasn't helped find an answer to my question.

I'm basically trying to get a simple "Hello World" in slf4j with log4j to work, so that I can later further customize it.

My Project is basically the maven hello world project, slightly adjusted:

App.java:

package xx.xxxx.logging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        System.out.println("Hello World!");

        LOGGER.info("Hello Logger!");
    }
}

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

        <Appenders>
                <Console name="STDOUT" target="System.out">
                        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
                </Console>
        </Appenders>

        <Loggers>
                <Root level="ALL">
                        <AppenderRef ref="STDOUT"/>
                </Root>
        </Loggers>

</Configuration>

pom.xml:

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

  <groupId>xx.xxxx.logging</groupId>
  <artifactId>logging-test</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>

  <name>logging-test</name>

  <properties>
    <jdk.version>1.8</jdk.version>
    <java.version>1.8</java.version>

    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
    <sonar.java.source>${java.version}</sonar.java.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <version.sl4j>1.7.21</version.sl4j>
    <version.sl4j.log4j>2.0.1</version.sl4j.log4j>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${version.sl4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
  </dependencies>

</project>

Trying to run App.java yields the following error:

2017-12-07 11:14:33,263 ERROR catching java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:133)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:744)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:683)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:675)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:349)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:150)
    at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:364)
    at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:422)
    at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:146)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:75)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:37)
    at org.apache.logging.log4j.LogManager.getContext(LogManager.java:263)
    at org.apache.logging.slf4j.Log4jLoggerFactory$PrivateManager.getContext(Log4jLoggerFactory.java:98)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getContext(Log4jLoggerFactory.java:84)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:44)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:358)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:383)
    at xx.xxxx.logging.App.<clinit>(App.java:8)
Caused by: java.lang.IllegalArgumentException: No enum constant org.apache.logging.log4j.core.appender.ConsoleAppender.Target.System.out
    at java.lang.Enum.valueOf(Enum.java:238)
    at org.apache.logging.log4j.core.appender.ConsoleAppender$Target.valueOf(ConsoleAppender.java:57)
    at org.apache.logging.log4j.core.appender.ConsoleAppender.createAppender(ConsoleAppender.java:98)
    ... 22 more

2017-12-07 11:14:33,268 ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.appender.ConsoleAppender for element Console.
2017-12-07 11:14:33,269 ERROR Null object returned for Console in Appenders.
2017-12-07 11:14:33,275 ERROR Unable to locate appender STDOUT for logger
Hello World!

Any leads on how to fix this would be greatly appreciated.


问:
What is in your Mathematica tool bag?
We all know that Mathematica is great, but it also often lacks critical functionality. What kind of external packages / tools / resources do you use with Mathematica?

I'll edit (and invite anyone else to do so too) this main post to include resources which are focused on general applicability in scientific research and which as many people as possible will find useful. Feel free to contribute anything, even small code snippets (as I did below for a timing routine).

Also, undocumented and useful features in Mathematica 7 and beyond you found yourself, or dug up from some paper/site are most welcome.

Please include a short description or comment on why something is great or what utility it provides. If you link to books on Amazon with affiliate links please mention it, e.g., by putting your name after the link.

Packages:

LevelScheme is a package that greatly expands Mathematica's capability to produce good looking plots. I use it if not for anything else then for the much, much improved control over frame/axes ticks. Its newest version is called SciDraw, and it will be released sometime this year.

David Park's Presentation Package (US$50 - no charge for updates)

Jeremy Michelson's grassmannOps package provides resources for doing algebra and calculus with Grassmann variables and operators that have non trivial commutation relations.

John Brown's GrassmannAlgebra package and book for working with Grassmann and Clifford algebras.

RISC (Research Institute for Symbolic Computation) has a variety of packages for Mathematica (and other languages) available for download. In particular, there is Theorema for automated theorem proving, and the multitude of packages for symbolic summation, difference equations, etc. at the Algorithmic Combinatorics group's software page.

Tools:

MASH is Daniel Reeves's excellent Perl script essentially providing scripting support for Mathematica v7. (Now built in as of Mathematica 8 with the -script option.)

An alternate Mathematica shell with a GNU readline input (using python, *nix only)

ColourMaths package allows you to visually select parts of an expression and manipulate them. http://www.dbaileyconsultancy.co.uk/colour_maths/colour_maths.html

Resources:

Wolfram's own repository MathSource has a lot of useful if narrow notebooks for various applications. Also check out the other sections such as

Current Documentation,

Courseware for lectures,

and Demos for, well, demos.

The Mathematica Wikibook.

Books:

Mathematica programming: an advanced introduction by Leonid Shifrin (web, pdf) is a must read if you want to do anything more than For loops in Mathematica. We have the pleasure of having Leonid himself answering questions here.

Quantum Methods with Mathematica by James F. Feagin (amazon)

The Mathematica Book by Stephen Wolfram (amazon) (web)

Schaum's Outline (amazon)

Mathematica in Action by Stan Wagon (amazon) - 600 pages of neat examples and goes up to Mathematica version 7. Visualization techniques are especially good, you can see some of them on the author's Demonstrations Page.

Mathematica Programming Fundamentals by Richard Gaylord (pdf) - A good concise introduction to most of what you need to know about Mathematica programming.

Mathematica Cookbook by Sal Mangano published by O'Reilly 2010 832 pages. - Written in the well known O'Reilly Cookbook style: Problem - Solution. For intermediates.

Differential Equations with  Mathematica, 3rd Ed. Elsevier 2004 Amsterdam
by Martha L. Abell, James P. Braselton - 893 pages For beginners, learn solving DEs and Mathematica at the same time.

Undocumented (or scarcely documented) features:

How to customize Mathematica keyboard shortcuts. See this question.

How to inspect patterns and functions used by Mathematica's own functions. See this answer

How to achieve consistent size for GraphPlots in Mathematica? See this question.

How to produce documents and presentations with Mathematica. See this question.

答:
Mathematica is a sharp tool, but it can cut you with its somewhat untyped behaviour and avalanches of cryptic diagnostic messages.  One way to deal with this is to define functions following this idiom:

```<code>ClearAll@zot
SetAttributes[zot, ...]
zot[a_] := ...
zot[b_ /; ...] := ...
zot[___] := (Message[zot::invalidArguments]; Abort[])
</code>```

That is a lot of boilerplate, which I'm frequently tempted to skip.  Especially when prototyping, which happens a lot in Mathematica.  So, I use a macro called define that allows me to stay disciplined, with much less boilerplate.

A basic usage of define is like this:

```<code>define[
  fact[0] = 1
; fact[n_ /; n > 0] := n * fact[n-1]
]

fact[5]

120
</code>```

It doesn't look like much at first, but there are some hidden benefits.  The first service that define provides is that it automatically applies ClearAll to the symbol being defined.  This ensures that there are no leftover definitions -- a common occurrence during the initial development of a function.

The second service is that the function being defined is automatically "closed".  By this I mean that the function will issue a message and abort if it is invoked with an argument list that is not matched by one of the definitions:

```<code>fact[-1]

define::badargs: There is no definition for 'fact' applicable to fact[-1].
$Aborted
</code>```

This is the primary value of define, which catches a very common class of error.

Another convenience is a concise way to specify attributes on the function being defined.  Let's make the function Listable:

```<code>define[
  fact[0] = 1
; fact[n_ /; n > 0] := n * fact[n-1]
, Listable
]

fact[{3, 5, 8}]

{6, 120, 40320}
</code>```

In addition to all of the normal attributes, define accepts an additional attribute called Open.  This prevents define from adding the catch-all error definition to the function:

```<code>define[
  successor[x_ /; x > 0] := x + 1
, Open
]

successor /@ {1, "hi"}

{2, successor["hi"]}
</code>```

Multiple attributes may be defined for a function:

```<code>define[
  flatHold[x___] := Hold[x]
, {Flat, HoldAll}
]

flatHold[flatHold[1+1, flatHold[2+3]], 4+5]

Hold[1 + 1, 2 + 3, 4 + 5]
</code>```

Without further ado, here is the definition of define:

```<code>ClearAll@define
SetAttributes[define, HoldAll]
define[body_, attribute_Symbol] := define[body, {attribute}]
define[body:(_Set|_SetDelayed), attributes_List:{}] := define[CompoundExpression[body], attributes]
define[body:CompoundExpression[((Set|SetDelayed)[name_Symbol[___], _])..], attributes_List:{}] :=
  ( ClearAll@name
  ; SetAttributes[name, DeleteCases[attributes, Open]]
  ; If[!MemberQ[attributes, Open]
    , def:name[___] := (Message[define::badargs, name, Defer@def]; Abort[])
    ]
  ; body
  ;
  )
def:define[___] := (Message[define::malformed, Defer@def]; Abort[])

define::badargs = "There is no definition for '``' applicable to ``.";
define::malformed = "Malformed definition: ``";
</code>```

The exhibited implementation supports neither up-values nor currying, nor patterns more general than simple function definition.  It remains useful, however.

Title: What is in your Mathematica tool bag?

Body:
Mathematica is a sharp tool, but it can cut you with its somewhat untyped behaviour and avalanches of cryptic diagnostic messages.  One way to deal with this is to define functions following this idiom:

ClearAll@zot
SetAttributes[zot, ...]
zot[a_] := ...
zot[b_ /; ...] := ...
zot[___] := (Message[zot::invalidArguments]; Abort[])

That is a lot of boilerplate, which I'm frequently tempted to skip.  Especially when prototyping, which happens a lot in Mathematica.  So, I use a macro called define that allows me to stay disciplined, with much less boilerplate.

A basic usage of define is like this:

define[
  fact[0] = 1
; fact[n_ /; n > 0] := n * fact[n-1]
]

fact[5]

120

It doesn't look like much at first, but there are some hidden benefits.  The first service that define provides is that it automatically applies ClearAll to the symbol being defined.  This ensures that there are no leftover definitions -- a common occurrence during the initial development of a function.

The second service is that the function being defined is automatically "closed".  By this I mean that the function will issue a message and abort if it is invoked with an argument list that is not matched by one of the definitions:

fact[-1]

define::badargs: There is no definition for 'fact' applicable to fact[-1].
$Aborted

This is the primary value of define, which catches a very common class of error.

Another convenience is a concise way to specify attributes on the function being defined.  Let's make the function Listable:

define[
  fact[0] = 1
; fact[n_ /; n > 0] := n * fact[n-1]
, Listable
]

fact[{3, 5, 8}]

{6, 120, 40320}

In addition to all of the normal attributes, define accepts an additional attribute called Open.  This prevents define from adding the catch-all error definition to the function:

define[
  successor[x_ /; x > 0] := x + 1
, Open
]

successor /@ {1, "hi"}

{2, successor["hi"]}

Multiple attributes may be defined for a function:

define[
  flatHold[x___] := Hold[x]
, {Flat, HoldAll}
]

flatHold[flatHold[1+1, flatHold[2+3]], 4+5]

Hold[1 + 1, 2 + 3, 4 + 5]

Without further ado, here is the definition of define:

ClearAll@define
SetAttributes[define, HoldAll]
define[body_, attribute_Symbol] := define[body, {attribute}]
define[body:(_Set|_SetDelayed), attributes_List:{}] := define[CompoundExpression[body], attributes]
define[body:CompoundExpression[((Set|SetDelayed)[name_Symbol[___], _])..], attributes_List:{}] :=
  ( ClearAll@name
  ; SetAttributes[name, DeleteCases[attributes, Open]]
  ; If[!MemberQ[attributes, Open]
    , def:name[___] := (Message[define::badargs, name, Defer@def]; Abort[])
    ]
  ; body
  ;
  )
def:define[___] := (Message[define::malformed, Defer@def]; Abort[])

define::badargs = "There is no definition for '``' applicable to ``.";
define::malformed = "Malformed definition: ``";

The exhibited implementation supports neither up-values nor currying, nor patterns more general than simple function definition.  It remains useful, however.


问:
MongoDB - $push if array length < n, while update_one
That's a small part of my update query using pymongo in python. I want to $push ip variable to an array only if its length is less than 10. I know that I can solve this problem firstly finding this user (find_one) and checking array's length but it's not an efficient solution. How to handle this problem using mongo?

I read that $cond works only in aggregation so I can't figure anything else.

Part of my script:

```<code>self.db[coll_name].update_one(
             {
                 'summary.userId': user_id
             },
             {'$push':
                 {
                     'summary.ip': ip
                 },
             }
             upsert=True
        )
</code>```

What my brain wants to do:

```<code>self.db[coll_name].update_one(
             {
                 'summary.userId': user_id
             },
             {
                 "$cond": {"if": {"$size": {"$summary.ip": {"$ne": 10}}},
                         "then": {"$push": ip},
                         "else": pass
             }},
             upsert=True
        )
</code>```

I'm trying to limit myself to pymongo but answers using MongoDB with JS are more than welcome.

EDIT: Sorry for the inconvenience.

I want to be able to update other fields event if the condition wasn't met.

```<code>self.db[coll_name].update_one(
                 {
                     'summary.userId': user_id
                 },
                 {'$push':
                     {
                         'summary.ip': ip
                     },

                 '$addToSet':
                     {
                         'summary.something_list': something
                     },
                 }
                 upsert=True
            )
</code>```

If I filter by the length of ip array, I won't add something if ip list eq 9, which I have to do.

答:
In the filter passed to Collections.update_one, you can filter where an ip index of 9 doesn't exist in the collection.

```<code>filter_ = {
    'summary.userId': user_id,
    'summary.ip.9': {
        '$exists': False
    }
}
update =  {
    '$push': {
        'summary.ip': ip
    }
}
self.db[coll_name].update_one(filter_, update, upsert=True)
</code>```

Body:
That's a small part of my update query using pymongo in python. I want to $push ip variable to an array only if its length is less than 10. I know that I can solve this problem firstly finding this user (find_one) and checking array's length but it's not an efficient solution. How to handle this problem using mongo?

I read that $cond works only in aggregation so I can't figure anything else.

Part of my script:

self.db[coll_name].update_one(
             {
                 'summary.userId': user_id
             },
             {'$push':
                 {
                     'summary.ip': ip
                 },
             }
             upsert=True
        )

What my brain wants to do:

self.db[coll_name].update_one(
             {
                 'summary.userId': user_id
             },
             {
                 "$cond": {"if": {"$size": {"$summary.ip": {"$ne": 10}}},
                         "then": {"$push": ip},
                         "else": pass
             }},
             upsert=True
        )

I'm trying to limit myself to pymongo but answers using MongoDB with JS are more than welcome.

EDIT: Sorry for the inconvenience.

I want to be able to update other fields event if the condition wasn't met.

self.db[coll_name].update_one(
                 {
                     'summary.userId': user_id
                 },
                 {'$push':
                     {
                         'summary.ip': ip
                     },

                 '$addToSet':
                     {
                         'summary.something_list': something
                     },
                 }
                 upsert=True
            )

If I filter by the length of ip array, I won't add something if ip list eq 9, which I have to do.

Body:
In the filter passed to Collections.update_one, you can filter where an ip index of 9 doesn't exist in the collection.

filter_ = {
    'summary.userId': user_id,
    'summary.ip.9': {
        '$exists': False
    }
}
update =  {
    '$push': {
        'summary.ip': ip
    }
}
self.db[coll_name].update_one(filter_, update, upsert=True)


问:
Double login to MVC and WebAPI
I develop two separated applications: MVC and WebAPI. On some pages of MVC application I perform ajax requests to WebAPI. Furthermore, I use IdentityServer3 as an authentication/authorization framework.

I've already implemented cookie-based authentication for MVC part and token-based for WebAPI basing on tutorials/samples published on GitHub. Each of them works as intended, but user has to log in twice (separately in MVC and WebAPI), which seems to be reasonable because I've used different authentication types.

Is it possible to use IdentityServer3 in a way that user is required to log in once? I'm wondering if it's a good idea to generate access token by MVC app (after cookie-based authorization) and provide it to JavaScript part of application (the token would be used during ajax calls). I think that this solution allows to avoid double signing in. I've read a lot of posts about similar problems, but they haven't given unambiguous answer.

Edit:

I've followed Paul Taylor's suggestion to use "Hybrid Flow" and I've found a couple of samples which illustrate how to implement it (among other things this tutorial), but I cannot figure out how to perform valid ajax requests to WebAPI. Currently, I get 401 Unauthorized error, though HTTP header Authorization: Bearer <access token> is set for all ajax requests.

IdentityServer project

Scopes:

```<code>var scopes = new List<Scope>
{
    StandardScopes.OfflineAccess,
    new Scope
    {
        Enabled = true,
        Name = "roles",
        Type = ScopeType.Identity,
        Claims = new List<ScopeClaim>
        {
            new ScopeClaim(IdentityServer3.Core.Constants.ClaimTypes.Role, true)
        }
    },
    new Scope
    {
        Enabled = true,
        DisplayName = "Web API",
        Name = "api",
        ScopeSecrets = new List<Secret>
        {
            new Secret("secret".Sha256())
        },
        Claims = new List<ScopeClaim>
        {
            new ScopeClaim(IdentityServer3.Core.Constants.ClaimTypes.Role, true)
        },
        Type = ScopeType.Resource
    }
};

scopes.AddRange(StandardScopes.All);
</code>```

Client:

```<code>new Client
{
    ClientName = "MVC Client",
    ClientId = "mvc",
    Flow = Flows.Hybrid,
    ClientSecrets =
    {
        new Secret("secret".Sha256())
    },
    AllowedScopes = new List<string>
    {
        Constants.StandardScopes.OpenId,
        Constants.StandardScopes.Profile,
        Constants.StandardScopes.Email,
        Constants.StandardScopes.Roles,
        Constants.StandardScopes.Address,
        Constants.StandardScopes.OfflineAccess,
        "api"
    },
    RequireConsent = false,
    AllowRememberConsent = true,
    AccessTokenType = AccessTokenType.Reference,

    RedirectUris = new List<string>
    {
        "http://localhost:48197/"
    },
    PostLogoutRedirectUris = new List<string>
    {
        "http://localhost:48197/"
    },
    AllowAccessTokensViaBrowser = true
}
</code>```

MVC application project

Startup configuration

```<code>const string AuthorityUri = "https://localhost:44311/identity";

public void Configuration(IAppBuilder app)
{
    JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = "Cookies"
    });

    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
    {
        ClientId = "mvc",
        Authority = AuthorityUri,
        RedirectUri = "http://localhost:48197/",
        ResponseType = "code id_token",
        Scope = "openid profile email roles api offline_access",
        TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name",
            RoleClaimType = "role"
        },
        SignInAsAuthenticationType = "Cookies",
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            AuthorizationCodeReceived = async n =>
            {
                var tokenClient = new TokenClient(AuthorityUri + "/connect/token", "mvc", "secret");

                TokenResponse tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);

                if (tokenResponse.IsError)
                    throw new Exception(tokenResponse.Error);

                UserInfoClient userInfoClient = new UserInfoClient(AuthorityUri + "/connect/userinfo");

                UserInfoResponse userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);

                ClaimsIdentity id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
                id.AddClaims(userInfoResponse.Claims);

                id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
                id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
                id.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
                id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));

                n.AuthenticationTicket = new AuthenticationTicket(
                    new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "name", "role"),
                    n.AuthenticationTicket.Properties);
            },
            RedirectToIdentityProvider = n => { // more code }
        }
    });
}
</code>```

After I receive access token, I store it in the sessionStorage.

```<code>@model IEnumerable<System.Security.Claims.Claim>
<script>
    sessionStorage.accessToken = '@Model.First(c => c.Type == "access_token").Value';
</script>
</code>```

Following JavaScript function is used to perform ajax requests:

```<code>function ajaxRequest(requestType, url, parameters)
{
    var headers = {};
    if (sessionStorage.accessToken) {
        headers['Authorization'] = 'Bearer ' + sessionStorage.accessToken;
    }

    $.ajax({
        url: url,
        method: requestType,
        dataType: 'json',
        data: parameters,
        headers: headers
    });
}
</code>```

WebAPI project

Startup configuration:

```<code>JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
    Authority = "https://localhost:44311/identity",
    ClientId = "mvc",
    ClientSecret = "secret",
    RequiredScopes = new[] { "api", "roles" }
});
</code>```

Could you tell me what I'm doing wrong?

Edit (solved)

I had invalid configuration of WebAPI because nomenclature is misleading. It turned out that ClientId and ClientSecret should contian name of scope and its secret (link to reported issue).

Following Startup configuration of WebAPI works as intended:

```<code>app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
    Authority = "https://localhost:44311/identity",

    // It has been changed:
    ClientId = "api", // Scope name
    ClientSecret = "secret", // Scope secret

    RequiredScopes = new[] { "api", "roles" }
});
</code>```

答:
You need to use IdentityServer3's "Hybrid Flow".

Here's a tutorial on how to implement it with IdentityServer3. https://identityserver.github.io/Documentation/docsv2/overview/mvcGettingStarted.html

This page for an explanation of how the Hybrid Flow works, and how to implement it (using IdentityServer4 - which unlike IdentityServer3, is still actively developed in case you have the option to upgrade). http://docs.identityserver.io/en/release/quickstarts/5_hybrid_and_api_access.html.

Title: Double login to MVC and WebAPI

Body:
I develop two separated applications: MVC and WebAPI. On some pages of MVC application I perform ajax requests to WebAPI. Furthermore, I use IdentityServer3 as an authentication/authorization framework.

I've already implemented cookie-based authentication for MVC part and token-based for WebAPI basing on tutorials/samples published on GitHub. Each of them works as intended, but user has to log in twice (separately in MVC and WebAPI), which seems to be reasonable because I've used different authentication types.

Is it possible to use IdentityServer3 in a way that user is required to log in once? I'm wondering if it's a good idea to generate access token by MVC app (after cookie-based authorization) and provide it to JavaScript part of application (the token would be used during ajax calls). I think that this solution allows to avoid double signing in. I've read a lot of posts about similar problems, but they haven't given unambiguous answer.

Edit:

I've followed Paul Taylor's suggestion to use "Hybrid Flow" and I've found a couple of samples which illustrate how to implement it (among other things this tutorial), but I cannot figure out how to perform valid ajax requests to WebAPI. Currently, I get 401 Unauthorized error, though HTTP header Authorization: Bearer <access token> is set for all ajax requests.

IdentityServer project

Scopes:

var scopes = new List<Scope>
{
    StandardScopes.OfflineAccess,
    new Scope
    {
        Enabled = true,
        Name = "roles",
        Type = ScopeType.Identity,
        Claims = new List<ScopeClaim>
        {
            new ScopeClaim(IdentityServer3.Core.Constants.ClaimTypes.Role, true)
        }
    },
    new Scope
    {
        Enabled = true,
        DisplayName = "Web API",
        Name = "api",
        ScopeSecrets = new List<Secret>
        {
            new Secret("secret".Sha256())
        },
        Claims = new List<ScopeClaim>
        {
            new ScopeClaim(IdentityServer3.Core.Constants.ClaimTypes.Role, true)
        },
        Type = ScopeType.Resource
    }
};

scopes.AddRange(StandardScopes.All);

Client:

new Client
{
    ClientName = "MVC Client",
    ClientId = "mvc",
    Flow = Flows.Hybrid,
    ClientSecrets =
    {
        new Secret("secret".Sha256())
    },
    AllowedScopes = new List<string>
    {
        Constants.StandardScopes.OpenId,
        Constants.StandardScopes.Profile,
        Constants.StandardScopes.Email,
        Constants.StandardScopes.Roles,
        Constants.StandardScopes.Address,
        Constants.StandardScopes.OfflineAccess,
        "api"
    },
    RequireConsent = false,
    AllowRememberConsent = true,
    AccessTokenType = AccessTokenType.Reference,

    RedirectUris = new List<string>
    {
        "http://localhost:48197/"
    },
    PostLogoutRedirectUris = new List<string>
    {
        "http://localhost:48197/"
    },
    AllowAccessTokensViaBrowser = true
}

MVC application project

Startup configuration

const string AuthorityUri = "https://localhost:44311/identity";

public void Configuration(IAppBuilder app)
{
    JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = "Cookies"
    });

    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
    {
        ClientId = "mvc",
        Authority = AuthorityUri,
        RedirectUri = "http://localhost:48197/",
        ResponseType = "code id_token",
        Scope = "openid profile email roles api offline_access",
        TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name",
            RoleClaimType = "role"
        },
        SignInAsAuthenticationType = "Cookies",
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            AuthorizationCodeReceived = async n =>
            {
                var tokenClient = new TokenClient(AuthorityUri + "/connect/token", "mvc", "secret");

                TokenResponse tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);

                if (tokenResponse.IsError)
                    throw new Exception(tokenResponse.Error);

                UserInfoClient userInfoClient = new UserInfoClient(AuthorityUri + "/connect/userinfo");

                UserInfoResponse userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);

                ClaimsIdentity id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
                id.AddClaims(userInfoResponse.Claims);

                id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
                id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
                id.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
                id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));

                n.AuthenticationTicket = new AuthenticationTicket(
                    new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "name", "role"),
                    n.AuthenticationTicket.Properties);
            },
            RedirectToIdentityProvider = n => { // more code }
        }
    });
}

After I receive access token, I store it in the sessionStorage.

@model IEnumerable<System.Security.Claims.Claim>

Following JavaScript function is used to perform ajax requests:

function ajaxRequest(requestType, url, parameters)
{
    var headers = {};
    if (sessionStorage.accessToken) {
        headers['Authorization'] = 'Bearer ' + sessionStorage.accessToken;
    }

    $.ajax({
        url: url,
        method: requestType,
        dataType: 'json',
        data: parameters,
        headers: headers
    });
}

WebAPI project

Startup configuration:

JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
    Authority = "https://localhost:44311/identity",
    ClientId = "mvc",
    ClientSecret = "secret",
    RequiredScopes = new[] { "api", "roles" }
});

Could you tell me what I'm doing wrong?

Edit (solved)

I had invalid configuration of WebAPI because nomenclature is misleading. It turned out that ClientId and ClientSecret should contian name of scope and its secret (link to reported issue).

Following Startup configuration of WebAPI works as intended:

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
    Authority = "https://localhost:44311/identity",

    // It has been changed:
    ClientId = "api", // Scope name
    ClientSecret = "secret", // Scope secret

    RequiredScopes = new[] { "api", "roles" }
});


问:
Removing strings from another string in java
Lets say I have this list of words:

```<code> String[] stopWords = new String[]{"i","a","and","about","an","are","as","at","be","by","com","for","from","how","in","is","it","not","of","on","or","that","the","this","to","was","what","when","where","who","will","with","the","www"};
</code>```

Than I have text

```<code> String text = "I would like to do a nice novel about nature AND people"
</code>```

Is there method that matches the stopWords and removes them while ignoring case; like this somewhere out there?:

```<code> String noStopWordsText = remove(text, stopWords);
</code>```

Result:

```<code> " would like do nice novel nature people"
</code>```

If you know about regex that wold work great but I would really prefer something like commons solution that is bit more performance oriented.

BTW, right now I'm using this commons method which is lacking proper insensitive case handling:

```<code> private static final String[] stopWords = new String[]{"i", "a", "and", "about", "an", "are", "as", "at", "be", "by", "com", "for", "from", "how", "in", "is", "it", "not", "of", "on", "or", "that", "the", "this", "to", "was", "what", "when", "where", "who", "will", "with", "the", "www", "I", "A", "AND", "ABOUT", "AN", "ARE", "AS", "AT", "BE", "BY", "COM", "FOR", "FROM", "HOW", "IN", "IS", "IT", "NOT", "OF", "ON", "OR", "THAT", "THE", "THIS", "TO", "WAS", "WHAT", "WHEN", "WHERE", "WHO", "WILL", "WITH", "THE", "WWW"};
 private static final String[] blanksForStopWords = new String[]{"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};

 noStopWordsText = StringUtils.replaceEach(text, stopWords, blanksForStopWords);
</code>```

答:
Create a regular expression with your stop words, make it case insensitive, and then use the matcher's replaceAll method to replace all matches with an empty string

```<code>import java.util.regex.*;

Pattern stopWords = Pattern.compile("\\b(?:i|a|and|about|an|are|...)\\b\\s*", Pattern.CASE_INSENSITIVE);
Matcher matcher = stopWords.matcher("I would like to do a nice novel about nature AND people");
String clean = matcher.replaceAll("");
</code>```

the ... in the pattern is just me being lazy, continue the list of stop words.

Another method is to loop over all the stop words and use String's replaceAll method. The problem with that approach is that replaceAll will compile a new regular expression for each call, so it's not very efficient to use in loops. Also, you can't pass the flag that makes the regular expression case insensitive when you use String's replaceAll.

Edit: I added \b around the pattern to make it match whole words only. I also added \s* to make it glob up any spaces after, that's maybe not necessary.

Body:
Lets say I have this list of words:

 String[] stopWords = new String[]{"i","a","and","about","an","are","as","at","be","by","com","for","from","how","in","is","it","not","of","on","or","that","the","this","to","was","what","when","where","who","will","with","the","www"};

Than I have text

 String text = "I would like to do a nice novel about nature AND people"

Is there method that matches the stopWords and removes them while ignoring case; like this somewhere out there?:

 String noStopWordsText = remove(text, stopWords);

Result:

 " would like do nice novel nature people"

If you know about regex that wold work great but I would really prefer something like commons solution that is bit more performance oriented.

BTW, right now I'm using this commons method which is lacking proper insensitive case handling:

 private static final String[] stopWords = new String[]{"i", "a", "and", "about", "an", "are", "as", "at", "be", "by", "com", "for", "from", "how", "in", "is", "it", "not", "of", "on", "or", "that", "the", "this", "to", "was", "what", "when", "where", "who", "will", "with", "the", "www", "I", "A", "AND", "ABOUT", "AN", "ARE", "AS", "AT", "BE", "BY", "COM", "FOR", "FROM", "HOW", "IN", "IS", "IT", "NOT", "OF", "ON", "OR", "THAT", "THE", "THIS", "TO", "WAS", "WHAT", "WHEN", "WHERE", "WHO", "WILL", "WITH", "THE", "WWW"};
 private static final String[] blanksForStopWords = new String[]{"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};

 noStopWordsText = StringUtils.replaceEach(text, stopWords, blanksForStopWords);

Body:
Create a regular expression with your stop words, make it case insensitive, and then use the matcher's replaceAll method to replace all matches with an empty string

import java.util.regex.*;

Pattern stopWords = Pattern.compile("\\b(?:i|a|and|about|an|are|...)\\b\\s*", Pattern.CASE_INSENSITIVE);
Matcher matcher = stopWords.matcher("I would like to do a nice novel about nature AND people");
String clean = matcher.replaceAll("");

the ... in the pattern is just me being lazy, continue the list of stop words.

Another method is to loop over all the stop words and use String's replaceAll method. The problem with that approach is that replaceAll will compile a new regular expression for each call, so it's not very efficient to use in loops. Also, you can't pass the flag that makes the regular expression case insensitive when you use String's replaceAll.

Edit: I added \b around the pattern to make it match whole words only. I also added \s* to make it glob up any spaces after, that's maybe not necessary.