问:
Getting return value from stored procedure in C#
I have the following query:

```<code>set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[Validate]
@a varchar(50),
@b varchar(50) output

AS

SET @Password =
(SELECT Password
FROM dbo.tblUser
WHERE Login = @a)

RETURN @b
GO
</code>```

This compiles perfectly fine. I want to execute this query and get the return value. My code is below:

```<code>  SqlConnection SqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyLocalSQLServer"].ConnectionString.ToString());
        System.Data.SqlClient.SqlCommand sqlcomm = new System.Data.SqlClient.SqlCommand("Validate", SqlConn);

        string returnValue = string.Empty;

        try
        {
            SqlConn.Open();
            sqlcomm.CommandType = CommandType.StoredProcedure;

            SqlParameter param = new SqlParameter("@a", SqlDbType.VarChar);
            param.Direction = ParameterDirection.Input;
            param.Value = Username;
            sqlcomm.Parameters.Add(param);

            SqlParameter retval = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar);
            retval.Direction = ParameterDirection.ReturnValue;

            string retunvalue = (string)sqlcomm.Parameters["@b"].Value;
</code>```

Note: Exception handling cut to keep the code short. Everytime I get to the last line, null is returned. What's the logic error with this code?

答:
May be this will help.

Database script:

```<code>USE [edata]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[InsertNewUser](
 @neuname NVARCHAR(255),
 @neupassword NVARCHAR(255),
 @neuposition NVARCHAR(255)
 )

AS

BEGIN

BEGIN TRY

 DECLARE @check INT;

 SET @check = (SELECT count(eid) FROM eusers WHERE euname = @neuname);

IF(@check = 0)

INSERT INTO  eusers(euname,eupassword,eposition)
VALUES(@neuname,@neupassword,@neuposition);

DECLARE @lastid INT;

SET @lastid = @@IDENTITY;

RETURN @lastid;

END TRY

BEGIN CATCH

SELECT ERROR_LINE() as errline,
       ERROR_MESSAGE() as errmessage,
       ERROR_SEVERITY() as errsevirity

END CATCH

END
</code>```

Application configuration file:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="conStr" value="Data Source=User\SQLEXPRESS;Initial Catalog=edata;Integrated Security=True"/>
  </appSettings>
</configuration>
</code>```

Data Access Layer (DAL):

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace DAL
{
    public static class DAL
    {
        public static SqlConnection conn;

        static DAL()
        {

            conn = new SqlConnection(ConfigurationManager.AppSettings["conStr"].ToString());
            conn.Open();

        }

    }
}
</code>```

Business Logic Layer(BLL):

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using DAL;
namespace BLL
{
    public static class BLL
    {

        public static int InsertUser(string lastid, params SqlParameter[] coll)
        {

            int lastInserted = 0;

            try
            {

                SqlCommand comm = new SqlCommand();

                comm.Connection = DAL.DAL.conn;

                foreach (var param in coll)
                {

                    comm.Parameters.Add(param);

                }

                SqlParameter lastID = new SqlParameter();
                lastID.ParameterName = lastid;
                lastID.SqlDbType = SqlDbType.Int;
                lastID.Direction = ParameterDirection.ReturnValue;

                comm.Parameters.Add(lastID);

                comm.CommandType = CommandType.StoredProcedure;

                comm.CommandText = "InsertNewUser";

                comm.ExecuteNonQuery();

                lastInserted = (int)comm.Parameters[lastid].Value;

            }

            catch (SqlException ex)
            {

            }

            finally {

                if (DAL.DAL.conn.State != ConnectionState.Closed) {

                    DAL.DAL.conn.Close();
                }

            }

            return lastInserted;

        }

    }
}
</code>```

Implementation :

```<code>BLL.BLL.InsertUser("@lastid",new SqlParameter("neuname","Ded"),
                 new SqlParameter("neupassword","Moro$ilka"),
                 new SqlParameter("neuposition","Moroz")
                 );
</code>```

OwnerDisplayName: dotnetdev

Body:
I have the following query:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[Validate]
@a varchar(50),
@b varchar(50) output

AS

SET @Password =
(SELECT Password
FROM dbo.tblUser
WHERE Login = @a)

RETURN @b
GO

This compiles perfectly fine. I want to execute this query and get the return value. My code is below:

  SqlConnection SqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyLocalSQLServer"].ConnectionString.ToString());
        System.Data.SqlClient.SqlCommand sqlcomm = new System.Data.SqlClient.SqlCommand("Validate", SqlConn);

        string returnValue = string.Empty;

        try
        {
            SqlConn.Open();
            sqlcomm.CommandType = CommandType.StoredProcedure;

            SqlParameter param = new SqlParameter("@a", SqlDbType.VarChar);
            param.Direction = ParameterDirection.Input;
            param.Value = Username;
            sqlcomm.Parameters.Add(param);

            SqlParameter retval = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar);
            retval.Direction = ParameterDirection.ReturnValue;

            string retunvalue = (string)sqlcomm.Parameters["@b"].Value;

Note: Exception handling cut to keep the code short. Everytime I get to the last line, null is returned. What's the logic error with this code?

Body:
May be this will help.

Database script:

USE [edata]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[InsertNewUser](
 @neuname NVARCHAR(255),
 @neupassword NVARCHAR(255),
 @neuposition NVARCHAR(255)
 )

AS

BEGIN

BEGIN TRY

 DECLARE @check INT;

 SET @check = (SELECT count(eid) FROM eusers WHERE euname = @neuname);

IF(@check = 0)

INSERT INTO  eusers(euname,eupassword,eposition)
VALUES(@neuname,@neupassword,@neuposition);

DECLARE @lastid INT;

SET @lastid = @@IDENTITY;

RETURN @lastid;

END TRY

BEGIN CATCH

SELECT ERROR_LINE() as errline,
       ERROR_MESSAGE() as errmessage,
       ERROR_SEVERITY() as errsevirity

END CATCH

END

Application configuration file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="conStr" value="Data Source=User\SQLEXPRESS;Initial Catalog=edata;Integrated Security=True"/>
  </appSettings>
</configuration>

Data Access Layer (DAL):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace DAL
{
    public static class DAL
    {
        public static SqlConnection conn;

        static DAL()
        {

            conn = new SqlConnection(ConfigurationManager.AppSettings["conStr"].ToString());
            conn.Open();

        }

    }
}

Business Logic Layer(BLL):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using DAL;
namespace BLL
{
    public static class BLL
    {

        public static int InsertUser(string lastid, params SqlParameter[] coll)
        {

            int lastInserted = 0;

            try
            {

                SqlCommand comm = new SqlCommand();

                comm.Connection = DAL.DAL.conn;

                foreach (var param in coll)
                {

                    comm.Parameters.Add(param);

                }

                SqlParameter lastID = new SqlParameter();
                lastID.ParameterName = lastid;
                lastID.SqlDbType = SqlDbType.Int;
                lastID.Direction = ParameterDirection.ReturnValue;

                comm.Parameters.Add(lastID);

                comm.CommandType = CommandType.StoredProcedure;

                comm.CommandText = "InsertNewUser";

                comm.ExecuteNonQuery();

                lastInserted = (int)comm.Parameters[lastid].Value;

            }

            catch (SqlException ex)
            {

            }

            finally {

                if (DAL.DAL.conn.State != ConnectionState.Closed) {

                    DAL.DAL.conn.Close();
                }

            }

            return lastInserted;

        }

    }
}

Implementation :

BLL.BLL.InsertUser("@lastid",new SqlParameter("neuname","Ded"),
                 new SqlParameter("neupassword","Moro$ilka"),
                 new SqlParameter("neuposition","Moroz")
                 );


来源: stackexchange

问:
Downloading Oracle forms and reports 11g
Can anyone please suggest some useful weblinks for downloading for free Oracle forms and Reports 11G.
 Also suggest the perquisites for installation.</p>

答:
You first need to create an account in oracle.com

Then you can go to below link that has all the downloadable software by Oracle

https://edelivery.oracle.com/osdc/faces/Home.jspx

ContentLicense: CC BY-SA 3.0


问:
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?

答:
4.5 Seconds is being taken up by this section, if this is an accurate representation of when the app finishes loading.

```<code>04-01 07:53:15.443 D/Mono    ( 1742): [0x9ac5e930] hill climbing, change max number of threads 2
04-01 07:53:15.445 W/art     ( 1742): JNI RegisterNativeMethods: attempt to register 0 native methods for md54ada4fbe4a5955f6151fa282d30cfc48.SelfDisposingBitmapDrawable
Resolved pending breakpoint at 'CleanUpReceiver.cs:16,1' to void extrony.Droid.Receivers.CleanUpReceiver.OnReceive (Android.Content.Context context, Android.Content.Intent intent) [0x00000].
04-01 07:53:20.059 D/Mono    ( 1742): DllImport searching in: '/system/lib/libsqlite.so' ('/system/lib/libsqlite.so').
04-01 07:53:20.059 D/Mono    ( 1742): Searching for 'sqlite3_column_count'.
</code>```

Everything is loaded at this point, hence it's something in your code, most likely in the App.xaml.cs constructor. I notice you also have EF Core as well.

There could be many things going on here, but until App.xaml.cs is completed, it will still show the splashscreen.

I would recommend adding a StopWatch in parts of your code on startup and see what is taking the time. From there you could ask a different question in stackoverflow relating that problem.

```<code>System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
s.Start();

// Code in here

s.Stop();
System.Diagnostics.Debug.WriteLine($"Elapsed Time: {s.ElapsedMilliseconds.ToString("N0")}");
</code>```

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?

Body:
4.5 Seconds is being taken up by this section, if this is an accurate representation of when the app finishes loading.

04-01 07:53:15.443 D/Mono    ( 1742): [0x9ac5e930] hill climbing, change max number of threads 2
04-01 07:53:15.445 W/art     ( 1742): JNI RegisterNativeMethods: attempt to register 0 native methods for md54ada4fbe4a5955f6151fa282d30cfc48.SelfDisposingBitmapDrawable
Resolved pending breakpoint at 'CleanUpReceiver.cs:16,1' to void extrony.Droid.Receivers.CleanUpReceiver.OnReceive (Android.Content.Context context, Android.Content.Intent intent) [0x00000].
04-01 07:53:20.059 D/Mono    ( 1742): DllImport searching in: '/system/lib/libsqlite.so' ('/system/lib/libsqlite.so').
04-01 07:53:20.059 D/Mono    ( 1742): Searching for 'sqlite3_column_count'.

Everything is loaded at this point, hence it's something in your code, most likely in the App.xaml.cs constructor. I notice you also have EF Core as well.

There could be many things going on here, but until App.xaml.cs is completed, it will still show the splashscreen.

I would recommend adding a StopWatch in parts of your code on startup and see what is taking the time. From there you could ask a different question in stackoverflow relating that problem.

System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
s.Start();

// Code in here

s.Stop();
System.Diagnostics.Debug.WriteLine($"Elapsed Time: {s.ElapsedMilliseconds.ToString("N0")}");


问:
Should I use $_GET to dynamically load html?
I am working on a social networking site using PHP, MySQL(PDO), JQuery, and HTML(CSS). I'm working on the profile page right now and I want to determine if the user is on their own page or another's to determine what inputs they'll have. I would like to keep a framework for the profile page and load the respective options rather than having 2 different pages (my profile vs other profile).

I'm learning JQuery and PHP as I go, so right now I am thinking, in JQuery, I can get the $_GET (?username= ) and compare it to the user id of who's logged in, then load the components I need based on that.

Or I determine the user in PHP then run a certain scrip to load the components.

Would on of these ways work, or is there a different/better way to do this?

答:
The best security practice is to not rely on anything happening in browser.

This means you should always figure out privileges on the server (on PHP side).

Variant 1 (Simple)

Let's assume you have authenticated the user and have the user as $currentUser and their id as $currentUser->id in PHP.

Now this user wants to view some profile by requesting url "profile?id=555"

So here's (basically) what you do on PHP side:

$requestedProfile = (int)$_GET['profile'];
if ($requestedProfile == $currentUser->id) {
    // they want own profile
    show_controls_for_own_profile();
} else {
    // they want someone else's profile
    show_controls_for_other_profile();
}
```

<p>In this case, jQuery has nothing to do here. </p>

<h2>Variant 2 (Separate requests)</h2>

<p>Further, let's assume you want to cache the entire profile page to quickly load it into browser, and only after that, ajax-load additional controls associated with user's privileges. </p>

<p>then you have two controller methods (php scripts, whatever) each serving it's own part:</p>

```public function showProfile() {
    $requestedProfile = (int)$_GET['profile'];
    if (profile_exists($requestedProfile)) {
        show_the_profile($requestedProfile); // no check here
    }
}
```

<p>The method above would return the generic profile page by its ID (with empty ".controls" element) and on that page, some <strong>jquery</strong> code would ask the server to return appropriate variant of user-dependent part.</p>

```$.ajax('/user-controls.php')
    .done(function(response) { $('.controls').html(response); });
```

<p>Notice it does not tell the server any user ID - server should already know current authenticated user ID from the session!</p>

<p>The second function, same as in the beginning, will return just HTML for the controls:</p>

<pre class="lang-php prettyprint-override"><code>// Example of getting current profile from server's headers
function get_viewed_profile_id()
{
    // url of previous profile page, e.g. http://example.com/profile?id=555
    $referer = $_SERVER['HTTP_REFERER'];
    $query = parse_url($referer, PHP_URL_QUERY); // id=555
    parse_str($query, $params); // ['id' => '555']
    return $params['id']; // 555
}

// we should store the authenticated user in session,
// not rely on anything user sends from their browser
$currentUserId = $_SESSION['user']->id;
$requestedProfileId = get_viewed_profile_id();

// now that we know both viewed profile and current user,
// we can compare them
if ($requestedProfileId == $currentUserId) {
    // they want own profile
    show_controls_for_own_profile();
} else {
    // they want someone else's profile
    show_controls_for_other_profile();
}
</code>```

Variant 3 (Passing PHP variable to javascript)

Same as above, but you don't rely on $_SERVER['HTTP_REFERER'], and move some logic to Javascript instead:

Browser asks:

```<code>// look up currently browsed profile from current window url
var q = new URLSearchParams(window.location.search);
var controlsURL = '/user-controls.php?viewedProfile=' + q.get('id');
// ask for controls, specifying the currently browsed profile
$.ajax(controlsURL)
    .done(function(response) { $('.controls').html(response); });
</code>```

And server responds with:

function get_viewed_profile_id()
{
    return (int)$_GET['viewedProfile'];
}

// we should store the authenticated user in session,
// not rely on anyhting user sends from their browser
$currentUserId = $_SESSION['user']->id;
$requestedProfileId = get_viewed_profile_id();

// now that we know both viewed profile and current user,
// we can compare them
if ($requestedProfileId == $currentUserId) {
    // they want own profile
    show_controls_for_own_profile();
} else {
    // they want someone else's profile
    show_controls_for_other_profile();
}
```

Body:
The best security practice is to not rely on anything happening in browser.

This means you should always figure out privileges on the server (on PHP side).

Variant 1 (Simple)

Let's assume you have authenticated the user and have the user as $currentUser and their id as $currentUser->id in PHP.

Now this user wants to view some profile by requesting url "profile?id=555"

So here's (basically) what you do on PHP side:

$requestedProfile = (int)$_GET['profile'];
if ($requestedProfile == $currentUser->id) {
    // they want own profile
    show_controls_for_own_profile();
} else {
    // they want someone else's profile
    show_controls_for_other_profile();
}

In this case, jQuery has nothing to do here.

Variant 2 (Separate requests)

Further, let's assume you want to cache the entire profile page to quickly load it into browser, and only after that, ajax-load additional controls associated with user's privileges.

then you have two controller methods (php scripts, whatever) each serving it's own part:

public function showProfile() {
    $requestedProfile = (int)$_GET['profile'];
    if (profile_exists($requestedProfile)) {
        show_the_profile($requestedProfile); // no check here
    }
}

The method above would return the generic profile page by its ID (with empty ".controls" element) and on that page, some jquery code would ask the server to return appropriate variant of user-dependent part.

$.ajax('/user-controls.php')
    .done(function(response) { $('.controls').html(response); });

Notice it does not tell the server any user ID - server should already know current authenticated user ID from the session!

The second function, same as in the beginning, will return just HTML for the controls:

// Example of getting current profile from server's headers
function get_viewed_profile_id()
{
    // url of previous profile page, e.g. http://example.com/profile?id=555
    $referer = $_SERVER['HTTP_REFERER'];
    $query = parse_url($referer, PHP_URL_QUERY); // id=555
    parse_str($query, $params); // ['id' => '555']
    return $params['id']; // 555
}

// we should store the authenticated user in session,
// not rely on anything user sends from their browser
$currentUserId = $_SESSION['user']->id;
$requestedProfileId = get_viewed_profile_id();

// now that we know both viewed profile and current user,
// we can compare them
if ($requestedProfileId == $currentUserId) {
    // they want own profile
    show_controls_for_own_profile();
} else {
    // they want someone else's profile
    show_controls_for_other_profile();
}

Variant 3 (Passing PHP variable to javascript)

Same as above, but you don't rely on $_SERVER['HTTP_REFERER'], and move some logic to Javascript instead:

Browser asks:

// look up currently browsed profile from current window url
var q = new URLSearchParams(window.location.search);
var controlsURL = '/user-controls.php?viewedProfile=' + q.get('id');
// ask for controls, specifying the currently browsed profile
$.ajax(controlsURL)
    .done(function(response) { $('.controls').html(response); });

And server responds with:

function get_viewed_profile_id()
{
    return (int)$_GET['viewedProfile'];
}

// we should store the authenticated user in session,
// not rely on anyhting user sends from their browser
$currentUserId = $_SESSION['user']->id;
$requestedProfileId = get_viewed_profile_id();

// now that we know both viewed profile and current user,
// we can compare them
if ($requestedProfileId == $currentUserId) {
    // they want own profile
    show_controls_for_own_profile();
} else {
    // they want someone else's profile
    show_controls_for_other_profile();
}


问:
How to allow only two letter two two numbers and two special characters but position is not fact in regular expression
I have to face problem when I create a regular expression for allow only two letter two numbers and two special characters. This is actually not a problem to create a regular expression. But when i change the position of characters then regular expression show not match. So please help me how to solve these problem.</p>

```<code>[A-Za-z]{2}[0-9]{2}[!@#$%^&]{2}
</code>```

答:
This type of matching can best be done with look ahead:

^(?=.*\d.*\d)(?=.*[A-Za-z].*[A-Za-z])(?=.*[!@#$%^&].*[!@#$%^&]).{6}$

The (?=   ) does not grab any characters, it just looks ahead, so you can check for different conditions, and only then grab them with a simple .{6}$ at the end, when all look-ahead conditions pass. The only condition left is that there are exactly 6 characters from the beginning (^) to the end ($).

As each sub-pattern repeats, you could also do it like this:

^(?=(?:.*\d){2})(?=(?:.*[A-Za-z]){2})(?=(?:.*[!@#$%^&]){2}).{6}$

Body:
I have to face problem when I create a regular expression for allow only two letter two numbers and two special characters. This is actually not a problem to create a regular expression. But when i change the position of characters then regular expression show not match. So please help me how to solve these problem.

[A-Za-z]{2}[0-9]{2}[!@#$%^&]{2}


问:
Is the "C# Language Specifications" updated for C# 6.0 or 7.0 yet?
C# is already 7.0. But C# Language Specifications is still for 5.0.

I realize the specifications is outdated when I couldn't find GetValueOrDefault() for a nullable type  in the document.

I wonder if the specification has been updated yet, at least for 6.0?

答:
The current status is:

Microsoft's officially released spec is indeed 5.0.

An unofficial version of the 6.0 spec exists.

Work is being done to update the ECMA spec to 6.0 and 7.x. ECMA has released its 5.0 spec in December 2017.

But those are just specifications of the C# language, they don't specify types and members that exist in the base class library (with some exceptions that are required for various language features). Until recently, each framework defined its library on its own, but now even that is standardized, though the .Net Standard.

ContentLicense: CC BY-SA 4.0


问:
When is preferable to use if 'key' in dict: instead of if dict.get('key') is not None:?
I've been using the following syntax in my code for checking the existence of a key:

```<code>if dict.get("key") is not None:
    print "key found"
</code>```

However, I have seen in other people's code the following syntax:

```<code>if 'key' in dict:
   print "key found"
</code>```

I was just wondering which way is best to express a dictionary key null check and if there is an advantage (if any) to using one over the other.

I saw the existing question addressing the similar question of what are the alternatives to using .get() but just want to know if there is any advantage between the two examples I provided.

答:
These two ways is different.

dict.get("key") is not None means dict has "key" and dict["key"] is not None.

"key" in dict means dict has "key" and don't care it's value is None or other.

Body:
I've been using the following syntax in my code for checking the existence of a key:

if dict.get("key") is not None:
    print "key found"

However, I have seen in other people's code the following syntax:

if 'key' in dict:
   print "key found"

I was just wondering which way is best to express a dictionary key null check and if there is an advantage (if any) to using one over the other.

I saw the existing question addressing the similar question of what are the alternatives to using .get() but just want to know if there is any advantage between the two examples I provided.


问:
Jqplot graph is not displaying inside nested div tags
I'm testing a jqplot mixed bar and line graph inside a JSF2.2 template client xhtml page that has a tabbed view. If I put the graph inside the tabbed view it will not not show. If I put it outside the view it shows:

```<code><div id="datanalytics">
<div class="w3-layout-container">
<div id="chart2"> </div>
</div>
</div>
</code>```

The above just comes out as a blank area where the graph should be. I see  no JS errors in either Chrome or Firefox (Firebug). If I put the graph outside the main div like this, it will show perfectly:

```<code><div id="chart2"> </div>
<div id="datanalytics">
<div class="w3-layout-container">
</div>
</div>
</code>```

I am including the following JS at the bottom of the xhtml page:

```<code><script>
 $(document).ready(function () {
  var line1 = [['Cup Holder Pinion Bob', 7], ['Generic Fog Lamp', 9], ['HDTV Receiver', 15],
  ['8 Track Control Module', 12], [' Sludge Pump Fourier Modulator', 3],
  ['Transcender/Spice Rack', 6], ['Hair Spray Danger Indicator', 18]];
  var line2 = [['Nickle', 28], ['Aluminum', 13], ['Xenon', 54], ['Silver', 47],
  ['Sulfer', 16], ['Silicon', 14], ['Vanadium', 23]];

  var plot2 = $.jqplot('chart2', [line1, line2], {
  series: [{renderer: $.jqplot.BarRenderer}, {xaxis: 'x2axis', yaxis: 'y2axis'}],
  axesDefaults: {
  tickRenderer: $.jqplot.CanvasAxisTickRenderer,
  tickOptions: {
  angle: 30
  }
  },
  axes: {
  xaxis: {
  renderer: $.jqplot.CategoryAxisRenderer
  },
  x2axis: {
  renderer: $.jqplot.CategoryAxisRenderer
  },
  yaxis: {
  autoscale: true
  },
  y2axis: {
  autoscale: true
  }
  }
  });

  });

  </script>
</code>```

In my xhtml template page I have the following libraries added (at the end of the body tag so that the scripts execute after page loading):

```<code>    <h:outputScript name="js/jqplot/jqplot.canvasAxisTickRenderer.js"/>
    <h:outputScript name="js/jqplot/jqplot.dateAxisRenderer.js"/>
    <h:outputScript name="js/jqplot/chartExtender.js" />
    <h:outputScript name="js/jqplot/excanvas.js" />
    <h:outputScript name="js/jqplot/chartExtender.js" />
    <h:outputScript name="js/jqplot/jqplot.categoryAxisRenderer.js" />
    <h:outputScript name="js/jqplot/jqplot.barRenderer.js" />
</code>```

The problem is solved if I don't use      $(document).ready(function () and instead use:

```<code>  function processChartAsClick() {

 .......
 }
</code>```

I think this is because the script does not get fired inside a tabbed view because the tabbed view is a separate Jquery UI event, but putting it outside the tabbed view fires the event when the document is loaded?
Would appreciate any clarification on this. Thank you!

答:
The answer is simply to give the script its own (autonomous) function since the document ready method is fired upon page loading. This means that if the JS/Jquery script is inside a div which uses its own JS UI function, then it will get ignored unless the script is part of the nested div JS function.

I added a button and corresponding function and the chart is now showing:

```<code><button type="button" class="button" onclick="showChart()">Show the chart </button>

<script>

 function showChart() {
 JS code here
 .......
}
</script>
</code>```

While this renders the chart it throws some more questions about how to handle events in nested divs in a JSF applications, but that needs to be posted separately.

Body:
I'm testing a jqplot mixed bar and line graph inside a JSF2.2 template client xhtml page that has a tabbed view. If I put the graph inside the tabbed view it will not not show. If I put it outside the view it shows:

The above just comes out as a blank area where the graph should be. I see  no JS errors in either Chrome or Firefox (Firebug). If I put the graph outside the main div like this, it will show perfectly:

I am including the following JS at the bottom of the xhtml page:

In my xhtml template page I have the following libraries added (at the end of the body tag so that the scripts execute after page loading):

    <h:outputScript name="js/jqplot/jqplot.canvasAxisTickRenderer.js"/>
    <h:outputScript name="js/jqplot/jqplot.dateAxisRenderer.js"/>
    <h:outputScript name="js/jqplot/chartExtender.js" />
    <h:outputScript name="js/jqplot/excanvas.js" />
    <h:outputScript name="js/jqplot/chartExtender.js" />
    <h:outputScript name="js/jqplot/jqplot.categoryAxisRenderer.js" />
    <h:outputScript name="js/jqplot/jqplot.barRenderer.js" />

The problem is solved if I don't use      $(document).ready(function () and instead use:

  function processChartAsClick() {

 .......
 }

I think this is because the script does not get fired inside a tabbed view because the tabbed view is a separate Jquery UI event, but putting it outside the tabbed view fires the event when the document is loaded?
Would appreciate any clarification on this. Thank you!

Body:
The answer is simply to give the script its own (autonomous) function since the document ready method is fired upon page loading. This means that if the JS/Jquery script is inside a div which uses its own JS UI function, then it will get ignored unless the script is part of the nested div JS function.

I added a button and corresponding function and the chart is now showing:

<button type="button" class="button" onclick="showChart()">Show the chart </button>

<script>

 function showChart() {
 JS code here
 .......
}
</script>

While this renders the chart it throws some more questions about how to handle events in nested divs in a JSF applications, but that needs to be posted separately.


问:
Which versions of SQL Server does LINQ to SQL support?
Can SQL Server 2000 be used as the database for LINQ to SQL?

Does LINQ to SQL rely on a specific version of Microsoft SQL Server?

答: As of VS 2010, L2S for SQL Server 2000 is not supported under any scenario (although some third party tools add support back).

OwnerDisplayName: Nick

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ALassek


问:
understanding some concepts in java generics
So I came across this code while studying linkedlists. The code here uses generics and I am having problem understanding some of the things here.

```<code>public static class Node<E>
{
     E element;
     Node <E> next;
    public Node(E e,Node <E> n)
    {
        element=e;
        next=n;System.out.println(next);
    }
    public E getelement() {return element;}
    public Node<E> getnext(){ return next;}
    public void setnext(Node <E> n)
    {
        next=n;
    }
}
</code>```

So what does class Node <E> mean?
I think E element; means  element is of type E. Am I right?
Node <E> next; what does this mean?

答:
I always learn best from example, so put Node to a simple use:

```<code>import java.awt.Point;

public class TestNode{

    public static void main(String[] args) {

        //assume you have 3 points
        Point point1 = new Point(40,40);
        Point point2 = new Point(80,120);
        Point point3 = new Point(70,200);

        //each point is connected to one other point. to represent such connection you
        //can create a Node<Point> or in other words Node of Point.
        //define the last node in the chain, which has no next node:
        Node<Point> node3 = new Node<>(point3, null);
        //Note: because Node<E> is generic you could define Node<Cats>, Node<Dogs>, Node<AnyType>

        //define the point2-point3 connection
        Node<Point> node2 = new Node<>(point2, node3);
        //define point1-point2 connection
        Node<Point> node1 = new Node<>(point1, node2);

        //now put it to test. node1.getnext() return node2, node1.getnext().getelement() returns point2
        System.out.println("Point 2 x-y " +node1.getnext().getelement().getX()
                                                              +"-"+node1.getnext().getelement().getY());

        //now put it to test. node1.getnext().getnext() return node3
        System.out.println("Point 3 x-y " +node1.getnext().getnext().getelement().getX()
                                                    +"-"+node1.getnext().getnext().getelement().getY());
    }
}
</code>```

Body:
So I came across this code while studying linkedlists. The code here uses generics and I am having problem understanding some of the things here.

public static class Node<E>
{
     E element;
     Node <E> next;
    public Node(E e,Node <E> n)
    {
        element=e;
        next=n;System.out.println(next);
    }
    public E getelement() {return element;}
    public Node<E> getnext(){ return next;}
    public void setnext(Node <E> n)
    {
        next=n;
    }
}

So what does class Node <E> mean?
I think E element; means  element is of type E. Am I right?
Node <E> next; what does this mean?

Body:
I always learn best from example, so put Node to a simple use:

import java.awt.Point;

public class TestNode{

    public static void main(String[] args) {

        //assume you have 3 points
        Point point1 = new Point(40,40);
        Point point2 = new Point(80,120);
        Point point3 = new Point(70,200);

        //each point is connected to one other point. to represent such connection you
        //can create a Node<Point> or in other words Node of Point.
        //define the last node in the chain, which has no next node:
        Node<Point> node3 = new Node<>(point3, null);
        //Note: because Node<E> is generic you could define Node<Cats>, Node<Dogs>, Node<AnyType>

        //define the point2-point3 connection
        Node<Point> node2 = new Node<>(point2, node3);
        //define point1-point2 connection
        Node<Point> node1 = new Node<>(point1, node2);

        //now put it to test. node1.getnext() return node2, node1.getnext().getelement() returns point2
        System.out.println("Point 2 x-y " +node1.getnext().getelement().getX()
                                                              +"-"+node1.getnext().getelement().getY());

        //now put it to test. node1.getnext().getnext() return node3
        System.out.println("Point 3 x-y " +node1.getnext().getnext().getelement().getX()
                                                    +"-"+node1.getnext().getnext().getelement().getY());
    }
}


问:
How to change certain words into the tagged forms of training lists
I tried to change certain strings into the forms of tagged words listed in train.

```<code>train = c('love/POS','happy/POS','sad/NEG','fearsome/NEG','lazy/NEG')
test = c('I love you', 'I am so happy now', 'You look sad somehow', 'the lazy boy look so fearsome')
</code>```

With them, I wanted to make an outcome like

```<code>[1]'I love/POS you' 'I am so happy/POS now' 'You look sad/NEG somehow' 'the lazy/NEG boy look so fearsome/NEG'
</code>```

Of course, I can use gsub like this as a primitive way

```<code>part1 = gsub('love', 'love/POS', test)
part2 = gsub('happy', 'happy/POS', part1)
.......
</code>```

However, this way is not productive at all when I have bigger training lists.

In order to make it possible in a more effective way, I tried

```<code>process1 = unlist(strsplit(test, '[[:space:]]+'))

mgsub <- function(pattern, replacement, x, ...) {
  if (length(pattern)!=length(replacement)) {
    stop("pattern and replacement do not have the same length.")
  }
  result <- x
  for (i in 1:length(pattern)) {
    result <- gsub(pattern[i], replacement[i], result, ...)
  }
  result
}

trainedtest = mgsub(process1, train, test)
trainedtest
</code>```

In fact, it is not working at all because the length of process1 and train lists are not same. Technically, I should make a program which can select certain words to change into tagged forms of train lists, calculating similarities between process1 and train.

Is there any way to make it possible?

答:
If you want to replace multiple patterns with desired strings use gsubfn:

```<code>require(gsubfn)
input = c("I love you", "I am so happy now")
toreplace<-list("love" = "love/POS", "happy" = "happy/POS")
gsubfn(paste(names(toreplace),collapse="|"),toreplace, input)
</code>```

Body:
I tried to change certain strings into the forms of tagged words listed in train.

train = c('love/POS','happy/POS','sad/NEG','fearsome/NEG','lazy/NEG')
test = c('I love you', 'I am so happy now', 'You look sad somehow', 'the lazy boy look so fearsome')

With them, I wanted to make an outcome like

[1]'I love/POS you' 'I am so happy/POS now' 'You look sad/NEG somehow' 'the lazy/NEG boy look so fearsome/NEG'

Of course, I can use gsub like this as a primitive way

part1 = gsub('love', 'love/POS', test)
part2 = gsub('happy', 'happy/POS', part1)
.......

However, this way is not productive at all when I have bigger training lists.

In order to make it possible in a more effective way, I tried

process1 = unlist(strsplit(test, '[[:space:]]+'))

mgsub <- function(pattern, replacement, x, ...) {
  if (length(pattern)!=length(replacement)) {
    stop("pattern and replacement do not have the same length.")
  }
  result <- x
  for (i in 1:length(pattern)) {
    result <- gsub(pattern[i], replacement[i], result, ...)
  }
  result
}

trainedtest = mgsub(process1, train, test)
trainedtest

In fact, it is not working at all because the length of process1 and train lists are not same. Technically, I should make a program which can select certain words to change into tagged forms of train lists, calculating similarities between process1 and train.

Is there any way to make it possible?

Body:
If you want to replace multiple patterns with desired strings use gsubfn:

require(gsubfn)
input = c("I love you", "I am so happy now")
toreplace<-list("love" = "love/POS", "happy" = "happy/POS")
gsubfn(paste(names(toreplace),collapse="|"),toreplace, input)


问:
nginx and supervisor setup in Ubuntu
I'm using django-gunicorn-nginx setup by following this tutorial http://ijcdigital.com/blog/django-gunicorn-and-nginx-setup/ Upto nginx setup, it is working. Then I installed supervisor, configured it and then I reboot my server and checked, it shows 502 bad gateway. I'm using Ubuntu 12.04 LTS

/etc/supervisor/conf.d/qlimp.conf

```<code>[program: qlimp]
directory = /home/nirmal/project/qlimp/qlimp.sh
user = nirmal
command = /home/nirmal/project/qlimp/qlimp.sh
stdout_logfile = /path/to/supervisor/log/file/logfile.log
stderr_logfile = /path/to/supervisor/log/file/error-logfile.log
</code>```

Then I restarted supervisor and I run this command $ supervisorctl start qlimp and I'm getting this error

```<code>unix:///var/run/supervisor.sock no such file
</code>```

Is there any problem in my supervisor setup?

Thanks!

答:
You can do something like this :-

```<code>sudo touch /var/run/supervisor.sock
sudo chmod 777 /var/run/supervisor.sock
sudo service supervisor restart
</code>```

It's definitely work, try this.

Title: nginx and supervisor setup in Ubuntu

Body:
I'm using django-gunicorn-nginx setup by following this tutorial http://ijcdigital.com/blog/django-gunicorn-and-nginx-setup/ Upto nginx setup, it is working. Then I installed supervisor, configured it and then I reboot my server and checked, it shows 502 bad gateway. I'm using Ubuntu 12.04 LTS

/etc/supervisor/conf.d/qlimp.conf

[program: qlimp]
directory = /home/nirmal/project/qlimp/qlimp.sh
user = nirmal
command = /home/nirmal/project/qlimp/qlimp.sh
stdout_logfile = /path/to/supervisor/log/file/logfile.log
stderr_logfile = /path/to/supervisor/log/file/error-logfile.log

Then I restarted supervisor and I run this command $ supervisorctl start qlimp and I'm getting this error

unix:///var/run/supervisor.sock no such file

Is there any problem in my supervisor setup?

Thanks!

Body:
You can do something like this :-

sudo touch /var/run/supervisor.sock
sudo chmod 777 /var/run/supervisor.sock
sudo service supervisor restart

It's definitely work, try this.


问:
Sorl-thumbnail generates black lines and undesired crops
I'm using Sorl Thumbnail 12.4a1, Pillow 4.0.0 in a django project

It works fine for most images but for some of them I run into unexpected behaviour.

The original image is portrait jpg 765x1110

After running this code: get_thumbnail('/media/ryzsUIKZVUc.jpg', '464', upscale=False)

I receive a 464x320 image with black background on it's left and right and cropped on top and bottom

this is the original:
https://www.dropbox.com/s/ia7906ec19xjhro/ryzsUIKZVUc.jpg?dl=0

and this is the result: https://www.dropbox.com/s/adgut5zkw4xln6e/62b2439654a00312defafddb862eda9b.jpg?dl=0

p.s.
tried to upload the original here as an image but it was automatically converted to portrait.. could it mean something?

答:
This bug has already been fixed in the repository on the github.
This PR https://github.com/mariocesar/sorl-thumbnail/pull/233

But in pypi is still an old package. https://pypi.python.org/pypi/sorl-thumbnail/12.4a1 updated at 2015-11-17

To use the new version, install the package directly from the github.

```<code>pip install -e git+https://github.com/mariocesar/sorl-thumbnail.git#egg=sorl-thumbnail
</code>```

After installation, you will need to clear the image cache

```<code>$ rm -rf path/to/media/cache/
$ python manage.py thumbnail clear
$ python manage.py thumbnail cleanup
</code>```

Body:
This bug has already been fixed in the repository on the github.
This PR https://github.com/mariocesar/sorl-thumbnail/pull/233

But in pypi is still an old package. https://pypi.python.org/pypi/sorl-thumbnail/12.4a1 updated at 2015-11-17

To use the new version, install the package directly from the github.

pip install -e git+https://github.com/mariocesar/sorl-thumbnail.git#egg=sorl-thumbnail

After installation, you will need to clear the image cache

$ rm -rf path/to/media/cache/
$ python manage.py thumbnail clear
$ python manage.py thumbnail cleanup


问:
Is there a way in haskell to compactly and efficiently compare by multiple parameters and in different orders
Suppose we have a list of tuples and we need to find maximum on some criterion. The criterion is the following - most important is the first element of the tuple (more is better) less important is second element (less is better).

I know two ways of expressing this in Haskell.

First one is to create a function that would make all the comparisons and return (EQ, LT, GT)

```<code>compareSol (s1, w1) (s2, w2) = if weightComp == EQ then sizeComp else weightComp where
    weightComp = compare w1 w2
    sizeComp = compare (Map.foldl' (+) 0  s2) (Map.foldl' (+) 0  s1)
</code>```

The second one is to use comparing from Data.Ord and give it a function that would return a score \ (x, y) -> (x, 1 / y) Which is I think more declarative, but would require more computations (1 / y)

Is there a way of expressing this in both declarative and efficient way, like is sql?

答:
I can't understand the precise ordering you want, but probably some variation of the following is what you are looking for

```<code>compareSol (s1, w1) (s2, w2) = compare (w1, sum s2) (w2, sum s1)
</code>```

the above is equivalent to

```<code>compareSol (s1, w1) (s2, w2)
   | w1 < w2   = LT
   | w1 > w2   = GT
   | otherwise = compare (sum s2) (sum s1)
</code>```

or, fully expanded,

```<code>compareSol (s1, w1) (s2, w2)
   | w1 < w2 = LT
   | w1 > w2 = GT
   | sum s1 < sum s2 = GT
   | sum s1 > sum s2 = LT
   | otherwise = EQ
</code>```

Feel free to swap the comparisons around so to meet your goal.

Body:
Suppose we have a list of tuples and we need to find maximum on some criterion. The criterion is the following - most important is the first element of the tuple (more is better) less important is second element (less is better).

I know two ways of expressing this in Haskell.

First one is to create a function that would make all the comparisons and return (EQ, LT, GT)

compareSol (s1, w1) (s2, w2) = if weightComp == EQ then sizeComp else weightComp where
    weightComp = compare w1 w2
    sizeComp = compare (Map.foldl' (+) 0  s2) (Map.foldl' (+) 0  s1)

The second one is to use comparing from Data.Ord and give it a function that would return a score \ (x, y) -> (x, 1 / y) Which is I think more declarative, but would require more computations (1 / y)

Is there a way of expressing this in both declarative and efficient way, like is sql?

Body:
I can't understand the precise ordering you want, but probably some variation of the following is what you are looking for

compareSol (s1, w1) (s2, w2) = compare (w1, sum s2) (w2, sum s1)

the above is equivalent to

compareSol (s1, w1) (s2, w2)
   | w1 < w2   = LT
   | w1 > w2   = GT
   | otherwise = compare (sum s2) (sum s1)

or, fully expanded,

compareSol (s1, w1) (s2, w2)
   | w1 < w2 = LT
   | w1 > w2 = GT
   | sum s1 < sum s2 = GT
   | sum s1 > sum s2 = LT
   | otherwise = EQ

Feel free to swap the comparisons around so to meet your goal.


问:
Anaconda error after install on Windows
I want to install Anaconda on my x64 Windows machine, and I downloaded the Python 2.7 version 64-bit installer. The installation process looks good.

Then I installed pip with choco and installed several packages like zbar,
however, when I want to try to launch Anaconda, I entered conda in Powershell, this is what I got:

```<code>Traceback (most recent call last):
  File "C:\Users\Ruiyang\Anaconda2\Scripts\conda-script.py", line 3, in <module>
    import conda.cli
ImportError: No module named conda.cli
</code>```

Does anyone knows how to fix this?

答:
Though @devautor's method doesn't work for me, a comment in his reference shows me the correct answer:

Unset both PYTHONPATH and PYTHONHOME, then my problem is solved.

Title: Anaconda error after install on Windows

Body:
I want to install Anaconda on my x64 Windows machine, and I downloaded the Python 2.7 version 64-bit installer. The installation process looks good.

Then I installed pip with choco and installed several packages like zbar,
however, when I want to try to launch Anaconda, I entered conda in Powershell, this is what I got:

Traceback (most recent call last):
  File "C:\Users\Ruiyang\Anaconda2\Scripts\conda-script.py", line 3, in <module>
    import conda.cli
ImportError: No module named conda.cli

Does anyone knows how to fix this?


问:
Symfony: Service Container VS Static Method
Let's take this as example, I have a method call validateDateTime in a Validator class. This function is just simple as to check if the date time is in the required format.

```<code>namespace MyApp\Util;

use \DateTime;

class Validator {
    public static function validateDateTime($dateTime, $format = 'Y-m-d') {
        $d = DateTime::createFromFormat($format, $dateTime);
        return $d && $d->format($format) == $dateTime;
    }
}
</code>```

Before I learned Symfony, I always use static method for the ease of the use of function if the function has to be shared across the application.

After I have learned Symfony, I know that Symfony has a very power full feature which is service container to perform the same convenience to access the function that will be used across entire application.

My questions are:

What are the pros and cons of using static method vs service container

In Symfony best practice, is it recommended to use service container over static method if I want to achieve same purpose (Function that sharing across entire application).

In what situation, when and why, we need to use static method

Your comment and opinion are very much appreciated.

答:
Don't use static methods if you may need -in future- another implementation of the functionality you're writing. Static method are meant to be "static", not to be changed or extended.

Service "IoC" container is used to make your code easier to be changed or extended by decoupling components and inversing dependability between them, you can add new implementations or change existing ones without the need to do any changes to any dependent components.

Body:
Let's take this as example, I have a method call validateDateTime in a Validator class. This function is just simple as to check if the date time is in the required format.

namespace MyApp\Util;

use \DateTime;

class Validator {
    public static function validateDateTime($dateTime, $format = 'Y-m-d') {
        $d = DateTime::createFromFormat($format, $dateTime);
        return $d && $d->format($format) == $dateTime;
    }
}

Before I learned Symfony, I always use static method for the ease of the use of function if the function has to be shared across the application.

After I have learned Symfony, I know that Symfony has a very power full feature which is service container to perform the same convenience to access the function that will be used across entire application.

My questions are:

What are the pros and cons of using static method vs service container

In Symfony best practice, is it recommended to use service container over static method if I want to achieve same purpose (Function that sharing across entire application).

In what situation, when and why, we need to use static method

Your comment and opinion are very much appreciated.


问:
How to write a variable from jsp to html div after downloading file
I am trying to build a very simple application. There will be a password field. If an user enters wrong password, then a message will be shown "Password incorrect.". If the password is correct, then I have to do two tasks:

A file will be downloaded (suppose a.txt). The file resides in WEB-INF folder.

Show message "password is correct"

I tried to show the message in the following way :

```<code><div style="">
  <%=passwordMatchText%>
</div>
</code>```

When an user enters correct password, the file is downloaded but the text inside the div does not changes. It seems jsp does not write the value of the passwordMatchText inside the div. I have printed the text with system.out.print(); the text is printed correctly in console, but it is not written in the div correctly.

I have also tried to put the value in a session variable and write in the div. But none of them worked. How can i sovle the problem

```<code><%@ page trimDirectiveWhitespaces="true" %>
<%@ page language="java" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.io.FileOutputStream" %>
<%@ page import="java.io.File" %>

<%
    String header=request.getHeader("user-agent");
    String fileName="a.txt";

    String originalPassword="1";

    String passwordMatchText="";
    String passwordTextStyle="";

    String password = request.getParameter("password");

if(password==null  ||!password.equals(originalPassword)){
    passwordMatchText="Password does not match.";
    passwordTextStyle="color:red;";
}
    else {
        passwordMatchText="Password matched.";
        passwordTextStyle="color:green;";

        String baseFilePath = request.getServletContext().getRealPath("/") + "WEB-INF/" + fileName;

        File newFile= new File(baseFilePath);
        if(newFile.exists()){
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream inputStream = new FileInputStream(baseFilePath);
            int fileLength = inputStream.available();

            response.setContentType("application/octet-stream");
            response.setContentLength(fileLength);
            response.setHeader("Content-Disposition","attachment;filename=" + fileName);

            byte[] outputByte = new byte[4096];
            // copy binary content to output stream
            while (inputStream.read(outputByte, 0, 4096) != -1) {
                outputStream.write(outputByte, 0, 4096);
                //out.write(outputByte.toString());
            }

            inputStream.close();
            outputStream.flush();
            outputStream.close();

        }
        else {
            response.getWriter().println("File does not exists.");
        }

    }
%><!DOCTYPE HTML>
<html>
    <head>
        <html:base />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="GENERATOR" content="Microsoft FrontPage 5.0">
        <meta name="ProgId" content="FrontPage.Editor.Document">
        <meta name="viewport" content="width=device-width, initial-scale=1">

    </head>
    <body>
        <!-- header menu closed  -->
        <div > <!-- container for body -->
            <div  style="border:1px solid black;margin-top:10px;padding:10px;"> <!-- div for content -->
                <form  action="test2.jsp" method="POST">
                <div>

                        <div style=""><%=passwordMatchText%>
                        </div>
                    </div>

                    <div >
                        <div sytle ="width:100px">
                            Enter Password :
                        </div>
                        <div >
                            <input type="password" name="password" size="20" style="width: 100%;" />
                        </div>
                    </div>
                    <div >
                        <div >
                            <input class="cmd" type="submit" value="Submit" name="B2">
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <!-- body closed  -->

    </body>
</html>
</code>```

答:
This issue can solve to use auto submit. For example:</p>

```<code><%@ page trimDirectiveWhitespaces="true"%>
<%@ page language="java"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="java.io.FileInputStream"%>
<%@ page import="java.io.FileOutputStream"%>
<%@ page import="java.io.File"%>

<%
    String header = request.getHeader("user-agent");
            String fileName = "a.txt";

            String originalPassword = "1";

            String passwordMatchText = "";
            String passwordTextStyle = "";

            String password = request.getParameter("password");

            if ("".equals(password) && "val1".equals(request.getParameter("name1"))) {
                String baseFilePath = request.getServletContext().getRealPath("/") + "/WEB-INF/" + fileName;

                File newFile = new File(baseFilePath);
                if (newFile.exists()) {
                    ServletOutputStream outputStream = response.getOutputStream();
                    FileInputStream inputStream = new FileInputStream(baseFilePath);
                    int fileLength = inputStream.available();

                    response.setContentType("application/octet-stream");
                    response.setContentLength(fileLength);
                    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

                    byte[] outputByte = new byte[4096];
                    // copy binary content to output stream
                    while (inputStream.read(outputByte, 0, 4096) != -1) {
                        outputStream.write(outputByte, 0, 4096);
                        //out.write(outputByte.toString());
                    }

                    inputStream.close();
                    outputStream.flush();
                    outputStream.close();

                } else {
                    response.getWriter().println("File does not exists.");
                }
            } else if (password == null || !password.equals(originalPassword)) {
                passwordMatchText = "Password does not match.";
                passwordTextStyle = "color:red;";
            } else {
                passwordMatchText = "Password matched.";
                passwordTextStyle = "color:green;";

            }
%><!DOCTYPE HTML>
<html>
<head>
<html:base />
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="GENERATOR" content="Microsoft FrontPage 5.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>
    <!-- header menu closed  -->
    <div>
        <!-- container for body -->
        <div style="border: 1px solid black; margin-top: 10px; padding: 10px;">
            <!-- div for content -->
            <form name="test2form" action="test2.jsp" method="POST">
                <%
                    if (password != null && password.equals(originalPassword)) {
                %>
                <input type="hidden" name="name1" value="val1">
                <%
                    }
                %>

                <div>

                    <div style="<%=passwordTextStyle%>"><%=passwordMatchText%>
                    </div>
                </div>

                <div>
                    <div sytle="width:100px">Enter Password :</div>
                    <div>
                        <input type="password" name="password" size="20"
                            style="width: 100%;" />
                    </div>
                </div>
                <div>
                    <div>
                        <input class="cmd" type="submit" value="Submit" name="B2">
                    </div>
                </div>
            </form>
        </div>
    </div>
    <!-- body closed  -->

</body>
<%
    if (password != null && password.equals(originalPassword)) {
%>
<SCRIPT language="JavaScript">
    document.test2form.submit();
</SCRIPT>
<%
    }
%>
</code>```

Body:
I am trying to build a very simple application. There will be a password field. If an user enters wrong password, then a message will be shown "Password incorrect.". If the password is correct, then I have to do two tasks:

A file will be downloaded (suppose a.txt). The file resides in WEB-INF folder.

Show message "password is correct"

I tried to show the message in the following way :

  <%=passwordMatchText%>

When an user enters correct password, the file is downloaded but the text inside the div does not changes. It seems jsp does not write the value of the passwordMatchText inside the div. I have printed the text with system.out.print(); the text is printed correctly in console, but it is not written in the div correctly.

I have also tried to put the value in a session variable and write in the div. But none of them worked. How can i sovle the problem

<%@ page trimDirectiveWhitespaces="true" %>
<%@ page language="java" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.io.FileOutputStream" %>
<%@ page import="java.io.File" %>

<%
    String header=request.getHeader("user-agent");
    String fileName="a.txt";

    String originalPassword="1";

    String passwordMatchText="";
    String passwordTextStyle="";

    String password = request.getParameter("password");

if(password==null  ||!password.equals(originalPassword)){
    passwordMatchText="Password does not match.";
    passwordTextStyle="color:red;";
}
    else {
        passwordMatchText="Password matched.";
        passwordTextStyle="color:green;";

        String baseFilePath = request.getServletContext().getRealPath("/") + "WEB-INF/" + fileName;

        File newFile= new File(baseFilePath);
        if(newFile.exists()){
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream inputStream = new FileInputStream(baseFilePath);
            int fileLength = inputStream.available();

            response.setContentType("application/octet-stream");
            response.setContentLength(fileLength);
            response.setHeader("Content-Disposition","attachment;filename=" + fileName);

            byte[] outputByte = new byte[4096];
            // copy binary content to output stream
            while (inputStream.read(outputByte, 0, 4096) != -1) {
                outputStream.write(outputByte, 0, 4096);
                //out.write(outputByte.toString());
            }

            inputStream.close();
            outputStream.flush();
            outputStream.close();

        }
        else {
            response.getWriter().println("File does not exists.");
        }

    }
%><!DOCTYPE HTML>

        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="GENERATOR" content="Microsoft FrontPage 5.0">
        <meta name="ProgId" content="FrontPage.Editor.Document">
        <meta name="viewport" content="width=device-width, initial-scale=1">

                <form  action="test2.jsp" method="POST">

<%=passwordMatchText%>

                            Enter Password :

                            <input type="password" name="password" size="20" style="width: 100%;" />

                            <input class="cmd" type="submit" value="Submit" name="B2">

                </form>

Body:
This issue can solve to use auto submit. For example:

<%@ page trimDirectiveWhitespaces="true"%>
<%@ page language="java"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="java.io.FileInputStream"%>
<%@ page import="java.io.FileOutputStream"%>
<%@ page import="java.io.File"%>

<%
    String header = request.getHeader("user-agent");
            String fileName = "a.txt";

            String originalPassword = "1";

            String passwordMatchText = "";
            String passwordTextStyle = "";

            String password = request.getParameter("password");

            if ("".equals(password) && "val1".equals(request.getParameter("name1"))) {
                String baseFilePath = request.getServletContext().getRealPath("/") + "/WEB-INF/" + fileName;

                File newFile = new File(baseFilePath);
                if (newFile.exists()) {
                    ServletOutputStream outputStream = response.getOutputStream();
                    FileInputStream inputStream = new FileInputStream(baseFilePath);
                    int fileLength = inputStream.available();

                    response.setContentType("application/octet-stream");
                    response.setContentLength(fileLength);
                    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

                    byte[] outputByte = new byte[4096];
                    // copy binary content to output stream
                    while (inputStream.read(outputByte, 0, 4096) != -1) {
                        outputStream.write(outputByte, 0, 4096);
                        //out.write(outputByte.toString());
                    }

                    inputStream.close();
                    outputStream.flush();
                    outputStream.close();

                } else {
                    response.getWriter().println("File does not exists.");
                }
            } else if (password == null || !password.equals(originalPassword)) {
                passwordMatchText = "Password does not match.";
                passwordTextStyle = "color:red;";
            } else {
                passwordMatchText = "Password matched.";
                passwordTextStyle = "color:green;";

            }
%><!DOCTYPE HTML>
<html>
<head>
<html:base />
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="GENERATOR" content="Microsoft FrontPage 5.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>
    <!-- header menu closed  -->
    <div>
        <!-- container for body -->
        <div style="border: 1px solid black; margin-top: 10px; padding: 10px;">
            <!-- div for content -->
            <form name="test2form" action="test2.jsp" method="POST">
                <%
                    if (password != null && password.equals(originalPassword)) {
                %>
                <input type="hidden" name="name1" value="val1">
                <%
                    }
                %>

                <div>

                    <div style="<%=passwordTextStyle%>"><%=passwordMatchText%>
                    </div>
                </div>

                <div>
                    <div sytle="width:100px">Enter Password :</div>
                    <div>
                        <input type="password" name="password" size="20"
                            style="width: 100%;" />
                    </div>
                </div>
                <div>
                    <div>
                        <input class="cmd" type="submit" value="Submit" name="B2">
                    </div>
                </div>
            </form>
        </div>
    </div>
    <!-- body closed  -->

</body>
<%
    if (password != null && password.equals(originalPassword)) {
%>
<SCRIPT language="JavaScript">
    document.test2form.submit();
</SCRIPT>
<%
    }
%>


问:
having difficulties using setGravity with Toasts
I'm a complete noob learning my way through java.

I'm trying to use setGravity to push my Toast to the top of the page but having a lot of difficulties.

If i use the line Toast.setGravity (TOP, 30, 30); then TOP comes up as an error, I use Alt+Ent and it produces an import
import static android.view.Gravity.TOP;

This allows it to recognise TOP but then when i run it tells me that it cannot reference Gravity and Show() from static context.

I've also added import android.view.Gravity; but that just comes up as unused.

What am I doing wrong?

my code

答:
import android.view.Gravity;

import android.widget.Toast;

Try this

```<code>Toast t = Toast.makeText(this, "Your Message!!", Toast.LENGTH_SHORT);
t.setGravity(Gravity.TOP,30, 30);
t.show();
</code>```

Body:
import android.view.Gravity;

import android.widget.Toast;

Try this

Toast t = Toast.makeText(this, "Your Message!!", Toast.LENGTH_SHORT);
t.setGravity(Gravity.TOP,30, 30);
t.show();


问:
How to make excel only change some cell values when auto filling
I have a formula for calculating a sum based on dates.

```<code>=SUMIF('Daily Expense'!A:A,CONCATENATE("2/",B1,"/2017"),'Daily Expense'!B:B)
</code>```

Now I want all the columns of a row to have the same formula with only 1 change like

```<code>=SUMIF('Daily Expense'!A:A,CONCATENATE("2/",C1,"/2017"),'Daily Expense'!B:B)
</code>```

For the next column and D1 for the next one and so on.

When I use the auto fill method of dragging the mouse from the bottom right it fills the function and changes it to

```<code>=SUMIF('Daily Expense'!B:B,CONCATENATE("2/",C1,"/2017"),'Daily Expense'!C:C)
</code>```

All I want to change is the cell value in the concatenate function not the others.

Any idea how to do this?

答:
A:A is a relative reference which will update as you move the formula. You just need to change it to absolute, like $A:$A:

```<code>=SUMIF('Daily Expense'!$A:$A,CONCATENATE("2/",B1,"/2017"),'Daily Expense'!$B:$B)
</code>```

Now when you autofill it will only update the B1 reference.

Body:
I have a formula for calculating a sum based on dates.

=SUMIF('Daily Expense'!A:A,CONCATENATE("2/",B1,"/2017"),'Daily Expense'!B:B)

Now I want all the columns of a row to have the same formula with only 1 change like

=SUMIF('Daily Expense'!A:A,CONCATENATE("2/",C1,"/2017"),'Daily Expense'!B:B)

For the next column and D1 for the next one and so on.

When I use the auto fill method of dragging the mouse from the bottom right it fills the function and changes it to

=SUMIF('Daily Expense'!B:B,CONCATENATE("2/",C1,"/2017"),'Daily Expense'!C:C)

All I want to change is the cell value in the concatenate function not the others.

Any idea how to do this?

Body:
A:A is a relative reference which will update as you move the formula. You just need to change it to absolute, like $A:$A:

=SUMIF('Daily Expense'!$A:$A,CONCATENATE("2/",B1,"/2017"),'Daily Expense'!$B:$B)

Now when you autofill it will only update the B1 reference.


问:
Install Specific version of cassandra on ubuntu AWS
I want to install 3.0.10 version of cassandra on my EC2 instance. Basically I need to add a new instance to my existing cluster.

I have 3 nodes with 3.0.10 version installed.

When I try to attach new node to cluster the default installation steps installs 3.0.12 version. Then my instance goes in UJ state and never goes in UN state.

I am not finding any issues in the logs.

These are default steps for installation

```<code>1  sudo add-apt-repository ppa:webupd8team/java
    2  sudo apt-get update
    3  sudo apt-get install oracle-java8-installer
    4  echo "deb http://www.apache.org/dist/cassandra/debian 30x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list
    5  echo "deb-src http://www.apache.org/dist/cassandra/debian 30x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list
    6  gpg --keyserver pgp.mit.edu --recv-keys F758CE318D77295D
    7  gpg --export --armor F758CE318D77295D | sudo apt-key add -
    8  gpg --keyserver pgp.mit.edu --recv-keys 2B5C1B00
    9  gpg --export --armor 2B5C1B00 | sudo apt-key add -
   10  gpg --keyserver pgp.mit.edu --recv-keys 0353B12C
   11  gpg --export --armor 0353B12C | sudo apt-key add -
   12  sudo apt-get update
   13  sudo apt-get install cassandra=3.0.10
   14  sudo apt-key adv --keyserver pool.sks-keyservers.net --recv-key A278B781FE4B2BDA
   15  sudo apt-get install cassandra=3.0.10
   16  history

ubuntu@ip-172-31-15-65:~$ sudo apt-get install cassandra=3.0.10
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Version '3.0.10' for 'cassandra' was not found
</code>```

答:
Try Tarball installation

```<code>wget http://archive.apache.org/dist/cassandra/3.0.10/apache-cassandra-3.0.10-bin.tar.gz
tar -xvf apache-cassandra-3.0.10-bin.tar.gz
sudo rm -rf apache-cassandra-3.0.10-bin.tar.gz
cd apache-cassandra-3.0.10*
</code>```

Configure your cassandra.yaml in conf folder

then for starting cassandra execute(from cassandra home dir)

```<code>cd bin/
./cassandra
</code>```

or

```<code>cd bin/
sudo ./cassandra -R
</code>```

Body:
I want to install 3.0.10 version of cassandra on my EC2 instance. Basically I need to add a new instance to my existing cluster.

I have 3 nodes with 3.0.10 version installed.

When I try to attach new node to cluster the default installation steps installs 3.0.12 version. Then my instance goes in UJ state and never goes in UN state.

I am not finding any issues in the logs.

These are default steps for installation

1  sudo add-apt-repository ppa:webupd8team/java
    2  sudo apt-get update
    3  sudo apt-get install oracle-java8-installer
    4  echo "deb http://www.apache.org/dist/cassandra/debian 30x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list
    5  echo "deb-src http://www.apache.org/dist/cassandra/debian 30x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list
    6  gpg --keyserver pgp.mit.edu --recv-keys F758CE318D77295D
    7  gpg --export --armor F758CE318D77295D | sudo apt-key add -
    8  gpg --keyserver pgp.mit.edu --recv-keys 2B5C1B00
    9  gpg --export --armor 2B5C1B00 | sudo apt-key add -
   10  gpg --keyserver pgp.mit.edu --recv-keys 0353B12C
   11  gpg --export --armor 0353B12C | sudo apt-key add -
   12  sudo apt-get update
   13  sudo apt-get install cassandra=3.0.10
   14  sudo apt-key adv --keyserver pool.sks-keyservers.net --recv-key A278B781FE4B2BDA
   15  sudo apt-get install cassandra=3.0.10
   16  history

ubuntu@ip-172-31-15-65:~$ sudo apt-get install cassandra=3.0.10
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Version '3.0.10' for 'cassandra' was not found

Body:
Try Tarball installation

wget http://archive.apache.org/dist/cassandra/3.0.10/apache-cassandra-3.0.10-bin.tar.gz
tar -xvf apache-cassandra-3.0.10-bin.tar.gz
sudo rm -rf apache-cassandra-3.0.10-bin.tar.gz
cd apache-cassandra-3.0.10*

Configure your cassandra.yaml in conf folder

then for starting cassandra execute(from cassandra home dir)

cd bin/
./cassandra

or

cd bin/
sudo ./cassandra -R


问:
Is this method bad for using 2D coordinates as keys in std::unordered_map?
I need to store 2D coordinates as keys in a std::unordered_map.
I know that each component of a coordinate will not exceed 16bits.

Is it bad practice to merge a coordinate pair (x,y) to an uint32_t like this

```<code>uint32_t coordinate_id = (x << 16) | y;
</code>```

and use the coordinate_id as the "hash" for the map?
Or should I rather use a dedicated hash function to calculate the keys?
If I don't miss anything the method provided above will not lead to any collisions.

答:
Your approach will certainly work. It will even work, if components can exceed 16 bits: hashes are allowed to collide.

The problem here is that your hash is no better that identity function for integers. Changes to point coordinates will lead to easily predictable changes to hash. And if point coordinates follow some law, it is easy to accidently run into correlation between that law and bucket choosing algorithm.

Imagine if unordered_map created 100 buckets and places items in buckets depending on two last digits of hash. And you have points with y-coordinate evenly divisible by 100. All of your ponts will go to the same bucket, defeating purpose of hash table!

Body:
I need to store 2D coordinates as keys in a std::unordered_map.
I know that each component of a coordinate will not exceed 16bits.

Is it bad practice to merge a coordinate pair (x,y) to an uint32_t like this

uint32_t coordinate_id = (x << 16) | y;

and use the coordinate_id as the "hash" for the map?
Or should I rather use a dedicated hash function to calculate the keys?
If I don't miss anything the method provided above will not lead to any collisions.