问:
jQuery animate() showing error of $(...).animate is not a function
```<code><!DOCTYPE html>
<html>
<head>
  <title>Alive Time</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" type="text/css" href="style.css">
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
  <script src="code.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
</head>
  <body>
    <i class="fa fa-cog" style="font-size:100px"></i>
    <i class="fa fa-arrow-right" style="font-size:100px"></i>

  </body>

</html>
----------------------------------------------------------------------------
.fa-cog{
    margin: 10% 50%;
    color: red;
    /*-moz-transition: all 0.5s linear;
    -webkit-transition: all 0.5s linear;
    transition: all 0.5s linear;*/
}

.down {
       -moz-transform:rotate(180deg);
    -webkit-transform:rotate(180deg);
    transform:rotate(180deg);
}
--------------------------------------------------------------------------------------------------------------
$(document).ready(function(){

   $(".fa-cog").on('mouseenter',function(){
 $(this).animate({rotate:180},{
  step:function(now,fx){

    /*$(this).css({' -moz-transform':'rotate('+now+'deg)',
    '-webkit-transform':'rotate('+now+'deg)',
    'transform':'rotate('+now+'deg)'});*/

    $(this).css('-webkit-transform','rotate('+now+'deg)');
      $(this).css('-moz-transform','rotate('+now+'deg)');
      $(this).css('transform','rotate('+now+'deg)');
  },duration:'slow'},'linear');
});
});
</code>```

Guys I am trying to use specifically animate() method of jquery to rotate a cog. I know I can make a class use some transition,transform and then add or remove that class. But I want to use animate() up here. Couple of docs on stackoverflow said that we don’t actually have to use a real CSS property, like text-index or border-spacing, but instead you can specify a fake CSS property, like rotation or my-awesome-property or else. It might be a good idea to use something that does not risk becoming an actual CSS property in the future. I tried every thing couldnt find the mistake in my code. Ignore the code which I have commented out.

答:
As I can see you are using slim version of jQuery which does not include animation library. Please use the full version of jQuery.</p>

```<code><script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</code>```

Body:
<!DOCTYPE html>

  <title>Alive Time</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" type="text/css" href="style.css">

----------------------------------------------------------------------------
.fa-cog{
    margin: 10% 50%;
    color: red;
    /*-moz-transition: all 0.5s linear;
    -webkit-transition: all 0.5s linear;
    transition: all 0.5s linear;*/
}

.down {
       -moz-transform:rotate(180deg);
    -webkit-transform:rotate(180deg);
    transform:rotate(180deg);
}
--------------------------------------------------------------------------------------------------------------
$(document).ready(function(){

   $(".fa-cog").on('mouseenter',function(){
 $(this).animate({rotate:180},{
  step:function(now,fx){

    /*$(this).css({' -moz-transform':'rotate('+now+'deg)',
    '-webkit-transform':'rotate('+now+'deg)',
    'transform':'rotate('+now+'deg)'});*/

    $(this).css('-webkit-transform','rotate('+now+'deg)');
      $(this).css('-moz-transform','rotate('+now+'deg)');
      $(this).css('transform','rotate('+now+'deg)');
  },duration:'slow'},'linear');
});
});

Guys I am trying to use specifically animate() method of jquery to rotate a cog. I know I can make a class use some transition,transform and then add or remove that class. But I want to use animate() up here. Couple of docs on stackoverflow said that we don’t actually have to use a real CSS property, like text-index or border-spacing, but instead you can specify a fake CSS property, like rotation or my-awesome-property or else. It might be a good idea to use something that does not risk becoming an actual CSS property in the future. I tried every thing couldnt find the mistake in my code. Ignore the code which I have commented out.

Body:
As I can see you are using slim version of jQuery which does not include animation library. Please use the full version of jQuery.

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>


来源: stackexchange

问:
dataframe apply with vectorized function behaving weirdly
I am constructing a dataframe from the following dictionary:

```<code>diction = {"a":{"aa":0, "bb":2, "cc":3}, "b":{"aa":4, "bb":5, "cc":6}, "c":{"aa":7, "bb":8, "cc":9}}
df = pandas.DataFrame(diction)
</code>```

I am then trying to perform some operations on the dataframe by using the following functions:

```<code>import pandas
import numpy as np
import math

def applyGivenTotals(rowOrColumn, rowOrColumnTotals, rowOrColumnName):
  return rowOrColumn/float(rowOrColumnTotals[rowOrColumnName])

def piLogpi(value):
  if(value==0):
    return 0
  else:
    return -value * math.log10(value)

def someFunction(df):
  entropy = {}
  rowTotals = df.sum(axis=1)
  rowApplied = df.apply(lambda row:applyGivenTotals(row, rowTotals, row.name), axis=1)
  unSummedPis = rowApplied.apply(np.vectorize(piLogpi))
  return unSummedPis
</code>```

I am getting zeros in the left-most column but I don't understand why.

To clarify, my expected result is:

```<code>    a         b         c
aa  0         0.159757  0.124915
bb  0.116675  0.159040  0.145601
cc  0.129692  0.159040  0.150515
</code>```

But I am getting:

```<code>    a         b         c
aa  0  0.159757  0.124915
bb  0  0.159040  0.145601
cc  0  0.159040  0.150515
</code>```

答:
I think you need applymap for elementwise process:

```<code>def someFunction(df):
  entropy = {}
  rowTotals = df.sum(axis=1)
  rowApplied = df.apply(lambda row:applyGivenTotals(row, rowTotals, row.name), axis=1)
  unSummedPis = rowApplied.applymap(np.vectorize(piLogpi))
  return unSummedPis

print (someFunction(df))

           a         b         c
aa  0.000000  0.159757  0.124915
bb  0.116675  0.159040  0.145601
cc  0.129692  0.159040  0.150515
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am constructing a dataframe from the following dictionary:

diction = {"a":{"aa":0, "bb":2, "cc":3}, "b":{"aa":4, "bb":5, "cc":6}, "c":{"aa":7, "bb":8, "cc":9}}
df = pandas.DataFrame(diction)

I am then trying to perform some operations on the dataframe by using the following functions:

import pandas
import numpy as np
import math

def applyGivenTotals(rowOrColumn, rowOrColumnTotals, rowOrColumnName):
  return rowOrColumn/float(rowOrColumnTotals[rowOrColumnName])

def piLogpi(value):
  if(value==0):
    return 0
  else:
    return -value * math.log10(value)

def someFunction(df):
  entropy = {}
  rowTotals = df.sum(axis=1)
  rowApplied = df.apply(lambda row:applyGivenTotals(row, rowTotals, row.name), axis=1)
  unSummedPis = rowApplied.apply(np.vectorize(piLogpi))
  return unSummedPis

I am getting zeros in the left-most column but I don't understand why.

To clarify, my expected result is:

    a         b         c
aa  0         0.159757  0.124915
bb  0.116675  0.159040  0.145601
cc  0.129692  0.159040  0.150515

But I am getting:

    a         b         c
aa  0  0.159757  0.124915
bb  0  0.159040  0.145601
cc  0  0.159040  0.150515

Body:
I think you need applymap for elementwise process:

def someFunction(df):
  entropy = {}
  rowTotals = df.sum(axis=1)
  rowApplied = df.apply(lambda row:applyGivenTotals(row, rowTotals, row.name), axis=1)
  unSummedPis = rowApplied.applymap(np.vectorize(piLogpi))
  return unSummedPis

print (someFunction(df))

           a         b         c
aa  0.000000  0.159757  0.124915
bb  0.116675  0.159040  0.145601
cc  0.129692  0.159040  0.150515


问:
Why CMake "option" does not refresh value on CMakeCache?
In the CMakeLists file of a project I just joined, they use OPTION as way to enable/disable some flags for the project configuration.
The problem I see, is that if I generate the VS2017 project with the option as OFF and then turn it into ON. The project does not reflects that change.

```<code>OPTION(RENDER_OFFSCREEN "Set the application to render offscreen" OFF)
</code>```

This generates the project and it does render offscreen, now if I turn it ON in the CMakeLists.txt file, the project still renders offscreen. Usually I have to regenerate the project for it to work.

I think I am missing something about the OPTION statement in CMake but I don't know what it is. Any advise?

答:
I found the following post What can cause a CMake option not work? in SO that explains that changing the CMakeLists won't update the Cache file.

Therefore, the only alternative is to pass -DRENDER_OFFSCREEN=ON when building using the command line.

Body:
In the CMakeLists file of a project I just joined, they use OPTION as way to enable/disable some flags for the project configuration.
The problem I see, is that if I generate the VS2017 project with the option as OFF and then turn it into ON. The project does not reflects that change.

OPTION(RENDER_OFFSCREEN "Set the application to render offscreen" OFF)

This generates the project and it does render offscreen, now if I turn it ON in the CMakeLists.txt file, the project still renders offscreen. Usually I have to regenerate the project for it to work.

I think I am missing something about the OPTION statement in CMake but I don't know what it is. Any advise?


问:
bundle exec - You have already activated json X, but your Gemfile requires json Y
Trying to execute jekyll on cygwin (x64) on Windows when I get this error in spite of using bundle exec prefix.

Shouldn’t the dependency defined in the Gemfile (i.e. 1.8.6) be activated when executing?

Any thoughts on what is going wrong here? I am totally new to the world of Ruby gems.  I have looked at other "You have already activated .. " posts showing similar messages but the answers there didn’t solve my problem.

$ bundle exec jekyll serve

```<code>$ bundle exec jekyll serve
/cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler/runtime.rb:40:in
 `block in setup': You have already activated json 2.0.2, but your Gemfile requires json 1.8.6.
 Prepending `bundle exec` to your command may solve this. (Gem::LoadError)
</code>```

Environment

Cygwin x86_64 installed on Windows 7

RVM installed on Cygwin

```<code>$ rvm -v
rvm 1.29.0 (latest) by Michal Papis, Piotr Kuczynski, Wayne E. Seguin [https://rvm.io/]

$ ruby -v
ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-cygwin]
</code>```

Gemfile - for the jekyll project

```<code>source 'https://rubygems.org'

require 'json'
require 'open-uri'
versions = JSON.parse(open('https://pages.github.com/versions.json').read)

gem 'github-pages', group: :jekyll_plugins
gem 'json', '~> 1.8.0'
</code>```

$ gem environment

```<code>$ gem environment
RubyGems Environment:
  - RUBYGEMS VERSION: 2.6.10
  - RUBY VERSION: 2.4.0 (2016-12-24 patchlevel 0) [x86_64-cygwin]
  - INSTALLATION DIRECTORY: /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0
  - USER INSTALLATION DIRECTORY: /cygdrive/c/Users/mochapenguin/.gem/ruby/2.4.0
  - RUBY EXECUTABLE: /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/bin/ruby.exe
  - EXECUTABLE DIRECTORY: /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/bin
  - SPEC CACHE DIRECTORY: /cygdrive/c/Users/mochapenguin/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-cygwin
  - GEM PATHS:
     - /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0
     - /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/bin
     - /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0@global/bin
     - /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/bin
     - /usr/local/bin
     - /usr/bin
     - /cygdrive/c/Windows/system32
     - /cygdrive/c/Windows
     - /cygdrive/c/Windows/System32/Wbem
     - /cygdrive/c/Windows/System32/WindowsPowerShell/v1.0
     - /cygdrive/c/Program Files/Java/jdk1.8.0_121/bin
     ..... snip .....
     - /cygdrive/c/Users/mochapenguin/AppData/Local/atom/bin
     - /usr/lib/lapack
     - /cygdrive/c/Users/mochapenguin/.rvm/bin
</code>```

bundle update

```<code>$ bundle update
Fetching gem metadata from https://rubygems.org/...........
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies...
Using i18n 0.8.1
Using json 1.8.6
Using minitest 5.10.1
Using thread_safe 0.3.6
Using public_suffix 2.0.5
Using coffee-script-source 1.12.2
Using execjs 2.7.0
Using colorator 1.1.0
Using ffi 1.9.18
Using multipart-post 2.0.0
Using forwardable-extended 2.6.0
Using gemoji 3.0.0
Using net-dns 0.8.0
Using sass 3.4.23
Using rb-fsevent 0.9.8
Using kramdown 1.13.2
Using liquid 3.0.6
Using mercenary 0.3.6
Using rouge 1.11.1
Using safe_yaml 1.0.4
Using mini_portile2 2.1.0
Using jekyll-paginate 1.1.0
Using jekyll-swiss 0.4.0
Using minima 2.0.0
Using unicode-display_width 1.1.3
Using bundler 1.14.6
Using tzinfo 1.2.3
Using addressable 2.5.0
Using coffee-script 2.4.1
Using ethon 0.10.1
Using rb-inotify 0.9.8
Using faraday 0.11.0
Using pathutil 0.14.0
Using jekyll-sass-converter 1.5.0
Using nokogiri 1.7.1
Using terminal-table 1.7.3
Using activesupport 4.2.7
Using jekyll-coffeescript 1.0.1
Using typhoeus 0.8.0
Using listen 3.0.6
Using sawyer 0.8.1
Using html-pipeline 2.5.0
Using jekyll-watch 1.5.0
Using octokit 4.6.2
Using jekyll 3.4.3
Using github-pages-health-check 1.3.3
Using jekyll-gist 1.4.0
Using jekyll-avatar 0.4.2
Using jekyll-default-layout 0.1.4
Using jekyll-feed 0.9.2
Using jekyll-github-metadata 2.3.1
Using jekyll-mentions 1.2.0
Using jekyll-optional-front-matter 0.1.2
Using jekyll-readme-index 0.1.0
Using jekyll-redirect-from 0.12.1
Using jekyll-relative-links 0.4.0
Using jekyll-seo-tag 2.1.0
Using jekyll-sitemap 1.0.0
Using jekyll-theme-architect 0.0.3
Using jekyll-theme-cayman 0.0.3
Using jekyll-theme-dinky 0.0.3
Using jekyll-theme-hacker 0.0.3
Using jekyll-theme-leap-day 0.0.3
Using jekyll-theme-merlot 0.0.3
Using jekyll-theme-midnight 0.0.3
Using jekyll-theme-minimal 0.0.3
Using jekyll-theme-modernist 0.0.3
Using jekyll-theme-primer 0.1.7
Using jekyll-theme-slate 0.0.3
Using jekyll-theme-tactile 0.0.3
Using jekyll-theme-time-machine 0.0.3
Using jekyll-titles-from-headings 0.1.5
Using jemoji 0.8.0
Using github-pages 132
Bundle updated!
</code>```

bundle exec - Full error message

```<code>$ bundle exec jekyll serve
/cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler/runtime.rb:40:in `block in setup': You have already activated json 2.0.2, but your Gemfile requires json 1.8.6. Prepending `bundle exec` to your command may solve this. (Gem::LoadError)
        from /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/forwardable.rb:228:in `each'
        from /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/forwardable.rb:228:in `each'
        from /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler/runtime.rb:25:in `map'
        from /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler/runtime.rb:25:in `setup'
        from /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler.rb:100:in `setup'
        from /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler/setup.rb:10:in `<top (required)>'
        from /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
</code>```

json gems

```<code>$ gem list json

*** LOCAL GEMS ***
json (default: 2.0.2, 1.8.6)
</code>```

bundle show json

```<code>$ bundle show json
/cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/json-1.8.6
</code>```

Can't uninstall a default gem

```<code>$ gem uninstall json -v2.0.2
ERROR:  While executing gem ... (Gem::InstallError)
    gem "json" cannot be uninstalled because it is a default gem
</code>```

UPDATE - 12-Apr-2017

I don't know what the issue is still, but I trimmed down the Gemfile to this and it doesn't fall in a heap. Maybe it somehow works when those particular version dependencies are not enforced.

```<code>source 'https://rubygems.org'

# sample suggested [here](https://jekyllrb.com/docs/github-pages/) and in github help
gem 'github-pages', group: :jekyll_plugins
</code>```

UPDATE - 21-Apr-2017

This issue with bundler and system gems is highlighted at Gem Versioning and Bundler - Doing it right

Bundler's sandbox relies on its ability to be present at the very beginning of the Ruby process, and to therefore have the ability to ensure that the versions of all loaded libraries will reflect the ones listed in the Gemfile.lock. By running a system executable, you are executing Ruby code before Bundler can modify the load path and replace the normal Rubygems loading mechanism, allowing arbitrary unmanaged gems to get loaded into memory. Once that happens, all bets are off.

This is what seems to be happening in this situation.

But, as mentioned above - can't uninstall the system json 2.0.2 gem.

答:
A bit late to the game, but hey, I have a solution! this is how I did it: so besides looking in your standard place where gems are installed, there is one other place where gems can apparently be "defined", and brought into the system. I install stuff using rbenv (I recommend this over RVM), and these are the directories for me:

```<code>/home/jf/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems
/home/jf/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/specifications/default
</code>```

In your case, your exact location/s might be different, but you should be able to figure it out. If a gem is in the standard place (/home/jf/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems), you would be able to 'gem uninstall' without a problem. For the other location, though... tough. To simply prevent the system version from being recognized so that you can use the version from the Gemfile, simply move the json-X.gemspec file away from that second directory (/home/jf/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/specifications/default above) somewhere else. And that's it!

Body:
Trying to execute jekyll on cygwin (x64) on Windows when I get this error in spite of using bundle exec prefix.

Shouldn’t the dependency defined in the Gemfile (i.e. 1.8.6) be activated when executing?

Any thoughts on what is going wrong here? I am totally new to the world of Ruby gems.  I have looked at other "You have already activated .. " posts showing similar messages but the answers there didn’t solve my problem.

$ bundle exec jekyll serve

$ bundle exec jekyll serve
/cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler/runtime.rb:40:in
 `block in setup': You have already activated json 2.0.2, but your Gemfile requires json 1.8.6.
 Prepending `bundle exec` to your command may solve this. (Gem::LoadError)

Environment

Cygwin x86_64 installed on Windows 7

RVM installed on Cygwin

$ rvm -v
rvm 1.29.0 (latest) by Michal Papis, Piotr Kuczynski, Wayne E. Seguin [https://rvm.io/]

$ ruby -v
ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-cygwin]

Gemfile - for the jekyll project

source 'https://rubygems.org'

require 'json'
require 'open-uri'
versions = JSON.parse(open('https://pages.github.com/versions.json').read)

gem 'github-pages', group: :jekyll_plugins
gem 'json', '~> 1.8.0'

$ gem environment

$ gem environment
RubyGems Environment:
  - RUBYGEMS VERSION: 2.6.10
  - RUBY VERSION: 2.4.0 (2016-12-24 patchlevel 0) [x86_64-cygwin]
  - INSTALLATION DIRECTORY: /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0
  - USER INSTALLATION DIRECTORY: /cygdrive/c/Users/mochapenguin/.gem/ruby/2.4.0
  - RUBY EXECUTABLE: /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/bin/ruby.exe
  - EXECUTABLE DIRECTORY: /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/bin
  - SPEC CACHE DIRECTORY: /cygdrive/c/Users/mochapenguin/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-cygwin
  - GEM PATHS:
     - /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0
     - /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/bin
     - /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0@global/bin
     - /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/bin
     - /usr/local/bin
     - /usr/bin
     - /cygdrive/c/Windows/system32
     - /cygdrive/c/Windows
     - /cygdrive/c/Windows/System32/Wbem
     - /cygdrive/c/Windows/System32/WindowsPowerShell/v1.0
     - /cygdrive/c/Program Files/Java/jdk1.8.0_121/bin
     ..... snip .....
     - /cygdrive/c/Users/mochapenguin/AppData/Local/atom/bin
     - /usr/lib/lapack
     - /cygdrive/c/Users/mochapenguin/.rvm/bin

bundle update

$ bundle update
Fetching gem metadata from https://rubygems.org/...........
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies...
Using i18n 0.8.1
Using json 1.8.6
Using minitest 5.10.1
Using thread_safe 0.3.6
Using public_suffix 2.0.5
Using coffee-script-source 1.12.2
Using execjs 2.7.0
Using colorator 1.1.0
Using ffi 1.9.18
Using multipart-post 2.0.0
Using forwardable-extended 2.6.0
Using gemoji 3.0.0
Using net-dns 0.8.0
Using sass 3.4.23
Using rb-fsevent 0.9.8
Using kramdown 1.13.2
Using liquid 3.0.6
Using mercenary 0.3.6
Using rouge 1.11.1
Using safe_yaml 1.0.4
Using mini_portile2 2.1.0
Using jekyll-paginate 1.1.0
Using jekyll-swiss 0.4.0
Using minima 2.0.0
Using unicode-display_width 1.1.3
Using bundler 1.14.6
Using tzinfo 1.2.3
Using addressable 2.5.0
Using coffee-script 2.4.1
Using ethon 0.10.1
Using rb-inotify 0.9.8
Using faraday 0.11.0
Using pathutil 0.14.0
Using jekyll-sass-converter 1.5.0
Using nokogiri 1.7.1
Using terminal-table 1.7.3
Using activesupport 4.2.7
Using jekyll-coffeescript 1.0.1
Using typhoeus 0.8.0
Using listen 3.0.6
Using sawyer 0.8.1
Using html-pipeline 2.5.0
Using jekyll-watch 1.5.0
Using octokit 4.6.2
Using jekyll 3.4.3
Using github-pages-health-check 1.3.3
Using jekyll-gist 1.4.0
Using jekyll-avatar 0.4.2
Using jekyll-default-layout 0.1.4
Using jekyll-feed 0.9.2
Using jekyll-github-metadata 2.3.1
Using jekyll-mentions 1.2.0
Using jekyll-optional-front-matter 0.1.2
Using jekyll-readme-index 0.1.0
Using jekyll-redirect-from 0.12.1
Using jekyll-relative-links 0.4.0
Using jekyll-seo-tag 2.1.0
Using jekyll-sitemap 1.0.0
Using jekyll-theme-architect 0.0.3
Using jekyll-theme-cayman 0.0.3
Using jekyll-theme-dinky 0.0.3
Using jekyll-theme-hacker 0.0.3
Using jekyll-theme-leap-day 0.0.3
Using jekyll-theme-merlot 0.0.3
Using jekyll-theme-midnight 0.0.3
Using jekyll-theme-minimal 0.0.3
Using jekyll-theme-modernist 0.0.3
Using jekyll-theme-primer 0.1.7
Using jekyll-theme-slate 0.0.3
Using jekyll-theme-tactile 0.0.3
Using jekyll-theme-time-machine 0.0.3
Using jekyll-titles-from-headings 0.1.5
Using jemoji 0.8.0
Using github-pages 132
Bundle updated!

bundle exec - Full error message

$ bundle exec jekyll serve
/cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler/runtime.rb:40:in `block in setup': You have already activated json 2.0.2, but your Gemfile requires json 1.8.6. Prepending `bundle exec` to your command may solve this. (Gem::LoadError)
        from /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/forwardable.rb:228:in `each'
        from /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/forwardable.rb:228:in `each'
        from /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler/runtime.rb:25:in `map'
        from /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler/runtime.rb:25:in `setup'
        from /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler.rb:100:in `setup'
        from /cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/bundler-1.14.6/lib/bundler/setup.rb:10:in `<top (required)>'
        from /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /cygdrive/c/Users/mochapenguin/.rvm/rubies/ruby-2.4.0/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'

json gems

$ gem list json

*** LOCAL GEMS ***
json (default: 2.0.2, 1.8.6)

bundle show json

$ bundle show json
/cygdrive/c/Users/mochapenguin/.rvm/gems/ruby-2.4.0/gems/json-1.8.6

Can't uninstall a default gem

$ gem uninstall json -v2.0.2
ERROR:  While executing gem ... (Gem::InstallError)
    gem "json" cannot be uninstalled because it is a default gem

UPDATE - 12-Apr-2017

I don't know what the issue is still, but I trimmed down the Gemfile to this and it doesn't fall in a heap. Maybe it somehow works when those particular version dependencies are not enforced.

source 'https://rubygems.org'

# sample suggested [here](https://jekyllrb.com/docs/github-pages/) and in github help
gem 'github-pages', group: :jekyll_plugins

UPDATE - 21-Apr-2017

This issue with bundler and system gems is highlighted at Gem Versioning and Bundler - Doing it right

Bundler's sandbox relies on its ability to be present at the very beginning of the Ruby process, and to therefore have the ability to ensure that the versions of all loaded libraries will reflect the ones listed in the Gemfile.lock. By running a system executable, you are executing Ruby code before Bundler can modify the load path and replace the normal Rubygems loading mechanism, allowing arbitrary unmanaged gems to get loaded into memory. Once that happens, all bets are off.

This is what seems to be happening in this situation.

But, as mentioned above - can't uninstall the system json 2.0.2 gem.

Body:
A bit late to the game, but hey, I have a solution! this is how I did it: so besides looking in your standard place where gems are installed, there is one other place where gems can apparently be "defined", and brought into the system. I install stuff using rbenv (I recommend this over RVM), and these are the directories for me:

/home/jf/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems
/home/jf/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/specifications/default

In your case, your exact location/s might be different, but you should be able to figure it out. If a gem is in the standard place (/home/jf/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems), you would be able to 'gem uninstall' without a problem. For the other location, though... tough. To simply prevent the system version from being recognized so that you can use the version from the Gemfile, simply move the json-X.gemspec file away from that second directory (/home/jf/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/specifications/default above) somewhere else. And that's it!


问:
How do I open a Chrome extension in its own window?
I installed a Chrome Extension that plays the Pandora client in a web extension (Anesidora), it works fine, but I just can't seem to find a way to open this extension in its own window.

I have to fire up the Chrome browser, click on the extension next to the address bar, and then click on the extension, and as soon as I click away, the music extension disappears, having me to click on the extension and view my music controls again.

Is there a way to update the behavior of the JSON file or popup.html or even backgroud.html page, so this can be viewed all by itself in one page or something?

答:
If I've understood you correctly you just need the URL of the popup.html.
Do a right click on the player controls, choose Inspect and enter location.href in the console. This way you get the URL of the popup that you can use to open the controls in a new browser window.


问:
Not getting result of HttpClient.PostAsync()
Developing a .NET Core web application that need to call a Json REST Api.

The caller :

```<code>        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            AuthorizationUser user = new AuthorizationUser { User = "<user>", Application = "<app>" };

            var content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(new Uri("http://localhost:8081/Roles"), content);
            // ...
        }
</code>```

The callee :

```<code>    [AllowAnonymous]
    [HttpPost]
    public HttpResponseMessage Post(AuthorizationUser user)
    {
        try
        {
            user = FillRoles(user);
            return Request.CreateResponse(HttpStatusCode.OK, user);
        }
        catch (System.Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
        }
    }
</code>```

The model (in caller and callee):

```<code>public class AuthorizationUser
{

    public AuthorizationUser() // Added thanks to CodeFuller
    { }

    public AuthorizationUser(string user, string application)
    {
        User = user ?? throw new ArgumentNullException(nameof(user));
        Application = application ?? throw new ArgumentNullException(nameof(application));

    }
    public string User { get; set; }
    public string Application { get; set; }
    public IEnumerable<string> Roles { get; set; }
}
</code>```

When reaching the breakpoint in the callee, received user is always null.
I tried to add [FromBody] and [FromUri] before it but same result.

What I am doing wrong?

答:
I cannot reproduce your problem, getting correctly filled user with User and Application fields.

Seems like some error during model binding happens. To diagnose the problem check the following:

What is the value of ActionContext.ModelState.IsValid in Post() method. Is it true or false?

If it's false, check collection ActionContext.ModelState.Values in debugger. It should contain model binding errors.

Body:
Developing a .NET Core web application that need to call a Json REST Api.

The caller :

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            AuthorizationUser user = new AuthorizationUser { User = "<user>", Application = "<app>" };

            var content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(new Uri("http://localhost:8081/Roles"), content);
            // ...
        }

The callee :

    [AllowAnonymous]
    [HttpPost]
    public HttpResponseMessage Post(AuthorizationUser user)
    {
        try
        {
            user = FillRoles(user);
            return Request.CreateResponse(HttpStatusCode.OK, user);
        }
        catch (System.Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
        }
    }

The model (in caller and callee):

public class AuthorizationUser
{

    public AuthorizationUser() // Added thanks to CodeFuller
    { }

    public AuthorizationUser(string user, string application)
    {
        User = user ?? throw new ArgumentNullException(nameof(user));
        Application = application ?? throw new ArgumentNullException(nameof(application));

    }
    public string User { get; set; }
    public string Application { get; set; }
    public IEnumerable<string> Roles { get; set; }
}

When reaching the breakpoint in the callee, received user is always null.
I tried to add [FromBody] and [FromUri] before it but same result.

What I am doing wrong?


问:
Alternative to for and ifelse loops - determining whether elements lie within generated confidence intervals
I am trying to rewrite my code to not contain any for loops or ifelse loops. The purpose is to extract a matrix containing 0s and 1s depending on variable mu and variable cinterval - to generate a 1 if y0 falls within its 95th CI, and 0 y0 falls within its 95th CI, and likewise for y1. This would be repeated with both y0 and y1 for a number of modules.

mu contains values for y0 and y1; cinterval contains four rows:

lower 95th CI limit for y0

upper 95th CI limit for y0

lower 95th CI limit for y1

upper 95th CI limit for y1

cinterval can be programmed to have any number of modules:

```<code>cinterval.fn <- function(y0y1modules) {
  matrix(c(y0results, y1results) nrow=4, ncol=no.of.modules, byrow=T) #simplified from true code
  rownames(cinterval) <- c("y0 95LCI", "y0 95UCI", "y1 95LCI", "y1 95UCI")
  colnames(cinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(cinterval)
}

> cinterval
         module.1 module.2  module.3
y0 95LCI 2.434602 1.784056  1.751713
y0 95UCI 5.988160 6.519465  6.833455
y1 95LCI 3.778811 2.681708  2.805293
y1 95UCI 9.228941 9.716476 10.258412
</code>```

mu looks like this:

```<code>mu <- c(4, 8)
mu
y0 y1
 4  8
</code>```

The code I have is:

```<code>incinterval.fn <- function(cov.xy, mu, n1, dr) {
  cinterval <- cintervaloutput.fn(cov.xy, mu, n1, dr) # Generates matrix with 95% CI values for y0 and y1 after modules
  y0 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y0 <- cbind(y0, ifelse (cinterval[1, module.no] <= mu["y0"] || mu["y0"] <= cinterval[2, module.no], 1, 0))
  }            # If y0 inside CI, 1, else 0
  y1 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y1 <- cbind(y1, ifelse (cinterval[3, module.no] <= mu["y1"] || mu["y1"] <= cinterval[4, module.no], 1, 0))
  }            # If y1 inside CI, 1, else 0
  incinterval <- rbind(y0, y1) # Combines vectors
  colnames(incinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(incinterval)
}
</code>```

The result, incinterval, looks like this:

```<code>     module.1 module.2 module.3
[y0]        1        1        1
[y1]        1        1        1
</code>```

Any assistance with more efficient coding to replace for and ifelse would be greatly appreciated! I currently use 2 for and ifeelse loops.

答:
Assuming your input data is created something like:

```<code>mu = c(y0 = 4, y1 = 8)

cinterval <-
    data.frame(names = c("y0", "y0", "y1", "y1"),
               CI = c("LCI", "UCI", "LCI", "UCI"),
               module.1 = c(2.434602, 5.988160, 3.778811, 9.228941),
               module.2 = c(1.784056, 6.519465, 2.681708, 9.716476),
               module.3 = c(1.751713, 6.833455, 2.805293, 10.258412))
</code>```

Then something like this might do what you want:

```<code>sapply(seq_along(mu),
     function(y) {

          cis  <- cinterval[cinterval[["names"]] == names(mu)[y], -1:-2]

         apply(cis, 2, function(ci) {
              findInterval(mu[y], ci)
          })

})
</code>```

Body:
I am trying to rewrite my code to not contain any for loops or ifelse loops. The purpose is to extract a matrix containing 0s and 1s depending on variable mu and variable cinterval - to generate a 1 if y0 falls within its 95th CI, and 0 y0 falls within its 95th CI, and likewise for y1. This would be repeated with both y0 and y1 for a number of modules.

mu contains values for y0 and y1; cinterval contains four rows:

lower 95th CI limit for y0

upper 95th CI limit for y0

lower 95th CI limit for y1

upper 95th CI limit for y1

cinterval can be programmed to have any number of modules:

cinterval.fn <- function(y0y1modules) {
  matrix(c(y0results, y1results) nrow=4, ncol=no.of.modules, byrow=T) #simplified from true code
  rownames(cinterval) <- c("y0 95LCI", "y0 95UCI", "y1 95LCI", "y1 95UCI")
  colnames(cinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(cinterval)
}

> cinterval
         module.1 module.2  module.3
y0 95LCI 2.434602 1.784056  1.751713
y0 95UCI 5.988160 6.519465  6.833455
y1 95LCI 3.778811 2.681708  2.805293
y1 95UCI 9.228941 9.716476 10.258412

mu looks like this:

mu <- c(4, 8)
mu
y0 y1
 4  8

The code I have is:

incinterval.fn <- function(cov.xy, mu, n1, dr) {
  cinterval <- cintervaloutput.fn(cov.xy, mu, n1, dr) # Generates matrix with 95% CI values for y0 and y1 after modules
  y0 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y0 <- cbind(y0, ifelse (cinterval[1, module.no] <= mu["y0"] || mu["y0"] <= cinterval[2, module.no], 1, 0))
  }            # If y0 inside CI, 1, else 0
  y1 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y1 <- cbind(y1, ifelse (cinterval[3, module.no] <= mu["y1"] || mu["y1"] <= cinterval[4, module.no], 1, 0))
  }            # If y1 inside CI, 1, else 0
  incinterval <- rbind(y0, y1) # Combines vectors
  colnames(incinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(incinterval)
}

The result, incinterval, looks like this:

     module.1 module.2 module.3
[y0]        1        1        1
[y1]        1        1        1

Any assistance with more efficient coding to replace for and ifelse would be greatly appreciated! I currently use 2 for and ifeelse loops.

Body:
Assuming your input data is created something like:

mu = c(y0 = 4, y1 = 8)

cinterval <-
    data.frame(names = c("y0", "y0", "y1", "y1"),
               CI = c("LCI", "UCI", "LCI", "UCI"),
               module.1 = c(2.434602, 5.988160, 3.778811, 9.228941),
               module.2 = c(1.784056, 6.519465, 2.681708, 9.716476),
               module.3 = c(1.751713, 6.833455, 2.805293, 10.258412))

Then something like this might do what you want:

sapply(seq_along(mu),
     function(y) {

          cis  <- cinterval[cinterval[["names"]] == names(mu)[y], -1:-2]

         apply(cis, 2, function(ci) {
              findInterval(mu[y], ci)
          })

})


问:
How would I check if user input is over the Int limit using public static main void (String args[])
This is what I've put so far:

```<code>public class CheckNum {

    public static void main (String args[]) {
        for (int i = 0; i < args.length; i++) {
            if (Integer.parseInt(args[i]) > Integer.MAX_VALUE) {
                System.out.println("Input value is too big");
            }

        }
    }

}
</code>```

However when I do put in a digit in linux thats over the Integer Max Value like this:

java CheckNum 1234567890

I get a NumberFormats error at parseInt, which I'm guessing is from the inability to convert the too large number into an Integer even before comparing with the max value of Integer. Is there another way to check if the number entered is too large for an integer using just the inputs on String args[]?

答:
You can use an exception to validate that the user has entered a wrong value. Knowing what exactly is the problem is a bit harder because it can be caused from many things. The easiest (and best solution) would be to make it like:

```<code>try {
  int result=Integer.parseInt(args[i]);
} catch (NumberFormatException e){
   System.out.println("Input value is not an integer [-2147483648 : 2147483647 ]");
}
</code>```

If you insist on knowing the problem you need to do additional checks. But you will need to use the arg[0] as a string and do some string manipulation. Like for example if you try to cast it to long it might be bigger even than a long. Or it might contain a letter or even something like @#$@$^!@T!@$^. So you need to check if it contains just numbers, check if it is floating point value, try casting it to BigInteger for example. But all these tests are meaningless because they still lead to the same problem - wrong input :)

Body:
This is what I've put so far:

public class CheckNum {

    public static void main (String args[]) {
        for (int i = 0; i < args.length; i++) {
            if (Integer.parseInt(args[i]) > Integer.MAX_VALUE) {
                System.out.println("Input value is too big");
            }

        }
    }

}

However when I do put in a digit in linux thats over the Integer Max Value like this:

java CheckNum 1234567890

I get a NumberFormats error at parseInt, which I'm guessing is from the inability to convert the too large number into an Integer even before comparing with the max value of Integer. Is there another way to check if the number entered is too large for an integer using just the inputs on String args[]?

Body:
You can use an exception to validate that the user has entered a wrong value. Knowing what exactly is the problem is a bit harder because it can be caused from many things. The easiest (and best solution) would be to make it like:

try {
  int result=Integer.parseInt(args[i]);
} catch (NumberFormatException e){
   System.out.println("Input value is not an integer [-2147483648 : 2147483647 ]");
}

If you insist on knowing the problem you need to do additional checks. But you will need to use the arg[0] as a string and do some string manipulation. Like for example if you try to cast it to long it might be bigger even than a long. Or it might contain a letter or even something like @#$@$^!@T!@$^. So you need to check if it contains just numbers, check if it is floating point value, try casting it to BigInteger for example. But all these tests are meaningless because they still lead to the same problem - wrong input :)


问:
How to push json keys and json values into two arrays
I have one json file with following structure:

```<code>{
    "won":3,
    "lost":0,
    "void":0,
    "active":1
}
</code>```

I've been trying to figure out how to make two arrays in javascript that will contain following information:

```<code>var labels = ["won", "lost", "void", "active"];
var data = ["3","0", "0","1"];
</code>```

But I can't my head around how to do it.

答:
Try This :

var obj = {
    "won":3,
    "lost":0,
    "void":0,
    "active":1
}
var keys = new Array();
var values = new Array();

for (var key in obj) {
  keys.push(key)
  values.push(obj[key]);
}

console.log(keys);
console.log(values);```

Body:
I have one json file with following structure:

{
    "won":3,
    "lost":0,
    "void":0,
    "active":1
}

I've been trying to figure out how to make two arrays in javascript that will contain following information:

var labels = ["won", "lost", "void", "active"];
var data = ["3","0", "0","1"];

But I can't my head around how to do it.


问:
JVM leaking memory outside heap and buffer pools
We have a java application as a long running service (actual up-time for this JVM 31 days 3 hrs 35 min)

Due to Windows taskmanager the process uses 1,075,384,320 B - nearly one GB.

Heap size of the JVM is restricted to 256 MB (-Xmx256m)

Memory-Data

```<code>Memory:
Size: 268,435,456 B
Max: 268,435,456 B
Used: 100,000,000 up to 200,000,000 B
</code>```

- no leak here

Buffer Pools

```<code>Direct:
Count: 137
Memory Used and Total Capacity: 1,348,354 B

Mapped:
Count: 0
Memory Used and Total Capacity: 0 B
</code>```

- no leak here

my question: where does the JVM uses the additional memory?

Additional informations:

```<code>Java: version 1.8.0_74 32 bit (Oracle)

Classes:
Total loaded: 17,248
Total unloaded: 35,761

Threads:
Live: 273
Live peak: 285
Daemon: 79
Total started: 486,282
</code>```

After a restart it takes some days for the process size to grow, so of course regular restart would help, and maybe using a newer java version also may solve the problem, but I would like to have an explanation for this behaviour, e. g. known bug in 1.8.0 before 111, fixed in ... - I did not find anything, yet.

We use about 350 of such installations in different places so changing is not so easy.

答:
Don't forget to run your JVM in server mode on long running tasks!

The reason for this kind of memory leak was the JVM running in client mode.
Our solutions runs in a couple of chain stores on old windows xp 32-bit PCs.
Default for JVMs on this platform is client mode.

In most cases we run JRE 1.8.0_74-32bit. With our application this JVM leaks memory in "Thread Arena Space" - seems to be nothing returned ever.

After switching to server mode by setting the parameter -server on JVM start the problems disappeared.

Body:
We have a java application as a long running service (actual up-time for this JVM 31 days 3 hrs 35 min)

Due to Windows taskmanager the process uses 1,075,384,320 B - nearly one GB.

Heap size of the JVM is restricted to 256 MB (-Xmx256m)

Memory-Data

Memory:
Size: 268,435,456 B
Max: 268,435,456 B
Used: 100,000,000 up to 200,000,000 B

- no leak here

Buffer Pools

Direct:
Count: 137
Memory Used and Total Capacity: 1,348,354 B

Mapped:
Count: 0
Memory Used and Total Capacity: 0 B

- no leak here

my question: where does the JVM uses the additional memory?

Additional informations:

Java: version 1.8.0_74 32 bit (Oracle)

Classes:
Total loaded: 17,248
Total unloaded: 35,761

Threads:
Live: 273
Live peak: 285
Daemon: 79
Total started: 486,282

After a restart it takes some days for the process size to grow, so of course regular restart would help, and maybe using a newer java version also may solve the problem, but I would like to have an explanation for this behaviour, e. g. known bug in 1.8.0 before 111, fixed in ... - I did not find anything, yet.

We use about 350 of such installations in different places so changing is not so easy.


问:
Can I refer another namespace and expose its functions as public for the current ns?
I thought use would do it but it seems the mapping created in the current namespace is not public. Here is an example of what I'd like to achieve:

```<code>(ns my-ns
  (:use [another-ns :only (another-fct)]))

(defn my-fct
  []
  (another-fct 123)) ; this works fine
</code>```

Then I have another namespace like this:

```<code>(ns my-ns-2
   (:require [my-ns :as my]))

(defn my-fct-2
  []
  (my/another-fct 456)) ; this doesn't work
</code>```

I would like to do that because another-ns is a library to access a database. I would like to isolate all the calls to this library in a single namespace (my-ns), this way all the DB dependent functions would be isolated in a single namespace and it becomes easier to switch to another DB if needed.

Some of the functions of this library are just fine for me but I'd like to augment others. Let's say the read functions are fine but I'd like to augment the write functions with some validation.

The only way I see so far is to hand-code all the mapping into my-ns even for the functions I don't augment.

答:
One way to do this selectively (specifying each function explicitly) is to use something like Zach Tellman's Potemkin library.  An example of it's use is found in the lamina.core namespace which serves as the public entry point for Lamina, importing the key public functions from all other internal namespaces.

You can also use clojure.contrib.def/defalias:

```<code>(use 'clojure.contrib.def/defalias)
(defalias foo clojure.string/blank?)
(foo "")
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I thought use would do it but it seems the mapping created in the current namespace is not public. Here is an example of what I'd like to achieve:

(ns my-ns
  (:use [another-ns :only (another-fct)]))

(defn my-fct
  []
  (another-fct 123)) ; this works fine

Then I have another namespace like this:

(ns my-ns-2
   (:require [my-ns :as my]))

(defn my-fct-2
  []
  (my/another-fct 456)) ; this doesn't work

I would like to do that because another-ns is a library to access a database. I would like to isolate all the calls to this library in a single namespace (my-ns), this way all the DB dependent functions would be isolated in a single namespace and it becomes easier to switch to another DB if needed.

Some of the functions of this library are just fine for me but I'd like to augment others. Let's say the read functions are fine but I'd like to augment the write functions with some validation.

The only way I see so far is to hand-code all the mapping into my-ns even for the functions I don't augment.

Body:
One way to do this selectively (specifying each function explicitly) is to use something like Zach Tellman's Potemkin library.  An example of it's use is found in the lamina.core namespace which serves as the public entry point for Lamina, importing the key public functions from all other internal namespaces.

You can also use clojure.contrib.def/defalias:

(use 'clojure.contrib.def/defalias)
(defalias foo clojure.string/blank?)
(foo "")


问:
chrome extension inject javascript at top of head before any other js

What I want to do.

Using a Chrome extension I need to inject a script into the page context in such a way that the injected script runs before any other javascript on the page.

Why do I need this?

I need to hijack all console commands for a specific page so my extension can listen to the messages.

My current issue

Currently I am catching some of the messages logged by the page but not all of them, specifically, all messages from web-directory-132a3f16cf1ea31e167fdf5294387073.js are not being caught. After some digging I discovered that the web-directory-132a3f16cf1ea31e167fdf5294387073.js is also hijacking console but doing so before my script has a chance to.

As a visual, if I look at the network tab after loading the page, I see this:

My injected script is consoleInterceptor.js. It correctly captures the output of the js files that are loaded here accept web-directory-132a3f16cf1ea31e167fdf5294387073.js

Inside of web-directory-132a3f16cf1ea31e167fdf5294387073.js is some code something like this:

```<code>   ....
    _originalLogger: t.default.Logger,
   ...
    // do stuff with logging ....
    this._originalLogger[e].apply(this._originalLogger, s),
</code>```

What I think the problem is

It seems to me that, web-directory-132a3f16cf1ea31e167fdf5294387073.js is grabbing the standard console functions and storing them internally before my script has had a chance to replace them with my own versions. So even though my script works, the  web-directory-132a3f16cf1ea31e167fdf5294387073.js still uses the original standard console functions it saved.

Note that web-directory-132a3f16cf1ea31e167fdf5294387073.js is an ember application and I dont see any simple way to hook into that code to overwrite those functions too but Im open to that as a solution.

My current code:

manifest.js

```<code>  ...
  "web_accessible_resources": [
    "js/ajaxInterceptor.js",
    "js/consoleInterceptor.js"
  ],
  "version" : "5.2",
  "manifest_version": 2,
  "permissions": [
    "<all_urls>",
    "tabs",
    "activeTab",
    "storage",
    "webNavigation",
    "unlimitedStorage",
    "notifications",
    "clipboardWrite",
    "downloads",
    "tabCapture",
    "cookies",
    "browsingData",
    "webRequest",
    "*://*/*",
    "gcm",
    "contextMenus",
    "management"
  ],
  "externally_connectable": {
    "matches": ["*://apps.mypurecloud.com/*","*://*.cloudfront.net/*"]
  },
  ...
</code>```

background.js

```<code>var options = {url: [{hostContains: 'apps.mypurecloud.com'}]};
chrome.webNavigation.onCommitted.addListener(function(details) {
        // first inject the chrome extension's id
        chrome.tabs.executeScript(details.tabId, {
            code: "var chromeExtensionId = " + JSON.stringify(chrome.runtime.id)
        });
        // then inject the script which will use the dynamically added extension id
        // to talk to the extension
        chrome.tabs.executeScript(details.tabId, {
            file: 'js/injectConsoleInterceptor.js'
        });
    },
    options
);
chrome.runtime.onMessageExternal.addListener(
    function(msg, sender, sendResponse) {
        if(msg.action === 'console_intercepted'){
            _this.processConsoleMessage(sender, msg.details.method, msg.details.arguments);

        }
    });
</code>```

injectConsoleInterceptor.js

```<code>var interceptorScript = document.createElement('script');
interceptorScript.src = chrome.extension.getURL('js/consoleInterceptor.js');
interceptorScript.onload = function(){this.remove();};
(document.head || document.documentElement).prepend(interceptorScript);
</code>```

consoleInterceptor.js

```<code>if(!window.hasConsoleInterceptor){
    window.hasConsoleInterceptor = true;
    console.log('overriding console functions');
    var originals ={};
    var console = window.console;
    if (console){
        function interceptConsoleMethod(method){
            originals[method] = console[method];
            console[method] = function(){
                // send the data to the extension
                // chromeExtensionId should be injected into the page separately and before this script
                var data = {
                    action: 'console_intercepted',
                    details: {
                        method: method,
                        arguments: arguments
                    }
                };
                chrome.runtime.sendMessage(chromeExtensionId, data);
                originals[method].apply(console, arguments)
            }
        }
        // an array of the methods we want to observe
        var methods = ['assert', 'count', 'debug', 'dir', 'dirxml', 'error', 'group','groupCollapsed','groupEnd','info','log', 'profile', 'profileEnd','time','timeEnd','timeStamp','trace','warn','table'];
        for (var i = 0; i < methods.length; i++){
            interceptConsoleMethod(methods[i])
        }
        console.log('Successfully overridden console functions: '+methods.join(','));
    }
}
</code>```

My question

What can I do to make consoleInterceptor.js run before web-directory-132a3f16cf1ea31e167fdf5294387073.js loads so that web-directory-132a3f16cf1ea31e167fdf5294387073.js uses my modified console functions rather than the default browser console funcitons?

答:
You can try this.

In manifest.json file:

```

    "content_scripts": [
            {
              "matches": ["http://*/*", "https://*/*"],
              "js": ["script/inject.js"],
              "run_at":"document_start"
            }
        ]

```

In inject.js:

var ss = document.createElement("script");
ss.innerHTML= "xxx";
document.documentElement.appendChild(ss);```

Body:
What I want to do.

Using a Chrome extension I need to inject a script into the page context in such a way that the injected script runs before any other javascript on the page.

Why do I need this?

I need to hijack all console commands for a specific page so my extension can listen to the messages.

My current issue

Currently I am catching some of the messages logged by the page but not all of them, specifically, all messages from web-directory-132a3f16cf1ea31e167fdf5294387073.js are not being caught. After some digging I discovered that the web-directory-132a3f16cf1ea31e167fdf5294387073.js is also hijacking console but doing so before my script has a chance to.

As a visual, if I look at the network tab after loading the page, I see this:

My injected script is consoleInterceptor.js. It correctly captures the output of the js files that are loaded here accept web-directory-132a3f16cf1ea31e167fdf5294387073.js

Inside of web-directory-132a3f16cf1ea31e167fdf5294387073.js is some code something like this:

   ....
    _originalLogger: t.default.Logger,
   ...
    // do stuff with logging ....
    this._originalLogger[e].apply(this._originalLogger, s),

What I think the problem is

It seems to me that, web-directory-132a3f16cf1ea31e167fdf5294387073.js is grabbing the standard console functions and storing them internally before my script has had a chance to replace them with my own versions. So even though my script works, the  web-directory-132a3f16cf1ea31e167fdf5294387073.js still uses the original standard console functions it saved.

Note that web-directory-132a3f16cf1ea31e167fdf5294387073.js is an ember application and I dont see any simple way to hook into that code to overwrite those functions too but Im open to that as a solution.

My current code:

manifest.js

  ...
  "web_accessible_resources": [
    "js/ajaxInterceptor.js",
    "js/consoleInterceptor.js"
  ],
  "version" : "5.2",
  "manifest_version": 2,
  "permissions": [
    "<all_urls>",
    "tabs",
    "activeTab",
    "storage",
    "webNavigation",
    "unlimitedStorage",
    "notifications",
    "clipboardWrite",
    "downloads",
    "tabCapture",
    "cookies",
    "browsingData",
    "webRequest",
    "*://*/*",
    "gcm",
    "contextMenus",
    "management"
  ],
  "externally_connectable": {
    "matches": ["*://apps.mypurecloud.com/*","*://*.cloudfront.net/*"]
  },
  ...

background.js

var options = {url: [{hostContains: 'apps.mypurecloud.com'}]};
chrome.webNavigation.onCommitted.addListener(function(details) {
        // first inject the chrome extension's id
        chrome.tabs.executeScript(details.tabId, {
            code: "var chromeExtensionId = " + JSON.stringify(chrome.runtime.id)
        });
        // then inject the script which will use the dynamically added extension id
        // to talk to the extension
        chrome.tabs.executeScript(details.tabId, {
            file: 'js/injectConsoleInterceptor.js'
        });
    },
    options
);
chrome.runtime.onMessageExternal.addListener(
    function(msg, sender, sendResponse) {
        if(msg.action === 'console_intercepted'){
            _this.processConsoleMessage(sender, msg.details.method, msg.details.arguments);

        }
    });

injectConsoleInterceptor.js

var interceptorScript = document.createElement('script');
interceptorScript.src = chrome.extension.getURL('js/consoleInterceptor.js');
interceptorScript.onload = function(){this.remove();};
(document.head || document.documentElement).prepend(interceptorScript);

consoleInterceptor.js

if(!window.hasConsoleInterceptor){
    window.hasConsoleInterceptor = true;
    console.log('overriding console functions');
    var originals ={};
    var console = window.console;
    if (console){
        function interceptConsoleMethod(method){
            originals[method] = console[method];
            console[method] = function(){
                // send the data to the extension
                // chromeExtensionId should be injected into the page separately and before this script
                var data = {
                    action: 'console_intercepted',
                    details: {
                        method: method,
                        arguments: arguments
                    }
                };
                chrome.runtime.sendMessage(chromeExtensionId, data);
                originals[method].apply(console, arguments)
            }
        }
        // an array of the methods we want to observe
        var methods = ['assert', 'count', 'debug', 'dir', 'dirxml', 'error', 'group','groupCollapsed','groupEnd','info','log', 'profile', 'profileEnd','time','timeEnd','timeStamp','trace','warn','table'];
        for (var i = 0; i < methods.length; i++){
            interceptConsoleMethod(methods[i])
        }
        console.log('Successfully overridden console functions: '+methods.join(','));
    }
}

My question

What can I do to make consoleInterceptor.js run before web-directory-132a3f16cf1ea31e167fdf5294387073.js loads so that web-directory-132a3f16cf1ea31e167fdf5294387073.js uses my modified console functions rather than the default browser console funcitons?

Body:
You can try this.

In manifest.json file:

    "content_scripts": [
            {
              "matches": ["http://*/*", "https://*/*"],
              "js": ["script/inject.js"],
              "run_at":"document_start"
            }
        ]

In inject.js:

var ss = document.createElement("script");
ss.innerHTML= "xxx";
document.documentElement.appendChild(ss);


问:
PHP: Use parent namespace by default in child namespaced class
For example my root namespace is myns where are all helper classes. There is myns\controllers namespace where are all the controllers.

I want to use myns namespace by default in all myns\controllers classes, avoiding many

use myns\classname;

declarations at the beginning.

Is that possible?

答:
No. The "default namespace" is established by namespace, not use. You have two options:

Switch the namespace:

```<code>namespace myns\controllers {
    class Foo {}
}

namespace myns {
    use myns\controllers\Foo;

    new Foo;  // above Foo class
    new Bar;  // myns\Bar class
}
</code>```

Use a shortened handle:

```<code>use myns as m;

new m\Bar;  // myns\Bar
</code>```

Practically speaking, in sane code, you shouldn't be having a ton of stuff from other namespaces that you're going to use; explicitly aliasing a small handful (say, up to around a dozen) of functions and classes at the top of the file is pretty normal. A decent IDE can pretty much auto-generate those use statements as you type.

Body:
No. The "default namespace" is established by namespace, not use. You have two options:

Switch the namespace:

namespace myns\controllers {
    class Foo {}
}

namespace myns {
    use myns\controllers\Foo;

    new Foo;  // above Foo class
    new Bar;  // myns\Bar class
}

Use a shortened handle:

use myns as m;

new m\Bar;  // myns\Bar

Practically speaking, in sane code, you shouldn't be having a ton of stuff from other namespaces that you're going to use; explicitly aliasing a small handful (say, up to around a dozen) of functions and classes at the top of the file is pretty normal. A decent IDE can pretty much auto-generate those use statements as you type.


问:
change DD-MMM-YYYY to YYYYMMDD in oracle
i have a date 07-OCT-2017, I have to get it converted as 20171007 in oracle.</p>

```<code>Below code doesn't work for me
select To_date(to_char('07-OCT-2017','DD-MMM-YYYY'), 'yyyymmdd') from dual;
</code>```

答:
i have a date 07-OCT-2017, I have to get it converted as 20171007 in oracle.

Dates (stored in tables) are represented by 7 bytes - they do not have any format associated with them. If they are formatted as a string then that is the client program which you are using to access the database applying its own formatting to the date (which you can usually set via the preferences in that program).

So, you can get your date using a date literal:

```<code>SELECT DATE '2017-10-07' FROM DUAL;
</code>```

or, using TO_DATE:

```<code>SELECT TO_DATE( '07-OCT'2017', 'DD-MON-YYYY', 'NLS_DATE_LANGUAGE=English' )
FROM   DUAL;
</code>```

However, the client program you are using will convert those 7-bytes to something that you, the user, can understand using its default format for dates. You can change this default format in:

SQL Developer using this answer.

SQL/Plus using this this answer

If you do not want to change your defaults or need to show it in a format for other users then you will need to convert your date (internally 7-bytes without a format) to a formatted string using TO_CHAR:

```<code>SELECT TO_CHAR( DATE '2017-10-07', 'YYYYMMDD' ) FROM DUAL;
</code>```

or

```<code>SELECT TO_CHAR(
         TO_DATE( '07-OCT'2017', 'DD-MON-YYYY', 'NLS_DATE_LANGUAGE=English' ),
         'YYYYMMDD'
       )
FROM   DUAL;
</code>```

Body:
i have a date 07-OCT-2017, I have to get it converted as 20171007 in oracle.

Below code doesn't work for me
select To_date(to_char('07-OCT-2017','DD-MMM-YYYY'), 'yyyymmdd') from dual;

Body:
i have a date 07-OCT-2017, I have to get it converted as 20171007 in oracle.

Dates (stored in tables) are represented by 7 bytes - they do not have any format associated with them. If they are formatted as a string then that is the client program which you are using to access the database applying its own formatting to the date (which you can usually set via the preferences in that program).

So, you can get your date using a date literal:

SELECT DATE '2017-10-07' FROM DUAL;

or, using TO_DATE:

SELECT TO_DATE( '07-OCT'2017', 'DD-MON-YYYY', 'NLS_DATE_LANGUAGE=English' )
FROM   DUAL;

However, the client program you are using will convert those 7-bytes to something that you, the user, can understand using its default format for dates. You can change this default format in:

SQL Developer using this answer.

SQL/Plus using this this answer

If you do not want to change your defaults or need to show it in a format for other users then you will need to convert your date (internally 7-bytes without a format) to a formatted string using TO_CHAR:

SELECT TO_CHAR( DATE '2017-10-07', 'YYYYMMDD' ) FROM DUAL;

or

SELECT TO_CHAR(
         TO_DATE( '07-OCT'2017', 'DD-MON-YYYY', 'NLS_DATE_LANGUAGE=English' ),
         'YYYYMMDD'
       )
FROM   DUAL;


问:
A Web-based Database Simulator for students
I'm tasked to work on a web based SQL simulator much like what can be found on SQL Fiddle or the one on W3Schools' SQL Tryit editor. Here are the requirements for the simulator:

Multiple Students will be using the simulator at the same time.

The teacher should be able to see or track their changes and queries.

DDL should be included (e.g, CREATE, ALTER, DROP DATABASES & TABLES), of course certain privileges are enforced as to not ruin the database.

And also a simulation using MySQL directly obviously won't work. So, to anyone who has a suggestion on how to go about doing this, that would be awesome.

答:
Hmmm quite a difficult task you got there...

I would try an approach like this:

Create a sample database with some entries and tables based on the task for the students

Whenever a students logs in and starts the task, copy this sample database for this specific user

Create an input field for all MySQL commands in your view and an execute button

Whenever the student clicks on execute: log his input and maybe the current database state to a log and execute the command on the database created for the user and return the return values you get from MySQL (errors, messages or selects) to the user

This approach is easy and reliable because the student can't harm another database besides his own (provided the database rights are configured correctly) and he can just restore the database from the sample database if he f*cked up.

It should also meet your requirements:

Multiple students can work on it simultaneously: Check

The teacher can track their changes: Check

DDL is possible and the student can't harm anything besides his own DB: Check


问:
How to create Kiosk which shows a page for a number of seconds and then another
I would like to develop a web application which should run in kiosk mode. It should have two modes for displaying information in sequences on two monitors.

Mode1 should display on monitor1 this sequence: Screen 1 (x seconds) -> Screen2 (y seconds) -> Screen 3 (x seconds) and repeat

Mode 2 should should display on monitor2 this sequence: Screen 1 (x seconds) -> Screen 3 (y seconds) and repeat

Unfortunately I have almost no idea how to implement the logic.
Maybe with iframes?

I would prefer a centralized solution.

E.g. when I go to http://localhost:8084/monitor1 it should display mode1 screen sequence without reloading page

And when I go to http://localhost:8084/monitor2 it should display mode2 screen sequence without reloading the page

Thanks in advance.

答:
Please provide more info on what exactly you need to develop. As per my assumption, you need something like this</p>

```<code>            var timer = setInterval(function () {
                //Your logic goes here
            }, 10)
</code>```

Body:
Please provide more info on what exactly you need to develop. As per my assumption, you need something like this

            var timer = setInterval(function () {
                //Your logic goes here
            }, 10)


问:
How to get audio path to play audio file?
This is my code that gets list of songs:

```<code>  List<String> getsonglist() {

        List<String> songlist = new ArrayList<>();
        ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        Cursor cursor = contentResolver.query(uri, null, null, null, null);
        if (cursor == null) {
            // query failed, handle error.
        } else if (!cursor.moveToFirst()) {
            // no media on the device
        } else {
            int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
            int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
            do {
                long thisId = cursor.getLong(idColumn);
                String thisTitle = cursor.getString(titleColumn);
                // ...process entry...

                songlist.add(thisTitle);
            } while (cursor.moveToNext());
        }

        return songlist;
    }
</code>```

I want to play that song by giving its path to music player() method.

答:
Try this one</p>

```<code>String fullPath = cursor.getString(cursor.getColumnIndex("_data"));
</code>```

Body:
This is my code that gets list of songs:

  List<String> getsonglist() {

        List<String> songlist = new ArrayList<>();
        ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        Cursor cursor = contentResolver.query(uri, null, null, null, null);
        if (cursor == null) {
            // query failed, handle error.
        } else if (!cursor.moveToFirst()) {
            // no media on the device
        } else {
            int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
            int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
            do {
                long thisId = cursor.getLong(idColumn);
                String thisTitle = cursor.getString(titleColumn);
                // ...process entry...

                songlist.add(thisTitle);
            } while (cursor.moveToNext());
        }

        return songlist;
    }

I want to play that song by giving its path to music player() method.

Body:
Try this one

String fullPath = cursor.getString(cursor.getColumnIndex("_data"));


问:
Rails SQL injection vulnerability
Does using Model.find(params[:id]) can lead to sql injection vulnerability?

答:
No, it can't. Quote from Guides (http://guides.rubyonrails.org/security.html#sql-injection):

Ruby on Rails has a built-in filter for special SQL characters, which will escape ' , " , NULL character and line breaks. Using Model.find(id) or Model.find_by_some thing(something) automatically applies this countermeasure.

BTW you probably meant Model.find(params[:id]) or Model.find_by(id: params[:id]), Model.find(id: params[:id]) makes no sense.

Title: Rails SQL injection vulnerability


问:
Vue2 Router link from server data
I have a Vue2 SPA page which is loading content from the server.
It is editable by client in a CMS.

When user is adding relative link (lets say /about-us), this should be picked by Vue and treated as the menu link (which already has /about-us link).

However link to /about-us added in the content is reloading the whole page, so it is not picked as vue route.

How is it possible to attach router to such links?

What I did so far is changing the content in the backend response.

So I am essentially changing

```<code><a href="/about-us">Text</a>
</code>```

into

```<code><router-link :to="{ path: '/about-us'}">Text</router-link>
</code>```

Using:

```<code>function parseVueLinks($value)
{
    $pattern = "/<a([^>]*) href=\\\"[^http|https|mailto|tel]([^\\\"]*)\"([^>]*)>(.*?)<(\\/a>)/";
    $replace = "<router-link$1 :to=\"{ path: '$2'}\">$4</router-link>";

    return preg_replace($pattern, $replace, $value);
}
</code>```

Still no luck.

How is this possible?

答:
The simplest regex pattern to do this is /]*)">(.+)<\/a>/.

Test example:

console.clear()

const parseVueLinks = ($value) => {
  const re = /]*)">(.+)<\/a>/g;
  const matches = re.exec($value);
  return `<router-link :to="{ path: '${matches[1]}'}">${matches[2]}</router-link>`
}

console.log(parseVueLinks('Text'))
console.log(parseVueLinks('Goooooogle'))```
</div>
</div>
</p>
<br/>
I don't know PHP, but am guessing the equivalent PHP might be (tested at https://www.functions-online.com/preg_match.html):
```function parseVueLinks($value)
{
  $pattern = "/]*)">(.+)<\/a>/";
  $matches = [];
  preg_match($pattern, $replace, $matches);
  return "<router-link :to=\"{ path: '" + $matches[1] + "'}\">" + $matches[2] + "</router-link>";
}
```
<p>I'm wondering about the presence of <code>http|https|mailto|tel</code> in your regex, does this mean you want to do some validation on the link?</p>
<p>If so, using <code>preg_match()</code> allows a second regex step to be performed on <code>$matches[1]</code> before output. It would seem simpler to validate as a second step rather than using one big regex.</p>
<hr />
<h2><strong>Edit following comment</strong></h2>
<blockquote>
<p>The issue is not in regex. It is in Vue not parsing content pulled from the server</p>
</blockquote>
<p>This may not apply if you're using server side rendering, but this is how I apply links from content.</p>
<p><strong>MyComponent.ts</strong></p>
<pre class="lang-html prettyprint-override"><code><template>
  <div class="row">
    ...
      <router-link :to="'/' + measure.link" class="measure">
        <i class="measure-icon fa fa-lg" :class="measure.icon" aria-hidden="true">
          <span class="title">{{measure.title}}</span>
        </i>
      </router-link>
</code>```

Here, measure is an object that is fetched from the server. I you are fetching the full <router-link>, that may work with a href="https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components" rel="nofollow noreferrer">Dynamic Component but it seems like overkill, since you know the element will be a <router-link.

Note, if there's also a problem with the server responding with 404 to the click, you can use hash-mode routing (default) by adding # before the link, e.g #/about-us.

Alternatively, set history mode in the Vue router.

const router = new Router({
  routes,
  mode: 'history'
})
```
<p>This requires the server to redirect to <code>index.html</code> for a 404. See href="https://router.vuejs.org/en/essentials/history-mode.html" rel="nofollow noreferrer">HTML History Mode.</p>
<p>Also, you then need to handle <strong>404</strong> in Vue with a catch-all route,</p>
```const routes = [
  ...
  { path: '*', component: NotFoundComponent },
]
```

Title: Vue2 Router link from server data

Body:
I have a Vue2 SPA page which is loading content from the server.
It is editable by client in a CMS.

When user is adding relative link (lets say /about-us), this should be picked by Vue and treated as the menu link (which already has /about-us link).

However link to /about-us added in the content is reloading the whole page, so it is not picked as vue route.

How is it possible to attach router to such links?

What I did so far is changing the content in the backend response.

So I am essentially changing

Text

into

<router-link :to="{ path: '/about-us'}">Text</router-link>

Using:

function parseVueLinks($value)
{
    $pattern = "/]*) href=\\\"[^http|https|mailto|tel]([^\\\"]*)\"([^>]*)>(.*?)<(\\/a>)/";
    $replace = "<router-link$1 :to=\"{ path: '$2'}\">$4</router-link>";

    return preg_replace($pattern, $replace, $value);
}

Still no luck.

How is this possible?

Body:
The simplest regex pattern to do this is /<a href="([^>]*)">(.+)<\/a>/.

Test example:

console.clear()

const parseVueLinks = ($value) => {
  const re = /<a href="([^>]*)">(.+)<\/a>/g;
  const matches = re.exec($value);
  return `<router-link :to="{ path: '${matches[1]}'}">${matches[2]}</router-link>`
}

console.log(parseVueLinks('<a href="/about-us">Text</a>'))
console.log(parseVueLinks('<a href="http://google.com">Goooooogle</a>'))

I don't know PHP, but am guessing the equivalent PHP might be (tested at https://www.functions-online.com/preg_match.html):

function parseVueLinks($value)
{
  $pattern = "/<a href="([^>]*)">(.+)<\/a>/";
  $matches = [];
  preg_match($pattern, $replace, $matches);
  return "<router-link :to=\"{ path: '" + $matches[1] + "'}\">" + $matches[2] + "</router-link>";
}

I'm wondering about the presence of http|https|mailto|tel in your regex, does this mean you want to do some validation on the link?

If so, using preg_match() allows a second regex step to be performed on $matches[1] before output. It would seem simpler to validate as a second step rather than using one big regex.

Edit following comment

The issue is not in regex. It is in Vue not parsing content pulled from the server

This may not apply if you're using server side rendering, but this is how I apply links from content.

MyComponent.ts

<template>
  <div class="row">
    ...
      <router-link :to="'/' + measure.link" class="measure">
        <i class="measure-icon fa fa-lg" :class="measure.icon" aria-hidden="true">
          <span class="title">{{measure.title}}</span>
        </i>
      </router-link>

Here, measure is an object that is fetched from the server. I you are fetching the full <router-link>, that may work with a Dynamic Component but it seems like overkill, since you know the element will be a <router-link.

Note, if there's also a problem with the server responding with 404 to the click, you can use hash-mode routing (default) by adding # before the link, e.g #/about-us.

Alternatively, set history mode in the Vue router.

const router = new Router({
  routes,
  mode: 'history'
})

This requires the server to redirect to index.html for a 404. See HTML History Mode.

Also, you then need to handle 404 in Vue with a catch-all route,

const routes = [
  ...
  { path: '*', component: NotFoundComponent },
]

ContentLicense: CC BY-SA 4.0


问:
C++ regex: convert C# regex to C++ Linux
I can I convert exactly this regex in c#:

```<code>Regex (@"\s*nameserver\s+(?<address>.*)")
Regex (@"\s*search\s+(?<domain>.*)")
</code>```

to std::tr1::regex or to regex.h in C++? (Linux)

thanks!

答:
std::tr1::regex in GCC is incompelete. std::regex have bugs.

Consider boost::regex.

Body:
I can I convert exactly this regex in c#:

Regex (@"\s*nameserver\s+(?<address>.*)")
Regex (@"\s*search\s+(?<domain>.*)")

to std::tr1::regex or to regex.h in C++? (Linux)

thanks!


问:
Java exceptions wrapping: bad practice?
Coming from a PHP world where there's only one way to write exceptions handling.. I found the wrapping of exceptions in Java a bit "ugly":

```<code>public void exampleOneException(String input) throws MyBusinessException {
    try {
        // do something
    } catch (NumberFormatException e) {
        throw new MyBusinessException("Error...", e);
    }
}
</code>```

I prefer to use this style instead:

```<code>public void exampleTwoException() {
    try {
        // do something
    } catch (MyBusinessException e) {
        log.error("Error...: " + e);
    } catch (NumberFormatException e) {
        log.error("Error...: " + e);
    }
}
</code>```

Is there any difference or best practices on those approaches on handling exceptions?

答:
The first example would generally be seen as the better approach.

You should also not consider the MyBusinessException to be wrapping the NumberFormatException, but rather the NumberFormatException is the cause of the MyBusinessException.

Exceptions should be appropriate for the interface being exposed. A caller of your interface should not need to know, or deal with, the implementation details. Unless a NumberFormatException genuinely makes sense as a type of error when calling exampleOneException, it should be translated into a more suitable exception.

A more concrete example typically includes differing implementations, where the users of the interface should not be required to deal with the implementation specifics (which may not even be known at compile time).

```<code>interface MyRepository {
    Object read(int id) throws ObjectNotFoundException;
}

// a sql backed repository
class JdbcRepository implements MyRepository {
    public Object read(int id) throws ObjectNotFoundException {
        try { ... }
        catch (SQLException ex) {
            throw new ObjectNotFoundException(ex);
        }
    }
 }

// a file backed repository
class FileRepository implements MyRepository {
    public Object read(int id) throws ObjectNotFoundException {
        try { ... }
        catch (FileNotFoundException ex) {
            throw new ObjectNotFoundException(ex)
        }
    }
}
</code>```

Because the interface declares the types of errors it can return, the clients of that interface can be consistent and rational. Adding code to handle FileNotFoundException and SQLException then the actual implementation may be either, or neither, is not fantastic.

Consider if there were multiple places in the implementation of FileRepository which could throw FileNotFoundException. Does that imply each and every one of them implies object not found?

When considering option two, exampleTwoException, it's important to realise that your catch block is effectively stating that the effects of whatever error occurred have been mitigated. There are cases where checked exceptions are reasonably ignored, but it is far more likely that a simple

```<code>try { ... }
catch (SomeException ex) {
    log.error("caught some exception", ex);
}
</code>```

is actually the result of a developer not considering the consequences of the exception, or the code should have included a FIXME.

This is even more true when you see catch (Exception ex), or the unconscionable catch (Throwable ex).

And finally, would you want to be the person to dig through an application finding all the places where you need to add (yet) another catch block to handle a new implementation? Perhaps that's a cause of catch (Exception ex)...

Always throw exceptions appropriate to the abstraction

Title: Java exceptions wrapping: bad practice?

Body:
Coming from a PHP world where there's only one way to write exceptions handling.. I found the wrapping of exceptions in Java a bit "ugly":

public void exampleOneException(String input) throws MyBusinessException {
    try {
        // do something
    } catch (NumberFormatException e) {
        throw new MyBusinessException("Error...", e);
    }
}

I prefer to use this style instead:

public void exampleTwoException() {
    try {
        // do something
    } catch (MyBusinessException e) {
        log.error("Error...: " + e);
    } catch (NumberFormatException e) {
        log.error("Error...: " + e);
    }
}

Is there any difference or best practices on those approaches on handling exceptions?

Body:
The first example would generally be seen as the better approach.

You should also not consider the MyBusinessException to be wrapping the NumberFormatException, but rather the NumberFormatException is the cause of the MyBusinessException.

Exceptions should be appropriate for the interface being exposed. A caller of your interface should not need to know, or deal with, the implementation details. Unless a NumberFormatException genuinely makes sense as a type of error when calling exampleOneException, it should be translated into a more suitable exception.

A more concrete example typically includes differing implementations, where the users of the interface should not be required to deal with the implementation specifics (which may not even be known at compile time).

interface MyRepository {
    Object read(int id) throws ObjectNotFoundException;
}

// a sql backed repository
class JdbcRepository implements MyRepository {
    public Object read(int id) throws ObjectNotFoundException {
        try { ... }
        catch (SQLException ex) {
            throw new ObjectNotFoundException(ex);
        }
    }
 }

// a file backed repository
class FileRepository implements MyRepository {
    public Object read(int id) throws ObjectNotFoundException {
        try { ... }
        catch (FileNotFoundException ex) {
            throw new ObjectNotFoundException(ex)
        }
    }
}

Because the interface declares the types of errors it can return, the clients of that interface can be consistent and rational. Adding code to handle FileNotFoundException and SQLException then the actual implementation may be either, or neither, is not fantastic.

Consider if there were multiple places in the implementation of FileRepository which could throw FileNotFoundException. Does that imply each and every one of them implies object not found?

When considering option two, exampleTwoException, it's important to realise that your catch block is effectively stating that the effects of whatever error occurred have been mitigated. There are cases where checked exceptions are reasonably ignored, but it is far more likely that a simple

try { ... }
catch (SomeException ex) {
    log.error("caught some exception", ex);
}

is actually the result of a developer not considering the consequences of the exception, or the code should have included a FIXME.

This is even more true when you see catch (Exception ex), or the unconscionable catch (Throwable ex).

And finally, would you want to be the person to dig through an application finding all the places where you need to add (yet) another catch block to handle a new implementation? Perhaps that's a cause of catch (Exception ex)...

Always throw exceptions appropriate to the abstraction


问:
Cannot resolve GoogleSignIn and GoogleSignInClient
I am not able to use GoogleSignIn(com.google.android.gms.auth.api.signin.GoogleSignIn
) and GoogleSignInClient(com.google.android.gms.auth.api.signin.GoogleSignInClient
) while implementing Google Sign In in Android Studio while I can access other classes in App like

```<code>com.google.android.gms.auth.api.signin.GoogleSignInAccount;
com.google.android.gms.auth.api.signin.GoogleSignInOptions;
com.google.android.gms.common.SignInButton;
</code>```

A strip down version of my build.gradle(app) file is as follow

```<code>android {

}

dependencies {

    compile 'com.google.android.gms:play-services-auth:11.4.2'
    compile('com.google.api-client:google-api-client-android:1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    compile('com.google.apis:google-api-services-gmail:v1-rev72-1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    implementation 'com.google.gms:google-services:3.1.2'
}

apply plugin: 'com.google.gms.google-services'
</code>```

and my build.gradle(package) is

```<code>buildscript {

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.1.2'
    }
}
</code>```

Any help would be appreciated

答:
For me I was applying a plugin for the google play services in my app's build.gradle:

```<code>apply plugin: 'com.google.gms.google-services'
</code>```

along with that in my Project's Build.gradle I had google services.

```<code>buildscript {
    ext.kotlin_version = '1.1.60'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.google.gms:google-services:3.1.2' // <== this guy
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
</code>```

I remember I added them with some compiling issues. But apparently I didn't need them.

By removing them I found there were no more issues with the gms versions.

EDIT

So removing solved my issue initially, but gave me issues later with google sign in. adding the apply plugin: 'com.google.gms.google-services' to the bottom of my projects gradle instead of at the top did actually solve it.

Body:
I am not able to use GoogleSignIn(com.google.android.gms.auth.api.signin.GoogleSignIn
) and GoogleSignInClient(com.google.android.gms.auth.api.signin.GoogleSignInClient
) while implementing Google Sign In in Android Studio while I can access other classes in App like

com.google.android.gms.auth.api.signin.GoogleSignInAccount;
com.google.android.gms.auth.api.signin.GoogleSignInOptions;
com.google.android.gms.common.SignInButton;

A strip down version of my build.gradle(app) file is as follow

android {

}

dependencies {

    compile 'com.google.android.gms:play-services-auth:11.4.2'
    compile('com.google.api-client:google-api-client-android:1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    compile('com.google.apis:google-api-services-gmail:v1-rev72-1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    implementation 'com.google.gms:google-services:3.1.2'
}

apply plugin: 'com.google.gms.google-services'

and my build.gradle(package) is

buildscript {

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.1.2'
    }
}

Any help would be appreciated

Body:
For me I was applying a plugin for the google play services in my app's build.gradle:

apply plugin: 'com.google.gms.google-services'

along with that in my Project's Build.gradle I had google services.

buildscript {
    ext.kotlin_version = '1.1.60'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.google.gms:google-services:3.1.2' // <== this guy
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

I remember I added them with some compiling issues. But apparently I didn't need them.

By removing them I found there were no more issues with the gms versions.

EDIT

So removing solved my issue initially, but gave me issues later with google sign in. adding the apply plugin: 'com.google.gms.google-services' to the bottom of my projects gradle instead of at the top did actually solve it.


问:
How to change color of bootstrap glyphicon .?
How do I change the color of my star glyphicon? My code is

```<code><span  class="glyphicon glyphicon-star-empty " onclick = "addToFav()">      </span>
</code>```

I am calling a javascript function on the click of glyphicon. I also want to change the color of the glyphicon as shown in the image below. I tried changing the background color of the gyphicon but it doesn't give me the desired output.
**Update"' On changing the style.color of the glyphicon, it just changes the color of the glyphicon but doesn't fill the glypicon with the desired color. The first image is the original glyphicon. The second image is the desired result. The third image is the glyphicon on changing the background color of the glyphicon. The fourth image shows what happens to glyphicon on changing style.color of glyphicon to red.

答:
Try with this.</p>

```<code> <span  class="glyphicon glyphicon-star-empty " onclick = "addToFav(this)"> </span>
<script>
    function addToFav(ths){
        ths.style.color = "#ffea00";
    }
</script>
</code>```

Body:
How do I change the color of my star glyphicon? My code is

I am calling a javascript function on the click of glyphicon. I also want to change the color of the glyphicon as shown in the image below. I tried changing the background color of the gyphicon but it doesn't give me the desired output.
**Update"' On changing the style.color of the glyphicon, it just changes the color of the glyphicon but doesn't fill the glypicon with the desired color. The first image is the original glyphicon. The second image is the desired result. The third image is the glyphicon on changing the background color of the glyphicon. The fourth image shows what happens to glyphicon on changing style.color of glyphicon to red.

Body:
Try with this.

 <span  class="glyphicon glyphicon-star-empty " onclick = "addToFav(this)"> </span>
<script>
    function addToFav(ths){
        ths.style.color = "#ffea00";
    }
</script>


问:
Is it better to use the column name or column index on .Net DataSets?
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

```<code>int price = (int)dr["Price"];
</code>```

While column index is just faster (I think):

```<code>int price = (int)dr[3];
</code>```

Would using column names break if you decide to obfuscate the database?

答:
for me, I'm using reflection(not sure it's the correct way to name what I do) to get the columnnameColumn from the table

no "hardcoding" is better

```<code>  int price = (int)dr[DatableVar.PriceColumn];
</code>```

OwnerDisplayName: tpower

Body:
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

int price = (int)dr["Price"];

While column index is just faster (I think):

int price = (int)dr[3];

Would using column names break if you decide to obfuscate the database?

LastEditorDisplayName: tpower

Body:
for me, I'm using reflection(not sure it's the correct way to name what I do) to get the columnnameColumn from the table

no "hardcoding" is better

  int price = (int)dr[DatableVar.PriceColumn];

OwnerDisplayName: Fredou


问:
Excel if 2 rows are similar, delete the second one
I have a sheet with generated dates, for example :

This cells are generated by my software. There are 2 calculations : of bank vs the analyst.
In this 2 tables are included only charges that current loan has.

In already generated Excel as you can see attached, I want to write a formula that compare each Charge (Interest, Frais de garantie, etc) from first "table" with the same values from the second table. If values of this charges (6938.82, 236.75) are equal, then delete all row from the second table.
In the second table I want to remain only the charges that has the red value, I mean only the charges that has value 0 in first table.

I don't know how to do it in Excel, I'm a PHP developer and have somehow to solve current issue.
I see it kind of :

If text-cell from column A has a match in same column, compare their values from column B. If values are equal, delete entire row from the second table, else -> do nothing.

To generate the Excel I am using PHPExcel.

答:
In Microsoft Office it would be easy with VBA, but in LibreOffice you can't use the Microsoft script language. You may be able to do it with Libre-Office Basic. Which don't have really good documentation or examples.

But when you already generate a excel file from your program, why don't you handle this in the generating program? It is easy to ready and manipulate excel files from C#/Java/Python etc. I never tried this in PHP, but it should be possible to.

See this GitHub Project:
https://github.com/PHPOffice/PHPExcel


问:
setting font for a project
currently practicing making an application using android studio.
I have this customized font and saved into res/font directory for the later use.
Inside the activity, i am trying to call getfont(R.font.my_customized_font) with the typeface object. ex) Typeface font = getResources().getfont(R.font.mycustomizedfont)

However, when i try to run the project with the actual device which has the API level 24, it won't activate since the getfont() method requires the min sdk level with 26.

I know that you can set the font of text view in the xml file by doing android:fontfamily but i am using the textswitcher instead of textview.

Emulator works fine by setting up min sdk with 26 but I would like to figure this out by using the actual device.

I found the solution by reading through the developer's website
I just added Typeface font = ResourcesCompat.getfont(context, R.font.mycustomizedfont)

答:
You can use via xml layout simple is that just use like this:-

```<code>android:fontFamily="@fonts/avenir"
</code>```

Instead of avenir use your font name under res/font folder.
Hope it will help you.

Title: setting font for a project

Body:
You can use via xml layout simple is that just use like this:-

android:fontFamily="@fonts/avenir"

Instead of avenir use your font name under res/font folder.
Hope it will help you.


问:
jquery traversing an appended to ol/ul
I'm trying to traverse a ul that has been appended to before traversing like so:

```<code>var items = [];
$('#list').append('<li id="item_10">item 10</li>');
$('#list').each(function () {
    var item = $(this).attr('id');
    items.push(item);
});
alert(items.toString());
</code>```

But when I alert the output I don't see the item I added. Anyone have a clue on how I can add to a list then traverse it?

答:
You are looping over the ul parent. Probably want something like

```<code>$('#list li').each(function() {
});
</code>```

to loop over the li nodes.

Title: jquery traversing an appended to ol/ul

Body:
I'm trying to traverse a ul that has been appended to before traversing like so:

var items = [];
$('#list').append('
item 10
');
$('#list').each(function () {
    var item = $(this).attr('id');
    items.push(item);
});
alert(items.toString());

But when I alert the output I don't see the item I added. Anyone have a clue on how I can add to a list then traverse it?

Body:
You are looping over the ul parent. Probably want something like

$('#list li').each(function() {
});

to loop over the li nodes.