问:
Why is ecto raising Ecto.NoPrimaryKeyValueError when I have a primary key and it has a value?
Whenever I run this code:

```<code>{:ok, act_1} = %Kempelen.Models.GameAct{}
  |> Kempelen.Models.GameAct.changeset(%{
      game_play: place_road,
      game_player: player_1,
      game_round: round_1
    })
  |> Kempelen.Database.Repo.insert
</code>```

I'm getting this exception:

```<code>** (Ecto.NoPrimaryKeyValueError) struct `%Kempelen.Models.GamePlayer{__meta__: #Ecto.Schema.Metadata<:loaded, "game_players">, account: %Kempelen.Models.Account{__meta__: #Ecto.Schema.Metadata<:loaded, "accounts">, email: "kurtis@difference-engineers.org", game_players: #Ecto.Association.NotLoaded<association :game_players is not loaded>, game_rounds: #Ecto.Association.NotLoaded<association :game_rounds is not loaded>, game_tables: #Ecto.Association.NotLoaded<association :game_tables is not loaded>, id: "65880220-e39b-450d-ba7f-0642bea8dbc8", inserted_at: ~N[2020-02-16 16:15:33], name: nil, onboarding_state: "converted", organization_memberships: #Ecto.Association.NotLoaded<association :organization_memberships is not loaded>, organizations: #Ecto.Association.NotLoaded<association :organizations is not loaded>, password: nil, password_hash: nil, role_state: "user", unconfirmed_email: "kurtis@difference-engineers.org", updated_at: ~N[2020-02-16 16:15:33], username: nil}, account_id: "65880220-e39b-450d-ba7f-0642bea8dbc8", game_acts: #Ecto.Association.NotLoaded<association :game_acts is not loaded>, game_robot: nil, game_robot_id: nil, game_table: %Kempelen.Models.GameTable{__meta__: #Ecto.Schema.Metadata<:loaded, "game_tables">, game: %Kempelen.Models.Game{__meta__: #Ecto.Schema.Metadata<:loaded, "games">, game_plays: #Ecto.Association.NotLoaded<association :game_plays is not loaded>, game_tables: #Ecto.Association.NotLoaded<association :game_tables is not loaded>, id: "31eee3b8-b43c-411a-8528-479269c63d2d", inserted_at: ~N[2020-02-16 16:15:33], name: "Settlers of Catan", organization: %Kempelen.Models.Organization{__meta__: #Ecto.Schema.Metadata<:loaded, "organizations">, accounts: #Ecto.Association.NotLoaded<association :accounts is not loaded>, games: #Ecto.Association.NotLoaded<association :games is not loaded>, id: "3311c337-f480-4292-9582-c45f249730b2", inserted_at: ~N[2020-02-16 16:15:32], name: "Hasbro", organization_memberships: #Ecto.Association.NotLoaded<association :organization_memberships is not loaded>, robots: #Ecto.Association.NotLoaded<association :robots is not loaded>, slug: "hasbro", updated_at: ~N[2020-02-16 16:15:32]}, organization_id: "3311c337-f480-4292-9582-c45f249730b2", slug: "settlers-of-catan", updated_at: ~N[2020-02-16 16:15:33]}, game_id: "31eee3b8-b43c-411a-8528-479269c63d2d", game_players: #Ecto.Association.NotLoaded<association :game_players is not loaded>, game_rounds: #Ecto.Association.NotLoaded<association :game_rounds is not loaded>, id: "2cda5e3c-c57d-4117-a541-0c6a409984b6", inserted_at: ~N[2020-02-16 16:15:33], name: "FFA", slug: "ffa", updated_at: ~N[2020-02-16 16:15:33]}, game_table_id: "2cda5e3c-c57d-4117-a541-0c6a409984b6", host: true, id: "591227e6-3ea0-4f3f-8a44-471d7073c2df", inserted_at: ~N[2020-02-16 16:15:33], name: "Kurtis", slug: "kurtis", updated_at: ~N[2020-02-16 16:15:33]}` is missing primary key value
</code>```

Here's are the models:

```<code>defmodule Kempelen.Models.GameAct do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "game_acts" do
    belongs_to :game_play, Kempelen.Models.GamePlay, primary_key: true
    belongs_to :game_player, Kempelen.Models.GamePlayer, primary_key: true
    belongs_to :game_round, Kempelen.Models.GameRound, primary_key: true

    timestamps()
  end

  @doc false
  def changeset(%{} = record, attributes \\ %{}) do
    record
    |> cast(attributes, [])
    |> validate_required([])
    |> assoc_constraint(:game_play)
    |> assoc_constraint(:game_player)
    |> assoc_constraint(:game_round)
    |> put_assoc(:game_play, attributes.game_play)
    |> put_assoc(:game_player, attributes.game_player)
    |> put_assoc(:game_round, attributes.game_round)
  end
end
</code>```

```<code>defmodule Kempelen.Models.GamePlayer do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "game_players" do
    field :name, :string
    field :slug, Kempelen.Slugs.Name.Type
    field :host, :boolean, default: false
    belongs_to :game_table, Kempelen.Models.GameTable, primary_key: true
    belongs_to :account, Kempelen.Models.Account, primary_key: true
    belongs_to :game_robot, Kempelen.Models.GameRobot, primary_key: true
    has_many :game_acts, Kempelen.Models.GameAct

    timestamps()
  end

  @doc false
  def changeset(%{} = record, attributes \\ %{}) do
    record
      |> cast(attributes, [:name, :host])
      |> validate_required([:name, :host])
      |> assoc_constraint(:game_table)
      |> assoc_constraint(:account)
      |> assoc_constraint(:game_robot)
      |> Kempelen.Slugs.Name.maybe_generate_slug
      |> Kempelen.Slugs.Name.unique_constraint
      |> put_assoc(:game_robot, attributes[:game_robot])
      |> put_assoc(:account, attributes[:account])
      |> put_assoc(:game_table, attributes.game_table)
  end
end
</code>```

It's not just the game_play model either, it also happens of the game_player.

The changeset appears to think it's valid, as well:

```<code>#Ecto.Changeset<
  action: nil,
  changes: %{
    game_play: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
     data: #Kempelen.Models.GamePlay<>, valid?: true>,
    game_player: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
     data: #Kempelen.Models.GamePlayer<>, valid?: true>,
    game_round: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
     data: #Kempelen.Models.GameRound<>, valid?: true>
  },
  errors: [],
  data: #Kempelen.Models.GameAct<>,
  valid?: true
>
</code>```

答: Alright, so I finally figured it out. It turns out that while I wanted the account and game_robot relationships to be optional (one or the other, in business logic), the primary_key: true option for belongs_to in the schema means that the foreign key column must have a value.

Body:
Whenever I run this code:

{:ok, act_1} = %Kempelen.Models.GameAct{}
  |> Kempelen.Models.GameAct.changeset(%{
      game_play: place_road,
      game_player: player_1,
      game_round: round_1
    })
  |> Kempelen.Database.Repo.insert

I'm getting this exception:

** (Ecto.NoPrimaryKeyValueError) struct `%Kempelen.Models.GamePlayer{__meta__: #Ecto.Schema.Metadata<:loaded, "game_players">, account: %Kempelen.Models.Account{__meta__: #Ecto.Schema.Metadata<:loaded, "accounts">, email: "kurtis@difference-engineers.org", game_players: #Ecto.Association.NotLoaded<association :game_players is not loaded>, game_rounds: #Ecto.Association.NotLoaded<association :game_rounds is not loaded>, game_tables: #Ecto.Association.NotLoaded<association :game_tables is not loaded>, id: "65880220-e39b-450d-ba7f-0642bea8dbc8", inserted_at: ~N[2020-02-16 16:15:33], name: nil, onboarding_state: "converted", organization_memberships: #Ecto.Association.NotLoaded<association :organization_memberships is not loaded>, organizations: #Ecto.Association.NotLoaded<association :organizations is not loaded>, password: nil, password_hash: nil, role_state: "user", unconfirmed_email: "kurtis@difference-engineers.org", updated_at: ~N[2020-02-16 16:15:33], username: nil}, account_id: "65880220-e39b-450d-ba7f-0642bea8dbc8", game_acts: #Ecto.Association.NotLoaded<association :game_acts is not loaded>, game_robot: nil, game_robot_id: nil, game_table: %Kempelen.Models.GameTable{__meta__: #Ecto.Schema.Metadata<:loaded, "game_tables">, game: %Kempelen.Models.Game{__meta__: #Ecto.Schema.Metadata<:loaded, "games">, game_plays: #Ecto.Association.NotLoaded<association :game_plays is not loaded>, game_tables: #Ecto.Association.NotLoaded<association :game_tables is not loaded>, id: "31eee3b8-b43c-411a-8528-479269c63d2d", inserted_at: ~N[2020-02-16 16:15:33], name: "Settlers of Catan", organization: %Kempelen.Models.Organization{__meta__: #Ecto.Schema.Metadata<:loaded, "organizations">, accounts: #Ecto.Association.NotLoaded<association :accounts is not loaded>, games: #Ecto.Association.NotLoaded<association :games is not loaded>, id: "3311c337-f480-4292-9582-c45f249730b2", inserted_at: ~N[2020-02-16 16:15:32], name: "Hasbro", organization_memberships: #Ecto.Association.NotLoaded<association :organization_memberships is not loaded>, robots: #Ecto.Association.NotLoaded<association :robots is not loaded>, slug: "hasbro", updated_at: ~N[2020-02-16 16:15:32]}, organization_id: "3311c337-f480-4292-9582-c45f249730b2", slug: "settlers-of-catan", updated_at: ~N[2020-02-16 16:15:33]}, game_id: "31eee3b8-b43c-411a-8528-479269c63d2d", game_players: #Ecto.Association.NotLoaded<association :game_players is not loaded>, game_rounds: #Ecto.Association.NotLoaded<association :game_rounds is not loaded>, id: "2cda5e3c-c57d-4117-a541-0c6a409984b6", inserted_at: ~N[2020-02-16 16:15:33], name: "FFA", slug: "ffa", updated_at: ~N[2020-02-16 16:15:33]}, game_table_id: "2cda5e3c-c57d-4117-a541-0c6a409984b6", host: true, id: "591227e6-3ea0-4f3f-8a44-471d7073c2df", inserted_at: ~N[2020-02-16 16:15:33], name: "Kurtis", slug: "kurtis", updated_at: ~N[2020-02-16 16:15:33]}` is missing primary key value

Here's are the models:

defmodule Kempelen.Models.GameAct do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "game_acts" do
    belongs_to :game_play, Kempelen.Models.GamePlay, primary_key: true
    belongs_to :game_player, Kempelen.Models.GamePlayer, primary_key: true
    belongs_to :game_round, Kempelen.Models.GameRound, primary_key: true

    timestamps()
  end

  @doc false
  def changeset(%{} = record, attributes \\ %{}) do
    record
    |> cast(attributes, [])
    |> validate_required([])
    |> assoc_constraint(:game_play)
    |> assoc_constraint(:game_player)
    |> assoc_constraint(:game_round)
    |> put_assoc(:game_play, attributes.game_play)
    |> put_assoc(:game_player, attributes.game_player)
    |> put_assoc(:game_round, attributes.game_round)
  end
end

defmodule Kempelen.Models.GamePlayer do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "game_players" do
    field :name, :string
    field :slug, Kempelen.Slugs.Name.Type
    field :host, :boolean, default: false
    belongs_to :game_table, Kempelen.Models.GameTable, primary_key: true
    belongs_to :account, Kempelen.Models.Account, primary_key: true
    belongs_to :game_robot, Kempelen.Models.GameRobot, primary_key: true
    has_many :game_acts, Kempelen.Models.GameAct

    timestamps()
  end

  @doc false
  def changeset(%{} = record, attributes \\ %{}) do
    record
      |> cast(attributes, [:name, :host])
      |> validate_required([:name, :host])
      |> assoc_constraint(:game_table)
      |> assoc_constraint(:account)
      |> assoc_constraint(:game_robot)
      |> Kempelen.Slugs.Name.maybe_generate_slug
      |> Kempelen.Slugs.Name.unique_constraint
      |> put_assoc(:game_robot, attributes[:game_robot])
      |> put_assoc(:account, attributes[:account])
      |> put_assoc(:game_table, attributes.game_table)
  end
end

It's not just the game_play model either, it also happens of the game_player.

The changeset appears to think it's valid, as well:

#Ecto.Changeset<
  action: nil,
  changes: %{
    game_play: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
     data: #Kempelen.Models.GamePlay<>, valid?: true>,
    game_player: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
     data: #Kempelen.Models.GamePlayer<>, valid?: true>,
    game_round: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
     data: #Kempelen.Models.GameRound<>, valid?: true>
  },
  errors: [],
  data: #Kempelen.Models.GameAct<>,
  valid?: true
>


来源: stackexchange

问:
Loop colnames basis a vector pattern
I wish to filter basis column names basis a vector and subsequently bind them together.

This is my data frame -

```<code>df = data.frame("Applefor_yes" = 1:4,
                "Applefor_no" = 2:5,
                "Bananfor_yes" = 1:4,
                "Bananfor_no" = 2:5)

   Applefor_yes Applefor_no Bananfor_yes Bananfor_no
1            1           2            1           2
2            2           3            2           3
3            3           4            3           4
4            4           5            4           5
</code>```

I want the output to look like this.

```<code>     fruit yes no
1 Applefor   1  2
2 Applefor   2  3
3 Applefor   3  4
4 Applefor   4  5
5 Bananfor   1  2
6 Bananfor   2  3
7 Bananfor   3  4
8 Bananfor   4  5
</code>```

In short, I want to loop the column names basis a vector c("Bananfor", "Applefor")

答:
Here is a base R solution

```<code>pat <- c("yes","no")
u <- data.frame(setNames(lapply(pat, function(x) unlist(subset(df,select = grep(x,names(df))))),pat))
dfout <- data.frame(fruit = gsub("_.*","",rownames(u)),u,row.names = NULL)
</code>```

or

```<code>dfout <- do.call(rbind,
                 c(make.row.names = F,
                   Map(function(x) data.frame(fruit = gsub("_.*","",names(x)),
                                              setNames(x,gsub(".*_","",names(x)))),
                       split(unclass(df),gsub("(.*)_.*","\\1",names(df))))))
</code>```

such that

```<code>> dfout
     fruit yes no
1 Applefor   1  2
2 Applefor   2  3
3 Applefor   3  4
4 Applefor   4  5
5 Bananfor   1  2
6 Bananfor   2  3
7 Bananfor   3  4
8 Bananfor   4  5
</code>```

ContentLicense: CC BY-SA 4.0

Title: Loop colnames basis a vector pattern

Body:
I wish to filter basis column names basis a vector and subsequently bind them together.

This is my data frame -

df = data.frame("Applefor_yes" = 1:4,
                "Applefor_no" = 2:5,
                "Bananfor_yes" = 1:4,
                "Bananfor_no" = 2:5)

   Applefor_yes Applefor_no Bananfor_yes Bananfor_no
1            1           2            1           2
2            2           3            2           3
3            3           4            3           4
4            4           5            4           5

I want the output to look like this.

     fruit yes no
1 Applefor   1  2
2 Applefor   2  3
3 Applefor   3  4
4 Applefor   4  5
5 Bananfor   1  2
6 Bananfor   2  3
7 Bananfor   3  4
8 Bananfor   4  5

In short, I want to loop the column names basis a vector c("Bananfor", "Applefor")

Body:
Here is a base R solution

pat <- c("yes","no")
u <- data.frame(setNames(lapply(pat, function(x) unlist(subset(df,select = grep(x,names(df))))),pat))
dfout <- data.frame(fruit = gsub("_.*","",rownames(u)),u,row.names = NULL)

or

dfout <- do.call(rbind,
                 c(make.row.names = F,
                   Map(function(x) data.frame(fruit = gsub("_.*","",names(x)),
                                              setNames(x,gsub(".*_","",names(x)))),
                       split(unclass(df),gsub("(.*)_.*","\\1",names(df))))))

such that

> dfout
     fruit yes no
1 Applefor   1  2
2 Applefor   2  3
3 Applefor   3  4
4 Applefor   4  5
5 Bananfor   1  2
6 Bananfor   2  3
7 Bananfor   3  4
8 Bananfor   4  5


问:
Converting C# Objects to Json format
(Edited) My asp.net core version is 2.0

I am new to programming.
I am currently trying to call Microsoft Graph to list all of the application objects in my Azure AD tenant and save them JSON files.

I am using the Microsoft Graph SDK. When I make the call, the results comes back as a collection of Microsoft.Graph.Application objects but I can't convert them to JSON.

I've tried to convert the result using .ToString(), but each object just becomes "Microsoft.Graph.Application".

Is there a good way to do this?

```<code>IConfidentialClientApplication daemonClient = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithClientSecret(clientSecret)
    .WithTenantId(tenantId)
    .Build();

ClientCredentialProvider authProvider = new ClientCredentialProvider(daemonClient);
GraphServiceClient graphServiceClient = new GraphServiceClient(authProvider);
GetApplicationList(graphServiceClient, log).GetAwaiter().GetResult();

var applicationList = await graphServiceClient.Applications.Request().GetAsync();
</code>```

答:
You didn't write which version of asp .net core you use.

In version 2.0 Json Newtonsoft library is used to handle json serialization/deserialization.

```<code>Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
//   "Name": "Apple",
//   "Expiry": "2008-12-28T00:00:00",
//   "Sizes": [
//     "Small"
//   ]
// }
</code>```

In version 3.0 has been introduced new default library for handling json operations System.Text.Json, but you can change configuration to still use Newtonsoft. Example usage of the System.Text.Json.

```<code>string jsonString;
jsonString = JsonSerializer.Serialize(weatherForecast);
// {
//  "Date": "2019-08-01T00:00:00-07:00",
//  "TemperatureCelsius": 25,
//  "Summary": "Hot",
//  "DatesAvailable": ["2019-08-01T00:00:00-07:00",
//  "2019-08-02T00:00:00-07:00"],
//  "TemperatureRanges": {
//      "Cold": {
//          "High": 20,
//          "Low": -10
//      },
//      "Hot": {
//          "High": 60,
//          "Low": 20
//      }
//  },
//  "SummaryWords": ["Cool",
//  "Windy",
//  "Humid"]
// }
</code>```

Title: Converting C# Objects to Json format

Body:
(Edited) My asp.net core version is 2.0

I am new to programming.
I am currently trying to call Microsoft Graph to list all of the application objects in my Azure AD tenant and save them JSON files.

I am using the Microsoft Graph SDK. When I make the call, the results comes back as a collection of Microsoft.Graph.Application objects but I can't convert them to JSON.

I've tried to convert the result using .ToString(), but each object just becomes "Microsoft.Graph.Application".

Is there a good way to do this?

IConfidentialClientApplication daemonClient = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithClientSecret(clientSecret)
    .WithTenantId(tenantId)
    .Build();

ClientCredentialProvider authProvider = new ClientCredentialProvider(daemonClient);
GraphServiceClient graphServiceClient = new GraphServiceClient(authProvider);
GetApplicationList(graphServiceClient, log).GetAwaiter().GetResult();

var applicationList = await graphServiceClient.Applications.Request().GetAsync();

Body:
You didn't write which version of asp .net core you use.

In version 2.0 Json Newtonsoft library is used to handle json serialization/deserialization.

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
//   "Name": "Apple",
//   "Expiry": "2008-12-28T00:00:00",
//   "Sizes": [
//     "Small"
//   ]
// }

In version 3.0 has been introduced new default library for handling json operations System.Text.Json, but you can change configuration to still use Newtonsoft. Example usage of the System.Text.Json.

string jsonString;
jsonString = JsonSerializer.Serialize(weatherForecast);
// {
//  "Date": "2019-08-01T00:00:00-07:00",
//  "TemperatureCelsius": 25,
//  "Summary": "Hot",
//  "DatesAvailable": ["2019-08-01T00:00:00-07:00",
//  "2019-08-02T00:00:00-07:00"],
//  "TemperatureRanges": {
//      "Cold": {
//          "High": 20,
//          "Low": -10
//      },
//      "Hot": {
//          "High": 60,
//          "Low": 20
//      }
//  },
//  "SummaryWords": ["Cool",
//  "Windy",
//  "Humid"]
// }


问:
Rails 3 complex associations using nested_has_many_through
I have been trying to develop a movie based rails application which has support for multiple regions (Hollywood, Bollywood etc). I call the multiple regions as languages in the application.

Each language has its own set of data i.e., english has all the movies related to hollywood and language hindi has all the movies related to bollywood.

Language Model

```<code>class Language < ActiveRecord::Base
  has_many :movies
  has_many :cast_and_crews, :through => :movies, :uniq => true
  has_many :celebrities, :through => :cast_and_crews, :uniq => true

  # FIXME: Articles for celebrities and movies
  has_many :article_associations, :through => :celebrities
  has_many :articles, :through => :article_associations, :uniq => true
end
</code>```

Here movies and celebrities both have articles using the article_association class.

Movie Model

```<code>class Movie < ActiveRecord::Base
  belongs_to :language
  has_many :cast_and_crews
  has_many :celebrities, :through => :cast_and_crews
  has_many :article_associations
  has_many :articles, :through => :article_associations, :uniq => true
end
</code>```

Celebrity Model

```<code>class Celebrity < ActiveRecord::Base
  has_many :cast_and_crews
  has_many :movies, :through => :cast_and_crews, :uniq => true
  has_many :article_associations
  has_many :articles, :through => :article_associations, :uniq => true
end

class ArticleAssociation < ActiveRecord::Base
  belongs_to :article
  belongs_to :celebrity
  belongs_to :movie
end
</code>```

and this is how my Article model is defined

```<code>class Article < ActiveRecord::Base
  has_many :article_associations
  has_many :celebrities, :through => :article_associations
  has_many :movies, :through => :article_associations
end
</code>```

What I am trying to achieve is language.article should return all the articles related to celebrities and movies.

The reason why I am not using SQL is find_by_sql does not support ActiveRelation and I will not be able use has_scope functionality.

I am using nested_has_many_through, has_scope and inherited_resources gems

Any help in this will be greatly appreciated.

答:
There are few tricks that should allow what you need, going out of Article you can query all the Moviesfor given language id

```<code>class Article < ActiveRecord::Base
  has_many :article_associations
  has_many :celebrities, :through => :article_associations
  has_many :article_movies, :through => :article_associations, :class => 'Movie'
  scope :for_language, lambda {|lang_id|
    joins(
      :article_associations=>[
        :article_movies,
        {:celebrities => { :cast_and_crews => :movies } }
      ]
    ).where(
      'movies.language_id = ? OR article_movies.language_id = ?',
      lang_id, lang_id
    )
  }
end
</code>```

Then in language define a method that will use earlier scope of Article

```<code>class Language < ActiveRecord::Base
  has_many :movies
  has_many :cast_and_crews, :through => :movies, :uniq => true
  has_many :celebrities, :through => :cast_and_crews, :uniq => true

  def articles
    Article.for_language id
  end
end
</code>```

The only unsure part here is how :article_movies will be represented in sql ...

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to develop a movie based rails application which has support for multiple regions (Hollywood, Bollywood etc). I call the multiple regions as languages in the application.

Each language has its own set of data i.e., english has all the movies related to hollywood and language hindi has all the movies related to bollywood.

Language Model

class Language < ActiveRecord::Base
  has_many :movies
  has_many :cast_and_crews, :through => :movies, :uniq => true
  has_many :celebrities, :through => :cast_and_crews, :uniq => true

  # FIXME: Articles for celebrities and movies
  has_many :article_associations, :through => :celebrities
  has_many :articles, :through => :article_associations, :uniq => true
end

Here movies and celebrities both have articles using the article_association class.

Movie Model

class Movie < ActiveRecord::Base
  belongs_to :language
  has_many :cast_and_crews
  has_many :celebrities, :through => :cast_and_crews
  has_many :article_associations
  has_many :articles, :through => :article_associations, :uniq => true
end

Celebrity Model

class Celebrity < ActiveRecord::Base
  has_many :cast_and_crews
  has_many :movies, :through => :cast_and_crews, :uniq => true
  has_many :article_associations
  has_many :articles, :through => :article_associations, :uniq => true
end

class ArticleAssociation < ActiveRecord::Base
  belongs_to :article
  belongs_to :celebrity
  belongs_to :movie
end

and this is how my Article model is defined

class Article < ActiveRecord::Base
  has_many :article_associations
  has_many :celebrities, :through => :article_associations
  has_many :movies, :through => :article_associations
end

What I am trying to achieve is language.article should return all the articles related to celebrities and movies.

The reason why I am not using SQL is find_by_sql does not support ActiveRelation and I will not be able use has_scope functionality.

I am using nested_has_many_through, has_scope and inherited_resources gems

Any help in this will be greatly appreciated.

Body:
There are few tricks that should allow what you need, going out of Article you can query all the Moviesfor given language id

class Article < ActiveRecord::Base
  has_many :article_associations
  has_many :celebrities, :through => :article_associations
  has_many :article_movies, :through => :article_associations, :class => 'Movie'
  scope :for_language, lambda {|lang_id|
    joins(
      :article_associations=>[
        :article_movies,
        {:celebrities => { :cast_and_crews => :movies } }
      ]
    ).where(
      'movies.language_id = ? OR article_movies.language_id = ?',
      lang_id, lang_id
    )
  }
end

Then in language define a method that will use earlier scope of Article

class Language < ActiveRecord::Base
  has_many :movies
  has_many :cast_and_crews, :through => :movies, :uniq => true
  has_many :celebrities, :through => :cast_and_crews, :uniq => true

  def articles
    Article.for_language id
  end
end

The only unsure part here is how :article_movies will be represented in sql ...


问:
Get Visual Studio to run a T4 Template on every build
How do I get a T4 template to generate its output on every build?  As it is now, it only regenerates it when I make a change to the template.

I have found other questions similar to this:

T4 transformation and build order in Visual Studio (unanswered)

How to get t4 files to build in visual studio? (answers are not detailed enough [while still being plenty complicated] and don't even make total sense)

There has got to be a simpler way to do this!

答:
Here's a pre-build event using only Microsoft Tooling and standard paths. It's tested in vs2019/netcore3.1.

Replace "AppDbContext.tt" with your project-relative file path:

```<code>"$(MSBuildBinPath)\msbuild" "$(SolutionPath)" /t:$(ProjectName):Transform /p:TransformFile="AppDbContext.tt" /p:CustomAfterMicrosoftCommonTargets="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TextTemplating\Microsoft.TextTemplating.targets"
</code>```

Microsoft also has a guide to make macros like "$(SolutionDirectory)" available in the template by using T4ParameterValues in your project file.

ContentLicense: CC BY-SA 2.5

Body:
Here's a pre-build event using only Microsoft Tooling and standard paths. It's tested in vs2019/netcore3.1.

Replace "AppDbContext.tt" with your project-relative file path:

"$(MSBuildBinPath)\msbuild" "$(SolutionPath)" /t:$(ProjectName):Transform /p:TransformFile="AppDbContext.tt" /p:CustomAfterMicrosoftCommonTargets="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TextTemplating\Microsoft.TextTemplating.targets"

Microsoft also has a guide to make macros like "$(SolutionDirectory)" available in the template by using T4ParameterValues in your project file.


问:
How to translate callbacks to kotlin
I need to make this request with Kotlin:

```<code>One one = One.getInstance(getApplicationContext());
one.sendInteraction("/interactionName", new GetCallback<ResponseObject>() {

    public void done(ResponseObject response, ThunderheadException e) {
        if (e == null) {
             // Success!
            one.processResponse(response);
        } else {
            // Failure!
        }
    }
});
</code>```

When I try to convert on Android Studio translator the code not fit well. I am a newbie with Kotlin, I tried some ways but always fail.
My problem it's with callback method

```<code>new GetCallback<ResponseObject>() { public void done(ResponseObject response, ThunderHeadException e){...}}`
</code>```

Could you help me to find the way to do it in Kotlin?

答:
When the callback has only one method, you can treat it like a lambda:</p>

```<code>one.sendInteraction("/interactionName") { response, e ->
    if (e == null) {
         // Success!
        one.processResponse(response);
    } else {
        // Failure!
    }
}
</code>```

Title: How to translate callbacks to kotlin

Body:
I need to make this request with Kotlin:

One one = One.getInstance(getApplicationContext());
one.sendInteraction("/interactionName", new GetCallback<ResponseObject>() {

    public void done(ResponseObject response, ThunderheadException e) {
        if (e == null) {
             // Success!
            one.processResponse(response);
        } else {
            // Failure!
        }
    }
});

When I try to convert on Android Studio translator the code not fit well. I am a newbie with Kotlin, I tried some ways but always fail.
My problem it's with callback method

new GetCallback<ResponseObject>() { public void done(ResponseObject response, ThunderHeadException e){...}}`

Could you help me to find the way to do it in Kotlin?

Body:
When the callback has only one method, you can treat it like a lambda:

one.sendInteraction("/interactionName") { response, e ->
    if (e == null) {
         // Success!
        one.processResponse(response);
    } else {
        // Failure!
    }
}


问:
IBM liberty datasource taking too much time (after AWS RDS failover)
I have configured the datasource with oracle connection details like below.

```<code><dataSource id="auditLogDatasource" jndiName="jdbc/audit_log" type="javax.sql.DataSource" validationTimeout="10s">
        <jdbcDriver libraryRef="OracleLib"/>

        <properties.oracle description="main db pipe" URL="jdbc:oracle:thin://@localhost:1686/mkapp"
                           password="test" user="test"/>
        <connectionManager id="ConnectionManager"
                           maxPoolSize="30" minPoolSize="1" purgePolicy="FailingConnectionOnly" />
</dataSource>
</code>```

Java code

```<code>@Resource(lookup = "jdbc/audit_log")
public void setDataSource(DataSource dataSource) {
    if (this.dataSource == null) {
        this.dataSource = dataSource;
    }
}

public void store(@Observes AuditRecord auditRecord) {
    Connection con = null;
    PreparedStatement preparedStatement = null;
    try {
        log.info("DB connection requested");
        con = this.dataSource.getConnection();
        preparedStatement = con.prepareStatement(INSERT_QUERY);
        int index = 1;
        preparedStatement.setString(index++, auditRecord.getAction());
        preparedStatement.setString(index++, auditRecord.getUserInitiating());
        preparedStatement.setString(index++, auditRecord.getUserAffected());
        preparedStatement.setString(index++, auditRecord.getAdditionalInfo());
        preparedStatement.setTimestamp(index++, new Timestamp(auditRecord.getCreateTime().getTime()));
        preparedStatement.setString(index++, auditRecord.getServer());
        preparedStatement.executeUpdate();
        log.info("DB record added");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    } finally {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}
</code>```

Initially everything working fine mostly I am seeing only 1 Free connection count.

But once I trigger AWS RDS failover (Reboot with failover) server
  taking too much time to discard the invalid connection from pool & creating new connection.

```<code>2019/11/15 17:31:28.571 [Default Executor-thread-60] INFO dao.AuditDao : DB connection requested
2019/11/15 17:47:03.741 [Default Executor-thread-60] INFO dao.AuditDao : DB record added
</code>```

error in message.log after 16 min

```<code>[ERROR   ] J2CA0081E: Method destroy failed while trying to execute method destroy on ManagedConnection WSRdbManagedConnectionImpl@10e0477e from resource No longer available. Caught exception: com.ibm.ws.rsadapter.exceptions.DataStoreAdapterException: DSRA0080E: An exception was received by the Data Store Adapter. See original exception message: {0}. with SQL State : 08000 SQL Code : 17410
    at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.destroy(WSRdbManagedConnectionImpl.java:2513)
    at [internal classes]
    at com.test.auth.dao.AuditDao.store(AuditDao.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:88)
    at [internal classes]
    at com.test.auth.AuthHomeServlet.audit(AuthHomeServlet.java:72)
    at com.test.auth.AuthHomeServlet.doPost(AuthHomeServlet.java:37)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1255)
    at [internal classes]
    at com.test.auth.UserPrincipalFilter.doFilter(MkidUserPrincipalFilter.java:38)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:201)
    at [internal classes]
Caused by: java.sql.SQLRecoverableException: No more data to read from socket DSRA0010E: SQL State = 08000, Error Code = 17,410
    at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1157)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:350)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
    at oracle.jdbc.driver.T4C7Ocommoncall.doOLOGOFF(T4C7Ocommoncall.java:61)
    at oracle.jdbc.driver.T4CConnection.logoff(T4CConnection.java:574)
    at oracle.jdbc.driver.PhysicalConnection.close(PhysicalConnection.java:4011)
    at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.destroy(WSRdbManagedConnectionImpl.java:2508)
    ... 17 more
</code>```

Is there any way that I can configure the connection close timeout ? though I configured the validationTimeout seems like it is not working.

```<code>Liberty version: 17.0.0.4
Database product version : Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
JDBC driver version  : 12.1.0.2.0
Driver lib: ojdbc6.jar / ojdbc7.jar
</code>```

Is it related to DNS issue? Can anyone point me to right direction...

UPDATE

This is what I got from thread dump

```<code>Default Executor-thread-29" #87 daemon prio=5 os_prio=31 tid=0x00007fa06793d800 nid=0x13d03 waiting for monitor entry [0x0000700012743000]
   java.lang.Thread.State: BLOCKED (on object monitor)
    at oracle.jdbc.driver.PhysicalConnection.isProxySession(PhysicalConnection.java:4398)
    - waiting to lock <0x00000007bd6d0900> (a oracle.jdbc.driver.T4CConnection)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.ibm.ws.rsadapter.impl.OracleHelper.doConnectionCleanup(OracleHelper.java:354)
    at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.cleanupStates(WSRdbManagedConnectionImpl.java:2847)
    at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.cleanup(WSRdbManagedConnectionImpl.java:2774)
    at com.ibm.ejs.j2c.MCWrapper.cleanup(MCWrapper.java:1541)
    at com.ibm.ejs.j2c.FreePool.cleanupAndDestroyMCWrapper(FreePool.java:459)
    at com.ibm.ejs.j2c.PoolManager.reserve(PoolManager.java:1602)
    at com.ibm.ejs.j2c.ConnectionManager.allocateMCWrapper(ConnectionManager.java:581)
    at com.ibm.ejs.j2c.ConnectionManager.allocateConnection(ConnectionManager.java:314)
    at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:138)
    at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:112)
    at test.dao.AuditDao.store(AuditDao.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:88)
    at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:78)
    at org.jboss.weld.injection.MethodInvocationStrategy$SimpleMethodInvocationStrategy.invoke(MethodInvocationStrategy.java:129)
    at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:299)
    at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:277)
    at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:255)
    at org.jboss.weld.event.ObserverNotifier.notifySyncObservers(ObserverNotifier.java:269)
    at org.jboss.weld.event.ObserverNotifier.notify(ObserverNotifier.java:258)
    at org.jboss.weld.event.EventImpl.fire(EventImpl.java:92)
    at test.AuthHomeServlet.audit(AuthHomeServlet.java:72)
    at test.AuthHomeServlet.doPost(AuthHomeServlet.java:37)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1230)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:729)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:426)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:182)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:93)
    at test.MkidUserPrincipalFilter.doFilter(MkidUserPrincipalFilter.java:38)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:201)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:90)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:1001)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1139)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1010)
    at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:75)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:938)
    at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.run(DynamicVirtualHost.java:279)
    at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink$TaskWrapper.run(HttpDispatcherLink.java:1136)
    at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.wrapHandlerAndExecute(HttpDispatcherLink.java:417)
    at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.ready(HttpDispatcherLink.java:376)
    at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:548)
    at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleNewRequest(HttpInboundLink.java:482)
    at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.processRequest(HttpInboundLink.java:347)
    at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.ready(HttpInboundLink.java:318)
    at com.ibm.ws.channel.ssl.internal.SSLConnectionLink.determineNextChannel(SSLConnectionLink.java:1077)
    at com.ibm.ws.channel.ssl.internal.SSLConnectionLink$MyReadCompletedCallback.complete(SSLConnectionLink.java:656)
    at com.ibm.ws.channel.ssl.internal.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1803)
    at com.ibm.ws.tcpchannel.internal.WorkQueueManager.requestComplete(WorkQueueManager.java:503)
    at com.ibm.ws.tcpchannel.internal.WorkQueueManager.attemptIO(WorkQueueManager.java:573)
    at com.ibm.ws.tcpchannel.internal.WorkQueueManager.workerRun(WorkQueueManager.java:954)
    at com.ibm.ws.tcpchannel.internal.WorkQueueManager$Worker.run(WorkQueueManager.java:1043)
    at com.ibm.ws.threading.internal.ExecutorServiceImpl$RunnableWrapper.run(ExecutorServiceImpl.java:239)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

   Locked ownable synchronizers:
    - <0x00000007822c8b38> (a java.util.concurrent.ThreadPoolExecutor$Worker)
</code>```

From requestTiming feature

```<code>[11/17/19 20:03:22:442 AEDT] 000000ee com.ibm.ws.request.timing.manager.SlowRequestManager         W TRAS0112W: Request AAAcI1bXZti_AAAAAAAAAAD has been running on thread 000000df for at least 30016.328ms. The following stack trace shows what this thread is currently running.

     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
     at java.lang.reflect.Method.invoke(Method.java:508)
     at com.ibm.ws.rsadapter.impl.OracleHelper.doConnectionCleanup(OracleHelper.java:355)
     at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.cleanupStates(WSRdbManagedConnectionImpl.java:2752)
     at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.cleanup(WSRdbManagedConnectionImpl.java:2679)
     at com.ibm.ejs.j2c.MCWrapper.cleanup(MCWrapper.java:1492)
     at com.ibm.ejs.j2c.FreePool.cleanupAndDestroyMCWrapper(FreePool.java:444)
     at com.ibm.ejs.j2c.PoolManager.reserve(PoolManager.java:1543)
     at com.ibm.ejs.j2c.ConnectionManager.allocateMCWrapper(ConnectionManager.java:547)
     at com.ibm.ejs.j2c.ConnectionManager.allocateConnection(ConnectionManager.java:283)
     at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:143)
     at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:116)
     at com.testt.auth.dao.AuditDao.store(AuditDao.java:37)
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
     at java.lang.reflect.Method.invoke(Method.java:508)
     at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:88)
     at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:78)
     at org.jboss.weld.injection.MethodInvocationStrategy$SimpleMethodInvocationStrategy.invoke(MethodInvocationStrategy.java:129)
     at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:299)
     at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:277)
     at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:255)
     at org.jboss.weld.event.ObserverNotifier.notifySyncObservers(ObserverNotifier.java:269)
     at org.jboss.weld.event.ObserverNotifier.notify(ObserverNotifier.java:258)
     at org.jboss.weld.event.EventImpl.fire(EventImpl.java:91)
     at com.test.auth.AuthHomeServlet.audit(AuthHomeServlet.java:72)
     at com.test.auth.AuthHomeServlet.doPost(AuthHomeServlet.java:37)
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
     at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1255)
     at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:743)
     at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:440)
     at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:147)
     at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:89)
     at com.test.auth.MkidUserPrincipalFilter.doFilter(MkidUserPrincipalFilter.java:38)
     at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:201)
     at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:86)
     at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:995)
     at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1124)
     at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1004)
     at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:76)
     at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:926)
     at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.run(DynamicVirtualHost.java:279)
     at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink$TaskWrapper.run(HttpDispatcherLink.java:957)
     at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.wrapHandlerAndExecute(HttpDispatcherLink.java:357)
     at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.ready(HttpDispatcherLink.java:316)
     at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:499)
     at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleNewRequest(HttpInboundLink.java:433)
     at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.processRequest(HttpInboundLink.java:313)
     at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.ready(HttpInboundLink.java:284)
     at com.ibm.ws.channel.ssl.internal.SSLConnectionLink.determineNextChannel(SSLConnectionLink.java:1029)
     at com.ibm.ws.channel.ssl.internal.SSLConnectionLink.readyInboundPostHandshake(SSLConnectionLink.java:695)
     at com.ibm.ws.channel.ssl.internal.SSLConnectionLink$MyHandshakeCompletedCallback.complete(SSLConnectionLink.java:383)
     at com.ibm.ws.channel.ssl.internal.SSLUtils.handleHandshake(SSLUtils.java:947)
     at com.ibm.ws.channel.ssl.internal.SSLHandshakeIOCallback.complete(SSLHandshakeIOCallback.java:85)
     at com.ibm.ws.tcpchannel.internal.WorkQueueManager.requestComplete(WorkQueueManager.java:501)
     at com.ibm.ws.tcpchannel.internal.WorkQueueManager.attemptIO(WorkQueueManager.java:571)
     at com.ibm.ws.tcpchannel.internal.WorkQueueManager.workerRun(WorkQueueManager.java:926)
     at com.ibm.ws.tcpchannel.internal.WorkQueueManager$Worker.run(WorkQueueManager.java:1015)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1153)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
     at java.lang.Thread.run(Thread.java:785)

The following table shows the events that have run during this request.

Duration      Operation
30018.682ms + websphere.servlet.service | auth | authHomeServlet
</code>```

答: After switching to Oracle UCP, this issue disappeared as it has timeout on connection validation (15 sec). I posted this issue on Openliberty github, hope it will be fixed in future releases.</p>

Body:
I have configured the datasource with oracle connection details like below.

<dataSource id="auditLogDatasource" jndiName="jdbc/audit_log" type="javax.sql.DataSource" validationTimeout="10s">
        <jdbcDriver libraryRef="OracleLib"/>

        <properties.oracle description="main db pipe" URL="jdbc:oracle:thin://@localhost:1686/mkapp"
                           password="test" user="test"/>
        <connectionManager id="ConnectionManager"
                           maxPoolSize="30" minPoolSize="1" purgePolicy="FailingConnectionOnly" />
</dataSource>

Java code

@Resource(lookup = "jdbc/audit_log")
public void setDataSource(DataSource dataSource) {
    if (this.dataSource == null) {
        this.dataSource = dataSource;
    }
}

public void store(@Observes AuditRecord auditRecord) {
    Connection con = null;
    PreparedStatement preparedStatement = null;
    try {
        log.info("DB connection requested");
        con = this.dataSource.getConnection();
        preparedStatement = con.prepareStatement(INSERT_QUERY);
        int index = 1;
        preparedStatement.setString(index++, auditRecord.getAction());
        preparedStatement.setString(index++, auditRecord.getUserInitiating());
        preparedStatement.setString(index++, auditRecord.getUserAffected());
        preparedStatement.setString(index++, auditRecord.getAdditionalInfo());
        preparedStatement.setTimestamp(index++, new Timestamp(auditRecord.getCreateTime().getTime()));
        preparedStatement.setString(index++, auditRecord.getServer());
        preparedStatement.executeUpdate();
        log.info("DB record added");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    } finally {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}

Initially everything working fine mostly I am seeing only 1 Free connection count.

But once I trigger AWS RDS failover (Reboot with failover) server
  taking too much time to discard the invalid connection from pool & creating new connection.

2019/11/15 17:31:28.571 [Default Executor-thread-60] INFO dao.AuditDao : DB connection requested
2019/11/15 17:47:03.741 [Default Executor-thread-60] INFO dao.AuditDao : DB record added

error in message.log after 16 min

[ERROR   ] J2CA0081E: Method destroy failed while trying to execute method destroy on ManagedConnection WSRdbManagedConnectionImpl@10e0477e from resource No longer available. Caught exception: com.ibm.ws.rsadapter.exceptions.DataStoreAdapterException: DSRA0080E: An exception was received by the Data Store Adapter. See original exception message: {0}. with SQL State : 08000 SQL Code : 17410
    at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.destroy(WSRdbManagedConnectionImpl.java:2513)
    at [internal classes]
    at com.test.auth.dao.AuditDao.store(AuditDao.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:88)
    at [internal classes]
    at com.test.auth.AuthHomeServlet.audit(AuthHomeServlet.java:72)
    at com.test.auth.AuthHomeServlet.doPost(AuthHomeServlet.java:37)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1255)
    at [internal classes]
    at com.test.auth.UserPrincipalFilter.doFilter(MkidUserPrincipalFilter.java:38)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:201)
    at [internal classes]
Caused by: java.sql.SQLRecoverableException: No more data to read from socket DSRA0010E: SQL State = 08000, Error Code = 17,410
    at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1157)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:350)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
    at oracle.jdbc.driver.T4C7Ocommoncall.doOLOGOFF(T4C7Ocommoncall.java:61)
    at oracle.jdbc.driver.T4CConnection.logoff(T4CConnection.java:574)
    at oracle.jdbc.driver.PhysicalConnection.close(PhysicalConnection.java:4011)
    at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.destroy(WSRdbManagedConnectionImpl.java:2508)
    ... 17 more

Is there any way that I can configure the connection close timeout ? though I configured the validationTimeout seems like it is not working.

Liberty version: 17.0.0.4
Database product version : Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
JDBC driver version  : 12.1.0.2.0
Driver lib: ojdbc6.jar / ojdbc7.jar

Is it related to DNS issue? Can anyone point me to right direction...

UPDATE

This is what I got from thread dump

Default Executor-thread-29" #87 daemon prio=5 os_prio=31 tid=0x00007fa06793d800 nid=0x13d03 waiting for monitor entry [0x0000700012743000]
   java.lang.Thread.State: BLOCKED (on object monitor)
    at oracle.jdbc.driver.PhysicalConnection.isProxySession(PhysicalConnection.java:4398)
    - waiting to lock <0x00000007bd6d0900> (a oracle.jdbc.driver.T4CConnection)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.ibm.ws.rsadapter.impl.OracleHelper.doConnectionCleanup(OracleHelper.java:354)
    at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.cleanupStates(WSRdbManagedConnectionImpl.java:2847)
    at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.cleanup(WSRdbManagedConnectionImpl.java:2774)
    at com.ibm.ejs.j2c.MCWrapper.cleanup(MCWrapper.java:1541)
    at com.ibm.ejs.j2c.FreePool.cleanupAndDestroyMCWrapper(FreePool.java:459)
    at com.ibm.ejs.j2c.PoolManager.reserve(PoolManager.java:1602)
    at com.ibm.ejs.j2c.ConnectionManager.allocateMCWrapper(ConnectionManager.java:581)
    at com.ibm.ejs.j2c.ConnectionManager.allocateConnection(ConnectionManager.java:314)
    at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:138)
    at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:112)
    at test.dao.AuditDao.store(AuditDao.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:88)
    at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:78)
    at org.jboss.weld.injection.MethodInvocationStrategy$SimpleMethodInvocationStrategy.invoke(MethodInvocationStrategy.java:129)
    at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:299)
    at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:277)
    at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:255)
    at org.jboss.weld.event.ObserverNotifier.notifySyncObservers(ObserverNotifier.java:269)
    at org.jboss.weld.event.ObserverNotifier.notify(ObserverNotifier.java:258)
    at org.jboss.weld.event.EventImpl.fire(EventImpl.java:92)
    at test.AuthHomeServlet.audit(AuthHomeServlet.java:72)
    at test.AuthHomeServlet.doPost(AuthHomeServlet.java:37)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1230)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:729)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:426)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:182)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:93)
    at test.MkidUserPrincipalFilter.doFilter(MkidUserPrincipalFilter.java:38)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:201)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:90)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:1001)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1139)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1010)
    at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:75)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:938)
    at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.run(DynamicVirtualHost.java:279)
    at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink$TaskWrapper.run(HttpDispatcherLink.java:1136)
    at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.wrapHandlerAndExecute(HttpDispatcherLink.java:417)
    at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.ready(HttpDispatcherLink.java:376)
    at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:548)
    at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleNewRequest(HttpInboundLink.java:482)
    at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.processRequest(HttpInboundLink.java:347)
    at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.ready(HttpInboundLink.java:318)
    at com.ibm.ws.channel.ssl.internal.SSLConnectionLink.determineNextChannel(SSLConnectionLink.java:1077)
    at com.ibm.ws.channel.ssl.internal.SSLConnectionLink$MyReadCompletedCallback.complete(SSLConnectionLink.java:656)
    at com.ibm.ws.channel.ssl.internal.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1803)
    at com.ibm.ws.tcpchannel.internal.WorkQueueManager.requestComplete(WorkQueueManager.java:503)
    at com.ibm.ws.tcpchannel.internal.WorkQueueManager.attemptIO(WorkQueueManager.java:573)
    at com.ibm.ws.tcpchannel.internal.WorkQueueManager.workerRun(WorkQueueManager.java:954)
    at com.ibm.ws.tcpchannel.internal.WorkQueueManager$Worker.run(WorkQueueManager.java:1043)
    at com.ibm.ws.threading.internal.ExecutorServiceImpl$RunnableWrapper.run(ExecutorServiceImpl.java:239)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

   Locked ownable synchronizers:
    - <0x00000007822c8b38> (a java.util.concurrent.ThreadPoolExecutor$Worker)

From requestTiming feature

[11/17/19 20:03:22:442 AEDT] 000000ee com.ibm.ws.request.timing.manager.SlowRequestManager         W TRAS0112W: Request AAAcI1bXZti_AAAAAAAAAAD has been running on thread 000000df for at least 30016.328ms. The following stack trace shows what this thread is currently running.

     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
     at java.lang.reflect.Method.invoke(Method.java:508)
     at com.ibm.ws.rsadapter.impl.OracleHelper.doConnectionCleanup(OracleHelper.java:355)
     at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.cleanupStates(WSRdbManagedConnectionImpl.java:2752)
     at com.ibm.ws.rsadapter.impl.WSRdbManagedConnectionImpl.cleanup(WSRdbManagedConnectionImpl.java:2679)
     at com.ibm.ejs.j2c.MCWrapper.cleanup(MCWrapper.java:1492)
     at com.ibm.ejs.j2c.FreePool.cleanupAndDestroyMCWrapper(FreePool.java:444)
     at com.ibm.ejs.j2c.PoolManager.reserve(PoolManager.java:1543)
     at com.ibm.ejs.j2c.ConnectionManager.allocateMCWrapper(ConnectionManager.java:547)
     at com.ibm.ejs.j2c.ConnectionManager.allocateConnection(ConnectionManager.java:283)
     at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:143)
     at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:116)
     at com.testt.auth.dao.AuditDao.store(AuditDao.java:37)
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
     at java.lang.reflect.Method.invoke(Method.java:508)
     at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:88)
     at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:78)
     at org.jboss.weld.injection.MethodInvocationStrategy$SimpleMethodInvocationStrategy.invoke(MethodInvocationStrategy.java:129)
     at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:299)
     at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:277)
     at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:255)
     at org.jboss.weld.event.ObserverNotifier.notifySyncObservers(ObserverNotifier.java:269)
     at org.jboss.weld.event.ObserverNotifier.notify(ObserverNotifier.java:258)
     at org.jboss.weld.event.EventImpl.fire(EventImpl.java:91)
     at com.test.auth.AuthHomeServlet.audit(AuthHomeServlet.java:72)
     at com.test.auth.AuthHomeServlet.doPost(AuthHomeServlet.java:37)
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
     at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1255)
     at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:743)
     at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:440)
     at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:147)
     at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:89)
     at com.test.auth.MkidUserPrincipalFilter.doFilter(MkidUserPrincipalFilter.java:38)
     at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:201)
     at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:86)
     at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:995)
     at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1124)
     at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1004)
     at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:76)
     at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:926)
     at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.run(DynamicVirtualHost.java:279)
     at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink$TaskWrapper.run(HttpDispatcherLink.java:957)
     at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.wrapHandlerAndExecute(HttpDispatcherLink.java:357)
     at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.ready(HttpDispatcherLink.java:316)
     at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:499)
     at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleNewRequest(HttpInboundLink.java:433)
     at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.processRequest(HttpInboundLink.java:313)
     at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.ready(HttpInboundLink.java:284)
     at com.ibm.ws.channel.ssl.internal.SSLConnectionLink.determineNextChannel(SSLConnectionLink.java:1029)
     at com.ibm.ws.channel.ssl.internal.SSLConnectionLink.readyInboundPostHandshake(SSLConnectionLink.java:695)
     at com.ibm.ws.channel.ssl.internal.SSLConnectionLink$MyHandshakeCompletedCallback.complete(SSLConnectionLink.java:383)
     at com.ibm.ws.channel.ssl.internal.SSLUtils.handleHandshake(SSLUtils.java:947)
     at com.ibm.ws.channel.ssl.internal.SSLHandshakeIOCallback.complete(SSLHandshakeIOCallback.java:85)
     at com.ibm.ws.tcpchannel.internal.WorkQueueManager.requestComplete(WorkQueueManager.java:501)
     at com.ibm.ws.tcpchannel.internal.WorkQueueManager.attemptIO(WorkQueueManager.java:571)
     at com.ibm.ws.tcpchannel.internal.WorkQueueManager.workerRun(WorkQueueManager.java:926)
     at com.ibm.ws.tcpchannel.internal.WorkQueueManager$Worker.run(WorkQueueManager.java:1015)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1153)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
     at java.lang.Thread.run(Thread.java:785)

The following table shows the events that have run during this request.

Duration      Operation
30018.682ms + websphere.servlet.service | auth | authHomeServlet


问:
lambda with custom authorizer works on test with console but not with postman
I have a lambda function that works when testing on the AWS console. But once I test on Postman it gives me the following response

```<code>{
    "message": "Unauthorized"
}
</code>```

I basically have a Authorization on the header with a Bearer token like so

```<code>Bearer <my token>
</code>```

The body is empty as it's only a Get endpoint. Not sure what I'm missing on my request from postman. Any suggestion is appreciated.

答:
Make sure that your custom authorizer in API Gateway is properly configured (you can go to authorizers and test it from there too). Then make sure that the endpoint that calls that lambda has your custom authorizer set. Finally if you are just developing a few lambdas, creating them using the aws console it's fine, but maybe it would be better for you to use a serverless deployment framework like https://serverless.com/ or SAM. I have found that even for small projects they let you have more control over what you do in an easy way, and the learning curve it's not that hard.
Hope you fix it, and have a great day.</p>

Body:
I have a lambda function that works when testing on the AWS console. But once I test on Postman it gives me the following response

{
    "message": "Unauthorized"
}

I basically have a Authorization on the header with a Bearer token like so

Bearer <my token>

The body is empty as it's only a Get endpoint. Not sure what I'm missing on my request from postman. Any suggestion is appreciated.


问:
Qt + OS X + Bluetooth
I would like to create an app to send text alerts to bt devices on the neighbourhood but i'm finding incredible hard to get examples, APIs etc. is BT not so used?

Is it possible to use Qt to do that? (I think yes as the API of IObluetooth is C)

I've managed to import the IObluetooth.framework to Qt, but I cannot find any C/C++ examples, api or help. any help here?

thanks

答:
QtMobility has a  connectivity Module that supports BlueTooth transfers but currently only on Symbian and Linux.
    http://doc.qt.nokia.com/qtmobility-1.2/connectivity-api.html </p>

<p>You either have to search for a 3rd party library or use Native Code to achieve this. </p>

Title: Qt + OS X + Bluetooth

Body:
QtMobility has a  connectivity Module that supports BlueTooth transfers but currently only on Symbian and Linux.
    http://doc.qt.nokia.com/qtmobility-1.2/connectivity-api.html

You either have to search for a 3rd party library or use Native Code to achieve this.


问:
How do I change all font sizes in Eclipse?
Regarding Stack Overflow question How can I change font size in Eclipse for Java text editors?:

This question asks how to change the font size in an editor window. But is there a way to change all the font sizes for the entire Eclipse GUI?

答:
Add to Eclipse\plugins\org.eclipse.ui.themes_<version>\css\dark\e4-dark_globalstyle.css:

```<code> * {
    font-size: 13;
}
</code>```

Depending on the Eclipse version and theme (I'm using dark theme!) you are using, you might need to add this to another css file, e.g. e4_basestyle.css.

Body:
Add to Eclipse\plugins\org.eclipse.ui.themes_<version>\css\dark\e4-dark_globalstyle.css:

 * {
    font-size: 13;
}

Depending on the Eclipse version and theme (I'm using dark theme!) you are using, you might need to add this to another css file, e.g. e4_basestyle.css.


问:
What does the f do in plt.ylabel(f'g(x)')?
Firstly,

```<code>import matplotlib.pyplot as plt
import matplotlib
</code>```

In an elementary example on how to plot with matplotlib in our lecture I encountered the following line

```<code>plt.ylabel(f'g(x)')
</code>```

What I have tried

In the documentation there's no mention of an additional parameter to be inserted before the actual label text. I further checked out examples where plt.ylabel was used and discovered here that also r seems to be a valid option.
Also, I discovered in this example that the "parameter" r can also be used in plt.title, but also in the corresponding documentation I didn't find anything.

Entire Code

```<code>plt.figure(figsize=(6,4))
X = np.arange(0,2*np.pi,0.2)
plt.plot(X,np.sin(X),'o-',label='$\sin(x)$')
plt.plot(X,np.cos(X),'*-',c='g', label='$\cos(x)$')
plt.ylabel(f'f(x)' rotation=0)
plt.grid() # adds grid
_=plt.legend(loc=3)
</code>```

答:
As others have mentioned, the f in your code is probably a leftover from an f-string. You can read more on f-strings here.

As you mentioned, you can also find an r (or R) before a string. This defines a raw string. Raw strings are raw string literals that treat backslash (\) as a literal and not as an escape character.

Example:

```<code>dummy_str = "This is a \n normal string"
print(dummy_str)

raw_dummy_str = r"This is a \n raw string"
print(raw_dummy_str)
</code>```

The above code will print out:

```<code>This is a
 normal string
This is a \n raw string
</code>```

You can read more about raw string here.

Body:
Firstly,

import matplotlib.pyplot as plt
import matplotlib

In an elementary example on how to plot with matplotlib in our lecture I encountered the following line

plt.ylabel(f'g(x)')

What I have tried

In the documentation there's no mention of an additional parameter to be inserted before the actual label text. I further checked out examples where plt.ylabel was used and discovered here that also r seems to be a valid option.
Also, I discovered in this example that the "parameter" r can also be used in plt.title, but also in the corresponding documentation I didn't find anything.

Entire Code

plt.figure(figsize=(6,4))
X = np.arange(0,2*np.pi,0.2)
plt.plot(X,np.sin(X),'o-',label='$\sin(x)$')
plt.plot(X,np.cos(X),'*-',c='g', label='$\cos(x)$')
plt.ylabel(f'f(x)' rotation=0)
plt.grid() # adds grid
_=plt.legend(loc=3)

Body:
As others have mentioned, the f in your code is probably a leftover from an f-string. You can read more on f-strings here.

As you mentioned, you can also find an r (or R) before a string. This defines a raw string. Raw strings are raw string literals that treat backslash (\) as a literal and not as an escape character.

Example:

dummy_str = "This is a \n normal string"
print(dummy_str)

raw_dummy_str = r"This is a \n raw string"
print(raw_dummy_str)

The above code will print out:

This is a
 normal string
This is a \n raw string

You can read more about raw string here.


问:
Lazy loaded React router routes loading anyway
I've been trying to lazy load routes in React using React.lazy and Suspense. But some components are loading regardless of the current route, exactly: Feed, Profile and Settings.

Notice I don't actually want to lazy load Components like MenuAppBar and SnackAlert but if I import them normally and remove their Suspense, code-splitting straight doesn't even work and everything loads and the whole app is just a single chunk.

```<code>import {createMuiTheme, MuiThemeProvider} from "@material-ui/core";
import {yellow} from "@material-ui/core/colors";
import CssBaseline from "@material-ui/core/CssBaseline";
import axios from "axios";
import React, {lazy, Suspense, useEffect, useState} from "react";
import {BrowserRouter as Router, Route, Switch} from "react-router-dom";
import "./css/feed.css";
import "./css/style.css";

const Feed = lazy(() => import("./routes/Feed"));
const Profile = lazy(() => import("./routes/Profile"));
const Home = lazy(() => import("./routes/Home"));
const Settings = lazy(() => import("./routes/Settings"));
const NotFound = lazy(() => import("./routes/NotFound"));
const MenuAppBar = lazy(() => import("./components/MenuAppBar"));
const SnackAlert = lazy(() => import("./components/SnackAlert"));

const App: React.FC = () => {
    const [isLogged, setIsLogged] = useState(localStorage.getItem("token") ? true : false);

    const [user, setUser] = useState<User>(
        isLogged ? JSON.parse(localStorage.getItem("userInfo") as string) : {admin: false}
    );
    const [openError, setOpenError] = useState<boolean>(false);
    const [errorMsg, setErrorMsg] = useState<string>("");
    const [severity, setSeverity] = useState<Severity>(undefined);
    const [pwa, setPwa] = useState<any>(null);
    const [showBtn, setShowBtn] = useState<boolean>(false);
    const [isLight, setIsLight] = useState<boolean>(
        (JSON.parse(localStorage.getItem("theme") as string) as boolean) ? true : false
    );

    const theme: customTheme = {
        darkTheme: {
            palette: {
                type: "dark",
                primary: {
                    main: yellow[600]
                }
            }
        },
        lightTheme: {
            palette: {
                type: "light",
                primary: {
                    main: yellow[700]
                }
            }
        }
    };

    window.addEventListener("beforeinstallprompt", (event) => {
        event.preventDefault();
        setPwa(event);
        setShowBtn(true);
    });

    window.addEventListener("appinstalled", (e) => {
        setShowBtn(false);
        setErrorMsg("App installed!");
        setSeverity("success");
        setOpenError(true);
    });

    const handleClick = () => {
        if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
            setErrorMsg(`Please, open the share menu and select "Add to Home Screen"`);
            setSeverity("info");
            setOpenError(true);
        } else {
            if (pwa) {
                pwa.prompt();
                pwa.userChoice.then((choiceResult: {outcome: "accepted" | "refused"}) => {
                    if (choiceResult.outcome === "accepted") {
                        setErrorMsg("App downloading in the background..");
                        setSeverity("info");
                        setOpenError(true);
                    }
                    setPwa(null);
                });
            }
        }
    };

    useEffect(() => {
        const token: string | null = localStorage.getItem("token");
        let userInfo: User = JSON.parse(localStorage.getItem("userInfo") as string);
        if (userInfo && token && !userInfo.admin) {
            setUser(userInfo);
            setIsLogged(true);
        }
        if (isLogged) {
            axios
                .get("/api/auth/user", {
                    headers: {
                        "x-auth-token": `${token}`
                    }
                })
                .then((res) => {
                    if (!userInfo || !token) {
                        setUser(res.data as User);
                    }
                    localStorage.setItem(`userInfo`, JSON.stringify(res.data as User));
                    setIsLogged(true);
                })
                .catch((err) => {
                    if (err) {
                        setIsLogged(false);
                    }
                });
        } else {
            localStorage.removeItem("token");
            localStorage.removeItem("userInfo");
        }
    }, [isLogged]);

    return (
        <MuiThemeProvider theme={isLight ? createMuiTheme(theme.lightTheme) : createMuiTheme(theme.darkTheme)}>
            <CssBaseline />
            <Router>
                <Suspense fallback={<div></div>}>
                    <Route
                        path="/"
                        render={() => (
                            <>
                                <MenuAppBar
                                    isLogged={isLogged}
                                    setIsLogged={setIsLogged}
                                    user={user}
                                    setUser={setUser}
                                    isLight={isLight}
                                    setIsLight={setIsLight}
                                />
                                <SnackAlert severity={severity} errorMsg={errorMsg} setOpenError={setOpenError} openError={openError} />
                            </>
                        )}
                    />
                </Suspense>
                <Suspense fallback={<div></div>}>
                    <Switch>
                        <Route exact path="/" render={() => <Home />} />

                        <Route exact path="/profile/:id" render={() => <Profile />} />

                        <Route exact path="/feed" render={() => <Feed isLogged={isLogged} user={user} />} />

                        <Route
                            exact
                            path="/settings"
                            render={() => (
                                <Settings isLight={isLight} setIsLight={setIsLight} handleClick={handleClick} showBtn={showBtn} />
                            )}
                        />
                        <Route render={() => <NotFound />} />
                    </Switch>
                </Suspense>
            </Router>
        </MuiThemeProvider>
    );
};

export default App;
</code>```

答:
You are wrapping your entire Switch in a single Suspense, so all components will be lazily loaded at the same time. You probably only want each to be fetched/loaded when the specific route is rendered the first time.

```<code><Switch>
  <Route
    exact
    path="/"
    render={props => (
      <Suspense fallback={<div>Loading...<div>}>
        <Home {...props} />
      </Suspense>
    )}
  />
  <Route
    exact
    path="/profile/:id"
    render={props => (
      <Suspense fallback={<div>Loading...<div>}>
        <Profile {...props} />
      </Suspense>
    )}
  />
  <Route
    exact
    path="/feed"
    render={() => (
      <Suspense fallback={<div>Loading...<div>}>
        <Feed isLogged={isLogged} user={user} {...props} />
      </Suspense>
    )}
  />
  <Route
    exact
    path="/settings"
    render={() => (
      <Suspense fallback={<div>Loading...<div>}>
        <Settings
          isLight={isLight}
          setIsLight={setIsLight}
          handleClick={handleClick}
          showBtn={showBtn}
          {...props}
        />
      </Suspense>
    )}
  />
  <Route
    render={() => <NotFound />}
  />
</Switch>
</code>```

There is a lot of repetition here, so it is practical to factor out the suspense into a HOC.

```<code>const withSuspense = (WrappedComponent, fallback) => props => (
  <Suspense fallback={fallback}>
    <WrappedComponent {...props} />
  </Suspense>
);
</code>```

You can either decorate each perspective default export, i.e.

```<code>export default withSuspense(Home, <div>Loading...<div>);
</code>```

App.js

```<code>...
<Switch>
  <Route exact path="/" render={props => <Home {...props} />} />
</code>```

or decorate them in your App

```<code>const HomeWithSuspense = withSuspense(Home, <div>Loading...<div>);

...

<Switch>
  <Route
    exact
    path="/"
    render={props => <HomeWithSuspense {...props} />}
  />
  ...
</Switch>
</code>```

Body:
I've been trying to lazy load routes in React using React.lazy and Suspense. But some components are loading regardless of the current route, exactly: Feed, Profile and Settings.

Notice I don't actually want to lazy load Components like MenuAppBar and SnackAlert but if I import them normally and remove their Suspense, code-splitting straight doesn't even work and everything loads and the whole app is just a single chunk.

import {createMuiTheme, MuiThemeProvider} from "@material-ui/core";
import {yellow} from "@material-ui/core/colors";
import CssBaseline from "@material-ui/core/CssBaseline";
import axios from "axios";
import React, {lazy, Suspense, useEffect, useState} from "react";
import {BrowserRouter as Router, Route, Switch} from "react-router-dom";
import "./css/feed.css";
import "./css/style.css";

const Feed = lazy(() => import("./routes/Feed"));
const Profile = lazy(() => import("./routes/Profile"));
const Home = lazy(() => import("./routes/Home"));
const Settings = lazy(() => import("./routes/Settings"));
const NotFound = lazy(() => import("./routes/NotFound"));
const MenuAppBar = lazy(() => import("./components/MenuAppBar"));
const SnackAlert = lazy(() => import("./components/SnackAlert"));

const App: React.FC = () => {
    const [isLogged, setIsLogged] = useState(localStorage.getItem("token") ? true : false);

    const [user, setUser] = useState<User>(
        isLogged ? JSON.parse(localStorage.getItem("userInfo") as string) : {admin: false}
    );
    const [openError, setOpenError] = useState<boolean>(false);
    const [errorMsg, setErrorMsg] = useState<string>("");
    const [severity, setSeverity] = useState<Severity>(undefined);
    const [pwa, setPwa] = useState<any>(null);
    const [showBtn, setShowBtn] = useState<boolean>(false);
    const [isLight, setIsLight] = useState<boolean>(
        (JSON.parse(localStorage.getItem("theme") as string) as boolean) ? true : false
    );

    const theme: customTheme = {
        darkTheme: {
            palette: {
                type: "dark",
                primary: {
                    main: yellow[600]
                }
            }
        },
        lightTheme: {
            palette: {
                type: "light",
                primary: {
                    main: yellow[700]
                }
            }
        }
    };

    window.addEventListener("beforeinstallprompt", (event) => {
        event.preventDefault();
        setPwa(event);
        setShowBtn(true);
    });

    window.addEventListener("appinstalled", (e) => {
        setShowBtn(false);
        setErrorMsg("App installed!");
        setSeverity("success");
        setOpenError(true);
    });

    const handleClick = () => {
        if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
            setErrorMsg(`Please, open the share menu and select "Add to Home Screen"`);
            setSeverity("info");
            setOpenError(true);
        } else {
            if (pwa) {
                pwa.prompt();
                pwa.userChoice.then((choiceResult: {outcome: "accepted" | "refused"}) => {
                    if (choiceResult.outcome === "accepted") {
                        setErrorMsg("App downloading in the background..");
                        setSeverity("info");
                        setOpenError(true);
                    }
                    setPwa(null);
                });
            }
        }
    };

    useEffect(() => {
        const token: string | null = localStorage.getItem("token");
        let userInfo: User = JSON.parse(localStorage.getItem("userInfo") as string);
        if (userInfo && token && !userInfo.admin) {
            setUser(userInfo);
            setIsLogged(true);
        }
        if (isLogged) {
            axios
                .get("/api/auth/user", {
                    headers: {
                        "x-auth-token": `${token}`
                    }
                })
                .then((res) => {
                    if (!userInfo || !token) {
                        setUser(res.data as User);
                    }
                    localStorage.setItem(`userInfo`, JSON.stringify(res.data as User));
                    setIsLogged(true);
                })
                .catch((err) => {
                    if (err) {
                        setIsLogged(false);
                    }
                });
        } else {
            localStorage.removeItem("token");
            localStorage.removeItem("userInfo");
        }
    }, [isLogged]);

    return (
        <MuiThemeProvider theme={isLight ? createMuiTheme(theme.lightTheme) : createMuiTheme(theme.darkTheme)}>
            <CssBaseline />
            <Router>
                <Suspense fallback={

}>
                    <Route
                        path="/"
                        render={() => (
                            <>
                                <MenuAppBar
                                    isLogged={isLogged}
                                    setIsLogged={setIsLogged}
                                    user={user}
                                    setUser={setUser}
                                    isLight={isLight}
                                    setIsLight={setIsLight}
                                />
                                <SnackAlert severity={severity} errorMsg={errorMsg} setOpenError={setOpenError} openError={openError} />
                            </>
                        )}
                    />
                </Suspense>
                <Suspense fallback={

}>
                    <Switch>
                        <Route exact path="/" render={() => <Home />} />

                        <Route exact path="/profile/:id" render={() => <Profile />} />

                        <Route exact path="/feed" render={() => <Feed isLogged={isLogged} user={user} />} />

                        <Route
                            exact
                            path="/settings"
                            render={() => (
                                <Settings isLight={isLight} setIsLight={setIsLight} handleClick={handleClick} showBtn={showBtn} />
                            )}
                        />
                        <Route render={() => <NotFound />} />
                    </Switch>
                </Suspense>
            </Router>
        </MuiThemeProvider>
    );
};

export default App;

Body:
You are wrapping your entire Switch in a single Suspense, so all components will be lazily loaded at the same time. You probably only want each to be fetched/loaded when the specific route is rendered the first time.

<Switch>
  <Route
    exact
    path="/"
    render={props => (
      <Suspense fallback={<div>Loading...<div>}>
        <Home {...props} />
      </Suspense>
    )}
  />
  <Route
    exact
    path="/profile/:id"
    render={props => (
      <Suspense fallback={<div>Loading...<div>}>
        <Profile {...props} />
      </Suspense>
    )}
  />
  <Route
    exact
    path="/feed"
    render={() => (
      <Suspense fallback={<div>Loading...<div>}>
        <Feed isLogged={isLogged} user={user} {...props} />
      </Suspense>
    )}
  />
  <Route
    exact
    path="/settings"
    render={() => (
      <Suspense fallback={<div>Loading...<div>}>
        <Settings
          isLight={isLight}
          setIsLight={setIsLight}
          handleClick={handleClick}
          showBtn={showBtn}
          {...props}
        />
      </Suspense>
    )}
  />
  <Route
    render={() => <NotFound />}
  />
</Switch>

There is a lot of repetition here, so it is practical to factor out the suspense into a HOC.

const withSuspense = (WrappedComponent, fallback) => props => (
  <Suspense fallback={fallback}>
    <WrappedComponent {...props} />
  </Suspense>
);

You can either decorate each perspective default export, i.e.

export default withSuspense(Home, <div>Loading...<div>);

App.js

...
<Switch>
  <Route exact path="/" render={props => <Home {...props} />} />

or decorate them in your App

const HomeWithSuspense = withSuspense(Home, <div>Loading...<div>);

...

<Switch>
  <Route
    exact
    path="/"
    render={props => <HomeWithSuspense {...props} />}
  />
  ...
</Switch>


问:
Which of these lines is more efficient (CPU/memory-wise) when executed in jQuery?
I have two scenerios. In each scenerio, tell me which version of doing the same exact thing is more efficient (e.g. uses less CPU or memory):

First scenerio:

```<code>/*version 1*/
    $('body').append('#something');
/*version 2*/
    $('#something').insertAfter('body > *:last-child');
</code>```

Second scenerio:

```<code>/*version 1*/
    $('#something').method1();
    $('#something').method2();
    $('#something').method3();
/*version 2*/
    var $reference = $('#something');
    $reference.method1();
    $reference.method2();
    $reference.method3();
</code>```

So in each scenerio, which version is more efficient?

答:
In the first scenario the first is more efficent since $("#someid") ultimatly amounts to a document.getElementById call which is a call to native code. Id selectors are fairly cheap compared to class selectors. A call to $('body > *:last-child') is going to going to be a much more complex call to SizzleJS.

In the second scenario the second is more efficient since you avoid making an additional two calls to document.getElementById and just declare your object up front.

Body:
I have two scenerios. In each scenerio, tell me which version of doing the same exact thing is more efficient (e.g. uses less CPU or memory):

First scenerio:

/*version 1*/
    $('body').append('#something');
/*version 2*/
    $('#something').insertAfter('body > *:last-child');

Second scenerio:

/*version 1*/
    $('#something').method1();
    $('#something').method2();
    $('#something').method3();
/*version 2*/
    var $reference = $('#something');
    $reference.method1();
    $reference.method2();
    $reference.method3();

So in each scenerio, which version is more efficient?


问:
How do I identify the row number in a For / Select / Loop
I have a section of code from an Oracle procedure.  This parts works well as it is:

```<code>for r in (select * from json_table
            (l_resp, '$.items[0].volumeInfo.authors[*]'
                columns author varchar2(256) path '$'
            )
          )
    loop
        dbms_output.put_line('The value of Author ' ||  ' is: ' || r.author);
    end loop r;
</code>```

What I'd like to do is get the row number that is currently being processed.  Something like a ROWNUM for the row "r".

I'd like to adjust the dbms_output line to look something like:

```<code>dbms_output.put_line('The value of Author ' || r.rownum || ' is: ' || r.author);
</code>```

But the r.rownum doesn't work.  How do I reference something like "r.rownum"?

答:
I found a way.

```<code>For rowz in
    (select rownum rn, j_auth_tab.*
        from json_table(l_resp, '$.items[0].volumeInfo.authors[*]'
                        columns author varchar2(512) path '$') j_auth_tab)
Loop
    dbms_output.put_line('Rownum: ' || rowz.rn || ' Author: ' || rowz.author);
End loop rowz;
</code>```

That solved my problem.

Body:
I have a section of code from an Oracle procedure.  This parts works well as it is:

for r in (select * from json_table
            (l_resp, '$.items[0].volumeInfo.authors[*]'
                columns author varchar2(256) path '$'
            )
          )
    loop
        dbms_output.put_line('The value of Author ' ||  ' is: ' || r.author);
    end loop r;

What I'd like to do is get the row number that is currently being processed.  Something like a ROWNUM for the row "r".

I'd like to adjust the dbms_output line to look something like:

dbms_output.put_line('The value of Author ' || r.rownum || ' is: ' || r.author);

But the r.rownum doesn't work.  How do I reference something like "r.rownum"?

Body:
I found a way.

For rowz in
    (select rownum rn, j_auth_tab.*
        from json_table(l_resp, '$.items[0].volumeInfo.authors[*]'
                        columns author varchar2(512) path '$') j_auth_tab)
Loop
    dbms_output.put_line('Rownum: ' || rowz.rn || ' Author: ' || rowz.author);
End loop rowz;

That solved my problem.


问:
How to bring object out of a for loop
I have the following method that should return a product object if its name attribute matches the input string.

```<code>public Product find(String nameInput){
 for(Product product : this.Products){
        if(product.getName().equalsIgnoreCase(nameInput)){
            return product;
        }
   }
}
</code>```

Its giving me the following error:

I know that I could return null at the end of the method, however is there a more elegant way to do this?

答:
Do it as follows:</p>

```<code>public Product find(String nameInput){
    Product p = null;
    for(Product product : this.Products){
        if(product.getName().equalsIgnoreCase(nameInput)){
            p = product;
            break;
        }
    }
    return p;
}
</code>```

Title: How to bring object out of a for loop

Body:
I have the following method that should return a product object if its name attribute matches the input string.

public Product find(String nameInput){
 for(Product product : this.Products){
        if(product.getName().equalsIgnoreCase(nameInput)){
            return product;
        }
   }
}

Its giving me the following error:

I know that I could return null at the end of the method, however is there a more elegant way to do this?

Body:
Do it as follows:

public Product find(String nameInput){
    Product p = null;
    for(Product product : this.Products){
        if(product.getName().equalsIgnoreCase(nameInput)){
            p = product;
            break;
        }
    }
    return p;
}


问:
Can't create a new domain in Ampps 3.9
I start heading on the ampps page to add a new domain for my project which has his location in another partition.

I successfully enter and fill the form on the add_domain's page but when I submit. I unfortunately and always get an error like this :

The unexpected thing is that the domain which is providing an error has seen to be saved on the manage_domain's page just like on the following picture :

I'm getting an "ERR_NAME_NOT_RESOLVED" when I try accessing my project with the so-called new domain's.

.

Please, if anyone has an idea to get rid of this matter. I will be very grateful to (him/her)!
Sorry for my bad writing and happy "pre-new year" Everyone  (:b)

答: I don't know if working for you, but I manually added my own domain name into hosts, and after i created the domain, and unchecked add an entry, still give me that error, but when i click on list domains, appears my domain, then i restart ampps and close all browsers, and that works good.

Title: Can't create a new domain in Ampps 3.9