问:
Why won't Kibana Node server start up?
I just upgraded to Elasticsearch and Kibana 6.0.1 from 5.6.4 and I'm having trouble getting the Kibana server running. The service appears to be running, but nothing is binding to the port and I don't see any errors in the logs.

Verifying the version I have running:

```<code>root@my-server:/var/log# /usr/share/kibana/bin/kibana --version
6.0.1
</code>```

Checking the service status:

```<code>root@my-server:/var/log# sudo service kibana start
root@my-server:/var/log# sudo service kibana status
● kibana.service - Kibana
   Loaded: loaded (/etc/systemd/system/kibana.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2017-12-08 21:17:53 UTC; 1s ago
 Main PID: 17766 (node)
    Tasks: 6 (limit: 4915)
   Memory: 86.6M
      CPU: 1.981s
   CGroup: /system.slice/kibana.service
           └─17766 /usr/share/kibana/bin/../node/bin/node --no-warnings /usr/share/kibana/bin/../src/cli -c /etc/kibana/kibana.yml
</code>```

The contents of my /etc/kibana/kibana.yml config file:

```<code>elasticsearch.password: mypassword
elasticsearch.url: http://my-server:9200
elasticsearch.username: elastic
logging.dest: /var/log/kibana.log
logging.verbose: true
server.basePath: /kibana
server.host: localhost
server.port: 5601
</code>```

The contents of my log file:

```<code>root@my-server:/var/log# tail /var/log/kibana.log -n1000
{"type":"log","@timestamp":"2017-12-08T21:17:04Z","tags":["plugins","debug"],"pid":17712,"dir":"/usr/share/kibana/plugins","message":"Scanning `/usr/share/kibana/plugins` for plugins"}
{"type":"log","@timestamp":"2017-12-08T21:17:04Z","tags":["plugins","debug"],"pid":17712,"dir":"/usr/share/kibana/src/core_plugins","message":"Scanning `/usr/share/kibana/src/core_plugins` for plugins"}
{"type":"log","@timestamp":"2017-12-08T21:17:16Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/plugins/x-pack/index.js","message":"Found plugin at /usr/share/kibana/plugins/x-pack/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:16Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/console/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/console/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:16Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/elasticsearch/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/elasticsearch/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:16Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/kbn_doc_views/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/kbn_doc_views/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:16Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/kbn_vislib_vis_types/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/kbn_vislib_vis_types/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/kibana/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/kibana/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/markdown_vis/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/markdown_vis/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/metrics/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/metrics/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/region_map/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/region_map/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/spy_modes/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/spy_modes/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/state_session_storage_redirect/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/state_session_storage_redirect/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/status_page/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/status_page/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/table_vis/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/table_vis/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/tagcloud/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/tagcloud/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/tile_map/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/tile_map/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/timelion/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/timelion/index.js"}
{"type":"ops","@timestamp":"2017-12-08T21:17:18Z","tags":[],"pid":17712,"os":{"load":[1.03271484375,1.29541015625,2.1494140625],"mem":{"total":2094931968,"free":763858944},"uptime":10018},"proc":{"uptime":16.017,"mem":{"rss":269451264,"heapTotal":239005696,"heapUsed":200227592,"external":489126},"delay":3.2269310001283884},"load":{"requests":{},"concurrents":{"5601":0},"responseTimes":{},"sockets":{"http":{"total":0},"https":{"total":0}}},"message":"memory: 191.0MB uptime: 0:00:16 load: [1.03 1.30 2.15] delay: 3.227"}
{"type":"log","@timestamp":"2017-12-08T21:17:18Z","tags":["info","optimize"],"pid":17712,"message":"Optimizing and caching bundles for graph, monitoring, ml, kibana, stateSessionStorageRedirect, timelion, login, logout, dashboardViewer and status_page. This may take a few minutes"}
</code>```

Confirming that ES is up and running:

```<code>root@my-server:/var/log# curl -u elastic:"mypassword" http://my-
server:9200/
{
  "name" : "vf9xM-O",
  "cluster_name" : "my-server",
  "cluster_uuid" : "pdwwLfCOTgehc_5B8oB-8g",
  "version" : {
    "number" : "6.0.1",
    "build_hash" : "601be4a",
    "build_date" : "2017-12-04T09:29:09.525Z",
    "build_snapshot" : false,
    "lucene_version" : "7.0.1",
    "minimum_wire_compatibility_version" : "5.6.0",
    "minimum_index_compatibility_version" : "5.0.0"
  },
  "tagline" : "You Know, for Search"
}
</code>```

When I try to CURL the Kibana Node server (which should be running on 5601 as per the config):

```<code>root@my-server:/var/log# curl 'localhost:5601'
curl: (7) Failed to connect to localhost port 5601: Connection refused
</code>```

Indeed when I list the open ports, I see lots of things, but nothing on 5601:

```<code>root@my-server:/var/log# netstat -ntlp | grep LISTEN
tcp        0      0 0.0.0.0:9191            0.0.0.0:*               LISTEN      1412/uwsgi
tcp        0      0 0.0.0.0:5355            0.0.0.0:*               LISTEN      1413/systemd-resolv
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      15924/nginx: master
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1519/sshd
tcp        0      0 0.0.0.0:3031            0.0.0.0:*               LISTEN      1412/uwsgi
tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN      1591/postgres
tcp6       0      0 :::5355                 :::*                    LISTEN      1413/systemd-resolv
tcp6       0      0 :::9200                 :::*                    LISTEN      16108/java
tcp6       0      0 :::9300                 :::*                    LISTEN      16108/java
tcp6       0      0 :::22                   :::*                    LISTEN      1519/sshd
tcp6       0      0 :::5432                 :::*                    LISTEN      1591/postgres
</code>```

I'm not sure what else to try to troubleshoot Kibana, any ideas are really really appreciated!

答:
Well I'm not really sure why, but this seemed to work after I rebooted the machine:

```<code>root@my-server:~# sudo reboot
</code>```

after a minute I SSHed back in and voila:

```<code>root@my-server:~# netstat -ntlp | grep LISTEN
tcp        0      0 127.0.0.1:5601          0.0.0.0:*               LISTEN      1428/node
tcp        0      0 0.0.0.0:9191            0.0.0.0:*               LISTEN      1414/uwsgi
tcp        0      0 0.0.0.0:5355            0.0.0.0:*               LISTEN      1427/systemd-resolv
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1467/nginx: master
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1510/sshd
tcp        0      0 0.0.0.0:3031            0.0.0.0:*               LISTEN      1414/uwsgi
tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN      1578/postgres
tcp6       0      0 :::5355                 :::*                    LISTEN      1427/systemd-resolv
tcp6       0      0 :::9200                 :::*                    LISTEN      2011/java
tcp6       0      0 :::9300                 :::*                    LISTEN      2011/java
tcp6       0      0 :::22                   :::*                    LISTEN      1510/sshd
tcp6       0      0 :::5432                 :::*                    LISTEN      1578/postgres
</code>```

¯_(ツ)_/¯

Title: Why won't Kibana Node server start up?

Body:
I just upgraded to Elasticsearch and Kibana 6.0.1 from 5.6.4 and I'm having trouble getting the Kibana server running. The service appears to be running, but nothing is binding to the port and I don't see any errors in the logs.

Verifying the version I have running:

root@my-server:/var/log# /usr/share/kibana/bin/kibana --version
6.0.1

Checking the service status:

root@my-server:/var/log# sudo service kibana start
root@my-server:/var/log# sudo service kibana status
● kibana.service - Kibana
   Loaded: loaded (/etc/systemd/system/kibana.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2017-12-08 21:17:53 UTC; 1s ago
 Main PID: 17766 (node)
    Tasks: 6 (limit: 4915)
   Memory: 86.6M
      CPU: 1.981s
   CGroup: /system.slice/kibana.service
           └─17766 /usr/share/kibana/bin/../node/bin/node --no-warnings /usr/share/kibana/bin/../src/cli -c /etc/kibana/kibana.yml

The contents of my /etc/kibana/kibana.yml config file:

elasticsearch.password: mypassword
elasticsearch.url: http://my-server:9200
elasticsearch.username: elastic
logging.dest: /var/log/kibana.log
logging.verbose: true
server.basePath: /kibana
server.host: localhost
server.port: 5601

The contents of my log file:

root@my-server:/var/log# tail /var/log/kibana.log -n1000
{"type":"log","@timestamp":"2017-12-08T21:17:04Z","tags":["plugins","debug"],"pid":17712,"dir":"/usr/share/kibana/plugins","message":"Scanning `/usr/share/kibana/plugins` for plugins"}
{"type":"log","@timestamp":"2017-12-08T21:17:04Z","tags":["plugins","debug"],"pid":17712,"dir":"/usr/share/kibana/src/core_plugins","message":"Scanning `/usr/share/kibana/src/core_plugins` for plugins"}
{"type":"log","@timestamp":"2017-12-08T21:17:16Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/plugins/x-pack/index.js","message":"Found plugin at /usr/share/kibana/plugins/x-pack/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:16Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/console/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/console/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:16Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/elasticsearch/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/elasticsearch/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:16Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/kbn_doc_views/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/kbn_doc_views/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:16Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/kbn_vislib_vis_types/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/kbn_vislib_vis_types/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/kibana/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/kibana/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/markdown_vis/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/markdown_vis/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/metrics/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/metrics/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/region_map/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/region_map/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/spy_modes/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/spy_modes/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/state_session_storage_redirect/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/state_session_storage_redirect/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/status_page/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/status_page/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/table_vis/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/table_vis/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/tagcloud/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/tagcloud/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/tile_map/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/tile_map/index.js"}
{"type":"log","@timestamp":"2017-12-08T21:17:17Z","tags":["plugins","debug"],"pid":17712,"path":"/usr/share/kibana/src/core_plugins/timelion/index.js","message":"Found plugin at /usr/share/kibana/src/core_plugins/timelion/index.js"}
{"type":"ops","@timestamp":"2017-12-08T21:17:18Z","tags":[],"pid":17712,"os":{"load":[1.03271484375,1.29541015625,2.1494140625],"mem":{"total":2094931968,"free":763858944},"uptime":10018},"proc":{"uptime":16.017,"mem":{"rss":269451264,"heapTotal":239005696,"heapUsed":200227592,"external":489126},"delay":3.2269310001283884},"load":{"requests":{},"concurrents":{"5601":0},"responseTimes":{},"sockets":{"http":{"total":0},"https":{"total":0}}},"message":"memory: 191.0MB uptime: 0:00:16 load: [1.03 1.30 2.15] delay: 3.227"}
{"type":"log","@timestamp":"2017-12-08T21:17:18Z","tags":["info","optimize"],"pid":17712,"message":"Optimizing and caching bundles for graph, monitoring, ml, kibana, stateSessionStorageRedirect, timelion, login, logout, dashboardViewer and status_page. This may take a few minutes"}

Confirming that ES is up and running:

root@my-server:/var/log# curl -u elastic:"mypassword" http://my-
server:9200/
{
  "name" : "vf9xM-O",
  "cluster_name" : "my-server",
  "cluster_uuid" : "pdwwLfCOTgehc_5B8oB-8g",
  "version" : {
    "number" : "6.0.1",
    "build_hash" : "601be4a",
    "build_date" : "2017-12-04T09:29:09.525Z",
    "build_snapshot" : false,
    "lucene_version" : "7.0.1",
    "minimum_wire_compatibility_version" : "5.6.0",
    "minimum_index_compatibility_version" : "5.0.0"
  },
  "tagline" : "You Know, for Search"
}

When I try to CURL the Kibana Node server (which should be running on 5601 as per the config):

root@my-server:/var/log# curl 'localhost:5601'
curl: (7) Failed to connect to localhost port 5601: Connection refused

Indeed when I list the open ports, I see lots of things, but nothing on 5601:

root@my-server:/var/log# netstat -ntlp | grep LISTEN
tcp        0      0 0.0.0.0:9191            0.0.0.0:*               LISTEN      1412/uwsgi
tcp        0      0 0.0.0.0:5355            0.0.0.0:*               LISTEN      1413/systemd-resolv
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      15924/nginx: master
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1519/sshd
tcp        0      0 0.0.0.0:3031            0.0.0.0:*               LISTEN      1412/uwsgi
tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN      1591/postgres
tcp6       0      0 :::5355                 :::*                    LISTEN      1413/systemd-resolv
tcp6       0      0 :::9200                 :::*                    LISTEN      16108/java
tcp6       0      0 :::9300                 :::*                    LISTEN      16108/java
tcp6       0      0 :::22                   :::*                    LISTEN      1519/sshd
tcp6       0      0 :::5432                 :::*                    LISTEN      1591/postgres

I'm not sure what else to try to troubleshoot Kibana, any ideas are really really appreciated!

Body:
Well I'm not really sure why, but this seemed to work after I rebooted the machine:

root@my-server:~# sudo reboot

after a minute I SSHed back in and voila:

root@my-server:~# netstat -ntlp | grep LISTEN
tcp        0      0 127.0.0.1:5601          0.0.0.0:*               LISTEN      1428/node
tcp        0      0 0.0.0.0:9191            0.0.0.0:*               LISTEN      1414/uwsgi
tcp        0      0 0.0.0.0:5355            0.0.0.0:*               LISTEN      1427/systemd-resolv
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1467/nginx: master
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1510/sshd
tcp        0      0 0.0.0.0:3031            0.0.0.0:*               LISTEN      1414/uwsgi
tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN      1578/postgres
tcp6       0      0 :::5355                 :::*                    LISTEN      1427/systemd-resolv
tcp6       0      0 :::9200                 :::*                    LISTEN      2011/java
tcp6       0      0 :::9300                 :::*                    LISTEN      2011/java
tcp6       0      0 :::22                   :::*                    LISTEN      1510/sshd
tcp6       0      0 :::5432                 :::*                    LISTEN      1578/postgres

¯_(ツ)_/¯


来源: stackexchange

问:
Capybara not working with mini-test and rails. Keep getting "uninitialized constant Capybara::Minitest::Capybara"
I know this usually means something is missing by way of a require, but I can't figure it out. Here's my test_helper.rb:

```<code>ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment", __FILE__)
require "rails/test_help"
require "minitest/rails"
require 'capybara/rails'
require 'capybara/minitest'

# To add Capybara feature tests add `gem "minitest-rails-capybara"`
# to the test group in the Gemfile and uncomment the following:

require 'minitest/rails/capybara'
</code>```

and a portion of my Gemfile.lock

```<code>minitest-capybara (0.8.2)
  capybara (~> 2.2)
  minitest (~> 5.0)
  rake
minitest-metadata (0.6.0)
  minitest (>= 4.7, < 6.0)
minitest-rails (3.0.0)
  minitest (~> 5.8)
  railties (~> 5.0)
minitest-rails-capybara (3.0.1)
  capybara (~> 2.7)
  minitest-capybara (~> 0.8)
  minitest-metadata (~> 0.6)
  minitest-rails (~> 3.0)
</code>```

If I comment out this line:

```<code>require 'minitest/rails/capybara'
</code>```

I get:

```<code>undefined method `feature' for main:Object (NoMethodError)
</code>```

While trying to test a feature.

Anyone have any ideas?

Full trace for gigs:

```<code>ruby test/features/can_access_home_test.rb
/usr/local/bundle/gems/minitest-capybara-0.8.2/lib/capybara/assertions.rb:37:in `<module:Assertions>': uninitialized constant Capybara::Minitest::Capybara (NameError)
    from /usr/local/bundle/gems/minitest-capybara-0.8.2/lib/capybara/assertions.rb:2:in `<module:Capybara>'
    from /usr/local/bundle/gems/minitest-capybara-0.8.2/lib/capybara/assertions.rb:1:in `<top (required)>'
    from /usr/local/bundle/gems/minitest-capybara-0.8.2/lib/minitest/capybara.rb:23:in `<top (required)>'
    from /usr/local/bundle/gems/minitest-capybara-0.8.2/lib/minitest-capybara.rb:2:in `<top (required)>'
    from /usr/local/bundle/gems/minitest-rails-capybara-3.0.1/lib/minitest/rails/capybara.rb:3:in `<top (required)>'
    from /usr/src/app/test/test_helper.rb:11:in `<top (required)>'
    from test/features/can_access_home_test.rb:1:in `require_relative'
    from test/features/can_access_home_test.rb:1:in `<main>'
</code>```

答:
Try taking out these lines from your test_helper.rb:</p>

```<code>require "minitest/rails"
require 'capybara/rails'
require 'capybara/minitest'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know this usually means something is missing by way of a require, but I can't figure it out. Here's my test_helper.rb:

ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment", __FILE__)
require "rails/test_help"
require "minitest/rails"
require 'capybara/rails'
require 'capybara/minitest'

# To add Capybara feature tests add `gem "minitest-rails-capybara"`
# to the test group in the Gemfile and uncomment the following:

require 'minitest/rails/capybara'

and a portion of my Gemfile.lock

minitest-capybara (0.8.2)
  capybara (~> 2.2)
  minitest (~> 5.0)
  rake
minitest-metadata (0.6.0)
  minitest (>= 4.7, < 6.0)
minitest-rails (3.0.0)
  minitest (~> 5.8)
  railties (~> 5.0)
minitest-rails-capybara (3.0.1)
  capybara (~> 2.7)
  minitest-capybara (~> 0.8)
  minitest-metadata (~> 0.6)
  minitest-rails (~> 3.0)

If I comment out this line:

require 'minitest/rails/capybara'

I get:

undefined method `feature' for main:Object (NoMethodError)

While trying to test a feature.

Anyone have any ideas?

Full trace for gigs:

ruby test/features/can_access_home_test.rb
/usr/local/bundle/gems/minitest-capybara-0.8.2/lib/capybara/assertions.rb:37:in `<module:Assertions>': uninitialized constant Capybara::Minitest::Capybara (NameError)
    from /usr/local/bundle/gems/minitest-capybara-0.8.2/lib/capybara/assertions.rb:2:in `<module:Capybara>'
    from /usr/local/bundle/gems/minitest-capybara-0.8.2/lib/capybara/assertions.rb:1:in `<top (required)>'
    from /usr/local/bundle/gems/minitest-capybara-0.8.2/lib/minitest/capybara.rb:23:in `<top (required)>'
    from /usr/local/bundle/gems/minitest-capybara-0.8.2/lib/minitest-capybara.rb:2:in `<top (required)>'
    from /usr/local/bundle/gems/minitest-rails-capybara-3.0.1/lib/minitest/rails/capybara.rb:3:in `<top (required)>'
    from /usr/src/app/test/test_helper.rb:11:in `<top (required)>'
    from test/features/can_access_home_test.rb:1:in `require_relative'
    from test/features/can_access_home_test.rb:1:in `'

Body:
Try taking out these lines from your test_helper.rb:

require "minitest/rails"
require 'capybara/rails'
require 'capybara/minitest'


问:
error rsqlite_fetch in R
I have a "CSV" format dataset with 28 variables and 7400 observation. I import the dataset in R with the name of "films" and I want to clean that. In this way, I use "sqldf" and "SQLite" libraries. But when I use "sqldf" I receive the warnings and consequently my dataset does not update too:

```<code>color   director_name   num_critic_for_reviews  duration
Color   James Cameron   723                       178
Color   Gore Verbinski  302                       169
Color   Sam Mendes      602                       148
</code>```

the code I have used is as below:

```<code>library(RSQLite)
library(sqldf)
db <- dbConnect(SQLite(), "tempdb")

dbWriteTable(db,"films",films, overwrite=TRUE)

d <- sqldf(c('update films set movie_title=lower(movie_title)', 'select * from films'))
d <- sqldf(c('update films set actor_3_name=lower(actor_3_name)', 'select * from films'))
d <- sqldf(c('update films set actor_2_name=lower(actor_2_name)', 'select * from films'))
d <- sqldf(c('update films set actor_1_name=lower(actor_1_name)', 'select * from films'))
d <- sqldf(c('update films set director_name=lower(director_name)', 'select * from films'))

# Warning message:
# In rsqlite_fetch(res@ptr, n = n) :
#   Don't need to call dbFetch() for statements, only for queries
</code>```

What is the problem?

答:
There are several problems at work here.

First:

```<code># Warning message:
# In rsqlite_fetch(res@ptr, n = n) :
#   Don't need to call dbFetch() for statements, only for queries
</code>```

This is a warning, not an error. In fact, it appears to be somewhat new issue in RSQLite, and is referenced in an open issue: https://github.com/r-dbi/RSQLite/issues/227.

(For cleanness, I'm removing it from the output in the rest of this answer, though it occurs with each non-select query.)

Second, RSQLite deals with a database, period. It has no opinion or awareness of variables within the R environment, so there is no suggestion that a variable in R is an immediate and perpetual representation of a database table. (There are similar methodologies using dbplyr that do do this, roughly speaking.)

In order to provide this type of tie between R and some form of SQL querying, there's sqldf that allows you to query against R variables as if they were actual SQL tables. When you do such a query, it grabs the data.frame as it currently looks, inserts it into a temporary database table (whether RSQLite or another), runs the SQL code, then returns what you need.

Third: despite this apparent tie, it is quite functional in that it does not produce side-effects within the R environment. That means that if you want to store the resulting data in a way that R can use, you need to explicitly capture the new table into an R variable.

For example:

```<code>library(sqldf)
(mt <- mtcars[1:5,1:5])
#                    mpg cyl disp  hp drat
# Mazda RX4         21.0   6  160 110 3.90
# Mazda RX4 Wag     21.0   6  160 110 3.90
# Datsun 710        22.8   4  108  93 3.85
# Hornet 4 Drive    21.4   6  258 110 3.08
# Hornet Sportabout 18.7   8  360 175 3.15
</code>```

After the update, the original data is untouched.

```<code>sqldf('update mt set cyl=5 where cyl>5')
mt
#                    mpg cyl disp  hp drat
# Mazda RX4         21.0   6  160 110 3.90
# Mazda RX4 Wag     21.0   6  160 110 3.90
# Datsun 710        22.8   4  108  93 3.85
# Hornet 4 Drive    21.4   6  258 110 3.08
# Hornet Sportabout 18.7   8  360 175 3.15
</code>```

You can get the data individually or in the same line by including a select * from ... in your call to sqldf:

```<code>mt2 <- sqldf(c('update mt set cyl=5 where cyl>5', 'select * from mt'))
mt2
#    mpg cyl disp  hp drat
# 1 21.0   5  160 110 3.90
# 2 21.0   5  160 110 3.90
# 3 22.8   4  108  93 3.85
# 4 21.4   5  258 110 3.08
# 5 18.7   5  360 175 3.15
</code>```

(In this case I saved it to mt2, but you could just have easily over-written it.)

All of this is discussed in various forms in the sqldf FAQ 8, "8. Why am I having problems with update?"

EDIT

There appear to be several misunderstandings about sqldf and such.

You are creating a db handle for direct SQL queries (not sqldf), but you never use it. As you'll see later, either (a) use dbExecute (and related functions) with the db handle, or (b) use sqldf, no need for dbConnect and friends.

When using sqldf, on each and every call to sqldf it does a complete copy of the current instance of the variable into a database. (This is both helpful and, at times, inefficient. With smaller datasets, the time lost is likely not felt, but still ...) So when you keep referring to the table films, it is ignoring the d you created, because it has no way to infer what you are trying to do outside of its call ... it just copies, queries, and discards.

```<code># assuming this is something like what you do ... but it doesn't matter
films <- read.csv("films.csv", ...)
#    `-<---<---<---<---<---<---<---<---<---<---<---<---<---<---<-+-<--.
db <- dbConnect(SQLite(), "tempdb") # not used in sqldf          ^     \
dbWriteTable(db, "films", films, overwrite=TRUE) # never used    ^      \
#                             `--- is referring to --->--->--->--'       \
d <- sqldf(c('update films set movie_title=lower(movie_title)', #         \
                             'select * from films')) #                     \
#                        \                      `--- (internal to sqldf)    ^
#                         `--- refers to the original 'films' --->--->--->--'
</code>```

Option 1, use the RSQLite functions, not sqldf:

```<code>db <- dbConnect(SQLite(), "tempdb")
dbWriteTable(db,"films",films, overwrite=TRUE)
dbExecute(db, 'update films set actor_3_name=lower(actor_3_name)')
#        `--- repeat for all updates
films <- dbGetQuery(db, 'select * from films')
</code>```

Option 2, (not my preferred) use the variable created on the previous line:

```<code>films <- read.csv("films.csv", ...)
#   `--<---<---<---<---<---<---<---<---<---<---<---<---<---<---<---<---<-.
d <- sqldf(c('update films set movie_title=lower(movie_title)', #         \
                             'select * from films')) #                     \
#\                        \                      `--- (internal to sqldf)    ^
# \                        `--- refers to original 'films' --->--->--->--->--'
#  `--<---<---<---<---<---<---<---<---<---<---<---<---<---<---<---<--.
d <- sqldf(c('update d set actor_3_name=lower(actor_3_name)', #       \
                             'select * from d')) #                     \
#                    \                      `--- (internal to sqldf)    ^
#                     `--- refers to previously-created 'd' --->--->--->'
#                         (repeat for other updates)
</code>```

Option 3, always reference/overwrite the original films variable:

```<code>films <- read.csv("films.csv", ...)
#   `--<---<---<---<---<---<---<---<---<---<---<---+--<---<---<---<---<---.
films <- sqldf(c('update films set movie_title=lower(movie_title)', #      \
                              'select * from films')) #                     \
#   \                        \                   `--- (internal to sqldf)    ^
#    \                        ` --- refers to the first 'films' -->--->--->--'
#     `-<---<---<---<---<---<---<---<---<---<---<---+--<---<---<---<---<--.
films <- sqldf(c('update films set actor_3_name=lower(actor_3_name)', #    \
                              'select * from films')) #                     \
#                            \                   `--- (internal to sqldf)    ^
#                             ` --- refers to the second 'films' -->--->--->-'
#                              (repeat for other updates)
</code>```

sqldf inefficiencies. Each time you make a call to sqldf, it copies the entire dataset into a temporary table. Every. Time. You can reduce some of the overhead by combining all query strings into a single call, like so:

```<code>films <- read.csv("films.csv", ...)
films <- sqldf(c('update films set actor_3_name=lower(actor_3_name)',
                 'update films set actor_2_name=lower(actor_2_name)',
                 'update films set actor_1_name=lower(actor_1_name)',
                 'update films set director_name=lower(director_name)',
                 'select * from films'))
</code>```

SQL inefficiencies. Your original code may be simplified for the question (which is fine), but if not then here goes. Since you do not appear to be conditioning your updates at all, you can combine the data-cleaning into one update. (This can be used with dbExecute as well.)

```<code>films <- read.csv("films.csv", ...)
films <- sqldf(c('update films set actor_3_name=lower(actor_3_name),
                                   actor_3_name=lower(actor_3_name),
                                   actor_2_name=lower(actor_2_name),
                                   actor_1_name=lower(actor_1_name),
                                   director_name=lower(director_name)',
                 'select * from films'))
</code>```

Do you really need SQL? This can be done quite easily/quickly in R:

```<code>library(sqldf)
(mt <- mtcars[1:5,1:5])
#                    mpg cyl disp  hp drat
# Mazda RX4         21.0   6  160 110 3.90
# Mazda RX4 Wag     21.0   6  160 110 3.90
# Datsun 710        22.8   4  108  93 3.85
# Hornet 4 Drive    21.4   6  258 110 3.08
# Hornet Sportabout 18.7   8  360 175 3.15
</code>```0

Title: error rsqlite_fetch in R

Body:
I have a "CSV" format dataset with 28 variables and 7400 observation. I import the dataset in R with the name of "films" and I want to clean that. In this way, I use "sqldf" and "SQLite" libraries. But when I use "sqldf" I receive the warnings and consequently my dataset does not update too:

color   director_name   num_critic_for_reviews  duration
Color   James Cameron   723                       178
Color   Gore Verbinski  302                       169
Color   Sam Mendes      602                       148

the code I have used is as below:

library(RSQLite)
library(sqldf)
db <- dbConnect(SQLite(), "tempdb")

dbWriteTable(db,"films",films, overwrite=TRUE)

d <- sqldf(c('update films set movie_title=lower(movie_title)', 'select * from films'))
d <- sqldf(c('update films set actor_3_name=lower(actor_3_name)', 'select * from films'))
d <- sqldf(c('update films set actor_2_name=lower(actor_2_name)', 'select * from films'))
d <- sqldf(c('update films set actor_1_name=lower(actor_1_name)', 'select * from films'))
d <- sqldf(c('update films set director_name=lower(director_name)', 'select * from films'))

# Warning message:
# In rsqlite_fetch(res@ptr, n = n) :
#   Don't need to call dbFetch() for statements, only for queries

What is the problem?

Body:
There are several problems at work here.

First:

# Warning message:
# In rsqlite_fetch(res@ptr, n = n) :
#   Don't need to call dbFetch() for statements, only for queries

This is a warning, not an error. In fact, it appears to be somewhat new issue in RSQLite, and is referenced in an open issue: https://github.com/r-dbi/RSQLite/issues/227.

(For cleanness, I'm removing it from the output in the rest of this answer, though it occurs with each non-select query.)

Second, RSQLite deals with a database, period. It has no opinion or awareness of variables within the R environment, so there is no suggestion that a variable in R is an immediate and perpetual representation of a database table. (There are similar methodologies using dbplyr that do do this, roughly speaking.)

In order to provide this type of tie between R and some form of SQL querying, there's sqldf that allows you to query against R variables as if they were actual SQL tables. When you do such a query, it grabs the data.frame as it currently looks, inserts it into a temporary database table (whether RSQLite or another), runs the SQL code, then returns what you need.

Third: despite this apparent tie, it is quite functional in that it does not produce side-effects within the R environment. That means that if you want to store the resulting data in a way that R can use, you need to explicitly capture the new table into an R variable.

For example:

library(sqldf)
(mt <- mtcars[1:5,1:5])
#                    mpg cyl disp  hp drat
# Mazda RX4         21.0   6  160 110 3.90
# Mazda RX4 Wag     21.0   6  160 110 3.90
# Datsun 710        22.8   4  108  93 3.85
# Hornet 4 Drive    21.4   6  258 110 3.08
# Hornet Sportabout 18.7   8  360 175 3.15

After the update, the original data is untouched.

sqldf('update mt set cyl=5 where cyl>5')
mt
#                    mpg cyl disp  hp drat
# Mazda RX4         21.0   6  160 110 3.90
# Mazda RX4 Wag     21.0   6  160 110 3.90
# Datsun 710        22.8   4  108  93 3.85
# Hornet 4 Drive    21.4   6  258 110 3.08
# Hornet Sportabout 18.7   8  360 175 3.15

You can get the data individually or in the same line by including a select * from ... in your call to sqldf:

mt2 <- sqldf(c('update mt set cyl=5 where cyl>5', 'select * from mt'))
mt2
#    mpg cyl disp  hp drat
# 1 21.0   5  160 110 3.90
# 2 21.0   5  160 110 3.90
# 3 22.8   4  108  93 3.85
# 4 21.4   5  258 110 3.08
# 5 18.7   5  360 175 3.15

(In this case I saved it to mt2, but you could just have easily over-written it.)

All of this is discussed in various forms in the sqldf FAQ 8, "8. Why am I having problems with update?"

EDIT

There appear to be several misunderstandings about sqldf and such.

You are creating a db handle for direct SQL queries (not sqldf), but you never use it. As you'll see later, either (a) use dbExecute (and related functions) with the db handle, or (b) use sqldf, no need for dbConnect and friends.

When using sqldf, on each and every call to sqldf it does a complete copy of the current instance of the variable into a database. (This is both helpful and, at times, inefficient. With smaller datasets, the time lost is likely not felt, but still ...) So when you keep referring to the table films, it is ignoring the d you created, because it has no way to infer what you are trying to do outside of its call ... it just copies, queries, and discards.

# assuming this is something like what you do ... but it doesn't matter
films <- read.csv("films.csv", ...)
#    `-<---<---<---<---<---<---<---<---<---<---<---<---<---<---<-+-<--.
db <- dbConnect(SQLite(), "tempdb") # not used in sqldf          ^     \
dbWriteTable(db, "films", films, overwrite=TRUE) # never used    ^      \
#                             `--- is referring to --->--->--->--'       \
d <- sqldf(c('update films set movie_title=lower(movie_title)', #         \
                             'select * from films')) #                     \
#                        \                      `--- (internal to sqldf)    ^
#                         `--- refers to the original 'films' --->--->--->--'

Option 1, use the RSQLite functions, not sqldf:

db <- dbConnect(SQLite(), "tempdb")
dbWriteTable(db,"films",films, overwrite=TRUE)
dbExecute(db, 'update films set actor_3_name=lower(actor_3_name)')
#        `--- repeat for all updates
films <- dbGetQuery(db, 'select * from films')

Option 2, (not my preferred) use the variable created on the previous line:

films <- read.csv("films.csv", ...)
#   `--<---<---<---<---<---<---<---<---<---<---<---<---<---<---<---<---<-.
d <- sqldf(c('update films set movie_title=lower(movie_title)', #         \
                             'select * from films')) #                     \
#\                        \                      `--- (internal to sqldf)    ^
# \                        `--- refers to original 'films' --->--->--->--->--'
#  `--<---<---<---<---<---<---<---<---<---<---<---<---<---<---<---<--.
d <- sqldf(c('update d set actor_3_name=lower(actor_3_name)', #       \
                             'select * from d')) #                     \
#                    \                      `--- (internal to sqldf)    ^
#                     `--- refers to previously-created 'd' --->--->--->'
#                         (repeat for other updates)

Option 3, always reference/overwrite the original films variable:

films <- read.csv("films.csv", ...)
#   `--<---<---<---<---<---<---<---<---<---<---<---+--<---<---<---<---<---.
films <- sqldf(c('update films set movie_title=lower(movie_title)', #      \
                              'select * from films')) #                     \
#   \                        \                   `--- (internal to sqldf)    ^
#    \                        ` --- refers to the first 'films' -->--->--->--'
#     `-<---<---<---<---<---<---<---<---<---<---<---+--<---<---<---<---<--.
films <- sqldf(c('update films set actor_3_name=lower(actor_3_name)', #    \
                              'select * from films')) #                     \
#                            \                   `--- (internal to sqldf)    ^
#                             ` --- refers to the second 'films' -->--->--->-'
#                              (repeat for other updates)

sqldf inefficiencies. Each time you make a call to sqldf, it copies the entire dataset into a temporary table. Every. Time. You can reduce some of the overhead by combining all query strings into a single call, like so:

films <- read.csv("films.csv", ...)
films <- sqldf(c('update films set actor_3_name=lower(actor_3_name)',
                 'update films set actor_2_name=lower(actor_2_name)',
                 'update films set actor_1_name=lower(actor_1_name)',
                 'update films set director_name=lower(director_name)',
                 'select * from films'))

SQL inefficiencies. Your original code may be simplified for the question (which is fine), but if not then here goes. Since you do not appear to be conditioning your updates at all, you can combine the data-cleaning into one update. (This can be used with dbExecute as well.)

films <- read.csv("films.csv", ...)
films <- sqldf(c('update films set actor_3_name=lower(actor_3_name),
                                   actor_3_name=lower(actor_3_name),
                                   actor_2_name=lower(actor_2_name),
                                   actor_1_name=lower(actor_1_name),
                                   director_name=lower(director_name)',
                 'select * from films'))

Do you really need SQL? This can be done quite easily/quickly in R:

films <- read.csv("films.csv", ...)
films <- within(films, {
  actor_3_name <- tolower(actor_3_name)
  actor_2_name <- tolower(actor_2_name)
  actor_1_name <- tolower(actor_1_name)
  director_name <- tolower(director_name)
})


问:
How are people handling user authentication for web services?
I'm creating a web service to expose some data via publicly accessible APIs. At a high level, what mechanisms are people using to secure their APIs to ensure that a valid, authenticated user is making the call?

The service will be C#, the consumer could be anything (Facebook or iPhone app as well as a website) so Microsoft only solutions are out.

It's not a new problem so I assume there are some standard practices in place to deal with it but my google-fu is failing me on this one. Can the collective point me to any resources? Thanks.

答:
We use the WS-Security.  It's a published standard so any client (in theory) can use it to send authentication credentials.

Here's another SO question that covers using WS-Security with C#.

How to use WS-Security in C#?

ContentLicense: CC BY-SA 2.5


问:
Expected argument of type "AppBundle\Entity\Sales", "DateTime" given
Regardless of date format used (Symfony 3.3.14), the error in title appears on submitting a form with the following field definition:

```<code>use Symfony\Component\Form\Extension\Core\Type\DateType;
...

    $builder
        ->add('sales', DateType::class, [
            'widget' => 'single_text',
            'html5' => false,
            'attr' => ['class' => 'js-datepicker'],
            'format' => 'mm-dd-yyyy',
            ])
</code>```

and with the associated javascript

```<code>$('.js-datepicker').datepicker({
    format: 'mm-dd-yyyy'
});
</code>```

as called in the template with

```<code>{{ form_row(form.sales) }}
...
    {%  block javascripts %}
        {{ parent() }}
        <script src="/js/bootstrap-datepicker.js"></script>
        <script src="/js/tickets.js"></script>
    {%  endblock javascripts %}
</code>```

答:
DOH!

The entity definition that included the sales field some how got

```<code>public function setSales(Sales $sales)
{
    $this->sales = $sales;

    return $this;
}
</code>```

when it should have been

```<code>public function setSales($sales)
{
    $this->sales = $sales;

    return $this;
}
</code>```

Body:
Regardless of date format used (Symfony 3.3.14), the error in title appears on submitting a form with the following field definition:

use Symfony\Component\Form\Extension\Core\Type\DateType;
...

    $builder
        ->add('sales', DateType::class, [
            'widget' => 'single_text',
            'html5' => false,
            'attr' => ['class' => 'js-datepicker'],
            'format' => 'mm-dd-yyyy',
            ])

and with the associated javascript

$('.js-datepicker').datepicker({
    format: 'mm-dd-yyyy'
});

as called in the template with

{{ form_row(form.sales) }}
...
    {%  block javascripts %}
        {{ parent() }}

    {%  endblock javascripts %}

Body:
DOH!

The entity definition that included the sales field some how got

public function setSales(Sales $sales)
{
    $this->sales = $sales;

    return $this;
}

when it should have been

public function setSales($sales)
{
    $this->sales = $sales;

    return $this;
}


问:
Decimal format conversion from one locale to another locale(en_US) in java
I have a decimal in a string format in a locale that is not 'en_US'. I would like to convert it to a decimal in 'en_US' locale.

Eg: "123.345.123,45" -> "123345123.45" or "123,345,123.45"

"123 345,45"  -> "123345.45" or "123,345.45"

"123.345"   -> "123345" or "123,345"

答:
It seems like NumberFormat will do what you're looking for.

Found this snippet in the oracle documentation:

```<code>static public void displayNumber(Locale currentLocale) {

Integer quantity = new Integer(123456);
Double amount = new Double(345987.246);
NumberFormat numberFormatter;
String quantityOut;
String amountOut;

numberFormatter = NumberFormat.getNumberInstance(currentLocale);
quantityOut = numberFormatter.format(quantity);
amountOut = numberFormatter.format(amount);
System.out.println(quantityOut + "   " + currentLocale.toString());
System.out.println(amountOut + "   " + currentLocale.toString());
}
</code>```

This example prints the following; it shows how the format of the same number varies with Locale:

123 456   fr_FR

345 987,246   fr_FR

123.456   de_DE

345.987,246   de_DE

123,456   en_US 3

45,987.246   en_US

Here's the link that content is from:

https://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html

In order to convert a formatted number string from one Locale to another, you must know the Locale from which the string was generated.  From there you can use NumberFormat.parse to convert the string back to a Number.  Then use the target Locale to create another NumberFormat and use the .format method to change the string  representation.

```<code>static public String displayNumber(String startValue, Locale startLocale, Locale endLocale) throws ParseException {
    NumberFormat parser = NumberFormat.getNumberInstance(startLocale);
    NumberFormat formatter = NumberFormat.getNumberInstance(endLocale);

    Number rawNumber = parser.parse(startValue);

    return formatter.format(rawNumber);
}
</code>```

Body:
It seems like NumberFormat will do what you're looking for.

Found this snippet in the oracle documentation:

static public void displayNumber(Locale currentLocale) {

Integer quantity = new Integer(123456);
Double amount = new Double(345987.246);
NumberFormat numberFormatter;
String quantityOut;
String amountOut;

numberFormatter = NumberFormat.getNumberInstance(currentLocale);
quantityOut = numberFormatter.format(quantity);
amountOut = numberFormatter.format(amount);
System.out.println(quantityOut + "   " + currentLocale.toString());
System.out.println(amountOut + "   " + currentLocale.toString());
}

This example prints the following; it shows how the format of the same number varies with Locale:

123 456   fr_FR

345 987,246   fr_FR

123.456   de_DE

345.987,246   de_DE

123,456   en_US 3

45,987.246   en_US

Here's the link that content is from:

https://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html

In order to convert a formatted number string from one Locale to another, you must know the Locale from which the string was generated.  From there you can use NumberFormat.parse to convert the string back to a Number.  Then use the target Locale to create another NumberFormat and use the .format method to change the string  representation.

static public String displayNumber(String startValue, Locale startLocale, Locale endLocale) throws ParseException {
    NumberFormat parser = NumberFormat.getNumberInstance(startLocale);
    NumberFormat formatter = NumberFormat.getNumberInstance(endLocale);

    Number rawNumber = parser.parse(startValue);

    return formatter.format(rawNumber);
}


问:
How to specify the order of icons in an explorer view in a VSCode extension?
In my extension I have some buttons on the bar of an explorer view:

How can I specify the order in which the buttons will appear?

I tried changing in the package.json the order of the commands in the commands property:

```<code>"commands": [
  {
    "command": "codeFragments.exportFragments",
    "title": "Export all fragments to Json",
    "icon": {
      "light": "images/icon-export-light.png",
      "dark": "images/icon-export-dark.png"
    }
  },
  {
    "command": "codeFragments.importFragments",
    "title": "Import fragments from Json",
    "icon": {
      "light": "images/icon-import-light.png",
      "dark": "images/icon-import-dark.png"
    }
  },
  {
    "command": "codeFragments.deleteAllFragments",
    "title": "Delete all fragments",
    "icon": {
      "light": "images/icon-delete-light.png",
      "dark": "images/icon-delete-dark.png"
    }
  }
],
</code>```

Also tried reordering in the part where I specify the UI, in the view/title property:

```<code>"view/title": [
  {
    "command": "codeFragments.exportFragments",
    "when": "view == codeFragments",
    "group": "navigation"
  },
  {
    "command": "codeFragments.importFragments",
    "when": "view == codeFragments",
    "group": "navigation"
  },
  {
    "command": "codeFragments.deleteAllFragments",
    "when": "view == codeFragments",
    "group": "navigation"
  }
],
</code>```

And also tried to change the order in the part when I'm pushing the command subscriptions:

```<code>context.subscriptions.push(
  vscode.commands.registerCommand('codeFragments.exportFragments', exportFragments));
context.subscriptions.push(
  vscode.commands.registerCommand('codeFragments.importFragments', importFragments));
context.subscriptions.push(
  vscode.commands.registerCommand('codeFragments.deleteAllFragments', deleteAllFragments));
</code>```

But none of these approaches seem to affect the order, the buttons always appear in a seemingly incidental order.

What's the proper way to specify the order?

答:
After debugging the vscode source for a while, I found the solution, the sorting is happening here: https://github.com/Microsoft/vscode/blob/master/src/vs/platform/actions/electron-browser/menusExtensionPoint.ts#L365

Basically the order number can be appended to the group name of the command after an @ symbol, so I had to do the following.

```<code>"view/title": [
  {
    "command": "codeFragments.exportFragments",
    "when": "view == codeFragments",
    "group": "navigation@0"
  },
  {
    "command": "codeFragments.importFragments",
    "when": "view == codeFragments",
    "group": "navigation@1"
  },
  {
    "command": "codeFragments.deleteAllFragments",
    "when": "view == codeFragments",
    "group": "navigation@2"
  }
],
</code>```

And after finding this, I tried to google again, and it turns out this was properly documented already, but somehow I missed it when searching for it the first time: https://code.visualstudio.com/docs/extensionAPI/extension-points#_sorting-inside-groups

Body:
In my extension I have some buttons on the bar of an explorer view:

How can I specify the order in which the buttons will appear?

I tried changing in the package.json the order of the commands in the commands property:

"commands": [
  {
    "command": "codeFragments.exportFragments",
    "title": "Export all fragments to Json",
    "icon": {
      "light": "images/icon-export-light.png",
      "dark": "images/icon-export-dark.png"
    }
  },
  {
    "command": "codeFragments.importFragments",
    "title": "Import fragments from Json",
    "icon": {
      "light": "images/icon-import-light.png",
      "dark": "images/icon-import-dark.png"
    }
  },
  {
    "command": "codeFragments.deleteAllFragments",
    "title": "Delete all fragments",
    "icon": {
      "light": "images/icon-delete-light.png",
      "dark": "images/icon-delete-dark.png"
    }
  }
],

Also tried reordering in the part where I specify the UI, in the view/title property:

"view/title": [
  {
    "command": "codeFragments.exportFragments",
    "when": "view == codeFragments",
    "group": "navigation"
  },
  {
    "command": "codeFragments.importFragments",
    "when": "view == codeFragments",
    "group": "navigation"
  },
  {
    "command": "codeFragments.deleteAllFragments",
    "when": "view == codeFragments",
    "group": "navigation"
  }
],

And also tried to change the order in the part when I'm pushing the command subscriptions:

context.subscriptions.push(
  vscode.commands.registerCommand('codeFragments.exportFragments', exportFragments));
context.subscriptions.push(
  vscode.commands.registerCommand('codeFragments.importFragments', importFragments));
context.subscriptions.push(
  vscode.commands.registerCommand('codeFragments.deleteAllFragments', deleteAllFragments));

But none of these approaches seem to affect the order, the buttons always appear in a seemingly incidental order.

What's the proper way to specify the order?

Body:
After debugging the vscode source for a while, I found the solution, the sorting is happening here: https://github.com/Microsoft/vscode/blob/master/src/vs/platform/actions/electron-browser/menusExtensionPoint.ts#L365

Basically the order number can be appended to the group name of the command after an @ symbol, so I had to do the following.

"view/title": [
  {
    "command": "codeFragments.exportFragments",
    "when": "view == codeFragments",
    "group": "navigation@0"
  },
  {
    "command": "codeFragments.importFragments",
    "when": "view == codeFragments",
    "group": "navigation@1"
  },
  {
    "command": "codeFragments.deleteAllFragments",
    "when": "view == codeFragments",
    "group": "navigation@2"
  }
],

And after finding this, I tried to google again, and it turns out this was properly documented already, but somehow I missed it when searching for it the first time: https://code.visualstudio.com/docs/extensionAPI/extension-points#_sorting-inside-groups


问:
Change value of position in a vector + automatically create that position & increase vector-range if needed
The basic question is above, just an quick example to illustrate:

Let’s say I wanna roll a 6-sided dice until I get a 4 and then play this “game” 10 times.

Now I want to get a very basic probability distribution of how many throws are needed to get a 4. So e.g. in 2 games I needed only 1 throw, in 4 games  three throws, in 3 games 4 throws, and in 1 game 78 throws. So before playing I never actually know how many throws are needed, the game could go on endlessly.

To simplify record-keeping I want to use a vector, where the position/index of the vector indicates the number of throws needed to get a 4 and the value of the position says how often this many throws were needed. So such a vector for earlier example would look sth. like this: {0, 2, 0, 4, 3, 0, [another 72 zeros), 1}.

How would I code this in C++?

(I’m pretty sure that something similar must have been asked before, but couldn’t find a matching question. Also I’m just beginning to learn C++, so please don’t invoke very technical concepts if they aren’t needed to understand the solution.)

```<code>C++-Code/Pseudocode
vector<int> recordvec = {0};
for (1 to 10){
    game();
    recordvec[game.throwsneededtowin()]=recordvec[game.throwsneededtowin()] +1
    //How to make sure that I don't get an out-of-range error here if game.throwsneededtowin() is e.g. 1464?
}
print recordvec
</code>```

答:
Changing to std::vectoras OP requested

```<code>#include <iostream>
#include <vector>
#include <ctime>

int main()
{
    std::vector<int> stats;
    std::srand(static_cast<unsigned int>(std::time(0)));

    for (int i = 0; i < 10; ++i)
    {
        int is4;
        size_t throws = 0;
        do
        {
            is4 = int(std::rand() % 6 + 1 == 4);
            if (throws < stats.size())
                stats[throws] += is4;
            else
                stats.push_back(is4);
            ++throws;
        }
        while (!is4);
    }

    for (auto const &stat : stats)
        std::cout << stat << " ";

    std::cout << std::endl;

    system("pause");
    return 0;
}
</code>```

Body:
The basic question is above, just an quick example to illustrate:

Let’s say I wanna roll a 6-sided dice until I get a 4 and then play this “game” 10 times.

Now I want to get a very basic probability distribution of how many throws are needed to get a 4. So e.g. in 2 games I needed only 1 throw, in 4 games  three throws, in 3 games 4 throws, and in 1 game 78 throws. So before playing I never actually know how many throws are needed, the game could go on endlessly.

To simplify record-keeping I want to use a vector, where the position/index of the vector indicates the number of throws needed to get a 4 and the value of the position says how often this many throws were needed. So such a vector for earlier example would look sth. like this: {0, 2, 0, 4, 3, 0, [another 72 zeros), 1}.

How would I code this in C++?

(I’m pretty sure that something similar must have been asked before, but couldn’t find a matching question. Also I’m just beginning to learn C++, so please don’t invoke very technical concepts if they aren’t needed to understand the solution.)

C++-Code/Pseudocode
vector<int> recordvec = {0};
for (1 to 10){
    game();
    recordvec[game.throwsneededtowin()]=recordvec[game.throwsneededtowin()] +1
    //How to make sure that I don't get an out-of-range error here if game.throwsneededtowin() is e.g. 1464?
}
print recordvec

Body:
Changing to std::vectoras OP requested

#include <iostream>
#include <vector>
#include <ctime>

int main()
{
    std::vector<int> stats;
    std::srand(static_cast<unsigned int>(std::time(0)));

    for (int i = 0; i < 10; ++i)
    {
        int is4;
        size_t throws = 0;
        do
        {
            is4 = int(std::rand() % 6 + 1 == 4);
            if (throws < stats.size())
                stats[throws] += is4;
            else
                stats.push_back(is4);
            ++throws;
        }
        while (!is4);
    }

    for (auto const &stat : stats)
        std::cout << stat << " ";

    std::cout << std::endl;

    system("pause");
    return 0;
}


问:
wso2is 5.3 account recovery using other email addresses
I have just implemented wso2is 5.3 and I am looking at setting up the password and username recovery options.

Wso2is is set up with our Active Directory domain as the primary user store. In AD, the 'mail' attribute holds the user's primary email address, and 'otherMailbox' contains additional, external email addresses for the user.

I would like to use the email recovery, but we can't use the primary email, since the password for that account is the password they are trying to reset. We need to have the recovery process use one of the addresses in 'otherMail'.

I can't find anywhere in the documentation where you can define any option for what email is used for the recovery process.

Is the primary email the only one supported for password recovery? How can I tell the password and username recovery process to use a different email?

Thanks

Don

答:
The answer, it turns out, is to change the claim mapping for the email address claim in WSO2 to point to the otherMailbox attribute in AD. It properly deals with the multi-valued email address list and for the purposes of password recovery, it sends the notification to all of the listed email addresses.

We then created another claim called Campus Email and pointed it at the mail attribute in AD.

There doesn't seem to be any negative issue with having 'our' email not be the 'primary' email.

Don


问:
How to slice particular values from a string using regular expression in JavaScript or Java
How do I slice, and get only string values excluding characters inside {} braces.

I'm able to get characters inside curly braces, but how to get contents outside the curly braces?

I have a string like this:

name is {response.vital.name} and disease is {response.vital.some} and drug is {response.vital.dis}

I want output array like this:

["the name is","and disease is","and drug is"]

答:
Sub-Strings Outside Bracketed Sub-Strings:

If you want all sub-strings outside of the curly braces then you can use the String.split() method with a simple Regular Expression:

```<code>String strg = "name is {response.vital.name} and disease is " +
               "{response.vital.some} and drug is {response.vital.dis}";
String[] array = strg.split("\\{.*?\\}");
</code>```

and to simply display the sub-strings within the array to console:

```<code>System.out.println(Arrays.toString(array));
</code>```

Console output will be:

```<code>[name is ,  and disease is ,  and drug is]
</code>```

Regular Expression Explanation:

\\ matches the character \ literally (case sensitive). We need to apply this escape character since all the brackets or braces we may want to work against are RegEx special characters and must be escaped in order to use them as literal characters. And, because the Regular Expression is a string we need to escape the escape character \\ to make it legal. You can not place a single escape character into a Java String.

{ matches the character { literally (case sensitive).

.*? matches any character (except for line terminators).

*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy).

\\ matches the character \ literally (case sensitive). Again we need to escape the following close bracket.

} matches the character } literally (case sensitive).

You could create a method to do this and accommodate any type of brace:

```<code>/**
 * Retrieves all sub-strings on either side of the supplied open brace and close brace.
 * Everything within braces (including the braces) is excluded.<br>
 *
 * @param inputString (String) The string to process. if Null or Null String is
 * supplied then this method will throw a IllegalArgumentException exception.<br><br>
 *
 * @param openBrace (String) The Open Brace of which to ignore content within.
 * This can be Parentheses ( ( ), Square Brackets ( [ ), Curly Braces ( { ), or
 * Chevron Brackets ( < ). if Null or Null String is supplied then this method
 * will throw a IllegalArgumentException exception.<br>
 *
 * @param closeBrace (String) The Close Brace of which to ignore content within.
 * This can be Parentheses ( ) ), Square Brackets ( ] ), Curly Braces ( } ), or
 * Chevron Brackets ( > ). if Null or Null String is supplied then this method
 * will throw a IllegalArgumentException exception.<br>
 *
 * @param trimElements (Optional - Boolean - Default is false) If this optional
 * parameter is set to boolean true then the returned array elements will have
 * any leading or trailing white-spaces removed.<br>
 *
 * @return (Single Dimensional String Array) The detected sub-strings within a
 * 1D String Array.
 */
public String[] getSubstringsOutsideBraces(String inputString, String openBrace,
        String closeBrace, boolean... trimElements) {
    if (inputString == null || inputString.equals("") ||
        openBrace == null || openBrace.equals("") ||
        closeBrace == null || closeBrace.equals("")) {
        throw new IllegalArgumentException("\ngetSubstringsOutsideBraces() Method Error! "
                + "A method argument contains Null or Null String!\n");
    }
    boolean trim = false;
    if (trimElements.length > 0) {
        trim = trimElements[0];
    }
    String[] array = inputString.split(
        // Using Ternary Operator so as to apply an additional
        // RegEx to the split() method in order to remove the
        // need for IF/ELSE and a FOR loop to trim elements if
        // desired to do so.
       (trim) ? "\\s*\\" + openBrace + ".*?\\" + closeBrace +
             "\\s*" : "\\" + openBrace + ".*?\\" + closeBrace
    );
    return array;
}
</code>```

And to use this method you might do it this way:

```<code>String strg = "name is {response.vital.name} and disease is "
                + "{response.vital.some} and drug is "
                + "{response.vital.dis} More string content.";
String[] a = getSubstringsOutsideBraces(strg, "{", "}", true);
System.out.println(Arrays.toString(a));
</code>```

Console output will be:

```<code>[name is, and disease is, and drug is, More string content.]
</code>```

Get Strings Inside Bracketed Sub-Strings:

If what you are wanting to do is to collect the sub-string(s) or token(s) contained between Brackets or Braces within a string then a Pattern/Matcher approach works quite well for this task:

```<code>// Apply the Regular Expression to Pattern
Pattern regex = Pattern.compile("\\{(.*?)\\}");
// Run the pattern to see if there are any matches.
Matcher matcher = regex.matcher(inputString);

// Establish a String List Object to hold any matches.
List<String> list = new ArrayList<>();

// Retrieve any matches found and add to List.
while (matcher.find()) {
    list.add(matcher.group(1));
}
</code>```

Regular Expression Explanation:

Here is the explanation for the Regular Expression supplied to Pattern:

\\ matches the character \ literally (case sensitive). We need to apply this escape character since all the brackets or braces we may want to work against are RegEx special characters and must be escaped in order to use them as literal characters. And, because the Regular Expression is a string we need to escape the escape character \\ to make it legal. You can not place a single escape character into a Java String.

{ matches the character { literally (case sensitive).

1st Capturing Group (.*?) The Regular Expression indicates only 1 group.

.*? matches any character (except for line terminators).

*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy).

\\ matches the character \ literally (case sensitive). Again we need to escape the following close bracket.

} matches the character } literally (case sensitive).

For ease of use, this concept can also be placed into and used as a method, for example:

```<code>/**
 * Retrieves all sub-strings inside of the supplied open brace and close brace.
 * Everything outside of braces (including the braces) is excluded.<br>
 *
 * @param inputString (String) The string to process. if Null or Null String is
 * supplied then this method will throw a IllegalArgumentException exception.<br>
 *
 * @param openBrace (String) The Open Brace of which to get content within.
 * This can be Parentheses ( ( ), Square Brackets ( [ ), Curly Braces ( { ), or
 * Chevron Brackets ( < ). if Null or Null String is supplied then this method
 * will throw a IllegalArgumentException exception.<br>
 *
 * @param closeBrace (String) The Close Brace of which to get content within.
 * This can be Parentheses ( ) ), Square Brackets ( ] ), Curly Braces ( } ), or
 * Chevron Brackets ( > ). if Null or Null String is supplied then this method
 * will throw a IllegalArgumentException exception.<br>
 *
 * @param trimElements (Optional - Boolean - Default is false) If this optional
 * parameter is set to boolean true then the returned array elements will have
 * any leading or trailing white-spaces removed.<br>
 *
 * @return (Single Dimensional String Array) The detected sub-strings within a
 * 1D String Array.
 */
public String[] getSubstringsInsideBraces(String inputString, String openBrace,
        String closeBrace, boolean... trimElements) {
    // Make sure all arguments are supplied...
    if (inputString == null || inputString.equals("") ||
        openBrace == null || openBrace.equals("") ||
        closeBrace == null || closeBrace.equals("")) {
        throw new IllegalArgumentException("\ngetSubstringsInsideBraces() Method Error! "
                + "A method argument contains Null or Null String!\n");
    }
    // See if the option to trim bracketed content is desired.
    boolean trim = false;
    if (trimElements.length > 0) {
        trim = trimElements[0];
    }

    // Apply the Regular Expression to Pattern. The supplied
    // open and close braces are used within the expression.
    Pattern regex = Pattern.compile("\\" + openBrace + "(.*?)\\" + closeBrace);
    // Run the pattern to see if there are any matches.
    Matcher matcher = regex.matcher(inputString);
    // Establish a String List Object to hold any matches.
    List<String> list = new ArrayList<>();

    // Retrieve any matches found and add to List.
    while (matcher.find()) {
        // Using a ternary operator against whether or not to
        // Trim the matched item if desired before adding it
        // to the List. This saves on doing a IF/THEN/ELSE.
        list.add((trim) ? matcher.group(1).trim() : matcher.group(1));
    }

    // Convert the List to a 1D String Array
    if (list.isEmpty()) { return null; }
    String[] array = new String[list.size()];
    array = list.toArray(array);

    // Return the 1D String Array
    return array;
}
</code>```

To use the above method:

```<code>String strg = "name is {response.vital.name} and disease is "
                    + "{response.vital.some  } and drug is "
                    + "{response.vital.dis } More string content.";
String[] a = getSubstringsInsideBraces(strg, "{", "}", true);
System.out.println(Arrays.toString(a));
</code>```

The console output will be:

```<code>[response.vital.name, response.vital.some, response.vital.dis]
</code>```

If you want the above method to return a List object (which is what it fills to start with) then simply remove the conversion code within the method, instead of return array; use return list;, and declare your method to return a List<String> instead of String[]. Of course change the text within the JavaDoc above the method to reflect this change.

Body:
Sub-Strings Outside Bracketed Sub-Strings:

If you want all sub-strings outside of the curly braces then you can use the String.split() method with a simple Regular Expression:

String strg = "name is {response.vital.name} and disease is " +
               "{response.vital.some} and drug is {response.vital.dis}";
String[] array = strg.split("\\{.*?\\}");

and to simply display the sub-strings within the array to console:

System.out.println(Arrays.toString(array));

Console output will be:

[name is ,  and disease is ,  and drug is]

Regular Expression Explanation:

\\ matches the character \ literally (case sensitive). We need to apply this escape character since all the brackets or braces we may want to work against are RegEx special characters and must be escaped in order to use them as literal characters. And, because the Regular Expression is a string we need to escape the escape character \\ to make it legal. You can not place a single escape character into a Java String.

{ matches the character { literally (case sensitive).

.*? matches any character (except for line terminators).

*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy).

\\ matches the character \ literally (case sensitive). Again we need to escape the following close bracket.

} matches the character } literally (case sensitive).

You could create a method to do this and accommodate any type of brace:

/**
 * Retrieves all sub-strings on either side of the supplied open brace and close brace.
 * Everything within braces (including the braces) is excluded.<br>
 *
 * @param inputString (String) The string to process. if Null or Null String is
 * supplied then this method will throw a IllegalArgumentException exception.<br><br>
 *
 * @param openBrace (String) The Open Brace of which to ignore content within.
 * This can be Parentheses ( ( ), Square Brackets ( [ ), Curly Braces ( { ), or
 * Chevron Brackets ( &lt; ). if Null or Null String is supplied then this method
 * will throw a IllegalArgumentException exception.<br>
 *
 * @param closeBrace (String) The Close Brace of which to ignore content within.
 * This can be Parentheses ( ) ), Square Brackets ( ] ), Curly Braces ( } ), or
 * Chevron Brackets ( &gt; ). if Null or Null String is supplied then this method
 * will throw a IllegalArgumentException exception.<br>
 *
 * @param trimElements (Optional - Boolean - Default is false) If this optional
 * parameter is set to boolean true then the returned array elements will have
 * any leading or trailing white-spaces removed.<br>
 *
 * @return (Single Dimensional String Array) The detected sub-strings within a
 * 1D String Array.
 */
public String[] getSubstringsOutsideBraces(String inputString, String openBrace,
        String closeBrace, boolean... trimElements) {
    if (inputString == null || inputString.equals("") ||
        openBrace == null || openBrace.equals("") ||
        closeBrace == null || closeBrace.equals("")) {
        throw new IllegalArgumentException("\ngetSubstringsOutsideBraces() Method Error! "
                + "A method argument contains Null or Null String!\n");
    }
    boolean trim = false;
    if (trimElements.length > 0) {
        trim = trimElements[0];
    }
    String[] array = inputString.split(
        // Using Ternary Operator so as to apply an additional
        // RegEx to the split() method in order to remove the
        // need for IF/ELSE and a FOR loop to trim elements if
        // desired to do so.
       (trim) ? "\\s*\\" + openBrace + ".*?\\" + closeBrace +
             "\\s*" : "\\" + openBrace + ".*?\\" + closeBrace
    );
    return array;
}

And to use this method you might do it this way:

String strg = "name is {response.vital.name} and disease is "
                + "{response.vital.some} and drug is "
                + "{response.vital.dis} More string content.";
String[] a = getSubstringsOutsideBraces(strg, "{", "}", true);
System.out.println(Arrays.toString(a));

Console output will be:

[name is, and disease is, and drug is, More string content.]

Get Strings Inside Bracketed Sub-Strings:

If what you are wanting to do is to collect the sub-string(s) or token(s) contained between Brackets or Braces within a string then a Pattern/Matcher approach works quite well for this task:

// Apply the Regular Expression to Pattern
Pattern regex = Pattern.compile("\\{(.*?)\\}");
// Run the pattern to see if there are any matches.
Matcher matcher = regex.matcher(inputString);

// Establish a String List Object to hold any matches.
List<String> list = new ArrayList<>();

// Retrieve any matches found and add to List.
while (matcher.find()) {
    list.add(matcher.group(1));
}

Regular Expression Explanation:

Here is the explanation for the Regular Expression supplied to Pattern:

\\ matches the character \ literally (case sensitive). We need to apply this escape character since all the brackets or braces we may want to work against are RegEx special characters and must be escaped in order to use them as literal characters. And, because the Regular Expression is a string we need to escape the escape character \\ to make it legal. You can not place a single escape character into a Java String.

{ matches the character { literally (case sensitive).

1st Capturing Group (.*?) The Regular Expression indicates only 1 group.

.*? matches any character (except for line terminators).

*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy).

\\ matches the character \ literally (case sensitive). Again we need to escape the following close bracket.

} matches the character } literally (case sensitive).

For ease of use, this concept can also be placed into and used as a method, for example:

/**
 * Retrieves all sub-strings inside of the supplied open brace and close brace.
 * Everything outside of braces (including the braces) is excluded.<br>
 *
 * @param inputString (String) The string to process. if Null or Null String is
 * supplied then this method will throw a IllegalArgumentException exception.<br>
 *
 * @param openBrace (String) The Open Brace of which to get content within.
 * This can be Parentheses ( ( ), Square Brackets ( [ ), Curly Braces ( { ), or
 * Chevron Brackets ( &lt; ). if Null or Null String is supplied then this method
 * will throw a IllegalArgumentException exception.<br>
 *
 * @param closeBrace (String) The Close Brace of which to get content within.
 * This can be Parentheses ( ) ), Square Brackets ( ] ), Curly Braces ( } ), or
 * Chevron Brackets ( &gt; ). if Null or Null String is supplied then this method
 * will throw a IllegalArgumentException exception.<br>
 *
 * @param trimElements (Optional - Boolean - Default is false) If this optional
 * parameter is set to boolean true then the returned array elements will have
 * any leading or trailing white-spaces removed.<br>
 *
 * @return (Single Dimensional String Array) The detected sub-strings within a
 * 1D String Array.
 */
public String[] getSubstringsInsideBraces(String inputString, String openBrace,
        String closeBrace, boolean... trimElements) {
    // Make sure all arguments are supplied...
    if (inputString == null || inputString.equals("") ||
        openBrace == null || openBrace.equals("") ||
        closeBrace == null || closeBrace.equals("")) {
        throw new IllegalArgumentException("\ngetSubstringsInsideBraces() Method Error! "
                + "A method argument contains Null or Null String!\n");
    }
    // See if the option to trim bracketed content is desired.
    boolean trim = false;
    if (trimElements.length > 0) {
        trim = trimElements[0];
    }

    // Apply the Regular Expression to Pattern. The supplied
    // open and close braces are used within the expression.
    Pattern regex = Pattern.compile("\\" + openBrace + "(.*?)\\" + closeBrace);
    // Run the pattern to see if there are any matches.
    Matcher matcher = regex.matcher(inputString);
    // Establish a String List Object to hold any matches.
    List<String> list = new ArrayList<>();

    // Retrieve any matches found and add to List.
    while (matcher.find()) {
        // Using a ternary operator against whether or not to
        // Trim the matched item if desired before adding it
        // to the List. This saves on doing a IF/THEN/ELSE.
        list.add((trim) ? matcher.group(1).trim() : matcher.group(1));
    }

    // Convert the List to a 1D String Array
    if (list.isEmpty()) { return null; }
    String[] array = new String[list.size()];
    array = list.toArray(array);

    // Return the 1D String Array
    return array;
}

To use the above method:

String strg = "name is {response.vital.name} and disease is "
                    + "{response.vital.some  } and drug is "
                    + "{response.vital.dis } More string content.";
String[] a = getSubstringsInsideBraces(strg, "{", "}", true);
System.out.println(Arrays.toString(a));

The console output will be:

[response.vital.name, response.vital.some, response.vital.dis]

If you want the above method to return a List object (which is what it fills to start with) then simply remove the conversion code within the method, instead of return array; use return list;, and declare your method to return a List<String> instead of String[]. Of course change the text within the JavaDoc above the method to reflect this change.


问:
What is sane way in vuejs + vuex form handling?
I have a large forms to submit in single page.

```<code><container>
  <formA>
  <formB>
  <formC>
  <submitButton>
<container>
</code>```

it looks apparently like this. and I have a store which save every form data. then when user click submit button, I gather all form data using vuex store.

The problem is I need to update the form data in store everytime.

so I'll be like this in vue component

```<code> watch: {
   userInput (val) {
     this.updateState(val)
 }
</code>```

update state when input changes by watching form data(binded with v-model).

or like this which is documented in vuex doc.

```<code>  userInput: {
    get () {
      return this.$store.state.userInput
    },
    set (val) {
      this.updateState(val)
    }
  }
</code>```

well.. I don't think these are good idea. Is there any better way to form handling with vuex?

答:
I would use deep watchers for this and have all fields in a object, you could use multiple approaches for saving the data, iterating over Object.keys to store each field with it's variable name in the form object, or storing the entire form, whatever you might need.

You could also use v-model.lazy="form.myfield" to indicate that you only want the binding to update once the user has left the field.

Form component

```<code><template>
    <div>
        <!-- You can optionally use v-model.lazy="form.field1" to only update once user has exited the field or pressed enter -->
        <input v-model="form.field1" />
        <input v-model.lazy="form.field2" />
    </div>
</template>

<script>
    export default {
        props: ['value'],

        data: function () {
            return {
                internalForm: {
                    field1: null,
                    field2: null
                }
            }
        },

        watch: {
            internalForm: {
                handler: function (newValue) {
                // Emit new form object to parent component so we can use v-model there
                this.$emit('input', this.form)
                // Or save form data
                this.handleFormSave(this.form)
                },
                // Tell vue to do a deep watch of entire form object to watch child items in the object
                deep: true
            }
        }
    }
</script>
</code>```

Parent component

```<code><template>
    <form-component v-model="forms.form1" />
    <submit-button @click="saveAllFormData" />
</template>

<script>
    export default {
        data: function () {
            return {
                forms: {
                    form1: null // This will be updated when 'input' is emitted
                }
            }
        },

        watch: {
            forms: {
                handler: function (newValue) {
                    if (allFormsValid && readyToSave)
                        saveAllFormData(newValue);
                },
                deep: true
            }
        }
    }
</script>
</code>```

Body:
I have a large forms to submit in single page.

<container>
  <formA>
  <formB>
  <formC>
  <submitButton>
<container>

it looks apparently like this. and I have a store which save every form data. then when user click submit button, I gather all form data using vuex store.

The problem is I need to update the form data in store everytime.

so I'll be like this in vue component

 watch: {
   userInput (val) {
     this.updateState(val)
 }

update state when input changes by watching form data(binded with v-model).

or like this which is documented in vuex doc.

  userInput: {
    get () {
      return this.$store.state.userInput
    },
    set (val) {
      this.updateState(val)
    }
  }

well.. I don't think these are good idea. Is there any better way to form handling with vuex?

Body:
I would use deep watchers for this and have all fields in a object, you could use multiple approaches for saving the data, iterating over Object.keys to store each field with it's variable name in the form object, or storing the entire form, whatever you might need.

You could also use v-model.lazy="form.myfield" to indicate that you only want the binding to update once the user has left the field.

Form component

<template>
    <div>
        <!-- You can optionally use v-model.lazy="form.field1" to only update once user has exited the field or pressed enter -->
        <input v-model="form.field1" />
        <input v-model.lazy="form.field2" />
    </div>
</template>

<script>
    export default {
        props: ['value'],

        data: function () {
            return {
                internalForm: {
                    field1: null,
                    field2: null
                }
            }
        },

        watch: {
            internalForm: {
                handler: function (newValue) {
                // Emit new form object to parent component so we can use v-model there
                this.$emit('input', this.form)
                // Or save form data
                this.handleFormSave(this.form)
                },
                // Tell vue to do a deep watch of entire form object to watch child items in the object
                deep: true
            }
        }
    }
</script>

Parent component

<template>
    <form-component v-model="forms.form1" />
    <submit-button @click="saveAllFormData" />
</template>

<script>
    export default {
        data: function () {
            return {
                forms: {
                    form1: null // This will be updated when 'input' is emitted
                }
            }
        },

        watch: {
            forms: {
                handler: function (newValue) {
                    if (allFormsValid && readyToSave)
                        saveAllFormData(newValue);
                },
                deep: true
            }
        }
    }
</script>


问:
Select Least with sql query with depended statment on mulitple columns
I am not even sure how to ask this question... but here goes. i want to run a query that selects least of 13 columns when the value of the column is greater than O ( i got that part) but i want to check a corresponding column for each column ( price, qty) so if qty =0 do not include the price column associated with that quantity in the least query. so here is what i have so far

```<code>**SELECT isbn13,  LEAST(
IF(Price1,Price1,999999),
IF(Price2,Price2,999999),
IF(Price3,Price3,999999),
IF(Price4,Price4,999999),
IF(Price5,Price5,999999),
IF(Price6,Price6,999999),
IF(Price7,Price7,999999),
IF(Price8,Price8,999999),
IF(Price9,Price9,999999),
IF(Price10,Price10,999999),
IF(Price11,Price11,999999),
IF(Price12,Price12,999999),
IF(Price13,Price13,999999),) as theMin

FROM table
where po='po1'**
</code>```

the part i need to ad is where Price1>0 and Qty1 >0 use Price1 in least Statement and so on and so forth for Price1-13 and Qty1-13. If i am making this too hard please i am open to any solution.

i have tried adding IF(Price13,Price13,999999) and QTY13>0, (no dice)
also  where po='po1' and (Qty1>0 or Qty2>0....) is not what i want

答:
```<code>SELECT
    isbn13,
    LEAST(
        IF (price1 > 0 AND qty1 > 0, price1, 999999),
        IF (price2 > 0 AND qty2 > 0, price2, 999999)
        etc.
    )
FROM table_name
</code>```

DEMO: http://sqlfiddle.com/#!9/130cb7/1

Body:
I am not even sure how to ask this question... but here goes. i want to run a query that selects least of 13 columns when the value of the column is greater than O ( i got that part) but i want to check a corresponding column for each column ( price, qty) so if qty =0 do not include the price column associated with that quantity in the least query. so here is what i have so far

**SELECT isbn13,  LEAST(
IF(Price1,Price1,999999),
IF(Price2,Price2,999999),
IF(Price3,Price3,999999),
IF(Price4,Price4,999999),
IF(Price5,Price5,999999),
IF(Price6,Price6,999999),
IF(Price7,Price7,999999),
IF(Price8,Price8,999999),
IF(Price9,Price9,999999),
IF(Price10,Price10,999999),
IF(Price11,Price11,999999),
IF(Price12,Price12,999999),
IF(Price13,Price13,999999),) as theMin

FROM table
where po='po1'**

the part i need to ad is where Price1>0 and Qty1 >0 use Price1 in least Statement and so on and so forth for Price1-13 and Qty1-13. If i am making this too hard please i am open to any solution.

i have tried adding IF(Price13,Price13,999999) and QTY13>0, (no dice)
also  where po='po1' and (Qty1>0 or Qty2>0....) is not what i want

Body:
SELECT
    isbn13,
    LEAST(
        IF (price1 > 0 AND qty1 > 0, price1, 999999),
        IF (price2 > 0 AND qty2 > 0, price2, 999999)
        etc.
    )
FROM table_name

DEMO: http://sqlfiddle.com/#!9/130cb7/1


问:
How can I increment a variable inside a CTE recursion with SQL Server 2008
I am having the following code, which I want to do a recursion with CTE and increment the variable inside so the recursion can use that to do a subquery.

```<code>WITH cte as
(
    select @layer as layers,
    case when exists(select * from #table where layer=@layer and string in ('abc','xyz)) then 10 else 0 end
    union all
    select layers + 1, total
    from cte
    where layers + 1<4 -- 4 is a max number that is unknown and given by the user
)select * from cte
</code>```

The #table has the following structure but the amount of data is dynamic

```<code>string     layer
abc        1
xyz        1
abc        2
xyz        2
</code>```

So at layer 1, if it has either 'abc' or 'xyz' it will has a point of 10, same things happen for layer 2 until the the max layer given by the user. I want to get the point and the corresponding level from the recursion. While loop and cursor are forbidden. I am having trouble on incrementing the @layer in the recursion. Any suggestion? Thanks

答:
I've never see a variable used in recursion, but I think you can do what you want with a tally table.

```<code>if object_id('tempdb..#table') is not null drop table #table

create table #table (string varchar(64), layer int)
insert into #table
values
('abc',1),
('abc',2),
('xyz',2),
            --missing layer 3
            --missing layer 4
('fgh',5),  --not in the abc or xyz clause
('abc',6),
('xyz',7)   --greate than the max passed in via @layer

declare @layer int = 6

;WITH
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
    E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
    cteTally(N) AS
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
    )

select
    N as Layer
    ,case when max(layer) is not null then 10 else 0 end
from
    cteTally
    full join #table
    on N = layer and string in ('abc','xyz')
where N <= @layer
group by N
order by N
</code>```

If you are really set on using recursion, which could be a lot slower if the @layer or max number passed in is large, then here is how you would accomplish that.

```<code>declare @layer int = 6

;with cte as(
    select
        1 as layer
        ,total = case when exists(select * from #table t2 where t2.layer=layer and t2.string in ('abc','xyz')) then 10 else 0 end
    union all
    select
        layer + 1
        ,total = case when exists(select * from #table t2 where t2.layer=c.layer + 1 and t2.string in ('abc','xyz')) then 10 else 0 end
    from cte c
    where layer < @layer)

select distinct
    layer
    ,total = max(total)
from cte
group by layer
order by layer
</code>```

Body:
I am having the following code, which I want to do a recursion with CTE and increment the variable inside so the recursion can use that to do a subquery.

WITH cte as
(
    select @layer as layers,
    case when exists(select * from #table where layer=@layer and string in ('abc','xyz)) then 10 else 0 end
    union all
    select layers + 1, total
    from cte
    where layers + 1<4 -- 4 is a max number that is unknown and given by the user
)select * from cte

The #table has the following structure but the amount of data is dynamic

string     layer
abc        1
xyz        1
abc        2
xyz        2

So at layer 1, if it has either 'abc' or 'xyz' it will has a point of 10, same things happen for layer 2 until the the max layer given by the user. I want to get the point and the corresponding level from the recursion. While loop and cursor are forbidden. I am having trouble on incrementing the @layer in the recursion. Any suggestion? Thanks

Body:
I've never see a variable used in recursion, but I think you can do what you want with a tally table.

if object_id('tempdb..#table') is not null drop table #table

create table #table (string varchar(64), layer int)
insert into #table
values
('abc',1),
('abc',2),
('xyz',2),
            --missing layer 3
            --missing layer 4
('fgh',5),  --not in the abc or xyz clause
('abc',6),
('xyz',7)   --greate than the max passed in via @layer

declare @layer int = 6

;WITH
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
    E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
    cteTally(N) AS
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
    )

select
    N as Layer
    ,case when max(layer) is not null then 10 else 0 end
from
    cteTally
    full join #table
    on N = layer and string in ('abc','xyz')
where N <= @layer
group by N
order by N

If you are really set on using recursion, which could be a lot slower if the @layer or max number passed in is large, then here is how you would accomplish that.

declare @layer int = 6

;with cte as(
    select
        1 as layer
        ,total = case when exists(select * from #table t2 where t2.layer=layer and t2.string in ('abc','xyz')) then 10 else 0 end
    union all
    select
        layer + 1
        ,total = case when exists(select * from #table t2 where t2.layer=c.layer + 1 and t2.string in ('abc','xyz')) then 10 else 0 end
    from cte c
    where layer < @layer)

select distinct
    layer
    ,total = max(total)
from cte
group by layer
order by layer


问:
Runing multiple processes within python script
Within my python script I need to launch several processes :
1) I need to run another python script ( a flask app with the command python app.py)
2)then I need to launch the command ngrok http 5000 and from this command output get the url on which ngrok is forwarding.

I have tried to use the subprocess module, but when it executes :

```<code>subprocess.Popen( "python app/app.py",shell=True)
</code>```

it launches the interactive shell and blocks the execution of my script.

What is the correct way to achieve this ?

答:
Just instead of Popen function, should to use the call function.

```<code>subprocess.call('python app.py', shell=True)
</code>```

Also see the documentation subprocess docs

Body:
Within my python script I need to launch several processes :
1) I need to run another python script ( a flask app with the command python app.py)
2)then I need to launch the command ngrok http 5000 and from this command output get the url on which ngrok is forwarding.

I have tried to use the subprocess module, but when it executes :

subprocess.Popen( "python app/app.py",shell=True)

it launches the interactive shell and blocks the execution of my script.

What is the correct way to achieve this ?

Body:
Just instead of Popen function, should to use the call function.

subprocess.call('python app.py', shell=True)

Also see the documentation subprocess docs