问:
failed to start child: EvercamAdmin.Storage ** (EXIT) :badarg elixir
I have added a GenServer as

```<code>defmodule EvercamAdmin.Storage do

  use GenServer
  require Logger

  def start_link(args) do
    GenServer.start_link(__MODULE__, [args])
  end

  def init(args) do
    Logger.info "Starting to create storage.json."
    {:ok, 1}
  end
end
</code>```

And I am starting it through application.ex file such as

```<code>  def start(_type, _args) do
    # List all child processes to be supervised
    children = [
      EvercamAdminWeb.Endpoint,
      {EvercamAdmin.Storage, []}
    ]

    opts = [strategy: :one_for_one, name: EvercamAdmin.Supervisor]
    Supervisor.start_link(children, opts)
  end
</code>```

It was working fine but all of a sudden it started giving errors or ** (EXIT) :badarg

I have tried to change .stark_link(__MODULE__, :ok, [args]) as well but the error is the same.

UPDATE: whole error message

```<code>Erlang/OTP 21 [erts-10.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe]

Compiling 2 files (.ex)
[info] Running EvercamAdminWeb.Endpoint with cowboy 2.6.1 at http://localhost:4000
[info] Starting to create storage.json.

[info] Application evercam_admin exited: EvercamAdmin.Application.start(:normal, []) returned an error: shutdown: failed to start child: EvercamAdmin.Storage
    ** (EXIT) :badarg
** (Mix) Could not start application evercam_admin: EvercamAdmin.Application.start(:normal, []) returned an error: shutdown: failed to start child: EvercamAdmin.Storage
    ** (EXIT) :badarg
</code>```

Update: Full EvercamAdmin.Storage module

```<code>defmodule EvercamAdmin.Storage do

  use GenServer
  require Logger
  import Ecto.Query

  @seaweedfs_new Application.get_env(:evercam_admin, :seaweedfs_new)
  @seaweedfs_old Application.get_env(:evercam_admin, :seaweedfs_old)
  @seaweedfs_oldest Application.get_env(:evercam_admin, :seaweedfs_oldest)

  @proxy_host Application.get_env(:evercam_admin, :proxy_host)
  @proxy_pass Application.get_env(:evercam_admin, :proxy_pass)

  def start_link(args \\ []) do
    GenServer.start_link(__MODULE__, args)
  end

  def init(args) do
    Logger.info "Starting to create storage.json."
    check_for_online_json_file()
    |> whats_next(args)
    {:ok, 1}
  end

  defp whats_next(:ok, ["refresh"]), do: whats_next(:start, ["refresh"])
  defp whats_next(:ok, _), do: :noop
  defp whats_next(:start, _args) do
    construction_cameras =
      Camera
      |> where([cam], cam.owner_id  in [13959, 109148])
      |> preload(:owner)
      |> Evercam.Repo.all

    years = ["2015", "2016", "2017", "2018", "2019"]
    servers = [@seaweedfs_new, @seaweedfs_old, @seaweedfs_oldest]

    big_data =
      Enum.map(construction_cameras, fn camera ->
        servers =
          Enum.map(servers, fn server ->
            type = seaweefs_type(server)
            attribute = seaweedfs_attribute(server)
            url = "http://" <> server <> ":8888" <> "/#{camera.exid}/snapshots/recordings/"
            year_values =
              Enum.map(years, fn year ->
                final_url = url <> year <> "/"
                %{
                  "#{year}" => request_from_seaweedfs(final_url, type, attribute)
                }
              end)

            %{
              "#{server}" => year_values
            }
          end)
        %{
          camera_name: camera.name,
          camera_exid: camera.exid,
          oldest_snapshot_date: _snapshot_date(:oldest, camera),
          latest_snapshot_date: _snapshot_date(:latest, camera),
          servers: servers
        }
      end)
    File.write("storage.json", Poison.encode!(big_data), [:binary])
    seaweedfs_save(big_data, 1)
  end

  defp seaweefs_type(@seaweedfs_new), do: "Entries"
  defp seaweefs_type(_), do: "Directories"

  defp seaweedfs_attribute(@seaweedfs_new), do: "FullPath"
  defp seaweedfs_attribute(_), do: "Name"

  defp _snapshot_date(atom, camera) do
    with {:ok, %HTTPoison.Response{body: body, status_code: 200}} <- HTTPoison.get(
                                            "https://media.evercam.io/v2/cameras/#{camera.exid}/recordings/snapshots/#{atom |> to_string}?api_id=#{camera.owner.api_id}&api_key=#{camera.owner.api_key}"
                                            )
    do
      {:ok, %{"created_at" => date}} = Jason.decode(body)
      date
    else
      _ ->
        ""
    end
  end

  def check_for_online_json_file do
    with {:ok, %HTTPoison.Response{status_code: 200}} <- HTTPoison.get(
                              "http://#{@seaweedfs_new}:8888/evercam-admin3/storage.json",
                              ["Accept": "application/json"],
                              hackney: [pool: :seaweedfs_download_pool],
                              proxy: {@proxy_host, 80},
                              proxy_auth: {"fixie", @proxy_pass}
                            )
    do :ok
    else
      _ ->
        :start
    end

  end

  def request_from_seaweedfs(url, type, attribute) do
    hackney = [pool: :seaweedfs_download_pool, recv_timeout: 15000]
    with {:ok, response} <- HTTPoison.get(url, ["Accept": "application/json"], hackney: hackney, proxy: {@proxy_host, 80}, proxy_auth: {"fixie", @proxy_pass}),
         %HTTPoison.Response{status_code: 200, body: body} <- response,
         {:ok, data} <- Poison.decode(body),
         true <- is_list(data[type]) do
      Enum.map(data[type], fn(item) -> item[attribute] |> get_base_name(type, attribute) end)
    else
      _ -> []
    end
  end

  defp get_base_name(list, "Entries", "FullPath"), do: list |> Path.basename
  defp get_base_name(list, _, _), do: list

  def seaweedfs_save(_data, _tries = 4), do: :noop
  def seaweedfs_save(data, tries) do
    hackney = [pool: :seaweedfs_upload_pool]
    case HTTPoison.post("http://#{@seaweedfs_new}:8888/evercam-admin3/storage.json", {:multipart, [{"/evercam-admin3/storage.json", Jason.encode!(data), []}]}, [], hackney: hackney, proxy: {@proxy_host, 80}, proxy_auth: {"fixie", @proxy_pass}) do
      {:ok, response} -> response
      {:error, error} ->
        seaweedfs_save(data, tries + 1)
        Logger.info "[seaweedfs_save] [#{inspect error}]"
    end
  end
end
</code>```

答:
{EvercamAdmin.Storage, []} (essentially the same as EvercamAdmin.Storage) child argument in call to Supervisor.start_link/2 tells the Supervisor to call EvercamAdmin.Storage.start_link/1 without arguments, while your implementation expects the single argument (arity is exactly 1.)

There is a mess with args in general. You expect args, then you wrap it in a list (what for?) then you pass it to init/1 and never use later. The below should do:

```<code>defmodule EvercamAdmin.Storage do
  use GenServer
  require Logger

  def start_link(args \\ []), # accept no params
    do: GenServer.start_link(__MODULE__, args)

  def init(args) do
    Logger.info "Starting to create storage.json."
    {:ok, args} # What did `1` suppose to mean?
  end
end
</code>```

And in call to Supervisor.start_link/2:

```<code>children = [
  EvercamAdminWeb.Endpoint,
  EvercamAdmin.Storage # `start_link` now accepts empty args
]
</code>```

Body:
I have added a GenServer as

defmodule EvercamAdmin.Storage do

  use GenServer
  require Logger

  def start_link(args) do
    GenServer.start_link(__MODULE__, [args])
  end

  def init(args) do
    Logger.info "Starting to create storage.json."
    {:ok, 1}
  end
end

And I am starting it through application.ex file such as

  def start(_type, _args) do
    # List all child processes to be supervised
    children = [
      EvercamAdminWeb.Endpoint,
      {EvercamAdmin.Storage, []}
    ]

    opts = [strategy: :one_for_one, name: EvercamAdmin.Supervisor]
    Supervisor.start_link(children, opts)
  end

It was working fine but all of a sudden it started giving errors or ** (EXIT) :badarg

I have tried to change .stark_link(__MODULE__, :ok, [args]) as well but the error is the same.

UPDATE: whole error message

Erlang/OTP 21 [erts-10.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe]

Compiling 2 files (.ex)
[info] Running EvercamAdminWeb.Endpoint with cowboy 2.6.1 at http://localhost:4000
[info] Starting to create storage.json.

[info] Application evercam_admin exited: EvercamAdmin.Application.start(:normal, []) returned an error: shutdown: failed to start child: EvercamAdmin.Storage
    ** (EXIT) :badarg
** (Mix) Could not start application evercam_admin: EvercamAdmin.Application.start(:normal, []) returned an error: shutdown: failed to start child: EvercamAdmin.Storage
    ** (EXIT) :badarg

Update: Full EvercamAdmin.Storage module

defmodule EvercamAdmin.Storage do

  use GenServer
  require Logger
  import Ecto.Query

  @seaweedfs_new Application.get_env(:evercam_admin, :seaweedfs_new)
  @seaweedfs_old Application.get_env(:evercam_admin, :seaweedfs_old)
  @seaweedfs_oldest Application.get_env(:evercam_admin, :seaweedfs_oldest)

  @proxy_host Application.get_env(:evercam_admin, :proxy_host)
  @proxy_pass Application.get_env(:evercam_admin, :proxy_pass)

  def start_link(args \\ []) do
    GenServer.start_link(__MODULE__, args)
  end

  def init(args) do
    Logger.info "Starting to create storage.json."
    check_for_online_json_file()
    |> whats_next(args)
    {:ok, 1}
  end

  defp whats_next(:ok, ["refresh"]), do: whats_next(:start, ["refresh"])
  defp whats_next(:ok, _), do: :noop
  defp whats_next(:start, _args) do
    construction_cameras =
      Camera
      |> where([cam], cam.owner_id  in [13959, 109148])
      |> preload(:owner)
      |> Evercam.Repo.all

    years = ["2015", "2016", "2017", "2018", "2019"]
    servers = [@seaweedfs_new, @seaweedfs_old, @seaweedfs_oldest]

    big_data =
      Enum.map(construction_cameras, fn camera ->
        servers =
          Enum.map(servers, fn server ->
            type = seaweefs_type(server)
            attribute = seaweedfs_attribute(server)
            url = "http://" <> server <> ":8888" <> "/#{camera.exid}/snapshots/recordings/"
            year_values =
              Enum.map(years, fn year ->
                final_url = url <> year <> "/"
                %{
                  "#{year}" => request_from_seaweedfs(final_url, type, attribute)
                }
              end)

            %{
              "#{server}" => year_values
            }
          end)
        %{
          camera_name: camera.name,
          camera_exid: camera.exid,
          oldest_snapshot_date: _snapshot_date(:oldest, camera),
          latest_snapshot_date: _snapshot_date(:latest, camera),
          servers: servers
        }
      end)
    File.write("storage.json", Poison.encode!(big_data), [:binary])
    seaweedfs_save(big_data, 1)
  end

  defp seaweefs_type(@seaweedfs_new), do: "Entries"
  defp seaweefs_type(_), do: "Directories"

  defp seaweedfs_attribute(@seaweedfs_new), do: "FullPath"
  defp seaweedfs_attribute(_), do: "Name"

  defp _snapshot_date(atom, camera) do
    with {:ok, %HTTPoison.Response{body: body, status_code: 200}} <- HTTPoison.get(
                                            "https://media.evercam.io/v2/cameras/#{camera.exid}/recordings/snapshots/#{atom |> to_string}?api_id=#{camera.owner.api_id}&api_key=#{camera.owner.api_key}"
                                            )
    do
      {:ok, %{"created_at" => date}} = Jason.decode(body)
      date
    else
      _ ->
        ""
    end
  end

  def check_for_online_json_file do
    with {:ok, %HTTPoison.Response{status_code: 200}} <- HTTPoison.get(
                              "http://#{@seaweedfs_new}:8888/evercam-admin3/storage.json",
                              ["Accept": "application/json"],
                              hackney: [pool: :seaweedfs_download_pool],
                              proxy: {@proxy_host, 80},
                              proxy_auth: {"fixie", @proxy_pass}
                            )
    do :ok
    else
      _ ->
        :start
    end

  end

  def request_from_seaweedfs(url, type, attribute) do
    hackney = [pool: :seaweedfs_download_pool, recv_timeout: 15000]
    with {:ok, response} <- HTTPoison.get(url, ["Accept": "application/json"], hackney: hackney, proxy: {@proxy_host, 80}, proxy_auth: {"fixie", @proxy_pass}),
         %HTTPoison.Response{status_code: 200, body: body} <- response,
         {:ok, data} <- Poison.decode(body),
         true <- is_list(data[type]) do
      Enum.map(data[type], fn(item) -> item[attribute] |> get_base_name(type, attribute) end)
    else
      _ -> []
    end
  end

  defp get_base_name(list, "Entries", "FullPath"), do: list |> Path.basename
  defp get_base_name(list, _, _), do: list

  def seaweedfs_save(_data, _tries = 4), do: :noop
  def seaweedfs_save(data, tries) do
    hackney = [pool: :seaweedfs_upload_pool]
    case HTTPoison.post("http://#{@seaweedfs_new}:8888/evercam-admin3/storage.json", {:multipart, [{"/evercam-admin3/storage.json", Jason.encode!(data), []}]}, [], hackney: hackney, proxy: {@proxy_host, 80}, proxy_auth: {"fixie", @proxy_pass}) do
      {:ok, response} -> response
      {:error, error} ->
        seaweedfs_save(data, tries + 1)
        Logger.info "[seaweedfs_save] [#{inspect error}]"
    end
  end
end

Body:
{EvercamAdmin.Storage, []} (essentially the same as EvercamAdmin.Storage) child argument in call to Supervisor.start_link/2 tells the Supervisor to call EvercamAdmin.Storage.start_link/1 without arguments, while your implementation expects the single argument (arity is exactly 1.)

There is a mess with args in general. You expect args, then you wrap it in a list (what for?) then you pass it to init/1 and never use later. The below should do:

defmodule EvercamAdmin.Storage do
  use GenServer
  require Logger

  def start_link(args \\ []), # accept no params
    do: GenServer.start_link(__MODULE__, args)

  def init(args) do
    Logger.info "Starting to create storage.json."
    {:ok, args} # What did `1` suppose to mean?
  end
end

And in call to Supervisor.start_link/2:

children = [
  EvercamAdminWeb.Endpoint,
  EvercamAdmin.Storage # `start_link` now accepts empty args
]


来源: stackexchange

问:
Express cors not allowing credentials
I have a frontend setup with react and a back-end made with express and mongodb, I have a component which needs to make a fetch request including the credentials with should be already set. All of the routes work on postman but I'm not able to recreate the functionality with the fetch function.
Express server:

```<code>...
    server.use(helmet());
    server.use(compression());
    server.use(cors({
      credentials: true,
    }));

    if (process.env.NODE_ENV !== "production") {
      server.use(logger("dev"));
    }
    server.use(express.json());
    server.use(express.urlencoded({ extended: false }));

    server.use(cookieParser());

    server.use(
      session({
        secret: process.env.COOKIE_SECRET,
        resave: true,
        saveUninitialized: false,
        store: new MongoStore({ mongooseConnection: mongoose.connection })
      })
    );

    server.use(auth.initialize);
    server.use(auth.session);
    server.use(auth.setUser);

    //API ROUTES
    server.use("/user", require("./api/routes/user"));
    server.use("/pitch", require("./api/routes/pitch"));
    server.use("/match", require("./api/routes/matchmaking"));
...
</code>```

User routes:

```<code>router.post("/login", passport.authenticate("local"), (req, res, next) => {
  return res.status(200).json({
    message: "User logged in correctly",
    redirect: "/"
  });
});

router.get("/checklogin", (req, res, next) => {
  if (req.user) return next();
  else
    return res.status(401).json({
      error: "User not authenticated"
    });
},
 (req, res, next) => {
  return res.status(200).json({
    message: "User logged in correctly",
    redirect: "/"
  });
});
</code>```

Frontend:

```<code>  useEffect(() => {
    async function fetchData() {
      const response = await fetch("http://localhost:8000/user/checklogin", {
        credentials: 'include'
      });
      const data = await response.json();

      console.log(data);

    }

    fetchData();
  }, []);
</code>```

Using this code I get this error

```<code>Access to fetch at 'http://localhost:8000/user/checklogin' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
</code>```

As I said prior everything works on postman but not with the fetch function.

答:
As the error says:

The value of the 'Access-Control-Allow-Origin' header in the response
  must not be the wildcard '*' when the request's credentials mode is
  'include'.

When you do this server.use(cors()), all of the requests are allowed by default and because of which, the 'Access-Control-Allow-Origin' header is set to '*'.

So, you might want to specify the corsOptions to get around this issue.

```<code>var whitelist = ['http://localhost:3000', /** other domains if any */ ]
var corsOptions = {
  credentials: true,
  origin: function(origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

server.use(cors(corsOptions));
</code>```

ContentLicense: CC BY-SA 4.0

Title: Express cors not allowing credentials

Body:
I have a frontend setup with react and a back-end made with express and mongodb, I have a component which needs to make a fetch request including the credentials with should be already set. All of the routes work on postman but I'm not able to recreate the functionality with the fetch function.
Express server:

...
    server.use(helmet());
    server.use(compression());
    server.use(cors({
      credentials: true,
    }));

    if (process.env.NODE_ENV !== "production") {
      server.use(logger("dev"));
    }
    server.use(express.json());
    server.use(express.urlencoded({ extended: false }));

    server.use(cookieParser());

    server.use(
      session({
        secret: process.env.COOKIE_SECRET,
        resave: true,
        saveUninitialized: false,
        store: new MongoStore({ mongooseConnection: mongoose.connection })
      })
    );

    server.use(auth.initialize);
    server.use(auth.session);
    server.use(auth.setUser);

    //API ROUTES
    server.use("/user", require("./api/routes/user"));
    server.use("/pitch", require("./api/routes/pitch"));
    server.use("/match", require("./api/routes/matchmaking"));
...

User routes:

router.post("/login", passport.authenticate("local"), (req, res, next) => {
  return res.status(200).json({
    message: "User logged in correctly",
    redirect: "/"
  });
});

router.get("/checklogin", (req, res, next) => {
  if (req.user) return next();
  else
    return res.status(401).json({
      error: "User not authenticated"
    });
},
 (req, res, next) => {
  return res.status(200).json({
    message: "User logged in correctly",
    redirect: "/"
  });
});

Frontend:

  useEffect(() => {
    async function fetchData() {
      const response = await fetch("http://localhost:8000/user/checklogin", {
        credentials: 'include'
      });
      const data = await response.json();

      console.log(data);

    }

    fetchData();
  }, []);

Using this code I get this error

Access to fetch at 'http://localhost:8000/user/checklogin' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

As I said prior everything works on postman but not with the fetch function.

Body:
As the error says:

The value of the 'Access-Control-Allow-Origin' header in the response
  must not be the wildcard '*' when the request's credentials mode is
  'include'.

When you do this server.use(cors()), all of the requests are allowed by default and because of which, the 'Access-Control-Allow-Origin' header is set to '*'.

So, you might want to specify the corsOptions to get around this issue.

var whitelist = ['http://localhost:3000', /** other domains if any */ ]
var corsOptions = {
  credentials: true,
  origin: function(origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

server.use(cors(corsOptions));


问:
CFN stuck while ugrading ecs task
I want to trigger an ecs task upgrade via cloudformation. This works fine as long as the ELB health checks is ok after some time.
In case of a failing healthcheck it never send this error back to CFN, but keeps restarting new task instances and wait again.
Is there a way to limit the number of restart attempts?</p>

答: There's not a way to limit the number of restart attempts. However, you can set a timeout on cloudformation stack update.</p>

Title: CFN stuck while ugrading ecs task


问:
Can you specify a nested key for a table in KSQL?
I'm trying to create a table from a topic with an object key, but KSQL didn't recognize the variable.

Any solution for this?

```<code>create table csvexporttable (HEADER STRUCT<BusinessDate varchar>,
                             body STRUCT<ActiveStore_SalesTransaction_170 STRUCT<ThirdPartyLoyaltyData STRUCT<TotalAdvantage STRUCT<AdvantageAmount int>,CustomerNo varchar>,TransactionDetail ARRAY <STRUCT<TransactionDetailGroup STRUCT<item STRUCT<ManualPrice int,PriceOverride int>>,DetailFlagVoid int>>,SuspendFlag int,Total Array<STRUCT<TotalAmount DOUBLE>>>>)
with (KAFKA_TOPIC='************',
      VALUE_FORMAT='JSON',
      KEY='HEADER->BusinessDate');
</code>```

答: Structured keys are not yet supported by KSQL.  You can upvote (+1) the feature request at https://github.com/confluentinc/ksql/issues/824.</p>

Body:
I'm trying to create a table from a topic with an object key, but KSQL didn't recognize the variable.

Any solution for this?

create table csvexporttable (HEADER STRUCT<BusinessDate varchar>,
                             body STRUCT<ActiveStore_SalesTransaction_170 STRUCT<ThirdPartyLoyaltyData STRUCT<TotalAdvantage STRUCT<AdvantageAmount int>,CustomerNo varchar>,TransactionDetail ARRAY <STRUCT<TransactionDetailGroup STRUCT<item STRUCT<ManualPrice int,PriceOverride int>>,DetailFlagVoid int>>,SuspendFlag int,Total Array<STRUCT<TotalAmount DOUBLE>>>>)
with (KAFKA_TOPIC='************',
      VALUE_FORMAT='JSON',
      KEY='HEADER->BusinessDate');


问:
Set expiry time for laravel jwt dynamically
Hi I am using angular js in front end with satellizer and laravel at backend with tymon jwt library. I am using jwt authentication. I want to make remember me functionalities in my web app. I see 'ttl' to set expiry time of token in laravel 'config/jwt.php.

```<code> /*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour
|
*/

'ttl' => 60,
</code>```

By default, it will be 1 hour. But I want to change this dynamically to 1 week if user clicks remember me while login. How can I change it dynamically. Thank you.

答:
You can do following to generate JWT token with needed expire time:</p>

```<code>JWTAuth::customClaims(['exp' => Carbon\Carbon::now()->addDays(2)->timestamp])
    ->fromUser($user);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I am using angular js in front end with satellizer and laravel at backend with tymon jwt library. I am using jwt authentication. I want to make remember me functionalities in my web app. I see 'ttl' to set expiry time of token in laravel 'config/jwt.php.

 /*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour
|
*/

'ttl' => 60,

By default, it will be 1 hour. But I want to change this dynamically to 1 week if user clicks remember me while login. How can I change it dynamically. Thank you.

Body:
You can do following to generate JWT token with needed expire time:

JWTAuth::customClaims(['exp' => Carbon\Carbon::now()->addDays(2)->timestamp])
    ->fromUser($user);


问:
How to import js file from src file into index.html?
I am creating one system using React and I am still new to React. I need to add js file in my index.html where that js file is located in the src folder. I need to import this js file in order to make my system works. Does anyone know how to solve my problem? Thanks in advance.

This is how I import my js file. I think there is something wrong with my path. Does anyone know the correct path to import my js file?

```<code>      //index.html
      <!DOCTYPE html>
       <html lang="en">
        <head>
         <meta charset="utf-8" />
         <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
         <meta name="viewport" content="width=device-width, initial-scale=1" />
         <meta name="theme-color" content="#000000" />
         <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
         <title>React App</title>
         </head>
         <body>
           <noscript>You need to enable JavaScript to run this app.</noscript>
           <div id="root"></div>
           <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
           <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
           <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
           <script src="https://unpkg.com/@coreui/coreui/dist/js/coreui.min.js"></script>
           <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js" crossorigin></script>
           <script type="text/javascript" src='../src/js/index.js'></script>
         </body>
        </html>
</code>```

As you can see from the picture above, my index.js is located under the src folder.

答:
As i think this is not good way to do this. your trying to add your ./src some js file to ./public folder index.html

this is not recommended way. but if you want add some external links, put it under ./public folder and import it but this not recommended way.

ref :  sample project for external import

Body:
I am creating one system using React and I am still new to React. I need to add js file in my index.html where that js file is located in the src folder. I need to import this js file in order to make my system works. Does anyone know how to solve my problem? Thanks in advance.

This is how I import my js file. I think there is something wrong with my path. Does anyone know the correct path to import my js file?

      //index.html
      <!DOCTYPE html>

         <meta charset="utf-8" />
         <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
         <meta name="viewport" content="width=device-width, initial-scale=1" />
         <meta name="theme-color" content="#000000" />
         <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
         <title>React App</title>

           You need to enable JavaScript to run this app.

As you can see from the picture above, my index.js is located under the src folder.


问:
How to add a checkbox control to a datatable?
How can i add a checkbox to a datatable and bind it to a datagrid?

```<code>DataTable ColumnList = new DataTable();
ColumnList.Columns.Add("Column Fields");

int j = 1, i = 0;
CheckBox colCheckbox = new CheckBox();
foreach (Columns col in ColumnNames)
{
    colCheckbox.Name = col.ColumnName;
    ColumnList.Rows.Add(colCheckbox); // This is getting displayed as System.Windows.Forms.CheckBox,CheckState=0
}
</code>```

Please help.

答:
You'll have to have a boolean field (column) in the DataTable. When you bind the DataTable to the DataGridView, a checkbox column will be created for that boolean field.

Sample Code:

```<code>var dt = new DataTable();
dt.Columns.Add(new DataColumn("Selected", typeof(bool))); //this will show checkboxes
dt.Columns.Add(new DataColumn("Text", typeof(string)));   //this will show text

var dgv = new DataGridView();
dgv.DataSource = dt;
</code>```

This will bind the dt DataTable to the dgv DataGridView. The DataGridView will automatically display a DataGridViewCheckBoxColumn for the first DataColumn (Selected) and a DataGridViewTextBoxColumn for the second DataColumn (Text).

Body:
How can i add a checkbox to a datatable and bind it to a datagrid?

DataTable ColumnList = new DataTable();
ColumnList.Columns.Add("Column Fields");

int j = 1, i = 0;
CheckBox colCheckbox = new CheckBox();
foreach (Columns col in ColumnNames)
{
    colCheckbox.Name = col.ColumnName;
    ColumnList.Rows.Add(colCheckbox); // This is getting displayed as System.Windows.Forms.CheckBox,CheckState=0
}

Please help.

Body:
You'll have to have a boolean field (column) in the DataTable. When you bind the DataTable to the DataGridView, a checkbox column will be created for that boolean field.

Sample Code:

var dt = new DataTable();
dt.Columns.Add(new DataColumn("Selected", typeof(bool))); //this will show checkboxes
dt.Columns.Add(new DataColumn("Text", typeof(string)));   //this will show text

var dgv = new DataGridView();
dgv.DataSource = dt;

This will bind the dt DataTable to the dgv DataGridView. The DataGridView will automatically display a DataGridViewCheckBoxColumn for the first DataColumn (Selected) and a DataGridViewTextBoxColumn for the second DataColumn (Text).


问:
Search / and replace it with ; in xml tag with sublime text 3
I am working on an .xml file with this tag

<Categories><![CDATA[Test/Test1-Test2-Test3|Test4/Test5-Test6|Test7/Test8]]></Categories>

and I am trying to replace / with ; by using regular expressions in Sublime Text 3.

The output should be

<Categories><![CDATA[Test;Test1-Test2-Test3|Test4;Test5-Test6|Test7;Test8]]></Categories>

When I use this (<Categories>\S+)\/(.+</Categories>) it matches all the line and of course if I use this \/ it matches all / everywhere inside the .xml file.

Could you please help?

答:
For you example string, you could make use of a \G to assert the position at the end of the previous match and use \K to forget what has already been matched and then match a forward slash.

In the replacement use a ;

Use a positive lookahead to assert what is on the right is ]]></Categories>

```<code>(?:<Categories><!\[CDATA\[|\G(?!^))[^/]*\K/(?=[^][]*]]></Categories>)
</code>```

Explanation

(?: Non capturing group

<Categories><!\[CDATA\[ Match <Categories><![CDATA[

| Or

\G(?!^) Assert the position at the end of the previous match, not at the start

) Close non capturing group

[^/]* Match 0+ times not / using a negated character class

\K/ Forget what was matched, then match /

(?= Positive lookahead, assert what is on the right is

[^][]*]]></Categories> Match 0+ times not [ or ], then match ]]></Categories>

) Close positive lookahead

Regex demo

Body:
For you example string, you could make use of a \G to assert the position at the end of the previous match and use \K to forget what has already been matched and then match a forward slash.

In the replacement use a ;

Use a positive lookahead to assert what is on the right is ]]></Categories>

(?:<Categories><!\[CDATA\[|\G(?!^))[^/]*\K/(?=[^][]*]]></Categories>)

Explanation

(?: Non capturing group

<Categories><!\[CDATA\[ Match <Categories><![CDATA[

| Or

\G(?!^) Assert the position at the end of the previous match, not at the start

) Close non capturing group

[^/]* Match 0+ times not / using a negated character class

\K/ Forget what was matched, then match /

(?= Positive lookahead, assert what is on the right is

[^][]*]]></Categories> Match 0+ times not [ or ], then match ]]></Categories>

) Close positive lookahead

Regex demo


问:
Understanding esModuleInterop in tsconfig file
I was checking out someone .tsconfig file and there I spotted --esModuleInterop

This is his .tsconfig file

```<code>{
  "compilerOptions": {
    "moduleResolution": "node",
    "target": "es6",
    "module": "commonjs",
    "lib": ["esnext"],
    "strict": true,
    "sourceMap": true,
    "declaration": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "declarationDir": "./dist",
    "outDir": "./dist",
    "typeRoots": ["node_modules/@types"]
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modues"]
}
</code>```

Here, My primary question is what is    "esModuleInterop": true, and
"allowSyntheticDefaultImports": true,. I know they are sort of dependent on the  "module": "commonjs", . Can someone try to explain it in the best human language possible?

The official docs for allowSyntheticDefaultImports states

Allow default imports from modules with no default export. This does
not affect code emit, just typechecking.

What does that mean? If there isn't any export default then I think the only use case of the import default would be to initialize something? Like a singleton?

The following question/answer does not make sense as well
Is there a way to use --esModuleInterop in tsconfig as opposed to it being a flag?

And --esModuleInterop definition on the compiler page

Emit __importStar and __importDefault helpers for runtime babel
ecosystem compatibility and enable --allowSyntheticDefaultImports for
typesystem compatibility.

Also seemed difficult for me to understand/comprehend

答:
esModuleInterop generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:

```<code>//ts
import React from 'react'
//js
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
</code>```

__importDefault: If the module is not an es module then what is returned by require becomes the default. This means that if you use default import on a commonjs module, the whole module is actually the default.

__importStar is best described in this PR:

TypeScript treats a namespace import (i.e. import * as foo from "foo") as equivalent to const foo = require("foo"). Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures.
  ECMAScript basically says a namespace record is a plain object.

Babel first requires in the module, and checks for a property named __esModule. If __esModule is set to true, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:

All properties are plucked off of the require'd module and made available as named imports.

The originally require'd module is made available as a default import.

So we get this:

```<code>// ts
import * as React from 'react'

// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));
</code>```

allowSyntheticDefaultImports is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react' will raise the error Module '".../node_modules/@types/react/index"' has no default export. if allowSyntheticDefaultImports is false.

Body:
I was checking out someone .tsconfig file and there I spotted --esModuleInterop

This is his .tsconfig file

{
  "compilerOptions": {
    "moduleResolution": "node",
    "target": "es6",
    "module": "commonjs",
    "lib": ["esnext"],
    "strict": true,
    "sourceMap": true,
    "declaration": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "declarationDir": "./dist",
    "outDir": "./dist",
    "typeRoots": ["node_modules/@types"]
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modues"]
}

Here, My primary question is what is    "esModuleInterop": true, and
"allowSyntheticDefaultImports": true,. I know they are sort of dependent on the  "module": "commonjs", . Can someone try to explain it in the best human language possible?

The official docs for allowSyntheticDefaultImports states

Allow default imports from modules with no default export. This does
not affect code emit, just typechecking.

What does that mean? If there isn't any export default then I think the only use case of the import default would be to initialize something? Like a singleton?

The following question/answer does not make sense as well
Is there a way to use --esModuleInterop in tsconfig as opposed to it being a flag?

And --esModuleInterop definition on the compiler page

Emit __importStar and __importDefault helpers for runtime babel
ecosystem compatibility and enable --allowSyntheticDefaultImports for
typesystem compatibility.

Also seemed difficult for me to understand/comprehend

Body:
esModuleInterop generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:

//ts
import React from 'react'
//js
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));

__importDefault: If the module is not an es module then what is returned by require becomes the default. This means that if you use default import on a commonjs module, the whole module is actually the default.

__importStar is best described in this PR:

TypeScript treats a namespace import (i.e. import * as foo from "foo") as equivalent to const foo = require("foo"). Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures.
  ECMAScript basically says a namespace record is a plain object.

Babel first requires in the module, and checks for a property named __esModule. If __esModule is set to true, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:

All properties are plucked off of the require'd module and made available as named imports.

The originally require'd module is made available as a default import.

So we get this:

// ts
import * as React from 'react'

// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));

allowSyntheticDefaultImports is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react' will raise the error Module '".../node_modules/@types/react/index"' has no default export. if allowSyntheticDefaultImports is false.


问:
Sort and manipulate array in javascript
I have the following array:

var curr =     [{
      "Year": 2019,
      "Title": "Asset Management Sample",
      "Sum": 1020000.0,
      "Budget":0

```<code>}, {
  "Year": 2019,
  "Title": "Monday test 2",
  "Sum": 2546658.0,
  "Budget":100
}, {
  "Year": 2020,
  "Title": "Asset Management Sample",
  "Sum": 1020000.0,
  "Budget":1000
}, {
  "Year": 2020,
  "Title": "Monday test 2",
  "Sum": 3472000.0,
  "Budget":100
}, {
  "Year": 2021,
  "Title": "Asset Management Sample",
  "Sum": 1020000.0,
  "Budget":100
}, {
  "Year": 2021,
  "Title": "Monday test 2",
  "Sum": 2452000.0,
  "Budget":100
}]
</code>```

That I need to change to:

```<code>[{
  "Year": 2019,
  "Asset Management Sample": 1020000.0,
  "Monday test": 2546658.0
}, {
  "Year": 2020,
  "Asset Management Sample": 1020000.0,
  "Monday test 2": 3472000.0
}, {
  "Year": 2021,
  "Asset Management Sample": 1020000.0,
  "Monday test 2": 2452000.0
}]
</code>```

With help from earlier posters I have used .reduce (slightly modified from below) to generate this:

```<code>      var res = arr.reduce(function(acc, curr) {
      acc[curr.Year] = acc[curr.Year];
      acc[curr.Year] = acc[curr.Year] || { Year: curr.Year } ;
      acc[curr.Year][curr.Title] = curr.Sum;

      return acc;
</code>```

I need to expand this to include a sum of all the budget values for each year (there should be a single budget value per year). I added the following line in before the return:

```<code>acc[curr.Year][curr.Budget] = curr[curr.Budget] || { Budget: curr.Budget } ;
</code>```

It is adding individual entries for each Budget value. How do I sum the Budget values and return it without affecting the other returned array?

答:
Use reduce like so:

const arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
const res = Object.values(arr.reduce((acc, { Year, Title, Sum }) => (acc[Year] = acc[Year] || { Year }, acc[Year][Title] = Sum, acc), {}));
console.log(res);```
</div>
</div>
</p>

<p>More verbose version:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
const res = Object.values(arr.reduce((acc, { Year, Title, Sum }) => {
  acc[Year] = acc[Year] || { Year };
  acc[Year][Title] = Sum;
  return acc;
}, {}));
console.log(res);</code>```

.as-console-wrapper { max-height: 100% !important; top: auto; }```
</div>
</div>
</p>

<p>ES5 syntax:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
var res = arr.reduce(function(acc, curr) {
  acc[curr.Year] = acc[curr.Year] || { Year: curr.Year };
  acc[curr.Year][curr.Title] = curr.Sum;
  return acc;
}, {});
res = Object.keys(res).map(function(key) {
  return res[key];
});
console.log(res);</code>```

.as-console-wrapper { max-height: 100% !important; top: auto; }```

Title: Sort and manipulate array in javascript

Body:
I have the following array:

var curr =     [{
      "Year": 2019,
      "Title": "Asset Management Sample",
      "Sum": 1020000.0,
      "Budget":0

}, {
  "Year": 2019,
  "Title": "Monday test 2",
  "Sum": 2546658.0,
  "Budget":100
}, {
  "Year": 2020,
  "Title": "Asset Management Sample",
  "Sum": 1020000.0,
  "Budget":1000
}, {
  "Year": 2020,
  "Title": "Monday test 2",
  "Sum": 3472000.0,
  "Budget":100
}, {
  "Year": 2021,
  "Title": "Asset Management Sample",
  "Sum": 1020000.0,
  "Budget":100
}, {
  "Year": 2021,
  "Title": "Monday test 2",
  "Sum": 2452000.0,
  "Budget":100
}]

That I need to change to:

[{
  "Year": 2019,
  "Asset Management Sample": 1020000.0,
  "Monday test": 2546658.0
}, {
  "Year": 2020,
  "Asset Management Sample": 1020000.0,
  "Monday test 2": 3472000.0
}, {
  "Year": 2021,
  "Asset Management Sample": 1020000.0,
  "Monday test 2": 2452000.0
}]

With help from earlier posters I have used .reduce (slightly modified from below) to generate this:

      var res = arr.reduce(function(acc, curr) {
      acc[curr.Year] = acc[curr.Year];
      acc[curr.Year] = acc[curr.Year] || { Year: curr.Year } ;
      acc[curr.Year][curr.Title] = curr.Sum;

      return acc;

I need to expand this to include a sum of all the budget values for each year (there should be a single budget value per year). I added the following line in before the return:

acc[curr.Year][curr.Budget] = curr[curr.Budget] || { Budget: curr.Budget } ;

It is adding individual entries for each Budget value. How do I sum the Budget values and return it without affecting the other returned array?

Body:
Use reduce like so:

const arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
const res = Object.values(arr.reduce((acc, { Year, Title, Sum }) => (acc[Year] = acc[Year] || { Year }, acc[Year][Title] = Sum, acc), {}));
console.log(res);

More verbose version:

const arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
const res = Object.values(arr.reduce((acc, { Year, Title, Sum }) => {
  acc[Year] = acc[Year] || { Year };
  acc[Year][Title] = Sum;
  return acc;
}, {}));
console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }

ES5 syntax:

var arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
var res = arr.reduce(function(acc, curr) {
  acc[curr.Year] = acc[curr.Year] || { Year: curr.Year };
  acc[curr.Year][curr.Title] = curr.Sum;
  return acc;
}, {});
res = Object.keys(res).map(function(key) {
  return res[key];
});
console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }


问:
Can't upload a video in laravel
I am new in Laravel. I'm trying to make a movie site so I need to upload videos and then make their playback. The thing is when I try to upload a video .mp4 format it gives the following exception:

failed to open stream: Permission denied.

My method code in controller looks like this:

```<code>public function create(Request $request)
{
    $this->validate($request,[
        'poster_name' => 'required|image'
    ]);

    // Handle poster upload
    $imageName = $request->file('poster_name')->getClientOriginalName();
    $request->file('poster_name')->storeAs('public/images', $imageName);

    // Handle video upload.
    $videoName = $request->file('file_name')->getClientOriginalName();
    $request->file('file_name')->storeAs('public/videos', $videoName);

    $movie = new Movie;

    $movie->name = $request->name;
    $movie->description = $request->description;
    $movie->release_date = $request->release_date;
    $movie->country = $request->country;
    $movie->poster_name = $imageName;
    $movie->file_name = $videoName;

    $movie->save();

    return redirect()->action('MovieController@main');
}
</code>```

Please note that I am using windows 10. Any suggestions?

答:
Sometimes this error is caused by php.ini. The file size is more than 2M, because its a video file.

go to C:\xampp\php directory and open php.ini with your editor.
find upload_max_filesize and post_max_size, and change to 100M.

then restart Apache server and you are good to go.

Title: Can't upload a video in laravel

Body:
I am new in Laravel. I'm trying to make a movie site so I need to upload videos and then make their playback. The thing is when I try to upload a video .mp4 format it gives the following exception:

failed to open stream: Permission denied.

My method code in controller looks like this:

public function create(Request $request)
{
    $this->validate($request,[
        'poster_name' => 'required|image'
    ]);

    // Handle poster upload
    $imageName = $request->file('poster_name')->getClientOriginalName();
    $request->file('poster_name')->storeAs('public/images', $imageName);

    // Handle video upload.
    $videoName = $request->file('file_name')->getClientOriginalName();
    $request->file('file_name')->storeAs('public/videos', $videoName);

    $movie = new Movie;

    $movie->name = $request->name;
    $movie->description = $request->description;
    $movie->release_date = $request->release_date;
    $movie->country = $request->country;
    $movie->poster_name = $imageName;
    $movie->file_name = $videoName;

    $movie->save();

    return redirect()->action('MovieController@main');
}

Please note that I am using windows 10. Any suggestions?


问:
How to print substring in React JSX?
I have two variables in my react component. I want to divide one variable from another and print the value for only one decimal place. So, I choose the substring method as following:

```<code> <div className="col-md-8">
      {(total_star / total_user).substring(0,2)}
 </div>
</code>```

In the output I am getting the following error:

```<code>TypeError: (total_star / total_user).substring is not a function

</code>```

Kindly help to print substring in jsx.

答:
That is because the result is a float not a string, you could use .toFixed(...) instead of substring

```<code>(total_star / total_user).toFixed(2);
</code>```

Or convert the result to string and the use .substring(...)

```<code>(total_star / total_user).toString().substring(0,2)
</code>```

The first example may not get you the result you're looking for because .substring(0, 2) will give you the first two characters and .toFixed(2) will give you the result with two decimals after the decimal point.

Title: How to print substring in React JSX?

Body:
I have two variables in my react component. I want to divide one variable from another and print the value for only one decimal place. So, I choose the substring method as following:

      {(total_star / total_user).substring(0,2)}

In the output I am getting the following error:

TypeError: (total_star / total_user).substring is not a function

Kindly help to print substring in jsx.

Body:
That is because the result is a float not a string, you could use .toFixed(...) instead of substring

(total_star / total_user).toFixed(2);

Or convert the result to string and the use .substring(...)

(total_star / total_user).toString().substring(0,2)

The first example may not get you the result you're looking for because .substring(0, 2) will give you the first two characters and .toFixed(2) will give you the result with two decimals after the decimal point.


问:
Determine the source of the change in the richtextbox
I have a form with a richtextbox.
I change the text programmatically and the user is able to change it.
Is there a way to determine what caused the change?

The programmatically changes done by changing its rtf property:

```<code>rtb1.Rtf = rtb2.Rtf;
</code>```

答:
Try this:

Create a property MyRtf to save your changes

```<code>public string MyRtf { get; set; }
public Form1()
{
    InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
    MyRtf = richTextBox1.Rtf;
}
</code>```

In RichTextBox1_TextChanged event check for MyRtf. like this:

```<code>private void RichTextBox1_TextChanged(object sender, EventArgs e)
{
    if (richTextBox1.Rtf != MyRtf)
    {
        // do something
    }
}
</code>```

Body:
I have a form with a richtextbox.
I change the text programmatically and the user is able to change it.
Is there a way to determine what caused the change?

The programmatically changes done by changing its rtf property:

rtb1.Rtf = rtb2.Rtf;

Body:
Try this:

Create a property MyRtf to save your changes

public string MyRtf { get; set; }
public Form1()
{
    InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
    MyRtf = richTextBox1.Rtf;
}

In RichTextBox1_TextChanged event check for MyRtf. like this:

private void RichTextBox1_TextChanged(object sender, EventArgs e)
{
    if (richTextBox1.Rtf != MyRtf)
    {
        // do something
    }
}


问:
Add attachments to attachments array
I have the below function that adds attachments from an <input type="file" multiple /> to a parent's state.

That works fine until the user wants to add another attachment/s, the new attachment/s override the existing ones, how can I have the new attachments be added to the existing attachments array?

```<code>handleAddAttachments = fileList => {
  this.props.handleChange('attachments', Array.from(fileList));
};
</code>```

I tried that but it doesn't seem to work.

```<code>handleAddAttachments = fileList => {
  const { attachments } = this.props.ticket;
  this.props.handleChange('attachments', [...attachments, fileList]);
};
</code>```

The parent handleChange function:

```<code>makeHandleChange = (pageName, change) => {
  this.setState({
    ticket: { ...this.state.ticket, [pageName]: change },
  });
};
</code>```

答:
In your second version you are missing the Array.from() part. The change from a fileInput is not directly an array, so the spread operator does not work.

This should do the trick:

```<code>handleAddAttachments = fileList => {
  const { attachments } = this.props.ticket;
  this.props.handleChange('attachments', [...attachments, ...Array.from(fileList)]);
};
</code>```

For further information why it is not an array, you can find some information here: Why isn't the FileList object an array?

Thanks @sigmus, I added the missing spread to the Array.from()

Title: Add attachments to attachments array

Body:
I have the below function that adds attachments from an <input type="file" multiple /> to a parent's state.

That works fine until the user wants to add another attachment/s, the new attachment/s override the existing ones, how can I have the new attachments be added to the existing attachments array?

handleAddAttachments = fileList => {
  this.props.handleChange('attachments', Array.from(fileList));
};

I tried that but it doesn't seem to work.

handleAddAttachments = fileList => {
  const { attachments } = this.props.ticket;
  this.props.handleChange('attachments', [...attachments, fileList]);
};

The parent handleChange function:

makeHandleChange = (pageName, change) => {
  this.setState({
    ticket: { ...this.state.ticket, [pageName]: change },
  });
};

Body:
In your second version you are missing the Array.from() part. The change from a fileInput is not directly an array, so the spread operator does not work.

This should do the trick:

handleAddAttachments = fileList => {
  const { attachments } = this.props.ticket;
  this.props.handleChange('attachments', [...attachments, ...Array.from(fileList)]);
};

For further information why it is not an array, you can find some information here: Why isn't the FileList object an array?

Thanks @sigmus, I added the missing spread to the Array.from()


问:
How to immediately stop a running DbContext.SaveChanges()
I am currently developing a service. Services have limited time to shut down (4s).

I have a shutdown procedure, and this also pushes some minor data via EF6 to an sql database.

...

shutdown!

Step1 (stops normal operation)

step2 pushes some shutdown data to the db

step3 Final shutdown, dispose all etc.

The app has more than one context, and one execution strategy that is set in a way that it retries for about a minute. I'd like to keep that this way.

Now it may so happen that the database is down - and thus this call to the database takes a long time, maximum 1 minute because of the execution policy.

This is way over the 4s and so i would like to have an option to immediately stop the action. I cannot ask for more time.

So far i have tried the SaveChangesAsync(cancellationToken); but this still continues execution for a minute, cancelling the token does nothing. I then tried using a second Task to call dispose on the context, close the connection, etc. This sometimes seemed to work, but in other cases this still waits a minute before throwing an exception.

```<code>var timeoutTask = Task.Run(() =>
            {
                while (true)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        context.Database.Connection.Close();
                        Debug.WriteLine($"{DateTime.Now:G} {nameof(cancellationToken)} token is canceled!");
                        using(context) { }
                        return;
                    }

                    Task.Delay(10, timeoutTaskTokenSource.Token).Wait(timeoutTaskTokenSource.Token);

                    timeoutTaskTokenSource.Token.ThrowIfCancellationRequested();
                }
            }, cancellationToken);
</code>```

Right now i am thinking about creating a thread and aborting it, however i hope i can find a more sensible solution.

EDIT:

Connection timeout is set in the connection string:

```<code>Data Source=localhost;Initial Catalog=MyDb;Integrated Security=False;User ID=someuser;Password=somepassword;MultipleActiveResultSets=True;Connect Timeout=1;Application ame=somename;ConnectRetryCount=0;ConnectRetryInterval=1
</code>```

The command timeout is set to 1 aswell.

答:
If the database is unavailable you could use the Connection Timeout property of your connection string. This will abort the connection attempt after the delay. </p>

<p>If you wantn to abort a command you could use the CommandTimeout property. </p>

```<code>context.Database.CommandTimeout = 5;
</code>```

Body:
I am currently developing a service. Services have limited time to shut down (4s).

I have a shutdown procedure, and this also pushes some minor data via EF6 to an sql database.

...

shutdown!

Step1 (stops normal operation)

step2 pushes some shutdown data to the db

step3 Final shutdown, dispose all etc.

The app has more than one context, and one execution strategy that is set in a way that it retries for about a minute. I'd like to keep that this way.

Now it may so happen that the database is down - and thus this call to the database takes a long time, maximum 1 minute because of the execution policy.

This is way over the 4s and so i would like to have an option to immediately stop the action. I cannot ask for more time.

So far i have tried the SaveChangesAsync(cancellationToken); but this still continues execution for a minute, cancelling the token does nothing. I then tried using a second Task to call dispose on the context, close the connection, etc. This sometimes seemed to work, but in other cases this still waits a minute before throwing an exception.

var timeoutTask = Task.Run(() =>
            {
                while (true)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        context.Database.Connection.Close();
                        Debug.WriteLine($"{DateTime.Now:G} {nameof(cancellationToken)} token is canceled!");
                        using(context) { }
                        return;
                    }

                    Task.Delay(10, timeoutTaskTokenSource.Token).Wait(timeoutTaskTokenSource.Token);

                    timeoutTaskTokenSource.Token.ThrowIfCancellationRequested();
                }
            }, cancellationToken);

Right now i am thinking about creating a thread and aborting it, however i hope i can find a more sensible solution.

EDIT:

Connection timeout is set in the connection string:

Data Source=localhost;Initial Catalog=MyDb;Integrated Security=False;User ID=someuser;Password=somepassword;MultipleActiveResultSets=True;Connect Timeout=1;Application ame=somename;ConnectRetryCount=0;ConnectRetryInterval=1

The command timeout is set to 1 aswell.

Body:
If the database is unavailable you could use the Connection Timeout property of your connection string. This will abort the connection attempt after the delay.

If you wantn to abort a command you could use the CommandTimeout property.

context.Database.CommandTimeout = 5;


问:
Mocha test with SuperTest always passes (even when wrong)
I'm using Mocha and SuperTest to test my Express API. However my first test always seems to pass when inside the .then() of my request().

I'm passing in a String to a test that is expecting an Array. So should definitely fail the test.

It fails outside of the then() as expected, but I won't have access to the res.body there to perform my tests.

Here is my code:

```<code>const expect = require('chai').expect;
const request = require('supertest');

const router = require('../../routes/api/playlist.route');
const app = require('../../app');

describe('Playlist Route', function() {
    // before((done) => {

    // }
    describe('Get all playlists by user', function() {
        it('Should error out with "No playlists found" if there are no Playlists', function() {
            request(app).get('/api/playlists/all')
                .then(res => {
                    const { body } = res;

                    // Test passes if expect here
                    expect('sdfb').to.be.an('array');
                })
                .catch(err => {
                    console.log('err: ', err);
                });
            // Test fails if expect here
            expect('sdfb').to.be.an('array');
        })
    })
});
</code>```

I found this article but I'm not using a try catch block, but I thought maybe it could have something to do with the promise.

答:
Quick reponse

```<code>it('decription', function(done) {
    asyncFunc()
        .then(() => {
            expect(something).to.be(somethingElse)
            done()
        })
})
</code>```

Detailed response in the comment of @jonrsharpe

Body:
I'm using Mocha and SuperTest to test my Express API. However my first test always seems to pass when inside the .then() of my request().

I'm passing in a String to a test that is expecting an Array. So should definitely fail the test.

It fails outside of the then() as expected, but I won't have access to the res.body there to perform my tests.

Here is my code:

const expect = require('chai').expect;
const request = require('supertest');

const router = require('../../routes/api/playlist.route');
const app = require('../../app');

describe('Playlist Route', function() {
    // before((done) => {

    // }
    describe('Get all playlists by user', function() {
        it('Should error out with "No playlists found" if there are no Playlists', function() {
            request(app).get('/api/playlists/all')
                .then(res => {
                    const { body } = res;

                    // Test passes if expect here
                    expect('sdfb').to.be.an('array');
                })
                .catch(err => {
                    console.log('err: ', err);
                });
            // Test fails if expect here
            expect('sdfb').to.be.an('array');
        })
    })
});

I found this article but I'm not using a try catch block, but I thought maybe it could have something to do with the promise.

Body:
Quick reponse

it('decription', function(done) {
    asyncFunc()
        .then(() => {
            expect(something).to.be(somethingElse)
            done()
        })
})

Detailed response in the comment of @jonrsharpe


问:
How to send a jms message to activeMQ and decode it in javascript with mqttJS properly
I have a java backend, where I can send messages to topics via

```<code>jmsTemplate.convertAndSend("topic", "Hello World!");
</code>```

In my javascript frontend I use mqttJS to connect to activeMQ and recieve the massage:

```<code>    let mqtt = require('mqtt')
    let options ={
        clientId:"test",
        username:"username",
        useSSL: true,
        password:"password",
        clean:true};
    let client  = mqtt.connect(
        'wss://someUrl.com:61619',
        options);

    client.on('connect', function () {
        client.subscribe('myTopic', function (err) {
            if (!err) {
                console.log("successfully connected to myTopic'");
            }
        })
    });

    client.on('message', function (topic, message) {
        console.log(message.toString());
    });
</code>```

The message I recieve from the backend is something like this:

```<code>S�A S�)�x-opt-jms-destQ�x-opt-jms-msg-typeQ Ss�   f
�/ID:myID@�topic://myTopic@@@@�  j��< St�
e Sw�  Hello World!
</code>```

My message "Hello World!" is there. But also a bunch of unreadable into, I would guess from the header.

I tried different MessageConverters on the backend side and different parsers on the frontend side. Nothing works.

What do I need to do, to get just "Hello World!" as message? Or is there a better way to send the message, using jms, which is required.

答:
If tou are using mqtt 3.0.0 you should add extra parameters:

If you are connecting to a broker that supports only MQTT 3.1 (not 3.1.1 compliant), you should pass these additional options:

```<code>{
   protocolId: 'MQIsdp',
   protocolVersion: 3
 }
</code>```

Body:
I have a java backend, where I can send messages to topics via

jmsTemplate.convertAndSend("topic", "Hello World!");

In my javascript frontend I use mqttJS to connect to activeMQ and recieve the massage:

    let mqtt = require('mqtt')
    let options ={
        clientId:"test",
        username:"username",
        useSSL: true,
        password:"password",
        clean:true};
    let client  = mqtt.connect(
        'wss://someUrl.com:61619',
        options);

    client.on('connect', function () {
        client.subscribe('myTopic', function (err) {
            if (!err) {
                console.log("successfully connected to myTopic'");
            }
        })
    });

    client.on('message', function (topic, message) {
        console.log(message.toString());
    });

The message I recieve from the backend is something like this:

S�A S�)�x-opt-jms-destQ�x-opt-jms-msg-typeQ Ss�   f
�/ID:myID@�topic://myTopic@@@@�  j��< St�
e Sw�  Hello World!

My message "Hello World!" is there. But also a bunch of unreadable into, I would guess from the header.

I tried different MessageConverters on the backend side and different parsers on the frontend side. Nothing works.

What do I need to do, to get just "Hello World!" as message? Or is there a better way to send the message, using jms, which is required.

Body:
If tou are using mqtt 3.0.0 you should add extra parameters:

If you are connecting to a broker that supports only MQTT 3.1 (not 3.1.1 compliant), you should pass these additional options:

{
   protocolId: 'MQIsdp',
   protocolVersion: 3
 }


问:
How to zip files from folder but keep it separated
I have 1 folder that contains many txt files. I want to zip them but separated.

Example:

In this folder I have A.txt, B.txt, C.txt.

I want to zip all the files but separated so the result will be A.zip, B.zip, C.zip.

string outputPath = "C:\\Users\\Desktop\\VA";
string path = outputPath + "\\VA_" + tglskrg;
foreach (string dirFile in Directory.GetDirectories(path))
{
    foreach (string fileName in Directory.GetFiles(dirFile))
    {
        using (ZipFile zip = new ZipFile())
        {
            zip.UseUnicodeAsNecessary = true;
            zip.AddFile(); //dont know what to put
            zip.Save(); //dont know what to put
        }
    }
}
```

Any help will be appreciated.

I'm using dotnetzip (Ionic.zip) and C# Visual Studio Express 2010.

答:
You could do that as follows:

```<code>foreach (string fileName in Directory.GetFiles(dirFile))
{
    var zipFile = Path.Combine(outputPath, Path.ChangeExtension(fileName, ".zip"));
    using (ZipFile zip = new ZipFile())
    {
        zip.AddFile(fileName); // add A.txt to the zip file
        zip.Save(zipFile); // save as A.zip
    }
}
</code>```

This takes all the files found in the folder dirFile, and saves them under outputPath, with the same file name but replacing the extension with .zip.

Body:
I have 1 folder that contains many txt files. I want to zip them but separated.

Example:

In this folder I have A.txt, B.txt, C.txt.

I want to zip all the files but separated so the result will be A.zip, B.zip, C.zip.

string outputPath = "C:\\Users\\Desktop\\VA";
string path = outputPath + "\\VA_" + tglskrg;
foreach (string dirFile in Directory.GetDirectories(path))
{
    foreach (string fileName in Directory.GetFiles(dirFile))
    {
        using (ZipFile zip = new ZipFile())
        {
            zip.UseUnicodeAsNecessary = true;
            zip.AddFile(); //dont know what to put
            zip.Save(); //dont know what to put
        }
    }
}

Any help will be appreciated.

I'm using dotnetzip (Ionic.zip) and C# Visual Studio Express 2010.

Body:
You could do that as follows:

foreach (string fileName in Directory.GetFiles(dirFile))
{
    var zipFile = Path.Combine(outputPath, Path.ChangeExtension(fileName, ".zip"));
    using (ZipFile zip = new ZipFile())
    {
        zip.AddFile(fileName); // add A.txt to the zip file
        zip.Save(zipFile); // save as A.zip
    }
}

This takes all the files found in the folder dirFile, and saves them under outputPath, with the same file name but replacing the extension with .zip.


问:
NodeJS - Send JSON object parameters with node-fetch
I'm trying to create a webhook via the GitHub API. The docs say that I need to provide a config parameter, which should be an object, but I'm not sure how I can send a JSON in the URL parameters. Here's what I've tried:

```<code>fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config={"url": "https://webhooks.example.com", "content_type": "json"}`, {
    method: "POST",
    headers: {
        Accept: "application/vnd.github.v3+json",
        Authorization: `token ${account.accessToken}`
    }
});
</code>```

and

```<code>fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config.url=https://webhooks.example.com&config.content_type=json`, {
    method: "POST",
    headers: {
        Accept: "application/vnd.github.v3+json",
        Authorization: `token ${account.accessToken}`
    }
});
</code>```

They both result in the following error:

```<code>{
    "message": "Validation Failed",
    "errors": [
        {
            "resource": "Hook",
            "code": "custom",
            "message": "Config must contain URL for webhooks"
        }
    ],
    "documentation_url": "https://developer.github.com/v3/repos/hooks/#create-a-hook"
}
</code>```

How do I properly send a JSON object? I'm looking for a solution using node-fetch

答:
When you are doing a post request, it's implied that there will be a payload and the lib you are using will be expecting a body property containing your payload.

So just add

fetch('https://api.github.com/repos/${repo.full_name}/hooks', {
    method: "POST",
    headers: {
        Accept: "application/vnd.github.v3+json",
        Authorization: `token ${account.accessToken}`
    },
    body:JSON.stringify(yourJSON) //here this is how you send your datas
});
```

And node-fetch will send your body with your request.

If you want more details on that i'll expand my answer

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods here for a quick description of different http request type (verb)

Body:
I'm trying to create a webhook via the GitHub API. The docs say that I need to provide a config parameter, which should be an object, but I'm not sure how I can send a JSON in the URL parameters. Here's what I've tried:

fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config={"url": "https://webhooks.example.com", "content_type": "json"}`, {
    method: "POST",
    headers: {
        Accept: "application/vnd.github.v3+json",
        Authorization: `token ${account.accessToken}`
    }
});

and

fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config.url=https://webhooks.example.com&config.content_type=json`, {
    method: "POST",
    headers: {
        Accept: "application/vnd.github.v3+json",
        Authorization: `token ${account.accessToken}`
    }
});

They both result in the following error:

{
    "message": "Validation Failed",
    "errors": [
        {
            "resource": "Hook",
            "code": "custom",
            "message": "Config must contain URL for webhooks"
        }
    ],
    "documentation_url": "https://developer.github.com/v3/repos/hooks/#create-a-hook"
}

How do I properly send a JSON object? I'm looking for a solution using node-fetch

Body:
When you are doing a post request, it's implied that there will be a payload and the lib you are using will be expecting a body property containing your payload.

So just add

fetch('https://api.github.com/repos/${repo.full_name}/hooks', {
    method: "POST",
    headers: {
        Accept: "application/vnd.github.v3+json",
        Authorization: `token ${account.accessToken}`
    },
    body:JSON.stringify(yourJSON) //here this is how you send your datas
});

And node-fetch will send your body with your request.

If you want more details on that i'll expand my answer

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods here for a quick description of different http request type (verb)


问:
Control does not switch while new window pops up
This is regarding selenium automation testing based in java, While trying to select a language from a window that pops up after i make a click on the current window, the control however does not transfer from the current window to the popped up window.

How do i enter values on the new pop up tab and then go back to the original one.

答:
That's a new window, For that you'd have to switch the focus of web driver :

```<code>String winHandleBefore = driver.getWindowHandle();
// write the code here for click on Page 1
for(String winHandle : driver.getWindowHandles()){
            driver.switchTo().window(winHandle);
}
</code>```

//Do your things on Page2

//Switching Back to Page 1

```<code>driver.switchTo().window(winHandleBefore);
driver().switchTo().defaultContent()
</code>```

Body:
That's a new window, For that you'd have to switch the focus of web driver :

String winHandleBefore = driver.getWindowHandle();
// write the code here for click on Page 1
for(String winHandle : driver.getWindowHandles()){
            driver.switchTo().window(winHandle);
}

//Do your things on Page2

//Switching Back to Page 1

driver.switchTo().window(winHandleBefore);
driver().switchTo().defaultContent()


问:
Forcing usermod with running program
I've been looking for a way to force usermod to modify the password/group/... files despite the user being in use.

What I do get now is this:

```<code>!! Failed to execute 'usermod --home '...' --password '...' --shell '/bin/false' 'zabbix' 2>&1':
usermod: user zabbix is currently used by process 518
</code>```

I know that for being secure I need to restart the service. But this is done within a setup script. I am restarting all services at the end.

Is there any way to say --force? (well, except for modifying all necessary files.)

Thanks

答:
You can run usermod in a separate user namespace (with a recent enough linux), but you need to map the root user to root (otherwise you won't have permissions to modify /etc/passwd).

I.e. something like this:

```<code>unshare --user --map-root-user usermod ...
</code>```

Now usermod won't find the processes running with the uid of user you are modifying.

You probably won't be able to modify the root user itself with this.

Title: Forcing usermod with running program

Body:
I've been looking for a way to force usermod to modify the password/group/... files despite the user being in use.

What I do get now is this:

!! Failed to execute 'usermod --home '...' --password '...' --shell '/bin/false' 'zabbix' 2>&1':
usermod: user zabbix is currently used by process 518

I know that for being secure I need to restart the service. But this is done within a setup script. I am restarting all services at the end.

Is there any way to say --force? (well, except for modifying all necessary files.)

Thanks

Body:
You can run usermod in a separate user namespace (with a recent enough linux), but you need to map the root user to root (otherwise you won't have permissions to modify /etc/passwd).

I.e. something like this:

unshare --user --map-root-user usermod ...

Now usermod won't find the processes running with the uid of user you are modifying.

You probably won't be able to modify the root user itself with this.


问:
KSQL 'SELECT *' query takes 10 seconds before it starts returning any results
I have a ksql table with less than 1000 records in it. When I run this query select * from table_name it takes up to 10 seconds before the query starts to return any data.

The machine running Kafka, zookeeper, ksql and schema registry is not overloaded or anything like that.

I am using a dev setup with 1 broker and 1 ksql server.

The table has simple un-nested json with two fields, email and a user id

This is a problem because I can't use this for a single lookup, for example, using a query like this

SELECT * FROM TABLE_NAME WHERE col='value';
```

since it takes too long to return a result. I expected results would be returned instantly.

The time taken is the same if I use streams instead of tables

答:
When I run this query select * from table_name it takes up to 15 seconds before the query starts to return any data.

It may take a little while until a streaming query in KSQL is fully up and running. Fifteen seconds sounds a bit too long, but depending on your local environment the startup delay may still explain the observed behavior.

I have a ksql table with less than 1000 records in it.

If the SELECT query is up and running, and you then write a few new records into the table's underlying topic (e.g. in another terminal), how quickly do these records show up in the SELECT query? This should happen much faster because there is no startup delay (the query should be fully up and running at that point).

Body:
I have a ksql table with less than 1000 records in it. When I run this query select * from table_name it takes up to 10 seconds before the query starts to return any data.

The machine running Kafka, zookeeper, ksql and schema registry is not overloaded or anything like that.

I am using a dev setup with 1 broker and 1 ksql server.

The table has simple un-nested json with two fields, email and a user id

This is a problem because I can't use this for a single lookup, for example, using a query like this

SELECT * FROM TABLE_NAME WHERE col='value';

since it takes too long to return a result. I expected results would be returned instantly.

The time taken is the same if I use streams instead of tables


问:
Oracle : Selecting date by month with where clause
I came across a problem that in selecting the date for current desired month and year. I tried the 2 statements shown below but failed to execute the query

```<code>select to_char(sysdate, 'Month') from income

select * from income where to_char(sysdate,month) = 'feb'
</code>```

Update

But after researching and learning more in depth on oracle docs website. What i came out with is to use  "between" clause. Specifying the first day and last day of the month . Doing so, it will execute the desired month/year

For an example

```<code>SELECT column_name
FROM table_name where column_name = (Your own value) AND
column_date >= to_date('01/02/2012', 'dd/mm/yyyy')
and column_date <  to_date('01/03/2012', 'dd/mm/yyyy')
</code>```

I hope this help :)

答:
Are you after something like:

```<code>select *
from   income
where  <date_column> >= to_date('01/05/2019', 'dd/mm/yyyy')
and    <date_column> <  to_date('01/06/2019', 'dd/mm/yyyy')
</code>```

(replacing <date_column> with the name of the date column in your income table that you want to filter on)?

Body:
I came across a problem that in selecting the date for current desired month and year. I tried the 2 statements shown below but failed to execute the query

select to_char(sysdate, 'Month') from income

select * from income where to_char(sysdate,month) = 'feb'

Update

But after researching and learning more in depth on oracle docs website. What i came out with is to use  "between" clause. Specifying the first day and last day of the month . Doing so, it will execute the desired month/year

For an example

SELECT column_name
FROM table_name where column_name = (Your own value) AND
column_date >= to_date('01/02/2012', 'dd/mm/yyyy')
and column_date <  to_date('01/03/2012', 'dd/mm/yyyy')

I hope this help :)

Body:
Are you after something like:

select *
from   income
where  <date_column> >= to_date('01/05/2019', 'dd/mm/yyyy')
and    <date_column> <  to_date('01/06/2019', 'dd/mm/yyyy')

(replacing <date_column> with the name of the date column in your income table that you want to filter on)?


问:
Installing npm package fails with 404
Using the command prompt, I am trying to install angular CLI and it fails. I have npm version 5.5.1 and node version v8.9.1. I am trying to install angular cli using the command

npm install -g @angular/cli@latest

and it fails with the error:

npm ERR! code E404
  npm ERR! 404 Not Found: @angular/cli@latest
  npm ERR! A complete log of this run can be found in:

I look at the log file and I see its trying to fetch the package from a location that doesn't exist. Not sure from where it gets pulled. How do I fix this location path and install angular cli. Same happens when I try to install typescript or any other npm package. all of them try to install from the location mentioned below and it fails with 404

```<code>8 http fetch GET 404
       http://nuget.feed.xyz.corp:8729/npm/FeedNPM/@angular%2fcli 109ms
9 silly fetchPackageMetaData error for @angular/cli@latest 404 Not Found:
     @angular/cli@latest
10 verbose stack Error: 404 Not Found: @angular/cli@latest
</code>```

答:
I had same problem with a private package.
Need to:

npm adduser

npm login

Title: Installing npm package fails with 404

Body:
Using the command prompt, I am trying to install angular CLI and it fails. I have npm version 5.5.1 and node version v8.9.1. I am trying to install angular cli using the command

npm install -g @angular/cli@latest

and it fails with the error:

npm ERR! code E404
  npm ERR! 404 Not Found: @angular/cli@latest
  npm ERR! A complete log of this run can be found in:

I look at the log file and I see its trying to fetch the package from a location that doesn't exist. Not sure from where it gets pulled. How do I fix this location path and install angular cli. Same happens when I try to install typescript or any other npm package. all of them try to install from the location mentioned below and it fails with 404

8 http fetch GET 404
       http://nuget.feed.xyz.corp:8729/npm/FeedNPM/@angular%2fcli 109ms
9 silly fetchPackageMetaData error for @angular/cli@latest 404 Not Found:
     @angular/cli@latest
10 verbose stack Error: 404 Not Found: @angular/cli@latest


问:
Get executing assembly name from referenced DLL in C#
What is the best way to get the application name (i.e MyApplication.exe) of the executing assembly from a referenced class library in C#?

I need to open the application's app.config to retrieve some appSettings variables for the referenced DLL.

答:
You should never couple your libraries to a consumer (in this case Web, WinForm or WCF app). If your library needs configuration settings, then GIVE it to the library.

Don't code the library to pull that data from a consumer's config file. Provide overloaded constructors for this (that's what they are for).

If you've ever looked at the ConfigurationManager.AppSettings object, it is simply a NameValueCollection. So create a constructor in your library to accept a NameValueCollection and have your consumer GIVE that data to the library.

```<code>//Library
public class MyComponent
{
  //Constructor
  public MyComponent(NameValueCollection settings)
  {
     //do something with your settings now, like assign to a local collection
  }
}

//Consumer
class Program
{
  static void Main(string[] args)
  {
    MyComponent component = new MyComponent(ConfigurationManager.AppSettings);
  }
}
</code>```

OwnerDisplayName: Michael Kniskern

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mdb

Body:
You should never couple your libraries to a consumer (in this case Web, WinForm or WCF app). If your library needs configuration settings, then GIVE it to the library.

Don't code the library to pull that data from a consumer's config file. Provide overloaded constructors for this (that's what they are for).

If you've ever looked at the ConfigurationManager.AppSettings object, it is simply a NameValueCollection. So create a constructor in your library to accept a NameValueCollection and have your consumer GIVE that data to the library.

//Library
public class MyComponent
{
  //Constructor
  public MyComponent(NameValueCollection settings)
  {
     //do something with your settings now, like assign to a local collection
  }
}

//Consumer
class Program
{
  static void Main(string[] args)
  {
    MyComponent component = new MyComponent(ConfigurationManager.AppSettings);
  }
}


问:
CSS Height:100% issue
I'm trying to get the div wrapper to surround all the divs within it so depending on the amount of content the height of wrapper will grow.

I guessed that the way of doing this would be to set height: 100% but as you can see from the screen grab below, this is not the case.

Where it says 'No :-(' is what having height: 100% is doing where ideally I would like wrapper to be at the bottom where it says 'Yes' and I have drawn a red line.

Any help is much appreciated.

答:
If you are using floats, giving the container overflow:hidden might fix the problem. If no fixed size is given to the div, this makes it stretch over the floated elements.

If you have absolutely positioned elements inside the container, it would be good to see the html/css for a solution.

Title: CSS Height:100% issue


问:
why identical() return true on two strings
I'm new to Dart. The documentation say: "To test whether two objects x and y represent the same thing, use the == operator. (In the rare case where you need to know whether two objects are the exact same object, use the identical() function instead.)"

So, if type this code:

var foo = 'bar';
var baz = 'bar';
print(identical(foo, baz));
```

If i've well understood, foo and bar do not reference the same object. So identical() must return false, isn't it ?
But it's not the case, at least in DartPad.

Where is the problem.

答:
In this case foo and bar do reference the same object.
That is because the compiler canonicalizes string literals.

The specification requires most constants to be canonicalized. If you create const Duration(seconds: 1) in two places, it will become the same object. Integers, doubles and booleans are always canonicalized, whether constant or not (the language pretends that there is only one instance per value).

Strings are special in that the specification is not entirely clear on whether they need to be canonicalized or not, but constant strings need to be canonicalized for constants to make sense, and all the compilers do that.
A literal is a constant expression, so string literals are always canonicalized. That means that 'bar' denotes the same object no matter where it occurs in your code.

Body:
I'm new to Dart. The documentation say: "To test whether two objects x and y represent the same thing, use the == operator. (In the rare case where you need to know whether two objects are the exact same object, use the identical() function instead.)"

So, if type this code:

var foo = 'bar';
var baz = 'bar';
print(identical(foo, baz));

If i've well understood, foo and bar do not reference the same object. So identical() must return false, isn't it ?
But it's not the case, at least in DartPad.

Where is the problem.


问:
JSON.NET Error Self referencing loop detected for type
I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used

JsonConvert.SerializeObject
```

I got the following error:

Error Self referencing loop detected for type System.data.entity occurs.

How do I solve this problem?

答:
My Problem Solved With Custom Config JsonSerializerSettings:</p>

```<code>services.AddMvc(
  // ...
               ).AddJsonOptions(opt =>
                 {
                opt.SerializerSettings.ReferenceLoopHandling =
                    Newtonsoft.Json.ReferenceLoopHandling.Serialize;
                opt.SerializerSettings.PreserveReferencesHandling =
                    Newtonsoft.Json.PreserveReferencesHandling.Objects;
                 });
</code>```

Body:
I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used

JsonConvert.SerializeObject

I got the following error:

Error Self referencing loop detected for type System.data.entity occurs.

How do I solve this problem?

Body:
My Problem Solved With Custom Config JsonSerializerSettings:

services.AddMvc(
  // ...
               ).AddJsonOptions(opt =>
                 {
                opt.SerializerSettings.ReferenceLoopHandling =
                    Newtonsoft.Json.ReferenceLoopHandling.Serialize;
                opt.SerializerSettings.PreserveReferencesHandling =
                    Newtonsoft.Json.PreserveReferencesHandling.Objects;
                 });


问:
Can the bootstrap servers be changed without restarting the KAFKA clients?
KAFKA clients (producer & consumer) discover the topology by connecting to one the configured bootstrap server and from then on it will work with those set of broker nodes in the cluster directly.

With that standard thing, can we change producer and consumer without restarting them to work with different cluster by changing the bootstrap servers? Can we change the bootstrap server Config without restarting the clients?

There is a client config called metadata.max.age.ms which will force the client to refresh the broker topology but that covers only new partition leader and new broker node added to the cluster.

This is mainly to cover the scenario where KAFKA Cluster in a DC is down for some unexpected reason and clients from the same DC who already established connection with the same DC KAFKA cluster and want to explore the option of redirecting already started KAFKA clients to work with other DC KAFKA cluster in case same DC cluster is down.

答:
You cannot change the configured bootstrap servers in the official Kafka Client.

Clients are able to discover the full Kafka cluster from the initial bootstrap servers and will periodically refresh this data (every metadata.max.age.ms) but they cannot be moved to another cluster on the fly.

As you mentioned, clients will need to be restarted pointing to the new cluster.


问:
Why is a Base64 string displayed as empty in Message Box?
I have to encode some HTML source code into base64 format before form submission, and then decode it back to original code in the code behind. Here is the testing code by MsgBox:

```<code>MsgBox(HttpContext.Current.Request.Form("encodedSourceCode"))
MsgBox(Convert.ToString(HttpContext.Current.Request.Form("encodedSourceCode").GetType()))
Dim b = Convert.FromBase64String(HttpContext.Current.Request.Form("encodedSourceCode"))
Dim html = System.Text.Encoding.UTF8.GetString(b)
MsgBox(html)
</code>```

And I have added an alert() for encodedSourceCode in client script.

The results turn out to be:

First MsgBox: Empty

Second MsgBox: "System.String"

Last MsgBox: Original HTML source code

And the JS alert dialog shows the base64 string, which consists of a bunch of digits and alphabets.

In short, everything is fine, except the first MsgBox, which is supposed to be base64 encoded string but turns out to be empty. Why? Is it normal?

Actually it does not matter much because even the final result (after decoding) seems to have no problem, but I'm just curious why the interim result is not shown as what it's supposed to be.

答:
It seems that the string is simply too long without 'wrappable' characters, I suppose. MsgBox cuts out the 'last word' and shows nothing.

This may confirm it:

```<code>dim test = HttpContext.Current.Request.Form("encodedSourceCode")
MsgBox(test) ' empty
test = test.Substring(0, 20)
MsgBox(test) ' shows the first 20 characters
</code>```

Testing in LinqPad, I get the limit around 43.000 characters:

```<code>MsgBox("".PadLeft(43000, "a"))
MsgBox("".PadLeft(44000, "a"))
MsgBox("".PadLeft(43000, "a") & " " & "".PadLeft(1000, "a"))
</code>```

1st: shows text.

2nd: shows empty box, length = 44.000

3rd: shows text, although the total length is 44.001, but wrappable at the space.

Body:
I have to encode some HTML source code into base64 format before form submission, and then decode it back to original code in the code behind. Here is the testing code by MsgBox:

MsgBox(HttpContext.Current.Request.Form("encodedSourceCode"))
MsgBox(Convert.ToString(HttpContext.Current.Request.Form("encodedSourceCode").GetType()))
Dim b = Convert.FromBase64String(HttpContext.Current.Request.Form("encodedSourceCode"))
Dim html = System.Text.Encoding.UTF8.GetString(b)
MsgBox(html)

And I have added an alert() for encodedSourceCode in client script.

The results turn out to be:

First MsgBox: Empty

Second MsgBox: "System.String"

Last MsgBox: Original HTML source code

And the JS alert dialog shows the base64 string, which consists of a bunch of digits and alphabets.

In short, everything is fine, except the first MsgBox, which is supposed to be base64 encoded string but turns out to be empty. Why? Is it normal?

Actually it does not matter much because even the final result (after decoding) seems to have no problem, but I'm just curious why the interim result is not shown as what it's supposed to be.

Body:
It seems that the string is simply too long without 'wrappable' characters, I suppose. MsgBox cuts out the 'last word' and shows nothing.

This may confirm it:

dim test = HttpContext.Current.Request.Form("encodedSourceCode")
MsgBox(test) ' empty
test = test.Substring(0, 20)
MsgBox(test) ' shows the first 20 characters

Testing in LinqPad, I get the limit around 43.000 characters:

MsgBox("".PadLeft(43000, "a"))
MsgBox("".PadLeft(44000, "a"))
MsgBox("".PadLeft(43000, "a") & " " & "".PadLeft(1000, "a"))

1st: shows text.

2nd: shows empty box, length = 44.000

3rd: shows text, although the total length is 44.001, but wrappable at the space.