问:
will_paginate mistaking a relation for an array
Rails 5 application with will_paginate has the following log entry:

```<code>  Usercontent Load (0.7ms)  SELECT "usercontents".* FROM "usercontents" WHERE (id IN (171,172,33,34,35,156,173,144,78,81,88,90,93,96,36,37,38,48,87,89,94,39,175,176) AND  contenttype_id = 1)
   ↳ app/controllers/travels_controller.rb:45
</code>```

and the controller action specifies

```<code>@points = Usercontent.where('id IN (?) AND  contenttype_id = ?', @all_valid_usercontents, 1).paginate(page: params[:page], per_page: 18)
</code>```

if I run in the console that line as

```<code>@points = Usercontent.where('id IN (?) AND  contenttype_id = ?', [171,172,33,34,35,156,173,144,78,81,88,90,93,96,36,37,38,48,87,89,94,39,175,176], 1).paginate(page: 1, per_page: 18)
</code>```

then

```<code>> @points.class
=> Usercontent::ActiveRecord_Relation
</code>```

Inserting in the controller debugging points:

```<code>Rails.logger.info @a_points.class
Rails.logger.info @points.class
</code>```

returns

```<code>Usercontent::ActiveRecord_Relation
Usercontent::ActiveRecord_Relation
</code>```

View

```<code><div id='yield_pcontent'>
  <%= render 'points' %>
</div>
<div id="infinite-scrolling">
  <%= will_paginate %>
</div>
</code>```

partial _points.html.erb

```<code><div id=points class='tableize'>
  <%= render partial: 'point', collection: @points %>
</div>
</code>```

How can will_paginate thus recognize helper <%= will_paginate %> as an array

```<code>undefined method `total_pages' for #<Array:0x00007f9a27d47718>
</code>```

note: adding require 'will_paginate/array' does not change this behaviour

update

```<code>activerecord (5.2.3) lib/active_record/relation/delegation.rb:125:in `method_missing'
will_paginate (3.1.7) lib/will_paginate/view_helpers.rb:73:in `will_paginate'
will_paginate (3.1.7) lib/will_paginate/view_helpers/action_view.rb:33:in `will_paginate'
app/views/travels/_region_points.html.erb:5:in `_app_views_travels__region_points_html_erb__2375899185333558082_70150028432340'
actionview (5.2.3) lib/action_view/template.rb:159:in `block in render'
activesupport (5.2.3) lib/active_support/notifications.rb:170:in `instrument'
actionview (5.2.3) lib/action_view/template.rb:354:in `instrument_render_template'
actionview (5.2.3) lib/action_view/template.rb:157:in `render'
actionview (5.2.3) lib/action_view/renderer/partial_renderer.rb:344:in `block in render_partial'
actionview (5.2.3) lib/action_view/renderer/abstract_renderer.rb:44:in `block in instrument'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `block in instrument'
activesupport (5.2.3) lib/active_support/notifications/instrumenter.rb:23:in `instrument'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `instrument'
actionview (5.2.3) lib/action_view/renderer/abstract_renderer.rb:43:in `instrument'
actionview (5.2.3) lib/action_view/renderer/partial_renderer.rb:333:in `render_partial'
actionview (5.2.3) lib/action_view/renderer/partial_renderer.rb:312:in `render'
actionview (5.2.3) lib/action_view/renderer/renderer.rb:49:in `render_partial'
actionview (5.2.3) lib/action_view/helpers/rendering_helper.rb:36:in `render'
app/views/travels/cc.html.erb:33:in `_app_views_travels_cc_html_erb___2132430413937746159_70149902220280'
actionview (5.2.3) lib/action_view/template.rb:159:in `block in render'
activesupport (5.2.3) lib/active_support/notifications.rb:170:in `instrument'
actionview (5.2.3) lib/action_view/template.rb:354:in `instrument_render_template'
actionview (5.2.3) lib/action_view/template.rb:157:in `render'
actionview (5.2.3) lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template'
actionview (5.2.3) lib/action_view/renderer/abstract_renderer.rb:44:in `block in instrument'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `block in instrument'
activesupport (5.2.3) lib/active_support/notifications/instrumenter.rb:23:in `instrument'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `instrument'
actionview (5.2.3) lib/action_view/renderer/abstract_renderer.rb:43:in `instrument'
actionview (5.2.3) lib/action_view/renderer/template_renderer.rb:53:in `block in render_template'
actionview (5.2.3) lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'
actionview (5.2.3) lib/action_view/renderer/template_renderer.rb:52:in `render_template'
actionview (5.2.3) lib/action_view/renderer/template_renderer.rb:16:in `render'
actionview (5.2.3) lib/action_view/renderer/renderer.rb:44:in `render_template'
actionview (5.2.3) lib/action_view/renderer/renderer.rb:25:in `render'
actionview (5.2.3) lib/action_view/rendering.rb:103:in `_render_template'
actionpack (5.2.3) lib/action_controller/metal/streaming.rb:219:in `_render_template'
actionview (5.2.3) lib/action_view/rendering.rb:84:in `render_to_body'
actionpack (5.2.3) lib/action_controller/metal/rendering.rb:52:in `render_to_body'
actionpack (5.2.3) lib/action_controller/metal/renderers.rb:142:in `render_to_body'
actionpack (5.2.3) lib/abstract_controller/rendering.rb:25:in `render'
actionpack (5.2.3) lib/action_controller/metal/rendering.rb:36:in `render'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:46:in `block (2 levels) in render'
activesupport (5.2.3) lib/active_support/core_ext/benchmark.rb:14:in `block in ms'
/home/jerdvo/.rbenv/versions/2.6.1/lib/ruby/2.6.0/benchmark.rb:308:in `realtime'
activesupport (5.2.3) lib/active_support/core_ext/benchmark.rb:14:in `ms'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:46:in `block in render'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
activerecord (5.2.3) lib/active_record/railties/controller_runtime.rb:31:in `cleanup_view_runtime'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:45:in `render'
wicked_pdf (1.2.2) lib/wicked_pdf/pdf_helper.rb:46:in `call'
wicked_pdf (1.2.2) lib/wicked_pdf/pdf_helper.rb:46:in `render_with_wicked_pdf'
wicked_pdf (1.2.2) lib/wicked_pdf/pdf_helper.rb:30:in `render'
app/controllers/travels_controller.rb:59:in `cc'
actionpack (5.2.3) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
actionpack (5.2.3) lib/abstract_controller/base.rb:194:in `process_action'
actionpack (5.2.3) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (5.2.3) lib/abstract_controller/callbacks.rb:42:in `block in process_action'
activesupport (5.2.3) lib/active_support/callbacks.rb:132:in `run_callbacks'
actionpack (5.2.3) lib/abstract_controller/callbacks.rb:41:in `process_action'
actionpack (5.2.3) lib/action_controller/metal/rescue.rb:22:in `process_action'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:34:in `block in process_action'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `block in instrument'
activesupport (5.2.3) lib/active_support/notifications/instrumenter.rb:23:in `instrument'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `instrument'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:32:in `process_action'
actionpack (5.2.3) lib/action_controller/metal/params_wrapper.rb:256:in `process_action'
activerecord (5.2.3) lib/active_record/railties/controller_runtime.rb:24:in `process_action'
actionpack (5.2.3) lib/abstract_controller/base.rb:134:in `process'
actionview (5.2.3) lib/action_view/rendering.rb:32:in `process'
actionpack (5.2.3) lib/action_controller/metal.rb:191:in `dispatch'
actionpack (5.2.3) lib/action_controller/metal.rb:252:in `dispatch'
actionpack (5.2.3) lib/action_dispatch/routing/route_set.rb:52:in `dispatch'
actionpack (5.2.3) lib/action_dispatch/routing/route_set.rb:34:in `serve'
actionpack (5.2.3) lib/action_dispatch/journey/router.rb:52:in `block in serve'
actionpack (5.2.3) lib/action_dispatch/journey/router.rb:35:in `each'
actionpack (5.2.3) lib/action_dispatch/journey/router.rb:35:in `serve'
actionpack (5.2.3) lib/action_dispatch/routing/route_set.rb:840:in `call'
warden (1.2.8) lib/warden/manager.rb:36:in `block in call'
warden (1.2.8) lib/warden/manager.rb:34:in `catch'
warden (1.2.8) lib/warden/manager.rb:34:in `call'
rack (2.0.7) lib/rack/tempfile_reaper.rb:15:in `call'
rack (2.0.7) lib/rack/etag.rb:25:in `call'
rack (2.0.7) lib/rack/conditional_get.rb:25:in `call'
rack (2.0.7) lib/rack/head.rb:12:in `call'
actionpack (5.2.3) lib/action_dispatch/http/content_security_policy.rb:18:in `call'
rack (2.0.7) lib/rack/session/abstract/id.rb:232:in `context'
rack (2.0.7) lib/rack/session/abstract/id.rb:226:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/cookies.rb:670:in `call'
activerecord (5.2.3) lib/active_record/migration.rb:559:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
activesupport (5.2.3) lib/active_support/callbacks.rb:98:in `run_callbacks'
actionpack (5.2.3) lib/action_dispatch/middleware/callbacks.rb:26:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:61:in `call'
web-console (3.7.0) lib/web_console/middleware.rb:135:in `call_app'
web-console (3.7.0) lib/web_console/middleware.rb:22:in `block 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:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (5.2.3) lib/rails/rack/logger.rb:38:in `call_app'
railties (5.2.3) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:71:in `block in tagged'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:71:in `tagged'
railties (5.2.3) lib/rails/rack/logger.rb:26:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
request_store (1.4.1) lib/request_store/middleware.rb:19:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.0.7) lib/rack/method_override.rb:22:in `call'
rack (2.0.7) lib/rack/runtime.rb:22:in `call'
activesupport (5.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/static.rb:127:in `call'
rack (2.0.7) lib/rack/sendfile.rb:111:in `call'
railties (5.2.3) lib/rails/engine.rb:524:in `call'
/usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:97:in `process_request'
/usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:149:in `accept_and_process_next_request'
/usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:110:in `main_loop'
/usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler.rb:415:in `block (3 levels) in start_threads'
/usr/lib/ruby/vendor_ruby/phusion_passenger/utils.rb:113:in `block in create_thread_and_abort_on_exception'
</code>```

Update 2
based on a suggestion, two behaviours are being observed:

```<code><%= will_paginate %>  => undefined method `total_pages' for #<Array:0x00007f9a261e2540>
<%= will_paginate @points %> => undefined method `total_pages' for #<Usercontent::ActiveRecord_Relation:0x00007f9a26d07ab0>
</code>```

答:
He is waiting for an Object, not an Array. I share my solution, adapt it to your case.

def render_partial_resource(resources)
    if resources.present?
      if resources.respond_to?(:model_name)
        folder = resources.model_name.name.pluralize.downcase
        partial = resources.model_name.name.downcase
      else
        folder = resources.object.name.pluralize.downcase
        partial = resources.object.name.downcase
      end

      resources.map do |resource|
        render partial:"#{folder}/#{partial}", locals:{"#{partial}": resource}
      end.join(" ").html_safe
    end
  end
```

Body:
Rails 5 application with will_paginate has the following log entry:

  Usercontent Load (0.7ms)  SELECT "usercontents".* FROM "usercontents" WHERE (id IN (171,172,33,34,35,156,173,144,78,81,88,90,93,96,36,37,38,48,87,89,94,39,175,176) AND  contenttype_id = 1)
   ↳ app/controllers/travels_controller.rb:45

and the controller action specifies

@points = Usercontent.where('id IN (?) AND  contenttype_id = ?', @all_valid_usercontents, 1).paginate(page: params[:page], per_page: 18)

if I run in the console that line as

@points = Usercontent.where('id IN (?) AND  contenttype_id = ?', [171,172,33,34,35,156,173,144,78,81,88,90,93,96,36,37,38,48,87,89,94,39,175,176], 1).paginate(page: 1, per_page: 18)

then

> @points.class
=> Usercontent::ActiveRecord_Relation

Inserting in the controller debugging points:

Rails.logger.info @a_points.class
Rails.logger.info @points.class

returns

Usercontent::ActiveRecord_Relation
Usercontent::ActiveRecord_Relation

View

  <%= render 'points' %>

  <%= will_paginate %>

partial _points.html.erb

  <%= render partial: 'point', collection: @points %>

How can will_paginate thus recognize helper <%= will_paginate %> as an array

undefined method `total_pages' for #<Array:0x00007f9a27d47718>

note: adding require 'will_paginate/array' does not change this behaviour

update

activerecord (5.2.3) lib/active_record/relation/delegation.rb:125:in `method_missing'
will_paginate (3.1.7) lib/will_paginate/view_helpers.rb:73:in `will_paginate'
will_paginate (3.1.7) lib/will_paginate/view_helpers/action_view.rb:33:in `will_paginate'
app/views/travels/_region_points.html.erb:5:in `_app_views_travels__region_points_html_erb__2375899185333558082_70150028432340'
actionview (5.2.3) lib/action_view/template.rb:159:in `block in render'
activesupport (5.2.3) lib/active_support/notifications.rb:170:in `instrument'
actionview (5.2.3) lib/action_view/template.rb:354:in `instrument_render_template'
actionview (5.2.3) lib/action_view/template.rb:157:in `render'
actionview (5.2.3) lib/action_view/renderer/partial_renderer.rb:344:in `block in render_partial'
actionview (5.2.3) lib/action_view/renderer/abstract_renderer.rb:44:in `block in instrument'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `block in instrument'
activesupport (5.2.3) lib/active_support/notifications/instrumenter.rb:23:in `instrument'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `instrument'
actionview (5.2.3) lib/action_view/renderer/abstract_renderer.rb:43:in `instrument'
actionview (5.2.3) lib/action_view/renderer/partial_renderer.rb:333:in `render_partial'
actionview (5.2.3) lib/action_view/renderer/partial_renderer.rb:312:in `render'
actionview (5.2.3) lib/action_view/renderer/renderer.rb:49:in `render_partial'
actionview (5.2.3) lib/action_view/helpers/rendering_helper.rb:36:in `render'
app/views/travels/cc.html.erb:33:in `_app_views_travels_cc_html_erb___2132430413937746159_70149902220280'
actionview (5.2.3) lib/action_view/template.rb:159:in `block in render'
activesupport (5.2.3) lib/active_support/notifications.rb:170:in `instrument'
actionview (5.2.3) lib/action_view/template.rb:354:in `instrument_render_template'
actionview (5.2.3) lib/action_view/template.rb:157:in `render'
actionview (5.2.3) lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template'
actionview (5.2.3) lib/action_view/renderer/abstract_renderer.rb:44:in `block in instrument'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `block in instrument'
activesupport (5.2.3) lib/active_support/notifications/instrumenter.rb:23:in `instrument'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `instrument'
actionview (5.2.3) lib/action_view/renderer/abstract_renderer.rb:43:in `instrument'
actionview (5.2.3) lib/action_view/renderer/template_renderer.rb:53:in `block in render_template'
actionview (5.2.3) lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'
actionview (5.2.3) lib/action_view/renderer/template_renderer.rb:52:in `render_template'
actionview (5.2.3) lib/action_view/renderer/template_renderer.rb:16:in `render'
actionview (5.2.3) lib/action_view/renderer/renderer.rb:44:in `render_template'
actionview (5.2.3) lib/action_view/renderer/renderer.rb:25:in `render'
actionview (5.2.3) lib/action_view/rendering.rb:103:in `_render_template'
actionpack (5.2.3) lib/action_controller/metal/streaming.rb:219:in `_render_template'
actionview (5.2.3) lib/action_view/rendering.rb:84:in `render_to_body'
actionpack (5.2.3) lib/action_controller/metal/rendering.rb:52:in `render_to_body'
actionpack (5.2.3) lib/action_controller/metal/renderers.rb:142:in `render_to_body'
actionpack (5.2.3) lib/abstract_controller/rendering.rb:25:in `render'
actionpack (5.2.3) lib/action_controller/metal/rendering.rb:36:in `render'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:46:in `block (2 levels) in render'
activesupport (5.2.3) lib/active_support/core_ext/benchmark.rb:14:in `block in ms'
/home/jerdvo/.rbenv/versions/2.6.1/lib/ruby/2.6.0/benchmark.rb:308:in `realtime'
activesupport (5.2.3) lib/active_support/core_ext/benchmark.rb:14:in `ms'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:46:in `block in render'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
activerecord (5.2.3) lib/active_record/railties/controller_runtime.rb:31:in `cleanup_view_runtime'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:45:in `render'
wicked_pdf (1.2.2) lib/wicked_pdf/pdf_helper.rb:46:in `call'
wicked_pdf (1.2.2) lib/wicked_pdf/pdf_helper.rb:46:in `render_with_wicked_pdf'
wicked_pdf (1.2.2) lib/wicked_pdf/pdf_helper.rb:30:in `render'
app/controllers/travels_controller.rb:59:in `cc'
actionpack (5.2.3) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
actionpack (5.2.3) lib/abstract_controller/base.rb:194:in `process_action'
actionpack (5.2.3) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (5.2.3) lib/abstract_controller/callbacks.rb:42:in `block in process_action'
activesupport (5.2.3) lib/active_support/callbacks.rb:132:in `run_callbacks'
actionpack (5.2.3) lib/abstract_controller/callbacks.rb:41:in `process_action'
actionpack (5.2.3) lib/action_controller/metal/rescue.rb:22:in `process_action'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:34:in `block in process_action'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `block in instrument'
activesupport (5.2.3) lib/active_support/notifications/instrumenter.rb:23:in `instrument'
activesupport (5.2.3) lib/active_support/notifications.rb:168:in `instrument'
actionpack (5.2.3) lib/action_controller/metal/instrumentation.rb:32:in `process_action'
actionpack (5.2.3) lib/action_controller/metal/params_wrapper.rb:256:in `process_action'
activerecord (5.2.3) lib/active_record/railties/controller_runtime.rb:24:in `process_action'
actionpack (5.2.3) lib/abstract_controller/base.rb:134:in `process'
actionview (5.2.3) lib/action_view/rendering.rb:32:in `process'
actionpack (5.2.3) lib/action_controller/metal.rb:191:in `dispatch'
actionpack (5.2.3) lib/action_controller/metal.rb:252:in `dispatch'
actionpack (5.2.3) lib/action_dispatch/routing/route_set.rb:52:in `dispatch'
actionpack (5.2.3) lib/action_dispatch/routing/route_set.rb:34:in `serve'
actionpack (5.2.3) lib/action_dispatch/journey/router.rb:52:in `block in serve'
actionpack (5.2.3) lib/action_dispatch/journey/router.rb:35:in `each'
actionpack (5.2.3) lib/action_dispatch/journey/router.rb:35:in `serve'
actionpack (5.2.3) lib/action_dispatch/routing/route_set.rb:840:in `call'
warden (1.2.8) lib/warden/manager.rb:36:in `block in call'
warden (1.2.8) lib/warden/manager.rb:34:in `catch'
warden (1.2.8) lib/warden/manager.rb:34:in `call'
rack (2.0.7) lib/rack/tempfile_reaper.rb:15:in `call'
rack (2.0.7) lib/rack/etag.rb:25:in `call'
rack (2.0.7) lib/rack/conditional_get.rb:25:in `call'
rack (2.0.7) lib/rack/head.rb:12:in `call'
actionpack (5.2.3) lib/action_dispatch/http/content_security_policy.rb:18:in `call'
rack (2.0.7) lib/rack/session/abstract/id.rb:232:in `context'
rack (2.0.7) lib/rack/session/abstract/id.rb:226:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/cookies.rb:670:in `call'
activerecord (5.2.3) lib/active_record/migration.rb:559:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
activesupport (5.2.3) lib/active_support/callbacks.rb:98:in `run_callbacks'
actionpack (5.2.3) lib/action_dispatch/middleware/callbacks.rb:26:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:61:in `call'
web-console (3.7.0) lib/web_console/middleware.rb:135:in `call_app'
web-console (3.7.0) lib/web_console/middleware.rb:22:in `block 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:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (5.2.3) lib/rails/rack/logger.rb:38:in `call_app'
railties (5.2.3) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:71:in `block in tagged'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (5.2.3) lib/active_support/tagged_logging.rb:71:in `tagged'
railties (5.2.3) lib/rails/rack/logger.rb:26:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
request_store (1.4.1) lib/request_store/middleware.rb:19:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.0.7) lib/rack/method_override.rb:22:in `call'
rack (2.0.7) lib/rack/runtime.rb:22:in `call'
activesupport (5.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.3) lib/action_dispatch/middleware/static.rb:127:in `call'
rack (2.0.7) lib/rack/sendfile.rb:111:in `call'
railties (5.2.3) lib/rails/engine.rb:524:in `call'
/usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:97:in `process_request'
/usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:149:in `accept_and_process_next_request'
/usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:110:in `main_loop'
/usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler.rb:415:in `block (3 levels) in start_threads'
/usr/lib/ruby/vendor_ruby/phusion_passenger/utils.rb:113:in `block in create_thread_and_abort_on_exception'

Update 2
based on a suggestion, two behaviours are being observed:

<%= will_paginate %>  => undefined method `total_pages' for #<Array:0x00007f9a261e2540>
<%= will_paginate @points %> => undefined method `total_pages' for #<Usercontent::ActiveRecord_Relation:0x00007f9a26d07ab0>


来源: stackexchange

问:
GitLab Time Tracking does not show on issue sidebar for any issue
I am on “GitLab Enterprise Edition 11.6.0-ee” I believe. That is what GitLab>Help tells me on gitlab.com.

I put this into an issues comment field:

/estimate 1d 3h

/spend 2h

When I click Preview GitLab nicely shows:

Sets time estimate to 1d 3h. Adds 2h spent time.

But the “Time tracking” menu on the right hand side does not update and keeps showing:

Time tracking
No estimate or time spent

I am the project maintainer, so I should have the permissions to set these times?

I have tried with and without a due Due date, which shouldn’t influence estimate and time spent.

I have tried setting estimate and time spent for another team member. This team member can not see any estimate and time spent neither in the comments nor in the issue sidebar.

Please , where do I go wrong. Thanks for your help in advance.

答:
Check if the situation improves with GitLab 1.11 (May 2019)

View time tracking in sidebar of board view

Issue sidebars should be consistent in both board and issue views.

GitLab is moving towards this consistency by introducing time tracking into the issue sidebar view while on an issue board.

Simply navigate to an issue board, click on an issue to pull up the sidebar, and easily view time tracking information.

From issue 31331: see documentation.

ContentLicense: CC BY-SA 4.0


问:
why i am not getting a followed_by(followers) entry showing up on my page
i am making a twitter like clone(just to learn how things works in django)
so i am basically trying to  set up a many_to_many relationship.
i want to add the functionality of showing 'FOLLOWED_BY' and 'FOLLOWING' to a user profile but list of 'FOLLOWED_BY' is not showing on the page please someone help me!

in the models.py i have define two relationship

```<code>user = models.OneToOneField(settings.AUTH_USER_MODEL,
    on_delete=models.SET_NULL, related_name='profile', null=True,
    blank=True)

following = models.ManyToManyField(settings.AUTH_USER_MODEL,
     related_name='followed_by', blank=True)
</code>```

and in the user_detail.html i have the code for how a profile should look like

this is the models.py module:

```<code>from django.conf import settings
from django.db import models

# Create your models here.

class UserProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
               on_delete=models.SET_NULL, related_name='profile',
               null=True,
                blank=True)
    following = models.ManyToManyField(settings.AUTH_USER_MODEL,
                          related_name='followed_by', blank=True)

    def __str__(self):
        return str(self.following.all().count())
</code>```

below is the code for user_detail.html file:

```<code>{% extends "base.html" %}

{% block content %}
<div  class="row">
    <div class="col-sm-3 col-xs-12" style="background-color: yellow">
        <h1>{{ object.username }}</h1>
        <p>Followers: {{ object.followed_by.count }}</p>
    </div>
<div class="col-sm-9 col-xs-12">
    <h1>Tweets</h1>
    {% for tweet in object.tweet_set.all %}
    {{ tweet }}<br/>
    {% endfor %}
   <hr/>
    <h1>Following</h1>
    {% for user in object.profile.following.all %}
    <a href='/{{ user.username }}'>{{ user.username }}</a><br/>
    {% empty %}
    <h4>Not following any users</h4>
    {% endfor %}

   <hr/>
    <h1>Followed By</h1>
    {% for profile in object.profile.followed_by.all %}
    <a href='/{{ profile.user.username }}'>{{ profile.user.username }}</a><br/>
    {% empty %}
    <h4>Not followed by any user</h4>
    {% endfor %}

</div>
</code>```

```<code>{% endblock content %}
</code>```

for user profile i am getting the FOLLOWING field as i want but FOLLOWED_BY field is not showing how can i do that (what changes should i do in my code)??

答:
You defined a following field that points to the user model, not to a Profile. As a result a Profile has no followed_by relation, a User object has.

I think it probably is better to let following point to Profile, like:

```<code>class UserProfile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        related_name='profile',
        null=True,
        blank=True
    )
    following = models.ManyToManyField(
        <b>'self'</b>,
        related_name='followed_by',
        <b>symmetrical=False,</b>
        blank=True
    )

    def __str__(self):
        return str(self.following.all().count())</code>```

Then you can render this like:

```<code><div class="col-sm-3 col-xs-12" style="background-color: yellow">
    <h1>{{ object.username }}</h1>
    <p>Followers: {{ object.followed_by.count }}</p>
</div>
<div class="col-sm-9 col-xs-12">
    <h1>Tweets</h1>
    {% for tweet in object.tweet_set.all %}
        {{ tweet }}<br/>
    {% endfor %}
    <hr/>
    <h1>Following</h1>
    {% for <b>profile</b> in object.profile.following.all %}
        <a href='/{{ <b>profile.user.username</b> }}'>{{ <b>profile.user.username</b> }}</a><br/>
    {% empty %}
        <h4>Not following any users</h4>
    {% endfor %}

    <hr/>
    <h1>Followed By</h1>
    {% for profile in object.profile.followed_by.all %}
    <a href='/{{ <b>profile.user.username</b> }}'>{{ <b>profile.user.username</b> }}</a><br/>
    {% empty %}
       <h4>Not followed by any user</h4>
    {% endfor %}
</div></code>```

Your code has however some (serious) anti-patterns. The most important one is that you should not write business logic in the template. You should use the view for that. For example you can specify in the view a context like:

```<code>context = {
    'tweets': object.tweet_set.all()
    'followers': object.profile.following.<b>select_related('user')</b>.all()
    'followed_by': object.profile.followed_by.<b>select_related('user')</b>.all()
}</code>```

We here can also use a .select_related() [Django-doc] that will boost performance significantly, since now all the users are fetched in the same query.

You also better use the {% url ... %} template tag [Django-doc] to construct queries. So instead of writing:

```<code><a href="<s>/{{ profile.user.username }}</s>"></code>```

it is better to construct the query using a reverse lookup like:

```<code><a href="/<b>{% url 'profile_view' username=profile.user.username %}</b>"></code>```

Body:
i am making a twitter like clone(just to learn how things works in django)
so i am basically trying to  set up a many_to_many relationship.
i want to add the functionality of showing 'FOLLOWED_BY' and 'FOLLOWING' to a user profile but list of 'FOLLOWED_BY' is not showing on the page please someone help me!

in the models.py i have define two relationship

user = models.OneToOneField(settings.AUTH_USER_MODEL,
    on_delete=models.SET_NULL, related_name='profile', null=True,
    blank=True)

following = models.ManyToManyField(settings.AUTH_USER_MODEL,
     related_name='followed_by', blank=True)

and in the user_detail.html i have the code for how a profile should look like

this is the models.py module:

from django.conf import settings
from django.db import models

# Create your models here.

class UserProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
               on_delete=models.SET_NULL, related_name='profile',
               null=True,
                blank=True)
    following = models.ManyToManyField(settings.AUTH_USER_MODEL,
                          related_name='followed_by', blank=True)

    def __str__(self):
        return str(self.following.all().count())

below is the code for user_detail.html file:

{% extends "base.html" %}

{% block content %}

{{ object.username }}

Followers: {{ object.followed_by.count }}

Tweets

    {% for tweet in object.tweet_set.all %}
    {{ tweet }}

    {% endfor %}

Following

    {% for user in object.profile.following.all %}
    {{ user.username }}

    {% empty %}

Not following any users

    {% endfor %}

Followed By

    {% for profile in object.profile.followed_by.all %}
    {{ profile.user.username }}

    {% empty %}

Not followed by any user

    {% endfor %}

{% endblock content %}

for user profile i am getting the FOLLOWING field as i want but FOLLOWED_BY field is not showing how can i do that (what changes should i do in my code)??

Body:
You defined a following field that points to the user model, not to a Profile. As a result a Profile has no followed_by relation, a User object has.

I think it probably is better to let following point to Profile, like:

class UserProfile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        related_name='profile',
        null=True,
        blank=True
    )
    following = models.ManyToManyField(
        'self',
        related_name='followed_by',
        symmetrical=False,
        blank=True
    )

    def __str__(self):
        return str(self.following.all().count())

Then you can render this like:

<div class="col-sm-3 col-xs-12" style="background-color: yellow">
    <h1>{{ object.username }}</h1>
    <p>Followers: {{ object.followed_by.count }}</p>
</div>
<div class="col-sm-9 col-xs-12">
    <h1>Tweets</h1>
    {% for tweet in object.tweet_set.all %}
        {{ tweet }}<br/>
    {% endfor %}
    <hr/>
    <h1>Following</h1>
    {% for profile in object.profile.following.all %}
        <a href='/{{ profile.user.username }}'>{{ profile.user.username }}</a><br/>
    {% empty %}
        <h4>Not following any users</h4>
    {% endfor %}

    <hr/>
    <h1>Followed By</h1>
    {% for profile in object.profile.followed_by.all %}
    <a href='/{{ profile.user.username }}'>{{ profile.user.username }}</a><br/>
    {% empty %}
       <h4>Not followed by any user</h4>
    {% endfor %}
</div>

Your code has however some (serious) anti-patterns. The most important one is that you should not write business logic in the template. You should use the view for that. For example you can specify in the view a context like:

context = {
    'tweets': object.tweet_set.all()
    'followers': object.profile.following.select_related('user').all()
    'followed_by': object.profile.followed_by.select_related('user').all()
}

We here can also use a .select_related() [Django-doc] that will boost performance significantly, since now all the users are fetched in the same query.

You also better use the {% url ... %} template tag [Django-doc] to construct queries. So instead of writing:

<a href="<s>/{{ profile.user.username }}</s>">

it is better to construct the query using a reverse lookup like:

<a href="/{% url 'profile_view' username=profile.user.username %}">


问:
form multiselection - Cannot assign QuerySet, must be user instance
I'm attempting to build a basic Job/To Do List. In the Job create form, I'm trying to add the ability for the "author" to assign additional personnel to the job via a multiple select field from a list of registered users.

So far, it seems to work via the admin form. But when I do the same on the "Job create page" I get the following ValueError:

Cannot assign "QuerySet [CustomUser: testuser1, CustomUser: testuser2]": "Job.personnel" must be a "CustomUser" instance.

I'm not sure what I'm doing wrong in the view, I've seen similar topics but those options either didn't work or I just didn't understand the solution (I'm very new to Django/Python in general).

Any help, or suggestions on how this could be better implemented, would be greatly appreciated!

The Job Model from the job app

```<code>from django.conf import settings
from django.db import models
from user.models import CustomUser

class Job(models.Model):
    """A model for active jobs"""
    job_title = models.CharField(max_length=200)
    author = models.ForeignKey(
        CustomUser,
        null=True,
        on_delete=models.SET_NULL,
        related_name = 'authors'
        )
    personnel = models.ForeignKey(
        CustomUser,
        null=True,
        on_delete=models.SET_NULL,
        related_name = 'addition_personnel'
        )
    job_text = models.TextField()
    created_date = models.DateTimeField(auto_now_add=True)
    last_update = models.DateTimeField(null=True, auto_now=True)
    close_date = models.DateField(null=True, blank=True)
    #  Job status choices
    OPEN = 'Open'
    CLOSED = 'Closed'
    JOB_STATUS_CHOICES = (
        (OPEN, 'Open'),
        (CLOSED, 'Closed')
    )
    job_status = models.CharField(
        choices = JOB_STATUS_CHOICES,
        max_length = 10,
        null = True,
        blank = True,
        default = ''
    )

    def __str__(self):
        return self.job_title
</code>```

The CustomUser Model from the user app

```<code>from django.contrib.auth.models import AbstractUser

from django.db import models

class CustomUser(AbstractUser):
    """ custom user model """
    Position = models.CharField(max_length=100, null='', blank = True)

</code>```

The Form - uses ModelForm with ModelMultipleChoiceField

```<code>from django import forms
from .models import Job
from user.models import CustomUser

class JobCreateForm(forms.ModelForm):
    """Create new job form"""
    personnel_queryset = CustomUser.objects.all()
    personnel = forms.ModelMultipleChoiceField(
        queryset=personnel_queryset,
        widget=forms.CheckboxSelectMultiple(),
        required=False
        )

    class Meta:
        model = Job
        fields = [
            'job_title',
            'job_text',
            'close_date',
            'job_status',
            'personnel'
        ]

</code>```

and the View snippet

```<code>def job_create(request):
    """Job create form view"""
    if request.method == 'POST':
        form = JobCreateForm(request.POST)
        personnel = CustomUser.objects.all()
        if form.is_valid():
            new_job = form.save(commit=False)
            new_job.author = request.user
            new_job.personnel = personnel
            new_job.save()
            return redirect('job_detail',
                            job_details_id=new_job.pk)
    #  if a GET (or any other mehtod) blank form is created
    else:
        form = JobCreateForm()
    return render(request, 'jobs/job_create.html', {'form':form})
</code>```

答:
I think I've sussed it/ just got it working.

I had a rethink about the relationship between personnel and jobs and changed it from Froeign key to many to many, as Jobs can have many personnel assigned to it and personnel can be assigned to many jobs.

From Jobs model.

```<code>...

personnel = models.ManyToManyField(CustomUser, blank=True)
...

</code>```

Then using this Trouble saving Django form: 'UserProfile' object has no attribute 'save_m2m'
and the topic on model forms and the save method from
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method.

I changed the view to:

```<code>def job_create(request):
    """Job creation view with form"""
    #  if this is a POST request we need to process the form data
    if request.method == 'POST':
        #  create a form instance and populate it with data from the request:
        form = JobCreateForm(request.POST)
        #  check whether form data is valid:
        personnel = CustomUser.objects.all()
        if form.is_valid():
            #  process the data in the form.cleaned_data as required
            # personnel_inst = CustomUser.objectss
            new_job = form.save(commit=False)
            new_job.author = request.user
            new_job.save()
            form.save_m2m()
            return redirect('job_detail', job_details_id=new_job.pk)
    #  if a GET (or any other mehtod) blank form is created
    else:
        form = JobCreateForm()
    return render(request, 'jobs/job_create.html', {'form':form})

</code>```

Body:
I'm attempting to build a basic Job/To Do List. In the Job create form, I'm trying to add the ability for the "author" to assign additional personnel to the job via a multiple select field from a list of registered users.

So far, it seems to work via the admin form. But when I do the same on the "Job create page" I get the following ValueError:

Cannot assign "QuerySet [CustomUser: testuser1, CustomUser: testuser2]": "Job.personnel" must be a "CustomUser" instance.

I'm not sure what I'm doing wrong in the view, I've seen similar topics but those options either didn't work or I just didn't understand the solution (I'm very new to Django/Python in general).

Any help, or suggestions on how this could be better implemented, would be greatly appreciated!

The Job Model from the job app

from django.conf import settings
from django.db import models
from user.models import CustomUser

class Job(models.Model):
    """A model for active jobs"""
    job_title = models.CharField(max_length=200)
    author = models.ForeignKey(
        CustomUser,
        null=True,
        on_delete=models.SET_NULL,
        related_name = 'authors'
        )
    personnel = models.ForeignKey(
        CustomUser,
        null=True,
        on_delete=models.SET_NULL,
        related_name = 'addition_personnel'
        )
    job_text = models.TextField()
    created_date = models.DateTimeField(auto_now_add=True)
    last_update = models.DateTimeField(null=True, auto_now=True)
    close_date = models.DateField(null=True, blank=True)
    #  Job status choices
    OPEN = 'Open'
    CLOSED = 'Closed'
    JOB_STATUS_CHOICES = (
        (OPEN, 'Open'),
        (CLOSED, 'Closed')
    )
    job_status = models.CharField(
        choices = JOB_STATUS_CHOICES,
        max_length = 10,
        null = True,
        blank = True,
        default = ''
    )

    def __str__(self):
        return self.job_title

The CustomUser Model from the user app

from django.contrib.auth.models import AbstractUser

from django.db import models

class CustomUser(AbstractUser):
    """ custom user model """
    Position = models.CharField(max_length=100, null='', blank = True)

The Form - uses ModelForm with ModelMultipleChoiceField

from django import forms
from .models import Job
from user.models import CustomUser

class JobCreateForm(forms.ModelForm):
    """Create new job form"""
    personnel_queryset = CustomUser.objects.all()
    personnel = forms.ModelMultipleChoiceField(
        queryset=personnel_queryset,
        widget=forms.CheckboxSelectMultiple(),
        required=False
        )

    class Meta:
        model = Job
        fields = [
            'job_title',
            'job_text',
            'close_date',
            'job_status',
            'personnel'
        ]

and the View snippet

def job_create(request):
    """Job create form view"""
    if request.method == 'POST':
        form = JobCreateForm(request.POST)
        personnel = CustomUser.objects.all()
        if form.is_valid():
            new_job = form.save(commit=False)
            new_job.author = request.user
            new_job.personnel = personnel
            new_job.save()
            return redirect('job_detail',
                            job_details_id=new_job.pk)
    #  if a GET (or any other mehtod) blank form is created
    else:
        form = JobCreateForm()
    return render(request, 'jobs/job_create.html', {'form':form})

Body:
I think I've sussed it/ just got it working.

I had a rethink about the relationship between personnel and jobs and changed it from Froeign key to many to many, as Jobs can have many personnel assigned to it and personnel can be assigned to many jobs.

From Jobs model.

...

personnel = models.ManyToManyField(CustomUser, blank=True)
...

Then using this Trouble saving Django form: 'UserProfile' object has no attribute 'save_m2m'
and the topic on model forms and the save method from
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method.

I changed the view to:

def job_create(request):
    """Job creation view with form"""
    #  if this is a POST request we need to process the form data
    if request.method == 'POST':
        #  create a form instance and populate it with data from the request:
        form = JobCreateForm(request.POST)
        #  check whether form data is valid:
        personnel = CustomUser.objects.all()
        if form.is_valid():
            #  process the data in the form.cleaned_data as required
            # personnel_inst = CustomUser.objectss
            new_job = form.save(commit=False)
            new_job.author = request.user
            new_job.save()
            form.save_m2m()
            return redirect('job_detail', job_details_id=new_job.pk)
    #  if a GET (or any other mehtod) blank form is created
    else:
        form = JobCreateForm()
    return render(request, 'jobs/job_create.html', {'form':form})


问:
When to use PECS when designing a library?
I am working on a library which makes heavy use of functional interfaces and currently struggle whether to apply PECS or not:

```<code>Predicate<A>
Function<A,B>
BiFunction<A,B,C>
</code>```

vs.

```<code>Predicate<? super A>
Function<? super A, ? extends B>
BiFunction<? super A,? super B,? extends C>
</code>```

It just seems so cluttered and even the error messages turn from:

```<code>Incompatible types: Function<Item, Long> is not convertible to Function<Item, String>
</code>```

to something like

```<code>Incompatible types:
Function<capture of ? super Item, capture of ? extends Long> is not
convertible to Function<capture of ? super Item, capture of ? extends String>
</code>```

which is so hard to read. I have read the following question but still struggle whether to apply it or not as it pollutes the library code and worsens the compiler error messages. Personally I would opt for PCES for the Predicate variants.

Is there some guideline whether to apply PECS or not? I know the pros and cons but I wonder how often people really store e.g. Predicate in fields as lamdas and method references are not affected by what PECS offers. I did not find any further advice on the web. Here is one of the classes affected by this.

答: As discussed extensively in the comments below the main post: consistency and alignment to the JDK / standard library and its use of PECS with the gained compatability improvement by using PECS is a good argument to always use PECS (at least when designing libraries)</p>

Body:
I am working on a library which makes heavy use of functional interfaces and currently struggle whether to apply PECS or not:

Predicate
Function
BiFunction

vs.

Predicate<? super A>
Function<? super A, ? extends B>
BiFunction<? super A,? super B,? extends C>

It just seems so cluttered and even the error messages turn from:

Incompatible types: Function<Item, Long> is not convertible to Function<Item, String>

to something like

Incompatible types:
Function<capture of ? super Item, capture of ? extends Long> is not
convertible to Function<capture of ? super Item, capture of ? extends String>

which is so hard to read. I have read the following question but still struggle whether to apply it or not as it pollutes the library code and worsens the compiler error messages. Personally I would opt for PCES for the Predicate variants.

Is there some guideline whether to apply PECS or not? I know the pros and cons but I wonder how often people really store e.g. Predicate in fields as lamdas and method references are not affected by what PECS offers. I did not find any further advice on the web. Here is one of the classes affected by this.


问:
How do I lock orientation?
I am trying to lock my iPad screen orientation/stop the screen rotating.
My code requires the screen/UI to be horizontal.

The only possible answer that I have found is:

```<code>v.present(style="full_screen", orientations=["portrait"])
</code>```

But I still can't get the screen to lock.

I am using pythonista

答:
Split-screen multitasking is enabled by default (since iOS 10),
and this is interfering with the setting.

The documentation explains that you should click the Requires Full Screen checkbox.

Title: How do I lock orientation?

Body:
I am trying to lock my iPad screen orientation/stop the screen rotating.
My code requires the screen/UI to be horizontal.

The only possible answer that I have found is:

v.present(style="full_screen", orientations=["portrait"])

But I still can't get the screen to lock.

I am using pythonista


问:
PM2 watch only in dev mode
I'm running a node.js app and using pm2 for startup.
For pm2 i have created a process.json file to define my app and two enviroments (prod and dev).

For dev mode i want to enable the watch option of pm2, but not in prod mode.

But i see no way to define this.
Either this option is activated in both modes or in none of them.

Can you please help me to do this?

```<code>{
"apps": [{
    "name": "myapp",
    "script": "./app.js",
    "watch": ["public", "views"],
    "env": {
        "LOGLEVEL": "debug",
        "LOGFILE": "debug.log"
    },
    "env_production": {
        "LOGLEVEL": "info",
        "LOGFILE": "info.log"
    }
}]
}
</code>```

答:
You can use pm2-dev which is included with pm2.

Simply remove the watch tag in your ecosystem.json or set it to false.

And then:

# Start in development env
pm2-dev ecosystem.json

# Start in production env
pm2 start ecosystem.json --env production
```

With pm2-dev watch mode is automatically enabled, and it is not with pm2 start.

ContentLicense: CC BY-SA 3.0

Title: PM2 watch only in dev mode

Body:
I'm running a node.js app and using pm2 for startup.
For pm2 i have created a process.json file to define my app and two enviroments (prod and dev).

For dev mode i want to enable the watch option of pm2, but not in prod mode.

But i see no way to define this.
Either this option is activated in both modes or in none of them.

Can you please help me to do this?

{
"apps": [{
    "name": "myapp",
    "script": "./app.js",
    "watch": ["public", "views"],
    "env": {
        "LOGLEVEL": "debug",
        "LOGFILE": "debug.log"
    },
    "env_production": {
        "LOGLEVEL": "info",
        "LOGFILE": "info.log"
    }
}]
}

Body:
You can use pm2-dev which is included with pm2.

Simply remove the watch tag in your ecosystem.json or set it to false.

And then:

# Start in development env
pm2-dev ecosystem.json

# Start in production env
pm2 start ecosystem.json --env production

With pm2-dev watch mode is automatically enabled, and it is not with pm2 start.


问:
Firebase observe new added data even when the function isn't called
I have a function that observes data from my Firebase database. This data will be inserted in an array, so it can be send to my tableviewcell Viewcontroller. All the data will be put correct in the tabelviewcell, but I have a problem when I update my Firebase database. Everytime I change a value in the database it will immediately update my tableView even when my function is not called. I am not sure what I am doing wrong and how to prevent this.

This is my function observe:

```<code>Database.database().reference().child("posts").child("\(postId)").child("comments").observe(.value, with: { snapshot in
   if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
     for snap in snapshots {
       if let postDict = snap.value as? Dictionary<String, AnyObject> {
          let key = snap.key
          let post = Comment.transformComment(dict: postDict)
          self.comments.insert(post, at: 0)
          self.tableView.reloadData()
       }
     }
   }
})
</code>```

Array:

```<code>var comments: [Comment] = []

extension Comment {
    static func transformComment(dict: [String: Any]) -> Comment {
        let comment = Comment()
        comment.commentText = dict["commentText"] as? String
        comment.uid = dict["uid"] as? String
        comment.timestamp = dict["timestamp"] as? Int
        comment.likeCount = dict["likeCount"] as? Int
        comment.childByAutoId = dict["childByAutoId"] as? String
        comment.id = dict["postId"] as? String
        return comment
    }
}
</code>```

Tablevieww Functions:

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if comments.count == 0 {
            self.tableView.setEmptyMessage("No comments yet!")
        } else {
            self.tableView.restore()
        }
        return comments.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Comment", for: indexPath) as! CommentTableViewCell
        let comment = comments[indexPath.row]
        cell.comment = comment
        cell.delegate = self

        return cell
    }
</code>```

答:
To listen once replace

```<code>.child("comments").observe(.value, with: { snapshot in
</code>```

With

```<code>.child("comments").observeSingleEvent(of: .value) { snapshot in
</code>```

Or

```<code>.child("comments").observe(.childChanged) { snapshot  in
</code>```

to listen to added childs

Body:
I have a function that observes data from my Firebase database. This data will be inserted in an array, so it can be send to my tableviewcell Viewcontroller. All the data will be put correct in the tabelviewcell, but I have a problem when I update my Firebase database. Everytime I change a value in the database it will immediately update my tableView even when my function is not called. I am not sure what I am doing wrong and how to prevent this.

This is my function observe:

Database.database().reference().child("posts").child("\(postId)").child("comments").observe(.value, with: { snapshot in
   if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
     for snap in snapshots {
       if let postDict = snap.value as? Dictionary<String, AnyObject> {
          let key = snap.key
          let post = Comment.transformComment(dict: postDict)
          self.comments.insert(post, at: 0)
          self.tableView.reloadData()
       }
     }
   }
})

Array:

var comments: [Comment] = []

extension Comment {
    static func transformComment(dict: [String: Any]) -> Comment {
        let comment = Comment()
        comment.commentText = dict["commentText"] as? String
        comment.uid = dict["uid"] as? String
        comment.timestamp = dict["timestamp"] as? Int
        comment.likeCount = dict["likeCount"] as? Int
        comment.childByAutoId = dict["childByAutoId"] as? String
        comment.id = dict["postId"] as? String
        return comment
    }
}

Tablevieww Functions:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if comments.count == 0 {
            self.tableView.setEmptyMessage("No comments yet!")
        } else {
            self.tableView.restore()
        }
        return comments.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Comment", for: indexPath) as! CommentTableViewCell
        let comment = comments[indexPath.row]
        cell.comment = comment
        cell.delegate = self

        return cell
    }

Body:
To listen once replace

.child("comments").observe(.value, with: { snapshot in

With

.child("comments").observeSingleEvent(of: .value) { snapshot in

Or

.child("comments").observe(.childChanged) { snapshot  in

to listen to added childs


问:
Material table not sorting records
I can't find what is wrong with my script, the list loads OK but when clicking on the table headers the sorting does not work.

I have tried putting the sorting part inside a TimeOut on the response and also moving it to the ngAfterViewInit() function. Everything else on my app works fine except for this.

Heres is the ts code:

```<code>import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CatalogosService } from 'src/app/services/catalogos.service';
import { MatPaginator, MatSort, MatTableDataSource, MatTableModule, MatTable,
  MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Response } from 'src/app/classes/response';

@Component({
  selector: 'app-lista-proveedores',
  templateUrl: './lista-proveedores.component.html',
  styleUrls: ['./lista-proveedores.component.css']
})
export class ListaProveedoresComponent implements OnInit {

  proveedores: any[];
  listData: MatTableDataSource<any>;
  displayColumns: string[]=['id','nombre','acciones'];
  searchKey: string;
  //spinner: SpinnerComponent= new SpinnerComponent;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(private proveedorService: CatalogosService,
              private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.getRecords();
  }

  getRecords(): void{
    this.proveedorService.getItems()
    .subscribe(
      (response: Response) => {
        //this.proveedores = response.object;
        this.listData= new MatTableDataSource(response.object);
        this.listData.sort= this.sort;
        this.listData.paginator= this.paginator;
        console.log("List data: ", this.sort);
      });
      this.changeDetectorRefs.detectChanges();
  }

}
</code>```

And here is the html:

```<code><div class="col-lg-12">
  <div class="row">
      <div class="col-lg-9 text-center">
          <h3 class="title-divider">
              <span>List</span>
          </h3>
      </div>
      <div class="col-lg-3 text-center">

      </div>
  </div>
  <div class="row">
      <div class="col-lg-12">
          <div class="mat-elevation-z8">
              <mat-table #table [dataSource]="listData" matSort>
                  <ng-container matColumnDef="id">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.ID}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="nombre">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>Nombre</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.Name}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="acciones">
                      <mat-header-cell *matHeaderCellDef>Acciones</mat-header-cell>
                      <mat-cell *matCellDef="let row">
                          <button mat-icon-button (click)="onDetail(row)"><mat-icon>details</mat-icon></button>
                          <button mat-icon-button (click)="onEdit(row)"><mat-icon>launch</mat-icon></button>
                          <button mat-icon-button color="warn" (click)="onDelete(row)"><mat-icon>delete_outline</mat-icon></button>
                      </mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="loading">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          Loading data
                      </mat-footer-cell>
                  </ng-container>
                  <ng-container matColumnDef="noData">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          No data
                      </mat-footer-cell>
                  </ng-container>
                  <mat-header-row *matHeaderRowDef="displayColumns; sticky:true "></mat-header-row>
                  <mat-row *matRowDef="let row; columns: displayColumns"></mat-row>
                  <mat-footer-row *matFooterRowDef="['loading']" [ngClass]="{'hide':listData!=null}"></mat-footer-row>
                  <mat-footer-row *matFooterRowDef="['noData']" [ngClass]="{'hide':!(listData!=null && listData.data.length==0)}"></mat-footer-row>
              </mat-table>
              <mat-paginator [pageSizeOptions]="[5, 10, 15, 25]" [pageSize]="5" showFirstLastButtons></mat-paginator>
          </div>
      </div>
  </div>

</div>
</code>```

Here's also the console log displaying the MatSort object:

```<code>MatSort {_disabled: false, _isInitialized: true, _pendingSubscribers: null, initialized: Observable, sortables: Map(2), …}
direction: (...)
disableClear: (...)
disabled: (...)
initialized: Observable
_isScalar: false
_subscribe: ƒ (subscriber)
arguments: (...)
caller: (...)
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: core.es5.js:474
[[Scopes]]: Scopes[4]
__proto__: Object
sortChange: EventEmitter
closed: false
hasError: false
isStopped: false
observers: (3) [Subscriber, Subscriber, Subscriber]
thrownError: null
__isAsync: false
_isScalar: false
__proto__: Subject
sortables: Map(2)
size: (...)
__proto__: Map
[[Entries]]: Array(2)
0: {"id" => MatSortHeader}
1: {"nombre" => MatSortHeader}
length: 2
start: "asc"
_direction: ""
_disabled: false
_isInitialized: true
_pendingSubscribers: null
_stateChanges: Subject {_isScalar: false, observers: Array(2), closed: false, isStopped: false, hasError: false, …}
__proto__: class_1
</code>```

I've imported MatSortModule and MatTableModule on the AppModule and I have no errors displayed by the JS console.

答:
made a few changes to make it more like the way I do it, can you copy this in and see if it works??:

```<code>import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CatalogosService } from 'src/app/services/catalogos.service';
import { MatPaginator, MatSort, MatTableDataSource, MatTableModule, MatTable,
  MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from
'@angular/material';
import { Response } from 'src/app/classes/response';

@Component({
  selector: 'app-lista-proveedores',
  templateUrl: './lista-proveedores.component.html',
  styleUrls: ['./lista-proveedores.component.css']
})
export class ListaProveedoresComponent implements OnInit {

  proveedores: any[];
  public listData = new MatTableDataSource<any>();

  displayColumns: string[] = ['id', 'nombre', 'acciones'];
  searchKey: string;
  //spinner: SpinnerComponent= new SpinnerComponent;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(private proveedorService: CatalogosService,
              private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.getRecords();
  }

  getRecords(): void{
    this.proveedorService.getItems()
    .subscribe(
      (response: Response) => {
        //this.proveedores = response.object;
        this.listData.data = response;
        this.listData.sort = this.sort;
        this.listData.paginator= this.paginator;
        console.log("List data: ", this.sort);
      });
      this.changeDetectorRefs.detectChanges();
  }

}
</code>```

also check your uppercase is correct for the matColumnDef in your html.  I think the case might not match what the object actually is.  You have element.ID and matColumndef=id as an example.
I just made this edit, and then saw Jesse said the same thing below.  So try that first.

Title: Material table not sorting records

Body:
I can't find what is wrong with my script, the list loads OK but when clicking on the table headers the sorting does not work.

I have tried putting the sorting part inside a TimeOut on the response and also moving it to the ngAfterViewInit() function. Everything else on my app works fine except for this.

Heres is the ts code:

import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CatalogosService } from 'src/app/services/catalogos.service';
import { MatPaginator, MatSort, MatTableDataSource, MatTableModule, MatTable,
  MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Response } from 'src/app/classes/response';

@Component({
  selector: 'app-lista-proveedores',
  templateUrl: './lista-proveedores.component.html',
  styleUrls: ['./lista-proveedores.component.css']
})
export class ListaProveedoresComponent implements OnInit {

  proveedores: any[];
  listData: MatTableDataSource<any>;
  displayColumns: string[]=['id','nombre','acciones'];
  searchKey: string;
  //spinner: SpinnerComponent= new SpinnerComponent;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(private proveedorService: CatalogosService,
              private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.getRecords();
  }

  getRecords(): void{
    this.proveedorService.getItems()
    .subscribe(
      (response: Response) => {
        //this.proveedores = response.object;
        this.listData= new MatTableDataSource(response.object);
        this.listData.sort= this.sort;
        this.listData.paginator= this.paginator;
        console.log("List data: ", this.sort);
      });
      this.changeDetectorRefs.detectChanges();
  }

}

And here is the html:

              List

              <mat-table #table [dataSource]="listData" matSort>
                  <ng-container matColumnDef="id">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.ID}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="nombre">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>Nombre</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.Name}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="acciones">
                      <mat-header-cell *matHeaderCellDef>Acciones</mat-header-cell>
                      <mat-cell *matCellDef="let row">
                          <button mat-icon-button (click)="onDetail(row)"><mat-icon>details</mat-icon></button>
                          <button mat-icon-button (click)="onEdit(row)"><mat-icon>launch</mat-icon></button>
                          <button mat-icon-button color="warn" (click)="onDelete(row)"><mat-icon>delete_outline</mat-icon></button>
                      </mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="loading">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          Loading data
                      </mat-footer-cell>
                  </ng-container>
                  <ng-container matColumnDef="noData">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          No data
                      </mat-footer-cell>
                  </ng-container>
                  <mat-header-row *matHeaderRowDef="displayColumns; sticky:true "></mat-header-row>
                  <mat-row *matRowDef="let row; columns: displayColumns"></mat-row>
                  <mat-footer-row *matFooterRowDef="['loading']" [ngClass]="{'hide':listData!=null}"></mat-footer-row>
                  <mat-footer-row *matFooterRowDef="['noData']" [ngClass]="{'hide':!(listData!=null && listData.data.length==0)}"></mat-footer-row>
              </mat-table>
              <mat-paginator [pageSizeOptions]="[5, 10, 15, 25]" [pageSize]="5" showFirstLastButtons></mat-paginator>

Here's also the console log displaying the MatSort object:

MatSort {_disabled: false, _isInitialized: true, _pendingSubscribers: null, initialized: Observable, sortables: Map(2), …}
direction: (...)
disableClear: (...)
disabled: (...)
initialized: Observable
_isScalar: false
_subscribe: ƒ (subscriber)
arguments: (...)
caller: (...)
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: core.es5.js:474
[[Scopes]]: Scopes[4]
__proto__: Object
sortChange: EventEmitter
closed: false
hasError: false
isStopped: false
observers: (3) [Subscriber, Subscriber, Subscriber]
thrownError: null
__isAsync: false
_isScalar: false
__proto__: Subject
sortables: Map(2)
size: (...)
__proto__: Map
[[Entries]]: Array(2)
0: {"id" => MatSortHeader}
1: {"nombre" => MatSortHeader}
length: 2
start: "asc"
_direction: ""
_disabled: false
_isInitialized: true
_pendingSubscribers: null
_stateChanges: Subject {_isScalar: false, observers: Array(2), closed: false, isStopped: false, hasError: false, …}
__proto__: class_1

I've imported MatSortModule and MatTableModule on the AppModule and I have no errors displayed by the JS console.

Body:
made a few changes to make it more like the way I do it, can you copy this in and see if it works??:

import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CatalogosService } from 'src/app/services/catalogos.service';
import { MatPaginator, MatSort, MatTableDataSource, MatTableModule, MatTable,
  MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from
'@angular/material';
import { Response } from 'src/app/classes/response';

@Component({
  selector: 'app-lista-proveedores',
  templateUrl: './lista-proveedores.component.html',
  styleUrls: ['./lista-proveedores.component.css']
})
export class ListaProveedoresComponent implements OnInit {

  proveedores: any[];
  public listData = new MatTableDataSource<any>();

  displayColumns: string[] = ['id', 'nombre', 'acciones'];
  searchKey: string;
  //spinner: SpinnerComponent= new SpinnerComponent;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(private proveedorService: CatalogosService,
              private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.getRecords();
  }

  getRecords(): void{
    this.proveedorService.getItems()
    .subscribe(
      (response: Response) => {
        //this.proveedores = response.object;
        this.listData.data = response;
        this.listData.sort = this.sort;
        this.listData.paginator= this.paginator;
        console.log("List data: ", this.sort);
      });
      this.changeDetectorRefs.detectChanges();
  }

}

also check your uppercase is correct for the matColumnDef in your html.  I think the case might not match what the object actually is.  You have element.ID and matColumndef=id as an example.
I just made this edit, and then saw Jesse said the same thing below.  So try that first.


问:
Google Vision for PDF
I need to send a PDF file to Google Vision to extract and return text. From documentation I understood that DPF file must be located on Google Storage, so I am putting the file to my Google Storage bucket like this:

```<code>require '../vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;

$storage = new StorageClient([
    'keyFilePath' => '/my-keyfile.json',
    'projectId' => PROJECT_ID
]);

$bucket = $storage->bucket(BUCKET_NAME);

$bucket->upload(
    fopen($_SESSION['local_pdf_url'], 'r')
);
</code>```

It works. After I redirect to another page that is suppose to get that file to Vision, and that's where it fails. I found an example function. Here's the code:

```<code>require '../vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Vision\V1\AnnotateFileResponse;
use Google\Cloud\Vision\V1\AsyncAnnotateFileRequest;
use Google\Cloud\Vision\V1\Feature;
use Google\Cloud\Vision\V1\Feature\Type;
use Google\Cloud\Vision\V1\GcsDestination;
use Google\Cloud\Vision\V1\GcsSource;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\InputConfig;
use Google\Cloud\Vision\V1\OutputConfig;

$storage = new StorageClient([
    'keyFilePath' => '/my-keyfile.json',
    'projectId' => PROJECT_ID
]);

$path = 'gs://my-bucket/'.$_SESSION['pdf_file_name'];
</code>```

When I run the second script I get the following errors:

Fatal error: Uncaught DomainException: Could not load the default
  credentials. Browse to
  https://developers.google.com/accounts/docs/application-default-credentials
  for more information in
  /home/domain/vendor/google/auth/src/ApplicationDefaultCredentials.php:168
  Stack trace: #0
  /home/domain/vendor/google/gax/src/CredentialsWrapper.php(197):
  Google\Auth\ApplicationDefaultCredentials::getCredentials(Array,
  Object(Google\Auth\HttpHandler\Guzzle6HttpHandler), NULL, NULL) #1
  /home/domain/vendor/google/gax/src/CredentialsWrapper.php(114):
  Google\ApiCore\CredentialsWrapper::buildApplicationDefaultCredentials(Array,
  Object(Google\Auth\HttpHandler\Guzzle6HttpHandler)) #2
  /home/domain/vendor/google/gax/src/GapicClientTrait.php(326):
  Google\ApiCore\CredentialsWrapper::build(Array) #3
  /home/domain/vendor/google/gax/src/GapicClientTrait.php(308):
  Google\Cloud\Vision\V1\Gapic\ImageAnnotatorGapicClient->createCredentialsWrapper(NULL,
  Array) #4
  /home/domain/vendor/google/cloud/Vision/src/V1/Gapic/ImageAnnotatorGapicClient.php(216):
  Google\Clou in
  /home/domain/vendor/google/gax/src/CredentialsWrapper.php on line 200

How do I authenticate for this service? What am I missing?

答:
I realize how frustrating it could be when documentation is somewhat lacking organization, content or good examples. Here's what I ended-up doing myself, that finally allowed my script to work. Hope it'll help someone too:</p>

```<code>require '../vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Vision\V1\AnnotateFileResponse;
use Google\Cloud\Vision\V1\AsyncAnnotateFileRequest;
use Google\Cloud\Vision\V1\Feature;
use Google\Cloud\Vision\V1\Feature\Type;
use Google\Cloud\Vision\V1\GcsDestination;
use Google\Cloud\Vision\V1\GcsSource;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\InputConfig;
use Google\Cloud\Vision\V1\OutputConfig;

putenv('GOOGLE_APPLICATION_CREDENTIALS=/my-keyfile.json');

$path = 'gs://my-bucket/'.$_SESSION['pdf_file_name'];
</code>```

Title: Google Vision for PDF

Body:
I need to send a PDF file to Google Vision to extract and return text. From documentation I understood that DPF file must be located on Google Storage, so I am putting the file to my Google Storage bucket like this:

require '../vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;

$storage = new StorageClient([
    'keyFilePath' => '/my-keyfile.json',
    'projectId' => PROJECT_ID
]);

$bucket = $storage->bucket(BUCKET_NAME);

$bucket->upload(
    fopen($_SESSION['local_pdf_url'], 'r')
);

It works. After I redirect to another page that is suppose to get that file to Vision, and that's where it fails. I found an example function. Here's the code:

require '../vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Vision\V1\AnnotateFileResponse;
use Google\Cloud\Vision\V1\AsyncAnnotateFileRequest;
use Google\Cloud\Vision\V1\Feature;
use Google\Cloud\Vision\V1\Feature\Type;
use Google\Cloud\Vision\V1\GcsDestination;
use Google\Cloud\Vision\V1\GcsSource;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\InputConfig;
use Google\Cloud\Vision\V1\OutputConfig;

$storage = new StorageClient([
    'keyFilePath' => '/my-keyfile.json',
    'projectId' => PROJECT_ID
]);

$path = 'gs://my-bucket/'.$_SESSION['pdf_file_name'];

When I run the second script I get the following errors:

Fatal error: Uncaught DomainException: Could not load the default
  credentials. Browse to
  https://developers.google.com/accounts/docs/application-default-credentials
  for more information in
  /home/domain/vendor/google/auth/src/ApplicationDefaultCredentials.php:168
  Stack trace: #0
  /home/domain/vendor/google/gax/src/CredentialsWrapper.php(197):
  Google\Auth\ApplicationDefaultCredentials::getCredentials(Array,
  Object(Google\Auth\HttpHandler\Guzzle6HttpHandler), NULL, NULL) #1
  /home/domain/vendor/google/gax/src/CredentialsWrapper.php(114):
  Google\ApiCore\CredentialsWrapper::buildApplicationDefaultCredentials(Array,
  Object(Google\Auth\HttpHandler\Guzzle6HttpHandler)) #2
  /home/domain/vendor/google/gax/src/GapicClientTrait.php(326):
  Google\ApiCore\CredentialsWrapper::build(Array) #3
  /home/domain/vendor/google/gax/src/GapicClientTrait.php(308):
  Google\Cloud\Vision\V1\Gapic\ImageAnnotatorGapicClient->createCredentialsWrapper(NULL,
  Array) #4
  /home/domain/vendor/google/cloud/Vision/src/V1/Gapic/ImageAnnotatorGapicClient.php(216):
  Google\Clou in
  /home/domain/vendor/google/gax/src/CredentialsWrapper.php on line 200

How do I authenticate for this service? What am I missing?

Body:
I realize how frustrating it could be when documentation is somewhat lacking organization, content or good examples. Here's what I ended-up doing myself, that finally allowed my script to work. Hope it'll help someone too:

require '../vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Vision\V1\AnnotateFileResponse;
use Google\Cloud\Vision\V1\AsyncAnnotateFileRequest;
use Google\Cloud\Vision\V1\Feature;
use Google\Cloud\Vision\V1\Feature\Type;
use Google\Cloud\Vision\V1\GcsDestination;
use Google\Cloud\Vision\V1\GcsSource;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\InputConfig;
use Google\Cloud\Vision\V1\OutputConfig;

putenv('GOOGLE_APPLICATION_CREDENTIALS=/my-keyfile.json');

$path = 'gs://my-bucket/'.$_SESSION['pdf_file_name'];


问:
no result with mongoose .find() when looking into array of a single document
I know it's me improperly formatting the query but i cannot seem to get entries in a document from a nested array. What i am attempting to do is retrieve all of the objects in the array with a specific value in the menu field.

I am also using mongo-tenant so the Settings object is already limited to a single document within the collection as it's the only document in settings for that tenant. (req.params.db is referenced earlier in the url than the visible route)

so far i have tried, based on many googlings

.find({}) // returns entire object as below

.find({dropsDowns: { menu: { $eq: req.params.menu }}}) // returns []

.find({ dropsDowns: { menu: req.params.menu } }) // returns []

.find({'dropDowns.menu':req.params.menu}) // returns entire object

.find({ ['dropDowns.menu']: req.params.menu }) // returns entire object

I also tried to do a few forms of the aggregation methods with less than ideal results as that assumes i actually know how to find the right stuff to aggregate, which i obviously do not.

```<code>settingsRoute.route('/dropDowns/:menu').get(function(req, res) {
  const Settings = baseSettings.byTenant(req.params.db)
  Settings.find({}).exec(function(
    err,
    menu
  ) {
    if (err) {
      return res.status(400).json(err)
    }
    res.status(200).json(menu)
  })
})
</code>```

this returns the below to my browser

```<code>[
{
_id: "5cea1b835e13fb4180be2699",
dropDowns: [
{
_id: "5cea1b835e13fb4180be26a7",
menu: "frequencyOptions",
text: "Monthly",
value: 30,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a6",
menu: "frequencyOptions",
text: "Every two months",
value: 60,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a3",
menu: "meterIntervals",
text: "250",
value: 250,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a2",
menu: "meterIntervals",
text: "500",
value: 500,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be269e",
menu: "transitionIntervals",
text: "Due at normal interval",
value: 0,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be269d",
menu: "transitionIntervals",
text: "Offset by 25% of normal",
value: 250,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z"
}
],
tenantId: "maxx1",
siteSettings: {
siteTheme: "dark",
friendlyName: "No Name Set :(",
activeStatus: "transit",
previousStatus: "transit",
numBackupsToKeep: 10,
daysPerBackup: 7,
_id: "5cea1b835e13fb4180be26ad",
backups: [ ],
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z"
},
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z",
__v: 0
}
]
</code>```

What is the proper formatting to only have something like the below return if i were to hit the api with /dropDowns/frequencyOptions

```<code>dropDowns: [
{
_id: "5cea1b835e13fb4180be26a7",
menu: "frequencyOptions",
text: "Monthly",
value: 30,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a6",
menu: "frequencyOptions",
text: "Every two months",
value: 60,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
}
</code>```

I am still building the structure of the database so if there is a more efficient way to go about getting this kind of data together then i am open to recommendations as well.

Thanks for any help.

答: I ended up just making a new collection just for the dropdown options, the tenant will sort them appropriatly for that page and i can then fo a direct sort with <code>.find({name:req.param.name})</code> to toArray's needed. Maybe later when i have gained more knowledge about how to handle the returns i will revisit pulling and parsing the array as needed. </p>

Body:
I know it's me improperly formatting the query but i cannot seem to get entries in a document from a nested array. What i am attempting to do is retrieve all of the objects in the array with a specific value in the menu field.

I am also using mongo-tenant so the Settings object is already limited to a single document within the collection as it's the only document in settings for that tenant. (req.params.db is referenced earlier in the url than the visible route)

so far i have tried, based on many googlings

.find({}) // returns entire object as below

.find({dropsDowns: { menu: { $eq: req.params.menu }}}) // returns []

.find({ dropsDowns: { menu: req.params.menu } }) // returns []

.find({'dropDowns.menu':req.params.menu}) // returns entire object

.find({ ['dropDowns.menu']: req.params.menu }) // returns entire object

I also tried to do a few forms of the aggregation methods with less than ideal results as that assumes i actually know how to find the right stuff to aggregate, which i obviously do not.

settingsRoute.route('/dropDowns/:menu').get(function(req, res) {
  const Settings = baseSettings.byTenant(req.params.db)
  Settings.find({}).exec(function(
    err,
    menu
  ) {
    if (err) {
      return res.status(400).json(err)
    }
    res.status(200).json(menu)
  })
})

this returns the below to my browser

[
{
_id: "5cea1b835e13fb4180be2699",
dropDowns: [
{
_id: "5cea1b835e13fb4180be26a7",
menu: "frequencyOptions",
text: "Monthly",
value: 30,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a6",
menu: "frequencyOptions",
text: "Every two months",
value: 60,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a3",
menu: "meterIntervals",
text: "250",
value: 250,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a2",
menu: "meterIntervals",
text: "500",
value: 500,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be269e",
menu: "transitionIntervals",
text: "Due at normal interval",
value: 0,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be269d",
menu: "transitionIntervals",
text: "Offset by 25% of normal",
value: 250,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z"
}
],
tenantId: "maxx1",
siteSettings: {
siteTheme: "dark",
friendlyName: "No Name Set :(",
activeStatus: "transit",
previousStatus: "transit",
numBackupsToKeep: 10,
daysPerBackup: 7,
_id: "5cea1b835e13fb4180be26ad",
backups: [ ],
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z"
},
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z",
__v: 0
}
]

What is the proper formatting to only have something like the below return if i were to hit the api with /dropDowns/frequencyOptions

dropDowns: [
{
_id: "5cea1b835e13fb4180be26a7",
menu: "frequencyOptions",
text: "Monthly",
value: 30,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a6",
menu: "frequencyOptions",
text: "Every two months",
value: 60,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
}

I am still building the structure of the database so if there is a more efficient way to go about getting this kind of data together then i am open to recommendations as well.

Thanks for any help.

Body: I ended up just making a new collection just for the dropdown options, the tenant will sort them appropriatly for that page and i can then fo a direct sort with .find({name:req.param.name}) to toArray's needed. Maybe later when i have gained more knowledge about how to handle the returns i will revisit pulling and parsing the array as needed.


问:
How to make a double loop inside a dictionary in Python?
I have a data cube with 2 dimensions of coordinates and a third dimension for wavelength. My goal is to write a mask for coordinates outside a circle of given radius to the central coordinates (x0 and y0 in my code). For this, I'm trying to use a dictionary, but I'm having throuble because it seems that I'll have to make a double loop inside the dictionary to iterate over the two dimensions, and as a beginner with dictionaries, I don't know yet how to do that.

I wrote the following code

```<code>x0 = 38
y0 = 45
radius = 9

xcoords = np.arange(1,flux.shape[1]+1,1)
ycoords = np.arange(1,flux.shape[2]+1,1)

mask = {'xmask': [xcoords[np.sqrt((xcoords[:]-x0)**2 + (y-y0)**2) < radius] for y in ycoords], 'ymask': [ycoords[np.sqrt((x-x0)**2 + (ycoords[:]-y0)**2) < radius] for x in xcoords]}
</code>```

And it returned several arrays, one for each value of y (for xmasks), and one for each value of x (for ymasks), although I want just one array for each one. Could anyone say what I made wrong and how to achieve my goal?

Note: I also made it without using a dictionary, as

```<code>xmask = []
for x in xcoords:
    for y in ycoords:
        if np.sqrt((x-x0)**2 + (y-y0)**2) < radius:
            xmask.append(x)
            break

ymask = []
for y in xcoords:
    for x in ycoords:
        if np.sqrt((x-x0)**2 + (y-y0)**2) < radius:
            ymask.append(y)
            break
</code>```

but I hope it's possible to make it more efficiently.

Thanks for any help!

Edit: I realized that no loop was needed. If I select y = y0 and x = x0, I get the values of x and y that are inside the circle, respectively. So I stayed with

```<code>mask = {'xmask': [xcoords[abs(xcoords[:]-x0) < radius]], 'ymask': [ycoords[abs(ycoords[:]-y0) < radius]]}
</code>```

答:
The OP explains that assigning

```<code>mask = {'xmask': [xcoords[abs(xcoords[:] - x0) < radius]],
        'ymask': [ycoords[abs(ycoords[:] - y0) < radius]]}
</code>```

solves the problem.

Body:
I have a data cube with 2 dimensions of coordinates and a third dimension for wavelength. My goal is to write a mask for coordinates outside a circle of given radius to the central coordinates (x0 and y0 in my code). For this, I'm trying to use a dictionary, but I'm having throuble because it seems that I'll have to make a double loop inside the dictionary to iterate over the two dimensions, and as a beginner with dictionaries, I don't know yet how to do that.

I wrote the following code

x0 = 38
y0 = 45
radius = 9

xcoords = np.arange(1,flux.shape[1]+1,1)
ycoords = np.arange(1,flux.shape[2]+1,1)

mask = {'xmask': [xcoords[np.sqrt((xcoords[:]-x0)**2 + (y-y0)**2) < radius] for y in ycoords], 'ymask': [ycoords[np.sqrt((x-x0)**2 + (ycoords[:]-y0)**2) < radius] for x in xcoords]}

And it returned several arrays, one for each value of y (for xmasks), and one for each value of x (for ymasks), although I want just one array for each one. Could anyone say what I made wrong and how to achieve my goal?

Note: I also made it without using a dictionary, as

xmask = []
for x in xcoords:
    for y in ycoords:
        if np.sqrt((x-x0)**2 + (y-y0)**2) < radius:
            xmask.append(x)
            break

ymask = []
for y in xcoords:
    for x in ycoords:
        if np.sqrt((x-x0)**2 + (y-y0)**2) < radius:
            ymask.append(y)
            break

but I hope it's possible to make it more efficiently.

Thanks for any help!

Edit: I realized that no loop was needed. If I select y = y0 and x = x0, I get the values of x and y that are inside the circle, respectively. So I stayed with

mask = {'xmask': [xcoords[abs(xcoords[:]-x0) < radius]], 'ymask': [ycoords[abs(ycoords[:]-y0) < radius]]}

Body:
The OP explains that assigning

mask = {'xmask': [xcoords[abs(xcoords[:] - x0) < radius]],
        'ymask': [ycoords[abs(ycoords[:] - y0) < radius]]}

solves the problem.


问:
Hook before deleting a file in wordpress
Few days ago, I was assigned to task in wordpress. This task is to limit media folder capacity for each user. For example, each user can upload only files only for 100MB.  I found a really nice post, which explained and used hooks named wp_handle_upload_prefilter and wp_handle_upload for retrieving the file size and storing them before upload.

Right now, I need to know, or hook some function when user presses "Delete permanently" in media folder, so that I can recalculate the capacity of media folder for specific user. Can anyone help me with this?

答:
In case anyone else needs to react to deleted media, this was my solution to get around the issue that there's no delete media action:</p>

```<code>function get_media_item_args( $args ) {

    if ($args["delete"] && $_GET["action" == "delete-post"])
    {
        $current_post_id = !empty( $_GET['id'] ) ? (int) $_GET['id'] : 0;

        if ($current_post_id > 0)
        {
            //Do your thing here.
        }
    }

    return $args;
}
add_filter( 'get_media_item_args', 'get_media_item_args', 10, 1 );
</code>```

Body:
In case anyone else needs to react to deleted media, this was my solution to get around the issue that there's no delete media action:

function get_media_item_args( $args ) {

    if ($args["delete"] && $_GET["action" == "delete-post"])
    {
        $current_post_id = !empty( $_GET['id'] ) ? (int) $_GET['id'] : 0;

        if ($current_post_id > 0)
        {
            //Do your thing here.
        }
    }

    return $args;
}
add_filter( 'get_media_item_args', 'get_media_item_args', 10, 1 );


问:
Replace missing values with column mean
I am not sure how to loop over each column to replace the NA values with the column mean. When I am trying to replace for one column using the following, it works well.

```<code>Column1[is.na(Column1)] <- round(mean(Column1, na.rm = TRUE))
</code>```

The code for looping over columns is not working:

```<code>for(i in 1:ncol(data)){
    data[i][is.na(data[i])] <- round(mean(data[i], na.rm = TRUE))
}
</code>```

the values are not replaced. Can someone please help me with this?

答:
A one-liner using tidyr's replace_na is

```<code>library(tidyr)
replace_na(mtcars,as.list(colMeans(mtcars,na.rm=T)))
</code>```

If your df has columns that are non-numeric, this takes a little bit more work than a one-liner.

```<code>mean_to_fill <- select_if(ungroup(df), is.numeric) %>%
 colMeans(na.rm=T)

bind_cols(select(df, group1, group2, group3),
          select_if(ungroup(df), is.numeric) %>%
            tidyr::replace_na(as.list(mean_to_fill))
          )
</code>```

Title: Replace missing values with column mean

Body:
I am not sure how to loop over each column to replace the NA values with the column mean. When I am trying to replace for one column using the following, it works well.

Column1[is.na(Column1)] <- round(mean(Column1, na.rm = TRUE))

The code for looping over columns is not working:

for(i in 1:ncol(data)){
    data[i][is.na(data[i])] <- round(mean(data[i], na.rm = TRUE))
}

the values are not replaced. Can someone please help me with this?

Body:
A one-liner using tidyr's replace_na is

library(tidyr)
replace_na(mtcars,as.list(colMeans(mtcars,na.rm=T)))

If your df has columns that are non-numeric, this takes a little bit more work than a one-liner.

mean_to_fill <- select_if(ungroup(df), is.numeric) %>%
 colMeans(na.rm=T)

bind_cols(select(df, group1, group2, group3),
          select_if(ungroup(df), is.numeric) %>%
            tidyr::replace_na(as.list(mean_to_fill))
          )


问:
What does type signature for `undefined` mean in Haskell?
I am a beginner in Haskell and I am taken aback by the undefined function's type signature.

I expected something more simple, but I found this on Hackage:

```<code>undefined :: forall (r :: RuntimeRep). forall (a :: TYPE r). HasCallStack => a
</code>```

A special case of error. It is expected that compilers will recognize this and insert error messages which are more appropriate to the context in which undefined appears.

Could you please explain what does this signature mean?

Thanks!

答:
This is a continuation of @leftaroundabout's answer.

In Haskell, values have types. But types themselves also have types. When a type is acting as the type of another type, we call it a "kind".

The most important and common kind in Haskell is Type, often denoted in signatures as *. It is the kind of types that are "lifted", that is, whose values can be thunks that, when evaluated, can diverge, throw an error, etc... For example the type Int has kind Type.

There are also other types like Int# that are not lifted. A value of type Int# is never a thunk, it's always an actual value in memory.

In short, the in-memory representation of values is controlled by their type's kind.

RuntimeRep is another kind. It is the kind of types like LiftedRep and IntRep. These types don't have any values, they exist merely to express things at the type level, as we shall see.

There is a super-magical type-level entity called TYPE that, when parameterized with a type of kind RuntimeRep (that is with a type that describes an in-memory representation) returns the kind of types whose values have that representation. For example, Type is TYPE LiftedRep, while the kind of Int# is TYPE IntRep.

```<code>ghci> :set -XMagicHash
ghci> import GHC.Prim
ghci> import GHC.Types
ghci> import Data.Kind
ghci> :kind (Int :: TYPE 'LiftedRep)
(Int :: TYPE 'LiftedRep) :: *
ghci> :kind Int#
Int# :: TYPE 'IntRep
</code>```

Now we can get back to why undefined has such a weird signature. The thing is, we want to be able to use undefined in all functions, be it functions that return types of kind Type, but also functions that return types of kind TYPE IntRep (in other words: the Int# type) or functions that return another unlifted type. Otherwise, we would need multiple different versions of undefined, which would be annoying.

The solution is to make undefined levity-polymorphic. The signature says: for any possible in-memory representation (RuntimeRep) and for any possible type whose values have that representation, undefined counts a member of that type.

Body:
I am a beginner in Haskell and I am taken aback by the undefined function's type signature.

I expected something more simple, but I found this on Hackage:

undefined :: forall (r :: RuntimeRep). forall (a :: TYPE r). HasCallStack => a

A special case of error. It is expected that compilers will recognize this and insert error messages which are more appropriate to the context in which undefined appears.

Could you please explain what does this signature mean?

Thanks!

Body:
This is a continuation of @leftaroundabout's answer.

In Haskell, values have types. But types themselves also have types. When a type is acting as the type of another type, we call it a "kind".

The most important and common kind in Haskell is Type, often denoted in signatures as *. It is the kind of types that are "lifted", that is, whose values can be thunks that, when evaluated, can diverge, throw an error, etc... For example the type Int has kind Type.

There are also other types like Int# that are not lifted. A value of type Int# is never a thunk, it's always an actual value in memory.

In short, the in-memory representation of values is controlled by their type's kind.

RuntimeRep is another kind. It is the kind of types like LiftedRep and IntRep. These types don't have any values, they exist merely to express things at the type level, as we shall see.

There is a super-magical type-level entity called TYPE that, when parameterized with a type of kind RuntimeRep (that is with a type that describes an in-memory representation) returns the kind of types whose values have that representation. For example, Type is TYPE LiftedRep, while the kind of Int# is TYPE IntRep.

ghci> :set -XMagicHash
ghci> import GHC.Prim
ghci> import GHC.Types
ghci> import Data.Kind
ghci> :kind (Int :: TYPE 'LiftedRep)
(Int :: TYPE 'LiftedRep) :: *
ghci> :kind Int#
Int# :: TYPE 'IntRep

Now we can get back to why undefined has such a weird signature. The thing is, we want to be able to use undefined in all functions, be it functions that return types of kind Type, but also functions that return types of kind TYPE IntRep (in other words: the Int# type) or functions that return another unlifted type. Otherwise, we would need multiple different versions of undefined, which would be annoying.

The solution is to make undefined levity-polymorphic. The signature says: for any possible in-memory representation (RuntimeRep) and for any possible type whose values have that representation, undefined counts a member of that type.