问:
Including Stripe card info in ajax form removes authenticity_token
I have a form_tag using Ajax to save a new user card with Stripe. It renders a Stripe card form, passes the input to a controller method, and then is supposed to serve a js file. It works without the Stripe stuff, but with it, I'm getting authentication issues.

Here's the basic code:

```<code><%= form_tag(save_card_path, id:'payment-form', remote: true) do %>
    <div id="card-element">
      <!-- A Stripe Element will be inserted here. -->
    </div>
  <button id="submit-card" class="submit-btn">Save Card</button>
<% end %>

<script type="text/javascript">

  var stripe = Stripe('<%= @stripe_public %>');
  var elements = stripe.elements();

  // Custom styling can be passed to options when creating an Element.
  var style = {
    base: {
      // Add your base input styles here. For example:
      fontSize: '20px',
      color: "#32325d",
    }
  };

  // Create an instance of the card Element.
  var card = elements.create('card', {style: style});

  // Add an instance of the card Element into the `card-element` <div>.
  card.mount('#card-element');

  card.addEventListener('change', function(event) {
    var displayError = document.getElementById('card-errors');
    if (event.error) {
      displayError.textContent = event.error.message;
    } else {
      displayError.textContent = '';
    }
  });

  // Create a token or display an error when the form is submitted.
  var form = document.getElementById('payment-form');
  form.addEventListener('submit', function(event) {
    event.preventDefault();

    stripe.createToken(card).then(function(result) {
      if (result.error) {
        // Inform the customer that there was an error.
        var errorElement = document.getElementById('card-errors');
        errorElement.textContent = result.error.message;
      } else {
        // Send the token to your server.
        stripeTokenHandler(result.token);
      }
    });
  });

  function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);

    // Submit the form
    form.submit();
  }
</script>
</code>```

card_controller.rb

```<code>def save_card
  respond_to do |format|
    format.js
  end
end
</code>```

save_card.js.erb

```<code>$("html").hide();
</code>```

So like I said, without the Stripe code everything works fine, and an authenticity_token is present in the params, but the code as I wrote it above gives the following error:

```<code>    def handle_unverified_request
      raise ActionController::InvalidAuthenticityToken
    end
</code>```

with only the params:

```<code>{"utf8"=>"✓", "stripeToken"=>"<token>"}
</code>```

When I add the option authenticity_token: true to the form, the params once again contain an authenticity_token, but now when it gets to the format.js line, I get the error

```<code>ActionController::UnknownFormat
</code>```

I've run into a similar problem before while trying to upload files in forms via Ajax, but I discovered the remotipart gem, and that solved it. But it doesn't appear to help in this case.

Does anyone know why including a Stripe field would get rid of my authenticity_token, and why even with an authenticity_token, the js format isn't recognized?

EDIT:

Jquery-ujs is included via the line //= require jquery_ujs in my application.js, the line <%= csrf_meta_tags %> is included in application.html.erb, and my source code includes the lines

```<code><meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="<TOKEN>" />
</code>```

This is the case whether my ajax call works or not.

UPDATE:

This is my full log when I add the option authenticity_token: true:

Started POST "/save_card" for 127.0.0.1 at 2020-02-20 00:07:04 +0100

Processing by UsersController#save_card as HTML

Parameters:
  {"utf8"=>"✓",
  "authenticity_token"=>"[LONG TOKEN]",
  "post"=>"47", "transaction"=>"bid",
  "stripeToken"=>"[STRIPE TOKEN]"}

User Load (0.9ms)

SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY
  "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]

(0.3ms)  BEGIN
  SQL

(2.3ms)  INSERT INTO "cards" ("stripe_customer_id", "brand",
  "last4", "exp_month", "exp_year", "user_id", "created_at",
  "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"
  [["stripe_customer_id", "[STRIPE TOKEN]"], ["brand", "Visa"],
  ["last4", "4242"], ["exp_month", "4"], ["exp_year", "2024"],
  ["user_id", 2], ["created_at", "2020-02-19 23:07:05.246789"],
  ["updated_at", "2020-02-19 23:07:05.246789"]]

(2.8ms)  COMMIT

Completed 406 Not Acceptable in 672ms (ActiveRecord: 6.3ms)

ActionController::UnknownFormat (ActionController::UnknownFormat):
  app/controllers/users_controller.rb:485:in `save_card' Started GET
  "/serviceworker.js" for 127.0.0.1 at 2020-02-20 00:07:05 +0100 Started
  GET "/serviceworker.js" for ::1 at 2020-02-20 00:07:21 +0100

and this is my log when I remove authenticity_token: true:

Started POST "/save_card" for 127.0.0.1 at 2020-02-20 00:33:17 +0100

Processing by UsersController#save_card as HTML

Parameters:
  {"utf8"=>"✓", "post"=>"47", "transaction"=>"bid",
  "stripeToken"=>"[STRIPE TOKEN]"} Can't verify CSRF token
  authenticity. Completed 422 Unprocessable Entity in 1ms (ActiveRecord:
  0.0ms)

ActionController::InvalidAuthenticityToken
  (ActionController::InvalidAuthenticityToken):    actionpack (5.1.7)
  lib/action_controller/metal/request_forgery_protection.rb:195:in
  handle_unverified_request' actionpack (5.1.7)
  lib/action_controller/metal/request_forgery_protection.rb:227:in
  handle_unverified_request' devise (4.7.0)
  lib/devise/controllers/helpers.rb:255:in handle_unverified_request'
  actionpack (5.1.7)
  lib/action_controller/metal/request_forgery_protection.rb:222:in
  verify_authenticity_token' activesupport (5.1.7)
  lib/active_support/callbacks.rb:413:in block in make_lambda'
  activesupport (5.1.7) lib/active_support/callbacks.rb:197:inblock (2
  levels) in halting' actionpack (5.1.7)
  lib/abstract_controller/callbacks.rb:12:in block (2 levels) in
  <module:Callbacks>' activesupport (5.1.7)
  lib/active_support/callbacks.rb:198:inblock in halting'
  activesupport (5.1.7) lib/active_support/callbacks.rb:507:in block in
  invoke_before' activesupport (5.1.7)
  lib/active_support/callbacks.rb:507:ineach' activesupport (5.1.7)
  lib/active_support/callbacks.rb:507:in invoke_before' activesupport
  (5.1.7) lib/active_support/callbacks.rb:130:inrun_callbacks'
  actionpack (5.1.7) lib/abstract_controller/callbacks.rb:19:in
  process_action' actionpack (5.1.7)
  lib/action_controller/metal/rescue.rb:20:inprocess_action'
  actionpack (5.1.7)
  lib/action_controller/metal/instrumentation.rb:32:in block in
  process_action' activesupport (5.1.7)
  lib/active_support/notifications.rb:166:inblock in instrument'
  activesupport (5.1.7)
  lib/active_support/notifications/instrumenter.rb:21:in instrument'
  activesupport (5.1.7) lib/active_support/notifications.rb:166:in
  instrument' actionpack (5.1.7)
  lib/action_controller/metal/instrumentation.rb:30:in process_action'
  actionpack (5.1.7)
  lib/action_controller/metal/params_wrapper.rb:252:inprocess_action'
  activerecord (5.1.7)
  lib/active_record/railties/controller_runtime.rb:22:in
  process_action' actionpack (5.1.7)
  lib/abstract_controller/base.rb:124:inprocess' actionview (5.1.7)
  lib/action_view/rendering.rb:30:in process' actionpack (5.1.7)
  lib/action_controller/metal.rb:189:indispatch' actionpack (5.1.7)
  lib/action_controller/metal.rb:253:in dispatch' actionpack (5.1.7)
  lib/action_dispatch/routing/route_set.rb:49:indispatch' actionpack
  (5.1.7) lib/action_dispatch/routing/route_set.rb:31:in serve'
  actionpack (5.1.7) lib/action_dispatch/journey/router.rb:50:inblock
  in serve' actionpack (5.1.7)
  lib/action_dispatch/journey/router.rb:33:in each' actionpack (5.1.7)
  lib/action_dispatch/journey/router.rb:33:inserve' actionpack (5.1.7)
  lib/action_dispatch/routing/route_set.rb:844:in call'
  serviceworker-rails (0.6.0) lib/serviceworker/middleware.rb:35:in
  call' remotipart (1.4.3) lib/remotipart/middleware.rb:32:in call'
  warden (1.2.8) lib/warden/manager.rb:36:inblock in call' warden
  (1.2.8) lib/warden/manager.rb:34:in catch' warden (1.2.8)
  lib/warden/manager.rb:34:incall' rack (2.0.7) lib/rack/etag.rb:25:in
  call' rack (2.0.7) lib/rack/conditional_get.rb:38:incall' rack
  (2.0.7) lib/rack/head.rb:12:in call' rack (2.0.7)
  lib/rack/session/abstract/id.rb:232:incontext' rack (2.0.7)
  lib/rack/session/abstract/id.rb:226:in call' actionpack (5.1.7)
  lib/action_dispatch/middleware/cookies.rb:613:incall' activerecord
  (5.1.7) lib/active_record/migration.rb:556:in call' actionpack
  (5.1.7) lib/action_dispatch/middleware/callbacks.rb:26:inblock in
  call' activesupport (5.1.7) lib/active_support/callbacks.rb:97:in
  run_callbacks' actionpack (5.1.7)
  lib/action_dispatch/middleware/callbacks.rb:24:incall' actionpack
  (5.1.7) lib/action_dispatch/middleware/executor.rb:12:in call'
  actionpack (5.1.7)
  lib/action_dispatch/middleware/debug_exceptions.rb:59:incall'
  web-console (3.7.0) lib/web_console/middleware.rb:135:in call_app'
  web-console (3.7.0) lib/web_console/middleware.rb:30:inblock in
  call' web-console (3.7.0) lib/web_console/middleware.rb:20:in catch'
  web-console (3.7.0) lib/web_console/middleware.rb:20:incall'
  actionpack (5.1.7)
  lib/action_dispatch/middleware/show_exceptions.rb:31:in call'
  railties (5.1.7) lib/rails/rack/logger.rb:36:incall_app' railties
  (5.1.7) lib/rails/rack/logger.rb:24:in block in call' activesupport
  (5.1.7) lib/active_support/tagged_logging.rb:69:inblock in tagged'
  activesupport (5.1.7) lib/active_support/tagged_logging.rb:26:in
  tagged' activesupport (5.1.7)
  lib/active_support/tagged_logging.rb:69:intagged' railties (5.1.7)
  lib/rails/rack/logger.rb:24:in call' sprockets-rails (3.2.1)
  lib/sprockets/rails/quiet_assets.rb:13:incall' actionpack (5.1.7)
  lib/action_dispatch/middleware/remote_ip.rb:79:in call' actionpack
  (5.1.7) lib/action_dispatch/middleware/request_id.rb:25:incall' rack
  (2.0.7) lib/rack/method_override.rb:22:in call' rack (2.0.7)
  lib/rack/runtime.rb:22:incall' activesupport (5.1.7)
  lib/active_support/cache/strategy/local_cache_middleware.rb:27:in
  call' actionpack (5.1.7)
  lib/action_dispatch/middleware/executor.rb:12:incall' actionpack
  (5.1.7) lib/action_dispatch/middleware/static.rb:125:in call' rack
  (2.0.7) lib/rack/sendfile.rb:111:incall' railties (5.1.7)
  lib/rails/engine.rb:522:in call' puma (3.12.1)
  lib/puma/configuration.rb:227:incall' puma (3.12.1)
  lib/puma/server.rb:660:in handle_request' puma (3.12.1)
  lib/puma/server.rb:474:inprocess_client' puma (3.12.1)
  lib/puma/server.rb:334:in block in run' puma (3.12.1)
  lib/puma/thread_pool.rb:135:inblock in spawn_thread' Started GET
  "/serviceworker.js" for 127.0.0.1 at 2020-02-20 00:33:18 +0100

答:
Keep everything as it was, and just update .submit()

The actual issue is sending as HTML instead of as JS on form.submit().

https://github.com/rails/rails/issues/29546

```<code> //from
 form.submit();

 //to
 form.dispatchEvent(new Event('submit', {bubbles: true}));
</code>```

Updated

Previously, You were submitting, then asking to submit it again. OnClick button, get stripe data then submit with my answer. Sample below.

Also, you need to add disable/enable for submit button on click, to ignore multiple clicks.

```<code>...
// Create a token or display an error when the form is submitted.
  let submitCardBtn = document.getElementById('submit-card');

  submitCardBtn.addEventListener('click', function(event) {
    event.preventDefault();

   // disable button
    submitCardBtn.disabled = true;

    stripe.createToken(card).then(function(result) {
      if (result.error) {
        // Inform the customer that there was an error.
        var errorElement = document.getElementById('card-errors');
        errorElement.textContent = result.error.message;

        // enable button on false
        submitCardBtn.disabled = false;
      } else {
        // Send the token to your server.
        stripeTokenHandler(result.token);
      }
    });
  });

  function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);

    // Submit the form
   form.dispatchEvent(new Event('submit', {bubbles: true}));

   // enable button
   submitCardBtn.disabled = false;
  }

</code>```

Body:
I have a form_tag using Ajax to save a new user card with Stripe. It renders a Stripe card form, passes the input to a controller method, and then is supposed to serve a js file. It works without the Stripe stuff, but with it, I'm getting authentication issues.

Here's the basic code:

<%= form_tag(save_card_path, id:'payment-form', remote: true) do %>

  <button id="submit-card" class="submit-btn">Save Card</button>
<% end %>

card_controller.rb

def save_card
  respond_to do |format|
    format.js
  end
end

save_card.js.erb

$("html").hide();

So like I said, without the Stripe code everything works fine, and an authenticity_token is present in the params, but the code as I wrote it above gives the following error:

    def handle_unverified_request
      raise ActionController::InvalidAuthenticityToken
    end

with only the params:

{"utf8"=>"✓", "stripeToken"=>"<token>"}

When I add the option authenticity_token: true to the form, the params once again contain an authenticity_token, but now when it gets to the format.js line, I get the error

ActionController::UnknownFormat

I've run into a similar problem before while trying to upload files in forms via Ajax, but I discovered the remotipart gem, and that solved it. But it doesn't appear to help in this case.

Does anyone know why including a Stripe field would get rid of my authenticity_token, and why even with an authenticity_token, the js format isn't recognized?

EDIT:

Jquery-ujs is included via the line //= require jquery_ujs in my application.js, the line <%= csrf_meta_tags %> is included in application.html.erb, and my source code includes the lines

<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="<TOKEN>" />

This is the case whether my ajax call works or not.

UPDATE:

This is my full log when I add the option authenticity_token: true:

Started POST "/save_card" for 127.0.0.1 at 2020-02-20 00:07:04 +0100

Processing by UsersController#save_card as HTML

Parameters:
  {"utf8"=>"✓",
  "authenticity_token"=>"[LONG TOKEN]",
  "post"=>"47", "transaction"=>"bid",
  "stripeToken"=>"[STRIPE TOKEN]"}

User Load (0.9ms)

SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY
  "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]

(0.3ms)  BEGIN
  SQL

(2.3ms)  INSERT INTO "cards" ("stripe_customer_id", "brand",
  "last4", "exp_month", "exp_year", "user_id", "created_at",
  "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"
  [["stripe_customer_id", "[STRIPE TOKEN]"], ["brand", "Visa"],
  ["last4", "4242"], ["exp_month", "4"], ["exp_year", "2024"],
  ["user_id", 2], ["created_at", "2020-02-19 23:07:05.246789"],
  ["updated_at", "2020-02-19 23:07:05.246789"]]

(2.8ms)  COMMIT

Completed 406 Not Acceptable in 672ms (ActiveRecord: 6.3ms)

ActionController::UnknownFormat (ActionController::UnknownFormat):
  app/controllers/users_controller.rb:485:in `save_card' Started GET
  "/serviceworker.js" for 127.0.0.1 at 2020-02-20 00:07:05 +0100 Started
  GET "/serviceworker.js" for ::1 at 2020-02-20 00:07:21 +0100

and this is my log when I remove authenticity_token: true:

Started POST "/save_card" for 127.0.0.1 at 2020-02-20 00:33:17 +0100

Processing by UsersController#save_card as HTML

Parameters:
  {"utf8"=>"✓", "post"=>"47", "transaction"=>"bid",
  "stripeToken"=>"[STRIPE TOKEN]"} Can't verify CSRF token
  authenticity. Completed 422 Unprocessable Entity in 1ms (ActiveRecord:
  0.0ms)

ActionController::InvalidAuthenticityToken
  (ActionController::InvalidAuthenticityToken):    actionpack (5.1.7)
  lib/action_controller/metal/request_forgery_protection.rb:195:in
  handle_unverified_request' actionpack (5.1.7)
  lib/action_controller/metal/request_forgery_protection.rb:227:in
  handle_unverified_request' devise (4.7.0)
  lib/devise/controllers/helpers.rb:255:in handle_unverified_request'
  actionpack (5.1.7)
  lib/action_controller/metal/request_forgery_protection.rb:222:in
  verify_authenticity_token' activesupport (5.1.7)
  lib/active_support/callbacks.rb:413:in block in make_lambda'
  activesupport (5.1.7) lib/active_support/callbacks.rb:197:inblock (2
  levels) in halting' actionpack (5.1.7)
  lib/abstract_controller/callbacks.rb:12:in block (2 levels) in
  <module:Callbacks>' activesupport (5.1.7)
  lib/active_support/callbacks.rb:198:inblock in halting'
  activesupport (5.1.7) lib/active_support/callbacks.rb:507:in block in
  invoke_before' activesupport (5.1.7)
  lib/active_support/callbacks.rb:507:ineach' activesupport (5.1.7)
  lib/active_support/callbacks.rb:507:in invoke_before' activesupport
  (5.1.7) lib/active_support/callbacks.rb:130:inrun_callbacks'
  actionpack (5.1.7) lib/abstract_controller/callbacks.rb:19:in
  process_action' actionpack (5.1.7)
  lib/action_controller/metal/rescue.rb:20:inprocess_action'
  actionpack (5.1.7)
  lib/action_controller/metal/instrumentation.rb:32:in block in
  process_action' activesupport (5.1.7)
  lib/active_support/notifications.rb:166:inblock in instrument'
  activesupport (5.1.7)
  lib/active_support/notifications/instrumenter.rb:21:in instrument'
  activesupport (5.1.7) lib/active_support/notifications.rb:166:in
  instrument' actionpack (5.1.7)
  lib/action_controller/metal/instrumentation.rb:30:in process_action'
  actionpack (5.1.7)
  lib/action_controller/metal/params_wrapper.rb:252:inprocess_action'
  activerecord (5.1.7)
  lib/active_record/railties/controller_runtime.rb:22:in
  process_action' actionpack (5.1.7)
  lib/abstract_controller/base.rb:124:inprocess' actionview (5.1.7)
  lib/action_view/rendering.rb:30:in process' actionpack (5.1.7)
  lib/action_controller/metal.rb:189:indispatch' actionpack (5.1.7)
  lib/action_controller/metal.rb:253:in dispatch' actionpack (5.1.7)
  lib/action_dispatch/routing/route_set.rb:49:indispatch' actionpack
  (5.1.7) lib/action_dispatch/routing/route_set.rb:31:in serve'
  actionpack (5.1.7) lib/action_dispatch/journey/router.rb:50:inblock
  in serve' actionpack (5.1.7)
  lib/action_dispatch/journey/router.rb:33:in each' actionpack (5.1.7)
  lib/action_dispatch/journey/router.rb:33:inserve' actionpack (5.1.7)
  lib/action_dispatch/routing/route_set.rb:844:in call'
  serviceworker-rails (0.6.0) lib/serviceworker/middleware.rb:35:in
  call' remotipart (1.4.3) lib/remotipart/middleware.rb:32:in call'
  warden (1.2.8) lib/warden/manager.rb:36:inblock in call' warden
  (1.2.8) lib/warden/manager.rb:34:in catch' warden (1.2.8)
  lib/warden/manager.rb:34:incall' rack (2.0.7) lib/rack/etag.rb:25:in
  call' rack (2.0.7) lib/rack/conditional_get.rb:38:incall' rack
  (2.0.7) lib/rack/head.rb:12:in call' rack (2.0.7)
  lib/rack/session/abstract/id.rb:232:incontext' rack (2.0.7)
  lib/rack/session/abstract/id.rb:226:in call' actionpack (5.1.7)
  lib/action_dispatch/middleware/cookies.rb:613:incall' activerecord
  (5.1.7) lib/active_record/migration.rb:556:in call' actionpack
  (5.1.7) lib/action_dispatch/middleware/callbacks.rb:26:inblock in
  call' activesupport (5.1.7) lib/active_support/callbacks.rb:97:in
  run_callbacks' actionpack (5.1.7)
  lib/action_dispatch/middleware/callbacks.rb:24:incall' actionpack
  (5.1.7) lib/action_dispatch/middleware/executor.rb:12:in call'
  actionpack (5.1.7)
  lib/action_dispatch/middleware/debug_exceptions.rb:59:incall'
  web-console (3.7.0) lib/web_console/middleware.rb:135:in call_app'
  web-console (3.7.0) lib/web_console/middleware.rb:30:inblock in
  call' web-console (3.7.0) lib/web_console/middleware.rb:20:in catch'
  web-console (3.7.0) lib/web_console/middleware.rb:20:incall'
  actionpack (5.1.7)
  lib/action_dispatch/middleware/show_exceptions.rb:31:in call'
  railties (5.1.7) lib/rails/rack/logger.rb:36:incall_app' railties
  (5.1.7) lib/rails/rack/logger.rb:24:in block in call' activesupport
  (5.1.7) lib/active_support/tagged_logging.rb:69:inblock in tagged'
  activesupport (5.1.7) lib/active_support/tagged_logging.rb:26:in
  tagged' activesupport (5.1.7)
  lib/active_support/tagged_logging.rb:69:intagged' railties (5.1.7)
  lib/rails/rack/logger.rb:24:in call' sprockets-rails (3.2.1)
  lib/sprockets/rails/quiet_assets.rb:13:incall' actionpack (5.1.7)
  lib/action_dispatch/middleware/remote_ip.rb:79:in call' actionpack
  (5.1.7) lib/action_dispatch/middleware/request_id.rb:25:incall' rack
  (2.0.7) lib/rack/method_override.rb:22:in call' rack (2.0.7)
  lib/rack/runtime.rb:22:incall' activesupport (5.1.7)
  lib/active_support/cache/strategy/local_cache_middleware.rb:27:in
  call' actionpack (5.1.7)
  lib/action_dispatch/middleware/executor.rb:12:incall' actionpack
  (5.1.7) lib/action_dispatch/middleware/static.rb:125:in call' rack
  (2.0.7) lib/rack/sendfile.rb:111:incall' railties (5.1.7)
  lib/rails/engine.rb:522:in call' puma (3.12.1)
  lib/puma/configuration.rb:227:incall' puma (3.12.1)
  lib/puma/server.rb:660:in handle_request' puma (3.12.1)
  lib/puma/server.rb:474:inprocess_client' puma (3.12.1)
  lib/puma/server.rb:334:in block in run' puma (3.12.1)
  lib/puma/thread_pool.rb:135:inblock in spawn_thread' Started GET
  "/serviceworker.js" for 127.0.0.1 at 2020-02-20 00:33:18 +0100

Body:
Keep everything as it was, and just update .submit()

The actual issue is sending as HTML instead of as JS on form.submit().

https://github.com/rails/rails/issues/29546

 //from
 form.submit();

 //to
 form.dispatchEvent(new Event('submit', {bubbles: true}));

Updated

Previously, You were submitting, then asking to submit it again. OnClick button, get stripe data then submit with my answer. Sample below.

Also, you need to add disable/enable for submit button on click, to ignore multiple clicks.

...
// Create a token or display an error when the form is submitted.
  let submitCardBtn = document.getElementById('submit-card');

  submitCardBtn.addEventListener('click', function(event) {
    event.preventDefault();

   // disable button
    submitCardBtn.disabled = true;

    stripe.createToken(card).then(function(result) {
      if (result.error) {
        // Inform the customer that there was an error.
        var errorElement = document.getElementById('card-errors');
        errorElement.textContent = result.error.message;

        // enable button on false
        submitCardBtn.disabled = false;
      } else {
        // Send the token to your server.
        stripeTokenHandler(result.token);
      }
    });
  });

  function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);

    // Submit the form
   form.dispatchEvent(new Event('submit', {bubbles: true}));

   // enable button
   submitCardBtn.disabled = false;
  }


来源: stackexchange

问:
Is there a shorter way to write this inline if?
Hey guys is there a shorter way to write this line.

```<code>int objectID = jsonObject != null && jsonObject.ObjectID.HasValue && jsonObject.ObjectID.Value > 0 ? jsonObject.ObjectID.Value : defaultObject.ObjectID;

//jsonObject.ObjectID is int?
</code>```

Can u use a null coalesce to check null and > 0?

答:
Something like this, it takes advantage of null conditional and lifted operators

```<code>int objectID = jsonObject?.ObjectID > 0 ? jsonObject.ObjectID.Value : defaultObject.ObjectID;
</code>```

Note : This assumes defaultObject.ObjectID is an int and not an int?

ContentLicense: CC BY-SA 4.0

Body:
Hey guys is there a shorter way to write this line.

int objectID = jsonObject != null && jsonObject.ObjectID.HasValue && jsonObject.ObjectID.Value > 0 ? jsonObject.ObjectID.Value : defaultObject.ObjectID;

//jsonObject.ObjectID is int?

Can u use a null coalesce to check null and > 0?

Body:
Something like this, it takes advantage of null conditional and lifted operators

int objectID = jsonObject?.ObjectID > 0 ? jsonObject.ObjectID.Value : defaultObject.ObjectID;

Note : This assumes defaultObject.ObjectID is an int and not an int?


问:
C# webrequest or webclient issue
I am implementing a forum board into my application.
The page is downloaded with a webrequest object, then applied it to the document text of a web browser control (must access the page through webrequest) and there is elements and normal advertisements missing. how can I fix this?

This is the function I am using:

```<code>        private void Navigate(string url, string credentials, ref WebBrowser wbBrowser)
        {
            WebRequest req;

            WebProxy proxy;

            WebResponse response;

            StreamReader sr;

            int index;

            string  username,
                    password,
                    ipAddress,
                    temp;

            index = 0;

            try
            {
                for (int i = 0; i < 2; i++)
                    index = credentials.IndexOf(':', index + 1);

                if (index != -1)
                {
                    ipAddress = credentials.Remove(index, credentials.Length - index);

                    temp = credentials.Remove(0, index + 1);

                    index = temp.IndexOf(':');

                    username = temp.Remove(index, temp.Length - index);
                    password = temp.Remove(0, index + 1);

                    proxy = new WebProxy(ipAddress, true);
                    proxy.Credentials = new NetworkCredential(username, password);

                    req = WebRequest.Create(url);
                    req.Proxy = proxy;

                    response = req.GetResponse();

                    sr = new StreamReader(response.GetResponseStream());

                    temp = sr.ReadToEnd();

                    index = temp.IndexOf("<head>");

                    if (index != -1)
                        temp = temp.Insert(index + 6, "<base href=\"" + url + " \" />");

                    mainDocument = null;

                    wbBrowser.DocumentText = temp;

                    while (mainDocument == null)
                        Thread.Sleep(250);
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.ToString());
            }
        }
</code>```

I use it as Navigate("page", "ip:port:username:password", ref demoBrowser)

答:
I'll quote myself from your other question, because it makes perfect sense when not dealing with proxies:

Well the problem here is that the HTML that you've received via the WebRequest contains relative paths to the CSS files that are not present in the current context. You can modify the HTML, by adding the following tag in the  section:

```<code><base href="http://domainname.com/" />
</code>```

After that the WebBrowser control resolves the relative CSS paths to the domain in this tag.

OwnerDisplayName: Anon

LastEditorDisplayName: Anon

ContentLicense: CC BY-SA 3.0

Title: C# webrequest or webclient issue

Body:
I am implementing a forum board into my application.
The page is downloaded with a webrequest object, then applied it to the document text of a web browser control (must access the page through webrequest) and there is elements and normal advertisements missing. how can I fix this?

This is the function I am using:

        private void Navigate(string url, string credentials, ref WebBrowser wbBrowser)
        {
            WebRequest req;

            WebProxy proxy;

            WebResponse response;

            StreamReader sr;

            int index;

            string  username,
                    password,
                    ipAddress,
                    temp;

            index = 0;

            try
            {
                for (int i = 0; i < 2; i++)
                    index = credentials.IndexOf(':', index + 1);

                if (index != -1)
                {
                    ipAddress = credentials.Remove(index, credentials.Length - index);

                    temp = credentials.Remove(0, index + 1);

                    index = temp.IndexOf(':');

                    username = temp.Remove(index, temp.Length - index);
                    password = temp.Remove(0, index + 1);

                    proxy = new WebProxy(ipAddress, true);
                    proxy.Credentials = new NetworkCredential(username, password);

                    req = WebRequest.Create(url);
                    req.Proxy = proxy;

                    response = req.GetResponse();

                    sr = new StreamReader(response.GetResponseStream());

                    temp = sr.ReadToEnd();

                    index = temp.IndexOf("");

                    if (index != -1)
                        temp = temp.Insert(index + 6, "<base href=\"" + url + " \" />");

                    mainDocument = null;

                    wbBrowser.DocumentText = temp;

                    while (mainDocument == null)
                        Thread.Sleep(250);
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.ToString());
            }
        }

I use it as Navigate("page", "ip:port:username:password", ref demoBrowser)

Body:
I'll quote myself from your other question, because it makes perfect sense when not dealing with proxies:

Well the problem here is that the HTML that you've received via the WebRequest contains relative paths to the CSS files that are not present in the current context. You can modify the HTML, by adding the following tag in the  section:

<base href="http://domainname.com/" />

After that the WebBrowser control resolves the relative CSS paths to the domain in this tag.


问:
How to return link to file in ASP Net Core?
I do not know how to serve links to files in ASP Net Core.I have tried using the PhyisicalFileProvider class to no avail.

What i want

Given a folder root on the hard disk , on receiving  a querystring
  like : /localFolder/test.txt i want the server to send a Link so
  the user can click and get the file test.txt

Important

I do not want to send the file but a link to it , so he can click it and download it.

What i have tried:

1.Using the extension method IApplicationBuilder.Map in order to direct the requests directly to the file.

2.Using the extension method IApplicationBuilder.Map + Adding a middleware ,though i do not know how to i serve the link ? (add it
    in the response body?)

Startup

```<code>public void ConfigureServices(IServiceCollection collection)
{
      //i have also added the provider to the service collection to further inject it in the middleware
       var phyisicalFileProvider = new PhysicalFileProvider(config.Storage.DocxFileRoot);
       services.AddSingleton<IFileProvider>(phyisicalFileProvider);
}
public void Configure()
{
  //scenario without middleware
   app.Map("/localfiles", x =>
         x.UseStaticFiles(new StaticFileOptions {
            FileProvider = new PhysicalFileProvider([some file root]),RequestPath ="/localfiles"}
           ));
   //scenario with middleware
   app.Map("/localfiles",x=>
               x.UseMiddleware<FileWare>()
          );

   app.UseEndpoints(endpoints => {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=File}/{action=Index}/{id?}");
   });

}
</code>```

Middleware

```<code>public class FileWare
{
      private IFileProvider provider;
      private RequestDelegate next;

      public FileWare(RequestDelegate next,IFileProvider provider)
      {
           this.provider=provider;
           this.next=next;
      }

      public async Task Invoke(HttpContext context)
      {
            var query = context.Request.Query;
            var path=query.First(x => x.Key == "path").Value;
            var fileInfo=this.provider.GetFileInfo(path);
            await fileInfo.CreateReadStream().CopyToAsync(context.Response.Body);
       }
}
</code>```

答:
If you just want to have a link in razor view,click the link to download a file in the local disk(for example C:\MyFolder), you could follow below steps:

1.Razor View

```<code><a asp-controller="File" asp-action="download" asp-route-path="C:\MyFolder\test.txt">Download</a>
</code>```

2.FileController

```<code>public IActionResult Download([FromQuery]string path)
    {

        string fileName = "test.txt";

        byte[] fileBytes = System.IO.File.ReadAllBytes(path);

        return File(fileBytes, "application/force-download", fileName);
    }
</code>```

Body:
I do not know how to serve links to files in ASP Net Core.I have tried using the PhyisicalFileProvider class to no avail.

What i want

Given a folder root on the hard disk , on receiving  a querystring
  like : /localFolder/test.txt i want the server to send a Link so
  the user can click and get the file test.txt

Important

I do not want to send the file but a link to it , so he can click it and download it.

What i have tried:

1.Using the extension method IApplicationBuilder.Map in order to direct the requests directly to the file.

2.Using the extension method IApplicationBuilder.Map + Adding a middleware ,though i do not know how to i serve the link ? (add it
    in the response body?)

Startup

public void ConfigureServices(IServiceCollection collection)
{
      //i have also added the provider to the service collection to further inject it in the middleware
       var phyisicalFileProvider = new PhysicalFileProvider(config.Storage.DocxFileRoot);
       services.AddSingleton<IFileProvider>(phyisicalFileProvider);
}
public void Configure()
{
  //scenario without middleware
   app.Map("/localfiles", x =>
         x.UseStaticFiles(new StaticFileOptions {
            FileProvider = new PhysicalFileProvider([some file root]),RequestPath ="/localfiles"}
           ));
   //scenario with middleware
   app.Map("/localfiles",x=>
               x.UseMiddleware<FileWare>()
          );

   app.UseEndpoints(endpoints => {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=File}/{action=Index}/{id?}");
   });

}

Middleware

public class FileWare
{
      private IFileProvider provider;
      private RequestDelegate next;

      public FileWare(RequestDelegate next,IFileProvider provider)
      {
           this.provider=provider;
           this.next=next;
      }

      public async Task Invoke(HttpContext context)
      {
            var query = context.Request.Query;
            var path=query.First(x => x.Key == "path").Value;
            var fileInfo=this.provider.GetFileInfo(path);
            await fileInfo.CreateReadStream().CopyToAsync(context.Response.Body);
       }
}

Body:
If you just want to have a link in razor view,click the link to download a file in the local disk(for example C:\MyFolder), you could follow below steps:

1.Razor View

<a asp-controller="File" asp-action="download" asp-route-path="C:\MyFolder\test.txt">Download</a>

2.FileController

public IActionResult Download([FromQuery]string path)
    {

        string fileName = "test.txt";

        byte[] fileBytes = System.IO.File.ReadAllBytes(path);

        return File(fileBytes, "application/force-download", fileName);
    }


问:
How to update npm modules, ignoring a git repo
I forked one of npm modules and now it is a git repo.

So my package.json:

```<code>"dependencies": {
    "some-module": "git+https://github.com/my-name/some-module.git",
}
</code>```

Forked repo is synchronized by fetching upstream and merging.
But when I try to update other npm modules it gives error:

```<code>npm ERR! git Appears to be a git repo or submodule.
npm ERR! git     /Users/.../node_modules/some-module
npm ERR! git Refusing to remove it. Update manually,
npm ERR! git or move it out of the way first.

npm ERR! System Darwin 13.4.0
npm ERR! command "node" "/usr/local/bin/npm" "update"
npm ERR! cwd /Users/...
npm ERR! node -v v0.10.32
npm ERR! npm -v 1.4.28
npm ERR! path /Users/.../node_modules/some-module
npm ERR! code EISGIT
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/.../npm-debug.log
npm ERR! not ok code 0
</code>```

Is there any way to ignore git repo when updating? Or to skip this error?

答:
```<code>rm -rf node_modules/*/.git/
</code>```

Try this

Body:
I forked one of npm modules and now it is a git repo.

So my package.json:

"dependencies": {
    "some-module": "git+https://github.com/my-name/some-module.git",
}

Forked repo is synchronized by fetching upstream and merging.
But when I try to update other npm modules it gives error:

npm ERR! git Appears to be a git repo or submodule.
npm ERR! git     /Users/.../node_modules/some-module
npm ERR! git Refusing to remove it. Update manually,
npm ERR! git or move it out of the way first.

npm ERR! System Darwin 13.4.0
npm ERR! command "node" "/usr/local/bin/npm" "update"
npm ERR! cwd /Users/...
npm ERR! node -v v0.10.32
npm ERR! npm -v 1.4.28
npm ERR! path /Users/.../node_modules/some-module
npm ERR! code EISGIT
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/.../npm-debug.log
npm ERR! not ok code 0

Is there any way to ignore git repo when updating? Or to skip this error?

Body:
rm -rf node_modules/*/.git/

Try this


问:
How to store every output from a for loop in dictionary
I cant figure out how to get all of the output values into my dict. When I run my code I only get last output, but if I use print inside the for loop to test I can see that I am collecting more outputs.

My goal is to get all of the outputs and not only the last.

CODE:

```<code>def cointelegraph():
    for div in soup.find_all('div', class_='post-preview-item-inline'):
        content = dict()
        title = div.find(class_='post-preview-item-inline__title').get_text()
        #print(title)
        content['title'] = title
        body = div.find(class_='post-preview-item-inline__text').get_text()
        #print(body)
        content['body'] = body
        for links in div.select('.post-preview-item-inline__figure-link'):
            link = links.get('href')
            #print(link)
            content['link'] = link
            content['total_body'] = body + '\n \n' +' Link to article: ' + link

    return content

#make_post(cointelegraph())
print(cointelegraph())
</code>```

RESULT:

```<code>{'title': ' Bitcoin Price Reclaims $10K Reversing Weekend Losses, XTZ Soars 13% ', 'body': ' Bitcoin price briefly reclaimed $10K after a bearish weekend which saw the creation of a new CME gap at $10,460. ', 'link': 'https://cointelegraph.com/news/bitcoin-price-reclaims-10k-reversing-weekend-losses-xtz-soars-13', 'total_body': ' Bitcoin price briefly reclaimed $10K after a bearish weekend which saw the creation of a new CME gap at $10,460. \n \n Link to article: https://cointelegraph.com/news/bitcoin-price-reclaims-10k-reversing-weekend-losses-xtz-soars-13'}
</code>```

答:
You are using a wrong data structure and at wrong place. Try something like below</p>

```<code>def cointelegraph():
    all_content = []

    for div in soup.find_all('div', class_='post-preview-item-inline'):
        content = dict()
        title = div.find(class_='post-preview-item-inline__title').get_text()
        #print(title)
        content['title'] = title
        body = div.find(class_='post-preview-item-inline__text').get_text()
        #print(body)
        content['body'] = body
        content['links'] = []
        for links in div.select('.post-preview-item-inline__figure-link'):
            link = links.get('href')
            #print(link)
            content['links'].append({"link": link, 'total_body': body + '\n \n' +' Link to article: ' + link})

        all_content.append(content)
    return all_content
</code>```

Body:
I cant figure out how to get all of the output values into my dict. When I run my code I only get last output, but if I use print inside the for loop to test I can see that I am collecting more outputs.

My goal is to get all of the outputs and not only the last.

CODE:

def cointelegraph():
    for div in soup.find_all('div', class_='post-preview-item-inline'):
        content = dict()
        title = div.find(class_='post-preview-item-inline__title').get_text()
        #print(title)
        content['title'] = title
        body = div.find(class_='post-preview-item-inline__text').get_text()
        #print(body)
        content['body'] = body
        for links in div.select('.post-preview-item-inline__figure-link'):
            link = links.get('href')
            #print(link)
            content['link'] = link
            content['total_body'] = body + '\n \n' +' Link to article: ' + link

    return content

#make_post(cointelegraph())
print(cointelegraph())

RESULT:

{'title': ' Bitcoin Price Reclaims $10K Reversing Weekend Losses, XTZ Soars 13% ', 'body': ' Bitcoin price briefly reclaimed $10K after a bearish weekend which saw the creation of a new CME gap at $10,460. ', 'link': 'https://cointelegraph.com/news/bitcoin-price-reclaims-10k-reversing-weekend-losses-xtz-soars-13', 'total_body': ' Bitcoin price briefly reclaimed $10K after a bearish weekend which saw the creation of a new CME gap at $10,460. \n \n Link to article: https://cointelegraph.com/news/bitcoin-price-reclaims-10k-reversing-weekend-losses-xtz-soars-13'}

Body:
You are using a wrong data structure and at wrong place. Try something like below

def cointelegraph():
    all_content = []

    for div in soup.find_all('div', class_='post-preview-item-inline'):
        content = dict()
        title = div.find(class_='post-preview-item-inline__title').get_text()
        #print(title)
        content['title'] = title
        body = div.find(class_='post-preview-item-inline__text').get_text()
        #print(body)
        content['body'] = body
        content['links'] = []
        for links in div.select('.post-preview-item-inline__figure-link'):
            link = links.get('href')
            #print(link)
            content['links'].append({"link": link, 'total_body': body + '\n \n' +' Link to article: ' + link})

        all_content.append(content)
    return all_content


问:
Error message "ENOENT, no such file or directory"
I'm getting this error from my Node.js application:

ENOENT, no such file or directory '~/Desktop/MyApp/newversion/partials/navigation.jade'

I know the file is there because when I try to open the file using the exact copied and pasted path, it works. I also know the application is using the right directory because, well, it outputs it in the error.

答: For me, it had my code folder in Dropbox on Windows 10. During the build process Dropbox would flip out over having more than 500,000 files. I moved my folder out and now it builds fine!</p>


问:
"Task function must be specified at Gulp.set" error when running gulp
I always have the same error when installing gulp:

```<code>C:\Users\Thomas\Desktop\Sites CT Graphics\colpaertmarc.be>gulp
assert.js:350
throw err;
^
</code>```

AssertionError [ERR_ASSERTION]: Task function must be specified
      at Gulp.set [as _setTask] (C:\Users\Thomas\Desktop\Sites CT Graphics\colpaertmarc.be\node_modules\undertaker\lib\set-task.js:10:3)
      at Gulp.task (C:\Users\Thomas\Desktop\Sites CT Graphics\colpaertmarc.be\node_modules\undertaker\lib\task.js:13:8)
      at Object. (C:\Users\Thomas\Desktop\Sites CT Graphics\colpaertmarc.be\gulpfile.js:19:6)
      at Module._compile (internal/modules/cjs/loader.js:689:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
      at Module.load (internal/modules/cjs/loader.js:599:32)
      at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
      at Function.Module._load (internal/modules/cjs/loader.js:530:3)
      at Module.require (internal/modules/cjs/loader.js:637:17)
      at require (internal/modules/cjs/helpers.js:22:18)

答:
GULP 4

```<code>const { series, parallel } = require('gulp');

gulp.task('clear', gulp.series( async function(){
  // your code
}));

gulp.task('build', gulp.series( async function(){
  // Your code
}));

gulp.task('watch', function(){
  gulp.watch('./javascripts/**/*.js', gulp.series('clear','build'));
});

gulp.task('default', gulp.series('clear','build','watch'));
</code>```

When I had upgraded the gulp version from ^3.9.1 to ^4.0.2, It worked. Maybe, this code will help you.

Body:
I always have the same error when installing gulp:

C:\Users\Thomas\Desktop\Sites CT Graphics\colpaertmarc.be>gulp
assert.js:350
throw err;
^

AssertionError [ERR_ASSERTION]: Task function must be specified
      at Gulp.set [as _setTask] (C:\Users\Thomas\Desktop\Sites CT Graphics\colpaertmarc.be\node_modules\undertaker\lib\set-task.js:10:3)
      at Gulp.task (C:\Users\Thomas\Desktop\Sites CT Graphics\colpaertmarc.be\node_modules\undertaker\lib\task.js:13:8)
      at Object. (C:\Users\Thomas\Desktop\Sites CT Graphics\colpaertmarc.be\gulpfile.js:19:6)
      at Module._compile (internal/modules/cjs/loader.js:689:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
      at Module.load (internal/modules/cjs/loader.js:599:32)
      at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
      at Function.Module._load (internal/modules/cjs/loader.js:530:3)
      at Module.require (internal/modules/cjs/loader.js:637:17)
      at require (internal/modules/cjs/helpers.js:22:18)

Body:
GULP 4

const { series, parallel } = require('gulp');

gulp.task('clear', gulp.series( async function(){
  // your code
}));

gulp.task('build', gulp.series( async function(){
  // Your code
}));

gulp.task('watch', function(){
  gulp.watch('./javascripts/**/*.js', gulp.series('clear','build'));
});

gulp.task('default', gulp.series('clear','build','watch'));

When I had upgraded the gulp version from ^3.9.1 to ^4.0.2, It worked. Maybe, this code will help you.


问:
Hibernate concurrent insert
I faced a problem. I have an App with Hibernate that loads data from XML files into tables in concurrent mode. Some part of data could be same and could be inserted from differnet threads. Each thread works in its own long-play transaction. There's an issue when two or more treads try to commit transaction. For example two threads inserted records into table City that has constraint on NAME field. It means that ConstraintViolationException occurs on flush() or commit(). I want to automatically handle this collisions and want new problem objects to be replaced with older already inserted objects. Is this possible? I look at saveOrUpdate() and optimistic version control in Hibernate.

答:
I assume that you use one of MVCC-based DBMS.

If transaction isolation level is not higher than READ COMMITTED, you can reduce probability of conflict by issuing a query to check for existence of Cities with the same name before inserting the new one.

Note that saveOrUpdate() can't help here, since name is not a primary key. Also note that you cannot prevent conflict at all (at least without using some DBMS-specific features), since basically it's an example of write skew anomaly, which can't be prevented in MVCC-based DBMS.

Also, if atomicity of importing XML file is not critical, you can break long transaction into several shorter ones, and simple retry them in a case of constraint violation.

Title: Hibernate concurrent insert


问:
How can I make sure the return is an array?
I am using the COALESCE operator to make sure I return a consistent data set.

The query looks as follows

```<code>SELECT c.id, c.ItemLevel, c.ItemNo, bv.variantId, bv.variantDescription, c.DetailedData.locales[0].images ?? c.BasicData.asset.assets[0].locations[1].path AS images, c.PriceData.WhitePrice, c.PriceData.RedPrice, c.PriceData.DiscountPercentage, c.PriceData.TypeOfDiscount
FROM c
JOIN bv IN c.BasicData.base.sales.variants
WHERE c.brand = 'XXX'
AND c.Consumer = 'YYY'
AND bv.variantId = 'TTT'
AND c.Season = 'XXX'
</code>```

My challenge is that c.DetailedData.locales[0].images is an array but c.BasicData.asset.assets[0].locations[1].path is not.

I need the c.BasicData.asset.assets[0].locations[1].path to be an array so that the JSON returned is consistent so I can loop the array in my mobile app directly.

How can this be done?

答:
I may get your points.

For example, you have below 2 sample documents:

```<code>[
    {
        "DetailedData": {
            "locales": [
                {
                    "images": [
                        {
                            "image": "pic1"
                        },
                        {
                            "image": "pic2"
                        }
                    ]
                }
            ]
        }
    },
    {
        "DetailedData": {},
        "BasicData": {
            "asset": {
                "assets": [
                    {
                        "locations": [
                            {
                                "path": "AAA"
                            },
                            {
                                "path": "BBB"
                            }
                        ]
                    }
                ]
            }
        }
    }
]
</code>```

If you execute your sql,you will get different format:

```<code>SELECT c.DetailedData.locales[0].images ?? c.BasicData.asset.assets[0].locations[1].path AS images
FROM c
</code>```

You could add [] to reset the column,like:

```<code>SELECT c.DetailedData.locales[0].images ?? [{"image": c.BasicData.asset.assets[0].locations[1].path}] AS images
FROM c
</code>```

Output:

Body:
I am using the COALESCE operator to make sure I return a consistent data set.

The query looks as follows

SELECT c.id, c.ItemLevel, c.ItemNo, bv.variantId, bv.variantDescription, c.DetailedData.locales[0].images ?? c.BasicData.asset.assets[0].locations[1].path AS images, c.PriceData.WhitePrice, c.PriceData.RedPrice, c.PriceData.DiscountPercentage, c.PriceData.TypeOfDiscount
FROM c
JOIN bv IN c.BasicData.base.sales.variants
WHERE c.brand = 'XXX'
AND c.Consumer = 'YYY'
AND bv.variantId = 'TTT'
AND c.Season = 'XXX'

My challenge is that c.DetailedData.locales[0].images is an array but c.BasicData.asset.assets[0].locations[1].path is not.

I need the c.BasicData.asset.assets[0].locations[1].path to be an array so that the JSON returned is consistent so I can loop the array in my mobile app directly.

How can this be done?

Body:
I may get your points.

For example, you have below 2 sample documents:

[
    {
        "DetailedData": {
            "locales": [
                {
                    "images": [
                        {
                            "image": "pic1"
                        },
                        {
                            "image": "pic2"
                        }
                    ]
                }
            ]
        }
    },
    {
        "DetailedData": {},
        "BasicData": {
            "asset": {
                "assets": [
                    {
                        "locations": [
                            {
                                "path": "AAA"
                            },
                            {
                                "path": "BBB"
                            }
                        ]
                    }
                ]
            }
        }
    }
]

If you execute your sql,you will get different format:

SELECT c.DetailedData.locales[0].images ?? c.BasicData.asset.assets[0].locations[1].path AS images
FROM c

You could add [] to reset the column,like:

SELECT c.DetailedData.locales[0].images ?? [{"image": c.BasicData.asset.assets[0].locations[1].path}] AS images
FROM c

Output:


问:
How to get correct Pie Nodes in R igraph?
I am creating a network with pie nodes however I have ran into a few issues:

The values I have for the slices of the pie do not match with the image produced

Example:

```<code>#generate random slice for my pie charts
valuesq <- lapply(1:23, function(x) sample(0:5,2))

[[1]]
[1] 1 0

[[2]]
[1] 5 1

[[3]]
[1] 1 0

[[4]]
[1] 4 5

[[5]]
[1] 5 3

[[6]]
[1] 1 2

[[7]]
[1] 5 2

[[8]]
[1] 0 2

[[9]]
[1] 0 3

[[10]]
[1] 1 5

[[11]]
[1] 5 3

[[12]]
[1] 5 4

[[13]]
[1] 3 1

[[14]]
[1] 0 3

[[15]]
[1] 4 5

[[16]]
[1] 3 1

[[17]]
[1] 4 1

[[18]]
[1] 4 2

[[19]]
[1] 1 2

[[20]]
[1] 2 4

[[21]]
[1] 1 4

[[22]]
[1] 1 2

[[23]]
[1] 4 1

#plot my chart which has 23 nodes
plot(newig,vertex.shape="pie",vertex.size=20, vertex.pie=valuesq, label.dist=1, label.degree=pi/4)
</code>```

It produces this plot:

Clearly this is wrong for example node 4(IV) is one solid colour but the vector defining its slices is 4 5

I don't really understand why this is happening any help would be great

A second question I have is how can I match the pie slices to colours e.g. all slices in first column = red and all in second = yellow?

答:
The most probable reason is that the code that assigns the labels to nodes(and is not included) assigns labels to the wrong nodes. Please note that igraph slices the pie in a way that the total area is equal to the sum of all values supplied for that node in the valuesq so for node which is labeled 4 the valuesq[[correctnodenumber]] equals a vector of one number(any number) and a zero. Regarding your second question, the answer is positive. You just need to supply the hexadecimal value (google the word "colorpicker"). I hope the following code and explanation helps.

```<code>library(igraph)

newig <- graph.star(n=23,mode="undirected")

valuesq <- lapply(1:23, function(x) c(sample(0:5,2)))
#you can assign up to 5 colors(random colors or exact hex values)
#to 5 slices. Exact hex values could be assigned to all nodes:
V(newig)$pie.color=list(c("#E495A5", "#BDAB66"))
#or to a specific node
V(newig)[10]$pie.color=list(c("#00FF66FF", "#CC00FFFF"))
# let's set a seed number to regenerate the graph so that nodes are
#positioned at the same place every time you run the code.

set.seed(1234)

plot(newig,
 vertex.shape="pie",
 vertex.size=25,
 vertex.pie=valuesq,
 vertex.label.dist=0.8,
 vertex.label.cex=0.6,
 vertex.label.degree=pi,
 vertex.label=LETTERS[1:23])
</code>```

```<code>> valuesq
> [[1]] [1] 2 3
>
> [[2]] [1] 1 5
>
> [[3]] [1] 0 1
>
> [[4]] [1] 5 0
>
> [[5]] [1] 1 4
>
> [[6]] [1] 0 2
>
> [[7]] [1] 4 3
>
> [[8]] [1] 1 0
>
> [[9]] [1] 4 5
>
> [[10]] [1] 4 1
>
> [[11]] [1] 5 2
>
> [[12]] [1] 5 3
>
> [[13]] [1] 0 5
>
> [[14]] [1] 5 1
>
> [[15]] [1] 2 3
>
> [[16]] [1] 2 1
>
> [[17]] [1] 3 2
>
> [[18]] [1] 4 0
>
> [[19]] [1] 2 3
>
> [[20]] [1] 3 0
>
> [[21]] [1] 5 4
>
> [[22]] [1] 4 5
>
> [[23]] [1] 3 2
</code>```

Body:
I am creating a network with pie nodes however I have ran into a few issues:

The values I have for the slices of the pie do not match with the image produced

Example:

#generate random slice for my pie charts
valuesq <- lapply(1:23, function(x) sample(0:5,2))

[[1]]
[1] 1 0

[[2]]
[1] 5 1

[[3]]
[1] 1 0

[[4]]
[1] 4 5

[[5]]
[1] 5 3

[[6]]
[1] 1 2

[[7]]
[1] 5 2

[[8]]
[1] 0 2

[[9]]
[1] 0 3

[[10]]
[1] 1 5

[[11]]
[1] 5 3

[[12]]
[1] 5 4

[[13]]
[1] 3 1

[[14]]
[1] 0 3

[[15]]
[1] 4 5

[[16]]
[1] 3 1

[[17]]
[1] 4 1

[[18]]
[1] 4 2

[[19]]
[1] 1 2

[[20]]
[1] 2 4

[[21]]
[1] 1 4

[[22]]
[1] 1 2

[[23]]
[1] 4 1

#plot my chart which has 23 nodes
plot(newig,vertex.shape="pie",vertex.size=20, vertex.pie=valuesq, label.dist=1, label.degree=pi/4)

It produces this plot:

Clearly this is wrong for example node 4(IV) is one solid colour but the vector defining its slices is 4 5

I don't really understand why this is happening any help would be great

A second question I have is how can I match the pie slices to colours e.g. all slices in first column = red and all in second = yellow?

Body:
The most probable reason is that the code that assigns the labels to nodes(and is not included) assigns labels to the wrong nodes. Please note that igraph slices the pie in a way that the total area is equal to the sum of all values supplied for that node in the valuesq so for node which is labeled 4 the valuesq[[correctnodenumber]] equals a vector of one number(any number) and a zero. Regarding your second question, the answer is positive. You just need to supply the hexadecimal value (google the word "colorpicker"). I hope the following code and explanation helps.

library(igraph)

newig <- graph.star(n=23,mode="undirected")

valuesq <- lapply(1:23, function(x) c(sample(0:5,2)))
#you can assign up to 5 colors(random colors or exact hex values)
#to 5 slices. Exact hex values could be assigned to all nodes:
V(newig)$pie.color=list(c("#E495A5", "#BDAB66"))
#or to a specific node
V(newig)[10]$pie.color=list(c("#00FF66FF", "#CC00FFFF"))
# let's set a seed number to regenerate the graph so that nodes are
#positioned at the same place every time you run the code.

set.seed(1234)

plot(newig,
 vertex.shape="pie",
 vertex.size=25,
 vertex.pie=valuesq,
 vertex.label.dist=0.8,
 vertex.label.cex=0.6,
 vertex.label.degree=pi,
 vertex.label=LETTERS[1:23])

> valuesq
> [[1]] [1] 2 3
>
> [[2]] [1] 1 5
>
> [[3]] [1] 0 1
>
> [[4]] [1] 5 0
>
> [[5]] [1] 1 4
>
> [[6]] [1] 0 2
>
> [[7]] [1] 4 3
>
> [[8]] [1] 1 0
>
> [[9]] [1] 4 5
>
> [[10]] [1] 4 1
>
> [[11]] [1] 5 2
>
> [[12]] [1] 5 3
>
> [[13]] [1] 0 5
>
> [[14]] [1] 5 1
>
> [[15]] [1] 2 3
>
> [[16]] [1] 2 1
>
> [[17]] [1] 3 2
>
> [[18]] [1] 4 0
>
> [[19]] [1] 2 3
>
> [[20]] [1] 3 0
>
> [[21]] [1] 5 4
>
> [[22]] [1] 4 5
>
> [[23]] [1] 3 2


问:
How do I write a method that has the same implementation for multiple kinds of objects (Java)?
I am writing a (currently) String-based Pokemon game in Java. With the structure I have, there are currently 2 kinds of objects that I want to do Type matchups for: Pokemon and moves. The method I want to write (isStrongAgainst()) would be the same for both. For example, a water type pokemon and a water type move are strong against fire type Pokemon, but these comparisons can imply different things based on context. Both classes have differently implemented isType() methods.

The idea I had was to use an interface that implements a default isStrongAgainst() method and declares an abstract isType() method. I would think that since any class that implements this interface would have to implement isType(), I could use it in my isStrongAgainst(), but I cannot. Is there any way around this or a better suggestion given my problem?

```<code>public interface TypeMatch<T> {
    boolean isType(Type t);
    default boolean isStrongAgainst(Pokemon opponent){
        if(T.isType(Type.NORMAL)){
            return false;
        }
        if(T.isType(Type.WATER)){
            return opponent.isType(Type.FIRE) ||
                    opponent.isType(Type.ROCK) ||
                    opponent.isType(Type.GROUND);
        } //etc...
</code>```

答: As far as understand, your game contains different behaviors according to type of a Pokemon. I highly recommend you to use strategy design pattern. </p>

Body:
I am writing a (currently) String-based Pokemon game in Java. With the structure I have, there are currently 2 kinds of objects that I want to do Type matchups for: Pokemon and moves. The method I want to write (isStrongAgainst()) would be the same for both. For example, a water type pokemon and a water type move are strong against fire type Pokemon, but these comparisons can imply different things based on context. Both classes have differently implemented isType() methods.

The idea I had was to use an interface that implements a default isStrongAgainst() method and declares an abstract isType() method. I would think that since any class that implements this interface would have to implement isType(), I could use it in my isStrongAgainst(), but I cannot. Is there any way around this or a better suggestion given my problem?

public interface TypeMatch<T> {
    boolean isType(Type t);
    default boolean isStrongAgainst(Pokemon opponent){
        if(T.isType(Type.NORMAL)){
            return false;
        }
        if(T.isType(Type.WATER)){
            return opponent.isType(Type.FIRE) ||
                    opponent.isType(Type.ROCK) ||
                    opponent.isType(Type.GROUND);
        } //etc...


问:
Can't get innerHTML of tag on IE8
I am trying to get the innerhtml of class name current_page_item[0]... And this is working  fine in FF and even in IE9 also. But in IE 8 it seems to be some javascript error in line" var classelem=document.getElementsByClassName('current_page_item')[0].innerHTML;.

I tried to put alert after the above line. But it is not displaying the message "Hello again".

Any idea how to solve the browser issue for this? Is it something that document.getElementsByClassName wont work in IE8?

```<code><html>
<head>
<script type="text/javascript">
function updatesidebar()
{
alert("Hello");
var classelem=document.getElementsByClassName('current_page_item')[0].innerHTML;

alert("Hello again");

}
</script>

</head>
<body>
<div id="main">

<div class="menu_main">

                      <ul class='mainmenu' id='root'>
<li><a href="/home" class="">Home</a></li>
<li><a href="/solutions" class="">Solutions</a>
</li><li><a href="/services" class="">Services</a></li>
<li><a href="/about-us" class="current_page_item">About Us</a></li>
<li><a href="/news" class="">News and Events</a></li>
<li><a href="/careers" class="">Careers</a></li>
<li><a href="/contact-us" class="">Contact Us</a></li>
</ul>

                </div>

</div>
<script type="text/javascript">
window.onload=updatesidebar();
</script>

</body>
</html>
</code>```

答:
Change:

```<code>window.onload=updatesidebar();
</code>```

to:

```<code>window.onload=updatesidebar;
</code>```

The way you have it just now will call the function immediately rather than when the page is loaded.

Title: Can't get innerHTML of tag on IE8

Body:
I am trying to get the innerhtml of class name current_page_item[0]... And this is working  fine in FF and even in IE9 also. But in IE 8 it seems to be some javascript error in line" var classelem=document.getElementsByClassName('current_page_item')[0].innerHTML;.

I tried to put alert after the above line. But it is not displaying the message "Hello again".

Any idea how to solve the browser issue for this? Is it something that document.getElementsByClassName wont work in IE8?

Home

Solutions

Services

About Us

News and Events

Careers

Contact Us

Body:
Change:

window.onload=updatesidebar();

to:

window.onload=updatesidebar;

The way you have it just now will call the function immediately rather than when the page is loaded.


问:
when I want to use pyinstaller to package my python script, what should I do if I want to use "pygame.font.SysFont" in my script?
I made my simple game with pygame package and It works well on my python editor

so I tried to package this file through pyinstaller

As a result, EXE file was builded successfully. but when I execute this file, this file is closed immediately after opening.

so I tried to debug my script and finally found that the problem is pygame.font.SysFont

when I didn't use pygame.font.SysFont and package this script through pyinstaller, I could play my game successfully

but If I tried to use pygame.font.SysFont at least once in my script and package this script through pyinstaller, I couldn't play my game because this file(exe output file of pyinstaller) is closed immediately after opening.

If anyone knows about this issue, please advise me

Thank you

```<code>import sys
import os
import random
import pygame as pg
from pygame.locals import QUIT, Rect, KEYDOWN, K_SPACE, K_r

def main():

    game_over = False
    ship_y = 250
    velocity = 0
    score = 0
    slope = random.randint(1, 6)
    walls = 160
    holes = []
    for xpos in range(walls):
        holes.append(Rect(xpos * 5, 100, 5, 400))

    parent_path = os.getcwd()
    ship_img = pg.image.load(os.path.join(parent_path, "img\\ship.png"))
    bang_img = pg.image.load(os.path.join(parent_path, "img\\bang.png"))

    while True:
        space_down = False
        for event in pg.event.get():
            if event.type == QUIT:
                pg.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_SPACE:
                    space_down = True

        if not game_over:
            score += 10
            velocity += -3 if space_down else 3
            ship_y += velocity

            # Scroll map automatically
            edge = holes[-1].copy()
            test = edge.move(0, slope)
            if test.top <= 0 or test.bottom >= 600:
                slope = random.randint(1, 6) * (-1 if slope > 0 else 1)
                if edge.height >= 160:
                    edge.inflate_ip(0, -20)

            edge.move_ip(5, slope)
            holes.append(edge)
            del holes[0]
            holes = [x.move(-5, 0) for x in holes]

            # Check crash
            if holes[0].top > ship_y or holes[0].bottom < ship_y + 50:
                game_over = True

        SURFACE.fill((0, 255, 0))
        for hole in holes:
            pg.draw.rect(SURFACE, (0, 0, 0), hole)
        SURFACE.blit(ship_img, (0, ship_y))

        score_board = SYSFONT.render(f"score : {score}", True, (0, 0, 225)) # I have to comment out this line
        SURFACE.blit(score_board, (600, 20))

        if game_over:

            end_msg = SYSFONT.render(f"press R to restart", True, (255, 255, 255)) # I have to comment out this line
            cal_level = int((400 - holes[0].height) / 20)
            level = SYSFONT.render(f"level : {cal_level}", True, (255, 0, 0)) # I have to comment out this line
            SURFACE.blit(end_msg, (320, 200))
            SURFACE.blit(level, (370, 240))
            SURFACE.blit(bang_img, (0, ship_y - 40))

            pg.display.update()

            while True:
                for event in pg.event.get():
                    if event.type == KEYDOWN:
                        if event.key == K_r:
                            game_over = False

                if not game_over:
                    ship_y = 250
                    velocity = 0
                    score = 0
                    slope = random.randint(1, 6)
                    holes = []
                    for xpos in range(walls):
                        holes.append(Rect(xpos * 5, 100, 5, 400))
                    break

        pg.display.update()
        FPS.tick(30)

if __name__ == "__main__":
    pg.init()
    pg.key.set_repeat(5, 5)
    SURFACE = pg.display.set_mode((800, 600))
    FPS = pg.time.Clock()
    SYSFONT = pg.font.SysFont(None, 36)   # I have to comment out this line

    main()

</code>```

答:
I found a solution myself

the problem is None in pygame.font.SysFont(None, 36, bold=True)

pyinstaller couldn't find default system font in pygame

so I specified my font type like Calibri and It works well after that

Body:
I made my simple game with pygame package and It works well on my python editor

so I tried to package this file through pyinstaller

As a result, EXE file was builded successfully. but when I execute this file, this file is closed immediately after opening.

so I tried to debug my script and finally found that the problem is pygame.font.SysFont

when I didn't use pygame.font.SysFont and package this script through pyinstaller, I could play my game successfully

but If I tried to use pygame.font.SysFont at least once in my script and package this script through pyinstaller, I couldn't play my game because this file(exe output file of pyinstaller) is closed immediately after opening.

If anyone knows about this issue, please advise me

Thank you

import sys
import os
import random
import pygame as pg
from pygame.locals import QUIT, Rect, KEYDOWN, K_SPACE, K_r

def main():

    game_over = False
    ship_y = 250
    velocity = 0
    score = 0
    slope = random.randint(1, 6)
    walls = 160
    holes = []
    for xpos in range(walls):
        holes.append(Rect(xpos * 5, 100, 5, 400))

    parent_path = os.getcwd()
    ship_img = pg.image.load(os.path.join(parent_path, "img\\ship.png"))
    bang_img = pg.image.load(os.path.join(parent_path, "img\\bang.png"))

    while True:
        space_down = False
        for event in pg.event.get():
            if event.type == QUIT:
                pg.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_SPACE:
                    space_down = True

        if not game_over:
            score += 10
            velocity += -3 if space_down else 3
            ship_y += velocity

            # Scroll map automatically
            edge = holes[-1].copy()
            test = edge.move(0, slope)
            if test.top <= 0 or test.bottom >= 600:
                slope = random.randint(1, 6) * (-1 if slope > 0 else 1)
                if edge.height >= 160:
                    edge.inflate_ip(0, -20)

            edge.move_ip(5, slope)
            holes.append(edge)
            del holes[0]
            holes = [x.move(-5, 0) for x in holes]

            # Check crash
            if holes[0].top > ship_y or holes[0].bottom < ship_y + 50:
                game_over = True

        SURFACE.fill((0, 255, 0))
        for hole in holes:
            pg.draw.rect(SURFACE, (0, 0, 0), hole)
        SURFACE.blit(ship_img, (0, ship_y))

        score_board = SYSFONT.render(f"score : {score}", True, (0, 0, 225)) # I have to comment out this line
        SURFACE.blit(score_board, (600, 20))

        if game_over:

            end_msg = SYSFONT.render(f"press R to restart", True, (255, 255, 255)) # I have to comment out this line
            cal_level = int((400 - holes[0].height) / 20)
            level = SYSFONT.render(f"level : {cal_level}", True, (255, 0, 0)) # I have to comment out this line
            SURFACE.blit(end_msg, (320, 200))
            SURFACE.blit(level, (370, 240))
            SURFACE.blit(bang_img, (0, ship_y - 40))

            pg.display.update()

            while True:
                for event in pg.event.get():
                    if event.type == KEYDOWN:
                        if event.key == K_r:
                            game_over = False

                if not game_over:
                    ship_y = 250
                    velocity = 0
                    score = 0
                    slope = random.randint(1, 6)
                    holes = []
                    for xpos in range(walls):
                        holes.append(Rect(xpos * 5, 100, 5, 400))
                    break

        pg.display.update()
        FPS.tick(30)

if __name__ == "__main__":
    pg.init()
    pg.key.set_repeat(5, 5)
    SURFACE = pg.display.set_mode((800, 600))
    FPS = pg.time.Clock()
    SYSFONT = pg.font.SysFont(None, 36)   # I have to comment out this line

    main()


问:
Is there a limit for showing RewardedAd of Admob?
Is there a limit or caution from Google for using RewardedAd for limited time?

So, in my app if I let my user to watch rewarded ad as many times he/she wants, will Google consider that as a invalid traffic which can lead to deactivation of account?

答:
No there is no such limitation for rewarded ads. But wherever you implement the rewarded ads, it should provide a good experience to the end-user, it should should provide value to the user with reward, like some feature will be unlocked.
Before clicking the link or button user should know what reward will it get.</p>


问:
Is Redux needed for every ReactJS project?
I have a question: Is Redux needed for every ReactJS project for development?</p>

答:
Short answer:
Absolutely not

Long answer:
You seem to be new here, so here are a few points that might help you

As your application grows in size and complexity managing the state will become harder, that is why tools like redux where created, they provide a certain abstraction that allows you not only to reason about your code in a more simple way but also to separate state management logic from other code, therefore redux will HELP you in this regard.

There are many tools to do state management, redux is one of them, but there is also mobx, mobx-state-tree, useReducer, using contexts, etc etc. they all have pros and cons, however in the end the point is the same to HELP you manage the state of your application.

You should try it yourself, try to develop a complex workflow without any state management tool first, see how it feels, then you might understand why having tooling that supports you is very useful, but not absolutely necessary.

Good luck!


问:
R shiny DT hover shows detailed table
I am trying to work on an R shiny app where I want to show a consolidated table on top and when the user hovers on any line item it would show the detailed section of that table.So here's the code for the first table

```<code>library(ggplot2)

ui <- fluidPage(
  titlePanel("Basic DataTable"),

  # Create a new row for the table.
  DT::dataTableOutput("table")
)
server <- function(input, output) {
  data <- mpg

  data <-data %>% group_by(manufacturer,year) %>%
    summarise(cty = round(mean(cty),2),hwy = round(2,mean(hwy)))

  # Filter data based on selections
  output$table <- DT::renderDataTable(DT::datatable({

    data
  }))

}

shinyApp(ui,server)
</code>```

Now when the user hovers on Audi for example it should show a detailed version just forAudi something like this in a table below.Can this be done in shiny with DT on hover or click.

答:
Here is a way. If you prefer to display the child table on click rather than on hover, replace "table.on('mouseover', 'td', function(){" with "table.on('click', 'td', function(){".

```<code>library(shiny)
library(DT)

data(mpg, package = "ggplot2")

callback <- c(
  "table.on('mouseover', 'td', function(){",
  "  var index = table.cell(this).index();",
  "  Shiny.setInputValue('cell', index, {priority: 'event'});",
  "});"
)

ui <- fluidPage(
  br(),
  DTOutput("tbl")
)

server <- function(input, output, session){

  dat <- mpg

  output[["tbl"]] <- renderDT({
    datatable(
      dat,
      callback = JS(callback)
    )
  })

  filteredData <- eventReactive(input[["cell"]], {
    i <- input[["cell"]]$row + 1
    j <- input[["cell"]]$column
    if(j > 0){
      dat[dat[[j]] == dat[i,j], , drop = FALSE]
    }else{
      NULL
    }
  })

  output[["tblfiltered"]] <- renderDT({
    datatable(
      filteredData(),
      fillContainer = TRUE,
      options = list(
        pageLength = 5
      )
    )
  })

  observeEvent(filteredData(), {
    showModal(
      modalDialog(
        DTOutput("tblfiltered"),
        size = "l",
        easyClose = TRUE
      )
    )
  })

}

shinyApp(ui, server)
</code>```

Title: R shiny DT hover shows detailed table

Body:
I am trying to work on an R shiny app where I want to show a consolidated table on top and when the user hovers on any line item it would show the detailed section of that table.So here's the code for the first table

library(ggplot2)

ui <- fluidPage(
  titlePanel("Basic DataTable"),

  # Create a new row for the table.
  DT::dataTableOutput("table")
)
server <- function(input, output) {
  data <- mpg

  data <-data %>% group_by(manufacturer,year) %>%
    summarise(cty = round(mean(cty),2),hwy = round(2,mean(hwy)))

  # Filter data based on selections
  output$table <- DT::renderDataTable(DT::datatable({

    data
  }))

}

shinyApp(ui,server)

Now when the user hovers on Audi for example it should show a detailed version just forAudi something like this in a table below.Can this be done in shiny with DT on hover or click.

Body:
Here is a way. If you prefer to display the child table on click rather than on hover, replace "table.on('mouseover', 'td', function(){" with "table.on('click', 'td', function(){".

library(shiny)
library(DT)

data(mpg, package = "ggplot2")

callback <- c(
  "table.on('mouseover', 'td', function(){",
  "  var index = table.cell(this).index();",
  "  Shiny.setInputValue('cell', index, {priority: 'event'});",
  "});"
)

ui <- fluidPage(
  br(),
  DTOutput("tbl")
)

server <- function(input, output, session){

  dat <- mpg

  output[["tbl"]] <- renderDT({
    datatable(
      dat,
      callback = JS(callback)
    )
  })

  filteredData <- eventReactive(input[["cell"]], {
    i <- input[["cell"]]$row + 1
    j <- input[["cell"]]$column
    if(j > 0){
      dat[dat[[j]] == dat[i,j], , drop = FALSE]
    }else{
      NULL
    }
  })

  output[["tblfiltered"]] <- renderDT({
    datatable(
      filteredData(),
      fillContainer = TRUE,
      options = list(
        pageLength = 5
      )
    )
  })

  observeEvent(filteredData(), {
    showModal(
      modalDialog(
        DTOutput("tblfiltered"),
        size = "l",
        easyClose = TRUE
      )
    )
  })

}

shinyApp(ui, server)


问:
Best way to include the stripe.js script in every gatsby page
The gatsby-stripe-plugin is deprecated. It states that stripe.js has its own solutions now on how to load stripe into the code, e.g. const stripe = await loadStripe(secret);

But stripe states in its readme that you should add the stripe script to every file/page and not only at the checkout page in order to check for fraud.

What would be the best way to do so. I am quite new to gatsby, is it a valid solution to just add the stripe script to the index.html in the public folder?

答: You can now npm install @stripe/stripe-js and then import '@stripe/stripe-js'; in every page and that will include it as suggested.


问:
How to protect username and pass of DataSource in Spring Boot?
I have developed some Spring Boot Project and I have initiated my database connection by using spring.datasource.username and spring.datasource.password in application.properties

I have tried to use jasypt to encrypt these properties but I think this is not a good way because I still need to store jasypt.encryptor.password which is not encrypted in application.properties.

I am having difficulties finding the solutions because the results from Internet just mention jasypt.

Are there any better way to protect username and pass for Spring Boot?

答:
Definitely you should not keep that sensitive data in properties file.

You should keep those data in vault.

Some of the vault providers :

Hashicorp Vault: https://www.vaultproject.io/

AWS Secrets Manager // for cloud

Keywhiz

Confidant etc

Then you should use spring config server token based security to get sensitive data out of sensitive storages such as vault.

Refer this for integration example of such use case with spring config server. here.


问:
how to check how many voice channel my discord bot is in?
I want my bot(coded in discord.js) to show how many voice channels my discord bot is in, and I have no idea how to do that.

Can I get some help? I would offer My bot's premium silver edition to those who helped just dm A350-1000#6715 on discord for redeem code.

答:
You can use .voiceConnections.

Like this:

```<code>client.on('message', message => {
    console.log(client.voiceConnections.size)
});
</code>```

Body:
You can use .voiceConnections.

Like this:

client.on('message', message => {
    console.log(client.voiceConnections.size)
});


问:
Difference between URL and Loader on Vector Source - OpenLayers 3
I have to load a  WFS layer from my Geoserver to my website with Openlayers 3.9.0.

According to the manual there are two options to load features, loader(ol.FeatureLoader) and url (ol.FeatureUrlFunction).

I dont get the difference between the two. They both used to load features, loader, does not set any URL and looks more complicated.

I tried:

    var url =  'http://localhost:8080/geoserver/mapname/wfs?service=WFS&'+'version=1.0.0&request=GetFeature&typeName=mapname:awesomelayer&'+'outputFormat=application/json&maxFeatures=50'
    var vectorSource = new ol.source.Vector({
              format: new ol.format.GeoJSON(),
              loader: function(extent){
                    $.ajax({
                    url: url,
                    type:'GET',
                    dataType: 'jsonp'
                    }).done(loadFeatures);
               },
              strategy: new ol.loadingstrategy.tile(ol.tilegrid.createXYZ({maxZoom: 20}))
    });

    var loadFeatures = function(response) {
      var features = vectorSource.readFeatures(response);
      vectorSource.addFeatures(features);
    };
```
<p>...and no errors at all, but also no features.</p>
<p>Then I simply set:</p>
<pre class="lang-js prettyprint-override"><code>    var url =  'http://localhost:8080/geoserver/mapname/wfs?service=WFS&'+'version=1.0.0&request=GetFeature&typeName=mapname:awesomelayer&'+'outputFormat=application/json&maxFeatures=50'
    var vectorSource = new ol.source.Vector({
              format: new ol.format.GeoJSON(),
              strategy: new ol.loadingstrategy.tile(ol.tilegrid.createXYZ({maxZoom: 20})),
              url: function(extent, resolution, projection){return url}
    });
</code>```

....which worked.

I do not get the difference, url is similar, quicker and does not require a loadFeatures function. I read the manual, but in practice, in terms of code, I cannot understand  it. What is loader for, why it does not set a URL and when to use it? What am I missing here?

答:
I just faced the same problem as yours. Method with url works well, but I faced problem when using the Loader.

Here's the problem, from your url I notice that your outputFormat=application/json, meanwhile inside the loader function you specified dataType: 'jsonp' .

The dataType: 'jsonp' only works if your outputFormat=text/javascript . Refer to this link by GeoServer , it explains format with its correct syntax.

Therefore you have to use JSONP instead of JSON, in order to enable JSONP please follow the answer in here https://gis.stackexchange.com/questions/57494/geoserver-2-3-how-to-enable-jsonp . After that change your outputFormat to outputFormat=text/javascript

Body:
I have to load a  WFS layer from my Geoserver to my website with Openlayers 3.9.0.

According to the manual there are two options to load features, loader(ol.FeatureLoader) and url (ol.FeatureUrlFunction).

I dont get the difference between the two. They both used to load features, loader, does not set any URL and looks more complicated.

I tried:

    var url =  'http://localhost:8080/geoserver/mapname/wfs?service=WFS&'+'version=1.0.0&request=GetFeature&typeName=mapname:awesomelayer&'+'outputFormat=application/json&maxFeatures=50'
    var vectorSource = new ol.source.Vector({
              format: new ol.format.GeoJSON(),
              loader: function(extent){
                    $.ajax({
                    url: url,
                    type:'GET',
                    dataType: 'jsonp'
                    }).done(loadFeatures);
               },
              strategy: new ol.loadingstrategy.tile(ol.tilegrid.createXYZ({maxZoom: 20}))
    });

    var loadFeatures = function(response) {
      var features = vectorSource.readFeatures(response);
      vectorSource.addFeatures(features);
    };

...and no errors at all, but also no features.

Then I simply set:

    var url =  'http://localhost:8080/geoserver/mapname/wfs?service=WFS&'+'version=1.0.0&request=GetFeature&typeName=mapname:awesomelayer&'+'outputFormat=application/json&maxFeatures=50'
    var vectorSource = new ol.source.Vector({
              format: new ol.format.GeoJSON(),
              strategy: new ol.loadingstrategy.tile(ol.tilegrid.createXYZ({maxZoom: 20})),
              url: function(extent, resolution, projection){return url}
    });

....which worked.

I do not get the difference, url is similar, quicker and does not require a loadFeatures function. I read the manual, but in practice, in terms of code, I cannot understand  it. What is loader for, why it does not set a URL and when to use it? What am I missing here?


问:
(ijson) Getting item with any prefix
I am having a json file like this:

```<code>{
    "europe": [
      "germany",
      "france",
      ...
    ],
    "america": [
      "usa",
      "canada",
      ...
    ]
  }
</code>```

I want to get all items of every prefix like this:

```<code>germany
france
usa
canada
</code>```

I use this:

```<code>with open('file.json', 'r', encoding='utf-8') as f:
    for object in ijson.items(f, "item"):
        print (object)
</code>```

I tried it with a regular expression that accept every string in front of item, but it does not work. I think there is a really easy solution I just don't see. Also looked in the documentation of ijson, but didn't find any solution either.

Maybe you can help me.

Greetings

答:
There's currently no way of doing this with items as it doesn't support wildcards or depth specifications. The closest you can get with no fuss (with 2.6) is doing:

for continent, countries in ijson.kvitems(f, ''):
   for country in countries:
      print(country)
```

If individual lists of countries are themselves too big to be held in memory you'd have to resort to a more manual approach based on ijson.parse() keeping track of the "depth" of your path.

Title: (ijson) Getting item with any prefix

Body:
I am having a json file like this:

{
    "europe": [
      "germany",
      "france",
      ...
    ],
    "america": [
      "usa",
      "canada",
      ...
    ]
  }

I want to get all items of every prefix like this:

germany
france
usa
canada

I use this:

with open('file.json', 'r', encoding='utf-8') as f:
    for object in ijson.items(f, "item"):
        print (object)

I tried it with a regular expression that accept every string in front of item, but it does not work. I think there is a really easy solution I just don't see. Also looked in the documentation of ijson, but didn't find any solution either.

Maybe you can help me.

Greetings

Body:
There's currently no way of doing this with items as it doesn't support wildcards or depth specifications. The closest you can get with no fuss (with 2.6) is doing:

for continent, countries in ijson.kvitems(f, ''):
   for country in countries:
      print(country)

If individual lists of countries are themselves too big to be held in memory you'd have to resort to a more manual approach based on ijson.parse() keeping track of the "depth" of your path.


问:
Font awesome icon does not show
I am working with Angular 4 in dev environment (localhost). I installed font awesome via npm and added:

```<code>"./node_modules/font-awesome/css/font-awesome.css",
</code>```

to my styles scripts.

When I check my icon in browser, everything looks fine:

But my icon does not appear on the page, just an empty square. What am I doing wrong?

答:
If you're using the free version. Try this..

First Delete fortawesome registry & authToken

```<code>npm config delete "@fortawesome:registry"
npm config delete "//npm.fontawesome.com/:_authToken"
</code>```

Then Install the package

```<code>npm install --save-dev @fortawesome/fontawesome-free
</code>```

After Installing the package, Add below code in your angular.json file

```<code>   ......
    "styles": [
    ......
    "node_modules/@fortawesome/fontawesome-free/css/all.css"
    ],
    "scripts": [
    ....
    "node_modules/@fortawesome/fontawesome-free/js/all.js"
    ],
    .....

</code>```

Note: There were twice of those blocks (styles/scripts). Add to both

Title: Font awesome icon does not show

Body:
I am working with Angular 4 in dev environment (localhost). I installed font awesome via npm and added:

"./node_modules/font-awesome/css/font-awesome.css",

to my styles scripts.

When I check my icon in browser, everything looks fine:

But my icon does not appear on the page, just an empty square. What am I doing wrong?

Body:
If you're using the free version. Try this..

First Delete fortawesome registry & authToken

npm config delete "@fortawesome:registry"
npm config delete "//npm.fontawesome.com/:_authToken"

Then Install the package

npm install --save-dev @fortawesome/fontawesome-free

After Installing the package, Add below code in your angular.json file

   ......
    "styles": [
    ......
    "node_modules/@fortawesome/fontawesome-free/css/all.css"
    ],
    "scripts": [
    ....
    "node_modules/@fortawesome/fontawesome-free/js/all.js"
    ],
    .....

Note: There were twice of those blocks (styles/scripts). Add to both


问:
How to copy images from gallery to app’s installation directory in React-native
I want to pick an image from gallery and copy that image to the currently running app’s installation directory using react-native.</p>

答:
You can use React Native Image Picker to pick an image from Camera Roll or Gallery.

See it's usage code here

To write any file into native file storage, you can use RNFS

See a basic example here


问:
Searching and adding product in cart of bigbasket using selenium
I was trying to search and add product in the cart using selenium but was not able to successfully do it

```<code>  driver.get("https://www.bigbasket.com/cl/fruits-vegetables/?nc=nb");
  List<WebElement> product = driver.findElements(By.xpath("//div[@qa=\'product\']"));
    System.out.println("prdoduct=" + product.size());
    for(int i=0;i<product.size();i++)
    {
        String name = product.get(i).getText();
        System.out.println("NAME is" + name);

        String  xp= "(//button[@qa=\'add\'])" + "["+i+ "]";
        System.out.println("xp="+xp);
        if(name.contains("Cauliflower"))
        {
            System.out.println("xp" +xp);
            driver.findElement(By.xpath(xp)).click();
         }
     }
</code>```

In this previous product is getting selected but when I was debugging it was on the cauliflower     but still the previous product is getting selected

答:
there is a chance that some time the element get overlapped by another element. At this time, the normal selenium click will try to click on the overlapped element. so it is better to use js click, it will click the exact element even if it is overlapped

```<code>WebElement element= driver.findElement(By.xpath(xp));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
</code>```

There is also a chance for issue in your xpath. Since list starts at 0 , you may need to change i in to i+1 in xp for getting current selection add button.do try this xpath too

```<code>String  xp= "(//button[@qa=\'add\'])" + "["+(i+1)+ "]";
</code>```

Body:
I was trying to search and add product in the cart using selenium but was not able to successfully do it

  driver.get("https://www.bigbasket.com/cl/fruits-vegetables/?nc=nb");
  List<WebElement> product = driver.findElements(By.xpath("//div[@qa=\'product\']"));
    System.out.println("prdoduct=" + product.size());
    for(int i=0;i<product.size();i++)
    {
        String name = product.get(i).getText();
        System.out.println("NAME is" + name);

        String  xp= "(//button[@qa=\'add\'])" + "["+i+ "]";
        System.out.println("xp="+xp);
        if(name.contains("Cauliflower"))
        {
            System.out.println("xp" +xp);
            driver.findElement(By.xpath(xp)).click();
         }
     }

In this previous product is getting selected but when I was debugging it was on the cauliflower     but still the previous product is getting selected

Body:
there is a chance that some time the element get overlapped by another element. At this time, the normal selenium click will try to click on the overlapped element. so it is better to use js click, it will click the exact element even if it is overlapped

WebElement element= driver.findElement(By.xpath(xp));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);

There is also a chance for issue in your xpath. Since list starts at 0 , you may need to change i in to i+1 in xp for getting current selection add button.do try this xpath too

String  xp= "(//button[@qa=\'add\'])" + "["+(i+1)+ "]";


答:
No, it's totally up to you on how you want to handle the state of your React app.

You can go with the Context API that react ships with if you don't want to add any third party library.

Further I'd suggest you give the following article a read, it's by Dan Abramov, he is the co-author of Redux and Create React App.

You might not need redux
https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367

Title: Is Redux needed for every ReactJS project?

Body: I have a question: Is Redux needed for every ReactJS project for development?


问:
Get accessed to plucked object using javascript and lodash
I have an array of users in my javascript. For each user I am comparing if that user appears in another list.

```<code>var users = USERS.getUsers();

for (var i = 0; i < users.length; i++) {
    var u = users[i];
    if (util.pluck(myList.adminUsers, 'email').includes(u.email)) {
        // How do I check the value of the plucked value for myList.adminUsers.locationId ?
        u.status = "admin";
    }
}
</code>```

users is an array of user objects.

```<code>[{...}]
    0:
        id: "1"
        email: "johndoe@gmail.com"
        firstname: "John"
        lastname: "Doe"
        roleid: "1"
        _proto__: Object
    1:
        id: "2"
        email: "janedoe@gmail.com"
        firstname: "Jane"
        lastname: "Doe"
        roleid: "1"
        _proto__: Object
</code>```

myList.adminUsers is also an array of user objects but also with locationId.

```<code>[{...}]
    0:
        id: "1"
        email: "johndoe@gmail.com"
        firstname: "John"
        lastname: "Doe"
        roleid: "1"
        locationId: "123"
        _proto__: Object
</code>```

I need to compare another field in this check. So I need to see if the plucked object from myList.adminUsers has a field locationId that equals x, but I'm not sure how to do this?

How can I get access to the plucked object so I can check the value of locationId?

答:
This should give you the list of admins that are found in the list of users and are in the location ID you provide as a value (I set it as a variable).

const users = [
  {
    id: "1",
    email: "johndoe@gmail.com",
    firstname: "John",
    lastname: "Doe",
    roleid: "1"
  },
  {
    id: "2",
    email: "janedoe@gmail.com",
    firstname: "Jane",
    lastname: "Doe",
    roleid: "1"
  }
];

const admins = [
  {
    id: "1",
    email: "johndoe@gmail.com",
    firstname: "John",
    lastname: "Doe",
    roleid: "1",
    locationId: "123"
  }
];

const locationIdToFind = '123';

const adminsWithLocation = _.intersectionWith(admins, users, (admin, user) => _.isEqual(admin.email, user.email) && _.isEqual(admin.locationId, locationIdToFind));

console.log(adminsWithLocation);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script></code>```

Body:
I have an array of users in my javascript. For each user I am comparing if that user appears in another list.

var users = USERS.getUsers();

for (var i = 0; i < users.length; i++) {
    var u = users[i];
    if (util.pluck(myList.adminUsers, 'email').includes(u.email)) {
        // How do I check the value of the plucked value for myList.adminUsers.locationId ?
        u.status = "admin";
    }
}

users is an array of user objects.

[{...}]
    0:
        id: "1"
        email: "johndoe@gmail.com"
        firstname: "John"
        lastname: "Doe"
        roleid: "1"
        _proto__: Object
    1:
        id: "2"
        email: "janedoe@gmail.com"
        firstname: "Jane"
        lastname: "Doe"
        roleid: "1"
        _proto__: Object

myList.adminUsers is also an array of user objects but also with locationId.

[{...}]
    0:
        id: "1"
        email: "johndoe@gmail.com"
        firstname: "John"
        lastname: "Doe"
        roleid: "1"
        locationId: "123"
        _proto__: Object

I need to compare another field in this check. So I need to see if the plucked object from myList.adminUsers has a field locationId that equals x, but I'm not sure how to do this?

How can I get access to the plucked object so I can check the value of locationId?

Body:
This should give you the list of admins that are found in the list of users and are in the location ID you provide as a value (I set it as a variable).

const users = [
  {
    id: "1",
    email: "johndoe@gmail.com",
    firstname: "John",
    lastname: "Doe",
    roleid: "1"
  },
  {
    id: "2",
    email: "janedoe@gmail.com",
    firstname: "Jane",
    lastname: "Doe",
    roleid: "1"
  }
];

const admins = [
  {
    id: "1",
    email: "johndoe@gmail.com",
    firstname: "John",
    lastname: "Doe",
    roleid: "1",
    locationId: "123"
  }
];

const locationIdToFind = '123';

const adminsWithLocation = _.intersectionWith(admins, users, (admin, user) => _.isEqual(admin.email, user.email) && _.isEqual(admin.locationId, locationIdToFind));

console.log(adminsWithLocation);

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>