问:
sort dataFrame index containing string and number
I have a dataframe where the index value is a mixture of string and number separated by an underscore.

```<code>    sub_int1_ICA_int2  #
</code>```

I would like to sort the column index using int1 first and after that int2
The expected output would be:

```<code>    sub_1_ICA_1
    sub_1_ICA_2
    sub_1_ICA_3
    ...........
    sub_2_ICA_1
    sub_2_ICA_2
    ...........
</code>```

I tried to use convert_numeric as I saw in many posts, but I get an error

```<code>     X.convert_objects(convert_numeric=True).sort_values(['id] , ascending=[True], inplace=True)
    >>(KeyError: 'id')
</code>```

Any help would be nice!

答:
Use reindex by sorted list by custom function with dictionary of tuples:

```<code>print (df)
              a
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_2_ICA_1   1
sub_2_ICA_2   3

a = df.index.tolist()
b = {}
for x in a:
    i = x.split('_')
    b[x] = ((int(i[1]), int(i[-1])))
print (b)
{'sub_1_ICA_10': (1, 10), 'sub_1_ICA_11': (1, 11),
'sub_1_ICA_1': (1, 1), 'sub_2_ICA_2': (2, 2),
 'sub_1_ICA_0': (1, 0), 'sub_1_ICA_12': (1, 12),
 'sub_1_ICA_3': (1, 3), 'sub_1_ICA_2': (1, 2),
 'sub_2_ICA_1': (2, 1)}

c = sorted(a, key=lambda x: b[x])
print (c)
['sub_1_ICA_0', 'sub_1_ICA_1', 'sub_1_ICA_2', 'sub_1_ICA_3',
'sub_1_ICA_10', 'sub_1_ICA_11', 'sub_1_ICA_12', 'sub_2_ICA_1', 'sub_2_ICA_2']
</code>```

```<code>df = df.reindex(c)
print (df)
              a
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_2_ICA_1   1
sub_2_ICA_2   3
</code>```

Another pure pandas solution:

```<code>#create MultiIndex by split index, convert to DataFrame
df1 = df.index.str.split('_', expand=True).to_frame()
#set columns and index to original df
df1.columns = list('abcd')
df1.index = df.index
#convert columns to int and sort
df1[['b','d']] = df1[['b','d']].astype(int)
df1 = df1.sort_values(['b','d'])
print (df1)
                a  b    c   d
sub_1_ICA_0   sub  1  ICA   0
sub_1_ICA_1   sub  1  ICA   1
sub_1_ICA_2   sub  1  ICA   2
sub_1_ICA_3   sub  1  ICA   3
sub_1_ICA_10  sub  1  ICA  10
sub_1_ICA_11  sub  1  ICA  11
sub_1_ICA_12  sub  1  ICA  12
sub_2_ICA_1   sub  2  ICA   1
sub_2_ICA_2   sub  2  ICA   2

df = df.reindex(df1.index)
print (df)
              a
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_2_ICA_1   1
sub_2_ICA_2   3
</code>```

And last version with natsort:

```<code>from natsort import natsorted

df = df.reindex(natsorted(df.index))
print (df)
              a
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_2_ICA_1   1
sub_2_ICA_2   3
</code>```

EDIT:

If duplicates values then create new columns by split, convert to int, sort and get back:

```<code>print (df)
              a
sub_1_ICA_0   4
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_2_ICA_1   1
sub_2_ICA_2   3

df.index = df.index.str.split('_', expand=True)
df = df.reset_index()
df[['level_1','level_3']] = df[['level_1','level_3']].astype(int)
df = df.sort_values(['level_1','level_3']).astype(str)

df = df.set_index(['level_0','level_1','level_2','level_3'])
df.index = df.index.map('_'.join)

print (df)

              a
sub_1_ICA_0   4
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_2_ICA_1   1
sub_2_ICA_2   3
</code>```

Body:
I have a dataframe where the index value is a mixture of string and number separated by an underscore.

    sub_int1_ICA_int2  #

I would like to sort the column index using int1 first and after that int2
The expected output would be:

    sub_1_ICA_1
    sub_1_ICA_2
    sub_1_ICA_3
    ...........
    sub_2_ICA_1
    sub_2_ICA_2
    ...........

I tried to use convert_numeric as I saw in many posts, but I get an error

     X.convert_objects(convert_numeric=True).sort_values(['id] , ascending=[True], inplace=True)
    >>(KeyError: 'id')

Any help would be nice!

Body:
Use reindex by sorted list by custom function with dictionary of tuples:

print (df)
              a
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_2_ICA_1   1
sub_2_ICA_2   3

a = df.index.tolist()
b = {}
for x in a:
    i = x.split('_')
    b[x] = ((int(i[1]), int(i[-1])))
print (b)
{'sub_1_ICA_10': (1, 10), 'sub_1_ICA_11': (1, 11),
'sub_1_ICA_1': (1, 1), 'sub_2_ICA_2': (2, 2),
 'sub_1_ICA_0': (1, 0), 'sub_1_ICA_12': (1, 12),
 'sub_1_ICA_3': (1, 3), 'sub_1_ICA_2': (1, 2),
 'sub_2_ICA_1': (2, 1)}

c = sorted(a, key=lambda x: b[x])
print (c)
['sub_1_ICA_0', 'sub_1_ICA_1', 'sub_1_ICA_2', 'sub_1_ICA_3',
'sub_1_ICA_10', 'sub_1_ICA_11', 'sub_1_ICA_12', 'sub_2_ICA_1', 'sub_2_ICA_2']

df = df.reindex(c)
print (df)
              a
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_2_ICA_1   1
sub_2_ICA_2   3

Another pure pandas solution:

#create MultiIndex by split index, convert to DataFrame
df1 = df.index.str.split('_', expand=True).to_frame()
#set columns and index to original df
df1.columns = list('abcd')
df1.index = df.index
#convert columns to int and sort
df1[['b','d']] = df1[['b','d']].astype(int)
df1 = df1.sort_values(['b','d'])
print (df1)
                a  b    c   d
sub_1_ICA_0   sub  1  ICA   0
sub_1_ICA_1   sub  1  ICA   1
sub_1_ICA_2   sub  1  ICA   2
sub_1_ICA_3   sub  1  ICA   3
sub_1_ICA_10  sub  1  ICA  10
sub_1_ICA_11  sub  1  ICA  11
sub_1_ICA_12  sub  1  ICA  12
sub_2_ICA_1   sub  2  ICA   1
sub_2_ICA_2   sub  2  ICA   2

df = df.reindex(df1.index)
print (df)
              a
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_2_ICA_1   1
sub_2_ICA_2   3

And last version with natsort:

from natsort import natsorted

df = df.reindex(natsorted(df.index))
print (df)
              a
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_2_ICA_1   1
sub_2_ICA_2   3

EDIT:

If duplicates values then create new columns by split, convert to int, sort and get back:

print (df)
              a
sub_1_ICA_0   4
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_2_ICA_1   1
sub_2_ICA_2   3

df.index = df.index.str.split('_', expand=True)
df = df.reset_index()
df[['level_1','level_3']] = df[['level_1','level_3']].astype(int)
df = df.sort_values(['level_1','level_3']).astype(str)

df = df.set_index(['level_0','level_1','level_2','level_3'])
df.index = df.index.map('_'.join)

print (df)

              a
sub_1_ICA_0   4
sub_1_ICA_0   4
sub_1_ICA_1   8
sub_1_ICA_2   6
sub_1_ICA_3   6
sub_1_ICA_10  7
sub_1_ICA_11  3
sub_1_ICA_12  2
sub_2_ICA_1   1
sub_2_ICA_2   3


来源: stackexchange

问:
If I wanted to change $_GET to $_POST in this code What would I do?
I can't seem to figure out how to post this instead of using get, I've found that you have to use a form but that's about it.
If anyone is willing to provide an answer that'd be awesome!
Thank you!!!!
.............................................................................................................................................................</p>

```<code><!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
<title>Portfolio Max</title>

<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>

  <div class= "header">
    <h1 id= "textinheader">Portfolio</h1></div>
    <div class= "portfolio text"> </div>

    <div class="menu">
        <a href="?page=1">pagina 1</a>
        <a href="?page=2">pagina2</a>
        <div class="dropdown">
          <button class="dropbutton">Meer
            <i class="down"></i>
          </button>
          <div class="dropdown-content">
            <a href="?page=3">pagina 3</a>
            <a href="?page=4">pagina 4</a>
            <a href="?page=5">pagina 5</a>
          </div>
        </div>
      </div>

    <?php  echo date("Y/M/D h:i:sa");?>

    </div>

   <?php

   /*
   if( $_GET ['page'] == '1')
   include 'page1.php';
   else
   include 'page2.php';
   */
  if (! isset($_GET ['page']))
  $_GET = array_merge( $_GET, array('page'=>1));

  include 'page'.$_GET ['page'].'.php';

   ?>

    </div>

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

答:
some pseudo code.</p>

```<code>$("a").click(function){
var  query_string=$(this).attr("href");
//Iam lazy to write query string parser. Google or write yourself.
var obj = querystring_parser_to_key_value(query_string);
$form = $('<form method="POST" action=""></form>');
$.each( obj, function( key, value ) {
  $form.append('<input type="hidden" name="'+key+'" value="'+value+'">');
});
  $form.submit();
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I can't seem to figure out how to post this instead of using get, I've found that you have to use a form but that's about it.
If anyone is willing to provide an answer that'd be awesome!
Thank you!!!!
.............................................................................................................................................................

<!DOCTYPE html>

 <meta charset="UTF-8">
<title>Portfolio Max</title>

<link rel="stylesheet" type="text/css" href="./style.css">

Portfolio

        pagina 1
        pagina2

          <button class="dropbutton">Meer

          </button>

            pagina 3
            pagina 4
            pagina 5

    <?php  echo date("Y/M/D h:i:sa");?>

   <?php

   /*
   if( $_GET ['page'] == '1')
   include 'page1.php';
   else
   include 'page2.php';
   */
  if (! isset($_GET ['page']))
  $_GET = array_merge( $_GET, array('page'=>1));

  include 'page'.$_GET ['page'].'.php';

   ?>

c

Body:
some pseudo code.

$("a").click(function){
var  query_string=$(this).attr("href");
//Iam lazy to write query string parser. Google or write yourself.
var obj = querystring_parser_to_key_value(query_string);
$form = $('<form method="POST" action=""></form>');
$.each( obj, function( key, value ) {
  $form.append('<input type="hidden" name="'+key+'" value="'+value+'">');
});
  $form.submit();
});


问:
How to insert a zero instead of a NULL in oracle?
How to insert 0 in place of null?

Is this correct

```<code>INSERT INTO TEMP(ID,NAME) SELECT ID,NVL(NAME,0) FROM TEST;
</code>```

答:
You can use any of the option below.

Using NVL()

```<code>SELECT ID
    ,NVL(NAME, 0)
FROM TEST;
</code>```

Using ANSI standard coalesce()

```<code>SELECT ID
    ,coalesce(NAME, '0')
FROM TEST;
</code>```

Using CASE

```<code>SELECT ID
    ,CASE
        WHEN NAME IS NOT NULL
            THEN NAME
        ELSE '0'
        END
FROM TEST;
</code>```

DEMO

ContentLicense: CC BY-SA 4.0

Body:
How to insert 0 in place of null?

Is this correct

INSERT INTO TEMP(ID,NAME) SELECT ID,NVL(NAME,0) FROM TEST;

Body:
You can use any of the option below.

Using NVL()

SELECT ID
    ,NVL(NAME, 0)
FROM TEST;

Using ANSI standard coalesce()

SELECT ID
    ,coalesce(NAME, '0')
FROM TEST;

Using CASE

SELECT ID
    ,CASE
        WHEN NAME IS NOT NULL
            THEN NAME
        ELSE '0'
        END
FROM TEST;

DEMO


问:
Using case in a aggregate sql query without splitting rows
In ms-sql i am using an aggregate group to filter results by user, i would also like to use case to filter by a row not contained in the aggregate so all the user results are on 1 line. I'm not sure this is possible.

Here is the query below which splits the results into two lines.

```<code>select case  when col_A='1' then sum(col b) End as Sum1_results,
case  when col_A='2' then sum(col_b) End as Sum2_Results, Username from tbl1
group by Username, col_A
</code>```

example of results is.

```<code>Sum1_results | Sum2_results | Username

 5499          null           John
 null          3400           John
</code>```

Ideally, i would like to just have these results merged into one line for each username if possible.
Any help would be appreciated

答:
Results merged into one line for each username.

Create table #tmp (col_A CHAR(1),col_b int,Username VARCHAR(10))

```<code>INSERT INTO #tmp VALUES('1',5000,'John')
INSERT INTO #tmp VALUES('2',400,'John')
INSERT INTO #tmp VALUES('1',499,'John')
INSERT INTO #tmp VALUES('2',3000,'John')

SELECT * FROM #tmp

select SUM(case when col_A='1' then col_b End) as Sum1_results,
     SUM(case when col_A='2' then col_b End) as Sum2_Results,Username
from #tmp

group by UserName

DROP TABLE #tmp
</code>```

Body:
In ms-sql i am using an aggregate group to filter results by user, i would also like to use case to filter by a row not contained in the aggregate so all the user results are on 1 line. I'm not sure this is possible.

Here is the query below which splits the results into two lines.

select case  when col_A='1' then sum(col b) End as Sum1_results,
case  when col_A='2' then sum(col_b) End as Sum2_Results, Username from tbl1
group by Username, col_A

example of results is.

Sum1_results | Sum2_results | Username

 5499          null           John
 null          3400           John

Ideally, i would like to just have these results merged into one line for each username if possible.
Any help would be appreciated

Body:
Results merged into one line for each username.

Create table #tmp (col_A CHAR(1),col_b int,Username VARCHAR(10))

INSERT INTO #tmp VALUES('1',5000,'John')
INSERT INTO #tmp VALUES('2',400,'John')
INSERT INTO #tmp VALUES('1',499,'John')
INSERT INTO #tmp VALUES('2',3000,'John')

SELECT * FROM #tmp

select SUM(case when col_A='1' then col_b End) as Sum1_results,
     SUM(case when col_A='2' then col_b End) as Sum2_Results,Username
from #tmp

group by UserName

DROP TABLE #tmp


问:
System.Data.Entity.Core.MetadataException when deployed
This post seems to be here a few more than a few times but I have gone through all of those and adjusted the code to have the true DLL name but still get the Unable to load the specified metadata resource error.

Now what comes the interesting part, this code works on the machine it was developed on in VS but does not work on any other machines or live version. I am not sure if this has anything to do with it.

Here is the Connection String - (Sources/Pass have been replaced with *)

```<code><add name="RMUplistEntities" connectionString="metadata=res://RM.Data/DataEntities.Model1.csdl|res://RM.Data/DataEntities.Model1.ssdl|res://RM.Data/DataEntities.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=*;initial catalog=RMUplist;user id=*;password=*;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</code>```

This is the stack trace

```<code>Exception stack trace:
  at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.LoadResource () [0x00016] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.CreateReader () [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.CreateReaders (System.Data.Entity.Core.Metadata.Edm.DataSpace spaceToGet) [0x0001c] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderComposite.CreateReaders (System.Data.Entity.Core.Metadata.Edm.DataSpace spaceToGet) [0x0001b] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataCache.LoadEdmItemCollection (System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoader loader) [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataCache+<>c__DisplayClass5.<GetMetadataWorkspace>b__0 (System.String k) [0x0000d] in <000f54522ad145bf987b3043022f9799>:0
  at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) [0x00034] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/external/corefx/src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs:1035
  at System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetMetadataWorkspace (System.String cacheKey, System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoader artifactLoader) [0x0000d] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetMetadataWorkspace (System.Data.Entity.Core.EntityClient.Internal.DbConnectionOptions effectiveConnectionOptions) [0x0001f] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.EntityClient.EntityConnection.GetMetadataWorkspace () [0x0000f] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection () [0x00014] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Objects.ObjectContext..ctor (System.Data.Entity.Core.EntityClient.EntityConnection connection, System.Boolean isConnectionConstructor, System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory, System.Data.Entity.Core.Common.Internal.Materialization.Translator translator, System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory columnMapFactory) [0x000ea] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Objects.ObjectContext..ctor (System.Data.Entity.Core.EntityClient.EntityConnection connection) [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.InternalConnection.CreateObjectContextFromConnectionModel () [0x00006] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel () [0x00006] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.LazyInternalContext.InitializeContext () [0x0007c] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.InternalContext.Initialize () [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType (System.Type entityType) [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.Linq.InternalSet`1[TEntity].Initialize () [0x0000e] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.Linq.InternalSet`1[TEntity].get_InternalContext () [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Infrastructure.DbQuery`1[TResult].System.Linq.IQueryable.get_Provider () [0x00016] in <000f54522ad145bf987b3043022f9799>:0
  at System.Linq.Queryable.Where[TSource] (System.Linq.IQueryable`1[T] source, System.Linq.Expressions.Expression`1[TDelegate] predicate) [0x0001c] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/external/corefx/src/System.Linq.Queryable/src/System/Linq/Queryable.cs:39
  at RM.UpList.Controllers.HomeController.DailyRotation (System.Nullable`1[T] date) [0x00099] in /*/RMUplist-master/RM.UpList/Controllers/HomeController.cs:109
  at (wrapper dynamic-method) System.Object:lambda_method (System.Runtime.CompilerServices.Closure,System.Web.Mvc.ControllerBase,object[])
  at System.Web.Mvc.ActionMethodDispatcher.Execute (System.Web.Mvc.ControllerBase controller, System.Object[] parameters) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ReflectedActionDescriptor.Execute (System.Web.Mvc.ControllerContext controllerContext, System.Collections.Generic.IDictionary`2[TKey,TValue] parameters) [0x00072] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod (System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionDescriptor actionDescriptor, System.Collections.Generic.IDictionary`2[TKey,TValue] parameters) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+ActionInvocation.InvokeSynchronousActionMethod () [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39 (System.IAsyncResult asyncResult, System.Web.Mvc.Async.AsyncControllerActionInvoker+ActionInvocation innerInvokeState) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at (wrapper delegate-invoke) System.Web.Mvc.Async.EndInvokeDelegate`2[System.Web.Mvc.Async.AsyncControllerActionInvoker+ActionInvocation,System.Web.Mvc.ActionResult]:invoke_TResult_IAsyncResult_TState (System.IAsyncResult,System.Web.Mvc.Async.AsyncControllerActionInvoker/ActionInvocation)
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResult`2[TResult,TState].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d () [0x00014] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+AsyncInvocationWithFilters+<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f () [0x00086] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32 (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResult`1[TResult].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+<>c__DisplayClass21+<>c__DisplayClass2b.<BeginInvokeAction>b__1c () [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+<>c__DisplayClass21.<BeginInvokeAction>b__1e (System.IAsyncResult asyncResult) [0x00041] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResult`1[TResult].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d (System.IAsyncResult asyncResult, System.Web.Mvc.Controller+ExecuteCoreState innerState) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at (wrapper delegate-invoke) System.Web.Mvc.Async.EndInvokeVoidDelegate`1[System.Web.Mvc.Controller+ExecuteCoreState]:invoke_void_IAsyncResult_TState (System.IAsyncResult,System.Web.Mvc.Controller/ExecuteCoreState)
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncVoid`1[TState].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End (System.IAsyncResult asyncResult, System.Object tag) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Controller.EndExecuteCore (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Controller.<BeginExecute>b__15 (System.IAsyncResult asyncResult, System.Web.Mvc.Controller controller) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncVoid`1[TState].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End (System.IAsyncResult asyncResult, System.Object tag) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Controller.EndExecute (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5 (System.IAsyncResult asyncResult, System.Web.Mvc.MvcHandler+ProcessRequestState innerState) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at (wrapper delegate-invoke) System.Web.Mvc.Async.EndInvokeVoidDelegate`1[System.Web.Mvc.MvcHandler+ProcessRequestState]:invoke_void_IAsyncResult_TState (System.IAsyncResult,System.Web.Mvc.MvcHandler/ProcessRequestState)
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncVoid`1[TState].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End (System.IAsyncResult asyncResult, System.Object tag) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.MvcHandler.EndProcessRequest (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest (System.IAsyncResult result) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.HttpApplication.async_handler_complete_cb (System.IAsyncResult ar) [0x00015] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/System.Web/System.Web/HttpApplication.cs:988
</code>```

答:
This error happens if you have the EDMX in one project and you are using it from another project and the later in not able to load the EDMX files.

Have you tried changing your conenctionstring to

```<code>connectionString="metadata=res://*/;
</code>```

There are also a lot of other possible causes for this. You can google around. This post has a lot of possible solutions.

Body:
This post seems to be here a few more than a few times but I have gone through all of those and adjusted the code to have the true DLL name but still get the Unable to load the specified metadata resource error.

Now what comes the interesting part, this code works on the machine it was developed on in VS but does not work on any other machines or live version. I am not sure if this has anything to do with it.

Here is the Connection String - (Sources/Pass have been replaced with *)

<add name="RMUplistEntities" connectionString="metadata=res://RM.Data/DataEntities.Model1.csdl|res://RM.Data/DataEntities.Model1.ssdl|res://RM.Data/DataEntities.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=*;initial catalog=RMUplist;user id=*;password=*;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

This is the stack trace

Exception stack trace:
  at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.LoadResource () [0x00016] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.CreateReader () [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.CreateReaders (System.Data.Entity.Core.Metadata.Edm.DataSpace spaceToGet) [0x0001c] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderComposite.CreateReaders (System.Data.Entity.Core.Metadata.Edm.DataSpace spaceToGet) [0x0001b] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataCache.LoadEdmItemCollection (System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoader loader) [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataCache+<>c__DisplayClass5.<GetMetadataWorkspace>b__0 (System.String k) [0x0000d] in <000f54522ad145bf987b3043022f9799>:0
  at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) [0x00034] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/external/corefx/src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs:1035
  at System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetMetadataWorkspace (System.String cacheKey, System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoader artifactLoader) [0x0000d] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetMetadataWorkspace (System.Data.Entity.Core.EntityClient.Internal.DbConnectionOptions effectiveConnectionOptions) [0x0001f] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.EntityClient.EntityConnection.GetMetadataWorkspace () [0x0000f] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection () [0x00014] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Objects.ObjectContext..ctor (System.Data.Entity.Core.EntityClient.EntityConnection connection, System.Boolean isConnectionConstructor, System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory, System.Data.Entity.Core.Common.Internal.Materialization.Translator translator, System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory columnMapFactory) [0x000ea] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Core.Objects.ObjectContext..ctor (System.Data.Entity.Core.EntityClient.EntityConnection connection) [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.InternalConnection.CreateObjectContextFromConnectionModel () [0x00006] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel () [0x00006] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.LazyInternalContext.InitializeContext () [0x0007c] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.InternalContext.Initialize () [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType (System.Type entityType) [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.Linq.InternalSet`1[TEntity].Initialize () [0x0000e] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Internal.Linq.InternalSet`1[TEntity].get_InternalContext () [0x00000] in <000f54522ad145bf987b3043022f9799>:0
  at System.Data.Entity.Infrastructure.DbQuery`1[TResult].System.Linq.IQueryable.get_Provider () [0x00016] in <000f54522ad145bf987b3043022f9799>:0
  at System.Linq.Queryable.Where[TSource] (System.Linq.IQueryable`1[T] source, System.Linq.Expressions.Expression`1[TDelegate] predicate) [0x0001c] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/external/corefx/src/System.Linq.Queryable/src/System/Linq/Queryable.cs:39
  at RM.UpList.Controllers.HomeController.DailyRotation (System.Nullable`1[T] date) [0x00099] in /*/RMUplist-master/RM.UpList/Controllers/HomeController.cs:109
  at (wrapper dynamic-method) System.Object:lambda_method (System.Runtime.CompilerServices.Closure,System.Web.Mvc.ControllerBase,object[])
  at System.Web.Mvc.ActionMethodDispatcher.Execute (System.Web.Mvc.ControllerBase controller, System.Object[] parameters) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ReflectedActionDescriptor.Execute (System.Web.Mvc.ControllerContext controllerContext, System.Collections.Generic.IDictionary`2[TKey,TValue] parameters) [0x00072] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod (System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionDescriptor actionDescriptor, System.Collections.Generic.IDictionary`2[TKey,TValue] parameters) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+ActionInvocation.InvokeSynchronousActionMethod () [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39 (System.IAsyncResult asyncResult, System.Web.Mvc.Async.AsyncControllerActionInvoker+ActionInvocation innerInvokeState) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at (wrapper delegate-invoke) System.Web.Mvc.Async.EndInvokeDelegate`2[System.Web.Mvc.Async.AsyncControllerActionInvoker+ActionInvocation,System.Web.Mvc.ActionResult]:invoke_TResult_IAsyncResult_TState (System.IAsyncResult,System.Web.Mvc.Async.AsyncControllerActionInvoker/ActionInvocation)
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResult`2[TResult,TState].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d () [0x00014] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+AsyncInvocationWithFilters+<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f () [0x00086] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32 (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResult`1[TResult].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+<>c__DisplayClass21+<>c__DisplayClass2b.<BeginInvokeAction>b__1c () [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker+<>c__DisplayClass21.<BeginInvokeAction>b__1e (System.IAsyncResult asyncResult) [0x00041] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResult`1[TResult].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d (System.IAsyncResult asyncResult, System.Web.Mvc.Controller+ExecuteCoreState innerState) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at (wrapper delegate-invoke) System.Web.Mvc.Async.EndInvokeVoidDelegate`1[System.Web.Mvc.Controller+ExecuteCoreState]:invoke_void_IAsyncResult_TState (System.IAsyncResult,System.Web.Mvc.Controller/ExecuteCoreState)
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncVoid`1[TState].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End (System.IAsyncResult asyncResult, System.Object tag) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Controller.EndExecuteCore (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Controller.<BeginExecute>b__15 (System.IAsyncResult asyncResult, System.Web.Mvc.Controller controller) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncVoid`1[TState].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End (System.IAsyncResult asyncResult, System.Object tag) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Controller.EndExecute (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5 (System.IAsyncResult asyncResult, System.Web.Mvc.MvcHandler+ProcessRequestState innerState) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at (wrapper delegate-invoke) System.Web.Mvc.Async.EndInvokeVoidDelegate`1[System.Web.Mvc.MvcHandler+ProcessRequestState]:invoke_void_IAsyncResult_TState (System.IAsyncResult,System.Web.Mvc.MvcHandler/ProcessRequestState)
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncVoid`1[TState].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.Async.AsyncResultWrapper.End (System.IAsyncResult asyncResult, System.Object tag) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.MvcHandler.EndProcessRequest (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest (System.IAsyncResult result) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0
  at System.Web.HttpApplication.async_handler_complete_cb (System.IAsyncResult ar) [0x00015] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/System.Web/System.Web/HttpApplication.cs:988

Body:
This error happens if you have the EDMX in one project and you are using it from another project and the later in not able to load the EDMX files.

Have you tried changing your conenctionstring to

connectionString="metadata=res://*/;

There are also a lot of other possible causes for this. You can google around. This post has a lot of possible solutions.


问:
error when pushing branch into github - 'remote: error: cannot lock ref 'refs/heads/master': Unable to create'
I get the below exception when I try to push my local branch into master

```<code>Total 0 (delta 0), reused 0 (delta 0)
remote: error: cannot lock ref 'refs/heads/master': Unable to create '/data/c01/n08/p/vp0664/data/d-41/r-27032041/refs/heads/master.lock': File exists.
remote:
remote: If no other git process is currently running, this probably means a
remote: git process crashed in this repository earlier. Make sure no other git
remote: process is running and remove the file manually to continue.
</code>```

I get this exception only when pushing the master branch.

I get this exception when pushing the master branch even from other computers.

I get this exception even when I try to merge dev branch into master on bitbucket website directly not involving the local computer.

Because of the above 3 reasons I don't think it is a issue with my local .git folder. I can't think of what the possible cause is.

I have tried solutions available in answers to similar exceptions, but all of them are about cleaning/purging/manipulating the files in the .git folder but I get this same issue even from different computers and even on the bitbucket portal itself.

Please vote for the issue, if you are hitting it as well.

PS: I am using the bitbucket.org cloud hosted option.

答:
Indeed, this problem is not with your computer, it is with the server.  This error message is actually coming from your Git server (note the prefix remote to the message, this indicates that the error originates on the server.)

If this was your own server with its own Git installation, I would advise you to make sure that there is no long-running Git process doing work and - if there wasn't - removing the lock file it's referring to since a process had indeed crashed.

Since you're running Bitbucket, however, it's probably best to ask them for support instead of changing things on the server directly.

Body:
I get the below exception when I try to push my local branch into master

Total 0 (delta 0), reused 0 (delta 0)
remote: error: cannot lock ref 'refs/heads/master': Unable to create '/data/c01/n08/p/vp0664/data/d-41/r-27032041/refs/heads/master.lock': File exists.
remote:
remote: If no other git process is currently running, this probably means a
remote: git process crashed in this repository earlier. Make sure no other git
remote: process is running and remove the file manually to continue.

I get this exception only when pushing the master branch.

I get this exception when pushing the master branch even from other computers.

I get this exception even when I try to merge dev branch into master on bitbucket website directly not involving the local computer.

Because of the above 3 reasons I don't think it is a issue with my local .git folder. I can't think of what the possible cause is.

I have tried solutions available in answers to similar exceptions, but all of them are about cleaning/purging/manipulating the files in the .git folder but I get this same issue even from different computers and even on the bitbucket portal itself.

Please vote for the issue, if you are hitting it as well.

PS: I am using the bitbucket.org cloud hosted option.


问:
Why it loads neg samples(40*40) too slowly when I using opencv_traincascade.exe?
Why it loads neg samples(40*40) too slowly when I using opencv_traincascade.exe? It may toke 1-2 minutes to load a neg samples.

答:
It's not just loading a single negative sample within that time, it is the collection of negative samples that are still classified as positive samples, so the new training stage can go and find features that distinguish your positive samples from those negative samples. With each stage, your classifier gets better and better and more negative samples are already classified correctly, the harder it gets to find negative samples that are usable in that training stage. After enough negative samples are collected, you'll see a value (acceptanceRatio) which shows you the rate of usable negative samples found.

For example, here is a stage preparation from a training I had once:

The acceptance ratio is 3.03652e-005 which means the negative samples collection had to test in average 32932.4 negative samples to find a single USABLE negative sample. Yes, this takes a long time (especially if the classifier gets more "complicated"). The more different negative sample pictures you use, typically the easier it gets to find usable samples. If you've chosen for example max false alarm rate of 0.5, in theory you'll have to double the number of negative images tested in each stage. This is also an indicator of how well your training is working. If the acceptance ratio doesn't go down in each stage, the training is probably not working well, it does not look like it is generalizing well.


问:
I cannot get Google Sign In integrated
```<code>import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;`enter code here`
import android.widget.Button;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInApi;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;

public class CreateUserAccount extends AppCompatActivity {
    @Override
    protected void onStart() {
        super.onStart();
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_user_account);

// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        final GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        SignInButton signInBtn = findViewById(R.id.sign_in_button);
        signInBtn.setOnClickListener(new View.OnClickListener() {

            private void signIn() {
                Intent signInIntent = mGoogleSignInClient.getSignInIntent();
                startActivityForResult(signInIntent, RC_SIGN_IN);
            }

            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.sign_in_button:
                        signIn();
                        break;
                    // ...

                }
            }

            });

        }
    }
</code>```

I followed the steps on https://developers.google.com/identity/sign-in/android/sign-in, but still no luck.

I want to get it to prompt the 'Sign in with google' window, and then return me an Email Address (Or an 'account' object).

答:
I believe you have not handled this function:

```<code> @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        handleSignInResult(task);
    }
}
</code>```

See examples.

Title: I cannot get Google Sign In integrated

Body:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;`enter code here`
import android.widget.Button;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInApi;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;

public class CreateUserAccount extends AppCompatActivity {
    @Override
    protected void onStart() {
        super.onStart();
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_user_account);

// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        final GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        SignInButton signInBtn = findViewById(R.id.sign_in_button);
        signInBtn.setOnClickListener(new View.OnClickListener() {

            private void signIn() {
                Intent signInIntent = mGoogleSignInClient.getSignInIntent();
                startActivityForResult(signInIntent, RC_SIGN_IN);
            }

            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.sign_in_button:
                        signIn();
                        break;
                    // ...

                }
            }

            });

        }
    }

I followed the steps on https://developers.google.com/identity/sign-in/android/sign-in, but still no luck.

I want to get it to prompt the 'Sign in with google' window, and then return me an Email Address (Or an 'account' object).

Body:
I believe you have not handled this function:

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        handleSignInResult(task);
    }
}

See examples.


问:
Assignment of data-member in read-only structure, class in STL set
The minimal example of the problem I'm having is reproduced below:

```<code>#include <set>
using namespace std;

class foo {
public:
  int value, x;
  foo(const int & in_v) {
   value = in_v;
   x = 0;
  }
  bool operator<(const foo & rhs) const {
   return value < rhs.value;
 }
};

int main() {
  foo y(3);
  set<foo> F;
  F.insert(y);

  // Now try to modify a member of the set
  F.begin()->x=1;
  return 0;
}
</code>```

With the error error: assignment of data-member ‘foo::value’ in read-only structure. I feel like I'm missing something simple here, but why am I unable to modify the member x in my class?

答:
Given that the "x" variable is not involved in the less-than comparison, it would be safe in this case to make "x" mutable, allowing you to modify it from within the set.  Your class definition would then become:

```<code>class foo {
public:
  int value;
  mutable int x;

  foo(const int & in_v) : value(in_v), x(0) { }
  bool operator<(const foo & rhs) const {
    return value < rhs.value;
  }
};
</code>```

And you can now use it in the std::set and modify x as you like.  In this case it is pointless to keep two copies of the data structure as the previous poster has suggested.

ContentLicense: CC BY-SA 2.5

Body:
The minimal example of the problem I'm having is reproduced below:

#include <set>
using namespace std;

class foo {
public:
  int value, x;
  foo(const int & in_v) {
   value = in_v;
   x = 0;
  }
  bool operator<(const foo & rhs) const {
   return value < rhs.value;
 }
};

int main() {
  foo y(3);
  set<foo> F;
  F.insert(y);

  // Now try to modify a member of the set
  F.begin()->x=1;
  return 0;
}

With the error error: assignment of data-member ‘foo::value’ in read-only structure. I feel like I'm missing something simple here, but why am I unable to modify the member x in my class?

Body:
Given that the "x" variable is not involved in the less-than comparison, it would be safe in this case to make "x" mutable, allowing you to modify it from within the set.  Your class definition would then become:

class foo {
public:
  int value;
  mutable int x;

  foo(const int & in_v) : value(in_v), x(0) { }
  bool operator<(const foo & rhs) const {
    return value < rhs.value;
  }
};

And you can now use it in the std::set and modify x as you like.  In this case it is pointless to keep two copies of the data structure as the previous poster has suggested.


问:
Why does Subject.doAs return the principal based on the logged in user instead of the switched subject?
I am trying to convert an existing api from a web application that was previously deployed in bea weblogic. I need to deploy this application now in JBoss EAP 7.

In my user login code, I am doing servlet authentication like so:

```<code>HttpServletRequest request = ServletActionContext.getRequest();
request.login("user1", "password");

testEJB= (TestEJB) LookupUtil.lookup("TestEJB");
System.out.println("logged in user: " + testEJB.getName()); //returns user1
</code>```

Now the sessionContext in every EJB looked up by the container returns the logged in user, which is perfect except that some app functions need to switch user and do some privileged actions e.g. uploading of document.

I am switching user and performing the privileged action like so:

```<code>LoginContext loginContext = new LoginContext("TestLoginContext", new UsernamePasswordHandler("user2", "password"));
loginContext.login();
String newUser = (String) Subject.doAs(loginContext.getSubject(), new TestPrivilegedAction());
System.out.println("privileged User: " + newUser); //still returns user1
</code>```

In my TestPrivilegedAction which implements PrivilegedAction, I have the following codes:

```<code>@Override
public Object run() {
    return this.getSwitchedUser();
}

private Object getSwitchedUser() {
    testEJB= (TestEJB) LookupUtil.lookup("TestEJB");
    System.out.println("logged in user: " + testEJB.getName());
}
</code>```

Basically, the original api used when the app was deployed in weblogic are:

```<code>Authenticate.authenticate
Security.runAs
</code>```

...then I replaced it with the following to make it work in JBoss:

```<code>LoginContext.login
Subject.doAs
</code>```

So why now it still returns the logged in user (user1), even though the authentication succeeded and the subject is already set to user2? Ive been searching the web and trying to see if Im just missing some configurations but i'm really stuck with this now. I appreciate any feedback or suggestions.

答:
After some time experimenting on the available APIs, I finally was able to solve my problem. I just want to put it here, just in case other people run into the same issue.

Basically, I reinvented the existing api used for weblogic server:

```<code>Authenticate.authenticate
Security.runAs
</code>```

Here is my Authenticate class:

```<code>public class Authenticate {

    private static Subject originalSubject = null;

    public static void authenticate(Hashtable env, Subject subject) throws LoginException {
        try {
            //retrieve the security context that contains the current subject (logged in user)
            SecurityContext securityContext = SecurityContextAssociation.getSecurityContext();
            SubjectInfo subjectInfo = securityContext.getSubjectInfo();

            //set the current subject as the original subject
            originalSubject = subjectInfo.getAuthenticatedSubject();

            //start authentication of the new subject
            CallbackHandler callbackHandler = new UsernamePasswordHandler((String) env.get(Context.SECURITY_PRINCIPAL), env.get(Context.SECURITY_CREDENTIALS));
            LoginContext loginContext = new LoginContext("JbossLoginContext", callbackHandler);
            loginContext.login();

            //set the new subject information to perform the privileged action
            subject.getPrincipals().addAll(loginContext.getSubject().getPrincipals());
            subjectInfo.setAuthenticatedSubject(loginContext.getSubject());
        } catch (LoginException e) {
            throw new LoginException();
        } catch (Exception e) {
            throw new Exception();
        }
    }

    public static void setOriginalSubject() {
        try {
            //if the login method is already invoked, replace the current subject with the original subject
            if(originalSubject != null) {
                SecurityContextAssociation.getSecurityContext().getSubjectInfo().setAuthenticatedSubject(originalSubject);
            }
        } catch (Exception e) {
            throw new Exception();
        }
    }
}
</code>```

I created a wrapper class for the Subject.doAs which doesn't have the function to switch back the original subject. Here is how I did it:

```<code>public class Security {

    public static Object runAs(Subject subject, PrivilegedAction privilegedAction) {
        try {
            Object object = Subject.doAs(subject, privilegedAction);
            Authenticate.setOriginalSubject();
            return object;
        } catch (Exception e) {
            throw new Exception();
        }
    }
}
</code>```

Now, notice that I still use the Subject.doAs method, then I call the Authenticate.setOriginalSubject to set the original subject back.

Everything works and I almost only had to update the package imports in the class files that use it.

Body:
I am trying to convert an existing api from a web application that was previously deployed in bea weblogic. I need to deploy this application now in JBoss EAP 7.

In my user login code, I am doing servlet authentication like so:

HttpServletRequest request = ServletActionContext.getRequest();
request.login("user1", "password");

testEJB= (TestEJB) LookupUtil.lookup("TestEJB");
System.out.println("logged in user: " + testEJB.getName()); //returns user1

Now the sessionContext in every EJB looked up by the container returns the logged in user, which is perfect except that some app functions need to switch user and do some privileged actions e.g. uploading of document.

I am switching user and performing the privileged action like so:

LoginContext loginContext = new LoginContext("TestLoginContext", new UsernamePasswordHandler("user2", "password"));
loginContext.login();
String newUser = (String) Subject.doAs(loginContext.getSubject(), new TestPrivilegedAction());
System.out.println("privileged User: " + newUser); //still returns user1

In my TestPrivilegedAction which implements PrivilegedAction, I have the following codes:

@Override
public Object run() {
    return this.getSwitchedUser();
}

private Object getSwitchedUser() {
    testEJB= (TestEJB) LookupUtil.lookup("TestEJB");
    System.out.println("logged in user: " + testEJB.getName());
}

Basically, the original api used when the app was deployed in weblogic are:

Authenticate.authenticate
Security.runAs

...then I replaced it with the following to make it work in JBoss:

LoginContext.login
Subject.doAs

So why now it still returns the logged in user (user1), even though the authentication succeeded and the subject is already set to user2? Ive been searching the web and trying to see if Im just missing some configurations but i'm really stuck with this now. I appreciate any feedback or suggestions.

Body:
After some time experimenting on the available APIs, I finally was able to solve my problem. I just want to put it here, just in case other people run into the same issue.

Basically, I reinvented the existing api used for weblogic server:

Authenticate.authenticate
Security.runAs

Here is my Authenticate class:

public class Authenticate {

    private static Subject originalSubject = null;

    public static void authenticate(Hashtable env, Subject subject) throws LoginException {
        try {
            //retrieve the security context that contains the current subject (logged in user)
            SecurityContext securityContext = SecurityContextAssociation.getSecurityContext();
            SubjectInfo subjectInfo = securityContext.getSubjectInfo();

            //set the current subject as the original subject
            originalSubject = subjectInfo.getAuthenticatedSubject();

            //start authentication of the new subject
            CallbackHandler callbackHandler = new UsernamePasswordHandler((String) env.get(Context.SECURITY_PRINCIPAL), env.get(Context.SECURITY_CREDENTIALS));
            LoginContext loginContext = new LoginContext("JbossLoginContext", callbackHandler);
            loginContext.login();

            //set the new subject information to perform the privileged action
            subject.getPrincipals().addAll(loginContext.getSubject().getPrincipals());
            subjectInfo.setAuthenticatedSubject(loginContext.getSubject());
        } catch (LoginException e) {
            throw new LoginException();
        } catch (Exception e) {
            throw new Exception();
        }
    }

    public static void setOriginalSubject() {
        try {
            //if the login method is already invoked, replace the current subject with the original subject
            if(originalSubject != null) {
                SecurityContextAssociation.getSecurityContext().getSubjectInfo().setAuthenticatedSubject(originalSubject);
            }
        } catch (Exception e) {
            throw new Exception();
        }
    }
}

I created a wrapper class for the Subject.doAs which doesn't have the function to switch back the original subject. Here is how I did it:

public class Security {

    public static Object runAs(Subject subject, PrivilegedAction privilegedAction) {
        try {
            Object object = Subject.doAs(subject, privilegedAction);
            Authenticate.setOriginalSubject();
            return object;
        } catch (Exception e) {
            throw new Exception();
        }
    }
}

Now, notice that I still use the Subject.doAs method, then I call the Authenticate.setOriginalSubject to set the original subject back.

Everything works and I almost only had to update the package imports in the class files that use it.


问:
Is polymer routing suitable for large scale website?
I have one big project which contains different layouts and structures (it is like 100 different pages), but the core elements are the same (like header and menus). I would like to use javascript frameworks, so I found polymer. In polymer there is <iron-ajax>. Is it suit for my requirements?

答:
Answer could be yes. You can use all of the modern framerworks/libraries like Angular, React, Polymer and so on.

If you want to develop in Polymer big website, you will have to take care of few things. Otherwise your website will be very slow.

First, lazy load necessary elements for the current screen.

Second, build process (minify, uglify)

Third, service workers

These thing are important if you will do them right, your application will be very fast. For example, I have an administration with more than 30 screens and it's going very well (I didn't find any problem with the size of the website)

Another thing is routing. I am using page.js , because I like it's routing instead of app-route where it is a little bit confusing (at least for me).

You asked something about iron-ajax. I don't understand why are you asking just for this element? this one is used to call XHTTP requests on your server. It's a great element if you get used to it.

Polymer is very easy to use (propably the easiest one of the mentioned frameworks above) and has many elements already built and ready to use with nice documentation. If you really want to develop your website in Polymer, use version 2.x. DO NOT TRY TO USE 1.x (it will become obsolete and unsupported in browsers soon)


问:
Laravel validation checkbox
I am using the laravel register function to register a user. I added a checkbox where the user needs to accept the terms and conditions. I only want the user to register when the checkbox is checked. Can I use the 'required' validation in laravel? This is my validation function:

```<code> return Validator::make($data, [
        'firstName' => 'required|max:255',
        'lastName' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|confirmed|min:6',
        'checkbox' =>'required',
    ]);
</code>```

When I use the function like this, laravel gives the required error for the checkbox even if it is checked.

This is the html of the checkbox

```<code><input type="checkbox" name="checkbox" id="option" value="{{old('option')}}"><label for="option"><span></span> <p>Ik ga akkoord met de <a href="#">algemene voorwaarden</a></p></label>
</code>```

I hope you guys can help me!

答:
I just had a big frustration, because the code i'm using returns the checkbox value as a boolean value.

If you have a similar situation you can use the following rule:

```<code>[
 'checkbox_field' => 'required|in:1',
]
</code>```

Title: Laravel validation checkbox

Body:
I am using the laravel register function to register a user. I added a checkbox where the user needs to accept the terms and conditions. I only want the user to register when the checkbox is checked. Can I use the 'required' validation in laravel? This is my validation function:

 return Validator::make($data, [
        'firstName' => 'required|max:255',
        'lastName' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|confirmed|min:6',
        'checkbox' =>'required',
    ]);

When I use the function like this, laravel gives the required error for the checkbox even if it is checked.

This is the html of the checkbox

<input type="checkbox" name="checkbox" id="option" value="{{old('option')}}">
Ik ga akkoord met de algemene voorwaarden

I hope you guys can help me!

Body:
I just had a big frustration, because the code i'm using returns the checkbox value as a boolean value.

If you have a similar situation you can use the following rule:

[
 'checkbox_field' => 'required|in:1',
]


问:
query total reduced by percent
Hey guys I have some query problem. I want to reduced my total with percentage but this code give me some error:

```<code>SELECT `id_sewa`,`nama_villa`,DATE_FORMAT(`tgl_transaksi`, '%d-%m-%Y'),`nama_tamu`,`cek_in`,`cek_out`, datediff(`cek_out`,`cek_in`) as rn,format(`harga`, 0),format(datediff(`cek_out`,`cek_in`) *`harga`, 0)as total,`ref`,
(
CASE
WHEN ref = "direct" THEN format(datediff(`cek_out`,`cek_in`) * `harga`, 0) - 10%
END) AS total_bersih

from sewa_villa
where tgl_transaksi BETWEEN '2017-11-12' and '2017-11-14';
</code>```

My expectation:

total
ref
total bersih

2,000,000
direct
1,800,000

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

<p>This the error:</p>

```1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') AS total_bersih
from sewa_villa where tgl_transaksi BETWEEN '2017-11-12' and ' at line 6
```

答:
The problem is your "-10%" :

```<code>SELECT `id_sewa`,`nama_villa`,DATE_FORMAT(`tgl_transaksi`, '%d-%m-%Y'),`nama_tamu`,`cek_in`,`cek_out`, datediff(`cek_out`,`cek_in`) as rn,format(`harga`, 0),format(datediff(`cek_out`,`cek_in`) *`harga`, 0)as total,`ref`,
(
CASE
WHEN ref = "direct" THEN format(datediff(`cek_out`,`cek_in`) * `harga`, 0) *0.9
END) AS total_bersih

from sewa_villa
where tgl_transaksi BETWEEN '2017-11-12' and '2017-11-14';
</code>```

Just a note : you didn't put any else in the case/when, are your sure about it ?

Title: query total reduced by percent

Body:
Hey guys I have some query problem. I want to reduced my total with percentage but this code give me some error:

SELECT `id_sewa`,`nama_villa`,DATE_FORMAT(`tgl_transaksi`, '%d-%m-%Y'),`nama_tamu`,`cek_in`,`cek_out`, datediff(`cek_out`,`cek_in`) as rn,format(`harga`, 0),format(datediff(`cek_out`,`cek_in`) *`harga`, 0)as total,`ref`,
(
CASE
WHEN ref = "direct" THEN format(datediff(`cek_out`,`cek_in`) * `harga`, 0) - 10%
END) AS total_bersih

from sewa_villa
where tgl_transaksi BETWEEN '2017-11-12' and '2017-11-14';

My expectation:

total
ref
total bersih

2,000,000
direct
1,800,000

This the error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') AS total_bersih
from sewa_villa where tgl_transaksi BETWEEN '2017-11-12' and ' at line 6

Body:
The problem is your "-10%" :

SELECT `id_sewa`,`nama_villa`,DATE_FORMAT(`tgl_transaksi`, '%d-%m-%Y'),`nama_tamu`,`cek_in`,`cek_out`, datediff(`cek_out`,`cek_in`) as rn,format(`harga`, 0),format(datediff(`cek_out`,`cek_in`) *`harga`, 0)as total,`ref`,
(
CASE
WHEN ref = "direct" THEN format(datediff(`cek_out`,`cek_in`) * `harga`, 0) *0.9
END) AS total_bersih

from sewa_villa
where tgl_transaksi BETWEEN '2017-11-12' and '2017-11-14';

Just a note : you didn't put any else in the case/when, are your sure about it ?


问:
Call a method from a child view
I'm trying to make some changes to the code a colleague made.

So, I have a ShellView that loads documents (and shows them as its content) with a method defined in its ViewModel, and the child view, a StatusBarView which holds the path navigated in the documents and some other infos.

```<code>public class ShellViewModel
{
    public StatusBarViewModel StatusBar { get; }

    public ShellViewModel(StatusBarViewModel statusBarViewModel, ...)
    {
        StatusBar = statusBarViewModel;

        var keymap = new Keymap();
        keymap.Map("F2", new SimpleCommand("open-file",
                                           "Shows the open file dialog",
                                            param => OpenFile());

    }

    private void OpenFile()
    {
        // Logic to open the file that uses other methods
        // inside this VM to validate the file
    }
}
</code>```

At the moment you can load a new pack of documents pressing a key, I'd like to do the same with a button in the Status Bar and calling that method.

What is the proper way to call a method existing in the parent view from the child view?

答:
There are many ways. First need to analyze your purpose.
- You can create an ActionEvent or EventHandler inside childview and on button click you can raise that event.
- Another way use can use Mediator pattern/Observer pattern

Example:
Inside child ViewModel:

```<code>public event EventHandler openFileEvent;
</code>```

Inside click button action on status bar:

```<code>private void btnClick()
{
  if(null != openFileEvent)
  {
     openFileEvent(this, new EventArgs{});
  }
}
</code>```

Inside Parent ViewModel:

```<code>statusBarViewModel.openFileEvent += new EventHandler(EventHandlerName);

private void EventHandlerName(objehct sender, EventArgs...)
{
   ...
   OpenFile();
   ...
}
</code>```

Title: Call a method from a child view

Body:
I'm trying to make some changes to the code a colleague made.

So, I have a ShellView that loads documents (and shows them as its content) with a method defined in its ViewModel, and the child view, a StatusBarView which holds the path navigated in the documents and some other infos.

public class ShellViewModel
{
    public StatusBarViewModel StatusBar { get; }

    public ShellViewModel(StatusBarViewModel statusBarViewModel, ...)
    {
        StatusBar = statusBarViewModel;

        var keymap = new Keymap();
        keymap.Map("F2", new SimpleCommand("open-file",
                                           "Shows the open file dialog",
                                            param => OpenFile());

    }

    private void OpenFile()
    {
        // Logic to open the file that uses other methods
        // inside this VM to validate the file
    }
}

At the moment you can load a new pack of documents pressing a key, I'd like to do the same with a button in the Status Bar and calling that method.

What is the proper way to call a method existing in the parent view from the child view?

Body:
There are many ways. First need to analyze your purpose.
- You can create an ActionEvent or EventHandler inside childview and on button click you can raise that event.
- Another way use can use Mediator pattern/Observer pattern

Example:
Inside child ViewModel:

public event EventHandler openFileEvent;

Inside click button action on status bar:

private void btnClick()
{
  if(null != openFileEvent)
  {
     openFileEvent(this, new EventArgs{});
  }
}

Inside Parent ViewModel:

statusBarViewModel.openFileEvent += new EventHandler(EventHandlerName);

private void EventHandlerName(objehct sender, EventArgs...)
{
   ...
   OpenFile();
   ...
}


问:
Uncaught (in promise) DOMException: Quota exceeded
I am trying to see the demo of offline status  from the below link and I get DOMException: Quota exceeded.

https://serviceworke.rs/offline-status_demo.html

This error occurs only in chrome. It works fine in firefox without error in firefox.

The error occurs in the install event of the service worker.
Code from the service worker in posted below for reference.

// /serviceworker-cookbook/offline-status/

var CACHE_NAME = 'dependencies-cache';

// Files required to make this app work offline
var REQUIRED_FILES = [
  'random-1.png',
  'random-2.png',
  'random-3.png',
  'random-4.png',
  'random-5.png',
  'random-6.png',
  'style.css',
  'index.html',
  'index.js',
  'app.js'
];

self.addEventListener('install', function(event) {
  // Perform install step:  loading each required file into cache
  event.waitUntil(  // Error occurs here... Why???
    caches.open(CACHE_NAME)
      .then(function(cache) {
        // Add all offline dependencies to the cache
        console.log('[install] Caches opened, adding all core components' +
          'to cache');
        return cache.addAll(REQUIRED_FILES);
      })
      .then(function() {
        console.log('[install] All required resources have been cached, ' +
          'we\'re good!');
        return self.skipWaiting();
      })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return the response from the cached version
        if (response) {
          console.log(
            '[fetch] Returning from ServiceWorker cache: ',
            event.request.url
          );
          return response;
        }

        // Not in cache - return the result from the live server
        // `fetch` is essentially a "fallback"
        console.log('[fetch] Returning from server: ', event.request.url);
        return fetch(event.request);
      }
    )
  );
});

self.addEventListener('activate', function(event) {
  console.log('[activate] Activating ServiceWorker!');

  // Calling claim() to force a "controllerchange" event on navigator.serviceWorker
  console.log('[activate] Claiming this ServiceWorker!');
  event.waitUntil(self.clients.claim());
});```

How to rectify this error? Is there a way to increase the quota limit in chrome?

EDIT1:

This link says that the Chrome checks quota limit per origin whereas firefox has unlimited quota.

Is there a way to delete all the files cached from the origin (reset to original state) ?

答:
The offline-status_demo downloads merely 700kb and hence can't exceed the 5MB Chrome quota limit on its own. Unless Chrome Cache is already full - as would be the case if you have too many open tabs.

Answer: try again in incognito mode.

Body:
I am trying to see the demo of offline status  from the below link and I get DOMException: Quota exceeded.

https://serviceworke.rs/offline-status_demo.html

This error occurs only in chrome. It works fine in firefox without error in firefox.

The error occurs in the install event of the service worker.
Code from the service worker in posted below for reference.

// /serviceworker-cookbook/offline-status/

var CACHE_NAME = 'dependencies-cache';

// Files required to make this app work offline
var REQUIRED_FILES = [
  'random-1.png',
  'random-2.png',
  'random-3.png',
  'random-4.png',
  'random-5.png',
  'random-6.png',
  'style.css',
  'index.html',
  'index.js',
  'app.js'
];

self.addEventListener('install', function(event) {
  // Perform install step:  loading each required file into cache
  event.waitUntil(  // Error occurs here... Why???
    caches.open(CACHE_NAME)
      .then(function(cache) {
        // Add all offline dependencies to the cache
        console.log('[install] Caches opened, adding all core components' +
          'to cache');
        return cache.addAll(REQUIRED_FILES);
      })
      .then(function() {
        console.log('[install] All required resources have been cached, ' +
          'we\'re good!');
        return self.skipWaiting();
      })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return the response from the cached version
        if (response) {
          console.log(
            '[fetch] Returning from ServiceWorker cache: ',
            event.request.url
          );
          return response;
        }

        // Not in cache - return the result from the live server
        // `fetch` is essentially a "fallback"
        console.log('[fetch] Returning from server: ', event.request.url);
        return fetch(event.request);
      }
    )
  );
});

self.addEventListener('activate', function(event) {
  console.log('[activate] Activating ServiceWorker!');

  // Calling claim() to force a "controllerchange" event on navigator.serviceWorker
  console.log('[activate] Claiming this ServiceWorker!');
  event.waitUntil(self.clients.claim());
});

How to rectify this error? Is there a way to increase the quota limit in chrome?

EDIT1:

This link says that the Chrome checks quota limit per origin whereas firefox has unlimited quota.

Is there a way to delete all the files cached from the origin (reset to original state) ?


问:
Get the label text from a custom checkbox with javascript in WooCommerce checkout
I am adding some little piece of javascript on woocommerce checkout page for the checkbox which can copy the text box value to another.

But it is not working.

Here is the code that I use:

```<code>add_action('woocommerce_before_checkout_form', 'cw_custom_checkbox_fields');
function cw_custom_checkbox_fields( $checkout ) {

    woocommerce_form_field( 'custom_checkbox', array(
        'type'          => 'checkbox',

        'label'         => __('Check if both addresses are same'),
        'required'  => false,
    ), $checkout->get_value( 'custom_checkbox' ));

    ?>
        <script type="text/javascript">
            var allgenders = document.getElementsByName("custom_checkbox");

        </script>
    <?php
}
</code>```

What I am doing wrong and how can I get the text from the checkbox label?

答:
You should better try this, getting the text label value (and the checked property of the checkbox) using jQuery:

```<code>add_action('woocommerce_before_checkout_form', 'cw_custom_checkbox_fields');
function cw_custom_checkbox_fields( $checkout ) {

    woocommerce_form_field( 'custom_checkbox', array(
        'type'          => 'checkbox',
        'label'         => __('Check if both addresses are same'),
        'required'  => false,
    ), $checkout->get_value( 'custom_checkbox' ));

    ?>
        <script type="text/javascript">
            jQuery(function($){
                var allgenders = $('p#custom_checkbox_field > label').text(),
                    checkedValue;
                console.log('Label text: '+allgenders); // Output the label text in browser console (for test)

                // optionally get the checked value of the checkbox
                $('input[name^="custom_checkbox"]').click(function(){
                    checkedValue = $(this).prop('checked'); // Get the checked value
                    console.log('Is checked: '+checkedValue); // Output checked value in console browser in browser console (for test)
                })
            });
        </script>
    <?php
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…

Body:
I am adding some little piece of javascript on woocommerce checkout page for the checkbox which can copy the text box value to another.

But it is not working.

Here is the code that I use:

add_action('woocommerce_before_checkout_form', 'cw_custom_checkbox_fields');
function cw_custom_checkbox_fields( $checkout ) {

    woocommerce_form_field( 'custom_checkbox', array(
        'type'          => 'checkbox',

        'label'         => __('Check if both addresses are same'),
        'required'  => false,
    ), $checkout->get_value( 'custom_checkbox' ));

    ?>

    <?php
}

What I am doing wrong and how can I get the text from the checkbox label?

Body:
You should better try this, getting the text label value (and the checked property of the checkbox) using jQuery:

add_action('woocommerce_before_checkout_form', 'cw_custom_checkbox_fields');
function cw_custom_checkbox_fields( $checkout ) {

    woocommerce_form_field( 'custom_checkbox', array(
        'type'          => 'checkbox',
        'label'         => __('Check if both addresses are same'),
        'required'  => false,
    ), $checkout->get_value( 'custom_checkbox' ));

    ?>
        <script type="text/javascript">
            jQuery(function($){
                var allgenders = $('p#custom_checkbox_field > label').text(),
                    checkedValue;
                console.log('Label text: '+allgenders); // Output the label text in browser console (for test)

                // optionally get the checked value of the checkbox
                $('input[name^="custom_checkbox"]').click(function(){
                    checkedValue = $(this).prop('checked'); // Get the checked value
                    console.log('Is checked: '+checkedValue); // Output checked value in console browser in browser console (for test)
                })
            });
        </script>
    <?php
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…


问:
How to connect two Foreign Key Fields
I have a model called Part that looks like this:

```<code>class Part(model.Model) =
    some attributes...
    uses = models.ForeignKey('self', null = True, blank = True, on_delete = models.SET_NULL, limit_choices_to={'used_in' : None}, related_name = 'part_uses')
    used_in = models.ForeignKey('self', null = True, blank = True, on_delete = models.SET_NULL, related_name = 'device_used_in')
</code>```

One Part can use or/and be used_in another Part, but I need to know which of them it is, to be able to show this in the DetailView. In other words, it's not enough to know that there is some kind of relationship between two Parts, I need to know which  kind  of relationship. (Thus the two different fields).
Now, I want to update uses in one object, when another is set to used_in, e.g.: if a.uses(b) I want to automatically set b.used_in(a).

I did this by setting it manually in the form_valid method of my UpdateView --> for example, if a.uses is changed, look for b and change its used_in.

For example:

```<code>if 'used_in' in form.changed_data:
    if self.object.used_in:
        other_device = Device.objects.filter(pk= self.object.used_in.pk)[0]
        other_device.uses = self.object
        other_device.save()
</code>```

However, this has several disadvantages. First of all, I don't really like having to do this manually and was wondering whether this could not be done some other way, but I didn't find anything on Google. The second problem is that one Part can use several other Parts, but with my method, only the last Part that was used is shown.

My question is: Is it somehow possible to connect the two foreign keys inside the model, or shift to only one foreign key, or do this in some other way that makes sense.

答:
If you want to create parent child relation in same table. There is no need to create two field, as used_in field is referencing the same object you are updating.

UPDATE

Suppose there are 4 objects of Part class.

```<code># first part
>>> part1 = Part.objects.create(name="car engine")
# second part
>>> part2 = Part.objects.create(name="Spark plug")
# third part
>>> part3 = Part.objects.create(name="Piston")
# fourth part
>>> part4 = Part.objects.create(name="Piston rings")

# mark part1 uses part2 and part3.
>>> part2.used_in = part1
>>> part2.save()
>>> part3.used_in = part1
>>> part3.save()

# find parts used in part1.
>>> Part.objects.filter(used_in=part1)

# find part3 is child of which part.
>>> part3.used_in

# mark part3 uses part4
>>> part4.used_in = part3
>>> part4.save()
# this means part1 uses part3 and part3 using part4
</code>```

You can remove uses field and make use of just used_in field.

Title: How to connect two Foreign Key Fields

Body:
I have a model called Part that looks like this:

class Part(model.Model) =
    some attributes...
    uses = models.ForeignKey('self', null = True, blank = True, on_delete = models.SET_NULL, limit_choices_to={'used_in' : None}, related_name = 'part_uses')
    used_in = models.ForeignKey('self', null = True, blank = True, on_delete = models.SET_NULL, related_name = 'device_used_in')

One Part can use or/and be used_in another Part, but I need to know which of them it is, to be able to show this in the DetailView. In other words, it's not enough to know that there is some kind of relationship between two Parts, I need to know which  kind  of relationship. (Thus the two different fields).
Now, I want to update uses in one object, when another is set to used_in, e.g.: if a.uses(b) I want to automatically set b.used_in(a).

I did this by setting it manually in the form_valid method of my UpdateView --> for example, if a.uses is changed, look for b and change its used_in.

For example:

if 'used_in' in form.changed_data:
    if self.object.used_in:
        other_device = Device.objects.filter(pk= self.object.used_in.pk)[0]
        other_device.uses = self.object
        other_device.save()

However, this has several disadvantages. First of all, I don't really like having to do this manually and was wondering whether this could not be done some other way, but I didn't find anything on Google. The second problem is that one Part can use several other Parts, but with my method, only the last Part that was used is shown.

My question is: Is it somehow possible to connect the two foreign keys inside the model, or shift to only one foreign key, or do this in some other way that makes sense.

Body:
If you want to create parent child relation in same table. There is no need to create two field, as used_in field is referencing the same object you are updating.

UPDATE

Suppose there are 4 objects of Part class.

# first part
>>> part1 = Part.objects.create(name="car engine")
# second part
>>> part2 = Part.objects.create(name="Spark plug")
# third part
>>> part3 = Part.objects.create(name="Piston")
# fourth part
>>> part4 = Part.objects.create(name="Piston rings")

# mark part1 uses part2 and part3.
>>> part2.used_in = part1
>>> part2.save()
>>> part3.used_in = part1
>>> part3.save()

# find parts used in part1.
>>> Part.objects.filter(used_in=part1)

# find part3 is child of which part.
>>> part3.used_in

# mark part3 uses part4
>>> part4.used_in = part3
>>> part4.save()
# this means part1 uses part3 and part3 using part4

You can remove uses field and make use of just used_in field.


问:
WPF tab order with custom controls?
I have a WPF page that contains several out of the box controls with the tab order set.

I have a custom control (NumericSpinner) that contains: border/grid/text box/2 Repeatbuttons (up/down).

Two issues:

1) when I am in the textbox for the custom selector control, I cannot tab out of it to other controls on the page.  However after clicking on one of the up/down arrows, I am able to tab over to other controls.

2) I am unable to tab into the textbox of the custom control in order.  It is only after I have tabbed through all of the controls, that the cursor lands in the text box (and cannot tab out).

Context:

```<code><ComboBox Margin="97,315,21,0" Name="txtdweldatcdu" Style="{StaticResource fieldComboBoxStyle}" IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Left" VerticalAlignment="Top" TabIndex="10" />
    <WpfControls:NumericSpinner Margin="97,338,21,0" Name="txtdweldatpctcomplete" HorizontalAlignment="Left" VerticalAlignment="Top" AllowNegativeValues="True" MaxValue="100" TabIndex="11" />
    <ComboBox Margin="97,363,21,0" Name="txtdweldatclass" Style="{StaticResource fieldComboBoxStyle}" IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Left" VerticalAlignment="Top" TabIndex="12" />
</code>```

Portion of the custom control:

```<code> <Border BorderThickness="1" BorderBrush="Gray" Margin="0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="20" Width="117">
        <Grid Margin="0">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="98"/>
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <TextBox Name="valueText"
                     BorderThickness="0"
                     Grid.RowSpan="2"
                     Style="{StaticResource spinnerTextBoxStyle}"
                     PreviewKeyDown="valueText_PreviewKeyDown"
                     PreviewTextInput="valueText_PreviewTextInput"
                     TextChanged="valueText_TextChanged"
                     IsReadOnly="{Binding ElementName=Spinner, Path=IsReadOnly}"
                     Text="{Binding ElementName=Spinner, Path=Value, Mode=TwoWay}"
                     KeyboardNavigation.IsTabStop="True"
                     AcceptsTab="True"/>
            <RepeatButton Name="upButton" Style="{StaticResource spinnerRepeatButtonStyle}" Click="upButton_Click"  Grid.Column="1" Grid.Row="0" Height="10" Width="18" VerticalAlignment="Top" HorizontalAlignment="Right" HorizontalContentAlignment="Center">
                <Polygon  HorizontalAlignment="Center" Points="3,2 2,3 4,3"  Fill="Black"  Stretch="Uniform"  Stroke="Black"  StrokeThickness="0" />
            </RepeatButton>
            <RepeatButton Name="downButton" Style="{StaticResource spinnerRepeatButtonStyle}" Click="downButton_Click"  Grid.Column="1" Grid.Row="1" Height="10" Width="18" VerticalAlignment="Top" HorizontalAlignment="Right" HorizontalContentAlignment="Center">
                <Polygon  HorizontalAlignment="Center" Points="2,2 4,2 3,3"  Fill="Black"  Stretch="Uniform"  Stroke="Black"  StrokeThickness="0" />
            </RepeatButton>
        </Grid>
    </Border>
</code>```

The custom control consists of the xaml and code-behind file.

Parent xaml page, containing all controls is loaded dynamically and contains no code-behind.

In the constructor for the custom control, I have set the following as a test:

```<code>    valueText.TabIndex = 3;
    this.TabIndex = 3;
</code>```

The fourth time I tab, I actually get the cursor into the text field, however I cannot tab out of it.

With this in mind, the first step would be to create a control parameter that I can pass a tab order number that would get set in the control's codebehind.

I created a CustomTabIndex property:

```<code>/// <summary>
/// Custom tab index property
/// </summary>
public int CustomTabIndex
{
    get { return (int)GetValue(CustomTabIndexProperty); }
    set { SetValue(CustomTabIndexProperty, value); }
}

public static readonly DependencyProperty CustomTabIndexProperty =
    DependencyProperty.Register("CustomTabIndex", typeof(int), typeof(NumericSpinner));
</code>```

And in the xaml, when I try to set CustomTabIndex="3", I receive the error:

The property 'CustomTabIndex' was not
  found in type 'NumericSpinner'.

Some assistance would be appreciated.

答:
I don't have a complete solution for you, but the following four things should be checked for tab-cycling:

TabIndex defines the tab-order

IsTabStop says if the control should be used for tab-cycling

FocusManager.IsFocusScope  says, if an element builds its own focus area

Focusable says if an UIElement can get the focus.

I could imagine that the IsFocusScope would be interesting.

Title: WPF tab order with custom controls?

Body:
I have a WPF page that contains several out of the box controls with the tab order set.

I have a custom control (NumericSpinner) that contains: border/grid/text box/2 Repeatbuttons (up/down).

Two issues:

1) when I am in the textbox for the custom selector control, I cannot tab out of it to other controls on the page.  However after clicking on one of the up/down arrows, I am able to tab over to other controls.

2) I am unable to tab into the textbox of the custom control in order.  It is only after I have tabbed through all of the controls, that the cursor lands in the text box (and cannot tab out).

Context:

<ComboBox Margin="97,315,21,0" Name="txtdweldatcdu" Style="{StaticResource fieldComboBoxStyle}" IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Left" VerticalAlignment="Top" TabIndex="10" />
    <WpfControls:NumericSpinner Margin="97,338,21,0" Name="txtdweldatpctcomplete" HorizontalAlignment="Left" VerticalAlignment="Top" AllowNegativeValues="True" MaxValue="100" TabIndex="11" />
    <ComboBox Margin="97,363,21,0" Name="txtdweldatclass" Style="{StaticResource fieldComboBoxStyle}" IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Left" VerticalAlignment="Top" TabIndex="12" />

Portion of the custom control:

 <Border BorderThickness="1" BorderBrush="Gray" Margin="0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="20" Width="117">
        <Grid Margin="0">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="98"/>
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <TextBox Name="valueText"
                     BorderThickness="0"
                     Grid.RowSpan="2"
                     Style="{StaticResource spinnerTextBoxStyle}"
                     PreviewKeyDown="valueText_PreviewKeyDown"
                     PreviewTextInput="valueText_PreviewTextInput"
                     TextChanged="valueText_TextChanged"
                     IsReadOnly="{Binding ElementName=Spinner, Path=IsReadOnly}"
                     Text="{Binding ElementName=Spinner, Path=Value, Mode=TwoWay}"
                     KeyboardNavigation.IsTabStop="True"
                     AcceptsTab="True"/>
            <RepeatButton Name="upButton" Style="{StaticResource spinnerRepeatButtonStyle}" Click="upButton_Click"  Grid.Column="1" Grid.Row="0" Height="10" Width="18" VerticalAlignment="Top" HorizontalAlignment="Right" HorizontalContentAlignment="Center">
                <Polygon  HorizontalAlignment="Center" Points="3,2 2,3 4,3"  Fill="Black"  Stretch="Uniform"  Stroke="Black"  StrokeThickness="0" />
            </RepeatButton>
            <RepeatButton Name="downButton" Style="{StaticResource spinnerRepeatButtonStyle}" Click="downButton_Click"  Grid.Column="1" Grid.Row="1" Height="10" Width="18" VerticalAlignment="Top" HorizontalAlignment="Right" HorizontalContentAlignment="Center">
                <Polygon  HorizontalAlignment="Center" Points="2,2 4,2 3,3"  Fill="Black"  Stretch="Uniform"  Stroke="Black"  StrokeThickness="0" />
            </RepeatButton>
        </Grid>
    </Border>

The custom control consists of the xaml and code-behind file.

Parent xaml page, containing all controls is loaded dynamically and contains no code-behind.

In the constructor for the custom control, I have set the following as a test:

    valueText.TabIndex = 3;
    this.TabIndex = 3;

The fourth time I tab, I actually get the cursor into the text field, however I cannot tab out of it.

With this in mind, the first step would be to create a control parameter that I can pass a tab order number that would get set in the control's codebehind.

I created a CustomTabIndex property:

///
/// Custom tab index property
///
public int CustomTabIndex
{
    get { return (int)GetValue(CustomTabIndexProperty); }
    set { SetValue(CustomTabIndexProperty, value); }
}

public static readonly DependencyProperty CustomTabIndexProperty =
    DependencyProperty.Register("CustomTabIndex", typeof(int), typeof(NumericSpinner));

And in the xaml, when I try to set CustomTabIndex="3", I receive the error:

The property 'CustomTabIndex' was not
  found in type 'NumericSpinner'.

Some assistance would be appreciated.


问:
" The job failed" in copying database SQL Server 2012
I'm trying to copy a database. When going through the Copy Database Wizard, I'm getting a Execute SQL Server Agent Job error. The error states

The job failed. Check the event log on the destination server for details

Performing operation

Add log for package (Success)

Add task for transferring database objects (Success)

Create package (Success)

Start SQL Server Agent Job (Success)

Execute SQL Server Agent Job (Error)

Error:

The job failed.  Check the event log on the destination server for details. (Copy Database Wizard)

I can't seem to find what causing this problem. Am I using the correct approach? I just need to copy this database. Thanks in advance.

答:
It usually because your account (NT Service\SQLSERVERAGENT) don't have permission on data folder (..Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA). Set it to full controll is ok

Account above is default, if you want to check which account running agent, go to services.msc . check account logon