问:
Xamarin.Forms Android Startup takes 10 seconds
My Android app (created using Xamarin.Forms) takes around 10 seconds to start (both in Debug & Release mode) on a real device (Asus Zenfone 2). The splash screen is showing for 8 seconds. Here is my log attached where as "extrony" is my app name. Only assembly loading takes this much time. Any help?

Android Startup log

EDIT 1:
It actually takes 10 seconds (I mentioned 8 by mistake, but updated now)

EDIT 2: On an Emulator (I am using Android Emulator for Visual Studio) the app starts faster i.e. within 4.3seconds. However on my real device (Asus Zenfone2), the time it takes is 10seconds. Here is additional thing I see on the debug output while debugging on a real device (It doesn't appear if you debug on the emulator) and loading these assemblies ALONE takes ~6seconds.

```<code>Android application is debugging.
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/extrony.Droid.dll
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Acr.Support.Android.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Acr.UserDialogs.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Acr.UserDialogs.Interface.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/AndHUD.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/CarouselView.FormsPlugin.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/CarouselView.FormsPlugin.Android.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/FFImageLoading.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/FFImageLoading.Forms.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/FFImageLoading.Forms.Droid.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/FFImageLoading.Platform.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/FormsViewGroup.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/HtmlAgilityPack.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.Analytics.Android.Bindings.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.Analytics.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.Android.Bindings.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.Crashes.Android.Bindings.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.Crashes.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Data.Sqlite.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.EntityFrameworkCore.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.EntityFrameworkCore.Relational.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.EntityFrameworkCore.Sqlite.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Caching.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Caching.Memory.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.DependencyInjection.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.DependencyInjection.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Logging.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Logging.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Options.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Primitives.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/ModernHttpClient.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Newtonsoft.Json.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/OkHttp.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Connectivity.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Connectivity.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.CurrentActivity.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Settings.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Settings.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Share.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Share.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Remotion.Linq.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/SgmlReaderDll.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Splat.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/System.Collections.Immutable.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/System.Diagnostics.DiagnosticSource.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/System.Interactive.Async.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/System.Runtime.CompilerServices.Unsafe.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.Animated.Vector.Drawable.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.CustomTabs.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.Design.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.v4.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.v7.AppCompat.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.v7.CardView.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.v7.MediaRouter.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.v7.RecyclerView.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.Vector.Drawable.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Forms.Core.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Forms.Platform.Android.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Forms.Platform.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Forms.Xaml.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/extrony.dll
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/extrony.Data.dll
Loaded assembly: Mono.Android.dll [External]
Loaded assembly: Java.Interop.dll [External]
Loaded assembly: System.Runtime.dll [External]
Loaded assembly: System.Collections.Concurrent.dll [External]
Loaded assembly: System.Reflection.dll [External]
Loaded assembly: System.Threading.dll [External]
Loaded assembly: System.Diagnostics.Debug.dll [External]
Loaded assembly: System.dll [External]
Loaded assembly: System.Runtime.InteropServices.dll [External]
Loaded assembly: System.Collections.dll [External]
Loaded assembly: System.Linq.dll [External]
Loaded assembly: System.Core.dll [External]
Loaded assembly: System.Reflection.Extensions.dll [External]
Loaded assembly: MonoDroidConstructors [External]
Loaded assembly: System.ObjectModel.dll [External]
Loaded assembly: System.Threading.Tasks.dll [External]
Loaded assembly: System.Xml.ReaderWriter.dll [External]
Loaded assembly: System.Xml.dll [External]
Loaded assembly: System.IO.dll [External]
Loaded assembly: System.Runtime.Extensions.dll [External]
Loaded assembly: System.Linq.Expressions.dll [External]
Loaded assembly: System.Resources.ResourceManager.dll [External]
Loaded assembly: System.Globalization.dll [External]
Loaded assembly: System.Dynamic.Runtime.dll [External]
Loaded assembly: System.ComponentModel.dll [External]
Thread started: <Thread Pool> #2
Thread started: <Thread Pool> #3
Thread started: <Thread Pool> #4
Thread started: <Thread Pool> #5
Loaded assembly: System.Linq.Queryable.dll [External]
Loaded assembly: Anonymously Hosted DynamicMethods Assembly [External]
Loaded assembly: System.Data.Common.dll [External]
Loaded assembly: System.Data.dll [External]
Thread started: <Thread Pool> #6
Loaded assembly: System.Diagnostics.Tracing.dll [External]
Loaded assembly: System.ComponentModel.Annotations.dll [External]
Loaded assembly: System.ComponentModel.DataAnnotations.dll [External]
</code>```

EDIT 3:
Tested on different devices per suggestion received via comments. These are the results (from a release build)

~8 to 10 seconds on Samsung Galaxy OnNXT

~6-7 seconds on Xiaomi Mi Max Prime

~4-5 seconds on Redmi Note 3

~9.5 seconds on Asus Zenfone2

Edit 4:
I have done a very detailed testing and I can confirm that "context.Migrate() and a simple query with SingleOrDefault()" (EFCore) takes 9 seconds. If I remove this call, the app starts in ~3 seconds.

EDIT 5:
I was expecting to do the db init on a different thread in the splash activity (like the below), since the Xamarin.Forms initialization (usually) takes around 3 seconds and I want the init also to happen in parallel. However it appears that even though it runs on a different thread the EFCore db init also contributes to the start-up time.
Am I doing anything wrong?

```<code> protected override void OnResume()
    {
        base.OnResume();

        System.Threading.Tasks.Task.Run(() =>
        {
            App.DbFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            App.InitializeDb();
        });

        StartActivity(typeof(MainActivity));

    }
</code>```

Any help with a suggestion?

答:
If your Main Page calls services , loads data or does something that needs some time to complete, you can add splash screen . This is solve my problem on android.

http://www.c-sharpcorner.com/UploadFile/oussamaalrifai/xamarin-forms-android-workaround-for-splash-screen-with-lo/

Body:
My Android app (created using Xamarin.Forms) takes around 10 seconds to start (both in Debug & Release mode) on a real device (Asus Zenfone 2). The splash screen is showing for 8 seconds. Here is my log attached where as "extrony" is my app name. Only assembly loading takes this much time. Any help?

Android Startup log

EDIT 1:
It actually takes 10 seconds (I mentioned 8 by mistake, but updated now)

EDIT 2: On an Emulator (I am using Android Emulator for Visual Studio) the app starts faster i.e. within 4.3seconds. However on my real device (Asus Zenfone2), the time it takes is 10seconds. Here is additional thing I see on the debug output while debugging on a real device (It doesn't appear if you debug on the emulator) and loading these assemblies ALONE takes ~6seconds.

Android application is debugging.
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/extrony.Droid.dll
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Acr.Support.Android.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Acr.UserDialogs.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Acr.UserDialogs.Interface.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/AndHUD.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/CarouselView.FormsPlugin.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/CarouselView.FormsPlugin.Android.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/FFImageLoading.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/FFImageLoading.Forms.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/FFImageLoading.Forms.Droid.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/FFImageLoading.Platform.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/FormsViewGroup.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/HtmlAgilityPack.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.Analytics.Android.Bindings.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.Analytics.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.Android.Bindings.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.Crashes.Android.Bindings.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.Crashes.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Azure.Mobile.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Data.Sqlite.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.EntityFrameworkCore.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.EntityFrameworkCore.Relational.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.EntityFrameworkCore.Sqlite.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Caching.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Caching.Memory.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.DependencyInjection.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.DependencyInjection.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Logging.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Logging.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Options.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Microsoft.Extensions.Primitives.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/ModernHttpClient.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Newtonsoft.Json.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/OkHttp.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Connectivity.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Connectivity.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.CurrentActivity.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Settings.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Settings.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Share.Abstractions.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Plugin.Share.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Remotion.Linq.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/SgmlReaderDll.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Splat.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/System.Collections.Immutable.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/System.Diagnostics.DiagnosticSource.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/System.Interactive.Async.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/System.Runtime.CompilerServices.Unsafe.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.Animated.Vector.Drawable.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.CustomTabs.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.Design.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.v4.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.v7.AppCompat.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.v7.CardView.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.v7.MediaRouter.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.v7.RecyclerView.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Android.Support.Vector.Drawable.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Forms.Core.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Forms.Platform.Android.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Forms.Platform.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/Xamarin.Forms.Xaml.dll [External]
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/extrony.dll
Loaded assembly: /storage/emulated/0/Android/data/com.abdullah.extrony/files/.__override__/extrony.Data.dll
Loaded assembly: Mono.Android.dll [External]
Loaded assembly: Java.Interop.dll [External]
Loaded assembly: System.Runtime.dll [External]
Loaded assembly: System.Collections.Concurrent.dll [External]
Loaded assembly: System.Reflection.dll [External]
Loaded assembly: System.Threading.dll [External]
Loaded assembly: System.Diagnostics.Debug.dll [External]
Loaded assembly: System.dll [External]
Loaded assembly: System.Runtime.InteropServices.dll [External]
Loaded assembly: System.Collections.dll [External]
Loaded assembly: System.Linq.dll [External]
Loaded assembly: System.Core.dll [External]
Loaded assembly: System.Reflection.Extensions.dll [External]
Loaded assembly: MonoDroidConstructors [External]
Loaded assembly: System.ObjectModel.dll [External]
Loaded assembly: System.Threading.Tasks.dll [External]
Loaded assembly: System.Xml.ReaderWriter.dll [External]
Loaded assembly: System.Xml.dll [External]
Loaded assembly: System.IO.dll [External]
Loaded assembly: System.Runtime.Extensions.dll [External]
Loaded assembly: System.Linq.Expressions.dll [External]
Loaded assembly: System.Resources.ResourceManager.dll [External]
Loaded assembly: System.Globalization.dll [External]
Loaded assembly: System.Dynamic.Runtime.dll [External]
Loaded assembly: System.ComponentModel.dll [External]
Thread started: <Thread Pool> #2
Thread started: <Thread Pool> #3
Thread started: <Thread Pool> #4
Thread started: <Thread Pool> #5
Loaded assembly: System.Linq.Queryable.dll [External]
Loaded assembly: Anonymously Hosted DynamicMethods Assembly [External]
Loaded assembly: System.Data.Common.dll [External]
Loaded assembly: System.Data.dll [External]
Thread started: <Thread Pool> #6
Loaded assembly: System.Diagnostics.Tracing.dll [External]
Loaded assembly: System.ComponentModel.Annotations.dll [External]
Loaded assembly: System.ComponentModel.DataAnnotations.dll [External]

EDIT 3:
Tested on different devices per suggestion received via comments. These are the results (from a release build)

~8 to 10 seconds on Samsung Galaxy OnNXT

~6-7 seconds on Xiaomi Mi Max Prime

~4-5 seconds on Redmi Note 3

~9.5 seconds on Asus Zenfone2

Edit 4:
I have done a very detailed testing and I can confirm that "context.Migrate() and a simple query with SingleOrDefault()" (EFCore) takes 9 seconds. If I remove this call, the app starts in ~3 seconds.

EDIT 5:
I was expecting to do the db init on a different thread in the splash activity (like the below), since the Xamarin.Forms initialization (usually) takes around 3 seconds and I want the init also to happen in parallel. However it appears that even though it runs on a different thread the EFCore db init also contributes to the start-up time.
Am I doing anything wrong?

 protected override void OnResume()
    {
        base.OnResume();

        System.Threading.Tasks.Task.Run(() =>
        {
            App.DbFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            App.InitializeDb();
        });

        StartActivity(typeof(MainActivity));

    }

Any help with a suggestion?


来源: stackexchange

问:
Is it possible to suppress fields from API results?
For example, I wish to get the like count for each post without getting name and Id details of each like.

The likes attribute returned for a call to me/posts?fields=likes.summary(true) would be:

```<code>      "likes": {
        "data": [
          {
            "id": "aaa",
            "name": "bbb"
          },
          {
            "id": "ccc",
            "name": "ddd"
          },
          ...
          ...
        ],
        "summary": {
          "total_count": 56,
          "can_like": true,
          "has_liked": false
        }
      }
</code>```

It's the "data" attribute I'd like to suppress coming back due to it (and the same for comments and other fields I'd like to turn off) substantially increasing the bandwidth of data received.

答:
It's the "data" attribute I'd like to suppress coming back due to it (and the same for comments and other fields I'd like to turn off) substantially increasing the bandwidth of data received.

Specify a limit of 0, then you will just get an empty data structure:

```<code>me/posts?fields=likes.summary(true).limit(0)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For example, I wish to get the like count for each post without getting name and Id details of each like.

The likes attribute returned for a call to me/posts?fields=likes.summary(true) would be:

      "likes": {
        "data": [
          {
            "id": "aaa",
            "name": "bbb"
          },
          {
            "id": "ccc",
            "name": "ddd"
          },
          ...
          ...
        ],
        "summary": {
          "total_count": 56,
          "can_like": true,
          "has_liked": false
        }
      }

It's the "data" attribute I'd like to suppress coming back due to it (and the same for comments and other fields I'd like to turn off) substantially increasing the bandwidth of data received.

Body:
It's the "data" attribute I'd like to suppress coming back due to it (and the same for comments and other fields I'd like to turn off) substantially increasing the bandwidth of data received.

Specify a limit of 0, then you will just get an empty data structure:

me/posts?fields=likes.summary(true).limit(0)


问:
Mapping users to all of their files(URLs) in a mysql database.
What I want is that when I have looked up a user in a table, I want to list all the file urls that the user have access to. My first thought was to have a field in the table with a list of file URLs. However, I have now understood that there are no such field type.

I was then thinking that maybe ForeignKeys might work, but I am having trouble getting my head around it.

Another solution maybe is to have one table for each user, with each row representing each file.

What would you say is best practice in this case?
I am also going to expand into having shared files, but thought that I'd address this issue first.

答: 2 tables: user and user_uri_permission? 2 columns in the second: userID and URI. When the User-URI pair is in the table the use has access.</p>


问:
Unity DI with MVC 5 in controllers
I'm currently having issues when trying to make a dependency injection inside a MVC controller.

The current exception is the following:

The current type, myproject.Core.ToolbarLogic, is an interface and
  cannot be constructed. Are you missing a type mapping?

Debugging I realized this exception is raised from this sentence (included in a Razor view):

```<code>@{ Html.RenderAction("Toolbar", "Toolbar");  }
</code>```

In the UnityConfig file, all types are registered conveniently,
I have an empty constructor in the controller,
the exception is raised from a place I cannot access debugging... Also I have read lots of answers here in StackOverflow and Google, I don't know what to try now (I have tried nearly everything).

Anyone knows what is the problem with the DI?

Code:

ToolbarController.cs

```<code>public class ToolbarController : BaseController
{

    [Dependency]
    public IToolbarLogic ToolbarLogic { get; set; }

    public ToolbarController()
    {
    }

    // GET: Common/Toolbar
    public ActionResult Toolbar()
    {
        bool ShowConfidential = ToolbarLogic.ShowConfidential();
        string linkHome = ToolbarLogic.BindHome(base.User.Identity.Name);
        return PartialView(new ToolbarModel() {
            ShowConfidential = ShowConfidential,
            lnkHome = linkHome
        });
        return PartialView();
    }

}
</code>```

UnityWebActivator.cs

```<code>/// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary>
public static class UnityWebActivator
{
    /// <summary>Integrates Unity when the application starts.</summary>
    public static void Start()
    {
        var container = UnityConfig.GetConfiguredContainer();

        FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
        FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        // TODO: Uncomment if you want to use PerRequestLifetimeManager
        // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
    }

    /// <summary>Disposes the Unity container when the application is shut down.</summary>
    public static void Shutdown()
    {
        var container = UnityConfig.GetConfiguredContainer();
        container.Dispose();
    }
}
</code>```

UnityConfig.cs

```<code>    /// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public class UnityConfig
{
    #region Unity Container
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    /// <summary>
    /// Gets the configured Unity container.
    /// </summary>
    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }
    #endregion

    /// <summary>Registers the type mappings with the Unity container.</summary>
    /// <param name="container">The unity container to configure.</param>
    /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
    /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
    public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<IToolbarLogic, ToolbarLogic>();

        // There is an Unity.config file
        container.LoadConfiguration();
    }
}
</code>```

Unity.config

```<code><?xml version="1.0"?>
<!-- Configuración de Unity -->
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <container>

  </container>
</unity>
</code>```

Edit 1:

I have commented the LoadConfiguration line as @Nkosi said, because it makes sense since I don't have any relevant information in my Unity.config (see above, it's empty).

The error stils the same:

```<code>Resolution of the dependency failed, type = "MVCControls.Controllers.ToolbarController", name = "(none)".
Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, interfaces_logic.Interfaces.IToolbarLogic, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:

  Resolving MVCControls.Controllers.ToolbarController,(none)
  Resolving value for property ToolbarController.ToolbarLogic
  Resolving interfaces_logic.Interfaces.IToolbarLogic,(none)
</code>```

答:
you can try this</p>

```<code>public class ToolbarControllerContext
{
    [Dependency]
    public IToolbarLogic ToolbarLogic { get; set; }
}

public class ToolbarController : BaseController
{
    private readonly IToolbarLogic _toolbarLogic;

    public ToolbarController(ToolbarControllerContext context)
    {
        _toolbarLogic = context.ToolbarLogic;
    }

    // GET: Common/Toolbar
    public ActionResult Toolbar()
    {
        bool ShowConfidential = _toolbarLogic.ShowConfidential();
        string linkHome = _toolbarLogic.BindHome(base.User.Identity.Name);
        return PartialView(new ToolbarModel() {
            ShowConfidential = ShowConfidential,
            lnkHome = linkHome
        });
        return PartialView();
    }
}
</code>```

Title: Unity DI with MVC 5 in controllers

Body:
I'm currently having issues when trying to make a dependency injection inside a MVC controller.

The current exception is the following:

The current type, myproject.Core.ToolbarLogic, is an interface and
  cannot be constructed. Are you missing a type mapping?

Debugging I realized this exception is raised from this sentence (included in a Razor view):

@{ Html.RenderAction("Toolbar", "Toolbar");  }

In the UnityConfig file, all types are registered conveniently,
I have an empty constructor in the controller,
the exception is raised from a place I cannot access debugging... Also I have read lots of answers here in StackOverflow and Google, I don't know what to try now (I have tried nearly everything).

Anyone knows what is the problem with the DI?

Code:

ToolbarController.cs

public class ToolbarController : BaseController
{

    [Dependency]
    public IToolbarLogic ToolbarLogic { get; set; }

    public ToolbarController()
    {
    }

    // GET: Common/Toolbar
    public ActionResult Toolbar()
    {
        bool ShowConfidential = ToolbarLogic.ShowConfidential();
        string linkHome = ToolbarLogic.BindHome(base.User.Identity.Name);
        return PartialView(new ToolbarModel() {
            ShowConfidential = ShowConfidential,
            lnkHome = linkHome
        });
        return PartialView();
    }

}

UnityWebActivator.cs

/// Provides the bootstrapping for integrating Unity with ASP.NET MVC.
public static class UnityWebActivator
{
    /// Integrates Unity when the application starts.
    public static void Start()
    {
        var container = UnityConfig.GetConfiguredContainer();

        FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
        FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        // TODO: Uncomment if you want to use PerRequestLifetimeManager
        // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
    }

    /// Disposes the Unity container when the application is shut down.
    public static void Shutdown()
    {
        var container = UnityConfig.GetConfiguredContainer();
        container.Dispose();
    }
}

UnityConfig.cs

    ///
/// Specifies the Unity configuration for the main container.
///
public class UnityConfig
{
    #region Unity Container
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    ///
    /// Gets the configured Unity container.
    ///
    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }
    #endregion

    /// Registers the type mappings with the Unity container.
    /// <param name="container">The unity container to configure.</param>
    /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
    /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
    public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<IToolbarLogic, ToolbarLogic>();

        // There is an Unity.config file
        container.LoadConfiguration();
    }
}

Unity.config

<?xml version="1.0"?>

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <container>

  </container>
</unity>

Edit 1:

I have commented the LoadConfiguration line as @Nkosi said, because it makes sense since I don't have any relevant information in my Unity.config (see above, it's empty).

The error stils the same:

Resolution of the dependency failed, type = "MVCControls.Controllers.ToolbarController", name = "(none)".
Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, interfaces_logic.Interfaces.IToolbarLogic, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:

  Resolving MVCControls.Controllers.ToolbarController,(none)
  Resolving value for property ToolbarController.ToolbarLogic
  Resolving interfaces_logic.Interfaces.IToolbarLogic,(none)

Body:
you can try this

public class ToolbarControllerContext
{
    [Dependency]
    public IToolbarLogic ToolbarLogic { get; set; }
}

public class ToolbarController : BaseController
{
    private readonly IToolbarLogic _toolbarLogic;

    public ToolbarController(ToolbarControllerContext context)
    {
        _toolbarLogic = context.ToolbarLogic;
    }

    // GET: Common/Toolbar
    public ActionResult Toolbar()
    {
        bool ShowConfidential = _toolbarLogic.ShowConfidential();
        string linkHome = _toolbarLogic.BindHome(base.User.Identity.Name);
        return PartialView(new ToolbarModel() {
            ShowConfidential = ShowConfidential,
            lnkHome = linkHome
        });
        return PartialView();
    }
}


问:
Rendering a partial with a new layout
I am trying to render a partial using an if statement and this renders alternate content. If I wanted to do this and render the content itself using a different layout (one without a header and footer for example), is this possible?

```<code><%= render partial: "partialname", layout: "layouts/blank" %>
</code>```

I've looked around and tried doing this in the view, but get an error which states

```<code>'Missing partial layouts/_blank'
</code>```

Am I missing something? The layout isn't a partial, so unsure why it's using an underscore.

Am I better off doing this in the controller?

答:
Try</p>

```<code><%= render partial: "partialname", :layout => false %>
</code>```

Title: Rendering a partial with a new layout

Body:
I am trying to render a partial using an if statement and this renders alternate content. If I wanted to do this and render the content itself using a different layout (one without a header and footer for example), is this possible?

<%= render partial: "partialname", layout: "layouts/blank" %>

I've looked around and tried doing this in the view, but get an error which states

'Missing partial layouts/_blank'

Am I missing something? The layout isn't a partial, so unsure why it's using an underscore.

Am I better off doing this in the controller?

Body:
Try

<%= render partial: "partialname", :layout => false %>


问:
After re-starting device my locker application is not working on the Android marshmallow device
I am working on App locker application. If installed this
    application in kitkat version device application locking and its
    working perfect. In marshmallow|(6.0) version device initially
    application is working, if we restart the device app lock is not
    working, Locked applications are open without asking any password.
    If we just enter application (app Lock app) and exit from app its
    working perfect. That time it asks password.

```<code>public class StartupServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
        if (AppLockerPreference.getInstance(context).isAutoStart()){
            if (AppLockerPreference.getInstance(context).isServiceEnabled()){
                context.startService(new Intent(context, DetectorService.class));
            }else{
                AppLockerPreference.getInstance(context).saveServiceEnabled(false);
            }
        }
        return;
    }else if (AppLockerPreference.getInstance(context).isServiceEnabled()){
        context.startService(new Intent(context, DetectorService.class));
    }
}
}

public class AppLockerPreference implements OnSharedPreferenceChangeListener {
Context mContext;

public boolean isAutoStart() {
    Log.d("AMK","AppLockerPreference1--->"+mApplicationList.length);
    return mAutoStart;
}

public boolean isServiceEnabled() {
    Log.d("AMK","AppLockerPreference2--->"+mApplicationList.length);
    return mServiceEnabled;
}
public void saveServiceEnabled(boolean serviceEnabled) {
    mServiceEnabled = serviceEnabled;
    mPref.edit().putBoolean(PREF_SERVICE_ENABLED, mServiceEnabled);
}
public String[] getApplicationList() {

    Log.d("AMK","AppLockerPreference3--->"+mApplicationList.length);
    return mApplicationList;
}
public void saveApplicationList(String[] applicationList) {
    mApplicationList = applicationList;
    String combined = "";
    for (int i=0; i<mApplicationList.length; i++){
        combined = combined + mApplicationList[i] + ";";
    }
    mPref.edit().putString(PREF_APPLICATION_LIST, combined).commit();
}

private static final String PREF_SERVICE_ENABLED = "service_enabled";
private static final String PREF_APPLICATION_LIST = "application_list";
private static final String PREF_AUTO_START = "start_service_after_boot";
private static final String PREF_PASSWORD = "password";

/**
 * Section for singleton pattern
 */
private SharedPreferences mPref;
private AppLockerPreference(Context context) {
    mPref = PreferenceManager.getDefaultSharedPreferences(context);
    mPref.registerOnSharedPreferenceChangeListener(this);
    reloadPreferences();
}
private void reloadPreferences() {
    mServiceEnabled = mPref.getBoolean(PREF_SERVICE_ENABLED, true);

    mApplicationList = mPref.getString(PREF_APPLICATION_LIST, "").split(";");

    Log.d("AMK","selectd apps--->"+mApplicationList);

    mAutoStart = mPref.getBoolean(PREF_AUTO_START, true);
    mPassword = mPref.getString(PREF_PASSWORD, "2468");
    if (mPref.getBoolean("relock_policy", true)){
        try{
            mRelockTimeout = Integer.parseInt(mPref.getString("relock_timeout", "-1"));
        }catch(Exception e){
            mRelockTimeout = -1;
        }
    }else{
        mRelockTimeout = -1;
    }
}

private static AppLockerPreference mInstance;
public static AppLockerPreference getInstance(Context context){
    return mInstance == null ?
            (mInstance = new AppLockerPreference(context)) :
                mInstance;
}

private boolean mServiceEnabled, mAutoStart;
private String[] mApplicationList;
private String mPassword;
private int mRelockTimeout;

public int getRelockTimeout(){
    return mRelockTimeout;
}

public String getPassword() {
    return mPassword;
}
public void savePassword(String password) {
    mPassword = password;
    mPref.edit().putString(PREF_PASSWORD, password);
}

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
        String key) {
    reloadPreferences();
}
}
</code>```

Could you please help me.

答:
check if the device is marshmallow and give permissions</p>

```<code>if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.MARSHMALLOW) {
     // only for marshmallow and newer versions
}
</code>```

Body:
I am working on App locker application. If installed this
    application in kitkat version device application locking and its
    working perfect. In marshmallow|(6.0) version device initially
    application is working, if we restart the device app lock is not
    working, Locked applications are open without asking any password.
    If we just enter application (app Lock app) and exit from app its
    working perfect. That time it asks password.

public class StartupServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
        if (AppLockerPreference.getInstance(context).isAutoStart()){
            if (AppLockerPreference.getInstance(context).isServiceEnabled()){
                context.startService(new Intent(context, DetectorService.class));
            }else{
                AppLockerPreference.getInstance(context).saveServiceEnabled(false);
            }
        }
        return;
    }else if (AppLockerPreference.getInstance(context).isServiceEnabled()){
        context.startService(new Intent(context, DetectorService.class));
    }
}
}

public class AppLockerPreference implements OnSharedPreferenceChangeListener {
Context mContext;

public boolean isAutoStart() {
    Log.d("AMK","AppLockerPreference1--->"+mApplicationList.length);
    return mAutoStart;
}

public boolean isServiceEnabled() {
    Log.d("AMK","AppLockerPreference2--->"+mApplicationList.length);
    return mServiceEnabled;
}
public void saveServiceEnabled(boolean serviceEnabled) {
    mServiceEnabled = serviceEnabled;
    mPref.edit().putBoolean(PREF_SERVICE_ENABLED, mServiceEnabled);
}
public String[] getApplicationList() {

    Log.d("AMK","AppLockerPreference3--->"+mApplicationList.length);
    return mApplicationList;
}
public void saveApplicationList(String[] applicationList) {
    mApplicationList = applicationList;
    String combined = "";
    for (int i=0; i<mApplicationList.length; i++){
        combined = combined + mApplicationList[i] + ";";
    }
    mPref.edit().putString(PREF_APPLICATION_LIST, combined).commit();
}

private static final String PREF_SERVICE_ENABLED = "service_enabled";
private static final String PREF_APPLICATION_LIST = "application_list";
private static final String PREF_AUTO_START = "start_service_after_boot";
private static final String PREF_PASSWORD = "password";

/**
 * Section for singleton pattern
 */
private SharedPreferences mPref;
private AppLockerPreference(Context context) {
    mPref = PreferenceManager.getDefaultSharedPreferences(context);
    mPref.registerOnSharedPreferenceChangeListener(this);
    reloadPreferences();
}
private void reloadPreferences() {
    mServiceEnabled = mPref.getBoolean(PREF_SERVICE_ENABLED, true);

    mApplicationList = mPref.getString(PREF_APPLICATION_LIST, "").split(";");

    Log.d("AMK","selectd apps--->"+mApplicationList);

    mAutoStart = mPref.getBoolean(PREF_AUTO_START, true);
    mPassword = mPref.getString(PREF_PASSWORD, "2468");
    if (mPref.getBoolean("relock_policy", true)){
        try{
            mRelockTimeout = Integer.parseInt(mPref.getString("relock_timeout", "-1"));
        }catch(Exception e){
            mRelockTimeout = -1;
        }
    }else{
        mRelockTimeout = -1;
    }
}

private static AppLockerPreference mInstance;
public static AppLockerPreference getInstance(Context context){
    return mInstance == null ?
            (mInstance = new AppLockerPreference(context)) :
                mInstance;
}

private boolean mServiceEnabled, mAutoStart;
private String[] mApplicationList;
private String mPassword;
private int mRelockTimeout;

public int getRelockTimeout(){
    return mRelockTimeout;
}

public String getPassword() {
    return mPassword;
}
public void savePassword(String password) {
    mPassword = password;
    mPref.edit().putString(PREF_PASSWORD, password);
}

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
        String key) {
    reloadPreferences();
}
}

Could you please help me.

Body:
check if the device is marshmallow and give permissions

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.MARSHMALLOW) {
     // only for marshmallow and newer versions
}


问:
How to add/remove a fieldset when click on button
I'm programming in Angular2/Typescript and for the add form, I need to add the possibility to add/remove a fieldset in which the input are linked to a ViewModel. So basically, I have a principal ViewModel which comprises a table of the secondary ViewModel (fieldset). I tried different things, but I'm new in Angular so I'm probably missing important things.

Here is the code of my HTML code :

                    Customer :
                    <select class="form-control" required ngControl="viewModel.selectedCustomerStr"
                            [(ngModel)]="viewModel.selectedCustomerStr">
                        <option value=""></option>
                        <option *ngFor="#customer of viewModel.customersListStr" [value]="customer">{{customer}}</option>
                    </select>

                    Service provided:
                    <select class="form-control" required ngControl="viewModel.serviceProvidedStr"
                            [(ngModel)]="viewModel.serviceProvidedStr">
                        <option value=null></option>
                        <option *ngFor="#service of viewModel.servicesListStr" [value]="service">{{service}}</option>
                    </select>

                    Service window :
                    <select class="form-control" required ngControl="viewModel.selectedServiceWindowStr"
                        [(ngModel)]="viewModel.selectedServiceWindowStr">
                        <option value=null></option>
                        <option *ngFor="#window of serviceWindowListStr" [value]="window">{{window}}</option>
                    </select>

                <fieldset *ngFor="#choice of choices">
                    <legend>DRP contact information</legend>

                        DRP contact name:
                        <input placeholder="Contact's Name" type="text" maxlenght=50 [(ngModel)]="viewModel.contactName"
                            class="form-control" required ngControl="name" #name="ngForm">

                        Start time:
                        <input class="form-control" ngControl="timeStart" required type="time"
                           [(ngModel)]="viewModel.timeStart">

                        End time:
                        <input class="form-control" ngControl="timeEnd" required type="time"
                           [(ngModel)]="viewModel.timeEnd">

                        Medium:
                        <select class="form-control" required [(ngModel)]="viewModel.selectedMediumStr" ngControl="viewModel.selectedMediumStr"
                            #medium="ngForm">
                        <option value=""></option>
                        <option *ngFor="#medium of viewModel.mediumsListStr" [value]="medium">{{medium}}</option>
                    </select>

                        DRP contact address:
                        <input placeholder="Contact's address" type="text" maxlenght=100 [(ngModel)]="viewModel.value"
                            class="form-control" required ngControl="value" #value="ngForm">

                    <button class="remove" (click)="onRemoveFieldset()">Remove</button>
                </fieldset>

                <button class="add" (click)="onAddFieldset()">Add a contact</button>

```
</div>
</div>
</p>

<p>Do I need to change the ngModel for every input in the fieldset to match the table cell ?</p>

<p>Next is the Typescript code :</p>

<pre class="lang-js prettyprint-override"><code>export class AddDrpsComponent extends BaseComponent implements OnInit {
    viewModel:DrpDetailViewModel = new DrpDetailViewModel();
    tabDrpContact:DrpContactDetailViewModel[];
    serviceWindowListStr:String[];

    onAddFieldset() {
        let newItemNo = this.tabDrpContact.length +1;
        this.tabDrpContact.push(new DrpContactDetailViewModel(newItemNo));
    }

    onRemoveFieldset(id:number) {
        this.tabDrpContact.splice(id,1);
    }
}
</code>```

For the moment, it's just a basic add and remove who do nothing behind.

Picture of the add form

I hope to have been clear, English is not my mother tongue.

Cordially,

Florian

Edit : Up

EDIT 2 : Here is my two ViewModel

import {DrpContact} from "./drp-contact";

export interface Drp {
    id:number;
    serviceWindow:string;
    status:string;
    customer:string;
    serviceProvidedType:string;
    drpContactList:DrpContact[];
}
```

<p>//////////////////////////////////////////////</p>

```export interface DrpContact {
    id:number;
    name:string;
    timeStart:string;
    timeEnd:string;
    value:string;
    mediumType:string;
}
```

<pre class="lang-js prettyprint-override"><code>import {SelectOptionElement} from "../../shared/model/select-option-element";
import {Serializable} from "../../shared/technical/serializable";
import {DrpContactDetailViewModel} from "./drp-contact-detail-view-model";

export class DrpDetailViewModel extends Serializable {
    id:number;

    selectedCustomer:SelectOptionElement;
    selectedCustomerStr:string;
    serviceProvided:SelectOptionElement;
    serviceProvidedStr:string;
    selectedServiceWindow:SelectOptionElement;
    selectedServiceWindowStr:string;
    status:string;
    drpContactDetailList:DrpContactDetailViewModel[];

    customer:SelectOptionElement[];
    customersListStr:String[];
    service:SelectOptionElement[];
    servicesListStr:String[];
    window:SelectOptionElement[];
}

/////////////////////

import {SelectOptionElement} from "../../shared/model/select-option-element";
import {Serializable} from "../../shared/technical/serializable";

export class DrpContactDetailViewModel extends Serializable {
    id:number;
    contactName:string;
    timeStart:string;
    timeEnd:string;
    selectedMedium:SelectOptionElement;
    selectedMediumStr:string;
    value:string;

    medium:SelectOptionElement[];
    mediumsListStr:String[];
}
</code>```

答:
You can just use ngFor's index to remove the correct fieldset :

In your template :

```<code><fieldset *ngFor="#choice of choices; let id = index">
  //Code ...
  <button class="remove" (click)="onRemoveFieldset(id)">Remove</button>
</fieldset>
</code>```

In your component :

```<code>onAddFieldset() {
    let newItemNo = this.choices.length +1;
    this.choices.push(new DrpDetailViewModel(newItemNo));
}

onRemoveFieldset(id:number) {
    this.choices.splice(id,1);
}
</code>```

This assumes you have a constructor that matches DrpDetailViewModel(id)

```<code>class DrpContactDetailViewModel extends Serializable {
  id:number;
  contactName:string;
  timeStart:string;
  timeEnd:string;
  selectedMedium:SelectOptionElement;
  selectedMediumStr:string;
  value:string;

  medium:SelectOptionElement[];
  mediumsListStr:String[];

  constructor(id : number) { this.id = id }
}
</code>```

Body:
I'm programming in Angular2/Typescript and for the add form, I need to add the possibility to add/remove a fieldset in which the input are linked to a ViewModel. So basically, I have a principal ViewModel which comprises a table of the secondary ViewModel (fieldset). I tried different things, but I'm new in Angular so I'm probably missing important things.

Here is the code of my HTML code :

                    Customer :
                    <select class="form-control" required ngControl="viewModel.selectedCustomerStr"
                            [(ngModel)]="viewModel.selectedCustomerStr">
                        <option value=""></option>
                        <option *ngFor="#customer of viewModel.customersListStr" [value]="customer">{{customer}}</option>
                    </select>

                    Service provided:
                    <select class="form-control" required ngControl="viewModel.serviceProvidedStr"
                            [(ngModel)]="viewModel.serviceProvidedStr">
                        <option value=null></option>
                        <option *ngFor="#service of viewModel.servicesListStr" [value]="service">{{service}}</option>
                    </select>

                    Service window :
                    <select class="form-control" required ngControl="viewModel.selectedServiceWindowStr"
                        [(ngModel)]="viewModel.selectedServiceWindowStr">
                        <option value=null></option>
                        <option *ngFor="#window of serviceWindowListStr" [value]="window">{{window}}</option>
                    </select>

                <fieldset *ngFor="#choice of choices">
                    <legend>DRP contact information</legend>

                        DRP contact name:
                        <input placeholder="Contact's Name" type="text" maxlenght=50 [(ngModel)]="viewModel.contactName"
                            class="form-control" required ngControl="name" #name="ngForm">

                        Start time:
                        <input class="form-control" ngControl="timeStart" required type="time"
                           [(ngModel)]="viewModel.timeStart">

                        End time:
                        <input class="form-control" ngControl="timeEnd" required type="time"
                           [(ngModel)]="viewModel.timeEnd">

                        Medium:
                        <select class="form-control" required [(ngModel)]="viewModel.selectedMediumStr" ngControl="viewModel.selectedMediumStr"
                            #medium="ngForm">
                        <option value=""></option>
                        <option *ngFor="#medium of viewModel.mediumsListStr" [value]="medium">{{medium}}</option>
                    </select>

                        DRP contact address:
                        <input placeholder="Contact's address" type="text" maxlenght=100 [(ngModel)]="viewModel.value"
                            class="form-control" required ngControl="value" #value="ngForm">

                    <button class="remove" (click)="onRemoveFieldset()">Remove</button>
                </fieldset>

                <button class="add" (click)="onAddFieldset()">Add a contact</button>

Do I need to change the ngModel for every input in the fieldset to match the table cell ?

Next is the Typescript code :

export class AddDrpsComponent extends BaseComponent implements OnInit {
    viewModel:DrpDetailViewModel = new DrpDetailViewModel();
    tabDrpContact:DrpContactDetailViewModel[];
    serviceWindowListStr:String[];

    onAddFieldset() {
        let newItemNo = this.tabDrpContact.length +1;
        this.tabDrpContact.push(new DrpContactDetailViewModel(newItemNo));
    }

    onRemoveFieldset(id:number) {
        this.tabDrpContact.splice(id,1);
    }
}

For the moment, it's just a basic add and remove who do nothing behind.

Picture of the add form

I hope to have been clear, English is not my mother tongue.

Cordially,

Florian

Edit : Up

EDIT 2 : Here is my two ViewModel

import {DrpContact} from "./drp-contact";

export interface Drp {
    id:number;
    serviceWindow:string;
    status:string;
    customer:string;
    serviceProvidedType:string;
    drpContactList:DrpContact[];
}

//////////////////////////////////////////////

export interface DrpContact {
    id:number;
    name:string;
    timeStart:string;
    timeEnd:string;
    value:string;
    mediumType:string;
}

import {SelectOptionElement} from "../../shared/model/select-option-element";
import {Serializable} from "../../shared/technical/serializable";
import {DrpContactDetailViewModel} from "./drp-contact-detail-view-model";

export class DrpDetailViewModel extends Serializable {
    id:number;

    selectedCustomer:SelectOptionElement;
    selectedCustomerStr:string;
    serviceProvided:SelectOptionElement;
    serviceProvidedStr:string;
    selectedServiceWindow:SelectOptionElement;
    selectedServiceWindowStr:string;
    status:string;
    drpContactDetailList:DrpContactDetailViewModel[];

    customer:SelectOptionElement[];
    customersListStr:String[];
    service:SelectOptionElement[];
    servicesListStr:String[];
    window:SelectOptionElement[];
}

/////////////////////

import {SelectOptionElement} from "../../shared/model/select-option-element";
import {Serializable} from "../../shared/technical/serializable";

export class DrpContactDetailViewModel extends Serializable {
    id:number;
    contactName:string;
    timeStart:string;
    timeEnd:string;
    selectedMedium:SelectOptionElement;
    selectedMediumStr:string;
    value:string;

    medium:SelectOptionElement[];
    mediumsListStr:String[];
}

Body:
You can just use ngFor's index to remove the correct fieldset :

In your template :

<fieldset *ngFor="#choice of choices; let id = index">
  //Code ...
  <button class="remove" (click)="onRemoveFieldset(id)">Remove</button>
</fieldset>

In your component :

onAddFieldset() {
    let newItemNo = this.choices.length +1;
    this.choices.push(new DrpDetailViewModel(newItemNo));
}

onRemoveFieldset(id:number) {
    this.choices.splice(id,1);
}

This assumes you have a constructor that matches DrpDetailViewModel(id)

class DrpContactDetailViewModel extends Serializable {
  id:number;
  contactName:string;
  timeStart:string;
  timeEnd:string;
  selectedMedium:SelectOptionElement;
  selectedMediumStr:string;
  value:string;

  medium:SelectOptionElement[];
  mediumsListStr:String[];

  constructor(id : number) { this.id = id }
}


问:
Using browser back button to remove modal
http://morningharwood.com/works clicking on the project button in lower right corner brings up a very basic modal.  When testing on I noticed that the back button does not remove the modal.  How do I make sure that the browser back button will remove the modal window?

Heres the full Gist

```<code>enter = $(".enter")
createModal = () ->
  $(".modal-bg").removeClass("animated fadeInUpBig").addClass "on animated fadeInUpBig"

$(enter).on "click", (event) ->
  createModal()
</code>```

HTML

```<code><a class="enter" href="#">View Project<span></span></a>
</code>```

SCSS

```<code>  modal-bg{
    background:#fff;
    position:absolute;
    bottom:0;
    left:0;
    right:0;
    z-index: 101;
    display:none;
    visibility:hidden;
    height:1px;

    &.on
        {
            display: block !important;
            visibility: visible !important;
            height:100%;
            top:0;
        }
}
</code>```

答:
//close modals with back btn
$('.modal').on('show.bs.modal', function (e) {
    window.history.pushState('forward', null, '#modal');
});

$('.modal').on('hide.bs.modal', function (e) {
    //pop the forward state to go back to original state before pushing the "Modal!" button
});

$(window).on('popstate', function () {
    $('.modal').modal('hide');
});```

This works. ^_^

Body:
http://morningharwood.com/works clicking on the project button in lower right corner brings up a very basic modal.  When testing on I noticed that the back button does not remove the modal.  How do I make sure that the browser back button will remove the modal window?

Heres the full Gist

enter = $(".enter")
createModal = () ->
  $(".modal-bg").removeClass("animated fadeInUpBig").addClass "on animated fadeInUpBig"

$(enter).on "click", (event) ->
  createModal()

HTML

View Project

SCSS

  modal-bg{
    background:#fff;
    position:absolute;
    bottom:0;
    left:0;
    right:0;
    z-index: 101;
    display:none;
    visibility:hidden;
    height:1px;

    &.on
        {
            display: block !important;
            visibility: visible !important;
            height:100%;
            top:0;
        }
}

Body:
//close modals with back btn
$('.modal').on('show.bs.modal', function (e) {
    window.history.pushState('forward', null, '#modal');
});

$('.modal').on('hide.bs.modal', function (e) {
    //pop the forward state to go back to original state before pushing the "Modal!" button
});

$(window).on('popstate', function () {
    $('.modal').modal('hide');
});

This works. ^_^


问:
Why is it "impossible" to implement garbage collection in C because of weak typing?
I was told by a rather smart person that you cannot implement garbage collection in C because of it's weakly typed. The basic idea seems to be that C gives you too much freedom. He mentioned casting pointers without type checking...

I don't really grok the idea. Can someone give me an explanation and possibly a code sample of why this wouldn't work.

NOTE: Obviously C is about speed and why would you want to add garbage collection? I'm just curious really.

答:
It's not impossible to implement a garbage collector for C (and in fact, they do exist, as a simple google search reveals), it's just difficult, because it can be difficult to determine if a certain string of bits is a pointer into an allocated block or just looks like one.

The reason this is an issue is because C (and C++, for that matter) allows you to cast from a pointer type to an integral type, so an integer variable might hold an address within an allocated block, preventing the GC from freeing that block, even though that value wasn't intended to be a pointer.

For example, let's say I have a block of memory allocated.  Let's suppose this block of memory is allocated starting at address 0x00100000 (1,048,576), and is 1 MB long, so extends to 0x001FFFFF (2,097,151).

Let's say I also am storing the size of an image file in a variable (let's call it fileSize).  This image file happens to be 1.5 MB (1,572,864 bytes).

So when the garbage collector runs, it will come across my fileSize variable, find it containing a value that corresponds to an address within my allocated block, and decide that it cannot free this block, lest it invalidate my maybe pointer.  That's because the GC doesn't know if I've done this:

```<code>int fileSize;
{
    char *mem = (char*)malloc(1048576);
    fileSize = (int)(mem + 524288);
}
// say GC runs here
</code>```

or if I've just done this:

```<code>int fileSize;
{
    char *mem = (char*)malloc(1048576);
    fileSize = 1572864;
}
// say GC runs here;
</code>```

In the latter case, it is safe to free the block at *mem, (if no other references exist), whereas in the former, it's not.  It must be conservative and assume that it's not, so the memory "leaks" (at least until fileSize goes out of scope or is changed to a value outside the allocated block).

But garbage collectors for C (and C++) do exist.  Whether or not they are valuable is a matter for a different discussion.

OwnerDisplayName: Tim Merrifield

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Norman Ramsey

Body:
It's not impossible to implement a garbage collector for C (and in fact, they do exist, as a simple google search reveals), it's just difficult, because it can be difficult to determine if a certain string of bits is a pointer into an allocated block or just looks like one.

The reason this is an issue is because C (and C++, for that matter) allows you to cast from a pointer type to an integral type, so an integer variable might hold an address within an allocated block, preventing the GC from freeing that block, even though that value wasn't intended to be a pointer.

For example, let's say I have a block of memory allocated.  Let's suppose this block of memory is allocated starting at address 0x00100000 (1,048,576), and is 1 MB long, so extends to 0x001FFFFF (2,097,151).

Let's say I also am storing the size of an image file in a variable (let's call it fileSize).  This image file happens to be 1.5 MB (1,572,864 bytes).

So when the garbage collector runs, it will come across my fileSize variable, find it containing a value that corresponds to an address within my allocated block, and decide that it cannot free this block, lest it invalidate my maybe pointer.  That's because the GC doesn't know if I've done this:

int fileSize;
{
    char *mem = (char*)malloc(1048576);
    fileSize = (int)(mem + 524288);
}
// say GC runs here

or if I've just done this:

int fileSize;
{
    char *mem = (char*)malloc(1048576);
    fileSize = 1572864;
}
// say GC runs here;

In the latter case, it is safe to free the block at *mem, (if no other references exist), whereas in the former, it's not.  It must be conservative and assume that it's not, so the memory "leaks" (at least until fileSize goes out of scope or is changed to a value outside the allocated block).

But garbage collectors for C (and C++) do exist.  Whether or not they are valuable is a matter for a different discussion.

OwnerDisplayName: P Daddy


问:
Compare 2 strings in Java upto a delimiter
String 1:

```<code>func1(test1)
</code>```

String 2:

```<code>func1(test2)
</code>```

I want to compare these 2 strings upto the first open braces '('.

So for the given example it should return true since the string upto '(' in both the strings is 'func1'.

Is there any way to do that without splitting?

答:
You can use String.matches() method to test if the second string matches the splitted one from the first string:

```<code>String s1 = "func1(test1)";
String s2 = "func1(test2)";
String methName = s1.substring(0, s1.indexOf("("));
System.out.println(s2.matches(methName+ "(.*)"));
</code>```

This is a working Demo.

Body:
String 1:

func1(test1)

String 2:

func1(test2)

I want to compare these 2 strings upto the first open braces '('.

So for the given example it should return true since the string upto '(' in both the strings is 'func1'.

Is there any way to do that without splitting?

Body:
You can use String.matches() method to test if the second string matches the splitted one from the first string:

String s1 = "func1(test1)";
String s2 = "func1(test2)";
String methName = s1.substring(0, s1.indexOf("("));
System.out.println(s2.matches(methName+ "(.*)"));

This is a working Demo.


问:
koa-static going to next middleware
I have a koa 2 server.

The following code are my middlewares:

```<code>// parse body
app.use( bodyParser() )

// serve static
app.use( serve( path.join(__dirname, '/public') ) )

// routes
app.use( routes )

// error middleware
app.use( async ctx => ctx.throw(500) )
</code>```

Everything works well but my problem is that when I go to localhost:8000, where my server lives, in the console I see the following error:

InternalServerError: Internal Server Error
        at Object.throw (/Users/work/Desktop/server/node_modules/koa/lib/context.js:91:23)

I'm suspecting that after static, the app is going to the next middleware, which is the error middleware.

PS. I'm using app.use( async ctx => ctx.throw(500) ), to call next() if I'm getting errors on the other routes.

Does anyone know how to fix this?

Thanks!

答:
I'm suspecting that after static, the app is going to the next
  middleware, which is the error middleware.

koa-static transfers control to the next middleware by design.
Your routes middleware also await to the next middleware.
So you get an error.

Does anyone know how to fix this?

It's hard to say what you are going to achieve in the first place.
Setting 500 manually is probably a wrong idea. There should be 404 like:

```<code>// 404 middleware
app.use(async ({response}, next) => {
  if (!this.body) {
    response.status = 404
    response.body = "Not Found" // or use template
  }
  await next() // send control flow back (upstream)
})
</code>```

For SPA (without SSR) you probably want this catch-all route to send APP layout instead. And move that 404 middleware to the beginning of the file (where it will take control on the second "bubbling" phase.

Make sure you checked this

Title: koa-static going to next middleware

Body:
I have a koa 2 server.

The following code are my middlewares:

// parse body
app.use( bodyParser() )

// serve static
app.use( serve( path.join(__dirname, '/public') ) )

// routes
app.use( routes )

// error middleware
app.use( async ctx => ctx.throw(500) )

Everything works well but my problem is that when I go to localhost:8000, where my server lives, in the console I see the following error:

InternalServerError: Internal Server Error
        at Object.throw (/Users/work/Desktop/server/node_modules/koa/lib/context.js:91:23)

I'm suspecting that after static, the app is going to the next middleware, which is the error middleware.

PS. I'm using app.use( async ctx => ctx.throw(500) ), to call next() if I'm getting errors on the other routes.

Does anyone know how to fix this?

Thanks!

Body:
I'm suspecting that after static, the app is going to the next
  middleware, which is the error middleware.

koa-static transfers control to the next middleware by design.
Your routes middleware also await to the next middleware.
So you get an error.

Does anyone know how to fix this?

It's hard to say what you are going to achieve in the first place.
Setting 500 manually is probably a wrong idea. There should be 404 like:

// 404 middleware
app.use(async ({response}, next) => {
  if (!this.body) {
    response.status = 404
    response.body = "Not Found" // or use template
  }
  await next() // send control flow back (upstream)
})

For SPA (without SSR) you probably want this catch-all route to send APP layout instead. And move that 404 middleware to the beginning of the file (where it will take control on the second "bubbling" phase.

Make sure you checked this


问:
How to get data for the last week data?
I am trying to write a report whereby the report will have the contract updated records for the past week using ms sql script. Every Monday the report will be sent for the last Mon-sun. I tried the below query. it doesnt seems to work. Any idea how to achieve this?

```<code>SET DATEFIRST 1

select distinct [...]
where CONTRACT_UPDATE_DATE>= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND CONTRACT_UPDATE_DATE<  dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
</code>```

Thanks.

答:
You could try to achieve this by using the calender week.
Try the following:

```<code>-- Get last calendar week in format JJJJWW
DECLARE @jjjjkw varchar(6)
SELECT @jjjjkw =
CONVERT(varchar, DATEPART(YYYY,GETDATE()-7)) +
CASE WHEN LEN(CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7))) = 1 THEN '0'
+ CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7))
ELSE CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7)) END

-- Compare with the calendar week of your data-set
SELECT DISTINCT [...]
WHERE
CONVERT(varchar, DATEPART(YYYY,CONTRACT_UPDATE_DATE)) +
CASE WHEN LEN(CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE))) = 1
THEN '0' + CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE))
ELSE CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE)) END = @jjjjkw
</code>```

Maybe not the most elegant way but it should work.

Title: How to get data for the last week data?

Body:
I am trying to write a report whereby the report will have the contract updated records for the past week using ms sql script. Every Monday the report will be sent for the last Mon-sun. I tried the below query. it doesnt seems to work. Any idea how to achieve this?

SET DATEFIRST 1

select distinct [...]
where CONTRACT_UPDATE_DATE>= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND CONTRACT_UPDATE_DATE<  dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))

Thanks.

Body:
You could try to achieve this by using the calender week.
Try the following:

-- Get last calendar week in format JJJJWW
DECLARE @jjjjkw varchar(6)
SELECT @jjjjkw =
CONVERT(varchar, DATEPART(YYYY,GETDATE()-7)) +
CASE WHEN LEN(CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7))) = 1 THEN '0'
+ CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7))
ELSE CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7)) END

-- Compare with the calendar week of your data-set
SELECT DISTINCT [...]
WHERE
CONVERT(varchar, DATEPART(YYYY,CONTRACT_UPDATE_DATE)) +
CASE WHEN LEN(CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE))) = 1
THEN '0' + CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE))
ELSE CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE)) END = @jjjjkw

Maybe not the most elegant way but it should work.


问:
Hide navigation when at the top
Hello how can i hide my navigation when not scrolling and show it when i scroll

i am using two menus at this link http://dev.thegabrielmethod.com/gabriel/

one on a white bg and the other on a blue bg

i would like to hide the navigation menu items on the white bg when not scrolling and then show them again when scrolling

This is what am trying which is not working

```<code><script type='text/javascript'>//<![CDATA[
$(document).ready(function() {
        var headerTop = $('#header').offset().top;
        var headerBottom = headerTop + 120; // Sub-menu should appear after this distance from top.
        $(window).scroll(function () {
            var scrollTop = $(window).scrollTop(); // Current vertical scroll position from the top
            if (scrollTop > headerBottom) { // Check to see if we have scrolled more than headerBottom
                if (($("#navigation-alongside").is(":visible") === false)) {
                    $('#navigation-alongside').fadeIn('slow');
                }
            } else {
                if ($("#navigation-alongside").is(":visible")) {
                    $('#navigation-alongside').hide();
                }
            }
        });
    });

</script>
</code>```

Please some one advice

答:
One way to do it is as follows:

```<code>window.onscroll = function(e) {
    topMenu = document.querySelector('.banner.include-nav');
    scrollTopAmount = document.body.scrollTop;

    if (scrollTopAmount != 0) {
        topMenu.style.display = 'none';
    }
    else
        topMeny.style.display = 'block';
}
</code>```

Hope this helps

Title: Hide navigation when at the top

Body:
Hello how can i hide my navigation when not scrolling and show it when i scroll

i am using two menus at this link http://dev.thegabrielmethod.com/gabriel/

one on a white bg and the other on a blue bg

i would like to hide the navigation menu items on the white bg when not scrolling and then show them again when scrolling

This is what am trying which is not working

Please some one advice

Body:
One way to do it is as follows:

window.onscroll = function(e) {
    topMenu = document.querySelector('.banner.include-nav');
    scrollTopAmount = document.body.scrollTop;

    if (scrollTopAmount != 0) {
        topMenu.style.display = 'none';
    }
    else
        topMeny.style.display = 'block';
}

Hope this helps


答:
You can use regex to find every thing between any delimiters, in your case () and compare the results, for example :

```<code>String START_DEL = "\\(";   //the start delimiter
String END_DEL = "\\)";     //the end delimiter

String str1 = "func1(test1)";
String str2 = "func1(test2)";

Pattern p = Pattern.compile(START_DEL + "(.*?)" + END_DEL);//This mean "\\((.*?)\\)"
Matcher m1 = p.matcher(str1);
Matcher m2 = p.matcher(str2);

if (m1.find() && m2.find()) {
    System.out.println(m1.group(1).equals(m2.group(1)));
}
</code>```

Title: Compare 2 strings in Java upto a delimiter

Body:
You can use regex to find every thing between any delimiters, in your case () and compare the results, for example :

String START_DEL = "\\(";   //the start delimiter
String END_DEL = "\\)";     //the end delimiter

String str1 = "func1(test1)";
String str2 = "func1(test2)";

Pattern p = Pattern.compile(START_DEL + "(.*?)" + END_DEL);//This mean "\\((.*?)\\)"
Matcher m1 = p.matcher(str1);
Matcher m2 = p.matcher(str2);

if (m1.find() && m2.find()) {
    System.out.println(m1.group(1).equals(m2.group(1)));
}


问:
Array AND() ? Logical ANDing of all elements
I have an array and I want to find out if there is at least one false value in it. I was thinking of creating an array_and() function, that just performs a logical AND on all the elements. It would return true if all values are true, otherwise false. Am I over-engineering?

答:
Easy but ugly => O(N)

```<code>$a = array(1, 2, false, 5, 6, 'a');

$_there_is_a_false = false
foreach ($a as $b) {
    $_there_is_a_false = !$b ? true : $_there_is_a_false;
}
</code>```

another option: array-filter

Body:
Easy but ugly => O(N)

$a = array(1, 2, false, 5, 6, 'a');

$_there_is_a_false = false
foreach ($a as $b) {
    $_there_is_a_false = !$b ? true : $_there_is_a_false;
}

another option: array-filter


问:
Export div to pdf in js
I have two divs with ids: element1 and element2

In between these divs, there is a button. After these divs, there is one more button with id: pdf.

In the divs there is a table and input box.

      Enter your name: <input>

      Enter your class: <input>

    <button>Click on the button</button>

          Name
          Class

          <input>
          <input>

    <button id="pdf">Create pdf</button>```

I am a beginner at JS. Now, I want to create a pdf file including the contents of both the divs excluding both the buttons. Also, the pdf file must contain the values entered in input box. The pdf can contain the contents of div in any format like text or jpg.

Please help me as I am a beginner. I have tried much with jspdf but it is not giving me the output.

答:
jspdf is the right library to begin with. What you can do is to manipulate your data before you put it inside the pdf. I think your best choose is to replace the inputs with  or  or what ever element you want. Then you can build your pdf. My choose is to put it inside wrapper

$('#pdf').click(function () {
    $('#PDFWrapper').find('input').each(function(){
        $(this).hide();
        $(this).after('' + $(this).val() + '');
    });
    $('#PDFWrapper').find('button').hide();

    var doc = new jsPDF();
    doc.fromHTML($('#PDFWrapper').html(), 10, 10, {
        'elementHandlers': {}
    });
    doc.save('download.pdf');

    $('#PDFWrapper').find('input').each(function(){
        $(this).show();
        $(this).next().remove();
    });
    $('#PDFWrapper').find('button').show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<div id="PDFWrapper">
  <div id="element1">
    Enter your name: <input><br>
    Enter your class: <input>
  </div>

  <button>Click on the button</button>

  <div id="element2">
    <table>
      <tr>
        <td>Name</td>
        <td>Class</td>
      </tr>
      <tr>
        <td><input></td>
        <td><input></td>
      </tr>
    </table>
  </div>
</div>

<button id="pdf">Create pdf</button></code>```

Title: Export div to pdf in js

Body:
I have two divs with ids: element1 and element2

In between these divs, there is a button. After these divs, there is one more button with id: pdf.

In the divs there is a table and input box.

      Enter your name: <input>

      Enter your class: <input>

    <button>Click on the button</button>

          Name
          Class

          <input>
          <input>

    <button id="pdf">Create pdf</button>

I am a beginner at JS. Now, I want to create a pdf file including the contents of both the divs excluding both the buttons. Also, the pdf file must contain the values entered in input box. The pdf can contain the contents of div in any format like text or jpg.

Please help me as I am a beginner. I have tried much with jspdf but it is not giving me the output.

Body:
jspdf is the right library to begin with. What you can do is to manipulate your data before you put it inside the pdf. I think your best choose is to replace the inputs with  or  or what ever element you want. Then you can build your pdf. My choose is to put it inside wrapper

$('#pdf').click(function () {
    $('#PDFWrapper').find('input').each(function(){
        $(this).hide();
        $(this).after('<span>' + $(this).val() + '</span>');
    });
    $('#PDFWrapper').find('button').hide();

    var doc = new jsPDF();
    doc.fromHTML($('#PDFWrapper').html(), 10, 10, {
        'elementHandlers': {}
    });
    doc.save('download.pdf');

    $('#PDFWrapper').find('input').each(function(){
        $(this).show();
        $(this).next().remove();
    });
    $('#PDFWrapper').find('button').show();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<div id="PDFWrapper">
  <div id="element1">
    Enter your name: <input><br>
    Enter your class: <input>
  </div>

  <button>Click on the button</button>

  <div id="element2">
    <table>
      <tr>
        <td>Name</td>
        <td>Class</td>
      </tr>
      <tr>
        <td><input></td>
        <td><input></td>
      </tr>
    </table>
  </div>
</div>

<button id="pdf">Create pdf</button>


问:
Solrcloud instance are not work properly
I got a problem in Solrcloud. It working perfectly in recent days but last two days, there is not enough for data, so I increase storage in my digitalOcean and restart sever, And now I got following error. </p>

```<code>625  INFO  (main) [   ] o.a.s.s.SolrDispatchFilter Loading solr.xml from SolrHome (not found in ZooKeeper)
628  INFO  (main) [   ] o.a.s.c.SolrXmlConfig Loading container configuration from /var/solr/data/solr.xml
629  ERROR (main) [   ] o.a.s.s.SolrDispatchFilter Could not start Solr. Check solr/home property and the logs
669  ERROR (main) [   ] o.a.s.c.SolrCore null:org.apache.solr.common.SolrException: Could not load SOLR configuration
at org.apache.solr.core.SolrXmlConfig.fromFile(SolrXmlConfig.java:116)
at org.apache.solr.core.SolrXmlConfig.fromSolrHome(SolrXmlConfig.java:140)
at org.apache.solr.servlet.SolrDispatchFilter.loadNodeConfig(SolrDispatchFilter.java:188)
at org.apache.solr.servlet.SolrDispatchFilter.createCoreContainer(SolrDispatchFilter.java:156)
at org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:134)
at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:137)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:856)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:348)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1379)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1341)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:772)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:261)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:517)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:41)
at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:188)
at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:499)
at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:147)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:180)
at org.eclipse.jetty.deploy.providers.WebAppProvider.fileAdded(WebAppProvider.java:458)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:64)
at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:610)
at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:529)
at org.eclipse.jetty.util.Scanner.scan(Scanner.java:392)
at org.eclipse.jetty.util.Scanner.doStart(Scanner.java:313)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:150)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:561)
at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:236)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
at org.eclipse.jetty.server.Server.start(Server.java:405)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
at org.eclipse.jetty.server.Server.doStart(Server.java:372)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1510)
at java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:1435)
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.eclipse.jetty.start.Main.invokeMain(Main.java:214)
at org.eclipse.jetty.start.Main.start(Main.java:457)
at org.eclipse.jetty.start.Main.main(Main.java:75)

Caused by: java.nio.file.AccessDeniedException: /var/solr/data/solr.xml
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:84)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
at java.nio.file.Files.newInputStream(Files.java:152)
at org.apache.solr.core.SolrXmlConfig.fromFile(SolrXmlConfig.java:111)
... 46 more
</code>```

<p>So, it error is zookeeper doesn't found solr.xml file but it exist under solr.home location. I search from google but didn't found proper answer for this solution. </p>

答:
Change the permission or ownership of the folder /var/solr

If you are running solr from solr user then change the ownership to solr user by the below command for linux

```<code>sudo chown -R solr:solr /var/solr
</code>```

This will change the ownership of that folder recursively to user solr

Body:
I got a problem in Solrcloud. It working perfectly in recent days but last two days, there is not enough for data, so I increase storage in my digitalOcean and restart sever, And now I got following error.

625  INFO  (main) [   ] o.a.s.s.SolrDispatchFilter Loading solr.xml from SolrHome (not found in ZooKeeper)
628  INFO  (main) [   ] o.a.s.c.SolrXmlConfig Loading container configuration from /var/solr/data/solr.xml
629  ERROR (main) [   ] o.a.s.s.SolrDispatchFilter Could not start Solr. Check solr/home property and the logs
669  ERROR (main) [   ] o.a.s.c.SolrCore null:org.apache.solr.common.SolrException: Could not load SOLR configuration
at org.apache.solr.core.SolrXmlConfig.fromFile(SolrXmlConfig.java:116)
at org.apache.solr.core.SolrXmlConfig.fromSolrHome(SolrXmlConfig.java:140)
at org.apache.solr.servlet.SolrDispatchFilter.loadNodeConfig(SolrDispatchFilter.java:188)
at org.apache.solr.servlet.SolrDispatchFilter.createCoreContainer(SolrDispatchFilter.java:156)
at org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:134)
at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:137)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:856)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:348)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1379)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1341)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:772)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:261)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:517)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:41)
at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:188)
at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:499)
at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:147)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:180)
at org.eclipse.jetty.deploy.providers.WebAppProvider.fileAdded(WebAppProvider.java:458)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:64)
at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:610)
at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:529)
at org.eclipse.jetty.util.Scanner.scan(Scanner.java:392)
at org.eclipse.jetty.util.Scanner.doStart(Scanner.java:313)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:150)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:561)
at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:236)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
at org.eclipse.jetty.server.Server.start(Server.java:405)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
at org.eclipse.jetty.server.Server.doStart(Server.java:372)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1510)
at java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:1435)
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.eclipse.jetty.start.Main.invokeMain(Main.java:214)
at org.eclipse.jetty.start.Main.start(Main.java:457)
at org.eclipse.jetty.start.Main.main(Main.java:75)

Caused by: java.nio.file.AccessDeniedException: /var/solr/data/solr.xml
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:84)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
at java.nio.file.Files.newInputStream(Files.java:152)
at org.apache.solr.core.SolrXmlConfig.fromFile(SolrXmlConfig.java:111)
... 46 more

So, it error is zookeeper doesn't found solr.xml file but it exist under solr.home location. I search from google but didn't found proper answer for this solution.

Body:
Change the permission or ownership of the folder /var/solr

If you are running solr from solr user then change the ownership to solr user by the below command for linux

sudo chown -R solr:solr /var/solr

This will change the ownership of that folder recursively to user solr