问:
MySQL query - find "new" users per day
I have a table of data with the following fields

```<code>EventID        : Int, AutoIncrement, Primary Key
EventType      : Int                             ' Defines what happened
EventTimeStamp : DateTime                        ' When the Event Happened
UserID         : Int                             ' Unique
</code>```

The query needs to tell me how many events occurred with new UserIDs for each day in the whole set. So, for each day, how many events exist which have a UserID which doesn't exist in any prior day. I've tried lots, and I can get unique users per day, but can't work out how to get 'NEW' users per day.

答:
Thank you all for your help - I've voted up the assistance. Here's what I did:

I created these 2 views (I needed to end up with a view, and had to create 2 as it seems you can't nest select statements within views).

Sightings:

```<code>select min(to_days(`Events`.TimeStamp)) AS Day0,
    `Events`.TimeStamp AS TimeStamp,
    `Events`.UserID AS UserID
from `Events` group by `Events`.UserID order by `Events`.UserID
</code>```

NewUsers:

```<code>select count(distinct Sightings.UserID) AS Count,
    date(Sightings.TimeStamp) AS Date from Sightings
    group by date(Sightings.TimeStamp)
</code>```

Title: MySQL query - find "new" users per day

Body:
I have a table of data with the following fields

EventID        : Int, AutoIncrement, Primary Key
EventType      : Int                             ' Defines what happened
EventTimeStamp : DateTime                        ' When the Event Happened
UserID         : Int                             ' Unique

The query needs to tell me how many events occurred with new UserIDs for each day in the whole set. So, for each day, how many events exist which have a UserID which doesn't exist in any prior day. I've tried lots, and I can get unique users per day, but can't work out how to get 'NEW' users per day.

Body:
Thank you all for your help - I've voted up the assistance. Here's what I did:

I created these 2 views (I needed to end up with a view, and had to create 2 as it seems you can't nest select statements within views).

Sightings:

select min(to_days(`Events`.TimeStamp)) AS Day0,
    `Events`.TimeStamp AS TimeStamp,
    `Events`.UserID AS UserID
from `Events` group by `Events`.UserID order by `Events`.UserID

NewUsers:

select count(distinct Sightings.UserID) AS Count,
    date(Sightings.TimeStamp) AS Date from Sightings
    group by date(Sightings.TimeStamp)


来源: stackexchange

问:
Get Index of an Item in a List of Class Items with Timer Member
I am trying to find the index of the Triggered Timer.

I created a list of Class Entry here in Program.cs

```<code>static public List<Entry> Table = new List<Entry>();
</code>```

This is the class called "Entry" with its constructors in Entry.cs

```<code>public class Entry
    {
        public int pktID;

        public Timer pktTimer= new Timer();
    }

public Entry()
      {
      }

public Entry(int _pktID, Boolean idleTimeOutStart)
        {
            this.pktID = _pktID;

            if (idleTimeOutStart == true)
            {
                pktTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());

                pktTimer.Interval = 10000; // 10000 ms is 10 seconds
                pktTimer.Start();

            }

        }

static void CallDeleteEntry(object sender, System.Timers.ElapsedEventArgs e, int pktIndex)
        {
            Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
            Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
        }
</code>```

The items in the list are created randomly. Now each Timer in the List (List Index) will start and then after 10000 msecs, CallDeleteEntry shall be called.

What I need to do is the pass the Index of the Timer when it elapses 10000msec to CallDeleteEntry, so it can remove that item row for the list.

I think something must be modified here to make it work.

```<code>idleTimeOutTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());
</code>```

The List will look like this

ListIndex | Entry Item

    0     |  pkt | pktTimer

    1     |  pkt | pktTimer

    2     |  pkt | pktTimer

    3     |  pkt | pktTimer

    4     |  pkt | pktTimer

答:
@Jason Mastnick

What caused the above error I mentioned in my comments to you was

```<code>            Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
            Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
</code>```

I should stop the timer first, then remove the packet

```<code>            Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
            Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
</code>```

By the way, your solution works. I should write it like this.

```<code>pktTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf(this));
</code>```

However, a problem occurs. I tried adding the Entries in the List sequentially. The first pktIndex passed is "1" not "0". Since the first item is added at Index 0. It should be the one to be removed first in this sequential scenario. Everything Works well, expect that this first item at Index 0 is not removed. Any ideas?

ContentLicense: CC BY-SA 3.0

Body:
I am trying to find the index of the Triggered Timer.

I created a list of Class Entry here in Program.cs

static public List<Entry> Table = new List<Entry>();

This is the class called "Entry" with its constructors in Entry.cs

public class Entry
    {
        public int pktID;

        public Timer pktTimer= new Timer();
    }

public Entry()
      {
      }

public Entry(int _pktID, Boolean idleTimeOutStart)
        {
            this.pktID = _pktID;

            if (idleTimeOutStart == true)
            {
                pktTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());

                pktTimer.Interval = 10000; // 10000 ms is 10 seconds
                pktTimer.Start();

            }

        }

static void CallDeleteEntry(object sender, System.Timers.ElapsedEventArgs e, int pktIndex)
        {
            Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
            Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
        }

The items in the list are created randomly. Now each Timer in the List (List Index) will start and then after 10000 msecs, CallDeleteEntry shall be called.

What I need to do is the pass the Index of the Timer when it elapses 10000msec to CallDeleteEntry, so it can remove that item row for the list.

I think something must be modified here to make it work.

idleTimeOutTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());

The List will look like this

ListIndex | Entry Item

    0     |  pkt | pktTimer

    1     |  pkt | pktTimer

    2     |  pkt | pktTimer

    3     |  pkt | pktTimer

    4     |  pkt | pktTimer

Body:
@Jason Mastnick

What caused the above error I mentioned in my comments to you was

            Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
            Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry

I should stop the timer first, then remove the packet

            Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
            Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index

By the way, your solution works. I should write it like this.

pktTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf(this));

However, a problem occurs. I tried adding the Entries in the List sequentially. The first pktIndex passed is "1" not "0". Since the first item is added at Index 0. It should be the one to be removed first in this sequential scenario. Everything Works well, expect that this first item at Index 0 is not removed. Any ideas?


问:
"An error occurred while installing sqlite3 (1.3.13), and Bundler cannot continue"
I am trying to run a bundle install, but when I do, I am getting an error message that says, "An error occurred while installing sqlite3 (1.3.13), and Bundler cannot continue." I tried running gem install sqlite3 -v '1.3.13', but am getting an error with that as well.

Here is my Gemfile:

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

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.1'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Use sqlite3 as the database for Active Record
    gem 'sqlite3'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

group :production do
    gem 'pg'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem 'jquery-rails'

gem 'devise'
</code>```

Here is the error I get when I try to run bundle install:

```<code>Kelly@LAPTOP /c/Sites/my_app (master)
$ bundle install
Fetching gem metadata from https://rubygems.org/.............
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies..................
Using rake 12.0.0
Using concurrent-ruby 1.0.5 (java)
Using i18n 0.8.4
Using minitest 5.10.2
Using thread_safe 0.3.6 (java)
Using builder 3.2.3
Using erubi 1.6.0
Using nokogiri 1.8.0 (java)
Using rack 2.0.3
Using nio4r 2.1.0 (java)
Using websocket-extensions 0.1.2
Using mime-types-data 3.2016.0521
Using arel 8.0.0
Using bundler 1.15.1
Using method_source 0.8.2
Using thor 0.19.4
Using puma 3.9.1 (java)
Using sass 3.4.24
Using tilt 2.0.7
Using execjs 2.7.0
Using coffee-script-source 1.12.2
Using turbolinks-source 5.0.3
Using multi_json 1.12.1
Fetching sqlite3 1.3.13
Installing sqlite3 1.3.13 with native extensions
C:/jruby-9.1.8.0/lib/ruby/stdlib/rubygems/ext/ext_conf_builder.rb:56: warning: Tempfile#unlink or delete called on open file; ignoring
Fetching bindex 0.5.0
Installing bindex 0.5.0 with native extensions
C:/jruby-9.1.8.0/lib/ruby/stdlib/rubygems/ext/ext_conf_builder.rb:56: warning: Tempfile#unlink or delete called on open file; ignoring
Using bcrypt 3.1.11 (java)
Using orm_adapter 0.5.0
Using tzinfo 1.2.3
Using loofah 2.0.3
Using rack-test 0.6.3
Using sprockets 3.7.1
Using warden 1.2.7
Using websocket-driver 0.6.5 (java)
Using mime-types 3.1
Using uglifier 3.2.0
Using coffee-script 2.4.1
Using turbolinks 5.0.1
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/sqlite3-1.3.13/ext/sqlite3
C:/jruby-9.1.8.0/bin/jruby.exe -r ./siteconf20170707-17112-s04bux.rb extconf.rb
checking for sqlite3.h... RuntimeError: The compiler failed to generate an
executable file.
You have to install development tools first.

                 try_do at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:456
                try_cpp at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:587
   block in find_header at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:1144
  block in checking_for at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:942
      block in postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:350
                   open at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:320
      block in postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:350
                   open at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:320
               postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:346
           checking_for at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:941
            find_header at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:1143
                 <main> at extconf.rb:50
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/jruby-9.1.8.0/bin/jruby
        --with-sqlite3-config
        --without-sqlite3-config
        --with-pkg-config
        --without-pkg-config
        --with-sqlite3-dir
        --without-sqlite3-dir
        --with-sqlite3-include
        --without-sqlite3-include=${sqlite3-dir}/include
        --with-sqlite3-lib
        --without-sqlite3-lib=${sqlite3-dir}/lib

To see why this extension failed to compile, please check the mkmf.log which can
be found here:

C:/jruby-9.1.8.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.3.0/sqlite3-1.3.13/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/sqlite3-1.3.13 for inspection.
Results logged to
C:/jruby-9.1.8.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.3.0/sqlite3-1.3.13/gem_make.out

An error occurred while installing sqlite3 (1.3.13), and Bundler cannot
continue.
Make sure that `gem install sqlite3 -v '1.3.13'` succeeds before bundling.

In Gemfile:
  sqlite3
</code>```

Here is the error I get when I try to run gem install sqlite -v '1.3.13':

```<code>Kelly@LAPTOP /c/Sites/my_app (master)
$ gem install sqlite3 -v '1.3.13'
Building native extensions.  This could take a while...
C:/jruby-9.1.8.0/lib/ruby/stdlib/rubygems/ext/ext_conf_builder.rb:56: warning: Tempfile#unlink or delete called on open file; ignoring
ERROR:  Error installing sqlite3:
        ERROR: Failed to build gem native extension.

    current directory: C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/sqlite3-1.3.13/ext/sqlite3
C:/jruby-9.1.8.0/bin/jruby.exe -r ./siteconf20170707-17048-ojikan.rb extconf.rb
checking for sqlite3.h... RuntimeError: The compiler failed to generate an executable file.
You have to install development tools first.

                 try_do at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:456
                try_cpp at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:587
   block in find_header at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:1144
  block in checking_for at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:942
      block in postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:350
                   open at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:320
      block in postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:350
                   open at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:320
               postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:346
           checking_for at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:941
            find_header at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:1143
                 <main> at extconf.rb:50
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/jruby-9.1.8.0/bin/jruby
        --with-sqlite3-config
        --without-sqlite3-config
        --with-pkg-config
        --without-pkg-config
        --with-sqlite3-dir
        --without-sqlite3-dir
        --with-sqlite3-include
        --without-sqlite3-include=${sqlite3-dir}/include
        --with-sqlite3-lib
        --without-sqlite3-lib=${sqlite3-dir}/lib

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  C:/jruby-9.1.8.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.3.0/sqlite3-1.3.13/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/sqlite3-1.3.13 for inspection.
Results logged to C:/jruby-9.1.8.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.3.0/sqlite3-1.3.13/gem_make.out
</code>```

Any help is appreciated as I cannot move forward until I run a successful bundle install and I've tried researching for days and cannot figure out how to fix this.

Updated 7/9/17: Here is my updated Gemfile where I am still not able to run bundle install nor bundle update:

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

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.1'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Use sqlite3 as the database for Active Record
    gem 'sqlite3', platform: :ruby
    gem 'jdbc-sqlite3', platform: :jruby
    gem 'activerecord-jdbc-adapter', platform: :jruby
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

group :production do
    gem 'pg'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem 'jquery-rails'

gem 'activerecord-jdbcsqlite3-adapter', '~> 1.3', '>= 1.3.23'
</code>```

Updated 7/10/17: After removing gem 'activerecord-jdbcsqlite3-adapter', '~> 1.3', '>= 1.3.23', I tried bundle install again and this time, I got a different error:

```<code>Kelly@LAPTOP /c/Sites/my_app (master)
$ bundle install
The dependency sqlite3 (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for x86-mingw32, java but the dependency is only for ruby. To add those platforms to the bundle, run `bundle lock --add-platform ruby`.
Fetching gem metadata from https://rubygems.org/...........
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies........................
Using rake 12.0.0
Using concurrent-ruby 1.0.5 (java)
Using i18n 0.8.4
Using minitest 5.10.2
Using thread_safe 0.3.6 (java)
Using builder 3.2.3
Using erubi 1.6.0
Using nokogiri 1.8.0 (java)
Using rack 2.0.3
Using nio4r 2.1.0 (java)
Using websocket-extensions 0.1.2
Using mime-types-data 3.2016.0521
Using arel 8.0.0
Using bundler 1.15.1
Using method_source 0.8.2
Using thor 0.19.4
Using puma 3.9.1 (java)
Using sass 3.4.24
Using tilt 2.0.7
Using execjs 2.7.0
Using coffee-script-source 1.12.2
Using turbolinks-source 5.0.3
Using multi_json 1.12.1
Using jdbc-sqlite3 3.15.1
Fetching bindex 0.5.0
Installing bindex 0.5.0 with native extensions
C:/jruby-9.1.8.0/lib/ruby/stdlib/rubygems/ext/ext_conf_builder.rb:56: warning: Tempfile#unlink or delete called on open file; ignoring
Using tzinfo 1.2.3
Using loofah 2.0.3
Using rack-test 0.6.3
Using sprockets 3.7.1
Using websocket-driver 0.6.5 (java)
Using mime-types 3.1
Using uglifier 3.2.0
Using coffee-script 2.4.1
Using turbolinks 5.0.1
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/bindex-0.5.0/ext/bindex
C:/jruby-9.1.8.0/bin/jruby.exe -r ./siteconf20170710-21728-1asiecp.rb extconf.rb

current directory:
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/bindex-0.5.0/ext/bindex
make "DESTDIR=" clean
'make' is not recognized as an internal or external command,
operable program or batch file.

current directory:
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/bindex-0.5.0/ext/bindex
make "DESTDIR="
'make' is not recognized as an internal or external command,
operable program or batch file.

make failed, exit code 1

Gem files will remain installed in
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/bindex-0.5.0 for inspection.
Results logged to
C:/jruby-9.1.8.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.3.0/bindex-0.5.0/gem_make.out

An error occurred while installing bindex (0.5.0), and Bundler cannot continue.
Make sure that `gem install bindex -v '0.5.0'` succeeds before bundling.

In Gemfile:
  web-console was resolved to 3.5.1, which depends on
    bindex
</code>```

答:
The gem activerecord-jdbcsqlite3-adapter is not yet compatible with Rails 5. I was able to successfully use JRuby with Rails 4.1.3, from a couple of years ago. The team working on JDBC adapters operates on an open source basis, which general means they work for free, so you get what you get.

You have two choices:

1) Uninstall JRuby and use Rails 5 with an MRI-based interpreter; or

2) Use JRuby with an older version of Rails, like 4.2.9 or lower.

My suggestion is to stick with option 1, since you don't have to do anything special at all -- MRI is the normal Ruby interpreter. You also never explained your reasons for choosing JRuby, which makes me suspect a bit of an XY Problem. If you go with option 2, please review your reasons for selecting JRuby and make sure you know both what you're doing and why you're doing it.

Body:
I am trying to run a bundle install, but when I do, I am getting an error message that says, "An error occurred while installing sqlite3 (1.3.13), and Bundler cannot continue." I tried running gem install sqlite3 -v '1.3.13', but am getting an error with that as well.

Here is my Gemfile:

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.1'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Use sqlite3 as the database for Active Record
    gem 'sqlite3'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

group :production do
    gem 'pg'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem 'jquery-rails'

gem 'devise'

Here is the error I get when I try to run bundle install:

Kelly@LAPTOP /c/Sites/my_app (master)
$ bundle install
Fetching gem metadata from https://rubygems.org/.............
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies..................
Using rake 12.0.0
Using concurrent-ruby 1.0.5 (java)
Using i18n 0.8.4
Using minitest 5.10.2
Using thread_safe 0.3.6 (java)
Using builder 3.2.3
Using erubi 1.6.0
Using nokogiri 1.8.0 (java)
Using rack 2.0.3
Using nio4r 2.1.0 (java)
Using websocket-extensions 0.1.2
Using mime-types-data 3.2016.0521
Using arel 8.0.0
Using bundler 1.15.1
Using method_source 0.8.2
Using thor 0.19.4
Using puma 3.9.1 (java)
Using sass 3.4.24
Using tilt 2.0.7
Using execjs 2.7.0
Using coffee-script-source 1.12.2
Using turbolinks-source 5.0.3
Using multi_json 1.12.1
Fetching sqlite3 1.3.13
Installing sqlite3 1.3.13 with native extensions
C:/jruby-9.1.8.0/lib/ruby/stdlib/rubygems/ext/ext_conf_builder.rb:56: warning: Tempfile#unlink or delete called on open file; ignoring
Fetching bindex 0.5.0
Installing bindex 0.5.0 with native extensions
C:/jruby-9.1.8.0/lib/ruby/stdlib/rubygems/ext/ext_conf_builder.rb:56: warning: Tempfile#unlink or delete called on open file; ignoring
Using bcrypt 3.1.11 (java)
Using orm_adapter 0.5.0
Using tzinfo 1.2.3
Using loofah 2.0.3
Using rack-test 0.6.3
Using sprockets 3.7.1
Using warden 1.2.7
Using websocket-driver 0.6.5 (java)
Using mime-types 3.1
Using uglifier 3.2.0
Using coffee-script 2.4.1
Using turbolinks 5.0.1
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/sqlite3-1.3.13/ext/sqlite3
C:/jruby-9.1.8.0/bin/jruby.exe -r ./siteconf20170707-17112-s04bux.rb extconf.rb
checking for sqlite3.h... RuntimeError: The compiler failed to generate an
executable file.
You have to install development tools first.

                 try_do at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:456
                try_cpp at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:587
   block in find_header at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:1144
  block in checking_for at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:942
      block in postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:350
                   open at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:320
      block in postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:350
                   open at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:320
               postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:346
           checking_for at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:941
            find_header at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:1143
                  at extconf.rb:50
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/jruby-9.1.8.0/bin/jruby
        --with-sqlite3-config
        --without-sqlite3-config
        --with-pkg-config
        --without-pkg-config
        --with-sqlite3-dir
        --without-sqlite3-dir
        --with-sqlite3-include
        --without-sqlite3-include=${sqlite3-dir}/include
        --with-sqlite3-lib
        --without-sqlite3-lib=${sqlite3-dir}/lib

To see why this extension failed to compile, please check the mkmf.log which can
be found here:

C:/jruby-9.1.8.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.3.0/sqlite3-1.3.13/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/sqlite3-1.3.13 for inspection.
Results logged to
C:/jruby-9.1.8.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.3.0/sqlite3-1.3.13/gem_make.out

An error occurred while installing sqlite3 (1.3.13), and Bundler cannot
continue.
Make sure that `gem install sqlite3 -v '1.3.13'` succeeds before bundling.

In Gemfile:
  sqlite3

Here is the error I get when I try to run gem install sqlite -v '1.3.13':

Kelly@LAPTOP /c/Sites/my_app (master)
$ gem install sqlite3 -v '1.3.13'
Building native extensions.  This could take a while...
C:/jruby-9.1.8.0/lib/ruby/stdlib/rubygems/ext/ext_conf_builder.rb:56: warning: Tempfile#unlink or delete called on open file; ignoring
ERROR:  Error installing sqlite3:
        ERROR: Failed to build gem native extension.

    current directory: C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/sqlite3-1.3.13/ext/sqlite3
C:/jruby-9.1.8.0/bin/jruby.exe -r ./siteconf20170707-17048-ojikan.rb extconf.rb
checking for sqlite3.h... RuntimeError: The compiler failed to generate an executable file.
You have to install development tools first.

                 try_do at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:456
                try_cpp at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:587
   block in find_header at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:1144
  block in checking_for at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:942
      block in postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:350
                   open at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:320
      block in postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:350
                   open at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:320
               postpone at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:346
           checking_for at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:941
            find_header at C:/jruby-9.1.8.0/lib/ruby/stdlib/mkmf.rb:1143
                  at extconf.rb:50
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/jruby-9.1.8.0/bin/jruby
        --with-sqlite3-config
        --without-sqlite3-config
        --with-pkg-config
        --without-pkg-config
        --with-sqlite3-dir
        --without-sqlite3-dir
        --with-sqlite3-include
        --without-sqlite3-include=${sqlite3-dir}/include
        --with-sqlite3-lib
        --without-sqlite3-lib=${sqlite3-dir}/lib

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  C:/jruby-9.1.8.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.3.0/sqlite3-1.3.13/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/sqlite3-1.3.13 for inspection.
Results logged to C:/jruby-9.1.8.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.3.0/sqlite3-1.3.13/gem_make.out

Any help is appreciated as I cannot move forward until I run a successful bundle install and I've tried researching for days and cannot figure out how to fix this.

Updated 7/9/17: Here is my updated Gemfile where I am still not able to run bundle install nor bundle update:

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.1'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Use sqlite3 as the database for Active Record
    gem 'sqlite3', platform: :ruby
    gem 'jdbc-sqlite3', platform: :jruby
    gem 'activerecord-jdbc-adapter', platform: :jruby
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

group :production do
    gem 'pg'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem 'jquery-rails'

gem 'activerecord-jdbcsqlite3-adapter', '~> 1.3', '>= 1.3.23'

Updated 7/10/17: After removing gem 'activerecord-jdbcsqlite3-adapter', '~> 1.3', '>= 1.3.23', I tried bundle install again and this time, I got a different error:

Kelly@LAPTOP /c/Sites/my_app (master)
$ bundle install
The dependency sqlite3 (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for x86-mingw32, java but the dependency is only for ruby. To add those platforms to the bundle, run `bundle lock --add-platform ruby`.
Fetching gem metadata from https://rubygems.org/...........
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies........................
Using rake 12.0.0
Using concurrent-ruby 1.0.5 (java)
Using i18n 0.8.4
Using minitest 5.10.2
Using thread_safe 0.3.6 (java)
Using builder 3.2.3
Using erubi 1.6.0
Using nokogiri 1.8.0 (java)
Using rack 2.0.3
Using nio4r 2.1.0 (java)
Using websocket-extensions 0.1.2
Using mime-types-data 3.2016.0521
Using arel 8.0.0
Using bundler 1.15.1
Using method_source 0.8.2
Using thor 0.19.4
Using puma 3.9.1 (java)
Using sass 3.4.24
Using tilt 2.0.7
Using execjs 2.7.0
Using coffee-script-source 1.12.2
Using turbolinks-source 5.0.3
Using multi_json 1.12.1
Using jdbc-sqlite3 3.15.1
Fetching bindex 0.5.0
Installing bindex 0.5.0 with native extensions
C:/jruby-9.1.8.0/lib/ruby/stdlib/rubygems/ext/ext_conf_builder.rb:56: warning: Tempfile#unlink or delete called on open file; ignoring
Using tzinfo 1.2.3
Using loofah 2.0.3
Using rack-test 0.6.3
Using sprockets 3.7.1
Using websocket-driver 0.6.5 (java)
Using mime-types 3.1
Using uglifier 3.2.0
Using coffee-script 2.4.1
Using turbolinks 5.0.1
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/bindex-0.5.0/ext/bindex
C:/jruby-9.1.8.0/bin/jruby.exe -r ./siteconf20170710-21728-1asiecp.rb extconf.rb

current directory:
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/bindex-0.5.0/ext/bindex
make "DESTDIR=" clean
'make' is not recognized as an internal or external command,
operable program or batch file.

current directory:
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/bindex-0.5.0/ext/bindex
make "DESTDIR="
'make' is not recognized as an internal or external command,
operable program or batch file.

make failed, exit code 1

Gem files will remain installed in
C:/jruby-9.1.8.0/lib/ruby/gems/shared/gems/bindex-0.5.0 for inspection.
Results logged to
C:/jruby-9.1.8.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.3.0/bindex-0.5.0/gem_make.out

An error occurred while installing bindex (0.5.0), and Bundler cannot continue.
Make sure that `gem install bindex -v '0.5.0'` succeeds before bundling.

In Gemfile:
  web-console was resolved to 3.5.1, which depends on
    bindex


问:
Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/spark/Logging
I'm new to Spark. I attempted to run a Spark app (.jar) on CDH 5.8.0-0 on Oracle VirtualBox 5.1.4r110228 which leveraged Spark Steaming to perform sentiment analysis on twitter. I have my twitter account created and all required (4) tokens were generated. I was blocked by the NoClassDefFoundError exception.

I've been googling around for a couple of days. The best advice I found so far was in the URL below but apparently my environment is still missing something.

http://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz4Ia99dsp0

What does it mean by a library showed up in Compile by was missing at RunTime? How can we fix this?

What is the library of Logging? I came across an article stating this Logging is subject to be deprecated. Besides that, I do see log4j in my environment.

In my CDH 5.8, I'm running these versions of software:
 Spark-2.0.0-bin-hadoop2.7 / spark-core_2.10-2.0.0
 jdk-8u101-linux-x64 / jre-bu101-linux-x64

I appended the detail of the exception at the end. Here is the procedure I performed to execute the app and some verification I did after hitting the exception:

Unzip twitter-streaming.zip  (the Spark app)

cd twitter-streaming

run ./sbt/sbt assembly

Update env.sh with your Twitter account

$ cat env.sh

```<code>export SPARK_HOME=/home/cloudera/spark-2.0.0-bin-hadoop2.7
export CONSUMER_KEY=<my_consumer_key>
export CONSUMER_SECRET=<my_consumer_secret>
export ACCESS_TOKEN=<my_twitterapp_access_token>
export ACCESS_TOKEN_SECRET=<my_twitterapp_access_token>
</code>```

The submit.sh script wrapped up the spark-submit command with required credential info in env.sh:

$ cat submit.sh

```<code>source ./env.sh
$SPARK_HOME/bin/spark-submit --class "TwitterStreamingApp" --master local[*] ./target/scala-2.10/twitter-streaming-assembly-1.0.jar $CONSUMER_KEY $CONSUMER_SECRET $ACCESS_TOKEN $ACCESS_TOKEN_SECRET
</code>```

The log of the assembly process:
[cloudera@quickstart twitter-streaming]$ ./sbt/sbt assembly

```<code>Launching sbt from sbt/sbt-launch-0.13.7.jar
[info] Loading project definition from /home/cloudera/workspace/twitter-streaming/project
[info] Set current project to twitter-streaming (in build file:/home/cloudera/workspace/twitter-streaming/)
[info] Including: twitter4j-stream-3.0.3.jar
[info] Including: twitter4j-core-3.0.3.jar
[info] Including: scala-library.jar
[info] Including: unused-1.0.0.jar
[info] Including: spark-streaming-twitter_2.10-1.4.1.jar
[info] Checking every *.class/*.jar file's SHA-1.
[info] Merging files...
[warn] Merging 'META-INF/LICENSE.txt' with strategy 'first'
[warn] Merging 'META-INF/MANIFEST.MF' with strategy 'discard'
[warn] Merging 'META-INF/maven/org.spark-project.spark/unused/pom.properties' with strategy 'first'
[warn] Merging 'META-INF/maven/org.spark-project.spark/unused/pom.xml' with strategy 'first'
[warn] Merging 'log4j.properties' with strategy 'discard'
[warn] Merging 'org/apache/spark/unused/UnusedStubClass.class' with strategy 'first'
[warn] Strategy 'discard' was applied to 2 files
[warn] Strategy 'first' was applied to 4 files
[info] SHA-1: 69146d6fdecc2a97e346d36fafc86c2819d5bd8f
[info] Packaging /home/cloudera/workspace/twitter-streaming/target/scala-2.10/twitter-streaming-assembly-1.0.jar ...
[info] Done packaging.
[success] Total time: 6 s, completed Aug 27, 2016 11:58:03 AM
</code>```

Not sure exactly what it means but everything looked good when I ran Hadoop NativeCheck:

$ hadoop checknative -a

```<code>16/08/27 13:27:22 INFO bzip2.Bzip2Factory: Successfully loaded & initialized native-bzip2 library system-native
16/08/27 13:27:22 INFO zlib.ZlibFactory: Successfully loaded & initialized native-zlib library
Native library checking:
hadoop:  true /usr/lib/hadoop/lib/native/libhadoop.so.1.0.0
zlib:    true /lib64/libz.so.1
snappy:  true /usr/lib/hadoop/lib/native/libsnappy.so.1
lz4:     true revision:10301
bzip2:   true /lib64/libbz2.so.1
openssl: true /usr/lib64/libcrypto.so
</code>```

Here is the console log of my exception:
$ ./submit.sh

```<code>Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
16/08/28 20:13:23 INFO SparkContext: Running Spark version 2.0.0
16/08/28 20:13:24 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/08/28 20:13:24 WARN Utils: Your hostname, quickstart.cloudera resolves to a loopback address: 127.0.0.1; using 10.0.2.15 instead (on interface eth0)
16/08/28 20:13:24 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
16/08/28 20:13:24 INFO SecurityManager: Changing view acls to: cloudera
16/08/28 20:13:24 INFO SecurityManager: Changing modify acls to: cloudera
16/08/28 20:13:24 INFO SecurityManager: Changing view acls groups to:
16/08/28 20:13:24 INFO SecurityManager: Changing modify acls groups to:
16/08/28 20:13:24 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(cloudera); groups with view permissions: Set(); users  with modify permissions: Set(cloudera); groups with modify permissions: Set()
16/08/28 20:13:25 INFO Utils: Successfully started service 'sparkDriver' on port 37550.
16/08/28 20:13:25 INFO SparkEnv: Registering MapOutputTracker
16/08/28 20:13:25 INFO SparkEnv: Registering BlockManagerMaster
16/08/28 20:13:25 INFO DiskBlockManager: Created local directory at /tmp/blockmgr-37a0492e-67e3-4ad5-ac38-40448c25d523
16/08/28 20:13:25 INFO MemoryStore: MemoryStore started with capacity 366.3 MB
16/08/28 20:13:25 INFO SparkEnv: Registering OutputCommitCoordinator
16/08/28 20:13:25 INFO Utils: Successfully started service 'SparkUI' on port 4040.
16/08/28 20:13:25 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://10.0.2.15:4040
16/08/28 20:13:25 INFO SparkContext: Added JAR file:/home/cloudera/workspace/twitter-streaming/target/scala-2.10/twitter-streaming-assembly-1.1.jar at spark://10.0.2.15:37550/jars/twitter-streaming-assembly-1.1.jar with timestamp 1472440405882
16/08/28 20:13:26 INFO Executor: Starting executor ID driver on host localhost
16/08/28 20:13:26 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 41264.
16/08/28 20:13:26 INFO NettyBlockTransferService: Server created on 10.0.2.15:41264
16/08/28 20:13:26 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, 10.0.2.15, 41264)
16/08/28 20:13:26 INFO BlockManagerMasterEndpoint: Registering block manager 10.0.2.15:41264 with 366.3 MB RAM, BlockManagerId(driver, 10.0.2.15, 41264)
16/08/28 20:13:26 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 10.0.2.15, 41264)
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/Logging
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)I
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.apache.spark.streaming.twitter.TwitterUtils$.createStream(TwitterUtils.scala:44)
    at TwitterStreamingApp$.main(TwitterStreamingApp.scala:42)
    at TwitterStreamingApp.main(TwitterStreamingApp.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:729)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: org.apache.spark.Logging
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 23 more
16/08/28 20:13:26 INFO SparkContext: Invoking stop() from shutdown hook
16/08/28 20:13:26 INFO SparkUI: Stopped Spark web UI at http://10.0.2.15:4040
16/08/28 20:13:26 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped!
16/08/28 20:13:26 INFO MemoryStore: MemoryStore cleared
16/08/28 20:13:26 INFO BlockManager: BlockManager stopped
16/08/28 20:13:26 INFO BlockManagerMaster: BlockManagerMaster stopped
16/08/28 20:13:26 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
16/08/28 20:13:26 INFO SparkContext: Successfully stopped SparkContext
16/08/28 20:13:26 INFO ShutdownHookManager: Shutdown hook called
16/08/28 20:13:26 INFO ShutdownHookManager: Deleting directory /tmp/spark-5e29c3b2-74c2-4d89-970f-5be89d176b26
</code>```

I understand my post was lengthy. Your advice or insights are highly appreciated!!

-jsung8

答:
You're using an old version of the Spark Twitter connector. This class from your stack trace hints at that:

```<code>org.apache.spark.streaming.twitter.TwitterUtils
</code>```

Spark removed that integration in version 2.0. You're using the one from an old Spark version that references the old Logging class which moved to a different package in Spark 2.0.

If you want to use Spark 2.0, you'll need to use the Twitter connector from the Bahir project.

Body:
I'm new to Spark. I attempted to run a Spark app (.jar) on CDH 5.8.0-0 on Oracle VirtualBox 5.1.4r110228 which leveraged Spark Steaming to perform sentiment analysis on twitter. I have my twitter account created and all required (4) tokens were generated. I was blocked by the NoClassDefFoundError exception.

I've been googling around for a couple of days. The best advice I found so far was in the URL below but apparently my environment is still missing something.

http://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz4Ia99dsp0

What does it mean by a library showed up in Compile by was missing at RunTime? How can we fix this?

What is the library of Logging? I came across an article stating this Logging is subject to be deprecated. Besides that, I do see log4j in my environment.

In my CDH 5.8, I'm running these versions of software:
 Spark-2.0.0-bin-hadoop2.7 / spark-core_2.10-2.0.0
 jdk-8u101-linux-x64 / jre-bu101-linux-x64

I appended the detail of the exception at the end. Here is the procedure I performed to execute the app and some verification I did after hitting the exception:

Unzip twitter-streaming.zip  (the Spark app)

cd twitter-streaming

run ./sbt/sbt assembly

Update env.sh with your Twitter account

$ cat env.sh

export SPARK_HOME=/home/cloudera/spark-2.0.0-bin-hadoop2.7
export CONSUMER_KEY=<my_consumer_key>
export CONSUMER_SECRET=<my_consumer_secret>
export ACCESS_TOKEN=<my_twitterapp_access_token>
export ACCESS_TOKEN_SECRET=<my_twitterapp_access_token>

The submit.sh script wrapped up the spark-submit command with required credential info in env.sh:

$ cat submit.sh

source ./env.sh
$SPARK_HOME/bin/spark-submit --class "TwitterStreamingApp" --master local[*] ./target/scala-2.10/twitter-streaming-assembly-1.0.jar $CONSUMER_KEY $CONSUMER_SECRET $ACCESS_TOKEN $ACCESS_TOKEN_SECRET

The log of the assembly process:
[cloudera@quickstart twitter-streaming]$ ./sbt/sbt assembly

Launching sbt from sbt/sbt-launch-0.13.7.jar
[info] Loading project definition from /home/cloudera/workspace/twitter-streaming/project
[info] Set current project to twitter-streaming (in build file:/home/cloudera/workspace/twitter-streaming/)
[info] Including: twitter4j-stream-3.0.3.jar
[info] Including: twitter4j-core-3.0.3.jar
[info] Including: scala-library.jar
[info] Including: unused-1.0.0.jar
[info] Including: spark-streaming-twitter_2.10-1.4.1.jar
[info] Checking every *.class/*.jar file's SHA-1.
[info] Merging files...
[warn] Merging 'META-INF/LICENSE.txt' with strategy 'first'
[warn] Merging 'META-INF/MANIFEST.MF' with strategy 'discard'
[warn] Merging 'META-INF/maven/org.spark-project.spark/unused/pom.properties' with strategy 'first'
[warn] Merging 'META-INF/maven/org.spark-project.spark/unused/pom.xml' with strategy 'first'
[warn] Merging 'log4j.properties' with strategy 'discard'
[warn] Merging 'org/apache/spark/unused/UnusedStubClass.class' with strategy 'first'
[warn] Strategy 'discard' was applied to 2 files
[warn] Strategy 'first' was applied to 4 files
[info] SHA-1: 69146d6fdecc2a97e346d36fafc86c2819d5bd8f
[info] Packaging /home/cloudera/workspace/twitter-streaming/target/scala-2.10/twitter-streaming-assembly-1.0.jar ...
[info] Done packaging.
[success] Total time: 6 s, completed Aug 27, 2016 11:58:03 AM

Not sure exactly what it means but everything looked good when I ran Hadoop NativeCheck:

$ hadoop checknative -a

16/08/27 13:27:22 INFO bzip2.Bzip2Factory: Successfully loaded & initialized native-bzip2 library system-native
16/08/27 13:27:22 INFO zlib.ZlibFactory: Successfully loaded & initialized native-zlib library
Native library checking:
hadoop:  true /usr/lib/hadoop/lib/native/libhadoop.so.1.0.0
zlib:    true /lib64/libz.so.1
snappy:  true /usr/lib/hadoop/lib/native/libsnappy.so.1
lz4:     true revision:10301
bzip2:   true /lib64/libbz2.so.1
openssl: true /usr/lib64/libcrypto.so

Here is the console log of my exception:
$ ./submit.sh

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
16/08/28 20:13:23 INFO SparkContext: Running Spark version 2.0.0
16/08/28 20:13:24 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/08/28 20:13:24 WARN Utils: Your hostname, quickstart.cloudera resolves to a loopback address: 127.0.0.1; using 10.0.2.15 instead (on interface eth0)
16/08/28 20:13:24 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
16/08/28 20:13:24 INFO SecurityManager: Changing view acls to: cloudera
16/08/28 20:13:24 INFO SecurityManager: Changing modify acls to: cloudera
16/08/28 20:13:24 INFO SecurityManager: Changing view acls groups to:
16/08/28 20:13:24 INFO SecurityManager: Changing modify acls groups to:
16/08/28 20:13:24 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(cloudera); groups with view permissions: Set(); users  with modify permissions: Set(cloudera); groups with modify permissions: Set()
16/08/28 20:13:25 INFO Utils: Successfully started service 'sparkDriver' on port 37550.
16/08/28 20:13:25 INFO SparkEnv: Registering MapOutputTracker
16/08/28 20:13:25 INFO SparkEnv: Registering BlockManagerMaster
16/08/28 20:13:25 INFO DiskBlockManager: Created local directory at /tmp/blockmgr-37a0492e-67e3-4ad5-ac38-40448c25d523
16/08/28 20:13:25 INFO MemoryStore: MemoryStore started with capacity 366.3 MB
16/08/28 20:13:25 INFO SparkEnv: Registering OutputCommitCoordinator
16/08/28 20:13:25 INFO Utils: Successfully started service 'SparkUI' on port 4040.
16/08/28 20:13:25 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://10.0.2.15:4040
16/08/28 20:13:25 INFO SparkContext: Added JAR file:/home/cloudera/workspace/twitter-streaming/target/scala-2.10/twitter-streaming-assembly-1.1.jar at spark://10.0.2.15:37550/jars/twitter-streaming-assembly-1.1.jar with timestamp 1472440405882
16/08/28 20:13:26 INFO Executor: Starting executor ID driver on host localhost
16/08/28 20:13:26 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 41264.
16/08/28 20:13:26 INFO NettyBlockTransferService: Server created on 10.0.2.15:41264
16/08/28 20:13:26 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, 10.0.2.15, 41264)
16/08/28 20:13:26 INFO BlockManagerMasterEndpoint: Registering block manager 10.0.2.15:41264 with 366.3 MB RAM, BlockManagerId(driver, 10.0.2.15, 41264)
16/08/28 20:13:26 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 10.0.2.15, 41264)
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/Logging
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)I
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.apache.spark.streaming.twitter.TwitterUtils$.createStream(TwitterUtils.scala:44)
    at TwitterStreamingApp$.main(TwitterStreamingApp.scala:42)
    at TwitterStreamingApp.main(TwitterStreamingApp.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:729)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: org.apache.spark.Logging
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 23 more
16/08/28 20:13:26 INFO SparkContext: Invoking stop() from shutdown hook
16/08/28 20:13:26 INFO SparkUI: Stopped Spark web UI at http://10.0.2.15:4040
16/08/28 20:13:26 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped!
16/08/28 20:13:26 INFO MemoryStore: MemoryStore cleared
16/08/28 20:13:26 INFO BlockManager: BlockManager stopped
16/08/28 20:13:26 INFO BlockManagerMaster: BlockManagerMaster stopped
16/08/28 20:13:26 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
16/08/28 20:13:26 INFO SparkContext: Successfully stopped SparkContext
16/08/28 20:13:26 INFO ShutdownHookManager: Shutdown hook called
16/08/28 20:13:26 INFO ShutdownHookManager: Deleting directory /tmp/spark-5e29c3b2-74c2-4d89-970f-5be89d176b26

I understand my post was lengthy. Your advice or insights are highly appreciated!!

-jsung8

Body:
You're using an old version of the Spark Twitter connector. This class from your stack trace hints at that:

org.apache.spark.streaming.twitter.TwitterUtils

Spark removed that integration in version 2.0. You're using the one from an old Spark version that references the old Logging class which moved to a different package in Spark 2.0.

If you want to use Spark 2.0, you'll need to use the Twitter connector from the Bahir project.


问:
how we can get two values of array from model in codeigniter
This code is in model...
i want to return these two values in controller.....please help me if you know

```<code>Array ( [disease_name] => magraines ) Array ( [disease_name] => brain cancer )
</code>```

when i do

```<code>return print_r($qq);
</code>```

then i get one value but i need two value that one value is

```<code>Array ( [disease_name] => magraines ) 1

function getDiseaseInfo()
{

             $spytoms = $_GET['syptoms'];

            foreach ($spytoms as $ss)
                {
                    $query = $this->db->query("SELECT d.disease_name FROM diseases d,syptoms s ,syptoms_disease sd
                        WHERE
                        '$ss' = s.syptom_name  AND
                        s.s_id = sd.s_id_fk
                        AND sd.d_id_fk IN (d.d_id)
                        ");
                    $qq = $query->row_array();
                    print_r($qq);
                }

}
</code>```

答:
From your model return $qq only.

you are returning return print_r($qq) thats not the correct way.

print_r will print the entire array.

if you want to return your array values to your controller you have to return it like return $qq;

Update 1

I think you are getting last row's values,if im right you have to follow below steps,

You have to introduce a new array variable above your foreach

and assign your query array values to this newly created array

and you have to return that newly created array

```<code>function getDiseaseInfo()
    {
        $spytoms = $_GET['syptoms'];
        $tmpArray = array();
        foreach ($spytoms as $ss)
            {
                $query = $this->db->query("SELECT d.disease_name FROM diseases d,syptoms s ,syptoms_disease sd WHERE '$ss' = s.syptom_name AND s.s_id = sd.s_id_fk AND sd.d_id_fk IN (d.d_id) ");
                $qq = $query->row_array();
                $tmpArray[] = $qq;
            }
            return $tmpArray;
    }
</code>```

Body:
This code is in model...
i want to return these two values in controller.....please help me if you know

Array ( [disease_name] => magraines ) Array ( [disease_name] => brain cancer )

when i do

return print_r($qq);

then i get one value but i need two value that one value is

Array ( [disease_name] => magraines ) 1

function getDiseaseInfo()
{

             $spytoms = $_GET['syptoms'];

            foreach ($spytoms as $ss)
                {
                    $query = $this->db->query("SELECT d.disease_name FROM diseases d,syptoms s ,syptoms_disease sd
                        WHERE
                        '$ss' = s.syptom_name  AND
                        s.s_id = sd.s_id_fk
                        AND sd.d_id_fk IN (d.d_id)
                        ");
                    $qq = $query->row_array();
                    print_r($qq);
                }

}

Body:
From your model return $qq only.

you are returning return print_r($qq) thats not the correct way.

print_r will print the entire array.

if you want to return your array values to your controller you have to return it like return $qq;

Update 1

I think you are getting last row's values,if im right you have to follow below steps,

You have to introduce a new array variable above your foreach

and assign your query array values to this newly created array

and you have to return that newly created array

function getDiseaseInfo()
    {
        $spytoms = $_GET['syptoms'];
        $tmpArray = array();
        foreach ($spytoms as $ss)
            {
                $query = $this->db->query("SELECT d.disease_name FROM diseases d,syptoms s ,syptoms_disease sd WHERE '$ss' = s.syptom_name AND s.s_id = sd.s_id_fk AND sd.d_id_fk IN (d.d_id) ");
                $qq = $query->row_array();
                $tmpArray[] = $qq;
            }
            return $tmpArray;
    }


问:
Get value from select box and add to total with jQuery
I have managed to get this code up and running, which in short calculates the total price of cleaning a house based on it's size. Now i want to add an second option: choosing desired time of day, but i'm not sure how to proceed and connect the two different form elements.

This is how my code looks like now:

```<code>$(document).ready(function(){

    $("#order").on('input', function(){
        var kvm2 = parseInt($('#kvm2').val()) || 0;
        var min_price = 299;
        var kvm2_price;
        if(kvm2 > 100) {
            kvm2_price = 6;
        }
        if(kvm2 > 200) {
            kvm2_price = 4;
        }
        if(kvm2 <= 100) {
            kvm2_price = 7;
        }
        var total = (kvm2_price * kvm2).toFixed(2);
        if(total < min_price) {
            $('#total').html(min_price);
        }
        else {
            $('#total').html(total);
        }
    });
});
</code>```

This is the select box I want to add:

```<code> <select name="timeslot" class="form-control form-control-lg">
    <option value="1">Dagtid (08 - 15) 0kr</option>
    <option value="2">Formiddag (12 - 15) 39kr</option>
    <option value="3">Ettermiddag (16 - 18) 39kr</option>
    <option value="4">Kveld (19 - 24) 129kr</option>
  </select>
</code>```

Based on the option you choose, either 0kr, 39kr or 129kr should be added on top of the total sales price.

答:
Here you go with the jsfiddle https://jsfiddle.net/5orednbn/</p>

```<code>**HTML**
<div id="subTotal">SubTotal: <span>200</span></div>
<select name="timeslot" class="form-control form-control-lg">
    <option value="0">Dagtid (08 - 15) 0kr</option>
    <option value="39">Formiddag (12 - 15) 39kr</option>
    <option value="39">Ettermiddag (16 - 18) 39kr</option>
    <option value="129">Kveld (19 - 24) 129kr</option>
</select>

<button type="button" id="order" value="submit" >Submit</button>

<div id="grandTotal">Total: <span></span></div>

**JS**
$("#order").on('click', function(){
    var subtotal = parseFloat($('#subTotal > span').text());
    var timeSlot = parseFloat($('select[name="timeslot"] option:selected').val());

    $('#grandTotal > span').html( subtotal + timeSlot);
});
</code>```

Body:
I have managed to get this code up and running, which in short calculates the total price of cleaning a house based on it's size. Now i want to add an second option: choosing desired time of day, but i'm not sure how to proceed and connect the two different form elements.

This is how my code looks like now:

$(document).ready(function(){

    $("#order").on('input', function(){
        var kvm2 = parseInt($('#kvm2').val()) || 0;
        var min_price = 299;
        var kvm2_price;
        if(kvm2 > 100) {
            kvm2_price = 6;
        }
        if(kvm2 > 200) {
            kvm2_price = 4;
        }
        if(kvm2 <= 100) {
            kvm2_price = 7;
        }
        var total = (kvm2_price * kvm2).toFixed(2);
        if(total < min_price) {
            $('#total').html(min_price);
        }
        else {
            $('#total').html(total);
        }
    });
});

This is the select box I want to add:

 <select name="timeslot" class="form-control form-control-lg">
    <option value="1">Dagtid (08 - 15) 0kr</option>
    <option value="2">Formiddag (12 - 15) 39kr</option>
    <option value="3">Ettermiddag (16 - 18) 39kr</option>
    <option value="4">Kveld (19 - 24) 129kr</option>
  </select>

Based on the option you choose, either 0kr, 39kr or 129kr should be added on top of the total sales price.

Body:
Here you go with the jsfiddle https://jsfiddle.net/5orednbn/

**HTML**
<div id="subTotal">SubTotal: <span>200</span></div>
<select name="timeslot" class="form-control form-control-lg">
    <option value="0">Dagtid (08 - 15) 0kr</option>
    <option value="39">Formiddag (12 - 15) 39kr</option>
    <option value="39">Ettermiddag (16 - 18) 39kr</option>
    <option value="129">Kveld (19 - 24) 129kr</option>
</select>

<button type="button" id="order" value="submit" >Submit</button>

<div id="grandTotal">Total: <span></span></div>

**JS**
$("#order").on('click', function(){
    var subtotal = parseFloat($('#subTotal > span').text());
    var timeSlot = parseFloat($('select[name="timeslot"] option:selected').val());

    $('#grandTotal > span').html( subtotal + timeSlot);
});


问:
Yii2 Update records resulting from query
I need to update month_no fields of the records resulting from a select query using some variables passed from controller but every field is written with the same value.

These are the variables:

```<code>    $id_calc = 27
    $from_y = "2013-05-01"
    $to_y = "2015-11-31"
</code>```

The table result:

```<code>   id   id_paid   year_ref     month_no
    1        26      2012         12
    2        26      2013         12
    4        27      2013         12  (should be 8)
    5        27      2014         12
    6        27      2015         12  (should be 11)
</code>```

This is model:

```<code> public function CorrectTable($id_calc, $from_y, $to_y)
    {
        $connection = Yii::$app->db;
        $query = "SELECT * FROM my_table where id_paid='$id_calc'";
        $data = $connection->createCommand($query)->queryAll();
        // calculate no. of month first and last year
        $month_no_begin = (13 - date("m",strtotime($from_y)));
        $month_no_end = (date("m",strtotime($to_y)));
        //
        foreach($data as $row)
        {
          $id = $row['id'];
          // calculate number of month per year
          if ($row['year_ref'] = date("Y",strtotime($from_y)))
          {
            $month_no = $month_no_begin;
          } elseif  ($row['year_ref'] = date("Y",strtotime($to_y)))
          {
            $month_no = $month_no_end;
          } else
          {
            $month_no = 12;
          }
            Yii::$app->db->createCommand()
            ->update('my_table', ['month_no' => $month_no], ['id' => $id])
            ->execute();
        }
</code>```

I tried to put the above code in controller with the same result.

答:
A careless mistake once I had made before. You should use == or === in the if statement to test equal condition, instead of =

```<code>public function CorrectTable($id_calc, $from_y, $to_y)
{
    $connection = Yii::$app->db;
    $query = "SELECT * FROM my_table where id_paid='$id_calc'";
    $data = $connection->createCommand($query)->queryAll();
    // calculate no. of month first and last year
    $month_no_begin = (13 - date("m",strtotime($from_y)));
    $month_no_end = (date("m",strtotime($to_y)));
    //
    foreach($data as $row)
    {
        $id = $row['id'];

        // use `==` instead of `=`
        if ($row['year_ref'] == date("Y",strtotime($from_y)))
        {
            $month_no = $month_no_begin;
        }

        // use `==` instead of `=`
        elseif ($row['year_ref'] == date("Y",strtotime($to_y)))
        {
            $month_no = $month_no_end;
        }
        else
        {
            $month_no = 12;
        }

        Yii::$app->db->createCommand()
            ->update('my_table', ['month_no' => $month_no], ['id' => $id])
            ->execute();
    }
}
</code>```

Body:
I need to update month_no fields of the records resulting from a select query using some variables passed from controller but every field is written with the same value.

These are the variables:

    $id_calc = 27
    $from_y = "2013-05-01"
    $to_y = "2015-11-31"

The table result:

   id   id_paid   year_ref     month_no
    1        26      2012         12
    2        26      2013         12
    4        27      2013         12  (should be 8)
    5        27      2014         12
    6        27      2015         12  (should be 11)

This is model:

 public function CorrectTable($id_calc, $from_y, $to_y)
    {
        $connection = Yii::$app->db;
        $query = "SELECT * FROM my_table where id_paid='$id_calc'";
        $data = $connection->createCommand($query)->queryAll();
        // calculate no. of month first and last year
        $month_no_begin = (13 - date("m",strtotime($from_y)));
        $month_no_end = (date("m",strtotime($to_y)));
        //
        foreach($data as $row)
        {
          $id = $row['id'];
          // calculate number of month per year
          if ($row['year_ref'] = date("Y",strtotime($from_y)))
          {
            $month_no = $month_no_begin;
          } elseif  ($row['year_ref'] = date("Y",strtotime($to_y)))
          {
            $month_no = $month_no_end;
          } else
          {
            $month_no = 12;
          }
            Yii::$app->db->createCommand()
            ->update('my_table', ['month_no' => $month_no], ['id' => $id])
            ->execute();
        }

I tried to put the above code in controller with the same result.

Body:
A careless mistake once I had made before. You should use == or === in the if statement to test equal condition, instead of =

public function CorrectTable($id_calc, $from_y, $to_y)
{
    $connection = Yii::$app->db;
    $query = "SELECT * FROM my_table where id_paid='$id_calc'";
    $data = $connection->createCommand($query)->queryAll();
    // calculate no. of month first and last year
    $month_no_begin = (13 - date("m",strtotime($from_y)));
    $month_no_end = (date("m",strtotime($to_y)));
    //
    foreach($data as $row)
    {
        $id = $row['id'];

        // use `==` instead of `=`
        if ($row['year_ref'] == date("Y",strtotime($from_y)))
        {
            $month_no = $month_no_begin;
        }

        // use `==` instead of `=`
        elseif ($row['year_ref'] == date("Y",strtotime($to_y)))
        {
            $month_no = $month_no_end;
        }
        else
        {
            $month_no = 12;
        }

        Yii::$app->db->createCommand()
            ->update('my_table', ['month_no' => $month_no], ['id' => $id])
            ->execute();
    }
}


问:
Package for testing models on unseen data
I am wondering what packages are out there that can split my data.

I would prefer to optimize my model on 2/3rds of the data.
Then run it over the last 1/3rd to see how well it holds up.

Also this might sound like a stupid question... but in order to forward run the optimized model over the last 1/3/rd of data, is there a way to do that? Otherwise I am backtesting again right? Idea is to forward test it over the last 1/3rd of data much like it would be seeing real live data.... if im making sense.

Is there a R package out there that can do this?

**Apprecaite the answers.

It would seem in this case that its a relativley simple task with the following steps:

Optimize the model to the first 2/3rds of the data.

Test those parameters on the last 1/3rd of the data.

This is in contrast to testing and optimizing a model over the entire sample size. This way the model gets to see unseen data.

答:
There are packages, but depending on what your requirements are, you can do this using base R's extraction operators. It sounds like your using time series or some kind of ordered observation.

After you have your data, create a training index.
Next, subset your data by the training index to create your training set.
Then create your test set by subsetting the data again, but subtracting the train index.

```<code>data <- data.frame(x=runif(10000), y=runif(10000))

train_index <- 1:(NROW(data)*0.666)

train_set <- data[train_index, ]

test_set <- data[-train_index, ]
</code>```

In addition, the caret package is very popular and has a train function that has many addition arguments for implementing sampling techniques of varying sophistication levels, depending on the model and data you are using. If you haven't used it, check it out.

If you are working with time series, the forecast package has two function that might be of interest, CVar and tsCV, although they will not split your data in the manner you require, they will train your data on a rolling basis which is more relevant for some time series models.

Good luck!

Body:
There are packages, but depending on what your requirements are, you can do this using base R's extraction operators. It sounds like your using time series or some kind of ordered observation.

After you have your data, create a training index.
Next, subset your data by the training index to create your training set.
Then create your test set by subsetting the data again, but subtracting the train index.

data <- data.frame(x=runif(10000), y=runif(10000))

train_index <- 1:(NROW(data)*0.666)

train_set <- data[train_index, ]

test_set <- data[-train_index, ]

In addition, the caret package is very popular and has a train function that has many addition arguments for implementing sampling techniques of varying sophistication levels, depending on the model and data you are using. If you haven't used it, check it out.

If you are working with time series, the forecast package has two function that might be of interest, CVar and tsCV, although they will not split your data in the manner you require, they will train your data on a rolling basis which is more relevant for some time series models.

Good luck!


问:
heatmap2 lmat,lhei, lwid parameters?
I'm trying to make a heat map with dendrogram in R. I'm also trying to make it so that the color matrix is on the bottom of the heat map. i understand that I would have to change the value of lmat for this. So far I have something like this for lmat.

```<code> lmat=rbind(c(0,3,0), c(2,1,0), c(0,4,0)).
</code>```

After I run it, it asks me to update the lhei and lwid values. After looking at the documentation, I understand that these are vectors for column width and row height. But I don't understand the multiple values needed for their values. For ex, when I set this , I get this error.

```<code>  lhei must have length = nrow(lmat) = 3
</code>```

I'm not sure what the three values for lhei would correspond to. This leads me to a broader question, what does each value in the vectors for lhei and lwid correspond to?

答:
lhei is the relative heights of the rows in the plot. Heatmaps in R are a bit screwy. The graphics device (think of a canvas you want to paint on) is divided into a grid where each element of the heatmap will be plotted: color key, dendrograms and the heatmap. This makes a 2x2 grid. when you add the colsideColors or rowsidecolors the grid expands by 1 in the appropriate dimension, (e.g. 1 more row when adding colsidecolors). When you add this extra row you need to tell R how much (relative) space it needs.

```<code>mat <- matrix(rnorm(200), nrow = 20)
colCols <- rep(c("red", "blue"), 5)
heatmap.2(mat, trace="none", ColSideColors = colCols,
          lmat=rbind(c(5,4), c(3,2), c(0,1)),
          lhei=c(2,4,0.2))
</code>```

Title: heatmap2 lmat,lhei, lwid parameters?

Body:
I'm trying to make a heat map with dendrogram in R. I'm also trying to make it so that the color matrix is on the bottom of the heat map. i understand that I would have to change the value of lmat for this. So far I have something like this for lmat.

 lmat=rbind(c(0,3,0), c(2,1,0), c(0,4,0)).

After I run it, it asks me to update the lhei and lwid values. After looking at the documentation, I understand that these are vectors for column width and row height. But I don't understand the multiple values needed for their values. For ex, when I set this , I get this error.

  lhei must have length = nrow(lmat) = 3

I'm not sure what the three values for lhei would correspond to. This leads me to a broader question, what does each value in the vectors for lhei and lwid correspond to?

Body:
lhei is the relative heights of the rows in the plot. Heatmaps in R are a bit screwy. The graphics device (think of a canvas you want to paint on) is divided into a grid where each element of the heatmap will be plotted: color key, dendrograms and the heatmap. This makes a 2x2 grid. when you add the colsideColors or rowsidecolors the grid expands by 1 in the appropriate dimension, (e.g. 1 more row when adding colsidecolors). When you add this extra row you need to tell R how much (relative) space it needs.

mat <- matrix(rnorm(200), nrow = 20)
colCols <- rep(c("red", "blue"), 5)
heatmap.2(mat, trace="none", ColSideColors = colCols,
          lmat=rbind(c(5,4), c(3,2), c(0,1)),
          lhei=c(2,4,0.2))


问:
vue-cli + webpack: where to include npm package js and css files?
I'm trying to import an npm package into my vue-cli dev site. Here are the instructions provided by the package website:

It says that it needs the css and js files to be included somewhere in the code. How would I go about doing this?

I'm guessing the css file is included by putting this in App.vue:

```<code><style>
  @import '../node_modules/swiper/dist/css/swiper.min.css';
....
</style>
</code>```

Is that right? How would I include the .js file? Inside App.vue, or main.js? I'm honestly not sure how the syntax for that would go either.

Here is my index.html file:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="build/swiper.min.css">
  </head>
  <body>
    <div id="app"></div>
    <script src="build/swiper.min.js"></script>
  </body>
</html>
</code>```

答:
you can include these files in build/index.htmllike common js and css

```<code><head>
....
 <link rel="stylesheet" href="path_to_css/idangerous.swiper.css">
 <script defer src="path_to_js/idangerous.swiper-2.x.min.js"></script>
....
</head>
</code>```

Body:
I'm trying to import an npm package into my vue-cli dev site. Here are the instructions provided by the package website:

It says that it needs the css and js files to be included somewhere in the code. How would I go about doing this?

I'm guessing the css file is included by putting this in App.vue:

Is that right? How would I include the .js file? Inside App.vue, or main.js? I'm honestly not sure how the syntax for that would go either.

Here is my index.html file:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="build/swiper.min.css">

Body:
you can include these files in build/index.htmllike common js and css

<head>
....
 <link rel="stylesheet" href="path_to_css/idangerous.swiper.css">
 <script defer src="path_to_js/idangerous.swiper-2.x.min.js"></script>
....
</head>


问:
How to convert String to Float
I have a simple dumbed down example. I have a prop template to store parameters and its value from different servers. The property value could either be String or numeric (Integer or Float). Currently, the "collector" that reads the properties from the systems generates the facts with the column value as String.

```<code>(deftemplate prop (slot serverid) (slot name) (slot value))
(assert (prop (serverid "ppn45r07vm_0") (name "email.encoding") (value "utf-8")))
(assert (prop (serverid "ppn45r07vm_0") (name "inventory.safety.threshold") (value "99.0")))
(assert (prop (serverid "ppn45r55vm_0") (name "inventory.safety.threshold") (value "993.1")))

(defrule check-range
    (prop (serverid ?s) (name "inventory.safety.threshold") (value ?v))
    (test (> (float ?v) 100.0) )
=>
    (printout t "safety threshold on server " ?s " is set too high at " ?v crlf)
)
</code>```

My question -- how do I convert the String value into either a Float or Integer value so that I can perform range checks, etc. The sample code above works in JESS because JESS's float function takes in a String argument and returns a Float. CLIPS's float function takes in a number and returns a float. I could not find a similar CLIPS function that converts String to Float.

Just for completeness, in CLIPS, I get the following error

```<code>CLIPS> (defrule check-range
    (prop (serverid ?s) (name "inventory.safety.threshold") (value ?v))
    (test (> (float ?v) 100.0) )
=>
    (printout t "safety threshold on server " ?s " is set too high at " ?v crlf)
)
[ARGACCES5] Function float expected argument #1 to be of type float

[DRIVE1] This error occurred in the join network
   Problem resides in associated join
      Of pattern #1 in rule check-range

[ARGACCES5] Function float expected argument #1 to be of type float

[DRIVE1] This error occurred in the join network
   Problem resides in associated join
      Of pattern #1 in rule check-range
</code>```

Apologies if there is an obvious answer. Thanks in advance for any help.

答:
You can overload the float function to get similar behavior to Jess with strings:</p>

```<code>CLIPS> (float "3")
[ARGACCES5] Function float expected argument #1 to be of type integer or float
CLIPS>
(defmethod float ((?s STRING))
   (float (string-to-field ?s)))
CLIPS> (float "3")
3.0
CLIPS>
</code>```

Title: How to convert String to Float

Body:
I have a simple dumbed down example. I have a prop template to store parameters and its value from different servers. The property value could either be String or numeric (Integer or Float). Currently, the "collector" that reads the properties from the systems generates the facts with the column value as String.

(deftemplate prop (slot serverid) (slot name) (slot value))
(assert (prop (serverid "ppn45r07vm_0") (name "email.encoding") (value "utf-8")))
(assert (prop (serverid "ppn45r07vm_0") (name "inventory.safety.threshold") (value "99.0")))
(assert (prop (serverid "ppn45r55vm_0") (name "inventory.safety.threshold") (value "993.1")))

(defrule check-range
    (prop (serverid ?s) (name "inventory.safety.threshold") (value ?v))
    (test (> (float ?v) 100.0) )
=>
    (printout t "safety threshold on server " ?s " is set too high at " ?v crlf)
)

My question -- how do I convert the String value into either a Float or Integer value so that I can perform range checks, etc. The sample code above works in JESS because JESS's float function takes in a String argument and returns a Float. CLIPS's float function takes in a number and returns a float. I could not find a similar CLIPS function that converts String to Float.

Just for completeness, in CLIPS, I get the following error

CLIPS> (defrule check-range
    (prop (serverid ?s) (name "inventory.safety.threshold") (value ?v))
    (test (> (float ?v) 100.0) )
=>
    (printout t "safety threshold on server " ?s " is set too high at " ?v crlf)
)
[ARGACCES5] Function float expected argument #1 to be of type float

[DRIVE1] This error occurred in the join network
   Problem resides in associated join
      Of pattern #1 in rule check-range

[ARGACCES5] Function float expected argument #1 to be of type float

[DRIVE1] This error occurred in the join network
   Problem resides in associated join
      Of pattern #1 in rule check-range

Apologies if there is an obvious answer. Thanks in advance for any help.

Body:
You can overload the float function to get similar behavior to Jess with strings:

CLIPS> (float "3")
[ARGACCES5] Function float expected argument #1 to be of type integer or float
CLIPS>
(defmethod float ((?s STRING))
   (float (string-to-field ?s)))
CLIPS> (float "3")
3.0
CLIPS>


问:
Get coupon data from WooCommerce orders
I have created in WooCommerce two custom coupon types:

```<code>function custom_discount_type( $discount_types ) {
    $discount_types['cash_back_fixed'] =__( 'Cash Back fixed discount', 'woocommerce' );
     $discount_types['cash_back_percentage'] =__( 'Cash Back Percentage discount', 'woocommerce' );
         return $discount_types;

     }

add_filter( 'woocommerce_coupon_discount_types', 'custom_discount_type',10, 1);
</code>```

I would like to get the discount type after Order status is "completed", something like :

```<code>function wc_m_move_order_money_to_user( $order_id, $old_status, $new_status ){

    if( $order->get_used_coupons() ) {
        if ($coupon->type == 'cash_back_fixed'){
           $coupons_amont =  ???
           ....

       }
    }
}
</code>```

But $coupon->type doesn't work.

How can I get the coupon types used in the order?

And how can I get the original coupon amount?.

Thanks

答:
Update 3

Since WooCommerce 3.7, you should now use the WC_Abstract method get_coupon_codes() on the WC_Order instance object to get the used coupons from an order, as get_used_coupons() method is deprecated.

So you will replace in the code:

```<code>foreach( $order->get_used_coupons() as $coupon_code ){
</code>```

by:

```<code>foreach( $order->get_coupon_codes() as $coupon_code ){
</code>```

Then you can get coupon details like:

```<code>foreach( $order->get_coupon_codes() as $coupon_code ) {
    // Get the WC_Coupon object
    $coupon = new WC_Coupon($coupon_code);

    $discount_type = $coupon->get_discount_type(); // Get coupon discount type
    $coupon_amount = $coupon->get_amount(); // Get coupon amount
}
</code>```

Update 2

First you can't access anymore WC objects properties since WooCommerce 3.

You should now use WC_Coupon getter methods to get coupon details from the WC_Coupon Object instance…

In your case you have to use get_discount_type() method or is_type( 'cash_back_fixed' ) method …

Here is the way to do it:

```<code>// Get an instance of WC_Order object
$order = wc_get_order( $order_id );

// Coupons used in the order LOOP (as they can be multiple)
foreach( $order->get_used_coupons() as $coupon_code ){

    // Retrieving the coupon ID
    $coupon_post_obj = get_page_by_title($coupon_code, OBJECT, 'shop_coupon');
    $coupon_id       = $coupon_post_obj->ID;

    // Get an instance of WC_Coupon object in an array(necessary to use WC_Coupon methods)
    $coupon = new WC_Coupon($coupon_id);

    // Now you can get type in your condition
    if ( $coupon->get_discount_type() == 'cash_back_percentage' ){
        // Get the coupon object amount
        $coupon_amount1 = $coupon->get_amount();
    }

    // Or use this other conditional method for coupon type
    if( $coupon->is_type( 'cash_back_fixed' ) ){
        // Get the coupon object amount
        $coupon_amount2 = $coupon->get_amount();
    }
}
</code>```

To get the coupons discount amounts (and to use also coupons types methods) here is the way:

```<code>$order = wc_get_order( $order_id );

// GET THE ORDER COUPON ITEMS
$order_items = $order->get_items('coupon');

// print_r($order_items); // For testing

// LOOP THROUGH ORDER COUPON ITEMS
foreach( $order_items as $item_id => $item ){

    // Retrieving the coupon ID reference
    $coupon_post_obj = get_page_by_title( $item->get_name(), OBJECT, 'shop_coupon' );
    $coupon_id = $coupon_post_obj->ID;

    // Get an instance of WC_Coupon object (necessary to use WC_Coupon methods)
    $coupon = new WC_Coupon($coupon_id);

    ## Filtering with your coupon custom types
    if( $coupon->is_type( 'cash_back_fixed' ) || $coupon->is_type( 'cash_back_percentage' ) ){

        // Get the Coupon discount amounts in the order
        $order_discount_amount = wc_get_order_item_meta( $item_id, 'discount_amount', true );
        $order_discount_tax_amount = wc_get_order_item_meta( $item_id, 'discount_amount_tax', true );

        ## Or get the coupon amount object
        $coupons_amount = $coupons->get_amount();
    }
}
</code>```

So to get the coupon price, we use the WC_Coupon get_amount() method

ContentLicense: CC BY-SA 4.0

Title: Get coupon data from WooCommerce orders

Body:
I have created in WooCommerce two custom coupon types:

function custom_discount_type( $discount_types ) {
    $discount_types['cash_back_fixed'] =__( 'Cash Back fixed discount', 'woocommerce' );
     $discount_types['cash_back_percentage'] =__( 'Cash Back Percentage discount', 'woocommerce' );
         return $discount_types;

     }

add_filter( 'woocommerce_coupon_discount_types', 'custom_discount_type',10, 1);

I would like to get the discount type after Order status is "completed", something like :

function wc_m_move_order_money_to_user( $order_id, $old_status, $new_status ){

    if( $order->get_used_coupons() ) {
        if ($coupon->type == 'cash_back_fixed'){
           $coupons_amont =  ???
           ....

       }
    }
}

But $coupon->type doesn't work.

How can I get the coupon types used in the order?

And how can I get the original coupon amount?.

Thanks

Body:
Update 3

Since WooCommerce 3.7, you should now use the WC_Abstract method get_coupon_codes() on the WC_Order instance object to get the used coupons from an order, as get_used_coupons() method is deprecated.

So you will replace in the code:

foreach( $order->get_used_coupons() as $coupon_code ){

by:

foreach( $order->get_coupon_codes() as $coupon_code ){

Then you can get coupon details like:

foreach( $order->get_coupon_codes() as $coupon_code ) {
    // Get the WC_Coupon object
    $coupon = new WC_Coupon($coupon_code);

    $discount_type = $coupon->get_discount_type(); // Get coupon discount type
    $coupon_amount = $coupon->get_amount(); // Get coupon amount
}

Update 2

First you can't access anymore WC objects properties since WooCommerce 3.

You should now use WC_Coupon getter methods to get coupon details from the WC_Coupon Object instance…

In your case you have to use get_discount_type() method or is_type( 'cash_back_fixed' ) method …

Here is the way to do it:

// Get an instance of WC_Order object
$order = wc_get_order( $order_id );

// Coupons used in the order LOOP (as they can be multiple)
foreach( $order->get_used_coupons() as $coupon_code ){

    // Retrieving the coupon ID
    $coupon_post_obj = get_page_by_title($coupon_code, OBJECT, 'shop_coupon');
    $coupon_id       = $coupon_post_obj->ID;

    // Get an instance of WC_Coupon object in an array(necessary to use WC_Coupon methods)
    $coupon = new WC_Coupon($coupon_id);

    // Now you can get type in your condition
    if ( $coupon->get_discount_type() == 'cash_back_percentage' ){
        // Get the coupon object amount
        $coupon_amount1 = $coupon->get_amount();
    }

    // Or use this other conditional method for coupon type
    if( $coupon->is_type( 'cash_back_fixed' ) ){
        // Get the coupon object amount
        $coupon_amount2 = $coupon->get_amount();
    }
}

To get the coupons discount amounts (and to use also coupons types methods) here is the way:

$order = wc_get_order( $order_id );

// GET THE ORDER COUPON ITEMS
$order_items = $order->get_items('coupon');

// print_r($order_items); // For testing

// LOOP THROUGH ORDER COUPON ITEMS
foreach( $order_items as $item_id => $item ){

    // Retrieving the coupon ID reference
    $coupon_post_obj = get_page_by_title( $item->get_name(), OBJECT, 'shop_coupon' );
    $coupon_id = $coupon_post_obj->ID;

    // Get an instance of WC_Coupon object (necessary to use WC_Coupon methods)
    $coupon = new WC_Coupon($coupon_id);

    ## Filtering with your coupon custom types
    if( $coupon->is_type( 'cash_back_fixed' ) || $coupon->is_type( 'cash_back_percentage' ) ){

        // Get the Coupon discount amounts in the order
        $order_discount_amount = wc_get_order_item_meta( $item_id, 'discount_amount', true );
        $order_discount_tax_amount = wc_get_order_item_meta( $item_id, 'discount_amount_tax', true );

        ## Or get the coupon amount object
        $coupons_amount = $coupons->get_amount();
    }
}

So to get the coupon price, we use the WC_Coupon get_amount() method


问:
Find most significant set bit in a long
I'm in the unique situation where searching for "most significant bit" yields too many results and I can't find an answer that fits my needs!

The question itself is pretty simple: "How do I find the most significant set bit in an unsigned long?" When I do my calculations the rightmost bit position is position '0'.

I know that it involves masking the lowest bit, checking and then shifting left to once while incrementing my count, and then repeating with the 2nd lowest, etc.

I've done this before but for whatever reason I can't do it now.

Edit: By "most significant" I mean leftmost set bit, sorry for any confusion!*

Below is my functioning solution and a few test cases:

```<code>#include <stdio.h>

int findExponent( unsigned long L ){

    int exponent = -1;

    unsigned long shift = L;

    while( 0 != shift )
        exponent++, shift >>=1;

    if ( exponent >= 0 )
        printf("The most significant bit of L is at position %d\n", exponent);
    else{
        exponent = 0;
        printf("L is zero\n");
    }
    return exponent;
}

int main(int argc, char** argv){

    long check = 8L;

    findExponent( check );//2
    findExponent( 21421L );//14
    findExponent( 0L );//(is zero)
    findExponent( 1L );//0
}
</code>```

答:
```<code>unsigned long x = val & ((~0ULL >> 1) ^ (~0ULL));
</code>```

of course if the value is signed all negatives have one in the most significative bit otherwise zero :)

shift right and XOR with one's... in an 8 bit example.

```<code>0011 1100 -> val
1111 1111 -> (~0)
0111 1111 -> (~0 >> 1)
1000 0000 -> ((~0 >> 1) ^ (~0))
0000 0000 -> val & ((~0 >> 1) ^ (~0))  !most significant bit from val is zero
</code>```

Title: Find most significant set bit in a long

Body:
I'm in the unique situation where searching for "most significant bit" yields too many results and I can't find an answer that fits my needs!

The question itself is pretty simple: "How do I find the most significant set bit in an unsigned long?" When I do my calculations the rightmost bit position is position '0'.

I know that it involves masking the lowest bit, checking and then shifting left to once while incrementing my count, and then repeating with the 2nd lowest, etc.

I've done this before but for whatever reason I can't do it now.

Edit: By "most significant" I mean leftmost set bit, sorry for any confusion!*

Below is my functioning solution and a few test cases:

#include <stdio.h>

int findExponent( unsigned long L ){

    int exponent = -1;

    unsigned long shift = L;

    while( 0 != shift )
        exponent++, shift >>=1;

    if ( exponent >= 0 )
        printf("The most significant bit of L is at position %d\n", exponent);
    else{
        exponent = 0;
        printf("L is zero\n");
    }
    return exponent;
}

int main(int argc, char** argv){

    long check = 8L;

    findExponent( check );//2
    findExponent( 21421L );//14
    findExponent( 0L );//(is zero)
    findExponent( 1L );//0
}

Body:
unsigned long x = val & ((~0ULL >> 1) ^ (~0ULL));

of course if the value is signed all negatives have one in the most significative bit otherwise zero :)

shift right and XOR with one's... in an 8 bit example.

0011 1100 -> val
1111 1111 -> (~0)
0111 1111 -> (~0 >> 1)
1000 0000 -> ((~0 >> 1) ^ (~0))
0000 0000 -> val & ((~0 >> 1) ^ (~0))  !most significant bit from val is zero


问:
Factory Pattern implementation in C#
I'm implementing a factory pattern that looks as follows.

```<code>public class FeedFactory
{
    #region Singleton Pattern
    //..
    #endregion

    private static Feed[] _factory = new Feed[(int)FeedType.Total];

    public void RegisterFeed(FeedType feedType,Feed feed)
    {
        if (_factory[(int)feedType] == null)
        {
            _factory[(int)feedType] = feed;
        }
        else
        {
            // already registered
        }
    }

    public Feed GetFeed(FeedType feedType)
    {
        return _factory[(int)feedType];
    }
}
</code>```

Here, Feed is an abstract class from which the different classes inherit. How can I register the different classes? Is it possible to do it from their constructor?

答:
Just register the type of the classes you want to create, then use Activator.CreateInstance to create instances of that type.

It should work this way:

```<code>private static Type[] _factory = new Type[(int)FeedType.Total];

public void RegisterFeed(FeedType feedType, Type type)
{
  ...
  _factory[(int)feedType] = type;
  ...
}

public Feed GetFeed(FeedType feedType)
{
    return Activator.CreateInstance(_factory[(int)feedType]) as Feed;
}
</code>```

You can call RegisterFeed like the following:

```<code>RegisterFeed(FeedType.SomethingSpecial, typeof(MyDerivedSpecialFeed));
</code>```

ContentLicense: CC BY-SA 2.5

Title: Factory Pattern implementation in C#

Body:
I'm implementing a factory pattern that looks as follows.

public class FeedFactory
{
    #region Singleton Pattern
    //..
    #endregion

    private static Feed[] _factory = new Feed[(int)FeedType.Total];

    public void RegisterFeed(FeedType feedType,Feed feed)
    {
        if (_factory[(int)feedType] == null)
        {
            _factory[(int)feedType] = feed;
        }
        else
        {
            // already registered
        }
    }

    public Feed GetFeed(FeedType feedType)
    {
        return _factory[(int)feedType];
    }
}

Here, Feed is an abstract class from which the different classes inherit. How can I register the different classes? Is it possible to do it from their constructor?

Body:
Just register the type of the classes you want to create, then use Activator.CreateInstance to create instances of that type.

It should work this way:

private static Type[] _factory = new Type[(int)FeedType.Total];

public void RegisterFeed(FeedType feedType, Type type)
{
  ...
  _factory[(int)feedType] = type;
  ...
}

public Feed GetFeed(FeedType feedType)
{
    return Activator.CreateInstance(_factory[(int)feedType]) as Feed;
}

You can call RegisterFeed like the following:

RegisterFeed(FeedType.SomethingSpecial, typeof(MyDerivedSpecialFeed));