问:
html getting two divs to match up in height
I'm having issues with getting two divs in html to end in the same exact spot. This snippet will pretty much explain the isue:

html,
body {
  height: 100%;
}

div.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
  width: 89.7%;
  float: right;
  display: inline-block;
  margin-top: 5px;
}

.tabContent {
  height: 100%;
  box-sizing: border-box;
}

#divTableList,
.contentDiv {
  border: 1px solid #ccc;
}

.contentDiv {
  height: 100%;
  width: 89.7%;
  margin-top: 2px;
  background-color: #f1f1f1;
  text-align: center;
  display: inline-block;
  float: right
}

#divTableList {
  height: 100%;
  box-sizing: border-box;
  width: 10%;
  margin-top: 5px;
  float: left;
  background-color: #f1f1f1;
  text-align: center;
  display: inline-block
}

/* Style the buttons inside the tab */

.tablinksimage {
  background-color: inherit;
  float: right;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transform: rotate(0);
  transition: all 0.3s;
}

.tablinksimagemain {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: all 0.3s;
}

.tablinks:hover,
.menulinks:hover,
.tablelinks:hover {
  background-color: #ccc;
}

.tablinks.active,
.menulinks.active,
.tablelinks.active {
  background-color: #ccc;
  color: #3f51b5;
}

.tablinksimagemain.active {
  background-color: #ccc;
}

.tablinksimagemain:hover {
  background-color: #ccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="tabDiv" style="width: 100%; height: 100%; padding-left: 5px; padding-right: 5px; visibility: visible">
    <div class="tab">
      <img src="img/table.png" class="tablinksimagemain active" onclick="openTab(event, 'tabContent', 0)">
      <img src="img/table-structure.png" class="tablinksimagemain" onclick="openTab(event, 'tabStructure', 1)">
      <img src="img/table-info.png" class="tablinksimagemain" onclick="openTab(event, 'tabInfo', 2)">
      <img src="img/proc.png" class="tablinksimagemain" onclick="openTab(event, 'tabProc', 3)">
      <img src="img/table-query.png" class="tablinksimagemain" onclick="openTab(event, 'tabQuery', 4)">
      <img id="imgLogout" class="tablinksimage" src="img/logout.png">
      <img id="imgRefresh" class="tablinksimage" src="img/refIcon.png">
    </div>
    <div id="divTableList">

    </div>
    <div id="tabContent" class="tabContent" style="display: block">
      <div id="contentDivContent" class="contentDiv">

      </div>
    </div>

    <div id="tabStructure" class="tabContent" style="display: none">

    </div>

    <div id="tabInfo" class="tabContent" style="display: none">

    </div>
    <div id="tabProc" class="tabContent" style="display: none">

    </div>

    <div id="tabQuery" class="tabContent" style="display: none">

    </div>
  </div>
</body></code>```

As you can see the div for the main content goes further than the the div on the left, I know this is due to the menubar but I'm confused as they are both of their heights are set to 100% as is the container they are both in.

I messed around with the percentages to get them to match up which brings me to my second issue: they match up on my screen resolution but they will no longer match up as soon as the resolution is changed (even opening the javascript console causes it).

I don't know what I'm doing wrong as I always thought setting the heights to 100% meant that it would stop at the height limit of the body.

Any ideas?

答:
The source of confusion may be that height percentages like "100%" don't actually "divide up" the height of the containing element. They simply resolve to a precise value based on the height of the containing element.

So you are free to have the following

```<code><style>
   .parent {
     height: 100px;
   }
   .child {
     height: 50%;
   }
</style>
<div class="parent">
  <div class="child">a</div>
  <div class="child">b</div>
  <div class="child">c</div>
</div>
</code>```

The children will each be 50px high. This means, of course, that there will be 3 x 50px or 150px of content and the content will overflow the parent div. That's fine too: HTML doesn't require that divs fit inside their containers.

This is basically what is happening in your snippet. The menu takes up some room, then the other div takes up 100% of, not the remaining room, but of the total size of the containing div. This makes it overflow the body and thus looks like the one on the left is too small.

One solution, in browsers that support it, is to use:

```<code>div.tab {
  height: 100px; // or whatever you want
}

.tabcontent {
  height: calc(100% - 100px);
}
</code>```

In other browsers, the answer is trickier.

Body:
I'm having issues with getting two divs in html to end in the same exact spot. This snippet will pretty much explain the isue:

html,
body {
  height: 100%;
}

div.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
  width: 89.7%;
  float: right;
  display: inline-block;
  margin-top: 5px;
}

.tabContent {
  height: 100%;
  box-sizing: border-box;
}

#divTableList,
.contentDiv {
  border: 1px solid #ccc;
}

.contentDiv {
  height: 100%;
  width: 89.7%;
  margin-top: 2px;
  background-color: #f1f1f1;
  text-align: center;
  display: inline-block;
  float: right
}

#divTableList {
  height: 100%;
  box-sizing: border-box;
  width: 10%;
  margin-top: 5px;
  float: left;
  background-color: #f1f1f1;
  text-align: center;
  display: inline-block
}

/* Style the buttons inside the tab */

.tablinksimage {
  background-color: inherit;
  float: right;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transform: rotate(0);
  transition: all 0.3s;
}

.tablinksimagemain {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: all 0.3s;
}

.tablinks:hover,
.menulinks:hover,
.tablelinks:hover {
  background-color: #ccc;
}

.tablinks.active,
.menulinks.active,
.tablelinks.active {
  background-color: #ccc;
  color: #3f51b5;
}

.tablinksimagemain.active {
  background-color: #ccc;
}

.tablinksimagemain:hover {
  background-color: #ccc;
}

As you can see the div for the main content goes further than the the div on the left, I know this is due to the menubar but I'm confused as they are both of their heights are set to 100% as is the container they are both in.

I messed around with the percentages to get them to match up which brings me to my second issue: they match up on my screen resolution but they will no longer match up as soon as the resolution is changed (even opening the javascript console causes it).

I don't know what I'm doing wrong as I always thought setting the heights to 100% meant that it would stop at the height limit of the body.

Any ideas?

Body:
The source of confusion may be that height percentages like "100%" don't actually "divide up" the height of the containing element. They simply resolve to a precise value based on the height of the containing element.

So you are free to have the following

<style>
   .parent {
     height: 100px;
   }
   .child {
     height: 50%;
   }
</style>
<div class="parent">
  <div class="child">a</div>
  <div class="child">b</div>
  <div class="child">c</div>
</div>

The children will each be 50px high. This means, of course, that there will be 3 x 50px or 150px of content and the content will overflow the parent div. That's fine too: HTML doesn't require that divs fit inside their containers.

This is basically what is happening in your snippet. The menu takes up some room, then the other div takes up 100% of, not the remaining room, but of the total size of the containing div. This makes it overflow the body and thus looks like the one on the left is too small.

One solution, in browsers that support it, is to use:

div.tab {
  height: 100px; // or whatever you want
}

.tabcontent {
  height: calc(100% - 100px);
}

In other browsers, the answer is trickier.


来源: stackexchange

问:
Cache management for watchQuery (Angular-Apollo)
I have a problem combining pagination, prefetching, and refetching of data using Apollo with Angular 2. My intended behaviour in the app is that there never should be any difference in data between the server and the client. I want to reduce loading time for the user by prefetching data onmouseover in the menu and have a spinner/loading screen in every component that hides the content until the data has been fetched. If a component already have been visited I want to trigger a refetch instead of a prefetch onmouseover so that the the client matches the server.

Today if I navigate to a component and paginate to, for example, the third page which shows that set of data and after that navigate to another component and then back to the first component again (before fetching of the new data is done) I get the cached data from the third page which trigger the spinner to hide and the wrong dataset to show for one/a couple of seconds before the subscribe gets the "right" data.

My question is: Is there any way to clear/control the cache of a specific query/watchQuery so that I'm always sure to not show cached data in the client?

答:
Here is an example using Apollo for Angular as described by @Eitan Frailich:</p>

```<code>import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

class AppModule {
    constructor(apollo: Apollo, httpLink: HttpLink) {
        apollo.create({
            link: httpLink.create(),
            cache: new InMemoryCache(),
            defaultOptions: {
            watchQuery: {
                fetchPolicy: 'cache-and-network',
                errorPolicy: 'ignore',
            },
            query: {
                fetchPolicy: 'network-only',
                errorPolicy: 'all',
            },
            mutate: {
                errorPolicy: 'all'
            }
        }
        });
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is an example using Apollo for Angular as described by @Eitan Frailich:

import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

class AppModule {
    constructor(apollo: Apollo, httpLink: HttpLink) {
        apollo.create({
            link: httpLink.create(),
            cache: new InMemoryCache(),
            defaultOptions: {
            watchQuery: {
                fetchPolicy: 'cache-and-network',
                errorPolicy: 'ignore',
            },
            query: {
                fetchPolicy: 'network-only',
                errorPolicy: 'all',
            },
            mutate: {
                errorPolicy: 'all'
            }
        }
        });
    }
}


问:
NameError: uninitialized constant in Rails app when testing with RSpec and Spork
I am trying to run my tests in my first Rails app using the following command in Terminal:

```<code>rspec spec/
</code>```

But it is only resulting in the following error(s):

```<code>Exception encountered: #<NameError: uninitialized constant PagesController>
backtrace:
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/backward_compatibility.rb:20:in `const_missing'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-expectations-2.3.0/lib/rspec/expectations/backward_compatibility.rb:6:in `const_missing'
/Users/rich/dev/rails_projects/abunchofletters/spec/controllers/pages_controller_spec.rb:3:in `<top (required)>'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `map'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load_spec_files'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/command_line.rb:18:in `run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/monkey/spork/test_framework/rspec.rb:4:in `run_tests'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:13:in `block in run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:21:in `block in initialize'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:18:in `fork'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:18:in `initialize'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:9:in `new'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:9:in `run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/server.rb:47:in `run'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1558:in `perform_without_block'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1518:in `perform'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1592:in `block (2 levels) in main_loop'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1588:in `loop'
</code>```

I can run the site successfully in the browser, and "Spork is ready and listening", which makes me think there is a problem with the Gems I'm running, RSpec, Spork or... something? Rather than the tests I've written as the PagesController and RSpec test were based on the RailsTutorial.org book. I am at a loss.

Here's my Gemfile:

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

gem 'rails', '3.0.3'
gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'
gem 'gravatar_image_tag', '0.1.0'
gem "nokogiri", '1.4.4'
gem 'will_paginate', '3.0.pre2'

group :development do
  gem 'rspec-rails', '2.3.0'
  gem 'annotate-models', '1.0.4'
  gem 'faker', '0.3.1'
end

group :test do
  gem 'rspec', '2.3.0'
  gem 'webrat', '0.7.1'
  gem 'spork', '0.9.0.rc2'
  gem 'factory_girl_rails', '1.0'
end
</code>```

Followed by my local gems list:

```<code>abstract (1.0.0)
actionmailer (3.0.3)
actionpack (3.0.3)
activemodel (3.0.3)
activerecord (3.0.3)
activeresource (3.0.3)
activesupport (3.0.3)
annotate-models (1.0.4)
arel (2.0.6)
autotest (4.3.2)
autotest-fsevent (0.2.2)
autotest-growl (0.2.4)
autotest-rails-pure (4.1.0)
builder (2.1.2)
bundler (1.0.3)
diff-lcs (1.1.2)
erubis (2.6.6)
factory_girl (1.3.2)
factory_girl_rails (1.0)
faker (0.3.1)
gravatar_image_tag (0.1.0)
i18n (0.5.0)
mail (2.2.12)
mime-types (1.16)
nokogiri (1.4.4)
polyglot (0.3.1)
rack (1.2.1)
rack-mount (0.6.13)
rack-test (0.5.6)
rails (3.0.3)
railties (3.0.3)
rake (0.8.7)
rdoc (2.5.11)
rspec (2.3.0)
rspec-core (2.3.0)
rspec-expectations (2.3.0)
rspec-mocks (2.3.0)
rspec-rails (2.3.0)
spork (0.9.0.rc2)
sqlite3-ruby (1.2.5)
sys-uname (0.8.4)
thor (0.14.6)
treetop (1.4.9)
tzinfo (0.3.23)
webrat (0.7.1)
will_paginate (3.0.pre2)
</code>```

Does anyone have any ideas or can I help by providing more information? I'm a Rails novice coming back to it every now and then seem to encounter problems before giving up again...

Update My Spec/spec_helper.rb file:

```<code>require 'rubygems'
require 'spork'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However,
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  ENV["RAILS_ENV"] ||= 'test'
  unless defined?(Rails)
    require File.dirname(__FILE__) + "/../config/environment"
  end
  require 'rspec/rails'

  # Requires supporting files with custom matchers and macros, etc,
  # in ./support/ and its subdirectories.
  Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

  Rspec.configure do |config|
    # == Mock Framework
    #
    # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
    #
    # config.mock_with :mocha
    # config.mock_with :flexmock
    # config.mock_with :rr
    config.mock_with :rspec

    config.fixture_path = "#{::Rails.root}/spec/fixtures"

    # If you're not using ActiveRecord, or you'd prefer not to run each of your
    # examples within a transaction, comment the following line or assign false
    # instead of true.
    config.use_transactional_fixtures = true

    ### Part of a Spork hack. See http://bit.ly/arY19y
    # Emulate initializer set_clear_dependencies_hook in
    # railties/lib/rails/application/bootstrap.rb
    ActiveSupport::Dependencies.clear
  end
end

Spork.each_run do
end
</code>```

And here is the output from Terminal when the contents of spec_helper are removed:

```<code>No DRb server is running. Running in local process instead ...
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/backward_compatibility.rb:20:in `const_missing': uninitialized constant Object::PagesController (NameError)
    from /Users/rich/dev/rails_projects/abunchofletters/spec/controllers/pages_controller_spec.rb:3:in `<top (required)>'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `map'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load_spec_files'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/command_line.rb:18:in `run'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:55:in `run_in_process'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:44:in `run'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:10:in `block in autorun'
</code>```

答: as it was written in rails tutorial "spork" sometimes "hang's up" so: restart "spork"</p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying to run my tests in my first Rails app using the following command in Terminal:

rspec spec/

But it is only resulting in the following error(s):

Exception encountered: #<NameError: uninitialized constant PagesController>
backtrace:
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/backward_compatibility.rb:20:in `const_missing'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-expectations-2.3.0/lib/rspec/expectations/backward_compatibility.rb:6:in `const_missing'
/Users/rich/dev/rails_projects/abunchofletters/spec/controllers/pages_controller_spec.rb:3:in `<top (required)>'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `map'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load_spec_files'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/command_line.rb:18:in `run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/monkey/spork/test_framework/rspec.rb:4:in `run_tests'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:13:in `block in run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:21:in `block in initialize'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:18:in `fork'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:18:in `initialize'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:9:in `new'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:9:in `run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/server.rb:47:in `run'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1558:in `perform_without_block'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1518:in `perform'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1592:in `block (2 levels) in main_loop'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1588:in `loop'

I can run the site successfully in the browser, and "Spork is ready and listening", which makes me think there is a problem with the Gems I'm running, RSpec, Spork or... something? Rather than the tests I've written as the PagesController and RSpec test were based on the RailsTutorial.org book. I am at a loss.

Here's my Gemfile:

source 'http://rubygems.org'

gem 'rails', '3.0.3'
gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'
gem 'gravatar_image_tag', '0.1.0'
gem "nokogiri", '1.4.4'
gem 'will_paginate', '3.0.pre2'

group :development do
  gem 'rspec-rails', '2.3.0'
  gem 'annotate-models', '1.0.4'
  gem 'faker', '0.3.1'
end

group :test do
  gem 'rspec', '2.3.0'
  gem 'webrat', '0.7.1'
  gem 'spork', '0.9.0.rc2'
  gem 'factory_girl_rails', '1.0'
end

Followed by my local gems list:

abstract (1.0.0)
actionmailer (3.0.3)
actionpack (3.0.3)
activemodel (3.0.3)
activerecord (3.0.3)
activeresource (3.0.3)
activesupport (3.0.3)
annotate-models (1.0.4)
arel (2.0.6)
autotest (4.3.2)
autotest-fsevent (0.2.2)
autotest-growl (0.2.4)
autotest-rails-pure (4.1.0)
builder (2.1.2)
bundler (1.0.3)
diff-lcs (1.1.2)
erubis (2.6.6)
factory_girl (1.3.2)
factory_girl_rails (1.0)
faker (0.3.1)
gravatar_image_tag (0.1.0)
i18n (0.5.0)
mail (2.2.12)
mime-types (1.16)
nokogiri (1.4.4)
polyglot (0.3.1)
rack (1.2.1)
rack-mount (0.6.13)
rack-test (0.5.6)
rails (3.0.3)
railties (3.0.3)
rake (0.8.7)
rdoc (2.5.11)
rspec (2.3.0)
rspec-core (2.3.0)
rspec-expectations (2.3.0)
rspec-mocks (2.3.0)
rspec-rails (2.3.0)
spork (0.9.0.rc2)
sqlite3-ruby (1.2.5)
sys-uname (0.8.4)
thor (0.14.6)
treetop (1.4.9)
tzinfo (0.3.23)
webrat (0.7.1)
will_paginate (3.0.pre2)

Does anyone have any ideas or can I help by providing more information? I'm a Rails novice coming back to it every now and then seem to encounter problems before giving up again...

Update My Spec/spec_helper.rb file:

require 'rubygems'
require 'spork'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However,
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  ENV["RAILS_ENV"] ||= 'test'
  unless defined?(Rails)
    require File.dirname(__FILE__) + "/../config/environment"
  end
  require 'rspec/rails'

  # Requires supporting files with custom matchers and macros, etc,
  # in ./support/ and its subdirectories.
  Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

  Rspec.configure do |config|
    # == Mock Framework
    #
    # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
    #
    # config.mock_with :mocha
    # config.mock_with :flexmock
    # config.mock_with :rr
    config.mock_with :rspec

    config.fixture_path = "#{::Rails.root}/spec/fixtures"

    # If you're not using ActiveRecord, or you'd prefer not to run each of your
    # examples within a transaction, comment the following line or assign false
    # instead of true.
    config.use_transactional_fixtures = true

    ### Part of a Spork hack. See http://bit.ly/arY19y
    # Emulate initializer set_clear_dependencies_hook in
    # railties/lib/rails/application/bootstrap.rb
    ActiveSupport::Dependencies.clear
  end
end

Spork.each_run do
end

And here is the output from Terminal when the contents of spec_helper are removed:

No DRb server is running. Running in local process instead ...
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/backward_compatibility.rb:20:in `const_missing': uninitialized constant Object::PagesController (NameError)
    from /Users/rich/dev/rails_projects/abunchofletters/spec/controllers/pages_controller_spec.rb:3:in `<top (required)>'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `map'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load_spec_files'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/command_line.rb:18:in `run'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:55:in `run_in_process'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:44:in `run'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:10:in `block in autorun'


问:
CNTK: How do I initialize LSTM hidden state?
I'm trying convert a working image captioning CNN-LSTM network from TensorFlow to CNTK, and have what I think is a correctly trained model, but am having trouble figuring out how to extract predictions from the final trained CNTK model.

This is the general architecture I'm working with:

This is my CNTK model:

```<code>def create_lstm_model(image_features, text_features):
    embedding_dim = 512
    hidden_dim = 512
    cell_dim = 512
    vocab_dim = 77

    image_embedding = Embedding(embedding_dim)
    text_embedding = Embedding(embedding_dim)
    lstm_classifier = Sequential([Stabilizer(),
                                  Recurrence(LSTM(hidden_dim)),
                                  Recurrence(LSTM(hidden_dim)),
                                  Stabilizer(),
                                  Dense(vocab_dim)])

    embedded_images = BatchNormalization()(image_embedding(image_features))
    embedded_text = text_embedding(text_features)
    lstm_input = C.plus(embedded_images, embedded_text)
    lstm_input = C.dropout(lstm_input, 0.5)
    output = lstm_classifier(lstm_input)

    return output
</code>```

I'm providing my data in CTF format, with fixed caption sequence sizes of 40, using this structure:

```<code>def create_reader(path, is_training):
    return MinibatchSource(CTFDeserializer(path, StreamDefs(
        target_tokens = StreamDef(field='target_tokens', shape=vocab_len, is_sparse=True),
        input_tokens = StreamDef(field='input_tokens', shape=vocab_len, is_sparse=True),
        image_features = StreamDef(field='image_features', shape=image_features_dim, is_sparse=False)
    )), randomize = is_training, max_sweeps = INFINITELY_REPEAT if is_training else 1)
</code>```

Aside: the reason for three streams of data - I have an input image feature vector (last 2048-dim layer of a pre-trained ResNet), a sequence of input text tokens, and a sequence of output text tokens. So basically my CTF file, in terms of sequences, looks like:

```<code>0 | target_token_0  | input_token_0 | input_image_feature_vector (2048-dim)
0 | target_token_1  | input_token_1 | empty array of 2048 zeros
0 | target_token_2  | input_token_2 | empty array of 2048 zeros
...
0 | target_token_40 | input_token_40 | empty array of 2048 zeros
1 | target_token_0  | input_token_0 | input_image_feature_vector (2048-dim)
1 | target_token_1  | input_token_1 | empty array of 2048 zeros
1 | target_token_2  | input_token_2 | empty array of 2048 zeros
...
1 | target_token_40 | input_token_40 | empty array of 2048 zeros
</code>```

Basically, I couldn't figure out how to slice & splice two sequences together in CNTK (even though you can splice two tensors easily), so I'm hacking around it by providing only the first element in a sequence with an input 2048-dim image feature vector, and the remaining elements in a sequence with an empty 2048-dim vector of zeros - setup for:

C.plus(embedded_images, embedded_text)

in the model above - where the goal is to essentially take the first element of a sequence of 40 [2048]->[512] image embeddings and hack-splice(TM) it in front of the last 39 elements of a sequence of 40 [vocab_dim]->[512] word embeddings. I'm counting on pretty empty [2048]->[512] image embeddings being learned for the empty image vectors (2048 zeros), so I'm taking my embedded image sequence and element-wise adding it to my embedded text sequence before all goes into the LSTM. Basically, this:

```<code>image embedding sequence: [-1, 40, 512]  (e.g., [-1, 0, 512])
text embedding sequence:  [-1, 40, 512]  (e.g., [-1, 1:40, 512)
+
---------------------------------------
lstm input sequence:      [-1, 40, 512]
</code>```

Which brings me to my actual question. Now that I have a model that trains decently well, I'd like to extract caption predictions from the model, basically doing something like this (from this PyTorch image captioning tutorial):

```<code>def sample(self, features, states=None):
    """Samples captions for given image features (Greedy search)."""
    sampled_ids = []
    inputs = features.unsqueeze(1)
    for i in range(20):                                      # maximum sampling length
        hiddens, states = self.lstm(inputs, states)          # (batch_size, 1, hidden_size),
        outputs = self.linear(hiddens.squeeze(1))            # (batch_size, vocab_size)
        predicted = outputs.max(1)[1]
        sampled_ids.append(predicted)
        inputs = self.embed(predicted)
        inputs = inputs.unsqueeze(1)                         # (batch_size, 1, embed_size)
    sampled_ids = torch.cat(sampled_ids, 1)                  # (batch_size, 20)
    return sampled_ids.squeeze()
</code>```

The problem is, I can't figure out the CNTK equivalent for getting the hidden state out of an LSTM and pumping it back in next time step:

```<code>hiddens, states = self.lstm(inputs, states)
</code>```

How does this work in CNTK?

答:
I faced the same issue recently. Below I'm providing a sample code I built to understand how to use Recurrence and RNNStep objects to obtain forecasts. Note here that the forecasts are just the next period state since this is not transformed in any way. I used an RNNStep because it contains fewer parameters which makes it easy to build a simple example. Same logic applies to LSTM.

The first part of the example builds a white noise process to play with (it could be any process):

```<code>process_dim = 1
n_periods = 100
np.random.seed(0)
x_data = np.random.multivariate_normal(mean=np.array([0.0], dtype=np.float32),
                                       cov=np.matrix([[0.1]], dtype=np.float32),
                                       size=n_periods).astype(np.float32)
</code>```

Then I build the RNN and sets its parameters in such a way that it is easy to understand its internal computations.

```<code>x = cntk.sequence.input_variable(shape=process_dim)
initial_state = 10
W = 1
H = 1
b = 1
with cntk.layers.default_options(initial_state=initial_state):
    model = cntk.layers.Recurrence(cntk.layers.RNNStep(shape=process_dim,
                                                       activation=lambda x_: x_,
                                                       init=W,
                                                       init_bias=b))(x)
</code>```

Note1: the argument init sets both H and W.
Note 2: if you don't use the with statement the initial state is set to 0 which works too.

Let's first look at how to evaluate the RNN one step ahead, i.e. combining the previous period state (initial state in our case) and the current period external input (an entry of x_data) to obtain the next state. The script below does that by calling model.eval() on some given inputs and then does the actual RNN computations manually to validate the output.

```<code>x0 = np.array(x_data[0]).reshape((1, 1))
x1 = np.array(x_data[1]).reshape((1, 1))
x2 = np.array(x_data[2]).reshape((1, 1))

h00 = model.eval({x: x0})
h01 = model.eval({x: x1})
h02 = model.eval({x: x2})

print("x0: {}, h00: {}".format(x0, h00))
print("x1: {}, h01: {}".format(x1, h01))
print("x2: {}, h02: {}".format(x2, h02))

# validation
h00_m = initial_state * H + x0[0, 0] * W + b
h01_m = initial_state * H + x1[0, 0] * W + b
h02_m = initial_state * H + x2[0, 0] * W + b

print("validation of state computed manually")
print("x0: {}, h00_m: {}".format(x0[0, 0], h00_m))
print("x1: {}, h01_m: {}".format(x1[0, 0], h01_m))
print("x2: {}, h02_m: {}".format(x2[0, 0], h02_m))
</code>```

Let's now see how to use model.eval() to obtain multiple periods ahead forecasts. Again, the script below does that and validates the output.

```<code># x0 now contains multiple entries
x0 = np.array(x_data[0:4]).reshape((4, 1))
h1234 = model.eval({x: x0})
print("forecasts obtained by model automatically")
print(h1234)

h01_m = initial_state * H + x0[0, 0] * W + b
h12_m = h01_m * H + x0[1, 0] * W + b
h23_m = h12_m * H + x0[2, 0] * W + b
h34_m = h23_m * H + x0[3, 0] * W + b

print("forecasts computed manually")
print(h01_m)
print(h12_m)
print(h23_m)
print(h34_m)
</code>```

So because RNNStep is used inside Recurrence, it automatically calls RNNStep according to the number of input(s) you provide to the model function. Each time the RNNStep is called it receives the previous period state and an entry of the array given to model.eval(). This is in line with what happens at training.

Here is some useful documentation of LSTMs and RNNs:
https://learn.microsoft.com/en-us/python/api/cntk.layers.blocks?view=cntk-py-2.2
Its content is not exactly the same as https://cntk.ai/pythondocs/index.html and in this case it is more useful.

Sorry I cannot help with the ctf part of your question, I have limited knowledge of this and I also have posted a question on this that has yet to be answered.

Body:
I'm trying convert a working image captioning CNN-LSTM network from TensorFlow to CNTK, and have what I think is a correctly trained model, but am having trouble figuring out how to extract predictions from the final trained CNTK model.

This is the general architecture I'm working with:

This is my CNTK model:

def create_lstm_model(image_features, text_features):
    embedding_dim = 512
    hidden_dim = 512
    cell_dim = 512
    vocab_dim = 77

    image_embedding = Embedding(embedding_dim)
    text_embedding = Embedding(embedding_dim)
    lstm_classifier = Sequential([Stabilizer(),
                                  Recurrence(LSTM(hidden_dim)),
                                  Recurrence(LSTM(hidden_dim)),
                                  Stabilizer(),
                                  Dense(vocab_dim)])

    embedded_images = BatchNormalization()(image_embedding(image_features))
    embedded_text = text_embedding(text_features)
    lstm_input = C.plus(embedded_images, embedded_text)
    lstm_input = C.dropout(lstm_input, 0.5)
    output = lstm_classifier(lstm_input)

    return output

I'm providing my data in CTF format, with fixed caption sequence sizes of 40, using this structure:

def create_reader(path, is_training):
    return MinibatchSource(CTFDeserializer(path, StreamDefs(
        target_tokens = StreamDef(field='target_tokens', shape=vocab_len, is_sparse=True),
        input_tokens = StreamDef(field='input_tokens', shape=vocab_len, is_sparse=True),
        image_features = StreamDef(field='image_features', shape=image_features_dim, is_sparse=False)
    )), randomize = is_training, max_sweeps = INFINITELY_REPEAT if is_training else 1)

Aside: the reason for three streams of data - I have an input image feature vector (last 2048-dim layer of a pre-trained ResNet), a sequence of input text tokens, and a sequence of output text tokens. So basically my CTF file, in terms of sequences, looks like:

0 | target_token_0  | input_token_0 | input_image_feature_vector (2048-dim)
0 | target_token_1  | input_token_1 | empty array of 2048 zeros
0 | target_token_2  | input_token_2 | empty array of 2048 zeros
...
0 | target_token_40 | input_token_40 | empty array of 2048 zeros
1 | target_token_0  | input_token_0 | input_image_feature_vector (2048-dim)
1 | target_token_1  | input_token_1 | empty array of 2048 zeros
1 | target_token_2  | input_token_2 | empty array of 2048 zeros
...
1 | target_token_40 | input_token_40 | empty array of 2048 zeros

Basically, I couldn't figure out how to slice & splice two sequences together in CNTK (even though you can splice two tensors easily), so I'm hacking around it by providing only the first element in a sequence with an input 2048-dim image feature vector, and the remaining elements in a sequence with an empty 2048-dim vector of zeros - setup for:

C.plus(embedded_images, embedded_text)

in the model above - where the goal is to essentially take the first element of a sequence of 40 [2048]->[512] image embeddings and hack-splice(TM) it in front of the last 39 elements of a sequence of 40 [vocab_dim]->[512] word embeddings. I'm counting on pretty empty [2048]->[512] image embeddings being learned for the empty image vectors (2048 zeros), so I'm taking my embedded image sequence and element-wise adding it to my embedded text sequence before all goes into the LSTM. Basically, this:

image embedding sequence: [-1, 40, 512]  (e.g., [-1, 0, 512])
text embedding sequence:  [-1, 40, 512]  (e.g., [-1, 1:40, 512)
+
---------------------------------------
lstm input sequence:      [-1, 40, 512]

Which brings me to my actual question. Now that I have a model that trains decently well, I'd like to extract caption predictions from the model, basically doing something like this (from this PyTorch image captioning tutorial):

def sample(self, features, states=None):
    """Samples captions for given image features (Greedy search)."""
    sampled_ids = []
    inputs = features.unsqueeze(1)
    for i in range(20):                                      # maximum sampling length
        hiddens, states = self.lstm(inputs, states)          # (batch_size, 1, hidden_size),
        outputs = self.linear(hiddens.squeeze(1))            # (batch_size, vocab_size)
        predicted = outputs.max(1)[1]
        sampled_ids.append(predicted)
        inputs = self.embed(predicted)
        inputs = inputs.unsqueeze(1)                         # (batch_size, 1, embed_size)
    sampled_ids = torch.cat(sampled_ids, 1)                  # (batch_size, 20)
    return sampled_ids.squeeze()

The problem is, I can't figure out the CNTK equivalent for getting the hidden state out of an LSTM and pumping it back in next time step:

hiddens, states = self.lstm(inputs, states)

How does this work in CNTK?

Body:
I faced the same issue recently. Below I'm providing a sample code I built to understand how to use Recurrence and RNNStep objects to obtain forecasts. Note here that the forecasts are just the next period state since this is not transformed in any way. I used an RNNStep because it contains fewer parameters which makes it easy to build a simple example. Same logic applies to LSTM.

The first part of the example builds a white noise process to play with (it could be any process):

process_dim = 1
n_periods = 100
np.random.seed(0)
x_data = np.random.multivariate_normal(mean=np.array([0.0], dtype=np.float32),
                                       cov=np.matrix([[0.1]], dtype=np.float32),
                                       size=n_periods).astype(np.float32)

Then I build the RNN and sets its parameters in such a way that it is easy to understand its internal computations.

x = cntk.sequence.input_variable(shape=process_dim)
initial_state = 10
W = 1
H = 1
b = 1
with cntk.layers.default_options(initial_state=initial_state):
    model = cntk.layers.Recurrence(cntk.layers.RNNStep(shape=process_dim,
                                                       activation=lambda x_: x_,
                                                       init=W,
                                                       init_bias=b))(x)

Note1: the argument init sets both H and W.
Note 2: if you don't use the with statement the initial state is set to 0 which works too.

Let's first look at how to evaluate the RNN one step ahead, i.e. combining the previous period state (initial state in our case) and the current period external input (an entry of x_data) to obtain the next state. The script below does that by calling model.eval() on some given inputs and then does the actual RNN computations manually to validate the output.

x0 = np.array(x_data[0]).reshape((1, 1))
x1 = np.array(x_data[1]).reshape((1, 1))
x2 = np.array(x_data[2]).reshape((1, 1))

h00 = model.eval({x: x0})
h01 = model.eval({x: x1})
h02 = model.eval({x: x2})

print("x0: {}, h00: {}".format(x0, h00))
print("x1: {}, h01: {}".format(x1, h01))
print("x2: {}, h02: {}".format(x2, h02))

# validation
h00_m = initial_state * H + x0[0, 0] * W + b
h01_m = initial_state * H + x1[0, 0] * W + b
h02_m = initial_state * H + x2[0, 0] * W + b

print("validation of state computed manually")
print("x0: {}, h00_m: {}".format(x0[0, 0], h00_m))
print("x1: {}, h01_m: {}".format(x1[0, 0], h01_m))
print("x2: {}, h02_m: {}".format(x2[0, 0], h02_m))

Let's now see how to use model.eval() to obtain multiple periods ahead forecasts. Again, the script below does that and validates the output.

# x0 now contains multiple entries
x0 = np.array(x_data[0:4]).reshape((4, 1))
h1234 = model.eval({x: x0})
print("forecasts obtained by model automatically")
print(h1234)

h01_m = initial_state * H + x0[0, 0] * W + b
h12_m = h01_m * H + x0[1, 0] * W + b
h23_m = h12_m * H + x0[2, 0] * W + b
h34_m = h23_m * H + x0[3, 0] * W + b

print("forecasts computed manually")
print(h01_m)
print(h12_m)
print(h23_m)
print(h34_m)

So because RNNStep is used inside Recurrence, it automatically calls RNNStep according to the number of input(s) you provide to the model function. Each time the RNNStep is called it receives the previous period state and an entry of the array given to model.eval(). This is in line with what happens at training.

Here is some useful documentation of LSTMs and RNNs:
https://learn.microsoft.com/en-us/python/api/cntk.layers.blocks?view=cntk-py-2.2
Its content is not exactly the same as https://cntk.ai/pythondocs/index.html and in this case it is more useful.

Sorry I cannot help with the ctf part of your question, I have limited knowledge of this and I also have posted a question on this that has yet to be answered.


问:
shuffle error in hadoop
Hi i get the following error in my cluster when i tried to execute a mapreduce program in hadoop. This code works fine for data which had lesser file size but hadoop throws the following error and i have sufficient place in the cluster. I tried increasing heapspace of reducer from 6gb to 10gb and still it fails.
Tag used

Please help me to fix this issue

Error: org.apache.hadoop.mapreduce.task.reduce.Shuffle$ShuffleError:
  error in shuffle in fetcher#7 at
  org.apache.hadoop.mapreduce.task.reduce.Shuffle.run(Shuffle.java:134)
  at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:376) at
  org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163) at
  java.security.AccessController.doPrivileged(Native Method) at
  javax.security.auth.Subject.doAs(Subject.java:415) at
  org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1671)
  at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158) Caused
  by: java.lang.OutOfMemoryError: Java heap space at
  org.apache.hadoop.io.BoundedByteArrayOutputStream.(BoundedByteArrayOutputStream.java:56)
  at
  org.apache.hadoop.io.BoundedByteArrayOutputStream.(BoundedByteArrayOutputStream.java:46)
  at
  org.apache.hadoop.mapreduce.task.reduce.InMemoryMapOutput.(InMemoryMapOutput.java:63)
  at
  org.apache.hadoop.mapreduce.task.reduce.MergeManagerImpl.unconditionalReserve(MergeManagerImpl.java:305)
  at
  org.apache.hadoop.mapreduce.task.reduce.MergeManagerImpl.reserve(MergeManagerImpl.java:295)
  at
  org.apache.hadoop.mapreduce.task.reduce.Fetcher.copyMapOutput(Fetcher.java:514)
  at
  org.apache.hadoop.mapreduce.task.reduce.Fetcher.copyFromHost(Fetcher.java:336)
  at
  org.apache.hadoop.mapreduce.task.reduce.Fetcher.run(Fetcher.java:193)

答:
Your question would have been more clearer if you have mentioned the Map Reduce properties which you are using for your code to run as it will provide some insights for the memory calculation for the shuffle phase.

memorylimit = Runtime.getRuntime().maxMemory()*(mapreduce.reduce.shuffle.input.buffer.percent).

The defualt value of mapreduce.reduce.shuffle.input.buffer.percent is 0.9 and you can decrease its value to 0.2 for your memoryLimit to be < 1. So properties you can include are :

```<code><property>
    <name>mapreduce.reduce.shuffle.input.buffer.percent</name>
    <value>0.20</value>
</property>
<property>
    <name>mapreduce.reduce.shuffle.parallelcopies</name>
    <value>4</value>
</property>
</code>```

For more clarification you can refer : https://issues.apache.org/jira/browse/MAPREDUCE-6447

Title: shuffle error in hadoop

Body:
Your question would have been more clearer if you have mentioned the Map Reduce properties which you are using for your code to run as it will provide some insights for the memory calculation for the shuffle phase.

memorylimit = Runtime.getRuntime().maxMemory()*(mapreduce.reduce.shuffle.input.buffer.percent).

The defualt value of mapreduce.reduce.shuffle.input.buffer.percent is 0.9 and you can decrease its value to 0.2 for your memoryLimit to be < 1. So properties you can include are :

<property>
    <name>mapreduce.reduce.shuffle.input.buffer.percent</name>
    <value>0.20</value>
</property>
<property>
    <name>mapreduce.reduce.shuffle.parallelcopies</name>
    <value>4</value>
</property>

For more clarification you can refer : https://issues.apache.org/jira/browse/MAPREDUCE-6447


问:
Creating a combo chart in Excel with VBA code
How do I adjust the code below to create a combo chart with a bar for the primary axis and line for the secondary axis?

I have two columns of data.

```<code>Sub CreateChart()
    Dim rng As Range
    Dim cht As Object

    Set rng = ActiveSheet.Range("C1:D6")
    Set cht = ActiveSheet.Shapes.AddChart2

    cht.Chart.SetSourceData Source:=rng

    cht.Chart.ChartType = xlColumnClustered

    cht.Chart.HasTitle = True
    cht.Chart.ChartTitle.Text = "Average Price and Dollar Volume of Sales"

End Sub
</code>```

Any help would be appreciated! Thank you!

答:
How about this:</p>

```<code>Sub foo()
    ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
    ActiveChart.SetSourceData Source:=Range("Sheet1!$C$1:$D$6") 'make sure the range is correct here
    ActiveChart.FullSeriesCollection(1).ChartType = xlColumnClustered 'select which column should be the Line or the Column
    ActiveChart.FullSeriesCollection(1).AxisGroup = 1
    ActiveChart.FullSeriesCollection(2).ChartType = xlLine
    ActiveChart.FullSeriesCollection(2).AxisGroup = 1
    ActiveChart.ChartTitle.Text = "Average Price and Dollar Volume of Sales"
End Sub
</code>```

Body:
How do I adjust the code below to create a combo chart with a bar for the primary axis and line for the secondary axis?

I have two columns of data.

Sub CreateChart()
    Dim rng As Range
    Dim cht As Object

    Set rng = ActiveSheet.Range("C1:D6")
    Set cht = ActiveSheet.Shapes.AddChart2

    cht.Chart.SetSourceData Source:=rng

    cht.Chart.ChartType = xlColumnClustered

    cht.Chart.HasTitle = True
    cht.Chart.ChartTitle.Text = "Average Price and Dollar Volume of Sales"

End Sub

Any help would be appreciated! Thank you!

Body:
How about this:

Sub foo()
    ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
    ActiveChart.SetSourceData Source:=Range("Sheet1!$C$1:$D$6") 'make sure the range is correct here
    ActiveChart.FullSeriesCollection(1).ChartType = xlColumnClustered 'select which column should be the Line or the Column
    ActiveChart.FullSeriesCollection(1).AxisGroup = 1
    ActiveChart.FullSeriesCollection(2).ChartType = xlLine
    ActiveChart.FullSeriesCollection(2).AxisGroup = 1
    ActiveChart.ChartTitle.Text = "Average Price and Dollar Volume of Sales"
End Sub


问:
WCF sessions with a wsHttpBinding and without windows security
I need to create a WCF service that is hosted in IIS, uses http transport and hold state in the server’s memory. While I’m aware that stateful services aren't a good idea, this last constrain is necessary to make the service work with a legacy client.

My first thought was to asp.net’s session to store the values. I activated the asp.net compatibility mode in my service, which gave me access to the HttpContext, but values that were placed in the session object were not being persisted in memory. I assume this was because the http module that handles session state was not correctly configured, but when googling for answer I came across, WCF sessions and thought it might be a better idea to use them.

However, WCF sessions seem what under-document and place a strange set of prerequises on a service, and I haven’t been able to find a configuration that suits my needs: must be hosted in IIS, must use http or https transport and can’t reply on windows authentication because the client and server will not be part of the same domain. I’m trying to get this going using the wsHttpBinding, I had heard WCF sessions required either security or reliable message, but:
- Using the standard binding and when the servers are not part of the same domain it fails with a “SecurityNegotiationException The caller was not authenticated by the service” exception. This is fairly logical as it was using windows security.

If I disable security complete it fails with a “Contract requires Session, but Binding 'WSHttpBinding' doesn't support it or isn't configured properly to support it.”

If while keeping security disabled I enable reliable message I get the exception “Binding validation failed because the WSHttpBinding does not support reliable sessions over transport security (HTTPS). The channel factory or service host could not be opened. Use message security for secure reliable messaging over HTTP.”

I’ve tried enabling transport level security but this doesn’t seem to make any difference to the error generated

Is there any configuration that might work for me? Or should I just go back to the plan of using asp.net sessions?

答:
You can have WCF hold session information in memory in a pretty simple way. To eliminate any possible external influences in my instructions, I'll assume you're starting with a brand new project:

Create a new WCF Service Library project. This project will already contain a service with a WSHttpBiding binding preconfigured.

Go to the service contract (IService1.cs) and change the ServiceContract attribute to the following:

```<code>[ServiceContract(SessionMode = SessionMode.Required)]
</code>```

Go to the service implimentation (Service1.cs) and add the following ServiceBehavior attribute to the service class (Service1):

```<code>[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Single)]
</code>```

Add session data as members of the service class (Service1):

```<code>public class Service1 : IService1
{
    ...

    private string UserFullName { get; set; }

    ...
}
</code>```

Use the members to present session specific data (remember to also add them to the service contract, IService1):

```<code>public class Service1 : IService1
{
    ...

    public string Welcome(string fullName)
    {
        UserFullName = fullName ?? "Guest";
        return string.Format("Welcome back, {0}!", UserFullName);
    }

    public string Goodbye()
    {
        return string.Format("Come back soon, {0}!", UserFullName ?? "Guest");
    }

    ...
}
</code>```

SessionMode.Required ensures that your clients are session-tracked.

InstanceContextMode.PerSession ensures that an instance of your service class (Service1) is created for every session, so that you can retain session data in it and it will exist in memory across multiple calls in the same session.

ConcurrencyMode.Single ensures that only one thread can enter each service class instance (Service1), and prevents possible concurrency issues if you only access data from the service class (and external thread-safe locations).

EDIT: By default, WSHttpBinding only allows security sessions. But it also support reliable sessions, which allow establishing sessions without security enabled. The following binding configuration disables security and enables reliable sessions:

```<code><wsHttpBinding>
    <binding name="wsHttpBindingConfiguration">
        <security mode="None" />
        <reliableSession enabled="true" />
    </binding>
</wsHttpBinding>
</code>```

Body:
You can have WCF hold session information in memory in a pretty simple way. To eliminate any possible external influences in my instructions, I'll assume you're starting with a brand new project:

Create a new WCF Service Library project. This project will already contain a service with a WSHttpBiding binding preconfigured.

Go to the service contract (IService1.cs) and change the ServiceContract attribute to the following:

[ServiceContract(SessionMode = SessionMode.Required)]

Go to the service implimentation (Service1.cs) and add the following ServiceBehavior attribute to the service class (Service1):

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Single)]

Add session data as members of the service class (Service1):

public class Service1 : IService1
{
    ...

    private string UserFullName { get; set; }

    ...
}

Use the members to present session specific data (remember to also add them to the service contract, IService1):

public class Service1 : IService1
{
    ...

    public string Welcome(string fullName)
    {
        UserFullName = fullName ?? "Guest";
        return string.Format("Welcome back, {0}!", UserFullName);
    }

    public string Goodbye()
    {
        return string.Format("Come back soon, {0}!", UserFullName ?? "Guest");
    }

    ...
}

SessionMode.Required ensures that your clients are session-tracked.

InstanceContextMode.PerSession ensures that an instance of your service class (Service1) is created for every session, so that you can retain session data in it and it will exist in memory across multiple calls in the same session.

ConcurrencyMode.Single ensures that only one thread can enter each service class instance (Service1), and prevents possible concurrency issues if you only access data from the service class (and external thread-safe locations).

EDIT: By default, WSHttpBinding only allows security sessions. But it also support reliable sessions, which allow establishing sessions without security enabled. The following binding configuration disables security and enables reliable sessions:

<wsHttpBinding>
    <binding name="wsHttpBindingConfiguration">
        <security mode="None" />
        <reliableSession enabled="true" />
    </binding>
</wsHttpBinding>


问:
How to softcode firebase storage image url's

I am using Firebase Storage to create and send image url's to Firebase Database.  I have this working well when I have both a 'currentUser' and a Firebase Storage child reference hardcoded.  But, how do I grab the actual currentUser from Firebase Database and put a fluid name to the child reference/references? I've seen some possible answers to this in Java. But not Javascript. Here's my code:

```<code>// openImage() is the function that grabs a photo from the camera roll
// I'm using react-native btw, so some of this code is handling the
// blob.

openImage() {
this.setState({ loading: true });
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob

// if I use this code, it won't return the urls: const {currentUser}
// = firebase.auth()

// So, I've got the 'currentUser' hardcoded in as "12345"

const { currentUser } = "12345"

// ImagePicker.openPicker() is just a library to access the camera roll

ImagePicker.openPicker({
  width: 400,
  height: 300,
  cropping: true,
  mediaType: 'photo',
}).then(image => {
  const imagePath = image.path;

  let uploadBlob = null;

  const storage = firebase.storage();
  const storageRef = storage.ref(currentUser);

  //I also have the .child reference name hardcoded as 'dp.jpg'

  const imageRef = storageRef.child('dp.jpg');
  const mime = 'image/jpg';
  fs.readFile(imagePath, 'base64')
    .then((data) => {

      return Blob.build(data, { type: `${mime};BASE64` });
  })
  .then((blob) => {
      uploadBlob = blob;
      return imageRef.put(blob, { contentType: mime });
    })
    .then(() => {
      uploadBlob.close();
      return imageRef.getDownloadURL();
    })
    .then((url) => {
      const { image } = this.props;

      this.props.entryUpdate({ prop: 'image', value: url })

  });
});
</code>```

}

    The image url is then passed to Firebase Database and sets it as a key of 'image' and a value of 'dp.jpg'. With the hardcoding, this works fine, but for only one image and one user (or folder in Firebase Storage) of course.  I'm aware of how Firebase Realtime Database will assign it's own id number to an item as in:

```<code>const { currentUser } = firebase.auth();
const item = firebase.database().ref(`/users/${currentUser.uid}/items`)
.push();
return () => {
item.set({ make, model, year, uid: item.key, image })
</code>```

where item.key is generated by Firebase, thus it doesn't have to be hardcoded in.  Is it possible to achieve this in Firebase Storage for both the image child name and the 'currentUser'? And do I really need to assign each image to a 'currentUser' folder in Firebase storage since the mobile app only is fetching the url from the database?

答:
@parohy Thanks for taking the time to search through the firebase docs.  I think .once() only works with Firebase Realtime Database.  And I'm looking for a unique name in Firebase Storage.  However, your answer helped me come to my solution.  I was trying to tap into the fact that Firebase Database already creates perfectly unique ids.  However, I'm don't think I can access those in Firebase Storage.  So I just did:

```<code>firebase.storage().ref().child(unique + '.jpg')

const unique = Date.now() + Math.random();
</code>```

not perfectly unique, but close enough.

Body:
I am using Firebase Storage to create and send image url's to Firebase Database.  I have this working well when I have both a 'currentUser' and a Firebase Storage child reference hardcoded.  But, how do I grab the actual currentUser from Firebase Database and put a fluid name to the child reference/references? I've seen some possible answers to this in Java. But not Javascript. Here's my code:

// openImage() is the function that grabs a photo from the camera roll
// I'm using react-native btw, so some of this code is handling the
// blob.

openImage() {
this.setState({ loading: true });
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob

// if I use this code, it won't return the urls: const {currentUser}
// = firebase.auth()

// So, I've got the 'currentUser' hardcoded in as "12345"

const { currentUser } = "12345"

// ImagePicker.openPicker() is just a library to access the camera roll

ImagePicker.openPicker({
  width: 400,
  height: 300,
  cropping: true,
  mediaType: 'photo',
}).then(image => {
  const imagePath = image.path;

  let uploadBlob = null;

  const storage = firebase.storage();
  const storageRef = storage.ref(currentUser);

  //I also have the .child reference name hardcoded as 'dp.jpg'

  const imageRef = storageRef.child('dp.jpg');
  const mime = 'image/jpg';
  fs.readFile(imagePath, 'base64')
    .then((data) => {

      return Blob.build(data, { type: `${mime};BASE64` });
  })
  .then((blob) => {
      uploadBlob = blob;
      return imageRef.put(blob, { contentType: mime });
    })
    .then(() => {
      uploadBlob.close();
      return imageRef.getDownloadURL();
    })
    .then((url) => {
      const { image } = this.props;

      this.props.entryUpdate({ prop: 'image', value: url })

  });
});

}

    The image url is then passed to Firebase Database and sets it as a key of 'image' and a value of 'dp.jpg'. With the hardcoding, this works fine, but for only one image and one user (or folder in Firebase Storage) of course.  I'm aware of how Firebase Realtime Database will assign it's own id number to an item as in:

const { currentUser } = firebase.auth();
const item = firebase.database().ref(`/users/${currentUser.uid}/items`)
.push();
return () => {
item.set({ make, model, year, uid: item.key, image })

where item.key is generated by Firebase, thus it doesn't have to be hardcoded in.  Is it possible to achieve this in Firebase Storage for both the image child name and the 'currentUser'? And do I really need to assign each image to a 'currentUser' folder in Firebase storage since the mobile app only is fetching the url from the database?

Body:
@parohy Thanks for taking the time to search through the firebase docs.  I think .once() only works with Firebase Realtime Database.  And I'm looking for a unique name in Firebase Storage.  However, your answer helped me come to my solution.  I was trying to tap into the fact that Firebase Database already creates perfectly unique ids.  However, I'm don't think I can access those in Firebase Storage.  So I just did:

firebase.storage().ref().child(unique + '.jpg')

const unique = Date.now() + Math.random();

not perfectly unique, but close enough.


问:
How to Remove or overwrite sonata admin pagination?
When creating a page, pagination takes a very long time. I want to delete it or override it. Tell me who faced I want to remove these things

答:
To remove only the Twig view (no impact on performance, it's just visual) :

you can define a custom Pager using this :

```<code># app/config/your_sonata_services_config.yml
services:
    app.admin.post:
        class: AppBundle\Admin\PostAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, group: "Content", label: "Post", pager_type: "simple" }
        arguments:
            - ~
            - AppBundle\Entity\Post
            - ~
        public: true
</code>```

With tag pager_type: simple, the view SonataAdminBundle:Pager:simple_pager_results.html.twig will be called.

source : https://symfony.com/doc/master/bundles/SonataAdminBundle/cookbook/recipe_improve_performance_large_datasets.html

To disable COUNT(*) of rows and improve performance :

You can have a look here https://github.com/sonata-project/SonataDoctrineORMAdminBundle/issues/297, you have to :

extend the default SonataPager with your own class that overrides computeNbResult()

extends the default SonataProxyQuery with your own class that overrides getFixedQueryBuilder()

extend the default SonataDatagridBuilder with your own class that overrides getBaseDatagrid()

Reference those in your services

Body:
To remove only the Twig view (no impact on performance, it's just visual) :

you can define a custom Pager using this :

# app/config/your_sonata_services_config.yml
services:
    app.admin.post:
        class: AppBundle\Admin\PostAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, group: "Content", label: "Post", pager_type: "simple" }
        arguments:
            - ~
            - AppBundle\Entity\Post
            - ~
        public: true

With tag pager_type: simple, the view SonataAdminBundle:Pager:simple_pager_results.html.twig will be called.

source : https://symfony.com/doc/master/bundles/SonataAdminBundle/cookbook/recipe_improve_performance_large_datasets.html

To disable COUNT(*) of rows and improve performance :

You can have a look here https://github.com/sonata-project/SonataDoctrineORMAdminBundle/issues/297, you have to :

extend the default SonataPager with your own class that overrides computeNbResult()

extends the default SonataProxyQuery with your own class that overrides getFixedQueryBuilder()

extend the default SonataDatagridBuilder with your own class that overrides getBaseDatagrid()

Reference those in your services


问:
How to resample and round every index into nearest seconds?
My data looks like (the datatype is Pandas DataFrame) :

```<code>price =

time                bid
03:03:34.797000     116.02
03:03:34.797000     116.02
03:03:54.152000     116.02
03:03:54.169000     116.02
03:03:54.169000     116.02
03:07:36.899000     116.24
03:07:48.760000     116.24
03:07:48.760000     116.24
03:07:48.761000     116.24
</code>```

I tried to resample the data into second level data and align every data into the nearest seconds no earlier than the original time. I expect the result to be:

```<code>03:04:00    116.02
03:05:00    NaN
03:06:00    NaN
03:07:00    NaN
03:08:00    116.24
</code>```

and used

```<code>price.resample('Min').last()
</code>```

However I got.

```<code>03:03:34.797000     116.02
03:04:34.797000     NaN
03:05:34.797000     NaN
03:06:34.797000     NaN
03:07:34.797000     116.24
</code>```

Everything goes well except the alignment. Anyone could help me solve the problem? Thanks.

Body:
My data looks like (the datatype is Pandas DataFrame) :

price =

time                bid
03:03:34.797000     116.02
03:03:34.797000     116.02
03:03:54.152000     116.02
03:03:54.169000     116.02
03:03:54.169000     116.02
03:07:36.899000     116.24
03:07:48.760000     116.24
03:07:48.760000     116.24
03:07:48.761000     116.24

I tried to resample the data into second level data and align every data into the nearest seconds no earlier than the original time. I expect the result to be:

03:04:00    116.02
03:05:00    NaN
03:06:00    NaN
03:07:00    NaN
03:08:00    116.24

and used

price.resample('Min').last()

However I got.

03:03:34.797000     116.02
03:04:34.797000     NaN
03:05:34.797000     NaN
03:06:34.797000     NaN
03:07:34.797000     116.24

Everything goes well except the alignment. Anyone could help me solve the problem? Thanks.

Body:
(df.groupby(df['time'].dt.round('1min') )['bid'].mean()).asfreq('Min')
Out[45]:
time
2017-12-06 03:04:00    116.02
2017-12-06 03:05:00       NaN
2017-12-06 03:06:00       NaN
2017-12-06 03:07:00       NaN
2017-12-06 03:08:00    116.24
Freq: T, Name: bid, dtype: float64


问:
remove value from string
If I have a string with IDs

```<code>$myIDs = '22,34,445,67889,23';
</code>```

and I am given a value, how do I remove it from the string, assuming I know for sure it is in the string?

```<code>$removeID = '445';
</code>```

Do I user preg_replace or is there a better method? For example, if it is in the middle of the string and I remove just a value, I'll end up with two commas and then I need to replace those with a single comma?

```<code>preg_replace($removeID, '', $myIDs);
</code>```

UPDATE: These are all great suggestions. However, I just thought about one potential issue. This probably need to be handled as an array instead of regex. What is my string looks like this

```<code>$myIDs = '2312,23,234234';
</code>```

and ID to remove

```<code>$removeID = '23';
</code>```

There's too many potential matches...

答:
The easiest way is this:

```<code>$myIDs = '22,34,445,67889,23';
$removeID = 445;

$myIDs = preg_replace("/($removeID,|,$removeID)/", '', $myIDs);
</code>```

Update:

```<code>$myIDs = preg_replace("/(^$removeID,|,$removeID$|,$removeID(?=,))/", '', $myIDs);
</code>```

Title: remove value from string

Body:
If I have a string with IDs

$myIDs = '22,34,445,67889,23';

and I am given a value, how do I remove it from the string, assuming I know for sure it is in the string?

$removeID = '445';

Do I user preg_replace or is there a better method? For example, if it is in the middle of the string and I remove just a value, I'll end up with two commas and then I need to replace those with a single comma?

preg_replace($removeID, '', $myIDs);

UPDATE: These are all great suggestions. However, I just thought about one potential issue. This probably need to be handled as an array instead of regex. What is my string looks like this

$myIDs = '2312,23,234234';

and ID to remove

$removeID = '23';

There's too many potential matches...

Body:
The easiest way is this:

$myIDs = '22,34,445,67889,23';
$removeID = 445;

$myIDs = preg_replace("/($removeID,|,$removeID)/", '', $myIDs);

Update:

$myIDs = preg_replace("/(^$removeID,|,$removeID$|,$removeID(?=,))/", '', $myIDs);


问:
Create WCF Data Service for use in service host
I have a service application that host several WCF endpoints through different bindings. I want now to host a WCF Data Service in the same service Host. This post makes me believe it's possible. However, every single example on how to create a WCF Data Service creates it from inside an ASP.NET Web project, not a Class Library or Service Application. In fact, the WCF Data Service doesn't even show up in the Add New Item when selected from one of these project types.

My question is how do I create a WCF Data Service inside a Class Library, that will be called by a service host, that's already hosting several other WCF endpoints? The link I already referenced shows me how to host the Data Service after it's created, but since it doesn't show up as an option of the Add New Item, I'm kinna stuck.

答:
After a lot of digging, I found the answer at this post: http://social.msdn.microsoft.com/Forums/en/adodotnetdataservices/thread/3191377e-f3f9-4d46-8daf-431cf74cef7c

I need to use the DataService<T> class, passing my ObjectContext that holds all my Entities. Worked perfectly


问:
Web interface for command line application
I'm developing an application in Ruby. It is used at the command line and has a lot of options, some of them fairly complex. I'd like to provide the ability to use the application through a web interface.

So I'm asking the general question of the best way to do that, or if there might be a better way to do this.

The idea I'm currently working with is that the application would fork itself and use WEBrick to create an http server on some 1024+ port. Then, in the parent process, it would launch the user's web browser using sensible-browser, sending the browser to localhost:port.

The user uses the web application. When they click some particular button (probably "save") then the server would send a final page and shut itself down. That last message would include a message telling the user to close the browser.

The parent process sees that the browser and server processes have closed and proceeds to use the information that was saved to some local file.

All that sounds rather complicated, which is why I'm not crazy about the idea. However, I'm setting out to create a really easy interface, which means not requiring the user to learn a bunch of command line parameters (though I probably will provide those too).

I can't find any gems that provides cursors-based forms, which is why I'm considering the web browser concept.

Opinions?

答:
If I'm understanding everything properly, one thing you might want to consider is breaking out the command line interface and the web-based (or desktop GUI-based) interface. So, for example, if I'm creating a calculator CLI, which you use in the fashion of

```<code>$ myscript -a 2 3
</code>```

where -a is for the "add" function and then you might have -s, -d, and -m (subtract, divide, multiply)...not very friendly having to remember that for the average Joe user. You could create a class such as

```<code>class Calculator
  class<<self
    def perform(operation, left_side, right_side)
      # figure out from operation what I need to do and do it or delegate it
    end
  end
end
</code>```

and then you create a CLI script

```<code>#!/usr/bin/env ruby
require 'calculator'

# parse options, couple ways to do this, you probably already have one in mind
operation_option = ... # check for -a or -s or -d or -m
left_side_option = ...
right_side_option = ...

Calculator.perform(operation_option, left_side_option, right_side_option)
</code>```

and now you can also create a web based (or desktop based) interface for it that also just calls out to the calculator class:

```<code>require 'calculator'

# read from text fields/drop downs/whatever
operation_option = ...
left_side_option = ...
right_side_option = ...

Calculator.perform(operation_option, left_side_option, right_side_option)
</code>```

This way is a tiny little bit of duplication, but not really...either way you would need to parse the text fields from the interface and just instead of writing them to an intermediate file that the CLI then reads from, you just bypass the CLI and go straight to the code you want to execute. So you have 2 (or more) interface files that are just responsible for showing (if applicable) and  reading from their specific interface and passing the data to the "work horse" class in a common format.

In terms of what to make the second interface, Ruby does have support for curses (I have a gem installed by that name) though you'll need to build the forms and interactions on your own (as far as I'm aware, I've never looked for gems to help make forms easier in curses) and a desktop based one is probably better than writing a web based thing, from your description (ruby does have a fair number of GUI gems, but I've never used any except for the curses one), but at this point it's all just "what's right for your project".

Body:
If I'm understanding everything properly, one thing you might want to consider is breaking out the command line interface and the web-based (or desktop GUI-based) interface. So, for example, if I'm creating a calculator CLI, which you use in the fashion of

$ myscript -a 2 3

where -a is for the "add" function and then you might have -s, -d, and -m (subtract, divide, multiply)...not very friendly having to remember that for the average Joe user. You could create a class such as

class Calculator
  class<<self
    def perform(operation, left_side, right_side)
      # figure out from operation what I need to do and do it or delegate it
    end
  end
end

and then you create a CLI script

#!/usr/bin/env ruby
require 'calculator'

# parse options, couple ways to do this, you probably already have one in mind
operation_option = ... # check for -a or -s or -d or -m
left_side_option = ...
right_side_option = ...

Calculator.perform(operation_option, left_side_option, right_side_option)

and now you can also create a web based (or desktop based) interface for it that also just calls out to the calculator class:

require 'calculator'

# read from text fields/drop downs/whatever
operation_option = ...
left_side_option = ...
right_side_option = ...

Calculator.perform(operation_option, left_side_option, right_side_option)

This way is a tiny little bit of duplication, but not really...either way you would need to parse the text fields from the interface and just instead of writing them to an intermediate file that the CLI then reads from, you just bypass the CLI and go straight to the code you want to execute. So you have 2 (or more) interface files that are just responsible for showing (if applicable) and  reading from their specific interface and passing the data to the "work horse" class in a common format.

In terms of what to make the second interface, Ruby does have support for curses (I have a gem installed by that name) though you'll need to build the forms and interactions on your own (as far as I'm aware, I've never looked for gems to help make forms easier in curses) and a desktop based one is probably better than writing a web based thing, from your description (ruby does have a fair number of GUI gems, but I've never used any except for the curses one), but at this point it's all just "what's right for your project".


问:
Check that a variable is a number in UNIX shell
How do I check to see if a variable is a number, or contains a number, in UNIX shell?</p>

答:
```<code>( test ! -z "$num" && test "$num" -eq "$num" 2> /dev/null ) && {
   # $num is a number
}
</code>```

OwnerDisplayName: Gregor

ContentLicense: CC BY-SA 4.0


问:
Focus() on TextBox does not work
I have a Form with a TextBox in it. Every time the text changes i use the TextChanged Event to create a PDF-file and load it to an AxAcroPDF-Object in the same Form. This works fine, but then the TextBox loses focus and for some reason the textBox.Focus() after loading the file doesn't work.

Has anyone ideas how I can arrange that you can go on typing while refreshing the PDF?

EDIT:

i had another idea, i made a separate thread where i update the PDF and in the TextChanged-event i only set a flag. But now im getting a strange error

```<code>Unable to cast COM object of type 'System.__ComObject' to interface type 'AcroPDFLib.IAcroAXDocShim'.
</code>```

答:
I could not get .Focus() and .Select() to work so I used Jquery and it works perfectly.</p>

```<code>$(document).ready(function () {
    setTimeout(function () {
        $(".contentWrapper input")[0].focus();
    }, 100);
});
</code>```

Title: Focus() on TextBox does not work

Body:
I have a Form with a TextBox in it. Every time the text changes i use the TextChanged Event to create a PDF-file and load it to an AxAcroPDF-Object in the same Form. This works fine, but then the TextBox loses focus and for some reason the textBox.Focus() after loading the file doesn't work.

Has anyone ideas how I can arrange that you can go on typing while refreshing the PDF?

EDIT:

i had another idea, i made a separate thread where i update the PDF and in the TextChanged-event i only set a flag. But now im getting a strange error

Unable to cast COM object of type 'System.__ComObject' to interface type 'AcroPDFLib.IAcroAXDocShim'.

Body:
I could not get .Focus() and .Select() to work so I used Jquery and it works perfectly.

$(document).ready(function () {
    setTimeout(function () {
        $(".contentWrapper input")[0].focus();
    }, 100);
});


问:
Type 'void' is not assignable to type 'any[]' when sending data to service
I'm getting  error on this line
    this.apiService.getGifs(searchValue.value).subscribe(data=>this.results=data);

My code works but I'm getting this error so I want to figure out how to fix it. I believe it is becaouse of this part .subscribe(data=>this.results=data); but without it code doesn't work.

apiService

```<code>@Injectable()
export class ApiService {

private results = new BehaviorSubject([]);

public getResults$(){
   return this.results.asObservable();
}

  constructor (private http: Http) {}
  link = 'http://api.giphy.com/v1/gifs/search?q=';
  ApiKey = 'MaklOv0qiTVslRvJlBShgpr46LWPs5Z0';

  public getGifs(searchValue:string) {
     return this.http.get(this.link + searchValue +'&api_key='+ this.ApiKey)
     .map((res:Response) => this.results.next(res.json().data));
  }
}
</code>```

Component which send data to service

```<code>export class SearchComponent implements OnInit {
  results = []

  constructor(private apiService: ApiService) { }

  ngOnInit() {
  }

  onSearch(searchValue) {
   this.apiService.getGifs(searchValue.value).subscribe(data=>this.results=data);
  }
}
</code>```

Component which receives data

```<code>export class OutputComponent implements OnInit {
  results = [];
    constructor(private apiService: ApiService){
    apiService.getResults$().subscribe(data => this.results = data)
}
</code>```

答:
in addition to what @jonrsharpe  said  this should work :</p>

```<code> import 'rxjs/add/operator/do';

 public getGifs(searchValue:string) {
     return this.http.get(this.link + searchValue +'&api_key='+ this.ApiKey)
     .map((res:Response) => res.json().data)
     .do( data => this.results.next(data))
  }
</code>```

Body:
I'm getting  error on this line
    this.apiService.getGifs(searchValue.value).subscribe(data=>this.results=data);

My code works but I'm getting this error so I want to figure out how to fix it. I believe it is becaouse of this part .subscribe(data=>this.results=data); but without it code doesn't work.

apiService

@Injectable()
export class ApiService {

private results = new BehaviorSubject([]);

public getResults$(){
   return this.results.asObservable();
}

  constructor (private http: Http) {}
  link = 'http://api.giphy.com/v1/gifs/search?q=';
  ApiKey = 'MaklOv0qiTVslRvJlBShgpr46LWPs5Z0';

  public getGifs(searchValue:string) {
     return this.http.get(this.link + searchValue +'&api_key='+ this.ApiKey)
     .map((res:Response) => this.results.next(res.json().data));
  }
}

Component which send data to service

export class SearchComponent implements OnInit {
  results = []

  constructor(private apiService: ApiService) { }

  ngOnInit() {
  }

  onSearch(searchValue) {
   this.apiService.getGifs(searchValue.value).subscribe(data=>this.results=data);
  }
}

Component which receives data

export class OutputComponent implements OnInit {
  results = [];
    constructor(private apiService: ApiService){
    apiService.getResults$().subscribe(data => this.results = data)
}

Body:
in addition to what @jonrsharpe  said  this should work :

 import 'rxjs/add/operator/do';

 public getGifs(searchValue:string) {
     return this.http.get(this.link + searchValue +'&api_key='+ this.ApiKey)
     .map((res:Response) => res.json().data)
     .do( data => this.results.next(data))
  }


问:
why use JndiObjectFactoryBean to config JNDI datasource did not work?
when I uss  Java-base to config my JNDI. Spring 4.2.5.

But If I use JndiObjectFactoryBean to config.when I want to get the datasource,the object will be null.

```<code>@Bean
    public DataSource dataSource(){
        JndiObjectFactoryBean jndiObjectFactoryBean =new JndiObjectFactoryBean();
        jndiObjectFactoryBean.setJndiName("jdbc/SpittrDS");
        jndiObjectFactoryBean.setResourceRef(true);
        jndiObjectFactoryBean.setProxyInterface(DataSource.class);
        return (DataSource) jndiObjectFactoryBean.getObject();  //NULL!!!
    }
</code>```

But if change the method to this,it work well.

```<code>@Bean
    public DataSource dataSource(){
        final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
        dsLookup.setResourceRef(true);
        DataSource dataSource = dsLookup.getDataSource("java:comp/env/jdbc/SpittrDS");
        return dataSource;
    }
</code>```

I do not know where is the problem.

Tomcat 9.0  context.xml

```<code><Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <Resource name="jdbc/SpittrDS"
      auth="Container"
      type="javax.sql.DataSource"
      driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://localhost:3306/spittrds"
      username="root"
      password="1"
      maxActive="100"
      maxIdle="20"
      minIdle="5"
      maxWait="10000"/>
</Context>
</code>```

答:
I landed here without realizing this was a problem I had faced in the past - Error Casting Spring's JndiObjectFactoryBean to ConnectionFactory for Solace-MQ JMS

So a workaround (not the preferred way) is to call afterPropertiesSet() on jndiObjectFactoryBean before attempting to getObject()

```<code>@Bean
    public DataSource dataSource(){
        JndiObjectFactoryBean jndiObjectFactoryBean =new JndiObjectFactoryBean();
        jndiObjectFactoryBean.setJndiName("jdbc/SpittrDS");
        jndiObjectFactoryBean.setResourceRef(true);
        jndiObjectFactoryBean.setProxyInterface(DataSource.class);
        jndiObjectFactoryBean.afterPropertiesSet();
        return (DataSource) jndiObjectFactoryBean.getObject();  //NOT NULL
    }
</code>```

Body:
when I uss  Java-base to config my JNDI. Spring 4.2.5.

But If I use JndiObjectFactoryBean to config.when I want to get the datasource,the object will be null.

@Bean
    public DataSource dataSource(){
        JndiObjectFactoryBean jndiObjectFactoryBean =new JndiObjectFactoryBean();
        jndiObjectFactoryBean.setJndiName("jdbc/SpittrDS");
        jndiObjectFactoryBean.setResourceRef(true);
        jndiObjectFactoryBean.setProxyInterface(DataSource.class);
        return (DataSource) jndiObjectFactoryBean.getObject();  //NULL!!!
    }

But if change the method to this,it work well.

@Bean
    public DataSource dataSource(){
        final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
        dsLookup.setResourceRef(true);
        DataSource dataSource = dsLookup.getDataSource("java:comp/env/jdbc/SpittrDS");
        return dataSource;
    }

I do not know where is the problem.

Tomcat 9.0  context.xml

<Context>

    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <Resource name="jdbc/SpittrDS"
      auth="Container"
      type="javax.sql.DataSource"
      driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://localhost:3306/spittrds"
      username="root"
      password="1"
      maxActive="100"
      maxIdle="20"
      minIdle="5"
      maxWait="10000"/>
</Context>

Body:
I landed here without realizing this was a problem I had faced in the past - Error Casting Spring's JndiObjectFactoryBean to ConnectionFactory for Solace-MQ JMS

So a workaround (not the preferred way) is to call afterPropertiesSet() on jndiObjectFactoryBean before attempting to getObject()

@Bean
    public DataSource dataSource(){
        JndiObjectFactoryBean jndiObjectFactoryBean =new JndiObjectFactoryBean();
        jndiObjectFactoryBean.setJndiName("jdbc/SpittrDS");
        jndiObjectFactoryBean.setResourceRef(true);
        jndiObjectFactoryBean.setProxyInterface(DataSource.class);
        jndiObjectFactoryBean.afterPropertiesSet();
        return (DataSource) jndiObjectFactoryBean.getObject();  //NOT NULL
    }


问:
Categorise the list of data under a single value in ArrayList in Android.(See Description)
Here is the for loop which prints all the contents of the array list:

```<code>        for(int i=0;i<arrayList.size();i++){
        Log.e(TAG, "## Price \t\t"+arrayList.get(i).getPrice()+"\t\t\t"+arrayList.get(i).getDate());
    }
</code>```

here is the output of log

12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price         150         Added On:03/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      75          Added On:03/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      450         Added On:03/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      356         Added On:04/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      541         Added On:04/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      415         Added On:04/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      200         Added On:04/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      600         Added On:04/12/2017
12-05 01:07:58.529 25822-25822/finlit.finlit E/ContentValues: ## Price      700         Added On:04/12/2017
12-05 01:07:58.529 25822-25822/finlit.finlit E/ContentValues: ## Price      70          Added On:04/12/2017
12-05 01:07:58.529 25822-25822/finlit.finlit E/ContentValues: ## Price      250         Added On:04/12/2017
12-05 01:07:58.529 25822-25822/finlit.finlit E/ContentValues: ## Price      250         Added On:04/12/2017
12-05 01:07:58.529 25822-25822/finlit.finlit E/ContentValues: ## Price      408         Added On:04/12/2017

What is the possible way to add the sum of prices under a date. E.g A
 hashmap {date , total sum of prices}.
To eloborate: On a given date : 03/12/2017 the total price is: 150+75+450=675.``
Hence categorise the further dates and their corresponding prices.
Hence for the hashmap key: 03/12/2017   value:675.
It would be appreciable if the code is available with date extracted using String functions and regex in java to extract required data.

答:
HashMap. Store Date as key. </p>

```<code>      Map<String, Integer> map = new HashMap();

        for (int i = 0; i < arrayList.size(); i++) {
            if (map.containsKey(arrayList.get(i).getDate())) {
                map.put(arrayList.get(i).getDate(), arrayList.get(i).getPrice() + map.get(arrayList.get(i).getDate()));
            } else {
                map.put(arrayList.get(i).getDate(), arrayList.get(i).getPrice());
            }
        }

        // Iterate over Map
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            Log.e(TAG, "## Price \t\t"+entry.getValue()+"\t\t\t"+entry.getKey());
        }
</code>```

Body:
Here is the for loop which prints all the contents of the array list:

        for(int i=0;i<arrayList.size();i++){
        Log.e(TAG, "## Price \t\t"+arrayList.get(i).getPrice()+"\t\t\t"+arrayList.get(i).getDate());
    }

here is the output of log

12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price         150         Added On:03/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      75          Added On:03/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      450         Added On:03/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      356         Added On:04/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      541         Added On:04/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      415         Added On:04/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      200         Added On:04/12/2017
12-05 01:07:58.528 25822-25822/finlit.finlit E/ContentValues: ## Price      600         Added On:04/12/2017
12-05 01:07:58.529 25822-25822/finlit.finlit E/ContentValues: ## Price      700         Added On:04/12/2017
12-05 01:07:58.529 25822-25822/finlit.finlit E/ContentValues: ## Price      70          Added On:04/12/2017
12-05 01:07:58.529 25822-25822/finlit.finlit E/ContentValues: ## Price      250         Added On:04/12/2017
12-05 01:07:58.529 25822-25822/finlit.finlit E/ContentValues: ## Price      250         Added On:04/12/2017
12-05 01:07:58.529 25822-25822/finlit.finlit E/ContentValues: ## Price      408         Added On:04/12/2017

What is the possible way to add the sum of prices under a date. E.g A
 hashmap {date , total sum of prices}.
To eloborate: On a given date : 03/12/2017 the total price is: 150+75+450=675.``
Hence categorise the further dates and their corresponding prices.
Hence for the hashmap key: 03/12/2017   value:675.
It would be appreciable if the code is available with date extracted using String functions and regex in java to extract required data.

Body:
HashMap. Store Date as key.

      Map<String, Integer> map = new HashMap();

        for (int i = 0; i < arrayList.size(); i++) {
            if (map.containsKey(arrayList.get(i).getDate())) {
                map.put(arrayList.get(i).getDate(), arrayList.get(i).getPrice() + map.get(arrayList.get(i).getDate()));
            } else {
                map.put(arrayList.get(i).getDate(), arrayList.get(i).getPrice());
            }
        }

        // Iterate over Map
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            Log.e(TAG, "## Price \t\t"+entry.getValue()+"\t\t\t"+entry.getKey());
        }


问:
POST to asp.net web api with content type x-www-form-urlencoded raises error 415 unsupported media type
I have developed a web service which will be called by twilio' webHook, but i'm facing an issue that my server expects a Content-type of JSon and Twilio sends a Content-type of x-www-form-urlencoded.

any help would be appreciated.

```<code>[HttpPost]
    public async Task<string>ProcessSms([FromBody] clsTwilio twilio)
    {

        IncomingSms incomingSms = new IncomingSms();
        incomingSms.twilio = twilio;
        return await incomingSms.ProcessSmsAsync();

    }
</code>```

答:
[FromBody] can only be used for simple types. Have you tried removing [FromBody]?

Documentation: Parameter binding in asp.net

Body:
I have developed a web service which will be called by twilio' webHook, but i'm facing an issue that my server expects a Content-type of JSon and Twilio sends a Content-type of x-www-form-urlencoded.

any help would be appreciated.

[HttpPost]
    public async Task<string>ProcessSms([FromBody] clsTwilio twilio)
    {

        IncomingSms incomingSms = new IncomingSms();
        incomingSms.twilio = twilio;
        return await incomingSms.ProcessSmsAsync();

    }


问:
c++ pthread_t: how can I ensure that it has started?
I haven't worked with threads a lot, but wondering how I can ensure that a thread has started (it will run until the system shuts down, I'm just using the default attributes on create).

I've googled this, but there's nothing for threads that won't terminate, have a thread_join waiting for them - I don't need or want to wait for it to terminate.

```<code>pthread_attr_t attr = { 0 };
pthread_t TID = 0;
pthread_attr_init(&attr);
if (!pthread_create(&TID, &attrSys, &threadProcess, NULL))
    std::cout << "Error on thread create." << std::endl;
</code>```

Is that enough to guarantee that the thread has actually started? I've looked at TID.joinable (which my compiler complained about), trying pthread_kill and looking for an error (but that was discounted due to the unreliability of the thread id in some cases).

Thanks so much.

答:
This is the declaration of pthread_create :

```<code>int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);
</code>```

pthread_create returns an <errno.h> code :

On success, pthread_create() returns 0; on error, it returns an error
       number, and the contents of *thread are undefined.

Body:
I haven't worked with threads a lot, but wondering how I can ensure that a thread has started (it will run until the system shuts down, I'm just using the default attributes on create).

I've googled this, but there's nothing for threads that won't terminate, have a thread_join waiting for them - I don't need or want to wait for it to terminate.

pthread_attr_t attr = { 0 };
pthread_t TID = 0;
pthread_attr_init(&attr);
if (!pthread_create(&TID, &attrSys, &threadProcess, NULL))
    std::cout << "Error on thread create." << std::endl;

Is that enough to guarantee that the thread has actually started? I've looked at TID.joinable (which my compiler complained about), trying pthread_kill and looking for an error (but that was discounted due to the unreliability of the thread id in some cases).

Thanks so much.

Body:
This is the declaration of pthread_create :

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

pthread_create returns an <errno.h> code :

On success, pthread_create() returns 0; on error, it returns an error
       number, and the contents of *thread are undefined.