问:
Could not load file or assembly Temporary ASP.NET Files
I am developing a website on ASP.NET in C# (.NET Framework 4). After creating a new website project I tried to run the project. But I am getting the below error:

Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5\b9e740fc\App_global.asax.yfqtni9g.dll' or one of its dependencies. The system cannot find the file specified.

I already went through the below links [and all speaks about access to the folder], but it didn't help me :(

https://stackoverflow.com/questions/10496875/could-not-load-file-or-assembly-file-c-windows-microsoft-net-framework-v4-0

https://stackoverflow.com/questions/784157/asp-net-corrupt-assembly-could-not-load-file-or-assembly-app-web

http://web.archive.org/web/20101023213019/http://www.yetanotherdeveloper.com/post/2008/08/10/Could-not-load-file-or-assembly-App_Web.aspx

I checked and gave full access "Temporary ASP.NET Files" and to its sub folders and files for Users user-group.

 Assembly Load Trace

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

 Stack Trace

```<code>[FileNotFoundException: Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +39
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) +132
System.Reflection.Assembly.Load(AssemblyName assemblyRef, Evidence assemblySecurity) +28
System.CodeDom.Compiler.CompilerResults.get_CompiledAssembly() +93
System.Web.Compilation.BuildProvider.CreateBuildResult(CompilerResults results) +60
System.Web.Compilation.BuildProvider.GetBuildResult(CompilerResults results) +16
System.Web.Compilation.ApplicationBuildProvider.GetGlobalAsaxBuildResult(Boolean isPrecompiledApp) +9118863
System.Web.Compilation.BuildManager.CompileGlobalAsax() +44
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +265

[HttpException (0x80004005): Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +62
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +421
System.Web.Compilation.BuildManager.CallAppInitializeMethod() +31
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +691

[HttpException (0x80004005): Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9090876
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +258
</code>```

 Please give me a link if this is a repeated question

 Thanks in adv.

I got the Log as follows

```

The operation was successful.
Bind result: hr = 0x0. The operation completed successfully.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: User = John-PC\John
LOG: DisplayName = Microsoft.VisualStudio.ComponentModelHost, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
 (Fully-specified)
LOG: Appbase = file:///G:/WorkShop/HTML-CSS/ASP/MyFirst/
LOG: Initial PrivatePath = G:\WorkShop\HTML-CSS\ASP\MyFirst\bin
LOG: Dynamic Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5
LOG: Cache Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5
LOG: AppName = b9e740fc
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: G:\WorkShop\HTML-CSS\ASP\MyFirst\web.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Found assembly by looking in the GAC.
LOG: Binding succeeds. Returns assembly from C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.ComponentModelHost\v4.0_10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.ComponentModelHost.dll.
LOG: Assembly is loaded in default load context.
```

I am not able to trace any error. Please help me....

答:
Removing contents inside  (web.config) block worked for me for a similar issue.

a)  Following describe why you should remove it

What exactly does <system.codedom>/<compilers> do in web.config in MVC 5?

Following Additional article from microsoft helps understand the concept

https://learn.microsoft.com/en-us/previous-versions/ms366723(v=vs.140)?redirectedfrom=MSDN

Compilation Folder Location:

By default, when you compile a Web application the compiled code is placed in the Temporary ASP.NET Files folder. This folder is a subdirectory of the location where you installed the .NET framework

Besides this, another article suggested double-checking the targetFramework and framework installed

Body:
I am developing a website on ASP.NET in C# (.NET Framework 4). After creating a new website project I tried to run the project. But I am getting the below error:

Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5\b9e740fc\App_global.asax.yfqtni9g.dll' or one of its dependencies. The system cannot find the file specified.

I already went through the below links [and all speaks about access to the folder], but it didn't help me :(

https://stackoverflow.com/questions/10496875/could-not-load-file-or-assembly-file-c-windows-microsoft-net-framework-v4-0

https://stackoverflow.com/questions/784157/asp-net-corrupt-assembly-could-not-load-file-or-assembly-app-web

http://web.archive.org/web/20101023213019/http://www.yetanotherdeveloper.com/post/2008/08/10/Could-not-load-file-or-assembly-App_Web.aspx

I checked and gave full access "Temporary ASP.NET Files" and to its sub folders and files for Users user-group.

 Assembly Load Trace

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

 Stack Trace

[FileNotFoundException: Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +39
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) +132
System.Reflection.Assembly.Load(AssemblyName assemblyRef, Evidence assemblySecurity) +28
System.CodeDom.Compiler.CompilerResults.get_CompiledAssembly() +93
System.Web.Compilation.BuildProvider.CreateBuildResult(CompilerResults results) +60
System.Web.Compilation.BuildProvider.GetBuildResult(CompilerResults results) +16
System.Web.Compilation.ApplicationBuildProvider.GetGlobalAsaxBuildResult(Boolean isPrecompiledApp) +9118863
System.Web.Compilation.BuildManager.CompileGlobalAsax() +44
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +265

[HttpException (0x80004005): Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +62
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +421
System.Web.Compilation.BuildManager.CallAppInitializeMethod() +31
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +691

[HttpException (0x80004005): Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\4ff7194b\2da62764\App_global.asax.h-eem9xt.dll' or one of its dependencies. The system cannot find the file specified.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9090876
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +258

 Please give me a link if this is a repeated question

 Thanks in adv.

I got the Log as follows

The operation was successful.
Bind result: hr = 0x0. The operation completed successfully.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: User = John-PC\John
LOG: DisplayName = Microsoft.VisualStudio.ComponentModelHost, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
 (Fully-specified)
LOG: Appbase = file:///G:/WorkShop/HTML-CSS/ASP/MyFirst/
LOG: Initial PrivatePath = G:\WorkShop\HTML-CSS\ASP\MyFirst\bin
LOG: Dynamic Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5
LOG: Cache Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myfirst\159977c5
LOG: AppName = b9e740fc
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: G:\WorkShop\HTML-CSS\ASP\MyFirst\web.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Found assembly by looking in the GAC.
LOG: Binding succeeds. Returns assembly from C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.ComponentModelHost\v4.0_10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.ComponentModelHost.dll.
LOG: Assembly is loaded in default load context.

I am not able to trace any error. Please help me....


来源: stackexchange

问:
Azure App Service Infrastructure Equivalent
How can I create the equivalent of an Azure AppService using individual pieces of infrastructure in Azure?

Is there an existing ARM template that would create something similar?

答:
If you're looking for a quick way, you can use azure quick start and deploy the template you need:

https://github.com/Azure/azure-quickstart-templates/tree/master/201-vmss-windows-autoscale

https://github.com/Azure/azure-quickstart-templates

ContentLicense: CC BY-SA 4.0


问:
max_value and min_value for each column in scikit IterativeImputer
I have this data set with 78 columns and 5707 rows. Almost every column has missing values and I would like to impute them with IterativeImputer. If I understood it correctly, it will make a "smarter" imputation on each column based on the information from other columns.

However, when imputing, I do not want the imputed values to be less than the observed minimum or more than the observed maximum. I realize there are max_value and min_value parameters, but I do not want to impose a "global" limit to the imputations, instead, I want each column to have its own max_value and min_value (which is the already observed maximum and minimum values). Because otherwise, the values in the columns do not make sense (negative values for headcounts, negative values for rates, etc.)

Is there a way to implement that?

答: So if you want to set max and min different for each column then you can go in a loop and in each iteration select the column using sklearn.compose.make_column_selector or sklearn.compose.make_column_transformer and then apply iterative imputer to that column giving max and min of that column as parameter.


问:
How can I set a floating point timeout value for a read command in bash?
I have a script where I must take input from the user with a timeout of less than a second (0.03). I use the read command with the option -t which works with floating point values on linux bash (at least on arch and debian). However the macOS version of bash's read builtin only works with integer values.

original command:

```<code>read -sn3 -t 0.03 INPUT
</code>```

I tried using the timeout command but of course it does not work with shell builtins. I also tried sending an input via a fifo after the desired amout of time to stop the read but I couldnt figure out how to read from the file and from stdin at the same time.

EDIT:

here is the error returned by read:

bash: read: 0.03: invalid timeout specification

答:
I have had the same issue. Try to launch these commands

```<code>$ echo $BASH_VERSION
3.2.57(1)-release

$ bash -c 'echo $BASH_VERSION'
5.0.7(1)-release
</code>```

As you see, there are two versions of the bash shell. Launch your script with this syntax

```<code>bash your-script-path
</code>```

and not just

```<code>your-script-path
</code>```

This way you will use the new bash, supporting the read command with decimal timeout.
If you have a different situation, eg. an older bash, install a newer one with homebrew

Body:
I have a script where I must take input from the user with a timeout of less than a second (0.03). I use the read command with the option -t which works with floating point values on linux bash (at least on arch and debian). However the macOS version of bash's read builtin only works with integer values.

original command:

read -sn3 -t 0.03 INPUT

I tried using the timeout command but of course it does not work with shell builtins. I also tried sending an input via a fifo after the desired amout of time to stop the read but I couldnt figure out how to read from the file and from stdin at the same time.

EDIT:

here is the error returned by read:

bash: read: 0.03: invalid timeout specification

Body:
I have had the same issue. Try to launch these commands

$ echo $BASH_VERSION
3.2.57(1)-release

$ bash -c 'echo $BASH_VERSION'
5.0.7(1)-release

As you see, there are two versions of the bash shell. Launch your script with this syntax

bash your-script-path

and not just

your-script-path

This way you will use the new bash, supporting the read command with decimal timeout.
If you have a different situation, eg. an older bash, install a newer one with homebrew


问:
How to force a link to use specific route (MVC routing)
I have these two routes:

```<code>routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "Default2", // Route name
            "{controller}/{action}/{OrderId}/{CustomerID}", // URL with parameters
            new { controller = "NorthwindOrders", action = "Index", OrderId = UrlParameter.Optional, CustomerID = UrlParameter.Optional } // Parameter defaults
        );
</code>```

and want to create link that uses the second route.

How can I do this?

答:
If you want to specifically use a route, you can use the Html helper Html.RouteLink :

```<code><%= Html.RouteLink("my link", "Default2", new {OrderId=1, CustomerId=2}) %>
</code>```

Also, you can put the second route first : the most generic route should be at the end, in order to be used only when no specific route was found.

ContentLicense: CC BY-SA 3.0

Body:
I have these two routes:

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "Default2", // Route name
            "{controller}/{action}/{OrderId}/{CustomerID}", // URL with parameters
            new { controller = "NorthwindOrders", action = "Index", OrderId = UrlParameter.Optional, CustomerID = UrlParameter.Optional } // Parameter defaults
        );

and want to create link that uses the second route.

How can I do this?

Body:
If you want to specifically use a route, you can use the Html helper Html.RouteLink :

<%= Html.RouteLink("my link", "Default2", new {OrderId=1, CustomerId=2}) %>

Also, you can put the second route first : the most generic route should be at the end, in order to be used only when no specific route was found.


问:
iterate array of object and save values
I have this objects in Javascript:

```<code>products = {
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    },
}
</code>```

I want to group the articles_ids in the same family.
I want get this result:

```<code>grouped_products = {
    {
      family : 'mugs', articles_ids : '1728,2748' //only mugs articles ids
    },
    {
      family : 'tees', articles_ids : '1332,1332' //only tees articles ids
    },
}
</code>```

I try with forEach and filter methods, but I dont know how to make this with perform mode.

答:
```<code>let products = [
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    }
]

function insertItem(accum,val){
    accum[val.family] = accum[val.family] ?  accum[val.family] + "," +  val.article_id : val.article_id ;
    return accum;
}

let mapped = products.reduce(insertItem,{});
let grouped = [];
Object.keys(mapped).map((key)=> grouped.push({"family":key, "article_ids":mapped[key]}))
</code>```

First I'm just grouping everything by family using an object as an associative array

Then I'm using a conditional assignment with the ? to append the value with a preceeding comma if there is one

I'm not sure if you actually wanted comma seperated values or an array for the article_ids but if you wanted commas, this should work

Title: iterate array of object and save values

Body:
I have this objects in Javascript:

products = {
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    },
}

I want to group the articles_ids in the same family.
I want get this result:

grouped_products = {
    {
      family : 'mugs', articles_ids : '1728,2748' //only mugs articles ids
    },
    {
      family : 'tees', articles_ids : '1332,1332' //only tees articles ids
    },
}

I try with forEach and filter methods, but I dont know how to make this with perform mode.

Body:
let products = [
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    }
]

function insertItem(accum,val){
    accum[val.family] = accum[val.family] ?  accum[val.family] + "," +  val.article_id : val.article_id ;
    return accum;
}

let mapped = products.reduce(insertItem,{});
let grouped = [];
Object.keys(mapped).map((key)=> grouped.push({"family":key, "article_ids":mapped[key]}))

First I'm just grouping everything by family using an object as an associative array

Then I'm using a conditional assignment with the ? to append the value with a preceeding comma if there is one

I'm not sure if you actually wanted comma seperated values or an array for the article_ids but if you wanted commas, this should work


问:
Infinite iteration with SQL XEvents QueryableXEventData
The request is: using XEvents API from SQL, I have to extract and analyze the event logs.
I have personalized this session "QuickSessionTSQL" so that it only logs procedures or queries.
The below code runs just fine, except that once it goes inside the first foreach block, it never leaves, it is just waiting for events to come, even if there is no other event to iterate on. It creates an infinite loop...

If I perform an SQL query, then it generates an event and the foreach will iterate that event in real time.

I tried to break it but I could not find a proper solution.

Has anyone dealt with this before?

```<code>        //Connection string
        SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
        csb.DataSource = @"DESKTOP-85BSKEM\MSSQLSERVER2016";
        csb.InitialCatalog = @"master";
        csb.IntegratedSecurity = true;

        //Session name
        string sessionName = "QuickSessionTSQL";

        SqlConnection sqlConnection = new SqlConnection(csb.ConnectionString);
        SqlStoreConnection connection = new SqlStoreConnection(sqlConnection);
        BaseXEStore store = new XEStore(connection);
        Session s = store.CreateSession(sessionName);

        s.Start();

        QueryableXEventData xEvents = new QueryableXEventData(csb.ConnectionString, sessionName, EventStreamSourceOptions.EventStream, EventStreamCacheOptions.DoNotCache);

        foreach (var evt in xEvents)
        {
            foreach (PublishedEventField fld in evt.Fields)
            {
                string fieldName = fld.Name;
                string fieldValue = fld.Value.ToString();
                Debug.WriteLine(fieldName + " " + fieldValue);
            }
        }
</code>```

答:
The choice of IEnumerable for this has some drawbacks.  It's the base type for all collections, and gives you LINQ access to the stream.  But it's a bit awkward to terminate.

Anyway, I think the pattern should be something like enumerating the collection on a background thread, and signaling from the foreground thread when you want the enumeration to terminate.  Like this:

```<code>    var xEvents = new QueryableXEventData(csb.ConnectionString, sessionName, EventStreamSourceOptions.EventStream, EventStreamCacheOptions.DoNotCache);
    var cancellationTokenSource = new CancellationTokenSource();

    var reader = Task.Factory.StartNew((o) =>
               {
                   foreach (var evt in xEvents)
                   {
                       foreach (PublishedEventField fld in evt.Fields)
                       {
                           string fieldName = fld.Name;
                           string fieldValue = fld.Value.ToString();
                           Console.WriteLine(fieldName + " " + fieldValue);
                       }
                   }
               }, TaskCreationOptions.LongRunning
                , cancellationTokenSource.Token);

    Console.WriteLine("Hit any key to exit");
    Console.ReadKey();
    cancellationTokenSource.Cancel();
    xEvents.Dispose();
    s.Stop();
    reader.Wait();
</code>```

Body:
The request is: using XEvents API from SQL, I have to extract and analyze the event logs.
I have personalized this session "QuickSessionTSQL" so that it only logs procedures or queries.
The below code runs just fine, except that once it goes inside the first foreach block, it never leaves, it is just waiting for events to come, even if there is no other event to iterate on. It creates an infinite loop...

If I perform an SQL query, then it generates an event and the foreach will iterate that event in real time.

I tried to break it but I could not find a proper solution.

Has anyone dealt with this before?

        //Connection string
        SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
        csb.DataSource = @"DESKTOP-85BSKEM\MSSQLSERVER2016";
        csb.InitialCatalog = @"master";
        csb.IntegratedSecurity = true;

        //Session name
        string sessionName = "QuickSessionTSQL";

        SqlConnection sqlConnection = new SqlConnection(csb.ConnectionString);
        SqlStoreConnection connection = new SqlStoreConnection(sqlConnection);
        BaseXEStore store = new XEStore(connection);
        Session s = store.CreateSession(sessionName);

        s.Start();

        QueryableXEventData xEvents = new QueryableXEventData(csb.ConnectionString, sessionName, EventStreamSourceOptions.EventStream, EventStreamCacheOptions.DoNotCache);

        foreach (var evt in xEvents)
        {
            foreach (PublishedEventField fld in evt.Fields)
            {
                string fieldName = fld.Name;
                string fieldValue = fld.Value.ToString();
                Debug.WriteLine(fieldName + " " + fieldValue);
            }
        }

Body:
The choice of IEnumerable for this has some drawbacks.  It's the base type for all collections, and gives you LINQ access to the stream.  But it's a bit awkward to terminate.

Anyway, I think the pattern should be something like enumerating the collection on a background thread, and signaling from the foreground thread when you want the enumeration to terminate.  Like this:

    var xEvents = new QueryableXEventData(csb.ConnectionString, sessionName, EventStreamSourceOptions.EventStream, EventStreamCacheOptions.DoNotCache);
    var cancellationTokenSource = new CancellationTokenSource();

    var reader = Task.Factory.StartNew((o) =>
               {
                   foreach (var evt in xEvents)
                   {
                       foreach (PublishedEventField fld in evt.Fields)
                       {
                           string fieldName = fld.Name;
                           string fieldValue = fld.Value.ToString();
                           Console.WriteLine(fieldName + " " + fieldValue);
                       }
                   }
               }, TaskCreationOptions.LongRunning
                , cancellationTokenSource.Token);

    Console.WriteLine("Hit any key to exit");
    Console.ReadKey();
    cancellationTokenSource.Cancel();
    xEvents.Dispose();
    s.Stop();
    reader.Wait();


问:
Find the min/max element of an array in JavaScript
How can I easily obtain the min or max element of a JavaScript array?

Example pseudocode:

```<code>let array = [100, 0, 50]

array.min() //=> 0
array.max() //=> 100
</code>```

答:
Aside using the math function max and min, another function to use is the built in function of sort(): here we go</p>
```<code>const nums = [12, 67, 58, 30].sort((x, y) =>
x -  y)
let min_val = nums[0]
let max_val = nums[nums.length -1]
</code>```

Body:
How can I easily obtain the min or max element of a JavaScript array?

Example pseudocode:

let array = [100, 0, 50]

array.min() //=> 0
array.max() //=> 100

Body:
Aside using the math function max and min, another function to use is the built in function of sort(): here we go

const nums = [12, 67, 58, 30].sort((x, y) =>
x -  y)
let min_val = nums[0]
let max_val = nums[nums.length -1]


问:
Is possible to recover whole app when it is killed(by user or by android), or at least get last activity?
Assuming that the user closes the application through "recent applications" or that Android for whatever reason closes the application, I then want to recover the last activity that the user was in, is there any way to do this, by Android standards, or do I need to create sophisticated schemes?

Ex:

Activity A -> B -> C

then user swipe to close app / android close it

on reopen, should go to Activity C

Thanks in advance for any help.

Ps:Is it possible to recover backstack aswell?

答:
not a piece of expert advice but you can try saving an instance of last activity in shared pref. n get the value of shared pref on the start of application to directly navigate to that last instance page from splash activity.

On every startActivity(); action replace previously shared pref value with new activity value.


问:
How to run a timer on the background that updates a label in a viewmodel
I am trying to run a timer that updates a label every second on background (async). The timer should run from 0 to 60 min and only show {MIN:SEC} in the label. But I am having a hard time to run the timer in background that updates the label. This is what I had for so for but it won't work:

```<code>Timer timer;
    Stopwatch sw;
    public TimerViewModel()
    {
        Title = "Tijd";
        StartTimer();
    }

    private async void StartTimer()
    {
        timer = new Timer();
        timer.Interval = (1000);
        //timer.Elapsed += new EventHandler(UpdateLabel);
        sw = new Stopwatch();
        timer.Start();
        sw.Start();
    }

    private async void UpdateLabel()
    {
        await Task.Run(async () =>
        {

        }).ConfigureAwait(false);
    }
</code>```

MainPage:

```<code><TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:views="clr-namespace:EscapeHaarlem.Views"
        x:Class="EscapeHaarlem.Views.MainPage">
<TabbedPage.Children>
    <NavigationPage Title="Tijd">
        <NavigationPage.Icon>
            <OnPlatform x:TypeArguments="FileImageSource">
                <On Platform="iOS" Value="tab_about.png"/>
            </OnPlatform>
        </NavigationPage.Icon>
        <x:Arguments>
            <views:AboutPage />
        </x:Arguments>
    </NavigationPage>

    <NavigationPage Title="Hints">
        <NavigationPage.Icon>
            <OnPlatform x:TypeArguments="FileImageSource">
                <On Platform="iOS" Value="tab_feed.png"/>
            </OnPlatform>
        </NavigationPage.Icon>
        <x:Arguments>
            <views:ItemsPage />
        </x:Arguments>
    </NavigationPage>
</TabbedPage.Children>
</code>```

About page:

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="EscapeHaarlem.Views.AboutPage"
         xmlns:vm="clr-namespace:EscapeHaarlem.ViewModels"
         Title="{Binding Title}">
<ContentPage.BindingContext>
    <vm:TimerViewModel />
</ContentPage.BindingContext>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="12*" />
        <ColumnDefinition Width="6*" />
        <ColumnDefinition Width="6*" />
        <ColumnDefinition Width="auto" />
    </Grid.ColumnDefinitions>
    <StackLayout x:Name="RealTimeTimer" Grid.Column="0" VerticalOptions="Center">
        <Label Text="{Binding RealTimeTimer}" HorizontalTextAlignment="Center" Rotation="270" FontSize="150" HorizontalOptions="Center"></Label>
    </StackLayout>
    <StackLayout Grid.Column="1" VerticalOptions="Center">
        <Label Text="Straftijd" HorizontalTextAlignment="Center" Rotation="270" FontSize="40" HorizontalOptions="End"></Label>
    </StackLayout>
    <StackLayout Grid.Column="2" VerticalOptions="Center">
            <Label Text="00:00" HorizontalTextAlignment="Center" Rotation="270" FontSize="40" HorizontalOptions="Start" ></Label>
    </StackLayout>
</Grid>
</code>```

thanks in advance

答:
You are wrongly assigning the event handler as seen in the docs.

Change

```<code>timer.Elapsed += new EventHandler(UpdateLabel);
</code>```

to

```<code>timer.Elapsed +=UpdateLabel; //or
timer.Elapsed +=System.EventHandler(UpdateLabel)
</code>```

not sure from the top of my head

And

```<code>private async void UpdateLabel()
</code>```

to

```<code>private static void UpdateLabel(Object source, System.Timers.ElapsedEventArgs e)
</code>```

This should allow you to to trigger the Elapsed event. You problem was your confusing regular functions and event functions. You should read up on it here

Body:
I am trying to run a timer that updates a label every second on background (async). The timer should run from 0 to 60 min and only show {MIN:SEC} in the label. But I am having a hard time to run the timer in background that updates the label. This is what I had for so for but it won't work:

Timer timer;
    Stopwatch sw;
    public TimerViewModel()
    {
        Title = "Tijd";
        StartTimer();
    }

    private async void StartTimer()
    {
        timer = new Timer();
        timer.Interval = (1000);
        //timer.Elapsed += new EventHandler(UpdateLabel);
        sw = new Stopwatch();
        timer.Start();
        sw.Start();
    }

    private async void UpdateLabel()
    {
        await Task.Run(async () =>
        {

        }).ConfigureAwait(false);
    }

MainPage:

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:views="clr-namespace:EscapeHaarlem.Views"
        x:Class="EscapeHaarlem.Views.MainPage">
<TabbedPage.Children>
    <NavigationPage Title="Tijd">
        <NavigationPage.Icon>
            <OnPlatform x:TypeArguments="FileImageSource">
                <On Platform="iOS" Value="tab_about.png"/>
            </OnPlatform>
        </NavigationPage.Icon>
        <x:Arguments>
            <views:AboutPage />
        </x:Arguments>
    </NavigationPage>

    <NavigationPage Title="Hints">
        <NavigationPage.Icon>
            <OnPlatform x:TypeArguments="FileImageSource">
                <On Platform="iOS" Value="tab_feed.png"/>
            </OnPlatform>
        </NavigationPage.Icon>
        <x:Arguments>
            <views:ItemsPage />
        </x:Arguments>
    </NavigationPage>
</TabbedPage.Children>

About page:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="EscapeHaarlem.Views.AboutPage"
         xmlns:vm="clr-namespace:EscapeHaarlem.ViewModels"
         Title="{Binding Title}">
<ContentPage.BindingContext>
    <vm:TimerViewModel />
</ContentPage.BindingContext>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="12*" />
        <ColumnDefinition Width="6*" />
        <ColumnDefinition Width="6*" />
        <ColumnDefinition Width="auto" />
    </Grid.ColumnDefinitions>
    <StackLayout x:Name="RealTimeTimer" Grid.Column="0" VerticalOptions="Center">

    </StackLayout>
    <StackLayout Grid.Column="1" VerticalOptions="Center">

    </StackLayout>
    <StackLayout Grid.Column="2" VerticalOptions="Center">

    </StackLayout>
</Grid>

thanks in advance

Body:
You are wrongly assigning the event handler as seen in the docs.

Change

timer.Elapsed += new EventHandler(UpdateLabel);

to

timer.Elapsed +=UpdateLabel; //or
timer.Elapsed +=System.EventHandler(UpdateLabel)

not sure from the top of my head

And

private async void UpdateLabel()

to

private static void UpdateLabel(Object source, System.Timers.ElapsedEventArgs e)

This should allow you to to trigger the Elapsed event. You problem was your confusing regular functions and event functions. You should read up on it here


问:
why is the address of a c++ function always True?
well why would,

```<code>#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}
</code>```

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?

答: All addresses in C++ are non-zero, because zero is the NULL pointer and is a reserved value. Any non-zero value is considered true.</p>

Body:
well why would,

#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?


问:
Programmatically loop a section of JSX within an output
I would like to programmatically repeat a section of JSX within an output.
Below I would like to get the same effect as below without repeating the PageLeft id="Diary" component 3 times. I'd like to use a loop or something.

```<code>const DiaryPages = {

}

  return (
    <Fragment>
     <PageLeftDivider
      />
      <PageRight
  header={bookData[0].pageHeader}
  pageNumber={bookData[0].id}
  htmlContent={bookData[0].htmlContent}
  bookSection={bookData[0].bookSection}
      />

      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />
      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />

      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />

    </Fragment>
  );
}
</code>```

答:
Or assuming that you wanted a <PageLeft /> for each entry in your bookData array, then you could remove the first entry with .splice() (as it is already displayed on <PageRight />) and then use .map().

```<code><>
   {bookData.splice(0,1).map( entry => <PageLeft id={"Diary" + entry.id}
        pageHeader={entry.pageHeader}
        pageNumber={entry.id}
        htmlContent={entry.htmlContent}
      />
   )}
</>
</code>```

I added id={"Diary" + entry.id} so that each <PageLeft /> has a different id.

Note: the <> </> are just a short form of React Fragments

Body:
I would like to programmatically repeat a section of JSX within an output.
Below I would like to get the same effect as below without repeating the PageLeft id="Diary" component 3 times. I'd like to use a loop or something.

const DiaryPages = {

}

  return (
    <Fragment>
     <PageLeftDivider
      />
      <PageRight
  header={bookData[0].pageHeader}
  pageNumber={bookData[0].id}
  htmlContent={bookData[0].htmlContent}
  bookSection={bookData[0].bookSection}
      />

      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />
      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />

      <PageLeft id="Diary"
        pageHeader={bookData[1].pageHeader}
        pageNumber={bookData[1].id}
        htmlContent={bookData[1].htmlContent}
      />

    </Fragment>
  );
}

Body:
Or assuming that you wanted a <PageLeft /> for each entry in your bookData array, then you could remove the first entry with .splice() (as it is already displayed on <PageRight />) and then use .map().

<>
   {bookData.splice(0,1).map( entry => <PageLeft id={"Diary" + entry.id}
        pageHeader={entry.pageHeader}
        pageNumber={entry.id}
        htmlContent={entry.htmlContent}
      />
   )}
</>

I added id={"Diary" + entry.id} so that each <PageLeft /> has a different id.

Note: the <> </> are just a short form of React Fragments


问:
create data stories in CKAN
Is there a way to create user stories in CKAN. I've found Showcases but they only display static information. I've also found dashboards but they can only display datasets, not custom text.
For every dataset I'd like to have an extra tab (like with showcases) where I can display some text in combination with some graphs of one or more datasets. That way I can explain what we can see in the dataset.
I'm not able to find any plugins.
Anybody has any experience with this?</p>

答:
You can check query-tool. The extension consist of a combination of three elements:

```<code>• Data-driven visualizations: charts, maps and tables.
• Support elements: text and images.
• Interactive elements: filters, download options, sharing options, among others.
</code>```

These elements can be combined and arranged in different ways to provide a user-friendly experience for exploring public data.

Title: create data stories in CKAN

Body:
You can check query-tool. The extension consist of a combination of three elements:

• Data-driven visualizations: charts, maps and tables.
• Support elements: text and images.
• Interactive elements: filters, download options, sharing options, among others.

These elements can be combined and arranged in different ways to provide a user-friendly experience for exploring public data.


问:
Catching an exception in an overridden method in C#
Why does the following catch block does not catch any exception?
Does this have anything to do with the override->base.Method() relationship?

On the screenshot you can see that an SqlException with a number 2627 is thrown, but the catch block never catches it.

```<code>    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (SqlException ex) when (ex.Number == 2627)
        {
            Log.Error($"Duplicate key constraint violation occured while submitting changes, {ex.Message}");
            var (resource, duplicateKey) = ExtractDuplicateKeyViolationDetails(ex.Message);
            throw new DuplicateKeyException(resource, duplicateKey);
        }
        catch (SqlException ex) when (ex.Number == 547)
        {
            Log.Error($"Constraint violation occured while submitting changes, {ex.Message}");
            var (resource, property) = ExtractConstraintViolationDetails(ex.Message);
            throw new ConstraintViolationException(resource, property);
        }
    }
</code>```

答:
Turns out the issue was the thrown exception was not an SqlException, but a DbUpdateException, where the SqlException was embedded as the InnerException's InnerException...

I've solved it with the following format:

```<code>    catch (DbUpdateException ex) when (ex.MostInnerException() is SqlException sqlException && sqlException.Number == 2627)
    {
        Log.Error($"Duplicate key constraint violation occured while submitting changes, {sqlException.Message}");
        var (resource, duplicateKey) = ExtractDuplicateKeyViolationDetails(sqlException.Message);
        throw new DuplicateKeyException(resource, duplicateKey);
    }

    internal static Exception MostInnerException(this Exception ex)
    {
        var innerException = ex;

        while (innerException.InnerException != null)
        {
            innerException = innerException.InnerException;
        }

        return innerException;
    }
</code>```

Body:
Why does the following catch block does not catch any exception?
Does this have anything to do with the override->base.Method() relationship?

On the screenshot you can see that an SqlException with a number 2627 is thrown, but the catch block never catches it.

    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (SqlException ex) when (ex.Number == 2627)
        {
            Log.Error($"Duplicate key constraint violation occured while submitting changes, {ex.Message}");
            var (resource, duplicateKey) = ExtractDuplicateKeyViolationDetails(ex.Message);
            throw new DuplicateKeyException(resource, duplicateKey);
        }
        catch (SqlException ex) when (ex.Number == 547)
        {
            Log.Error($"Constraint violation occured while submitting changes, {ex.Message}");
            var (resource, property) = ExtractConstraintViolationDetails(ex.Message);
            throw new ConstraintViolationException(resource, property);
        }
    }

Body:
Turns out the issue was the thrown exception was not an SqlException, but a DbUpdateException, where the SqlException was embedded as the InnerException's InnerException...

I've solved it with the following format:

    catch (DbUpdateException ex) when (ex.MostInnerException() is SqlException sqlException && sqlException.Number == 2627)
    {
        Log.Error($"Duplicate key constraint violation occured while submitting changes, {sqlException.Message}");
        var (resource, duplicateKey) = ExtractDuplicateKeyViolationDetails(sqlException.Message);
        throw new DuplicateKeyException(resource, duplicateKey);
    }

    internal static Exception MostInnerException(this Exception ex)
    {
        var innerException = ex;

        while (innerException.InnerException != null)
        {
            innerException = innerException.InnerException;
        }

        return innerException;
    }


问:
How is memory deallocated in c++
I understand pointer allocation of memory fully, but deallocation of memory only on a higher level. What I'm most curious about is how C++ keeps track of what memory has already been deallocated?

```<code>int* ptr = new int;
cout << ptr;
delete ptr;
cout << ptr;
// still pointing to the same place however it knows you can't access it or delete it again
*ptr // BAD
delete ptr // BAD
</code>```

How does C++ know I deallocated that memory. If it just turns it to arbitrary garbage binary numbers, wouldn't I just be reading in that garbage number when I dereference the pointer?

Instead, of course, c++ knows that these are segfaults somehow.

答:
C++ does not track memory for you. It doesn't know, it doesn't care. It is up to you: the programmer. (De)allocation is a request to the underlying OS. Or more precisely it is a call to libc++ (or possibly some other lib) which may or may not access the OS, that is an implementation detail.  Either way the OS (or some other library) tracks what parts of memory are available to you.

When you try to access a memory that the OS did not assigned to you, then the OS will issue segfault (technically it is raised by the CPU, assuming it supports memory protection, it's a bit complicated). And this is a good situation. That way the OS tells you: hey, you have a bug in your code. Note that the OS doesn't care whether you use C++, C, Rust or anything else. From the OS' perspective everything is a machine code.

However what is worse is that even after delete the memory may still be owned by your process (remember those libs that track memory?). So accessing such pointer is an undefined behaviour, anything can happen, including correct execution of the code (that's why it is often hard to find such bugs).

If it just turns it to arbitrary garbage binary numbers, wouldn't I just be reading in that garbage number when I dereference the pointer?

Who says it turns into garbage? What really happens to the underlying memory (whether the OS reclaims it, or it is filled with zeros or some garbage, or maybe nothing) is none of your concern. Everything you need to know is that after delete it is no longer safe to use the pointer. Even (or especially) when it looks ok.

Title: How is memory deallocated in c++

Body:
I understand pointer allocation of memory fully, but deallocation of memory only on a higher level. What I'm most curious about is how C++ keeps track of what memory has already been deallocated?

int* ptr = new int;
cout << ptr;
delete ptr;
cout << ptr;
// still pointing to the same place however it knows you can't access it or delete it again
*ptr // BAD
delete ptr // BAD

How does C++ know I deallocated that memory. If it just turns it to arbitrary garbage binary numbers, wouldn't I just be reading in that garbage number when I dereference the pointer?

Instead, of course, c++ knows that these are segfaults somehow.


问:
apache shiro url config for path variable
I have a spring controller like following:

```<code>@Controller
@RequestMapping("/tickets")
public class TicketWeb {

    @GetMapping("/{ticketNo}")
    ...

    @GetMapping("/a")

    @GetMapping("/b")

    @PostMapping("/c")

    //maybe more fixed path mapping
}
</code>```

In this controller, I have one path variable like /{ticketNo}, others are fixed path.

With apache shiro, I want annon for path variable only, all other fixed path are authc.

According to apache shiro doc, it seems that there are only two solutions to achieve my goal:

option 1 is :

```<code>filterChainDefinitionMap.put("/tickets/a","authc");
filterChainDefinitionMap.put("/tickets/b","authc");
filterChainDefinitionMap.put("/tickets/c","authc");

filterChainDefinitionMap.put("/tickets/*","annon");

</code>```

that is set fixed path to authc one by one explicitly, set path variable to annon, but this is not good because maybe there are some fixed path or add more fixed path in future.

option 2 is change path variable /{ticketNo} to another, e.g. /annon/{ticketNo}, to distinguish fixed path, such that developer can set

```<code>filterChainDefinitionMap.put("/tickets/annon/*","annon");

filterChainDefinitionMap.put("/tickets/*","authc");
</code>```

with only two lines.

So there are only these two solutions to implement my goal, am I right?

答: Shiro uses Ant-style pattern matching, see: https://shiro.apache.org/static/1.5.0/apidocs/org/apache/shiro/util/AntPathMatcher.html for some examples.</p>

Body:
I have a spring controller like following:

@Controller
@RequestMapping("/tickets")
public class TicketWeb {

    @GetMapping("/{ticketNo}")
    ...

    @GetMapping("/a")

    @GetMapping("/b")

    @PostMapping("/c")

    //maybe more fixed path mapping
}

In this controller, I have one path variable like /{ticketNo}, others are fixed path.

With apache shiro, I want annon for path variable only, all other fixed path are authc.

According to apache shiro doc, it seems that there are only two solutions to achieve my goal:

option 1 is :

filterChainDefinitionMap.put("/tickets/a","authc");
filterChainDefinitionMap.put("/tickets/b","authc");
filterChainDefinitionMap.put("/tickets/c","authc");

filterChainDefinitionMap.put("/tickets/*","annon");

that is set fixed path to authc one by one explicitly, set path variable to annon, but this is not good because maybe there are some fixed path or add more fixed path in future.

option 2 is change path variable /{ticketNo} to another, e.g. /annon/{ticketNo}, to distinguish fixed path, such that developer can set

filterChainDefinitionMap.put("/tickets/annon/*","annon");

filterChainDefinitionMap.put("/tickets/*","authc");

with only two lines.

So there are only these two solutions to implement my goal, am I right?


问:
Creating an employee Permission DB
I work for a small company that has many different permissions for different apps. Right now we track all of this on a spreadsheet that is slowly getting out of control. We look in a column, to match of a job grouping (say accounting- finance might be a group), then look at each row below that to find out how many applications they need, and the needed permissions for each application. Then with this information we go about giving them the access. I'd like to automate this whole thing at some point. But for now I'm focused on removing the spreadsheet

I'd like to make a simple database that would allow me to query and search by Logical Job group, and pull back the permissions for each individual app that pertain to that job grouping. I haven't worked in building databases before but I've installed SQL express, just need some help logically thinking out the tables and how they would interact. Each application obviously can have different permission groups, but can also contain mutliple. For example, Employee A, needs application X installed, with permission groups 1, 2, and 4.

Thanks!

答:
I would design an Applications table, a Roles table a Users table and a Permissions table. They would be related like this:

Users is related to Roles, one User may have many Roles.

Applications is related to Roles. One Application may have many Roles.

Roles is related to both Applications and Permissions. One Role may belong to one more Applications, and have one or more Permissions.

Permissions is related to Roles. Each permission belongs to a specific Role.

Hope this at the very least gives you and idea on how to proceed.

Title: Creating an employee Permission DB


问:
T-SQL IF problemo
I have the following stored procedure:

```<code>ALTER PROCEDURE [dbo].[getipmp]
@year varchar(4)
AS
BEGIN

select * from (

IF @year = ''
    select distinct carlinenm
    from [interchange].[dbo].[carline]
    WHERE CarlineYear >= 1990
ELSE
    select distinct carlinenm
    from [interchange].[dbo].[carline]
    WHERE CarlineYear = @year

UNION ALL

SELECT distinct cast(carlineyear as varchar(4)),'Y|' + rtrim(cast(carlineyear as varchar(4)))
from [interchange].[dbo].[carline]
WHERE carlineyear >= 1990

) U

END
</code>```

SQL-Express is saying:

```<code>Msg 156, Level 15, State 1, Procedure getipmp, Line 15 [Batch Start Line 7]
Incorrect syntax near the keyword 'IF'.
Msg 102, Level 15, State 1, Procedure getipmp, Line 43 [Batch Start Line 7]
Incorrect syntax near ')'.
</code>```

It refers to the "IF" at beginning and to the last ")" before the U.

Any idea what is wrong there?

Thanks!

答:
Shouldnt it be:</p>

```<code>ALTER PROCEDURE [dbo].[getipmp]
(
    @year varchar(4)
)
AS
BEGIN

    select  distinct carlinenm
    ,       null
    from [interchange].[dbo].[carline]
    WHERE (CarlineYear >= 1990 AND @year = '') OR CarlineYear = @year

    UNION ALL

    SELECT distinct
        cast(carlineyear as varchar(4))
    ,   'Y|' + rtrim(cast(carlineyear as varchar(4)))
    from [interchange].[dbo].[carline]
    WHERE carlineyear >= 1990
END
</code>```

Title: T-SQL IF problemo

Body:
I have the following stored procedure:

ALTER PROCEDURE [dbo].[getipmp]
@year varchar(4)
AS
BEGIN

select * from (

IF @year = ''
    select distinct carlinenm
    from [interchange].[dbo].[carline]
    WHERE CarlineYear >= 1990
ELSE
    select distinct carlinenm
    from [interchange].[dbo].[carline]
    WHERE CarlineYear = @year

UNION ALL

SELECT distinct cast(carlineyear as varchar(4)),'Y|' + rtrim(cast(carlineyear as varchar(4)))
from [interchange].[dbo].[carline]
WHERE carlineyear >= 1990

) U

END

SQL-Express is saying:

Msg 156, Level 15, State 1, Procedure getipmp, Line 15 [Batch Start Line 7]
Incorrect syntax near the keyword 'IF'.
Msg 102, Level 15, State 1, Procedure getipmp, Line 43 [Batch Start Line 7]
Incorrect syntax near ')'.

It refers to the "IF" at beginning and to the last ")" before the U.

Any idea what is wrong there?

Thanks!

Body:
Shouldnt it be:

ALTER PROCEDURE [dbo].[getipmp]
(
    @year varchar(4)
)
AS
BEGIN

    select  distinct carlinenm
    ,       null
    from [interchange].[dbo].[carline]
    WHERE (CarlineYear >= 1990 AND @year = '') OR CarlineYear = @year

    UNION ALL

    SELECT distinct
        cast(carlineyear as varchar(4))
    ,   'Y|' + rtrim(cast(carlineyear as varchar(4)))
    from [interchange].[dbo].[carline]
    WHERE carlineyear >= 1990
END


问:
C# Converting mixed JSON into an object
Yo Guys,

I'm currently trying to pass some mixed JSON, and was wondering if it was possible to do anything like the following?

```<code>struct example_data
{
    public Dictionary<string, List<string>> information {get; set;}
}

class TestClass
{
    static void Main(string[] args)
    {
        string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }"

        example_data deserialized_entry = JsonConvert.DeserializeObject<example_data>(test_string)
    }
}
</code>```

As you would expect the above code snippet fails, but I was hoping I could avoid wrapping each JSON entry in a JSON array or having to create a custom JSON reader in C#.

Any advice on the matter would be greatly appreciated.

答:
As you would expect the above code snippet fails

```<code>string test_string = @"{'EventSpecificInformation':
                               {
                               'measure':''
                               ,'Long name':'test_name'
                               ,'Short name':'test_s_name'
                               ,'Description':''
                               ,'Status':'Real (Imported)'
                               ,'Viewers':['Everyone']
                               ,'Modifiers':['Supervisor only']
                               ,'calculation':''
                               }
                           }"
</code>```

In the above you're clearly missing an ending ; at test_string assignment, this wont compile, fix this first (I'm sure it's a type-o). Next, this isn't valid json, you see all the ' in that json, it should be quotes: ". So in short, just replace the bad characters...

```<code> string test_string = @"{'EventSpecificInformation':
                               {
                               'measure':''
                               ,'Long name':'test_name'
                               ,'Short name':'test_s_name'
                               ,'Description':''
                               ,'Status':'Real (Imported)'
                               ,'Viewers':['Everyone']
                               ,'Modifiers':['Supervisor only']
                               ,'calculation':''
                               }
                           }".Replace("'", "\"");
</code>```

Note - As far as deserializing your json, create a new question with what you've tried (after fixing this), what isn't working and expected output; you've multiple issues, let's address one at a time.

Title: C# Converting mixed JSON into an object

Body:
Yo Guys,

I'm currently trying to pass some mixed JSON, and was wondering if it was possible to do anything like the following?

struct example_data
{
    public Dictionary<string, List<string>> information {get; set;}
}

class TestClass
{
    static void Main(string[] args)
    {
        string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }"

        example_data deserialized_entry = JsonConvert.DeserializeObject<example_data>(test_string)
    }
}

As you would expect the above code snippet fails, but I was hoping I could avoid wrapping each JSON entry in a JSON array or having to create a custom JSON reader in C#.

Any advice on the matter would be greatly appreciated.

Body:
As you would expect the above code snippet fails

string test_string = @"{'EventSpecificInformation':
                               {
                               'measure':''
                               ,'Long name':'test_name'
                               ,'Short name':'test_s_name'
                               ,'Description':''
                               ,'Status':'Real (Imported)'
                               ,'Viewers':['Everyone']
                               ,'Modifiers':['Supervisor only']
                               ,'calculation':''
                               }
                           }"

In the above you're clearly missing an ending ; at test_string assignment, this wont compile, fix this first (I'm sure it's a type-o). Next, this isn't valid json, you see all the ' in that json, it should be quotes: ". So in short, just replace the bad characters...

 string test_string = @"{'EventSpecificInformation':
                               {
                               'measure':''
                               ,'Long name':'test_name'
                               ,'Short name':'test_s_name'
                               ,'Description':''
                               ,'Status':'Real (Imported)'
                               ,'Viewers':['Everyone']
                               ,'Modifiers':['Supervisor only']
                               ,'calculation':''
                               }
                           }".Replace("'", "\"");

Note - As far as deserializing your json, create a new question with what you've tried (after fixing this), what isn't working and expected output; you've multiple issues, let's address one at a time.


问:
Ansible output extract package version using jq
I have below json output from ansible, I want to parse this file using jq.  I want to match packages name GeoIP and print version number.

How can I use jq to get this version number for matching package name? looking output like this

```<code>"GeoIP","1.5.0"
</code>```

sample ansible output

```<code>{
    "ansible_facts.packages": {
        "GConf2": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GConf2",
                "release": "8.el7",
                "source": "rpm",
                "version": "3.2.6"
            }
        ],
        "GeoIP": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GeoIP",
                "release": "14.el7",
                "source": "rpm",
                "version": "1.5.0"
            }
        ],
        "ImageMagick": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "ImageMagick",
                "release": "18.el7",
                "source": "rpm",
                "version": "6.7.8.9"
            }
        ],
    }
}
</code>```

答:
I assume you want to get a loop over all key-values attributes in the ansible_facts.packages, so it's recommended to use a Bash loop to iterate over it. Also the sample contents of the JSON you provided don't compile, I removed the comma 3 rows from the end.

You need one jq to get all the keys of the ansible_facts.packages and then in each iteration to get the version of the given key (package).

To get all the keys:

```<code>[http_offline@greenhat-30 tmp]$ cat file.json | jq '."ansible_facts.packages" | keys[]'
"GConf2"
"GeoIP"
"ImageMagick"
[http_offline@greenhat-30 tmp]$
</code>```

Loop:

```<code>for package in `cat file.json | jq '."ansible_facts.packages" | keys[]'`
do
VERSION=`cat file.json | jq ".\"ansible_facts.packages\".$package[0].version"`
echo "$package,$VERSION"
done
</code>```

Sample run:

```<code>[http_offline@greenhat-30 tmp]$ for package in `cat file.json | jq '."ansible_facts.packages" | keys[]'`
> do
> VERSION=`cat file.json | jq ".\"ansible_facts.packages\".$package[0].version"`
> echo "$package,$VERSION"
> done
"GConf2","3.2.6"
"GeoIP","1.5.0"
"ImageMagick","6.7.8.9"
[http_offline@greenhat-30 tmp]$
</code>```

Body:
I have below json output from ansible, I want to parse this file using jq.  I want to match packages name GeoIP and print version number.

How can I use jq to get this version number for matching package name? looking output like this

"GeoIP","1.5.0"

sample ansible output

{
    "ansible_facts.packages": {
        "GConf2": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GConf2",
                "release": "8.el7",
                "source": "rpm",
                "version": "3.2.6"
            }
        ],
        "GeoIP": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GeoIP",
                "release": "14.el7",
                "source": "rpm",
                "version": "1.5.0"
            }
        ],
        "ImageMagick": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "ImageMagick",
                "release": "18.el7",
                "source": "rpm",
                "version": "6.7.8.9"
            }
        ],
    }
}

Body:
I assume you want to get a loop over all key-values attributes in the ansible_facts.packages, so it's recommended to use a Bash loop to iterate over it. Also the sample contents of the JSON you provided don't compile, I removed the comma 3 rows from the end.

You need one jq to get all the keys of the ansible_facts.packages and then in each iteration to get the version of the given key (package).

To get all the keys:

[http_offline@greenhat-30 tmp]$ cat file.json | jq '."ansible_facts.packages" | keys[]'
"GConf2"
"GeoIP"
"ImageMagick"
[http_offline@greenhat-30 tmp]$

Loop:

for package in `cat file.json | jq '."ansible_facts.packages" | keys[]'`
do
VERSION=`cat file.json | jq ".\"ansible_facts.packages\".$package[0].version"`
echo "$package,$VERSION"
done

Sample run:

[http_offline@greenhat-30 tmp]$ for package in `cat file.json | jq '."ansible_facts.packages" | keys[]'`
> do
> VERSION=`cat file.json | jq ".\"ansible_facts.packages\".$package[0].version"`
> echo "$package,$VERSION"
> done
"GConf2","3.2.6"
"GeoIP","1.5.0"
"ImageMagick","6.7.8.9"
[http_offline@greenhat-30 tmp]$


问:
How to handle shell getopts with parameter containing blank spaces
I'm looking for a way to handle arguments containing blank spaces that has to be parsed
by shell getopts command.

```<code>while getopts ":a:i:o:e:v:u:" arg
  do
  echo "ARG is: $arg" >> /tmp/submit.log
  case "$arg" in
  a) arg1="$OPTARG" ;;
  i) arg2="$OPTARG" ;;
  o) arg3="$OPTARG" ;;
  ...
  u) argn="$OPTARG" ;;
  -) break ;;
  \?) ;;
  *) echo "unhandled option $arg" >> /tmp/submit.log ;;
  ?) echo $usage_string
     exit 1 ;;
  esac
done
</code>```

Now if -u has argument like "STRING WITH WHITE SPACE"
than just the first part of the string is triggered and the while loop doesn't go to the end.

many thanks.

答:
As Mat notes, your script fragment is already correct. If you're invoking your script from a shell, you need to quote arguments properly, e.g.

```<code>myscript -u "string with white space"
myscript -u 'string with white space'
myscript -u string\ with\ white\ space
myscript -u string' w'ith\ "whi"te" "''space
</code>```

Requiring these quotes is not a defect in your script, it's the way the calling shell works. All programs, scripts or otherwise, receive arguments as a list of strings. The quotes in the calling shell are used to sort these arguments into separate “words” (list elements). All the calls above (made from a unix shell) pass a list of three strings to the script: $0 is the script name (myscript), $1 is -u and $2 is the string string with white space.

Body:
I'm looking for a way to handle arguments containing blank spaces that has to be parsed
by shell getopts command.

while getopts ":a:i:o:e:v:u:" arg
  do
  echo "ARG is: $arg" >> /tmp/submit.log
  case "$arg" in
  a) arg1="$OPTARG" ;;
  i) arg2="$OPTARG" ;;
  o) arg3="$OPTARG" ;;
  ...
  u) argn="$OPTARG" ;;
  -) break ;;
  \?) ;;
  *) echo "unhandled option $arg" >> /tmp/submit.log ;;
  ?) echo $usage_string
     exit 1 ;;
  esac
done

Now if -u has argument like "STRING WITH WHITE SPACE"
than just the first part of the string is triggered and the while loop doesn't go to the end.

many thanks.

Body:
As Mat notes, your script fragment is already correct. If you're invoking your script from a shell, you need to quote arguments properly, e.g.

myscript -u "string with white space"
myscript -u 'string with white space'
myscript -u string\ with\ white\ space
myscript -u string' w'ith\ "whi"te" "''space

Requiring these quotes is not a defect in your script, it's the way the calling shell works. All programs, scripts or otherwise, receive arguments as a list of strings. The quotes in the calling shell are used to sort these arguments into separate “words” (list elements). All the calls above (made from a unix shell) pass a list of three strings to the script: $0 is the script name (myscript), $1 is -u and $2 is the string string with white space.


问:
How to add new specs content via impex on electronic store provide by hybris?
Hybris comes with an OOTB Electronics store.  All the products have a Specs page with a long list of specs.  Any anyone point to some documentation on how to add or remove one of those specs via impex and/or code?</p>

答:
I am not sure which exact page you have mentioned about. In general, all the product data related ImpEx files are in hybris ▸ bin ▸ modules ▸ b2c-accelerator ▸ electronicsstore ▸ resources ▸ electronicsstore ▸ import ▸ sampledata ▸ productCatalogs ▸ electronicsProductCatalog. Most likely, you are looking for products_en.impex in this path.

You can insert new data or update the existing data by executing similar ImpEx. Check here for information on ImpEx syntax.


问:
How to render jsx based on some condition using ternary operation in react?
i want to render the jsx based on a condition using ternary operation in react.

What i am trying to do?

i have the code like below that works perfect.

```<code>return (
    {this.has_rendered() && this.items_loaded()
        ? <ChildComponent/>
        : <ChildComponent
            on_prev={null}/>}
)
</code>```

Now i want to check for other condition if its !current_user then i want to pass another prop named "on_next" to ChildComponent.

```<code>{this.has_rendered() && this.items_loaded() && !current_user &&
    <ChildComponent/>}
{!this.has_rendered() && !this.items_loaded() && !current_user &&
    <ChildComponent on_prev={null}/>}
{this.has_rendered() && this.itemss_loaded() && current_user &&
    <ChildComponent
        on_next={somevalue}/>}
{!this.has_rendered() && !this.items_loaded() && current_user &&
                <NavigationContent
                    on_prev={null}
                    on_next={somevalue}/>}
</code>```

The above code works but as you see there is repetition of code. how can i fix this with ternary operator. could someone help me with this.

thanks.

答:
If on_prev and on_next attributes can have values all the time, consider this approch:

```<code>return (
    { this.has_rendered() &&
      <ChildComponent
        on_prev={this.items_loaded() ? somevalue : null }
        on_next={current_user ? someanothervalue : null} />
    }
)
</code>```

Body:
i want to render the jsx based on a condition using ternary operation in react.

What i am trying to do?

i have the code like below that works perfect.

return (
    {this.has_rendered() && this.items_loaded()
        ? <ChildComponent/>
        : <ChildComponent
            on_prev={null}/>}
)

Now i want to check for other condition if its !current_user then i want to pass another prop named "on_next" to ChildComponent.

{this.has_rendered() && this.items_loaded() && !current_user &&
    <ChildComponent/>}
{!this.has_rendered() && !this.items_loaded() && !current_user &&
    <ChildComponent on_prev={null}/>}
{this.has_rendered() && this.itemss_loaded() && current_user &&
    <ChildComponent
        on_next={somevalue}/>}
{!this.has_rendered() && !this.items_loaded() && current_user &&
                <NavigationContent
                    on_prev={null}
                    on_next={somevalue}/>}

The above code works but as you see there is repetition of code. how can i fix this with ternary operator. could someone help me with this.

thanks.

Body:
If on_prev and on_next attributes can have values all the time, consider this approch:

return (
    { this.has_rendered() &&
      <ChildComponent
        on_prev={this.items_loaded() ? somevalue : null }
        on_next={current_user ? someanothervalue : null} />
    }
)


问:
Show length of polygon in Mapbox GL JS draw
I'm new to coding in javascript etc. My backround is a little knowlegde in Python.

I'm following this example https://docs.mapbox.com/mapbox-gl-js/example/mapbox-gl-draw/ of how to draw a polygon in Mapbox and then showing the area of the polygon(s).

What I want also to do is to show the length of each drawn side of the polygon and be able to show it for the user and not only the area.

It would be extra-great if a label of the length could be shown next to each side of the polygon in the map. Any tips of how to do this? I would be really grateful, thanks!

答:
I'd suggest you use the library turf, which has really useful helper methods for this kind of geographic manipulation, and coincidentally (or not), the example you mention also uses it to calculate the area.

So what you'll need to do is to extract the 4 or more points that form the polygon once it is drawn from data (which will have the form of a geojson polygon). Then, with those points as input and using the helper length you can retrieve the lengths of each side of the polygon.

If then you'd like to show those lengths above the mid point of each respective line of the polygon, you could use the helper midpoint to get the coordinates on which you could create a marker with that information. To create markers you can check this example (although in your case you'd probably want to set the flag draggeable to false).

Hope this helps :)


问:
Get value from exact JSONpath level
I want to extract values from an JSON document with using the path operators.
For example I get all the product IDs included in the file via $..product_id.
But for getting the "id" when I use $..id I get an output for each id element, no matter on which level of the JSON the variable is.
For example in my output I get an row for the id "12345678" as well as for "11223344" which should not be because it is a subset of the first ID.

```<code> {
"next_offset": 20,
"records": [
    {
        "id": "12345678",
        "date": "2020-02-14",
        "product_id": "asdf1234",
        "product_name": "Product_test^_1",
        "template_link": {
            "name": "aassddff",
            "id": "11223344",
            "_acl": {
                "fields": [],
                "_hash": "345thvz356b56v456b"
            }
        },
        ....
    }
]
</code>```

}

How can I set the path operator to only access the "id" fields of one specific level?

答: For the JSON shown in your question, use $.records.*.id.

Title: Get value from exact JSONpath level

Body:
I want to extract values from an JSON document with using the path operators.
For example I get all the product IDs included in the file via $..product_id.
But for getting the "id" when I use $..id I get an output for each id element, no matter on which level of the JSON the variable is.
For example in my output I get an row for the id "12345678" as well as for "11223344" which should not be because it is a subset of the first ID.

 {
"next_offset": 20,
"records": [
    {
        "id": "12345678",
        "date": "2020-02-14",
        "product_id": "asdf1234",
        "product_name": "Product_test^_1",
        "template_link": {
            "name": "aassddff",
            "id": "11223344",
            "_acl": {
                "fields": [],
                "_hash": "345thvz356b56v456b"
            }
        },
        ....
    }
]

}

How can I set the path operator to only access the "id" fields of one specific level?


问:
Flex 4 INLINE Layout help required
In FLEX 4 Layout, how can one display a sequence of images, text, other object types INLINE wrt each other. For example:
TEXT1 IMAGE1 OBJECT1 (END OF LINE)
(NEW LINE)  ABCTEXT3 (END OF LINE)
(NEW LINE) XOBJECT2  (END OF LINE)

The horizontal span is not fixed for any element.
Vertical span is not a constraint.
Just that elements should follow each other INLINE.

答:
There's the TileGroup.

That will automatically wrap your items, though it does so in a grid format. If you want each line to be horizontally aligned I'm not sure how to do that. That's what I'm looking for at the moment!

ContentLicense: CC BY-SA 2.5

Title: Flex 4 INLINE Layout help required


问:
Conditionally moving the position of a single data label in a pie chart
The following sample code will generate the donut chart I'll use as my example:

```<code>import matplotlib.pyplot as plt
%matplotlib inline

# Following should supposedly set the font correctly:
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Muli'] + plt.rcParams['font.sans-serif']
plt.rcParams['font.weight'] = 'extra bold'

size_of_groups=[12,11,30,0.3]

colors = ['#a1daaa','#bbbbb4','#444511','#1afff2']

import matplotlib as mpl
mpl.rcParams['text.color'] = '#273859'

# Create a pieplot
my_pie,texts,_ = plt.pie(size_of_groups,radius = 1.2,colors=colors,autopct="%.1f%%",
textprops = {'color':'w',
             'size':15  #, 'weight':"extra bold"
            }, pctdistance=0.75, labeldistance=0.7) #pctdistance and labeldistance change label positions.
labels=['High','Low','Normal','NA']
plt.legend(my_pie,labels,loc='lower center',ncol=2,bbox_to_anchor=(0.5, -0.2))
plt.setp(my_pie, width=0.6, edgecolor='white')
fig1 = plt.gcf()
fig1.show()
</code>```

The above outputs this:

Mostly, this is great. Finally I got a nice looking donut chart!

But there is just one last thing to finesse - when the portion of the donut chart is very small (like the 0.6%), I need the labels to be moved out of the chart, and possibly colored black instead.

I managed to do something similar for bar charts using plt.text, but I don't think that will be feasible with pie charts at all. I figure someone has definitely solved a similar problem before, but I can't readily fine any decent solutions.

答:
Here is a way to move all percent-texts for patches smaller than some given amount (5 degrees in the code example).  Note that this will also fail when there would be multiple small pieces close to each other.

```<code>import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

size_of_groups = [12, 11, 30, 0.3]
colors = ['#a1daaa', '#bbbbb4', '#444511', '#1afff2']
my_pie, texts, pct_txts = plt.pie(size_of_groups, radius=1.2, colors=colors, autopct="%.1f%%",
                                  textprops={'color': 'w', 'size': 15}, pctdistance=0.75,
                                  labeldistance=0.7)
labels = ['High', 'Low', 'Normal', 'NA']
plt.legend(my_pie, labels, loc='lower center', ncol=2, bbox_to_anchor=(0.5, -0.2))
plt.setp(my_pie, width=0.6, edgecolor='white')

for patch, txt in zip(my_pie, pct_txts):
    if (patch.theta2 - patch.theta1) <= 5:
        # the angle at which the text is normally located
        angle = (patch.theta2 + patch.theta1) / 2.
        # new distance to the pie center
        x = patch.r * 1.2 * np.cos(angle * np.pi / 180)
        y = patch.r * 1.2 * np.sin(angle * np.pi / 180)
        # move text to new position
        txt.set_position((x, y))
        txt.set_color('black')
plt.tight_layout()
plt.show()
</code>```

Body:
The following sample code will generate the donut chart I'll use as my example:

import matplotlib.pyplot as plt
%matplotlib inline

# Following should supposedly set the font correctly:
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Muli'] + plt.rcParams['font.sans-serif']
plt.rcParams['font.weight'] = 'extra bold'

size_of_groups=[12,11,30,0.3]

colors = ['#a1daaa','#bbbbb4','#444511','#1afff2']

import matplotlib as mpl
mpl.rcParams['text.color'] = '#273859'

# Create a pieplot
my_pie,texts,_ = plt.pie(size_of_groups,radius = 1.2,colors=colors,autopct="%.1f%%",
textprops = {'color':'w',
             'size':15  #, 'weight':"extra bold"
            }, pctdistance=0.75, labeldistance=0.7) #pctdistance and labeldistance change label positions.
labels=['High','Low','Normal','NA']
plt.legend(my_pie,labels,loc='lower center',ncol=2,bbox_to_anchor=(0.5, -0.2))
plt.setp(my_pie, width=0.6, edgecolor='white')
fig1 = plt.gcf()
fig1.show()

The above outputs this:

Mostly, this is great. Finally I got a nice looking donut chart!

But there is just one last thing to finesse - when the portion of the donut chart is very small (like the 0.6%), I need the labels to be moved out of the chart, and possibly colored black instead.

I managed to do something similar for bar charts using plt.text, but I don't think that will be feasible with pie charts at all. I figure someone has definitely solved a similar problem before, but I can't readily fine any decent solutions.

Body:
Here is a way to move all percent-texts for patches smaller than some given amount (5 degrees in the code example).  Note that this will also fail when there would be multiple small pieces close to each other.

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

size_of_groups = [12, 11, 30, 0.3]
colors = ['#a1daaa', '#bbbbb4', '#444511', '#1afff2']
my_pie, texts, pct_txts = plt.pie(size_of_groups, radius=1.2, colors=colors, autopct="%.1f%%",
                                  textprops={'color': 'w', 'size': 15}, pctdistance=0.75,
                                  labeldistance=0.7)
labels = ['High', 'Low', 'Normal', 'NA']
plt.legend(my_pie, labels, loc='lower center', ncol=2, bbox_to_anchor=(0.5, -0.2))
plt.setp(my_pie, width=0.6, edgecolor='white')

for patch, txt in zip(my_pie, pct_txts):
    if (patch.theta2 - patch.theta1) <= 5:
        # the angle at which the text is normally located
        angle = (patch.theta2 + patch.theta1) / 2.
        # new distance to the pie center
        x = patch.r * 1.2 * np.cos(angle * np.pi / 180)
        y = patch.r * 1.2 * np.sin(angle * np.pi / 180)
        # move text to new position
        txt.set_position((x, y))
        txt.set_color('black')
plt.tight_layout()
plt.show()


问:
C# background worker not triggering dowork event on any pc besides my own
I'm having a really weird issue with a background worker in one of my applications. I recently overhauled it slightly with some GUI fixes but now when someone on another PC runs the .exe or installs my OneClick deployment the background worker doesn't enter the dowork event. The logic has not changed between the 2 releases. I've done a compare and besides adding more error logging nothing has changed.

I've gone as far as to include message boxes and breakpoints in the dowork event but it never enters it anywhere besides on my own PC. Even when i remote debug it doesnt enter the DoWork event

Any suggestions?

Button click even calls the runworkerasync event

```<code>private void ScanButton_Click_1(object sender, RoutedEventArgs e)
    {

        Scan = new BackgroundWorker();
        Scan.WorkerReportsProgress = true;
        Scan.DoWork += new DoWorkEventHandler(Scan_DoWork);
        Scan.ProgressChanged += new ProgressChangedEventHandler(Scan_ProgressChanged);
        Scan.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Scan_RunWorkerCompleted);
        Scan.RunWorkerAsync();
    }
</code>```

Below is the code that runs the DoWork event. Ive removed the other functions it does for simplicity. All it does is run a function that returns a string and places it inside of the list called scanresults.

```<code>private BackgroundWorker Scan;

    public void Scan_DoWork(object sender, DoWorkEventArgs e)
    {

        System.Windows.Forms.MessageBox.Show("Inside the DoWork");

        BackgroundWorker bw = sender as BackgroundWorker;

        float percentageDone = 0.0F;

        ScanResults = new List<string>();

        try
        {

            System.Windows.Forms.MessageBox.Show("Doing first scan check");

            ScanResults.Add(Functions.LocalComputerName());
            percentageDone = ((1 / 1f) * 100f);
            bw.ReportProgress((int)percentageDone);

        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message, "Error Encountered", MessageBoxButton.OK, MessageBoxImage.Exclamation);
        }
    }

public void Scan_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        try
        {
            if (ScanResults.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("Empty");
                return;
            }
            MachineNameBox.Text = ScanResults[0];
        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message, "Error Encountered", MessageBoxButton.OK, MessageBoxImage.Exclamation);
        }
    }
</code>```

It completely ignores the dowork event and enters the runworkercomplete event and passes a error for the index obviously because the list hasnt been filled as the function  do that has been skipped. Again this works perfectly on my PC but not on others no matter how i release it to them.

Thanks for any assistance

答:
Jay Riggs' answer is the right one, but I just wanted to add that exceptions caused by certain issues in DoWork won't even be caught by a try...catch in DoWork, which was amazing to me.

I had a situation where my DoWork routine used a third party library which in turn used another library, which was missing. When my application called DoWork, even though the library wasn't used right away and even though the entire method was wrapped in a try...catch, it failed outside the method and called RunWorkerCompleted as if all was well. So the background job did nothing but also didn't throw an exception, it just quietly put the exception in the Error property, which I was ignoring, because I never knew about it. This took some very careful debugging to uncover.

My takeaway is that you always need to check for an error in RunWorkerCompleted and that this is very counter-intuitive behavior. If Jay Riggs' answer wasn't here, I can't imagine how long it would have taken to figure it out.

Body:
I'm having a really weird issue with a background worker in one of my applications. I recently overhauled it slightly with some GUI fixes but now when someone on another PC runs the .exe or installs my OneClick deployment the background worker doesn't enter the dowork event. The logic has not changed between the 2 releases. I've done a compare and besides adding more error logging nothing has changed.

I've gone as far as to include message boxes and breakpoints in the dowork event but it never enters it anywhere besides on my own PC. Even when i remote debug it doesnt enter the DoWork event

Any suggestions?

Button click even calls the runworkerasync event

private void ScanButton_Click_1(object sender, RoutedEventArgs e)
    {

        Scan = new BackgroundWorker();
        Scan.WorkerReportsProgress = true;
        Scan.DoWork += new DoWorkEventHandler(Scan_DoWork);
        Scan.ProgressChanged += new ProgressChangedEventHandler(Scan_ProgressChanged);
        Scan.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Scan_RunWorkerCompleted);
        Scan.RunWorkerAsync();
    }

Below is the code that runs the DoWork event. Ive removed the other functions it does for simplicity. All it does is run a function that returns a string and places it inside of the list called scanresults.

private BackgroundWorker Scan;

    public void Scan_DoWork(object sender, DoWorkEventArgs e)
    {

        System.Windows.Forms.MessageBox.Show("Inside the DoWork");

        BackgroundWorker bw = sender as BackgroundWorker;

        float percentageDone = 0.0F;

        ScanResults = new List<string>();

        try
        {

            System.Windows.Forms.MessageBox.Show("Doing first scan check");

            ScanResults.Add(Functions.LocalComputerName());
            percentageDone = ((1 / 1f) * 100f);
            bw.ReportProgress((int)percentageDone);

        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message, "Error Encountered", MessageBoxButton.OK, MessageBoxImage.Exclamation);
        }
    }

public void Scan_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        try
        {
            if (ScanResults.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("Empty");
                return;
            }
            MachineNameBox.Text = ScanResults[0];
        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message, "Error Encountered", MessageBoxButton.OK, MessageBoxImage.Exclamation);
        }
    }

It completely ignores the dowork event and enters the runworkercomplete event and passes a error for the index obviously because the list hasnt been filled as the function  do that has been skipped. Again this works perfectly on my PC but not on others no matter how i release it to them.

Thanks for any assistance


问:
Matrix which is 1 when row and column are both odd or both even
I want to create a matrix which which has:

The value 1 if the row is odd and the column is odd

The value 1 if the row is even and the column is even

The value 0 Otherwise.

I want to get the same results as the code below, but in a one line (command window) expression:

```<code> N=8;
 A = zeros(N);

 for row = 1:1:length(A)
     for column = 1:1:length(A)
        if(mod(row,2) == 1 && mod(column,2) == 1)

             A(row,column*(mod(column,2) == 1)) = 1;

         elseif(mod(row,2)== 0 && mod(column,2) == 0 )

             A(row,column*(mod(column,2) == 0)) = 1;

        end
     end
  end
 disp(A)
</code>```

This is the expected result:

```<code> 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
</code>```

答:
You can try the function meshgrid to generate mesh grids and use mod to determine even or odd

```<code>[x,y] = meshgrid(1:N,1:N);
A = mod(x+y+1,2);
</code>```

such that

```<code>>> A
A =

   1   0   1   0   1   0   1   0
   0   1   0   1   0   1   0   1
   1   0   1   0   1   0   1   0
   0   1   0   1   0   1   0   1
   1   0   1   0   1   0   1   0
   0   1   0   1   0   1   0   1
   1   0   1   0   1   0   1   0
   0   1   0   1   0   1   0   1
</code>```

Body:
I want to create a matrix which which has:

The value 1 if the row is odd and the column is odd

The value 1 if the row is even and the column is even

The value 0 Otherwise.

I want to get the same results as the code below, but in a one line (command window) expression:

 N=8;
 A = zeros(N);

 for row = 1:1:length(A)
     for column = 1:1:length(A)
        if(mod(row,2) == 1 && mod(column,2) == 1)

             A(row,column*(mod(column,2) == 1)) = 1;

         elseif(mod(row,2)== 0 && mod(column,2) == 0 )

             A(row,column*(mod(column,2) == 0)) = 1;

        end
     end
  end
 disp(A)

This is the expected result:

 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1

Body:
You can try the function meshgrid to generate mesh grids and use mod to determine even or odd

[x,y] = meshgrid(1:N,1:N);
A = mod(x+y+1,2);

such that

>> A
A =

   1   0   1   0   1   0   1   0
   0   1   0   1   0   1   0   1
   1   0   1   0   1   0   1   0
   0   1   0   1   0   1   0   1
   1   0   1   0   1   0   1   0
   0   1   0   1   0   1   0   1
   1   0   1   0   1   0   1   0
   0   1   0   1   0   1   0   1


问:
Reactive messaging AMQP and Service Bus with Open Liberty
Open Liberty comes with the feature mpReactiveMessaging-1.0 which includes a Kafka connector.

I want to integrate with Azure Service Bus and I use the Smallrye AMQP connector (version 1.0.8).

When trying to send to a Service Bus queue using @Outgoing-annotation I get

javax.net.ssl.SSLHandshakeException: Failed to create SSL connection

which I spotted when debugging the Smallrye implementation.

I have looked through the Proton, vert.x and Azure Service Bus AMQP docs, but I cannot find examples or indication of what is wrong with my set of MP config properties for a working AMQP Service Bus connection.

```<code>mp.messaging.outgoing.servicebus.address=xxxxxxx
mp.messaging.outgoing.servicebus.connector=smallrye-amqp
mp.messaging.outgoing.servicebus.host=xxxxx.servicebus.windows.net
mp.messaging.outgoing.servicebus.port=5672
mp.messaging.outgoing.servicebus.username=my_saspolicyname
mp.messaging.outgoing.servicebus.password=the_saskey
mp.messaging.outgoing.servicebus.use-ssl=true
mp.messaging.outgoing.servicebus.hostname-verification-algorithm=''
mp.messaging.outgoing.servicebus.containerId=mycontainer
mp.messaging.outgoing.servicebus.amqp-use-ssl=true
</code>```

答:
Open Liberty, by default, does not trust the standard list of CA certificates provided by Java. I'm not familiar with Azure Service Bus, but since I can't find anything in the docs about configuring certificates, I'm assuming it uses a certificate signed by a trusted authority.

In this case, you probably need to add this to your server.xml to tell OpenLiberty to trust the CA certs included with Java.

```<code><ssl id="defaultSSLConfig" trustDefaultCerts="true"/>
</code>```

This option was added in Open Liberty version 19.0.0.12

Body:
Open Liberty comes with the feature mpReactiveMessaging-1.0 which includes a Kafka connector.

I want to integrate with Azure Service Bus and I use the Smallrye AMQP connector (version 1.0.8).

When trying to send to a Service Bus queue using @Outgoing-annotation I get

javax.net.ssl.SSLHandshakeException: Failed to create SSL connection

which I spotted when debugging the Smallrye implementation.

I have looked through the Proton, vert.x and Azure Service Bus AMQP docs, but I cannot find examples or indication of what is wrong with my set of MP config properties for a working AMQP Service Bus connection.

mp.messaging.outgoing.servicebus.address=xxxxxxx
mp.messaging.outgoing.servicebus.connector=smallrye-amqp
mp.messaging.outgoing.servicebus.host=xxxxx.servicebus.windows.net
mp.messaging.outgoing.servicebus.port=5672
mp.messaging.outgoing.servicebus.username=my_saspolicyname
mp.messaging.outgoing.servicebus.password=the_saskey
mp.messaging.outgoing.servicebus.use-ssl=true
mp.messaging.outgoing.servicebus.hostname-verification-algorithm=''
mp.messaging.outgoing.servicebus.containerId=mycontainer
mp.messaging.outgoing.servicebus.amqp-use-ssl=true

Body:
Open Liberty, by default, does not trust the standard list of CA certificates provided by Java. I'm not familiar with Azure Service Bus, but since I can't find anything in the docs about configuring certificates, I'm assuming it uses a certificate signed by a trusted authority.

In this case, you probably need to add this to your server.xml to tell OpenLiberty to trust the CA certs included with Java.

<ssl id="defaultSSLConfig" trustDefaultCerts="true"/>

This option was added in Open Liberty version 19.0.0.12