问:
AES 128 ECB decryption nodejs
https://www.devglan.com/online-tools/aes-encryption-decryption

Encrypted data results as image

now if i decrypt the result using Node.js

```<code>const CryptoJS = require('crypto-js');

var bytes  = CryptoJS.AES.decrypt('HcMV322sPPrFonlvXZ5pvFpXABVrxYVAXrEr9vcu7TIFOPNQVGq5svEv3959sRDxkDHB/nav80iGMPBiz8bDeA==', 'my secretkey 123');

var originalText = bytes.toString(CryptoJS.enc.Utf8);

console.log(originalText, '--->');
</code>```

image
results in empty string

答:
```<code>let keyUtf8 = CryptoJS.enc.Utf8.parse(secretKey)

ENC = CryptoJS.AES.decrypt(ENC, keyUtf8, { mode: CryptoJS.mode.ECB,  keySize: 128 });

ENC = CryptoJS.enc.Utf8.stringify(ENC).toString();
</code>```

Title: AES 128 ECB decryption nodejs

Body:
https://www.devglan.com/online-tools/aes-encryption-decryption

Encrypted data results as image

now if i decrypt the result using Node.js

const CryptoJS = require('crypto-js');

var bytes  = CryptoJS.AES.decrypt('HcMV322sPPrFonlvXZ5pvFpXABVrxYVAXrEr9vcu7TIFOPNQVGq5svEv3959sRDxkDHB/nav80iGMPBiz8bDeA==', 'my secretkey 123');

var originalText = bytes.toString(CryptoJS.enc.Utf8);

console.log(originalText, '--->');

image
results in empty string


来源: stackexchange

问:
Merge Excel workbooks to one Worksheet
I am trying to merge 250 database excel workbooks into one continuous worksheet.

All of the workbooks have the same kind of data, with the same headers.

I have tried using this VBA code:

```<code>Sub mergeFiles()
    'Merges all files in a folder to a main file.

    'Define variables:
    Dim numberOfFilesChosen, i As Integer
    Dim tempFileDialog As fileDialog
    Dim mainWorkbook, sourceWorkbook As Workbook
    Dim tempWorkSheet As Worksheet

    Set mainWorkbook = Application.ActiveWorkbook
    Set tempFileDialog = Application.fileDialog(msoFileDialogFilePicker)

    'Allow the user to select multiple workbooks
    tempFileDialog.AllowMultiSelect = True

    numberOfFilesChosen = tempFileDialog.Show

    'Loop through all selected workbooks
    For i = 1 To tempFileDialog.SelectedItems.Count

        'Open each workbook
        Workbooks.Open tempFileDialog.SelectedItems(i)

        Set sourceWorkbook = ActiveWorkbook

        'Copy each worksheet to the end of the main workbook
        For Each tempWorkSheet In sourceWorkbook.Worksheets
            tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
        Next tempWorkSheet

        'Close the source workbook
        sourceWorkbook.Close
    Next i

End Sub
</code>```

The code works fine, but it creates a new sheet for every workbook, instead of copying the data to the bottom row of 1 sheet.

答:
I used following macro to combine many CSV files in one worksheet in a new workbook.. You may need to make some changes to suit your need</p>

```<code>Sub GetFromCSVs()
  Dim WB As Workbook
  Dim R As Range
  Dim bFirst As Boolean
  Dim stFile As String
  Dim stPath As String
  stPath = "D:\CSV Files\" ' change the path to suit
  stFile = Dir(stPath & "*.csv")
  'bFirst = True
  Set R = Workbooks.Add(xlWorksheet).Sheets(1).Range("A1")
  Do Until stFile = ""
    Set WB = Workbooks.Open(stPath  & stFile, ReadOnly:=True)
    'If bFirst Then
     ' WB.Sheets(1).Range("A1").CurrentRegion.Copy Destination:=R
      WB.Sheets(1).Range(Selection, Range("A1").SpecialCells(xlLastCell)).Copy Destination:=R
      Set R = R.Offset(R.SpecialCells(xlLastCell).Row + 1 - R.Row, 0)

      'Set R = Range("A1").Offset(ActiveCell.SpecialCells(xlLastCell).Row, 0)
      'bFirst = False
    'Else
      'WB.Sheets(1).Range("A1").CurrentRegion.Columns(2).Copy Destination:=R
      'Set R = R.Offset(, 1)
    'End If
    WB.Close saveChanges:=False
    stFile = Dir()  ' next file
  Loop
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Title: Merge Excel workbooks to one Worksheet

Body:
I am trying to merge 250 database excel workbooks into one continuous worksheet.

All of the workbooks have the same kind of data, with the same headers.

I have tried using this VBA code:

Sub mergeFiles()
    'Merges all files in a folder to a main file.

    'Define variables:
    Dim numberOfFilesChosen, i As Integer
    Dim tempFileDialog As fileDialog
    Dim mainWorkbook, sourceWorkbook As Workbook
    Dim tempWorkSheet As Worksheet

    Set mainWorkbook = Application.ActiveWorkbook
    Set tempFileDialog = Application.fileDialog(msoFileDialogFilePicker)

    'Allow the user to select multiple workbooks
    tempFileDialog.AllowMultiSelect = True

    numberOfFilesChosen = tempFileDialog.Show

    'Loop through all selected workbooks
    For i = 1 To tempFileDialog.SelectedItems.Count

        'Open each workbook
        Workbooks.Open tempFileDialog.SelectedItems(i)

        Set sourceWorkbook = ActiveWorkbook

        'Copy each worksheet to the end of the main workbook
        For Each tempWorkSheet In sourceWorkbook.Worksheets
            tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
        Next tempWorkSheet

        'Close the source workbook
        sourceWorkbook.Close
    Next i

End Sub

The code works fine, but it creates a new sheet for every workbook, instead of copying the data to the bottom row of 1 sheet.

Body:
I used following macro to combine many CSV files in one worksheet in a new workbook.. You may need to make some changes to suit your need

Sub GetFromCSVs()
  Dim WB As Workbook
  Dim R As Range
  Dim bFirst As Boolean
  Dim stFile As String
  Dim stPath As String
  stPath = "D:\CSV Files\" ' change the path to suit
  stFile = Dir(stPath & "*.csv")
  'bFirst = True
  Set R = Workbooks.Add(xlWorksheet).Sheets(1).Range("A1")
  Do Until stFile = ""
    Set WB = Workbooks.Open(stPath  & stFile, ReadOnly:=True)
    'If bFirst Then
     ' WB.Sheets(1).Range("A1").CurrentRegion.Copy Destination:=R
      WB.Sheets(1).Range(Selection, Range("A1").SpecialCells(xlLastCell)).Copy Destination:=R
      Set R = R.Offset(R.SpecialCells(xlLastCell).Row + 1 - R.Row, 0)

      'Set R = Range("A1").Offset(ActiveCell.SpecialCells(xlLastCell).Row, 0)
      'bFirst = False
    'Else
      'WB.Sheets(1).Range("A1").CurrentRegion.Columns(2).Copy Destination:=R
      'Set R = R.Offset(, 1)
    'End If
    WB.Close saveChanges:=False
    stFile = Dir()  ' next file
  Loop
End Sub


问:
Angular 6 project displays 404 error after refresh
Refreshing my angular page gives me a 404 server error, it does the same if I manually navigate to directory in the search bar. I am hosting through an IIS Server.

This problem only occurs whenever I build my angular project with ng build --prod and then upload it to my web server. Many people say you should use the hash method, but I don't want a hash to be displayed inside my url, and it's a very old method. Some people also say I should change my <base> tag in my , but that hasn't worked.

Here's my  tag from my index.html if it is helpful.

```<code><head>
<!-- META DATA -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- APP -->
<title>SebastianElstadt</title>
<base href="/">
<link rel="icon" type="image/x-icon" href="assets/images/app-icon.png">

<!-- STYLES -->
<link rel="stylesheet" href="[fontawesome cdn]">
</head>
</code>```

I also use a component which gets displayed if the entered URL doesn't match any of my defined paths. But it doesn't get displayed.

So to summarize, whenever I refresh my page or manually navigate in the search bar on my angular site, it displays a 404 Server Error page. And I don't want to use the hash method.

答:
This will solve your problem, add .htaccess file to the root of your project

and put this content

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [L]
</IfModule>
</code>```

Body:
Refreshing my angular page gives me a 404 server error, it does the same if I manually navigate to directory in the search bar. I am hosting through an IIS Server.

This problem only occurs whenever I build my angular project with ng build --prod and then upload it to my web server. Many people say you should use the hash method, but I don't want a hash to be displayed inside my url, and it's a very old method. Some people also say I should change my <base> tag in my , but that hasn't worked.

Here's my  tag from my index.html if it is helpful.

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

<title>SebastianElstadt</title>
<base href="/">
<link rel="icon" type="image/x-icon" href="assets/images/app-icon.png">

<link rel="stylesheet" href="[fontawesome cdn]">

I also use a component which gets displayed if the entered URL doesn't match any of my defined paths. But it doesn't get displayed.

So to summarize, whenever I refresh my page or manually navigate in the search bar on my angular site, it displays a 404 Server Error page. And I don't want to use the hash method.

Body:
This will solve your problem, add .htaccess file to the root of your project

and put this content

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [L]
</IfModule>


问:
How to combined similar-named nested classes from a derived and its base class
I was working on a small project where I created standard implementations of add-ons for a system. These standard implementations would set up things like logging, configuration, etc. all in a uniform way. All with maintainability and re-usability in mind.

Now the thing I am struggling with right now is how to handle names of settings. Before I always created a nested class Settings in with I declared some const string values like

public const string BananaSetting = "BananaSetting";

so I pretty much never could misspell a setting's name ever again.

I however have an base class which should have a setting called DEBUG, to use as a generic debug-enabling setting; but also add-on specific settings, which only exist for that one specific add-on.
Seeing as I base every derived class on the class that has the DEBUG setting nested class, any derived class that tries to declare a similar nested class called Settings will trigger a compiler warning:

DerivedClass.Settings hides inherited member 'BaseClass.Settings'. Use the new keyword if hiding was intended.

But I do not want to hide it. What I would really like to do is combine the two Settings classes into one. Is there any way to do this, or is there an existing design pattern of some sort to do this correctly?

```<code>public abstract class BaseClass
{
    public class Settings
    {
        public const string BananaSetting = "BananaSetting";
    }

    public abstract void BaseAbstractMethod();
    public void BaseMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
    }
}

public class DerivedClass : BaseClass
{
    public class Settings
    {
        public const string DerivedBananaSetting = "DerivedBananaSetting";
    }

    public override void BaseAbstractMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
        var subSettingValue = settingsDictionary[Settings.DerivedBananaSetting];
    }
}
</code>```

答:
You need to make the settings class in the derived class new because it has the same name as the one in the base class. To be able to access the base settings in the derived class, you also need to inherit the nested settings class:

```<code>public class DerivedClass : BaseClass
{
    public new class Settings : BaseClass.Settings
    {
        public const string DerivedBananaSetting = "DerivedBananaSetting";
    }
// etc..
</code>```

The rest of your code doesn't change.

Body:
I was working on a small project where I created standard implementations of add-ons for a system. These standard implementations would set up things like logging, configuration, etc. all in a uniform way. All with maintainability and re-usability in mind.

Now the thing I am struggling with right now is how to handle names of settings. Before I always created a nested class Settings in with I declared some const string values like

public const string BananaSetting = "BananaSetting";

so I pretty much never could misspell a setting's name ever again.

I however have an base class which should have a setting called DEBUG, to use as a generic debug-enabling setting; but also add-on specific settings, which only exist for that one specific add-on.
Seeing as I base every derived class on the class that has the DEBUG setting nested class, any derived class that tries to declare a similar nested class called Settings will trigger a compiler warning:

DerivedClass.Settings hides inherited member 'BaseClass.Settings'. Use the new keyword if hiding was intended.

But I do not want to hide it. What I would really like to do is combine the two Settings classes into one. Is there any way to do this, or is there an existing design pattern of some sort to do this correctly?

public abstract class BaseClass
{
    public class Settings
    {
        public const string BananaSetting = "BananaSetting";
    }

    public abstract void BaseAbstractMethod();
    public void BaseMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
    }
}

public class DerivedClass : BaseClass
{
    public class Settings
    {
        public const string DerivedBananaSetting = "DerivedBananaSetting";
    }

    public override void BaseAbstractMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
        var subSettingValue = settingsDictionary[Settings.DerivedBananaSetting];
    }
}

Body:
You need to make the settings class in the derived class new because it has the same name as the one in the base class. To be able to access the base settings in the derived class, you also need to inherit the nested settings class:

public class DerivedClass : BaseClass
{
    public new class Settings : BaseClass.Settings
    {
        public const string DerivedBananaSetting = "DerivedBananaSetting";
    }
// etc..

The rest of your code doesn't change.


问:
How to disable html button using JSTL tags
I want disable HTML button depending on value present in Spring bean.I am using JSTL empty property but no luck.

Here is my code

```<code>   <input type="submit" value="SendEmail" disabled="${empty reportNotificationFbo.providersList}" >
</code>```

Here reportNotificationFbo is spring bean and providersList is a list.

I want to disable Submit button if providersList is empty.

-Thanks.

答:
If you have a disabled attribute with any value it will be rendered in the browser as disabled

Try

```<code><c:choose>
    <c:when test="${empty reportNotificationFbo.providersList}">
        <input type="submit" value="SendEmail" disabled="disabled" >
    </c:when>
    <c:otherwise>
       <input type="submit" value="SendEmail"  >
    </c:otherwise>
</c:choose>
</code>```

Sorry i haven't checked this code

ContentLicense: CC BY-SA 3.0

Body:
I want disable HTML button depending on value present in Spring bean.I am using JSTL empty property but no luck.

Here is my code

   <input type="submit" value="SendEmail" disabled="${empty reportNotificationFbo.providersList}" >

Here reportNotificationFbo is spring bean and providersList is a list.

I want to disable Submit button if providersList is empty.

-Thanks.

Body:
If you have a disabled attribute with any value it will be rendered in the browser as disabled

Try

<c:choose>
    <c:when test="${empty reportNotificationFbo.providersList}">
        <input type="submit" value="SendEmail" disabled="disabled" >
    </c:when>
    <c:otherwise>
       <input type="submit" value="SendEmail"  >
    </c:otherwise>
</c:choose>

Sorry i haven't checked this code


问:
Create linked service with key Vault using python
Here is my problem, I am trying to create linked service using python sdk and I was successful if I provide the storage account name and key. But I would like to create Linked service with key vaults reference, the below runs fine and creates the linked service. However when I go to datafactory and test connection.. it fails.. Please help!

```<code>store = LinkedServiceReference(reference_name ='LS_keyVault_Dev')
storage_string = AzureKeyVaultSecretReference( store=store, secret_name = 'access_key')

ls_azure_storage = AzureStorageLinkedService(connection_string=storage_string)
ls = adf_client.linked_services.create_or_update(rg_name, df_name, ls_name, ls_azure_storage)

</code>```

Error Message

```<code>Invalid storage connection string provided to 'AzureTableConnection'. Check the storage connection string in configuration. No valid combination of account information found.
</code>```

答:
I test your code, it created the linked service successfully, and I navigate to the portal to Test connection, it also works, you could follow the steps below.

1.Navigate to the azure keyvault in the portal -> Secrets -> Create a secret, I'm not sure why you can use access_key as the name of the secret, pey my test, it is invalid. So in my sample, I use accesskey as the name of the secret, then store the Connection string of the storage account.

2.Navigate to the Access policies of the keyvault, add the MSI of your data factory with correct secret permission. If you did not enable the MSI of the data factory, follow this link to generate it, this is used to for the Azure Key Vault linked service to access your keyvault secret.

3.Navigate to the Azure Key Vault linked service of your data factory, make sure the connection is successful.

4.Use the code below to create the storage linked service.

Version of the libraries:

```<code>azure-common==1.1.23
azure-mgmt-datafactory==0.9.0
</code>```

```<code>from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.datafactory import DataFactoryManagementClient
from azure.mgmt.datafactory.models import *

subscription_id = '<subscription-id>'
credentials = ServicePrincipalCredentials(client_id='<client-id>', secret='<client-secret>', tenant='<tenant-id>')
adf_client = DataFactoryManagementClient(credentials, subscription_id)

rg_name = '<resource-group-name>'
df_name = 'joyfactory'
ls_name = 'storageLinkedService'

store = LinkedServiceReference(reference_name ='AzureKeyVault1') # AzureKeyVault1 is the name of the Azure Key Vault linked service
storage_string = AzureKeyVaultSecretReference( store=store, secret_name = 'accesskey')

ls_azure_storage = AzureStorageLinkedService(connection_string=storage_string)
ls = adf_client.linked_services.create_or_update(rg_name, df_name, ls_name, ls_azure_storage)
print(ls)
</code>```

5.Go back to the linked service page, refresh and test the connection, it works fine.

Body:
Here is my problem, I am trying to create linked service using python sdk and I was successful if I provide the storage account name and key. But I would like to create Linked service with key vaults reference, the below runs fine and creates the linked service. However when I go to datafactory and test connection.. it fails.. Please help!

store = LinkedServiceReference(reference_name ='LS_keyVault_Dev')
storage_string = AzureKeyVaultSecretReference( store=store, secret_name = 'access_key')

ls_azure_storage = AzureStorageLinkedService(connection_string=storage_string)
ls = adf_client.linked_services.create_or_update(rg_name, df_name, ls_name, ls_azure_storage)

Error Message

Invalid storage connection string provided to 'AzureTableConnection'. Check the storage connection string in configuration. No valid combination of account information found.

Body:
I test your code, it created the linked service successfully, and I navigate to the portal to Test connection, it also works, you could follow the steps below.

1.Navigate to the azure keyvault in the portal -> Secrets -> Create a secret, I'm not sure why you can use access_key as the name of the secret, pey my test, it is invalid. So in my sample, I use accesskey as the name of the secret, then store the Connection string of the storage account.

2.Navigate to the Access policies of the keyvault, add the MSI of your data factory with correct secret permission. If you did not enable the MSI of the data factory, follow this link to generate it, this is used to for the Azure Key Vault linked service to access your keyvault secret.

3.Navigate to the Azure Key Vault linked service of your data factory, make sure the connection is successful.

4.Use the code below to create the storage linked service.

Version of the libraries:

azure-common==1.1.23
azure-mgmt-datafactory==0.9.0

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.datafactory import DataFactoryManagementClient
from azure.mgmt.datafactory.models import *

subscription_id = '<subscription-id>'
credentials = ServicePrincipalCredentials(client_id='<client-id>', secret='<client-secret>', tenant='<tenant-id>')
adf_client = DataFactoryManagementClient(credentials, subscription_id)

rg_name = '<resource-group-name>'
df_name = 'joyfactory'
ls_name = 'storageLinkedService'

store = LinkedServiceReference(reference_name ='AzureKeyVault1') # AzureKeyVault1 is the name of the Azure Key Vault linked service
storage_string = AzureKeyVaultSecretReference( store=store, secret_name = 'accesskey')

ls_azure_storage = AzureStorageLinkedService(connection_string=storage_string)
ls = adf_client.linked_services.create_or_update(rg_name, df_name, ls_name, ls_azure_storage)
print(ls)

5.Go back to the linked service page, refresh and test the connection, it works fine.


问:
.net transient database context being disposed prematurely
I am moving an asp.net mvc5 application using EF6 to asp.net core MVC 3.0 using EF Core.

In my mvc5 application I have some administrative operation that modify the database and take a long time, so I use a pattern when I create a new DBContext that is not the one that is associated with the request context and then run the task in the background using Task.Run.  This has been working fine for years.

In converting to .net core it was unclear how to create a new DBContext in the way that I was doing it in my old codebase.  It seems like I should be able to create a Transient DBContext in these cases and all should be fine.

So I created a subclass of MyDbContext called MyTransientDbContex and in my Configure class I  added this service:

```<code>            services.AddDbContext<MyTransientDbContex>(options =>
                options.UseSqlServer(
                    context.Configuration.GetConnectionString("MyContextConnection")),
                ServiceLifetime.Transient, ServiceLifetime.Transient);
</code>```

In my controller I inject the context in the action that needs the transient service and spawn a thread to do something with it:

```<code>public ActionResult Update([FromServices] MyTransientContext context) {

    Task.Run(() =>
    {
        try {
            // Do some long running operation with context
        }
        Catch (Exception e) {
            // Report Exception
        }
        finally {
            context.Dispose();
        }
    }

    return RedirectToAction("Status");
}
</code>```

I would not expect my transient context to be disposed until the finally block.  But I am getting this exception when attempting to access the context on the background thread:

```<code>Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'MyTransientContext'.'
</code>```

And indeed the _disposed flag is set to true on the context object.

I put a breakpoint on the constructer for MyTransientContext and "Made an Object ID" of the this pointer so that I could track the object.  This transient object is being created and is the same one that is inject into my controller action.  It's also the same object that I'm trying to reference when the exception is thrown.

I tried setting a data breakpoint on the _disposed member in order to get a callstack on when disposed is being set to true, but the breakpoint won't bind.

I also tried overriding the Dispose method on MyTransientContext, and it isn't called until my explicit dispose in the finally block, which is after the exception is thrown and caught.

I feel like I'm missing something fundamental here.  Isn't this what the transient services are for?  What would dispose a Transient service?

One last detail - MyTransientContext is derived from MyContext, which is in turn derived from IdentityDbContext (Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContex)

Edit: The reason that I went down the path of using a Transient was because of this ef core document page: https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext.  It states that "...any code that explicitly executes multiple threads in parallel should ensure that DbContext instances aren't ever accessed concurrently.  Using dependency injection,  this can be achieved by either registering the context as scoped and creating scopes (using IServiceScopeFactory) for each thread, or by registering the DbContext as transient (using the overload of AddDbContext which takes a ServiceLifetime parameter)."

As xabikos pointed out, this seems to be overriden by the scoping of the asp.net DI system, where it looks like anything created by that system is scoped to the request context, including Transient objects.  Can someone point out where that's documented so that I can better understand how to work with the limitations?

答:
f you want manage the lifetime of service, you can instantiate it manually (or use a factory) :

public ActionResult Update()
{
    Task.Run(() =>
    {
        using(var context = new MyTransientContext(...))
        {
            try
            {
                // Do some long running operation with context
            }
            catch (Exception e)
            {
                // Report Exception
            }
        }
    }
    return RedirectToAction("Status");
}
```

<p>Or you can use IServiceProvider to get and manage a service :</p>

<pre class="lang-cs prettyprint-override"><code>public class MyController
{
    private IServiceProvider _services;

    public MyController(IServiceProvider services)
    {
        _services = services;
    }

    public ActionResult Update()
    {
        var context = (MyTransientContext)_services.GetService(typeof(MyTransientContext));
        Task.Run(() =>
        {
            using (context)
            {
                try
                {
                    // Do some long running operation with context
                }
                catch (Exception e)
                {
                    // Report Exception
                }
            }
        }
        return RedirectToAction("Status");
    }
}
</code>```

Body:
I am moving an asp.net mvc5 application using EF6 to asp.net core MVC 3.0 using EF Core.

In my mvc5 application I have some administrative operation that modify the database and take a long time, so I use a pattern when I create a new DBContext that is not the one that is associated with the request context and then run the task in the background using Task.Run.  This has been working fine for years.

In converting to .net core it was unclear how to create a new DBContext in the way that I was doing it in my old codebase.  It seems like I should be able to create a Transient DBContext in these cases and all should be fine.

So I created a subclass of MyDbContext called MyTransientDbContex and in my Configure class I  added this service:

            services.AddDbContext<MyTransientDbContex>(options =>
                options.UseSqlServer(
                    context.Configuration.GetConnectionString("MyContextConnection")),
                ServiceLifetime.Transient, ServiceLifetime.Transient);

In my controller I inject the context in the action that needs the transient service and spawn a thread to do something with it:

public ActionResult Update([FromServices] MyTransientContext context) {

    Task.Run(() =>
    {
        try {
            // Do some long running operation with context
        }
        Catch (Exception e) {
            // Report Exception
        }
        finally {
            context.Dispose();
        }
    }

    return RedirectToAction("Status");
}

I would not expect my transient context to be disposed until the finally block.  But I am getting this exception when attempting to access the context on the background thread:

Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'MyTransientContext'.'

And indeed the _disposed flag is set to true on the context object.

I put a breakpoint on the constructer for MyTransientContext and "Made an Object ID" of the this pointer so that I could track the object.  This transient object is being created and is the same one that is inject into my controller action.  It's also the same object that I'm trying to reference when the exception is thrown.

I tried setting a data breakpoint on the _disposed member in order to get a callstack on when disposed is being set to true, but the breakpoint won't bind.

I also tried overriding the Dispose method on MyTransientContext, and it isn't called until my explicit dispose in the finally block, which is after the exception is thrown and caught.

I feel like I'm missing something fundamental here.  Isn't this what the transient services are for?  What would dispose a Transient service?

One last detail - MyTransientContext is derived from MyContext, which is in turn derived from IdentityDbContext (Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContex)

Edit: The reason that I went down the path of using a Transient was because of this ef core document page: https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext.  It states that "...any code that explicitly executes multiple threads in parallel should ensure that DbContext instances aren't ever accessed concurrently.  Using dependency injection,  this can be achieved by either registering the context as scoped and creating scopes (using IServiceScopeFactory) for each thread, or by registering the DbContext as transient (using the overload of AddDbContext which takes a ServiceLifetime parameter)."

As xabikos pointed out, this seems to be overriden by the scoping of the asp.net DI system, where it looks like anything created by that system is scoped to the request context, including Transient objects.  Can someone point out where that's documented so that I can better understand how to work with the limitations?

Body:
f you want manage the lifetime of service, you can instantiate it manually (or use a factory) :

public ActionResult Update()
{
    Task.Run(() =>
    {
        using(var context = new MyTransientContext(...))
        {
            try
            {
                // Do some long running operation with context
            }
            catch (Exception e)
            {
                // Report Exception
            }
        }
    }
    return RedirectToAction("Status");
}

Or you can use IServiceProvider to get and manage a service :

public class MyController
{
    private IServiceProvider _services;

    public MyController(IServiceProvider services)
    {
        _services = services;
    }

    public ActionResult Update()
    {
        var context = (MyTransientContext)_services.GetService(typeof(MyTransientContext));
        Task.Run(() =>
        {
            using (context)
            {
                try
                {
                    // Do some long running operation with context
                }
                catch (Exception e)
                {
                    // Report Exception
                }
            }
        }
        return RedirectToAction("Status");
    }
}


问:
creating a sequential pair of time lists
I have a list of times that look like this, every time is incremented by 5 mins with the last time being 23:59:00.000

```<code>list_of_times = ['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000', '2020-01-30 00:10:00.000', '2020-01-30 00:15:00.000', '2020-01-30 00:20:00.000'... '2020-01-30 23:59:00.000']
</code>```

What I want to do is end up with a list of time pairs like this:

```<code>list_of_pairs = [['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000'],['2020-01-30 00:05:00.000','2020-01-30 00:05:00.000'], ... ['2020-01-30 23:55:00.000','2020-01-30 23:59:00.000']]
</code>```

So note how in the list_of_pairs the end time of the first pair  ['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000'], is the start time for the next pair ['2020-01-30 00:05:00.000','2020-01-30 00:05:00.000']

My code:

```<code>start_times = list_of_times[::2]
end_times = list_of_times[1::2]
count = 0
try:
    for item in start_times:
        pair_of_times.append([start_times[count],end_times[count]])
        count +=1
except:
    pass
print(pair_of_times)
</code>```

But my result is as expected, note how the start time of the 2nd pair is 2020-01-30 00:10:00.000'. I would like it to be the end time of the previous pair. Here is how my result looks now :

```<code>[['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000'], ['2020-01-30 00:10:00.000', '2020-01-30 00:15:00.000']...]
</code>```

Not sure how to slice correctly, or even if slicing is the right method to get the result I'm looking for. I'm also open to generating the time from scratch since I'm given the start and end time ie start = '2020-01-30 00:00:00.000'. end = '2020-01-30 23:59:00.000'

答:
You could remedy this by using step=1 on your slices, since every time (except the first and last) will be both a start and an end time, so you should not skip any time in either list:

```<code># ...
start_times = list_of_times  # no slice needed at all
end_times = list_of_times[1:]
# ...
</code>```

You can further simplify this by using a typical pattern using zip:

```<code>pair_of_times = list(zip(list_of_times, list_of_times[1:]))
</code>```

More space efficient yet:

```<code>pair_of_times = [list_of_times[i:i+2] for i in range(len(list_of_times) - 1)]
</code>```

Body:
I have a list of times that look like this, every time is incremented by 5 mins with the last time being 23:59:00.000

list_of_times = ['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000', '2020-01-30 00:10:00.000', '2020-01-30 00:15:00.000', '2020-01-30 00:20:00.000'... '2020-01-30 23:59:00.000']

What I want to do is end up with a list of time pairs like this:

list_of_pairs = [['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000'],['2020-01-30 00:05:00.000','2020-01-30 00:05:00.000'], ... ['2020-01-30 23:55:00.000','2020-01-30 23:59:00.000']]

So note how in the list_of_pairs the end time of the first pair  ['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000'], is the start time for the next pair ['2020-01-30 00:05:00.000','2020-01-30 00:05:00.000']

My code:

start_times = list_of_times[::2]
end_times = list_of_times[1::2]
count = 0
try:
    for item in start_times:
        pair_of_times.append([start_times[count],end_times[count]])
        count +=1
except:
    pass
print(pair_of_times)

But my result is as expected, note how the start time of the 2nd pair is 2020-01-30 00:10:00.000'. I would like it to be the end time of the previous pair. Here is how my result looks now :

[['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000'], ['2020-01-30 00:10:00.000', '2020-01-30 00:15:00.000']...]

Not sure how to slice correctly, or even if slicing is the right method to get the result I'm looking for. I'm also open to generating the time from scratch since I'm given the start and end time ie start = '2020-01-30 00:00:00.000'. end = '2020-01-30 23:59:00.000'

Body:
You could remedy this by using step=1 on your slices, since every time (except the first and last) will be both a start and an end time, so you should not skip any time in either list:

# ...
start_times = list_of_times  # no slice needed at all
end_times = list_of_times[1:]
# ...

You can further simplify this by using a typical pattern using zip:

pair_of_times = list(zip(list_of_times, list_of_times[1:]))

More space efficient yet:

pair_of_times = [list_of_times[i:i+2] for i in range(len(list_of_times) - 1)]


问:
self.navigationItem.rightBarButtonItem?.customView = nil crash
When I used the method self.navigationItem.rightBarButtonItem?.customView = nil. Then got a crash and the log was -[__NSArrayM replaceObjectAtIndex:withObject:]: object cannot be nil. This problem only occurred in a little devices.

答:
If you try to access self.navigationItem.rightBarButtonItem?.customView it will return nil or result in app crash.

In order to access your customView after added, you have to access it using Swift standard way:

```<code>navigationItem.rightBarButtonItems?.first?.customView
</code>```

Check bellow answer:

https://stackoverflow.com/a/60295524/1399938

Help vote up for other if this work for you.

Body:
If you try to access self.navigationItem.rightBarButtonItem?.customView it will return nil or result in app crash.

In order to access your customView after added, you have to access it using Swift standard way:

navigationItem.rightBarButtonItems?.first?.customView

Check bellow answer:

https://stackoverflow.com/a/60295524/1399938

Help vote up for other if this work for you.


问:
Return Data of two tables using mysql join as one java Object in Spring boot
CPT Table

```<code>@Entity
@Table(name = "CPT")
public class CPTCodeset {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id")
    private int id;

    @Column(name = "Code")
    private String code;

    @Column(name = "Description")
    private String desc;
//getters and setters
}
</code>```

CPT Procedures Table

```<code>@Entity
@Table(name = "cptprocedures")
public class CPTProcedures {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id")
    private int Id;

    @OneToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "ProcedureId")
    private Procedure procedure;
    @Transient
    private int procedureId;

    @OneToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "CPTCodeSet")
    private CPTCodeset cpt;
    @Transient
    private int cptCodeSet;
//getters and setters
}
</code>```

CPTRepository

```<code>@Query(nativeQuery = true, value = "SELECT cp.ProcedureId,c.Code,c.Description FROM cptprocedures cp JOIN CPT c ON cp.CPTCodeSet = c.Id where c.Description like \"%ane\";")
List<CPTCodeset> findBySearch(@Param("searchString") String searchString);
</code>```

This Query Returning Data is what I want. But how can I map this data into a single object where as it includes 2 tables.

How can I do it by using @Entity without creating a table. Any suggestions?

答:
You're doing it wrong if you are using JPA and still thinking in terms of tables first. The whole point of JPA is to have SQL generated from objects so you can pretend that the relational model doesn't exist

For this example you can use a projection interface

That can solve your problem, you doing your projection, and later set the information into a WrapperObject. But you cant do a Wrapper in your JPARepository, if that wrapper doesn't exists in your Database.

Body:
CPT Table

@Entity
@Table(name = "CPT")
public class CPTCodeset {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id")
    private int id;

    @Column(name = "Code")
    private String code;

    @Column(name = "Description")
    private String desc;
//getters and setters
}

CPT Procedures Table

@Entity
@Table(name = "cptprocedures")
public class CPTProcedures {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id")
    private int Id;

    @OneToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "ProcedureId")
    private Procedure procedure;
    @Transient
    private int procedureId;

    @OneToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "CPTCodeSet")
    private CPTCodeset cpt;
    @Transient
    private int cptCodeSet;
//getters and setters
}

CPTRepository

@Query(nativeQuery = true, value = "SELECT cp.ProcedureId,c.Code,c.Description FROM cptprocedures cp JOIN CPT c ON cp.CPTCodeSet = c.Id where c.Description like \"%ane\";")
List<CPTCodeset> findBySearch(@Param("searchString") String searchString);

This Query Returning Data is what I want. But how can I map this data into a single object where as it includes 2 tables.

How can I do it by using @Entity without creating a table. Any suggestions?


问:
How to get browser extension popup to display a variable
I am creating my first Firefox extension.
The idea is simple:

Find all lists on page.

Put a border around them.

Record the number of lists to a variable.

Display this variable in the popup.

I can't figure out #4, displaying the variable in the popup. Please help a beginner!

Here is my code:

```<code>// Variables
const $ulList = document.querySelectorAll('ul')
const $olList = document.querySelectorAll('ol')
const $dlList = document.querySelectorAll('dl')

// Finds all list elements
function findLists($ulList, $olList, $dlList) {
    // Gives them a pink border
    for (const $ul of $ulList) {
        $ul.style.border = "5px solid pink";
    }
    for (const $ol of $olList) {
        $ol.style.border = "5px solid pink";
    }
    for (const $dl of $dlList) {
        $dl.style.border = "5px solid hotpink";
    }
}

// Records length of all lists
var $ulListLength = $ulList.length
console.log('ul Lists: ' + $ulListLength)
var $olListLength = $olList.length
console.log('ol Lists: ' + $olListLength)
var $dlListLength = $dlList.length
console.log('dl Lists: ' + $dlListLength)

// The total number of lists on the page
$totalListsLength = $ulListLength + $olListLength + $dlListLength
console.log('Total lists: ' + $totalListsLength)
</code>```

Here is the manifest.json. Please note that pop-display.js is currently empty.

```<code>{
  "description": "QA common style mistakes for Canada.ca style guide.",
  "manifest_version": 2,
  "name": "WebPubQA",
  "version": "1.0",
  "homepage_url": "https://github.com/sinc0115/web-pub-qa",
  "icons": {
    "48": "icon/outline_highlight_black_48dp.png"
  },

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["webPubQA.js", "pop-display.js"]
    }
  ],

   "permissions": [
    "activeTab"
  ],

  "background": {
        "scripts": ["pop-display.js"]
    },

  "browser_action": {
    "default_icon": "icon/outline_highlight_black_48dp.png",
    "default_title": "Web Pub QA",
    "default_popup": "index-pop.html"
  }

}
</code>```

答:
There are a few ways that it can be done.

Here is one which doesn't require "content_scripts" to function:

```<code>// in popup.js
const code = `
const ul = document.querySelectorAll('ul');
const ol = document.querySelectorAll('ol');
const dl = document.querySelectorAll('dl');

// add border to all
[...ul, ...ol, ...dl].forEach(item => item.style.border = '5px solid pink');

// Records length of all lists
const ulLen = ul.length;
const olLen = ol.length;
const dlLen = dl.length;
const total = ulLen + olLen + dlLen;

console.log('ul Lists: ' + ulLen);
console.log('ol Lists: ' + olLen);
console.log('dl Lists: ' + dlLen);
console.log('Total lists: ' + total);

// return value is passed back to the tabs.executeScript
return total;
`;

// tabs.executeScript without tabId inject into active tab
chrome.tabs.executeScript({code}, result => {
  // result is array, the value passed is result[0]
  // do whatever with result[0]
});
</code>```

Another method is:

add a content script

have a runtime.onMessage.addListener() in content script

send a tabs.sendMessage() from pop up to count the LIST

wait for a message back from content script to display total in pop-up

Body:
I am creating my first Firefox extension.
The idea is simple:

Find all lists on page.

Put a border around them.

Record the number of lists to a variable.

Display this variable in the popup.

I can't figure out #4, displaying the variable in the popup. Please help a beginner!

Here is my code:

// Variables
const $ulList = document.querySelectorAll('ul')
const $olList = document.querySelectorAll('ol')
const $dlList = document.querySelectorAll('dl')

// Finds all list elements
function findLists($ulList, $olList, $dlList) {
    // Gives them a pink border
    for (const $ul of $ulList) {
        $ul.style.border = "5px solid pink";
    }
    for (const $ol of $olList) {
        $ol.style.border = "5px solid pink";
    }
    for (const $dl of $dlList) {
        $dl.style.border = "5px solid hotpink";
    }
}

// Records length of all lists
var $ulListLength = $ulList.length
console.log('ul Lists: ' + $ulListLength)
var $olListLength = $olList.length
console.log('ol Lists: ' + $olListLength)
var $dlListLength = $dlList.length
console.log('dl Lists: ' + $dlListLength)

// The total number of lists on the page
$totalListsLength = $ulListLength + $olListLength + $dlListLength
console.log('Total lists: ' + $totalListsLength)

Here is the manifest.json. Please note that pop-display.js is currently empty.

{
  "description": "QA common style mistakes for Canada.ca style guide.",
  "manifest_version": 2,
  "name": "WebPubQA",
  "version": "1.0",
  "homepage_url": "https://github.com/sinc0115/web-pub-qa",
  "icons": {
    "48": "icon/outline_highlight_black_48dp.png"
  },

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["webPubQA.js", "pop-display.js"]
    }
  ],

   "permissions": [
    "activeTab"
  ],

  "background": {
        "scripts": ["pop-display.js"]
    },

  "browser_action": {
    "default_icon": "icon/outline_highlight_black_48dp.png",
    "default_title": "Web Pub QA",
    "default_popup": "index-pop.html"
  }

}

Body:
There are a few ways that it can be done.

Here is one which doesn't require "content_scripts" to function:

// in popup.js
const code = `
const ul = document.querySelectorAll('ul');
const ol = document.querySelectorAll('ol');
const dl = document.querySelectorAll('dl');

// add border to all
[...ul, ...ol, ...dl].forEach(item => item.style.border = '5px solid pink');

// Records length of all lists
const ulLen = ul.length;
const olLen = ol.length;
const dlLen = dl.length;
const total = ulLen + olLen + dlLen;

console.log('ul Lists: ' + ulLen);
console.log('ol Lists: ' + olLen);
console.log('dl Lists: ' + dlLen);
console.log('Total lists: ' + total);

// return value is passed back to the tabs.executeScript
return total;
`;

// tabs.executeScript without tabId inject into active tab
chrome.tabs.executeScript({code}, result => {
  // result is array, the value passed is result[0]
  // do whatever with result[0]
});

Another method is:

add a content script

have a runtime.onMessage.addListener() in content script

send a tabs.sendMessage() from pop up to count the LIST

wait for a message back from content script to display total in pop-up


答:
```<code>@Query("SELECT new com.dto.ProduceCPT(cp.ProcedureId, c.Code, c.Description) FROM cptprocedures cp JOIN CPT c ON cp.CPTCodeSet = c.Id where c.Description like \"%ane\" ")
List< ProduceCPT> fetchProduceCPT();
</code>```

Title: Return Data of two tables using mysql join as one java Object in Spring boot


问:
TypeScript loop trough Object
I have this really easy problem, where I want to loop through an Object in TypeScript.

```<code>const an_object = {
    one: 1,
    two: 2,
    three: 3
};

for (let key in an_object) {
    let value = an_object[key];
    // Do something with value
}
</code>```

This row let value = an_object[key]; is causing a TypeScript error:

[react-scripts] Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ one: number; two: number; three: number; }'.

I'm new to TypeScript and don't really understand the problem.

This works fine on JavaScript but not on TypeScript.

Any suggestions on how to loop through an object in TypeScript correctly, without getting errors?

答:
TypeScript is named TYPEScript for a reason.

The problem is that it's not specified what will be inside the object.

Any suggestions on how to loop through an object in TypeScript correctly, without getting errors?

To do this correctly you should specify what is inside the object. This can be done by:

creating an interface

```<code>interface MyObjectsInterface {
    [key: string]: number;
}
</code>```

assign it to the object.

```<code>const an_object: MyObjectsInterface = {
    one: 1,
    two: 2,
    three: 3
};
</code>```

now you can use the value in the forloop

```<code>for (let key in an_object) {
    let value: number = an_object[key];
    // Do something with value
}
</code>```

In this way, you will always know what will be inside an object.

Title: TypeScript loop trough Object

Body:
I have this really easy problem, where I want to loop through an Object in TypeScript.

const an_object = {
    one: 1,
    two: 2,
    three: 3
};

for (let key in an_object) {
    let value = an_object[key];
    // Do something with value
}

This row let value = an_object[key]; is causing a TypeScript error:

[react-scripts] Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ one: number; two: number; three: number; }'.

I'm new to TypeScript and don't really understand the problem.

This works fine on JavaScript but not on TypeScript.

Any suggestions on how to loop through an object in TypeScript correctly, without getting errors?

Body:
TypeScript is named TYPEScript for a reason.

The problem is that it's not specified what will be inside the object.

Any suggestions on how to loop through an object in TypeScript correctly, without getting errors?

To do this correctly you should specify what is inside the object. This can be done by:

creating an interface

interface MyObjectsInterface {
    [key: string]: number;
}

assign it to the object.

const an_object: MyObjectsInterface = {
    one: 1,
    two: 2,
    three: 3
};

now you can use the value in the forloop

for (let key in an_object) {
    let value: number = an_object[key];
    // Do something with value
}

In this way, you will always know what will be inside an object.


问:
Angular deployment - 404 on page Refresh
i would like to deploy my app in Angular to production server but I have problems. App works corectly when I use only angular routing (change component, not redirecting) but when I refresh the page in browser, I get a 404 page returned from IIS (I use IIS as the web server)

Here is my angular routing:

```<code>const appRoutes: Routes = [
    { path: '', redirectTo: '/home', pathMatch: 'full', canActivate: [AuthGuard] },
    { path: 'home', component: DashboardComponent, canActivate: [AuthGuard] },
    { path: "profile", component: UserProfileComponent, canActivate: [AuthGuard] },
    { path: '400', component: ErrorComponent },
    { path: '401', component: ErrorComponent },
    { path: '403', component: ErrorComponent },
    { path: '404', component: ErrorComponent },
    { path: '500', component: ErrorComponent },
    { path: '503', component: ErrorComponent },
    { path: '**', redirectTo: '/404' }
]
</code>```

答:
This work for angular 8, add .htaccess to your project file

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [L]
</code>```

Body:
i would like to deploy my app in Angular to production server but I have problems. App works corectly when I use only angular routing (change component, not redirecting) but when I refresh the page in browser, I get a 404 page returned from IIS (I use IIS as the web server)

Here is my angular routing:

const appRoutes: Routes = [
    { path: '', redirectTo: '/home', pathMatch: 'full', canActivate: [AuthGuard] },
    { path: 'home', component: DashboardComponent, canActivate: [AuthGuard] },
    { path: "profile", component: UserProfileComponent, canActivate: [AuthGuard] },
    { path: '400', component: ErrorComponent },
    { path: '401', component: ErrorComponent },
    { path: '403', component: ErrorComponent },
    { path: '404', component: ErrorComponent },
    { path: '500', component: ErrorComponent },
    { path: '503', component: ErrorComponent },
    { path: '**', redirectTo: '/404' }
]

Body:
This work for angular 8, add .htaccess to your project file

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [L]


问:
Change multiple and codependent tkinter Entry value
So I'm trying to create something like the goole unit conversion tool
So far I have this:

```<code>import tkinter

rate = 3.281

def command_P():
    print("button pressed")

def callback1(arg):
    try:
        float(amount1.get())
        amount2.delete(0,"end")
        amount2.insert(0,float(amount1.get())*rate)
    except Exception as e:
        print(e)

def callback2(arg):
    try:
        float(amount2.get())
        amount1.delete(0,"end")
        amount1.insert(0,float(amount2.get())/rate)
    except Exception as e:
        print(e)

trade_w = tkinter.Tk()
trade_w.title("Unit Converter")

label_mont1 = tkinter.Label(trade_w,
                    text = "Metre:")
label_mont1.grid(column=0, row=1)

sv = tkinter.StringVar()
sv.trace("w", lambda name, index, mode, sv=sv: callback1(sv))

amount1 = tkinter.Entry(trade_w,textvariable=sv)
amount1.grid(column=1, row=1)

label_mont2 = tkinter.Label(trade_w,
                    text = "Foot:")
label_mont2.grid(column=2, row=1)

vs = tkinter.StringVar()
vs.trace("w", lambda name, index, mode, vs=vs: callback2(vs))

amount2 = tkinter.Entry(trade_w, textvariable=vs)
amount2.grid(column=3, row=1)

trade_w.mainloop()
</code>```

Everything seem to work fine but when I write something on either box it moves the text cursor to the end of the Entry box, thats becouse when I do the .get() for amount1 or amount2 it does the callback function and recalculate the value.

Any idea of how to bypass or solve this?

Thanks!

答:
You can use <KeyRelease> event callback instead of tracing change of tkinter variable:

```<code>import tkinter

rate = 3.281

def on_entry_change(event):
    try:
        if event.widget is amount1:
            value = float(sv.get())
            vs.set(value * rate)
        else:
            value = float(vs.get())
            sv.set(value / rate)
    except Exception as e:
        print(e)

trade_w = tkinter.Tk()
trade_w.title("Unit Converter")

label_mont1 = tkinter.Label(trade_w, text="Metre:")
label_mont1.grid(column=0, row=1)

sv = tkinter.StringVar()
amount1 = tkinter.Entry(trade_w, textvariable=sv)
amount1.grid(column=1, row=1)
amount1.bind('<KeyRelease>', on_entry_change)

label_mont2 = tkinter.Label(trade_w, text="Foot:")
label_mont2.grid(column=2, row=1)

vs = tkinter.StringVar()
amount2 = tkinter.Entry(trade_w, textvariable=vs)
amount2.grid(column=3, row=1)
amount2.bind('<KeyRelease>', on_entry_change)

trade_w.mainloop()
</code>```

Body:
So I'm trying to create something like the goole unit conversion tool
So far I have this:

import tkinter

rate = 3.281

def command_P():
    print("button pressed")

def callback1(arg):
    try:
        float(amount1.get())
        amount2.delete(0,"end")
        amount2.insert(0,float(amount1.get())*rate)
    except Exception as e:
        print(e)

def callback2(arg):
    try:
        float(amount2.get())
        amount1.delete(0,"end")
        amount1.insert(0,float(amount2.get())/rate)
    except Exception as e:
        print(e)

trade_w = tkinter.Tk()
trade_w.title("Unit Converter")

label_mont1 = tkinter.Label(trade_w,
                    text = "Metre:")
label_mont1.grid(column=0, row=1)

sv = tkinter.StringVar()
sv.trace("w", lambda name, index, mode, sv=sv: callback1(sv))

amount1 = tkinter.Entry(trade_w,textvariable=sv)
amount1.grid(column=1, row=1)

label_mont2 = tkinter.Label(trade_w,
                    text = "Foot:")
label_mont2.grid(column=2, row=1)

vs = tkinter.StringVar()
vs.trace("w", lambda name, index, mode, vs=vs: callback2(vs))

amount2 = tkinter.Entry(trade_w, textvariable=vs)
amount2.grid(column=3, row=1)

trade_w.mainloop()

Everything seem to work fine but when I write something on either box it moves the text cursor to the end of the Entry box, thats becouse when I do the .get() for amount1 or amount2 it does the callback function and recalculate the value.

Any idea of how to bypass or solve this?

Thanks!

Body:
You can use <KeyRelease> event callback instead of tracing change of tkinter variable:

import tkinter

rate = 3.281

def on_entry_change(event):
    try:
        if event.widget is amount1:
            value = float(sv.get())
            vs.set(value * rate)
        else:
            value = float(vs.get())
            sv.set(value / rate)
    except Exception as e:
        print(e)

trade_w = tkinter.Tk()
trade_w.title("Unit Converter")

label_mont1 = tkinter.Label(trade_w, text="Metre:")
label_mont1.grid(column=0, row=1)

sv = tkinter.StringVar()
amount1 = tkinter.Entry(trade_w, textvariable=sv)
amount1.grid(column=1, row=1)
amount1.bind('<KeyRelease>', on_entry_change)

label_mont2 = tkinter.Label(trade_w, text="Foot:")
label_mont2.grid(column=2, row=1)

vs = tkinter.StringVar()
amount2 = tkinter.Entry(trade_w, textvariable=vs)
amount2.grid(column=3, row=1)
amount2.bind('<KeyRelease>', on_entry_change)

trade_w.mainloop()


问:
Invalid Request Origin after Python post request
I've been trying to write a program which gets my school timetable which is locked behind a login screen, however when I run my python script I am greeted by:

```<code>Sorry, we are unable to complete this request

An error occured while submitting the form:

Invalid Request Origin
</code>```

This is the code I've written so far:

```<code>import requests

login_url =     'https://WEBSITE/login?page=%2Fhomepage'
timetable_url = 'https://WEBSITE/timetable'

payload = {
    'username': 'USERNAME',
    'password': 'PASSWORD'
}

with requests.Session() as session:
    post = session.post(login_url, data=payload, verify = True)
    r = session.get(timetable_url)
    print (post.text)
</code>```

And this is the html from the login page:

```<code><div id="content">
   <form id="login" method="post" action="/login?page=%2Flogin%2F">
      <input type="hidden" name="page" value="/login/" />
      <div class="row collapse">
         <div class="small-12 column">
            <div class="logo">
               <img src="/images/logo.php?logo=skin_logo_login&size=normal" alt="Schoolbox" />
            </div>
         </div>
         <div class="small-12 column">
            <p id="error-msg" class="alert-box alert"></p>
         </div>
         <div class="small-12 column">
            <input type="text" name="username" id="username" placeholder="Username" />
            <input type="password" name="password" id="password" placeholder="Password" />
         </div>
      </div>
      <div class="row collapse">
         <div class="small-12 column">
            <p><a href="/forgotten-password.php">Forgotten your password?</a></p>
         </div>
         <div class="small-12 column">
            <input id="rememberme" type="checkbox" name="rememberme" value="1" />
            <label for="rememberme">Remember me</label>
         </div>
         <div class="small-12 column login-links">
            <input type="submit" name="Submit" value="Login" alt="Login" />
         </div>
      </div>
   </form>
</div>
</code>```

How exactly would I be able to solve this error, or would there be any other more viable solutions? Thank you.

答: This error Invalid Request Origin means that your origin does not match what is restricted by the server. You could try adding the Origin: header specifying your timetable_url, but it is likely that the page can only be called by another page on the server.

Body:
I've been trying to write a program which gets my school timetable which is locked behind a login screen, however when I run my python script I am greeted by:

Sorry, we are unable to complete this request

An error occured while submitting the form:

Invalid Request Origin

This is the code I've written so far:

import requests

login_url =     'https://WEBSITE/login?page=%2Fhomepage'
timetable_url = 'https://WEBSITE/timetable'

payload = {
    'username': 'USERNAME',
    'password': 'PASSWORD'
}

with requests.Session() as session:
    post = session.post(login_url, data=payload, verify = True)
    r = session.get(timetable_url)
    print (post.text)

And this is the html from the login page:

   <form id="login" method="post" action="/login?page=%2Flogin%2F">
      <input type="hidden" name="page" value="/login/" />

            <input type="text" name="username" id="username" placeholder="Username" />
            <input type="password" name="password" id="password" placeholder="Password" />

Forgotten your password?

            <input id="rememberme" type="checkbox" name="rememberme" value="1" />
            Remember me

            <input type="submit" name="Submit" value="Login" alt="Login" />

   </form>

How exactly would I be able to solve this error, or would there be any other more viable solutions? Thank you.


问:
jQuery show/hide options if button selected
How I can change SELECT form to TAB from.

I have this code:

var $clonedOpts = $("#layout_select").children().clone();

$("#column_select").change(function() {
  var $layOpts = $clonedOpts.clone().filter('[value^=' + $(this).val() + ']');
  $("#layout_select").html($layOpts);
}).change();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="column_select" id="column_select">
  <option value="col1">1 column</option>
  <option value="col2">2 column</option>
  <option value="col3">3 column</option>
</select>

<select name="layout_select" id="layout_select">
  <!--Below shows when '1 column' is selected is hidden otherwise-->
  <option value="col1">none</option>

  <!--Below shows when '2 column' is selected is hidden otherwise-->
  <option value="col2_ms">layout 1</option>
  <option value="col2_sm">layout 2</option>

  <!--Below shows when '3 column' is selected is hidden otherwise-->
  <option value="col3_mss">layout 3</option>
  <option value="col3_ssm" selected="selected">layout 4</option>
  <option value="col3_sms">layout 5</option>
</select></code>```

I want change this code (select options):

<select name="column_select" id="column_select">
  <option value="col1">1 column</option>
  <option value="col2">2 column</option>
  <option value="col3">3 column</option>
</select>```
</div>
</div>
</p>

<p>To this code (TAB forms):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tab">
  <button>TAB1</button>
  <button>TAB2</button>
  <button>TAB3</button>
</div></code>```

What I should change in javascript?

答:
You can use data- attribute to attach values on button

And change event to click

var $clonedOpts = $("#layout_select").children().clone();

$(".tab button").click(function() {
  var $layOpts = $clonedOpts.clone().filter('[value^=' + $(this).data("val") + ']');
  $("#layout_select").html($layOpts);
});
$(".tab button").eq(0).click();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab">
  <button data-val="col1">TAB1</button>
  <button data-val="col2">TAB2</button>
  <button data-val="col3">TAB3</button>
</div>

<select name="layout_select" id="layout_select">
  <!--Below shows when '1 column' is selected is hidden otherwise-->
  <option value="col1">none</option>

  <!--Below shows when '2 column' is selected is hidden otherwise-->
  <option value="col2_ms">layout 1</option>
  <option value="col2_sm">layout 2</option>

  <!--Below shows when '3 column' is selected is hidden otherwise-->
  <option value="col3_mss">layout 3</option>
  <option value="col3_ssm" selected="selected">layout 4</option>
  <option value="col3_sms">layout 5</option>
</select></code>```

Body:
How I can change SELECT form to TAB from.

I have this code:

var $clonedOpts = $("#layout_select").children().clone();

$("#column_select").change(function() {
  var $layOpts = $clonedOpts.clone().filter('[value^=' + $(this).val() + ']');
  $("#layout_select").html($layOpts);
}).change();

<select name="column_select" id="column_select">
  <option value="col1">1 column</option>
  <option value="col2">2 column</option>
  <option value="col3">3 column</option>
</select>

<select name="layout_select" id="layout_select">

  <option value="col1">none</option>

  <option value="col2_ms">layout 1</option>
  <option value="col2_sm">layout 2</option>

  <option value="col3_mss">layout 3</option>
  <option value="col3_ssm" selected="selected">layout 4</option>
  <option value="col3_sms">layout 5</option>
</select>

I want change this code (select options):

<select name="column_select" id="column_select">
  <option value="col1">1 column</option>
  <option value="col2">2 column</option>
  <option value="col3">3 column</option>
</select>

To this code (TAB forms):

  <button>TAB1</button>
  <button>TAB2</button>
  <button>TAB3</button>

What I should change in javascript?

Body:
You can use data- attribute to attach values on button

And change event to click

var $clonedOpts = $("#layout_select").children().clone();

$(".tab button").click(function() {
  var $layOpts = $clonedOpts.clone().filter('[value^=' + $(this).data("val") + ']');
  $("#layout_select").html($layOpts);
});
$(".tab button").eq(0).click();

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab">
  <button data-val="col1">TAB1</button>
  <button data-val="col2">TAB2</button>
  <button data-val="col3">TAB3</button>
</div>

<select name="layout_select" id="layout_select">
  <!--Below shows when '1 column' is selected is hidden otherwise-->
  <option value="col1">none</option>

  <!--Below shows when '2 column' is selected is hidden otherwise-->
  <option value="col2_ms">layout 1</option>
  <option value="col2_sm">layout 2</option>

  <!--Below shows when '3 column' is selected is hidden otherwise-->
  <option value="col3_mss">layout 3</option>
  <option value="col3_ssm" selected="selected">layout 4</option>
  <option value="col3_sms">layout 5</option>
</select>


问:
Typescript - Using Fetch and Async to access Open Trivia Database
We're modifying a trivia game that uses TypeScript and its own local database to rely on Open Trivia DB instead. There's a lot of async / await functions that I don't want to mess with (in the case that the old database functionality is required), and so I've taken to using Fetch.

Here's my code so far:

```<code>public async getCategories() {
    let cats = null;
    let counts = null;
    if (!this.IS_USING_OTDB) {
        cats = await this.db.query('SELECT DISTINCT categoryid, category FROM questionsTest ORDER BY categoryid');
        counts = await this.db.query('SELECT categoryid, category, difficulty, count(*) FROM questionsTest GROUP by categoryid, category, difficulty ORDER BY count DESC');
        console.log(cats.rows, cats.rowCount, counts.rows);
    } else {
        console.log('Connecting to opentdb instead of postgres.');
        const fetchResult = await fetch('https://opentdb.com/api_category.php');
        console.log(fetchResult);
        const body = fetchResult.json;
        console.log(JSON.stringify(body));
    }
    // more code for processing here
}
</code>```

This works per se, in the sense that it doesn't crash. However, the result (console logged fetchResult) is not what I was expecting:

```<code>Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: true,
      allowHalfOpen: true,
      _transformState: [Object],
      [Symbol(kCapture)]: false
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://opentdb.com/api_category.php',
    status: 200,
    statusText: 'OK',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}
</code>```

The JSON strinigified result of fetchResult.json is also undefined.

Which is strange, since the link https://opentdb.com/api_category.php immediately returns the following (and you can check it for yourself by clicking the above link):

```<code>{"trivia_categories":[{"id":9,"name":"General Knowledge"},{"id":10,"name":"Entertainment: Books"},{"id":11,"name":"Entertainment: Film"},{"id":12,"name":"Entertainment: Music"},{"id":13,"name":"Entertainment: Musicals & Theatres"},{"id":14,"name":"Entertainment: Television"},{"id":15,"name":"Entertainment: Video Games"},{"id":16,"name":"Entertainment: Board Games"},{"id":17,"name":"Science & Nature"},{"id":18,"name":"Science: Computers"},{"id":19,"name":"Science: Mathematics"},{"id":20,"name":"Mythology"},{"id":21,"name":"Sports"},{"id":22,"name":"Geography"},{"id":23,"name":"History"},{"id":24,"name":"Politics"},{"id":25,"name":"Art"},{"id":26,"name":"Celebrities"},{"id":27,"name":"Animals"},{"id":28,"name":"Vehicles"},{"id":29,"name":"Entertainment: Comics"},{"id":30,"name":"Science: Gadgets"},{"id":31,"name":"Entertainment: Japanese Anime & Manga"},{"id":32,"name":"Entertainment: Cartoon & Animations"}]}
</code>```

How do I get the above results from fetching from the URL? Did I miss anything?

答:
fetchResult.json() is a method, not a property and it returns a promise.

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

https://developer.mozilla.org/en-US/docs/Web/API/Body/json

Try this:

```<code>const fetchResult = await fetch('https://opentdb.com/api_category.php');
const data = await fetchResult.json();
console.log(data);
</code>```

Body:
We're modifying a trivia game that uses TypeScript and its own local database to rely on Open Trivia DB instead. There's a lot of async / await functions that I don't want to mess with (in the case that the old database functionality is required), and so I've taken to using Fetch.

Here's my code so far:

public async getCategories() {
    let cats = null;
    let counts = null;
    if (!this.IS_USING_OTDB) {
        cats = await this.db.query('SELECT DISTINCT categoryid, category FROM questionsTest ORDER BY categoryid');
        counts = await this.db.query('SELECT categoryid, category, difficulty, count(*) FROM questionsTest GROUP by categoryid, category, difficulty ORDER BY count DESC');
        console.log(cats.rows, cats.rowCount, counts.rows);
    } else {
        console.log('Connecting to opentdb instead of postgres.');
        const fetchResult = await fetch('https://opentdb.com/api_category.php');
        console.log(fetchResult);
        const body = fetchResult.json;
        console.log(JSON.stringify(body));
    }
    // more code for processing here
}

This works per se, in the sense that it doesn't crash. However, the result (console logged fetchResult) is not what I was expecting:

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: true,
      allowHalfOpen: true,
      _transformState: [Object],
      [Symbol(kCapture)]: false
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://opentdb.com/api_category.php',
    status: 200,
    statusText: 'OK',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

The JSON strinigified result of fetchResult.json is also undefined.

Which is strange, since the link https://opentdb.com/api_category.php immediately returns the following (and you can check it for yourself by clicking the above link):

{"trivia_categories":[{"id":9,"name":"General Knowledge"},{"id":10,"name":"Entertainment: Books"},{"id":11,"name":"Entertainment: Film"},{"id":12,"name":"Entertainment: Music"},{"id":13,"name":"Entertainment: Musicals & Theatres"},{"id":14,"name":"Entertainment: Television"},{"id":15,"name":"Entertainment: Video Games"},{"id":16,"name":"Entertainment: Board Games"},{"id":17,"name":"Science & Nature"},{"id":18,"name":"Science: Computers"},{"id":19,"name":"Science: Mathematics"},{"id":20,"name":"Mythology"},{"id":21,"name":"Sports"},{"id":22,"name":"Geography"},{"id":23,"name":"History"},{"id":24,"name":"Politics"},{"id":25,"name":"Art"},{"id":26,"name":"Celebrities"},{"id":27,"name":"Animals"},{"id":28,"name":"Vehicles"},{"id":29,"name":"Entertainment: Comics"},{"id":30,"name":"Science: Gadgets"},{"id":31,"name":"Entertainment: Japanese Anime & Manga"},{"id":32,"name":"Entertainment: Cartoon & Animations"}]}

How do I get the above results from fetching from the URL? Did I miss anything?

Body:
fetchResult.json() is a method, not a property and it returns a promise.

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

https://developer.mozilla.org/en-US/docs/Web/API/Body/json

Try this:

const fetchResult = await fetch('https://opentdb.com/api_category.php');
const data = await fetchResult.json();
console.log(data);


问:
Change class for selected div only
I would like it to only change the class for the clicked div. Currently it will change the class for all divs. I have written this as a Blazor component.

```<code>@for (int i = 0; i < 5; i++)
{
    <div class="@divClass" @onclick="_ => ChangeDivClass()">@i</div>
}

@code
{
    String divClass;

    private void ChangeDivClass()
    {
        if (divClass == "red")
        {
            divClass = String.Empty;
        }
        else
        {
            divClass = "red";
        }
    }
}
</code>```

答:
You can use an array instead of one variable.</p>

```<code>@for (int i = 0; i < divClass.Length; i++)
 {
   var index = i;
   <div class="@divClass[i]" @onclick="_ => ChangeDivClass(index)">@i</div>
 }

@code
 {
   string[] divClass= new string[5];

   private void ChangeDivClass(int i)
    {
     if (divClass[i] == "red")
      {
        divClass[i] = String.Empty;
      }
     else
      {
        divClass[i] = "red";
      }
  }
}
</code>```

Title: Change class for selected div only

Body:
I would like it to only change the class for the clicked div. Currently it will change the class for all divs. I have written this as a Blazor component.

@for (int i = 0; i < 5; i++)
{

 ChangeDivClass()">@i

}

@code
{
    String divClass;

    private void ChangeDivClass()
    {
        if (divClass == "red")
        {
            divClass = String.Empty;
        }
        else
        {
            divClass = "red";
        }
    }
}

Body:
You can use an array instead of one variable.

@for (int i = 0; i < divClass.Length; i++)
 {
   var index = i;
   <div class="@divClass[i]" @onclick="_ => ChangeDivClass(index)">@i</div>
 }

@code
 {
   string[] divClass= new string[5];

   private void ChangeDivClass(int i)
    {
     if (divClass[i] == "red")
      {
        divClass[i] = String.Empty;
      }
     else
      {
        divClass[i] = "red";
      }
  }
}


问:
How to select all checkboxes, while clicking the main checkbox in android?
I need selecting the main checkbox, the all other partial checkboxes also selected

My Requirement is ,I have a checkbox selectAll and some other checkboxes,by clicking this selectAll checkbox ,all other checkboxes must selected.And while clicking the partial checkbox the selectAll checkbox selection must gone.

```<code> selectAllCheckbox.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                CheckBox cb = (CheckBox) view;
                isPartial = true;
                splitItemAdapter.selectAllItem(cb.isChecked());
                if (isFromCashPayment) {
                    if (cb.isChecked()) {
                      selectAllCheckbox.setChecked(true);
                      isitemChecked = true;

                    } else {

                        selectAllCheckbox.setChecked(false);

                        isitemChecked = false;

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

答:
You can try this code:

OnCreate

```<code>        parent = findViewById(R.id.parent_checkbox);
        child1 = findViewById(R.id.child_checkbox_1);
        child2 = findViewById(R.id.child_checkbox_2);

        parent.setOnCheckedChangeListener(this);
        child1.setOnCheckedChangeListener(this);
        child2.setOnCheckedChangeListener(this);
</code>```

OnCheckChanged

```<code>@Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        checkCheckBox(buttonView);
    }
</code>```

checkCheckBox Method

```<code>public void checkCheckBox(View view){
     if (parent.isChecked() && view.getId() == R.id.parent_checkbox){
         child1.setChecked(true);
         child2.setChecked(true);
     }
     else if (!parent.isChecked() && view.getId() == R.id.parent_checkbox){
         if (child1.isChecked() && child2.isChecked()){
             child1.setChecked(false);
             child2.setChecked(false);
         }
     }
     else if (!parent.isChecked()){
         if (child1.isChecked() && child2.isChecked()){
             parent.setChecked(true);
         }
     }
     else if (parent.isChecked() && !child1.isChecked() || !child2.isChecked()){
         parent.setChecked(false);
     }
    }
</code>```

Body:
I need selecting the main checkbox, the all other partial checkboxes also selected

My Requirement is ,I have a checkbox selectAll and some other checkboxes,by clicking this selectAll checkbox ,all other checkboxes must selected.And while clicking the partial checkbox the selectAll checkbox selection must gone.

 selectAllCheckbox.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                CheckBox cb = (CheckBox) view;
                isPartial = true;
                splitItemAdapter.selectAllItem(cb.isChecked());
                if (isFromCashPayment) {
                    if (cb.isChecked()) {
                      selectAllCheckbox.setChecked(true);
                      isitemChecked = true;

                    } else {

                        selectAllCheckbox.setChecked(false);

                        isitemChecked = false;

                    }
                }
            }
        });

Body:
You can try this code:

OnCreate

        parent = findViewById(R.id.parent_checkbox);
        child1 = findViewById(R.id.child_checkbox_1);
        child2 = findViewById(R.id.child_checkbox_2);

        parent.setOnCheckedChangeListener(this);
        child1.setOnCheckedChangeListener(this);
        child2.setOnCheckedChangeListener(this);

OnCheckChanged

@Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        checkCheckBox(buttonView);
    }

checkCheckBox Method

public void checkCheckBox(View view){
     if (parent.isChecked() && view.getId() == R.id.parent_checkbox){
         child1.setChecked(true);
         child2.setChecked(true);
     }
     else if (!parent.isChecked() && view.getId() == R.id.parent_checkbox){
         if (child1.isChecked() && child2.isChecked()){
             child1.setChecked(false);
             child2.setChecked(false);
         }
     }
     else if (!parent.isChecked()){
         if (child1.isChecked() && child2.isChecked()){
             parent.setChecked(true);
         }
     }
     else if (parent.isChecked() && !child1.isChecked() || !child2.isChecked()){
         parent.setChecked(false);
     }
    }


问:
Is it normal to have two different dependent assembly but have the same public key token?
System.IO.FileSystem.Primitives -> b03f5f7f11d50a3a

System.Runtime.CompilerServices.Unsafe -> b03f5f7f11d50a3a

```<code><dependentAssembly>
            <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
</dependentAssembly>
</code>```

I have this error:

An assembly with the same identity 'System.IO.FileSystem.Primitives,
  Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' has
  already been imported. Try removing one of the duplicate references.

答: Yes, this is normal; the key-token here is the thumbprint of the key used to strong-name the assembly - it isn't unique to the assembly itself (unless the library author created a key and only used it to sign one assembly). In the case of system assemblies, they are all usually signed by the same key (or small set of keys). b03f5f7f11d50a3a is a very well known key token - it is even mentioned in the ECMA-335 specification.

Body:
System.IO.FileSystem.Primitives -> b03f5f7f11d50a3a

System.Runtime.CompilerServices.Unsafe -> b03f5f7f11d50a3a

<dependentAssembly>
            <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
</dependentAssembly>

I have this error:

An assembly with the same identity 'System.IO.FileSystem.Primitives,
  Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' has
  already been imported. Try removing one of the duplicate references.


问:
I want a Report based of this 2 tables
```<code>   create table label_table(
   label_id number not null,
   label_name varchar2(50),
   no_months number not null,
   no_of_mobile_sims number not null,
   no_of_services number not null,
   delayed number not null,
   value_of_client number(6,2),
   constraint pk PRIMARY KEY(label_id)
   );

   create table client(
   customer_id number not null,
   customer_name varchar2(50) not null,
   no_months number not null,
   no_of_mobile_sims number not null,
   no_of_services number not null,
   delayed number not null,
  value_of_client number(6,2),
  constraint pk_key PRIMARY KEY(customer_id)
  ) ;

  SELECT
   l.label_id,
   l.label_name,
   k.customer_id,
   k.customer_name
   FROM
   label_table   l
   inner JOIN client k ON k.value_of_client>l.value_of_client
   ORDER BY 1;
</code>```

If we do a select * from client we have this output:

```<code>13 x_name        3                 4              2           0           74.38
</code>```

And if we do a select * from label_table we this output:

```<code>1 Diamond                  2                 2              2          0              70
2 Gold                     2                 1              2          2              50
</code>```

We have our client x_name who join our phone company let s say and i want to have a report where
it will say that x_name is a diamond client based on a comparison between the common columns of these 2 tables and i want an output like this:

13 x_name Diamond

And i want to this with a join but the problem is every time i try my client will be identified with both labels because he respect the conditions(>,<,!=,=) of both labels.
The idea is i have 16 clients that have different values and i want to put every one of them in a unique label not in more based on this 2 tables.
For example client.no_of_months>label.table.no_of_months,client.value_of_client>label.client.value_of_client then a label but how i said upper i need every client to be in his first choice label if a client is a diamond the output will be diamond not diamond,gold,silver,bronze even if he can be in that labels too.

答:
I guess you may try below query -</p>

```<code>SELECT customer_id, customer_name, label_name
FROM (SELECT k.customer_id,
             k.customer_name,
             l.label_name,
             ROW_NUMBER() OVER(PARTITION BY k.customer_id ORDER BY l.value_of_client DESC) RN
      FROM label_table   l
      inner JOIN client k ON k.value_of_client>l.value_of_client)
WHERE RN = 1
ORDER BY 1;
</code>```

Title: I want a Report based of this 2 tables

Body:
   create table label_table(
   label_id number not null,
   label_name varchar2(50),
   no_months number not null,
   no_of_mobile_sims number not null,
   no_of_services number not null,
   delayed number not null,
   value_of_client number(6,2),
   constraint pk PRIMARY KEY(label_id)
   );

   create table client(
   customer_id number not null,
   customer_name varchar2(50) not null,
   no_months number not null,
   no_of_mobile_sims number not null,
   no_of_services number not null,
   delayed number not null,
  value_of_client number(6,2),
  constraint pk_key PRIMARY KEY(customer_id)
  ) ;

  SELECT
   l.label_id,
   l.label_name,
   k.customer_id,
   k.customer_name
   FROM
   label_table   l
   inner JOIN client k ON k.value_of_client>l.value_of_client
   ORDER BY 1;

If we do a select * from client we have this output:

13 x_name        3                 4              2           0           74.38

And if we do a select * from label_table we this output:

1 Diamond                  2                 2              2          0              70
2 Gold                     2                 1              2          2              50

We have our client x_name who join our phone company let s say and i want to have a report where
it will say that x_name is a diamond client based on a comparison between the common columns of these 2 tables and i want an output like this:

13 x_name Diamond

And i want to this with a join but the problem is every time i try my client will be identified with both labels because he respect the conditions(>,<,!=,=) of both labels.
The idea is i have 16 clients that have different values and i want to put every one of them in a unique label not in more based on this 2 tables.
For example client.no_of_months>label.table.no_of_months,client.value_of_client>label.client.value_of_client then a label but how i said upper i need every client to be in his first choice label if a client is a diamond the output will be diamond not diamond,gold,silver,bronze even if he can be in that labels too.

Body:
I guess you may try below query -

SELECT customer_id, customer_name, label_name
FROM (SELECT k.customer_id,
             k.customer_name,
             l.label_name,
             ROW_NUMBER() OVER(PARTITION BY k.customer_id ORDER BY l.value_of_client DESC) RN
      FROM label_table   l
      inner JOIN client k ON k.value_of_client>l.value_of_client)
WHERE RN = 1
ORDER BY 1;


问:
Output of invoice from number of tables
I have the following tables

```<code>customers

cust_id     cust_name
1           a company
2           a company 2
3           a company 3

tariffs

tariff_id   cost_1     cost_2     cost_3
1           2          0          3
2           1          1          1
3           4          0          0

terminals

term_id     cust_id      term_number     tariff_id
1           1            12345           1
2           1            67890           2
3           2            14324           1
4           3            78788           3

usage

term_ident  usage_type   usage_amount    date
12345       1            20              11/12/2010
67890       2            10              31/12/2010
14324       1            1               01/01/2011
14324       2            5               01/01/2011
78788       1            0               14/01/2011
</code>```

In real life the tables are quite large - there are 5000 customers, 250 tariffs, 500000 terminals and 5 million usage records.

In the terminals table - term_id, cust_id and tariff_id are all foreign keys. There are no foreign keys in the usage table - this is just raw data imported from a csv file.

There could be terminals in the usage table that do not exist in the terminals table - these can be ignored.

What I need to do is produce an invoice per customer on usage. I only want to include usage between 15/12/2010 and 15/01/2011 - this is the billing period. I need to calculate the line items of the invoice for the usage based on its tariff ... for example: take the first record in the usage table - the cost of usage_1 (for term_id 1) would be 90x2=180, this is because term_ident uses tariff_id number 1.

The output should be as follows

```<code>Customer 2

date         terminal  usage_cost_1  usage_cost_2  usage_cost_3  total cost
01/01/2011   14324     18            0             6             24
</code>```

I am a competent PHP developer - but only a beginner with SQL. What I need some advice on is the most efficient process for producing the invoices - perhaps there is an SQL query that would help me before the processing in PHP starts to calculate the costs - or perhaps the SQL statement could produce the costs too ? Any advice is welcome ....

Edit:

1) There is something currently running this process - its written in C++ and takes around 24 hours to process this ... i do not have access to the source.

2) I am using Doctrine in Symfony - im not sure how helpfuly Doctrine will be as retrieving data as Objects is only going to slow down the process - and I'm not sure if the use of Objects will help too much here ?

Edit @13:54 ->

Had the usage table specified incorrectly ... Sorry !

I have to map the usage_type to a cost on the specific tariff for each terminal ie usage_type of 1 = cost_1 in appropriate tariff ... I guess that makes it slightly more complicated ?

答:
There you go, should take less than 24 hours ;)

```<code>SELECT u.date, u.term_ident terminal,
    (ta.cost_1 * u.usage_1) usage_cost_1,
    (ta.cost_2 * u.usage_2) usage_cost_2,
    (ta.cost_3 * u.usage_3) usage_cost_3,
    (usage_cost_1 + usage_cost_2 + usage_cost_3) total_cost
FROM usage u
INNER JOIN terminals te ON te.term_number = u.term_ident
INNER JOIN tariffs ta ON ta.tariff_id = te.tariff_id
INNER JOIN customers c ON c.cust_id = te.cust_id
WHERE u.date BETWEEN '2010-12-15' AND '2011-01-15'
    AND c.cust_id = 2
</code>```

This query is only for the customer with cust_id = 2. If you want a result for the whole dataset, just remove the condition.

Update

It's not that trivial with your new requirements. You could transform the usage table to the new one you posted before.

To make a decision in SELECT queries you can do something like this. But this is not the result you expect. It could be used to create the transformed new usage table.

```<code>SELECT u.date, u.term_ident terminal,
    CASE u.usage_type
        WHEN 1 then ta.cost_1 * u.usage_1
        WHEN 2 then ta.cost_2 * u.usage_2
        WHEN 3 THEN ta.cost_3 * u.usage_3
    AS usage_cost
FROM usage u
INNER JOIN terminals te ON te.term_number = u.term_ident
INNER JOIN tariffs ta ON ta.tariff_id = te.tariff_id
INNER JOIN customers c ON c.cust_id = te.cust_id
WHERE u.date BETWEEN '2010-12-15' AND '2011-01-15'
    AND c.cust_id = 2
</code>```

Title: Output of invoice from number of tables

Body:
I have the following tables

customers

cust_id     cust_name
1           a company
2           a company 2
3           a company 3

tariffs

tariff_id   cost_1     cost_2     cost_3
1           2          0          3
2           1          1          1
3           4          0          0

terminals

term_id     cust_id      term_number     tariff_id
1           1            12345           1
2           1            67890           2
3           2            14324           1
4           3            78788           3

usage

term_ident  usage_type   usage_amount    date
12345       1            20              11/12/2010
67890       2            10              31/12/2010
14324       1            1               01/01/2011
14324       2            5               01/01/2011
78788       1            0               14/01/2011

In real life the tables are quite large - there are 5000 customers, 250 tariffs, 500000 terminals and 5 million usage records.

In the terminals table - term_id, cust_id and tariff_id are all foreign keys. There are no foreign keys in the usage table - this is just raw data imported from a csv file.

There could be terminals in the usage table that do not exist in the terminals table - these can be ignored.

What I need to do is produce an invoice per customer on usage. I only want to include usage between 15/12/2010 and 15/01/2011 - this is the billing period. I need to calculate the line items of the invoice for the usage based on its tariff ... for example: take the first record in the usage table - the cost of usage_1 (for term_id 1) would be 90x2=180, this is because term_ident uses tariff_id number 1.

The output should be as follows

Customer 2

date         terminal  usage_cost_1  usage_cost_2  usage_cost_3  total cost
01/01/2011   14324     18            0             6             24

I am a competent PHP developer - but only a beginner with SQL. What I need some advice on is the most efficient process for producing the invoices - perhaps there is an SQL query that would help me before the processing in PHP starts to calculate the costs - or perhaps the SQL statement could produce the costs too ? Any advice is welcome ....

Edit:

1) There is something currently running this process - its written in C++ and takes around 24 hours to process this ... i do not have access to the source.

2) I am using Doctrine in Symfony - im not sure how helpfuly Doctrine will be as retrieving data as Objects is only going to slow down the process - and I'm not sure if the use of Objects will help too much here ?

Edit @13:54 ->

Had the usage table specified incorrectly ... Sorry !

I have to map the usage_type to a cost on the specific tariff for each terminal ie usage_type of 1 = cost_1 in appropriate tariff ... I guess that makes it slightly more complicated ?

Body:
There you go, should take less than 24 hours ;)

SELECT u.date, u.term_ident terminal,
    (ta.cost_1 * u.usage_1) usage_cost_1,
    (ta.cost_2 * u.usage_2) usage_cost_2,
    (ta.cost_3 * u.usage_3) usage_cost_3,
    (usage_cost_1 + usage_cost_2 + usage_cost_3) total_cost
FROM usage u
INNER JOIN terminals te ON te.term_number = u.term_ident
INNER JOIN tariffs ta ON ta.tariff_id = te.tariff_id
INNER JOIN customers c ON c.cust_id = te.cust_id
WHERE u.date BETWEEN '2010-12-15' AND '2011-01-15'
    AND c.cust_id = 2

This query is only for the customer with cust_id = 2. If you want a result for the whole dataset, just remove the condition.

Update

It's not that trivial with your new requirements. You could transform the usage table to the new one you posted before.

To make a decision in SELECT queries you can do something like this. But this is not the result you expect. It could be used to create the transformed new usage table.

SELECT u.date, u.term_ident terminal,
    CASE u.usage_type
        WHEN 1 then ta.cost_1 * u.usage_1
        WHEN 2 then ta.cost_2 * u.usage_2
        WHEN 3 THEN ta.cost_3 * u.usage_3
    AS usage_cost
FROM usage u
INNER JOIN terminals te ON te.term_number = u.term_ident
INNER JOIN tariffs ta ON ta.tariff_id = te.tariff_id
INNER JOIN customers c ON c.cust_id = te.cust_id
WHERE u.date BETWEEN '2010-12-15' AND '2011-01-15'
    AND c.cust_id = 2