问:
IAM Permissions Errors When Using boto3 for AWS Comprehend
I'm playing around with the command line to run some sentiment analysis through aws and am running into some IAM issues. When running the "detect_dominant_language" function, I'm hitting NotAuthorizedExceptions despite having the policy in place to allow for all comprehend functions. The policy for the account is:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "comprehend:*",
                "s3:ListAllMyBuckets",
                "s3:ListBucket",
                "s3:GetBucketLocation",
                "iam:ListRoles",
                "iam:GetRole"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}
</code>```

Any ideas of where I might be going wrong with this? I've triple-checked my access key to make sure that I'm referring to the correct account. When I check the policy, it's there so I'm a little bit at a loss as to the disconnect. S3 seems to be working fine as well.

Steps already taken:

Resetting access key/secret access key.

Creating iam policy which explicitly refers to the needed functionality and attaching it to the "Admin" user.

Calling this method from the CLI (get the same error).

Below, I've included additional information that may be helpful...

Code to check iam policies:

```<code>iam = boto3.client('iam',
                   aws_access_key_id = '*********************',
                   aws_secret_access_key = '*************************************')

iam.list_attached_user_policies(UserName="Admin")
</code>```

Output:

```<code>{'AttachedPolicies': [{'PolicyName': 'ComprehendFullAccess',
   'PolicyArn': 'arn:aws:iam::aws:policy/ComprehendFullAccess'},
  {'PolicyName': 'AdministratorAccess',
   'PolicyArn': 'arn:aws:iam::aws:policy/AdministratorAccess'},
  {'PolicyName': 'Comprehend-Limitied',
   'PolicyArn': 'arn:aws:iam::401311205158:policy/Comprehend-Limitied'}],
 'IsTruncated': False,
 'ResponseMetadata': {'RequestId': '9094d8ff-1730-44b8-af0f-9222a63b32e9',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': '9094d8ff-1730-44b8-af0f-9222a63b32e9',
   'content-type': 'text/xml',
   'content-length': '871',
   'date': 'Thu, 20 Jan 2022 21:48:11 GMT'},
  'RetryAttempts': 0}}
</code>```

Code to trigger error:

```<code>comprehend = boto3.client('comprehend',
                   aws_access_key_id = '*********************',
                   aws_secret_access_key = '********************************')

test_language_string = "This is a test string. I'm hoping that AWS Comprehend can interprete this as english..."

comprehend.detect_dominant_language(Text=test_language_string)
</code>```

Output:

```<code>ClientError: An error occurred (NotAuthorizedException) when calling the DetectDominantLanguage operation: Your account is not authorized to make this call.
</code>```

答: UPDATE: Thanks for all the feedback y'all! It turns out us-west-1 doesn't support comprehend. Switching to a different availability zone did the trick, so I would recommend anyone with similar problems try different zones before digging too deep into permissions//access keys.</p>

Body:
I'm playing around with the command line to run some sentiment analysis through aws and am running into some IAM issues. When running the "detect_dominant_language" function, I'm hitting NotAuthorizedExceptions despite having the policy in place to allow for all comprehend functions. The policy for the account is:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "comprehend:*",
                "s3:ListAllMyBuckets",
                "s3:ListBucket",
                "s3:GetBucketLocation",
                "iam:ListRoles",
                "iam:GetRole"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

Any ideas of where I might be going wrong with this? I've triple-checked my access key to make sure that I'm referring to the correct account. When I check the policy, it's there so I'm a little bit at a loss as to the disconnect. S3 seems to be working fine as well.

Steps already taken:

Resetting access key/secret access key.

Creating iam policy which explicitly refers to the needed functionality and attaching it to the "Admin" user.

Calling this method from the CLI (get the same error).

Below, I've included additional information that may be helpful...

Code to check iam policies:

iam = boto3.client('iam',
                   aws_access_key_id = '*********************',
                   aws_secret_access_key = '*************************************')

iam.list_attached_user_policies(UserName="Admin")

Output:

{'AttachedPolicies': [{'PolicyName': 'ComprehendFullAccess',
   'PolicyArn': 'arn:aws:iam::aws:policy/ComprehendFullAccess'},
  {'PolicyName': 'AdministratorAccess',
   'PolicyArn': 'arn:aws:iam::aws:policy/AdministratorAccess'},
  {'PolicyName': 'Comprehend-Limitied',
   'PolicyArn': 'arn:aws:iam::401311205158:policy/Comprehend-Limitied'}],
 'IsTruncated': False,
 'ResponseMetadata': {'RequestId': '9094d8ff-1730-44b8-af0f-9222a63b32e9',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': '9094d8ff-1730-44b8-af0f-9222a63b32e9',
   'content-type': 'text/xml',
   'content-length': '871',
   'date': 'Thu, 20 Jan 2022 21:48:11 GMT'},
  'RetryAttempts': 0}}

Code to trigger error:

comprehend = boto3.client('comprehend',
                   aws_access_key_id = '*********************',
                   aws_secret_access_key = '********************************')

test_language_string = "This is a test string. I'm hoping that AWS Comprehend can interprete this as english..."

comprehend.detect_dominant_language(Text=test_language_string)

Output:

ClientError: An error occurred (NotAuthorizedException) when calling the DetectDominantLanguage operation: Your account is not authorized to make this call.


来源: stackexchange

问:
Entity Framework & MVC Models
Our team is currently developing a web application, in that we have a class library with Entity Framework .edmx added and have generated the POCO classes.

Our Web Application is based on MVC, we have defined our classes in models with the same name and attributes (copy paste of the POCO classes from the .edmx). The .edmx class library is refrenced to MVC web application.

The Views are strongly typed of MVC Model classes. We have used MVC Models for Display, StringLength & Required.

In our controller when there is a CRUD operation we are accepting the POCO Classes Type such as

```<code>     public ActionResult Create(EFModels.User user)    {    }
</code>```

EFModels.User is a class from the .edmx (POCO generated class) and the MVC View is strongly typed to the model which is MvcWebApplication.Models.User.

Question is how are we getting data from the MvcWebApplication.Models.User (from Model) to EFModels.User (EF class) in the ActionResult Create ??

I am able to get the data, I know it is coz of the same property name. I tried changing the class name but still it works, but if we change the property name it does not work. I cannot understand the logic behind it.

Initially we never knew it didn`t work and we were using AutoMapper to convert the Model Class to Edmx POCO class.

Any ideas, Thanks.

The question is how are we getting the values of the Model Class to the EF class with any mapping. I don`t need to use AutoMapper, without using that I am getting the values.

Have a look at the code, hope that explains better...

//POCO CLASS

```<code>namespace EFModels
{
    using System;
    using System.Collections.Generic;

    public partial class User
    {
        public int Id { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
    }
}
</code>```

//MVC Model Class

```<code>namespace MvcWebSamp.Models
{
    public class User
    {
        public int Id { get; set; }

        [Display(ResourceType = typeof(BasicTags), Name = "Type")]
        [StringLength(15, ErrorMessageResourceName = "TypeLength", ErrorMessageResourceType = typeof(BasicTags))]
        [Required(ErrorMessageResourceName = "TypeRequired", ErrorMessageResourceType = typeof(BasicTags))]
        public string TypeName { get; set; }
        public string Name { get; set; }

        public Address Address { get; set; }
    }
}
</code>```

//MVC VIEW PAGE

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcWebSamp.Models.User>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    User
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>User</h2>
  <% using (Html.BeginForm("Create", "User", FormMethod.Post))
       {
    %>
     <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>User</legend>
        <div class="editor-field">
            <%: Html.LabelFor(model => model.TypeName) %>
            <%: Html.EditorFor(model => model.TypeName)%>
            <%: Html.ValidationMessageFor(model => model.TypeName)%>
        </div>
        <div class="editor-field">
            <%: Html.LabelFor(model => model.Name) %>
            <%: Html.EditorFor(model => model.Name)%>
             <%: Html.EditorFor(model => model.Address.street)%>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
    <% } %>
</asp:Content>
</code>```

//Controller Method

```<code> public ActionResult Create(EFModels.User user)
    {
        Model1Container con = new Model1Container();
        con.Users.Add(user);
        con.SaveChanges();
        return View("User");
    }
</code>```

When I hit the Create Button, I am posting data of the type MvcWebSamp.Models.User and in the Create Action I am able to get the data of the type EFModels.User user without using any AutoMapper. I want to know how this works???

答:
You should be using your view model as the argument type for your create method:

```<code>[HttpPost]
public ActionResult Create(UserViewModel model)
{
    if (ModelState.IsValid)
    {
        int id = UserService.CreateFromViewModel(model);
        return RedirectToAction("View", new { id });
    }

    return View(model);
}
</code>```

You controller should be designed to create and accept view models, and it passes those to an appropriate service which interacts with your data layer to create your domain model. This keeps your controller action quite thin.

You can use something like AutoMapper in your service to easily map between your view model and your domain model:

```<code>var user = Mapper.Map<UserViewModel, User>(model);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Entity Framework & MVC Models

Body:
Our team is currently developing a web application, in that we have a class library with Entity Framework .edmx added and have generated the POCO classes.

Our Web Application is based on MVC, we have defined our classes in models with the same name and attributes (copy paste of the POCO classes from the .edmx). The .edmx class library is refrenced to MVC web application.

The Views are strongly typed of MVC Model classes. We have used MVC Models for Display, StringLength & Required.

In our controller when there is a CRUD operation we are accepting the POCO Classes Type such as

     public ActionResult Create(EFModels.User user)    {    }

EFModels.User is a class from the .edmx (POCO generated class) and the MVC View is strongly typed to the model which is MvcWebApplication.Models.User.

Question is how are we getting data from the MvcWebApplication.Models.User (from Model) to EFModels.User (EF class) in the ActionResult Create ??

I am able to get the data, I know it is coz of the same property name. I tried changing the class name but still it works, but if we change the property name it does not work. I cannot understand the logic behind it.

Initially we never knew it didn`t work and we were using AutoMapper to convert the Model Class to Edmx POCO class.

Any ideas, Thanks.

The question is how are we getting the values of the Model Class to the EF class with any mapping. I don`t need to use AutoMapper, without using that I am getting the values.

Have a look at the code, hope that explains better...

//POCO CLASS

namespace EFModels
{
    using System;
    using System.Collections.Generic;

    public partial class User
    {
        public int Id { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
    }
}

//MVC Model Class

namespace MvcWebSamp.Models
{
    public class User
    {
        public int Id { get; set; }

        [Display(ResourceType = typeof(BasicTags), Name = "Type")]
        [StringLength(15, ErrorMessageResourceName = "TypeLength", ErrorMessageResourceType = typeof(BasicTags))]
        [Required(ErrorMessageResourceName = "TypeRequired", ErrorMessageResourceType = typeof(BasicTags))]
        public string TypeName { get; set; }
        public string Name { get; set; }

        public Address Address { get; set; }
    }
}

//MVC VIEW PAGE

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcWebSamp.Models.User>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    User
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

User

  <% using (Html.BeginForm("Create", "User", FormMethod.Post))
       {
    %>
     <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>User</legend>

            <%: Html.LabelFor(model => model.TypeName) %>
            <%: Html.EditorFor(model => model.TypeName)%>
            <%: Html.ValidationMessageFor(model => model.TypeName)%>

            <%: Html.LabelFor(model => model.Name) %>
            <%: Html.EditorFor(model => model.Name)%>
             <%: Html.EditorFor(model => model.Address.street)%>

            <input type="submit" value="Create" />

    </fieldset>
    <% } %>
</asp:Content>

//Controller Method

 public ActionResult Create(EFModels.User user)
    {
        Model1Container con = new Model1Container();
        con.Users.Add(user);
        con.SaveChanges();
        return View("User");
    }

When I hit the Create Button, I am posting data of the type MvcWebSamp.Models.User and in the Create Action I am able to get the data of the type EFModels.User user without using any AutoMapper. I want to know how this works???

Body:
You should be using your view model as the argument type for your create method:

[HttpPost]
public ActionResult Create(UserViewModel model)
{
    if (ModelState.IsValid)
    {
        int id = UserService.CreateFromViewModel(model);
        return RedirectToAction("View", new { id });
    }

    return View(model);
}

You controller should be designed to create and accept view models, and it passes those to an appropriate service which interacts with your data layer to create your domain model. This keeps your controller action quite thin.

You can use something like AutoMapper in your service to easily map between your view model and your domain model:

var user = Mapper.Map<UserViewModel, User>(model);


问:
Ruby: BUILD FAILED (macOS 11.2 using ruby-build 20210119) Mac Big Sur
I looked at this Ruby installation (2.2.2) fails in macOS Big Sur

My macOS is Big Sur and the version I have is 11.2 and it was the closest I could find to the issue I'm having with my OS, I followed what I could by trying

```<code>CFLAGS="-Wno-error=implicit-function-declaration" rbenv install 2.5.3
</code>```

and also

```<code>RUBY_CFLAGS=-DUSE_FFI_CLOSURE_ALLOC rbenv install 2.5.3
</code>```

This is the output in my Terminal:

```<code>Downloading openssl-1.1.1i.tar.gz...
-> https://dqw8nmjcqpjn7.cloudfront.net/e8be6a35fe41d10603c3cc635e93289ed00bf34b79671a3a4de64fcee00d5242
Installing openssl-1.1.1i...
Installed openssl-1.1.1i to /Users/richard/.rbenv/versions/2.5.3

Downloading ruby-2.5.3.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.3.tar.bz2
Installing ruby-2.5.3...

WARNING: ruby-2.5.3 is nearing its end of life.
It only receives critical security updates, no bug fixes.

ruby-build: using readline from homebrew
/opt/homebrew/bin/ruby-build: line 1121: 31528 Killed: 9               "$RUBY_BIN" -e '
    manager = ARGV[0]
    packages = {
      "apt-get" => Hash.new {|h,k| "lib#{k}-dev" }.update(
        "openssl" => "libssl-dev",
        "zlib" => "zlib1g-dev"
      ),
      "yum" => Hash.new {|h,k| "#{k}-devel" }.update(
        "yaml" => "libyaml-devel"
      )
    }

    failed = %w[openssl readline zlib yaml].reject do |lib|
      begin
        require lib
      rescue LoadError
        $stderr.puts "The Ruby #{lib} extension was not compiled."
      end
    end

    if failed.size > 0
      $stderr.puts "ERROR: Ruby install aborted due to missing extensions"
      $stderr.print "Try running `%s install -y %s` to fetch missing dependencies.\n\n" % [
        manager,
        failed.map { |lib| packages.fetch(manager)[lib] }.join(" ")
      ] unless manager.empty?
      $stderr.puts "Configure options used:"
      require "rbconfig"; require "shellwords"
      RbConfig::CONFIG.fetch("configure_args").shellsplit.each { |arg| $stderr.puts "  #{arg}" }
      exit 1
    end
  ' "$(basename "$(type -p yum apt-get | head -1)")" 1>&4 2>&1

BUILD FAILED (macOS 11.2 using ruby-build 20210119)

Inspect or clean up the working tree at /var/folders/rn/c7nmr3x12gg5r8qwsr4ty8hh0000gn/T/ruby-build.20210209143521.94730.xfFT9O
Results logged to /var/folders/rn/c7nmr3x12gg5r8qwsr4ty8hh0000gn/T/ruby-build.20210209143521.94730.log

Last 10 log lines:
installing bundled gems:            /Users/richard/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0 (build_info, cache, doc, extensions, gems, specifications)
                                    power_assert 1.1.1
                                    net-telnet 0.1.1
                                    did_you_mean 1.2.0
                                    xmlrpc 0.3.0
                                    rake 12.3.0
                                    minitest 5.10.3
                                    test-unit 3.2.7
installing rdoc:                    /Users/richard/.rbenv/versions/2.5.3/share/ri/2.5.0/system
installing capi-docs:               /Users/richard/.rbenv/versions/2.5.3/share/doc/ruby
</code>```

I get this error for both commands mentioned above and both give this same output.
The version of Ruby also doesn't seem to matter, I've tried 3.0.0 as well and get the same results.

Additionally this is the original output when I try to just install ruby with rbenv install

```<code>Downloading openssl-1.1.1i.tar.gz...
-> https://dqw8nmjcqpjn7.cloudfront.net/e8be6a35fe41d10603c3cc635e93289ed00bf34b79671a3a4de64fcee00d5242
Installing openssl-1.1.1i...
Installed openssl-1.1.1i to /Users/richard/.rbenv/versions/2.5.3
Downloading ruby-2.5.3.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.3.tar.bz2
Installing ruby-2.5.3...
WARNING: ruby-2.5.3 is nearing its end of life.
It only receives critical security updates, no bug fixes.
ruby-build: using readline from homebrew
BUILD FAILED (macOS 11.2 using ruby-build 20210119)
Inspect or clean up the working tree at /var/folders/rn/c7nmr3x12gg5r8qwsr4ty8hh0000gn/T/ruby-build.20210209143107.60561.YqaRpk
Results logged to /var/folders/rn/c7nmr3x12gg5r8qwsr4ty8hh0000gn/T/ruby-build.20210209143107.60561.log
Last 10 log lines:
compiling ../.././ext/psych/yaml/reader.c
compiling ../.././ext/psych/yaml/emitter.c
compiling ../.././ext/psych/yaml/parser.c
linking shared-object json/ext/generator.bundle
5 warnings generated.
linking shared-object date_core.bundle
linking shared-object zlib.bundle
1 warning generated.
linking shared-object psych.bundle
make: *** [build-ext] Error 2
</code>```

xcode-select version is 2384.

Homebrew version is 3.0.0 and brew doctor say's I'm ready to brew.

My .zshrc file also contains this line eval "$(rbenv init -)"

At this point I'm not sure where else to turn
If there is any specifics you want to see in the log file let me know where from, the log file is too big to share here. Why is this happening and how can I fix this? ♂

答:
While installing rbenv, I faced the same issue on MacOS Monterey 12.2 (M1 Pro chip).
This solution worked for me-

Instead of running this-
rbenv install 2.5.3

run this-
RUBY_CFLAGS="-Wno-error=implicit-function-declaration" rbenv install 2.5.3

ContentLicense: CC BY-SA 4.0

Body:
I looked at this Ruby installation (2.2.2) fails in macOS Big Sur

My macOS is Big Sur and the version I have is 11.2 and it was the closest I could find to the issue I'm having with my OS, I followed what I could by trying

CFLAGS="-Wno-error=implicit-function-declaration" rbenv install 2.5.3

and also

RUBY_CFLAGS=-DUSE_FFI_CLOSURE_ALLOC rbenv install 2.5.3

This is the output in my Terminal:

Downloading openssl-1.1.1i.tar.gz...
-> https://dqw8nmjcqpjn7.cloudfront.net/e8be6a35fe41d10603c3cc635e93289ed00bf34b79671a3a4de64fcee00d5242
Installing openssl-1.1.1i...
Installed openssl-1.1.1i to /Users/richard/.rbenv/versions/2.5.3

Downloading ruby-2.5.3.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.3.tar.bz2
Installing ruby-2.5.3...

WARNING: ruby-2.5.3 is nearing its end of life.
It only receives critical security updates, no bug fixes.

ruby-build: using readline from homebrew
/opt/homebrew/bin/ruby-build: line 1121: 31528 Killed: 9               "$RUBY_BIN" -e '
    manager = ARGV[0]
    packages = {
      "apt-get" => Hash.new {|h,k| "lib#{k}-dev" }.update(
        "openssl" => "libssl-dev",
        "zlib" => "zlib1g-dev"
      ),
      "yum" => Hash.new {|h,k| "#{k}-devel" }.update(
        "yaml" => "libyaml-devel"
      )
    }

    failed = %w[openssl readline zlib yaml].reject do |lib|
      begin
        require lib
      rescue LoadError
        $stderr.puts "The Ruby #{lib} extension was not compiled."
      end
    end

    if failed.size > 0
      $stderr.puts "ERROR: Ruby install aborted due to missing extensions"
      $stderr.print "Try running `%s install -y %s` to fetch missing dependencies.\n\n" % [
        manager,
        failed.map { |lib| packages.fetch(manager)[lib] }.join(" ")
      ] unless manager.empty?
      $stderr.puts "Configure options used:"
      require "rbconfig"; require "shellwords"
      RbConfig::CONFIG.fetch("configure_args").shellsplit.each { |arg| $stderr.puts "  #{arg}" }
      exit 1
    end
  ' "$(basename "$(type -p yum apt-get | head -1)")" 1>&4 2>&1

BUILD FAILED (macOS 11.2 using ruby-build 20210119)

Inspect or clean up the working tree at /var/folders/rn/c7nmr3x12gg5r8qwsr4ty8hh0000gn/T/ruby-build.20210209143521.94730.xfFT9O
Results logged to /var/folders/rn/c7nmr3x12gg5r8qwsr4ty8hh0000gn/T/ruby-build.20210209143521.94730.log

Last 10 log lines:
installing bundled gems:            /Users/richard/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0 (build_info, cache, doc, extensions, gems, specifications)
                                    power_assert 1.1.1
                                    net-telnet 0.1.1
                                    did_you_mean 1.2.0
                                    xmlrpc 0.3.0
                                    rake 12.3.0
                                    minitest 5.10.3
                                    test-unit 3.2.7
installing rdoc:                    /Users/richard/.rbenv/versions/2.5.3/share/ri/2.5.0/system
installing capi-docs:               /Users/richard/.rbenv/versions/2.5.3/share/doc/ruby

I get this error for both commands mentioned above and both give this same output.
The version of Ruby also doesn't seem to matter, I've tried 3.0.0 as well and get the same results.

Additionally this is the original output when I try to just install ruby with rbenv install

Downloading openssl-1.1.1i.tar.gz...
-> https://dqw8nmjcqpjn7.cloudfront.net/e8be6a35fe41d10603c3cc635e93289ed00bf34b79671a3a4de64fcee00d5242
Installing openssl-1.1.1i...
Installed openssl-1.1.1i to /Users/richard/.rbenv/versions/2.5.3
Downloading ruby-2.5.3.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.3.tar.bz2
Installing ruby-2.5.3...
WARNING: ruby-2.5.3 is nearing its end of life.
It only receives critical security updates, no bug fixes.
ruby-build: using readline from homebrew
BUILD FAILED (macOS 11.2 using ruby-build 20210119)
Inspect or clean up the working tree at /var/folders/rn/c7nmr3x12gg5r8qwsr4ty8hh0000gn/T/ruby-build.20210209143107.60561.YqaRpk
Results logged to /var/folders/rn/c7nmr3x12gg5r8qwsr4ty8hh0000gn/T/ruby-build.20210209143107.60561.log
Last 10 log lines:
compiling ../.././ext/psych/yaml/reader.c
compiling ../.././ext/psych/yaml/emitter.c
compiling ../.././ext/psych/yaml/parser.c
linking shared-object json/ext/generator.bundle
5 warnings generated.
linking shared-object date_core.bundle
linking shared-object zlib.bundle
1 warning generated.
linking shared-object psych.bundle
make: *** [build-ext] Error 2

xcode-select version is 2384.

Homebrew version is 3.0.0 and brew doctor say's I'm ready to brew.

My .zshrc file also contains this line eval "$(rbenv init -)"

At this point I'm not sure where else to turn
If there is any specifics you want to see in the log file let me know where from, the log file is too big to share here. Why is this happening and how can I fix this? ♂


问:
how to use map in react typescript
Currently using a react in typescript.
make a separate file and manage it.
I want to do map work on the `card component

parameter on the map wrong?
definition wrong?
Can I get some advice...

Card.tsx

```<code>import { LIST_DATA, ListData } from './data';

const Card = () => {
return(
  {LIST_DATA.map(({ id, title }: ListData[]) => {
    return <S.InfoTitle key={id}>{title}</S.InfoTitle>;
  })}
)
}
</code>```

data.tsx

```<code>export interface ListData {
  id: number;
  title: string;
}

export const LIST_DATA: ListData[] = [
  {
    id: 0,
    title: 'drawing',
  },
  {
    id: 1,
    title: 'total',
  },
  {
    id: 2,
    title: 'method',
  },
  {
    id: 3,
    title: 'material',
  },
];

</code>```

答:
When you map, each item inside the map as argument is only one item from the original array. In your case you have an array of ListData but when you map each argument is only one of this ListData item type, therefore you have to change ListData[] to ListData as such:

```<code>import { LIST_DATA, ListData } from './data';

const Card = () => {
   return(
     {LIST_DATA.map(({ id, title }: ListData) => {
       return <S.InfoTitle key={id}>{title}</S.InfoTitle>;
     })}
   )
}
</code>```

Otherwise to answer the main question: map in typescript is the same as map in javascript, you just have to ensure you input the right type in order to "secure" your app.

Title: how to use map in react typescript

Body:
Currently using a react in typescript.
make a separate file and manage it.
I want to do map work on the `card component

parameter on the map wrong?
definition wrong?
Can I get some advice...

Card.tsx

import { LIST_DATA, ListData } from './data';

const Card = () => {
return(
  {LIST_DATA.map(({ id, title }: ListData[]) => {
    return <S.InfoTitle key={id}>{title}</S.InfoTitle>;
  })}
)
}

data.tsx

export interface ListData {
  id: number;
  title: string;
}

export const LIST_DATA: ListData[] = [
  {
    id: 0,
    title: 'drawing',
  },
  {
    id: 1,
    title: 'total',
  },
  {
    id: 2,
    title: 'method',
  },
  {
    id: 3,
    title: 'material',
  },
];

Body:
When you map, each item inside the map as argument is only one item from the original array. In your case you have an array of ListData but when you map each argument is only one of this ListData item type, therefore you have to change ListData[] to ListData as such:

import { LIST_DATA, ListData } from './data';

const Card = () => {
   return(
     {LIST_DATA.map(({ id, title }: ListData) => {
       return <S.InfoTitle key={id}>{title}</S.InfoTitle>;
     })}
   )
}

Otherwise to answer the main question: map in typescript is the same as map in javascript, you just have to ensure you input the right type in order to "secure" your app.


问:
ES7 React/Redux/GraphQL/React-Native snippets not working
I'm unable to use ES7 React/Redux/GraphQL/React-Native snippets for some reason even though I have installed the extension required.

答:
Had same problem, check this:

Open your VSCode JSON settings,

"ctrl + shift + P" or "Cmd + Shift + P" => then type "Open Settings (JSON)"

copy your current settings and save somewhere else to use it again,
then clear all JSON settings and save it by "ctrl + s", close VSCode and open it again, check if ES7 snippets works, then go to JSON settings again and paste your previous settings copied before.


问:
Excel row locking from .Net
I am generating an Excel spreadsheet from code.  I am trying to customize the cells using .net code,
and I would like to lock the header row so that it won't allow text to be entered into those cells.

I tries following 2 ways with no success

worksheet.Range("A1", "A1").EntireRow.Locked = True

worksheet.Unprotect()

worksheet.Range("A1","A100").Locked = True

worksheet.Protect()

Is that anything I am missing here?

---CODE---

Public Sub CreatNewExcelWithAppliedRules(ByVal noOfWSheets As List(Of String))

```<code>    Dim misValue As Object = System.Reflection.Missing.Value
    Dim App As New Application
    Dim workbook As Workbook = App.Workbooks.Add()
    Dim worksheet As Worksheet = workbook.Worksheets(1)
    Dim sFile As String = "sample-excel"

    ---READ HEADERS FROM XML
    Dim xmlFile = "E:\ExcelPOC\ExcelValidation\App_Data\Headers.xml"
    Dim fsReadXml As New System.IO.FileStream(xmlFile, System.IO.FileMode.Open)
    dsHeaders.ReadXml(fsReadXml)
    dtHeader = dsHeaders.Tables("Column")

    ---ADD HEADERS LIST TO EXCEL
    FillColumnHeader(worksheet, dtHeader, culture)

    worksheet.Unprotect()
    ---ADD VALIDATION RULES
    For Each worksheet In workbook.Worksheets
        ListValidExcelRule(worksheet)
        DateValidExcelRule(worksheet)
        TextLengthValidExcelRule(worksheet)
        DecimalValidExcelRule(worksheet)
    Next
    worksheet.Range("1:1").Locked = True
    worksheet.Protect()

    ---SAVE THE EXCEL
     sFile = App.GetSaveAsFilename(InitialFilename:=sFile, FileFilter:="xls Files  (*.xls), *.xls")

    If sFile <> "False" Then
        workbook.SaveAs(Filename:=sFile, _
                              FileFormat:=XlFileFormat.xlWorkbookNormal, _
                              Password:="", _
                              WriteResPassword:="", _
                              ReadOnlyRecommended:=False, _
                              CreateBackup:=False)
    Else
        App.DisplayAlerts = False
    End If

    workbook.Close(True, misValue, misValue)
    App.Quit()
    releaseObject(worksheet)
    releaseObject(workbook)
    releaseObject(App)

End Sub
</code>```

答:
A1:A100 is the left-hand column.  A1:IV1 is the top row.  Both of your attempts are close.

Try:

```<code>worksheet.Cells.Locked = False
worksheet.Range("1:1").Locked = True
worksheet.Protect
</code>```

In a new Excel worksheet, all cells are locked by default.  Unless you're unlocking the entire worksheet first, you're better off selecting the cells to unlock rather than the cells to lock.

Title: Excel row locking from .Net

Body:
I am generating an Excel spreadsheet from code.  I am trying to customize the cells using .net code,
and I would like to lock the header row so that it won't allow text to be entered into those cells.

I tries following 2 ways with no success

worksheet.Range("A1", "A1").EntireRow.Locked = True

worksheet.Unprotect()

worksheet.Range("A1","A100").Locked = True

worksheet.Protect()

Is that anything I am missing here?

---CODE---

Public Sub CreatNewExcelWithAppliedRules(ByVal noOfWSheets As List(Of String))

    Dim misValue As Object = System.Reflection.Missing.Value
    Dim App As New Application
    Dim workbook As Workbook = App.Workbooks.Add()
    Dim worksheet As Worksheet = workbook.Worksheets(1)
    Dim sFile As String = "sample-excel"

    ---READ HEADERS FROM XML
    Dim xmlFile = "E:\ExcelPOC\ExcelValidation\App_Data\Headers.xml"
    Dim fsReadXml As New System.IO.FileStream(xmlFile, System.IO.FileMode.Open)
    dsHeaders.ReadXml(fsReadXml)
    dtHeader = dsHeaders.Tables("Column")

    ---ADD HEADERS LIST TO EXCEL
    FillColumnHeader(worksheet, dtHeader, culture)

    worksheet.Unprotect()
    ---ADD VALIDATION RULES
    For Each worksheet In workbook.Worksheets
        ListValidExcelRule(worksheet)
        DateValidExcelRule(worksheet)
        TextLengthValidExcelRule(worksheet)
        DecimalValidExcelRule(worksheet)
    Next
    worksheet.Range("1:1").Locked = True
    worksheet.Protect()

    ---SAVE THE EXCEL
     sFile = App.GetSaveAsFilename(InitialFilename:=sFile, FileFilter:="xls Files  (*.xls), *.xls")

    If sFile <> "False" Then
        workbook.SaveAs(Filename:=sFile, _
                              FileFormat:=XlFileFormat.xlWorkbookNormal, _
                              Password:="", _
                              WriteResPassword:="", _
                              ReadOnlyRecommended:=False, _
                              CreateBackup:=False)
    Else
        App.DisplayAlerts = False
    End If

    workbook.Close(True, misValue, misValue)
    App.Quit()
    releaseObject(worksheet)
    releaseObject(workbook)
    releaseObject(App)

End Sub

Body:
A1:A100 is the left-hand column.  A1:IV1 is the top row.  Both of your attempts are close.

Try:

worksheet.Cells.Locked = False
worksheet.Range("1:1").Locked = True
worksheet.Protect

In a new Excel worksheet, all cells are locked by default.  Unless you're unlocking the entire worksheet first, you're better off selecting the cells to unlock rather than the cells to lock.


问:
Angular Button Click Registering on Both the Button and Div Underneath
Whenever I click on my #dropDown button, it functions as intended and opens the dropdown menu; however, the click also hits the  underneath which is also clickable. I don't want the button click event to also hit the div underneath, as that is not the intended function.

{{post.title}}

{{post.date_of_job}}

Description:

{{post.care_description}}

Start: {{post.start_time}} | End: {{post.end_time}}

                    <button #dropDown (click)="toggleDropdown()" class="dropdownbutton mt-2 relative z-10 block p-2 text-gray-700 bg-white border border-transparent rounded-md dark:text-white focus:border-blue-500 focus:ring-opacity-40 dark:focus:ring-opacity-40 focus:ring-blue-300 dark:focus:ring-blue-400 focus:ring dark:bg-gray-800 focus:outline-none">
                        <svg class="w-5 h-5 text-gray-800 dark:text-white" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                        </svg>
                    </button>

Your Application:
 {{post.applications[0].message}}

```

答:
It's happening because the event are bubbling, both the clicks on the button and the div get registered. We can tell our function to stop further propagation of the current event by using event.stopPropagation()

In your, capture the $event in your function as a parameter HTML

 <button #dropDown (click)="toggleDropdown($event)" class="dropdownbutton mt-2 relative z-10 block p-2 text-gray-700 bg-white border border-transparent rounded-md dark:text-white focus:border-blue-500 focus:ring-opacity-40 dark:focus:ring-opacity-40 focus:ring-blue-300 dark:focus:ring-blue-400 focus:ring dark:bg-gray-800 focus:outline-none">
 <svg class="w-5 h-5 text-gray-800 dark:text-white" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
  </svg>
</button>
```
<p>and then in your <code>.ts</code> component, use that event to stop further bubbling of events, so that the div click won't be called:</p>
<pre class="lang-js prettyprint-override"><code>toggleDropdown($event: Event):void {
  $event.stopPropagation();
}
</code>```

Body:
It's happening because the event are bubbling, both the clicks on the button and the div get registered. We can tell our function to stop further propagation of the current event by using event.stopPropagation()

In your, capture the $event in your function as a parameter HTML

 <button #dropDown (click)="toggleDropdown($event)" class="dropdownbutton mt-2 relative z-10 block p-2 text-gray-700 bg-white border border-transparent rounded-md dark:text-white focus:border-blue-500 focus:ring-opacity-40 dark:focus:ring-opacity-40 focus:ring-blue-300 dark:focus:ring-blue-400 focus:ring dark:bg-gray-800 focus:outline-none">
 <svg class="w-5 h-5 text-gray-800 dark:text-white" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
  </svg>
</button>

and then in your .ts component, use that event to stop further bubbling of events, so that the div click won't be called:

toggleDropdown($event: Event):void {
  $event.stopPropagation();
}


问:
What does "ufunc did not contain a loop with signature matching types" mean?
I have code that I thought was great. I am getting the following error message:

Traceback (most recent call last):
  File "C:\Users\ablev\eclipse-workspace\matrix\matrix.py", line 149, in <module>
    print("Transpose of matrice is:\n" + transpose(subtract())),
numpy.core._exceptions._UFuncNoLoopError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U25'), dtype('int32')) -> None
```
<p>What does this mean?</p>
```def matrix_one():
    print("Enter your first 3x3 matrix: ")
    global matrix1
    matrix1=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix1.append(row)

    print("Your first 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix1[i][j],end=" ")
        print()

def matrix_two():
    print("Enter your second 3x3 matrix: ")
    global matrix2
    matrix2=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix2.append(row)
    print("Your second 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix2[i][j],end=" ")
        print()

def subtract():
    '''function to subtract results of matrix'''
    results = np.subtract(matrix1,matrix2)
    return results
def transpose(function):
    '''transpose function'''
    transpose = np.transpose(function)
    return transpose()
matrix_one()
matrix_two()
subtract()
print(subtract())
print("Transpose of matrice is:\n" + transpose(subtract())),
```

答:
As the comments pointed out,

```<code>print("Transpose of matrice is:\n", transpose(subtract()))
</code>```

instead of

```<code>print("Transpose of matrice is:\n" + transpose(subtract()))
</code>```

will solve your problem since the operator + need strings as arguments, and the result of transpose is not a string but an np.array.

Another approach would be to make transpose() return the string representation of the matrix, like so:

```<code>def transpose(function):
'''transpose function'''
trans = np.transpose(function)
return str(trans)
</code>```

Leaving out the extra parenthesis.

Body:
I have code that I thought was great. I am getting the following error message:

Traceback (most recent call last):
  File "C:\Users\ablev\eclipse-workspace\matrix\matrix.py", line 149, in <module>
    print("Transpose of matrice is:\n" + transpose(subtract())),
numpy.core._exceptions._UFuncNoLoopError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U25'), dtype('int32')) -> None

What does this mean?

def matrix_one():
    print("Enter your first 3x3 matrix: ")
    global matrix1
    matrix1=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix1.append(row)

    print("Your first 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix1[i][j],end=" ")
        print()

def matrix_two():
    print("Enter your second 3x3 matrix: ")
    global matrix2
    matrix2=[]
    for i in range(3):
            while True:
                row=input().split()
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Please enter 3 rows of 3 columns of\
numbers separated by a space: ")
                else:
                    break
            matrix2.append(row)
    print("Your second 3x3 matrix is: ")
    for i in range(3):
        for j in range(3):
            print(matrix2[i][j],end=" ")
        print()

def subtract():
    '''function to subtract results of matrix'''
    results = np.subtract(matrix1,matrix2)
    return results
def transpose(function):
    '''transpose function'''
    transpose = np.transpose(function)
    return transpose()
matrix_one()
matrix_two()
subtract()
print(subtract())
print("Transpose of matrice is:\n" + transpose(subtract())),

Body:
As the comments pointed out,

print("Transpose of matrice is:\n", transpose(subtract()))

instead of

print("Transpose of matrice is:\n" + transpose(subtract()))

will solve your problem since the operator + need strings as arguments, and the result of transpose is not a string but an np.array.

Another approach would be to make transpose() return the string representation of the matrix, like so:

def transpose(function):
'''transpose function'''
trans = np.transpose(function)
return str(trans)

Leaving out the extra parenthesis.


问:
Sending DM with embeds using discord.py
I have tried many things but I can't get discord.py to send a message with embeds. But I have gotten it to send a normal message when a command is typed using this code.

```<code>@client.event
async def on_message(message):
  msg = message.content

  if msg.startswith('$helpme'):
    await message.author.send("this text would be sent via dm, but with no embeds...")
</code>```

It would be a help menu which the bot would the dm the user when $helpme is typed. Problem is I can't get it to send this embed code.

```<code>  embed=discord.Embed(title=" Help", description="I am here to help!", color=0x0000ff)
  embed.set_author(name="Meerdus", icon_url="https://cdn.discordapp.com/attachments/834885490451808286/939646209092616312/M.png")
  embed.add_field(name="$helpme", value="Shows this menu!", inline=False)
  embed.add_field(name="$kick", value="Kick a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$ban", value="Ban a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$unban", value="Unban a member if you have Administrator permissions.", inline=False)
  embed.add_field(name="$lock", value="Lock a channel if you have the permission to manage channels!", inline=False)
  embed.add_field(name="$meme", value="Display a random clean meme! :)", inline=False)
  embed.add_field(name="$doggo", value="Show a random dog picture and dog fact!", inline=False)
  embed.add_field(name="$kitty", value="Show a random cat picture and cat fact!", inline=False)
  embed.add_field(name="$birdy", value="Show a random bird picture and bird fact!", inline=False)
  embed.add_field(name="$randomnum", value="Display a random number between 1 and 100!", inline=False)
  embed.add_field(name="$tictactoe", value="Play tictactoe with two people by specifing <command> <yourusername> <secondplayersusername>", inline=False)
  embed.add_field(name="DONT ACTUALLY ENTER THE <>", value="You have to enter the things said inside them.", inline=False)
  await ctx.send(embed=embed)
</code>```

答:
Instead of ctx.send use ctx.author.send

  embed=discord.Embed(title=" Help", description="I am here to help!", color=0x0000ff)
  embed.set_author(name="Meerdus", icon_url="https://cdn.discordapp.com/attachments/834885490451808286/939646209092616312/M.png")
  embed.add_field(name="$helpme", value="Shows this menu!", inline=False)
  embed.add_field(name="$kick", value="Kick a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$ban", value="Ban a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$unban", value="Unban a member if you have Administrator permissions.", inline=False)
  embed.add_field(name="$lock", value="Lock a channel if you have the permission to manage channels!", inline=False)
  embed.add_field(name="$meme", value="Display a random clean meme! :)", inline=False)
  embed.add_field(name="$doggo", value="Show a random dog picture and dog fact!", inline=False)
  embed.add_field(name="$kitty", value="Show a random cat picture and cat fact!", inline=False)
  embed.add_field(name="$birdy", value="Show a random bird picture and bird fact!", inline=False)
  embed.add_field(name="$randomnum", value="Display a random number between 1 and 100!", inline=False)
  embed.add_field(name="$tictactoe", value="Play tictactoe with two people by specifing <command> <yourusername> <secondplayersusername>", inline=False)
  embed.add_field(name="DONT ACTUALLY ENTER THE <>", value="You have to enter the things said inside them.", inline=False)
  await ctx.author.send(embed=embed)
```

Title: Sending DM with embeds using discord.py

Body:
I have tried many things but I can't get discord.py to send a message with embeds. But I have gotten it to send a normal message when a command is typed using this code.

@client.event
async def on_message(message):
  msg = message.content

  if msg.startswith('$helpme'):
    await message.author.send("this text would be sent via dm, but with no embeds...")

It would be a help menu which the bot would the dm the user when $helpme is typed. Problem is I can't get it to send this embed code.

  embed=discord.Embed(title=" Help", description="I am here to help!", color=0x0000ff)
  embed.set_author(name="Meerdus", icon_url="https://cdn.discordapp.com/attachments/834885490451808286/939646209092616312/M.png")
  embed.add_field(name="$helpme", value="Shows this menu!", inline=False)
  embed.add_field(name="$kick", value="Kick a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$ban", value="Ban a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$unban", value="Unban a member if you have Administrator permissions.", inline=False)
  embed.add_field(name="$lock", value="Lock a channel if you have the permission to manage channels!", inline=False)
  embed.add_field(name="$meme", value="Display a random clean meme! :)", inline=False)
  embed.add_field(name="$doggo", value="Show a random dog picture and dog fact!", inline=False)
  embed.add_field(name="$kitty", value="Show a random cat picture and cat fact!", inline=False)
  embed.add_field(name="$birdy", value="Show a random bird picture and bird fact!", inline=False)
  embed.add_field(name="$randomnum", value="Display a random number between 1 and 100!", inline=False)
  embed.add_field(name="$tictactoe", value="Play tictactoe with two people by specifing <command> <yourusername> <secondplayersusername>", inline=False)
  embed.add_field(name="DONT ACTUALLY ENTER THE <>", value="You have to enter the things said inside them.", inline=False)
  await ctx.send(embed=embed)


问:
value of state increment twice in reducer.js file
Order is an array of Objects and there is a key 'count' inside each variable. When ADD_ITEM_IN_ORDER case is executed than the count of particular object should be increment by 1. But, in this case, when the particular item is already present in the array than the value of count of that item incrementing by 2, which should not happen(it should increment by 1).

reducer.js

```<code>export const initialState = {
  Order: [],
  };
const reducer = (state, action) => {
  console.log(action);
  switch (action.type) {

    case "ADD_ITEM_IN_ORDER":
      const tempOrder1 = [...state.Order];
      const index1 = state.Order.findIndex((item) => item.id === action.item.id);

      if (index1 >= 0) {
        console.log("before",tempOrder1[index1].Count);
        tempOrder1[index1].Count += 1;
        return { ...state, Order: tempOrder1 };
      }
      else {
        console.log("New item added");
        return {
          ...state,
          Order: [...state.Order, action.item]
        };
      }

      default:
        return state;
    }
  };

  export default reducer;
</code>```

action file

```<code>import React from 'react';
import VegIcon from '../Images/VegIcon.png';
import NonVegIcon from '../Images/NonVegIcon.png';
import { useStateValue } from '../StateProvider';
import { db } from '../firebase';

const CartMenu = (props) => {
    const [{ Order }, dispatch] = useStateValue();

    const add = () => {

                dispatch({
                    type: "ADD_ITEM_IN_ORDER",
                    item: {
                    id: props.id,
                    menuCollectionName:props.menuCollectionName,
                    VegNonV: props.VegNonV,
                    Menu: props.Menu,
                    Price: props.Price,
                    Count: 1,
                    // RestuarantId: props.restuarantId
                    }
                });
                console.log(Order);

    };
    const remove = () => {

        dispatch({
            type: "REMOVE_ITEM_FROM_ORDER",
            item: {
                id: props.id,  // id of a dish
                restuarantId: props.restuarantId
            }
        });
    };

    return (
        <div className='Menu_Display'>
            <div className='Menu_Display_subsection1'>
            {props.VegNonV === "Veg" ?
                <img className="Menu_Veg_NonVeg" src={VegIcon} />
                :
                <img className="Menu_Veg_NonVeg" src={NonVegIcon} />
            }
                <div className='Menu_Name'>{props.Menu}</div>
            </div>
            <div className="Menu_Add_Button" >
                <div className="Menu_minus" onClick={remove}>−</div>
                    <span>{props.Count}</span>
                    <div className="Menu_plus" onClick={add}>+</div>
            </div>
            <div className='Menu_Price'>
                <span></span>
                <span>₹{Math.round(props.Price * props.Count * 100) / 100}</span>
            </div>
        </div>
    );
 };

export default CartMenu;
</code>```

StateProvider.js

```<code>//setup data layer
// we need this to track the basket data

import React,{createContext,useContext,useReducer} from 'react';

export const StateContext  = createContext();

//Build Provider
export const StateProvider = ({reducer,initialState,children}) =>
(
    <StateContext.Provider value = {useReducer(reducer,initialState)}>
        {children}
    </StateContext.Provider>
);

export const useStateValue = () => useContext(StateContext);
</code>```

答:
The context API broadcasts updates when it notices a change in the value. Since you are invoking useReducer within the value props, that returns an array (state value and dispatch function), it is this, that is likely causing double dispatch. I recommend you re-write your Provider logic.

```<code>import React,{createContext,useContext,useReducer} from 'react';

export const StateContext  = createContext({ //Make sure to export this
  Order:[], //Will be consuimg the state value from here
  addItem:(arg)=>{} //This function will be hooked to a dispatch function below
});

//Build Provider
export const StateProvider = ({reducer,initialState,children}) =>
{
    const [state,dispatchFn] = useReducer(reducer,initialState)

    const addItemHandler = (item) => {
         dispatchFn(item)
    }
    return(<StateContext.Provider value = {{Order:state.Order,addItem:addItemHandler}}>
        {children}
    </StateContext.Provider>)
};
</code>```

You can then wrap your root component with the context provider component StateProvider so that all the components can access the state values.
In your index.js wrap the component like this:

```<code>import {StateProvider} from './path/to/provider'

ReactDOM.render(<StateProvider><App/></StateProvider>,doucment.getElementById("root"))
</code>```

You can then use the context state and dispatch function from useContext hook by, passing the context variable.

In your action file:

```<code>import {useContext},React from 'react'; //Import use context
import {StateContext} from './path/to/state/context'
import VegIcon from '../Images/VegIcon.png';
import NonVegIcon from '../Images/NonVegIcon.png';

import { db } from '../firebase';

const CartMenu = (props) => {
    const order_ctx = useContext(StateContext);

    const add = () => {

                order_ctx.addItem({
                    type: "ADD_ITEM_IN_ORDER",
                    item: {
                    id: props.id,
                    menuCollectionName:props.menuCollectionName,
                    VegNonV: props.VegNonV,
                    Menu: props.Menu,
                    Price: props.Price,
                    Count: 1,
                    // RestuarantId: props.restuarantId
                    }
                });
                console.log(Order);

    };
    const remove = () => {

        order_ctx.rmItem({                //Note: rmItem method is not added to createContext, but this is just to demonstrate how state update methods can be invoked by using the context instance.
            type: "REMOVE_ITEM_FROM_ORDER",
            item: {
                id: props.id,  // id of a dish
                restuarantId: props.restuarantId
            }
        });
    };

    return (
        <div className='Menu_Display'>
            <div className='Menu_Display_subsection1'>
            {props.VegNonV === "Veg" ?
                <img className="Menu_Veg_NonVeg" src={VegIcon} />
                :
                <img className="Menu_Veg_NonVeg" src={NonVegIcon} />
            }
                <div className='Menu_Name'>{props.Menu}</div>
            </div>
            <div className="Menu_Add_Button" >
                <div className="Menu_minus" onClick={remove}>−</div>
                    <span>{props.Count}</span>
                    <div className="Menu_plus" onClick={add}>+</div>
            </div>
            <div className='Menu_Price'>
                <span></span>
                <span>₹{Math.round(props.Price * props.Count * 100) / 100}</span>
            </div>
        </div>
    );
 };

export default CartMenu;
</code>```

And also since, your state contains only an array of orders, you can just return the updated array without having to override the previous state.

In your reducer:

```<code>case "ADD_ITEM_IN_ORDER":
      const tempOrder1 = [...state.Order];
      const index1 = state.Order.findIndex((item) => item.id === action.item.id);

      if (index1 >= 0) {
        console.log("before",tempOrder1[index1].Count);
        tempOrder1[index1].Count += 1;
        return { Order: [...tempOrder1] }; //Return updated array only
      }
      else {
        console.log("New item added");
        return {
          Order: [...state.Order, action.item] //Return updated array only
        };
      }

      default:
        return state;
    }
</code>```

Body:
Order is an array of Objects and there is a key 'count' inside each variable. When ADD_ITEM_IN_ORDER case is executed than the count of particular object should be increment by 1. But, in this case, when the particular item is already present in the array than the value of count of that item incrementing by 2, which should not happen(it should increment by 1).

reducer.js

export const initialState = {
  Order: [],
  };
const reducer = (state, action) => {
  console.log(action);
  switch (action.type) {

    case "ADD_ITEM_IN_ORDER":
      const tempOrder1 = [...state.Order];
      const index1 = state.Order.findIndex((item) => item.id === action.item.id);

      if (index1 >= 0) {
        console.log("before",tempOrder1[index1].Count);
        tempOrder1[index1].Count += 1;
        return { ...state, Order: tempOrder1 };
      }
      else {
        console.log("New item added");
        return {
          ...state,
          Order: [...state.Order, action.item]
        };
      }

      default:
        return state;
    }
  };

  export default reducer;

action file

import React from 'react';
import VegIcon from '../Images/VegIcon.png';
import NonVegIcon from '../Images/NonVegIcon.png';
import { useStateValue } from '../StateProvider';
import { db } from '../firebase';

const CartMenu = (props) => {
    const [{ Order }, dispatch] = useStateValue();

    const add = () => {

                dispatch({
                    type: "ADD_ITEM_IN_ORDER",
                    item: {
                    id: props.id,
                    menuCollectionName:props.menuCollectionName,
                    VegNonV: props.VegNonV,
                    Menu: props.Menu,
                    Price: props.Price,
                    Count: 1,
                    // RestuarantId: props.restuarantId
                    }
                });
                console.log(Order);

    };
    const remove = () => {

        dispatch({
            type: "REMOVE_ITEM_FROM_ORDER",
            item: {
                id: props.id,  // id of a dish
                restuarantId: props.restuarantId
            }
        });
    };

    return (

            {props.VegNonV === "Veg" ?

                :

            }

{props.Menu}

−

                    {props.Count}

+

                ₹{Math.round(props.Price * props.Count * 100) / 100}

    );
 };

export default CartMenu;

StateProvider.js

//setup data layer
// we need this to track the basket data

import React,{createContext,useContext,useReducer} from 'react';

export const StateContext  = createContext();

//Build Provider
export const StateProvider = ({reducer,initialState,children}) =>
(
    <StateContext.Provider value = {useReducer(reducer,initialState)}>
        {children}
    </StateContext.Provider>
);

export const useStateValue = () => useContext(StateContext);

Body:
The context API broadcasts updates when it notices a change in the value. Since you are invoking useReducer within the value props, that returns an array (state value and dispatch function), it is this, that is likely causing double dispatch. I recommend you re-write your Provider logic.

import React,{createContext,useContext,useReducer} from 'react';

export const StateContext  = createContext({ //Make sure to export this
  Order:[], //Will be consuimg the state value from here
  addItem:(arg)=>{} //This function will be hooked to a dispatch function below
});

//Build Provider
export const StateProvider = ({reducer,initialState,children}) =>
{
    const [state,dispatchFn] = useReducer(reducer,initialState)

    const addItemHandler = (item) => {
         dispatchFn(item)
    }
    return(<StateContext.Provider value = {{Order:state.Order,addItem:addItemHandler}}>
        {children}
    </StateContext.Provider>)
};

You can then wrap your root component with the context provider component StateProvider so that all the components can access the state values.
In your index.js wrap the component like this:

import {StateProvider} from './path/to/provider'

ReactDOM.render(<StateProvider><App/></StateProvider>,doucment.getElementById("root"))

You can then use the context state and dispatch function from useContext hook by, passing the context variable.

In your action file:

import {useContext},React from 'react'; //Import use context
import {StateContext} from './path/to/state/context'
import VegIcon from '../Images/VegIcon.png';
import NonVegIcon from '../Images/NonVegIcon.png';

import { db } from '../firebase';

const CartMenu = (props) => {
    const order_ctx = useContext(StateContext);

    const add = () => {

                order_ctx.addItem({
                    type: "ADD_ITEM_IN_ORDER",
                    item: {
                    id: props.id,
                    menuCollectionName:props.menuCollectionName,
                    VegNonV: props.VegNonV,
                    Menu: props.Menu,
                    Price: props.Price,
                    Count: 1,
                    // RestuarantId: props.restuarantId
                    }
                });
                console.log(Order);

    };
    const remove = () => {

        order_ctx.rmItem({                //Note: rmItem method is not added to createContext, but this is just to demonstrate how state update methods can be invoked by using the context instance.
            type: "REMOVE_ITEM_FROM_ORDER",
            item: {
                id: props.id,  // id of a dish
                restuarantId: props.restuarantId
            }
        });
    };

    return (
        <div className='Menu_Display'>
            <div className='Menu_Display_subsection1'>
            {props.VegNonV === "Veg" ?
                <img className="Menu_Veg_NonVeg" src={VegIcon} />
                :
                <img className="Menu_Veg_NonVeg" src={NonVegIcon} />
            }
                <div className='Menu_Name'>{props.Menu}</div>
            </div>
            <div className="Menu_Add_Button" >
                <div className="Menu_minus" onClick={remove}>−</div>
                    <span>{props.Count}</span>
                    <div className="Menu_plus" onClick={add}>+</div>
            </div>
            <div className='Menu_Price'>
                <span></span>
                <span>₹{Math.round(props.Price * props.Count * 100) / 100}</span>
            </div>
        </div>
    );
 };

export default CartMenu;

And also since, your state contains only an array of orders, you can just return the updated array without having to override the previous state.

In your reducer:

case "ADD_ITEM_IN_ORDER":
      const tempOrder1 = [...state.Order];
      const index1 = state.Order.findIndex((item) => item.id === action.item.id);

      if (index1 >= 0) {
        console.log("before",tempOrder1[index1].Count);
        tempOrder1[index1].Count += 1;
        return { Order: [...tempOrder1] }; //Return updated array only
      }
      else {
        console.log("New item added");
        return {
          Order: [...state.Order, action.item] //Return updated array only
        };
      }

      default:
        return state;
    }


问:
Switching between tab using activity group it want to display last activity - Tab ActivityGroup
I have written tab for my android application.

My question is switching between tab using activity group it want to display last activity. I want to show last open/visited screen when we navigate the tab.My one is go to first screen:

I need to show last opened screen when navigate through Tab

Tab 1 -> Sales. This  contain 10 screen inside (actiivity)
Tab 2 -> Admin .This contain 5 screen inside (actiivity)
Tab 3 -> Setting.This contain 8 screen inside. (actiivity)

I clicked Tab 1 , it load tab 1's screen which is contain list of sales route .then I clicked one sales route , it goes to list of retailer in the first tab.Then I cliched tab 3  "Setting " finish some work & come back to sales, That time it should show last open screen in the "sales" tab.

When I clicked tab, It should show last open activity How to do?

I did like this.Please indicate where I want to change the code for my requirements.

MainActivity.It will call after login

```<code>  public class MainActivity extends TabActivity {
int selectedTab;
TabHost tabHost ;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tabview);

    TabHost t = getTabHost();
    tabHost = (TabHost)findViewById(android.R.id.tabhost);

    TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
    TabSpec secondTabSpec = tabHost.newTabSpec("tid1");
    TabSpec thirdTabSpec = tabHost.newTabSpec("tid1");
    /** TabSpec setIndicator() is used to set name for the tab. */
    /** TabSpec setContent() is used to set content for a particular tab. */
    firstTabSpec.setIndicator("Sales").setContent(new Intent(this,SalesActivityGroup.class));
    secondTabSpec.setIndicator("Admin").setContent(new Intent(this,SettingActivityGroup.class));
    thirdTabSpec.setIndicator("Setting").setContent(new Intent(this,SettingActivityGroup.class));

    tabHost.addTab(firstTabSpec);
    tabHost.addTab(secondTabSpec);
    tabHost.addTab(thirdTabSpec);
    tabHost.setCurrentTab(0);
    tabHost.setMinimumHeight(25);
}

public void onTabChanged(String arg0) {
        selectedTab = tabHost.getCurrentTab();

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(false);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
</code>```

}

First Tab1(Sales)'s SalesGroupActivity

```<code> public class SalesActivityGroup extends ActivityGroup {

public static SalesActivityGroup group;
private ArrayList<View> history;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.history = new ArrayList<View>();
    group = this;

    View view = getLocalActivityManager().startActivity("Sales",
            new Intent(this, SalesRouteActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
            .getDecorView();

    replaceView(view);

}

public void replaceView(View v) {
    history.add(v);
    setContentView(v);

}

public void back() {
    if (history.size() > 0) {
        history.remove(history.size() - 1);
        if (history.size() > 0) {
            setContentView(history.get(history.size() - 1));
        } else {
            finish();
        }
    } else {
        finish();
    }
}

@Override
public void onBackPressed() {
    SalesActivityGroup.group.back();
    return;
}
</code>```

Edited
This is FirstTab's firstActivity - SalesRouteActivity

```<code>    public class SalesRouteActivity extends ListActivity{
     TableLayout tl;
     static int positions = 0;
     static String keyword ="";
     int uploadSize = 0;
     private NotificationManager mNotificationManager;
     private int SIMPLE_NOTFICATION_ID;
     String strBusinessUnit = "";
     String strExecutive = "";
     String strTerritoryCode = "";
     SimpleAdapter sd;
     View row = null;
     View selectRow = null;

     @Override
     public void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);
         setContentView(R.layout.sales_routes);

         SharedPreferences myPrefs = this.getSharedPreferences("myLogedPrefs",MODE_WORLD_READABLE);
         strBusinessUnit = myPrefs.getString("BusinessUnit", "");
         strExecutive = myPrefs.getString("Executive", "");
         strTerritoryCode = myPrefs.getString("TerritoryCode", "");

         ArrayList<SalesRoutes> routeList = getSalesRoute();

         ArrayList<HashMap<String, String>> routhPath = new ArrayList<HashMap<String, String>>();
         for (int i = 0; i < routeList.size(); i++) {
            if(Integer.parseInt(routeList.get(i).getOutlets()) >0){
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("routeCode",((SalesRoutes) routeList.get(i)).getRouteCode());
                map.put("routeName",((SalesRoutes) routeList.get(i)).getDescription());
                map.put("outlets", ((SalesRoutes) routeList.get(i)).getOutlets());
                routhPath.add(map);
             }
         }

         ListView list = getListView();
         sd = new SimpleAdapter(this, routhPath, R.layout.route_path,new String[] {"routeCode","routeName","outlets" },new int[] { R.id.routeCode,R.id.routeName,R.id.outlets});
         row = getLayoutInflater().inflate(R.layout.route_path_row, null, false);
         getListView().addHeaderView(row);
         list.setAdapter(sd);
         list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        list.setSelected(true);
        list.setTextFilterEnabled(true);
        list.setItemsCanFocus(true);
        list.setItemChecked(positions, true);
        list.setSelectionAfterHeaderView();

        if (routeList.size() > 0) {
            keyword = routeList.get(0).getRouteCode();
        }

        uploadSize = new UploadActivity().getUploadTable();

        if (uploadSize > 0) {
            mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            final Notification notifyDetails = new Notification(R.drawable.icon, "New Alert, Click Me!",System.currentTimeMillis());
            Context context = getApplicationContext();
            CharSequence contentTitle = "Upload Available...";
            CharSequence contentText = "Browse Android Official Site by clicking me";
            Intent notifyIntent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://www.android.com"));
            PendingIntent intent = PendingIntent.getActivity(SalesRouteActivity.this, 0, notifyIntent,android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
            notifyDetails.setLatestEventInfo(context, contentTitle,contentText, intent);
            mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        HashMap<String, String> hashMap = (HashMap<String, String>) l.getItemAtPosition(position);
        keyword = hashMap.get("routeCode");

        positions = position;
        if(position == 0 ){

        }else if(position != 1){
            Intent showContent = new Intent(v.getContext(),SalesRouteDevitionActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("RouteCode", keyword);
            showContent.putExtras(bundle);
            getParent().startActivityForResult(showContent, 5);
        }else{
            Intent intent = new Intent(SalesRouteActivity.this, ListRetailerActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("RouteName", keyword);
            intent.putExtras(bundle);
            View view = SalesActivityGroup.group.getLocalActivityManager().startActivity("", intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
            SalesActivityGroup.group.replaceView(view);

        }
    }

    @Override
    public void onBackPressed() {
        SalesActivityGroup.group.back();
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public ArrayList<SalesRoutes> getSalesRoute(){
         DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(this);
          try {
              dbAdapter.createDataBase();
         } catch (IOException e) {
              Log.i("*** select ",e.getMessage());
         }
         dbAdapter.openDataBase();
         String sql = "SELECT RouteCode, Description, OutletsAttached  " +
                       "FROM WMRoute  " +
                       "WHERE ActiveStatus = '1' AND  RouteDefaultExecutive = ? AND  BusinessUnit = ? AND TerritoryCode = ?  " +
                       "ORDER BY RouteCode  ";

         String[]d = new String[]{strExecutive,strBusinessUnit,strTerritoryCode};
         ArrayList stringList = dbAdapter.selectRecordsFromDBList(sql, d);
         dbAdapter.close();
         ArrayList<SalesRoutes> salesRoutesList = new ArrayList<SalesRoutes>();
         for (int i = 0; i < stringList.size(); i++) {
            ArrayList<Object> arrayList = (ArrayList<Object>) stringList.get(i);
            ArrayList<Object> list = arrayList;
            SalesRoutes salesRoutes = new SalesRoutes();
            try {
                salesRoutes.setRouteCode((String) list.get(0));
                salesRoutes.setDescription((String) list.get(1));
                salesRoutes.setOutlets((String)list.get(2));

            } catch (Exception e) {
                Log.i("***" + SalesRouteActivity.class.toString(), e.getMessage());
            }
            salesRoutesList.add(salesRoutes);
        }
        return salesRoutesList;
    }
}
</code>```

probably my ActivityGroups are being created again and again when you switch between tabs
So   groups want to create only once and resumed when i switch between tabs

Every screen details/contents getting from database..

I am facing this issue more than 2 days....Please help me.
Please help me on this....

Thanks  in advance.....

答:
Thanks All;

There were issue in my MainActivity.

```<code> tabHost = getTabHost();
    TabHost.TabSpec spec;
    Intent intent;

    intent = new Intent().setClass(this, SalesActivityGroup.class);
    spec = getTabHost().newTabSpec("Sales").setIndicator("Sales",getResources().getDrawable(R.drawable.ic_tab_artists_grey)).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SettingActivityGroup.class);
    spec = getTabHost().newTabSpec("Admin").setIndicator("Admin",getResources().getDrawable(R.drawable.admin)).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SettingActivityGroup.class);
    spec = getTabHost().newTabSpec("Setting").setIndicator("Setting",getResources().getDrawable(R.drawable.ic_tab_artists_grey)).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SettingActivityGroup.class);
    spec = getTabHost().newTabSpec("Inquiry").setIndicator("Inquiry",getResources().getDrawable(R.drawable.ic_tab_artists_grey)).setContent(intent);
    tabHost.addTab(spec);

    tabHost.setCurrentTab(0);
    tabHost.setMinimumHeight(18);
    tabHost.setFadingEdgeLength(5);
    tabHost.setFocusable(true);
    tabHost.requestFocus();
    tabHost.setFadingEdgeLength(5);
  }
}
</code>```

And I agree @Vaibhav Jani @Dharmendra @Suri, I missed that onKeyPressed() in all Activity.

Body:
I have written tab for my android application.

My question is switching between tab using activity group it want to display last activity. I want to show last open/visited screen when we navigate the tab.My one is go to first screen:

I need to show last opened screen when navigate through Tab

Tab 1 -> Sales. This  contain 10 screen inside (actiivity)
Tab 2 -> Admin .This contain 5 screen inside (actiivity)
Tab 3 -> Setting.This contain 8 screen inside. (actiivity)

I clicked Tab 1 , it load tab 1's screen which is contain list of sales route .then I clicked one sales route , it goes to list of retailer in the first tab.Then I cliched tab 3  "Setting " finish some work & come back to sales, That time it should show last open screen in the "sales" tab.

When I clicked tab, It should show last open activity How to do?

I did like this.Please indicate where I want to change the code for my requirements.

MainActivity.It will call after login

  public class MainActivity extends TabActivity {
int selectedTab;
TabHost tabHost ;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tabview);

    TabHost t = getTabHost();
    tabHost = (TabHost)findViewById(android.R.id.tabhost);

    TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
    TabSpec secondTabSpec = tabHost.newTabSpec("tid1");
    TabSpec thirdTabSpec = tabHost.newTabSpec("tid1");
    /** TabSpec setIndicator() is used to set name for the tab. */
    /** TabSpec setContent() is used to set content for a particular tab. */
    firstTabSpec.setIndicator("Sales").setContent(new Intent(this,SalesActivityGroup.class));
    secondTabSpec.setIndicator("Admin").setContent(new Intent(this,SettingActivityGroup.class));
    thirdTabSpec.setIndicator("Setting").setContent(new Intent(this,SettingActivityGroup.class));

    tabHost.addTab(firstTabSpec);
    tabHost.addTab(secondTabSpec);
    tabHost.addTab(thirdTabSpec);
    tabHost.setCurrentTab(0);
    tabHost.setMinimumHeight(25);
}

public void onTabChanged(String arg0) {
        selectedTab = tabHost.getCurrentTab();

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(false);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

}

First Tab1(Sales)'s SalesGroupActivity

 public class SalesActivityGroup extends ActivityGroup {

public static SalesActivityGroup group;
private ArrayList<View> history;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.history = new ArrayList<View>();
    group = this;

    View view = getLocalActivityManager().startActivity("Sales",
            new Intent(this, SalesRouteActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
            .getDecorView();

    replaceView(view);

}

public void replaceView(View v) {
    history.add(v);
    setContentView(v);

}

public void back() {
    if (history.size() > 0) {
        history.remove(history.size() - 1);
        if (history.size() > 0) {
            setContentView(history.get(history.size() - 1));
        } else {
            finish();
        }
    } else {
        finish();
    }
}

@Override
public void onBackPressed() {
    SalesActivityGroup.group.back();
    return;
}

Edited
This is FirstTab's firstActivity - SalesRouteActivity

    public class SalesRouteActivity extends ListActivity{
     TableLayout tl;
     static int positions = 0;
     static String keyword ="";
     int uploadSize = 0;
     private NotificationManager mNotificationManager;
     private int SIMPLE_NOTFICATION_ID;
     String strBusinessUnit = "";
     String strExecutive = "";
     String strTerritoryCode = "";
     SimpleAdapter sd;
     View row = null;
     View selectRow = null;

     @Override
     public void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);
         setContentView(R.layout.sales_routes);

         SharedPreferences myPrefs = this.getSharedPreferences("myLogedPrefs",MODE_WORLD_READABLE);
         strBusinessUnit = myPrefs.getString("BusinessUnit", "");
         strExecutive = myPrefs.getString("Executive", "");
         strTerritoryCode = myPrefs.getString("TerritoryCode", "");

         ArrayList<SalesRoutes> routeList = getSalesRoute();

         ArrayList<HashMap<String, String>> routhPath = new ArrayList<HashMap<String, String>>();
         for (int i = 0; i < routeList.size(); i++) {
            if(Integer.parseInt(routeList.get(i).getOutlets()) >0){
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("routeCode",((SalesRoutes) routeList.get(i)).getRouteCode());
                map.put("routeName",((SalesRoutes) routeList.get(i)).getDescription());
                map.put("outlets", ((SalesRoutes) routeList.get(i)).getOutlets());
                routhPath.add(map);
             }
         }

         ListView list = getListView();
         sd = new SimpleAdapter(this, routhPath, R.layout.route_path,new String[] {"routeCode","routeName","outlets" },new int[] { R.id.routeCode,R.id.routeName,R.id.outlets});
         row = getLayoutInflater().inflate(R.layout.route_path_row, null, false);
         getListView().addHeaderView(row);
         list.setAdapter(sd);
         list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        list.setSelected(true);
        list.setTextFilterEnabled(true);
        list.setItemsCanFocus(true);
        list.setItemChecked(positions, true);
        list.setSelectionAfterHeaderView();

        if (routeList.size() > 0) {
            keyword = routeList.get(0).getRouteCode();
        }

        uploadSize = new UploadActivity().getUploadTable();

        if (uploadSize > 0) {
            mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            final Notification notifyDetails = new Notification(R.drawable.icon, "New Alert, Click Me!",System.currentTimeMillis());
            Context context = getApplicationContext();
            CharSequence contentTitle = "Upload Available...";
            CharSequence contentText = "Browse Android Official Site by clicking me";
            Intent notifyIntent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://www.android.com"));
            PendingIntent intent = PendingIntent.getActivity(SalesRouteActivity.this, 0, notifyIntent,android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
            notifyDetails.setLatestEventInfo(context, contentTitle,contentText, intent);
            mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        HashMap<String, String> hashMap = (HashMap<String, String>) l.getItemAtPosition(position);
        keyword = hashMap.get("routeCode");

        positions = position;
        if(position == 0 ){

        }else if(position != 1){
            Intent showContent = new Intent(v.getContext(),SalesRouteDevitionActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("RouteCode", keyword);
            showContent.putExtras(bundle);
            getParent().startActivityForResult(showContent, 5);
        }else{
            Intent intent = new Intent(SalesRouteActivity.this, ListRetailerActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("RouteName", keyword);
            intent.putExtras(bundle);
            View view = SalesActivityGroup.group.getLocalActivityManager().startActivity("", intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
            SalesActivityGroup.group.replaceView(view);

        }
    }

    @Override
    public void onBackPressed() {
        SalesActivityGroup.group.back();
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public ArrayList<SalesRoutes> getSalesRoute(){
         DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(this);
          try {
              dbAdapter.createDataBase();
         } catch (IOException e) {
              Log.i("*** select ",e.getMessage());
         }
         dbAdapter.openDataBase();
         String sql = "SELECT RouteCode, Description, OutletsAttached  " +
                       "FROM WMRoute  " +
                       "WHERE ActiveStatus = '1' AND  RouteDefaultExecutive = ? AND  BusinessUnit = ? AND TerritoryCode = ?  " +
                       "ORDER BY RouteCode  ";

         String[]d = new String[]{strExecutive,strBusinessUnit,strTerritoryCode};
         ArrayList stringList = dbAdapter.selectRecordsFromDBList(sql, d);
         dbAdapter.close();
         ArrayList<SalesRoutes> salesRoutesList = new ArrayList<SalesRoutes>();
         for (int i = 0; i < stringList.size(); i++) {
            ArrayList<Object> arrayList = (ArrayList<Object>) stringList.get(i);
            ArrayList<Object> list = arrayList;
            SalesRoutes salesRoutes = new SalesRoutes();
            try {
                salesRoutes.setRouteCode((String) list.get(0));
                salesRoutes.setDescription((String) list.get(1));
                salesRoutes.setOutlets((String)list.get(2));

            } catch (Exception e) {
                Log.i("***" + SalesRouteActivity.class.toString(), e.getMessage());
            }
            salesRoutesList.add(salesRoutes);
        }
        return salesRoutesList;
    }
}

probably my ActivityGroups are being created again and again when you switch between tabs
So   groups want to create only once and resumed when i switch between tabs

Every screen details/contents getting from database..

I am facing this issue more than 2 days....Please help me.
Please help me on this....

Thanks  in advance.....

Body:
Thanks All;

There were issue in my MainActivity.

 tabHost = getTabHost();
    TabHost.TabSpec spec;
    Intent intent;

    intent = new Intent().setClass(this, SalesActivityGroup.class);
    spec = getTabHost().newTabSpec("Sales").setIndicator("Sales",getResources().getDrawable(R.drawable.ic_tab_artists_grey)).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SettingActivityGroup.class);
    spec = getTabHost().newTabSpec("Admin").setIndicator("Admin",getResources().getDrawable(R.drawable.admin)).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SettingActivityGroup.class);
    spec = getTabHost().newTabSpec("Setting").setIndicator("Setting",getResources().getDrawable(R.drawable.ic_tab_artists_grey)).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SettingActivityGroup.class);
    spec = getTabHost().newTabSpec("Inquiry").setIndicator("Inquiry",getResources().getDrawable(R.drawable.ic_tab_artists_grey)).setContent(intent);
    tabHost.addTab(spec);

    tabHost.setCurrentTab(0);
    tabHost.setMinimumHeight(18);
    tabHost.setFadingEdgeLength(5);
    tabHost.setFocusable(true);
    tabHost.requestFocus();
    tabHost.setFadingEdgeLength(5);
  }
}

And I agree @Vaibhav Jani @Dharmendra @Suri, I missed that onKeyPressed() in all Activity.


问:
How do I shorten this CSS which has CSS Pseudo-elements using SCSS?
How do I shorten this CSS which has CSS Pseudo-elements using SCSS?

```<code>.bar-color1 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;

  &::after {
    color: #28A745;
    content: url("../../assets/images/arrow.png");;
    display: inline-block !important;
    width: 0;
    height: 0;
    position: absolute;
    right: 6px;
    top: -6px;
  }
}
.bar-color2 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;

  &::after {
    content: "" !important;
  }
}
</code>```

As you can see both has these common styles

```<code>  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;
</code>```

答:
You can use multiple selector:

.bar-color1, .bar-color2 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;
}
```
<h3>CSS</h3>
<pre class="lang-css prettyprint-override"><code>.bar-color1, .bar-color2 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;
}

.bar-color1 {
  &::after {
    color: #28A745;
    content: url("../../assets/images/arrow.png");;
    display: inline-block !important;
    width: 0;
    height: 0;
    position: absolute;
    right: 6px;
    top: -6px;
  }
}

.bar-color2 {
  &::after {
    content: "" !important;
  }
}
</code>```

Body:
How do I shorten this CSS which has CSS Pseudo-elements using SCSS?

.bar-color1 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;

  &::after {
    color: #28A745;
    content: url("../../assets/images/arrow.png");;
    display: inline-block !important;
    width: 0;
    height: 0;
    position: absolute;
    right: 6px;
    top: -6px;
  }
}
.bar-color2 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;

  &::after {
    content: "" !important;
  }
}

As you can see both has these common styles

  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;

Body:
You can use multiple selector:

.bar-color1, .bar-color2 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;
}

CSS

.bar-color1, .bar-color2 {
  background: #28A745;
  position: absolute;
  top: 0; bottom: 0; left: 0;
}

.bar-color1 {
  &::after {
    color: #28A745;
    content: url("../../assets/images/arrow.png");;
    display: inline-block !important;
    width: 0;
    height: 0;
    position: absolute;
    right: 6px;
    top: -6px;
  }
}

.bar-color2 {
  &::after {
    content: "" !important;
  }
}


问:
How to looping trough an array of object when array name is not consistent?
Consider below example:

```<code>const obj ={
price:[{multiple items},{multiple items}],
name:"",
id:"",
}
</code>```

i want to apply foreach on price property but the issue is the property name is changing wrt cases like saleprice , taxprice etc.

if i am using obj.keys() method it doesn't work because it returns key as a string.

答:
You can try this:</p>
```<code>const obj = {
  price: [10, 20, 30],
  name: "",
  id: "",
};

const pricePropertyName = Object.keys(obj).find((prop) => prop.includes('price'));
if (pricePropertyName) {
  obj[pricePropertyName].forEach(el => {
    console.log(el);
  });
}
</code>```

Body:
Consider below example:

const obj ={
price:[{multiple items},{multiple items}],
name:"",
id:"",
}

i want to apply foreach on price property but the issue is the property name is changing wrt cases like saleprice , taxprice etc.

if i am using obj.keys() method it doesn't work because it returns key as a string.

Body:
You can try this:

const obj = {
  price: [10, 20, 30],
  name: "",
  id: "",
};

const pricePropertyName = Object.keys(obj).find((prop) => prop.includes('price'));
if (pricePropertyName) {
  obj[pricePropertyName].forEach(el => {
    console.log(el);
  });
}


问:
"You are debugging a release build" when debug is selected
I am attempting to debug my solution, which is set to start a few different projects. One of these projects is giving me an error when it is hit saying that it is running in release mode. This same solution has been running fine on Windows 7, but I just switched to a new machine running Windows 10 and am now getting this error message. I have attempted cleaning the solution and doing a rebuild with Debug and Any CPU selected to no avail. The code that is failing is within a class library that is referenced by a Web Api project. I am able to send a request to the Web Api that does not require the use of the class library and that works as intended.

答:
I have tried all solution above and didn't work. and I found this solution work :

Debug > Options > Debugging > General > (check) Surpress JIT optimization on module load (Managed only)


问:
Java regex for image filename?
I have to filter filenames to match only image (png,jpg,gif,bmp) files, is possible to make a such regex or do I have to have different regex for every file type? It also cannot contain path like ../../ or /var/app/filename.exe etc.</p>

答:
Link:

http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression/

I hope you find it useful.

Title: Java regex for image filename?


问:
After I update my student.Id it refuses to be added to my Hashtable
In a lesson on hashtables, the online teacher lightly suggests trying to update a "students ID", represented as student.Id in foreach loop, depending on an instance where two IDs are identical.

I tried to make foreach loop, to check with the metod ContainsKey() and then executs an update or adds the student.Id to the hashtable. The problem i've found is the student.Id gets updated, e.g. ID 2 becomes 3 because 2 was already added to the list, but refuses to add it to this list thereafter.

I'm thinking i've overlooked something obvious?

static void Main(string[] args)
{

            Hashtable studentsTable = new Hashtable();

            Student[] students = new Student[5];
            students[0] = new Student(1, "Maria", 98);
            students[1] = new Student(2, "Bob", 62);
            students[2] = new Student(1, "Mary", 90);
            students[3] = new Student(4, "Eric", 88);
            students[4] = new Student(5, "Clint", 72);

            foreach(Student student in students)
            {

                if(!studentsTable.ContainsKey(student.Id))
                {
                    studentsTable.Add(student.Id, student);
                    Console.WriteLine("Student with Id{0} was added!.", student.Id);
                }
                else if (studentsTable.ContainsKey(student.Id))
                {
                    do
                    {

                    student.Id += 1;

                    // this write line was to check that the id was being updated

                    Console.WriteLine(student.Id);

                    } while (studentsTable.ContainsKey(student.Id));

                    // same as above comment

                    Console.WriteLine(student.Id);

                    studentsTable.Add(student.Id, student);
                }
                else
                 {
                 Console.WriteLine("Sorry, A student with the same ID: {0}, already Exists.", student.Id);
                 }

            }

        }

        class Student
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public float GPA { get; set; }

            public Student(int id, string name, float GPA)
            {
                this.Id = id;
                this.Name = name;
                this.GPA = GPA;
            }

        }
```

答:
We can simplify your logic to:

```<code>    foreach(Student student in students)
    {

        while(studentsTable.ContainsKey(student.Id)){
          student.Id++;
        }

        studentsTable.Add(student.Id, student);
        Console.WriteLine("Student with Id{0} was added!.", student.Id);

    }
</code>```

but I don't see a problem with it as is. A hash table ID must be unique so while there is already a student in the table with the same ID as the one we want to add, we increment the id of the student we are trying to add and check again, until we find an ID not in the table. In practice this means the second student with ID 1 will have the Id bumped to 3 before they can be added. If you printed the table at the end of the foreach would see 1,2,3,4,5 (well, hashtables aren't ordered so you might see any order, but you'd see 5 unique IDs and Mary would be 3)

Incidentally, and an interesting point for sakes of learning about reference types, whether you printed out the list or the hash table, you would see that in each one Mary has had their ID updated to 3. This is because there is only ever one Mary in memory, so updates to the memory data itself mean that all things that have a reference to Mary (the list, the hash table, any temporary loop variable) all experience the update because that are multiple references to one block of data, like multiple shortcuts to one original file

Note, it's incredibly unlikely your else logic will ever be used, so I removed it

Body:
We can simplify your logic to:

    foreach(Student student in students)
    {

        while(studentsTable.ContainsKey(student.Id)){
          student.Id++;
        }

        studentsTable.Add(student.Id, student);
        Console.WriteLine("Student with Id{0} was added!.", student.Id);

    }

but I don't see a problem with it as is. A hash table ID must be unique so while there is already a student in the table with the same ID as the one we want to add, we increment the id of the student we are trying to add and check again, until we find an ID not in the table. In practice this means the second student with ID 1 will have the Id bumped to 3 before they can be added. If you printed the table at the end of the foreach would see 1,2,3,4,5 (well, hashtables aren't ordered so you might see any order, but you'd see 5 unique IDs and Mary would be 3)

Incidentally, and an interesting point for sakes of learning about reference types, whether you printed out the list or the hash table, you would see that in each one Mary has had their ID updated to 3. This is because there is only ever one Mary in memory, so updates to the memory data itself mean that all things that have a reference to Mary (the list, the hash table, any temporary loop variable) all experience the update because that are multiple references to one block of data, like multiple shortcuts to one original file

Note, it's incredibly unlikely your else logic will ever be used, so I removed it