问:
How to remove some default identity tables in ASP.NET Core 2.2
I am trying to remove some of default identity tables by ignoring them in OnModelCreating as follows:

```<code>public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ApplicationUser>(p => p.HasOne(e=>e.Department).WithOne().IsRequired());
        modelBuilder.Ignore<IdentityUserToken<string>>();
        modelBuilder.Ignore<IdentityUserClaim<string>>();
        modelBuilder.Ignore<IdentityUserLogin<string>>();
        modelBuilder.Ignore<IdentityRoleClaim<string>>();
        modelBuilder.Ignore<IdentityUser<string>>();
    }
}
</code>```

and in startup.cs I configured the identity like:

```<code>services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>();
</code>```

When I register a user everything work fine, but when a user tries to login it throws this error:

Cannot create a DbSet for 'IdentityUserClaim' because this
  type is not included in the model for the context

what did I miss in my configurations?

please don't mark it as duplicate because I searched a lot and yet couldn't fine an appropriate solution

答:
I did this in the following  way and it worked for me. I ignored some ASP Identity Tables and also unnecessary column for my scenario from AspNetUser
I am using ASP .Net  Core 2.2</p>

```<code>public class ApplicationContext: IdentityDbContext
{
    public ApplicationContext(DbContextOptions options): base(options)
    {

    }

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Ignore<IdentityRole>();
        modelBuilder.Ignore<IdentityUserToken<string>>();
        modelBuilder.Ignore<IdentityUserRole<string>>();
        modelBuilder.Ignore<IdentityUserLogin<string>>();
        modelBuilder.Ignore<IdentityUserClaim<string>>();
        modelBuilder.Ignore<IdentityRoleClaim<string>>();
        modelBuilder.Entity<IdentityUser>()

            .Ignore(c => c.AccessFailedCount)
            .Ignore(c => c.LockoutEnabled)
            .Ignore(c => c.TwoFactorEnabled)
            .Ignore(c => c.ConcurrencyStamp)
            .Ignore(c => c.LockoutEnd)
            .Ignore(c => c.EmailConfirmed)
            .Ignore(c => c.TwoFactorEnabled)
            .Ignore(c => c.LockoutEnd)
            .Ignore(c => c.AccessFailedCount)
            .Ignore(c => c.PhoneNumberConfirmed)
            .Ignore(c => c.Email)
            .Ignore(c => c.NormalizedEmail)
            .Ignore(c => c.PhoneNumber);

        modelBuilder.Entity<IdentityUser>().ToTable("Users");//to change the name of table.

    } }}
</code>```

Body:
I am trying to remove some of default identity tables by ignoring them in OnModelCreating as follows:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ApplicationUser>(p => p.HasOne(e=>e.Department).WithOne().IsRequired());
        modelBuilder.Ignore<IdentityUserToken<string>>();
        modelBuilder.Ignore<IdentityUserClaim<string>>();
        modelBuilder.Ignore<IdentityUserLogin<string>>();
        modelBuilder.Ignore<IdentityRoleClaim<string>>();
        modelBuilder.Ignore<IdentityUser<string>>();
    }
}

and in startup.cs I configured the identity like:

services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>();

When I register a user everything work fine, but when a user tries to login it throws this error:

Cannot create a DbSet for 'IdentityUserClaim' because this
  type is not included in the model for the context

what did I miss in my configurations?

please don't mark it as duplicate because I searched a lot and yet couldn't fine an appropriate solution

Body:
I did this in the following  way and it worked for me. I ignored some ASP Identity Tables and also unnecessary column for my scenario from AspNetUser
I am using ASP .Net  Core 2.2

public class ApplicationContext: IdentityDbContext
{
    public ApplicationContext(DbContextOptions options): base(options)
    {

    }

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Ignore<IdentityRole>();
        modelBuilder.Ignore<IdentityUserToken<string>>();
        modelBuilder.Ignore<IdentityUserRole<string>>();
        modelBuilder.Ignore<IdentityUserLogin<string>>();
        modelBuilder.Ignore<IdentityUserClaim<string>>();
        modelBuilder.Ignore<IdentityRoleClaim<string>>();
        modelBuilder.Entity<IdentityUser>()

            .Ignore(c => c.AccessFailedCount)
            .Ignore(c => c.LockoutEnabled)
            .Ignore(c => c.TwoFactorEnabled)
            .Ignore(c => c.ConcurrencyStamp)
            .Ignore(c => c.LockoutEnd)
            .Ignore(c => c.EmailConfirmed)
            .Ignore(c => c.TwoFactorEnabled)
            .Ignore(c => c.LockoutEnd)
            .Ignore(c => c.AccessFailedCount)
            .Ignore(c => c.PhoneNumberConfirmed)
            .Ignore(c => c.Email)
            .Ignore(c => c.NormalizedEmail)
            .Ignore(c => c.PhoneNumber);

        modelBuilder.Entity<IdentityUser>().ToTable("Users");//to change the name of table.

    } }}


来源: stackexchange

问:
How can I know what are the automatically bins will be created?
This code is from "SystemVerilog IEEE STD 1800-2017 ":

```<code>bit [7:0] a;
covergroup ga ( int abm);
  option.auto_bin_max = abm;
  coverpoint a { ignore_bins i = {3}; }
endgroup

ga gv1 = new (64);
ga gv2 = new (32);
</code>```

It is written that in the example above:
"In this case, the bins of the instance referenced by gv1 are “auto[0:3]” through “auto[252:255],” while the
bins of the instance referenced by gv2 are “auto[0:7]” through “auto[248:255].”"

Can someone explain it to me, why those bins are created?

答:
Yes. The option auto_bin_max sets the maximum number of bins that will be created automatically. So, with an 8-bit variable a (as you have here), instead of creating 256 bins (one bin per value), you get auto_bin_max bins.

When auto_bin_max is set to 64 for covergroup instance gv1 (which is actually its default value anyway), so you get 64 equally-sized bins. 256/64=4, each bin is 4 values.

When auto_bin_max is set to 32 for covergroup instance gv2, so you get 32 equally-sized bins. 256/32=8, so each bin is 8 values.

ContentLicense: CC BY-SA 4.0

Body:
This code is from "SystemVerilog IEEE STD 1800-2017 ":

bit [7:0] a;
covergroup ga ( int abm);
  option.auto_bin_max = abm;
  coverpoint a { ignore_bins i = {3}; }
endgroup

ga gv1 = new (64);
ga gv2 = new (32);

It is written that in the example above:
"In this case, the bins of the instance referenced by gv1 are “auto[0:3]” through “auto[252:255],” while the
bins of the instance referenced by gv2 are “auto[0:7]” through “auto[248:255].”"

Can someone explain it to me, why those bins are created?


问:
Object reference is required for the non-static field method or property
I have a problem with calling a method encrypt. It shows an error CS0210 "An object reference is required for the nonstatic field, method, or property". I tried to rectify this by adding 'static' keyword to encrypt method, but it also didn't work. How do I fix this?

```<code>class Program
{
    string alphabet = "ABCDEFGHIJKLMNOPQRSTYVWXYZ";
    string alph = "abcdefghijklmnopqrstuvwxyz";
    static void Main(string[] args)
    {
        Console.WriteLine("Input text to encrypt: ");
        string text = Console.ReadLine();
        Console.WriteLine("Input key: ");
        string key = Console.ReadLine();

        encrypt(text, key);
        Console.ReadLine();
    }

    int positionAlphabet(char letter)
    {
        for (int i = 0; i < alphabet.Length; i++)
        {
            if (alphabet[i] == letter || alph[i] == letter)
            {
                return i;
            }
        }
        return -1;
    }
    public void encrypt(string text, string key)
    {
        string output = "";

        for (int i = 0; i < text.Length; i++)
        {
            int positionLetterKey = positionAlphabet(key[i % key.Length]);
            int positionLetterText = positionAlphabet(text[i]);
            output += alphabet[(positionLetterText + positionLetterKey) % alphabet.Length];
        }
        Console.WriteLine("Encryption output: \n", output);
    }
}
</code>```

答: You should add a static keyword before the function PositionAlphabet as well. You cannot call a non-static function from another static function.</p>

Body:
I have a problem with calling a method encrypt. It shows an error CS0210 "An object reference is required for the nonstatic field, method, or property". I tried to rectify this by adding 'static' keyword to encrypt method, but it also didn't work. How do I fix this?

class Program
{
    string alphabet = "ABCDEFGHIJKLMNOPQRSTYVWXYZ";
    string alph = "abcdefghijklmnopqrstuvwxyz";
    static void Main(string[] args)
    {
        Console.WriteLine("Input text to encrypt: ");
        string text = Console.ReadLine();
        Console.WriteLine("Input key: ");
        string key = Console.ReadLine();

        encrypt(text, key);
        Console.ReadLine();
    }

    int positionAlphabet(char letter)
    {
        for (int i = 0; i < alphabet.Length; i++)
        {
            if (alphabet[i] == letter || alph[i] == letter)
            {
                return i;
            }
        }
        return -1;
    }
    public void encrypt(string text, string key)
    {
        string output = "";

        for (int i = 0; i < text.Length; i++)
        {
            int positionLetterKey = positionAlphabet(key[i % key.Length]);
            int positionLetterText = positionAlphabet(text[i]);
            output += alphabet[(positionLetterText + positionLetterKey) % alphabet.Length];
        }
        Console.WriteLine("Encryption output: \n", output);
    }
}


问:
Azure Powershell Function App Interacting with Blob
Very new to Azure and Function Apps.

I'm trying to set up a simple Function app using Powershell which needs to read the content from a blob (simple .txt file), do some simple processing on it and write a copy of that file into different blob.

So far I have set up the integration on the app, which I can see provides a binding I can use. Looks like this:

```<code> {
  "name": "inputBlob",
  "direction": "in",
  "type": "blob",
  "path": "input/logs.txt",
  "connection": "AzureWebJobsStorage"
}
</code>```

I'm referencing that binding in the powershell params at the start of the script:

```<code># Input bindings are passed in via param block.
param($Request, $TriggerMetadata, $inputBlob)
</code>```

As I understand things this should allow me to connect to that blob and interact with it. What I don't understand is how should that be done? I have tried to use the cmdlet that seems to make the most sense for the situation:  Get-AzStorageBlobContent

for example:

```<code>$blobContent = Get-AzStorageBlobContent -name $inputBlob
</code>```

But when I try to return that content in my http reponse (so I can check that it was read), the response body is empty.

I presume that I will need to add further bindings for outputing to blobs too?

For example, the Set-AzStorageBlobContent  cmdlet seems to only support 'files' but in my case within the function app, I don't have a file, just a string or an array, so how do I push that content into the target blob?

Would appreciate any pointers on how to achieve this,

答:
The $inputBlob variable should contain the blob data as an array of bytes, so you can do:

```<code>foreach ($value in $inputBlob) { ... }
</code>```

or anything else you would do with an array of bytes.

If you need to output to a blob, you need to add an output binding:

```<code>    {
      "name": "myOutputBlob",
      "type": "blob",
      "path": "output/data.txt",
      "connection": "AzureWebJobsStorage",
      "direction": "out"
    }
</code>```

and push the data to this binding from your function code:

```<code>Push-OutputBinding -Name myOutputBlob -Value 'my value'
</code>```

Body:
Very new to Azure and Function Apps.

I'm trying to set up a simple Function app using Powershell which needs to read the content from a blob (simple .txt file), do some simple processing on it and write a copy of that file into different blob.

So far I have set up the integration on the app, which I can see provides a binding I can use. Looks like this:

 {
  "name": "inputBlob",
  "direction": "in",
  "type": "blob",
  "path": "input/logs.txt",
  "connection": "AzureWebJobsStorage"
}

I'm referencing that binding in the powershell params at the start of the script:

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata, $inputBlob)

As I understand things this should allow me to connect to that blob and interact with it. What I don't understand is how should that be done? I have tried to use the cmdlet that seems to make the most sense for the situation:  Get-AzStorageBlobContent

for example:

$blobContent = Get-AzStorageBlobContent -name $inputBlob

But when I try to return that content in my http reponse (so I can check that it was read), the response body is empty.

I presume that I will need to add further bindings for outputing to blobs too?

For example, the Set-AzStorageBlobContent  cmdlet seems to only support 'files' but in my case within the function app, I don't have a file, just a string or an array, so how do I push that content into the target blob?

Would appreciate any pointers on how to achieve this,

Body:
The $inputBlob variable should contain the blob data as an array of bytes, so you can do:

foreach ($value in $inputBlob) { ... }

or anything else you would do with an array of bytes.

If you need to output to a blob, you need to add an output binding:

    {
      "name": "myOutputBlob",
      "type": "blob",
      "path": "output/data.txt",
      "connection": "AzureWebJobsStorage",
      "direction": "out"
    }

and push the data to this binding from your function code:

Push-OutputBinding -Name myOutputBlob -Value 'my value'


问:
Azure VM connection error - The user account is currently disabled and cannot be used
Using Azure Powershell create a new VM using my own Vhd based on the tutorial:
https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-create-upload-vhd-windows-server/

When try to connect to the VM it pops the error:

The user account is currently disabled and cannot be used.

Below is the scripts for creating the VM

```<code>#create the vm using the image
$image = Get-AzureVMImage $MyImage
$vmname = "Test-Machine"
$vmsize = "Large"
$vm1=New-AzureVMConfig -Name $vmname -InstanceSize $vmsize -ImageName $image.imageName
$vm1 | Add-AzureProvisioningConfig -Windows -AdminUsername $username -Password $password
New-AzureVM –ServiceName $myServiceName -VMs $vm1
</code>```

答:
I just ran into this issue as well, trying to login a fresh Azure Windows 10 virtual machine.

You can fix this issue by:

On the virtual machine page, head over to Run command

Click on EnableAdminAccount

Run the cmdlet

You should see something like:

```<code>Admin account was disabled. Enabling the Admin account.

Path          : \\localhost\root\cimv2:Win32_UserAccount.Domain="PaoloWin10",Name="PaoloUser"
RelativePath  : Win32_UserAccount.Domain="PaoloWin10",Name="PaoloUser"
Server        : localhost
NamespacePath : root\cimv2
ClassName     : Win32_UserAccount
IsClass       : False
IsInstance    : True
IsSingleton   : False
</code>```

You should now be able to login in the virtual machine successfully.

Body:
Using Azure Powershell create a new VM using my own Vhd based on the tutorial:
https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-create-upload-vhd-windows-server/

When try to connect to the VM it pops the error:

The user account is currently disabled and cannot be used.

Below is the scripts for creating the VM

#create the vm using the image
$image = Get-AzureVMImage $MyImage
$vmname = "Test-Machine"
$vmsize = "Large"
$vm1=New-AzureVMConfig -Name $vmname -InstanceSize $vmsize -ImageName $image.imageName
$vm1 | Add-AzureProvisioningConfig -Windows -AdminUsername $username -Password $password
New-AzureVM –ServiceName $myServiceName -VMs $vm1

Body:
I just ran into this issue as well, trying to login a fresh Azure Windows 10 virtual machine.

You can fix this issue by:

On the virtual machine page, head over to Run command

Click on EnableAdminAccount

Run the cmdlet

You should see something like:

Admin account was disabled. Enabling the Admin account.

Path          : \\localhost\root\cimv2:Win32_UserAccount.Domain="PaoloWin10",Name="PaoloUser"
RelativePath  : Win32_UserAccount.Domain="PaoloWin10",Name="PaoloUser"
Server        : localhost
NamespacePath : root\cimv2
ClassName     : Win32_UserAccount
IsClass       : False
IsInstance    : True
IsSingleton   : False

You should now be able to login in the virtual machine successfully.


问:
How to wrap a static class in a non-static instance object (dynamically)
I have an interesting problem.  I need to wrap static classes dynamically.  I.e. return a non-static instance to my callers. e.g.:

```<code>public object CreateInstance(string className) {
  Type t = assembly.GetType(className);
  if (IsStatic(t)) {
    return CreateStaticWrapper(t);
  } else {
    return Activator.CreateInstance(t);
  }
}
</code>```

So what I need is pointers as to how to implement CreateStaticWrapper.

Note: I cannot use Dynamic objects unfortunately.

So what are my options?  I'm not that keen on learning IL generation?  If IL generation (Reflection.Emit, or is there other ways now?) is the way to go does anyone have pointers there?

Edit: It's important to note that I can return a Dictionary of Delegates.  So I could use Delegate.CreateDelegate for this but I can't seem to work out how to handle overloaded methods and Generic methods.

Edit2: Another option would be to inject an empty constructor into the type using Emit, again any pointers? Is this even possible on a type marked as static? Does the static keyword make it into the IL?

Edit3: For a bit of context, I'm passing this to a javascript environment see:  my project.  So I would like to be able to (in JavaScript):

```<code>var fileHelper = .create('System.IO.File');
if (fileHelper.Exists(fileName)) { fileHelper.Delete(fileName); }
</code>```

Thanks All.

答:
I'd say go for IL generation. Creating a proxy is a pretty simple scenario. I actually wrote a blog post about it: einarwh.posterous.com/patching-polymorphic-pain-at-runtime. The scenario is different, but the solution almost identical.

You can basically do exactly as in the blog post, except you don't need to load the 'this' reference onto the stack (since you're doing static method calls).

ContentLicense: CC BY-SA 3.0

Body:
I have an interesting problem.  I need to wrap static classes dynamically.  I.e. return a non-static instance to my callers. e.g.:

public object CreateInstance(string className) {
  Type t = assembly.GetType(className);
  if (IsStatic(t)) {
    return CreateStaticWrapper(t);
  } else {
    return Activator.CreateInstance(t);
  }
}

So what I need is pointers as to how to implement CreateStaticWrapper.

Note: I cannot use Dynamic objects unfortunately.

So what are my options?  I'm not that keen on learning IL generation?  If IL generation (Reflection.Emit, or is there other ways now?) is the way to go does anyone have pointers there?

Edit: It's important to note that I can return a Dictionary of Delegates.  So I could use Delegate.CreateDelegate for this but I can't seem to work out how to handle overloaded methods and Generic methods.

Edit2: Another option would be to inject an empty constructor into the type using Emit, again any pointers? Is this even possible on a type marked as static? Does the static keyword make it into the IL?

Edit3: For a bit of context, I'm passing this to a javascript environment see:  my project.  So I would like to be able to (in JavaScript):

var fileHelper = .create('System.IO.File');
if (fileHelper.Exists(fileName)) { fileHelper.Delete(fileName); }

Thanks All.


问:
Switching appsettings.json according to subdomain
How can I switch "appsettings.json" file when current subdomain change?

I want to implement multi-tenancy with separate databases.

for example:

When the URL is {x.site.com}, then I connect to database x.

When the URL is {y.site.com}, then I connect to database y.

答:
appsettings.json is just a JSON file, not a special file like app.config or web.config used to be. The configuration system loads settings from any configured source (json files, databases, command line, environment variables), with newer settings overriding older ones. This is described in ASP.NET Configuration. Despite the name, configuration works the same way for all .NET Core applications and .NET Old applications using the Microsoft.Extension.Configuration NuGet package.

appsettings.json is just the default file added by the host builder. The host builder also loads an environment-based file after that by checking an environment variable, eg appsettings.Production.json or appsettings.Staging.json. Nothing prevents you from loading another file called eg MyFavoriteSettings.json or, if you like ini files, MySettings.ini to override the settings loaded by previous files.

To override a connection string defined in app settings.json, eg :

```<code>{
  "ConnectionStrings": {
    "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
  },
}
</code>```

All you have to do is load a setting with the same name (ConnectionStrings:BloggingDatabase) as the setting you want to override. For example, in appsettings.Production.json you could enter :

```<code>{
  "ConnectionStrings": {
    "BloggingDatabase": "Server=localhost;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
  },
}
</code>```

and then, add another settings file, eg MyCustomerA.json

```<code>{
  "ConnectionStrings": {
    "BloggingDatabase": "Server=localhost;Database=CustomerA;Trusted_Connection=True;"
  },
}
</code>```

and register it

```<code>    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("CustomerA.json",
                    optional: true,
                    reloadOnChange: true);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
</code>```

The JSON Configuration Provider section has examples that show how to register multiple files.

You could also pass the connection string through an environment variable or command-line parameter. The default host builder configuration settings load environment variables after the json files and command line parameters last of all, overriding all previous settings.

In a multi-tenant environment using containers, environment variables would be an excellent way to override connection strings from the outside, without modifying the container itself. The connection string prefixes section explains how to name connection string environment variables for different database providers,

Body:
appsettings.json is just a JSON file, not a special file like app.config or web.config used to be. The configuration system loads settings from any configured source (json files, databases, command line, environment variables), with newer settings overriding older ones. This is described in ASP.NET Configuration. Despite the name, configuration works the same way for all .NET Core applications and .NET Old applications using the Microsoft.Extension.Configuration NuGet package.

appsettings.json is just the default file added by the host builder. The host builder also loads an environment-based file after that by checking an environment variable, eg appsettings.Production.json or appsettings.Staging.json. Nothing prevents you from loading another file called eg MyFavoriteSettings.json or, if you like ini files, MySettings.ini to override the settings loaded by previous files.

To override a connection string defined in app settings.json, eg :

{
  "ConnectionStrings": {
    "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
  },
}

All you have to do is load a setting with the same name (ConnectionStrings:BloggingDatabase) as the setting you want to override. For example, in appsettings.Production.json you could enter :

{
  "ConnectionStrings": {
    "BloggingDatabase": "Server=localhost;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
  },
}

and then, add another settings file, eg MyCustomerA.json

{
  "ConnectionStrings": {
    "BloggingDatabase": "Server=localhost;Database=CustomerA;Trusted_Connection=True;"
  },
}

and register it

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("CustomerA.json",
                    optional: true,
                    reloadOnChange: true);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

The JSON Configuration Provider section has examples that show how to register multiple files.

You could also pass the connection string through an environment variable or command-line parameter. The default host builder configuration settings load environment variables after the json files and command line parameters last of all, overriding all previous settings.

In a multi-tenant environment using containers, environment variables would be an excellent way to override connection strings from the outside, without modifying the container itself. The connection string prefixes section explains how to name connection string environment variables for different database providers,


问:
JavaScript - Use addition on values of multiple dynamically created objects with same name in array
I have an array of objects that's created dynamically (in React, although I don't think it matters), and I'm attempting to use addition on values that have the same name.

for example:

```<code>[{ n1:"1", n2:"2", n3:"3"},
 { n1:"4", n2:"6", n3:"4"},
 { n1:"3", n2:"1", n3:"2"}]
</code>```

the result of which would then be:

```<code>[{ n1:"8", n2:"9", n3:"9"}]
</code>```

Spread Syntax and the .assign method seem like they'd accomplish this, but both examples have predefined arrays, not dynamically created ones.

If it would be easier to parse the data so each name could occupy a new array, that'd be fine too. ie [n1:"8"],[n2:"9"],[n3:"9"]

答:
You could reduce the objects by creating a new object with the key/value pairs and add the value.

var data = [{ n1: "1", n2: "2", n3: "3"}, { n1: "4", n2: "6", n3: "4"}, { n1: "3", n2: "1", n3: "2"}],
    sums = data.reduce((target, source) => {
        Object.entries(source).forEach(([k, v]) => target[k] = (target[k] || 0) + +v);
        return target;
    }, {});

console.log(sums);```

Body:
I have an array of objects that's created dynamically (in React, although I don't think it matters), and I'm attempting to use addition on values that have the same name.

for example:

[{ n1:"1", n2:"2", n3:"3"},
 { n1:"4", n2:"6", n3:"4"},
 { n1:"3", n2:"1", n3:"2"}]

the result of which would then be:

[{ n1:"8", n2:"9", n3:"9"}]

Spread Syntax and the .assign method seem like they'd accomplish this, but both examples have predefined arrays, not dynamically created ones.

If it would be easier to parse the data so each name could occupy a new array, that'd be fine too. ie [n1:"8"],[n2:"9"],[n3:"9"]


问:
How to call a method of component in plugin
I made a component called dialog, and I want to make it plugin and register it as a global function.

However, I don't know how to access the component from plugin and call the component's method.

```<code>import Vue from 'vue'
import AlertDialog from '@/components/AlertDialog'

const methods = {
  openDialog: (
    maxWidth,
    title,
    message
  ) =>
    AlertDialog.openDialog(
      maxWidth,
      title,
      message
    ),
  closeDialog: () => AlertDialog.closeDialog()
}

Vue.prototype.openDialog = methods.openDialog
Vue.prototype.closeDialog = methods.closeDialog
</code>```

This is a dialog_plugin.js.

But it doesn't work.

edit
 ::

```<code><template>
  <v-dialog
    v-if="isShow"
    v-model="isShow"
    :max-width="maxWidth ? maxWidth : 290"
  >
    <v-card>
      ...
    </v-card>
  </v-dialog>
</template>

<script>
export default {
  data() {
    return {
      isShow: false,
      maxWidth: null,
      title: null
    }
  },
  methods: {
    openDialog(
      maxWidth,
      title
    ) {
      this.isShow = true
      ...
    },
    closeDialog() {
      this.isShow = false
    }
  }
}
</script>
</code>```

This is AlertDialog.vue

答:
A component's methods are only intended to be called from within the component itself. Trying to expose them to be called by outside code is really going against the way Vue is designed to work.

If you want to affect the state of a component from outside of itself, there are a couple of ways:

Props - Rather than isShow being a piece of the AlertDialog's state, you would pass this value in as a prop. That way the parent component can change the value to show/hide the alert as needed.

Vuex - If you needed to have a single instance of a component in your app (e.g. for a toast display), having it receive its state from a Vuex store would make it easy to display messages from any part of your app.

An Event Bus - For a simpler app where you don't want to bring in Vuex, you can always use an instance of Vue as an event bus, to control your component by emitting events from anywhere else in your app. Your component can then listen for these events and show/hide as needed.

Body:
I made a component called dialog, and I want to make it plugin and register it as a global function.

However, I don't know how to access the component from plugin and call the component's method.

import Vue from 'vue'
import AlertDialog from '@/components/AlertDialog'

const methods = {
  openDialog: (
    maxWidth,
    title,
    message
  ) =>
    AlertDialog.openDialog(
      maxWidth,
      title,
      message
    ),
  closeDialog: () => AlertDialog.closeDialog()
}

Vue.prototype.openDialog = methods.openDialog
Vue.prototype.closeDialog = methods.closeDialog

This is a dialog_plugin.js.

But it doesn't work.

edit
 ::

<template>
  <v-dialog
    v-if="isShow"
    v-model="isShow"
    :max-width="maxWidth ? maxWidth : 290"
  >
    <v-card>
      ...
    </v-card>
  </v-dialog>
</template>

This is AlertDialog.vue


问:
How to support Zoom like Safari with WKWebView on macOS
In Safari the user can enlarge the content by using the Zoom commands, like Command +. This enlarges not only the content, including font size, but it also adjusts the content to remain between the window margins.

I want to achieve the same feature with WKWebView on macOS, but I don't know how to do that when using the loadRequest() command on the web view control.

I have tried the following, without much success:

Inject javascript like "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust='150%'". It seems that webkitTextSizeAdjust is not supported anymore on the macOS version of WKWebView, see https://trac.webkit.org/changeset/145168/webkit.

Use the magnification property. This works, but this simply enlarges (or minimises) everything, without adjusting the content to remain between the control width (viewport), like Safari does.

Please take note that I'm using loadRequest(), not loadHTMLString().

答:
As an alternative to injecting javascript, as described in the accepted answer of @elsonpeng, you can also adjust the zoom level at any time like this (Swift):

```<code>webView.evaluateJavaScript("document.body.style.zoom = 1.5", completionHandler: nil)
</code>```

This can of course also be used in combination with WKNavigationDelegate, to execute the script when the page is fully loaded:

```<code>func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.body.style.zoom = 1.5", completionHandler: nil)
}
</code>```

This approach is a bit more flexible, but a bit slower then code injection, depending on the complexity of the page that you load.

Body:
As an alternative to injecting javascript, as described in the accepted answer of @elsonpeng, you can also adjust the zoom level at any time like this (Swift):

webView.evaluateJavaScript("document.body.style.zoom = 1.5", completionHandler: nil)

This can of course also be used in combination with WKNavigationDelegate, to execute the script when the page is fully loaded:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.body.style.zoom = 1.5", completionHandler: nil)
}

This approach is a bit more flexible, but a bit slower then code injection, depending on the complexity of the page that you load.


问:
How to differentiate between left alt key and right alt key in javascript key event and?
I am working on a project which require hotkeys implementation. It require Alt + Q for some purpose. I have implemented it but the problem is that it is working only for left side Alt key but when I press Alt + Q with right side Alt key, then it does not work. So I want to know how can I implement right Alt key in my project using javascript.

答:
DOM3 added a location property of keyboard events (see MDN) (earlier versions had a keyLocation property instead) which does what you want and is implemented in recent versions of all major browsers.

```<code>document.onkeydown = function (e) {
  alert(e.location || e.keyLocation); // '1' for LeftAlt, and '2' for RightAlt
}
</code>```

Body:
DOM3 added a location property of keyboard events (see MDN) (earlier versions had a keyLocation property instead) which does what you want and is implemented in recent versions of all major browsers.

document.onkeydown = function (e) {
  alert(e.location || e.keyLocation); // '1' for LeftAlt, and '2' for RightAlt
}


问:
How to use mouse click and keyboard keys in combination / together to perform or call any function in JAVASCRIPT?
I have a function which is called on click of a button i.e:

```<code>function print(){
alert("PRINT")
}

btn.addEventListener("click", print);
</code>```

This will print as soon as button is clicked . But I want to call this function on the combination of keyboard key + mouse click i.e something like (q+click) i.e user press q key of keyboard and by clicking the q along mouse click . For control key it can be done easily , but for other keys how it could be done ??

Thanks

答:
You should keep track of the keys pressed and released for yourself

"use strict";
console.clear()
{
  let keysPressed = {}

  const onKeyDown = e => {
    if (!e.repeat) {
      keysPressed[e.key] = true
    }
  }

  const onKeyUp = e => {
      delete keysPressed[e.key]
  }

  const onClick = e => {
    if (e.target.id == 'click-btn') {
      console.log('Keys pressed:', Object.keys(keysPressed).join(', '))
    }
  }

  document.addEventListener('click', onClick)
  document.addEventListener('keydown', onKeyDown)
  document.addEventListener('keyup', onKeyUp)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="click-btn">Click</button></code>```

Body:
I have a function which is called on click of a button i.e:

function print(){
alert("PRINT")
}

btn.addEventListener("click", print);

This will print as soon as button is clicked . But I want to call this function on the combination of keyboard key + mouse click i.e something like (q+click) i.e user press q key of keyboard and by clicking the q along mouse click . For control key it can be done easily , but for other keys how it could be done ??

Thanks

Body:
You should keep track of the keys pressed and released for yourself

"use strict";
console.clear()
{
  let keysPressed = {}

  const onKeyDown = e => {
    if (!e.repeat) {
      keysPressed[e.key] = true
    }
  }

  const onKeyUp = e => {
      delete keysPressed[e.key]
  }

  const onClick = e => {
    if (e.target.id == 'click-btn') {
      console.log('Keys pressed:', Object.keys(keysPressed).join(', '))
    }
  }

  document.addEventListener('click', onClick)
  document.addEventListener('keydown', onKeyDown)
  document.addEventListener('keyup', onKeyUp)
}

<button id="click-btn">Click</button>


问:
Runtime error in codeforces but worked just fine in Dev-C++
I'm trying to solve a problem which requires: a sentence that has less than 150 characters as an input and makes that sentence's characters all to uppercase while removing all extra white spaces, then prints the changed sentence and its number of characters to the screen.
For example:
Input: Look            in to the   abyss
Output:LOOK IN TO THE ABYSS:20

 I tested this program on Dev-C++ and it worked just fine but when i submitted it to CodeForces I got runtime error. I hope anyone can help me with this.

( I tried to use scanf("%[^\n]%*c", sen) and fgets(sen, sizeof(sen), stdin) instead of gets(sen) but i still get runtime error. Also, i use a different function strlength instead of strlen since i had another type-related error when submitting that piece of code to CodeForces )
 P/s: Sorry for my bad English

```<code>#include <ctype.h>
#include <stdio.h>

int strlength(char* str){
    int i,j = 0;
    for (i=0; str[i]!= '\0';i++)
        ++j;
    return j;
}
void strip_white_spaces(char* str){
    int x,i;
    for (x=i=0; str[i]!='\0';i++){
        if (!isspace(str[i])||((i>0) && (!isspace(str[i-1]))))
            str[x++] = str[i];
    }
    if (isspace(str[x-1]))
        str[x-1]='\0';
    else str[x] ='\0';
}
void touppercase(char* str){
    int i;
    for (i = 0; str[i] != '\0';i++ ){
        if (str[i] >= 'a' && str[i] <= 'z')
            str[i] -= 32;
    }
}
void main(){
 char sen[150];
 gets(sen);
 strip_white_spaces(sen);
 touppercase(sen);
 int s = strlength(sen);
 printf("%s:%d", sen, s);
}
</code>```

答: isspace(str[i-1]) will read out of bounds for i == 0, which might cause the program to crash if you are lucky. You need to rewrite that function with different logic.

Body:
I'm trying to solve a problem which requires: a sentence that has less than 150 characters as an input and makes that sentence's characters all to uppercase while removing all extra white spaces, then prints the changed sentence and its number of characters to the screen.
For example:
Input: Look            in to the   abyss
Output:LOOK IN TO THE ABYSS:20

 I tested this program on Dev-C++ and it worked just fine but when i submitted it to CodeForces I got runtime error. I hope anyone can help me with this.

( I tried to use scanf("%[^\n]%*c", sen) and fgets(sen, sizeof(sen), stdin) instead of gets(sen) but i still get runtime error. Also, i use a different function strlength instead of strlen since i had another type-related error when submitting that piece of code to CodeForces )
 P/s: Sorry for my bad English

#include <ctype.h>
#include <stdio.h>

int strlength(char* str){
    int i,j = 0;
    for (i=0; str[i]!= '\0';i++)
        ++j;
    return j;
}
void strip_white_spaces(char* str){
    int x,i;
    for (x=i=0; str[i]!='\0';i++){
        if (!isspace(str[i])||((i>0) && (!isspace(str[i-1]))))
            str[x++] = str[i];
    }
    if (isspace(str[x-1]))
        str[x-1]='\0';
    else str[x] ='\0';
}
void touppercase(char* str){
    int i;
    for (i = 0; str[i] != '\0';i++ ){
        if (str[i] >= 'a' && str[i] <= 'z')
            str[i] -= 32;
    }
}
void main(){
 char sen[150];
 gets(sen);
 strip_white_spaces(sen);
 touppercase(sen);
 int s = strlength(sen);
 printf("%s:%d", sen, s);
}


问:
How to determine Daytime or Nighttime from sunrise and sunset timestamps
I am implementing a weather widget in my angular application with the help of open weather api. I have used One call Api where I am getting current weather and upcoming 7 days forecast. Now for the current weather I am getting two different timestamps sunrise and sunset.

How can I determine if the current time is daytime or nighttime using those timestamps. Because based on that I will change icons in my widget.

Current time json Object -

```<code>"current":{
      "dt":1591169581,
      "sunrise":1591140098,
      "sunset":1591188490,
      "temp":35,
      "feels_like":39.04,
      "pressure":1005,
      "humidity":59,
      "dew_point":25.78,
      "uvi":13,
      "clouds":20,
      "visibility":4000,
      "wind_speed":4.1,
      "wind_deg":220,
      "weather":[
         {
            "id":721,
            "main":"Haze",
            "description":"haze",
            "icon":"50d"
         }
      ]
   },
</code>```

答:
var current = {
  "sunrise":1591140098,
  "sunset":1591188490,
}

if (new Date().valueOf() / 1000 < current.sunset) {
  console.log('Day Time');
} else {
  console.log('Night Time');
}```

Body:
I am implementing a weather widget in my angular application with the help of open weather api. I have used One call Api where I am getting current weather and upcoming 7 days forecast. Now for the current weather I am getting two different timestamps sunrise and sunset.

How can I determine if the current time is daytime or nighttime using those timestamps. Because based on that I will change icons in my widget.

Current time json Object -

"current":{
      "dt":1591169581,
      "sunrise":1591140098,
      "sunset":1591188490,
      "temp":35,
      "feels_like":39.04,
      "pressure":1005,
      "humidity":59,
      "dew_point":25.78,
      "uvi":13,
      "clouds":20,
      "visibility":4000,
      "wind_speed":4.1,
      "wind_deg":220,
      "weather":[
         {
            "id":721,
            "main":"Haze",
            "description":"haze",
            "icon":"50d"
         }
      ]
   },


问:
general programming logic
I have a general question - regarding testing of values, I have run into this issue multiple time and I end up with some unsightly long code to accomplish something that logically seems simple.

the issue - I have one or multiple values I want to test against other values....SUCH THAT my code ends up looking like this (conceptually)

```<code>IF (A > B
AND A < C
AND A < D
AND A < E)
THEN print "Yes"
</code>```

LOGICALLY I can express this as IF A > b,c,d,e etc.

If I also need to check other values in that list - you can see that the conditional statement to test against could become significantly larger and messier than the code the condition is intended to yield...

there MUST be a way problematically OR mathematically to express this common instance.

I know each language has 'syntax' specific ways to to this but .. I'll take suggestions and try em.

答:
If you want the test that is in your code, in python at least you can use

```<code>if B<A<min(C,D,E):
    print "Yes"
</code>```

And similarly for the test in your question below the code you can use

```<code>if A>max(B,C,D,E):
    print "Yes"
</code>```

Title: general programming logic

Body:
I have a general question - regarding testing of values, I have run into this issue multiple time and I end up with some unsightly long code to accomplish something that logically seems simple.

the issue - I have one or multiple values I want to test against other values....SUCH THAT my code ends up looking like this (conceptually)

IF (A > B
AND A < C
AND A < D
AND A < E)
THEN print "Yes"

LOGICALLY I can express this as IF A > b,c,d,e etc.

If I also need to check other values in that list - you can see that the conditional statement to test against could become significantly larger and messier than the code the condition is intended to yield...

there MUST be a way problematically OR mathematically to express this common instance.

I know each language has 'syntax' specific ways to to this but .. I'll take suggestions and try em.

Body:
If you want the test that is in your code, in python at least you can use

if B<A<min(C,D,E):
    print "Yes"

And similarly for the test in your question below the code you can use

if A>max(B,C,D,E):
    print "Yes"


问:
How can a numpy array be both F-contguous and C-contiguous at the same time?
I 'm working on the below simple numpy array to understand strides. However I came across an output in its .flags that doesn't make sense to me.

```<code>> print(a)
[[100 200  50 400]
 [ 50   0   0 100]
 [350 100  50 200]]

> a.ravel()
array([100, 200,  50, 400,  50,   0,   0, 100, 350, 100,  50, 200])

> print(a.flags)
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False

> abytes=a.ravel().view(dtype=np.uint8)
> print(abytes)
[100   0   0   0   0   0   0   0 200   0   0   0   0   0   0   0  50   0
   0   0   0   0   0   0 144   1   0   0   0   0   0   0  50   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0 100   0   0   0   0   0   0   0  94   1   0   0   0   0   0   0
 100   0   0   0   0   0   0   0  50   0   0   0   0   0   0   0 200   0
   0   0   0   0   0   0]

> print(abytes.flags)
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False

</code>```

How is abytes both F and C Contiguous ? I also do not understand how such an array operates.

Thanks in advance.

答:
As mentioned in comments, a 1-D array is both F-contiguous and C-contiguous. a.ravel creates such an array. To understand the concept of argument order in np.ravel(), this example might help:

```<code>a = np.arange(6).reshape(2,3)

a
[[0 1 2]
 [3 4 5]]

a.ravel(order='C')
[0 1 2 3 4 5]

a.ravel(order='F')
[0 3 1 4 2 5]
</code>```

As you can see in this example, when order='C', it reads each row and stacks them to make a 1-D array, while, in case of order='F', it reads each column and stacks them to create the 1-D array. Regardless of the order, the output is a 1-D array which is always both C-contiguous and F-contiguous.

Body:
I 'm working on the below simple numpy array to understand strides. However I came across an output in its .flags that doesn't make sense to me.

> print(a)
[[100 200  50 400]
 [ 50   0   0 100]
 [350 100  50 200]]

> a.ravel()
array([100, 200,  50, 400,  50,   0,   0, 100, 350, 100,  50, 200])

> print(a.flags)
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False

> abytes=a.ravel().view(dtype=np.uint8)
> print(abytes)
[100   0   0   0   0   0   0   0 200   0   0   0   0   0   0   0  50   0
   0   0   0   0   0   0 144   1   0   0   0   0   0   0  50   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0 100   0   0   0   0   0   0   0  94   1   0   0   0   0   0   0
 100   0   0   0   0   0   0   0  50   0   0   0   0   0   0   0 200   0
   0   0   0   0   0   0]

> print(abytes.flags)
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False

How is abytes both F and C Contiguous ? I also do not understand how such an array operates.

Thanks in advance.

Body:
As mentioned in comments, a 1-D array is both F-contiguous and C-contiguous. a.ravel creates such an array. To understand the concept of argument order in np.ravel(), this example might help:

a = np.arange(6).reshape(2,3)

a
[[0 1 2]
 [3 4 5]]

a.ravel(order='C')
[0 1 2 3 4 5]

a.ravel(order='F')
[0 3 1 4 2 5]

As you can see in this example, when order='C', it reads each row and stacks them to make a 1-D array, while, in case of order='F', it reads each column and stacks them to create the 1-D array. Regardless of the order, the output is a 1-D array which is always both C-contiguous and F-contiguous.


问:
How to get a flatten dataframe from lists of dictionaries which contain lists?
I'm trying to flat this kind of data structure into a "plain" dataframe.

Raw data is a list of dictionaries, which contain lists.

Data looks like this( reproducible example):

```<code>data = [{'A':[1,2,3,4], 'B':[11,12,13,14]}, {'A':[5,6,7,8], 'B':[15,16,17,18]}]
</code>```

My desidered output should be the following pandas dataframe:

```<code>Out[01]:
   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18
</code>```

How can i achieve this result?
Thanks

答:
You can simply generate each DataFrame and concatenate them all:    </p>

```<code>import pandas as pd

data = [{'A':[1,2,3,4], 'B':[11,12,13,14]}, {'A':[5,6,7,8], 'B':[15,16,17,18]}]

df = pd.concat((pd.DataFrame(elm) for elm in data), ignore_index=True)
print(df)

   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18
</code>```

Body:
I'm trying to flat this kind of data structure into a "plain" dataframe.

Raw data is a list of dictionaries, which contain lists.

Data looks like this( reproducible example):

data = [{'A':[1,2,3,4], 'B':[11,12,13,14]}, {'A':[5,6,7,8], 'B':[15,16,17,18]}]

My desidered output should be the following pandas dataframe:

Out[01]:
   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18

How can i achieve this result?
Thanks

Body:
You can simply generate each DataFrame and concatenate them all:

import pandas as pd

data = [{'A':[1,2,3,4], 'B':[11,12,13,14]}, {'A':[5,6,7,8], 'B':[15,16,17,18]}]

df = pd.concat((pd.DataFrame(elm) for elm in data), ignore_index=True)
print(df)

   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18


问:
const_defined? vs. defined? in Ruby
To test, whether a constant (say: a class) is known at a certain point in the code, I can write for instance:

```<code>if defined? :String
</code>```

or I can write

```<code>if self.class.const_defined? :String
</code>```

Is there a situation where I these two ways of testing would make a difference? Note that I don't ask about the case where I have an explicit receiver, such as MyModule.const_defined? :Something, but only for the case where I want to test whether a certain constant (which in my case happens to be a constant denoting a class) is already defined.

答:
Is there a situation where I these two ways of testing would make a difference?

const_defined? only checks the receiver and its ancestors, but it doesn't take the current module nesting into account:

```<code>module Foo
  ABC = 123

  class Bar
    def self.test
      p defined?(ABC)        #=> "constant"
      p const_defined?(:ABC) #=> false
    end
  end
end
</code>```

In order to do so, you have to traverse Module.nesting:

```<code>module Foo
  ABC = 123

  class Bar
    def self.test
      p defined?(ABC)                                      #=> "constant"
      p Module.nesting.any? { |m| m.const_defined?(:ABC) } #=> true
    end
  end
end
</code>```

Title: const_defined? vs. defined? in Ruby

Body:
To test, whether a constant (say: a class) is known at a certain point in the code, I can write for instance:

if defined? :String

or I can write

if self.class.const_defined? :String

Is there a situation where I these two ways of testing would make a difference? Note that I don't ask about the case where I have an explicit receiver, such as MyModule.const_defined? :Something, but only for the case where I want to test whether a certain constant (which in my case happens to be a constant denoting a class) is already defined.

Body:
Is there a situation where I these two ways of testing would make a difference?

const_defined? only checks the receiver and its ancestors, but it doesn't take the current module nesting into account:

module Foo
  ABC = 123

  class Bar
    def self.test
      p defined?(ABC)        #=> "constant"
      p const_defined?(:ABC) #=> false
    end
  end
end

In order to do so, you have to traverse Module.nesting:

module Foo
  ABC = 123

  class Bar
    def self.test
      p defined?(ABC)                                      #=> "constant"
      p Module.nesting.any? { |m| m.const_defined?(:ABC) } #=> true
    end
  end
end


问:
Index.js Error: UserForm(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null
Hi I am fairly new to react . I am fairly new to react and I am trying add a row in my react app on the click of a button. I followed this link How to add and remove table rows Dynamically in React.js

to do so but I am not able to translate it to my code.

I am getting this error.

Error: UserForm(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

```<code>Module../src/index.js
D:/react_bpms1/src/index.js:7
   4 | import App from './App';
   5 | import * as serviceWorker from './serviceWorker';
   6 |
>  7 | ReactDOM.render(
   8 |   <React.StrictMode>
   9 |     <App />
  10 |   </React.StrictMode>,
View compiled
__webpack_require__
D:/react_bpms1/webpack/bootstrap:784
  781 | };
  782 |
  783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  785 |
  786 | // Flag the module as loaded
  787 | module.l = true;
View compiled
fn
D:/react_bpms1/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
1
http://localhost:3000/static/js/main.chunk.js:2076:18
__webpack_require__
D:/react_bpms1/webpack/bootstrap:784
  781 | };
  782 |
  783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  785 |
  786 | // Flag the module as loaded
  787 | module.l = true;
View compiled
checkDeferredModules
D:/react_bpms1/webpack/bootstrap:45
  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 |  }
  47 | }
  48 |
View compiled
Array.webpackJsonpCallback [as push]
D:/react_bpms1/webpack/bootstrap:32
  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 |
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;
View compiled
(anonymous function)
http://localhost:3000/static/js/main.chunk.js:1:75
</code>```

Here is my code:

My code here: KPIDetails.js Here I am rendering the view in KPI Details.js file.

```<code><MuiThemeProvider>
  <React.Fragment>
    <Grid container>
      <Grid item xs={6} direction="row" alignItems="center">
        <table className="table table-bordered table-hover" id="tab_logic">
          <thead>
            <tr>
              <th className="text-center"> KPI</th>
              <th className="text-center"> UOM</th>
              <th className="text-center"> Base</th>
              <th className="text-center"> Target</th>
              <th className="text-center"> Target Date</th>
            </tr>
          </thead>
          <tbody>
            {this.state.rows.map((item, idx) => (
              <tr id="addr0" key={idx}>
                <td>{idx}</td>
                <td>
                  <input
                    type="text"
                    name="Kpi_Before"
                    value={this.state.rows[idx].Kpi_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />
                </td>
                <td>
                  <input
                    type="text"
                    name="UOM_Before"
                    value={this.state.rows[idx].UOM_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />
                </td>
                <td>
                  <input
                    type="text"
                    name="Base_Before"
                    value={this.state.rows[idx].Base_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />
                </td>
                <td>
                  <input
                    type="text"
                    name="Target_Before"
                    value={this.state.rows[idx].Target_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />
                </td>
                <td>
                  <input
                    type="text"
                    name="Target_Before"
                    value={this.state.rows[idx].dateTime}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <button
          onClick={this.handleRemoveRow}
          className="pull-right btn btn-default"
        >
          Delete Row
        </button>
        <Button
          variant="outlined"
          color="primary"
          onClick={this.handleAddRow}
          size="small"
          style={styles.button}
        >
          +
        </Button>
      </Grid>
    </Grid>
  </React.Fragment>
</MuiThemeProvider>;
</code>```

Here is my code for UserFormjs where I write all the functions:

```<code>export class UserForm extends Component {
  state = {
    step: 1,
    Title: "",
    Details: "",
    What: "",
    Why: "",
    How: "",
    Status: "",
    Cost: "",
    Benefits: "",
    Kpi_Before: "",
    Kpi_After: "",
    Time: "",
    UOM_Before: "",
    Base_Before: "",
    Target_Before: "",
    dateTime: null,
    rows: []
  };

  //1
  handleChangeRows = idx => e => {
    const { Kpi_Before, value } = e.target;
    const rows = [...this.state.rows];
    rows[idx] = {
      [Kpi_Before]: value
    };
    this.setState({
      rows
    });
  };

  //2
  handleAddRow = () => {
    const item = {
      KPI_Before: "",
      UOM_Before: "",
      Base_Before: "",
      Target_Before: "",
      dateTime: ""
    };
    this.setState({
      rows: [...this.state.rows, item]
    });
  };

  //3
  handleRemoveRow = () => {
    this.setState({
      rows: this.state.rows.slice(0, -1)
    });
  };
}
</code>```

This is index.js:

```<code>import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

serviceWorker.unregister();
</code>```

I don't understand this error. Also is there another way to do this? Achieve creating a table row on the click of a button?

答: Removed a constructor which was causing the problem and it solved the issue</p>

Body:
Hi I am fairly new to react . I am fairly new to react and I am trying add a row in my react app on the click of a button. I followed this link How to add and remove table rows Dynamically in React.js

to do so but I am not able to translate it to my code.

I am getting this error.

Error: UserForm(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

Module../src/index.js
D:/react_bpms1/src/index.js:7
   4 | import App from './App';
   5 | import * as serviceWorker from './serviceWorker';
   6 |
>  7 | ReactDOM.render(
   8 |   <React.StrictMode>
   9 |     <App />
  10 |   </React.StrictMode>,
View compiled
__webpack_require__
D:/react_bpms1/webpack/bootstrap:784
  781 | };
  782 |
  783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  785 |
  786 | // Flag the module as loaded
  787 | module.l = true;
View compiled
fn
D:/react_bpms1/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
1
http://localhost:3000/static/js/main.chunk.js:2076:18
__webpack_require__
D:/react_bpms1/webpack/bootstrap:784
  781 | };
  782 |
  783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  785 |
  786 | // Flag the module as loaded
  787 | module.l = true;
View compiled
checkDeferredModules
D:/react_bpms1/webpack/bootstrap:45
  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 |  }
  47 | }
  48 |
View compiled
Array.webpackJsonpCallback [as push]
D:/react_bpms1/webpack/bootstrap:32
  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 |
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;
View compiled
(anonymous function)
http://localhost:3000/static/js/main.chunk.js:1:75

Here is my code:

My code here: KPIDetails.js Here I am rendering the view in KPI Details.js file.

<MuiThemeProvider>
  <React.Fragment>
    <Grid container>
      <Grid item xs={6} direction="row" alignItems="center">

               KPI
               UOM
               Base
               Target
               Target Date

            {this.state.rows.map((item, idx) => (

                {idx}

                  <input
                    type="text"
                    name="Kpi_Before"
                    value={this.state.rows[idx].Kpi_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />

                  <input
                    type="text"
                    name="UOM_Before"
                    value={this.state.rows[idx].UOM_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />

                  <input
                    type="text"
                    name="Base_Before"
                    value={this.state.rows[idx].Base_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />

                  <input
                    type="text"
                    name="Target_Before"
                    value={this.state.rows[idx].Target_Before}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />

                  <input
                    type="text"
                    name="Target_Before"
                    value={this.state.rows[idx].dateTime}
                    onChange={this.handleChangeRows(idx)}
                    className="form-control"
                  />

            ))}

        <button
          onClick={this.handleRemoveRow}
          className="pull-right btn btn-default"
        >
          Delete Row
        </button>
        <Button
          variant="outlined"
          color="primary"
          onClick={this.handleAddRow}
          size="small"
          style={styles.button}
        >
          +
        </Button>
      </Grid>
    </Grid>
  </React.Fragment>
</MuiThemeProvider>;

Here is my code for UserFormjs where I write all the functions:

export class UserForm extends Component {
  state = {
    step: 1,
    Title: "",
    Details: "",
    What: "",
    Why: "",
    How: "",
    Status: "",
    Cost: "",
    Benefits: "",
    Kpi_Before: "",
    Kpi_After: "",
    Time: "",
    UOM_Before: "",
    Base_Before: "",
    Target_Before: "",
    dateTime: null,
    rows: []
  };

  //1
  handleChangeRows = idx => e => {
    const { Kpi_Before, value } = e.target;
    const rows = [...this.state.rows];
    rows[idx] = {
      [Kpi_Before]: value
    };
    this.setState({
      rows
    });
  };

  //2
  handleAddRow = () => {
    const item = {
      KPI_Before: "",
      UOM_Before: "",
      Base_Before: "",
      Target_Before: "",
      dateTime: ""
    };
    this.setState({
      rows: [...this.state.rows, item]
    });
  };

  //3
  handleRemoveRow = () => {
    this.setState({
      rows: this.state.rows.slice(0, -1)
    });
  };
}

This is index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

serviceWorker.unregister();

I don't understand this error. Also is there another way to do this? Achieve creating a table row on the click of a button?


问:
Convert two NSarray to NSString
Hi so I have two NS Arrays in my view controller, with both the same number of count. btw this is for submitting for upload.

```<code>barcodeItems = [[NSMutableArray alloc] init];

barcodeItemsQuantity = [[NSMutableArray alloc] init];
</code>```

Once the arrays have been populated this method will be called,

```<code>-(void) performUploadOperation {
parameters = [NSMutableDictionary dictionary];

// Add barcodes and quantity
if (barcodeItems != nil || barcodeItemsQuantity != nil) {

    [parameters setValue:barcodeItems forKey:@"upc"];
    [parameters setValue:barcodeItemsQuantity forKey:@"upcQuantity"];

   }
}
</code>```

Once this is submitted another method will be called to convert it to nsstring

```<code>NSArray* upc = [parameters objectForKey:@"upc"];
NSArray* upcQuantity = [parameters objectForKey:@"upcQuantity"];

NSString* sample = [NSString stringWithFormat:@"{\"upc_list\" : { \"%@\": %@}}", upc, upcQuantity];
NSLog(@"%@", sample);
</code>```

The result is this

```<code>{"upc_list" : { "(
    76239878,
    0827755090991,
    76239878
)": (
    12,
    23,
    32
)}}
</code>```

and what I want to achieve is something like this. both arrays have the same count always

```<code>{"upc_list" : { "
   (
    "76239878" : 12,
    "0827755090991" : 23,
    "76239878" : 32
   )
 }}
</code>```

答:
@jordanzee: You can use the below code to get your expected result.</p>

```<code>NSArray *upc = [parameters objectForKey:@"upc"];
NSArray *upcQuantity = [parameters objectForKey:@"upcQuantity"];

NSMutableDictionary *aMutDict = [NSMutableDictionary dictionary];
for(NSInteger aIndex = 0; aIndex < upc.count; aIndex++){
   [aMutDict setValue:upcQuantity[aIndex] forKey:upc[aIndex]];
}

NSString *sample = [NSString stringWithFormat:@"{\"upc_list\" : %@}", aMutDict];
NSLog(@"%@", sample);
</code>```

Title: Convert two NSarray to NSString

Body:
Hi so I have two NS Arrays in my view controller, with both the same number of count. btw this is for submitting for upload.

barcodeItems = [[NSMutableArray alloc] init];

barcodeItemsQuantity = [[NSMutableArray alloc] init];

Once the arrays have been populated this method will be called,

-(void) performUploadOperation {
parameters = [NSMutableDictionary dictionary];

// Add barcodes and quantity
if (barcodeItems != nil || barcodeItemsQuantity != nil) {

    [parameters setValue:barcodeItems forKey:@"upc"];
    [parameters setValue:barcodeItemsQuantity forKey:@"upcQuantity"];

   }
}

Once this is submitted another method will be called to convert it to nsstring

NSArray* upc = [parameters objectForKey:@"upc"];
NSArray* upcQuantity = [parameters objectForKey:@"upcQuantity"];

NSString* sample = [NSString stringWithFormat:@"{\"upc_list\" : { \"%@\": %@}}", upc, upcQuantity];
NSLog(@"%@", sample);

The result is this

{"upc_list" : { "(
    76239878,
    0827755090991,
    76239878
)": (
    12,
    23,
    32
)}}

and what I want to achieve is something like this. both arrays have the same count always

{"upc_list" : { "
   (
    "76239878" : 12,
    "0827755090991" : 23,
    "76239878" : 32
   )
 }}

Body:
@jordanzee: You can use the below code to get your expected result.

NSArray *upc = [parameters objectForKey:@"upc"];
NSArray *upcQuantity = [parameters objectForKey:@"upcQuantity"];

NSMutableDictionary *aMutDict = [NSMutableDictionary dictionary];
for(NSInteger aIndex = 0; aIndex < upc.count; aIndex++){
   [aMutDict setValue:upcQuantity[aIndex] forKey:upc[aIndex]];
}

NSString *sample = [NSString stringWithFormat:@"{\"upc_list\" : %@}", aMutDict];
NSLog(@"%@", sample);


问:
How to constantly check expiration time in reactjs?
How to constantly check if token from sessionStorage has expired or not.

I have got the session expiration time from using the package jsonwebtoken .

and calculated the current time using this new Date().getTime() / 1000;

How to check this constantly if session has expired or not. How to run a function every time.

Your help is much appreciated.

Thanks in advance.

答:
You can declare a interval ref that will check at each amount of time checkHereForToken()

```<code>  let interval = useRef(null);
  useEffect(() => {
     interval.current = setInterval(checkHereForToken, 1000);
     return () => clearInterval(interval.current);
  }, [])
</code>```

Body:
You can declare a interval ref that will check at each amount of time checkHereForToken()

  let interval = useRef(null);
  useEffect(() => {
     interval.current = setInterval(checkHereForToken, 1000);
     return () => clearInterval(interval.current);
  }, [])


问:
Background image is not displayed in Firefox
An image set as the background of a DIV is displayed in IE, but not in Firefox.

CSS example:

```<code>div.something {
background:transparent url(../images/table_column.jpg) repeat scroll 0 0;
}
</code>```

(The issue is described in many places but haven't seen any conclusive explanation or fix.)

答: In my case it caused by "Strict" mode in FF Privacy & Security settings. After I have changed to "Standard" all background images had become visible.

ContentLicense: CC BY-SA 2.5

Body:
An image set as the background of a DIV is displayed in IE, but not in Firefox.

CSS example:

div.something {
background:transparent url(../images/table_column.jpg) repeat scroll 0 0;
}

(The issue is described in many places but haven't seen any conclusive explanation or fix.)


答:
Try the following code:

import pandas as pd
data = [{'A':[1,2,3,4], 'B':[11,12,13,14]}, {'A':[5,6,7,8], 'B':[15,16,17,18]}]

df = pd.DataFrame(data).apply(pd.Series.explode).reset_index(drop=True)

print(df)
```

Title: How to get a flatten dataframe from lists of dictionaries which contain lists?


问:
Copy images from one folder to another in digitalocean spaces
I am working with digital ocean spaces and I have uploaded the images on it in a temporary folder. Now I want to move that image from temporary folder to permanent folder. I have searched the things from all over but got nothing much satisfying. Is it possible to do so ?
and if yes please help me with the javascript code.

First I generated the signed url and with the help of that signed url I uploaded the image on digitalocean spaces. Following is the code for generating signed url and uploading images.

const getSignedUrl = async () => {
    const body = {
        fileName: 'temp/' + file.name,
        fileType: file.type,
    }

    const response = await fetch(`${API_URL}/presigned_url`, {
        method: 'POST',
        body: JSON.stringify(body),
        headers: { 'Content-Type': 'application/json' }
    })
    const { signedUrl } = await response.json()

    return signedUrl
}

const uploadFile = async signedUrl => {
    const res = await fetch(signedUrl, {
        method: 'PUT',
        body: file,
        headers: {
            'Content-Type': file.type,
            'x-amz-acl': 'public-read',
        }
    })
    return res
}
```

please help me how can I move my image from temporary folder to permanent folder.

答:
So finally after searching I got the answer,
From the front end side I call an API to copy my image

const copyFile = async (file) => {
    try {
        const body = {
            fileName: file.name
        }
        const res = await fetch(`${API_URL}/copy_file`, {
            method: 'PUT',
            body: JSON.stringify(body),
            headers: { 'Content-Type': 'application/json' }
        })
        return res
    } catch (error) {
        console.log(error);
    }
}
```

<p>And in the backend side the API I made is </p>

```app.put('/copy_file', (req, res) => {
    const fileName = req.body.fileName
    console.log("body", fileName);
    const params = {
        Bucket: config.spaces.spaceName,
        CopySource: `/bucketName/temp/${fileName}`,
        Key: `original/${fileName}`,
    }
    spaces.copyObject(params, function (err, data) {
        if (err) {
            console.log("Error", err)
            // console.log(err, err.stack); // an error occurred
        } else {
            res.json({ data })
        }
    });
});
```

This will copy you image in original folder

Body:
I am working with digital ocean spaces and I have uploaded the images on it in a temporary folder. Now I want to move that image from temporary folder to permanent folder. I have searched the things from all over but got nothing much satisfying. Is it possible to do so ?
and if yes please help me with the javascript code.

First I generated the signed url and with the help of that signed url I uploaded the image on digitalocean spaces. Following is the code for generating signed url and uploading images.

const getSignedUrl = async () => {
    const body = {
        fileName: 'temp/' + file.name,
        fileType: file.type,
    }

    const response = await fetch(`${API_URL}/presigned_url`, {
        method: 'POST',
        body: JSON.stringify(body),
        headers: { 'Content-Type': 'application/json' }
    })
    const { signedUrl } = await response.json()

    return signedUrl
}

const uploadFile = async signedUrl => {
    const res = await fetch(signedUrl, {
        method: 'PUT',
        body: file,
        headers: {
            'Content-Type': file.type,
            'x-amz-acl': 'public-read',
        }
    })
    return res
}

please help me how can I move my image from temporary folder to permanent folder.

Body:
So finally after searching I got the answer,
From the front end side I call an API to copy my image

const copyFile = async (file) => {
    try {
        const body = {
            fileName: file.name
        }
        const res = await fetch(`${API_URL}/copy_file`, {
            method: 'PUT',
            body: JSON.stringify(body),
            headers: { 'Content-Type': 'application/json' }
        })
        return res
    } catch (error) {
        console.log(error);
    }
}

And in the backend side the API I made is

app.put('/copy_file', (req, res) => {
    const fileName = req.body.fileName
    console.log("body", fileName);
    const params = {
        Bucket: config.spaces.spaceName,
        CopySource: `/bucketName/temp/${fileName}`,
        Key: `original/${fileName}`,
    }
    spaces.copyObject(params, function (err, data) {
        if (err) {
            console.log("Error", err)
            // console.log(err, err.stack); // an error occurred
        } else {
            res.json({ data })
        }
    });
});

This will copy you image in original folder