问:
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

答:
Could you try the following,

Add the option authenticity_token: true to the form, then the params once again contain an authenticity_token. And rename your save_card.js to save_card.js.erb.

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


来源: stackexchange

问:
Write a function called randomization that takes as input a positive integer n, and returns A, a random n x 1 Numpy array
Write a function called randomization that takes as input a positive integer n, and returns A, a random n x 1 numpy array.

Below is what I have but it's not working.

import numpy as np

def randomization(n):
    if n>0 and n==int:
        A=np.random.random([n, 1])
    print(A)
x=int(input("enter a positive number: "))
r=randomization(x)
print(r)
```

If I run this I get a message saying "local variable 'A' referenced before assignment".

答:
First, n == int will always be false, because n is not the type int. Use isinstance(n, int) instead.

Because of that, A is never assigned, but then you call print(A) as if it were assigned.

ContentLicense: CC BY-SA 4.0

Body:
Write a function called randomization that takes as input a positive integer n, and returns A, a random n x 1 numpy array.

Below is what I have but it's not working.

import numpy as np

def randomization(n):
    if n>0 and n==int:
        A=np.random.random([n, 1])
    print(A)
x=int(input("enter a positive number: "))
r=randomization(x)
print(r)

If I run this I get a message saying "local variable 'A' referenced before assignment".


问:
how to restrict user from accessing a perticular action of a controller?
HI.
I have two user's for my app.one is admin n other visitors..i have two actions in my controller.i admin can act on both but i want visitors to be restricted from accessing 2nd action.how to achieve it?

Waiting for answer with advance thanks,

答:
The spring security plugin is the way to go. http://grails.org/plugin/spring-security-core

I would recommend using the annotation approach. There is a section on using annotations in the blog post http://blog.springsource.com/2010/08/11/simplified-spring-security-with-grails/

I would recommend reading the above blog post in its entirety

E.g. Controller action would be secured like....

```<code>//all users
@Secured(['IS_AUTHENTICATED_REMEMBERED'])
def firstAction = { ... }

//only admin
@Secured(['ROLE_ADMIN'])
def secondAction = { ... }
</code>```

The plugin also offers a "remember me" option if you dont want to force your users to always login

ContentLicense: CC BY-SA 3.0

Body:
The spring security plugin is the way to go. http://grails.org/plugin/spring-security-core

I would recommend using the annotation approach. There is a section on using annotations in the blog post http://blog.springsource.com/2010/08/11/simplified-spring-security-with-grails/

I would recommend reading the above blog post in its entirety

E.g. Controller action would be secured like....

//all users
@Secured(['IS_AUTHENTICATED_REMEMBERED'])
def firstAction = { ... }

//only admin
@Secured(['ROLE_ADMIN'])
def secondAction = { ... }

The plugin also offers a "remember me" option if you dont want to force your users to always login


问:
Discrepancy between diagram and equations of GRU?
While I was reading the blog of Colah,
In the diagram we can clearly see that zt is going to
~ht and not rt
But the equations say otherwise. Isn’t this supposed to be zt*ht-1 And not rt*ht-1.
Please correct me if I’m wrong.

答: I see this is somehow old, however, if you still haven't figured it out and care, or for any other person who would end up here, the answer is that the figure and equations are consistent. Note that, the operator (x) in the diagram (the pink circle with an X in it) is the Hadamard product, which is an element-wise multiplication between two tensors of the same size. In the equations, this operator is illustrated by * (usually it is represented by a circle and a dot at its center). ~h_t is the output of the tanh operator. The tanh operator receives a linear combination of the input at time t, x_t, and the result of the Hadamard product between r_t and h_{t-1}. Note that r_t should have already been updated by passing the linear combination of x_t and h_{t-1} through a sigmoid. I hope the reset is clear.


问:
React state missing
I am working with React and I can't seem to define properly the state of a component (handlePoints). When I want to assign a new state using shallow copy it creates a new entry (key).

Apologies that part of the question is not in code. I couldn't edit it here. If you need more information please reach out. Thanks! I've added an image where you can see that there is a new entry added instead of a modification happening to an existing entry.

```<code>cons anecdotes = ['Anecdote A', 'Anecdote B', 'Anecdote C', 'Anecdote D', 'Anecdote E', 'Anecdote F']
const Button = ({text, onClick}) => <div>
<button onClick={onClick}>{text}</button>
</code>```

```<code>const records = () => {
  const temp = {};
  for (let i = 0; i < anecdotes.length; i++) {
    temp[i] = 0;
  }
  return temp}

const copy = {...records()};

const App = (props) => {
console.log('Copy', copy);
const [selected, setSelected] = useState(0);
const [points, setPoints] = useState(copy);
const handleSelection = () => {
    setSelected((Math.random() * (anecdotes.length) ) << 0);
};
const handlePoints = () => {
    setPoints({...copy, selected: copy[selected] += 1})
};

return (
    <div>
        <p>{JSON.stringify({copy})}</p>
        <p>{JSON.stringify({points})}</p>
        <p>Selected:  {selected}</p>
        <Button onClick={handleSelection} text={'next anecdote'}/>
        <Button onClick={handlePoints} text={'vote'}/>
        has {copy[selected]} votes <br/>
        {props.anecdotes[selected]} <br/>
    </div>
);};
</code>```

The line where I cannot set the state correctly is:

```<code>const handlePoints = () => {
    setPoints({...copy, selected: copy[selected] += 1})
};
</code>```

As you can see, a new entry was added instead of updating one of the existing one.

答:
In terms of why a new field with key 'selected' is being added, is due to how you are creating the new object.
If you want to to update the key with the variable selected, you would need to modify the handlePoints function to be:

```<code>const handlePoints = () => {
    setPoints({...copy, [selected]: copy[selected] += 1})
};
</code>```

The brackets around the variable selected is how it determines to use the value of the variable selected. Instead of interpreting it as a the key 'selected'. This is making use of the computed property names introduced in emca2015. More info - Computed property names

Hopefully this solves your problem :)
Good luck :D

Also:

As for what I can see, your copy function it isn't actually copying any object, it seems to be a default? Or is the purpose just to create the keys for the number of anecdotes there are?
Just curious XD

Title: React state missing

Body:
I am working with React and I can't seem to define properly the state of a component (handlePoints). When I want to assign a new state using shallow copy it creates a new entry (key).

Apologies that part of the question is not in code. I couldn't edit it here. If you need more information please reach out. Thanks! I've added an image where you can see that there is a new entry added instead of a modification happening to an existing entry.

cons anecdotes = ['Anecdote A', 'Anecdote B', 'Anecdote C', 'Anecdote D', 'Anecdote E', 'Anecdote F']
const Button = ({text, onClick}) =>

<button onClick={onClick}>{text}</button>

const records = () => {
  const temp = {};
  for (let i = 0; i < anecdotes.length; i++) {
    temp[i] = 0;
  }
  return temp}

const copy = {...records()};

const App = (props) => {
console.log('Copy', copy);
const [selected, setSelected] = useState(0);
const [points, setPoints] = useState(copy);
const handleSelection = () => {
    setSelected((Math.random() * (anecdotes.length) ) << 0);
};
const handlePoints = () => {
    setPoints({...copy, selected: copy[selected] += 1})
};

return (

{JSON.stringify({copy})}

{JSON.stringify({points})}

Selected:  {selected}

        <Button onClick={handleSelection} text={'next anecdote'}/>
        <Button onClick={handlePoints} text={'vote'}/>
        has {copy[selected]} votes

        {props.anecdotes[selected]}

);};

The line where I cannot set the state correctly is:

const handlePoints = () => {
    setPoints({...copy, selected: copy[selected] += 1})
};

As you can see, a new entry was added instead of updating one of the existing one.

Body:
In terms of why a new field with key 'selected' is being added, is due to how you are creating the new object.
If you want to to update the key with the variable selected, you would need to modify the handlePoints function to be:

const handlePoints = () => {
    setPoints({...copy, [selected]: copy[selected] += 1})
};

The brackets around the variable selected is how it determines to use the value of the variable selected. Instead of interpreting it as a the key 'selected'. This is making use of the computed property names introduced in emca2015. More info - Computed property names

Hopefully this solves your problem :)
Good luck :D

Also:

As for what I can see, your copy function it isn't actually copying any object, it seems to be a default? Or is the purpose just to create the keys for the number of anecdotes there are?
Just curious XD


问:
accessing python interpreter from a pyinstaller bundle #2
I'm trying to execute a python script which is included in datas, and bundled into a pyinstaller executable (on a mac). I need to pass parameters to this script, so I can't just exec(open(read()). Outside of pyinstaller, sys.executable is the python interpreter, so calling the python script works fine. In pyinstaller, sys.executable is the 'main' py script, so it just opens up my app again instead of calling the new script. How can I call my additional python script inside my app? This is what I'm trying to acheive, which does not work with a bundled pyinstaller app:</p>

```<code>subprocess.call([sys.executable, os.path.join(wd,"tests","errorMessage.py"), vArgument])
</code>```

答:
This is how I got it to work, which is kinda janky imo. It doesn't call the python interpreter as I originally wanted, but executes the py script including arguments:

```<code># set the arguments beforehand
sys.argv = [os.path.join(wd,"tests","errorMessage.py"), vArguments]
# execute the script, but also bring in globals so imported modules are there
exec(open(os.path.join(wd,"tests","errorMessage.py")).read(), globals())
</code>```

Pyinstaller seems to work after this whole deal.. omg...

Body:
I'm trying to execute a python script which is included in datas, and bundled into a pyinstaller executable (on a mac). I need to pass parameters to this script, so I can't just exec(open(read()). Outside of pyinstaller, sys.executable is the python interpreter, so calling the python script works fine. In pyinstaller, sys.executable is the 'main' py script, so it just opens up my app again instead of calling the new script. How can I call my additional python script inside my app? This is what I'm trying to acheive, which does not work with a bundled pyinstaller app:

subprocess.call([sys.executable, os.path.join(wd,"tests","errorMessage.py"), vArgument])

Body:
This is how I got it to work, which is kinda janky imo. It doesn't call the python interpreter as I originally wanted, but executes the py script including arguments:

# set the arguments beforehand
sys.argv = [os.path.join(wd,"tests","errorMessage.py"), vArguments]
# execute the script, but also bring in globals so imported modules are there
exec(open(os.path.join(wd,"tests","errorMessage.py")).read(), globals())

Pyinstaller seems to work after this whole deal.. omg...


问:
facet_wrap with layout like facet_grid
Using facet_grid wraps panels according to the factor levels in the variables provided, even if there is no data present for a given combination. This is the behaviour I am after.

Unfortunately, the y-axes scales can not be made independent on the individual panel level (see here and here). For that, you must use facet_wrap.

facet_wrap, however, doesn't provide the same layout as facet_grid, and only displays the panels that have values to be plotted.

How can I keep the facet_grid-like layout but with independent y-axis scales? It is okay if the panels without data are blank/void as long as they occupy the appropriate space.

Reproducible example:

```<code>library(ggplot2)
set.seed(1)

# Generate data
test <- data.frame(x = c(rep(1, 6), rep(2, 6)),
                   facet_1 = rep(c("A", "A", "A", "B", "B", "C"), 2),
                   facet_2 = rep(c("B", "C", "D", "C", "D", "D"), 2),
                   y = c(1e0, 1e1, 1e2, 1e3, 1e4, 1e5, rnorm(1, 1e0, 1e0*.34), rnorm(1, 1e1, 1e1*.34), rnorm(1, 1e2, 1e2*.34), rnorm(1, 1e3, 1e3*.34), rnorm(1, 1e4, 1e4*.34), rnorm(1, 1e5, 1e5*.34)))

# facet_grid - Shows blank panels B-B, B-C, and C-C. This is what I want.
#            - Does NOT scale y appropriately at the individual panel level.
ggplot(test, aes(x = x, y = y)) +
  facet_grid(facet_2 ~ facet_1, scales = "free") +
  geom_line()
</code>```

```<code># facet_wrap - Does NOT show blank panels B-B, B-C, and C-C.
#            - Does scale y appropriately at the individual panel level.
ggplot(test, aes(x = x, y = y)) +
  facet_wrap(vars(facet_1, facet_2), scales = "free") +
  geom_line()
</code>```

答:
You can complete the missing combination and then plot.

```<code>library(ggplot2)

tidyr::complete(test, facet_1, facet_2, fill = list(x = 0, y = 0)) %>%
#Keeping them as NA would give a blank plot
#tidyr::complete(test, facet_1, facet_2) %>%
   ggplot() + aes(x = x, y = y) +
   facet_wrap(vars(facet_1, facet_2), scales = "free") +
   geom_line()
</code>```

This would give you a warning as there is only one observation in those 3 groups.

Title: facet_wrap with layout like facet_grid

Body:
Using facet_grid wraps panels according to the factor levels in the variables provided, even if there is no data present for a given combination. This is the behaviour I am after.

Unfortunately, the y-axes scales can not be made independent on the individual panel level (see here and here). For that, you must use facet_wrap.

facet_wrap, however, doesn't provide the same layout as facet_grid, and only displays the panels that have values to be plotted.

How can I keep the facet_grid-like layout but with independent y-axis scales? It is okay if the panels without data are blank/void as long as they occupy the appropriate space.

Reproducible example:

library(ggplot2)
set.seed(1)

# Generate data
test <- data.frame(x = c(rep(1, 6), rep(2, 6)),
                   facet_1 = rep(c("A", "A", "A", "B", "B", "C"), 2),
                   facet_2 = rep(c("B", "C", "D", "C", "D", "D"), 2),
                   y = c(1e0, 1e1, 1e2, 1e3, 1e4, 1e5, rnorm(1, 1e0, 1e0*.34), rnorm(1, 1e1, 1e1*.34), rnorm(1, 1e2, 1e2*.34), rnorm(1, 1e3, 1e3*.34), rnorm(1, 1e4, 1e4*.34), rnorm(1, 1e5, 1e5*.34)))

# facet_grid - Shows blank panels B-B, B-C, and C-C. This is what I want.
#            - Does NOT scale y appropriately at the individual panel level.
ggplot(test, aes(x = x, y = y)) +
  facet_grid(facet_2 ~ facet_1, scales = "free") +
  geom_line()

# facet_wrap - Does NOT show blank panels B-B, B-C, and C-C.
#            - Does scale y appropriately at the individual panel level.
ggplot(test, aes(x = x, y = y)) +
  facet_wrap(vars(facet_1, facet_2), scales = "free") +
  geom_line()

Body:
You can complete the missing combination and then plot.

library(ggplot2)

tidyr::complete(test, facet_1, facet_2, fill = list(x = 0, y = 0)) %>%
#Keeping them as NA would give a blank plot
#tidyr::complete(test, facet_1, facet_2) %>%
   ggplot() + aes(x = x, y = y) +
   facet_wrap(vars(facet_1, facet_2), scales = "free") +
   geom_line()

This would give you a warning as there is only one observation in those 3 groups.


问:
cancelling default touchmove event
i have created a little slide show in jQuery. On clicking-n-dragging your mouse it shows next/previous slide. I have added special code for dealing with iphone. But on iphone (safari)
when i move my finger over the object the whole page is dragged left-right.
here is the code

```<code>        var oldX = 0;
        $('#movieShow').bind('touchstart',function(e){
                if(e.touches.length == 1){
                    var touch = e.touches[0];
                    oldX = touch.pageX;
                }
                return false;
            }).bind('touchmove',function(e){
                if(e.touches.length == 1){
                    var touch = e.touches[0];
                    if((touch.pageX - oldX) > 0){
                        var t = touch.pageX - oldX;
                        if(t%5==0){
                            oldX = touch.pageX;
                            rightClick();
                        }
                    }
                    else{
                        var t = oldX - touch.pageX;
                        if(t%5==0){
                            oldX = touch.pageX;
                            leftClick();
                        }
                    }
                }
                return false;
            });
</code>```

how do i cancel defaults iphone event?

答: you can use event.preventDefault();</p>

ContentLicense: CC BY-SA 2.5

Title: cancelling default touchmove event

Body:
i have created a little slide show in jQuery. On clicking-n-dragging your mouse it shows next/previous slide. I have added special code for dealing with iphone. But on iphone (safari)
when i move my finger over the object the whole page is dragged left-right.
here is the code

        var oldX = 0;
        $('#movieShow').bind('touchstart',function(e){
                if(e.touches.length == 1){
                    var touch = e.touches[0];
                    oldX = touch.pageX;
                }
                return false;
            }).bind('touchmove',function(e){
                if(e.touches.length == 1){
                    var touch = e.touches[0];
                    if((touch.pageX - oldX) > 0){
                        var t = touch.pageX - oldX;
                        if(t%5==0){
                            oldX = touch.pageX;
                            rightClick();
                        }
                    }
                    else{
                        var t = oldX - touch.pageX;
                        if(t%5==0){
                            oldX = touch.pageX;
                            leftClick();
                        }
                    }
                }
                return false;
            });

how do i cancel defaults iphone event?

Body: you can use event.preventDefault();


问:
Trouble with C# console code. Trying to get a while loop to average 3 test scores. Final product is only using the first number entered in while loop
Struggling with understanding the while loop. I'm just starting to learn programming. While testing the code, it appears as if only the second number entered gets processed into the final answer. </p>

```<code>  static void Main(string[] args)
    {
        Console.WriteLine("Enter test score");

        string input = Console.ReadLine();
        double value = Double.Parse(input);

        double sum = 0.0;
        int counter = 1;
        int total = 3;

        while (counter < total)
        {
            sum = sum + value;
            counter = counter + 1;

            Console.WriteLine("Enter another test score");
            input = Console.ReadLine();
            value = Double.Parse(input);

        }
        Console.WriteLine("Test score average is: {0:N2}", sum / total);
        Console.Read();
    }
</code>```

答:
You use Wrong number

total is 3, but you need repeat 3 times calculate

counter 1 calculate clear

counter 2 calculate clear

but counter 3 is while false.

you need to fix counter <=total or counter started 0

Body:
Struggling with understanding the while loop. I'm just starting to learn programming. While testing the code, it appears as if only the second number entered gets processed into the final answer.

  static void Main(string[] args)
    {
        Console.WriteLine("Enter test score");

        string input = Console.ReadLine();
        double value = Double.Parse(input);

        double sum = 0.0;
        int counter = 1;
        int total = 3;

        while (counter < total)
        {
            sum = sum + value;
            counter = counter + 1;

            Console.WriteLine("Enter another test score");
            input = Console.ReadLine();
            value = Double.Parse(input);

        }
        Console.WriteLine("Test score average is: {0:N2}", sum / total);
        Console.Read();
    }


问:
Custom xib inside another xib not being sized properly
To get started, here is the hierarchy of my views:

```<code>- Table view
-- Table view cell (loaded from custom xib)
--- Collection view
---- Collection view cell (loaded from custom xib)
----- Custom view (loaded from custom xib)
</code>```

What I'm having trouble with is that last view, the custom view, that I'm loading into the collection view cell as a custom xib. For some reason, it isn't being sized properly:

As you can see, the view has a giant white space above it, instead of filling out the cell properly. Funnily enough, if I scroll down the table view a bit, and then scroll back up, it displays at it should:

Here is part of my collection view code:

```<code>// I use this to size the collection view cells to be of 16:9 ratio, nothing crazy
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // Get the width of the screen
    let width = UIScreen.main.bounds.width

    let imageWidth = width
    let imageHeight = imageWidth / (16 / 9)

    self.postMediaHeight = imageHeight

    return CGSize(width: imageWidth, height: imageHeight)
}

// Here I initialize the cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PostMediaCollectionViewCell", for: indexPath as IndexPath) as? PostMediaCollectionViewCell else {
        fatalError("The dequeued cell is not an instance of PostMediaCollectionViewCell.")
    }

    let media = post.images[indexPath.row]

    cell.initialize()

    return cell
}
</code>```

Here is my collection view cell class, PostMediaCollectionViewCell. Nothing out of the ordinary:

```<code>class PostMediaCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var container: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var moreView: UIView!
    @IBOutlet weak var moreViewLabel: UILabel!
    @IBOutlet weak var myCustomView: MyCustomView!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func initialize() {
        //
    }
}
</code>```

And lastly, here is my class for MyCustomView:

```<code>class MyCustomView: UIView {
    @IBOutlet var rootView: UIView!
    @IBOutlet weak var videoView: VideoView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialize()
    }

    func initialize() {
        Bundle.main.loadNibNamed("MyCustomView", owner: self, options: nil)
        addSubview(rootView)
        rootView.frame = self.bounds
        rootView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    }
}
</code>```

I've made sure that I have my constraints set right in my xibs, so auto layout should be working, but it's clearly not:

PostMediaCollectionViewCell xib:
https://i.stack.imgur.com/GQLpj.png

MyCustomView xib:
https://i.stack.imgur.com/jpSi0.png

So what am I doing wrong here?

答:
Add a breakpoint on line         rootView.frame = self.bounds and check self.bounds values. If is the value different from the value after scrolling, you should change your awakeFromNib method.

lass PostMediaCollectionViewCell: UICollectionViewCell {

```<code>@IBOutlet weak var container: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var moreView: UIView!
@IBOutlet weak var moreViewLabel: UILabel!
@IBOutlet weak var myCustomView: MyCustomView!

override func awakeFromNib() {
    super.awakeFromNib()

    self.myCustomView.frame = self.bounds
    self.myCustomView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

}

func initialize() {
    //
}
</code>```

}

Body:
To get started, here is the hierarchy of my views:

- Table view
-- Table view cell (loaded from custom xib)
--- Collection view
---- Collection view cell (loaded from custom xib)
----- Custom view (loaded from custom xib)

What I'm having trouble with is that last view, the custom view, that I'm loading into the collection view cell as a custom xib. For some reason, it isn't being sized properly:

As you can see, the view has a giant white space above it, instead of filling out the cell properly. Funnily enough, if I scroll down the table view a bit, and then scroll back up, it displays at it should:

Here is part of my collection view code:

// I use this to size the collection view cells to be of 16:9 ratio, nothing crazy
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // Get the width of the screen
    let width = UIScreen.main.bounds.width

    let imageWidth = width
    let imageHeight = imageWidth / (16 / 9)

    self.postMediaHeight = imageHeight

    return CGSize(width: imageWidth, height: imageHeight)
}

// Here I initialize the cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PostMediaCollectionViewCell", for: indexPath as IndexPath) as? PostMediaCollectionViewCell else {
        fatalError("The dequeued cell is not an instance of PostMediaCollectionViewCell.")
    }

    let media = post.images[indexPath.row]

    cell.initialize()

    return cell
}

Here is my collection view cell class, PostMediaCollectionViewCell. Nothing out of the ordinary:

class PostMediaCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var container: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var moreView: UIView!
    @IBOutlet weak var moreViewLabel: UILabel!
    @IBOutlet weak var myCustomView: MyCustomView!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func initialize() {
        //
    }
}

And lastly, here is my class for MyCustomView:

class MyCustomView: UIView {
    @IBOutlet var rootView: UIView!
    @IBOutlet weak var videoView: VideoView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialize()
    }

    func initialize() {
        Bundle.main.loadNibNamed("MyCustomView", owner: self, options: nil)
        addSubview(rootView)
        rootView.frame = self.bounds
        rootView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    }
}

I've made sure that I have my constraints set right in my xibs, so auto layout should be working, but it's clearly not:

PostMediaCollectionViewCell xib:
https://i.stack.imgur.com/GQLpj.png

MyCustomView xib:
https://i.stack.imgur.com/jpSi0.png

So what am I doing wrong here?

Body:
Add a breakpoint on line         rootView.frame = self.bounds and check self.bounds values. If is the value different from the value after scrolling, you should change your awakeFromNib method.

lass PostMediaCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var container: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var moreView: UIView!
@IBOutlet weak var moreViewLabel: UILabel!
@IBOutlet weak var myCustomView: MyCustomView!

override func awakeFromNib() {
    super.awakeFromNib()

    self.myCustomView.frame = self.bounds
    self.myCustomView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

}

func initialize() {
    //
}

}


问:
Elisp extend variable lifetime
I have a loop in which I create a local variable during each iteration. I then declare a lambda that uses the local variable sometime in the future.

```<code>      (dolist (entry (read-lines "~/.emacs-projects"))
         (let ((project (car (json-read-from-string entry)))) ;; <---- I NEED THIS ONE
             (widget-create 'link
                     :button-prefix ""
                     :button-suffix ""
                     :action (lambda (wid &rest ignore) (load-project project)) ;; HERE
                     (format "%s : %s\n" (car project) (cdr project)))))
</code>```

In the code above I create project and when :action triggers I want to use project as an argument to another function. Currently i am getting Symbol’s value as variable is void: project when the lambda is run which makes me think that the outer scope is not preserved.

How can I extend the lifetime of project so that I can access it in the lambda?

答:
Either use lexical scoping (non-nil variable lexical-binding) or use a list lambda form with the value of project substituted for the variable itself:

 (dolist (entry (read-lines "~/.emacs-projects"))
         (let ((project (car (json-read-from-string entry)))) ;; <---- I NEED THIS ONE
             (widget-create 'link
                     :button-prefix ""
                     :button-suffix ""
                     :action `(lambda (wid &rest ignore) (load-project ',project)) ;; HERE
                     (format "%s : %s\n" (car project) (cdr project)))))
```

If your action function does not really need project as a variable, but it just needs its value, then you can just substitute the value, as shown.

But in that case your lambda form will be a list (whose car is lambda, etc.), so it will not be recognized as a function before it is evaluated. In particular, the byte compiler will see it only as a list, not as a function.

Title: Elisp extend variable lifetime

Body:
I have a loop in which I create a local variable during each iteration. I then declare a lambda that uses the local variable sometime in the future.

      (dolist (entry (read-lines "~/.emacs-projects"))
         (let ((project (car (json-read-from-string entry)))) ;; <---- I NEED THIS ONE
             (widget-create 'link
                     :button-prefix ""
                     :button-suffix ""
                     :action (lambda (wid &rest ignore) (load-project project)) ;; HERE
                     (format "%s : %s\n" (car project) (cdr project)))))

In the code above I create project and when :action triggers I want to use project as an argument to another function. Currently i am getting Symbol’s value as variable is void: project when the lambda is run which makes me think that the outer scope is not preserved.

How can I extend the lifetime of project so that I can access it in the lambda?

Body:
Either use lexical scoping (non-nil variable lexical-binding) or use a list lambda form with the value of project substituted for the variable itself:

 (dolist (entry (read-lines "~/.emacs-projects"))
         (let ((project (car (json-read-from-string entry)))) ;; <---- I NEED THIS ONE
             (widget-create 'link
                     :button-prefix ""
                     :button-suffix ""
                     :action `(lambda (wid &rest ignore) (load-project ',project)) ;; HERE
                     (format "%s : %s\n" (car project) (cdr project)))))

If your action function does not really need project as a variable, but it just needs its value, then you can just substitute the value, as shown.

But in that case your lambda form will be a list (whose car is lambda, etc.), so it will not be recognized as a function before it is evaluated. In particular, the byte compiler will see it only as a list, not as a function.


问:
How do I get text color to contrast its container?
With Quasar, I'm trying to put q-breadcrumb-el inside a q-toolbar.
However, the breadcrumb text is invisible, because it's the same color as the background of the toolbar (the theme primary color).

Quasar components intended for use in the toolbar (e.g q-toolbar-title) render text in a color that contrasts correctly.
I can hard-code the color in my template, but that will fail if the theme primary color is changed to a light color.

Is there a common idiom to say something like, "contrasting with background color" or "same color as text in xxx element"  in Quasar (or Vue, or vanilla CSS)?  (I.e, something that all the cool kids just know?)

How can I determine how q-toolbar-title does it?

<q-toolbar>
  <q-toolbar-title>Wiki Page</q-toolbar-title>
  <q-breadcrumbs>
    <q-breadcrumbs-el
      v-for="section in sections"
      :key="section.label"
      :label="section.label"
      :to="section.path"
      class="text-white"
    ></q-breadcrumbs-el>
  </q-breadcrumbs>
</q-toolbar>
```

答:
If I get want you mean.

Add a CSS text-stroke property the color should be black or white only.
So as to differentiate the text color from the toolbar color.

```<code><q-toolbar>
  <q-toolbar-title>Wiki Page</q-toolbar-title>  <!-- <== white text on primary color background -->
  <q-breadcrumbs style="font-size: 20px;-webkit-text-stroke: 0.4px black;">
    <q-breadcrumbs-el
      v-for="section in sections"
      :key="section.label"
      :label="section.label"
      :to="section.path"
      class="text-white"    <!-- <== works, but is fragile -->
    ></q-breadcrumbs-el>
  </q-breadcrumbs>
</q-toolbar>
</code>```

Body:
If I get want you mean.

Add a CSS text-stroke property the color should be black or white only.
So as to differentiate the text color from the toolbar color.

<q-toolbar>
  <q-toolbar-title>Wiki Page</q-toolbar-title>  <!-- <== white text on primary color background -->
  <q-breadcrumbs style="font-size: 20px;-webkit-text-stroke: 0.4px black;">
    <q-breadcrumbs-el
      v-for="section in sections"
      :key="section.label"
      :label="section.label"
      :to="section.path"
      class="text-white"    <!-- <== works, but is fragile -->
    ></q-breadcrumbs-el>
  </q-breadcrumbs>
</q-toolbar>


问:
Send Discord Embed of Product Stock Parsed form HTML with BS4 and Requests
So I have the code:

```<code>import requests
import discord
from bs4 import BeautifulSoup

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_message(self, message):
        if (message.channel.id == 678447420643868674):
                if "test" in message.content:
                    r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
                    soup = BeautifulSoup(r.text, 'html.parser')
                    embed = discord.Embed(color=0x00ff00)
                    embed.title = "test"
                    for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():
                        if "piunavailable" in anchor_tag['class']:
                            embed.description = f"Size {anchor_tag.text} OOS"
                            await message.channel.send(embed=embed)
                        else:
                            embed.description = f"Size {anchor_tag.text}  in stock!"
                            await message.channel.send(embed=embed)
client = MyClient()
client.run('NjY2MDMyMDc0NjM3MTgwOTQ4.XkjBLg.I3dtsL2nkVh_bafTlycSwBApQfU')
</code>```

And that sends the item stock as an embed for each size:
https://gyazo.com/7a7c868d00a99fc3798a3c24feb9ea7e

How would I change the code to make it send for every size in one embed instead of an embed per size?

Thanks :)

答:
Embeds in discord can have field which you can add with the embed.add_field() function embed.add_field(name="Field1", value="hi", inline=False)

Embed have a few limits in size (copied from https://discordjs.guide/popular-topics/embeds.html#notes):

A field's name is limited to 256 characters and its value to 1024 characters

There can be up to 25 fields

In addition, the sum of all characters in an embed structure must not exceed 6000 characters

Due to this you will have to likely split your product stock into multiple embed when it exceeds 25 field or 6000 character by having a counter for both and if it goes over resetting and sending message.

Here is a part example (I've not tested it but logic should be correct)

```<code>r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
soup = BeautifulSoup(r.text, 'html.parser')
charCount = 0
fieldCount = 0
embed = discord.Embed(color=0x00ff00)
embed.title = "test"
for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():
    anchor_text = anchor_tag.text
    charCount += len(anchor_text)

    if charCount >=6000 or fieldCount >=25:
        charCount = len(anchor_text)
        fieldCount = 0

        await message.channel.send(embed=embed)
        embed = discord.Embed(color=0x00ff00)
        embed.title = "test"

    if "piunavailable" in anchor_tag['class']:
        embed.add_field(name= f"Size {anchor_text}", value="Out Of Stock")
    else:
        embed.add_field(name= f"Size {anchor_text}", value="In stock!")

    fieldCount +=1
</code>```

Body:
So I have the code:

import requests
import discord
from bs4 import BeautifulSoup

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_message(self, message):
        if (message.channel.id == 678447420643868674):
                if "test" in message.content:
                    r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
                    soup = BeautifulSoup(r.text, 'html.parser')
                    embed = discord.Embed(color=0x00ff00)
                    embed.title = "test"
                    for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():
                        if "piunavailable" in anchor_tag['class']:
                            embed.description = f"Size {anchor_tag.text} OOS"
                            await message.channel.send(embed=embed)
                        else:
                            embed.description = f"Size {anchor_tag.text}  in stock!"
                            await message.channel.send(embed=embed)
client = MyClient()
client.run('NjY2MDMyMDc0NjM3MTgwOTQ4.XkjBLg.I3dtsL2nkVh_bafTlycSwBApQfU')

And that sends the item stock as an embed for each size:
https://gyazo.com/7a7c868d00a99fc3798a3c24feb9ea7e

How would I change the code to make it send for every size in one embed instead of an embed per size?

Thanks :)

Body:
Embeds in discord can have field which you can add with the embed.add_field() function embed.add_field(name="Field1", value="hi", inline=False)

Embed have a few limits in size (copied from https://discordjs.guide/popular-topics/embeds.html#notes):

A field's name is limited to 256 characters and its value to 1024 characters

There can be up to 25 fields

In addition, the sum of all characters in an embed structure must not exceed 6000 characters

Due to this you will have to likely split your product stock into multiple embed when it exceeds 25 field or 6000 character by having a counter for both and if it goes over resetting and sending message.

Here is a part example (I've not tested it but logic should be correct)

r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
soup = BeautifulSoup(r.text, 'html.parser')
charCount = 0
fieldCount = 0
embed = discord.Embed(color=0x00ff00)
embed.title = "test"
for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():
    anchor_text = anchor_tag.text
    charCount += len(anchor_text)

    if charCount >=6000 or fieldCount >=25:
        charCount = len(anchor_text)
        fieldCount = 0

        await message.channel.send(embed=embed)
        embed = discord.Embed(color=0x00ff00)
        embed.title = "test"

    if "piunavailable" in anchor_tag['class']:
        embed.add_field(name= f"Size {anchor_text}", value="Out Of Stock")
    else:
        embed.add_field(name= f"Size {anchor_text}", value="In stock!")

    fieldCount +=1


问:
Mimic Windows Task Scheduler with code
I'm looking for a way to make a program that runs itself (or a method) every X time (days, weeks, whatever). Basically, I want my program to do what the Windows Task Scheduler could do. The reason I don't use the Task Scheduler is because I plan to deploy this application on a server which I have no remote access to, but need to re-generate some files every given time.

Suggestions?

答: You can just run a program as a service, it can have a Timer that is executed on the schedule you need. Topshelf is a simple service host for .NET that could you generate that service. I think the sample service provided does just that at a small interval.

Title: Mimic Windows Task Scheduler with code


答:
In addition to what chepner said, np.random.rand expects dimensions as arguments and not a list. That is, you should use A=np.random.rand(n, 1). Note that this returns a uniformly distributed random vector.
Also, your function doesn't return any value. use - return A at the end.</p>

Title: Write a function called randomization that takes as input a positive integer n, and returns A, a random n x 1 Numpy array

Body:
Write a function called randomization that takes as input a positive integer n, and returns A, a random n x 1 numpy array.

Below is what I have but it's not working.

import numpy as np

def randomization(n):
    if n>0 and n==int:
        A=np.random.random([n, 1])
    print(A)
x=int(input("enter a positive number: "))
r=randomization(x)
print(r)

If I run this I get a message saying "local variable 'A' referenced before assignment".


问:
Get rendered bounds of a view in viewDidLoad()
I've been searching for help on this all day but I can't find an answer.

I have a subview in which I am drawing a rectangle, the rectangle is framed by the subview so I need to know the size of the subview as adjusted by autolayout to correctly frame it.  I can't find a way of doing this from ViewDidLoad(), so that the rectangle is correctly rendered at start-up.  I have tried the following:

Using dayView.setNeedsLayout() followed by dayView.layoutIfNeeded() before I draw the rectangle in viewDidLoad() but a check either side of these statements shows the dayView.bounds unchanged.

Drawing the view from viewDidLayoutSubviews(), which works, but results in my rectangle being drawn 5 times as viewDidLayoutSubviews() is called for every subview (I have 5 of them) that is redrawn (the relevant subview containing the rectangle is redrawn on call 4 of 5) - this seems wasteful of resources, surely there is a better way?

Drawing the view twice within ViewDidLoad(), hoping the first forced draw will cause the view to be resized, so the second draw will have access to the new bounds after the first draw (desperate I know, but it still doesn't work).

I hope someone can help.

```<code>func drawGradient(object: UIView, rect: CGRect, slackX: Int, gradWidth: Int, yPos: Int) -> Void {
    // the rectangle width and height set to fit within view with x & y border.

    let gradientView = UIView(frame: rect)
    let gradient = CAGradientLayer()

    gradient.frame = gradientView.frame
    gradient.colors = getDayGradientLocations().gradientCol
    gradient.locations = getDayGradientLocations().gradientLoc
    dayView.layer.addSublayer(gradient)

    let civilDawn = getTimeAsProportionOfDay(time: tides.civilDawn) * Double(rect.height) + Double(yPos)
    let path = UIBezierPath()
    path.move(to: CGPoint(x: slackX, y: Int(civilDawn)))
    path.addLine(to: CGPoint(x: slackX + Int(rect.width), y: Int(civilDawn)))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = CGFloat(2)

    let civilDusk = getTimeAsProportionOfDay(time: tides.civilDusk) * Double(rect.height) + Double(yPos)
    path.move(to: CGPoint(x: slackX, y: Int(civilDusk)))
    path.addLine(to: CGPoint(x: slackX + Int(rect.width), y: Int(civilDusk)))
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = CGFloat(2)

    object.layer.addSublayer(shapeLayer)

    drawLabel(object: object, rect: rect, slackX: slackX, offset: 15, time: tides.civilDawn)
    drawLabel(object: object, rect: rect, slackX: slackX, offset: -15, time: tides.civilDusk)
}
</code>```

答:
A couple of observations:

If you are adjusting a view’s frame in your view controller, the right place to do this is in viewDidLayoutSubviews. Yes, this is called a number of times, but it generally doesn’t have any observable impact on performance.

I wouldn't advise any of those extremely brittle techniques of setNeedsLayout, layoutIfNeeded, or DispatchQueue.main.async inside viewDidLoad. The viewDidLayoutSubviews is the right place if you’re going to do this in the view controller.

Generally, if doing custom subview drawing and layout of subviews, you do this in the layoutSubviews of the view, rather than in any of the view controller methods.

Likewise, if you're doing any manual drawing, you’d put that in the UIView subclass (or any of the relevant CALayer subclasses), not the view controller.

Even better, rather than adjusting frames manually, it’s better to let the auto layout system handle this for you if you can. If you find yourself manually adjusting a frame, there are generally better patterns.

FWIW, you can define a container view’s constraints to be based upon the size (or intrinsic size) of its subviews (and set the content-hugging and compression-resistance of the relevant views). We often think of auto-layout as a top-down engine, but it works both ways.

If you show us your “drawing” code and/or a screen snapshot or two, we can probably offer more concrete counsel.

Body:
I've been searching for help on this all day but I can't find an answer.

I have a subview in which I am drawing a rectangle, the rectangle is framed by the subview so I need to know the size of the subview as adjusted by autolayout to correctly frame it.  I can't find a way of doing this from ViewDidLoad(), so that the rectangle is correctly rendered at start-up.  I have tried the following:

Using dayView.setNeedsLayout() followed by dayView.layoutIfNeeded() before I draw the rectangle in viewDidLoad() but a check either side of these statements shows the dayView.bounds unchanged.

Drawing the view from viewDidLayoutSubviews(), which works, but results in my rectangle being drawn 5 times as viewDidLayoutSubviews() is called for every subview (I have 5 of them) that is redrawn (the relevant subview containing the rectangle is redrawn on call 4 of 5) - this seems wasteful of resources, surely there is a better way?

Drawing the view twice within ViewDidLoad(), hoping the first forced draw will cause the view to be resized, so the second draw will have access to the new bounds after the first draw (desperate I know, but it still doesn't work).

I hope someone can help.

func drawGradient(object: UIView, rect: CGRect, slackX: Int, gradWidth: Int, yPos: Int) -> Void {
    // the rectangle width and height set to fit within view with x & y border.

    let gradientView = UIView(frame: rect)
    let gradient = CAGradientLayer()

    gradient.frame = gradientView.frame
    gradient.colors = getDayGradientLocations().gradientCol
    gradient.locations = getDayGradientLocations().gradientLoc
    dayView.layer.addSublayer(gradient)

    let civilDawn = getTimeAsProportionOfDay(time: tides.civilDawn) * Double(rect.height) + Double(yPos)
    let path = UIBezierPath()
    path.move(to: CGPoint(x: slackX, y: Int(civilDawn)))
    path.addLine(to: CGPoint(x: slackX + Int(rect.width), y: Int(civilDawn)))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = CGFloat(2)

    let civilDusk = getTimeAsProportionOfDay(time: tides.civilDusk) * Double(rect.height) + Double(yPos)
    path.move(to: CGPoint(x: slackX, y: Int(civilDusk)))
    path.addLine(to: CGPoint(x: slackX + Int(rect.width), y: Int(civilDusk)))
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = CGFloat(2)

    object.layer.addSublayer(shapeLayer)

    drawLabel(object: object, rect: rect, slackX: slackX, offset: 15, time: tides.civilDawn)
    drawLabel(object: object, rect: rect, slackX: slackX, offset: -15, time: tides.civilDusk)
}


问:
Webpack 4 as JSX files
Is there a way to load JSX files on Webpack 4?

I tried:

```<code>module.exports = {
    resolve: {
        extensions: [".jsx", ".js"]
    }
}
</code>```

But apparently my src/index.jsx file is loaded but not processed.

答:
you need to install

```<code> npm i @babel/preset-react --save
</code>```

add this to .babelrc file inside presets array. We use loaders inside module property of the webpack.config object because loaders are effective on one type of files whereas plugins are effective on the entire bundle.

.babelrc

```<code>{
  "presets": [
    ["@babel/preset-env", { "targets": { "esmodules": true } }],
    "@babel/preset-react"
  ],
</code>```

all webpack projects needs @babel/preset-env. you might install that as well.
}

Title: Webpack 4 as JSX files

Body:
Is there a way to load JSX files on Webpack 4?

I tried:

module.exports = {
    resolve: {
        extensions: [".jsx", ".js"]
    }
}

But apparently my src/index.jsx file is loaded but not processed.

Body:
you need to install

 npm i @babel/preset-react --save

add this to .babelrc file inside presets array. We use loaders inside module property of the webpack.config object because loaders are effective on one type of files whereas plugins are effective on the entire bundle.

.babelrc

{
  "presets": [
    ["@babel/preset-env", { "targets": { "esmodules": true } }],
    "@babel/preset-react"
  ],

all webpack projects needs @babel/preset-env. you might install that as well.
}


问:
Sequelize Join on Non Primary Key
I have two tables I need to associate. TableA has One TableB. I'm able to do this in the TableA Model:

```<code>TableA.hasOne( models.TableB, { as: 'TableB', foreignKey: 'someID' } );
</code>```

Looking at the SQL, this tries to join TableA.ID and TableB.someID. What I actually want, is to join TableA.someNonPrimaryKey and TableB.someID.

How can I tell sequelize to join with someNonPrimaryKey?

答:
I know this is old; I am responding for the sake of others that might need the answer.

You can now associate tables on non-primary key columns. In your case, the association would be:

```<code>TableA.hasOne(TableB, {
  sourceKey: 'someNonPrimaryKeyColumnOnTableA',
  foreignKey: 'matchingColumnOnTableB'
});
</code>```

Please note, the column someNonPrimaryKeyColumnOnTableA must have unique set to true in the model definition.

You can read more about it here: https://sequelize.org/master/manual/assocs.html

Title: Sequelize Join on Non Primary Key

Body:
I have two tables I need to associate. TableA has One TableB. I'm able to do this in the TableA Model:

TableA.hasOne( models.TableB, { as: 'TableB', foreignKey: 'someID' } );

Looking at the SQL, this tries to join TableA.ID and TableB.someID. What I actually want, is to join TableA.someNonPrimaryKey and TableB.someID.

How can I tell sequelize to join with someNonPrimaryKey?

Body:
I know this is old; I am responding for the sake of others that might need the answer.

You can now associate tables on non-primary key columns. In your case, the association would be:

TableA.hasOne(TableB, {
  sourceKey: 'someNonPrimaryKeyColumnOnTableA',
  foreignKey: 'matchingColumnOnTableB'
});

Please note, the column someNonPrimaryKeyColumnOnTableA must have unique set to true in the model definition.

You can read more about it here: https://sequelize.org/master/manual/assocs.html


问:
How to run Pentaho console on linux from localhost:port/pentaho?
I am trying to use pentaho which I downloaded from sourceforge (pentaho files). I run the schema-workbench shell correctly and a window opens with the interface, but I still haven't been able to connect to the admin console  on http://localhost:8080/pentaho.
Any ideas on which this doesn't seem to work for me?
Best regards</p>

答:
Pentaho by default will start PuC Pentaho USer Console on http://localhost:8080/pentaho once server is up and running. For getting the data integration i.e Spoon interface go to
For Windows : Pentaho install directory>> design-tools>> data-integration>>spoon.bat
For Linux/Mac:Pentaho install directory>> design-tools>> data-integration>>spoon.sh

I hope this helps.


问:
Multi-Threading and saving function results
I wrote a script that goes through API and collect data,
it was slow and i've tried to do multi-threading and ended up with this:

```<code>import requests
from collections import defaultdict
import csv
import time
from queue import Queue
from threading import Thread

def dmg(ID):
    server='countryball'
    my_dict = defaultdict(lambda: {'dmg':0})
    time.sleep(0.3)
    r = requests.get('https://'+server+'.e-sim.org/apiFights.html?battleId='+str(ID)).json()
    for hit in r:
        try:my_dict[hit['citizenId']]['dmg'] += hit['damage']
        except:my_dict[hit['citizenId']]['dmg'] += hit['damage']
    my_dict={k:dict(v) for k,v in my_dict.items()}
    if my_dict:
        with open('dmg.csv','a',newline='') as f:
            writer = csv.writer(f)
            writer.writerow([my_dict])

battle_ids=list(range(10317,10900))
NUM_WORKERS = 6
task_queue = Queue()
def worker():
    while True:
        ID = task_queue.get()
        time.sleep(0.5)
        dmg(ID)
        task_queue.task_done()
threads = [Thread(target=worker) for _ in range(NUM_WORKERS)]
[task_queue.put(item) for item in battle_ids]
[thread.start() for thread in threads]
task_queue.join()
</code>```

a small part of output is such as below:

```<code>"{2174: {'dmg': 377156}, 469: {'dmg': 785358}, 535: {'dmg': 63542}}"
{226: {'dmg': 688205}}
{1330: {'dmg': 59370}}
"{37068: {'dmg': 184975}, 1164: {'dmg': 239162}, 1244: {'dmg': 734525}}"
"{1852: {'dmg': 306785}, 12218: {'dmg': 112228}, 9481: {'dmg': 22745}}"
{933: {'dmg': 21747}}
{2702: {'dmg': 375177}}
{1796: {'dmg': 21845}}
"{36683: {'dmg': 241816}, 41129: {'dmg': 200211}, 303: {'dmg': 1601865}}"
"{1546: {'dmg': 434303}, 1158: {'dmg': 1138277}, 9834: {'dmg': 37585}, 1750: {'dmg': 347775}}"
{362: {'dmg': 880661}}
"{24132: {'dmg': 459637}, 7566: {'dmg': 100760}}"
{1049: {'dmg': 185024}}
</code>```

since there are multiple keys with different values and i have to sum up value of those keys,
this output is not valuable to me, hence i need help with 2 possible solutions,

how can i store output of dmg, which is my_dict in a list and sum up data and benefit from multi-threading(currently not possible with multi-threading .)

reading csv file,storing data in a list like this : data = [[key(ex:2174):value(ex:{'dmg': 377156})]]

-for the second part, i've tried multiple approaches but i cant read the dictionary part({'dmg': 377156}) as a dictionary, its always str.

If anyone is kind enough, help me with this, im new to coding...

答:
fixed my problem,

```<code>buffer=[]
def dmg(ID):
    my_dict = defaultdict(lambda: {'dmg':0})
    time.sleep(0.3)
    r = requests.get('https://'+server+'.e-sim.org/apiFights.html?battleId='+str(ID)).json()
    for hit in r:
        try:my_dict[hit['citizenId']]['dmg'] += hit['damage']
        except:my_dict[hit['citizenId']]['dmg'] += hit['damage']
    my_dict={k:dict(v) for k,v in my_dict.items()}
    if my_dict:
        buffer.append(my_dict)
</code>```

i've tried using other lists as a storage but it didnt work, for some reason, using buffer is allowed.

if anyone knows the reason, let me know please...

```<code>my_dict = defaultdict(lambda: {'dmg':0})
for item in buffer:
    a = item
    for k,v in a.items():
        my_dict[k]['dmg'] += v['dmg']
my_dict={k:dict(v) for k,v in my_dict.items()}
</code>```

Body:
I wrote a script that goes through API and collect data,
it was slow and i've tried to do multi-threading and ended up with this:

import requests
from collections import defaultdict
import csv
import time
from queue import Queue
from threading import Thread

def dmg(ID):
    server='countryball'
    my_dict = defaultdict(lambda: {'dmg':0})
    time.sleep(0.3)
    r = requests.get('https://'+server+'.e-sim.org/apiFights.html?battleId='+str(ID)).json()
    for hit in r:
        try:my_dict[hit['citizenId']]['dmg'] += hit['damage']
        except:my_dict[hit['citizenId']]['dmg'] += hit['damage']
    my_dict={k:dict(v) for k,v in my_dict.items()}
    if my_dict:
        with open('dmg.csv','a',newline='') as f:
            writer = csv.writer(f)
            writer.writerow([my_dict])

battle_ids=list(range(10317,10900))
NUM_WORKERS = 6
task_queue = Queue()
def worker():
    while True:
        ID = task_queue.get()
        time.sleep(0.5)
        dmg(ID)
        task_queue.task_done()
threads = [Thread(target=worker) for _ in range(NUM_WORKERS)]
[task_queue.put(item) for item in battle_ids]
[thread.start() for thread in threads]
task_queue.join()

a small part of output is such as below:

"{2174: {'dmg': 377156}, 469: {'dmg': 785358}, 535: {'dmg': 63542}}"
{226: {'dmg': 688205}}
{1330: {'dmg': 59370}}
"{37068: {'dmg': 184975}, 1164: {'dmg': 239162}, 1244: {'dmg': 734525}}"
"{1852: {'dmg': 306785}, 12218: {'dmg': 112228}, 9481: {'dmg': 22745}}"
{933: {'dmg': 21747}}
{2702: {'dmg': 375177}}
{1796: {'dmg': 21845}}
"{36683: {'dmg': 241816}, 41129: {'dmg': 200211}, 303: {'dmg': 1601865}}"
"{1546: {'dmg': 434303}, 1158: {'dmg': 1138277}, 9834: {'dmg': 37585}, 1750: {'dmg': 347775}}"
{362: {'dmg': 880661}}
"{24132: {'dmg': 459637}, 7566: {'dmg': 100760}}"
{1049: {'dmg': 185024}}

since there are multiple keys with different values and i have to sum up value of those keys,
this output is not valuable to me, hence i need help with 2 possible solutions,

how can i store output of dmg, which is my_dict in a list and sum up data and benefit from multi-threading(currently not possible with multi-threading .)

reading csv file,storing data in a list like this : data = [[key(ex:2174):value(ex:{'dmg': 377156})]]

-for the second part, i've tried multiple approaches but i cant read the dictionary part({'dmg': 377156}) as a dictionary, its always str.

If anyone is kind enough, help me with this, im new to coding...

Body:
fixed my problem,

buffer=[]
def dmg(ID):
    my_dict = defaultdict(lambda: {'dmg':0})
    time.sleep(0.3)
    r = requests.get('https://'+server+'.e-sim.org/apiFights.html?battleId='+str(ID)).json()
    for hit in r:
        try:my_dict[hit['citizenId']]['dmg'] += hit['damage']
        except:my_dict[hit['citizenId']]['dmg'] += hit['damage']
    my_dict={k:dict(v) for k,v in my_dict.items()}
    if my_dict:
        buffer.append(my_dict)

i've tried using other lists as a storage but it didnt work, for some reason, using buffer is allowed.

if anyone knows the reason, let me know please...

my_dict = defaultdict(lambda: {'dmg':0})
for item in buffer:
    a = item
    for k,v in a.items():
        my_dict[k]['dmg'] += v['dmg']
my_dict={k:dict(v) for k,v in my_dict.items()}


问:
Django: How to add static files in shared templates?
I have shared templates that doesn't belongs to any particular app. Here's my project tree:

```<code>.
├── root_app
│   ├── asgi.py
│   ├── forms.py
│   ├── __init__.py
│   ├── __pycache__
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
├── db.sqlite3
├── another_app
│   ├── admin.py
│   ├── api_services.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── __pycache__
│   ├── templates
│   ├── tests.py
│   ├── urls.py
│   ├── utils.py
│   └── views.py
├── manage.py
├── Pipfile
├── Pipfile.lock
├── README.md
├── requirements.txt
├── static
│   └── css
│       └── styles.css
└── templates
    ├── base.html
    └── home.html
</code>```

In my settings file I have:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

INSTALLED_APPS = [
    ...
    ...
    'django.contrib.staticfiles',
]
STATIC_URL = '/static/'

STATIC_DIR = [os.path.join(BASE_DIR, 'static')]
```

<p>In my base.html template, I'm trying to call the styles.css from static/css/styles.css this way:</p>

<pre class="lang-py prettyprint-override"><code>{% load static %}
<link rel="stylesheet" type="text/css" href="{% static "css/styles.css" %}" />
</code>```

But the server responds with a not found:

"GET /static/css/styles.css HTTP/1.1" 404
```

What I'm doing wrong?

答:
Seems like you're in development, so the DEBUG is True.

STATICFILES_DIRS is the list of folders where Django will search for additional static files aside from the static folder of each app installed.

Try to insert this list to your settings:

STATICFILES_DIRS = ['/home/path/to/your/static/',]
```

Body:
I have shared templates that doesn't belongs to any particular app. Here's my project tree:

.
├── root_app
│   ├── asgi.py
│   ├── forms.py
│   ├── __init__.py
│   ├── __pycache__
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
├── db.sqlite3
├── another_app
│   ├── admin.py
│   ├── api_services.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── __pycache__
│   ├── templates
│   ├── tests.py
│   ├── urls.py
│   ├── utils.py
│   └── views.py
├── manage.py
├── Pipfile
├── Pipfile.lock
├── README.md
├── requirements.txt
├── static
│   └── css
│       └── styles.css
└── templates
    ├── base.html
    └── home.html

In my settings file I have:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

INSTALLED_APPS = [
    ...
    ...
    'django.contrib.staticfiles',
]
STATIC_URL = '/static/'

STATIC_DIR = [os.path.join(BASE_DIR, 'static')]

In my base.html template, I'm trying to call the styles.css from static/css/styles.css this way:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static "css/styles.css" %}" />

But the server responds with a not found:

"GET /static/css/styles.css HTTP/1.1" 404

What I'm doing wrong?


问:
pygame world generation algorithm
I am working on a game for a school project using pygame and was struggling to make a world generation algorithm I was wondering if anyone could help me. for anyone wondering the game is a rip off version of the game Terreira if that helps.</p>

答:
One way of making a map in pygame is to do it using tiles, but I find that it to be massive effort, since you first have to learn how to use it. Another more common way to do it is to create a 2-D list representing your x and y for every point in your map, depending on how you scale the map.First lets talk about the map creation:

```<code># lets say 0 represents empty space
# 1 represents a block image u might have for example dirt image or a wall

    layout = [ [1, 0, 2],
               [0, 1, 1] ]
</code>```

Then, to actually draw the map you can loop over this list, first every  layer in the list, then every element in that layer, like this:

```<code> y = 0
    for layer in layout:
        x = 0
        for element in layer:
           if element == 1:
               D.blit(your image, (x *  block_length, y * block_height))
           if element == 2:
               D.blit(your image, (x *  other_block_length, y * other_block_height))
           else: # else do nothing, which  leaves the area empty
               pass
       x += 1 # add 1 to x every inner loop
     y += 1 # add 1 to y value every outer loop
</code>```

Here is an example from one of my games

```<code>class Game_map:
    def __init__(self):
        self.land = pygame.image.load(r"C:\Users\pro-gramar\OneDrive\Documents\A level python codes\final game\land.png").convert()
        self.height = 200
        self.width = 200
        self.land = pygame.transform.scale(self.land, (170 , 200))
        self.land.set_colorkey((0, 0, 0))

        self.map_width = 6000
        self.map_height = 2000

        # 0 = emepty
        # 1 = land

        self.layout = [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0 ,0 ,0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ,0 ,0 ,0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0 ],
                              [ 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]]

    def draw(self):
        y = 0
        for layer in self.layout:
            x = 0
            for land in layer:
                if land == 1:
                    D.blit(self.land, (x * 160 ,  y * 200 ))
                if land == 0:
                    pass

                x += 1
            y += 1
</code>```

Title: pygame world generation algorithm

Body:
One way of making a map in pygame is to do it using tiles, but I find that it to be massive effort, since you first have to learn how to use it. Another more common way to do it is to create a 2-D list representing your x and y for every point in your map, depending on how you scale the map.First lets talk about the map creation:

# lets say 0 represents empty space
# 1 represents a block image u might have for example dirt image or a wall

    layout = [ [1, 0, 2],
               [0, 1, 1] ]

Then, to actually draw the map you can loop over this list, first every  layer in the list, then every element in that layer, like this:

 y = 0
    for layer in layout:
        x = 0
        for element in layer:
           if element == 1:
               D.blit(your image, (x *  block_length, y * block_height))
           if element == 2:
               D.blit(your image, (x *  other_block_length, y * other_block_height))
           else: # else do nothing, which  leaves the area empty
               pass
       x += 1 # add 1 to x every inner loop
     y += 1 # add 1 to y value every outer loop

Here is an example from one of my games

class Game_map:
    def __init__(self):
        self.land = pygame.image.load(r"C:\Users\pro-gramar\OneDrive\Documents\A level python codes\final game\land.png").convert()
        self.height = 200
        self.width = 200
        self.land = pygame.transform.scale(self.land, (170 , 200))
        self.land.set_colorkey((0, 0, 0))

        self.map_width = 6000
        self.map_height = 2000

        # 0 = emepty
        # 1 = land

        self.layout = [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0 ,0 ,0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ,0 ,0 ,0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0 ],
                              [ 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
                              [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]]

    def draw(self):
        y = 0
        for layer in self.layout:
            x = 0
            for land in layer:
                if land == 1:
                    D.blit(self.land, (x * 160 ,  y * 200 ))
                if land == 0:
                    pass

                x += 1
            y += 1


问:
Multi-Author Google Analytics (Combining PHP Variable from DB to JS)
I am trying to let authors on my site retrieve their own Google analytics data by setting up a channel in Analytics and submitting it via their profile. I ahve been trying plenty of ways to do this, but here is what I have so far.

    window.google_analytics_uacct = "UA-xxxxxxx-xx";

```<code><script type="text/javascript">//<![CDATA[

var _gaq = _gaq || [];
_gaq.push(['_setAccount','UA-xxxxxxx-xx']);
_gaq.push(['_trackPageview']);
_gaq.push(['_setAccount', 'UA-xxxxxxx-xx']);
_gaq.push(['_trackPageview']);
(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//]]></script>
</code>```

I was trying to incorporate the following PHP around the second account data is pushed to.

```<code>    <?php if ( get_the_author_meta( 'analytics' ) ) { ?>
        <?php the_author_meta( 'analytics' ); ?>
    <?php } ?>
</code>```

I was using the if statement around the second set of

```<code>_gaq.push(['_setAccount', 'UA-xxxxxxx-xx']);
_gaq.push(['_trackPageview']);
</code>```

With the view of only displaying this set if the site author has submitted their Analytics ID.

Unfortunately just getting the value from the database in itself is causing me a lot of problems! Any help would be appreciated :)

Kind Regards

Oli

答:
-Try this one. Author meta 'analytics' must be like UA-1234567-12</p>

```<code><script type="text/javascript">//<![CDATA[

var _gaq = _gaq || [];
_gaq.push(['_setAccount','UA-xxxxxxx-xx']);

<?php if($ganal = get_the_author_meta('analytics')): ?>
_gaq.push(['_setAccount', '<?php echo $ganal; ?>']);
<?php endif; ?>

_gaq.push(['_trackPageview']);
(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//]]></script>
</code>```

Body:
I am trying to let authors on my site retrieve their own Google analytics data by setting up a channel in Analytics and submitting it via their profile. I ahve been trying plenty of ways to do this, but here is what I have so far.

    window.google_analytics_uacct = "UA-xxxxxxx-xx";

I was trying to incorporate the following PHP around the second account data is pushed to.

    <?php if ( get_the_author_meta( 'analytics' ) ) { ?>
        <?php the_author_meta( 'analytics' ); ?>
    <?php } ?>

I was using the if statement around the second set of

_gaq.push(['_setAccount', 'UA-xxxxxxx-xx']);
_gaq.push(['_trackPageview']);

With the view of only displaying this set if the site author has submitted their Analytics ID.

Unfortunately just getting the value from the database in itself is causing me a lot of problems! Any help would be appreciated :)

Kind Regards

Oli

Body:
-Try this one. Author meta 'analytics' must be like UA-1234567-12

<script type="text/javascript">//<![CDATA[

var _gaq = _gaq || [];
_gaq.push(['_setAccount','UA-xxxxxxx-xx']);

<?php if($ganal = get_the_author_meta('analytics')): ?>
_gaq.push(['_setAccount', '<?php echo $ganal; ?>']);
<?php endif; ?>

_gaq.push(['_trackPageview']);
(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//]]></script>