问:
react- native: 'adb' is not recognized as an internal or external command, operable program or batch file
Am new to react-native android app development. Please help me solve this issue.

Am not able to run my first application, am getting error as adb' is not recognized as an internal or external command, operable program or batch file.

I checked inside android sdk->platform-tools->i can see adb.exe there.

Build is successfull but getting error during run time. Below is my cmd prompt

```<code>Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.
E:\ReactWorkSpace\MyFirstApp>react-native run-android
Scanning 560 folders for symlinks in E:\ReactWorkSpace\MyFirstApp\node_modules (72ms)
JS server already running.
Building and installing the app on the device (cd android && gradlew.bat installDebug)...
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library
:app:prepareComAndroidSupportRecyclerviewV72340Library
:app:prepareComAndroidSupportSupportV42340Library
:app:prepareComFacebookFbuiTextlayoutbuilderTextlayoutbuilder100Library
:app:prepareComFacebookFrescoDrawee101Library
:app:prepareComFacebookFrescoFbcore101Library
:app:prepareComFacebookFrescoFresco101Library
:app:prepareComFacebookFrescoImagepipeline101Library
:app:prepareComFacebookFrescoImagepipelineBase101Library
:app:prepareComFacebookFrescoImagepipelineOkhttp3101Library
:app:prepareComFacebookReactReactNative0434Library
:app:prepareComFacebookSoloaderSoloader010Library
:app:prepareOrgWebkitAndroidJscR174650Library
:app:prepareDebugDependencies
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:mergeDebugShaders
:app:compileDebugShaders
:app:generateDebugAssets
:app:mergeDebugAssets
:app:generateDebugResValues
:app:generateDebugResources
:app:mergeDebugResources
:app:bundleDebugJsAndAssets SKIPPED
:app:processDebugManifest
:app:processDebugResources
:app:generateDebugSources
:app:incrementalDebugJavaCompilationSafeguard
:app:compileDebugJavaWithJavac
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources
:app:transformClassesWithDexForDebug
Running dex in-process requires build tools 23.0.2.
For faster builds update this project to use the latest build tools.
:app:mergeDebugJniLibFolders
:app:transformNative_libsWithMergeJniLibsForDebug
:app:processDebugJavaRes UP-TO-DATE
:app:transformResourcesWithMergeJavaResForDebug
:app:validateSigningDebug
:app:packageDebug
:app:assembleDebug
:app:installDebug
Installing APK 'app-debug.apk' on 'A16 - 4.2.2' for app:debug
Installed on 1 device.

BUILD SUCCESSFUL

Total time: 7 mins 4.412 secs
'adb' is not recognized as an internal or external command,
operable program or batch file.
Starting the app (D:\Android\sdk/platform-tools/adb shell am start -n com.myfirstapp/.MainActivity...
Starting: Intent { cmp=com.myfirstapp/.MainActivity }

E:\ReactWorkSpace\MyFirstApp>
</code>```

Am not using emulator, am using my own mobile device. App is launched in my device but all i see is a white blank screen. I followed all the instructions properly as mentioned in the official website.

Thank you.

答:
You see blank screen because your server is not running or stopped

Did you run adb reverse if you are debugging using usb

try connecting laptop and mobile to same wifi and enter your ip:8081 in dev settings

Body:
Am new to react-native android app development. Please help me solve this issue.

Am not able to run my first application, am getting error as adb' is not recognized as an internal or external command, operable program or batch file.

I checked inside android sdk->platform-tools->i can see adb.exe there.

Build is successfull but getting error during run time. Below is my cmd prompt

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.
E:\ReactWorkSpace\MyFirstApp>react-native run-android
Scanning 560 folders for symlinks in E:\ReactWorkSpace\MyFirstApp\node_modules (72ms)
JS server already running.
Building and installing the app on the device (cd android && gradlew.bat installDebug)...
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library
:app:prepareComAndroidSupportRecyclerviewV72340Library
:app:prepareComAndroidSupportSupportV42340Library
:app:prepareComFacebookFbuiTextlayoutbuilderTextlayoutbuilder100Library
:app:prepareComFacebookFrescoDrawee101Library
:app:prepareComFacebookFrescoFbcore101Library
:app:prepareComFacebookFrescoFresco101Library
:app:prepareComFacebookFrescoImagepipeline101Library
:app:prepareComFacebookFrescoImagepipelineBase101Library
:app:prepareComFacebookFrescoImagepipelineOkhttp3101Library
:app:prepareComFacebookReactReactNative0434Library
:app:prepareComFacebookSoloaderSoloader010Library
:app:prepareOrgWebkitAndroidJscR174650Library
:app:prepareDebugDependencies
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:mergeDebugShaders
:app:compileDebugShaders
:app:generateDebugAssets
:app:mergeDebugAssets
:app:generateDebugResValues
:app:generateDebugResources
:app:mergeDebugResources
:app:bundleDebugJsAndAssets SKIPPED
:app:processDebugManifest
:app:processDebugResources
:app:generateDebugSources
:app:incrementalDebugJavaCompilationSafeguard
:app:compileDebugJavaWithJavac
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources
:app:transformClassesWithDexForDebug
Running dex in-process requires build tools 23.0.2.
For faster builds update this project to use the latest build tools.
:app:mergeDebugJniLibFolders
:app:transformNative_libsWithMergeJniLibsForDebug
:app:processDebugJavaRes UP-TO-DATE
:app:transformResourcesWithMergeJavaResForDebug
:app:validateSigningDebug
:app:packageDebug
:app:assembleDebug
:app:installDebug
Installing APK 'app-debug.apk' on 'A16 - 4.2.2' for app:debug
Installed on 1 device.

BUILD SUCCESSFUL

Total time: 7 mins 4.412 secs
'adb' is not recognized as an internal or external command,
operable program or batch file.
Starting the app (D:\Android\sdk/platform-tools/adb shell am start -n com.myfirstapp/.MainActivity...
Starting: Intent { cmp=com.myfirstapp/.MainActivity }

E:\ReactWorkSpace\MyFirstApp>

Am not using emulator, am using my own mobile device. App is launched in my device but all i see is a white blank screen. I followed all the instructions properly as mentioned in the official website.

Thank you.


来源: stackexchange

问:
XamlBindingHelper Class
Can somebody provide an overview for use of the XamlBindingHelper class with examples? Specifically the GetDataTemplateComponent and SetDataTemplateComponent method.

答:
In the official document, it says

This class is for use in code that is generated by the XAML compiler.

This tells me that I should be able to find some reference of it in code-generated classes (.g.cs) by x:Bind, given there's not a single thread on the Internet that explains what exactly it does.

So I created a test UWP project with a ListView, and inside its ItemTemplate I threw in some x:Bind with x:Phase. After I compiled the project, I found some of its methods used inside my MainPage.g.cs -

XamlBindingHelper.ConvertValue

```<code>public static void Set_Windows_UI_Xaml_Controls_ItemsControl_ItemsSource(global::Windows.UI.Xaml.Controls.ItemsControl obj, global::System.Object value, string targetNullValue)
{
    if (value == null && targetNullValue != null)
    {
        value = (global::System.Object) global::Windows.UI.Xaml.Markup.XamlBindingHelper.ConvertValue(typeof(global::System.Object), targetNullValue);
    }
    obj.ItemsSource = value;
}
</code>```

Apparently the XamlBindingHelper.ConvertValue method is for converting values. I knew this already, as I used it in one of my recent answers on SO.

XamlBindingHelper.SuspendRendering & XamlBindingHelper.ResumeRendering

```<code>public int ProcessBindings(global::Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs args)
{
    int nextPhase = -1;
    switch(args.Phase)
    {
        case 0:
            nextPhase = 1;
            this.SetDataRoot(args.Item);
            if (!removedDataContextHandler)
            {
                removedDataContextHandler = true;
                ((global::Windows.UI.Xaml.Controls.StackPanel)args.ItemContainer.ContentTemplateRoot).DataContextChanged -= this.DataContextChangedHandler;
            }
            this.initialized = true;
            break;
        case 1:
            global::Windows.UI.Xaml.Markup.XamlBindingHelper.ResumeRendering(this.obj4);
            nextPhase = -1;
            break;
    }
    this.Update_((global::System.String) args.Item, 1 << (int)args.Phase);
    return nextPhase;
}

public void ResetTemplate()
{
    this.bindingsTracking.ReleaseAllListeners();
    global::Windows.UI.Xaml.Markup.XamlBindingHelper.SuspendRendering(this.obj4);
}
</code>```

XamlBindingHelper.SuspendRendering & XamlBindingHelper.ResumeRendering look very interesting. They seem to be the key functions to enable ListView/GridView's incremental item rendering which helps improve the overall panning/scrolling experience.

So apart from x:DeferLoadingStrategy and x:Load(Creators Update), they are something else that could be used to improve your app performance.

IDataTemplateComponent & IDataTemplateExtension

However, I couldn't find anything related to GetDataTemplateComponent and SetDataTemplateComponent. I even tried to manually set this attached property in XAML but the get method always returned null.

And here's the interesting bit. I later found this piece of code in the generated class.

```<code>case 2: // MainPage.xaml line 13
    {
        global::Windows.UI.Xaml.Controls.Grid element2 = (global::Windows.UI.Xaml.Controls.Grid)target;
        MainPage_obj2_Bindings bindings = new MainPage_obj2_Bindings();
        returnValue = bindings;
        bindings.SetDataRoot(element2.DataContext);
        element2.DataContextChanged += bindings.DataContextChangedHandler;
        global::Windows.UI.Xaml.DataTemplate.SetExtensionInstance(element2, bindings);
    }
    break;
</code>```

The method DataTemplate.SetExtensionInstance looks very similar to XamlBindingHelper.SetDataTemplateComponent. It takes element2 which is the root Grid inside the ItemTemplate of my ListView, and an IDataTemplateExtension; where the latter takes an element and an IDataTemplateComponent. If you have a look at their definitions, their functionalities are very similar, which makes me think if DataTemplate.SetExtensionInstance is the replacement of XamlBindingHelper.SetDataTemplateComponent? I'd love to know if otherwise.

Unlike IDataTemplateComponent, you can get an instance of the IDataTemplateExtension in your code -

```<code>var firstItemContainer = (ListViewItem)MyListView.ContainerFromIndex(0);
var rootGrid = (Grid)firstItemContainer?.ContentTemplateRoot;
var dataTemplateEx = DataTemplate.GetExtensionInstance(rootGrid);
</code>```

In my case, the dataTemplateEx is an instance of another generated class called MainPage_obj2_Bindings, where you have access to methods like ResetTemplate and ProcessBindings.

I assume they could be helpful if you were to build your own custom list controls, but other than that I just can't see why you would ever need them.

ContentLicense: CC BY-SA 3.0

Title: XamlBindingHelper Class

Body:
In the official document, it says

This class is for use in code that is generated by the XAML compiler.

This tells me that I should be able to find some reference of it in code-generated classes (.g.cs) by x:Bind, given there's not a single thread on the Internet that explains what exactly it does.

So I created a test UWP project with a ListView, and inside its ItemTemplate I threw in some x:Bind with x:Phase. After I compiled the project, I found some of its methods used inside my MainPage.g.cs -

XamlBindingHelper.ConvertValue

public static void Set_Windows_UI_Xaml_Controls_ItemsControl_ItemsSource(global::Windows.UI.Xaml.Controls.ItemsControl obj, global::System.Object value, string targetNullValue)
{
    if (value == null && targetNullValue != null)
    {
        value = (global::System.Object) global::Windows.UI.Xaml.Markup.XamlBindingHelper.ConvertValue(typeof(global::System.Object), targetNullValue);
    }
    obj.ItemsSource = value;
}

Apparently the XamlBindingHelper.ConvertValue method is for converting values. I knew this already, as I used it in one of my recent answers on SO.

XamlBindingHelper.SuspendRendering & XamlBindingHelper.ResumeRendering

public int ProcessBindings(global::Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs args)
{
    int nextPhase = -1;
    switch(args.Phase)
    {
        case 0:
            nextPhase = 1;
            this.SetDataRoot(args.Item);
            if (!removedDataContextHandler)
            {
                removedDataContextHandler = true;
                ((global::Windows.UI.Xaml.Controls.StackPanel)args.ItemContainer.ContentTemplateRoot).DataContextChanged -= this.DataContextChangedHandler;
            }
            this.initialized = true;
            break;
        case 1:
            global::Windows.UI.Xaml.Markup.XamlBindingHelper.ResumeRendering(this.obj4);
            nextPhase = -1;
            break;
    }
    this.Update_((global::System.String) args.Item, 1 << (int)args.Phase);
    return nextPhase;
}

public void ResetTemplate()
{
    this.bindingsTracking.ReleaseAllListeners();
    global::Windows.UI.Xaml.Markup.XamlBindingHelper.SuspendRendering(this.obj4);
}

XamlBindingHelper.SuspendRendering & XamlBindingHelper.ResumeRendering look very interesting. They seem to be the key functions to enable ListView/GridView's incremental item rendering which helps improve the overall panning/scrolling experience.

So apart from x:DeferLoadingStrategy and x:Load(Creators Update), they are something else that could be used to improve your app performance.

IDataTemplateComponent & IDataTemplateExtension

However, I couldn't find anything related to GetDataTemplateComponent and SetDataTemplateComponent. I even tried to manually set this attached property in XAML but the get method always returned null.

And here's the interesting bit. I later found this piece of code in the generated class.

case 2: // MainPage.xaml line 13
    {
        global::Windows.UI.Xaml.Controls.Grid element2 = (global::Windows.UI.Xaml.Controls.Grid)target;
        MainPage_obj2_Bindings bindings = new MainPage_obj2_Bindings();
        returnValue = bindings;
        bindings.SetDataRoot(element2.DataContext);
        element2.DataContextChanged += bindings.DataContextChangedHandler;
        global::Windows.UI.Xaml.DataTemplate.SetExtensionInstance(element2, bindings);
    }
    break;

The method DataTemplate.SetExtensionInstance looks very similar to XamlBindingHelper.SetDataTemplateComponent. It takes element2 which is the root Grid inside the ItemTemplate of my ListView, and an IDataTemplateExtension; where the latter takes an element and an IDataTemplateComponent. If you have a look at their definitions, their functionalities are very similar, which makes me think if DataTemplate.SetExtensionInstance is the replacement of XamlBindingHelper.SetDataTemplateComponent? I'd love to know if otherwise.

Unlike IDataTemplateComponent, you can get an instance of the IDataTemplateExtension in your code -

var firstItemContainer = (ListViewItem)MyListView.ContainerFromIndex(0);
var rootGrid = (Grid)firstItemContainer?.ContentTemplateRoot;
var dataTemplateEx = DataTemplate.GetExtensionInstance(rootGrid);

In my case, the dataTemplateEx is an instance of another generated class called MainPage_obj2_Bindings, where you have access to methods like ResetTemplate and ProcessBindings.

I assume they could be helpful if you were to build your own custom list controls, but other than that I just can't see why you would ever need them.


问:
Catch a non-specific exception when the caller apply the same action for each exception handle
I have to dynamically instantiate  certain class based on runtime configuration. So, I need to invoke the method newInstance() and accordingly handle the exceptions:

```<code>try {
    clazz.newInstance();
} catch (InstantiationException ex) {
    logger.error(ex, ex);
    throw new RuntimeException(ex);
} catch (IllegalAccessException e) {
    logger.error(ex, ex);
    throw new RuntimeException(ex);
}
</code>```

In this point of my code the only way to handle this exceptions is by attempting to log the error and present a friendly message to the user (rethrowing the exception as runtime ,the view layer will
catch the runtime exception)

```<code><exception class="java.lang.Exception">
  <redirect view-id="/error.xhtml" />
</exception>
</code>```

The point is that if I can't reasonable recover the error for any exception throw when method newInstance()  is called and for each exception the same action  is applied (log and rethrow the exception), is a better approach to replace the code above handling a non-specific exception like :

```<code>try {
    clazz.newInstance();
} catch (Exception ex) {
    logger.error(ex, ex);
    throw new RuntimeException(ex);
}
</code>```

答:
I found this nice article about generic-exceptions Beware the dangers of generic Exceptions. The author explain several reasons in order to avoid handle generic-exception (with a few exceptions)
. Generally speaking in my opinion these are the relevant points :

A generic catch (Exception e) catches all subclasses of RuntimeException. And according that runtime exceptions indicate programming erros AND is not expected to recover those errors.

If your code just catches Exception , you'll probably never know if the method you are calling later adds a new checked exception to its method signature.

The caller may be able to recover from some errors but not from others.

Logging is limited because only one catch clause doesn't know the specific exception being caught.

ContentLicense: CC BY-SA 2.5

Body:
I have to dynamically instantiate  certain class based on runtime configuration. So, I need to invoke the method newInstance() and accordingly handle the exceptions:

try {
    clazz.newInstance();
} catch (InstantiationException ex) {
    logger.error(ex, ex);
    throw new RuntimeException(ex);
} catch (IllegalAccessException e) {
    logger.error(ex, ex);
    throw new RuntimeException(ex);
}

In this point of my code the only way to handle this exceptions is by attempting to log the error and present a friendly message to the user (rethrowing the exception as runtime ,the view layer will
catch the runtime exception)

<exception class="java.lang.Exception">
  <redirect view-id="/error.xhtml" />
</exception>

The point is that if I can't reasonable recover the error for any exception throw when method newInstance()  is called and for each exception the same action  is applied (log and rethrow the exception), is a better approach to replace the code above handling a non-specific exception like :

try {
    clazz.newInstance();
} catch (Exception ex) {
    logger.error(ex, ex);
    throw new RuntimeException(ex);
}


问:
Adding delay or something between hundred of promises
I'm using node for requesting app details from another website but the problem i'm facing is, it sends hundreds ( or maybe thousands ) of request, and then I get error and I receive nothing.

Read comments in code for info...

```<code>// I'm reading links from another file using 'fs'
fs.readFile('./google_apps/GAME_ACTION.json', 'utf8', function (err, data) {
    if (err) throw err;

    obj = JSON.parse(data);
    // creating a empty array
    var promiseStack = [];

    for (var index in obj['GAME_ACTION']) {
        var linksArray = obj['GAME_ACTION'][index];
        linksArray.forEach( function(link, index) {
            var appID = link.match(/id=.*/g)
            var instr = appID.toString();

            var appIDSliced = instr.slice(3)
            // Here appIDSliced is ID, which is sliced from a link
            // there are thousands on link in this file which I opened

            console.log('sending') // for testing purpose

            // here i'm pushing promises into that empty array
            // store.app({id: appIDSliced}) is a promise I guess because I can use .then() on it...
            // and store.app sends request to another website from which it receives an object in return.
            // (Variable store is from another file 'require()' above in my node app fie )
            promiseStack.push( store.app({id: appIDSliced}))

        });
    }

    // After pushing all promises into array, now i'm trying to resolve them using Promise.all
    Promise.all(promiseStack).then((responses) => {
        console.log("Dealing with responses")

        // Dealing with response (which is an object coming)
        responses.map(response => {
            var title = response.title
            var package_name = response.appId
            var appCategory = response.primaryGenre
            var appSize = parseFloat((response.size/1024)/1024).toFixed(2)
            var developerName = response.developer
            var developerWebsite = response.developerWebsite
            if (typeof developerWebsite == 'undefined') {
                developerWebsite = "N/A"
            }
            var appPrice = response.price
            var lastUpdated = response.updated
            var contentRating = response.contentRating
            if (typeof contentRating == 'undefined') {
                contentRating = "N/A"
            }
            var userRating = response.score
            if (typeof userRating == 'undefined') {
                userRating = "N/A"
            }
            var dataRow = [appID, title, package_name, appCategory, appSize, developerName, developerWebsite, appPrice, lastUpdated, contentRating, userRating]
            var dataToAdd = [dataRow];
            console.log("Appending now")

            // here i'm using google API to append that into my sheet on google
            authentication.authenticate().then((auth)=>{
                appendData(auth, dataToAdd);
            });
        })
    })
})
</code>```

See the image below ... Those are the Errors I receive on my console
It keep logging 'sending' like for 80 secs and then I get error "UnhandledPromiseRejectionWarning" where I just get stuck for 2 mins and I keep pressing 'CTRL+C'.

Thanks.

答:
You could use a pseudo recursive approach to slowly iterate one request after another:</p>

```<code>var finished=new Promise(function(resolve){
   (function iterate( index=0) {
        var link=linksArray[index];
        var appID = link.match(/id=.*/g)
        var instr = appID.toString();
        var appIDSliced = instr.slice(3)
        var promise=store.app({id: appIDSliced});
        promise.then(function(value){
             promiseStack.push(value);
             if(index<linksArray.length) return iterate(index+1);
             resolve(promiseStack);
        });
   })();
});

finished.then(function(responses){
 //your promise all code
});
</code>```

Body:
I'm using node for requesting app details from another website but the problem i'm facing is, it sends hundreds ( or maybe thousands ) of request, and then I get error and I receive nothing.

Read comments in code for info...

// I'm reading links from another file using 'fs'
fs.readFile('./google_apps/GAME_ACTION.json', 'utf8', function (err, data) {
    if (err) throw err;

    obj = JSON.parse(data);
    // creating a empty array
    var promiseStack = [];

    for (var index in obj['GAME_ACTION']) {
        var linksArray = obj['GAME_ACTION'][index];
        linksArray.forEach( function(link, index) {
            var appID = link.match(/id=.*/g)
            var instr = appID.toString();

            var appIDSliced = instr.slice(3)
            // Here appIDSliced is ID, which is sliced from a link
            // there are thousands on link in this file which I opened

            console.log('sending') // for testing purpose

            // here i'm pushing promises into that empty array
            // store.app({id: appIDSliced}) is a promise I guess because I can use .then() on it...
            // and store.app sends request to another website from which it receives an object in return.
            // (Variable store is from another file 'require()' above in my node app fie )
            promiseStack.push( store.app({id: appIDSliced}))

        });
    }

    // After pushing all promises into array, now i'm trying to resolve them using Promise.all
    Promise.all(promiseStack).then((responses) => {
        console.log("Dealing with responses")

        // Dealing with response (which is an object coming)
        responses.map(response => {
            var title = response.title
            var package_name = response.appId
            var appCategory = response.primaryGenre
            var appSize = parseFloat((response.size/1024)/1024).toFixed(2)
            var developerName = response.developer
            var developerWebsite = response.developerWebsite
            if (typeof developerWebsite == 'undefined') {
                developerWebsite = "N/A"
            }
            var appPrice = response.price
            var lastUpdated = response.updated
            var contentRating = response.contentRating
            if (typeof contentRating == 'undefined') {
                contentRating = "N/A"
            }
            var userRating = response.score
            if (typeof userRating == 'undefined') {
                userRating = "N/A"
            }
            var dataRow = [appID, title, package_name, appCategory, appSize, developerName, developerWebsite, appPrice, lastUpdated, contentRating, userRating]
            var dataToAdd = [dataRow];
            console.log("Appending now")

            // here i'm using google API to append that into my sheet on google
            authentication.authenticate().then((auth)=>{
                appendData(auth, dataToAdd);
            });
        })
    })
})

See the image below ... Those are the Errors I receive on my console
It keep logging 'sending' like for 80 secs and then I get error "UnhandledPromiseRejectionWarning" where I just get stuck for 2 mins and I keep pressing 'CTRL+C'.

Thanks.

Body:
You could use a pseudo recursive approach to slowly iterate one request after another:

var finished=new Promise(function(resolve){
   (function iterate( index=0) {
        var link=linksArray[index];
        var appID = link.match(/id=.*/g)
        var instr = appID.toString();
        var appIDSliced = instr.slice(3)
        var promise=store.app({id: appIDSliced});
        promise.then(function(value){
             promiseStack.push(value);
             if(index<linksArray.length) return iterate(index+1);
             resolve(promiseStack);
        });
   })();
});

finished.then(function(responses){
 //your promise all code
});


问:
Campaign tracking of PDF downloads with piwik
We are running wordpress and piwik and would like to track direct downloads using campaigns. The problem is close to this one: Track .zip Downloads with Piwik

Is there a good way to have a url (with a campaign code) that can be called directly that returns a pdf? What I mean by that is not to access the pdf directly but using a kind of gateway that is tracking the access to the pdf (within the campaign).

答:
I see one possible solution (without gateway):

In the anchor tag, include directly the css class "piwik_download" and in your href, include the campaign as parameter: "example.pdf?pk_campaign=pdf201707". Full example: Download pdf.

You can find more documentation here: https://developer.piwik.org/guides/tracking-javascript-guide#recording-a-click-as-a-download

PS: In case you need a gateway, you could do the same and, track a manual page view event with the JS tracker on the gateway.

Body:
I see one possible solution (without gateway):

In the anchor tag, include directly the css class "piwik_download" and in your href, include the campaign as parameter: "example.pdf?pk_campaign=pdf201707". Full example: <a href="example.pdf?pk_campaign=pdf201707" class="piwik_download">Download pdf</a>.

You can find more documentation here: https://developer.piwik.org/guides/tracking-javascript-guide#recording-a-click-as-a-download

PS: In case you need a gateway, you could do the same and, track a manual page view event with the JS tracker on the gateway.


问:
browsersync.reload task is not finishing
I have a few tasks running to manage my javascript, these are the tasks:

```<code>gulp.task('watch:js', function() {
    return gulp.watch(local.js,
        gulp.series('babel', 'cleanJsBundles', 'browserify', 'reload'));
});

gulp.task('reload', function() {
    return browserSync.reload();
});

gulp.task('watch', gulp.parallel('watch:sass', 'watch:svgsingles', 'watch:js'));
</code>```

Everything works in order - after browserify, the browser reloads. But then everything freezes. In the shell I can see that 'reload' starts, but is not finishing. What can I do to solve this problem?

答:
EDIT

It seems there's a problem with this custom task reload, could you try this:

```<code>gulp.task('watch:js', function() {
    return gulp.watch(local.js, gulp.series('babel', 'cleanJsBundles', 'browserify')).on('change', browserSync.reload);
});

gulp.task('watch', ['watch:sass', 'watch:svgsingles', 'watch:js']);
</code>```

Body:
I have a few tasks running to manage my javascript, these are the tasks:

gulp.task('watch:js', function() {
    return gulp.watch(local.js,
        gulp.series('babel', 'cleanJsBundles', 'browserify', 'reload'));
});

gulp.task('reload', function() {
    return browserSync.reload();
});

gulp.task('watch', gulp.parallel('watch:sass', 'watch:svgsingles', 'watch:js'));

Everything works in order - after browserify, the browser reloads. But then everything freezes. In the shell I can see that 'reload' starts, but is not finishing. What can I do to solve this problem?

Body:
EDIT

It seems there's a problem with this custom task reload, could you try this:

gulp.task('watch:js', function() {
    return gulp.watch(local.js, gulp.series('babel', 'cleanJsBundles', 'browserify')).on('change', browserSync.reload);
});

gulp.task('watch', ['watch:sass', 'watch:svgsingles', 'watch:js']);


问:
Is it possible to bind an django-user account to one specific workstation?
My goal is that every user can only log in to my Django web app from a specific workstation.

If the user tries to log in from another workstation, the login should be denied.

Is it possible to implement such a licensing model in Django, possibly via identifying the hostname of the workstation?

I'm using Django 1.10/Python 3.5.

答:
Identifying a workstation by IP address or other means that is available over HTTP only is very error prone and not reliable.  Instead, I'd require that the user installs a client certificate that you have generated.

This assumes you can control the installation of a certificate (there are two parts, a private key and the certificate itself), so you can make sure the certificate is installed on just one workstation. Your installer can do the verification here, as it has can gather much more information about the workstation, running locally.

Once a certificate is installed, you'd need to verify this. Have the front-end server do this, NGINX for example has full support for handling certificate exchange and validation, passing you the DN or even the full certificate for your app (Django) to use in the authorisation. See https://github.com/kimvais/django-ssl-client-auth for a project that lets you handle NGINX-verified certificate information.

On Windows and OS X, private keys can be imported as 'non-exportable'. This flag can still be circumvented, but no software licensing scheme is unbreakable. Make sure you have a proper licensing in place, log host information (IP addresses, user agent strings, etc.) and if you see the same cert being used from multiple IP addresses or have other proof that they are using the certificate from more than one machine, terminate the license and revoke the certificate. In other words: take reasonable precautions, make it harder to willingly break your license, and when they do anyway, you have grounds to revoke the license.


问:
How big should batch size and number of epochs be when fitting a model?
My training set has 970 samples and validation set has 243 samples.

How big should batch size and number of epochs be when fitting a model to optimize the val_acc? Is there any sort of rule of thumb to use based on data input size?

答:
I used Keras to perform non linear regression for market mix modelling. I got best results with a batch size of 32 and epochs = 100 while training a Sequential model in Keras with 3 hidden layers. Generally batch size of 32 or 25 is good, with epochs = 100 unless you have large dataset. in case of large dataset you can go with batch size of 10 with epochs b/w 50 to 100.
Again the above mentioned figures have worked fine for me.</p>

ContentLicense: CC BY-SA 4.0


问:
With Oauth2 Google Extension for Geoserver, GeoServer home page does not redirect to Google Login page
I have installed the OAuth2 Extensions for Geoserver successfully and I was able to create the Authentication Filter and added Google_Oauth2 to  the filter chains web
rest
gwc
default

I have also created the truststore and added it to the JAVA_OPTS Path as as ../cacerts.cks

All the steps I have followed are as in the official docs

Now, when I navigate to the Geoserver Home Page as directed by the Docs, I'm not getting the Google Login Page as supposed to.

One of the issues I have discovered is after adding the Google-Oauth2 to the filter chains, when I logout as Geoserver admin, the Google-Oauth is again removed from the selected chains.

What I'd like to know is how to do a stepwise check to determine the root cause of this problem.
Any help will be appreciated.

I have the Google Login ICon, when I click on it I get a 404 Error for this URL http://:8080/geoserver/web/j_spring_oauth2_google_login

Here is the Logfile, I cant find anything in here to point to the problem, just a few warnings here and there which are not related to Authentication

```<code>04 Jul 15:08:00 DEBUG [geoserver.global] - Found Java environment variable GEOSERVER_DATA_DIR to be unset
    04-Jul-2017 15:08:00.911 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'XStreamPersisterInitializer', but ApplicationContext is unset.
    04-Jul-2017 15:08:00.912 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionFilter', but ApplicationContext is unset.
    04-Jul-2017 15:08:00.914 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionProvider', but ApplicationContext is unset.
    04-Jul-2017 15:08:00.914 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionFilter', but ApplicationContext is unset.
    log4j:WARN File option not set for appender [geoserverlogfile].
    log4j:WARN Are you using FileAppender instead of ConsoleAppender?
    04-Jul-2017 15:08:03.435 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'GeoServerSecurityProvider', but ApplicationContext is unset.
    04-Jul-2017 15:08:03.435 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionFilter', but ApplicationContext is unset.
    04-Jul-2017 15:08:03.435 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionProvider', but ApplicationContext is unset.
    04-Jul-2017 15:08:03.435 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionFilter', but ApplicationContext is unset.
    04 Jul 15:08:04 INFO [config.GeoServerPropertyConfigurer] - Loading properties file from org.geoserver.config.SpringResourceAdaptor@6653368c
    04 Jul 15:08:04 INFO [geoserver.monitor] - Configuring monitoring database from: monitoring/db.properties
    04 Jul 15:08:04 WARN [impl.SessionFactoryObjectFactory] - InitialContext did not implement EventContext
<Loaded smth........>
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Will look for 'geowebcache.xml' in directory '/var/lib/geoserver_data/gwc'.
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:07 WARN [config.XMLConfiguration] - ********************************************************************************
    04 Jul 15:08:07 WARN [config.XMLConfiguration] - *** GWC configuration validation error: cvc-elt.1: Cannot find the declaration of element 'gwcConfiguration'.
    04 Jul 15:08:07 WARN [config.XMLConfiguration] - *** Will try to use configuration anyway. Please check the order of declared elements against the schema.
    04 Jul 15:08:07 WARN [config.XMLConfiguration] - ********************************************************************************
    04 Jul 15:08:07 INFO [gwc.layer] - Initializing GWC configuration based on GeoServer's Catalog
    04 Jul 15:08:07 INFO [gwc.layer] - GeoServer TileLayer store base directory is: gwc-layers
    04 Jul 15:08:07 INFO [gwc.layer] - Loading tile layers from gwc-layers
    04 Jul 15:08:07 INFO [config.XMLConfiguration] - Initializing GridSets from gwc
    04 Jul 15:08:07 INFO [config.XMLConfiguration] - Initializing layers from gwc
    04 Jul 15:08:07 INFO [layer.TileLayerDispatcher] - Configuration gwc contained no layers.
    04 Jul 15:08:07 INFO [storage.DefaultStorageFinder] - **************************************************************************************************************************
    04 Jul 15:08:07 INFO [storage.DefaultStorageFinder] - *** Found Servlet context parameter GEOSERVER_DATA_DIR set to /var/lib/geoserver_data, using it as the default prefix. ***
    04 Jul 15:08:07 INFO [storage.DefaultStorageFinder] - **************************************************************************************************************************
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Will look for 'geowebcache-diskquota.xml' in directory '/var/lib/geoserver_data/gwc'.
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Will look for 'geowebcache-diskquota-jdbc.xml' in directory '/var/lib/geoserver_data/gwc'.
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:07 INFO [diskquota.ConfigLoader] - Quota config is: gwc/geowebcache-diskquota.xml
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:09 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:09 INFO [diskquota.ConfigLoader] - Quota config is: gwc/geowebcache-diskquota.xml
    04 Jul 15:08:09 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:09 INFO [diskquota.DiskQuotaMonitor] - Setting up disk quota periodic enforcement task
    04 Jul 15:08:09 INFO [diskquota.DiskQuotaMonitor] - 0 layers configured with their own quotas.
    04 Jul 15:08:09 INFO [diskquota.DiskQuotaMonitor] - 24 layers attached to global quota 500.0 MB
    04 Jul 15:08:09 INFO [diskquota.DiskQuotaMonitor] - Disk quota periodic enforcement task set up every 30 SECONDS
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WPSInfoImpl--ecf5ed2:15cf44cc45b:-8000', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'wcs', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WMTSInfoImpl--387a6a83:15d0d802c5c:-8000', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'wms', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'wfs', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WPSInfoImpl-2db12f5c:15cf83a5f1b:-7fdb', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WCSInfoImpl-2db12f5c:15cf83a5f1b:-7fdc', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WMTSInfoImpl-2db12f5c:15cf83a5f1b:-7fdf', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WMSInfoImpl-2db12f5c:15cf83a5f1b:-7fde', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WFSInfoImpl-2db12f5c:15cf83a5f1b:-7fdd', enabled
    04 Jul 15:08:10 INFO [geoserver.monitor] - Monitor hibernate extension enabled
    04 Jul 15:08:10 INFO [gwc.config] - Initializing GeoServer specific GWC configuration from gwc-gs.xml
    04 Jul 15:08:11 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wps] onto handler 'dispatcher'
    04 Jul 15:08:11 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wps/*] onto handler 'dispatcher'
    04 Jul 15:08:11 INFO [ows.OWSHandlerMapping] - Mapped URL path [/temp/**] onto handler 'filePublisher'
    04 Jul 15:08:11 INFO [geoserver.wps] - Found 89 bindable processes in Deprecated processes
    04 Jul 15:08:11 INFO [geoserver.wps] - Found 5 bindable processes in GeoServer specific processes
    04 Jul 15:08:11 INFO [geoserver.wps] - Found 48 bindable processes in Geometry processes
    04 Jul 15:08:11 INFO [geoserver.wps] - Found 30 bindable processes in Vector processes
    04 Jul 15:08:11 INFO [geoserver.wps] - Blacklisting process ras:ConvolveCoverage as the input kernel of type class javax.media.jai.KernelJAI cannot be handled
    04 Jul 15:08:11 INFO [geoserver.wps] - Blacklisting process ras:RasterZonalStatistics2 as the input zones of type class java.lang.Object cannot be handled
    04 Jul 15:08:11 INFO [geoserver.wps] - Blacklisting process ras:RasterZonalStatistics2 as the input nodata of type class it.geosolutions.jaiext.range.Range cannot be handled
    04 Jul 15:08:11 INFO [geoserver.wps] - Blacklisting process ras:RasterZonalStatistics2 as the input rangeData of type class java.lang.Object cannot be handled
    04 Jul 15:08:11 INFO [geoserver.wps] - Blacklisting process ras:RasterZonalStatistics2 as the output zonal statistics of type interface java.util.List cannot be handled
    04 Jul 15:08:11 INFO [geoserver.wps] - Found 17 bindable processes in Raster processes
    04 Jul 15:08:11 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wcs] onto handler 'dispatcher'
    04 Jul 15:08:11 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wcs/*] onto handler 'dispatcher'
    04 Jul 15:08:11 INFO [org.geoserver] - GeoServer configuration lock is enabled
    04 Jul 15:08:11 WARN [turbojpeg.TurboJPEGMapResponse] - The turbo jpeg encoder is available for usage
    04 Jul 15:08:12 INFO [ows.OWSHandlerMapping] - Mapped URL path [/kml] onto handler 'dispatcher'
    04 Jul 15:08:12 INFO [ows.OWSHandlerMapping] - Mapped URL path [/kml/*] onto handler 'dispatcher'
    04 Jul 15:08:12 INFO [ows.OWSHandlerMapping] - Mapped URL path [/kml/icon/**/*] onto handler 'kmlIconService'
    04 Jul 15:08:13 INFO [ows.OWSHandlerMapping] - Mapped URL path [/gwc/service/**] onto handler 'dispatcher'
    04 Jul 15:08:13 INFO [geowebcache.GeoWebCacheDispatcher] - Invoked setServletPrefix(gwc)
    04 Jul 15:08:13 INFO [georss.GeoRSSPoller] - Initializing GeoRSS poller in a background job...
    04 Jul 15:08:13 INFO [georss.GeoRSSPoller] - No enabled GeoRSS feeds found, poller will not run.
    04 Jul 15:08:13 INFO [rest.RESTDispatcher] - Created RESTDispatcher with 15 paths
    04 Jul 15:08:13 INFO [wms.WMSService] - Will NOT recombine tiles for non-tiling clients.
    04 Jul 15:08:13 INFO [wms.WMSService] - Will proxy requests to backend that are not getmap or getcapabilities.
    04 Jul 15:08:13 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wms] onto handler 'dispatcher'
    04 Jul 15:08:13 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wms/*] onto handler 'dispatcher'
    04 Jul 15:08:14 INFO [ows.OWSHandlerMapping] - Mapped URL path [/animate/*] onto handler 'dispatcher'
    04 Jul 15:08:14 INFO [ows.OWSHandlerMapping] - Mapped URL path [/animate] onto handler 'dispatcher'
    04 Jul 15:08:14 INFO [ows.OWSHandlerMapping] - Mapped URL path [/TestWfsPost] onto handler 'wfsTestServlet'
    04 Jul 15:08:14 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wfs/*] onto handler 'dispatcher'
    04 Jul 15:08:14 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wfs] onto handler 'dispatcher'
    04 Jul 15:08:17 INFO [geoserver.monitor] - Monitor extension enabled
    04 Jul 15:08:18 INFO [ows.OWSHandlerMapping] - Mapped URL path [/ows/**] onto handler 'dispatcher'
    04 Jul 15:08:18 INFO [ows.OWSHandlerMapping] - Mapped URL path [/ows] onto handler 'dispatcher'
    04 Jul 15:08:18 INFO [geoserver.security] - Start reloading user/groups for service named default
    04 Jul 15:08:18 INFO [geoserver.security] - Reloading user/groups successful for service named default
    04 Jul 15:08:18 INFO [geoserver.security] - AuthenticationCache Initialized with 1000 Max Entries, 300 seconds idle time, 600 seconds time to live and 3 concurrency level
    04 Jul 15:08:18 INFO [geoserver.security] - AuthenticationCache Eviction Task created to run every 600 seconds
    04-Jul-2017 15:08:18.990 SEVERE [localhost-startStop-1] org.apache.catalina.session.StandardManager.startInternal Exception loading sessions from persistent storage
     java.lang.ClassCastException: java.io.ObjectStreamClass cannot be cast to java.lang.String
            at java.io.ObjectInputStream.readTypeString(ObjectInputStream.java:1612)
            at java.io.ObjectStreamClass.readNonProxy(ObjectStreamClass.java:719)
            at java.io.ObjectInputStream.readClassDescriptor(ObjectInputStream.java:882)
            at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1815)
            at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
            at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2000)
            at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
            at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
            at org.apache.catalina.session.StandardSession.doReadObject(StandardSession.java:1611)
            at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:1077)
            at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:218)
            at org.apache.catalina.session.StandardManager.load(StandardManager.java:162)
            at org.apache.catalina.session.StandardManager.startInternal(StandardManager.java:356)
            at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
            at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5224)
            at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
            at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
            at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
            at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
            at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
            at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
            at java.util.concurrent.FutureTask.run(FutureTask.java:266)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
            at java.lang.Thread.run(Thread.java:748)

    04-Jul-2017 15:08:19.031 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/tomcat/webapps/geoserver.war has finished in 27,515 ms
    04-Jul-2017 15:08:19.032 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /opt/tomcat/webapps/host-manager
    04-Jul-2017 15:08:19.060 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat/webapps/host-manager has finished in 28 ms
    04-Jul-2017 15:08:19.061 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /opt/tomcat/webapps/manager
    04-Jul-2017 15:08:19.079 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat/webapps/manager has finished in 18 ms
    04-Jul-2017 15:08:19.079 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /opt/tomcat/webapps/examples
    04-Jul-2017 15:08:19.217 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat/webapps/examples has finished in 137 ms
    04-Jul-2017 15:08:19.217 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /opt/tomcat/webapps/docs
    04-Jul-2017 15:08:19.227 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat/webapps/docs has finished in 10 ms
    04-Jul-2017 15:08:19.228 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /opt/tomcat/webapps/ROOT
    04-Jul-2017 15:08:19.238 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat/webapps/ROOT has finished in 10 ms
    04-Jul-2017 15:08:19.245 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
    04-Jul-2017 15:08:19.254 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
    04-Jul-2017 15:08:19.274 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 27815 ms
    04 Jul 15:08:19 WARN [util.JDBCExceptionReporter] - SQL Error: 0, SQLState: 23502
    04 Jul 15:08:19 ERROR [util.JDBCExceptionReporter] - ERROR: null value in column "id" violates not-null constraint
      Detail: Failing row contains (null, FINISHED, OTHER, /, null, null, null, 0, 192.168.1.235, ROS-GS3, GET, 2017-07-04 15:08:19.893, 2017-07-04 15:08:19.911, 18, 192.168.1.185, null, null, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KH..., null, null, 0, 0, null, null, null, null, null, 0, null, null, 200, null, 1, 1, -1, -1, null).
    04 Jul 15:08:19 WARN [util.JDBCExceptionReporter] - SQL Error: 0, SQLState: 23502
    04 Jul 15:08:19 ERROR [util.JDBCExceptionReporter] - ERROR: null value in column "id" violates not-null constraint
      Detail: Failing row contains (null, FINISHED, OTHER, /, null, null, null, 0, 192.168.1.235, ROS-GS3, GET, 2017-07-04 15:08:19.893, 2017-07-04 15:08:19.911, 18, 192.168.1.185, null, null, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KH..., null, null, 0, 0, null, null, null, null, null, 0, null, null, 200, null, 1, 1, -1, -1, null).
    04 Jul 15:26:15 WARN [geoserver.security] - Failed login, user admin from 192.168.1.185
    04 Jul 15:26:15 INFO [geoserver.security] - Brute force attack prevention, delaying login for 1672ms
    04 Jul 15:26:16 INFO [geoserver.security] - Strong cryptography is available
</code>```

I dug a little deeper and found this

```<code>2017-07-04 14:52:19,339 WARN [servlet.PageNotFound] - No mapping found for HTTP request with URI [/geoserver/j_spring_oauth2_google_login] in DispatcherServlet with name 'dispatcher'
</code>```

答:
would it be possible for you to provide the piece of GeoServer logs concerning the authentication phase?

It should report any potential exception you might encounter. If not, try to rise up the GeoServer Log Level to DEBUG.

Usually that behavior means that somehow the request to the OAuth2 Provider fails, and in your specific case (if I understood correctly what you are trying to do) most probably it depends on PKIX issue with certs. It is possible that somehow you did not correctly configured the truststore on your Tomcat instance.

Also keep in mind that if you want to enable SSL protocol you also need to use HTTPS endpoint for your GeoServer instance. Otherwise I kindly suggest to go for the plain one.

Body:
I have installed the OAuth2 Extensions for Geoserver successfully and I was able to create the Authentication Filter and added Google_Oauth2 to  the filter chains web
rest
gwc
default

I have also created the truststore and added it to the JAVA_OPTS Path as as ../cacerts.cks

All the steps I have followed are as in the official docs

Now, when I navigate to the Geoserver Home Page as directed by the Docs, I'm not getting the Google Login Page as supposed to.

One of the issues I have discovered is after adding the Google-Oauth2 to the filter chains, when I logout as Geoserver admin, the Google-Oauth is again removed from the selected chains.

What I'd like to know is how to do a stepwise check to determine the root cause of this problem.
Any help will be appreciated.

I have the Google Login ICon, when I click on it I get a 404 Error for this URL http://:8080/geoserver/web/j_spring_oauth2_google_login

Here is the Logfile, I cant find anything in here to point to the problem, just a few warnings here and there which are not related to Authentication

04 Jul 15:08:00 DEBUG [geoserver.global] - Found Java environment variable GEOSERVER_DATA_DIR to be unset
    04-Jul-2017 15:08:00.911 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'XStreamPersisterInitializer', but ApplicationContext is unset.
    04-Jul-2017 15:08:00.912 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionFilter', but ApplicationContext is unset.
    04-Jul-2017 15:08:00.914 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionProvider', but ApplicationContext is unset.
    04-Jul-2017 15:08:00.914 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionFilter', but ApplicationContext is unset.
    log4j:WARN File option not set for appender [geoserverlogfile].
    log4j:WARN Are you using FileAppender instead of ConsoleAppender?
    04-Jul-2017 15:08:03.435 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'GeoServerSecurityProvider', but ApplicationContext is unset.
    04-Jul-2017 15:08:03.435 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionFilter', but ApplicationContext is unset.
    04-Jul-2017 15:08:03.435 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionProvider', but ApplicationContext is unset.
    04-Jul-2017 15:08:03.435 WARNING [localhost-startStop-1] org.geoserver.platform.GeoServerExtensions.checkContext Extension lookup 'ExtensionFilter', but ApplicationContext is unset.
    04 Jul 15:08:04 INFO [config.GeoServerPropertyConfigurer] - Loading properties file from org.geoserver.config.SpringResourceAdaptor@6653368c
    04 Jul 15:08:04 INFO [geoserver.monitor] - Configuring monitoring database from: monitoring/db.properties
    04 Jul 15:08:04 WARN [impl.SessionFactoryObjectFactory] - InitialContext did not implement EventContext
<Loaded smth........>
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Will look for 'geowebcache.xml' in directory '/var/lib/geoserver_data/gwc'.
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:07 WARN [config.XMLConfiguration] - ********************************************************************************
    04 Jul 15:08:07 WARN [config.XMLConfiguration] - *** GWC configuration validation error: cvc-elt.1: Cannot find the declaration of element 'gwcConfiguration'.
    04 Jul 15:08:07 WARN [config.XMLConfiguration] - *** Will try to use configuration anyway. Please check the order of declared elements against the schema.
    04 Jul 15:08:07 WARN [config.XMLConfiguration] - ********************************************************************************
    04 Jul 15:08:07 INFO [gwc.layer] - Initializing GWC configuration based on GeoServer's Catalog
    04 Jul 15:08:07 INFO [gwc.layer] - GeoServer TileLayer store base directory is: gwc-layers
    04 Jul 15:08:07 INFO [gwc.layer] - Loading tile layers from gwc-layers
    04 Jul 15:08:07 INFO [config.XMLConfiguration] - Initializing GridSets from gwc
    04 Jul 15:08:07 INFO [config.XMLConfiguration] - Initializing layers from gwc
    04 Jul 15:08:07 INFO [layer.TileLayerDispatcher] - Configuration gwc contained no layers.
    04 Jul 15:08:07 INFO [storage.DefaultStorageFinder] - **************************************************************************************************************************
    04 Jul 15:08:07 INFO [storage.DefaultStorageFinder] - *** Found Servlet context parameter GEOSERVER_DATA_DIR set to /var/lib/geoserver_data, using it as the default prefix. ***
    04 Jul 15:08:07 INFO [storage.DefaultStorageFinder] - **************************************************************************************************************************
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Will look for 'geowebcache-diskquota.xml' in directory '/var/lib/geoserver_data/gwc'.
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Will look for 'geowebcache-diskquota-jdbc.xml' in directory '/var/lib/geoserver_data/gwc'.
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:07 INFO [diskquota.ConfigLoader] - Quota config is: gwc/geowebcache-diskquota.xml
    04 Jul 15:08:07 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:09 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:09 INFO [diskquota.ConfigLoader] - Quota config is: gwc/geowebcache-diskquota.xml
    04 Jul 15:08:09 INFO [config.GeoserverXMLResourceProvider] - Found configuration file in gwc
    04 Jul 15:08:09 INFO [diskquota.DiskQuotaMonitor] - Setting up disk quota periodic enforcement task
    04 Jul 15:08:09 INFO [diskquota.DiskQuotaMonitor] - 0 layers configured with their own quotas.
    04 Jul 15:08:09 INFO [diskquota.DiskQuotaMonitor] - 24 layers attached to global quota 500.0 MB
    04 Jul 15:08:09 INFO [diskquota.DiskQuotaMonitor] - Disk quota periodic enforcement task set up every 30 SECONDS
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WPSInfoImpl--ecf5ed2:15cf44cc45b:-8000', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'wcs', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WMTSInfoImpl--387a6a83:15d0d802c5c:-8000', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'wms', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'wfs', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WPSInfoImpl-2db12f5c:15cf83a5f1b:-7fdb', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WCSInfoImpl-2db12f5c:15cf83a5f1b:-7fdc', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WMTSInfoImpl-2db12f5c:15cf83a5f1b:-7fdf', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WMSInfoImpl-2db12f5c:15cf83a5f1b:-7fde', enabled
    04 Jul 15:08:10 INFO [org.geoserver] - Loaded service 'WFSInfoImpl-2db12f5c:15cf83a5f1b:-7fdd', enabled
    04 Jul 15:08:10 INFO [geoserver.monitor] - Monitor hibernate extension enabled
    04 Jul 15:08:10 INFO [gwc.config] - Initializing GeoServer specific GWC configuration from gwc-gs.xml
    04 Jul 15:08:11 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wps] onto handler 'dispatcher'
    04 Jul 15:08:11 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wps/*] onto handler 'dispatcher'
    04 Jul 15:08:11 INFO [ows.OWSHandlerMapping] - Mapped URL path [/temp/**] onto handler 'filePublisher'
    04 Jul 15:08:11 INFO [geoserver.wps] - Found 89 bindable processes in Deprecated processes
    04 Jul 15:08:11 INFO [geoserver.wps] - Found 5 bindable processes in GeoServer specific processes
    04 Jul 15:08:11 INFO [geoserver.wps] - Found 48 bindable processes in Geometry processes
    04 Jul 15:08:11 INFO [geoserver.wps] - Found 30 bindable processes in Vector processes
    04 Jul 15:08:11 INFO [geoserver.wps] - Blacklisting process ras:ConvolveCoverage as the input kernel of type class javax.media.jai.KernelJAI cannot be handled
    04 Jul 15:08:11 INFO [geoserver.wps] - Blacklisting process ras:RasterZonalStatistics2 as the input zones of type class java.lang.Object cannot be handled
    04 Jul 15:08:11 INFO [geoserver.wps] - Blacklisting process ras:RasterZonalStatistics2 as the input nodata of type class it.geosolutions.jaiext.range.Range cannot be handled
    04 Jul 15:08:11 INFO [geoserver.wps] - Blacklisting process ras:RasterZonalStatistics2 as the input rangeData of type class java.lang.Object cannot be handled
    04 Jul 15:08:11 INFO [geoserver.wps] - Blacklisting process ras:RasterZonalStatistics2 as the output zonal statistics of type interface java.util.List cannot be handled
    04 Jul 15:08:11 INFO [geoserver.wps] - Found 17 bindable processes in Raster processes
    04 Jul 15:08:11 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wcs] onto handler 'dispatcher'
    04 Jul 15:08:11 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wcs/*] onto handler 'dispatcher'
    04 Jul 15:08:11 INFO [org.geoserver] - GeoServer configuration lock is enabled
    04 Jul 15:08:11 WARN [turbojpeg.TurboJPEGMapResponse] - The turbo jpeg encoder is available for usage
    04 Jul 15:08:12 INFO [ows.OWSHandlerMapping] - Mapped URL path [/kml] onto handler 'dispatcher'
    04 Jul 15:08:12 INFO [ows.OWSHandlerMapping] - Mapped URL path [/kml/*] onto handler 'dispatcher'
    04 Jul 15:08:12 INFO [ows.OWSHandlerMapping] - Mapped URL path [/kml/icon/**/*] onto handler 'kmlIconService'
    04 Jul 15:08:13 INFO [ows.OWSHandlerMapping] - Mapped URL path [/gwc/service/**] onto handler 'dispatcher'
    04 Jul 15:08:13 INFO [geowebcache.GeoWebCacheDispatcher] - Invoked setServletPrefix(gwc)
    04 Jul 15:08:13 INFO [georss.GeoRSSPoller] - Initializing GeoRSS poller in a background job...
    04 Jul 15:08:13 INFO [georss.GeoRSSPoller] - No enabled GeoRSS feeds found, poller will not run.
    04 Jul 15:08:13 INFO [rest.RESTDispatcher] - Created RESTDispatcher with 15 paths
    04 Jul 15:08:13 INFO [wms.WMSService] - Will NOT recombine tiles for non-tiling clients.
    04 Jul 15:08:13 INFO [wms.WMSService] - Will proxy requests to backend that are not getmap or getcapabilities.
    04 Jul 15:08:13 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wms] onto handler 'dispatcher'
    04 Jul 15:08:13 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wms/*] onto handler 'dispatcher'
    04 Jul 15:08:14 INFO [ows.OWSHandlerMapping] - Mapped URL path [/animate/*] onto handler 'dispatcher'
    04 Jul 15:08:14 INFO [ows.OWSHandlerMapping] - Mapped URL path [/animate] onto handler 'dispatcher'
    04 Jul 15:08:14 INFO [ows.OWSHandlerMapping] - Mapped URL path [/TestWfsPost] onto handler 'wfsTestServlet'
    04 Jul 15:08:14 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wfs/*] onto handler 'dispatcher'
    04 Jul 15:08:14 INFO [ows.OWSHandlerMapping] - Mapped URL path [/wfs] onto handler 'dispatcher'
    04 Jul 15:08:17 INFO [geoserver.monitor] - Monitor extension enabled
    04 Jul 15:08:18 INFO [ows.OWSHandlerMapping] - Mapped URL path [/ows/**] onto handler 'dispatcher'
    04 Jul 15:08:18 INFO [ows.OWSHandlerMapping] - Mapped URL path [/ows] onto handler 'dispatcher'
    04 Jul 15:08:18 INFO [geoserver.security] - Start reloading user/groups for service named default
    04 Jul 15:08:18 INFO [geoserver.security] - Reloading user/groups successful for service named default
    04 Jul 15:08:18 INFO [geoserver.security] - AuthenticationCache Initialized with 1000 Max Entries, 300 seconds idle time, 600 seconds time to live and 3 concurrency level
    04 Jul 15:08:18 INFO [geoserver.security] - AuthenticationCache Eviction Task created to run every 600 seconds
    04-Jul-2017 15:08:18.990 SEVERE [localhost-startStop-1] org.apache.catalina.session.StandardManager.startInternal Exception loading sessions from persistent storage
     java.lang.ClassCastException: java.io.ObjectStreamClass cannot be cast to java.lang.String
            at java.io.ObjectInputStream.readTypeString(ObjectInputStream.java:1612)
            at java.io.ObjectStreamClass.readNonProxy(ObjectStreamClass.java:719)
            at java.io.ObjectInputStream.readClassDescriptor(ObjectInputStream.java:882)
            at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1815)
            at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
            at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2000)
            at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
            at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
            at org.apache.catalina.session.StandardSession.doReadObject(StandardSession.java:1611)
            at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:1077)
            at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:218)
            at org.apache.catalina.session.StandardManager.load(StandardManager.java:162)
            at org.apache.catalina.session.StandardManager.startInternal(StandardManager.java:356)
            at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
            at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5224)
            at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
            at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
            at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
            at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
            at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
            at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
            at java.util.concurrent.FutureTask.run(FutureTask.java:266)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
            at java.lang.Thread.run(Thread.java:748)

    04-Jul-2017 15:08:19.031 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/tomcat/webapps/geoserver.war has finished in 27,515 ms
    04-Jul-2017 15:08:19.032 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /opt/tomcat/webapps/host-manager
    04-Jul-2017 15:08:19.060 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat/webapps/host-manager has finished in 28 ms
    04-Jul-2017 15:08:19.061 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /opt/tomcat/webapps/manager
    04-Jul-2017 15:08:19.079 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat/webapps/manager has finished in 18 ms
    04-Jul-2017 15:08:19.079 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /opt/tomcat/webapps/examples
    04-Jul-2017 15:08:19.217 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat/webapps/examples has finished in 137 ms
    04-Jul-2017 15:08:19.217 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /opt/tomcat/webapps/docs
    04-Jul-2017 15:08:19.227 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat/webapps/docs has finished in 10 ms
    04-Jul-2017 15:08:19.228 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /opt/tomcat/webapps/ROOT
    04-Jul-2017 15:08:19.238 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat/webapps/ROOT has finished in 10 ms
    04-Jul-2017 15:08:19.245 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
    04-Jul-2017 15:08:19.254 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
    04-Jul-2017 15:08:19.274 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 27815 ms
    04 Jul 15:08:19 WARN [util.JDBCExceptionReporter] - SQL Error: 0, SQLState: 23502
    04 Jul 15:08:19 ERROR [util.JDBCExceptionReporter] - ERROR: null value in column "id" violates not-null constraint
      Detail: Failing row contains (null, FINISHED, OTHER, /, null, null, null, 0, 192.168.1.235, ROS-GS3, GET, 2017-07-04 15:08:19.893, 2017-07-04 15:08:19.911, 18, 192.168.1.185, null, null, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KH..., null, null, 0, 0, null, null, null, null, null, 0, null, null, 200, null, 1, 1, -1, -1, null).
    04 Jul 15:08:19 WARN [util.JDBCExceptionReporter] - SQL Error: 0, SQLState: 23502
    04 Jul 15:08:19 ERROR [util.JDBCExceptionReporter] - ERROR: null value in column "id" violates not-null constraint
      Detail: Failing row contains (null, FINISHED, OTHER, /, null, null, null, 0, 192.168.1.235, ROS-GS3, GET, 2017-07-04 15:08:19.893, 2017-07-04 15:08:19.911, 18, 192.168.1.185, null, null, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KH..., null, null, 0, 0, null, null, null, null, null, 0, null, null, 200, null, 1, 1, -1, -1, null).
    04 Jul 15:26:15 WARN [geoserver.security] - Failed login, user admin from 192.168.1.185
    04 Jul 15:26:15 INFO [geoserver.security] - Brute force attack prevention, delaying login for 1672ms
    04 Jul 15:26:16 INFO [geoserver.security] - Strong cryptography is available

I dug a little deeper and found this

2017-07-04 14:52:19,339 WARN [servlet.PageNotFound] - No mapping found for HTTP request with URI [/geoserver/j_spring_oauth2_google_login] in DispatcherServlet with name 'dispatcher'


问:
javascript - Google Maps Full Screen Button Not Working ( Non-google maps app )
As shown below, beides the '+' icon is the full screen button.

When clicked on it, it does not go full screen.

I tried basic jQuery :

```<code> $("#fullScreen-btn").css({height: 100%, width: 100%});
</code>```

This does not seem to work.

I need it to work like we press F11 on browsers, it must go full screen on mobile (not the google maps app)

Can anyone help me out here ?

答:
Try this. I calculated the height separately to achieve the results. Tested in android device.

$(document).ready(function() {
  let height = $(document).height();
  $('.fullscreen').on('click', function() {
    $('iframe').css({
      height: height,
      width: '100%'
    });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
}

.fullscreen {
  position: absolute;
  top: 10px;
  right: 10px;
}</code>```

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">

    <input type="button" name="fullscreen" value="fullscreen" class="fullscreen" />

```

Body:
As shown below, beides the '+' icon is the full screen button.

When clicked on it, it does not go full screen.

I tried basic jQuery :

 $("#fullScreen-btn").css({height: 100%, width: 100%});

This does not seem to work.

I need it to work like we press F11 on browsers, it must go full screen on mobile (not the google maps app)

Can anyone help me out here ?

Body:
Try this. I calculated the height separately to achieve the results. Tested in android device.

$(document).ready(function() {
  let height = $(document).height();
  $('.fullscreen').on('click', function() {
    $('iframe').css({
      height: height,
      width: '100%'
    });
  });
});

body {
  margin: 0;
  padding: 0;
}

.fullscreen {
  position: absolute;
  top: 10px;
  right: 10px;
}

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>
  <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d423283.3363121453!2d-118.69191670818714!3d34.020750397391296!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x80c2c75ddc27da13%3A0xe22fdf6f254608f4!2sLos+Angeles%2C+CA%2C+USA!5e0!3m2!1sen!2srw!4v1499159650271"
    width="250" height="250" frameborder="0" style="border:0" allowfullscreen></iframe>
  <div class="container">
    <input type="button" name="fullscreen" value="fullscreen" class="fullscreen" />
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>

</html>


问:
Adding and Updating a List object does not work in C#
Newbie with C# and Linq.

I am trying to add an object and update an object if exists in a List. The list is not getting updated or not getting added with new inputs.It is not throwing any exception. Kindly, help.

```<code>private IList<SettingsEntity> Settings = new List<SettingsEntity>();

public SettingsRepository() {
            Settings.Add(new SettingsEntity() { UserID = "alpha", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "bravo", ApplicationName = "view", SettingKey = "RefreshRate", SettingValue = "10", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "charlie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "foxtrot", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "lima", ApplicationName = "view", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "Julie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "tango", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "victor", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "yankee", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "zulu", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
        }

 public bool Save(SettingsEntity entity)
        {
            var flag = false;
            if (entity != null)
            {
                var existing = Settings.Where(se => se.UserID == entity.UserID && se.ApplicationName == entity.ApplicationName && se.SettingKey == entity.SettingKey).ToList();
                if (existing != null)
                {
                    existing.ForEach(f => f.SettingValue = entity.SettingValue);
                    flag = true;
                }
                else
                {
                    Settings.Add(entity);
                    flag = true;
                }
                return flag;
            }
            else {
                throw new ArgumentNullException();
            }

        }

 [HttpPost]
        public IActionResult Post([FromBody] SettingsEntity entity)
        {
            var result = _SettingsRepository.Save(entity);
            if (result == true)
            {
                return Ok();
            }
            else
            {
                return BadRequest();
            }
        }
</code>```

答:
Linq queries always return Ienumerable collection which either has zero or more than zero elements. So, It will never be null. Moreover, you can skip the flag variable too. By putting a count check to ensure that something has been added or not.

Or try to avoid using Count method. As it has complexity of o(n). So, if you just want to ensure is there any item, then prefer to use Any() method instead of Count();

Body:
Newbie with C# and Linq.

I am trying to add an object and update an object if exists in a List. The list is not getting updated or not getting added with new inputs.It is not throwing any exception. Kindly, help.

private IList<SettingsEntity> Settings = new List<SettingsEntity>();

public SettingsRepository() {
            Settings.Add(new SettingsEntity() { UserID = "alpha", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "bravo", ApplicationName = "view", SettingKey = "RefreshRate", SettingValue = "10", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "charlie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "foxtrot", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "lima", ApplicationName = "view", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "Julie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "tango", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "victor", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "yankee", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "zulu", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
        }

 public bool Save(SettingsEntity entity)
        {
            var flag = false;
            if (entity != null)
            {
                var existing = Settings.Where(se => se.UserID == entity.UserID && se.ApplicationName == entity.ApplicationName && se.SettingKey == entity.SettingKey).ToList();
                if (existing != null)
                {
                    existing.ForEach(f => f.SettingValue = entity.SettingValue);
                    flag = true;
                }
                else
                {
                    Settings.Add(entity);
                    flag = true;
                }
                return flag;
            }
            else {
                throw new ArgumentNullException();
            }

        }

 [HttpPost]
        public IActionResult Post([FromBody] SettingsEntity entity)
        {
            var result = _SettingsRepository.Save(entity);
            if (result == true)
            {
                return Ok();
            }
            else
            {
                return BadRequest();
            }
        }


问:
ASP.Net HTTP2 PushPromise is slow
I'm trying to implement the Http2 push server functionality using "PushPromise" .NET 4.6.1, for this I have a "html extension" with Razor (we did not implement MVC only used the Razor engine to build the pages).

```<code>    public static IHtmlString PushPromiseStylesheet(this HtmlHelper htmlHelper, string src, bool addDomElement = true)
    {
        var context = HttpContext.Current;
        var path = System.Web.Optimization.Styles.Url(src).ToString();

        var headers = new NameValueCollection { { "accept-encoding", context.Request.Headers["accept-encoding"] } };
        context.Response.PushPromise(path, "GET", headers);

        var styleElement = $"<link rel=\"preload\" href=\"{path}\" as=\"style\">";

        return new HtmlString(addDomElement ? styleElement : String.Empty);
    }

    public static IHtmlString PushPromiseJavascript(this HtmlHelper htmlHelper, string src)
    {
        var context = HttpContext.Current;
        var path = System.Web.Optimization.Scripts.Url(src).ToString();

        var headers = new NameValueCollection { { "accept-encoding", context.Request.Headers["accept-encoding"] } };
        context.Response.PushPromise(path,"GET",headers);

        var javascriptElement = $"<link rel=\"preload\" href=\"{path}\" as=\"script\">";

        return new HtmlString(javascriptElement);
    }
    public static IHtmlString PushPromiseImage(this HtmlHelper htmlHelper, string src, bool addDomElement = false)
    {
        var context = HttpContext.Current;
        var path = System.Web.Optimization.Scripts.Url(src).ToString();

        var headers = new NameValueCollection { { "accept-encoding", context.Request.Headers["accept-encoding"] } };
        context.Response.PushPromise(path,"GET",headers);

        var imgElement = $"<link rel=\"preload\" href=\"{path}\">";

        return new HtmlString(addDomElement ? imgElement : String.Empty);
    }

    public static IHtmlString PushPromiseWebFont(this HtmlHelper htmlHelper, string src, string type = null)
    {
        var context = HttpContext.Current;
        var path = System.Web.Optimization.Scripts.Url(src).ToString();
        type = string.IsNullOrWhiteSpace(type) ? "font/woff2" : type;

        var headers = new NameValueCollection { { "accept-encoding", context.Request.Headers["accept-encoding"] } };
        context.Response.PushPromise(path, "GET", headers);

        var fontElement = $"<link rel=\"preload\" href=\"{path}\" as=\"font\" type=\"{type}\"> ";

        return new HtmlString(fontElement);
    }
</code>```

And in the  of the page:

```<code><head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<title>@Page.Title</title>
@Html.PushPromiseStylesheet("~/css/app/fonts.css")
@Html.PushPromiseStylesheet("~/css/landing.base.css")
@Html.PushPromiseStylesheet("~/css/landing.style.css")
@Html.PushPromiseImage("/assets/img/bg-ofertas.jpg")
@Html.PushPromiseImage("/assets/img/landings/v2/iphone.png")
@Html.PushPromiseImage("/assets/img/landings/v2/ipad-new.png")
@Html.PushPromiseImage("/assets/img/landings/v2/macbook-new.png")

@Html.PushPromiseWebFont("/assets/fonts/CredimejoraIcons.woff2?miydpz")
@Html.PushPromiseWebFont("/assets/fonts/centrale_sans_regular_italic-webfont.woff2")
@Html.PushPromiseWebFont("/assets/fonts/centrale_sans_bold_italic-webfont.woff2")
@Html.PushPromiseWebFont("/assets/fonts/centrale_sans_regular-webfont.woff2")
@Html.PushPromiseWebFont("/assets/fonts/centrale_sans_bold-webfont.woff2")

@Html.PushPromiseJavascript("/assets/js/public/libs/jquery.inputmask.bundle-3.3.6.2.js")
</code>```

I have hosted the same project "without using PushPromise" (credimejorademo), and in another domain I have implemented PushPromise (aquituinmueble):

https://www.webpagetest.org/video/compare.php?tests=170609_PD_e32f303e034aef3fef7140fef181a738,170609_FK_7d538ecdacf071cce320ad14bf97414c

答:
Just a couple of things I'd mention here. Firstly, although this may seem counter-intuitive, you're probably best off not pushing -everything-. The limited amount of testing I've seen (eg: https://www.smashingmagazine.com/2017/04/guide-http2-server-push/) suggests that pushing css only is probably the best way to improve performance, although it's worth playing around with on an individual site basis.

The other thing is that the way you are implementing PushPromise means that IIS is only getting that request once it's already started processing the page. ie, you're requesting the push at more or less the same time the page would have requested it via a standard .

Hope this helps.

Title: ASP.Net HTTP2 PushPromise is slow

Body:
I'm trying to implement the Http2 push server functionality using "PushPromise" .NET 4.6.1, for this I have a "html extension" with Razor (we did not implement MVC only used the Razor engine to build the pages).

    public static IHtmlString PushPromiseStylesheet(this HtmlHelper htmlHelper, string src, bool addDomElement = true)
    {
        var context = HttpContext.Current;
        var path = System.Web.Optimization.Styles.Url(src).ToString();

        var headers = new NameValueCollection { { "accept-encoding", context.Request.Headers["accept-encoding"] } };
        context.Response.PushPromise(path, "GET", headers);

        var styleElement = $"<link rel=\"preload\" href=\"{path}\" as=\"style\">";

        return new HtmlString(addDomElement ? styleElement : String.Empty);
    }

    public static IHtmlString PushPromiseJavascript(this HtmlHelper htmlHelper, string src)
    {
        var context = HttpContext.Current;
        var path = System.Web.Optimization.Scripts.Url(src).ToString();

        var headers = new NameValueCollection { { "accept-encoding", context.Request.Headers["accept-encoding"] } };
        context.Response.PushPromise(path,"GET",headers);

        var javascriptElement = $"<link rel=\"preload\" href=\"{path}\" as=\"script\">";

        return new HtmlString(javascriptElement);
    }
    public static IHtmlString PushPromiseImage(this HtmlHelper htmlHelper, string src, bool addDomElement = false)
    {
        var context = HttpContext.Current;
        var path = System.Web.Optimization.Scripts.Url(src).ToString();

        var headers = new NameValueCollection { { "accept-encoding", context.Request.Headers["accept-encoding"] } };
        context.Response.PushPromise(path,"GET",headers);

        var imgElement = $"<link rel=\"preload\" href=\"{path}\">";

        return new HtmlString(addDomElement ? imgElement : String.Empty);
    }

    public static IHtmlString PushPromiseWebFont(this HtmlHelper htmlHelper, string src, string type = null)
    {
        var context = HttpContext.Current;
        var path = System.Web.Optimization.Scripts.Url(src).ToString();
        type = string.IsNullOrWhiteSpace(type) ? "font/woff2" : type;

        var headers = new NameValueCollection { { "accept-encoding", context.Request.Headers["accept-encoding"] } };
        context.Response.PushPromise(path, "GET", headers);

        var fontElement = $"<link rel=\"preload\" href=\"{path}\" as=\"font\" type=\"{type}\"> ";

        return new HtmlString(fontElement);
    }

And in the  of the page:

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<title>@Page.Title</title>
@Html.PushPromiseStylesheet("~/css/app/fonts.css")
@Html.PushPromiseStylesheet("~/css/landing.base.css")
@Html.PushPromiseStylesheet("~/css/landing.style.css")
@Html.PushPromiseImage("/assets/img/bg-ofertas.jpg")
@Html.PushPromiseImage("/assets/img/landings/v2/iphone.png")
@Html.PushPromiseImage("/assets/img/landings/v2/ipad-new.png")
@Html.PushPromiseImage("/assets/img/landings/v2/macbook-new.png")

@Html.PushPromiseWebFont("/assets/fonts/CredimejoraIcons.woff2?miydpz")
@Html.PushPromiseWebFont("/assets/fonts/centrale_sans_regular_italic-webfont.woff2")
@Html.PushPromiseWebFont("/assets/fonts/centrale_sans_bold_italic-webfont.woff2")
@Html.PushPromiseWebFont("/assets/fonts/centrale_sans_regular-webfont.woff2")
@Html.PushPromiseWebFont("/assets/fonts/centrale_sans_bold-webfont.woff2")

@Html.PushPromiseJavascript("/assets/js/public/libs/jquery.inputmask.bundle-3.3.6.2.js")

I have hosted the same project "without using PushPromise" (credimejorademo), and in another domain I have implemented PushPromise (aquituinmueble):

https://www.webpagetest.org/video/compare.php?tests=170609_PD_e32f303e034aef3fef7140fef181a738,170609_FK_7d538ecdacf071cce320ad14bf97414c