content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Java | Java | propagate the cancel signal to the downstream | 09da10cc6c585995f4623793aa2b2f6a38b5284d | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ChannelSendOperator.java
<ide> private class WriteCompletionBarrier implements CoreSubscriber<Void>, Subscripti
<ide>
<ide> private final WriteBarrier writeBarrier;
<ide>
<add> @Nullable
<add> private Subscription subscription;
<add>
<ide>
<ide> public WriteCompletionBarrier(CoreSubscriber<? super Void> subscriber, WriteBarrier writeBarrier) {
<ide> this.completionSubscriber = subscriber;
<ide> public void connect() {
<ide>
<ide> @Override
<ide> public void onSubscribe(Subscription subscription) {
<add> this.subscription = subscription;
<ide> subscription.request(Long.MAX_VALUE);
<ide> }
<ide>
<ide> public void request(long n) {
<ide> @Override
<ide> public void cancel() {
<ide> this.writeBarrier.cancel();
<add> Subscription subscription = this.subscription;
<add> if (subscription != null) {
<add> subscription.cancel();
<add> }
<ide> }
<ide> }
<ide> | 1 |
Text | Text | fix punctation in readme.md | 7c4e4fd9c2e3a21706a91bc44a0d5c94df390d77 | <ide><path>README.md
<ide> Using unpkg CDN:
<ide>
<ide> ## Example
<ide>
<del>Performing a `GET` request
<add>> **Note** CommonJS usage
<add>> In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()`, use the following approach:
<ide>
<ide> ```js
<ide> import axios from 'axios'; | 1 |
Text | Text | add solution from english | 2ae32d13aa662c620aec3e3dce67142c3415dd8c | <ide><path>curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-media-queries-to-create-responsive-layouts.spanish.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style>
<add> .item1 {
<add> background: LightSkyBlue;
<add> grid-area: header;
<add> }
<add>
<add> .item2 {
<add> background: LightSalmon;
<add> grid-area: advert;
<add> }
<add>
<add> .item3 {
<add> background: PaleTurquoise;
<add> grid-area: content;
<add> }
<add>
<add> .item4 {
<add> background: lightpink;
<add> grid-area: footer;
<add> }
<add>
<add> .container {
<add> font-size: 1.5em;
<add> min-height: 300px;
<add> width: 100%;
<add> background: LightGray;
<add> display: grid;
<add> grid-template-columns: 1fr;
<add> grid-template-rows: 50px auto 1fr auto;
<add> grid-gap: 10px;
<add> grid-template-areas:
<add> "header"
<add> "advert"
<add> "content"
<add> "footer";
<add> }
<add>
<add> @media (min-width: 300px){
<add> .container{
<add> grid-template-columns: auto 1fr;
<add> grid-template-rows: auto 1fr auto;
<add> grid-template-areas:
<add> "advert header"
<add> "advert content"
<add> "advert footer";
<add> }
<add> }
<add>
<add> @media (min-width: 400px){
<add> .container{
<add> /* change the code below this line */
<add>
<add> grid-template-areas:
<add> "header header"
<add> "advert content"
<add> "footer footer";
<add>
<add> /* change the code above this line */
<add> }
<add> }
<add></style>
<add>
<add><div class="container">
<add> <div class="item1">header</div>
<add> <div class="item2">advert</div>
<add> <div class="item3">content</div>
<add> <div class="item4">footer</div>
<add></div>
<ide> ```
<ide> </section> | 1 |
Ruby | Ruby | add undeclared dependencies to tab when installing | 40ca03e975041b4fce9a3097fed5739653c039f3 | <ide><path>Library/Homebrew/formula.rb
<ide> require "tap"
<ide> require "keg"
<ide> require "migrator"
<add>require "os/mac/linkage_checker"
<ide> require "extend/ENV"
<ide> require "language/python"
<ide>
<ide> def declared_runtime_dependencies
<ide> end
<ide>
<ide> def undeclared_runtime_dependencies
<del> return [] unless optlinked?
<add> if optlinked?
<add> keg = Keg.new(opt_prefix)
<add> elsif prefix.directory?
<add> keg = Keg.new(prefix)
<add> else
<add> return []
<add> end
<ide>
<del> keg = Keg.new(opt_prefix)
<ide> linkage_checker = LinkageChecker.new(keg, self)
<ide> dylib_formula_names = linkage_checker.brewed_dylibs.keys
<ide> linked_formulae_names = dylib_formula_names - [name] | 1 |
Python | Python | reintroduce image_shape and filter_shape in conv2d | 6c1ce0f6e9059c93c87d839b7e091d857cbfc0de | <ide><path>examples/mnist_cnn.py
<ide> model = Sequential()
<ide>
<ide> model.add(Convolution2D(nb_filters, nb_conv, nb_conv,
<del> border_mode='same',
<add> border_mode='valid',
<ide> input_shape=(1, img_rows, img_cols)))
<ide> model.add(Activation('relu'))
<ide> model.add(Convolution2D(nb_filters, nb_conv, nb_conv))
<ide><path>keras/backend/tensorflow_backend.py
<ide> def dropout(x, level, seed=None):
<ide> # CONVOLUTIONS
<ide>
<ide>
<del>def conv2d(x, kernel, strides=(1, 1), border_mode='valid', dim_ordering='th'):
<add>def conv2d(x, kernel, strides=(1, 1), border_mode='valid', dim_ordering='th',
<add> image_shape=None, filter_shape=None):
<ide> '''
<ide> Run on cuDNN if available.
<ide> border_mode: string, "same" or "valid".
<ide><path>keras/backend/theano_backend.py
<ide> def dropout(x, level, seed=None):
<ide> # CONVOLUTIONS
<ide>
<ide>
<del>def conv2d(x, kernel, strides=(1, 1), border_mode='valid', dim_ordering='th'):
<add>def conv2d(x, kernel, strides=(1, 1), border_mode='valid', dim_ordering='th',
<add> image_shape=None, filter_shape=None):
<ide> '''
<ide> Run on cuDNN if available.
<ide> border_mode: string, "same" or "valid".
<ide> def conv2d(x, kernel, strides=(1, 1), border_mode='valid', dim_ordering='th'):
<ide> # TF kernel shape: (rows, cols, input_depth, depth)
<ide> x = x.dimshuffle((0, 3, 1, 2))
<ide> kernel = kernel.dimshuffle((3, 2, 0, 1))
<add> if image_shape:
<add> image_shape = (image_shape[0], image_shape[3],
<add> image_shape[1], image_shape[2])
<add> if filter_shape:
<add> filter_shape = (filter_shape[3], filter_shape[2],
<add> filter_shape[0], filter_shape[1])
<ide>
<ide> if _on_gpu() and dnn.dnn_available():
<ide> if border_mode == 'same':
<ide> def conv2d(x, kernel, strides=(1, 1), border_mode='valid', dim_ordering='th'):
<ide>
<ide> conv_out = T.nnet.conv.conv2d(x, kernel,
<ide> border_mode=th_border_mode,
<del> subsample=strides)
<add> subsample=strides,
<add> image_shape=image_shape,
<add> filter_shape=filter_shape)
<ide> if border_mode == 'same':
<ide> shift_x = (kernel.shape[2] - 1) // 2
<ide> shift_y = (kernel.shape[3] - 1) // 2
<ide><path>keras/layers/convolutional.py
<ide> def get_output(self, train=False):
<ide> X = K.expand_dims(X, -1) # add a dimension of the right
<ide> X = K.permute_dimensions(X, (0, 2, 1, 3))
<ide> conv_out = K.conv2d(X, self.W, strides=self.subsample,
<del> border_mode=self.border_mode, dim_ordering='th')
<add> border_mode=self.border_mode,
<add> dim_ordering='th')
<ide>
<ide> output = conv_out + K.reshape(self.b, (1, self.nb_filter, 1, 1))
<ide> output = self.activation(output)
<ide> def get_output(self, train=False):
<ide> X = self.get_input(train)
<ide> conv_out = K.conv2d(X, self.W, strides=self.subsample,
<ide> border_mode=self.border_mode,
<del> dim_ordering=self.dim_ordering)
<add> dim_ordering=self.dim_ordering,
<add> image_shape=self.input_shape,
<add> filter_shape=self.W_shape)
<ide>
<ide> output = conv_out + K.reshape(self.b, (1, self.nb_filter, 1, 1))
<ide> output = self.activation(output) | 4 |
Javascript | Javascript | improve port validation" | bd965aaf366b39c4c99093892df07d3f9f9eca85 | <ide><path>lib/url.js
<ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) {
<ide>
<ide> // validate a little.
<ide> if (!ipv6Hostname) {
<del> rest = getHostname(this, rest, hostname, url);
<add> rest = getHostname(this, rest, hostname);
<ide> }
<ide>
<ide> if (this.hostname.length > hostnameMaxLen) {
<ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) {
<ide> return this;
<ide> };
<ide>
<del>function getHostname(self, rest, hostname, url) {
<add>function getHostname(self, rest, hostname) {
<ide> for (let i = 0; i < hostname.length; ++i) {
<ide> const code = hostname.charCodeAt(i);
<ide> const isValid = (code !== CHAR_FORWARD_SLASH &&
<ide> function getHostname(self, rest, hostname, url) {
<ide> code !== CHAR_COLON);
<ide>
<ide> if (!isValid) {
<del> // If leftover starts with :, then it represents an invalid port.
<del> if (hostname.charCodeAt(i) === 58) {
<del> throw new ERR_INVALID_URL(url);
<del> }
<ide> self.hostname = hostname.slice(0, i);
<ide> return `/${hostname.slice(i)}${rest}`;
<ide> }
<ide><path>test/parallel/test-url-parse-format.js
<ide> const parseTests = {
<ide> href: 'http://a%22%20%3C\'b:b@cd/e?f'
<ide> },
<ide>
<add> // Git urls used by npm
<add> 'git+ssh://git@github.com:npm/npm': {
<add> protocol: 'git+ssh:',
<add> slashes: true,
<add> auth: 'git',
<add> host: 'github.com',
<add> port: null,
<add> hostname: 'github.com',
<add> hash: null,
<add> search: null,
<add> query: null,
<add> pathname: '/:npm/npm',
<add> path: '/:npm/npm',
<add> href: 'git+ssh://git@github.com/:npm/npm'
<add> },
<add>
<ide> 'https://*': {
<ide> protocol: 'https:',
<ide> slashes: true,
<ide><path>test/parallel/test-url-parse-invalid-input.js
<ide> if (common.hasIntl) {
<ide> (e) => e.code === 'ERR_INVALID_URL',
<ide> 'parsing http://\u00AD/bad.com/');
<ide> }
<del>
<del>{
<del> const badURLs = [
<del> 'https://evil.com:.example.com',
<del> 'git+ssh://git@github.com:npm/npm',
<del> ];
<del> badURLs.forEach((badURL) => {
<del> assert.throws(() => { url.parse(badURL); },
<del> (e) => e.code === 'ERR_INVALID_URL',
<del> `parsing ${badURL}`);
<del> });
<del>} | 3 |
Mixed | Ruby | add missing data types for activerecord migrations | 7f2037a990fd81e07f612169f72e8d59fc2a4e52 | <ide><path>activerecord/CHANGELOG.md
<add>* Added methods for PostgreSQL geometric data types to use in migrations
<add>
<add> Example:
<add>
<add> create_table :foo do |t|
<add> t.line :foo_line
<add> t.lseg :foo_lseg
<add> t.box :foo_box
<add> t.path :foo_path
<add> t.polygon :foo_polygon
<add> t.circle :foo_circle
<add> end
<add>
<add> *Mehmet Emin İNAÇ*
<add>
<ide> * Deprecate the PG `:point` type in favor of a new one which will return
<ide> `Point` objects instead of an `Array`
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_definitions.rb
<ide> def point(*args, **options)
<ide> args.each { |name| column(name, :point, options) }
<ide> end
<ide>
<add> def line(*args, **options)
<add> args.each { |name| column(name, :line, options) }
<add> end
<add>
<add> def lseg(*args, **options)
<add> args.each { |name| column(name, :lseg, options) }
<add> end
<add>
<add> def box(*args, **options)
<add> args.each { |name| column(name, :box, options) }
<add> end
<add>
<add> def path(*args, **options)
<add> args.each { |name| column(name, :path, options) }
<add> end
<add>
<add> def polygon(*args, **options)
<add> args.each { |name| column(name, :polygon, options) }
<add> end
<add>
<add> def circle(*args, **options)
<add> args.each { |name| column(name, :circle, options) }
<add> end
<add>
<ide> def serial(*args, **options)
<ide> args.each { |name| column(name, :serial, options) }
<ide> end
<ide><path>activerecord/test/cases/migration/postgresql_geometric_types_test.rb
<add>require 'cases/helper'
<add>
<add>module ActiveRecord
<add> class Migration
<add> class PostgreSQLGeometricTypesTest < ActiveRecord::TestCase
<add> attr_reader :connection, :table_name
<add>
<add> def setup
<add> super
<add> @connection = ActiveRecord::Base.connection
<add> @table_name = :testings
<add> end
<add>
<add> if current_adapter?(:PostgreSQLAdapter)
<add> def test_creating_column_with_point_type
<add> connection.create_table(table_name) do |t|
<add> t.point :foo_point
<add> end
<add>
<add> assert_column_exists(:foo_point)
<add> assert_type_correct(:foo_point, :point)
<add> end
<add>
<add> def test_creating_column_with_line_type
<add> connection.create_table(table_name) do |t|
<add> t.line :foo_line
<add> end
<add>
<add> assert_column_exists(:foo_line)
<add> assert_type_correct(:foo_line, :line)
<add> end
<add>
<add> def test_creating_column_with_lseg_type
<add> connection.create_table(table_name) do |t|
<add> t.lseg :foo_lseg
<add> end
<add>
<add> assert_column_exists(:foo_lseg)
<add> assert_type_correct(:foo_lseg, :lseg)
<add> end
<add>
<add> def test_creating_column_with_box_type
<add> connection.create_table(table_name) do |t|
<add> t.box :foo_box
<add> end
<add>
<add> assert_column_exists(:foo_box)
<add> assert_type_correct(:foo_box, :box)
<add> end
<add>
<add> def test_creating_column_with_path_type
<add> connection.create_table(table_name) do |t|
<add> t.path :foo_path
<add> end
<add>
<add> assert_column_exists(:foo_path)
<add> assert_type_correct(:foo_path, :path)
<add> end
<add>
<add> def test_creating_column_with_polygon_type
<add> connection.create_table(table_name) do |t|
<add> t.polygon :foo_polygon
<add> end
<add>
<add> assert_column_exists(:foo_polygon)
<add> assert_type_correct(:foo_polygon, :polygon)
<add> end
<add>
<add> def test_creating_column_with_circle_type
<add> connection.create_table(table_name) do |t|
<add> t.circle :foo_circle
<add> end
<add>
<add> assert_column_exists(:foo_circle)
<add> assert_type_correct(:foo_circle, :circle)
<add> end
<add> end
<add>
<add> private
<add> def assert_column_exists(column_name)
<add> columns = connection.columns(table_name)
<add> assert columns.map(&:name).include?(column_name.to_s)
<add> end
<add>
<add> def assert_type_correct(column_name, type)
<add> columns = connection.columns(table_name)
<add> column = columns.select{ |c| c.name == column_name.to_s }.first
<add> assert_equal type.to_s, column.sql_type
<add> end
<add>
<add> end
<add> end
<add>end
<ide>\ No newline at end of file | 3 |
Python | Python | remove blank line | a9a06e8ab27782aec39087c3385bd62d6eae0422 | <ide><path>libcloud/test/dns/test_linode.py
<ide> def test_list_records_success(self):
<ide> self.assertHasKeys(srvrecord.extra, ['protocol', 'ttl_sec', 'port',
<ide> 'priority', 'weight'])
<ide>
<del>
<ide> def test_list_records_zone_does_not_exist(self):
<ide> zone = self.driver.list_zones()[0]
<ide> | 1 |
Javascript | Javascript | add some comments + fix getcolorn_ir_pattern | 5bfa9e4f3b9f34369def38d0aa9aa5140f654f97 | <ide><path>pdf.js
<ide> var PartialEvaluator = (function() {
<ide> var dict = IsStream(pattern) ? pattern.dict : pattern;
<ide> var typeNum = dict.get('PatternType');
<ide>
<del> // Type1 is TilingPattern, Type2 is ShadingPattern.
<add> // Type1 is TilingPattern
<ide> if (typeNum == 1) {
<ide> // Create an IR of the pattern code.
<ide> var codeIR = this.evalRaw(pattern, xref,
<ide> dict.get('Resources'), fonts);
<ide>
<ide> args = TilingPattern.getIR(codeIR, dict);
<del>
<del> //patternName.code = this.evalRaw(pattern, xref,
<del> // dict.get('Resources'), fonts);
<del> } else {
<add> }
<add> // Type2 is ShadingPattern.
<add> else if (typeNum == 2) {
<ide> var shading = xref.fetchIfRef(dict.get('Shading'));
<ide> var matrix = dict.get('Matrix');
<ide> var pattern = Pattern.parseShading(shading, matrix, xref, res, null /*ctx*/);
<ide> args = pattern.getPatternRaw();
<add> } else {
<add> error("Unkown PatternType " + typeNum);
<ide> }
<ide> }
<ide> }
<ide> var CanvasGraphics = (function() {
<ide> this.setStrokeColor.apply(this, arguments);
<ide> }
<ide> },
<del> getColorN_IR_Pattern: function(IR) {
<add> getColorN_IR_Pattern: function(IR, cs) {
<ide> if (IR[0] == "TilingPatternIR") {
<ide> // First, build the `color` var like it's done in the
<ide> // Pattern.prototype.parse function.
<ide> var CanvasGraphics = (function() {
<ide> var cs = this.current.strokeColorSpace;
<ide>
<ide> if (cs.name == 'Pattern') {
<del> this.current.strokeColor = this.getColorN_IR_Pattern(arguments);
<add> this.current.strokeColor = this.getColorN_IR_Pattern(arguments, cs);
<ide> } else {
<ide> this.setStrokeColor.apply(this, arguments);
<ide> }
<ide> var CanvasGraphics = (function() {
<ide> var cs = this.current.fillColorSpace;
<ide>
<ide> if (cs.name == 'Pattern') {
<del> this.current.fillColor = this.getColorN_IR_Pattern(arguments);
<add> this.current.fillColor = this.getColorN_IR_Pattern(arguments, cs);
<ide> } else {
<ide> this.setFillColor.apply(this, arguments);
<ide> } | 1 |
Javascript | Javascript | update polar animation tests to less error prone | ce0f7ff903e42ea39677429644fb4f6cb38b4dda | <ide><path>test/fixtures/controller.polarArea/polar-area-animation-rotate.js
<ide> module.exports = {
<ide> animation: {
<ide> animateRotate: true,
<ide> animateScale: false,
<del> duration: 800,
<add> duration: 8000,
<ide> easing: 'linear'
<ide> },
<ide> responsive: false,
<ide> module.exports = {
<ide> },
<ide> run: function(chart) {
<ide> const animator = Chart.animator;
<del> const start = animator._getAnims(chart).items[0]._start;
<del> animator._running = false;
<del> return new Promise((resolve) => setTimeout(() => {
<del> for (let i = 0; i < 16; i++) {
<del> animator._update(start + i * 50);
<del> let x = i % 4 * 128;
<del> let y = Math.floor(i / 4) * 128;
<del> ctx.drawImage(chart.canvas, x, y, 128, 128);
<del> }
<del> Chart.helpers.clearCanvas(chart.canvas);
<del> chart.ctx.drawImage(canvas, 0, 0);
<del> resolve();
<del> }, 100));
<add> const anims = animator._getAnims(chart);
<add> // disable animator
<add> const backup = animator._refresh;
<add> animator._refresh = function() { };
<add>
<add> return new Promise((resolve) => {
<add> window.requestAnimationFrame(() => {
<add>
<add> const start = anims.items[0]._start;
<add> for (let i = 0; i < 16; i++) {
<add> animator._update(start + i * 500);
<add> let x = i % 4 * 128;
<add> let y = Math.floor(i / 4) * 128;
<add> ctx.drawImage(chart.canvas, x, y, 128, 128);
<add> }
<add>
<add> Chart.helpers.clearCanvas(chart.canvas);
<add> chart.ctx.drawImage(canvas, 0, 0);
<add>
<add> animator._refresh = backup;
<add> resolve();
<add> });
<add> });
<ide> }
<ide> }
<ide> };
<ide><path>test/fixtures/controller.polarArea/polar-area-animation-scale.js
<ide> module.exports = {
<ide> animation: {
<ide> animateRotate: false,
<ide> animateScale: true,
<del> duration: 800,
<add> duration: 8000,
<ide> easing: 'linear'
<ide> },
<ide> responsive: false,
<ide> module.exports = {
<ide> },
<ide> run: function(chart) {
<ide> const animator = Chart.animator;
<del> const start = animator._getAnims(chart).items[0]._start;
<del> animator._running = false;
<del> return new Promise((resolve) => setTimeout(() => {
<del> for (let i = 0; i < 16; i++) {
<del> animator._update(start + i * 50);
<del> let x = i % 4 * 128;
<del> let y = Math.floor(i / 4) * 128;
<del> ctx.drawImage(chart.canvas, x, y, 128, 128);
<del> }
<del> Chart.helpers.clearCanvas(chart.canvas);
<del> chart.ctx.drawImage(canvas, 0, 0);
<del> resolve();
<del> }, 100));
<add> const anims = animator._getAnims(chart);
<add> // disable animator
<add> const backup = animator._refresh;
<add> animator._refresh = function() { };
<add>
<add> return new Promise((resolve) => {
<add> window.requestAnimationFrame(() => {
<add>
<add> const start = anims.items[0]._start;
<add> for (let i = 0; i < 16; i++) {
<add> animator._update(start + i * 500);
<add> let x = i % 4 * 128;
<add> let y = Math.floor(i / 4) * 128;
<add> ctx.drawImage(chart.canvas, x, y, 128, 128);
<add> }
<add> Chart.helpers.clearCanvas(chart.canvas);
<add> chart.ctx.drawImage(canvas, 0, 0);
<add>
<add> animator._refresh = backup;
<add> resolve();
<add> });
<add> });
<ide> }
<ide> }
<ide> }; | 2 |
Text | Text | fix aborterror example for timers | 31d83f5542ce8742fb3a85a414ad0637c8588d53 | <ide><path>doc/api/timers.md
<ide> const signal = ac.signal;
<ide> setImmediatePromise('foobar', { signal })
<ide> .then(console.log)
<ide> .catch((err) => {
<del> if (err.message === 'AbortError')
<add> if (err.name === 'AbortError')
<ide> console.log('The immediate was aborted');
<ide> });
<ide>
<ide> const signal = ac.signal;
<ide> setTimeoutPromise(1000, 'foobar', { signal })
<ide> .then(console.log)
<ide> .catch((err) => {
<del> if (err.message === 'AbortError')
<add> if (err.name === 'AbortError')
<ide> console.log('The timeout was aborted');
<ide> });
<ide> | 1 |
Go | Go | remove unused filenotify | ee99b5f2e96aafa982487aadbb78478898ae0c71 | <ide><path>pkg/filenotify/filenotify.go
<del>// Package filenotify provides a mechanism for watching file(s) for changes.
<del>// Generally leans on fsnotify, but provides a poll-based notifier which fsnotify does not support.
<del>// These are wrapped up in a common interface so that either can be used interchangeably in your code.
<del>package filenotify
<del>
<del>import "gopkg.in/fsnotify.v1"
<del>
<del>// FileWatcher is an interface for implementing file notification watchers
<del>type FileWatcher interface {
<del> Events() <-chan fsnotify.Event
<del> Errors() <-chan error
<del> Add(name string) error
<del> Remove(name string) error
<del> Close() error
<del>}
<del>
<del>// New tries to use an fs-event watcher, and falls back to the poller if there is an error
<del>func New() (FileWatcher, error) {
<del> if watcher, err := NewEventWatcher(); err == nil {
<del> return watcher, nil
<del> }
<del> return NewPollingWatcher(), nil
<del>}
<del>
<del>// NewPollingWatcher returns a poll-based file watcher
<del>func NewPollingWatcher() FileWatcher {
<del> return &filePoller{
<del> events: make(chan fsnotify.Event),
<del> errors: make(chan error),
<del> }
<del>}
<del>
<del>// NewEventWatcher returns an fs-event based file watcher
<del>func NewEventWatcher() (FileWatcher, error) {
<del> watcher, err := fsnotify.NewWatcher()
<del> if err != nil {
<del> return nil, err
<del> }
<del> return &fsNotifyWatcher{watcher}, nil
<del>}
<ide><path>pkg/filenotify/fsnotify.go
<del>package filenotify
<del>
<del>import "gopkg.in/fsnotify.v1"
<del>
<del>// fsNotify wraps the fsnotify package to satisfy the FileNotifer interface
<del>type fsNotifyWatcher struct {
<del> *fsnotify.Watcher
<del>}
<del>
<del>// GetEvents returns the fsnotify event channel receiver
<del>func (w *fsNotifyWatcher) Events() <-chan fsnotify.Event {
<del> return w.Watcher.Events
<del>}
<del>
<del>// GetErrors returns the fsnotify error channel receiver
<del>func (w *fsNotifyWatcher) Errors() <-chan error {
<del> return w.Watcher.Errors
<del>}
<ide><path>pkg/filenotify/poller.go
<del>package filenotify
<del>
<del>import (
<del> "errors"
<del> "fmt"
<del> "os"
<del> "sync"
<del> "time"
<del>
<del> "github.com/Sirupsen/logrus"
<del>
<del> "gopkg.in/fsnotify.v1"
<del>)
<del>
<del>var (
<del> // errPollerClosed is returned when the poller is closed
<del> errPollerClosed = errors.New("poller is closed")
<del> // errNoSuchPoller is returned when trying to remove a watch that doesn't exist
<del> errNoSuchWatch = errors.New("poller does not exist")
<del>)
<del>
<del>// watchWaitTime is the time to wait between file poll loops
<del>const watchWaitTime = 200 * time.Millisecond
<del>
<del>// filePoller is used to poll files for changes, especially in cases where fsnotify
<del>// can't be run (e.g. when inotify handles are exhausted)
<del>// filePoller satisfies the FileWatcher interface
<del>type filePoller struct {
<del> // watches is the list of files currently being polled, close the associated channel to stop the watch
<del> watches map[string]chan struct{}
<del> // events is the channel to listen to for watch events
<del> events chan fsnotify.Event
<del> // errors is the channel to listen to for watch errors
<del> errors chan error
<del> // mu locks the poller for modification
<del> mu sync.Mutex
<del> // closed is used to specify when the poller has already closed
<del> closed bool
<del>}
<del>
<del>// Add adds a filename to the list of watches
<del>// once added the file is polled for changes in a separate goroutine
<del>func (w *filePoller) Add(name string) error {
<del> w.mu.Lock()
<del> defer w.mu.Unlock()
<del>
<del> if w.closed == true {
<del> return errPollerClosed
<del> }
<del>
<del> f, err := os.Open(name)
<del> if err != nil {
<del> return err
<del> }
<del> fi, err := os.Stat(name)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> if w.watches == nil {
<del> w.watches = make(map[string]chan struct{})
<del> }
<del> if _, exists := w.watches[name]; exists {
<del> return fmt.Errorf("watch exists")
<del> }
<del> chClose := make(chan struct{})
<del> w.watches[name] = chClose
<del>
<del> go w.watch(f, fi, chClose)
<del> return nil
<del>}
<del>
<del>// Remove stops and removes watch with the specified name
<del>func (w *filePoller) Remove(name string) error {
<del> w.mu.Lock()
<del> defer w.mu.Unlock()
<del> return w.remove(name)
<del>}
<del>
<del>func (w *filePoller) remove(name string) error {
<del> if w.closed == true {
<del> return errPollerClosed
<del> }
<del>
<del> chClose, exists := w.watches[name]
<del> if !exists {
<del> return errNoSuchWatch
<del> }
<del> close(chClose)
<del> delete(w.watches, name)
<del> return nil
<del>}
<del>
<del>// Events returns the event channel
<del>// This is used for notifications on events about watched files
<del>func (w *filePoller) Events() <-chan fsnotify.Event {
<del> return w.events
<del>}
<del>
<del>// Errors returns the errors channel
<del>// This is used for notifications about errors on watched files
<del>func (w *filePoller) Errors() <-chan error {
<del> return w.errors
<del>}
<del>
<del>// Close closes the poller
<del>// All watches are stopped, removed, and the poller cannot be added to
<del>func (w *filePoller) Close() error {
<del> w.mu.Lock()
<del> defer w.mu.Unlock()
<del>
<del> if w.closed {
<del> return nil
<del> }
<del>
<del> w.closed = true
<del> for name := range w.watches {
<del> w.remove(name)
<del> delete(w.watches, name)
<del> }
<del> close(w.events)
<del> close(w.errors)
<del> return nil
<del>}
<del>
<del>// sendEvent publishes the specified event to the events channel
<del>func (w *filePoller) sendEvent(e fsnotify.Event, chClose <-chan struct{}) error {
<del> select {
<del> case w.events <- e:
<del> case <-chClose:
<del> return fmt.Errorf("closed")
<del> }
<del> return nil
<del>}
<del>
<del>// sendErr publishes the specified error to the errors channel
<del>func (w *filePoller) sendErr(e error, chClose <-chan struct{}) error {
<del> select {
<del> case w.errors <- e:
<del> case <-chClose:
<del> return fmt.Errorf("closed")
<del> }
<del> return nil
<del>}
<del>
<del>// watch is responsible for polling the specified file for changes
<del>// upon finding changes to a file or errors, sendEvent/sendErr is called
<del>func (w *filePoller) watch(f *os.File, lastFi os.FileInfo, chClose chan struct{}) {
<del> for {
<del> time.Sleep(watchWaitTime)
<del> select {
<del> case <-chClose:
<del> logrus.Debugf("watch for %s closed", f.Name())
<del> return
<del> default:
<del> }
<del>
<del> fi, err := os.Stat(f.Name())
<del> if err != nil {
<del> // if we got an error here and lastFi is not set, we can presume that nothing has changed
<del> // This should be safe since before `watch()` is called, a stat is performed, there is any error `watch` is not called
<del> if lastFi == nil {
<del> continue
<del> }
<del> // If it doesn't exist at this point, it must have been removed
<del> // no need to send the error here since this is a valid operation
<del> if os.IsNotExist(err) {
<del> if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Remove, Name: f.Name()}, chClose); err != nil {
<del> return
<del> }
<del> lastFi = nil
<del> continue
<del> }
<del> // at this point, send the error
<del> if err := w.sendErr(err, chClose); err != nil {
<del> return
<del> }
<del> continue
<del> }
<del>
<del> if lastFi == nil {
<del> if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Create, Name: fi.Name()}, chClose); err != nil {
<del> return
<del> }
<del> lastFi = fi
<del> continue
<del> }
<del>
<del> if fi.Mode() != lastFi.Mode() {
<del> if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Chmod, Name: fi.Name()}, chClose); err != nil {
<del> return
<del> }
<del> lastFi = fi
<del> continue
<del> }
<del>
<del> if fi.ModTime() != lastFi.ModTime() || fi.Size() != lastFi.Size() {
<del> if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Write, Name: fi.Name()}, chClose); err != nil {
<del> return
<del> }
<del> lastFi = fi
<del> continue
<del> }
<del> }
<del>}
<ide><path>pkg/filenotify/poller_test.go
<del>package filenotify
<del>
<del>import (
<del> "fmt"
<del> "io/ioutil"
<del> "os"
<del> "runtime"
<del> "testing"
<del> "time"
<del>
<del> "gopkg.in/fsnotify.v1"
<del>)
<del>
<del>func TestPollerAddRemove(t *testing.T) {
<del> w := NewPollingWatcher()
<del>
<del> if err := w.Add("no-such-file"); err == nil {
<del> t.Fatal("should have gotten error when adding a non-existent file")
<del> }
<del> if err := w.Remove("no-such-file"); err == nil {
<del> t.Fatal("should have gotten error when removing non-existent watch")
<del> }
<del>
<del> f, err := ioutil.TempFile("", "asdf")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(f.Name())
<del>
<del> if err := w.Add(f.Name()); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if err := w.Remove(f.Name()); err != nil {
<del> t.Fatal(err)
<del> }
<del>}
<del>
<del>func TestPollerEvent(t *testing.T) {
<del> if runtime.GOOS == "windows" {
<del> t.Skip("No chmod on Windows")
<del> }
<del> w := NewPollingWatcher()
<del>
<del> f, err := ioutil.TempFile("", "test-poller")
<del> if err != nil {
<del> t.Fatal("error creating temp file")
<del> }
<del> defer os.RemoveAll(f.Name())
<del> f.Close()
<del>
<del> if err := w.Add(f.Name()); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> select {
<del> case <-w.Events():
<del> t.Fatal("got event before anything happened")
<del> case <-w.Errors():
<del> t.Fatal("got error before anything happened")
<del> default:
<del> }
<del>
<del> if err := ioutil.WriteFile(f.Name(), []byte("hello"), 644); err != nil {
<del> t.Fatal(err)
<del> }
<del> if err := assertEvent(w, fsnotify.Write); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if err := os.Chmod(f.Name(), 600); err != nil {
<del> t.Fatal(err)
<del> }
<del> if err := assertEvent(w, fsnotify.Chmod); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if err := os.Remove(f.Name()); err != nil {
<del> t.Fatal(err)
<del> }
<del> if err := assertEvent(w, fsnotify.Remove); err != nil {
<del> t.Fatal(err)
<del> }
<del>}
<del>
<del>func TestPollerClose(t *testing.T) {
<del> w := NewPollingWatcher()
<del> if err := w.Close(); err != nil {
<del> t.Fatal(err)
<del> }
<del> // test double-close
<del> if err := w.Close(); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> select {
<del> case _, open := <-w.Events():
<del> if open {
<del> t.Fatal("event chan should be closed")
<del> }
<del> default:
<del> t.Fatal("event chan should be closed")
<del> }
<del>
<del> select {
<del> case _, open := <-w.Errors():
<del> if open {
<del> t.Fatal("errors chan should be closed")
<del> }
<del> default:
<del> t.Fatal("errors chan should be closed")
<del> }
<del>
<del> f, err := ioutil.TempFile("", "asdf")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(f.Name())
<del> if err := w.Add(f.Name()); err == nil {
<del> t.Fatal("should have gotten error adding watch for closed watcher")
<del> }
<del>}
<del>
<del>func assertEvent(w FileWatcher, eType fsnotify.Op) error {
<del> var err error
<del> select {
<del> case e := <-w.Events():
<del> if e.Op != eType {
<del> err = fmt.Errorf("got wrong event type, expected %q: %v", eType, e)
<del> }
<del> case e := <-w.Errors():
<del> err = fmt.Errorf("got unexpected error waiting for events %v: %v", eType, e)
<del> case <-time.After(watchWaitTime * 3):
<del> err = fmt.Errorf("timeout waiting for event %v", eType)
<del> }
<del> return err
<del>} | 4 |
Ruby | Ruby | repair the message | 89868087fd8540118475b5f3bddf159c687317ec | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def update_report
<ide> puts_stdout_or_stderr
<ide> puts_stdout_or_stderr <<~EOS
<ide> You have #{msg} installed.
<del> You can check #{update_pronoun} with #{Tty.bold}brew outdated#{Tty.reset}.
<del> You can update #{update_pronoun} with #{Tty.bold}brew upgrade#{Tty.reset}.
<add> You can upgrade #{update_pronoun} with #{Tty.bold}brew upgrade#{Tty.reset}
<add> or check #{update_pronoun} with #{Tty.bold}brew outdated#{Tty.reset}.
<ide> EOS
<ide> end
<ide> end | 1 |
Go | Go | forbid certain paths within docker build add | 3104fc8d33ce4c26a446826639a7b2dba524264f | <ide><path>buildfile.go
<ide> func (b *buildFile) addContext(container *Container, orig, dest string) error {
<ide> if strings.HasSuffix(dest, "/") {
<ide> destPath = destPath + "/"
<ide> }
<add> if !strings.HasPrefix(origPath, b.context) {
<add> return fmt.Errorf("Forbidden path: %s", origPath)
<add> }
<ide> fi, err := os.Stat(origPath)
<ide> if err != nil {
<ide> return err
<ide><path>buildfile_test.go
<ide> func TestBuildImageWithoutCache(t *testing.T) {
<ide> t.Fail()
<ide> }
<ide> }
<add>
<add>func TestForbiddenContextPath(t *testing.T) {
<add> runtime, err := newTestRuntime()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer nuke(runtime)
<add>
<add> srv := &Server{
<add> runtime: runtime,
<add> pullingPool: make(map[string]struct{}),
<add> pushingPool: make(map[string]struct{}),
<add> }
<add>
<add> context := testContextTemplate{`
<add> from {IMAGE}
<add> maintainer dockerio
<add> add ../../ test/
<add> `,
<add> [][2]string{{"test.txt", "test1"}, {"other.txt", "other"}}, nil}
<add>
<add> httpServer, err := mkTestingFileServer(context.remoteFiles)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer httpServer.Close()
<add>
<add> idx := strings.LastIndex(httpServer.URL, ":")
<add> if idx < 0 {
<add> t.Fatalf("could not get port from test http server address %s", httpServer.URL)
<add> }
<add> port := httpServer.URL[idx+1:]
<add>
<add> ip := srv.runtime.networkManager.bridgeNetwork.IP
<add> dockerfile := constructDockerfile(context.dockerfile, ip, port)
<add>
<add> buildfile := NewBuildFile(srv, ioutil.Discard, false, true)
<add> _, err = buildfile.Build(mkTestContext(dockerfile, context.files, t))
<add>
<add> if err == nil {
<add> t.Log("Error should not be nil")
<add> t.Fail()
<add> }
<add>
<add> if err.Error() != "Forbidden path: /" {
<add> t.Logf("Error message is not expected: %s", err.Error())
<add> t.Fail()
<add> }
<add>} | 2 |
Ruby | Ruby | remove unused private method in fixtures.rb | caeca1f69b3a6f25248390daa37561cf2cbd8cd6 | <ide><path>activerecord/lib/active_record/fixtures.rb
<ide> def yaml_file_path
<ide> "#{@fixture_path}.yml"
<ide> end
<ide>
<del> def yaml_fixtures_key(path)
<del> ::File.basename(@fixture_path).split(".").first
<del> end
<ide> end
<ide>
<ide> class Fixture #:nodoc: | 1 |
Python | Python | log best epoch | b9df30b4ef2137ca6c10bddfe32661f21c67fbf8 | <ide><path>keras/callbacks.py
<ide> def on_train_begin(self, logs=None):
<ide> self.stopped_epoch = 0
<ide> self.best = np.Inf if self.monitor_op == np.less else -np.Inf
<ide> self.best_weights = None
<add> self.best_epoch = 0
<ide>
<ide> def on_epoch_end(self, epoch, logs=None):
<ide> current = self.get_monitor_value(logs)
<ide> def on_epoch_end(self, epoch, logs=None):
<ide> self.wait += 1
<ide> if self._is_improvement(current, self.best):
<ide> self.best = current
<add> self.best_epoch = epoch
<ide> if self.restore_best_weights:
<ide> self.best_weights = self.model.get_weights()
<ide> # Only restart wait if we beat both the baseline and our previous best.
<ide> def on_epoch_end(self, epoch, logs=None):
<ide> self.model.stop_training = True
<ide> if self.restore_best_weights and self.best_weights is not None:
<ide> if self.verbose > 0:
<del> print('Restoring model weights from the end of the best epoch.')
<add> print('Restoring model weights from the end of the best epoch (%s).'
<add> % (self.best_epoch + 1))
<ide> self.model.set_weights(self.best_weights)
<ide>
<ide> def on_train_end(self, logs=None): | 1 |
Ruby | Ruby | prefer tap to returning | 173ee14c3d95238cfb828400862a24a14aec600f | <ide><path>actionmailer/lib/action_mailer/helpers.rb
<ide> def inherited_with_helper(child)
<ide> private
<ide> # Extend the template class instance with our controller's helper module.
<ide> def initialize_template_class_with_helper(assigns)
<del> returning(template = initialize_template_class_without_helper(assigns)) do
<add> initialize_template_class_without_helper(assigns).tap do |template|
<ide> template.extend self.class.master_helper_module
<ide> end
<ide> end | 1 |
Go | Go | add test to check for plugin mounts on remove | 5017b5bef55c31db4c04c8058ef7db8597b11341 | <ide><path>plugin/manager_linux_test.go
<add>package plugin
<add>
<add>import (
<add> "io/ioutil"
<add> "os"
<add> "path/filepath"
<add> "testing"
<add>
<add> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/pkg/mount"
<add> "github.com/docker/docker/pkg/system"
<add> "github.com/docker/docker/plugin/v2"
<add>)
<add>
<add>func TestManagerWithPluginMounts(t *testing.T) {
<add> root, err := ioutil.TempDir("", "test-store-with-plugin-mounts")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer system.EnsureRemoveAll(root)
<add>
<add> s := NewStore()
<add> managerRoot := filepath.Join(root, "manager")
<add> p1 := newTestPlugin(t, "test1", "testcap", managerRoot)
<add>
<add> p2 := newTestPlugin(t, "test2", "testcap", managerRoot)
<add> p2.PluginObj.Enabled = true
<add>
<add> m, err := NewManager(
<add> ManagerConfig{
<add> Store: s,
<add> Root: managerRoot,
<add> ExecRoot: filepath.Join(root, "exec"),
<add> CreateExecutor: func(*Manager) (Executor, error) { return nil, nil },
<add> LogPluginEvent: func(_, _, _ string) {},
<add> })
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := s.Add(p1); err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := s.Add(p2); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // Create a mount to simulate a plugin that has created it's own mounts
<add> p2Mount := filepath.Join(p2.Rootfs, "testmount")
<add> if err := os.MkdirAll(p2Mount, 0755); err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := mount.Mount("tmpfs", p2Mount, "tmpfs", ""); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := m.Remove(p1.Name(), &types.PluginRmConfig{ForceRemove: true}); err != nil {
<add> t.Fatal(err)
<add> }
<add> if mounted, err := mount.Mounted(p2Mount); !mounted || err != nil {
<add> t.Fatalf("expected %s to be mounted, err: %v", p2Mount, err)
<add> }
<add>}
<add>
<add>func newTestPlugin(t *testing.T, name, cap, root string) *v2.Plugin {
<add> rootfs := filepath.Join(root, name)
<add> if err := os.MkdirAll(rootfs, 0755); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> p := v2.Plugin{PluginObj: types.Plugin{Name: name}}
<add> p.Rootfs = rootfs
<add> iType := types.PluginInterfaceType{Capability: cap, Prefix: "docker", Version: "1.0"}
<add> i := types.PluginConfigInterface{Socket: "plugins.sock", Types: []types.PluginInterfaceType{iType}}
<add> p.PluginObj.Config.Interface = i
<add> p.PluginObj.ID = name
<add>
<add> return &p
<add>} | 1 |
Python | Python | fix airflow.www.views import | d02932d0139215c790b12809e98df9a8ae1da41e | <ide><path>airflow/www/app.py
<ide> def init_plugin_blueprints(app):
<ide> log.debug("Adding blueprint %s:%s", bp["name"], bp["blueprint"].import_name)
<ide> app.register_blueprint(bp["blueprint"])
<ide>
<add> def init_error_handlers(app: Flask):
<add> from airflow.www import views
<add> app.register_error_handler(500, views.show_traceback)
<add> app.register_error_handler(404, views.circles)
<add>
<ide> init_views(appbuilder)
<ide> init_plugin_blueprints(app)
<add> init_error_handlers(app)
<ide>
<ide> if conf.getboolean('webserver', 'UPDATE_FAB_PERMS'):
<ide> security_manager = appbuilder.sm
<ide><path>airflow/www/views.py
<ide> from airflow.utils.session import create_session, provide_session
<ide> from airflow.utils.state import State
<ide> from airflow.www import utils as wwwutils
<del>from airflow.www.app import app, appbuilder
<add>from airflow.www.app import appbuilder
<ide> from airflow.www.decorators import action_logging, gzipped, has_dag_access
<ide> from airflow.www.forms import (
<ide> ConnectionForm, DagRunForm, DateTimeForm, DateTimeWithNumRunsForm, DateTimeWithNumRunsWithDagRunsForm,
<ide> def get_date_time_num_runs_dag_runs_form_data(request, session, dag):
<ide>
<ide>
<ide> ######################################################################################
<del># BaseViews
<add># Error handlers
<ide> ######################################################################################
<del>@app.errorhandler(404)
<add>
<ide> def circles(error):
<ide> return render_template(
<ide> 'airflow/circles.html', hostname=socket.getfqdn() if conf.getboolean(
<ide> def circles(error):
<ide> fallback=True) else 'redact'), 404
<ide>
<ide>
<del>@app.errorhandler(500)
<ide> def show_traceback(error):
<ide> from airflow.utils import asciiart as ascii_
<ide> return render_template(
<ide> def show_traceback(error):
<ide> 'EXPOSE_STACKTRACE',
<ide> fallback=True) else 'Error! Please contact server admin'), 500
<ide>
<add>######################################################################################
<add># BaseViews
<add>######################################################################################
<add>
<ide>
<ide> class AirflowBaseView(BaseView):
<ide> from airflow import macros | 2 |
Javascript | Javascript | get the package name back in the qunit header | 2c2136d26e09ba5069d3d1f3354b27142a174e19 | <ide><path>packages/qunit/lib/qunit-runner.js
<ide> if (!packageName) {
<ide> QUnit.config.autostart = false;
<ide> QUnit.config.autorun = false;
<ide>
<del> $('h1 > a').text(packageName);
<add> jQuery(function() {
<add> $('h1 > a').text(packageName);
<add> });
<ide>
<ide> QUnit.jsDump.setParser('object', function(obj) {
<ide> return obj.toString(); | 1 |
Python | Python | fix typos in ``example_branch_datetime_operator`` | 4ed455674efde607180b9ebf05cd505348bcb8bd | <ide><path>airflow/example_dags/example_branch_datetime_operator.py
<ide> dag=dag1,
<ide> )
<ide>
<del># Run empty_task_1 if cond1 executes between 2020-10-10 14:00:00 and 2020-10-10 15:00:00
<add># Run empty_task_11 if cond1 executes between 2020-10-10 14:00:00 and 2020-10-10 15:00:00
<ide> cond1 >> [empty_task_11, empty_task_21]
<ide> # [END howto_branch_datetime_operator]
<ide>
<ide> )
<ide>
<ide> # Since target_lower happens after target_upper, target_upper will be moved to the following day
<del># Run empty_task_1 if cond2 executes between 15:00:00, and 00:00:00 of the following day
<add># Run empty_task_12 if cond2 executes between 15:00:00, and 00:00:00 of the following day
<ide> cond2 >> [empty_task_12, empty_task_22]
<ide> # [END howto_branch_datetime_operator_next_day]
<ide>
<ide> dag=dag3,
<ide> )
<ide>
<del># Run empty_task_3 if cond1 executes between 2020-10-10 14:00:00 and 2020-10-10 15:00:00
<add># Run empty_task_13 if cond3 executes between 2020-10-10 14:00:00 and 2020-10-10 15:00:00
<ide> cond3 >> [empty_task_13, empty_task_23]
<ide> # [END howto_branch_datetime_operator_logical_date] | 1 |
Python | Python | add types of tok2vec embedding layers | 512197293020cc5252e3af67a5a5123df099617e | <ide><path>spacy/ml/models/tok2vec.py
<ide> def build_Tok2Vec_model(
<ide> @registry.architectures.register("spacy.MultiHashEmbed.v1")
<ide> def MultiHashEmbed(
<ide> width: int, rows: int, also_embed_subwords: bool, also_use_static_vectors: bool
<del>):
<add>) -> Model[List[Doc], List[Floats2d]]:
<ide> """Construct an embedding layer that separately embeds a number of lexical
<ide> attributes using hash embedding, concatenates the results, and passes it
<ide> through a feed-forward subnetwork to build a mixed representations.
<ide> def make_hash_embed(feature):
<ide> @registry.architectures.register("spacy.CharacterEmbed.v1")
<ide> def CharacterEmbed(
<ide> width: int, rows: int, nM: int, nC: int, also_use_static_vectors: bool
<del>):
<add>) -> Model[List[Doc], List[Floats2d]]:
<ide> """Construct an embedded representation based on character embeddings, using
<ide> a feed-forward network. A fixed number of UTF-8 byte characters are used for
<ide> each word, taken from the beginning and end of the word equally. Padding is | 1 |
Javascript | Javascript | add spaces to improve readability of css | 16c8f29ef6498991c31671d0dc0072543d156b41 | <ide><path>src/ng/directive/ngShowHide.js
<ide> var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
<ide> *
<ide> * ### Overriding `.ng-hide`
<ide> *
<del> * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
<add> * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
<ide> * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
<ide> * class in CSS:
<ide> *
<ide> * ```css
<ide> * .ng-hide {
<ide> * /* this is just another form of hiding an element */
<del> * display:block!important;
<del> * position:absolute;
<del> * top:-9999px;
<del> * left:-9999px;
<add> * display: block!important;
<add> * position: absolute;
<add> * top: -9999px;
<add> * left: -9999px;
<ide> * }
<ide> * ```
<ide> *
<ide> var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
<ide> * .my-element.ng-hide-add, .my-element.ng-hide-remove {
<ide> * /* this is required as of 1.3x to properly
<ide> * apply all styling in a show/hide animation */
<del> * transition:0s linear all;
<add> * transition: 0s linear all;
<ide> * }
<ide> *
<ide> * .my-element.ng-hide-add-active,
<ide> * .my-element.ng-hide-remove-active {
<ide> * /* the transition is defined in the active class */
<del> * transition:1s linear all;
<add> * transition: 1s linear all;
<ide> * }
<ide> *
<ide> * .my-element.ng-hide-add { ... }
<ide> var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
<ide> </file>
<ide> <file name="animations.css">
<ide> .animate-show {
<del> line-height:20px;
<del> opacity:1;
<del> padding:10px;
<del> border:1px solid black;
<del> background:white;
<add> line-height: 20px;
<add> opacity: 1;
<add> padding: 10px;
<add> border: 1px solid black;
<add> background: white;
<ide> }
<ide>
<ide> .animate-show.ng-hide-add.ng-hide-add-active,
<ide> .animate-show.ng-hide-remove.ng-hide-remove-active {
<del> -webkit-transition:all linear 0.5s;
<del> transition:all linear 0.5s;
<add> -webkit-transition: all linear 0.5s;
<add> transition: all linear 0.5s;
<ide> }
<ide>
<ide> .animate-show.ng-hide {
<del> line-height:0;
<del> opacity:0;
<del> padding:0 10px;
<add> line-height: 0;
<add> opacity: 0;
<add> padding: 0 10px;
<ide> }
<ide>
<ide> .check-element {
<del> padding:10px;
<del> border:1px solid black;
<del> background:white;
<add> padding: 10px;
<add> border: 1px solid black;
<add> background: white;
<ide> }
<ide> </file>
<ide> <file name="protractor.js" type="protractor">
<ide> var ngShowDirective = ['$animate', function($animate) {
<ide> *
<ide> * ### Overriding `.ng-hide`
<ide> *
<del> * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
<add> * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
<ide> * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
<ide> * class in CSS:
<ide> *
<ide> * ```css
<ide> * .ng-hide {
<ide> * /* this is just another form of hiding an element */
<del> * display:block!important;
<del> * position:absolute;
<del> * top:-9999px;
<del> * left:-9999px;
<add> * display: block!important;
<add> * position: absolute;
<add> * top: -9999px;
<add> * left: -9999px;
<ide> * }
<ide> * ```
<ide> *
<ide> var ngShowDirective = ['$animate', function($animate) {
<ide> * //a working example can be found at the bottom of this page
<ide> * //
<ide> * .my-element.ng-hide-add, .my-element.ng-hide-remove {
<del> * transition:0.5s linear all;
<add> * transition: 0.5s linear all;
<ide> * }
<ide> *
<ide> * .my-element.ng-hide-add { ... }
<ide> var ngShowDirective = ['$animate', function($animate) {
<ide> </file>
<ide> <file name="animations.css">
<ide> .animate-hide {
<del> -webkit-transition:all linear 0.5s;
<del> transition:all linear 0.5s;
<del> line-height:20px;
<del> opacity:1;
<del> padding:10px;
<del> border:1px solid black;
<del> background:white;
<add> -webkit-transition: all linear 0.5s;
<add> transition: all linear 0.5s;
<add> line-height: 20px;
<add> opacity: 1;
<add> padding: 10px;
<add> border: 1px solid black;
<add> background: white;
<ide> }
<ide>
<ide> .animate-hide.ng-hide {
<del> line-height:0;
<del> opacity:0;
<del> padding:0 10px;
<add> line-height: 0;
<add> opacity: 0;
<add> padding: 0 10px;
<ide> }
<ide>
<ide> .check-element {
<del> padding:10px;
<del> border:1px solid black;
<del> background:white;
<add> padding: 10px;
<add> border: 1px solid black;
<add> background: white;
<ide> }
<ide> </file>
<ide> <file name="protractor.js" type="protractor"> | 1 |
Python | Python | fix syntax for class references | e513c16e82221e0a150b97a31f2c3c864913c454 | <ide><path>src/transformers/generation_flax_utils.py
<ide> def _get_logits_warper(
<ide> self, top_k: int = None, top_p: float = None, temperature: float = None
<ide> ) -> FlaxLogitsProcessorList:
<ide> """
<del> This class returns a :obj:`~transformers.FlaxLogitsProcessorList` list object that contains all relevant
<del> :obj:`~transformers.FlaxLogitsWarper` instances used for multinomial sampling.
<add> This class returns a :class:`~transformers.FlaxLogitsProcessorList` list object that contains all relevant
<add> :class:`~transformers.FlaxLogitsWarper` instances used for multinomial sampling.
<ide> """
<ide>
<ide> # init warp parameters
<ide> def _get_logits_processor(
<ide> forced_eos_token_id: int,
<ide> ) -> FlaxLogitsProcessorList:
<ide> """
<del> This class returns a :obj:`~transformers.FlaxLogitsProcessorList` list object that contains all relevant
<del> :obj:`~transformers.FlaxLogitsProcessor` instances used to modify the scores of the language model head.
<add> This class returns a :class:`~transformers.FlaxLogitsProcessorList` list object that contains all relevant
<add> :class:`~transformers.FlaxLogitsProcessor` instances used to modify the scores of the language model head.
<ide> """
<ide> processors = FlaxLogitsProcessorList()
<ide>
<ide><path>src/transformers/generation_utils.py
<ide> def _get_logits_warper(
<ide> self, top_k: int = None, top_p: float = None, temperature: float = None, num_beams: int = None
<ide> ) -> LogitsProcessorList:
<ide> """
<del> This class returns a :obj:`~transformers.LogitsProcessorList` list object that contains all relevant
<del> :obj:`~transformers.LogitsWarper` instances used for multinomial sampling.
<add> This class returns a :class:`~transformers.LogitsProcessorList` list object that contains all relevant
<add> :class:`~transformers.LogitsWarper` instances used for multinomial sampling.
<ide> """
<ide>
<ide> # init warp parameters
<ide> def _get_logits_processor(
<ide> remove_invalid_values: bool,
<ide> ) -> LogitsProcessorList:
<ide> """
<del> This class returns a :obj:`~transformers.LogitsProcessorList` list object that contains all relevant
<del> :obj:`~transformers.LogitsProcessor` instances used to modify the scores of the language model head.
<add> This class returns a :class:`~transformers.LogitsProcessorList` list object that contains all relevant
<add> :class:`~transformers.LogitsProcessor` instances used to modify the scores of the language model head.
<ide> """
<ide> processors = LogitsProcessorList()
<ide>
<ide><path>src/transformers/modeling_tf_utils.py
<ide> def serving_output(output):
<ide> Prepare the output of the saved model. Each model must implement this function.
<ide>
<ide> Args:
<del> output (:obj:`~transformers.TFBaseModelOutput`):
<add> output (:class:`~transformers.TFBaseModelOutput`):
<ide> The output returned by the model.
<ide> """
<ide> raise NotImplementedError
<ide><path>src/transformers/models/tapas/tokenization_tapas.py
<ide> def _get_truncated_table_rows(
<ide> Total number of table columns
<ide> max_length (:obj:`int`):
<ide> Total maximum length.
<del> truncation_strategy (:obj:`str` or :obj:`~transformers.TapasTruncationStrategy`):
<add> truncation_strategy (:obj:`str` or :class:`~transformers.TapasTruncationStrategy`):
<ide> Truncation strategy to use. Seeing as this method should only be called when truncating, the only
<ide> available strategy is the :obj:`"drop_rows_to_fit"` strategy.
<ide>
<ide><path>src/transformers/pipelines/__init__.py
<ide> def pipeline(
<ide> - :obj:`"summarization"`: will return a :class:`~transformers.SummarizationPipeline`:.
<ide> - :obj:`"zero-shot-classification"`: will return a :class:`~transformers.ZeroShotClassificationPipeline`:.
<ide>
<del> model (:obj:`str` or :obj:`~transformers.PreTrainedModel` or :obj:`~transformers.TFPreTrainedModel`, `optional`):
<add> model (:obj:`str` or :class:`~transformers.PreTrainedModel` or :class:`~transformers.TFPreTrainedModel`, `optional`):
<ide> The model that will be used by the pipeline to make predictions. This can be a model identifier or an
<ide> actual instance of a pretrained model inheriting from :class:`~transformers.PreTrainedModel` (for PyTorch)
<ide> or :class:`~transformers.TFPreTrainedModel` (for TensorFlow).
<ide>
<ide> If not provided, the default for the :obj:`task` will be loaded.
<del> config (:obj:`str` or :obj:`~transformers.PretrainedConfig`, `optional`):
<add> config (:obj:`str` or :class:`~transformers.PretrainedConfig`, `optional`):
<ide> The configuration that will be used by the pipeline to instantiate the model. This can be a model
<ide> identifier or an actual pretrained model configuration inheriting from
<ide> :class:`~transformers.PretrainedConfig`.
<ide>
<ide> If not provided, the default configuration file for the requested model will be used. That means that if
<ide> :obj:`model` is given, its default configuration will be used. However, if :obj:`model` is not supplied,
<ide> this :obj:`task`'s default model's config is used instead.
<del> tokenizer (:obj:`str` or :obj:`~transformers.PreTrainedTokenizer`, `optional`):
<add> tokenizer (:obj:`str` or :class:`~transformers.PreTrainedTokenizer`, `optional`):
<ide> The tokenizer that will be used by the pipeline to encode data for the model. This can be a model
<ide> identifier or an actual pretrained tokenizer inheriting from :class:`~transformers.PreTrainedTokenizer`.
<ide>
<ide> If not provided, the default tokenizer for the given :obj:`model` will be loaded (if it is a string). If
<ide> :obj:`model` is not specified or not a string, then the default tokenizer for :obj:`config` is loaded (if
<ide> it is a string). However, if :obj:`config` is also not given or not a string, then the default tokenizer
<ide> for the given :obj:`task` will be loaded.
<del> feature_extractor (:obj:`str` or :obj:`~transformers.PreTrainedFeatureExtractor`, `optional`):
<add> feature_extractor (:obj:`str` or :class:`~transformers.PreTrainedFeatureExtractor`, `optional`):
<ide> The feature extractor that will be used by the pipeline to encode data for the model. This can be a model
<ide> identifier or an actual pretrained feature extractor inheriting from
<ide> :class:`~transformers.PreTrainedFeatureExtractor`.
<ide><path>src/transformers/pipelines/audio_classification.py
<ide> def __call__(
<ide> **kwargs,
<ide> ):
<ide> """
<del> Classify the sequence(s) given as inputs. See the :obj:`~transformers.AutomaticSpeechRecognitionPipeline`
<add> Classify the sequence(s) given as inputs. See the :class:`~transformers.AutomaticSpeechRecognitionPipeline`
<ide> documentation for more information.
<ide>
<ide> Args:
<ide><path>src/transformers/pipelines/automatic_speech_recognition.py
<ide> class AutomaticSpeechRecognitionPipeline(Pipeline):
<ide> def __init__(self, feature_extractor: Union["SequenceFeatureExtractor", str], *args, **kwargs):
<ide> """
<ide> Arguments:
<del> feature_extractor (:obj:`~transformers.SequenceFeatureExtractor`):
<add> feature_extractor (:class:`~transformers.SequenceFeatureExtractor`):
<ide> The feature extractor that will be used by the pipeline to encode waveform for the model.
<del> model (:obj:`~transformers.PreTrainedModel` or :obj:`~transformers.TFPreTrainedModel`):
<add> model (:class:`~transformers.PreTrainedModel` or :class:`~transformers.TFPreTrainedModel`):
<ide> The model that will be used by the pipeline to make predictions. This needs to be a model inheriting
<ide> from :class:`~transformers.PreTrainedModel` for PyTorch and :class:`~transformers.TFPreTrainedModel`
<ide> for TensorFlow.
<del> tokenizer (:obj:`~transformers.PreTrainedTokenizer`):
<add> tokenizer (:class:`~transformers.PreTrainedTokenizer`):
<ide> The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from
<ide> :class:`~transformers.PreTrainedTokenizer`.
<ide> modelcard (:obj:`str` or :class:`~transformers.ModelCard`, `optional`):
<ide> def __call__(
<ide> **kwargs,
<ide> ):
<ide> """
<del> Classify the sequence(s) given as inputs. See the :obj:`~transformers.AutomaticSpeechRecognitionPipeline`
<add> Classify the sequence(s) given as inputs. See the :class:`~transformers.AutomaticSpeechRecognitionPipeline`
<ide> documentation for more information.
<ide>
<ide> Args:
<ide><path>src/transformers/pipelines/base.py
<ide> def predict(self, X):
<ide>
<ide> PIPELINE_INIT_ARGS = r"""
<ide> Arguments:
<del> model (:obj:`~transformers.PreTrainedModel` or :obj:`~transformers.TFPreTrainedModel`):
<add> model (:class:`~transformers.PreTrainedModel` or :class:`~transformers.TFPreTrainedModel`):
<ide> The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from
<ide> :class:`~transformers.PreTrainedModel` for PyTorch and :class:`~transformers.TFPreTrainedModel` for
<ide> TensorFlow.
<del> tokenizer (:obj:`~transformers.PreTrainedTokenizer`):
<add> tokenizer (:class:`~transformers.PreTrainedTokenizer`):
<ide> The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from
<ide> :class:`~transformers.PreTrainedTokenizer`.
<ide> modelcard (:obj:`str` or :class:`~transformers.ModelCard`, `optional`):
<ide><path>src/transformers/pipelines/feature_extraction.py
<ide> class FeatureExtractionPipeline(Pipeline):
<ide> `huggingface.co/models <https://huggingface.co/models>`__.
<ide>
<ide> Arguments:
<del> model (:obj:`~transformers.PreTrainedModel` or :obj:`~transformers.TFPreTrainedModel`):
<add> model (:class:`~transformers.PreTrainedModel` or :class:`~transformers.TFPreTrainedModel`):
<ide> The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from
<ide> :class:`~transformers.PreTrainedModel` for PyTorch and :class:`~transformers.TFPreTrainedModel` for
<ide> TensorFlow.
<del> tokenizer (:obj:`~transformers.PreTrainedTokenizer`):
<add> tokenizer (:class:`~transformers.PreTrainedTokenizer`):
<ide> The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from
<ide> :class:`~transformers.PreTrainedTokenizer`.
<ide> modelcard (:obj:`str` or :class:`~transformers.ModelCard`, `optional`):
<ide><path>src/transformers/pipelines/zero_shot_classification.py
<ide> def __call__(
<ide> **kwargs,
<ide> ):
<ide> """
<del> Classify the sequence(s) given as inputs. See the :obj:`~transformers.ZeroShotClassificationPipeline`
<add> Classify the sequence(s) given as inputs. See the :class:`~transformers.ZeroShotClassificationPipeline`
<ide> documentation for more information.
<ide>
<ide> Args:
<ide><path>src/transformers/trainer.py
<ide> class Trainer:
<ide> compute_metrics (:obj:`Callable[[EvalPrediction], Dict]`, `optional`):
<ide> The function that will be used to compute metrics at evaluation. Must take a
<ide> :class:`~transformers.EvalPrediction` and return a dictionary string to metric values.
<del> callbacks (List of :obj:`~transformers.TrainerCallback`, `optional`):
<add> callbacks (List of :class:`~transformers.TrainerCallback`, `optional`):
<ide> A list of callbacks to customize the training loop. Will add those to the list of default callbacks
<ide> detailed in :doc:`here <callback>`.
<ide> | 11 |
Python | Python | move old finetuning script into the new folder | f19ba35b2b6192dd55e4e6f974bcec5b8d3f8865 | <add><path>examples/lm_finetuning/simple_lm_finetuning.py
<del><path>examples/run_lm_finetuning.py
<ide> from pytorch_pretrained_bert.tokenization import BertTokenizer
<ide> from pytorch_pretrained_bert.optimization import BertAdam, warmup_linear
<ide>
<del>from torch.utils.data import Dataset
<del>import random
<del>
<ide> logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
<ide> datefmt='%m/%d/%Y %H:%M:%S',
<ide> level=logging.INFO) | 1 |
Ruby | Ruby | extract #head into its own module and simplify it | d7499f8ee8faa80d12dccae5baf5ab2acc79e77d | <ide><path>actionpack/lib/action_controller.rb
<ide> module ActionController
<ide> autoload :Benchmarking, "action_controller/metal/benchmarking"
<ide> autoload :ConditionalGet, "action_controller/metal/conditional_get"
<ide> autoload :Configuration, "action_controller/metal/configuration"
<add> autoload :Head, "action_controller/metal/head"
<ide> autoload :Helpers, "action_controller/metal/helpers"
<ide> autoload :HideActions, "action_controller/metal/hide_actions"
<ide> autoload :Layouts, "action_controller/metal/layouts"
<ide><path>actionpack/lib/action_controller/metal/conditional_get.rb
<ide> module ConditionalGet
<ide> extend ActiveSupport::Concern
<ide>
<ide> include RackConvenience
<add> include Head
<ide>
<ide> # Sets the etag, last_modified, or both on the response and renders a
<ide> # "304 Not Modified" response if the request is already fresh.
<ide> def fresh_when(options)
<ide>
<ide> response.etag = options[:etag] if options[:etag]
<ide> response.last_modified = options[:last_modified] if options[:last_modified]
<add> response.cache_control[:public] = true if options[:public]
<ide>
<del> if options[:public]
<del> response.cache_control[:public] = true
<del> end
<del>
<del> if request.fresh?(response)
<del> head :not_modified
<del> end
<del> end
<del>
<del> # Return a response that has no content (merely headers). The options
<del> # argument is interpreted to be a hash of header names and values.
<del> # This allows you to easily return a response that consists only of
<del> # significant headers:
<del> #
<del> # head :created, :location => person_path(@person)
<del> #
<del> # It can also be used to return exceptional conditions:
<del> #
<del> # return head(:method_not_allowed) unless request.post?
<del> # return head(:bad_request) unless valid_request?
<del> # render
<del> def head(*args)
<del> if args.length > 2
<del> raise ArgumentError, "too many arguments to head"
<del> elsif args.empty?
<del> raise ArgumentError, "too few arguments to head"
<del> end
<del> options = args.extract_options!
<del> status = args.shift || options.delete(:status) || :ok
<del> location = options.delete(:location)
<del>
<del> options.each do |key, value|
<del> headers[key.to_s.dasherize.split(/-/).map { |v| v.capitalize }.join("-")] = value.to_s
<del> end
<del>
<del> render :nothing => true, :status => status, :location => location
<add> head :not_modified if request.fresh?(response)
<ide> end
<ide>
<ide> # Sets the etag and/or last_modified on the response and checks it against
<ide><path>actionpack/lib/action_controller/metal/head.rb
<add>module ActionController
<add> module Head
<add> # Return a response that has no content (merely headers). The options
<add> # argument is interpreted to be a hash of header names and values.
<add> # This allows you to easily return a response that consists only of
<add> # significant headers:
<add> #
<add> # head :created, :location => person_path(@person)
<add> #
<add> # It can also be used to return exceptional conditions:
<add> #
<add> # return head(:method_not_allowed) unless request.post?
<add> # return head(:bad_request) unless valid_request?
<add> # render
<add> def head(status, options = {})
<add> options, status = status, nil if status.is_a?(Hash)
<add> status ||= options.delete(:status) || :ok
<add> location = options.delete(:location)
<add>
<add> options.each do |key, value|
<add> headers[key.to_s.dasherize.split(/-/).map { |v| v.capitalize }.join("-")] = value.to_s
<add> end
<add>
<add> render :nothing => true, :status => status, :location => location
<add> end
<add> end
<add>end
<ide>\ No newline at end of file | 3 |
Javascript | Javascript | remove stray console.log() from line3 unit test | a685230753ffc8709f860af11824fb84829f2ee3 | <ide><path>test/unit/math/Line3.js
<ide> test( "closestPointToPoint/closestPointToPointParameter", function() {
<ide> // nearby the ray
<ide> ok( a.closestPointToPointParameter( zero3.clone(), false ) == -1, "Passed!" );
<ide> var b2 = a.closestPointToPoint( zero3.clone(), false );
<del> console.log( b2 );
<ide> ok( b2.distanceTo( new THREE.Vector3( 1, 1, 0 ) ) < 0.0001, "Passed!" );
<ide>
<ide> // nearby the ray | 1 |
Python | Python | add ex_metadata parameter to create_node | 9bfb08af7519d016e79a9fd75320eb1f8f6870ad | <ide><path>libcloud/compute/drivers/ec2.py
<ide> def create_node(self, **kwargs):
<ide> assign to the node.
<ide> :type ex_security_groups: ``list``
<ide>
<add> :keyword ex_metadata: Key/Value metadata to associate with a node
<add> :type ex_metadata: ``dict``
<add>
<ide> :keyword ex_mincount: Minimum number of instances to launch
<ide> :type ex_mincount: ``int``
<ide>
<ide> def create_node(self, **kwargs):
<ide>
<ide> for node in nodes:
<ide> tags = {'Name': kwargs['name']}
<add> if 'ex_metadata' in kwargs:
<add> tags.update(kwargs['ex_metadata'])
<ide>
<ide> try:
<ide> self.ex_create_tags(resource=node, tags=tags)
<ide><path>libcloud/test/compute/test_ec2.py
<ide> def test_create_node_with_ex_mincount(self):
<ide> self.assertEqual(node.extra['tags']['Name'], 'foo')
<ide> self.assertEqual(len(node.extra['tags']), 1)
<ide>
<add> def test_create_node_with_metadata(self):
<add> image = NodeImage(id='ami-be3adfd7',
<add> name=self.image_name,
<add> driver=self.driver)
<add> size = NodeSize('m1.small', 'Small Instance', None, None, None, None,
<add> driver=self.driver)
<add> node = self.driver.create_node(name='foo',
<add> image=image,
<add> size=size,
<add> ex_metadata={'Bar': 'baz', 'Num': '42'})
<add> self.assertEqual(node.name, 'foo')
<add> self.assertEqual(node.extra['tags']['Name'], 'foo')
<add> self.assertEqual(node.extra['tags']['Bar'], 'baz')
<add> self.assertEqual(node.extra['tags']['Num'], '42')
<add> self.assertEqual(len(node.extra['tags']), 3)
<add>
<ide> def test_create_node_idempotent(self):
<ide> EC2MockHttp.type = 'idempotent'
<ide> image = NodeImage(id='ami-be3adfd7', | 2 |
Java | Java | add channelinterceptor to spring-messaging module | 4b2847d9d12bad150e3a2e0730a331e07825b06c | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessageHeaderAccessor.java
<ide> protected SimpMessageHeaderAccessor(SimpMessageType messageType, Map<String, Lis
<ide> */
<ide> protected SimpMessageHeaderAccessor(Message<?> message) {
<ide> super(message);
<del> Assert.notNull(message, "message is required");
<ide> }
<ide>
<ide>
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/NativeMessageHeaderAccessor.java
<ide> public Map<String, List<String>> toNativeHeaderMap() {
<ide> return result;
<ide> }
<ide>
<del> protected List<String> getNativeHeader(String headerName) {
<add> /**
<add> * Return all values for the specified native header or {@code null}.
<add> */
<add> public List<String> getNativeHeader(String headerName) {
<ide> if (this.nativeHeaders.containsKey(headerName)) {
<ide> return this.nativeHeaders.get(headerName);
<ide> }
<ide> else if (this.originalNativeHeaders != null) {
<ide> return null;
<ide> }
<ide>
<add> /**
<add> * Return the first value for the specified native header of {@code null}.
<add> */
<ide> public String getFirstNativeHeader(String headerName) {
<ide> List<String> values = getNativeHeader(headerName);
<ide> return CollectionUtils.isEmpty(values) ? null : values.get(0);
<ide> }
<ide>
<ide> /**
<del> * Set the value for the given header name. If the provided value is {@code null} the
<del> * header will be removed.
<add> * Set the specified native header value.
<ide> */
<del> protected void putNativeHeader(String name, List<String> value) {
<add> public void setNativeHeader(String name, String value) {
<ide> if (!ObjectUtils.nullSafeEquals(value, getHeader(name))) {
<del> this.nativeHeaders.put(name, value);
<add> this.nativeHeaders.set(name, value);
<ide> }
<ide> }
<ide>
<del> public void setNativeHeader(String name, String value) {
<del> this.nativeHeaders.set(name, value);
<add> /**
<add> * Add the specified native header value.
<add> */
<add> public void addNativeHeader(String name, String value) {
<add> this.nativeHeaders.add(name, value);
<ide> }
<ide>
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/channel/AbstractMessageChannel.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.messaging.support.channel;
<add>
<add>import java.util.List;
<add>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>import org.springframework.beans.factory.BeanNameAware;
<add>import org.springframework.messaging.Message;
<add>import org.springframework.messaging.MessageChannel;
<add>import org.springframework.messaging.MessageDeliveryException;
<add>import org.springframework.messaging.MessagingException;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.ObjectUtils;
<add>
<add>
<add>/**
<add> * Abstract base class for {@link MessageChannel} implementations.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 4.0
<add> */
<add>public abstract class AbstractMessageChannel implements MessageChannel, BeanNameAware {
<add>
<add> protected Log logger = LogFactory.getLog(getClass());
<add>
<add> private String beanName;
<add>
<add> private final ChannelInterceptorChain interceptorChain = new ChannelInterceptorChain();
<add>
<add>
<add> public AbstractMessageChannel() {
<add> this.beanName = getClass().getSimpleName() + "@" + ObjectUtils.getIdentityHexString(this);
<add> }
<add>
<add> /**
<add> * {@inheritDoc}
<add> * <p>Used primarily for logging purposes.
<add> */
<add> @Override
<add> public void setBeanName(String name) {
<add> this.beanName = name;
<add> }
<add>
<add> /**
<add> * @return the name for this channel.
<add> */
<add> public String getBeanName() {
<add> return this.beanName;
<add> }
<add>
<add> /**
<add> * Set the list of channel interceptors. This will clear any existing interceptors.
<add> */
<add> public void setInterceptors(List<ChannelInterceptor> interceptors) {
<add> this.interceptorChain.set(interceptors);
<add> }
<add>
<add> /**
<add> * Add a channel interceptor to the end of the list.
<add> */
<add> public void addInterceptor(ChannelInterceptor interceptor) {
<add> this.interceptorChain.add(interceptor);
<add> }
<add>
<add> /**
<add> * Return a read-only list of the configured interceptors.
<add> */
<add> public List<ChannelInterceptor> getInterceptors() {
<add> return this.interceptorChain.getInterceptors();
<add> }
<add>
<add> /**
<add> * Exposes the interceptor list for subclasses.
<add> */
<add> protected ChannelInterceptorChain getInterceptorChain() {
<add> return this.interceptorChain;
<add> }
<add>
<add>
<add> @Override
<add> public final boolean send(Message<?> message) {
<add> return send(message, INDEFINITE_TIMEOUT);
<add> }
<add>
<add> @Override
<add> public final boolean send(Message<?> message, long timeout) {
<add>
<add> Assert.notNull(message, "Message must not be null");
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("[" + this.beanName + "] sending message " + message);
<add> }
<add>
<add> message = this.interceptorChain.preSend(message, this);
<add> if (message == null) {
<add> return false;
<add> }
<add>
<add> try {
<add> boolean sent = sendInternal(message, timeout);
<add> this.interceptorChain.postSend(message, this, sent);
<add> return sent;
<add> }
<add> catch (Exception e) {
<add> if (e instanceof MessagingException) {
<add> throw (MessagingException) e;
<add> }
<add> throw new MessageDeliveryException(message,
<add> "Failed to send message to channel '" + this.getBeanName() + "'", e);
<add> }
<add> }
<add>
<add> protected abstract boolean sendInternal(Message<?> message, long timeout);
<add>
<add>}
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/channel/AbstractSubscribableChannel.java
<ide>
<ide> package org.springframework.messaging.support.channel;
<ide>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<del>import org.springframework.beans.factory.BeanNameAware;
<del>import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessageHandler;
<ide> import org.springframework.messaging.SubscribableChannel;
<del>import org.springframework.util.Assert;
<del>import org.springframework.util.ObjectUtils;
<ide>
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>public abstract class AbstractSubscribableChannel implements SubscribableChannel, BeanNameAware {
<add>public abstract class AbstractSubscribableChannel extends AbstractMessageChannel implements SubscribableChannel {
<ide>
<del> protected Log logger = LogFactory.getLog(getClass());
<del>
<del> private String beanName;
<del>
<del>
<del> public AbstractSubscribableChannel() {
<del> this.beanName = getClass().getSimpleName() + "@" + ObjectUtils.getIdentityHexString(this);
<del> }
<del>
<del> /**
<del> * {@inheritDoc}
<del> * <p>Used primarily for logging purposes.
<del> */
<del> @Override
<del> public void setBeanName(String name) {
<del> this.beanName = name;
<del> }
<del>
<del> /**
<del> * @return the name for this channel.
<del> */
<del> public String getBeanName() {
<del> return this.beanName;
<del> }
<del>
<del> @Override
<del> public final boolean send(Message<?> message) {
<del> return send(message, INDEFINITE_TIMEOUT);
<del> }
<del>
<del> @Override
<del> public final boolean send(Message<?> message, long timeout) {
<del> Assert.notNull(message, "Message must not be null");
<del> if (logger.isTraceEnabled()) {
<del> logger.trace("[" + this.beanName + "] sending message " + message);
<del> }
<del> return sendInternal(message, timeout);
<del> }
<del>
<del> protected abstract boolean sendInternal(Message<?> message, long timeout);
<ide>
<ide> @Override
<ide> public final boolean subscribe(MessageHandler handler) {
<ide> if (hasSubscription(handler)) {
<del> logger.warn("[" + this.beanName + "] handler already subscribed " + handler);
<add> logger.warn("[" + getBeanName() + "] handler already subscribed " + handler);
<ide> return false;
<ide> }
<ide> if (logger.isDebugEnabled()) {
<del> logger.debug("[" + this.beanName + "] subscribing " + handler);
<add> logger.debug("[" + getBeanName() + "] subscribing " + handler);
<ide> }
<ide> return subscribeInternal(handler);
<ide> }
<ide> public final boolean subscribe(MessageHandler handler) {
<ide> @Override
<ide> public final boolean unsubscribe(MessageHandler handler) {
<ide> if (logger.isDebugEnabled()) {
<del> logger.debug("[" + this.beanName + "] unsubscribing " + handler);
<add> logger.debug("[" + getBeanName() + "] unsubscribing " + handler);
<ide> }
<ide> return unsubscribeInternal(handler);
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/channel/ChannelInterceptor.java
<add>/*
<add> * Copyright 2002-2010 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.messaging.support.channel;
<add>
<add>import org.springframework.messaging.Message;
<add>import org.springframework.messaging.MessageChannel;
<add>
<add>/**
<add> * Interface for interceptors that are able to view and/or modify the
<add> * {@link Message Messages} being sent-to and/or received-from a
<add> * {@link MessageChannel}.
<add> *
<add> * @author Mark Fisher
<add> * @since 4.0
<add> */
<add>public interface ChannelInterceptor {
<add>
<add> /**
<add> * Invoked before the Message is actually sent to the channel.
<add> * This allows for modification of the Message if necessary.
<add> * If this method returns <code>null</code>, then the actual
<add> * send invocation will not occur.
<add> */
<add> Message<?> preSend(Message<?> message, MessageChannel channel);
<add>
<add> /**
<add> * Invoked immediately after the send invocation. The boolean
<add> * value argument represents the return value of that invocation.
<add> */
<add> void postSend(Message<?> message, MessageChannel channel, boolean sent);
<add>
<add> /**
<add> * Invoked as soon as receive is called and before a Message is
<add> * actually retrieved. If the return value is 'false', then no
<add> * Message will be retrieved. This only applies to PollableChannels.
<add> */
<add> boolean preReceive(MessageChannel channel);
<add>
<add> /**
<add> * Invoked immediately after a Message has been retrieved but before
<add> * it is returned to the caller. The Message may be modified if
<add> * necessary. This only applies to PollableChannels.
<add> */
<add> Message<?> postReceive(Message<?> message, MessageChannel channel);
<add>
<add>}
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/channel/ChannelInterceptorAdapter.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.messaging.support.channel;
<add>
<add>import org.springframework.messaging.Message;
<add>import org.springframework.messaging.MessageChannel;
<add>
<add>/**
<add> * A {@link ChannelInterceptor} with empty method implementations as a convenience.
<add> *
<add> * @author Mark Fisher
<add> * @since 4.0
<add> */
<add>public class ChannelInterceptorAdapter implements ChannelInterceptor {
<add>
<add>
<add> public Message<?> preSend(Message<?> message, MessageChannel channel) {
<add> return message;
<add> }
<add>
<add> public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
<add> }
<add>
<add> public boolean preReceive(MessageChannel channel) {
<add> return true;
<add> }
<add>
<add> public Message<?> postReceive(Message<?> message, MessageChannel channel) {
<add> return message;
<add> }
<add>
<add>}
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/channel/ChannelInterceptorChain.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.messaging.support.channel;
<add>
<add>import java.util.Collections;
<add>import java.util.List;
<add>import java.util.concurrent.CopyOnWriteArrayList;
<add>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>import org.springframework.messaging.Message;
<add>import org.springframework.messaging.MessageChannel;
<add>
<add>
<add>/**
<add> * A convenience wrapper class for invoking a list of {@link ChannelInterceptor}s.
<add> *
<add> * @author Mark Fisher
<add> * @author Rossen Stoyanchev
<add> * @since 4.0
<add> */
<add>class ChannelInterceptorChain {
<add>
<add> private static final Log logger = LogFactory.getLog(ChannelInterceptorChain.class);
<add>
<add> private final List<ChannelInterceptor> interceptors = new CopyOnWriteArrayList<ChannelInterceptor>();
<add>
<add>
<add> public boolean set(List<ChannelInterceptor> interceptors) {
<add> synchronized (this.interceptors) {
<add> this.interceptors.clear();
<add> return this.interceptors.addAll(interceptors);
<add> }
<add> }
<add>
<add> public boolean add(ChannelInterceptor interceptor) {
<add> return this.interceptors.add(interceptor);
<add> }
<add>
<add> public List<ChannelInterceptor> getInterceptors() {
<add> return Collections.unmodifiableList(this.interceptors);
<add> }
<add>
<add>
<add> public Message<?> preSend(Message<?> message, MessageChannel channel) {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("preSend on channel '" + channel + "', message: " + message);
<add> }
<add> for (ChannelInterceptor interceptor : this.interceptors) {
<add> message = interceptor.preSend(message, channel);
<add> if (message == null) {
<add> return null;
<add> }
<add> }
<add> return message;
<add> }
<add>
<add> public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("postSend (sent=" + sent + ") on channel '" + channel + "', message: " + message);
<add> }
<add> for (ChannelInterceptor interceptor : this.interceptors) {
<add> interceptor.postSend(message, channel, sent);
<add> }
<add> }
<add>
<add> public boolean preReceive(MessageChannel channel) {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("preReceive on channel '" + channel + "'");
<add> }
<add> for (ChannelInterceptor interceptor : this.interceptors) {
<add> if (!interceptor.preReceive(channel)) {
<add> return false;
<add> }
<add> }
<add> return true;
<add> }
<add>
<add> public Message<?> postReceive(Message<?> message, MessageChannel channel) {
<add> if (message != null && logger.isTraceEnabled()) {
<add> logger.trace("postReceive on channel '" + channel + "', message: " + message);
<add> }
<add> else if (logger.isTraceEnabled()) {
<add> logger.trace("postReceive on channel '" + channel + "', message is null");
<add> }
<add> for (ChannelInterceptor interceptor : this.interceptors) {
<add> message = interceptor.postReceive(message, channel);
<add> if (message == null) {
<add> return null;
<add> }
<add> }
<add> return message;
<add> }
<add>
<add>
<add>}
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java
<ide>
<ide> package org.springframework.messaging.simp.stomp;
<ide>
<add>import java.util.List;
<add>import java.util.Map;
<add>
<ide> import org.junit.Test;
<add>import org.springframework.http.MediaType;
<add>import org.springframework.messaging.simp.SimpMessageType;
<ide> import org.springframework.util.LinkedMultiValueMap;
<add>import org.springframework.util.MultiValueMap;
<ide>
<ide> import static org.junit.Assert.*;
<ide>
<ide> public class StompHeaderAccessorTests {
<ide>
<ide>
<ide> @Test
<del> public void testStompCommandSet() {
<add> public void createWithCommand() {
<add>
<ide> StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED);
<ide> assertEquals(StompCommand.CONNECTED, accessor.getCommand());
<ide>
<ide> accessor = StompHeaderAccessor.create(StompCommand.CONNECTED, new LinkedMultiValueMap<String, String>());
<ide> assertEquals(StompCommand.CONNECTED, accessor.getCommand());
<ide> }
<ide>
<add> @Test
<add> public void createWithSubscribeNativeHeaders() {
<add>
<add> MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
<add> extHeaders.add(StompHeaderAccessor.STOMP_ID_HEADER, "s1");
<add> extHeaders.add(StompHeaderAccessor.STOMP_DESTINATION_HEADER, "/d");
<add>
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE, extHeaders);
<add>
<add> assertEquals(StompCommand.SUBSCRIBE, headers.getCommand());
<add> assertEquals(SimpMessageType.SUBSCRIBE, headers.getMessageType());
<add> assertEquals("/d", headers.getDestination());
<add> assertEquals("s1", headers.getSubscriptionId());
<add> }
<add>
<add> @Test
<add> public void createWithUnubscribeNativeHeaders() {
<add>
<add> MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
<add> extHeaders.add(StompHeaderAccessor.STOMP_ID_HEADER, "s1");
<add>
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.UNSUBSCRIBE, extHeaders);
<add>
<add> assertEquals(StompCommand.UNSUBSCRIBE, headers.getCommand());
<add> assertEquals(SimpMessageType.UNSUBSCRIBE, headers.getMessageType());
<add> assertEquals("s1", headers.getSubscriptionId());
<add> }
<add>
<add> @Test
<add> public void createWithMessageFrameNativeHeaders() {
<add>
<add> MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
<add> extHeaders.add(StompHeaderAccessor.DESTINATION_HEADER, "/d");
<add> extHeaders.add(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER, "s1");
<add> extHeaders.add(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER, "application/json");
<add>
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE, extHeaders);
<add>
<add> assertEquals(StompCommand.MESSAGE, headers.getCommand());
<add> assertEquals(SimpMessageType.MESSAGE, headers.getMessageType());
<add> assertEquals("s1", headers.getSubscriptionId());
<add> }
<add>
<add> @Test
<add> public void toNativeHeadersSubscribe() {
<add>
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
<add> headers.setSubscriptionId("s1");
<add> headers.setDestination("/d");
<add>
<add> Map<String, List<String>> actual = headers.toNativeHeaderMap();
<add>
<add> assertEquals(2, actual.size());
<add> assertEquals("s1", actual.get(StompHeaderAccessor.STOMP_ID_HEADER).get(0));
<add> assertEquals("/d", actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0));
<add> }
<add>
<add> @Test
<add> public void toNativeHeadersUnsubscribe() {
<add>
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.UNSUBSCRIBE);
<add> headers.setSubscriptionId("s1");
<add>
<add> Map<String, List<String>> actual = headers.toNativeHeaderMap();
<add>
<add> assertEquals(1, actual.size());
<add> assertEquals("s1", actual.get(StompHeaderAccessor.STOMP_ID_HEADER).get(0));
<add> }
<add>
<add> @Test
<add> public void toNativeHeadersMessageFrame() {
<add>
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE);
<add> headers.setSubscriptionId("s1");
<add> headers.setDestination("/d");
<add> headers.setContentType(MediaType.APPLICATION_JSON);
<add>
<add> Map<String, List<String>> actual = headers.toNativeHeaderMap();
<add>
<add> assertEquals(4, actual.size());
<add> assertEquals("s1", actual.get(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER).get(0));
<add> assertEquals("/d", actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0));
<add> assertEquals("application/json", actual.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER).get(0));
<add> assertNotNull("message-id was not created", actual.get(StompHeaderAccessor.STOMP_MESSAGE_ID_HEADER).get(0));
<add> }
<add>
<add> @Test
<add> public void modifyCustomNativeHeader() {
<add>
<add> MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
<add> extHeaders.add(StompHeaderAccessor.STOMP_ID_HEADER, "s1");
<add> extHeaders.add(StompHeaderAccessor.STOMP_DESTINATION_HEADER, "/d");
<add> extHeaders.add("accountId", "ABC123");
<add>
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE, extHeaders);
<add> String accountId = headers.getFirstNativeHeader("accountId");
<add> headers.setNativeHeader("accountId", accountId.toLowerCase());
<add>
<add> Map<String, List<String>> actual = headers.toNativeHeaderMap();
<add> assertEquals(3, actual.size());
<add>
<add> assertEquals("s1", actual.get(StompHeaderAccessor.STOMP_ID_HEADER).get(0));
<add> assertEquals("/d", actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0));
<add> assertNotNull("abc123", actual.get("accountId").get(0));
<add> }
<add>
<add>
<ide> }
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.messaging.support;
<add>
<add>import java.util.Collections;
<add>import java.util.HashMap;
<add>import java.util.Map;
<add>
<add>import org.junit.Test;
<add>import org.springframework.messaging.MessageHeaders;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>
<add>/**
<add> * Test fixture for {@link MessageHeaderAccessor}.
<add> *
<add> * @author Rossen Stoyanchev
<add> */
<add>public class MessageHeaderAccessorTests {
<add>
<add>
<add> @Test
<add> public void empty() {
<add> MessageHeaderAccessor headers = new MessageHeaderAccessor();
<add> assertEquals(Collections.emptyMap(), headers.toMap());
<add> }
<add>
<add> @Test
<add> public void wrapMessage() {
<add> Map<String, Object> original = new HashMap<>();
<add> original.put("foo", "bar");
<add> original.put("bar", "baz");
<add> GenericMessage<String> message = new GenericMessage<>("p", original);
<add>
<add> MessageHeaderAccessor headers = new MessageHeaderAccessor(message);
<add> Map<String, Object> actual = headers.toMap();
<add>
<add> assertEquals(4, actual.size());
<add> assertNotNull(actual.get(MessageHeaders.ID));
<add> assertNotNull(actual.get(MessageHeaders.TIMESTAMP));
<add> assertEquals("bar", actual.get("foo"));
<add> assertEquals("baz", actual.get("bar"));
<add> }
<add>
<add> @Test
<add> public void wrapMessageAndModifyHeaders() {
<add> Map<String, Object> original = new HashMap<>();
<add> original.put("foo", "bar");
<add> original.put("bar", "baz");
<add> GenericMessage<String> message = new GenericMessage<>("p", original);
<add>
<add> MessageHeaderAccessor headers = new MessageHeaderAccessor(message);
<add> headers.setHeader("foo", "BAR");
<add> Map<String, Object> actual = headers.toMap();
<add>
<add> assertEquals(4, actual.size());
<add> assertNotNull(actual.get(MessageHeaders.ID));
<add> assertNotNull(actual.get(MessageHeaders.TIMESTAMP));
<add> assertEquals("BAR", actual.get("foo"));
<add> assertEquals("baz", actual.get("bar"));
<add> }
<add>
<add>}
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/NativeMessageHeaderAccessorTests.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.messaging.support;
<add>
<add>import java.util.Arrays;
<add>import java.util.Collections;
<add>import java.util.HashMap;
<add>import java.util.List;
<add>import java.util.Map;
<add>
<add>import org.junit.Test;
<add>import org.springframework.messaging.Message;
<add>import org.springframework.messaging.MessageHeaders;
<add>import org.springframework.util.LinkedMultiValueMap;
<add>import org.springframework.util.MultiValueMap;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>
<add>/**
<add> * Test fixture for {@link NativeMessageHeaderAccessor}.
<add> *
<add> * @author Rossen Stoyanchev
<add> */
<add>public class NativeMessageHeaderAccessorTests {
<add>
<add>
<add> @Test
<add> public void originalNativeHeaders() {
<add> MultiValueMap<String, String> original = new LinkedMultiValueMap<>();
<add> original.add("foo", "bar");
<add> original.add("bar", "baz");
<add>
<add> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(original);
<add> Map<String, Object> actual = headers.toMap();
<add>
<add> assertEquals(1, actual.size());
<add> assertNotNull(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
<add> assertEquals(original, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
<add> }
<add>
<add> @Test
<add> public void wrapMessage() {
<add>
<add> MultiValueMap<String, String> originalNativeHeaders = new LinkedMultiValueMap<>();
<add> originalNativeHeaders.add("foo", "bar");
<add> originalNativeHeaders.add("bar", "baz");
<add>
<add> Map<String, Object> original = new HashMap<String, Object>();
<add> original.put("a", "b");
<add> original.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, originalNativeHeaders);
<add>
<add> GenericMessage<String> message = new GenericMessage<>("p", original);
<add>
<add> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(message);
<add> Map<String, Object> actual = headers.toMap();
<add>
<add> assertEquals(4, actual.size());
<add> assertNotNull(actual.get(MessageHeaders.ID));
<add> assertNotNull(actual.get(MessageHeaders.TIMESTAMP));
<add> assertEquals("b", actual.get("a"));
<add> assertNotNull(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
<add> assertEquals(originalNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
<add> }
<add>
<add> @Test
<add> public void wrapNullMessage() {
<add> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor((Message<?>) null);
<add> Map<String, Object> actual = headers.toMap();
<add>
<add> assertEquals(1, actual.size());
<add>
<add> @SuppressWarnings("unchecked")
<add> Map<String, List<String>> actualNativeHeaders =
<add> (Map<String, List<String>>) actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS);
<add>
<add> assertEquals(Collections.emptyMap(), actualNativeHeaders);
<add> }
<add>
<add> @Test
<add> public void wrapMessageAndModifyHeaders() {
<add>
<add> MultiValueMap<String, String> originalNativeHeaders = new LinkedMultiValueMap<>();
<add> originalNativeHeaders.add("foo", "bar");
<add> originalNativeHeaders.add("bar", "baz");
<add>
<add> Map<String, Object> original = new HashMap<String, Object>();
<add> original.put("a", "b");
<add> original.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, originalNativeHeaders);
<add>
<add> GenericMessage<String> message = new GenericMessage<>("p", original);
<add>
<add> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(message);
<add> headers.setHeader("a", "B");
<add> headers.setNativeHeader("foo", "BAR");
<add>
<add> Map<String, Object> actual = headers.toMap();
<add>
<add> assertEquals(4, actual.size());
<add> assertNotNull(actual.get(MessageHeaders.ID));
<add> assertNotNull(actual.get(MessageHeaders.TIMESTAMP));
<add> assertEquals("B", actual.get("a"));
<add>
<add> @SuppressWarnings("unchecked")
<add> Map<String, List<String>> actualNativeHeaders =
<add> (Map<String, List<String>>) actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS);
<add>
<add> assertNotNull(actualNativeHeaders);
<add> assertEquals(Arrays.asList("BAR"), actualNativeHeaders.get("foo"));
<add> assertEquals(Arrays.asList("baz"), actualNativeHeaders.get("bar"));
<add> }
<add>
<add>}
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/channel/ChannelInterceptorTests.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.messaging.support.channel;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<add>import java.util.concurrent.atomic.AtomicInteger;
<add>
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>import org.springframework.messaging.Message;
<add>import org.springframework.messaging.MessageChannel;
<add>import org.springframework.messaging.MessageHandler;
<add>import org.springframework.messaging.MessagingException;
<add>import org.springframework.messaging.support.MessageBuilder;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * Test fixture for the use of {@link ChannelInterceptor}s.
<add> * @author Rossen Stoyanchev
<add> */
<add>public class ChannelInterceptorTests {
<add>
<add> private ExecutorSubscribableChannel channel;
<add>
<add> private TestMessageHandler messageHandler;
<add>
<add>
<add> @Before
<add> public void setup() {
<add> this.channel = new ExecutorSubscribableChannel();
<add> this.messageHandler = new TestMessageHandler();
<add> this.channel.subscribe(this.messageHandler);
<add> }
<add>
<add>
<add> @Test
<add> public void preSendInterceptorReturningModifiedMessage() {
<add>
<add> this.channel.addInterceptor(new PreSendReturnsMessageInterceptor());
<add> this.channel.send(MessageBuilder.withPayload("test").build());
<add>
<add> assertEquals(1, this.messageHandler.messages.size());
<add> Message<?> result = this.messageHandler.messages.get(0);
<add>
<add> assertNotNull(result);
<add> assertEquals("test", result.getPayload());
<add> assertEquals(1, result.getHeaders().get(PreSendReturnsMessageInterceptor.class.getSimpleName()));
<add> }
<add>
<add> @Test
<add> public void preSendInterceptorReturningNull() {
<add>
<add> PreSendReturnsNullInterceptor interceptor = new PreSendReturnsNullInterceptor();
<add> this.channel.addInterceptor(interceptor);
<add> Message<?> message = MessageBuilder.withPayload("test").build();
<add> this.channel.send(message);
<add>
<add> assertEquals(1, interceptor.counter.get());
<add> assertEquals(0, this.messageHandler.messages.size());
<add> }
<add>
<add> @Test
<add> public void postSendInterceptorMessageWasSent() {
<add> final AtomicBoolean invoked = new AtomicBoolean(false);
<add> this.channel.addInterceptor(new ChannelInterceptorAdapter() {
<add> @Override
<add> public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
<add> assertNotNull(message);
<add> assertNotNull(channel);
<add> assertSame(ChannelInterceptorTests.this.channel, channel);
<add> assertTrue(sent);
<add> invoked.set(true);
<add> }
<add> });
<add> this.channel.send(MessageBuilder.withPayload("test").build());
<add> assertTrue(invoked.get());
<add> }
<add>
<add> @Test
<add> public void postSendInterceptorMessageWasNotSent() {
<add> final AbstractMessageChannel testChannel = new AbstractMessageChannel() {
<add> @Override
<add> protected boolean sendInternal(Message<?> message, long timeout) {
<add> return false;
<add> }
<add> };
<add> final AtomicBoolean invoked = new AtomicBoolean(false);
<add> testChannel.addInterceptor(new ChannelInterceptorAdapter() {
<add> @Override
<add> public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
<add> assertNotNull(message);
<add> assertNotNull(channel);
<add> assertSame(testChannel, channel);
<add> assertFalse(sent);
<add> invoked.set(true);
<add> }
<add> });
<add> testChannel.send(MessageBuilder.withPayload("test").build());
<add> assertTrue(invoked.get());
<add> }
<add>
<add>
<add> private static class TestMessageHandler implements MessageHandler {
<add>
<add> private List<Message<?>> messages = new ArrayList<Message<?>>();
<add>
<add> @Override
<add> public void handleMessage(Message<?> message) throws MessagingException {
<add> this.messages.add(message);
<add> }
<add> }
<add>
<add> private static class PreSendReturnsMessageInterceptor extends ChannelInterceptorAdapter {
<add>
<add> private AtomicInteger counter = new AtomicInteger();
<add>
<add> private String foo;
<add>
<add> @Override
<add> public Message<?> preSend(Message<?> message, MessageChannel channel) {
<add> assertNotNull(message);
<add> return MessageBuilder.fromMessage(message).setHeader(
<add> this.getClass().getSimpleName(), counter.incrementAndGet()).build();
<add> }
<add> }
<add>
<add> private static class PreSendReturnsNullInterceptor extends ChannelInterceptorAdapter {
<add>
<add> private AtomicInteger counter = new AtomicInteger();
<add>
<add> @Override
<add> public Message<?> preSend(Message<?> message, MessageChannel channel) {
<add> assertNotNull(message);
<add> counter.incrementAndGet();
<add> return null;
<add> }
<add> }
<add>
<add>}
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/channel/PublishSubscibeChannelTests.java
<ide> import org.mockito.MockitoAnnotations;
<ide> import org.springframework.core.task.TaskExecutor;
<ide> import org.springframework.messaging.Message;
<add>import org.springframework.messaging.MessageDeliveryException;
<ide> import org.springframework.messaging.MessageHandler;
<ide> import org.springframework.messaging.MessagingException;
<ide> import org.springframework.messaging.support.MessageBuilder;
<ide> public void failurePropagates() throws Exception {
<ide> try {
<ide> this.channel.send(message);
<ide> }
<del> catch(RuntimeException actualException) {
<del> assertThat(actualException, equalTo(ex));
<add> catch(MessageDeliveryException actualException) {
<add> assertThat((RuntimeException) actualException.getCause(), equalTo(ex));
<ide> }
<ide> verifyZeroInteractions(secondHandler);
<ide> } | 12 |
Java | Java | add more logs | 24ac66984c2d0c55ae09fb2df0f1e88a42339f21 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java
<ide> public void initializeWithInstance(CatalystInstance catalystInstance) {
<ide>
<ide> /** Initialize message queue threads using a ReactQueueConfiguration. */
<ide> public synchronized void initializeMessageQueueThreads(ReactQueueConfiguration queueConfig) {
<add> FLog.w(TAG, "initializeMessageQueueThreads() is called.");
<ide> if (mUiMessageQueueThread != null
<ide> || mNativeModulesMessageQueueThread != null
<ide> || mJSMessageQueueThread != null) { | 1 |
Text | Text | update readme to include the resnet checkpoint | 8479cc7c70f0a584d1b5c6fa00d9e2af47c40d33 | <ide><path>official/vision/detection/README.md
<ide> python3 ~/models/official/vision/detection/main.py \
<ide> --params_override="{ type: retinanet, train: { checkpoint: { path: ${RESNET_CHECKPOINT?}, prefix: resnet50/ }, train_file_pattern: ${TRAIN_FILE_PATTERN?} }, eval: { val_json_file: ${VAL_JSON_FILE?}, eval_file_pattern: ${EVAL_FILE_PATTERN?} } }"
<ide> ```
<ide>
<add>The pre-trained ResNet-50 checkpoint can be found here:
<add>
<add>```
<add>gs://cloud-tpu-artifacts/resnet/resnet-nhwc-2018-10-14/model.ckpt-112602
<add>```
<add>
<ide> ### Train a custom RetinaNet using the config file.
<ide>
<ide> First, create a YAML config file, e.g. *my_retinanet.yaml*. This file specifies | 1 |
Javascript | Javascript | use arrow function instead of bind | 571ecd1aed3a1f04c2910bcf72585506621bb256 | <ide><path>test/parallel/test-https-truncate.js
<ide> const test = common.mustCall(function(res) {
<ide> res.on('data', function(chunk) {
<ide> bytes += chunk.length;
<ide> this.pause();
<del> setTimeout(this.resume.bind(this), 1);
<add> setTimeout(() => { this.resume() }, 1);
<ide> });
<ide> }); | 1 |
Javascript | Javascript | avoid a bug in uglifyjs | f90bc4fd50cdf8d9e47fa01fd3428e6b7705bcd3 | <ide><path>d3.js
<ide> try {
<ide> d3_style_setProperty.call(this, name, value + "", priority);
<ide> };
<ide> }
<del>d3 = {version: "2.1.2"}; // semver
<add>d3 = {version: "2.1.3"}; // semver
<ide> var d3_arraySubclass = [].__proto__?
<ide>
<ide> // Until ECMAScript supports array subclassing, prototype injection works well.
<ide> d3.svg.axis = function() {
<ide>
<ide> // Domain.
<ide> var range = d3_scaleExtent(scale.range()),
<del> path = g.selectAll(".domain").data([,]),
<add> path = g.selectAll(".domain").data([0]),
<ide> pathEnter = path.enter().append("svg:path").attr("class", "domain"),
<ide> pathUpdate = transition(path);
<ide>
<ide><path>d3.min.js
<del>(function(){function dq(a,b,c){function i(a,b){var c=a.__domain||(a.__domain=a.domain()),d=a.range().map(function(a){return(a-b)/h});a.domain(c).domain(d.map(a.invert))}var d=Math.pow(2,(dc[2]=a)-c[2]),e=dc[0]=b[0]-d*c[0],f=dc[1]=b[1]-d*c[1],g=d3.event,h=Math.pow(2,a);d3.event={scale:h,translate:[e,f],transform:function(a,b){a&&i(a,e),b&&i(b,f)}};try{dd.apply(de,df)}finally{d3.event=g}g.preventDefault()}function dp(){dh&&(d3.event.stopPropagation(),d3.event.preventDefault(),dh=!1)}function dn(){c$&&(dg&&(dh=!0),dm(),c$=null)}function dm(){c_=null,c$&&(dg=!0,dq(dc[2],d3.svg.mouse(de),c$))}function dl(){var a=d3.svg.touches(de);switch(a.length){case 1:var b=a[0];dq(dc[2],b,da[b.identifier]);break;case 2:var c=a[0],d=a[1],e=[(c[0]+d[0])/2,(c[1]+d[1])/2],f=da[c.identifier],g=da[d.identifier],h=[(f[0]+g[0])/2,(f[1]+g[1])/2,f[2]];dq(Math.log(d3.event.scale)/Math.LN2+f[2],e,h)}}function dk(){var a=d3.svg.touches(de),b=-1,c=a.length,d;while(++b<c)da[(d=a[b]).identifier]=di(d);return a}function dj(){cZ||(cZ=d3.select("body").append("div").style("visibility","hidden").style("top",0).style("height",0).style("width",0).style("overflow-y","scroll").append("div").style("height","2000px").node().parentNode);var a=d3.event,b;try{cZ.scrollTop=1e3,cZ.dispatchEvent(a),b=1e3-cZ.scrollTop}catch(c){b=a.wheelDelta||-a.detail*5}return b*.005}function di(a){return[a[0]-dc[0],a[1]-dc[1],dc[2]]}function cY(){d3.event.stopPropagation(),d3.event.preventDefault()}function cX(){cS&&(cY(),cS=!1)}function cW(){!cO||(cT("dragend"),cO=null,cR&&(cS=!0,cY()))}function cV(){if(!!cO){var a=cO.parentNode;if(!a)return cW();cT("drag"),cY()}}function cU(a){return d3.event.touches?d3.svg.touches(a)[0]:d3.svg.mouse(a)}function cT(a){var b=d3.event,c=cO.parentNode,d=0,e=0;c&&(c=cU(c),d=c[0]-cQ[0],e=c[1]-cQ[1],cQ=c,cR|=d|e);try{d3.event={dx:d,dy:e},cN[a].dispatch.apply(cO,cP)}finally{d3.event=b}b.preventDefault()}function cM(a,b,c){e=[];if(c&&b.length>1){var d=bq(a.domain()),e,f=-1,g=b.length,h=(b[1]-b[0])/++c,i,j;while(++f<g)for(i=c;--i>0;)(j=+b[f]-i*h)>=d[0]&&e.push(j);for(--f,i=0;++i<c&&(j=+b[f]+i*h)<d[1];)e.push(j)}return e}function cL(a,b){a.attr("transform",function(a){return"translate(0,"+b(a)+")"})}function cK(a,b){a.attr("transform",function(a){return"translate("+b(a)+",0)"})}function cG(){return"circle"}function cF(){return 64}function cE(a,b){var c=(a.ownerSVGElement||a).createSVGPoint();if(cD<0&&(window.scrollX||window.scrollY)){var d=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),e=d[0][0].getScreenCTM();cD=!e.f&&!e.e,d.remove()}cD?(c.x=b.pageX,c.y=b.pageY):(c.x=b.clientX,c.y=b.clientY),c=c.matrixTransform(a.getScreenCTM().inverse());return[c.x,c.y]}function cC(a){return function(){var b=a.apply(this,arguments),c=b[0],d=b[1]+bO;return[c*Math.cos(d),c*Math.sin(d)]}}function cB(a){return[a.x,a.y]}function cA(a){return a.endAngle}function cz(a){return a.startAngle}function cy(a){return a.radius}function cx(a){return a.target}function cw(a){return a.source}function cv(a){return function(b,c){return a[c][1]}}function cu(a){return function(b,c){return a[c][0]}}function ct(a){function i(f){if(f.length<1)return null;var i=bV(this,f,b,d),j=bV(this,f,b===c?cu(i):c,d===e?cv(i):e);return"M"+g(a(j),h)+"L"+g(a(i.reverse()),h)+"Z"}var b=bW,c=bW,d=0,e=bX,f="linear",g=bY[f],h=.7;i.x=function(a){if(!arguments.length)return c;b=c=a;return i},i.x0=function(a){if(!arguments.length)return b;b=a;return i},i.x1=function(a){if(!arguments.length)return c;c=a;return i},i.y=function(a){if(!arguments.length)return e;d=e=a;return i},i.y0=function(a){if(!arguments.length)return d;d=a;return i},i.y1=function(a){if(!arguments.length)return e;e=a;return i},i.interpolate=function(a){if(!arguments.length)return f;g=bY[f=a];return i},i.tension=function(a){if(!arguments.length)return h;h=a;return i};return i}function cs(a){var b,c=-1,d=a.length,e,f;while(++c<d)b=a[c],e=b[0],f=b[1]+bO,b[0]=e*Math.cos(f),b[1]=e*Math.sin(f);return a}function cr(a){return a.length<3?bZ(a):a[0]+cd(a,cq(a))}function cq(a){var b=[],c,d,e,f,g=cp(a),h=-1,i=a.length-1;while(++h<i)c=co(a[h],a[h+1]),Math.abs(c)<1e-6?g[h]=g[h+1]=0:(d=g[h]/c,e=g[h+1]/c,f=d*d+e*e,f>9&&(f=c*3/Math.sqrt(f),g[h]=f*d,g[h+1]=f*e));h=-1;while(++h<=i)f=(a[Math.min(i,h+1)][0]-a[Math.max(0,h-1)][0])/(6*(1+g[h]*g[h])),b.push([f||0,g[h]*f||0]);return b}function cp(a){var b=0,c=a.length-1,d=[],e=a[0],f=a[1],g=d[0]=co(e,f);while(++b<c)d[b]=g+(g=co(e=f,f=a[b+1]));d[b]=g;return d}function co(a,b){return(b[1]-a[1])/(b[0]-a[0])}function cn(a,b,c){a.push("C",cj(ck,b),",",cj(ck,c),",",cj(cl,b),",",cj(cl,c),",",cj(cm,b),",",cj(cm,c))}function cj(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function ci(a,b){var c=a.length-1,d=a[0][0],e=a[0][1],f=a[c][0]-d,g=a[c][1]-e,h=-1,i,j;while(++h<=c)i=a[h],j=h/c,i[0]=b*i[0]+(1-b)*(d+j*f),i[1]=b*i[1]+(1-b)*(e+j*g);return cf(a)}function ch(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[cj(cm,g),",",cj(cm,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),cn(b,g,h);return b.join("")}function cg(a){if(a.length<4)return bZ(a);var b=[],c=-1,d=a.length,e,f=[0],g=[0];while(++c<3)e=a[c],f.push(e[0]),g.push(e[1]);b.push(cj(cm,f)+","+cj(cm,g)),--c;while(++c<d)e=a[c],f.shift(),f.push(e[0]),g.shift(),g.push(e[1]),cn(b,f,g);return b.join("")}function cf(a){if(a.length<3)return bZ(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),cn(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),cn(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),cn(b,h,i);return b.join("")}function ce(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function cd(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bZ(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function cc(a,b,c){return a.length<3?bZ(a):a[0]+cd(a,ce(a,b))}function cb(a,b){return a.length<3?bZ(a):a[0]+cd((a.push(a[0]),a),ce([a[a.length-2]].concat(a,[a[1]]),b))}function ca(a,b){return a.length<4?bZ(a):a[1]+cd(a.slice(1,a.length-1),ce(a,b))}function b_(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function b$(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bZ(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bX(a){return a[1]}function bW(a){return a[0]}function bV(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bU(a){function g(d){return d.length<1?null:"M"+e(a(bV(this,d,b,c)),f)}var b=bW,c=bX,d="linear",e=bY[d],f=.7;g.x=function(a){if(!arguments.length)return b;b=a;return g},g.y=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=bY[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g}function bT(a){return a.endAngle}function bS(a){return a.startAngle}function bR(a){return a.outerRadius}function bQ(a){return a.innerRadius}function bN(a,b,c){function g(){d=c.length/(b-a),e=c.length-1;return f}function f(b){return c[Math.max(0,Math.min(e,Math.floor(d*(b-a))))]}var d,e;f.domain=function(c){if(!arguments.length)return[a,b];a=+c[0],b=+c[c.length-1];return g()},f.range=function(a){if(!arguments.length)return c;c=a;return g()},f.copy=function(){return bN(a,b,c)};return g()}function bM(a,b){function e(a){return isNaN(a=+a)?NaN:b[d3.bisect(c,a)]}function d(){var d=0,f=a.length,g=b.length;c=[];while(++d<g)c[d-1]=d3.quantile(a,d/g);return e}var c;e.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending);return d()},e.range=function(a){if(!arguments.length)return b;b=a;return d()},e.quantiles=function(){return c},e.copy=function(){return bM(a,b)};return d()}function bH(a,b){function f(b){return d[((c[b]||(c[b]=a.push(b)))-1)%d.length]}var c,d,e;f.domain=function(d){if(!arguments.length)return a;a=[],c={};var e=-1,g=d.length,h;while(++e<g)c[h=d[e]]||(c[h]=a.push(h));return f[b.t](b.x,b.p)},f.range=function(a){if(!arguments.length)return d;d=a,e=0,b={t:"range",x:a};return f},f.rangePoints=function(c,g){arguments.length<2&&(g=0);var h=c[0],i=c[1],j=(i-h)/(a.length-1+g);d=a.length<2?[(h+i)/2]:d3.range(h+j*g/2,i+j/2,j),e=0,b={t:"rangePoints",x:c,p:g};return f},f.rangeBands=function(c,g){arguments.length<2&&(g=0);var h=c[0],i=c[1],j=(i-h)/(a.length+g);d=d3.range(h+j*g,i,j),e=j*(1-g),b={t:"rangeBands",x:c,p:g};return f},f.rangeRoundBands=function(c,g){arguments.length<2&&(g=0);var h=c[0],i=c[1],j=Math.floor((i-h)/(a.length+g)),k=i-h-(a.length-g)*j;d=d3.range(h+Math.round(k/2),i,j),e=Math.round(j*(1-g)),b={t:"rangeRoundBands",x:c,p:g};return f},f.rangeBand=function(){return e},f.copy=function(){return bH(a,b)};return f.domain(a)}function bG(a){return function(b){return b<0?-Math.pow(-b,a):Math.pow(b,a)}}function bF(a,b){function e(b){return a(c(b))}var c=bG(b),d=bG(1/b);e.invert=function(b){return d(a.invert(b))},e.domain=function(b){if(!arguments.length)return a.domain().map(d);a.domain(b.map(c));return e},e.ticks=function(a){return bx(e.domain(),a)},e.tickFormat=function(a){return by(e.domain(),a)},e.nice=function(){return e.domain(br(e.domain(),bv))},e.exponent=function(a){if(!arguments.length)return b;var f=e.domain();c=bG(b=a),d=bG(1/b);return e.domain(f)},e.copy=function(){return bF(a.copy(),b)};return bu(e,a)}function bE(a){return a.toPrecision(1)}function bD(a){return-Math.log(-a)/Math.LN10}function bC(a){return Math.log(a)/Math.LN10}function bB(a,b){function d(c){return a(b(c))}var c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=e[0]<0?bD:bC,c=b.pow,a.domain(e.map(b));return d},d.nice=function(){a.domain(br(a.domain(),bs));return d},d.ticks=function(){var d=bq(a.domain()),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===bD){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return bE},d.copy=function(){return bB(a.copy(),b)};return bu(d,a)}function bA(a,b,c,d){var e=[],f=[],g=0,h=a.length;while(++g<h)e.push(c(a[g-1],a[g])),f.push(d(b[g-1],b[g]));return function(b){var c=d3.bisect(a,b,1,a.length-1)-1;return f[c](e[c](b))}}function bz(a,b,c,d){var e=c(a[0],a[1]),f=d(b[0],b[1]);return function(a){return f(e(a))}}function by(a,b){return d3.format(",."+Math.max(0,-Math.floor(Math.log(bw(a,b)[2])/Math.LN10+.01))+"f")}function bx(a,b){return d3.range.apply(d3,bw(a,b))}function bw(a,b){var c=bq(a),d=c[1]-c[0],e=Math.pow(10,Math.floor(Math.log(d/b)/Math.LN10)),f=b/d*e;f<=.15?e*=10:f<=.35?e*=5:f<=.75&&(e*=2),c[0]=Math.ceil(c[0]/e)*e,c[1]=Math.floor(c[1]/e)*e+e*.5,c[2]=e;return c}function bv(a){a=Math.pow(10,Math.round(Math.log(a)/Math.LN10)-1);return{floor:function(b){return Math.floor(b/a)*a},ceil:function(b){return Math.ceil(b/a)*a}}}function bu(a,b){a.range=d3.rebind(a,b.range),a.rangeRound=d3.rebind(a,b.rangeRound),a.interpolate=d3.rebind(a,b.interpolate),a.clamp=d3.rebind(a,b.clamp);return a}function bt(a,b,c,d){function h(a){return e(a)}function g(){var g=a.length==2?bz:bA,i=d?H:G;e=g(a,b,i,c),f=g(b,a,i,d3.interpolate);return h}var e,f;h.invert=function(a){return f(a)},h.domain=function(b){if(!arguments.length)return a;a=b.map(Number);return g()},h.range=function(a){if(!arguments.length)return b;b=a;return g()},h.rangeRound=function(a){return h.range(a).interpolate(d3.interpolateRound)},h.clamp=function(a){if(!arguments.length)return d;d=a;return g()},h.interpolate=function(a){if(!arguments.length)return c;c=a;return g()},h.ticks=function(b){return bx(a,b)},h.tickFormat=function(b){return by(a,b)},h.nice=function(){br(a,bv);return g()},h.copy=function(){return bt(a,b,c,d)};return g()}function bs(){return Math}function br(a,b){var c=0,d=a.length-1,e=a[c],f=a[d],g;f<e&&(g=c,c=d,d=g,g=e,e=f,f=g),b=b(f-e),a[c]=b.floor(e),a[d]=b.ceil(f);return a}function bq(a){var b=a[0],c=a[a.length-1];return b<c?[b,c]:[c,b]}function bp(){}function bn(){var a=null,b=bj,c=Infinity;while(b)b.flush?b=a?a.next=b.next:bj=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function bm(){var a,b=Date.now(),c=bj;while(c)a=b-c.then,a>=c.delay&&(c.flush=c.callback(a)),c=c.next;var d=bn()-b;d>24?(isFinite(d)&&(clearTimeout(bl),bl=setTimeout(bm,d)),bk=0):(bk=1,bo(bm))}function bi(a){for(var b=0,c=this.length;b<c;b++)for(var d=this[b],e=0,f=d.length;e<f;e++){var g=d[e];g&&a.call(g=g.node,g.__data__,e,b)}return this}function bd(a){return typeof a=="function"?function(b,c,d){var e=a.call(this,b,c)+"";return d!=e&&d3.interpolate(d,e)}:(a=a+"",function(b,c,d){return d!=a&&d3.interpolate(d,a)})}function bc(a,b){d(a,be);var c={},e=d3.dispatch("start","end"),f=bh,g=Date.now();a.id=b,a.tween=function(b,d){if(arguments.length<2)return c[b];d==null?delete c[b]:c[b]=d;return a},a.ease=function(b){if(!arguments.length)return f;f=typeof b=="function"?b:d3.ease.apply(d3,arguments);return a},a.each=function(b,c){if(arguments.length<2)return bi.call(a,b);e[b].add(c);return a},d3.timer(function(d){a.each(function(h,i,j){function r(){--o.count||delete l.__transition__;return 1}function q(a){if(o.active!==b)return r();var c=(a-m)/n,d=f(c),g=k.length;while(g>0)k[--g].call(l,d);if(c>=1){r(),bg=b,e.end.dispatch.call(l,h,i),bg=0;return 1}}function p(a){if(o.active>b)return r();o.active=b;for(var d in c)(d=c[d].call(l,h,i))&&k.push(d);e.start.dispatch.call(l,h,i),q(a)||d3.timer(q,0,g);return 1}var k=[],l=this,m=a[j][i].delay,n=a[j][i].duration,o=l.__transition__||(l.__transition__={active:0,count:0});++o.count,m<=d?p(d):d3.timer(p,m,g)});return 1},0,g);return a}function ba(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function $(a){d(a,_);return a}function Z(a){return{__data__:a}}function Y(a){return function(){return V(a,this)}}function X(a){return function(){return U(a,this)}}function T(a){d(a,W);return a}function S(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);return a<60?d+(e-d)*a/60:a<180?e:a<240?d+(e-d)*(240-a)/60:d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return I(g(a+120),g(a),g(a-120))}function R(a,b,c){this.h=a,this.s=b,this.l=c}function Q(a,b,c){return new R(a,b,c)}function N(a){var b=parseFloat(a);return a.charAt(a.length-1)==="%"?Math.round(b*2.55):b}function M(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return Q(g,h,i)}function L(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(N(h[0]),N(h[1]),N(h[2]))}}if(i=O[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)==="#"&&(a.length===4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length===7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function K(a){return a<16?"0"+a.toString(16):a.toString(16)}function J(a,b,c){this.r=a,this.g=b,this.b=c}function I(a,b,c){return new J(a,b,c)}function H(a,b){b=b-(a=+a)?1/(b-a):0;return function(c){return Math.max(0,Math.min(1,(c-a)*b))}}function G(a,b){b=b-(a=+a)?1/(b-a):0;return function(c){return(c-a)*b}}function F(a){return a in E||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function C(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function B(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function A(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function z(a){return 1-Math.sqrt(1-a*a)}function y(a){return Math.pow(2,10*(a-1))}function x(a){return 1-Math.cos(a*Math.PI/2)}function w(a){return function(b){return Math.pow(b,a)}}function v(a){return a}function u(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function t(a){return function(b){return 1-a(1-b)}}function s(a){return function(b){return b<=0?0:b>=1?1:a(b)}}function n(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function m(a){return a+""}function j(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function h(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function g(a){return a==null}function f(a){return a.length}function e(){return this}Date.now||(Date.now=function(){return+(new Date)});try{document.createElement("div").style.setProperty("opacity",0,"")}catch(a){var b=CSSStyleDeclaration.prototype,c=b.setProperty;b.setProperty=function(a,b,d){c.call(this,a,b+"",d)}}d3={version:"2.1.2"};var d=[].__proto__?function(a,b){a.__proto__=b}:function(a,b){for(var c in b)a[c]=b[c]};d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:a>=b?0:NaN},d3.descending=function(a,b){return b<a?-1:b>a?1:b>=a?0:NaN},d3.min=function(a,b){var c=-1,d=a.length,e,f;if(arguments.length===1){while(++c<d&&((e=a[c])==null||e!=e))e=undefined;while(++c<d)(f=a[c])!=null&&e>f&&(e=f)}else{while(++c<d&&((e=b.call(a,a[c],c))==null||e!=e))e=undefined;while(++c<d)(f=b.call(a,a[c],c))!=null&&e>f&&(e=f)}return e},d3.max=function(a,b){var c=-1,d=a.length,e,f;if(arguments.length===1){while(++c<d&&((e=a[c])==null||e!=e))e=undefined;while(++c<d)(f=a[c])!=null&&f>e&&(e=f)}else{while(++c<d&&((e=b.call(a,a[c],c))==null||e!=e))e=undefined;while(++c<d)(f=b.call(a,a[c],c))!=null&&f>e&&(e=f)}return e},d3.sum=function(a,b){var c=0,d=a.length,e,f=-1;if(arguments.length===1)while(++f<d)isNaN(e=+a[f])||(c+=e);else while(++f<d)isNaN(e=+b.call(a,a[f],f))||(c+=e);return c},d3.quantile=function(a,b){var c=(a.length-1)*b+1,d=Math.floor(c),e=a[d-1],f=c-d;return f?e+f*(a[d]-e):e},d3.zip=function(){if(!(e=arguments.length))return[];for(var a=-1,b=d3.min(arguments,f),c=Array(b);++a<b;)for(var d=-1,e,g=c[a]=Array(e);++d<e;)g[d]=arguments[d][a];return c},d3.bisectLeft=function(a,b,c,d){arguments.length<3&&(c=0),arguments.length<4&&(d=a.length);while(c<d){var e=c+d>>1;a[e]<b?c=e+1:d=e}return c},d3.bisect=d3.bisectRight=function(a,b,c,d){arguments.length<3&&(c=0),arguments.length<4&&(d=a.length);while(c<d){var e=c+d>>1;b<a[e]?d=e:c=e+1}return c},d3.first=function(a,b){var c=0,d=a.length,e=a[0],f;arguments.length===1&&(b=d3.ascending);while(++c<d)b.call(a,e,f=a[c])>0&&(e=f);return e},d3.last=function(a,b){var c=0,d=a.length,e=a[0],f;arguments.length===1&&(b=d3.ascending);while(++c<d)b.call(a,e,f=a[c])<=0&&(e=f);return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.permute=function(a,b){var c=[],d=-1,e=b.length;while(++d<e)c[d]=a[b[d]];return c},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],e,f=-1,h=a.length;arguments.length<2&&(b=g);while(++f<h)b.call(d,e=a[f],f)?d=[]:(d.length||c.push(d),d.push(e));return c},d3.range=function(a,b,c){arguments.length<3&&(c=1,arguments.length<2&&(b=a,a=0));if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(i,"\\$&")};var i=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;d3.round=function(a,b){return b?Math.round(a*Math.pow(10,b))*Math.pow(10,-b):Math.round(a)},d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState===4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=j(c);return b},d3.format=function(a){var b=k.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9],j=!1,o=!1;h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4)));switch(i){case"n":g=!0,i="g";break;case"%":j=!0,i="f";break;case"p":j=!0,i="r";break;case"d":o=!0,h="0"}i=l[i]||m;return function(a){var b=j?a*100:+a,k=b<0&&(b=-b)?"−":d;if(o&&b%1)return"";a=i(b,h);if(e){var l=a.length+k.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=n(a)),a=k+a}else{g&&(a=n(a)),a=k+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}j&&(a+="%");return a}};var k=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l={g:function(a,b){return a.toPrecision(b)},e:function(a,b){return a.toExponential(b)},f:function(a,b){return a.toFixed(b)},r:function(a,b){var c=1+Math.floor(1e-15+Math.log(a)/Math.LN10);return d3.round(a,b-c).toFixed(Math.max(0,Math.min(20,b-c)))}},o=w(2),p=w(3),q={linear:function(){return v},poly:w,quad:function(){return o},cubic:function(){return p},sin:function(){return x},exp:function(){return y},circle:function(){return z},elastic:A,back:B,bounce:function(){return C}},r={"in":function(a){return a},out:t,"in-out":u,"out-in":function(a){return u(t(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return s(r[d](q[c].apply(null,Array.prototype.slice.call(arguments,1))))},d3.event=null,d3.interpolate=function(a,b){var c=d3.interpolators.length,d;while(--c>=0&&!(d=d3.interpolators[c](a,b)));return d},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;D.lastIndex=0;for(d=0;c=D.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=D.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=D.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;return h.length===1?h[0]==null?i[0].x:function(){return b}:function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return S(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=F(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var D=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,E={background:1,fill:1,stroke:1};d3.interpolators=[d3.interpolateObject,function(a,b){return b instanceof Array&&d3.interpolateArray(a,b)},function(a,b){return typeof b=="string"&&d3.interpolateString(String(a),b)},function(a,b){return(typeof b=="string"?b in O||/^(#|rgb\(|hsl\()/.test(b):b instanceof J||b instanceof R)&&d3.interpolateRgb(String(a),b)},function(a,b){return typeof b=="number"&&d3.interpolateNumber(+a,b)}],d3.rgb=function(a,b,c){return arguments.length===1?L(""+a,I,S):I(~~a,~~b,~~c)},J.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);var b=this.r,c=this.g,d=this.b,e=30;if(!b&&!c&&!d)return I(e,e,e);b&&b<e&&(b=e),c&&c<e&&(c=e),d&&d<e&&(d=e);return I(Math.min(255,Math.floor(b/a)),Math.min(255,Math.floor(c/a)),Math.min(255,Math.floor(d/a)))},J.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return I(Math.max(0,Math.floor(a*this.r)),Math.max(0,Math.floor(a*this.g)),Math.max(0,Math.floor(a*this.b)))},J.prototype.hsl=function(){return M(this.r,this.g,this.b)},J.prototype.toString=function(){return"#"+K(this.r)+K(this.g)+K(this.b)};var O={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var P in O)O[P]=L(O[P],I,S);d3.hsl=function(a,b,c){return arguments.length===1?L(""+a,M,Q):Q(+a,+b,+c)},R.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);return Q(this.h,this.s,this.l/a)},R.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return Q(this.h,this.s,a*this.l)},R.prototype.rgb=function(){return S(this.h,this.s,this.l)},R.prototype.toString=function(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"};var U=function(a,b){return b.querySelector(a)},V=function(a,b){return b.querySelectorAll(a)};typeof Sizzle=="function"&&(U=function(a,b){return Sizzle(a,b)[0]},V=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var W=[];d3.selection=function(){return bb},d3.selection.prototype=W,W.select=function(a){var b=[],c,d,e,f;typeof a!="function"&&(a=X(a));for(var g=-1,h=this.length;++g<h;){b.push(c=[]),c.parentNode=(e=this[g]).parentNode;for(var i=-1,j=e.length;++i<j;)(f=e[i])?(c.push(d=a.call(f,f.__data__,i)),d&&"__data__"in f&&(d.__data__=f.__data__)):c.push(null)}return T(b)},W.selectAll=function(a){var b=[],c,d;typeof a!="function"&&(a=Y(a));for(var e=-1,f=this.length;++e<f;)for(var g=this[e],h=-1,i=g.length;++h<i;)if(d=g[h])b.push(c=a.call(d,d.__data__,h)),c.parentNode=d;return T(b)},W.attr=function(a,b){function i(){var c=b.apply(this,arguments);c==null?this.removeAttributeNS(a.space,a.local):this.setAttributeNS(a.space,a.local,c)}function h(){var c=b.apply(this,arguments);c==null?this.removeAttribute(a):this.setAttribute(a,c)}function g(){this.setAttributeNS(a.space,a.local,b)}function f(){this.setAttribute(a,b)}function e(){this.removeAttributeNS(a.space,a.local)}function d(){this.removeAttribute(a)}a=d3.ns.qualify(a);if(arguments.length<2){var c=this.node();return a.local?c.getAttributeNS(a.space,a.local):c.getAttribute(a)}return this.each(b==null?a.local?e:d:typeof b=="function"?a.local?i:h:a.local?g:f)},W.classed=function(a,b){function i(){(b.apply(this,arguments)?f:g).call(this)}function g(){if(b=this.classList)return b.remove(a);var b=this.className,d=b.baseVal!=null,e=d?b.baseVal:b;e=h(e.replace(c," ")),d?b.baseVal=e:this.className=e}function f(){if(b=this.classList)return b.add(a);var b=this.className,d=b.baseVal!=null,e=d?b.baseVal:b;c.lastIndex=0,c.test(e)||(e=h(e+" "+a),d?b.baseVal=e:this.className=e)}var c=new RegExp("(^|\\s+)"+d3.requote(a)+"(\\s+|$)","g");if(arguments.length<2){var d=this.node();if(e=d.classList)return e.contains
<del>(a);var e=d.className;c.lastIndex=0;return c.test(e.baseVal!=null?e.baseVal:e)}return this.each(typeof b=="function"?i:b?f:g)},W.style=function(a,b,c){function f(){var d=b.apply(this,arguments);d==null?this.style.removeProperty(a):this.style.setProperty(a,d,c)}function e(){this.style.setProperty(a,b,c)}function d(){this.style.removeProperty(a)}arguments.length<3&&(c="");return arguments.length<2?window.getComputedStyle(this.node(),null).getPropertyValue(a):this.each(b==null?d:typeof b=="function"?f:e)},W.property=function(a,b){function e(){var c=b.apply(this,arguments);c==null?delete this[a]:this[a]=c}function d(){this[a]=b}function c(){delete this[a]}return arguments.length<2?this.node()[a]:this.each(b==null?c:typeof b=="function"?e:d)},W.text=function(a){return arguments.length<1?this.node().textContent:this.each(typeof a=="function"?function(){this.textContent=a.apply(this,arguments)}:function(){this.textContent=a})},W.html=function(a){return arguments.length<1?this.node().innerHTML:this.each(typeof a=="function"?function(){this.innerHTML=a.apply(this,arguments)}:function(){this.innerHTML=a})},W.append=function(a){function c(){return this.appendChild(document.createElementNS(a.space,a.local))}function b(){return this.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return this.select(a.local?c:b)},W.insert=function(a,b){function d(){return this.insertBefore(document.createElementNS(a.space,a.local),U(b,this))}function c(){return this.insertBefore(document.createElement(a),U(b,this))}a=d3.ns.qualify(a);return this.select(a.local?d:c)},W.remove=function(){return this.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},W.data=function(a,b){function f(a,f){var g,h=a.length,i=f.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(b){var q={},r=[],s,t=f.length;for(g=-1;++g<h;)s=b.call(o=a[g],o.__data__,g),s in q?n[t++]=o:q[s]=o,r.push(s);for(g=-1;++g<i;)o=q[s=b.call(f,p=f[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=Z(p),l[g]=n[g]=null),delete q[s];for(g=-1;++g<h;)r[g]in q&&(n[g]=a[g])}else{for(g=-1;++g<j;)o=a[g],p=f[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=Z(p),l[g]=n[g]=null);for(;g<i;++g)m[g]=Z(f[g]),l[g]=n[g]=null;for(;g<k;++g)n[g]=a[g],m[g]=l[g]=null}m.update=l,m.parentNode=l.parentNode=n.parentNode=a.parentNode,c.push(m),d.push(l),e.push(n)}var c=[],d=[],e=[],g=-1,h=this.length,i;if(typeof a=="function")while(++g<h)f(i=this[g],a.call(i,i.parentNode.__data__,g));else while(++g<h)f(i=this[g],a);var j=T(d);j.enter=function(){return $(c)},j.exit=function(){return T(e)};return j};var _=[];_.append=W.append,_.insert=W.insert,_.empty=W.empty,_.select=function(a){var b=[],c,d,e,f,g;for(var h=-1,i=this.length;++h<i;){e=(f=this[h]).update,b.push(c=[]),c.parentNode=f.parentNode;for(var j=-1,k=f.length;++j<k;)(g=f[j])?(c.push(e[j]=d=a.call(f.parentNode,g.__data__,j)),d.__data__=g.__data__):c.push(null)}return T(b)},W.filter=function(a){var b=[],c,d,e;for(var f=0,g=this.length;f<g;f++){b.push(c=[]),c.parentNode=(d=this[f]).parentNode;for(var h=0,i=d.length;h<i;h++)(e=d[h])&&a.call(e,e.__data__,h)&&c.push(e)}return T(b)},W.map=function(a){return this.each(function(){this.__data__=a.apply(this,arguments)})},W.sort=function(a){a=ba.apply(this,arguments);for(var b=0,c=this.length;b<c;b++)for(var d=this[b].sort(a),e=1,f=d.length,g=d[0];e<f;e++){var h=d[e];h&&(g&&g.parentNode.insertBefore(h,g.nextSibling),g=h)}return this},W.on=function(a,b,c){arguments.length<3&&(c=!1);var d="__on"+a,e=a.indexOf(".");e>0&&(a=a.substring(0,e));return arguments.length<2?(e=this.node()[d])&&e._:this.each(function(e,f){function h(a){var c=d3.event;d3.event=a;try{b.call(g,g.__data__,f)}finally{d3.event=c}}var g=this;g[d]&&g.removeEventListener(a,g[d],c),b&&g.addEventListener(a,g[d]=h,c),h._=b})},W.each=function(a){for(var b=-1,c=this.length;++b<c;)for(var d=this[b],e=-1,f=d.length;++e<f;){var g=d[e];g&&a.call(g,g.__data__,e,b)}return this},W.call=function(a){a.apply(this,(arguments[0]=this,arguments));return this},W.empty=function(){return!this.node()},W.node=function(a){for(var b=0,c=this.length;b<c;b++)for(var d=this[b],e=0,f=d.length;e<f;e++){var g=d[e];if(g)return g}return null},W.transition=function(){var a=[],b,c;for(var d=-1,e=this.length;++d<e;){a.push(b=[]);for(var f=this[d],g=-1,h=f.length;++g<h;)b.push((c=f[g])?{node:c,delay:0,duration:250}:null)}return bc(a,bg||++bf)};var bb=T([[document]]);bb[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?bb.select(a):T([[a]])},d3.selectAll=function(a){return typeof a=="string"?bb.selectAll(a):T([a])};var be=[],bf=0,bg=0,bh=d3.ease("cubic-in-out");be.call=W.call,d3.transition=function(){return bb.transition()},d3.transition.prototype=be,be.select=function(a){var b=[],c,d,e;typeof a!="function"&&(a=X(a));for(var f=-1,g=this.length;++f<g;){b.push(c=[]);for(var h=this[f],i=-1,j=h.length;++i<j;)(e=h[i])&&(d=a.call(e.node,e.node.__data__,i))?("__data__"in e.node&&(d.__data__=e.node.__data__),c.push({node:d,delay:e.delay,duration:e.duration})):c.push(null)}return bc(b,this.id).ease(this.ease())},be.selectAll=function(a){var b=[],c,d;typeof a!="function"&&(a=Y(a));for(var e=-1,f=this.length;++e<f;)for(var g=this[e],h=-1,i=g.length;++h<i;)if(d=g[h]){b.push(c=a.call(d.node,d.node.__data__,h));for(var j=-1,k=c.length;++j<k;)c[j]={node:c[j],delay:d.delay,duration:d.duration}}return bc(b,this.id).ease(this.ease())},be.attr=function(a,b){return this.attrTween(a,bd(b))},be.attrTween=function(a,b){function d(c,d){var e=b.call(this,c,d,this.getAttributeNS(a.space,a.local));return e&&function(b){this.setAttributeNS(a.space,a.local,e(b))}}function c(c,d){var e=b.call(this,c,d,this.getAttribute(a));return e&&function(b){this.setAttribute(a,e(b))}}a=d3.ns.qualify(a);return this.tween("attr."+a,a.local?d:c)},be.style=function(a,b,c){arguments.length<3&&(c="");return this.styleTween(a,bd(b),c)},be.styleTween=function(a,b,c){arguments.length<3&&(c="");return this.tween("style."+a,function(d,e){var f=b.call(this,d,e,window.getComputedStyle(this,null).getPropertyValue(a));return f&&function(b){this.style.setProperty(a,f(b),c)}})},be.text=function(a){return this.tween("text",function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a})},be.remove=function(){return this.each("end",function(){var a;!this.__transition__&&(a=this.parentNode)&&a.removeChild(this)})},be.delay=function(a){var b=this;return b.each(typeof a=="function"?function(c,d,e){b[e][d].delay=+a.apply(this,arguments)}:(a=+a,function(c,d,e){b[e][d].delay=a}))},be.duration=function(a){var b=this;return b.each(typeof a=="function"?function(c,d,e){b[e][d].duration=+a.apply(this,arguments)}:(a=+a,function(c,d,e){b[e][d].duration=a}))},be.transition=function(){return this.select(e)};var bj=null,bk,bl;d3.timer=function(a,b,c){var d=!1,e,f=bj;if(arguments.length<3){if(arguments.length<2)b=0;else if(!isFinite(b))return;c=Date.now()}while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||(bj={callback:a,then:c,delay:b,next:bj}),bk||(bl=clearTimeout(bl),bk=1,bo(bm))},d3.timer.flush=function(){var a,b=Date.now(),c=bj;while(c)a=b-c.then,c.delay||(c.flush=c.callback(a)),c=c.next;bn()};var bo=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){return bt([0,1],[0,1],d3.interpolate,!1)},d3.scale.log=function(){return bB(d3.scale.linear(),bC)},bC.pow=function(a){return Math.pow(10,a)},bD.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){return bF(d3.scale.linear(),1)},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){return bH([],{t:"range",x:[]})},d3.scale.category10=function(){return d3.scale.ordinal().range(bI)},d3.scale.category20=function(){return d3.scale.ordinal().range(bJ)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bK)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bL)};var bI=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bJ=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bK=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bL=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){return bM([],[])},d3.scale.quantize=function(){return bN(0,1,[0,1])},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bO,h=d.apply(this,arguments)+bO,i=(h<g&&(i=g,g=h,h=i),h-g),j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bP?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,0 0,"+ -e+"A"+e+","+e+" 0 1,0 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=bQ,b=bR,c=bS,d=bT;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bO;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bO=-Math.PI/2,bP=2*Math.PI-1e-6;d3.svg.line=function(){return bU(Object)};var bY={linear:bZ,"step-before":b$,"step-after":b_,basis:cf,"basis-open":cg,"basis-closed":ch,bundle:ci,cardinal:cc,"cardinal-open":ca,"cardinal-closed":cb,monotone:cr},ck=[0,2/3,1/3,0],cl=[0,1/3,2/3,0],cm=[0,1/6,2/3,1/6];d3.svg.line.radial=function(){var a=bU(cs);a.radius=a.x,delete a.x,a.angle=a.y,delete a.y;return a},d3.svg.area=function(){return ct(Object)},d3.svg.area.radial=function(){var a=ct(cs);a.radius=a.x,delete a.x,a.innerRadius=a.x0,delete a.x0,a.outerRadius=a.x1,delete a.x1,a.angle=a.y,delete a.y,a.startAngle=a.y0,delete a.y0,a.endAngle=a.y1,delete a.y1;return a},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bO,k=e.call(a,h,g)+bO;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=cw,b=cx,c=cy,d=bS,e=bT;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=cw,b=cx,c=cB;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.diagonal.radial=function(){var a=d3.svg.diagonal(),b=cB,c=a.projection;a.projection=function(a){return arguments.length?c(cC(b=a)):b};return a},d3.svg.mouse=function(a){return cE(a,d3.event)};var cD=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.touches=function(a){var b=d3.event.touches;return b?Array.prototype.map.call(b,function(b){var c=cE(a,b);c.identifier=b.identifier;return c}):[]},d3.svg.symbol=function(){function c(c,d){return(cH[a.call(this,c,d)]||cH.circle)(b.call(this,c,d))}var a=cG,b=cF;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c};var cH={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*cJ)),c=b*cJ;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/cI),c=b*cI/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/cI),c=b*cI/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}};d3.svg.symbolTypes=d3.keys(cH);var cI=Math.sqrt(3),cJ=Math.tan(30*Math.PI/180);d3.svg.axis=function(){function j(j){j.each(function(k,l,m){function F(a){return j.delay?a.transition().delay(j[m][l].delay).duration(j[m][l].duration).ease(j.ease()):a}var n=d3.select(this),o=a.ticks.apply(a,g),p=h==null?a.tickFormat.apply(a,g):h,q=cM(a,o,i),r=n.selectAll(".minor").data(q,String),s=r.enter().insert("svg:line","g").attr("class","tick minor").style("opacity",1e-6),t=F(r.exit()).style("opacity",1e-6).remove(),u=F(r).style("opacity",1),v=n.selectAll("g").data(o,String),w=v.enter().insert("svg:g","path").style("opacity",1e-6),x=F(v.exit()).style("opacity",1e-6).remove(),y=F(v).style("opacity",1),z,A=bq(a.range()),B=n.selectAll(".domain").data([]),C=B.enter().append("svg:path").attr("class","domain"),D=F(B),E=this.__chart__||a;this.__chart__=a.copy(),w.append("svg:line").attr("class","tick"),w.append("svg:text"),y.select("text").text(p);switch(b){case"bottom":z=cK,u.attr("y2",d),w.select("text").attr("dy",".71em").attr("text-anchor","middle"),y.select("line").attr("y2",c),y.select("text").attr("y",Math.max(c,0)+f),D.attr("d","M"+A[0]+","+e+"V0H"+A[1]+"V"+e);break;case"top":z=cK,u.attr("y2",-d),w.select("text").attr("text-anchor","middle"),y.select("line").attr("y2",-c),y.select("text").attr("y",-(Math.max(c,0)+f)),D.attr("d","M"+A[0]+","+ -e+"V0H"+A[1]+"V"+ -e);break;case"left":z=cL,u.attr("x2",-d),w.select("text").attr("dy",".32em").attr("text-anchor","end"),y.select("line").attr("x2",-c),y.select("text").attr("x",-(Math.max(c,0)+f)),D.attr("d","M"+ -e+","+A[0]+"H0V"+A[1]+"H"+ -e);break;case"right":z=cL,u.attr("x2",d),w.select("text").attr("dy",".32em"),y.select("line").attr("x2",c),y.select("text").attr("x",Math.max(c,0)+f),D.attr("d","M"+e+","+A[0]+"H0V"+A[1]+"H"+e)}w.call(z,E),y.call(z,a),x.call(z,a),s.call(z,E),u.call(z,a),t.call(z,a)})}var a=d3.scale.linear(),b="bottom",c=6,d=6,e=6,f=3,g=[10],h,i=0;j.scale=function(b){if(!arguments.length)return a;a=b;return j},j.orient=function(a){if(!arguments.length)return b;b=a;return j},j.ticks=function(){if(!arguments.length)return g;g=arguments;return j},j.tickFormat=function(a){if(!arguments.length)return h;h=a;return j},j.tickSize=function(a,b,f){if(!arguments.length)return c;var g=arguments.length-1;c=+a,d=g>1?+b:c,e=g>0?+arguments[g]:c;return j},j.tickPadding=function(a){if(!arguments.length)return f;f=+a;return j},j.tickSubdivide=function(a){if(!arguments.length)return i;i=+a;return j};return j},d3.behavior={},d3.behavior.drag=function(){function d(){c.apply(this,arguments),cT("dragstart")}function c(){cN=a,cQ=cU((cO=this).parentNode),cR=0,cP=arguments}function b(){this.on("mousedown.drag",d).on("touchstart.drag",d),d3.select(window).on("mousemove.drag",cV).on("touchmove.drag",cV).on("mouseup.drag",cW,!0).on("touchend.drag",cW,!0).on("click.drag",cX,!0)}var a=d3.dispatch("drag","dragstart","dragend");b.on=function(c,d){a[c].add(d);return b};return b};var cN,cO,cP,cQ,cR,cS;d3.behavior.zoom=function(){function h(){d.apply(this,arguments);var b=dk(),c,e=Date.now();b.length===1&&e-db<300&&dq(1+Math.floor(a[2]),c=b[0],da[c.identifier]),db=e}function g(){d.apply(this,arguments);var b=d3.svg.mouse(de);dq(d3.event.shiftKey?Math.ceil(a[2]-1):Math.floor(a[2]+1),b,di(b))}function f(){d.apply(this,arguments),c_||(c_=di(d3.svg.mouse(de))),dq(dj()+a[2],d3.svg.mouse(de),c_)}function e(){d.apply(this,arguments),c$=di(d3.svg.mouse(de)),dg=!1,d3.event.preventDefault(),window.focus()}function d(){dc=a,dd=b.zoom.dispatch,de=this,df=arguments}function c(){this.on("mousedown.zoom",e).on("mousewheel.zoom",f).on("DOMMouseScroll.zoom",f).on("dblclick.zoom",g).on("touchstart.zoom",h),d3.select(window).on("mousemove.zoom",dm).on("mouseup.zoom",dn).on("touchmove.zoom",dl).on("touchend.zoom",dk).on("click.zoom",dp,!0)}var a=[0,0,0],b=d3.dispatch("zoom");c.on=function(a,d){b[a].add(d);return c};return c};var cZ,c$,c_,da={},db=0,dc,dd,de,df,dg,dh})()
<ide>\ No newline at end of file
<add>(function(){function dq(a,b,c){function i(a,b){var c=a.__domain||(a.__domain=a.domain()),d=a.range().map(function(a){return(a-b)/h});a.domain(c).domain(d.map(a.invert))}var d=Math.pow(2,(dc[2]=a)-c[2]),e=dc[0]=b[0]-d*c[0],f=dc[1]=b[1]-d*c[1],g=d3.event,h=Math.pow(2,a);d3.event={scale:h,translate:[e,f],transform:function(a,b){a&&i(a,e),b&&i(b,f)}};try{dd.apply(de,df)}finally{d3.event=g}g.preventDefault()}function dp(){dh&&(d3.event.stopPropagation(),d3.event.preventDefault(),dh=!1)}function dn(){c$&&(dg&&(dh=!0),dm(),c$=null)}function dm(){c_=null,c$&&(dg=!0,dq(dc[2],d3.svg.mouse(de),c$))}function dl(){var a=d3.svg.touches(de);switch(a.length){case 1:var b=a[0];dq(dc[2],b,da[b.identifier]);break;case 2:var c=a[0],d=a[1],e=[(c[0]+d[0])/2,(c[1]+d[1])/2],f=da[c.identifier],g=da[d.identifier],h=[(f[0]+g[0])/2,(f[1]+g[1])/2,f[2]];dq(Math.log(d3.event.scale)/Math.LN2+f[2],e,h)}}function dk(){var a=d3.svg.touches(de),b=-1,c=a.length,d;while(++b<c)da[(d=a[b]).identifier]=di(d);return a}function dj(){cZ||(cZ=d3.select("body").append("div").style("visibility","hidden").style("top",0).style("height",0).style("width",0).style("overflow-y","scroll").append("div").style("height","2000px").node().parentNode);var a=d3.event,b;try{cZ.scrollTop=1e3,cZ.dispatchEvent(a),b=1e3-cZ.scrollTop}catch(c){b=a.wheelDelta||-a.detail*5}return b*.005}function di(a){return[a[0]-dc[0],a[1]-dc[1],dc[2]]}function cY(){d3.event.stopPropagation(),d3.event.preventDefault()}function cX(){cS&&(cY(),cS=!1)}function cW(){!cO||(cT("dragend"),cO=null,cR&&(cS=!0,cY()))}function cV(){if(!!cO){var a=cO.parentNode;if(!a)return cW();cT("drag"),cY()}}function cU(a){return d3.event.touches?d3.svg.touches(a)[0]:d3.svg.mouse(a)}function cT(a){var b=d3.event,c=cO.parentNode,d=0,e=0;c&&(c=cU(c),d=c[0]-cQ[0],e=c[1]-cQ[1],cQ=c,cR|=d|e);try{d3.event={dx:d,dy:e},cN[a].dispatch.apply(cO,cP)}finally{d3.event=b}b.preventDefault()}function cM(a,b,c){e=[];if(c&&b.length>1){var d=bq(a.domain()),e,f=-1,g=b.length,h=(b[1]-b[0])/++c,i,j;while(++f<g)for(i=c;--i>0;)(j=+b[f]-i*h)>=d[0]&&e.push(j);for(--f,i=0;++i<c&&(j=+b[f]+i*h)<d[1];)e.push(j)}return e}function cL(a,b){a.attr("transform",function(a){return"translate(0,"+b(a)+")"})}function cK(a,b){a.attr("transform",function(a){return"translate("+b(a)+",0)"})}function cG(){return"circle"}function cF(){return 64}function cE(a,b){var c=(a.ownerSVGElement||a).createSVGPoint();if(cD<0&&(window.scrollX||window.scrollY)){var d=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),e=d[0][0].getScreenCTM();cD=!e.f&&!e.e,d.remove()}cD?(c.x=b.pageX,c.y=b.pageY):(c.x=b.clientX,c.y=b.clientY),c=c.matrixTransform(a.getScreenCTM().inverse());return[c.x,c.y]}function cC(a){return function(){var b=a.apply(this,arguments),c=b[0],d=b[1]+bO;return[c*Math.cos(d),c*Math.sin(d)]}}function cB(a){return[a.x,a.y]}function cA(a){return a.endAngle}function cz(a){return a.startAngle}function cy(a){return a.radius}function cx(a){return a.target}function cw(a){return a.source}function cv(a){return function(b,c){return a[c][1]}}function cu(a){return function(b,c){return a[c][0]}}function ct(a){function i(f){if(f.length<1)return null;var i=bV(this,f,b,d),j=bV(this,f,b===c?cu(i):c,d===e?cv(i):e);return"M"+g(a(j),h)+"L"+g(a(i.reverse()),h)+"Z"}var b=bW,c=bW,d=0,e=bX,f="linear",g=bY[f],h=.7;i.x=function(a){if(!arguments.length)return c;b=c=a;return i},i.x0=function(a){if(!arguments.length)return b;b=a;return i},i.x1=function(a){if(!arguments.length)return c;c=a;return i},i.y=function(a){if(!arguments.length)return e;d=e=a;return i},i.y0=function(a){if(!arguments.length)return d;d=a;return i},i.y1=function(a){if(!arguments.length)return e;e=a;return i},i.interpolate=function(a){if(!arguments.length)return f;g=bY[f=a];return i},i.tension=function(a){if(!arguments.length)return h;h=a;return i};return i}function cs(a){var b,c=-1,d=a.length,e,f;while(++c<d)b=a[c],e=b[0],f=b[1]+bO,b[0]=e*Math.cos(f),b[1]=e*Math.sin(f);return a}function cr(a){return a.length<3?bZ(a):a[0]+cd(a,cq(a))}function cq(a){var b=[],c,d,e,f,g=cp(a),h=-1,i=a.length-1;while(++h<i)c=co(a[h],a[h+1]),Math.abs(c)<1e-6?g[h]=g[h+1]=0:(d=g[h]/c,e=g[h+1]/c,f=d*d+e*e,f>9&&(f=c*3/Math.sqrt(f),g[h]=f*d,g[h+1]=f*e));h=-1;while(++h<=i)f=(a[Math.min(i,h+1)][0]-a[Math.max(0,h-1)][0])/(6*(1+g[h]*g[h])),b.push([f||0,g[h]*f||0]);return b}function cp(a){var b=0,c=a.length-1,d=[],e=a[0],f=a[1],g=d[0]=co(e,f);while(++b<c)d[b]=g+(g=co(e=f,f=a[b+1]));d[b]=g;return d}function co(a,b){return(b[1]-a[1])/(b[0]-a[0])}function cn(a,b,c){a.push("C",cj(ck,b),",",cj(ck,c),",",cj(cl,b),",",cj(cl,c),",",cj(cm,b),",",cj(cm,c))}function cj(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function ci(a,b){var c=a.length-1,d=a[0][0],e=a[0][1],f=a[c][0]-d,g=a[c][1]-e,h=-1,i,j;while(++h<=c)i=a[h],j=h/c,i[0]=b*i[0]+(1-b)*(d+j*f),i[1]=b*i[1]+(1-b)*(e+j*g);return cf(a)}function ch(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[cj(cm,g),",",cj(cm,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),cn(b,g,h);return b.join("")}function cg(a){if(a.length<4)return bZ(a);var b=[],c=-1,d=a.length,e,f=[0],g=[0];while(++c<3)e=a[c],f.push(e[0]),g.push(e[1]);b.push(cj(cm,f)+","+cj(cm,g)),--c;while(++c<d)e=a[c],f.shift(),f.push(e[0]),g.shift(),g.push(e[1]),cn(b,f,g);return b.join("")}function cf(a){if(a.length<3)return bZ(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),cn(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),cn(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),cn(b,h,i);return b.join("")}function ce(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function cd(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bZ(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function cc(a,b,c){return a.length<3?bZ(a):a[0]+cd(a,ce(a,b))}function cb(a,b){return a.length<3?bZ(a):a[0]+cd((a.push(a[0]),a),ce([a[a.length-2]].concat(a,[a[1]]),b))}function ca(a,b){return a.length<4?bZ(a):a[1]+cd(a.slice(1,a.length-1),ce(a,b))}function b_(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function b$(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bZ(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bX(a){return a[1]}function bW(a){return a[0]}function bV(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bU(a){function g(d){return d.length<1?null:"M"+e(a(bV(this,d,b,c)),f)}var b=bW,c=bX,d="linear",e=bY[d],f=.7;g.x=function(a){if(!arguments.length)return b;b=a;return g},g.y=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=bY[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g}function bT(a){return a.endAngle}function bS(a){return a.startAngle}function bR(a){return a.outerRadius}function bQ(a){return a.innerRadius}function bN(a,b,c){function g(){d=c.length/(b-a),e=c.length-1;return f}function f(b){return c[Math.max(0,Math.min(e,Math.floor(d*(b-a))))]}var d,e;f.domain=function(c){if(!arguments.length)return[a,b];a=+c[0],b=+c[c.length-1];return g()},f.range=function(a){if(!arguments.length)return c;c=a;return g()},f.copy=function(){return bN(a,b,c)};return g()}function bM(a,b){function e(a){return isNaN(a=+a)?NaN:b[d3.bisect(c,a)]}function d(){var d=0,f=a.length,g=b.length;c=[];while(++d<g)c[d-1]=d3.quantile(a,d/g);return e}var c;e.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending);return d()},e.range=function(a){if(!arguments.length)return b;b=a;return d()},e.quantiles=function(){return c},e.copy=function(){return bM(a,b)};return d()}function bH(a,b){function f(b){return d[((c[b]||(c[b]=a.push(b)))-1)%d.length]}var c,d,e;f.domain=function(d){if(!arguments.length)return a;a=[],c={};var e=-1,g=d.length,h;while(++e<g)c[h=d[e]]||(c[h]=a.push(h));return f[b.t](b.x,b.p)},f.range=function(a){if(!arguments.length)return d;d=a,e=0,b={t:"range",x:a};return f},f.rangePoints=function(c,g){arguments.length<2&&(g=0);var h=c[0],i=c[1],j=(i-h)/(a.length-1+g);d=a.length<2?[(h+i)/2]:d3.range(h+j*g/2,i+j/2,j),e=0,b={t:"rangePoints",x:c,p:g};return f},f.rangeBands=function(c,g){arguments.length<2&&(g=0);var h=c[0],i=c[1],j=(i-h)/(a.length+g);d=d3.range(h+j*g,i,j),e=j*(1-g),b={t:"rangeBands",x:c,p:g};return f},f.rangeRoundBands=function(c,g){arguments.length<2&&(g=0);var h=c[0],i=c[1],j=Math.floor((i-h)/(a.length+g)),k=i-h-(a.length-g)*j;d=d3.range(h+Math.round(k/2),i,j),e=Math.round(j*(1-g)),b={t:"rangeRoundBands",x:c,p:g};return f},f.rangeBand=function(){return e},f.copy=function(){return bH(a,b)};return f.domain(a)}function bG(a){return function(b){return b<0?-Math.pow(-b,a):Math.pow(b,a)}}function bF(a,b){function e(b){return a(c(b))}var c=bG(b),d=bG(1/b);e.invert=function(b){return d(a.invert(b))},e.domain=function(b){if(!arguments.length)return a.domain().map(d);a.domain(b.map(c));return e},e.ticks=function(a){return bx(e.domain(),a)},e.tickFormat=function(a){return by(e.domain(),a)},e.nice=function(){return e.domain(br(e.domain(),bv))},e.exponent=function(a){if(!arguments.length)return b;var f=e.domain();c=bG(b=a),d=bG(1/b);return e.domain(f)},e.copy=function(){return bF(a.copy(),b)};return bu(e,a)}function bE(a){return a.toPrecision(1)}function bD(a){return-Math.log(-a)/Math.LN10}function bC(a){return Math.log(a)/Math.LN10}function bB(a,b){function d(c){return a(b(c))}var c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=e[0]<0?bD:bC,c=b.pow,a.domain(e.map(b));return d},d.nice=function(){a.domain(br(a.domain(),bs));return d},d.ticks=function(){var d=bq(a.domain()),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===bD){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return bE},d.copy=function(){return bB(a.copy(),b)};return bu(d,a)}function bA(a,b,c,d){var e=[],f=[],g=0,h=a.length;while(++g<h)e.push(c(a[g-1],a[g])),f.push(d(b[g-1],b[g]));return function(b){var c=d3.bisect(a,b,1,a.length-1)-1;return f[c](e[c](b))}}function bz(a,b,c,d){var e=c(a[0],a[1]),f=d(b[0],b[1]);return function(a){return f(e(a))}}function by(a,b){return d3.format(",."+Math.max(0,-Math.floor(Math.log(bw(a,b)[2])/Math.LN10+.01))+"f")}function bx(a,b){return d3.range.apply(d3,bw(a,b))}function bw(a,b){var c=bq(a),d=c[1]-c[0],e=Math.pow(10,Math.floor(Math.log(d/b)/Math.LN10)),f=b/d*e;f<=.15?e*=10:f<=.35?e*=5:f<=.75&&(e*=2),c[0]=Math.ceil(c[0]/e)*e,c[1]=Math.floor(c[1]/e)*e+e*.5,c[2]=e;return c}function bv(a){a=Math.pow(10,Math.round(Math.log(a)/Math.LN10)-1);return{floor:function(b){return Math.floor(b/a)*a},ceil:function(b){return Math.ceil(b/a)*a}}}function bu(a,b){a.range=d3.rebind(a,b.range),a.rangeRound=d3.rebind(a,b.rangeRound),a.interpolate=d3.rebind(a,b.interpolate),a.clamp=d3.rebind(a,b.clamp);return a}function bt(a,b,c,d){function h(a){return e(a)}function g(){var g=a.length==2?bz:bA,i=d?H:G;e=g(a,b,i,c),f=g(b,a,i,d3.interpolate);return h}var e,f;h.invert=function(a){return f(a)},h.domain=function(b){if(!arguments.length)return a;a=b.map(Number);return g()},h.range=function(a){if(!arguments.length)return b;b=a;return g()},h.rangeRound=function(a){return h.range(a).interpolate(d3.interpolateRound)},h.clamp=function(a){if(!arguments.length)return d;d=a;return g()},h.interpolate=function(a){if(!arguments.length)return c;c=a;return g()},h.ticks=function(b){return bx(a,b)},h.tickFormat=function(b){return by(a,b)},h.nice=function(){br(a,bv);return g()},h.copy=function(){return bt(a,b,c,d)};return g()}function bs(){return Math}function br(a,b){var c=0,d=a.length-1,e=a[c],f=a[d],g;f<e&&(g=c,c=d,d=g,g=e,e=f,f=g),b=b(f-e),a[c]=b.floor(e),a[d]=b.ceil(f);return a}function bq(a){var b=a[0],c=a[a.length-1];return b<c?[b,c]:[c,b]}function bp(){}function bn(){var a=null,b=bj,c=Infinity;while(b)b.flush?b=a?a.next=b.next:bj=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function bm(){var a,b=Date.now(),c=bj;while(c)a=b-c.then,a>=c.delay&&(c.flush=c.callback(a)),c=c.next;var d=bn()-b;d>24?(isFinite(d)&&(clearTimeout(bl),bl=setTimeout(bm,d)),bk=0):(bk=1,bo(bm))}function bi(a){for(var b=0,c=this.length;b<c;b++)for(var d=this[b],e=0,f=d.length;e<f;e++){var g=d[e];g&&a.call(g=g.node,g.__data__,e,b)}return this}function bd(a){return typeof a=="function"?function(b,c,d){var e=a.call(this,b,c)+"";return d!=e&&d3.interpolate(d,e)}:(a=a+"",function(b,c,d){return d!=a&&d3.interpolate(d,a)})}function bc(a,b){d(a,be);var c={},e=d3.dispatch("start","end"),f=bh,g=Date.now();a.id=b,a.tween=function(b,d){if(arguments.length<2)return c[b];d==null?delete c[b]:c[b]=d;return a},a.ease=function(b){if(!arguments.length)return f;f=typeof b=="function"?b:d3.ease.apply(d3,arguments);return a},a.each=function(b,c){if(arguments.length<2)return bi.call(a,b);e[b].add(c);return a},d3.timer(function(d){a.each(function(h,i,j){function r(){--o.count||delete l.__transition__;return 1}function q(a){if(o.active!==b)return r();var c=(a-m)/n,d=f(c),g=k.length;while(g>0)k[--g].call(l,d);if(c>=1){r(),bg=b,e.end.dispatch.call(l,h,i),bg=0;return 1}}function p(a){if(o.active>b)return r();o.active=b;for(var d in c)(d=c[d].call(l,h,i))&&k.push(d);e.start.dispatch.call(l,h,i),q(a)||d3.timer(q,0,g);return 1}var k=[],l=this,m=a[j][i].delay,n=a[j][i].duration,o=l.__transition__||(l.__transition__={active:0,count:0});++o.count,m<=d?p(d):d3.timer(p,m,g)});return 1},0,g);return a}function ba(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function $(a){d(a,_);return a}function Z(a){return{__data__:a}}function Y(a){return function(){return V(a,this)}}function X(a){return function(){return U(a,this)}}function T(a){d(a,W);return a}function S(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);return a<60?d+(e-d)*a/60:a<180?e:a<240?d+(e-d)*(240-a)/60:d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return I(g(a+120),g(a),g(a-120))}function R(a,b,c){this.h=a,this.s=b,this.l=c}function Q(a,b,c){return new R(a,b,c)}function N(a){var b=parseFloat(a);return a.charAt(a.length-1)==="%"?Math.round(b*2.55):b}function M(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return Q(g,h,i)}function L(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(N(h[0]),N(h[1]),N(h[2]))}}if(i=O[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)==="#"&&(a.length===4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length===7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function K(a){return a<16?"0"+a.toString(16):a.toString(16)}function J(a,b,c){this.r=a,this.g=b,this.b=c}function I(a,b,c){return new J(a,b,c)}function H(a,b){b=b-(a=+a)?1/(b-a):0;return function(c){return Math.max(0,Math.min(1,(c-a)*b))}}function G(a,b){b=b-(a=+a)?1/(b-a):0;return function(c){return(c-a)*b}}function F(a){return a in E||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function C(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function B(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function A(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function z(a){return 1-Math.sqrt(1-a*a)}function y(a){return Math.pow(2,10*(a-1))}function x(a){return 1-Math.cos(a*Math.PI/2)}function w(a){return function(b){return Math.pow(b,a)}}function v(a){return a}function u(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function t(a){return function(b){return 1-a(1-b)}}function s(a){return function(b){return b<=0?0:b>=1?1:a(b)}}function n(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function m(a){return a+""}function j(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function h(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function g(a){return a==null}function f(a){return a.length}function e(){return this}Date.now||(Date.now=function(){return+(new Date)});try{document.createElement("div").style.setProperty("opacity",0,"")}catch(a){var b=CSSStyleDeclaration.prototype,c=b.setProperty;b.setProperty=function(a,b,d){c.call(this,a,b+"",d)}}d3={version:"2.1.3"};var d=[].__proto__?function(a,b){a.__proto__=b}:function(a,b){for(var c in b)a[c]=b[c]};d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:a>=b?0:NaN},d3.descending=function(a,b){return b<a?-1:b>a?1:b>=a?0:NaN},d3.min=function(a,b){var c=-1,d=a.length,e,f;if(arguments.length===1){while(++c<d&&((e=a[c])==null||e!=e))e=undefined;while(++c<d)(f=a[c])!=null&&e>f&&(e=f)}else{while(++c<d&&((e=b.call(a,a[c],c))==null||e!=e))e=undefined;while(++c<d)(f=b.call(a,a[c],c))!=null&&e>f&&(e=f)}return e},d3.max=function(a,b){var c=-1,d=a.length,e,f;if(arguments.length===1){while(++c<d&&((e=a[c])==null||e!=e))e=undefined;while(++c<d)(f=a[c])!=null&&f>e&&(e=f)}else{while(++c<d&&((e=b.call(a,a[c],c))==null||e!=e))e=undefined;while(++c<d)(f=b.call(a,a[c],c))!=null&&f>e&&(e=f)}return e},d3.sum=function(a,b){var c=0,d=a.length,e,f=-1;if(arguments.length===1)while(++f<d)isNaN(e=+a[f])||(c+=e);else while(++f<d)isNaN(e=+b.call(a,a[f],f))||(c+=e);return c},d3.quantile=function(a,b){var c=(a.length-1)*b+1,d=Math.floor(c),e=a[d-1],f=c-d;return f?e+f*(a[d]-e):e},d3.zip=function(){if(!(e=arguments.length))return[];for(var a=-1,b=d3.min(arguments,f),c=Array(b);++a<b;)for(var d=-1,e,g=c[a]=Array(e);++d<e;)g[d]=arguments[d][a];return c},d3.bisectLeft=function(a,b,c,d){arguments.length<3&&(c=0),arguments.length<4&&(d=a.length);while(c<d){var e=c+d>>1;a[e]<b?c=e+1:d=e}return c},d3.bisect=d3.bisectRight=function(a,b,c,d){arguments.length<3&&(c=0),arguments.length<4&&(d=a.length);while(c<d){var e=c+d>>1;b<a[e]?d=e:c=e+1}return c},d3.first=function(a,b){var c=0,d=a.length,e=a[0],f;arguments.length===1&&(b=d3.ascending);while(++c<d)b.call(a,e,f=a[c])>0&&(e=f);return e},d3.last=function(a,b){var c=0,d=a.length,e=a[0],f;arguments.length===1&&(b=d3.ascending);while(++c<d)b.call(a,e,f=a[c])<=0&&(e=f);return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.permute=function(a,b){var c=[],d=-1,e=b.length;while(++d<e)c[d]=a[b[d]];return c},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],e,f=-1,h=a.length;arguments.length<2&&(b=g);while(++f<h)b.call(d,e=a[f],f)?d=[]:(d.length||c.push(d),d.push(e));return c},d3.range=function(a,b,c){arguments.length<3&&(c=1,arguments.length<2&&(b=a,a=0));if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(i,"\\$&")};var i=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;d3.round=function(a,b){return b?Math.round(a*Math.pow(10,b))*Math.pow(10,-b):Math.round(a)},d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState===4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=j(c);return b},d3.format=function(a){var b=k.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9],j=!1,o=!1;h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4)));switch(i){case"n":g=!0,i="g";break;case"%":j=!0,i="f";break;case"p":j=!0,i="r";break;case"d":o=!0,h="0"}i=l[i]||m;return function(a){var b=j?a*100:+a,k=b<0&&(b=-b)?"−":d;if(o&&b%1)return"";a=i(b,h);if(e){var l=a.length+k.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=n(a)),a=k+a}else{g&&(a=n(a)),a=k+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}j&&(a+="%");return a}};var k=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l={g:function(a,b){return a.toPrecision(b)},e:function(a,b){return a.toExponential(b)},f:function(a,b){return a.toFixed(b)},r:function(a,b){var c=1+Math.floor(1e-15+Math.log(a)/Math.LN10);return d3.round(a,b-c).toFixed(Math.max(0,Math.min(20,b-c)))}},o=w(2),p=w(3),q={linear:function(){return v},poly:w,quad:function(){return o},cubic:function(){return p},sin:function(){return x},exp:function(){return y},circle:function(){return z},elastic:A,back:B,bounce:function(){return C}},r={"in":function(a){return a},out:t,"in-out":u,"out-in":function(a){return u(t(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return s(r[d](q[c].apply(null,Array.prototype.slice.call(arguments,1))))},d3.event=null,d3.interpolate=function(a,b){var c=d3.interpolators.length,d;while(--c>=0&&!(d=d3.interpolators[c](a,b)));return d},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;D.lastIndex=0;for(d=0;c=D.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=D.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=D.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;return h.length===1?h[0]==null?i[0].x:function(){return b}:function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return S(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=F(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var D=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,E={background:1,fill:1,stroke:1};d3.interpolators=[d3.interpolateObject,function(a,b){return b instanceof Array&&d3.interpolateArray(a,b)},function(a,b){return typeof b=="string"&&d3.interpolateString(String(a),b)},function(a,b){return(typeof b=="string"?b in O||/^(#|rgb\(|hsl\()/.test(b):b instanceof J||b instanceof R)&&d3.interpolateRgb(String(a),b)},function(a,b){return typeof b=="number"&&d3.interpolateNumber(+a,b)}],d3.rgb=function(a,b,c){return arguments.length===1?L(""+a,I,S):I(~~a,~~b,~~c)},J.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);var b=this.r,c=this.g,d=this.b,e=30;if(!b&&!c&&!d)return I(e,e,e);b&&b<e&&(b=e),c&&c<e&&(c=e),d&&d<e&&(d=e);return I(Math.min(255,Math.floor(b/a)),Math.min(255,Math.floor(c/a)),Math.min(255,Math.floor(d/a)))},J.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return I(Math.max(0,Math.floor(a*this.r)),Math.max(0,Math.floor(a*this.g)),Math.max(0,Math.floor(a*this.b)))},J.prototype.hsl=function(){return M(this.r,this.g,this.b)},J.prototype.toString=function(){return"#"+K(this.r)+K(this.g)+K(this.b)};var O={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var P in O)O[P]=L(O[P],I,S);d3.hsl=function(a,b,c){return arguments.length===1?L(""+a,M,Q):Q(+a,+b,+c)},R.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);return Q(this.h,this.s,this.l/a)},R.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return Q(this.h,this.s,a*this.l)},R.prototype.rgb=function(){return S(this.h,this.s,this.l)},R.prototype.toString=function(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"};var U=function(a,b){return b.querySelector(a)},V=function(a,b){return b.querySelectorAll(a)};typeof Sizzle=="function"&&(U=function(a,b){return Sizzle(a,b)[0]},V=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var W=[];d3.selection=function(){return bb},d3.selection.prototype=W,W.select=function(a){var b=[],c,d,e,f;typeof a!="function"&&(a=X(a));for(var g=-1,h=this.length;++g<h;){b.push(c=[]),c.parentNode=(e=this[g]).parentNode;for(var i=-1,j=e.length;++i<j;)(f=e[i])?(c.push(d=a.call(f,f.__data__,i)),d&&"__data__"in f&&(d.__data__=f.__data__)):c.push(null)}return T(b)},W.selectAll=function(a){var b=[],c,d;typeof a!="function"&&(a=Y(a));for(var e=-1,f=this.length;++e<f;)for(var g=this[e],h=-1,i=g.length;++h<i;)if(d=g[h])b.push(c=a.call(d,d.__data__,h)),c.parentNode=d;return T(b)},W.attr=function(a,b){function i(){var c=b.apply(this,arguments);c==null?this.removeAttributeNS(a.space,a.local):this.setAttributeNS(a.space,a.local,c)}function h(){var c=b.apply(this,arguments);c==null?this.removeAttribute(a):this.setAttribute(a,c)}function g(){this.setAttributeNS(a.space,a.local,b)}function f(){this.setAttribute(a,b)}function e(){this.removeAttributeNS(a.space,a.local)}function d(){this.removeAttribute(a)}a=d3.ns.qualify(a);if(arguments.length<2){var c=this.node();return a.local?c.getAttributeNS(a.space,a.local):c.getAttribute(a)}return this.each(b==null?a.local?e:d:typeof b=="function"?a.local?i:h:a.local?g:f)},W.classed=function(a,b){function i(){(b.apply(this,arguments)?f:g).call(this)}function g(){if(b=this.classList)return b.remove(a);var b=this.className,d=b.baseVal!=null,e=d?b.baseVal:b;e=h(e.replace(c," ")),d?b.baseVal=e:this.className=e}function f(){if(b=this.classList)return b.add(a);var b=this.className,d=b.baseVal!=null,e=d?b.baseVal:b;c.lastIndex=0,c.test(e)||(e=h(e+" "+a),d?b.baseVal=e:this.className=e)}var c=new RegExp("(^|\\s+)"+d3.requote(a)+"(\\s+|$)","g");if(arguments.length<2){var d=this.node();if(e=d.classList)return e.contains
<add>(a);var e=d.className;c.lastIndex=0;return c.test(e.baseVal!=null?e.baseVal:e)}return this.each(typeof b=="function"?i:b?f:g)},W.style=function(a,b,c){function f(){var d=b.apply(this,arguments);d==null?this.style.removeProperty(a):this.style.setProperty(a,d,c)}function e(){this.style.setProperty(a,b,c)}function d(){this.style.removeProperty(a)}arguments.length<3&&(c="");return arguments.length<2?window.getComputedStyle(this.node(),null).getPropertyValue(a):this.each(b==null?d:typeof b=="function"?f:e)},W.property=function(a,b){function e(){var c=b.apply(this,arguments);c==null?delete this[a]:this[a]=c}function d(){this[a]=b}function c(){delete this[a]}return arguments.length<2?this.node()[a]:this.each(b==null?c:typeof b=="function"?e:d)},W.text=function(a){return arguments.length<1?this.node().textContent:this.each(typeof a=="function"?function(){this.textContent=a.apply(this,arguments)}:function(){this.textContent=a})},W.html=function(a){return arguments.length<1?this.node().innerHTML:this.each(typeof a=="function"?function(){this.innerHTML=a.apply(this,arguments)}:function(){this.innerHTML=a})},W.append=function(a){function c(){return this.appendChild(document.createElementNS(a.space,a.local))}function b(){return this.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return this.select(a.local?c:b)},W.insert=function(a,b){function d(){return this.insertBefore(document.createElementNS(a.space,a.local),U(b,this))}function c(){return this.insertBefore(document.createElement(a),U(b,this))}a=d3.ns.qualify(a);return this.select(a.local?d:c)},W.remove=function(){return this.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},W.data=function(a,b){function f(a,f){var g,h=a.length,i=f.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(b){var q={},r=[],s,t=f.length;for(g=-1;++g<h;)s=b.call(o=a[g],o.__data__,g),s in q?n[t++]=o:q[s]=o,r.push(s);for(g=-1;++g<i;)o=q[s=b.call(f,p=f[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=Z(p),l[g]=n[g]=null),delete q[s];for(g=-1;++g<h;)r[g]in q&&(n[g]=a[g])}else{for(g=-1;++g<j;)o=a[g],p=f[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=Z(p),l[g]=n[g]=null);for(;g<i;++g)m[g]=Z(f[g]),l[g]=n[g]=null;for(;g<k;++g)n[g]=a[g],m[g]=l[g]=null}m.update=l,m.parentNode=l.parentNode=n.parentNode=a.parentNode,c.push(m),d.push(l),e.push(n)}var c=[],d=[],e=[],g=-1,h=this.length,i;if(typeof a=="function")while(++g<h)f(i=this[g],a.call(i,i.parentNode.__data__,g));else while(++g<h)f(i=this[g],a);var j=T(d);j.enter=function(){return $(c)},j.exit=function(){return T(e)};return j};var _=[];_.append=W.append,_.insert=W.insert,_.empty=W.empty,_.select=function(a){var b=[],c,d,e,f,g;for(var h=-1,i=this.length;++h<i;){e=(f=this[h]).update,b.push(c=[]),c.parentNode=f.parentNode;for(var j=-1,k=f.length;++j<k;)(g=f[j])?(c.push(e[j]=d=a.call(f.parentNode,g.__data__,j)),d.__data__=g.__data__):c.push(null)}return T(b)},W.filter=function(a){var b=[],c,d,e;for(var f=0,g=this.length;f<g;f++){b.push(c=[]),c.parentNode=(d=this[f]).parentNode;for(var h=0,i=d.length;h<i;h++)(e=d[h])&&a.call(e,e.__data__,h)&&c.push(e)}return T(b)},W.map=function(a){return this.each(function(){this.__data__=a.apply(this,arguments)})},W.sort=function(a){a=ba.apply(this,arguments);for(var b=0,c=this.length;b<c;b++)for(var d=this[b].sort(a),e=1,f=d.length,g=d[0];e<f;e++){var h=d[e];h&&(g&&g.parentNode.insertBefore(h,g.nextSibling),g=h)}return this},W.on=function(a,b,c){arguments.length<3&&(c=!1);var d="__on"+a,e=a.indexOf(".");e>0&&(a=a.substring(0,e));return arguments.length<2?(e=this.node()[d])&&e._:this.each(function(e,f){function h(a){var c=d3.event;d3.event=a;try{b.call(g,g.__data__,f)}finally{d3.event=c}}var g=this;g[d]&&g.removeEventListener(a,g[d],c),b&&g.addEventListener(a,g[d]=h,c),h._=b})},W.each=function(a){for(var b=-1,c=this.length;++b<c;)for(var d=this[b],e=-1,f=d.length;++e<f;){var g=d[e];g&&a.call(g,g.__data__,e,b)}return this},W.call=function(a){a.apply(this,(arguments[0]=this,arguments));return this},W.empty=function(){return!this.node()},W.node=function(a){for(var b=0,c=this.length;b<c;b++)for(var d=this[b],e=0,f=d.length;e<f;e++){var g=d[e];if(g)return g}return null},W.transition=function(){var a=[],b,c;for(var d=-1,e=this.length;++d<e;){a.push(b=[]);for(var f=this[d],g=-1,h=f.length;++g<h;)b.push((c=f[g])?{node:c,delay:0,duration:250}:null)}return bc(a,bg||++bf)};var bb=T([[document]]);bb[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?bb.select(a):T([[a]])},d3.selectAll=function(a){return typeof a=="string"?bb.selectAll(a):T([a])};var be=[],bf=0,bg=0,bh=d3.ease("cubic-in-out");be.call=W.call,d3.transition=function(){return bb.transition()},d3.transition.prototype=be,be.select=function(a){var b=[],c,d,e;typeof a!="function"&&(a=X(a));for(var f=-1,g=this.length;++f<g;){b.push(c=[]);for(var h=this[f],i=-1,j=h.length;++i<j;)(e=h[i])&&(d=a.call(e.node,e.node.__data__,i))?("__data__"in e.node&&(d.__data__=e.node.__data__),c.push({node:d,delay:e.delay,duration:e.duration})):c.push(null)}return bc(b,this.id).ease(this.ease())},be.selectAll=function(a){var b=[],c,d;typeof a!="function"&&(a=Y(a));for(var e=-1,f=this.length;++e<f;)for(var g=this[e],h=-1,i=g.length;++h<i;)if(d=g[h]){b.push(c=a.call(d.node,d.node.__data__,h));for(var j=-1,k=c.length;++j<k;)c[j]={node:c[j],delay:d.delay,duration:d.duration}}return bc(b,this.id).ease(this.ease())},be.attr=function(a,b){return this.attrTween(a,bd(b))},be.attrTween=function(a,b){function d(c,d){var e=b.call(this,c,d,this.getAttributeNS(a.space,a.local));return e&&function(b){this.setAttributeNS(a.space,a.local,e(b))}}function c(c,d){var e=b.call(this,c,d,this.getAttribute(a));return e&&function(b){this.setAttribute(a,e(b))}}a=d3.ns.qualify(a);return this.tween("attr."+a,a.local?d:c)},be.style=function(a,b,c){arguments.length<3&&(c="");return this.styleTween(a,bd(b),c)},be.styleTween=function(a,b,c){arguments.length<3&&(c="");return this.tween("style."+a,function(d,e){var f=b.call(this,d,e,window.getComputedStyle(this,null).getPropertyValue(a));return f&&function(b){this.style.setProperty(a,f(b),c)}})},be.text=function(a){return this.tween("text",function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a})},be.remove=function(){return this.each("end",function(){var a;!this.__transition__&&(a=this.parentNode)&&a.removeChild(this)})},be.delay=function(a){var b=this;return b.each(typeof a=="function"?function(c,d,e){b[e][d].delay=+a.apply(this,arguments)}:(a=+a,function(c,d,e){b[e][d].delay=a}))},be.duration=function(a){var b=this;return b.each(typeof a=="function"?function(c,d,e){b[e][d].duration=+a.apply(this,arguments)}:(a=+a,function(c,d,e){b[e][d].duration=a}))},be.transition=function(){return this.select(e)};var bj=null,bk,bl;d3.timer=function(a,b,c){var d=!1,e,f=bj;if(arguments.length<3){if(arguments.length<2)b=0;else if(!isFinite(b))return;c=Date.now()}while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||(bj={callback:a,then:c,delay:b,next:bj}),bk||(bl=clearTimeout(bl),bk=1,bo(bm))},d3.timer.flush=function(){var a,b=Date.now(),c=bj;while(c)a=b-c.then,c.delay||(c.flush=c.callback(a)),c=c.next;bn()};var bo=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){return bt([0,1],[0,1],d3.interpolate,!1)},d3.scale.log=function(){return bB(d3.scale.linear(),bC)},bC.pow=function(a){return Math.pow(10,a)},bD.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){return bF(d3.scale.linear(),1)},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){return bH([],{t:"range",x:[]})},d3.scale.category10=function(){return d3.scale.ordinal().range(bI)},d3.scale.category20=function(){return d3.scale.ordinal().range(bJ)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bK)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bL)};var bI=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bJ=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bK=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bL=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){return bM([],[])},d3.scale.quantize=function(){return bN(0,1,[0,1])},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bO,h=d.apply(this,arguments)+bO,i=(h<g&&(i=g,g=h,h=i),h-g),j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bP?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,0 0,"+ -e+"A"+e+","+e+" 0 1,0 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=bQ,b=bR,c=bS,d=bT;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bO;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bO=-Math.PI/2,bP=2*Math.PI-1e-6;d3.svg.line=function(){return bU(Object)};var bY={linear:bZ,"step-before":b$,"step-after":b_,basis:cf,"basis-open":cg,"basis-closed":ch,bundle:ci,cardinal:cc,"cardinal-open":ca,"cardinal-closed":cb,monotone:cr},ck=[0,2/3,1/3,0],cl=[0,1/3,2/3,0],cm=[0,1/6,2/3,1/6];d3.svg.line.radial=function(){var a=bU(cs);a.radius=a.x,delete a.x,a.angle=a.y,delete a.y;return a},d3.svg.area=function(){return ct(Object)},d3.svg.area.radial=function(){var a=ct(cs);a.radius=a.x,delete a.x,a.innerRadius=a.x0,delete a.x0,a.outerRadius=a.x1,delete a.x1,a.angle=a.y,delete a.y,a.startAngle=a.y0,delete a.y0,a.endAngle=a.y1,delete a.y1;return a},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bO,k=e.call(a,h,g)+bO;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=cw,b=cx,c=cy,d=bS,e=bT;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=cw,b=cx,c=cB;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.diagonal.radial=function(){var a=d3.svg.diagonal(),b=cB,c=a.projection;a.projection=function(a){return arguments.length?c(cC(b=a)):b};return a},d3.svg.mouse=function(a){return cE(a,d3.event)};var cD=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.touches=function(a){var b=d3.event.touches;return b?Array.prototype.map.call(b,function(b){var c=cE(a,b);c.identifier=b.identifier;return c}):[]},d3.svg.symbol=function(){function c(c,d){return(cH[a.call(this,c,d)]||cH.circle)(b.call(this,c,d))}var a=cG,b=cF;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c};var cH={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*cJ)),c=b*cJ;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/cI),c=b*cI/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/cI),c=b*cI/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}};d3.svg.symbolTypes=d3.keys(cH);var cI=Math.sqrt(3),cJ=Math.tan(30*Math.PI/180);d3.svg.axis=function(){function j(j){j.each(function(k,l,m){function F(a){return j.delay?a.transition().delay(j[m][l].delay).duration(j[m][l].duration).ease(j.ease()):a}var n=d3.select(this),o=a.ticks.apply(a,g),p=h==null?a.tickFormat.apply(a,g):h,q=cM(a,o,i),r=n.selectAll(".minor").data(q,String),s=r.enter().insert("svg:line","g").attr("class","tick minor").style("opacity",1e-6),t=F(r.exit()).style("opacity",1e-6).remove(),u=F(r).style("opacity",1),v=n.selectAll("g").data(o,String),w=v.enter().insert("svg:g","path").style("opacity",1e-6),x=F(v.exit()).style("opacity",1e-6).remove(),y=F(v).style("opacity",1),z,A=bq(a.range()),B=n.selectAll(".domain").data([0]),C=B.enter().append("svg:path").attr("class","domain"),D=F(B),E=this.__chart__||a;this.__chart__=a.copy(),w.append("svg:line").attr("class","tick"),w.append("svg:text"),y.select("text").text(p);switch(b){case"bottom":z=cK,u.attr("y2",d),w.select("text").attr("dy",".71em").attr("text-anchor","middle"),y.select("line").attr("y2",c),y.select("text").attr("y",Math.max(c,0)+f),D.attr("d","M"+A[0]+","+e+"V0H"+A[1]+"V"+e);break;case"top":z=cK,u.attr("y2",-d),w.select("text").attr("text-anchor","middle"),y.select("line").attr("y2",-c),y.select("text").attr("y",-(Math.max(c,0)+f)),D.attr("d","M"+A[0]+","+ -e+"V0H"+A[1]+"V"+ -e);break;case"left":z=cL,u.attr("x2",-d),w.select("text").attr("dy",".32em").attr("text-anchor","end"),y.select("line").attr("x2",-c),y.select("text").attr("x",-(Math.max(c,0)+f)),D.attr("d","M"+ -e+","+A[0]+"H0V"+A[1]+"H"+ -e);break;case"right":z=cL,u.attr("x2",d),w.select("text").attr("dy",".32em"),y.select("line").attr("x2",c),y.select("text").attr("x",Math.max(c,0)+f),D.attr("d","M"+e+","+A[0]+"H0V"+A[1]+"H"+e)}w.call(z,E),y.call(z,a),x.call(z,a),s.call(z,E),u.call(z,a),t.call(z,a)})}var a=d3.scale.linear(),b="bottom",c=6,d=6,e=6,f=3,g=[10],h,i=0;j.scale=function(b){if(!arguments.length)return a;a=b;return j},j.orient=function(a){if(!arguments.length)return b;b=a;return j},j.ticks=function(){if(!arguments.length)return g;g=arguments;return j},j.tickFormat=function(a){if(!arguments.length)return h;h=a;return j},j.tickSize=function(a,b,f){if(!arguments.length)return c;var g=arguments.length-1;c=+a,d=g>1?+b:c,e=g>0?+arguments[g]:c;return j},j.tickPadding=function(a){if(!arguments.length)return f;f=+a;return j},j.tickSubdivide=function(a){if(!arguments.length)return i;i=+a;return j};return j},d3.behavior={},d3.behavior.drag=function(){function d(){c.apply(this,arguments),cT("dragstart")}function c(){cN=a,cQ=cU((cO=this).parentNode),cR=0,cP=arguments}function b(){this.on("mousedown.drag",d).on("touchstart.drag",d),d3.select(window).on("mousemove.drag",cV).on("touchmove.drag",cV).on("mouseup.drag",cW,!0).on("touchend.drag",cW,!0).on("click.drag",cX,!0)}var a=d3.dispatch("drag","dragstart","dragend");b.on=function(c,d){a[c].add(d);return b};return b};var cN,cO,cP,cQ,cR,cS;d3.behavior.zoom=function(){function h(){d.apply(this,arguments);var b=dk(),c,e=Date.now();b.length===1&&e-db<300&&dq(1+Math.floor(a[2]),c=b[0],da[c.identifier]),db=e}function g(){d.apply(this,arguments);var b=d3.svg.mouse(de);dq(d3.event.shiftKey?Math.ceil(a[2]-1):Math.floor(a[2]+1),b,di(b))}function f(){d.apply(this,arguments),c_||(c_=di(d3.svg.mouse(de))),dq(dj()+a[2],d3.svg.mouse(de),c_)}function e(){d.apply(this,arguments),c$=di(d3.svg.mouse(de)),dg=!1,d3.event.preventDefault(),window.focus()}function d(){dc=a,dd=b.zoom.dispatch,de=this,df=arguments}function c(){this.on("mousedown.zoom",e).on("mousewheel.zoom",f).on("DOMMouseScroll.zoom",f).on("dblclick.zoom",g).on("touchstart.zoom",h),d3.select(window).on("mousemove.zoom",dm).on("mouseup.zoom",dn).on("touchmove.zoom",dl).on("touchend.zoom",dk).on("click.zoom",dp,!0)}var a=[0,0,0],b=d3.dispatch("zoom");c.on=function(a,d){b[a].add(d);return c};return c};var cZ,c$,c_,da={},db=0,dc,dd,de,df,dg,dh})()
<ide>\ No newline at end of file
<ide><path>src/core/core.js
<del>d3 = {version: "2.1.2"}; // semver
<add>d3 = {version: "2.1.3"}; // semver
<ide><path>src/svg/axis.js
<ide> d3.svg.axis = function() {
<ide>
<ide> // Domain.
<ide> var range = d3_scaleExtent(scale.range()),
<del> path = g.selectAll(".domain").data([,]),
<add> path = g.selectAll(".domain").data([0]),
<ide> pathEnter = path.enter().append("svg:path").attr("class", "domain"),
<ide> pathUpdate = transition(path);
<ide> | 4 |
Text | Text | add v3.1.0-beta.3 to changelog | 25c2ec05bb9364ad2a489864d4ac80015feb2630 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.1.0-beta.3 (February 26, 2018)
<add>- [#16271](https://github.com/emberjs/ember.js/pull/16271) [BUGFIX] Fix ChainNode unchaining
<add>- [#16274](https://github.com/emberjs/ember.js/pull/16274) [BUGFIX] Ensure accessing a "proxy" itself does not error.
<add>- [#16282](https://github.com/emberjs/ember.js/pull/16282) [BUGFIX] Fix nested ObserverSet flushes
<add>- [#16285](https://github.com/emberjs/ember.js/pull/16285) [BUGFIX] Fix version with many special chars.
<add>- [#16286](https://github.com/emberjs/ember.js/pull/16286) [BUGFIX] Update to glimmer-vm@0.32.1.
<add>- [#16287](https://github.com/emberjs/ember.js/pull/16287) [BUGFIX] Update to router_js@2.0.0-beta.2.
<add>- [#16288](https://github.com/emberjs/ember.js/pull/16288) [BUGFIX] Ensure all "internal symbols" avoid the proxy assertion
<add>
<ide> ### v3.1.0-beta.2 (February 19, 2018)
<ide>
<ide> - [#13355](https://github.com/emberjs/ember.js/pull/13355) [BUGFIX] Fix issue with `Ember.trySet` on destroyed objects. | 1 |
Mixed | Javascript | support hover animation duration during updates | 009ae4dec6db9d8b94a77cad3dffbf907e720ad4 | <ide><path>docs/developers/api.md
<ide> This must be called before the canvas is reused for a new chart.
<ide> myLineChart.destroy();
<ide> ```
<ide>
<del>## .update(duration, lazy)
<add>## .update(config)
<ide>
<ide> Triggers an update of the chart. This can be safely called after updating the data object. This will update all scales, legends, and then re-render the chart.
<ide>
<ide> myLineChart.update(); // Calling update now animates the position of March from
<ide>
<ide> > **Note:** replacing the data reference (e.g. `myLineChart.data = {datasets: [...]}` only works starting **version 2.6**. Prior that, replacing the entire data object could be achieved with the following workaround: `myLineChart.config.data = {datasets: [...]}`.
<ide>
<add>A `config` object can be provided with additional configuration for the update process. This is useful when `update` is manually called inside an event handler and some different animation is desired.
<add>
<add>The following properties are supported:
<add>* **duration** (number): Time for the animation of the redraw in milliseconds
<add>* **lazy** (boolean): If true, the animation can be interrupted by other animations
<add>* **easing** (string): The animation easing function. See [Animation Easing](../configuration/animations.md) for possible values.
<add>
<add>Example:
<add>```javascript
<add>myChart.update({
<add> duration: 800,
<add> easing: 'easeOutBounce'
<add>})
<add>```
<add>
<ide> See [Updating Charts](updates.md) for more details.
<ide>
<ide> ## .reset()
<ide> Reset the chart to it's state before the initial animation. A new animation can
<ide> myLineChart.reset();
<ide> ```
<ide>
<del>## .render(duration, lazy)
<add>## .render(config)
<ide>
<ide> Triggers a redraw of all chart elements. Note, this does not update elements for new data. Use `.update()` in that case.
<ide>
<add>See `.update(config)` for more details on the config object.
<add>
<ide> ```javascript
<ide> // duration is the time for the animation of the redraw in milliseconds
<ide> // lazy is a boolean. if true, the animation can be interrupted by other animations
<del>myLineChart.render(duration, lazy);
<add>myLineChart.render({
<add> duration: 800,
<add> lazy: false,
<add> easing: 'easeOutBounce'
<add>});
<ide> ```
<ide>
<ide> ## .stop()
<ide><path>src/core/core.controller.js
<ide> module.exports = function(Chart) {
<ide> this.tooltip.initialize();
<ide> },
<ide>
<del> update: function(animationDuration, lazy) {
<add> update: function(config) {
<ide> var me = this;
<ide>
<add> if (!config || typeof config !== 'object') {
<add> // backwards compatibility
<add> config = {
<add> duration: config,
<add> lazy: arguments[1]
<add> };
<add> }
<add>
<ide> updateConfig(me);
<ide>
<ide> if (plugins.notify(me, 'beforeUpdate') === false) {
<ide> module.exports = function(Chart) {
<ide>
<ide> if (me._bufferedRender) {
<ide> me._bufferedRequest = {
<del> lazy: lazy,
<del> duration: animationDuration
<add> duration: config.duration,
<add> easing: config.easing,
<add> lazy: config.lazy
<ide> };
<ide> } else {
<del> me.render(animationDuration, lazy);
<add> me.render(config);
<ide> }
<ide> },
<ide>
<ide> module.exports = function(Chart) {
<ide> plugins.notify(me, 'afterDatasetUpdate', [args]);
<ide> },
<ide>
<del> render: function(duration, lazy) {
<add> render: function(config) {
<ide> var me = this;
<ide>
<add> if (!config || typeof config !== 'object') {
<add> // backwards compatibility
<add> config = {
<add> duration: config,
<add> lazy: arguments[1]
<add> };
<add> }
<add>
<add> var duration = config.duration;
<add> var lazy = config.lazy;
<add>
<ide> if (plugins.notify(me, 'beforeRender') === false) {
<ide> return;
<ide> }
<ide> module.exports = function(Chart) {
<ide> if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) {
<ide> var animation = new Chart.Animation({
<ide> numSteps: (duration || animationOptions.duration) / 16.66, // 60 fps
<del> easing: animationOptions.easing,
<add> easing: config.easing || animationOptions.easing,
<ide>
<ide> render: function(chart, animationObject) {
<ide> var easingFunction = helpers.easingEffects[animationObject.easing];
<ide> module.exports = function(Chart) {
<ide> var bufferedRequest = me._bufferedRequest;
<ide> if (bufferedRequest) {
<ide> // If we have an update that was triggered, we need to do a normal render
<del> me.render(bufferedRequest.duration, bufferedRequest.lazy);
<add> me.render(bufferedRequest);
<ide> } else if (changed && !me.animating) {
<ide> // If entering, leaving, or changing elements, animate the change via pivot
<ide> me.stop();
<ide><path>test/specs/core.controller.tests.js
<ide> describe('Chart', function() {
<ide> ]);
<ide> });
<ide> });
<add>
<add> describe('controller.update', function() {
<add> beforeEach(function() {
<add> this.chart = acquireChart({
<add> type: 'doughnut',
<add> options: {
<add> animation: {
<add> easing: 'linear',
<add> duration: 500
<add> }
<add> }
<add> });
<add>
<add> this.addAnimationSpy = spyOn(Chart.animationService, 'addAnimation');
<add> });
<add>
<add> it('should add an animation with the default options', function() {
<add> this.chart.update();
<add>
<add> expect(this.addAnimationSpy).toHaveBeenCalledWith(
<add> this.chart,
<add> jasmine.objectContaining({easing: 'linear'}),
<add> undefined,
<add> undefined
<add> );
<add> });
<add>
<add> it('should add an animation with the provided options', function() {
<add> this.chart.update({
<add> duration: 800,
<add> easing: 'easeOutBounce',
<add> lazy: false,
<add> });
<add>
<add> expect(this.addAnimationSpy).toHaveBeenCalledWith(
<add> this.chart,
<add> jasmine.objectContaining({easing: 'easeOutBounce'}),
<add> 800,
<add> false
<add> );
<add> });
<add> });
<ide> });
<ide><path>test/specs/global.deprecations.tests.js
<ide> describe('Deprecations', function() {
<add> describe('Version 2.7.0', function() {
<add> describe('Chart.Controller.update(duration, lazy)', function() {
<add> beforeEach(function() {
<add> this.chart = acquireChart({
<add> type: 'doughnut',
<add> options: {
<add> animation: {
<add> easing: 'linear',
<add> duration: 500
<add> }
<add> }
<add> });
<add>
<add> this.addAnimationSpy = spyOn(Chart.animationService, 'addAnimation');
<add> });
<add>
<add> it('should add an animation with the provided options', function() {
<add> this.chart.update(800, false);
<add>
<add> expect(this.addAnimationSpy).toHaveBeenCalledWith(
<add> this.chart,
<add> jasmine.objectContaining({easing: 'linear'}),
<add> 800,
<add> false
<add> );
<add> });
<add> });
<add>
<add> describe('Chart.Controller.render(duration, lazy)', function() {
<add> beforeEach(function() {
<add> this.chart = acquireChart({
<add> type: 'doughnut',
<add> options: {
<add> animation: {
<add> easing: 'linear',
<add> duration: 500
<add> }
<add> }
<add> });
<add>
<add> this.addAnimationSpy = spyOn(Chart.animationService, 'addAnimation');
<add> });
<add>
<add> it('should add an animation with the provided options', function() {
<add> this.chart.render(800, true);
<add>
<add> expect(this.addAnimationSpy).toHaveBeenCalledWith(
<add> this.chart,
<add> jasmine.objectContaining({easing: 'linear'}),
<add> 800,
<add> true
<add> );
<add> });
<add> });
<add> });
<add>
<ide> describe('Version 2.6.0', function() {
<ide> // https://github.com/chartjs/Chart.js/issues/2481
<ide> describe('Chart.Controller', function() { | 4 |
Javascript | Javascript | refine flow types | ffefb4e77f39c38a6fabb8677a585b2aa3991cd3 | <ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js
<ide> * @flow
<ide> */
<ide>
<del>import type {DOMTopLevelEventType} from 'legacy-events/TopLevelEventTypes';
<ide> import type {RootType} from './ReactDOMRoot';
<ide>
<ide> import {
<ide> export function registerEvent(
<ide> // Add the event listener to the target container (falling back to
<ide> // the target if we didn't find one).
<ide> listenToTopLevelEvent(
<del> ((type: any): DOMTopLevelEventType),
<add> type,
<ide> rootContainerInstance,
<ide> listenerMap,
<ide> passive,
<ide><path>packages/react-dom/src/client/ReactDOMUseEvent.js
<ide> * @flow
<ide> */
<ide>
<add>import type {DOMTopLevelEventType} from 'legacy-events/TopLevelEventTypes';
<ide> import type {EventPriority} from 'shared/ReactTypes';
<ide> import type {
<ide> ReactDOMListenerEvent,
<ide> function resolveDispatcher() {
<ide> }
<ide>
<ide> export function useEvent(
<del> type: string,
<add> type: DOMTopLevelEventType,
<ide> options?: EventOptions,
<ide> ): ReactDOMListenerMap {
<ide> const dispatcher = resolveDispatcher();
<ide> let capture = false;
<ide> let passive = undefined; // Undefined means to use the browser default
<del> let priority = getEventPriorityForListenerSystem((type: any));
<add> let priority;
<ide>
<ide> if (options != null) {
<ide> const optionsCapture = options.capture;
<ide> export function useEvent(
<ide> priority = optionsPriority;
<ide> }
<ide> }
<add> if (priority === undefined) {
<add> priority = getEventPriorityForListenerSystem(type);
<add> }
<ide> const event: ReactDOMListenerEvent = {
<ide> capture,
<ide> passive,
<ide><path>packages/react-dom/src/events/DOMEventProperties.js
<ide> export function getEventPriorityForPluginSystem(
<ide> return priority === undefined ? ContinuousEvent : priority;
<ide> }
<ide>
<del>export function getEventPriorityForListenerSystem(type: string): EventPriority {
<del> const priority = eventPriorities.get(((type: any): TopLevelType));
<add>export function getEventPriorityForListenerSystem(
<add> type: DOMTopLevelEventType,
<add>): EventPriority {
<add> const priority = eventPriorities.get(type);
<ide> if (priority !== undefined) {
<ide> return priority;
<ide> }
<ide><path>packages/react-dom/src/events/DOMModernPluginEventSystem.js
<ide> export function attachElementListener(listener: ReactDOMListener): void {
<ide> // Add the event listener to the target container (falling back to
<ide> // the target if we didn't find one).
<ide> listenToTopLevelEvent(
<del> ((type: any): DOMTopLevelEventType),
<add> type,
<ide> containerEventTarget,
<ide> listenerMap,
<ide> passive,
<ide><path>packages/shared/ReactDOMTypes.js
<ide> import type {
<ide> ReactEventResponderInstance,
<ide> EventPriority,
<ide> } from 'shared/ReactTypes';
<add>import type {DOMTopLevelEventType} from 'legacy-events/TopLevelEventTypes';
<ide>
<ide> type AnyNativeEvent = Event | KeyboardEvent | MouseEvent | Touch;
<ide>
<ide> export type ReactDOMListenerEvent = {|
<ide> capture: boolean,
<ide> passive: void | boolean,
<ide> priority: EventPriority,
<del> type: string,
<add> type: DOMTopLevelEventType,
<ide> |};
<ide>
<ide> export type ReactDOMListenerMap = {| | 5 |
Ruby | Ruby | move code away from cmd/ | 9bdd6619e23f498320c3d3a6be8bd8d095a6d521 | <ide><path>Library/Homebrew/cleanup.rb
<add>require "bottles"
<add>require "formula"
<add>require "thread"
<add>
<add>module Homebrew
<add> module Cleanup
<add> @@disk_cleanup_size = 0
<add>
<add> def self.cleanup
<add> cleanup_cellar
<add> cleanup_cache
<add> cleanup_logs
<add> unless ARGV.dry_run?
<add> cleanup_lockfiles
<add> rm_DS_Store
<add> end
<add> end
<add>
<add> def self.update_disk_cleanup_size(path_size)
<add> @@disk_cleanup_size += path_size
<add> end
<add>
<add> def self.disk_cleanup_size
<add> @@disk_cleanup_size
<add> end
<add>
<add> def self.cleanup_formula(formula)
<add> formula.eligible_kegs_for_cleanup.each do |keg|
<add> cleanup_path(keg) { keg.uninstall }
<add> end
<add> end
<add>
<add> def self.cleanup_logs
<add> return unless HOMEBREW_LOGS.directory?
<add> HOMEBREW_LOGS.subdirs.each do |dir|
<add> cleanup_path(dir) { dir.rmtree } if prune?(dir, :days_default => 14)
<add> end
<add> end
<add>
<add> def self.cleanup_cellar
<add> Formula.installed.each do |formula|
<add> cleanup_formula formula
<add> end
<add> end
<add>
<add> def self.cleanup_cache
<add> return unless HOMEBREW_CACHE.directory?
<add> HOMEBREW_CACHE.children.each do |path|
<add> if path.to_s.end_with? ".incomplete"
<add> cleanup_path(path) { path.unlink }
<add> next
<add> end
<add> if path.basename.to_s == "java_cache" && path.directory?
<add> cleanup_path(path) { FileUtils.rm_rf path }
<add> next
<add> end
<add> if prune?(path)
<add> if path.file?
<add> cleanup_path(path) { path.unlink }
<add> elsif path.directory? && path.to_s.include?("--")
<add> cleanup_path(path) { FileUtils.rm_rf path }
<add> end
<add> next
<add> end
<add>
<add> next unless path.file?
<add> file = path
<add>
<add> if Pathname::BOTTLE_EXTNAME_RX === file.to_s
<add> version = bottle_resolve_version(file) rescue file.version
<add> else
<add> version = file.version
<add> end
<add> next unless version
<add> next unless (name = file.basename.to_s[/(.*)-(?:#{Regexp.escape(version)})/, 1])
<add>
<add> next unless HOMEBREW_CELLAR.directory?
<add>
<add> begin
<add> f = Formulary.from_rack(HOMEBREW_CELLAR/name)
<add> rescue FormulaUnavailableError, TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError
<add> next
<add> end
<add>
<add> file_is_stale = if PkgVersion === version
<add> f.pkg_version > version
<add> else
<add> f.version > version
<add> end
<add>
<add> if file_is_stale || ARGV.switch?("s") && !f.installed? || bottle_file_outdated?(f, file)
<add> cleanup_path(file) { file.unlink }
<add> end
<add> end
<add> end
<add>
<add> def self.cleanup_path(path)
<add> if ARGV.dry_run?
<add> puts "Would remove: #{path} (#{path.abv})"
<add> else
<add> puts "Removing: #{path}... (#{path.abv})"
<add> yield
<add> end
<add>
<add> update_disk_cleanup_size(path.disk_usage)
<add> end
<add>
<add> def self.cleanup_lockfiles
<add> return unless HOMEBREW_CACHE_FORMULA.directory?
<add> candidates = HOMEBREW_CACHE_FORMULA.children
<add> lockfiles = candidates.select { |f| f.file? && f.extname == ".brewing" }
<add> lockfiles.each do |file|
<add> next unless file.readable?
<add> file.open.flock(File::LOCK_EX | File::LOCK_NB) && file.unlink
<add> end
<add> end
<add>
<add> def self.rm_DS_Store
<add> paths = Queue.new
<add> %w[Cellar Frameworks Library bin etc include lib opt sbin share var].
<add> map { |p| HOMEBREW_PREFIX/p }.each { |p| paths << p if p.exist? }
<add> workers = (0...Hardware::CPU.cores).map do
<add> Thread.new do
<add> begin
<add> while p = paths.pop(true)
<add> quiet_system "find", p, "-name", ".DS_Store", "-delete"
<add> end
<add> rescue ThreadError # ignore empty queue error
<add> end
<add> end
<add> end
<add> workers.map(&:join)
<add> end
<add>
<add> def self.prune?(path, options = {})
<add> @time ||= Time.now
<add>
<add> path_modified_time = path.mtime
<add> days_default = options[:days_default]
<add>
<add> prune = ARGV.value "prune"
<add>
<add> return true if prune == "all"
<add>
<add> prune_time = if prune
<add> @time - 60 * 60 * 24 * prune.to_i
<add> elsif days_default
<add> @time - 60 * 60 * 24 * days_default.to_i
<add> end
<add>
<add> return false unless prune_time
<add>
<add> path_modified_time < prune_time
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/cmd/cleanup.rb
<del>require "formula"
<del>require "keg"
<del>require "bottles"
<del>require "thread"
<add>require "cleanup"
<ide> require "utils"
<ide>
<ide> module Homebrew
<del> @@disk_cleanup_size = 0
<del>
<del> def update_disk_cleanup_size(path_size)
<del> @@disk_cleanup_size += path_size
<del> end
<del>
<ide> def cleanup
<ide> if ARGV.named.empty?
<del> cleanup_cellar
<del> cleanup_cache
<del> cleanup_logs
<del> unless ARGV.dry_run?
<del> cleanup_lockfiles
<del> rm_DS_Store
<del> end
<add> Cleanup.cleanup
<ide> else
<del> ARGV.resolved_formulae.each { |f| cleanup_formula(f) }
<add> ARGV.resolved_formulae.each { |f| Cleanup.cleanup_formula f }
<ide> end
<ide>
<del> if @@disk_cleanup_size > 0
<del> disk_space = disk_usage_readable(@@disk_cleanup_size)
<add> if Cleanup.disk_cleanup_size > 0
<add> disk_space = disk_usage_readable(Cleanup.disk_cleanup_size)
<ide> if ARGV.dry_run?
<ide> ohai "This operation would free approximately #{disk_space} of disk space."
<ide> else
<ide> ohai "This operation has freed approximately #{disk_space} of disk space."
<ide> end
<ide> end
<ide> end
<del>
<del> def cleanup_logs
<del> return unless HOMEBREW_LOGS.directory?
<del> HOMEBREW_LOGS.subdirs.each do |dir|
<del> cleanup_path(dir) { dir.rmtree } if prune?(dir, :days_default => 14)
<del> end
<del> end
<del>
<del> def cleanup_cellar
<del> Formula.installed.each do |formula|
<del> cleanup_formula formula
<del> end
<del> end
<del>
<del> def cleanup_formula(f)
<del> if f.installed?
<del> eligible_kegs = f.installed_kegs.select { |k| f.pkg_version > k.version }
<del> if eligible_kegs.any? && eligible_for_cleanup?(f)
<del> eligible_kegs.each { |keg| cleanup_keg(keg) }
<del> else
<del> eligible_kegs.each { |keg| opoo "Skipping (old) keg-only: #{keg}" }
<del> end
<del> elsif f.installed_prefixes.any? && !f.pinned?
<del> # If the cellar only has one version installed, don't complain
<del> # that we can't tell which one to keep. Don't complain at all if the
<del> # only installed version is a pinned formula.
<del> opoo "Skipping #{f.full_name}: most recent version #{f.pkg_version} not installed"
<del> end
<del> end
<del>
<del> def cleanup_keg(keg)
<del> if keg.linked?
<del> opoo "Skipping (old) #{keg} due to it being linked"
<del> else
<del> cleanup_path(keg) { keg.uninstall }
<del> end
<del> end
<del>
<del> def cleanup_cache
<del> return unless HOMEBREW_CACHE.directory?
<del> HOMEBREW_CACHE.children.each do |path|
<del> if path.to_s.end_with? ".incomplete"
<del> cleanup_path(path) { path.unlink }
<del> next
<del> end
<del> if path.basename.to_s == "java_cache" && path.directory?
<del> cleanup_path(path) { FileUtils.rm_rf path }
<del> next
<del> end
<del> if prune?(path)
<del> if path.file?
<del> cleanup_path(path) { path.unlink }
<del> elsif path.directory? && path.to_s.include?("--")
<del> cleanup_path(path) { FileUtils.rm_rf path }
<del> end
<del> next
<del> end
<del>
<del> next unless path.file?
<del> file = path
<del>
<del> if Pathname::BOTTLE_EXTNAME_RX === file.to_s
<del> version = bottle_resolve_version(file) rescue file.version
<del> else
<del> version = file.version
<del> end
<del> next unless version
<del> next unless (name = file.basename.to_s[/(.*)-(?:#{Regexp.escape(version)})/, 1])
<del>
<del> next unless HOMEBREW_CELLAR.directory?
<del>
<del> begin
<del> f = Formulary.from_rack(HOMEBREW_CELLAR/name)
<del> rescue FormulaUnavailableError, TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError
<del> next
<del> end
<del>
<del> file_is_stale = if PkgVersion === version
<del> f.pkg_version > version
<del> else
<del> f.version > version
<del> end
<del>
<del> if file_is_stale || ARGV.switch?("s") && !f.installed? || bottle_file_outdated?(f, file)
<del> cleanup_path(file) { file.unlink }
<del> end
<del> end
<del> end
<del>
<del> def cleanup_path(path)
<del> if ARGV.dry_run?
<del> puts "Would remove: #{path} (#{path.abv})"
<del> else
<del> puts "Removing: #{path}... (#{path.abv})"
<del> yield
<del> end
<del> update_disk_cleanup_size(path.disk_usage)
<del> end
<del>
<del> def cleanup_lockfiles
<del> return unless HOMEBREW_CACHE_FORMULA.directory?
<del> candidates = HOMEBREW_CACHE_FORMULA.children
<del> lockfiles = candidates.select { |f| f.file? && f.extname == ".brewing" }
<del> lockfiles.each do |file|
<del> next unless file.readable?
<del> file.open.flock(File::LOCK_EX | File::LOCK_NB) && file.unlink
<del> end
<del> end
<del>
<del> def rm_DS_Store
<del> paths = Queue.new
<del> %w[Cellar Frameworks Library bin etc include lib opt sbin share var].
<del> map { |p| HOMEBREW_PREFIX/p }.each { |p| paths << p if p.exist? }
<del> workers = (0...Hardware::CPU.cores).map do
<del> Thread.new do
<del> begin
<del> while p = paths.pop(true)
<del> quiet_system "find", p, "-name", ".DS_Store", "-delete"
<del> end
<del> rescue ThreadError # ignore empty queue error
<del> end
<del> end
<del> end
<del> workers.map(&:join)
<del> end
<del>
<del> def prune?(path, options = {})
<del> @time ||= Time.now
<del>
<del> path_modified_time = path.mtime
<del> days_default = options[:days_default]
<del>
<del> prune = ARGV.value "prune"
<del>
<del> return true if prune == "all"
<del>
<del> prune_time = if prune
<del> @time - 60 * 60 * 24 * prune.to_i
<del> elsif days_default
<del> @time - 60 * 60 * 24 * days_default.to_i
<del> end
<del>
<del> return false unless prune_time
<del>
<del> path_modified_time < prune_time
<del> end
<del>
<del> def eligible_for_cleanup?(formula)
<del> # It used to be the case that keg-only kegs could not be cleaned up, because
<del> # older brews were built against the full path to the keg-only keg. Then we
<del> # introduced the opt symlink, and built against that instead. So provided
<del> # no brew exists that was built against an old-style keg-only keg, we can
<del> # remove it.
<del> if !formula.keg_only? || ARGV.force?
<del> true
<del> elsif formula.opt_prefix.directory?
<del> # SHA records were added to INSTALL_RECEIPTS the same day as opt symlinks
<del> Formula.installed.select do |f|
<del> f.deps.any? do |d|
<del> d.to_formula.full_name == formula.full_name rescue d.name == formula.name
<del> end
<del> end.all? { |f| f.installed_prefixes.all? { |keg| Tab.for_keg(keg).HEAD } }
<del> end
<del> end
<ide> end
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> require "cmd/install"
<del>require "cmd/cleanup"
<add>require "cleanup"
<ide>
<ide> module Homebrew
<ide> def upgrade
<ide> def upgrade
<ide>
<ide> outdated.each do |f|
<ide> upgrade_formula(f)
<del> cleanup_formula(f) if ARGV.include?("--cleanup") && f.installed?
<add> next unless ARGV.include?("--cleanup")
<add> next unless f.installed?
<add> Homebrew::Cleanup.cleanup_formula f
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/formula.rb
<ide> def system(cmd, *args)
<ide> end
<ide> end
<ide>
<add> # @private
<add> def eligible_kegs_for_cleanup
<add> eligible_for_cleanup = []
<add> if installed?
<add> eligible_kegs = installed_kegs.select { |k| pkg_version > k.version }
<add> if eligible_kegs.any? && eligible_for_cleanup?
<add> eligible_kegs.each do |keg|
<add> if keg.linked?
<add> opoo "Skipping (old) #{keg} due to it being linked"
<add> else
<add> eligible_for_cleanup << keg
<add> end
<add> end
<add> else
<add> eligible_kegs.each { |keg| opoo "Skipping (old) keg-only: #{keg}" }
<add> end
<add> elsif installed_prefixes.any? && !pinned?
<add> # If the cellar only has one version installed, don't complain
<add> # that we can't tell which one to keep. Don't complain at all if the
<add> # only installed version is a pinned formula.
<add> opoo "Skipping #{full_name}: most recent version #{f.pkg_version} not installed"
<add> end
<add> eligible_for_cleanup
<add> end
<add>
<add> # @private
<add> def eligible_for_cleanup?
<add> # It used to be the case that keg-only kegs could not be cleaned up, because
<add> # older brews were built against the full path to the keg-only keg. Then we
<add> # introduced the opt symlink, and built against that instead. So provided
<add> # no brew exists that was built against an old-style keg-only keg, we can
<add> # remove it.
<add> if !keg_only? || ARGV.force?
<add> true
<add> elsif opt_prefix.directory?
<add> # SHA records were added to INSTALL_RECEIPTS the same day as opt symlinks
<add> Formula.installed.select do |f|
<add> f.deps.any? do |d|
<add> d.to_formula.full_name == full_name rescue d.name == name
<add> end
<add> end.all? { |f| f.installed_prefixes.all? { |keg| Tab.for_keg(keg).HEAD } }
<add> end
<add> end
<add>
<ide> private
<ide>
<ide> def exec_cmd(cmd, args, out, logfn)
<ide><path>Library/Homebrew/test/test_cleanup.rb
<add>require "testing_env"
<add>require "testball"
<add>require "cleanup"
<add>require "fileutils"
<add>require "pathname"
<add>
<add>class CleanupTests < Homebrew::TestCase
<add> def setup
<add> @ds_store = Pathname.new "#{HOMEBREW_PREFIX}/Library/.DS_Store"
<add> FileUtils.touch @ds_store
<add> end
<add>
<add> def teardown
<add> FileUtils.rm_f @ds_store
<add> ARGV.delete "--dry-run"
<add> ARGV.delete "--prune=all"
<add> end
<add>
<add> def test_cleanup
<add> shutup { Homebrew::Cleanup.cleanup }
<add> refute_predicate @ds_store, :exist?
<add> end
<add>
<add> def test_cleanup_dry_run
<add> ARGV << "--dry-run"
<add> shutup { Homebrew::Cleanup.cleanup }
<add> assert_predicate @ds_store, :exist?
<add> end
<add>
<add> def test_cleanup_formula
<add> f1 = Class.new(Testball) { version "0.1" }.new
<add> f2 = Class.new(Testball) { version "0.2" }.new
<add> f3 = Class.new(Testball) { version "0.3" }.new
<add>
<add> shutup do
<add> f1.brew { f1.install }
<add> f2.brew { f2.install }
<add> f3.brew { f3.install }
<add> end
<add>
<add> assert_predicate f1, :installed?
<add> assert_predicate f2, :installed?
<add> assert_predicate f3, :installed?
<add>
<add> shutup { Homebrew::Cleanup.cleanup_formula f3 }
<add>
<add> refute_predicate f1, :installed?
<add> refute_predicate f2, :installed?
<add> assert_predicate f3, :installed?
<add> ensure
<add> [f1, f2, f3].each(&:clear_cache)
<add> f3.rack.rmtree
<add> end
<add>
<add> def test_cleanup_logs
<add> path = (HOMEBREW_LOGS/"delete_me")
<add> path.mkpath
<add> ARGV << "--prune=all"
<add> shutup { Homebrew::Cleanup.cleanup_logs }
<add> refute_predicate path, :exist?
<add> end
<add>
<add> def test_cleanup_cache_incomplete_downloads
<add> incomplete = (HOMEBREW_CACHE/"something.incomplete")
<add> incomplete.mkpath
<add> shutup { Homebrew::Cleanup.cleanup_cache }
<add> refute_predicate incomplete, :exist?
<add> end
<add>
<add> def test_cleanup_cache_java_cache
<add> java_cache = (HOMEBREW_CACHE/"java_cache")
<add> java_cache.mkpath
<add> shutup { Homebrew::Cleanup.cleanup_cache }
<add> refute_predicate java_cache, :exist?
<add> end
<add>end
<ide><path>Library/Homebrew/test/test_cmd_cleanup.rb
<del>require "testing_env"
<del>require "testball"
<del>require "cmd/cleanup"
<del>
<del>class CleanupTests < Homebrew::TestCase
<del> def test_cleanup
<del> f1 = Class.new(Testball) { version "0.1" }.new
<del> f2 = Class.new(Testball) { version "0.2" }.new
<del> f3 = Class.new(Testball) { version "0.3" }.new
<del>
<del> shutup do
<del> f1.brew { f1.install }
<del> f2.brew { f2.install }
<del> f3.brew { f3.install }
<del> end
<del>
<del> assert_predicate f1, :installed?
<del> assert_predicate f2, :installed?
<del> assert_predicate f3, :installed?
<del>
<del> shutup { Homebrew.cleanup_formula(f3) }
<del>
<del> refute_predicate f1, :installed?
<del> refute_predicate f2, :installed?
<del> assert_predicate f3, :installed?
<del> ensure
<del> [f1, f2, f3].each(&:clear_cache)
<del> f3.rack.rmtree
<del> end
<del>end
<ide><path>Library/Homebrew/test/test_formula.rb
<ide> require "testing_env"
<ide> require "testball"
<add>require "formula"
<ide>
<ide> class FormulaTests < Homebrew::TestCase
<ide> def test_formula_instantiation
<ide> def test_to_hash_bottle
<ide> assert h.is_a?(Hash), "Formula#to_hash should return a Hash"
<ide> assert h["versions"]["bottle"], "The hash should say the formula is bottled"
<ide> end
<add>
<add> def test_eligible_kegs_for_cleanup
<add> f1 = Class.new(Testball) { version "0.1" }.new
<add> f2 = Class.new(Testball) { version "0.2" }.new
<add> f3 = Class.new(Testball) { version "0.3" }.new
<add>
<add> shutup do
<add> f1.brew { f1.install }
<add> f2.brew { f2.install }
<add> f3.brew { f3.install }
<add> end
<add>
<add> assert_predicate f1, :installed?
<add> assert_predicate f2, :installed?
<add> assert_predicate f3, :installed?
<add>
<add> assert_equal f3.installed_kegs[0..1], f3.eligible_kegs_for_cleanup
<add> ensure
<add> [f1, f2, f3].each(&:clear_cache)
<add> f3.rack.rmtree
<add> end
<ide> end | 7 |
Go | Go | get events until a time in the past | 55053d3537100eaeaad9c83b43e31f22d14fde7b | <ide><path>api/server/router/system/backend.go
<ide> package system
<ide>
<ide> import (
<add> "time"
<add>
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/engine-api/types/events"
<ide> "github.com/docker/engine-api/types/filters"
<ide> import (
<ide> type Backend interface {
<ide> SystemInfo() (*types.Info, error)
<ide> SystemVersion() types.Version
<del> SubscribeToEvents(since, sinceNano int64, ef filters.Args) ([]events.Message, chan interface{})
<add> SubscribeToEvents(since, until time.Time, ef filters.Args) ([]events.Message, chan interface{})
<ide> UnsubscribeFromEvents(chan interface{})
<ide> AuthenticateToRegistry(ctx context.Context, authConfig *types.AuthConfig) (string, string, error)
<ide> }
<ide><path>api/server/router/system/system_routes.go
<ide> package system
<ide>
<ide> import (
<ide> "encoding/json"
<add> "fmt"
<ide> "net/http"
<ide> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/server/httputils"
<add> "github.com/docker/docker/errors"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/engine-api/types/events"
<ide> func (s *systemRouter) getEvents(ctx context.Context, w http.ResponseWriter, r *
<ide> if err := httputils.ParseForm(r); err != nil {
<ide> return err
<ide> }
<del> since, sinceNano, err := timetypes.ParseTimestamps(r.Form.Get("since"), -1)
<add>
<add> since, err := eventTime(r.Form.Get("since"))
<ide> if err != nil {
<ide> return err
<ide> }
<del> until, untilNano, err := timetypes.ParseTimestamps(r.Form.Get("until"), -1)
<add> until, err := eventTime(r.Form.Get("until"))
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> var timeout <-chan time.Time
<del> if until > 0 || untilNano > 0 {
<del> dur := time.Unix(until, untilNano).Sub(time.Now())
<del> timeout = time.NewTimer(dur).C
<add> var (
<add> timeout <-chan time.Time
<add> onlyPastEvents bool
<add> )
<add> if !until.IsZero() {
<add> if until.Before(since) {
<add> return errors.NewBadRequestError(fmt.Errorf("`since` time (%s) cannot be after `until` time (%s)", r.Form.Get("since"), r.Form.Get("until")))
<add> }
<add>
<add> now := time.Now()
<add>
<add> onlyPastEvents = until.Before(now)
<add>
<add> if !onlyPastEvents {
<add> dur := until.Sub(now)
<add> timeout = time.NewTimer(dur).C
<add> }
<ide> }
<ide>
<ide> ef, err := filters.FromParam(r.Form.Get("filters"))
<ide> func (s *systemRouter) getEvents(ctx context.Context, w http.ResponseWriter, r *
<ide>
<ide> enc := json.NewEncoder(output)
<ide>
<del> buffered, l := s.backend.SubscribeToEvents(since, sinceNano, ef)
<add> buffered, l := s.backend.SubscribeToEvents(since, until, ef)
<ide> defer s.backend.UnsubscribeFromEvents(l)
<ide>
<ide> for _, ev := range buffered {
<ide> func (s *systemRouter) getEvents(ctx context.Context, w http.ResponseWriter, r *
<ide> }
<ide> }
<ide>
<add> if onlyPastEvents {
<add> return nil
<add> }
<add>
<ide> for {
<ide> select {
<ide> case ev := <-l:
<ide> func (s *systemRouter) postAuth(ctx context.Context, w http.ResponseWriter, r *h
<ide> IdentityToken: token,
<ide> })
<ide> }
<add>
<add>func eventTime(formTime string) (time.Time, error) {
<add> t, tNano, err := timetypes.ParseTimestamps(formTime, -1)
<add> if err != nil {
<add> return time.Time{}, err
<add> }
<add> if t == -1 {
<add> return time.Time{}, nil
<add> }
<add> return time.Unix(t, tNano), nil
<add>}
<ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/docker/docker/errors"
<ide> "github.com/docker/engine-api/types"
<ide> containertypes "github.com/docker/engine-api/types/container"
<del> eventtypes "github.com/docker/engine-api/types/events"
<del> "github.com/docker/engine-api/types/filters"
<ide> networktypes "github.com/docker/engine-api/types/network"
<ide> registrytypes "github.com/docker/engine-api/types/registry"
<ide> "github.com/docker/engine-api/types/strslice"
<ide> func (daemon *Daemon) GetByName(name string) (*container.Container, error) {
<ide> return e, nil
<ide> }
<ide>
<del>// SubscribeToEvents returns the currently record of events, a channel to stream new events from, and a function to cancel the stream of events.
<del>func (daemon *Daemon) SubscribeToEvents(since, sinceNano int64, filter filters.Args) ([]eventtypes.Message, chan interface{}) {
<del> ef := events.NewFilter(filter)
<del> return daemon.EventsService.SubscribeTopic(since, sinceNano, ef)
<del>}
<del>
<del>// UnsubscribeFromEvents stops the event subscription for a client by closing the
<del>// channel where the daemon sends events to.
<del>func (daemon *Daemon) UnsubscribeFromEvents(listener chan interface{}) {
<del> daemon.EventsService.Evict(listener)
<del>}
<del>
<ide> // GetLabels for a container or image id
<ide> func (daemon *Daemon) GetLabels(id string) map[string]string {
<ide> // TODO: TestCase
<ide><path>daemon/events.go
<ide> package daemon
<ide>
<ide> import (
<ide> "strings"
<add> "time"
<ide>
<ide> "github.com/docker/docker/container"
<add> daemonevents "github.com/docker/docker/daemon/events"
<ide> "github.com/docker/engine-api/types/events"
<add> "github.com/docker/engine-api/types/filters"
<ide> "github.com/docker/libnetwork"
<ide> )
<ide>
<ide> func (daemon *Daemon) LogNetworkEventWithAttributes(nw libnetwork.Network, actio
<ide> daemon.EventsService.Log(action, events.NetworkEventType, actor)
<ide> }
<ide>
<add>// SubscribeToEvents returns the currently record of events, a channel to stream new events from, and a function to cancel the stream of events.
<add>func (daemon *Daemon) SubscribeToEvents(since, until time.Time, filter filters.Args) ([]events.Message, chan interface{}) {
<add> ef := daemonevents.NewFilter(filter)
<add> return daemon.EventsService.SubscribeTopic(since, until, ef)
<add>}
<add>
<add>// UnsubscribeFromEvents stops the event subscription for a client by closing the
<add>// channel where the daemon sends events to.
<add>func (daemon *Daemon) UnsubscribeFromEvents(listener chan interface{}) {
<add> daemon.EventsService.Evict(listener)
<add>}
<add>
<ide> // copyAttributes guarantees that labels are not mutated by event triggers.
<ide> func copyAttributes(attributes, labels map[string]string) {
<ide> if labels == nil {
<ide><path>daemon/events/events.go
<ide> func (e *Events) Subscribe() ([]eventtypes.Message, chan interface{}, func()) {
<ide> // SubscribeTopic adds new listener to events, returns slice of 64 stored
<ide> // last events, a channel in which you can expect new events (in form
<ide> // of interface{}, so you need type assertion).
<del>func (e *Events) SubscribeTopic(since, sinceNano int64, ef *Filter) ([]eventtypes.Message, chan interface{}) {
<add>func (e *Events) SubscribeTopic(since, until time.Time, ef *Filter) ([]eventtypes.Message, chan interface{}) {
<ide> e.mu.Lock()
<ide>
<ide> var topic func(m interface{}) bool
<ide> if ef != nil && ef.filter.Len() > 0 {
<ide> topic = func(m interface{}) bool { return ef.Include(m.(eventtypes.Message)) }
<ide> }
<ide>
<del> buffered := e.loadBufferedEvents(since, sinceNano, topic)
<add> buffered := e.loadBufferedEvents(since, until, topic)
<ide>
<ide> var ch chan interface{}
<ide> if topic != nil {
<ide> func (e *Events) SubscribersCount() int {
<ide> }
<ide>
<ide> // loadBufferedEvents iterates over the cached events in the buffer
<del>// and returns those that were emitted before a specific date.
<del>// The date is splitted in two values:
<del>// - the `since` argument is a date timestamp without nanoseconds, or -1 to return an empty slice.
<del>// - the `sinceNano` argument is the nanoseconds offset from the timestamp.
<del>// It uses `time.Unix(seconds, nanoseconds)` to generate a valid date with those two first arguments.
<add>// and returns those that were emitted between two specific dates.
<add>// It uses `time.Unix(seconds, nanoseconds)` to generate valid dates with those arguments.
<ide> // It filters those buffered messages with a topic function if it's not nil, otherwise it adds all messages.
<del>func (e *Events) loadBufferedEvents(since, sinceNano int64, topic func(interface{}) bool) []eventtypes.Message {
<add>func (e *Events) loadBufferedEvents(since, until time.Time, topic func(interface{}) bool) []eventtypes.Message {
<ide> var buffered []eventtypes.Message
<del> if since == -1 {
<add> if since.IsZero() && until.IsZero() {
<ide> return buffered
<ide> }
<ide>
<del> sinceNanoUnix := time.Unix(since, sinceNano).UnixNano()
<add> var sinceNanoUnix int64
<add> if !since.IsZero() {
<add> sinceNanoUnix = since.UnixNano()
<add> }
<add>
<add> var untilNanoUnix int64
<add> if !until.IsZero() {
<add> untilNanoUnix = until.UnixNano()
<add> }
<add>
<ide> for i := len(e.events) - 1; i >= 0; i-- {
<ide> ev := e.events[i]
<add>
<ide> if ev.TimeNano < sinceNanoUnix {
<ide> break
<ide> }
<add>
<add> if untilNanoUnix > 0 && ev.TimeNano > untilNanoUnix {
<add> continue
<add> }
<add>
<ide> if topic == nil || topic(ev) {
<ide> buffered = append([]eventtypes.Message{ev}, buffered...)
<ide> }
<ide><path>daemon/events/events_test.go
<ide> func TestLoadBufferedEvents(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> since, sinceNano, err := timetypes.ParseTimestamps(f, -1)
<add> s, sNano, err := timetypes.ParseTimestamps(f, -1)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestLoadBufferedEvents(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> buffered := []events.Message{*m1, *m2, *m3}
<add> events := &Events{
<add> events: []events.Message{*m1, *m2, *m3},
<add> }
<add>
<add> since := time.Unix(s, sNano)
<add> until := time.Time{}
<add>
<add> out := events.loadBufferedEvents(since, until, nil)
<add> if len(out) != 1 {
<add> t.Fatalf("expected 1 message, got %d: %v", len(out), out)
<add> }
<add>}
<add>
<add>func TestLoadBufferedEventsOnlyFromPast(t *testing.T) {
<add> now := time.Now()
<add> f, err := timetypes.GetTimestamp("2016-03-07T17:28:03.090000000+02:00", now)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> s, sNano, err := timetypes.ParseTimestamps(f, 0)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> f, err = timetypes.GetTimestamp("2016-03-07T17:28:03.100000000+02:00", now)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> u, uNano, err := timetypes.ParseTimestamps(f, 0)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> m1, err := eventstestutils.Scan("2016-03-07T17:28:03.022433271+02:00 container die 0b863f2a26c18557fc6cdadda007c459f9ec81b874780808138aea78a3595079 (image=ubuntu, name=small_hoover)")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> m2, err := eventstestutils.Scan("2016-03-07T17:28:03.091719377+02:00 network disconnect 19c5ed41acb798f26b751e0035cd7821741ab79e2bbd59a66b5fd8abf954eaa0 (type=bridge, container=0b863f2a26c18557fc6cdadda007c459f9ec81b874780808138aea78a3595079, name=bridge)")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> m3, err := eventstestutils.Scan("2016-03-07T17:28:03.129014751+02:00 container destroy 0b863f2a26c18557fc6cdadda007c459f9ec81b874780808138aea78a3595079 (image=ubuntu, name=small_hoover)")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<ide>
<ide> events := &Events{
<del> events: buffered,
<add> events: []events.Message{*m1, *m2, *m3},
<ide> }
<ide>
<del> out := events.loadBufferedEvents(since, sinceNano, nil)
<add> since := time.Unix(s, sNano)
<add> until := time.Unix(u, uNano)
<add>
<add> out := events.loadBufferedEvents(since, until, nil)
<ide> if len(out) != 1 {
<ide> t.Fatalf("expected 1 message, got %d: %v", len(out), out)
<ide> }
<add>
<add> if out[0].Type != "network" {
<add> t.Fatalf("expected network event, got %s", out[0].Type)
<add> }
<add>}
<add>
<add>// #13753
<add>func TestIngoreBufferedWhenNoTimes(t *testing.T) {
<add> m1, err := eventstestutils.Scan("2016-03-07T17:28:03.022433271+02:00 container die 0b863f2a26c18557fc6cdadda007c459f9ec81b874780808138aea78a3595079 (image=ubuntu, name=small_hoover)")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> m2, err := eventstestutils.Scan("2016-03-07T17:28:03.091719377+02:00 network disconnect 19c5ed41acb798f26b751e0035cd7821741ab79e2bbd59a66b5fd8abf954eaa0 (type=bridge, container=0b863f2a26c18557fc6cdadda007c459f9ec81b874780808138aea78a3595079, name=bridge)")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> m3, err := eventstestutils.Scan("2016-03-07T17:28:03.129014751+02:00 container destroy 0b863f2a26c18557fc6cdadda007c459f9ec81b874780808138aea78a3595079 (image=ubuntu, name=small_hoover)")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> events := &Events{
<add> events: []events.Message{*m1, *m2, *m3},
<add> }
<add>
<add> since := time.Time{}
<add> until := time.Time{}
<add>
<add> out := events.loadBufferedEvents(since, until, nil)
<add> if len(out) != 0 {
<add> t.Fatalf("expected 0 buffered events, got %q", out)
<add> }
<ide> }
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildNoNamedVolume(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildTagEvent(c *check.C) {
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide>
<ide> dockerFile := `FROM busybox
<ide> RUN echo events
<ide> `
<ide> _, err := buildImage("test", dockerFile, false)
<ide> c.Assert(err, check.IsNil)
<ide>
<del> out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "type=image")
<add> until := daemonUnixTime(c)
<add> out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "type=image")
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> actions := eventActionsByIDAndType(c, events, "test:latest", "image")
<ide> var foundTag bool
<ide><path>integration-cli/docker_cli_events_test.go
<ide> import (
<ide> "net/http"
<ide> "os"
<ide> "os/exec"
<del> "strconv"
<ide> "strings"
<ide> "sync"
<ide> "time"
<ide> func (s *DockerSuite) TestEventsTimestampFormats(c *check.C) {
<ide> c.Assert(containerEvents[3], checker.Equals, "die", check.Commentf(out))
<ide> c.Assert(containerEvents[4], checker.Equals, "destroy", check.Commentf(out))
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsUntag(c *check.C) {
<ide> func (s *DockerSuite) TestEventsContainerFailStartDie(c *check.C) {
<ide> _, _, err := dockerCmdWithError("run", "--name", "testeventdie", "busybox", "blerg")
<ide> c.Assert(err, checker.NotNil, check.Commentf("Container run with command blerg should have failed, but it did not"))
<ide>
<del> out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c))
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide>
<ide> nEvents := len(events)
<ide> func (s *DockerSuite) TestEventsLimit(c *check.C) {
<ide> c.Assert(err, checker.IsNil, check.Commentf("%q failed with error", strings.Join(args, " ")))
<ide> }
<ide>
<del> out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c))
<ide> events := strings.Split(out, "\n")
<ide> nEvents := len(events) - 1
<ide> c.Assert(nEvents, checker.Equals, 64, check.Commentf("events should be limited to 64, but received %d", nEvents))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsContainerEvents(c *check.C) {
<del> containerID, _ := dockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true")
<del> containerID = strings.TrimSpace(containerID)
<add> dockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true")
<ide>
<del> out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--until", daemonUnixTime(c))
<ide> events := strings.Split(out, "\n")
<ide> events = events[:len(events)-1]
<ide>
<ide> func (s *DockerSuite) TestEventsContainerEvents(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsContainerEventsAttrSort(c *check.C) {
<del> since := daemonTime(c).Unix()
<del> containerID, _ := dockerCmd(c, "run", "-d", "--name", "container-events-test", "busybox", "true")
<del> containerID = strings.TrimSpace(containerID)
<add> since := daemonUnixTime(c)
<add> dockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true")
<ide>
<del> out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--filter", "container=container-events-test", "--since", since, "--until", daemonUnixTime(c))
<ide> events := strings.Split(out, "\n")
<ide>
<ide> nEvents := len(events)
<ide> c.Assert(nEvents, checker.GreaterOrEqualThan, 3) //Missing expected event
<ide> matchedEvents := 0
<ide> for _, event := range events {
<ide> matches := eventstestutils.ScanMap(event)
<del> if matches["id"] != containerID {
<del> continue
<del> }
<ide> if matches["eventType"] == "container" && matches["action"] == "create" {
<ide> matchedEvents++
<ide> c.Assert(out, checker.Contains, "(image=busybox, name=container-events-test)", check.Commentf("Event attributes not sorted"))
<ide> func (s *DockerSuite) TestEventsContainerEventsAttrSort(c *check.C) {
<ide> c.Assert(out, checker.Contains, "(image=busybox, name=container-events-test)", check.Commentf("Event attributes not sorted"))
<ide> }
<ide> }
<del> c.Assert(matchedEvents, checker.Equals, 2)
<add> c.Assert(matchedEvents, checker.Equals, 2, check.Commentf("missing events for container container-events-test:\n%s", out))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *check.C) {
<ide> dockerCmd(c, "run", "--rm", "--name", "since-epoch-test", "busybox", "true")
<ide> timeBeginning := time.Unix(0, 0).Format(time.RFC3339Nano)
<ide> timeBeginning = strings.Replace(timeBeginning, "Z", ".000000000Z", -1)
<del> out, _ := dockerCmd(c, "events", fmt.Sprintf("--since='%s'", timeBeginning), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--since", timeBeginning, "--until", daemonUnixTime(c))
<ide> events := strings.Split(out, "\n")
<ide> events = events[:len(events)-1]
<ide>
<ide> func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestEventsImageTag(c *check.C) {
<ide> time.Sleep(1 * time.Second) // because API has seconds granularity
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide> image := "testimageevents:tag"
<ide> dockerCmd(c, "tag", "busybox", image)
<ide>
<ide> out, _ := dockerCmd(c, "events",
<del> fmt.Sprintf("--since=%d", since),
<del> fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> "--since", since, "--until", daemonUnixTime(c))
<ide>
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(events, checker.HasLen, 1, check.Commentf("was expecting 1 event. out=%s", out))
<ide> func (s *DockerSuite) TestEventsImageTag(c *check.C) {
<ide> func (s *DockerSuite) TestEventsImagePull(c *check.C) {
<ide> // TODO Windows: Enable this test once pull and reliable image names are available
<ide> testRequires(c, DaemonIsLinux)
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide> testRequires(c, Network)
<ide>
<ide> dockerCmd(c, "pull", "hello-world")
<ide>
<ide> out, _ := dockerCmd(c, "events",
<del> fmt.Sprintf("--since=%d", since),
<del> fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> "--since", since, "--until", daemonUnixTime(c))
<ide>
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> event := strings.TrimSpace(events[len(events)-1])
<ide> func (s *DockerSuite) TestEventsImageImport(c *check.C) {
<ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide>
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide> out, _, err := runCommandPipelineWithOutput(
<ide> exec.Command(dockerBinary, "export", cleanedContainerID),
<ide> exec.Command(dockerBinary, "import", "-"),
<ide> )
<ide> c.Assert(err, checker.IsNil, check.Commentf("import failed with output: %q", out))
<ide> imageRef := strings.TrimSpace(out)
<ide>
<del> out, _ = dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "event=import")
<add> out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=import")
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(events, checker.HasLen, 1)
<ide> matches := eventstestutils.ScanMap(events[0])
<ide> func (s *DockerSuite) TestEventsImageImport(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsFilters(c *check.C) {
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide> dockerCmd(c, "run", "--rm", "busybox", "true")
<ide> dockerCmd(c, "run", "--rm", "busybox", "true")
<del> out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "event=die")
<add> out, _ := dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=die")
<ide> parseEvents(c, out, "die")
<ide>
<del> out, _ = dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "event=die", "--filter", "event=start")
<add> out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=die", "--filter", "event=start")
<ide> parseEvents(c, out, "die|start")
<ide>
<ide> // make sure we at least got 2 start events
<ide> func (s *DockerSuite) TestEventsFilters(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsFilterImageName(c *check.C) {
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide>
<ide> out, _ := dockerCmd(c, "run", "--name", "container_1", "-d", "busybox:latest", "true")
<ide> container1 := strings.TrimSpace(out)
<ide> func (s *DockerSuite) TestEventsFilterImageName(c *check.C) {
<ide> container2 := strings.TrimSpace(out)
<ide>
<ide> name := "busybox"
<del> out, _ = dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", fmt.Sprintf("image=%s", name))
<add> out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("image=%s", name))
<ide> events := strings.Split(out, "\n")
<ide> events = events[:len(events)-1]
<ide> c.Assert(events, checker.Not(checker.HasLen), 0) //Expected events but found none for the image busybox:latest
<ide> func (s *DockerSuite) TestEventsFilterImageName(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsFilterLabels(c *check.C) {
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide> label := "io.docker.testing=foo"
<ide>
<ide> out, _ := dockerCmd(c, "run", "-d", "-l", label, "busybox:latest", "true")
<ide> func (s *DockerSuite) TestEventsFilterLabels(c *check.C) {
<ide> out, _ = dockerCmd(
<ide> c,
<ide> "events",
<del> fmt.Sprintf("--since=%d", since),
<del> fmt.Sprintf("--until=%d", daemonTime(c).Unix()),
<add> "--since", since,
<add> "--until", daemonUnixTime(c),
<ide> "--filter", fmt.Sprintf("label=%s", label))
<ide>
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> func (s *DockerSuite) TestEventsFilterLabels(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsFilterImageLabels(c *check.C) {
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide> name := "labelfiltertest"
<ide> label := "io.docker.testing=image"
<ide>
<ide> func (s *DockerSuite) TestEventsFilterImageLabels(c *check.C) {
<ide> out, _ := dockerCmd(
<ide> c,
<ide> "events",
<del> fmt.Sprintf("--since=%d", since),
<del> fmt.Sprintf("--until=%d", daemonTime(c).Unix()),
<add> "--since", since,
<add> "--until", daemonUnixTime(c),
<ide> "--filter", fmt.Sprintf("label=%s", label),
<ide> "--filter", "type=image")
<ide>
<ide> func (s *DockerSuite) TestEventsFilterImageLabels(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsFilterContainer(c *check.C) {
<del> since := fmt.Sprintf("%d", daemonTime(c).Unix())
<add> since := daemonUnixTime(c)
<ide> nameID := make(map[string]string)
<ide>
<ide> for _, name := range []string{"container_1", "container_2"} {
<ide> func (s *DockerSuite) TestEventsFilterContainer(c *check.C) {
<ide> nameID[name] = id
<ide> }
<ide>
<del> until := fmt.Sprintf("%d", daemonTime(c).Unix())
<add> until := daemonUnixTime(c)
<ide>
<ide> checkEvents := func(id string, events []string) error {
<ide> if len(events) != 4 { // create, attach, start, die
<ide> func (s *DockerSuite) TestEventsFilterContainer(c *check.C) {
<ide> func (s *DockerSuite) TestEventsCommit(c *check.C) {
<ide> // Problematic on Windows as cannot commit a running container
<ide> testRequires(c, DaemonIsLinux)
<del> since := daemonTime(c).Unix()
<ide>
<del> out, _ := runSleepingContainer(c, "-d")
<add> out, _ := runSleepingContainer(c)
<ide> cID := strings.TrimSpace(out)
<ide> c.Assert(waitRun(cID), checker.IsNil)
<ide>
<ide> dockerCmd(c, "commit", "-m", "test", cID)
<ide> dockerCmd(c, "stop", cID)
<add> c.Assert(waitExited(cID, 5*time.Second), checker.IsNil)
<ide>
<del> out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since)))
<add> until := daemonUnixTime(c)
<add> out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until)
<ide> c.Assert(out, checker.Contains, "commit", check.Commentf("Missing 'commit' log event"))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsCopy(c *check.C) {
<del> since := daemonTime(c).Unix()
<del>
<ide> // Build a test image.
<ide> id, err := buildImage("cpimg", `
<ide> FROM busybox
<ide> func (s *DockerSuite) TestEventsCopy(c *check.C) {
<ide>
<ide> dockerCmd(c, "cp", "cptest:/file", tempFile.Name())
<ide>
<del> out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+strconv.Itoa(int(since)))
<add> until := daemonUnixTime(c)
<add> out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+until)
<ide> c.Assert(out, checker.Contains, "archive-path", check.Commentf("Missing 'archive-path' log event\n"))
<ide>
<ide> dockerCmd(c, "cp", tempFile.Name(), "cptest:/filecopy")
<ide>
<del> out, _ = dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+strconv.Itoa(int(since)))
<add> until = daemonUnixTime(c)
<add> out, _ = dockerCmd(c, "events", "-f", "container=cptest", "--until="+until)
<ide> c.Assert(out, checker.Contains, "extract-to-dir", check.Commentf("Missing 'extract-to-dir' log event"))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsResize(c *check.C) {
<del> since := daemonTime(c).Unix()
<del>
<ide> out, _ := runSleepingContainer(c, "-d")
<ide> cID := strings.TrimSpace(out)
<ide> c.Assert(waitRun(cID), checker.IsNil)
<ide> func (s *DockerSuite) TestEventsResize(c *check.C) {
<ide>
<ide> dockerCmd(c, "stop", cID)
<ide>
<del> out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since)))
<add> until := daemonUnixTime(c)
<add> out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until)
<ide> c.Assert(out, checker.Contains, "resize", check.Commentf("Missing 'resize' log event"))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsAttach(c *check.C) {
<ide> // TODO Windows CI: Figure out why this test fails intermittently (TP4 and TP5).
<ide> testRequires(c, DaemonIsLinux)
<del> since := daemonTime(c).Unix()
<ide>
<ide> out, _ := dockerCmd(c, "run", "-di", "busybox", "cat")
<ide> cID := strings.TrimSpace(out)
<add> c.Assert(waitRun(cID), checker.IsNil)
<ide>
<ide> cmd := exec.Command(dockerBinary, "attach", cID)
<ide> stdin, err := cmd.StdinPipe()
<ide> func (s *DockerSuite) TestEventsAttach(c *check.C) {
<ide> c.Assert(stdin.Close(), checker.IsNil)
<ide>
<ide> dockerCmd(c, "kill", cID)
<add> c.Assert(waitExited(cID, 5*time.Second), checker.IsNil)
<ide>
<del> out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since)))
<add> until := daemonUnixTime(c)
<add> out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until)
<ide> c.Assert(out, checker.Contains, "attach", check.Commentf("Missing 'attach' log event"))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsRename(c *check.C) {
<del> since := daemonTime(c).Unix()
<del>
<del> dockerCmd(c, "run", "--name", "oldName", "busybox", "true")
<add> out, _ := dockerCmd(c, "run", "--name", "oldName", "busybox", "true")
<add> cID := strings.TrimSpace(out)
<ide> dockerCmd(c, "rename", "oldName", "newName")
<ide>
<del> out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=newName", "--until="+strconv.Itoa(int(since)))
<add> until := daemonUnixTime(c)
<add> // filter by the container id because the name in the event will be the new name.
<add> out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until", until)
<ide> c.Assert(out, checker.Contains, "rename", check.Commentf("Missing 'rename' log event\n"))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsTop(c *check.C) {
<ide> // Problematic on Windows as Windows does not support top
<ide> testRequires(c, DaemonIsLinux)
<del> since := daemonTime(c).Unix()
<ide>
<ide> out, _ := runSleepingContainer(c, "-d")
<ide> cID := strings.TrimSpace(out)
<ide> func (s *DockerSuite) TestEventsTop(c *check.C) {
<ide> dockerCmd(c, "top", cID)
<ide> dockerCmd(c, "stop", cID)
<ide>
<del> out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since)))
<add> until := daemonUnixTime(c)
<add> out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until)
<ide> c.Assert(out, checker.Contains, " top", check.Commentf("Missing 'top' log event"))
<ide> }
<ide>
<del>// #13753
<del>func (s *DockerSuite) TestEventsDefaultEmpty(c *check.C) {
<del> dockerCmd(c, "run", "busybox")
<del> out, _ := dockerCmd(c, "events", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<del> c.Assert(strings.TrimSpace(out), checker.Equals, "")
<del>}
<del>
<ide> // #14316
<ide> func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *check.C) {
<ide> // Problematic to port for Windows CI during TP4/TP5 timeframe while
<ide> // not supporting push
<ide> testRequires(c, DaemonIsLinux)
<ide> testRequires(c, Network)
<del> since := daemonTime(c).Unix()
<ide> repoName := fmt.Sprintf("%v/dockercli/testf", privateRegistryURL)
<ide>
<ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
<ide> func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *check.C) {
<ide> dockerCmd(c, "stop", cID)
<ide> dockerCmd(c, "push", repoName)
<ide>
<del> out, _ = dockerCmd(c, "events", "--since=0", "-f", "image="+repoName, "-f", "event=push", "--until="+strconv.Itoa(int(since)))
<add> until := daemonUnixTime(c)
<add> out, _ = dockerCmd(c, "events", "-f", "image="+repoName, "-f", "event=push", "--until", until)
<ide> c.Assert(out, checker.Contains, repoName, check.Commentf("Missing 'push' log event for %s", repoName))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsFilterType(c *check.C) {
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide> name := "labelfiltertest"
<ide> label := "io.docker.testing=image"
<ide>
<ide> func (s *DockerSuite) TestEventsFilterType(c *check.C) {
<ide> out, _ := dockerCmd(
<ide> c,
<ide> "events",
<del> fmt.Sprintf("--since=%d", since),
<del> fmt.Sprintf("--until=%d", daemonTime(c).Unix()),
<add> "--since", since,
<add> "--until", daemonUnixTime(c),
<ide> "--filter", fmt.Sprintf("label=%s", label),
<ide> "--filter", "type=image")
<ide>
<ide> func (s *DockerSuite) TestEventsFilterType(c *check.C) {
<ide> out, _ = dockerCmd(
<ide> c,
<ide> "events",
<del> fmt.Sprintf("--since=%d", since),
<del> fmt.Sprintf("--until=%d", daemonTime(c).Unix()),
<add> "--since", since,
<add> "--until", daemonUnixTime(c),
<ide> "--filter", fmt.Sprintf("label=%s", label),
<ide> "--filter", "type=container")
<ide> events = strings.Split(strings.TrimSpace(out), "\n")
<ide> func (s *DockerSuite) TestEventsFilterType(c *check.C) {
<ide> out, _ = dockerCmd(
<ide> c,
<ide> "events",
<del> fmt.Sprintf("--since=%d", since),
<del> fmt.Sprintf("--until=%d", daemonTime(c).Unix()),
<add> "--since", since,
<add> "--until", daemonUnixTime(c),
<ide> "--filter", "type=network")
<ide> events = strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(len(events), checker.GreaterOrEqualThan, 1, check.Commentf("Events == %s", events))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsFilterImageInContainerAction(c *check.C) {
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide> dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true")
<ide> waitRun("test-container")
<ide>
<del> out, _ := dockerCmd(c, "events", "--filter", "image=busybox", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", daemonUnixTime(c))
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(len(events), checker.GreaterThan, 1, check.Commentf(out))
<ide> }
<ide> func (s *DockerSuite) TestEventsContainerRestart(c *check.C) {
<ide> startCount int
<ide> dieCount int
<ide> )
<del> out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "-f", "container=testEvent")
<add> out, _ := dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container=testEvent")
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide>
<ide> nEvents := len(events)
<ide> func (s *DockerSuite) TestEventsContainerRestart(c *check.C) {
<ide> c.Assert(createCount, checker.Equals, 1, check.Commentf("testEvent should be created 1 times: %v", actions))
<ide> c.Assert(startCount, checker.Equals, 4, check.Commentf("testEvent should start 4 times: %v", actions))
<ide> c.Assert(dieCount, checker.Equals, 4, check.Commentf("testEvent should die 4 times: %v", actions))
<add>}
<add>
<add>func (s *DockerSuite) TestEventsSinceInTheFuture(c *check.C) {
<add> dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true")
<add> waitRun("test-container")
<add>
<add> since := daemonTime(c)
<add> until := since.Add(time.Duration(-24) * time.Hour)
<add> out, _, err := dockerCmdWithError("events", "--filter", "image=busybox", "--since", parseEventTime(since), "--until", parseEventTime(until))
<add>
<add> c.Assert(err, checker.NotNil)
<add> c.Assert(out, checker.Contains, "cannot be after `until`")
<add>}
<add>
<add>func (s *DockerSuite) TestEventsUntilInThePast(c *check.C) {
<add> since := daemonUnixTime(c)
<add>
<add> dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true")
<add> waitRun("test-container")
<add>
<add> until := daemonUnixTime(c)
<add>
<add> dockerCmd(c, "run", "--name", "test-container2", "-d", "busybox", "true")
<add> waitRun("test-container2")
<add>
<add> out, _ := dockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", until)
<ide>
<add> c.Assert(out, checker.Not(checker.Contains), "test-container2")
<add> c.Assert(out, checker.Contains, "test-container")
<ide> }
<ide><path>integration-cli/docker_cli_events_unix_test.go
<ide> import (
<ide>
<ide> // #5979
<ide> func (s *DockerSuite) TestEventsRedirectStdout(c *check.C) {
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide> dockerCmd(c, "run", "busybox", "true")
<ide>
<ide> file, err := ioutil.TempFile("", "")
<ide> c.Assert(err, checker.IsNil, check.Commentf("could not create temp file"))
<ide> defer os.Remove(file.Name())
<ide>
<del> command := fmt.Sprintf("%s events --since=%d --until=%d > %s", dockerBinary, since, daemonTime(c).Unix(), file.Name())
<add> command := fmt.Sprintf("%s events --since=%s --until=%s > %s", dockerBinary, since, daemonUnixTime(c), file.Name())
<ide> _, tty, err := pty.Open()
<ide> c.Assert(err, checker.IsNil, check.Commentf("Could not open pty"))
<ide> cmd := exec.Command("sh", "-c", command)
<ide> func (s *DockerSuite) TestEventsOOMDisableFalse(c *check.C) {
<ide> c.Fatal("Timeout waiting for container to die on OOM")
<ide> }
<ide>
<del> out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=oomFalse", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=oomFalse", "--until", daemonUnixTime(c))
<ide> events := strings.Split(strings.TrimSuffix(out, "\n"), "\n")
<ide> nEvents := len(events)
<ide>
<ide> func (s *DockerSuite) TestEventsContainerFilterByName(c *check.C) {
<ide> cOut, _ = dockerCmd(c, "run", "--name=bar", "-d", "busybox", "top")
<ide> c2 := strings.TrimSpace(cOut)
<ide> waitRun("bar")
<del> out, _ := dockerCmd(c, "events", "-f", "container=foo", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "-f", "container=foo", "--since=0", "--until", daemonUnixTime(c))
<ide> c.Assert(out, checker.Contains, c1, check.Commentf(out))
<ide> c.Assert(out, checker.Not(checker.Contains), c2, check.Commentf(out))
<ide> }
<ide> func (s *DockerSuite) TestEventsContainerFilterBeforeCreate(c *check.C) {
<ide>
<ide> // calculate the time it takes to create and start a container and sleep 2 seconds
<ide> // this is to make sure the docker event will recevie the event of container
<del> since := daemonTime(c).Unix()
<add> since := daemonTime(c)
<ide> id, _ := dockerCmd(c, "run", "-d", "busybox", "top")
<ide> cID := strings.TrimSpace(id)
<ide> waitRun(cID)
<ide> time.Sleep(2 * time.Second)
<del> duration := daemonTime(c).Unix() - since
<add> duration := daemonTime(c).Sub(since)
<ide>
<ide> go func() {
<del> out, _ = dockerCmd(c, "events", "-f", "container=foo", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()+2*duration))
<add> // start events and wait for future events to
<add> // make sure the new container shows up even when
<add> // the event stream was created before the container.
<add> t := daemonTime(c).Add(2 * duration)
<add> out, _ = dockerCmd(c, "events", "-f", "container=foo", "--since=0", "--until", parseEventTime(t))
<ide> close(ch)
<ide> }()
<ide> // Sleep 2 second to wait docker event to start
<ide> func (s *DockerSuite) TestEventsContainerFilterBeforeCreate(c *check.C) {
<ide> func (s *DockerSuite) TestVolumeEvents(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide>
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide>
<ide> // Observe create/mount volume actions
<ide> dockerCmd(c, "volume", "create", "--name", "test-event-volume-local")
<ide> func (s *DockerSuite) TestVolumeEvents(c *check.C) {
<ide> dockerCmd(c, "rm", "-f", "test-volume-container")
<ide> dockerCmd(c, "volume", "rm", "test-event-volume-local")
<ide>
<del> out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> until := daemonUnixTime(c)
<add> out, _ := dockerCmd(c, "events", "--since", since, "--until", until)
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(len(events), checker.GreaterThan, 4)
<ide>
<ide> func (s *DockerSuite) TestVolumeEvents(c *check.C) {
<ide> func (s *DockerSuite) TestNetworkEvents(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide>
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide>
<ide> // Observe create/connect network actions
<ide> dockerCmd(c, "network", "create", "test-event-network-local")
<ide> func (s *DockerSuite) TestNetworkEvents(c *check.C) {
<ide> dockerCmd(c, "rm", "-f", "test-network-container")
<ide> dockerCmd(c, "network", "rm", "test-event-network-local")
<ide>
<del> out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> until := daemonUnixTime(c)
<add> out, _ := dockerCmd(c, "events", "--since", since, "--until", until)
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(len(events), checker.GreaterThan, 4)
<ide>
<ide> func (s *DockerSuite) TestEventsImageUntagDelete(c *check.C) {
<ide> func (s *DockerSuite) TestEventsFilterVolumeAndNetworkType(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide>
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide>
<ide> dockerCmd(c, "network", "create", "test-event-network-type")
<ide> dockerCmd(c, "volume", "create", "--name", "test-event-volume-type")
<ide>
<del> out, _ := dockerCmd(c, "events", "--filter", "type=volume", "--filter", "type=network", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--filter", "type=volume", "--filter", "type=network", "--since", since, "--until", daemonUnixTime(c))
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(len(events), checker.GreaterOrEqualThan, 2, check.Commentf(out))
<ide>
<ide> func (s *DockerSuite) TestEventsFilterVolumeAndNetworkType(c *check.C) {
<ide> func (s *DockerSuite) TestEventsFilterVolumeID(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide>
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide>
<ide> dockerCmd(c, "volume", "create", "--name", "test-event-volume-id")
<del> out, _ := dockerCmd(c, "events", "--filter", "volume=test-event-volume-id", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--filter", "volume=test-event-volume-id", "--since", since, "--until", daemonUnixTime(c))
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(events, checker.HasLen, 1)
<ide>
<ide> func (s *DockerSuite) TestEventsFilterVolumeID(c *check.C) {
<ide> func (s *DockerSuite) TestEventsFilterNetworkID(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide>
<del> since := daemonTime(c).Unix()
<add> since := daemonUnixTime(c)
<ide>
<ide> dockerCmd(c, "network", "create", "test-event-network-local")
<del> out, _ := dockerCmd(c, "events", "--filter", "network=test-event-network-local", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--filter", "network=test-event-network-local", "--since", since, "--until", daemonUnixTime(c))
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(events, checker.HasLen, 1)
<ide>
<ide><path>integration-cli/docker_cli_pause_test.go
<ide> package main
<ide>
<ide> import (
<del> "fmt"
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/pkg/integration/checker"
<ide> func (s *DockerSuite) TestPause(c *check.C) {
<ide>
<ide> dockerCmd(c, "unpause", name)
<ide>
<del> out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c))
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> actions := eventActionsByIDAndType(c, events, name, "container")
<ide>
<ide> func (s *DockerSuite) TestPauseMultipleContainers(c *check.C) {
<ide>
<ide> dockerCmd(c, append([]string{"unpause"}, containers...)...)
<ide>
<del> out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c))
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide>
<ide> for _, name := range containers {
<ide><path>integration-cli/docker_utils.go
<ide> func daemonTime(c *check.C) time.Time {
<ide> return dt
<ide> }
<ide>
<add>// daemonUnixTime returns the current time on the daemon host with nanoseconds precission.
<add>// It return the time formatted how the client sends timestamps to the server.
<add>func daemonUnixTime(c *check.C) string {
<add> return parseEventTime(daemonTime(c))
<add>}
<add>
<add>func parseEventTime(t time.Time) string {
<add> return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond()))
<add>}
<add>
<ide> func setupRegistry(c *check.C, schema1 bool, auth, tokenURL string) *testRegistryV2 {
<ide> reg, err := newTestRegistryV2(c, schema1, auth, tokenURL)
<ide> c.Assert(err, check.IsNil)
<ide><path>integration-cli/events_utils.go
<ide> func (e *eventObserver) CheckEventError(c *check.C, id, event string, match even
<ide> scannerOut := e.buffer.String()
<ide>
<ide> if e.disconnectionError != nil {
<del> until := strconv.FormatInt(daemonTime(c).Unix(), 10)
<add> until := daemonUnixTime(c)
<ide> out, _ := dockerCmd(c, "events", "--since", e.startTime, "--until", until)
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> for _, e := range events { | 12 |
Javascript | Javascript | add example for $cancelupdate | faec99794dfdda542a010040f686d868615c39af | <ide><path>src/ng/directive/input.js
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide> *
<ide> * If you have an input that uses `ng-model-options` to set up debounced events or events such
<ide> * as blur you can have a situation where there is a period when the value of the input element
<del> * is out of synch with the ngModel's `$viewValue`. You can run into difficulties if you try to
<del> * update the ngModel's `$modelValue` programmatically before these debounced/future events have
<del> * completed, because Angular's dirty checking mechanism is not able to tell whether the model
<del> * has actually changed or not. This method should be called before directly updating a model
<del> * from the scope in case you have an input with `ng-model-options` that do not include immediate
<del> * update of the default trigger. This is important in order to make sure that this input field
<del> * will be updated with the new value and any pending operation will be canceled.
<add> * is out of synch with the ngModel's `$viewValue`.
<add> *
<add> * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
<add> * programmatically before these debounced/future events have resolved/occurred, because Angular's
<add> * dirty checking mechanism is not able to tell whether the model has actually changed or not.
<add> *
<add> * The `$cancelUpdate()` method should be called before programmatically changing the model of an
<add> * input which may have such events pending. This is important in order to make sure that the
<add> * input field will be updated with the new model value and any pending operations are cancelled.
<add> *
<add> * <example name="ng-model-cancel-update" module="cancel-update-example">
<add> * <file name="app.js">
<add> * angular.module('cancel-update-example', [])
<add> *
<add> * .controller('CancelUpdateCtrl', function($scope) {
<add> * $scope.resetWithCancel = function (e) {
<add> * if (e.keyCode == 27) {
<add> * $scope.myForm.myInput1.$cancelUpdate();
<add> * $scope.myValue = '';
<add> * }
<add> * };
<add> * $scope.resetWithoutCancel = function (e) {
<add> * if (e.keyCode == 27) {
<add> * $scope.myValue = '';
<add> * }
<add> * };
<add> * });
<add> * </file>
<add> * <file name="index.html">
<add> * <div ng-controller="CancelUpdateCtrl">
<add> * <p>Try typing something in each input. See that the model only updates when you
<add> * blur off the input.
<add> * </p>
<add> * <p>Now see what happens if you start typing then press the Escape key</p>
<add> *
<add> * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
<add> * <p>With $cancelUpdate()</p>
<add> * <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/>
<add> * myValue: "{{ myValue }}"
<add> *
<add> * <p>Without $cancelUpdate()</p>
<add> * <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/>
<add> * myValue: "{{ myValue }}"
<add> * </form>
<add> * </div>
<add> * </file>
<add> * </example>
<ide> */
<ide> this.$cancelUpdate = function() {
<ide> $timeout.cancel(pendingDebounce);
<ide> var ngValueDirective = function() {
<ide> *
<ide> * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
<ide> * be different then the value in the actual model. This means that if you update the model you
<del> * should also invoke `$cancelUpdate` on the relevant input field in order to make sure it is
<del> * synchronized with the model and that any debounced action is canceled.
<add> * should also invoke {@link ngModel.NgModelController `$cancelUpdate`} on the relevant input field in
<add> * order to make sure it is synchronized with the model and that any debounced action is canceled.
<ide> *
<del> * The easiest way to reference the control's `$cancelUpdate` method is by making sure the input
<del> * is placed inside a form that has a `name` attribute. This is important because form controllers
<del> * are published to the related scope under the name in their `name` attribute.
<add> * The easiest way to reference the control's {@link ngModel.NgModelController `$cancelUpdate`}
<add> * method is by making sure the input is placed inside a form that has a `name` attribute. This is
<add> * important because `form` controllers are published to the related scope under the name in their
<add> * `name` attribute.
<ide> *
<ide> * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
<ide> * - `updateOn`: string specifying which event should be the input bound to. You can set several | 1 |
Python | Python | fix stray '.' in import statement | 4394515cd5632a7f110993ff75033d407d10861d | <ide><path>doc/cdoc/numpyfilter.py
<ide> if sys.version_info[0] >= 3:
<ide> import pickle
<ide> else:
<del> import cPickle as pickle.
<add> import cPickle as pickle
<ide>
<ide> CACHE_FILE = 'build/rst-cache.pck'
<ide>
<ide> def filter_comment(text):
<ide> if text.startswith('UFUNC_API'):
<ide> text = text[9:].strip()
<ide>
<del> html = render_html(text)
<add> html = render_html(text)
<ide> return html
<ide>
<ide> def process_match(m, cache=None): | 1 |
Text | Text | add solution for accessibility challenge | 30fd0aa78e59701a1f9575c5312e173c67b4af54 | <ide><path>curriculum/challenges/english/01-responsive-web-design/applied-accessibility/avoid-colorblindness-issues-by-carefully-choosing-colors-that-convey-information.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><head>
<add> <style>
<add> button {
<add> color: #003366;
<add> background-color: #FFFF33;
<add> font-size: 14px;
<add> padding: 10px;
<add> }
<add> </style>
<add></head>
<add><body>
<add> <header>
<add> <h1>Danger!</h1>
<add> </header>
<add> <button>Delete Internet</button>
<add></body>
<ide> ```
<ide> </section> | 1 |
Javascript | Javascript | make http and http2 co-exist | 2ed23314c35649f15d905cb1fca75d0b9d8b0d01 | <ide><path>lib/http.js
<ide> OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
<ide> }
<ide>
<ide> // keep-alive logic
<del> if (sentConnectionHeader === false) {
<add> if (sentConnectionHeader == false) {
<ide> if (this.shouldKeepAlive &&
<del> (sentContentLengthHeader || this.useChunkedEncodingByDefault || this.agent)) {
<add> (sentContentLengthHeader || this.useChunkedEncodingByDefault)) {
<ide> messageHeader += 'Connection: keep-alive\r\n';
<ide> } else {
<ide> this._last = true;
<ide> OutgoingMessage.prototype.end = function(data, encoding) {
<ide>
<ide> // There is the first message on the outgoing queue, and we've sent
<ide> // everything to the socket.
<del> debug('outgoing message end.');
<ide> if (this.output.length === 0 && this.connection._httpMessage === this) {
<add> debug('outgoing message end.');
<ide> this._finish();
<ide> }
<ide>
<ide> OutgoingMessage.prototype._flush = function() {
<ide> if (!this.socket) return;
<ide>
<ide> var ret;
<del> while (this.output.length) {
<ide>
<add> while (this.output.length) {
<ide> if (!this.socket.writable) return; // XXX Necessary?
<ide>
<ide> var data = this.output.shift();
<ide> ServerResponse.prototype.writeHead = function(statusCode) {
<ide> this._storeHeader(statusLine, headers);
<ide> };
<ide>
<add>
<ide> ServerResponse.prototype.writeHeader = function() {
<ide> this.writeHead.apply(this, arguments);
<ide> };
<ide>
<ide>
<del>// New Agent code.
<del>
<del>// The largest departure from the previous implementation is that
<del>// an Agent instance holds connections for a variable number of host:ports.
<del>// Surprisingly, this is still API compatible as far as third parties are
<del>// concerned. The only code that really notices the difference is the
<del>// request object.
<del>
<del>// Another departure is that all code related to HTTP parsing is in
<del>// ClientRequest.onSocket(). The Agent is now *strictly*
<del>// concerned with managing a connection pool.
<del>
<del>function Agent(options) {
<del> var self = this;
<del> self.options = options || {};
<del> self.requests = {};
<del> self.sockets = {};
<del> self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets;
<del> self.on('free', function(socket, host, port) {
<del> var name = host + ':' + port;
<del> if (self.requests[name] && self.requests[name].length) {
<del> self.requests[name].shift().onSocket(socket);
<del> } else {
<del> // If there are no pending requests just destroy the
<del> // socket and it will get removed from the pool. This
<del> // gets us out of timeout issues and allows us to
<del> // default to Connection:keep-alive.
<del> socket.destroy();
<del> }
<del> });
<del> self.createConnection = net.createConnection;
<del>}
<del>util.inherits(Agent, EventEmitter);
<del>exports.Agent = Agent;
<del>
<del>Agent.defaultMaxSockets = 5;
<del>
<del>Agent.prototype.defaultPort = 80;
<del>Agent.prototype.addRequest = function(req, host, port) {
<del> var name = host + ':' + port;
<del> if (!this.sockets[name]) {
<del> this.sockets[name] = [];
<del> }
<del> if (this.sockets[name].length < this.maxSockets) {
<del> // If we are under maxSockets create a new one.
<del> req.onSocket(this.createSocket(name, host, port));
<del> } else {
<del> // We are over limit so we'll add it to the queue.
<del> if (!this.requests[name]) {
<del> this.requests[name] = [];
<del> }
<del> this.requests[name].push(req);
<del> }
<del>};
<del>Agent.prototype.createSocket = function(name, host, port) {
<del> var self = this;
<del> var s = self.createConnection(port, host);
<del> if (!self.sockets[name]) {
<del> self.sockets[name] = [];
<del> }
<del> this.sockets[name].push(s);
<del> var onFree = function() {
<del> self.emit('free', s, host, port);
<del> }
<del> s.on('free', onFree);
<del> var onClose = function(err) {
<del> // This is the only place where sockets get removed from the Agent.
<del> // If you want to remove a socket from the pool, just close it.
<del> // All socket errors end in a close event anyway.
<del> self.removeSocket(s, name, host, port);
<del> }
<del> s.on('close', onClose);
<del> var onRemove = function() {
<del> // We need this function for cases like HTTP "upgrade"
<del> // (defined by WebSockets) where we need to remove a socket from the pool
<del> // because it'll be locked up indefinitely
<del> self.removeSocket(s, name, host, port);
<del> s.removeListener('close', onClose);
<del> s.removeListener('free', onFree);
<del> s.removeListener('agentRemove', onRemove);
<del> }
<del> s.on('agentRemove', onRemove);
<del> return s;
<del>};
<del>Agent.prototype.removeSocket = function(s, name, host, port) {
<del> if (this.sockets[name] && this.sockets[name].indexOf(s) !== -1) {
<del> this.sockets[name].shift(this.sockets[name].indexOf(s));
<del> } else if (this.sockets[name] && this.sockets[name].length === 0) {
<del> // don't leak
<del> delete this.sockets[name];
<del> delete this.requests[name];
<del> }
<del> if (this.requests[name] && this.requests[name].length) {
<del> // If we have pending requests and a socket gets closed a new one
<del> // needs to be created to take over in the pool for the one that closed.
<del> this.createSocket(name, host, port).emit('free');
<del> }
<del>};
<del>
<del>var globalAgent = new Agent();
<del>exports.globalAgent = globalAgent;
<del>
<del>function ClientRequest(options, cb) {
<del> var self = this;
<del> OutgoingMessage.call(self);
<del> self.agent = options.agent;
<del> options.defaultPort = options.defaultPort || 80;
<del>
<del> options.port = options.port || options.defaultPort;
<del> options.host = options.host || 'localhost';
<add>function ClientRequest(options, defaultPort) {
<add> OutgoingMessage.call(this);
<ide>
<del> if (options.setHost === undefined) {
<del> options.setHost = true;
<del> }
<add> if (!defaultPort) defaultPort = 80;
<ide>
<del> self.socketPath = options.socketPath;
<add> var method = this.method = (options.method || 'GET').toUpperCase();
<add> this.path = options.path || '/';
<ide>
<del> var method = self.method = (options.method || 'GET').toUpperCase();
<del> self.path = options.path || '/';
<del> if (cb) {
<del> self.on('response', cb);
<del> }
<del>
<del> if (!Array.isArray(options.headers)) {
<add> if (!Array.isArray(headers)) {
<ide> if (options.headers) {
<del> var keys = Object.keys(options.headers);
<add> var headers = options.headers;
<add> var keys = Object.keys(headers);
<ide> for (var i = 0, l = keys.length; i < l; i++) {
<ide> var key = keys[i];
<del> self.setHeader(key, options.headers[key]);
<add> this.setHeader(key, headers[key]);
<ide> }
<ide> }
<del> if (options.host && !this.getHeader('host') && options.setHost) {
<add> // Host header set by default.
<add> if (options.host && !this.getHeader('host')) {
<ide> var hostHeader = options.host;
<del> if (options.port && +options.port !== options.defaultPort) {
<add> if (options.port && +options.port !== defaultPort) {
<ide> hostHeader += ':' + options.port;
<ide> }
<ide> this.setHeader("Host", hostHeader);
<ide> }
<ide> }
<ide>
<add> this.shouldKeepAlive = false;
<ide> if (method === 'GET' || method === 'HEAD') {
<del> self.useChunkedEncodingByDefault = false;
<add> this.useChunkedEncodingByDefault = false;
<ide> } else {
<del> self.useChunkedEncodingByDefault = true;
<add> this.useChunkedEncodingByDefault = true;
<ide> }
<ide>
<del> if (Array.isArray(options.headers)) {
<del> self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', options.headers);
<del> } else if (self.getHeader('expect')) {
<del> self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', self._renderHeaders());
<del> }
<del> if (self.socketPath) {
<del> self._last = true;
<del> self.shouldKeepAlive = false;
<del> self.onSocket(net.createConnection(self.socketPath));
<del> } else if (self.agent) {
<del> // If there is an agent we should default to Connection:keep-alive.
<del> self._last = false;
<del> self.shouldKeepAlive = true;
<del> self.agent.addRequest(self, options.host, options.port);
<del> } else {
<del> // No agent should default to Connection:close.
<del> self._last = true;
<del> self.shouldKeepAlive = false;
<del> self.onSocket(net.createConnection(options.port, options.host));
<del> }
<add> // By default keep-alive is off. This is the last message unless otherwise
<add> // specified.
<add> this._last = true;
<ide>
<del> self._deferToConnect(null, null, function () {
<del> self._flush();
<del> })
<add> if (Array.isArray(headers)) {
<add> this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n', headers);
<add> } else if (this.getHeader('expect')) {
<add> this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n', this._renderHeaders());
<add> }
<ide>
<ide> }
<ide> util.inherits(ClientRequest, OutgoingMessage);
<ide>
<add>
<ide> exports.ClientRequest = ClientRequest;
<ide>
<ide> ClientRequest.prototype._implicitHeader = function() {
<ide> this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n', this._renderHeaders());
<del>};
<add>}
<ide>
<ide> ClientRequest.prototype.abort = function() {
<del> if (this.socket) {
<del> // in-progress
<del> this.socket.destroy();
<del> } else {
<del> // haven't been assigned a socket yet.
<del> // this could be more efficient, it could
<del> // remove itself from the pending requests
<del> this._deferToConnect('destroy', []);
<del> }
<del>};
<del>
<del>ClientRequest.prototype.onSocket = function(socket) {
<del> var parser = parsers.alloc();
<del> var req = this;
<del>
<del> req.socket = socket;
<del> req.connection = socket;
<del> parser.reinitialize('response');
<del> parser.socket = socket;
<del> parser.incoming = null;
<del> req.parser = parser;
<del>
<del> socket._httpMessage = req;
<del> // Setup "drain" propogation.
<del> httpSocketSetup(socket);
<del>
<del> var errorListener = function(err) {
<del> debug('HTTP SOCKET ERROR: ' + err.message + '\n' + err.stack);
<del> req.emit('error', err);
<del> // For Safety. Some additional errors might fire later on
<del> // and we need to make sure we don't double-fire the error event.
<del> req._hadError = true;
<del> parser.finish();
<del> }
<del> socket.on('error', errorListener);
<del>
<del> socket.ondata = function(d, start, end) {
<del> var ret = parser.execute(d, start, end - start);
<del> if (ret instanceof Error) {
<del> debug('parse error');
<del> socket.destroy(ret);
<del> } else if (parser.incoming && parser.incoming.upgrade) {
<del> var bytesParsed = ret;
<del> socket.ondata = null;
<del> socket.onend = null;
<del>
<del> var res = parser.incoming;
<del> req.res = res;
<del>
<del> // This is start + byteParsed + 1 due to the error of getting \n
<del> // in the upgradeHead from the closing lines of the headers
<del> var upgradeHead = d.slice(start + bytesParsed + 1, end);
<del> if (req.listeners('upgrade').length) {
<del> // Emit 'upgrade' on the Agent.
<del> req.upgraded = true;
<del> req.emit('upgrade', res, socket, upgradeHead);
<del> socket.emit('agentRemove');
<del> } else {
<del> // Got upgrade header, but have no handler.
<del> socket.destroy();
<del> }
<del> }
<del> };
<del>
<del> socket.onend = function() {
<del> if (!req.res) {
<del> // If we don't have a response then we know that the socket
<del> // ended prematurely and we need to emit an error on the request.
<del> req.emit('error', new Error("Request ended prematurely."));
<del> req._hadError = true;
<del> }
<del> parser.finish();
<del> parsers.free(parser); // I don't know if this is necessary --Mikeal
<del> socket.destroy();
<del> };
<del>
<del> var closeListener = function() {
<del> debug('HTTP socket close');
<del> req.emit('close');
<del> if (req.res && req.res.readable) {
<del> // Socket closed before we emitted "end" below.
<del> req.res.emit('aborted');
<del> req.res.emit('end');
<del> req.res.emit('close');
<del> } else if (!req.res && !req._hadError) {
<del> // This socket error fired before we started to
<del> // receive a response. The error needs to
<del> // fire on the request.
<del> req.emit('error', new Error('socket hang up'));
<del> }
<del> }
<del> socket.on('close', closeListener);
<del>
<del> parser.onIncoming = function(res, shouldKeepAlive) {
<del> debug('AGENT incoming response!');
<del>
<del> if (req.res) {
<del> // We already have a response object, this means the server
<del> // sent a double response.
<del> socket.destroy();
<del> return;
<del> }
<del> req.res = res;
<del>
<del> // Responses to HEAD requests are crazy.
<del> // HEAD responses aren't allowed to have an entity-body
<del> // but *can* have a content-length which actually corresponds
<del> // to the content-length of the entity-body had the request
<del> // been a GET.
<del> var isHeadResponse = req.method == 'HEAD';
<del> debug('AGENT isHeadResponse ' + isHeadResponse);
<del>
<del> if (res.statusCode == 100) {
<del> // restart the parser, as this is a continue message.
<del> delete req.res; // Clear res so that we don't hit double-responses.
<del> req.emit('continue');
<del> return true;
<del> }
<add> if (this._queue) {
<add> // queued for dispatch
<add> assert(!this.connection);
<add> var i = this._queue.indexOf(this);
<add> this._queue.splice(i, 1);
<ide>
<del> if (req.shouldKeepAlive && res.headers.connection !== 'keep-alive' && !req.upgraded) {
<del> // Server MUST respond with Connection:keep-alive for us to enable it.
<del> // If we've been upgraded (via WebSockets) we also shouldn't try to
<del> // keep the connection open.
<del> req.shouldKeepAlive = false;
<del> }
<del>
<del> res.addListener('end', function() {
<del> if (!req.shouldKeepAlive) {
<del> if (socket.writable) {
<del> debug('AGENT socket.destroySoon()');
<del> socket.destroySoon();
<del> }
<del> assert(!socket.writable);
<del> } else {
<del> debug('AGENT socket keep-alive');
<del> }
<del> });
<del>
<del> DTRACE_HTTP_CLIENT_RESPONSE(socket, req);
<del> req.emit('response', res);
<del>
<del> res.on('end', function() {
<del> if (req.shouldKeepAlive) {
<del> socket.removeListener('close', closeListener);
<del> socket.removeListener('error', errorListener);
<del> socket.emit('free');
<del> }
<del> });
<add> } else if (this.connection) {
<add> // in-progress
<add> var c = this.connection;
<add> this.detachSocket(c);
<add> c.destroy();
<ide>
<del> return isHeadResponse;
<del> };
<del> process.nextTick(function() {
<del> req.emit('socket', socket);
<del> });
<del>};
<del>ClientRequest.prototype._deferToConnect = function(method, arguments, cb) {
<del> // This function is for calls that need to happen once the socket is
<del> // connected and writable. It's an important promisy thing for all the socket
<del> // calls that happen either now (when a socket is assigned) or
<del> // in the future (when a socket gets assigned out of the pool and is
<del> // eventually writable).
<del> var self = this;
<del> var onSocket = function() {
<del> if (self.socket.writable) {
<del> if (method) {
<del> self.socket[method].apply(self.socket, arguments);
<del> }
<del> if (cb) { cb(); }
<del> } else {
<del> self.socket.on('connect', function() {
<del> if (method) {
<del> self.socket[method].apply(self.socket, arguments);
<del> }
<del> if (cb) { cb(); }
<del> });
<del> }
<del> }
<del> if (!self.socket) {
<del> self.once('socket', onSocket);
<ide> } else {
<del> onSocket();
<del> }
<del>};
<del>ClientRequest.prototype.setTimeout = function() {
<del> this._deferToConnect('setTimeout', arguments);
<del>};
<del>ClientRequest.prototype.setNoDelay = function() {
<del> this._deferToConnect('setNoDelay', arguments);
<del>};
<del>ClientRequest.prototype.setSocketKeepAlive = function() {
<del> this._deferToConnect('setKeepAlive', arguments);
<del>};
<del>ClientRequest.prototype.pause = function() {
<del> var self = this;
<del> self._deferToConnect(null, null, function() {
<del> OutgoingMessage.prototype.pause.apply(self, []);
<del> });
<del>};
<del>
<del>
<del>exports.request = function(options, cb) {
<del> if (options.agent === undefined) {
<del> options.agent = globalAgent;
<add> // already complete.
<ide> }
<del> return new ClientRequest(options, cb);
<ide> };
<ide>
<del>exports.get = function(options, cb) {
<del> options.method = 'GET';
<del> var req = exports.request(options, cb);
<del> req.end();
<del> return req;
<del>};
<ide>
<ide> function httpSocketSetup(socket) {
<ide> // NOTE: be sure not to use ondrain elsewhere in this file!
<ide> function connectionListener(socket) {
<ide> }
<ide> exports._connectionListener = connectionListener;
<ide>
<del>// Legacy Interface
<ide>
<del>function Client(port, host) {
<del> host = host || 'localhost';
<del> port = port || 80;
<del> this.host = host;
<del> this.port = port;
<add>function Agent(options) {
<add> this.options = options;
<add> this.host = options.host;
<add> this.port = options.port || this.defaultPort;
<add> this.socketPath = options.socketPath;
<add>
<add> this.queue = [];
<add> this.sockets = [];
<add> this.maxSockets = Agent.defaultMaxSockets;
<add>
<ide> }
<del>util.inherits(Client, EventEmitter);
<del>Client.prototype.request = function(method, path, headers) {
<add>util.inherits(Agent, EventEmitter);
<add>exports.Agent = Agent;
<add>
<add>
<add>Agent.defaultMaxSockets = 5;
<add>
<add>Agent.prototype.defaultPort = 80;
<add>Agent.prototype.appendMessage = function(options) {
<ide> var self = this;
<del> var options = {};
<del> options.host = self.host;
<del> options.port = self.port;
<del> if (method[0] === '/') {
<del> headers = path;
<del> path = method;
<del> method = 'GET';
<del> }
<del> options.method = method;
<del> options.path = path;
<del> options.headers = headers;
<del> var c = new ClientRequest(options);
<del> c.on('error', function(e) {
<del> self.emit('error', e);
<add>
<add> var req = new ClientRequest(options, this.defaultPort);
<add> this.queue.push(req);
<add> req._queue = this.queue;
<add>
<add> this._cycle();
<add>
<add> return req;
<add>};
<add>
<add>
<add>Agent.prototype._removeSocket = function(socket) {
<add> var i = this.sockets.indexOf(socket);
<add> if (i >= 0) this.sockets.splice(i, 1);
<add>};
<add>
<add>
<add>Agent.prototype._establishNewConnection = function() {
<add> var self = this;
<add> assert(this.sockets.length < this.maxSockets);
<add>
<add> // Grab a new "socket". Depending on the implementation of _getConnection
<add> // this could either be a raw TCP socket or a TLS stream.
<add> var socket = this._getConnection(self, function() {
<add> socket._httpConnecting = false;
<add> self.emit('connect'); // mostly for the shim.
<add> debug('Agent _getConnection callback');
<add> self._cycle();
<ide> });
<del> // The old Client interface emitted "end" on socket end.
<del> // This doesn't map to how we want things to operate in the future
<del> // but it will get removed when we remove this legacy interface.
<del> c.on('socket', function(s) {
<del> s.on('end', function() {
<del> self.emit('end');
<del> });
<add>
<add> // Use this special mark so that we know if the socket is connecting.
<add> // TODO: come up with a standard way of specifying that a stream is being
<add> // connected across tls and net.
<add> socket._httpConnecting = true;
<add>
<add> this.sockets.push(socket);
<add>
<add> // Cycle so the request can be assigned to this new socket.
<add> self._cycle();
<add> assert(socket._httpMessage);
<add>
<add> // Add a parser to the socket.
<add> var parser = parsers.alloc();
<add> parser.reinitialize('response');
<add> parser.socket = socket;
<add> parser.incoming = null;
<add>
<add> socket.on('error', function(err) {
<add> debug('AGENT SOCKET ERROR: ' + err.message + '\n' + err.stack);
<add> var req;
<add> if (socket._httpMessage) {
<add> req = socket._httpMessage;
<add> } else if (self.queue.length) {
<add> req = self.queue.shift();
<add> assert(req._queue === self.queue);
<add> req._queue = null;
<add> }
<add>
<add> if (req) {
<add> req.emit('error', err);
<add> req._hadError = true; // hacky
<add> }
<add>
<add> // clean up so that agent can handle new requests
<add> parser.finish();
<add> socket.destroy();
<add> self._removeSocket(socket);
<add> self._cycle();
<ide> });
<add>
<add> socket.ondata = function(d, start, end) {
<add> var ret = parser.execute(d, start, end - start);
<add> if (ret instanceof Error) {
<add> debug('parse error');
<add> socket.destroy(ret);
<add> } else if (parser.incoming && parser.incoming.upgrade) {
<add> var bytesParsed = ret;
<add> socket.ondata = null;
<add> socket.onend = null;
<add>
<add> var res = parser.incoming;
<add> assert(socket._httpMessage);
<add> socket._httpMessage.res = res;
<add>
<add> // This is start + byteParsed + 1 due to the error of getting \n
<add> // in the upgradeHead from the closing lines of the headers
<add> var upgradeHead = d.slice(start + bytesParsed + 1, end);
<add>
<add> // Make sure we don't try to send HTTP requests to it.
<add> self._removeSocket(socket);
<add>
<add> socket.on('end', function() {
<add> self.emit('end');
<add> });
<add>
<add> // XXX free the parser?
<add>
<add> if (self.listeners('upgrade').length) {
<add> // Emit 'upgrade' on the Agent.
<add> self.emit('upgrade', res, socket, upgradeHead);
<add> } else {
<add> // Got upgrade header, but have no handler.
<add> socket.destroy();
<add> }
<add> }
<add> };
<add>
<add> socket.onend = function() {
<add> self.emit('end'); // mostly for the shim.
<add> parser.finish();
<add> socket.destroy();
<add> };
<add>
<add> // When the socket closes remove it from the list of available sockets.
<add> socket.on('close', function() {
<add> debug('AGENT socket close');
<add> // This is really hacky: What if someone issues a request, the server
<add> // accepts, but then terminates the connection. There is no parse error,
<add> // there is no socket-level error. How does the user get informed?
<add> // We check to see if the socket has a request, if so if it has a
<add> // response (meaning that it emitted a 'response' event). If the socket
<add> // has a request but no response and it never emitted an error event:
<add> // THEN we need to trigger it manually.
<add> // There must be a better way to do this.
<add> if (socket._httpMessage) {
<add> if (socket._httpMessage.res) {
<add> socket._httpMessage.res.emit('aborted');
<add> socket._httpMessage.res.emit('close');
<add> } else {
<add> if (!socket._httpMessage._hadError) {
<add> socket._httpMessage.emit('error', new Error('socket hang up'));
<add> }
<add> }
<add> }
<add>
<add> self._removeSocket(socket);
<add> // unref the parser for easy gc
<add> parsers.free(parser);
<add>
<add> self._cycle();
<add> });
<add>
<add> parser.onIncoming = function(res, shouldKeepAlive) {
<add> debug('AGENT incoming response!');
<add>
<add> // If we're receiving a message but we don't have a corresponding
<add> // request - then somehow the server is seriously messed up and sending
<add> // multiple responses at us. In this case we'll just bail.
<add> if (!socket._httpMessage) {
<add> socket.destroy();
<add> return;
<add> }
<add>
<add> var req = socket._httpMessage;
<add> req.res = res;
<add>
<add> // Responses to HEAD requests are AWFUL. Ask Ryan.
<add> // A major oversight in HTTP. Hence this nastiness.
<add> var isHeadResponse = req.method == 'HEAD';
<add> debug('AGENT isHeadResponse ' + isHeadResponse);
<add>
<add> if (res.statusCode == 100) {
<add> // restart the parser, as this is a continue message.
<add> req.emit('continue');
<add> return true;
<add> }
<add>
<add> if (req.shouldKeepAlive && res.headers.connection === 'close') {
<add> req.shouldKeepAlive = false;
<add> }
<add>
<add> res.addListener('end', function() {
<add> debug('AGENT request complete');
<add> // For the moment we reconnect for every request. FIXME!
<add> // All that should be required for keep-alive is to not reconnect,
<add> // but outgoingFlush instead.
<add> if (!req.shouldKeepAlive) {
<add> if (socket.writable) {
<add> debug('AGENT socket.destroySoon()');
<add> socket.destroySoon();
<add> }
<add> assert(!socket.writable);
<add> } else {
<add> debug('AGENT socket keep-alive');
<add> }
<add>
<add> // The socket may already be detached and destroyed by an abort call
<add> if (socket._httpMessage) {
<add> req.detachSocket(socket);
<add> }
<add>
<add> assert(!socket._httpMessage);
<add>
<add> self._cycle();
<add> });
<add>
<add> DTRACE_HTTP_CLIENT_RESPONSE(socket, self);
<add> req.emit('response', res);
<add>
<add> return isHeadResponse;
<add> };
<add>};
<add>
<add>
<add>// Sub-classes can overwrite this method with e.g. something that supplies
<add>// TLS streams.
<add>Agent.prototype._getConnection = function(options, cb) {
<add> debug('Agent connected!');
<add>
<add> var c;
<add>
<add> if (options.host) {
<add> c = net.createConnection(options.port, options.host);
<add> } else if (options.socketPath) {
<add> c = net.createConnection(options.socketPath);
<add> } else {
<add> c = net.createConnection(options.port);
<add> }
<add> c.on('connect', cb);
<ide> return c;
<ide> };
<ide>
<add>
<add>// This method attempts to shuffle items along the queue into one of the
<add>// waiting sockets. If a waiting socket cannot be found, it will
<add>// start the process of establishing one.
<add>Agent.prototype._cycle = function() {
<add> debug('Agent _cycle sockets=' + this.sockets.length + ' queue=' + this.queue.length);
<add> var self = this;
<add>
<add> var first = this.queue[0];
<add> if (!first) return;
<add>
<add> // First try to find an available socket.
<add> for (var i = 0; i < this.sockets.length; i++) {
<add> var socket = this.sockets[i];
<add> // If the socket doesn't already have a message it's sending out
<add> // and the socket is available for writing or it's connecting.
<add> // In particular this rules out sockets that are closing.
<add> if (!socket._httpMessage &&
<add> ((socket.writable && socket.readable) || socket._httpConnecting)) {
<add> debug('Agent found socket, shift');
<add> // We found an available connection!
<add> this.queue.shift(); // remove first from queue.
<add> assert(first._queue === this.queue);
<add> first._queue = null;
<add>
<add> first.assignSocket(socket);
<add> httpSocketSetup(socket);
<add> self._cycle(); // try to dispatch another
<add> return;
<add> }
<add> }
<add>
<add> // If no sockets are connecting, and we have space for another we should
<add> // be starting a new connection to handle this request.
<add> if (this.sockets.length < this.maxSockets) {
<add> this._establishNewConnection();
<add> }
<add>
<add> // All sockets are filled and all sockets are busy.
<add>};
<add>
<add>
<add>// process-wide hash of agents.
<add>// keys: "host:port" string
<add>// values: instance of Agent
<add>// That is, one agent remote host.
<add>// TODO currently we never remove agents from this hash. This is a small
<add>// memory leak. Have a 2 second timeout after a agent's sockets are to try
<add>// to remove it?
<add>var agents = {};
<add>
<add>// Backwards compatible with legacy getAgent(host, port);
<add>function getAgent(options) {
<add> var agent;
<add> var host;
<add> var id;
<add> var port;
<add>
<add> var _opts = {};
<add>
<add> if (typeof options === 'string') {
<add> port = arguments[1] || 80;
<add> id = options + ':' + port;
<add> _opts.host = options;
<add> _opts.port = port;
<add> } else if (options && typeof options === 'object') {
<add> if (options.port || options.host) {
<add> host = options.host || 'localhost';
<add> port = options.port || 80;
<add> id = host + ':' + port;
<add> _opts.host = host;
<add> _opts.port = port;
<add> } else if (options.socketPath) {
<add> id = options.socketPath;
<add> _opts.socketPath = options.socketPath;
<add> } else {
<add> throw new TypeError('Invalid options specification to getAgent');
<add> }
<add> } else {
<add> throw new TypeError('Invalid argument to getAgent');
<add> }
<add>
<add> agent = agents[id];
<add>
<add> if (!agent) {
<add> agent = agents[id] = new Agent(_opts);
<add> }
<add>
<add> return agent;
<add>}
<add>exports.getAgent = getAgent;
<add>
<add>
<add>exports._requestFromAgent = function(options, cb) {
<add> var req = options.agent.appendMessage(options);
<add> req.agent = options.agent;
<add> if (cb) req.once('response', cb);
<add> return req;
<add>};
<add>
<add>
<add>exports.request = function(options, cb) {
<add> if (options.agent === undefined) {
<add> options.agent = getAgent(options);
<add> } else if (options.agent === false) {
<add> options.agent = new Agent(options);
<add> }
<add> return exports._requestFromAgent(options, cb);
<add>};
<add>
<add>
<add>exports.get = function(options, cb) {
<add> options.method = 'GET';
<add> var req = exports.request(options, cb);
<add> req.end();
<add> return req;
<add>};
<add>
<add>
<add>
<add>// Legacy Interface:
<add>
<add>
<add>
<add>function Client() {
<add> if (!(this instanceof Client)) return new Client();
<add> net.Stream.call(this, { allowHalfOpen: true });
<add> var self = this;
<add>
<add> // Possible states:
<add> // - disconnected
<add> // - connecting
<add> // - connected
<add> this._state = 'disconnected';
<add>
<add> httpSocketSetup(self);
<add> this._outgoing = [];
<add>
<add> function onData(d, start, end) {
<add> if (!self.parser) {
<add> throw new Error('parser not initialized prior to Client.ondata call');
<add> }
<add> var ret = self.parser.execute(d, start, end - start);
<add> if (ret instanceof Error) {
<add> self.destroy(ret);
<add> } else if (self.parser.incoming && self.parser.incoming.upgrade) {
<add> var bytesParsed = ret;
<add> self.ondata = null;
<add> self.onend = null;
<add> self._state = 'upgraded';
<add>
<add> var res = self.parser.incoming;
<add>
<add> if (self._httpMessage) {
<add> self._httpMessage.detachSocket(self);
<add> }
<add>
<add> var upgradeHead = d.slice(start + bytesParsed + 1, end);
<add>
<add> if (self.listeners('upgrade').length) {
<add> self.emit('upgrade', res, self, upgradeHead);
<add> } else {
<add> self.destroy();
<add> }
<add> }
<add> };
<add>
<add> self.addListener('connect', function() {
<add> debug('CLIENT connected');
<add>
<add> self.ondata = onData;
<add> self.onend = onEnd;
<add>
<add> self._state = 'connected';
<add>
<add> self._initParser();
<add>
<add> self._cycle();
<add> });
<add>
<add> function onEnd() {
<add> if (self.parser) self.parser.finish();
<add> debug('CLIENT got end closing. state = ' + self._state);
<add> self.end();
<add> };
<add>
<add> self.addListener('close', function(e) {
<add> self._state = 'disconnected';
<add> self._upgraded = false;
<add>
<add> // Free the parser.
<add> if (self.parser) {
<add> parsers.free(self.parser);
<add> self.parser = null;
<add> }
<add>
<add> if (e) return;
<add>
<add> // If we have an http message, then drop it
<add> var req = self._httpMessage;
<add> if (req && !req.res) {
<add> req.detachSocket(self);
<add> self.emit('error', new Error('socket hang up'));
<add> }
<add>
<add> debug('CLIENT onClose. state = ' + self._state);
<add> self._cycle();
<add> });
<add>}
<add>util.inherits(Client, net.Stream);
<add>
<add>
<ide> exports.Client = Client;
<add>
<add>
<ide> exports.createClient = function(port, host) {
<del> return new Client(port, host);
<add> var c = new Client();
<add> c.port = port;
<add> c.host = host;
<add> return c;
<ide> };
<ide>
<add>
<add>Client.prototype._initParser = function() {
<add> var self = this;
<add> if (!self.parser) self.parser = parsers.alloc();
<add> self.parser.reinitialize('response');
<add> self.parser.socket = self;
<add> self.parser.onIncoming = function(res) {
<add> debug('CLIENT incoming response!');
<add>
<add> assert(self._httpMessage);
<add> var req = self._httpMessage;
<add>
<add> req.res = res;
<add>
<add> // Responses to HEAD requests are AWFUL. Ask Ryan.
<add> // A major oversight in HTTP. Hence this nastiness.
<add> var isHeadResponse = req.method == 'HEAD';
<add> debug('CLIENT isHeadResponse ' + isHeadResponse);
<add>
<add> if (res.statusCode == 100) {
<add> // restart the parser, as this is a continue message.
<add> req.emit('continue');
<add> return true;
<add> }
<add>
<add> if (req.shouldKeepAlive && res.headers.connection === 'close') {
<add> req.shouldKeepAlive = false;
<add> }
<add>
<add> res.addListener('end', function() {
<add> debug('CLIENT response complete disconnecting. state = ' + self._state);
<add>
<add> if (!req.shouldKeepAlive) {
<add> self.end();
<add> }
<add>
<add> req.detachSocket(self);
<add> assert(!self._httpMessage);
<add> self._cycle();
<add> });
<add>
<add> DTRACE_HTTP_CLIENT_RESPONSE(self, self);
<add> req.emit('response', res);
<add>
<add> return isHeadResponse;
<add> };
<add>};
<add>
<add>
<add>Client.prototype._cycle = function() {
<add> debug("Client _cycle");
<add> if (this._upgraded) return;
<add>
<add> switch (this._state) {
<add> case 'connecting':
<add> break;
<add>
<add> case 'connected':
<add> if (this.writable && this.readable) {
<add> debug("Client _cycle shift()");
<add> if (this._httpMessage) {
<add> this._httpMessage._flush();
<add> } else {
<add> var req = this._outgoing.shift();
<add> if (req) {
<add> req.assignSocket(this);
<add> }
<add> }
<add> }
<add> break;
<add>
<add> case 'disconnected':
<add> if (this._httpMessage || this._outgoing.length) {
<add> this._ensureConnection();
<add> }
<add> break;
<add> }
<add>};
<add>
<add>
<add>Client.prototype._ensureConnection = function() {
<add> if (this._state == 'disconnected') {
<add> debug('CLIENT reconnecting state = ' + this._state);
<add> this.connect(this.port, this.host);
<add> this._state = 'connecting';
<add> }
<add>};
<add>
<add>
<add>Client.prototype.request = function(method, url, headers) {
<add> if (typeof(url) != 'string') {
<add> // assume method was omitted, shift arguments
<add> headers = url;
<add> url = method;
<add> method = 'GET';
<add> }
<add>
<add> var self = this;
<add>
<add> var options = {
<add> method: method || 'GET',
<add> path: url || '/',
<add> headers: headers
<add> };
<add>
<add> var req = new ClientRequest(options);
<add> this._outgoing.push(req);
<add> this._cycle();
<add>
<add> return req;
<add>};
<add>
<add>
<ide> exports.cat = function(url, encoding_, headers_) {
<del> var encoding = 'utf8';
<del> var headers = {};
<del> var callback = null;
<add> var encoding = 'utf8',
<add> headers = {},
<add> callback = null;
<ide>
<ide> console.error("http.cat will be removed in the near future. use http.get");
<ide>
<ide> exports.cat = function(url, encoding_, headers_) {
<ide>
<ide> var content = '';
<ide>
<del> var path = (url.pathname || '/') + (url.search || '') + (url.hash || '');
<add> var client = exports.createClient(url.port || 80, url.hostname);
<add> var req = client.request((url.pathname || '/') +
<add> (url.search || '') +
<add> (url.hash || ''),
<add> headers);
<add>
<add> if (url.protocol == 'https:') {
<add> client.https = true;
<add> }
<add>
<ide> var callbackSent = false;
<del> var req = exports.request({port: url.port || 80, host: url.hostname, path: path}, function(res) {
<add>
<add> req.addListener('response', function(res) {
<ide> if (res.statusCode < 200 || res.statusCode >= 300) {
<ide> if (callback && !callbackSent) {
<ide> callback(res.statusCode);
<ide> exports.cat = function(url, encoding_, headers_) {
<ide> });
<ide> });
<ide>
<del>
<del> req.addListener('error', function(err) {
<add> client.addListener('error', function(err) {
<ide> if (callback && !callbackSent) {
<ide> callback(err);
<ide> callbackSent = true;
<ide> }
<ide> });
<ide>
<add> client.addListener('close', function() {
<add> if (callback && !callbackSent) {
<add> callback(new Error('Connection closed unexpectedly'));
<add> callbackSent = true;
<add> }
<add> });
<ide> req.end();
<ide> };
<ide><path>lib/http2.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var util = require('util');
<add>var net = require('net');
<add>var stream = require('stream');
<add>var EventEmitter = require('events').EventEmitter;
<add>var FreeList = require('freelist').FreeList;
<add>var HTTPParser = process.binding('http_parser').HTTPParser;
<add>var assert = require('assert').ok;
<add>
<add>
<add>var debug;
<add>if (process.env.NODE_DEBUG && /http/.test(process.env.NODE_DEBUG)) {
<add> debug = function(x) { console.error('HTTP: %s', x); };
<add>} else {
<add> debug = function() { };
<add>}
<add>
<add>
<add>var parsers = new FreeList('parsers', 1000, function() {
<add> var parser = new HTTPParser('request');
<add>
<add> parser.onMessageBegin = function() {
<add> parser.incoming = new IncomingMessage(parser.socket);
<add> parser.field = null;
<add> parser.value = null;
<add> };
<add>
<add> // Only servers will get URL events.
<add> parser.onURL = function(b, start, len) {
<add> var slice = b.toString('ascii', start, start + len);
<add> if (parser.incoming.url) {
<add> parser.incoming.url += slice;
<add> } else {
<add> // Almost always will branch here.
<add> parser.incoming.url = slice;
<add> }
<add> };
<add>
<add> parser.onHeaderField = function(b, start, len) {
<add> var slice = b.toString('ascii', start, start + len).toLowerCase();
<add> if (parser.value != undefined) {
<add> parser.incoming._addHeaderLine(parser.field, parser.value);
<add> parser.field = null;
<add> parser.value = null;
<add> }
<add> if (parser.field) {
<add> parser.field += slice;
<add> } else {
<add> parser.field = slice;
<add> }
<add> };
<add>
<add> parser.onHeaderValue = function(b, start, len) {
<add> var slice = b.toString('ascii', start, start + len);
<add> if (parser.value) {
<add> parser.value += slice;
<add> } else {
<add> parser.value = slice;
<add> }
<add> };
<add>
<add> parser.onHeadersComplete = function(info) {
<add> if (parser.field && (parser.value != undefined)) {
<add> parser.incoming._addHeaderLine(parser.field, parser.value);
<add> parser.field = null;
<add> parser.value = null;
<add> }
<add>
<add> parser.incoming.httpVersionMajor = info.versionMajor;
<add> parser.incoming.httpVersionMinor = info.versionMinor;
<add> parser.incoming.httpVersion = info.versionMajor + '.' + info.versionMinor;
<add>
<add> if (info.method) {
<add> // server only
<add> parser.incoming.method = info.method;
<add> } else {
<add> // client only
<add> parser.incoming.statusCode = info.statusCode;
<add> }
<add>
<add> parser.incoming.upgrade = info.upgrade;
<add>
<add> var isHeadResponse = false;
<add>
<add> if (!info.upgrade) {
<add> // For upgraded connections, we'll emit this after parser.execute
<add> // so that we can capture the first part of the new protocol
<add> isHeadResponse = parser.onIncoming(parser.incoming, info.shouldKeepAlive);
<add> }
<add>
<add> return isHeadResponse;
<add> };
<add>
<add> parser.onBody = function(b, start, len) {
<add> // TODO body encoding?
<add> var slice = b.slice(start, start + len);
<add> if (parser.incoming._decoder) {
<add> var string = parser.incoming._decoder.write(slice);
<add> if (string.length) parser.incoming.emit('data', string);
<add> } else {
<add> parser.incoming.emit('data', slice);
<add> }
<add> };
<add>
<add> parser.onMessageComplete = function() {
<add> this.incoming.complete = true;
<add> if (parser.field && (parser.value != undefined)) {
<add> parser.incoming._addHeaderLine(parser.field, parser.value);
<add> }
<add> if (!parser.incoming.upgrade) {
<add> // For upgraded connections, also emit this after parser.execute
<add> parser.incoming.readable = false;
<add> parser.incoming.emit('end');
<add> }
<add> };
<add>
<add> return parser;
<add>});
<add>exports.parsers = parsers;
<add>
<add>
<add>var CRLF = '\r\n';
<add>var STATUS_CODES = exports.STATUS_CODES = {
<add> 100 : 'Continue',
<add> 101 : 'Switching Protocols',
<add> 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918
<add> 200 : 'OK',
<add> 201 : 'Created',
<add> 202 : 'Accepted',
<add> 203 : 'Non-Authoritative Information',
<add> 204 : 'No Content',
<add> 205 : 'Reset Content',
<add> 206 : 'Partial Content',
<add> 207 : 'Multi-Status', // RFC 4918
<add> 300 : 'Multiple Choices',
<add> 301 : 'Moved Permanently',
<add> 302 : 'Moved Temporarily',
<add> 303 : 'See Other',
<add> 304 : 'Not Modified',
<add> 305 : 'Use Proxy',
<add> 307 : 'Temporary Redirect',
<add> 400 : 'Bad Request',
<add> 401 : 'Unauthorized',
<add> 402 : 'Payment Required',
<add> 403 : 'Forbidden',
<add> 404 : 'Not Found',
<add> 405 : 'Method Not Allowed',
<add> 406 : 'Not Acceptable',
<add> 407 : 'Proxy Authentication Required',
<add> 408 : 'Request Time-out',
<add> 409 : 'Conflict',
<add> 410 : 'Gone',
<add> 411 : 'Length Required',
<add> 412 : 'Precondition Failed',
<add> 413 : 'Request Entity Too Large',
<add> 414 : 'Request-URI Too Large',
<add> 415 : 'Unsupported Media Type',
<add> 416 : 'Requested Range Not Satisfiable',
<add> 417 : 'Expectation Failed',
<add> 418 : 'I\'m a teapot', // RFC 2324
<add> 422 : 'Unprocessable Entity', // RFC 4918
<add> 423 : 'Locked', // RFC 4918
<add> 424 : 'Failed Dependency', // RFC 4918
<add> 425 : 'Unordered Collection', // RFC 4918
<add> 426 : 'Upgrade Required', // RFC 2817
<add> 500 : 'Internal Server Error',
<add> 501 : 'Not Implemented',
<add> 502 : 'Bad Gateway',
<add> 503 : 'Service Unavailable',
<add> 504 : 'Gateway Time-out',
<add> 505 : 'HTTP Version not supported',
<add> 506 : 'Variant Also Negotiates', // RFC 2295
<add> 507 : 'Insufficient Storage', // RFC 4918
<add> 509 : 'Bandwidth Limit Exceeded',
<add> 510 : 'Not Extended' // RFC 2774
<add>};
<add>
<add>
<add>var connectionExpression = /Connection/i;
<add>var transferEncodingExpression = /Transfer-Encoding/i;
<add>var closeExpression = /close/i;
<add>var chunkExpression = /chunk/i;
<add>var contentLengthExpression = /Content-Length/i;
<add>var expectExpression = /Expect/i;
<add>var continueExpression = /100-continue/i;
<add>
<add>
<add>/* Abstract base class for ServerRequest and ClientResponse. */
<add>function IncomingMessage(socket) {
<add> stream.Stream.call(this);
<add>
<add> // TODO Remove one of these eventually.
<add> this.socket = socket;
<add> this.connection = socket;
<add>
<add> this.httpVersion = null;
<add> this.complete = false;
<add> this.headers = {};
<add> this.trailers = {};
<add>
<add> this.readable = true;
<add>
<add> // request (server) only
<add> this.url = '';
<add>
<add> this.method = null;
<add>
<add> // response (client) only
<add> this.statusCode = null;
<add> this.client = this.socket;
<add>}
<add>util.inherits(IncomingMessage, stream.Stream);
<add>
<add>
<add>exports.IncomingMessage = IncomingMessage;
<add>
<add>
<add>IncomingMessage.prototype.destroy = function(error) {
<add> this.socket.destroy(error);
<add>};
<add>
<add>
<add>IncomingMessage.prototype.setEncoding = function(encoding) {
<add> var StringDecoder = require('string_decoder').StringDecoder; // lazy load
<add> this._decoder = new StringDecoder(encoding);
<add>};
<add>
<add>
<add>IncomingMessage.prototype.pause = function() {
<add> this.socket.pause();
<add>};
<add>
<add>
<add>IncomingMessage.prototype.resume = function() {
<add> this.socket.resume();
<add>};
<add>
<add>
<add>// Add the given (field, value) pair to the message
<add>//
<add>// Per RFC2616, section 4.2 it is acceptable to join multiple instances of the
<add>// same header with a ', ' if the header in question supports specification of
<add>// multiple values this way. If not, we declare the first instance the winner
<add>// and drop the second. Extended header fields (those beginning with 'x-') are
<add>// always joined.
<add>IncomingMessage.prototype._addHeaderLine = function(field, value) {
<add> var dest = this.complete ? this.trailers : this.headers;
<add>
<add> switch (field) {
<add> // Array headers:
<add> case 'set-cookie':
<add> if (field in dest) {
<add> dest[field].push(value);
<add> } else {
<add> dest[field] = [value];
<add> }
<add> break;
<add>
<add> // Comma separate. Maybe make these arrays?
<add> case 'accept':
<add> case 'accept-charset':
<add> case 'accept-encoding':
<add> case 'accept-language':
<add> case 'connection':
<add> case 'cookie':
<add> case 'pragma':
<add> case 'link':
<add> if (field in dest) {
<add> dest[field] += ', ' + value;
<add> } else {
<add> dest[field] = value;
<add> }
<add> break;
<add>
<add>
<add> default:
<add> if (field.slice(0, 2) == 'x-') {
<add> // except for x-
<add> if (field in dest) {
<add> dest[field] += ', ' + value;
<add> } else {
<add> dest[field] = value;
<add> }
<add> } else {
<add> // drop duplicates
<add> if (!(field in dest)) dest[field] = value;
<add> }
<add> break;
<add> }
<add>};
<add>
<add>
<add>function OutgoingMessage() {
<add> stream.Stream.call(this);
<add>
<add> this.output = [];
<add> this.outputEncodings = [];
<add>
<add> this.writable = true;
<add>
<add> this._last = false;
<add> this.chunkedEncoding = false;
<add> this.shouldKeepAlive = true;
<add> this.useChunkedEncodingByDefault = true;
<add>
<add> this._hasBody = true;
<add> this._trailer = '';
<add>
<add> this.finished = false;
<add>}
<add>util.inherits(OutgoingMessage, stream.Stream);
<add>
<add>
<add>exports.OutgoingMessage = OutgoingMessage;
<add>
<add>
<add>OutgoingMessage.prototype.assignSocket = function(socket) {
<add> assert(!socket._httpMessage);
<add> socket._httpMessage = this;
<add> this.socket = socket;
<add> this.connection = socket;
<add> this._flush();
<add>};
<add>
<add>
<add>OutgoingMessage.prototype.detachSocket = function(socket) {
<add> assert(socket._httpMessage == this);
<add> socket._httpMessage = null;
<add> this.socket = this.connection = null;
<add>};
<add>
<add>
<add>OutgoingMessage.prototype.destroy = function(error) {
<add> this.socket.destroy(error);
<add>};
<add>
<add>
<add>// This abstract either writing directly to the socket or buffering it.
<add>OutgoingMessage.prototype._send = function(data, encoding) {
<add> // This is a shameful hack to get the headers and first body chunk onto
<add> // the same packet. Future versions of Node are going to take care of
<add> // this at a lower level and in a more general way.
<add> if (!this._headerSent) {
<add> if (typeof data === 'string') {
<add> data = this._header + data;
<add> } else {
<add> this.output.unshift(this._header);
<add> this.outputEncodings.unshift('ascii');
<add> }
<add> this._headerSent = true;
<add> }
<add> return this._writeRaw(data, encoding);
<add>};
<add>
<add>
<add>OutgoingMessage.prototype._writeRaw = function(data, encoding) {
<add> if (this.connection &&
<add> this.connection._httpMessage === this &&
<add> this.connection.writable) {
<add> // There might be pending data in the this.output buffer.
<add> while (this.output.length) {
<add> if (!this.connection.writable) {
<add> this._buffer(data, encoding);
<add> return false;
<add> }
<add> var c = this.output.shift();
<add> var e = this.outputEncodings.shift();
<add> this.connection.write(c, e);
<add> }
<add>
<add> // Directly write to socket.
<add> return this.connection.write(data, encoding);
<add> } else {
<add> this._buffer(data, encoding);
<add> return false;
<add> }
<add>};
<add>
<add>
<add>OutgoingMessage.prototype._buffer = function(data, encoding) {
<add> if (data.length === 0) return;
<add>
<add> var length = this.output.length;
<add>
<add> if (length === 0 || typeof data != 'string') {
<add> this.output.push(data);
<add> this.outputEncodings.push(encoding);
<add> return false;
<add> }
<add>
<add> var lastEncoding = this.outputEncodings[length - 1];
<add> var lastData = this.output[length - 1];
<add>
<add> if ((encoding && lastEncoding === encoding) ||
<add> (!encoding && data.constructor === lastData.constructor)) {
<add> this.output[length - 1] = lastData + data;
<add> return false;
<add> }
<add>
<add> this.output.push(data);
<add> this.outputEncodings.push(encoding);
<add>
<add> return false;
<add>};
<add>
<add>
<add>OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
<add> var sentConnectionHeader = false;
<add> var sentContentLengthHeader = false;
<add> var sentTransferEncodingHeader = false;
<add> var sentExpect = false;
<add>
<add> // firstLine in the case of request is: 'GET /index.html HTTP/1.1\r\n'
<add> // in the case of response it is: 'HTTP/1.1 200 OK\r\n'
<add> var messageHeader = firstLine;
<add> var field, value;
<add> var self = this;
<add>
<add> function store(field, value) {
<add> messageHeader += field + ': ' + value + CRLF;
<add>
<add> if (connectionExpression.test(field)) {
<add> sentConnectionHeader = true;
<add> if (closeExpression.test(value)) {
<add> self._last = true;
<add> } else {
<add> self.shouldKeepAlive = true;
<add> }
<add>
<add> } else if (transferEncodingExpression.test(field)) {
<add> sentTransferEncodingHeader = true;
<add> if (chunkExpression.test(value)) self.chunkedEncoding = true;
<add>
<add> } else if (contentLengthExpression.test(field)) {
<add> sentContentLengthHeader = true;
<add>
<add> } else if (expectExpression.test(field)) {
<add> sentExpect = true;
<add> }
<add> }
<add>
<add> if (headers) {
<add> var keys = Object.keys(headers);
<add> var isArray = (Array.isArray(headers));
<add> var field, value;
<add>
<add> for (var i = 0, l = keys.length; i < l; i++) {
<add> var key = keys[i];
<add> if (isArray) {
<add> field = headers[key][0];
<add> value = headers[key][1];
<add> } else {
<add> field = key;
<add> value = headers[key];
<add> }
<add>
<add> if (Array.isArray(value)) {
<add> for (var j = 0; j < value.length; j++) {
<add> store(field, value[j]);
<add> }
<add> } else {
<add> store(field, value);
<add> }
<add> }
<add> }
<add>
<add> // keep-alive logic
<add> if (sentConnectionHeader === false) {
<add> if (this.shouldKeepAlive &&
<add> (sentContentLengthHeader || this.useChunkedEncodingByDefault || this.agent)) {
<add> messageHeader += 'Connection: keep-alive\r\n';
<add> } else {
<add> this._last = true;
<add> messageHeader += 'Connection: close\r\n';
<add> }
<add> }
<add>
<add> if (sentContentLengthHeader == false && sentTransferEncodingHeader == false) {
<add> if (this._hasBody) {
<add> if (this.useChunkedEncodingByDefault) {
<add> messageHeader += 'Transfer-Encoding: chunked\r\n';
<add> this.chunkedEncoding = true;
<add> } else {
<add> this._last = true;
<add> }
<add> } else {
<add> // Make sure we don't end the 0\r\n\r\n at the end of the message.
<add> this.chunkedEncoding = false;
<add> }
<add> }
<add>
<add> this._header = messageHeader + CRLF;
<add> this._headerSent = false;
<add>
<add> // wait until the first body chunk, or close(), is sent to flush,
<add> // UNLESS we're sending Expect: 100-continue.
<add> if (sentExpect) this._send('');
<add>};
<add>
<add>
<add>OutgoingMessage.prototype.setHeader = function(name, value) {
<add> if (arguments.length < 2) {
<add> throw new Error("`name` and `value` are required for setHeader().");
<add> }
<add>
<add> if (this._header) {
<add> throw new Error("Can't set headers after they are sent.");
<add> }
<add>
<add> var key = name.toLowerCase();
<add> this._headers = this._headers || {};
<add> this._headerNames = this._headerNames || {};
<add> this._headers[key] = value;
<add> this._headerNames[key] = name;
<add>};
<add>
<add>
<add>OutgoingMessage.prototype.getHeader = function(name) {
<add> if (arguments.length < 1) {
<add> throw new Error("`name` is required for getHeader().");
<add> }
<add>
<add> if (this._header) {
<add> throw new Error("Can't use mutable header APIs after sent.");
<add> }
<add>
<add> if (!this._headers) return;
<add>
<add> var key = name.toLowerCase();
<add> return this._headers[key];
<add>};
<add>
<add>
<add>OutgoingMessage.prototype.removeHeader = function(name) {
<add> if (arguments.length < 1) {
<add> throw new Error("`name` is required for removeHeader().");
<add> }
<add>
<add> if (this._header) {
<add> throw new Error("Can't remove headers after they are sent.");
<add> }
<add>
<add> if (!this._headers) return;
<add>
<add> var key = name.toLowerCase();
<add> delete this._headers[key];
<add> delete this._headerNames[key];
<add>};
<add>
<add>
<add>OutgoingMessage.prototype._renderHeaders = function() {
<add> if (this._header) {
<add> throw new Error("Can't render headers after they are sent to the client.");
<add> }
<add>
<add> if (!this._headers) return {};
<add>
<add> var headers = {};
<add> var keys = Object.keys(this._headers);
<add> for (var i = 0, l = keys.length; i < l; i++) {
<add> var key = keys[i];
<add> headers[this._headerNames[key]] = this._headers[key];
<add> }
<add> return headers;
<add>};
<add>
<add>
<add>
<add>OutgoingMessage.prototype.write = function(chunk, encoding) {
<add> if (!this._header) {
<add> this._implicitHeader();
<add> }
<add>
<add> if (!this._hasBody) {
<add> console.error('This type of response MUST NOT have a body. ' +
<add> 'Ignoring write() calls.');
<add> return true;
<add> }
<add>
<add> if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk) &&
<add> !Array.isArray(chunk)) {
<add> throw new TypeError('first argument must be a string, Array, or Buffer');
<add> }
<add>
<add> if (chunk.length === 0) return false;
<add>
<add> var len, ret;
<add> if (this.chunkedEncoding) {
<add> if (typeof(chunk) === 'string') {
<add> len = Buffer.byteLength(chunk, encoding);
<add> var chunk = len.toString(16) + CRLF + chunk + CRLF;
<add> debug('string chunk = ' + util.inspect(chunk));
<add> ret = this._send(chunk, encoding);
<add> } else {
<add> // buffer
<add> len = chunk.length;
<add> this._send(len.toString(16) + CRLF);
<add> this._send(chunk);
<add> ret = this._send(CRLF);
<add> }
<add> } else {
<add> ret = this._send(chunk, encoding);
<add> }
<add>
<add> debug('write ret = ' + ret);
<add> return ret;
<add>};
<add>
<add>
<add>OutgoingMessage.prototype.addTrailers = function(headers) {
<add> this._trailer = '';
<add> var keys = Object.keys(headers);
<add> var isArray = (Array.isArray(headers));
<add> var field, value;
<add> for (var i = 0, l = keys.length; i < l; i++) {
<add> var key = keys[i];
<add> if (isArray) {
<add> field = headers[key][0];
<add> value = headers[key][1];
<add> } else {
<add> field = key;
<add> value = headers[key];
<add> }
<add>
<add> this._trailer += field + ': ' + value + CRLF;
<add> }
<add>};
<add>
<add>
<add>OutgoingMessage.prototype.end = function(data, encoding) {
<add> if (!this._header) {
<add> this._implicitHeader();
<add> }
<add>
<add> if (data && !this._hasBody) {
<add> console.error('This type of response MUST NOT have a body. ' +
<add> 'Ignoring data passed to end().');
<add> data = false;
<add> }
<add>
<add> var ret;
<add>
<add> var hot = this._headerSent === false &&
<add> typeof(data) === 'string' &&
<add> data.length > 0 &&
<add> this.output.length === 0 &&
<add> this.connection &&
<add> this.connection.writable &&
<add> this.connection._httpMessage === this;
<add>
<add> if (hot) {
<add> // Hot path. They're doing
<add> // res.writeHead();
<add> // res.end(blah);
<add> // HACKY.
<add>
<add> if (this.chunkedEncoding) {
<add> var l = Buffer.byteLength(data, encoding).toString(16);
<add> ret = this.connection.write(this._header + l + CRLF +
<add> data + '\r\n0\r\n' +
<add> this._trailer + '\r\n', encoding);
<add> } else {
<add> ret = this.connection.write(this._header + data, encoding);
<add> }
<add> this._headerSent = true;
<add>
<add> } else if (data) {
<add> // Normal body write.
<add> ret = this.write(data, encoding);
<add> }
<add>
<add> if (!hot) {
<add> if (this.chunkedEncoding) {
<add> ret = this._send('0\r\n' + this._trailer + '\r\n'); // Last chunk.
<add> } else {
<add> // Force a flush, HACK.
<add> ret = this._send('');
<add> }
<add> }
<add>
<add> this.finished = true;
<add>
<add> // There is the first message on the outgoing queue, and we've sent
<add> // everything to the socket.
<add> debug('outgoing message end.');
<add> if (this.output.length === 0 && this.connection._httpMessage === this) {
<add> this._finish();
<add> }
<add>
<add> return ret;
<add>};
<add>
<add>
<add>OutgoingMessage.prototype._finish = function() {
<add> assert(this.connection);
<add> if (this instanceof ServerResponse) {
<add> DTRACE_HTTP_SERVER_RESPONSE(this.connection);
<add> } else {
<add> assert(this instanceof ClientRequest);
<add> DTRACE_HTTP_CLIENT_REQUEST(this, this.connection);
<add> }
<add> this.emit('finish');
<add>};
<add>
<add>
<add>OutgoingMessage.prototype._flush = function() {
<add> // This logic is probably a bit confusing. Let me explain a bit:
<add> //
<add> // In both HTTP servers and clients it is possible to queue up several
<add> // outgoing messages. This is easiest to imagine in the case of a client.
<add> // Take the following situation:
<add> //
<add> // req1 = client.request('GET', '/');
<add> // req2 = client.request('POST', '/');
<add> //
<add> // When the user does
<add> //
<add> // req2.write('hello world\n');
<add> //
<add> // it's possible that the first request has not been completely flushed to
<add> // the socket yet. Thus the outgoing messages need to be prepared to queue
<add> // up data internally before sending it on further to the socket's queue.
<add> //
<add> // This function, outgoingFlush(), is called by both the Server and Client
<add> // to attempt to flush any pending messages out to the socket.
<add>
<add> if (!this.socket) return;
<add>
<add> var ret;
<add> while (this.output.length) {
<add>
<add> if (!this.socket.writable) return; // XXX Necessary?
<add>
<add> var data = this.output.shift();
<add> var encoding = this.outputEncodings.shift();
<add>
<add> ret = this.socket.write(data, encoding);
<add> }
<add>
<add> if (this.finished) {
<add> // This is a queue to the server or client to bring in the next this.
<add> this._finish();
<add> } else if (ret) {
<add> // This is necessary to prevent https from breaking
<add> this.emit('drain');
<add> }
<add>};
<add>
<add>
<add>
<add>
<add>function ServerResponse(req) {
<add> OutgoingMessage.call(this);
<add>
<add> if (req.method === 'HEAD') this._hasBody = false;
<add>
<add> if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) {
<add> this.useChunkedEncodingByDefault = false;
<add> this.shouldKeepAlive = false;
<add> }
<add>}
<add>util.inherits(ServerResponse, OutgoingMessage);
<add>
<add>
<add>exports.ServerResponse = ServerResponse;
<add>
<add>ServerResponse.prototype.statusCode = 200;
<add>
<add>ServerResponse.prototype.writeContinue = function() {
<add> this._writeRaw('HTTP/1.1 100 Continue' + CRLF + CRLF, 'ascii');
<add> this._sent100 = true;
<add>};
<add>
<add>ServerResponse.prototype._implicitHeader = function() {
<add> this.writeHead(this.statusCode);
<add>};
<add>
<add>ServerResponse.prototype.writeHead = function(statusCode) {
<add> var reasonPhrase, headers, headerIndex;
<add>
<add> if (typeof arguments[1] == 'string') {
<add> reasonPhrase = arguments[1];
<add> headerIndex = 2;
<add> } else {
<add> reasonPhrase = STATUS_CODES[statusCode] || 'unknown';
<add> headerIndex = 1;
<add> }
<add> this.statusCode = statusCode;
<add>
<add> var obj = arguments[headerIndex];
<add>
<add> if (obj && this._headers) {
<add> // Slow-case: when progressive API and header fields are passed.
<add> headers = this._renderHeaders();
<add>
<add> if (Array.isArray(obj)) {
<add> // handle array case
<add> // TODO: remove when array is no longer accepted
<add> var field;
<add> for (var i = 0, len = obj.length; i < len; ++i) {
<add> field = obj[i][0];
<add> if (field in headers) {
<add> obj.push([field, headers[field]]);
<add> }
<add> }
<add> headers = obj;
<add>
<add> } else {
<add> // handle object case
<add> for (var k in obj) {
<add> if (k) headers[k] = obj[k];
<add> }
<add> }
<add> } else if (this._headers) {
<add> // only progressive api is used
<add> headers = this._renderHeaders();
<add> } else {
<add> // only writeHead() called
<add> headers = obj;
<add> }
<add>
<add> var statusLine = 'HTTP/1.1 ' + statusCode.toString() + ' ' +
<add> reasonPhrase + CRLF;
<add>
<add> if (statusCode === 204 || statusCode === 304 ||
<add> (100 <= statusCode && statusCode <= 199)) {
<add> // RFC 2616, 10.2.5:
<add> // The 204 response MUST NOT include a message-body, and thus is always
<add> // terminated by the first empty line after the header fields.
<add> // RFC 2616, 10.3.5:
<add> // The 304 response MUST NOT contain a message-body, and thus is always
<add> // terminated by the first empty line after the header fields.
<add> // RFC 2616, 10.1 Informational 1xx:
<add> // This class of status code indicates a provisional response,
<add> // consisting only of the Status-Line and optional headers, and is
<add> // terminated by an empty line.
<add> this._hasBody = false;
<add> }
<add>
<add> // don't keep alive connections where the client expects 100 Continue
<add> // but we sent a final status; they may put extra bytes on the wire.
<add> if (this._expect_continue && ! this._sent100) {
<add> this.shouldKeepAlive = false;
<add> }
<add>
<add> this._storeHeader(statusLine, headers);
<add>};
<add>
<add>ServerResponse.prototype.writeHeader = function() {
<add> this.writeHead.apply(this, arguments);
<add>};
<add>
<add>
<add>// New Agent code.
<add>
<add>// The largest departure from the previous implementation is that
<add>// an Agent instance holds connections for a variable number of host:ports.
<add>// Surprisingly, this is still API compatible as far as third parties are
<add>// concerned. The only code that really notices the difference is the
<add>// request object.
<add>
<add>// Another departure is that all code related to HTTP parsing is in
<add>// ClientRequest.onSocket(). The Agent is now *strictly*
<add>// concerned with managing a connection pool.
<add>
<add>function Agent(options) {
<add> var self = this;
<add> self.options = options || {};
<add> self.requests = {};
<add> self.sockets = {};
<add> self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets;
<add> self.on('free', function(socket, host, port) {
<add> var name = host + ':' + port;
<add> if (self.requests[name] && self.requests[name].length) {
<add> self.requests[name].shift().onSocket(socket);
<add> } else {
<add> // If there are no pending requests just destroy the
<add> // socket and it will get removed from the pool. This
<add> // gets us out of timeout issues and allows us to
<add> // default to Connection:keep-alive.
<add> socket.destroy();
<add> }
<add> });
<add> self.createConnection = net.createConnection;
<add>}
<add>util.inherits(Agent, EventEmitter);
<add>exports.Agent = Agent;
<add>
<add>Agent.defaultMaxSockets = 5;
<add>
<add>Agent.prototype.defaultPort = 80;
<add>Agent.prototype.addRequest = function(req, host, port) {
<add> var name = host + ':' + port;
<add> if (!this.sockets[name]) {
<add> this.sockets[name] = [];
<add> }
<add> if (this.sockets[name].length < this.maxSockets) {
<add> // If we are under maxSockets create a new one.
<add> req.onSocket(this.createSocket(name, host, port));
<add> } else {
<add> // We are over limit so we'll add it to the queue.
<add> if (!this.requests[name]) {
<add> this.requests[name] = [];
<add> }
<add> this.requests[name].push(req);
<add> }
<add>};
<add>Agent.prototype.createSocket = function(name, host, port) {
<add> var self = this;
<add> var s = self.createConnection(port, host);
<add> if (!self.sockets[name]) {
<add> self.sockets[name] = [];
<add> }
<add> this.sockets[name].push(s);
<add> var onFree = function() {
<add> self.emit('free', s, host, port);
<add> }
<add> s.on('free', onFree);
<add> var onClose = function(err) {
<add> // This is the only place where sockets get removed from the Agent.
<add> // If you want to remove a socket from the pool, just close it.
<add> // All socket errors end in a close event anyway.
<add> self.removeSocket(s, name, host, port);
<add> }
<add> s.on('close', onClose);
<add> var onRemove = function() {
<add> // We need this function for cases like HTTP "upgrade"
<add> // (defined by WebSockets) where we need to remove a socket from the pool
<add> // because it'll be locked up indefinitely
<add> self.removeSocket(s, name, host, port);
<add> s.removeListener('close', onClose);
<add> s.removeListener('free', onFree);
<add> s.removeListener('agentRemove', onRemove);
<add> }
<add> s.on('agentRemove', onRemove);
<add> return s;
<add>};
<add>Agent.prototype.removeSocket = function(s, name, host, port) {
<add> if (this.sockets[name] && this.sockets[name].indexOf(s) !== -1) {
<add> this.sockets[name].shift(this.sockets[name].indexOf(s));
<add> } else if (this.sockets[name] && this.sockets[name].length === 0) {
<add> // don't leak
<add> delete this.sockets[name];
<add> delete this.requests[name];
<add> }
<add> if (this.requests[name] && this.requests[name].length) {
<add> // If we have pending requests and a socket gets closed a new one
<add> // needs to be created to take over in the pool for the one that closed.
<add> this.createSocket(name, host, port).emit('free');
<add> }
<add>};
<add>
<add>var globalAgent = new Agent();
<add>exports.globalAgent = globalAgent;
<add>
<add>function ClientRequest(options, cb) {
<add> var self = this;
<add> OutgoingMessage.call(self);
<add> self.agent = options.agent;
<add> options.defaultPort = options.defaultPort || 80;
<add>
<add> options.port = options.port || options.defaultPort;
<add> options.host = options.host || 'localhost';
<add>
<add> if (options.setHost === undefined) {
<add> options.setHost = true;
<add> }
<add>
<add> self.socketPath = options.socketPath;
<add>
<add> var method = self.method = (options.method || 'GET').toUpperCase();
<add> self.path = options.path || '/';
<add> if (cb) {
<add> self.on('response', cb);
<add> }
<add>
<add> if (!Array.isArray(options.headers)) {
<add> if (options.headers) {
<add> var keys = Object.keys(options.headers);
<add> for (var i = 0, l = keys.length; i < l; i++) {
<add> var key = keys[i];
<add> self.setHeader(key, options.headers[key]);
<add> }
<add> }
<add> if (options.host && !this.getHeader('host') && options.setHost) {
<add> var hostHeader = options.host;
<add> if (options.port && +options.port !== options.defaultPort) {
<add> hostHeader += ':' + options.port;
<add> }
<add> this.setHeader("Host", hostHeader);
<add> }
<add> }
<add>
<add> if (method === 'GET' || method === 'HEAD') {
<add> self.useChunkedEncodingByDefault = false;
<add> } else {
<add> self.useChunkedEncodingByDefault = true;
<add> }
<add>
<add> if (Array.isArray(options.headers)) {
<add> self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', options.headers);
<add> } else if (self.getHeader('expect')) {
<add> self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', self._renderHeaders());
<add> }
<add> if (self.socketPath) {
<add> self._last = true;
<add> self.shouldKeepAlive = false;
<add> self.onSocket(net.createConnection(self.socketPath));
<add> } else if (self.agent) {
<add> // If there is an agent we should default to Connection:keep-alive.
<add> self._last = false;
<add> self.shouldKeepAlive = true;
<add> self.agent.addRequest(self, options.host, options.port);
<add> } else {
<add> // No agent should default to Connection:close.
<add> self._last = true;
<add> self.shouldKeepAlive = false;
<add> self.onSocket(net.createConnection(options.port, options.host));
<add> }
<add>
<add> self._deferToConnect(null, null, function () {
<add> self._flush();
<add> })
<add>
<add>}
<add>util.inherits(ClientRequest, OutgoingMessage);
<add>
<add>exports.ClientRequest = ClientRequest;
<add>
<add>ClientRequest.prototype._implicitHeader = function() {
<add> this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n', this._renderHeaders());
<add>};
<add>
<add>ClientRequest.prototype.abort = function() {
<add> if (this.socket) {
<add> // in-progress
<add> this.socket.destroy();
<add> } else {
<add> // haven't been assigned a socket yet.
<add> // this could be more efficient, it could
<add> // remove itself from the pending requests
<add> this._deferToConnect('destroy', []);
<add> }
<add>};
<add>
<add>ClientRequest.prototype.onSocket = function(socket) {
<add> var parser = parsers.alloc();
<add> var req = this;
<add>
<add> req.socket = socket;
<add> req.connection = socket;
<add> parser.reinitialize('response');
<add> parser.socket = socket;
<add> parser.incoming = null;
<add> req.parser = parser;
<add>
<add> socket._httpMessage = req;
<add> // Setup "drain" propogation.
<add> httpSocketSetup(socket);
<add>
<add> var errorListener = function(err) {
<add> debug('HTTP SOCKET ERROR: ' + err.message + '\n' + err.stack);
<add> req.emit('error', err);
<add> // For Safety. Some additional errors might fire later on
<add> // and we need to make sure we don't double-fire the error event.
<add> req._hadError = true;
<add> parser.finish();
<add> }
<add> socket.on('error', errorListener);
<add>
<add> socket.ondata = function(d, start, end) {
<add> var ret = parser.execute(d, start, end - start);
<add> if (ret instanceof Error) {
<add> debug('parse error');
<add> socket.destroy(ret);
<add> } else if (parser.incoming && parser.incoming.upgrade) {
<add> var bytesParsed = ret;
<add> socket.ondata = null;
<add> socket.onend = null;
<add>
<add> var res = parser.incoming;
<add> req.res = res;
<add>
<add> // This is start + byteParsed + 1 due to the error of getting \n
<add> // in the upgradeHead from the closing lines of the headers
<add> var upgradeHead = d.slice(start + bytesParsed + 1, end);
<add> if (req.listeners('upgrade').length) {
<add> // Emit 'upgrade' on the Agent.
<add> req.upgraded = true;
<add> req.emit('upgrade', res, socket, upgradeHead);
<add> socket.emit('agentRemove');
<add> } else {
<add> // Got upgrade header, but have no handler.
<add> socket.destroy();
<add> }
<add> }
<add> };
<add>
<add> socket.onend = function() {
<add> if (!req.res) {
<add> // If we don't have a response then we know that the socket
<add> // ended prematurely and we need to emit an error on the request.
<add> req.emit('error', new Error("Request ended prematurely."));
<add> req._hadError = true;
<add> }
<add> parser.finish();
<add> parsers.free(parser); // I don't know if this is necessary --Mikeal
<add> socket.destroy();
<add> };
<add>
<add> var closeListener = function() {
<add> debug('HTTP socket close');
<add> req.emit('close');
<add> if (req.res && req.res.readable) {
<add> // Socket closed before we emitted "end" below.
<add> req.res.emit('aborted');
<add> req.res.emit('end');
<add> req.res.emit('close');
<add> } else if (!req.res && !req._hadError) {
<add> // This socket error fired before we started to
<add> // receive a response. The error needs to
<add> // fire on the request.
<add> req.emit('error', new Error('socket hang up'));
<add> }
<add> }
<add> socket.on('close', closeListener);
<add>
<add> parser.onIncoming = function(res, shouldKeepAlive) {
<add> debug('AGENT incoming response!');
<add>
<add> if (req.res) {
<add> // We already have a response object, this means the server
<add> // sent a double response.
<add> socket.destroy();
<add> return;
<add> }
<add> req.res = res;
<add>
<add> // Responses to HEAD requests are crazy.
<add> // HEAD responses aren't allowed to have an entity-body
<add> // but *can* have a content-length which actually corresponds
<add> // to the content-length of the entity-body had the request
<add> // been a GET.
<add> var isHeadResponse = req.method == 'HEAD';
<add> debug('AGENT isHeadResponse ' + isHeadResponse);
<add>
<add> if (res.statusCode == 100) {
<add> // restart the parser, as this is a continue message.
<add> delete req.res; // Clear res so that we don't hit double-responses.
<add> req.emit('continue');
<add> return true;
<add> }
<add>
<add> if (req.shouldKeepAlive && res.headers.connection !== 'keep-alive' && !req.upgraded) {
<add> // Server MUST respond with Connection:keep-alive for us to enable it.
<add> // If we've been upgraded (via WebSockets) we also shouldn't try to
<add> // keep the connection open.
<add> req.shouldKeepAlive = false;
<add> }
<add>
<add> res.addListener('end', function() {
<add> if (!req.shouldKeepAlive) {
<add> if (socket.writable) {
<add> debug('AGENT socket.destroySoon()');
<add> socket.destroySoon();
<add> }
<add> assert(!socket.writable);
<add> } else {
<add> debug('AGENT socket keep-alive');
<add> }
<add> });
<add>
<add> DTRACE_HTTP_CLIENT_RESPONSE(socket, req);
<add> req.emit('response', res);
<add>
<add> res.on('end', function() {
<add> if (req.shouldKeepAlive) {
<add> socket.removeListener('close', closeListener);
<add> socket.removeListener('error', errorListener);
<add> socket.emit('free');
<add> }
<add> });
<add>
<add> return isHeadResponse;
<add> };
<add> process.nextTick(function() {
<add> req.emit('socket', socket);
<add> });
<add>};
<add>ClientRequest.prototype._deferToConnect = function(method, arguments, cb) {
<add> // This function is for calls that need to happen once the socket is
<add> // connected and writable. It's an important promisy thing for all the socket
<add> // calls that happen either now (when a socket is assigned) or
<add> // in the future (when a socket gets assigned out of the pool and is
<add> // eventually writable).
<add> var self = this;
<add> var onSocket = function() {
<add> if (self.socket.writable) {
<add> if (method) {
<add> self.socket[method].apply(self.socket, arguments);
<add> }
<add> if (cb) { cb(); }
<add> } else {
<add> self.socket.on('connect', function() {
<add> if (method) {
<add> self.socket[method].apply(self.socket, arguments);
<add> }
<add> if (cb) { cb(); }
<add> });
<add> }
<add> }
<add> if (!self.socket) {
<add> self.once('socket', onSocket);
<add> } else {
<add> onSocket();
<add> }
<add>};
<add>ClientRequest.prototype.setTimeout = function() {
<add> this._deferToConnect('setTimeout', arguments);
<add>};
<add>ClientRequest.prototype.setNoDelay = function() {
<add> this._deferToConnect('setNoDelay', arguments);
<add>};
<add>ClientRequest.prototype.setSocketKeepAlive = function() {
<add> this._deferToConnect('setKeepAlive', arguments);
<add>};
<add>ClientRequest.prototype.pause = function() {
<add> var self = this;
<add> self._deferToConnect(null, null, function() {
<add> OutgoingMessage.prototype.pause.apply(self, []);
<add> });
<add>};
<add>
<add>
<add>exports.request = function(options, cb) {
<add> if (options.agent === undefined) {
<add> options.agent = globalAgent;
<add> }
<add> return new ClientRequest(options, cb);
<add>};
<add>
<add>exports.get = function(options, cb) {
<add> options.method = 'GET';
<add> var req = exports.request(options, cb);
<add> req.end();
<add> return req;
<add>};
<add>
<add>function httpSocketSetup(socket) {
<add> // NOTE: be sure not to use ondrain elsewhere in this file!
<add> socket.ondrain = function() {
<add> if (socket._httpMessage) {
<add> socket._httpMessage.emit('drain');
<add> }
<add> };
<add>}
<add>
<add>
<add>function Server(requestListener) {
<add> if (!(this instanceof Server)) return new Server(requestListener);
<add> net.Server.call(this, { allowHalfOpen: true });
<add>
<add> if (requestListener) {
<add> this.addListener('request', requestListener);
<add> }
<add>
<add> // Similar option to this. Too lazy to write my own docs.
<add> // http://www.squid-cache.org/Doc/config/half_closed_clients/
<add> // http://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F
<add> this.httpAllowHalfOpen = false;
<add>
<add> this.addListener('connection', connectionListener);
<add>}
<add>util.inherits(Server, net.Server);
<add>
<add>
<add>exports.Server = Server;
<add>
<add>
<add>exports.createServer = function(requestListener) {
<add> return new Server(requestListener);
<add>};
<add>
<add>
<add>function connectionListener(socket) {
<add> var self = this;
<add> var outgoing = [];
<add> var incoming = [];
<add>
<add> function abortIncoming() {
<add> while (incoming.length) {
<add> var req = incoming.shift();
<add> req.emit('aborted');
<add> req.emit('close');
<add> }
<add> // abort socket._httpMessage ?
<add> }
<add>
<add> debug('SERVER new http connection');
<add>
<add> httpSocketSetup(socket);
<add>
<add> socket.setTimeout(2 * 60 * 1000); // 2 minute timeout
<add> socket.addListener('timeout', function() {
<add> socket.destroy();
<add> });
<add>
<add> var parser = parsers.alloc();
<add> parser.reinitialize('request');
<add> parser.socket = socket;
<add> parser.incoming = null;
<add>
<add> socket.addListener('error', function(e) {
<add> self.emit('clientError', e);
<add> });
<add>
<add> socket.ondata = function(d, start, end) {
<add> var ret = parser.execute(d, start, end - start);
<add> if (ret instanceof Error) {
<add> debug('parse error');
<add> socket.destroy(ret);
<add> } else if (parser.incoming && parser.incoming.upgrade) {
<add> var bytesParsed = ret;
<add> socket.ondata = null;
<add> socket.onend = null;
<add>
<add> var req = parser.incoming;
<add>
<add> // This is start + byteParsed + 1 due to the error of getting \n
<add> // in the upgradeHead from the closing lines of the headers
<add> var upgradeHead = d.slice(start + bytesParsed + 1, end);
<add>
<add> if (self.listeners('upgrade').length) {
<add> self.emit('upgrade', req, req.socket, upgradeHead);
<add> } else {
<add> // Got upgrade header, but have no handler.
<add> socket.destroy();
<add> }
<add> }
<add> };
<add>
<add> socket.onend = function() {
<add> var ret = parser.finish();
<add>
<add> if (ret instanceof Error) {
<add> debug('parse error');
<add> socket.destroy(ret);
<add> return;
<add> }
<add>
<add> if (!self.httpAllowHalfOpen) {
<add> abortIncoming();
<add> if (socket.writable) socket.end();
<add> } else if (outgoing.length) {
<add> outgoing[outgoing.length - 1]._last = true;
<add> } else if (socket._httpMessage) {
<add> socket._httpMessage._last = true;
<add> } else {
<add> if (socket.writable) socket.end();
<add> }
<add> };
<add>
<add> socket.addListener('close', function() {
<add> debug('server socket close');
<add> // unref the parser for easy gc
<add> parsers.free(parser);
<add>
<add> abortIncoming();
<add> });
<add>
<add> // The following callback is issued after the headers have been read on a
<add> // new message. In this callback we setup the response object and pass it
<add> // to the user.
<add> parser.onIncoming = function(req, shouldKeepAlive) {
<add> incoming.push(req);
<add>
<add> var res = new ServerResponse(req);
<add> debug('server response shouldKeepAlive: ' + shouldKeepAlive);
<add> res.shouldKeepAlive = shouldKeepAlive;
<add> DTRACE_HTTP_SERVER_REQUEST(req, socket);
<add>
<add> if (socket._httpMessage) {
<add> // There are already pending outgoing res, append.
<add> outgoing.push(res);
<add> } else {
<add> res.assignSocket(socket);
<add> }
<add>
<add> // When we're finished writing the response, check if this is the last
<add> // respose, if so destroy the socket.
<add> res.on('finish', function() {
<add> // Usually the first incoming element should be our request. it may
<add> // be that in the case abortIncoming() was called that the incoming
<add> // array will be empty.
<add> assert(incoming.length == 0 || incoming[0] === req);
<add>
<add> incoming.shift();
<add>
<add> res.detachSocket(socket);
<add>
<add> if (res._last) {
<add> socket.destroySoon();
<add> } else {
<add> // start sending the next message
<add> var m = outgoing.shift();
<add> if (m) {
<add> m.assignSocket(socket);
<add> }
<add> }
<add> });
<add>
<add> if ('expect' in req.headers &&
<add> (req.httpVersionMajor == 1 && req.httpVersionMinor == 1) &&
<add> continueExpression.test(req.headers['expect'])) {
<add> res._expect_continue = true;
<add> if (self.listeners('checkContinue').length) {
<add> self.emit('checkContinue', req, res);
<add> } else {
<add> res.writeContinue();
<add> self.emit('request', req, res);
<add> }
<add> } else {
<add> self.emit('request', req, res);
<add> }
<add> return false; // Not a HEAD response. (Not even a response!)
<add> };
<add>}
<add>exports._connectionListener = connectionListener;
<add>
<add>// Legacy Interface
<add>
<add>function Client(port, host) {
<add> host = host || 'localhost';
<add> port = port || 80;
<add> this.host = host;
<add> this.port = port;
<add>}
<add>util.inherits(Client, EventEmitter);
<add>Client.prototype.request = function(method, path, headers) {
<add> var self = this;
<add> var options = {};
<add> options.host = self.host;
<add> options.port = self.port;
<add> if (method[0] === '/') {
<add> headers = path;
<add> path = method;
<add> method = 'GET';
<add> }
<add> options.method = method;
<add> options.path = path;
<add> options.headers = headers;
<add> var c = new ClientRequest(options);
<add> c.on('error', function(e) {
<add> self.emit('error', e);
<add> });
<add> // The old Client interface emitted "end" on socket end.
<add> // This doesn't map to how we want things to operate in the future
<add> // but it will get removed when we remove this legacy interface.
<add> c.on('socket', function(s) {
<add> s.on('end', function() {
<add> self.emit('end');
<add> });
<add> });
<add> return c;
<add>};
<add>
<add>exports.Client = Client;
<add>exports.createClient = function(port, host) {
<add> return new Client(port, host);
<add>};
<add>
<add>exports.cat = function(url, encoding_, headers_) {
<add> var encoding = 'utf8';
<add> var headers = {};
<add> var callback = null;
<add>
<add> console.error("http.cat will be removed in the near future. use http.get");
<add>
<add> // parse the arguments for the various options... very ugly
<add> if (typeof(arguments[1]) == 'string') {
<add> encoding = arguments[1];
<add> if (typeof(arguments[2]) == 'object') {
<add> headers = arguments[2];
<add> if (typeof(arguments[3]) == 'function') callback = arguments[3];
<add> } else {
<add> if (typeof(arguments[2]) == 'function') callback = arguments[2];
<add> }
<add> } else {
<add> // didn't specify encoding
<add> if (typeof(arguments[1]) == 'object') {
<add> headers = arguments[1];
<add> callback = arguments[2];
<add> } else {
<add> callback = arguments[1];
<add> }
<add> }
<add>
<add> var url = require('url').parse(url);
<add>
<add> var hasHost = false;
<add> if (Array.isArray(headers)) {
<add> for (var i = 0, l = headers.length; i < l; i++) {
<add> if (headers[i][0].toLowerCase() === 'host') {
<add> hasHost = true;
<add> break;
<add> }
<add> }
<add> } else if (typeof headers === 'Object') {
<add> var keys = Object.keys(headers);
<add> for (var i = 0, l = keys.length; i < l; i++) {
<add> var key = keys[i];
<add> if (key.toLowerCase() == 'host') {
<add> hasHost = true;
<add> break;
<add> }
<add> }
<add> }
<add> if (!hasHost) headers['Host'] = url.hostname;
<add>
<add> var content = '';
<add>
<add> var path = (url.pathname || '/') + (url.search || '') + (url.hash || '');
<add> var callbackSent = false;
<add> var req = exports.request({port: url.port || 80, host: url.hostname, path: path}, function(res) {
<add> if (res.statusCode < 200 || res.statusCode >= 300) {
<add> if (callback && !callbackSent) {
<add> callback(res.statusCode);
<add> callbackSent = true;
<add> }
<add> client.end();
<add> return;
<add> }
<add> res.setEncoding(encoding);
<add> res.addListener('data', function(chunk) { content += chunk; });
<add> res.addListener('end', function() {
<add> if (callback && !callbackSent) {
<add> callback(null, content);
<add> callbackSent = true;
<add> }
<add> });
<add> });
<add>
<add>
<add> req.addListener('error', function(err) {
<add> if (callback && !callbackSent) {
<add> callback(err);
<add> callbackSent = true;
<add> }
<add> });
<add>
<add> req.end();
<add>};
<ide><path>lib/https.js
<ide> exports.createServer = function(opts, requestListener) {
<ide>
<ide>
<ide> // HTTPS agents.
<add>var agents = {};
<ide>
<ide> function Agent(options) {
<ide> http.Agent.call(this, options);
<del> this.createConnection = function(port, host) {
<del> return tls.connect(port, host, options);
<del> };
<ide> }
<ide> inherits(Agent, http.Agent);
<add>
<add>
<ide> Agent.prototype.defaultPort = 443;
<ide>
<del>var globalAgent = new Agent();
<ide>
<del>exports.globalAgent = globalAgent;
<add>Agent.prototype._getConnection = function(options, cb) {
<add> if (NPN_ENABLED && !this.options.NPNProtocols) {
<add> this.options.NPNProtocols = ['http/1.1', 'http/1.0'];
<add> }
<add>
<add> var s = tls.connect(options.port, options.host, this.options, function() {
<add> // do other checks here?
<add> if (cb) cb();
<add> });
<add>
<add> return s;
<add>};
<add>
<add>
<add>function getAgent(options) {
<add> if (!options.port) options.port = 443;
<add>
<add> var id = options.host + ':' + options.port;
<add> var agent = agents[id];
<add>
<add> if (!agent) {
<add> agent = agents[id] = new Agent(options);
<add> }
<add>
<add> return agent;
<add>}
<add>exports.getAgent = getAgent;
<ide> exports.Agent = Agent;
<ide>
<ide> exports.request = function(options, cb) {
<ide> if (options.agent === undefined) {
<del> options.agent = globalAgent;
<add> options.agent = getAgent(options);
<add> } else if (options.agent === false) {
<add> options.agent = new Agent(options);
<ide> }
<del> return http.request(options, cb);
<add> return http._requestFromAgent(options, cb);
<ide> };
<ide>
<add>
<ide> exports.get = function(options, cb) {
<ide> options.method = 'GET';
<ide> var req = exports.request(options, cb);
<ide><path>lib/https2.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var tls = require('tls');
<add>var http = require('http');
<add>var inherits = require('util').inherits;
<add>
<add>var NPN_ENABLED = process.binding('constants').NPN_ENABLED;
<add>
<add>function Server(opts, requestListener) {
<add> if (!(this instanceof Server)) return new Server(opts, requestListener);
<add>
<add> if (NPN_ENABLED && !opts.NPNProtocols) {
<add> opts.NPNProtocols = ['http/1.1', 'http/1.0'];
<add> }
<add>
<add> tls.Server.call(this, opts, http._connectionListener);
<add>
<add> this.httpAllowHalfOpen = false;
<add>
<add> if (requestListener) {
<add> this.addListener('request', requestListener);
<add> }
<add>}
<add>inherits(Server, tls.Server);
<add>
<add>
<add>exports.Server = Server;
<add>
<add>
<add>exports.createServer = function(opts, requestListener) {
<add> return new Server(opts, requestListener);
<add>};
<add>
<add>
<add>// HTTPS agents.
<add>
<add>function Agent(options) {
<add> http.Agent.call(this, options);
<add> this.createConnection = function(port, host) {
<add> return tls.connect(port, host, options);
<add> };
<add>}
<add>inherits(Agent, http.Agent);
<add>Agent.prototype.defaultPort = 443;
<add>
<add>var globalAgent = new Agent();
<add>
<add>exports.globalAgent = globalAgent;
<add>exports.Agent = Agent;
<add>
<add>exports.request = function(options, cb) {
<add> if (options.agent === undefined) {
<add> options.agent = globalAgent;
<add> }
<add> return http.request(options, cb);
<add>};
<add>
<add>exports.get = function(options, cb) {
<add> options.method = 'GET';
<add> var req = exports.request(options, cb);
<add> req.end();
<add> return req;
<add>}; | 4 |
Text | Text | keep other translations table | fde255c6d4dfb750be1eeca6d499cd35f1c9149d | <ide><path>docs/spanish/how-to-work-on-coding-challenges.md
<add><table>
<add> <tr>
<add> <td> Read these guidelines in </td>
<add> <td><a href="/CONTRIBUTING.md"> English </a></td>
<add> <td><a href="/docs/chinese/CONTRIBUTING.md"> 中文 </a></td>
<add> <td><a href="/docs/russian/CONTRIBUTING.md"> русский </a></td>
<add> <td><a href="/docs/arabic/CONTRIBUTING.md"> عربى </a></td>
<add> <td><a href="/docs/spanish/CONTRIBUTING.md"> Español </a></td>
<add> <td><a href="/docs/portuguese/CONTRIBUTING.md"> Português </a></td>
<add> </tr>
<add></table>
<add>
<ide> # Cómo trabajar en los Desafíos de Programación
<ide>
<ide> ### Editando en GitHub
<ide> Creando y Editando Desafíos:
<ide>
<ide> 2. [Tipos de desafíos](https://github.com/freeCodeCamp/learn/blob/a5cb25704168aa37f59a582f0bb5a19b7bd89b46/utils/challengeTypes.js) - que significa el valor numerico de 'challengeType' (enum).
<ide>
<del>3. [Contribuyendo a freeCodeCamp - Escribiendo Pruebas de Desafío en ES6](https://www.youtube.com/watch?v=iOdD84OSfAE#t=2h49m55s) - un video siguiendo a [Ethan Arrowood](https://twitter.com/ArrowoodTech) mientras contribuye a la version antigua del currículo
<ide>\ No newline at end of file
<add>3. [Contribuyendo a freeCodeCamp - Escribiendo Pruebas de Desafío en ES6](https://www.youtube.com/watch?v=iOdD84OSfAE#t=2h49m55s) - un video siguiendo a [Ethan Arrowood](https://twitter.com/ArrowoodTech) mientras contribuye a la version antigua del currículo | 1 |
Javascript | Javascript | add relative path to accommodate limit | 0101a8f1a6eb363e1ae5ac7aca19223e37025f78 | <ide><path>test/parallel/test-net-connect-options-fd.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const net = require('net');
<add>const path = require('path');
<ide> const Pipe = process.binding('pipe_wrap').Pipe;
<ide>
<ide> if (common.isWindows) {
<ide> const forAllClients = (cb) => common.mustCall(cb, CLIENT_VARIANTS);
<ide>
<ide> // Test Pipe fd is wrapped correctly
<ide> {
<del> const prefix = `${common.PIPE}-net-connect-options-fd`;
<add> // Use relative path to avoid hitting 108-char length limit
<add> // for socket paths in libuv.
<add> const prefix = path.relative('.', `${common.PIPE}-net-connect-options-fd`);
<ide> const serverPath = `${prefix}-server`;
<ide> let counter = 0;
<ide> let socketCounter = 0; | 1 |
Javascript | Javascript | fix code style in the shader | ab7458e32694ee1c3f7695559db0781d87bd36ec | <ide><path>src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl.js
<ide> export default /* glsl */`
<ide> vec3 T = q1perp * st0.x + q0perp * st1.x;
<ide> vec3 B = q1perp * st0.y + q0perp * st1.y;
<ide>
<del> float det = max( dot(T,T), dot(B,B) );
<del> float scale = (det == 0.0) ? 0.0 : faceDirection * inversesqrt( det );
<add> float det = max( dot( T, T ), dot( B, B ) );
<add> float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );
<ide>
<del> return normalize( T * (mapN.x * scale) + B * ( mapN.y * scale ) + N * mapN.z );
<add> return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );
<ide>
<ide> }
<ide> | 1 |
Go | Go | remount everything as private in new mntns | b511d1f0cabd32ca30c87fa1bbc7ecac283dab39 | <ide><path>pkg/chrootarchive/chroot_linux.go
<ide> func chroot(path string) (err error) {
<ide> return fmt.Errorf("Error creating mount namespace before pivot: %v", err)
<ide> }
<ide>
<del> if err := mount.MakeRPrivate(path); err != nil {
<add> // make everything in new ns private
<add> if err := mount.MakeRPrivate("/"); err != nil {
<add> return err
<add> }
<add> // ensure path is a mountpoint
<add> if err := mount.MakePrivate(path); err != nil {
<ide> return err
<ide> }
<ide> | 1 |
Go | Go | use 0755 instead of 0700 | 1c509f4350d943c6aa8b9bff8dcbed28ee803735 | <ide><path>image.go
<ide> func StoreImage(img *Image, layerData Archive, root string, store bool) error {
<ide> }
<ide> // Store the layer
<ide> layer := layerPath(root)
<del> if err := os.MkdirAll(layer, 0700); err != nil {
<add> if err := os.MkdirAll(layer, 0755); err != nil {
<ide> return err
<ide> }
<ide> | 1 |
Ruby | Ruby | fix the underscore inflector optimization | dd5b00cd6c074944d53281cc1e111ce1ff57e1c3 | <ide><path>activesupport/lib/active_support/inflector/methods.rb
<ide> def underscore(camel_cased_word)
<ide> return camel_cased_word unless /[A-Z-]|::/.match?(camel_cased_word)
<ide> word = camel_cased_word.to_s.gsub("::", "/")
<ide> word.gsub!(inflections.acronyms_underscore_regex) { "#{$1 && '_' }#{$2.downcase}" }
<del> word.gsub!(/([A-Z\d]+)([A-Z][a-z])|([a-z\d])([A-Z])/) do
<del> if first_match = $1
<del> first_match << "_" << $2
<del> else
<del> $3 << "_" << $4
<del> end
<del> end
<add> word.gsub!(/([A-Z\d]+)(?=[A-Z][a-z])|([a-z\d])(?=[A-Z])/) { ($1 || $2) << "_" }
<ide> word.tr!("-", "_")
<ide> word.downcase!
<ide> word
<ide><path>activesupport/test/inflector_test_cases.rb
<ide> module InflectorTestCases
<ide> "Product" => "product",
<ide> "SpecialGuest" => "special_guest",
<ide> "ApplicationController" => "application_controller",
<del> "Area51Controller" => "area51_controller"
<add> "Area51Controller" => "area51_controller",
<add> "AppCDir" => "app_c_dir"
<ide> }
<ide>
<ide> UnderscoreToLowerCamel = { | 2 |
Javascript | Javascript | submit directive for use with forms | 04a4d8b061d98f46dc97fb550d388d248845b369 | <ide><path>src/directives.js
<ide> angularDirective("ng:click", function(expression, element){
<ide> };
<ide> });
<ide>
<add>
<add>/**
<add> * Enables binding angular expressions to onsubmit events.
<add> *
<add> * Additionally it prevents the default action (which for form means sending the request to the
<add> * server and reloading the current page).
<add> */
<add>angularDirective("ng:submit", function(expression, element) {
<add> return function(element) {
<add> var self = this;
<add> element.bind('submit', function(event) {
<add> self.$tryEval(expression, element);
<add> self.$root.$eval();
<add> event.preventDefault();
<add> });
<add> };
<add>});
<add>
<add>
<ide> angularDirective("ng:watch", function(expression, element){
<ide> return function(element){
<ide> var self = this;
<ide><path>test/directivesSpec.js
<ide> describe("directives", function(){
<ide> });
<ide> });
<ide>
<add>
<add> describe('ng:submit', function() {
<add> it('should get called on form submit', function() {
<add> var scope = compile('<form action="" ng:submit="submitted = true">' +
<add> '<input id="submit" type="submit"/>' +
<add> '</form>');
<add> scope.$eval();
<add> expect(scope.submitted).not.toBeDefined();
<add>
<add> browserTrigger(element.children()[0]);
<add> expect(scope.submitted).toEqual(true);
<add> });
<add> });
<add>
<ide> it('should ng:class', function(){
<ide> var scope = compile('<div class="existing" ng:class="[\'A\', \'B\']"></div>');
<ide> scope.$eval(); | 2 |
Python | Python | test nan_to_num with integer list input | 71dea15af12ca296cb0f360f09bbedd7c5edfd15 | <ide><path>numpy/lib/tests/test_type_check.py
<ide> def test_generic(self):
<ide> def test_integer(self):
<ide> vals = nan_to_num(1)
<ide> assert_all(vals == 1)
<add> vals = nan_to_num([1])
<add> assert_array_equal(vals, np.array([1], np.int))
<ide>
<ide> def test_complex_good(self):
<ide> vals = nan_to_num(1+1j) | 1 |
PHP | PHP | listener feedback | 191a8499eb9c7226e4564633143a82bdfd9510bd | <ide><path>src/Illuminate/Foundation/Console/ListenerMakeCommand.php
<ide> class ListenerMakeCommand extends GeneratorCommand
<ide> */
<ide> protected $type = 'Listener';
<ide>
<add> /**
<add> * Execute the console command.
<add> *
<add> * @return void
<add> */
<add> public function fire()
<add> {
<add> if (!$this->option('event')) {
<add> return $this->error("Missing required --event option");
<add> }
<add>
<add> parent::fire();
<add> }
<add>
<ide> /**
<ide> * Build the class with the given name.
<ide> * | 1 |
Javascript | Javascript | fix an unmatched link | bfba95ce46fd3e1605c5ee4ade1f1b1ca351cb4b | <ide><path>src/ngResource/resource.js
<ide> function shallowClearAndCopy(src, dst) {
<ide> * @requires $http
<ide> * @requires ng.$log
<ide> * @requires $q
<del> * @requires $timeout
<add> * @requires ng.$timeout
<ide> *
<ide> * @description
<ide> * A factory which creates a resource object that lets you interact with | 1 |
Ruby | Ruby | treat outdated brews as installed | 75a7c33e6aac30db7827ef3f1076b282057fff5b | <ide><path>Library/Homebrew/cmd/options.rb
<ide> require 'formula'
<add>require 'cmd/outdated'
<ide>
<ide> def ff
<ide> if ARGV.include? "--all"
<ide> Formula.all
<ide> elsif ARGV.include? "--installed"
<del> Formula.all.reject{ |f| not f.installed? }
<add> # outdated brews count as installed
<add> outdated = Homebrew.outdated_brews.collect{ |b| b.name }
<add> Formula.all.select do |f|
<add> f.installed? or outdated.include? f.name
<add> end
<ide> else
<ide> ARGV.formulae
<ide> end | 1 |
Python | Python | add exhaustive test for fpes in casts | 54d6ac5bf42d671ce7aa79e13dbdda1b9b2175a8 | <ide><path>numpy/core/tests/test_casting_floatingpoint_errors.py
<add>import pytest
<add>from pytest import param
<add>
<add>import numpy as np
<add>
<add>
<add>def values_and_dtypes():
<add> """
<add> Generate value+dtype pairs that generate floating point errors during
<add> casts. The invalid casts to integers will generate "invalid" value
<add> warnings, the float casts all generate "overflow".
<add>
<add> (The Python int/float paths don't need to get tested in all the same
<add> situations, but it does not hurt.)
<add> """
<add> # Casting to float16:
<add> yield param(70000, "float16", id="int-to-f2")
<add> yield param("70000", "float16", id="str-to-f2")
<add> yield param(70000.0, "float16", id="float-to-f2")
<add> yield param(np.longdouble(70000.), "float16", id="longdouble-to-f2")
<add> yield param(np.float64(70000.), "float16", id="double-to-f2")
<add> yield param(np.float32(70000.), "float16", id="float-to-f2")
<add> # Casting to float32:
<add> yield param(10**100, "float32", id="int-to-f4")
<add> yield param(1e100, "float32", id="float-to-f2")
<add> yield param(np.longdouble(1e300), "float32", id="longdouble-to-f2")
<add> yield param(np.float64(1e300), "float32", id="double-to-f2")
<add> # Casting to float64:
<add> if np.finfo(np.longdouble).max > np.finfo(np.float64).max:
<add> yield param(np.finfo(np.longdouble).max, "float64",
<add> id="longdouble-to-f4")
<add>
<add> # Invalid float to integer casts:
<add> with np.errstate(over="ignore"):
<add> for to_dt in np.typecodes["AllInteger"]:
<add> for value in [np.inf, np.nan]:
<add> for from_dt in np.typecodes["AllFloat"]:
<add> from_dt = np.dtype(from_dt)
<add> from_val = from_dt.type(value)
<add>
<add> yield param(from_val, to_dt, id=f"{from_val}-to-{to_dt}")
<add>
<add>
<add>def check_operations(dtype, value):
<add> """
<add> There are many dedicated paths in NumPy which cast and should check for
<add> floating point errors which occurred during those casts.
<add> """
<add> if dtype.kind != 'i':
<add> def assignment():
<add> arr = np.empty(3, dtype=dtype)
<add> arr[0] = value
<add>
<add> yield assignment
<add>
<add> def fill():
<add> arr = np.empty(3, dtype=dtype)
<add> arr.fill(value)
<add>
<add> yield fill
<add>
<add> def copyto_scalar():
<add> arr = np.empty(3, dtype=dtype)
<add> np.copyto(arr, value, casting="unsafe")
<add>
<add> yield copyto_scalar
<add>
<add> def copyto():
<add> arr = np.empty(3, dtype=dtype)
<add> np.copyto(arr, np.array([value, value, value]), casting="unsafe")
<add>
<add> yield copyto
<add>
<add> def copyto_scalar_masked():
<add> arr = np.empty(3, dtype=dtype)
<add> np.copyto(arr, value, casting="unsafe",
<add> where=[True, False, True])
<add>
<add> yield copyto_scalar_masked
<add>
<add> def copyto_masked():
<add> arr = np.empty(3, dtype=dtype)
<add> np.copyto(arr, np.array([value, value, value]), casting="unsafe",
<add> where=[True, False, True])
<add>
<add> yield copyto_masked
<add>
<add> def direct_cast():
<add> np.array([value, value, value]).astype(dtype)
<add>
<add> yield direct_cast
<add>
<add> def direct_cast_nd_strided():
<add> arr = np.full((5, 5, 5), fill_value=value)[:, ::2, :]
<add> arr.astype(dtype)
<add>
<add> yield direct_cast_nd_strided
<add>
<add> def boolean_array_assignment():
<add> arr = np.empty(3, dtype=dtype)
<add> arr[[True, False, True]] = np.array([value, value])
<add>
<add> yield boolean_array_assignment
<add>
<add> def integer_array_assignment():
<add> arr = np.empty(3, dtype=dtype)
<add> values = np.array([value, value])
<add>
<add> arr[[0, 1]] = values
<add>
<add> #yield integer_array_assignment
<add>
<add> def integer_array_assignment_with_subspace():
<add> arr = np.empty((5, 3), dtype=dtype)
<add> values = np.array([value, value, value])
<add>
<add> arr[[0, 2]] = values
<add>
<add> yield integer_array_assignment_with_subspace
<add>
<add>
<add>@pytest.mark.parametrize(["value", "dtype"], values_and_dtypes())
<add>@pytest.mark.filterwarnings("ignore::numpy.ComplexWarning")
<add>def test_floatingpoint_errors_casting(dtype, value):
<add> dtype = np.dtype(dtype)
<add> for operation in check_operations(dtype, value):
<add> dtype = np.dtype(dtype)
<add>
<add> match = "invalid" if dtype.kind in 'iu' else "overflow"
<add> with pytest.warns(RuntimeWarning, match=match):
<add> operation()
<add>
<add> with np.errstate(all="raise"):
<add> with pytest.raises(FloatingPointError, match=match):
<add> operation() | 1 |
Javascript | Javascript | add missing file | 418811360c170b974902a22ecf73f06307db42d1 | <ide><path>src/core/transition-filter.js
<add>d3_transitionPrototype.filter = function(filter) {
<add> return d3_transition(d3_selectionFilterSubgroups.call(this, filter),
<add> d3_transitionId || ++d3_transitionNextId, Date.now());
<add>}; | 1 |
Text | Text | update python versions [ci skip] | 383e2e1f128950b18435e75428777eb5c76902d9 | <ide><path>website/docs/usage/index.md
<ide> menu:
<ide> - ['Changelog', 'changelog']
<ide> ---
<ide>
<del>spaCy is compatible with **64-bit CPython 2.6+/3.3+** and runs on
<add>spaCy is compatible with **64-bit CPython 2.7+/3.4+** and runs on
<ide> **Unix/Linux**, **macOS/OS X** and **Windows**. The latest spaCy releases are
<ide> available over [pip](https://pypi.python.org/pypi/spacy) and
<ide> [conda](https://anaconda.org/conda-forge/spacy). | 1 |
Javascript | Javascript | replace ngerror with minerr | 003861d2fdb37b83e1d0939d49b70fbc67766997 | <ide><path>angularFiles.js
<ide> angularFiles = {
<ide> 'angularSrc': [
<add> 'src/minErr.js',
<ide> 'src/Angular.js',
<ide> 'src/loader.js',
<ide> 'src/AngularPublic.js',
<ide> 'src/jqLite.js',
<ide> 'src/apis.js',
<del> 'src/ngError.js',
<ide>
<ide> 'src/auto/injector.js',
<ide>
<ide><path>src/Angular.js
<ide> var /** holds major version number for IE or NaN for real browsers */
<ide> slice = [].slice,
<ide> push = [].push,
<ide> toString = Object.prototype.toString,
<add> ngMinErr = minErr('ng'),
<ide>
<ide>
<ide> _angular = window.angular,
<ide> function isLeafNode (node) {
<ide> */
<ide> function copy(source, destination){
<ide> if (isWindow(source) || isScope(source)) {
<del> throw ngError(43, "Can't copy! Making copies of Window or Scope instances is not supported.");
<add> throw ngMinErr('cpws', "Can't copy! Making copies of Window or Scope instances is not supported.");
<ide> }
<ide>
<ide> if (!destination) {
<ide> function copy(source, destination){
<ide> }
<ide> }
<ide> } else {
<del> if (source === destination) throw ngError(44, "Can't copy! Source and destination are identical.");
<add> if (source === destination) throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
<ide> if (isArray(source)) {
<ide> destination.length = 0;
<ide> for ( var i = 0; i < source.length; i++) {
<ide> function bindJQuery() {
<ide> */
<ide> function assertArg(arg, name, reason) {
<ide> if (!arg) {
<del> throw ngError(45, "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
<add> throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
<ide> }
<ide> return arg;
<ide> }
<ide><path>src/auto/injector.js
<ide> var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
<ide> var FN_ARG_SPLIT = /,/;
<ide> var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
<ide> var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
<add>var $injectorMinErr = minErr('$injector');
<ide> function annotate(fn) {
<ide> var $inject,
<ide> fnText,
<ide> function createInjector(modulesToLoad) {
<ide> },
<ide> providerInjector = (providerCache.$injector =
<ide> createInternalInjector(providerCache, function() {
<del> throw ngError(1, "Unknown provider: {0}", path.join(' <- '));
<add> throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
<ide> })),
<ide> instanceCache = {},
<ide> instanceInjector = (instanceCache.$injector =
<ide> function createInjector(modulesToLoad) {
<ide> provider_ = providerInjector.instantiate(provider_);
<ide> }
<ide> if (!provider_.$get) {
<del> throw ngError(2, "Provider '{0}' must define $get factory method.", name);
<add> throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
<ide> }
<ide> return providerCache[name + providerSuffix] = provider_;
<ide> }
<ide> function createInjector(modulesToLoad) {
<ide> function getService(serviceName) {
<ide> if (cache.hasOwnProperty(serviceName)) {
<ide> if (cache[serviceName] === INSTANTIATING) {
<del> throw ngError(4, 'Circular dependency found: {0}', path.join(' <- '));
<add> throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- '));
<ide> }
<ide> return cache[serviceName];
<ide> } else {
<ide> function createInjector(modulesToLoad) {
<ide> for(i = 0, length = $inject.length; i < length; i++) {
<ide> key = $inject[i];
<ide> if (typeof key !== 'string') {
<del> throw ngError(3, 'Incorrect injection token! Expected service name as string, got {0}', key);
<add> throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key);
<ide> }
<ide> args.push(
<ide> locals && locals.hasOwnProperty(key)
<ide><path>src/jqLite.js
<ide> function JQLite(element) {
<ide> }
<ide> if (!(this instanceof JQLite)) {
<ide> if (isString(element) && element.charAt(0) != '<') {
<del> throw ngError(46, 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
<add> throw minErr('jqLite')('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
<ide> }
<ide> return new JQLite(element);
<ide> }
<ide><path>src/loader.js
<ide> function setupModuleLoader(window) {
<ide> }
<ide> return ensure(modules, name, function() {
<ide> if (!requires) {
<del> throw ngError(47, "Module '{0}' is not available! You either misspelled the module name or forgot to load it.", name);
<add> throw minErr('$injector')('nomod', "Module '{0}' is not available! You either misspelled the module name or forgot to load it.", name);
<ide> }
<ide>
<ide> /** @type {!Array.<Array.<*>>} */
<ide><path>src/minErr.js
<add>'use strict';
<add>
<add>/**
<add> * @description
<add> *
<add> * This object provides a utility for producing rich Error messages within
<add> * Angular. It can be called as follows:
<add> *
<add> * var exampleMinErr = minErr('example');
<add> * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
<add> *
<add> * The above creates an instance of minErr in the example namespace. The
<add> * resulting error will have a namespaced error code of example.one. The
<add> * resulting error will replace {0} with the value of foo, and {1} with the
<add> * value of bar. The object is not restricted in the number of arguments it can
<add> * take.
<add> *
<add> * If fewer arguments are specified than necessary for interpolation, the extra
<add> * interpolation markers will be preserved in the final string.
<add> *
<add> * Since data will be parsed statically during a build step, some restrictions
<add> * are applied with respect to how minErr instances are created and called.
<add> * Instances should have names of the form namespaceMinErr for a minErr created
<add> * using minErr('namespace') . Error codes, namespaces and template strings
<add> * should all be static strings, not variables or general expressions.
<add> *
<add> * @param {string} module The namespace to use for the new minErr instance.
<add> * @returns {function(string, string, ...): Error} instance
<add> */
<add>
<add>function minErr(module) {
<add> return function () {
<add> var prefix = '[' + (module ? module + ':' : '') + arguments[0] + '] ',
<add> template = arguments[1],
<add> templateArgs = arguments,
<add> message;
<add>
<add> message = prefix + template.replace(/\{\d+\}/g, function (match) {
<add> var index = +match.slice(1, -1), arg;
<add>
<add> if (index + 2 < templateArgs.length) {
<add> arg = templateArgs[index + 2];
<add> if (isFunction(arg)) {
<add> return arg.toString().replace(/ \{[\s\S]*$/, '');
<add> } else if (isUndefined(arg)) {
<add> return 'undefined';
<add> } else if (!isString(arg)) {
<add> return toJson(arg);
<add> }
<add> return arg;
<add> }
<add> return match;
<add> });
<add>
<add> return new Error(message);
<add> };
<add>}
<ide><path>src/ng/cacheFactory.js
<ide> function $CacheFactoryProvider() {
<ide>
<ide> function cacheFactory(cacheId, options) {
<ide> if (cacheId in caches) {
<del> throw ngError(10, "CacheId '{0}' is already taken!", cacheId);
<add> throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
<ide> }
<ide>
<ide> var size = 0,
<ide><path>src/ng/compile.js
<ide> * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
<ide> */
<ide>
<add>var $compileMinErr = minErr('$compile');
<ide>
<ide> /**
<ide> * @ngdoc service
<ide> function $CompileProvider($provide) {
<ide> var startNode = node;
<ide> do {
<ide> if (!node) {
<del> throw ngError(51, "Unterminated attribute, found '{0}' but no matching '{1}' found.", attrStart, attrEnd);
<add> throw $compileMinErr('utrat', "Unterminated attribute, found '{0}' but no matching '{1}' found.", attrStart, attrEnd);
<ide> }
<ide> if (node.nodeType == 1 /** Element **/) {
<ide> if (node.hasAttribute(attrStart)) depth++;
<ide> function $CompileProvider($provide) {
<ide> compileNode = $template[0];
<ide>
<ide> if ($template.length != 1 || compileNode.nodeType !== 1) {
<del> throw ngError(12, "Template for directive '{0}' must have exactly one root element.", directiveName);
<add> throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", directiveName, '');
<ide> }
<ide>
<ide> replaceWith(jqCollection, $compileNode, compileNode);
<ide> function $CompileProvider($provide) {
<ide> }
<ide> value = $element[retrievalMethod]('$' + require + 'Controller');
<ide> if (!value && !optional) {
<del> throw ngError(13, "Controller '{0}', required by directive '{1}', can't be found!", require, directiveName);
<add> throw $compileMinErr('ctreq', "Controller '{0}', required by directive '{1}', can't be found!", require, directiveName);
<ide> }
<ide> return value;
<ide> } else if (isArray(require)) {
<ide> function $CompileProvider($provide) {
<ide> parentSet = parentGet.assign || function() {
<ide> // reset the change, or we will throw this exception on every $digest
<ide> lastValue = scope[scopeName] = parentGet(parentScope);
<del> throw ngError(14, "Expression '{0}' used with directive '{1}' is non-assignable!",
<add> throw $compileMinErr('noass', "Expression '{0}' used with directive '{1}' is non-assignable!",
<ide> attrs[attrName], newIsolateScopeDirective.name);
<ide> };
<ide> lastValue = scope[scopeName] = parentGet(parentScope);
<ide> function $CompileProvider($provide) {
<ide> }
<ide>
<ide> default: {
<del> throw ngError(15, "Invalid isolate scope definition for directive '{0}'. Definition: {... {1}: '{2}' ...}",
<add> throw $compileMinErr('iscp', "Invalid isolate scope definition for directive '{0}'. Definition: {... {1}: '{2}' ...}",
<ide> newIsolateScopeDirective.name, scopeName, definition);
<ide> }
<ide> }
<ide> function $CompileProvider($provide) {
<ide> compileNode = $template[0];
<ide>
<ide> if ($template.length != 1 || compileNode.nodeType !== 1) {
<del> throw ngError(16, "Template for directive '{0}' must have exactly one root element. Template: {1}",
<add> throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}",
<ide> origAsyncDirective.name, templateUrl);
<ide> }
<ide>
<ide> function $CompileProvider($provide) {
<ide> linkQueue = null;
<ide> }).
<ide> error(function(response, code, headers, config) {
<del> throw ngError(17, 'Failed to load template: {0}', config.url);
<add> throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
<ide> });
<ide>
<ide> return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
<ide> function $CompileProvider($provide) {
<ide>
<ide> function assertNoDuplicate(what, previousDirective, directive, element) {
<ide> if (previousDirective) {
<del> throw ngError(18, 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
<add> throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
<ide> previousDirective.name, directive.name, what, startingTag(element));
<ide> }
<ide> }
<ide><path>src/ng/controller.js
<ide> function $ControllerProvider() {
<ide>
<ide> if (identifier) {
<ide> if (!(locals && typeof locals.$scope == 'object')) {
<del> throw ngError(47, "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", constructor || expression.name, identifier);
<add> throw minErr('$controller')('noscp', "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", constructor || expression.name, identifier);
<ide> }
<ide>
<ide> locals.$scope[identifier] = instance;
<ide><path>src/ng/directive/input.js
<ide> function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
<ide> var patternObj = scope.$eval(pattern);
<ide>
<ide> if (!patternObj || !patternObj.test) {
<del> throw ngError(5, 'ngPattern error! Expected {0} to be a RegExp but was {1}. Element: {2}',
<del> pattern, patternObj, startingTag(element));
<add> throw minErr('ngPattern')('noregexp',
<add> 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern,
<add> patternObj, startingTag(element));
<ide> }
<ide> return validate(patternObj, value);
<ide> };
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide> ngModelSet = ngModelGet.assign;
<ide>
<ide> if (!ngModelSet) {
<del> throw ngError(6, "ngModel error! Expression '{0}' is non-assignable. Element: {1}", $attr.ngModel,
<del> startingTag($element));
<add> throw minErr('ngModel')('noass', "Expression '{0}' is non-assignable. Element: {1}",
<add> $attr.ngModel, startingTag($element));
<ide> }
<ide>
<ide> /**
<ide><path>src/ng/directive/ngRepeat.js
<ide> */
<ide> var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
<ide> var NG_REMOVED = '$$NG_REMOVED';
<add> var ngRepeatMinErr = minErr('ngRepeat');
<ide> return {
<ide> transclude: 'element',
<ide> priority: 1000,
<ide> var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
<ide> hashFnLocals = {$id: hashKey};
<ide>
<ide> if (!match) {
<del> throw ngError(7, "ngRepeat error! Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
<add> throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
<ide> expression);
<ide> }
<ide>
<ide> var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
<ide>
<ide> match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
<ide> if (!match) {
<del> throw ngError(8, "ngRepeat error! '_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
<add> throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
<ide> lhs);
<ide> }
<ide> valueIdentifier = match[3] || match[1];
<ide> var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
<ide> if (block && block.startNode) lastBlockMap[block.id] = block;
<ide> });
<ide> // This is a duplicate and we need to throw an error
<del> throw ngError(50, "ngRepeat error! Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}",
<add> throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}",
<ide> expression, trackById);
<ide> } else {
<ide> // new never before seen block
<ide><path>src/ng/directive/select.js
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> var match;
<ide>
<ide> if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
<del> throw ngError(9,
<del> "ngOptions error! Expected expression in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_' but got '{0}'. Element: {1}",
<add> throw minErr('ngOptions')('iexp',
<add> "Expected expression in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_' but got '{0}'. Element: {1}",
<ide> optionsExp, startingTag(selectElement));
<ide> }
<ide>
<ide><path>src/ng/httpBackend.js
<ide> var XHR = window.XMLHttpRequest || function() {
<ide> try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
<ide> try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
<ide> try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
<del> throw ngError(19, "This browser does not support XMLHttpRequest.");
<add> throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest.");
<ide> };
<ide>
<ide>
<ide><path>src/ng/interpolate.js
<ide> function $InterpolateProvider() {
<ide> return concat.join('');
<ide> }
<ide> catch(err) {
<del> var newErr = ngError(48, "$interpolate error! Can't interpolate: {0}\n{1}", text, err.toString());
<add> var newErr = minErr('$interpolate')('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
<ide> $exceptionHandler(newErr);
<ide> }
<ide> };
<ide><path>src/ng/location.js
<ide> var SERVER_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
<ide> PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
<ide> DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
<add>var $locationMinErr = minErr('$location');
<ide>
<ide>
<ide> /**
<ide> function LocationHtml5Url(appBase, basePrefix) {
<ide> matchUrl(url, parsed);
<ide> var pathUrl = beginsWith(appBaseNoFile, url);
<ide> if (!isString(pathUrl)) {
<del> throw ngError(21, '$location error! Invalid url "{0}", missing path prefix "{1}".', url, appBaseNoFile);
<add> throw $locationMinErr('nopp', 'Invalid url "{0}", missing path prefix "{1}".', url, appBaseNoFile);
<ide> }
<ide> matchAppUrl(pathUrl, parsed);
<ide> extend(this, parsed);
<ide> function LocationHashbangUrl(appBase, hashPrefix) {
<ide> matchUrl(url, this);
<ide> var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
<ide> if (!isString(withoutBaseUrl)) {
<del> throw ngError(22, '$location error! Invalid url "{0}", does not start with "{1}".', url, appBase);
<add> throw $locationMinErr('istart', 'Invalid url "{0}", does not start with "{1}".', url, appBase);
<ide> }
<ide> var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' ? beginsWith(hashPrefix, withoutBaseUrl) : withoutBaseUrl;
<ide> if (!isString(withoutHashUrl)) {
<del> throw ngError(49, '$location error! Invalid url "{0}", missing hash prefix "{1}".', url, hashPrefix);
<add> throw $locationMinErr('nohash', 'Invalid url "{0}", missing hash prefix "{1}".', url, hashPrefix);
<ide> }
<ide> matchAppUrl(withoutHashUrl, this);
<ide> this.$$compose();
<ide><path>src/ng/parse.js
<ide> var OPERATORS = {
<ide> '!':function(self, locals, a){return !a(self, locals);}
<ide> };
<ide> var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
<add>var $parseMinErr = minErr('$parse');
<ide>
<ide> function lex(text, csp){
<ide> var tokens = [],
<ide> function lex(text, csp){
<ide> var colStr = (isDefined(start) ?
<ide> "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
<ide> : " " + end);
<del> throw ngError(23, "Lexer Error: {0} at column{1} in expression [{2}].",
<add> throw $parseMinErr('lexerr', "Lexer Error: {0} at column{1} in expression [{2}].",
<ide> error, colStr, text);
<ide> }
<ide>
<ide> function parser(text, json, $filter, csp){
<ide>
<ide> ///////////////////////////////////
<ide> function throwError(msg, token) {
<del> throw ngError(24,
<add> throw $parseMinErr('syntax',
<ide> "Syntax Error: Token '{0}' {1} at column {2} of the expression [{3}] starting at [{4}].",
<ide> token.text, msg, (token.index + 1), text, text.substring(token.index));
<ide> }
<ide>
<ide> function peekToken() {
<ide> if (tokens.length === 0)
<del> throw ngError(25, "Unexpected end of expression: {0}", text);
<add> throw $parseMinErr('ueoe', "Unexpected end of expression: {0}", text);
<ide> return tokens[0];
<ide> }
<ide>
<ide><path>src/ng/rootScope.js
<ide> */
<ide> function $RootScopeProvider(){
<ide> var TTL = 10;
<add> var $rootScopeMinErr = minErr('$rootScope');
<ide>
<ide> this.digestTtl = function(value) {
<ide> if (arguments.length) {
<ide> function $RootScopeProvider(){
<ide>
<ide> if(dirty && !(ttl--)) {
<ide> clearPhase();
<del> throw ngError(27,
<add> throw $rootScopeMinErr('infdig',
<ide> '{0} $digest() iterations reached. Aborting!\nWatchers fired in the last 5 iterations: {1}',
<ide> TTL, toJson(watchLog));
<ide> }
<ide> function $RootScopeProvider(){
<ide>
<ide> function beginPhase(phase) {
<ide> if ($rootScope.$$phase) {
<del> throw ngError(28, '{0} already in progress', $rootScope.$$phase);
<add> throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
<ide> }
<ide>
<ide> $rootScope.$$phase = phase;
<ide><path>src/ngError.js
<del>'use strict';
<del>
<del>/**
<del> * @description
<del> *
<del> * This object extends the error class and provides interpolation capability
<del> * to make it easier to write and read Error messages within Angular. It can
<del> * be called as follows:
<del> *
<del> * throw ngError(13, 'This {0} is {1}', foo, bar);
<del> *
<del> * The above will replace {0} with the value of foo, and {1} with the value of
<del> * bar. The object is not restricted in the number of arguments it can take.
<del> *
<del> * If fewer arguments are specified than necessary for interpolation, the extra
<del> * interpolation markers will be preserved in the final string.
<del> *
<del> * @param {...} arguments The first argument to this object is the error
<del> * number, the second argument the message with templated points for
<del> * Interpolation (of the for {0} for the first, {1} for the second and
<del> * so on). The second argument onwards are interpolated into the error
<del> * message string in order.
<del> */
<del>function ngError() {
<del> var message = '[NgErr' + arguments[0] + '] ' + arguments[1],
<del> i = 0,
<del> l = arguments.length - 2,
<del> curlyRegexp, arg;
<del>
<del> for (; i < l; i++) {
<del> curlyRegexp = new RegExp("\\{" + i + "\\}", "gm");
<del> arg = arguments[i + 2];
<del>
<del> if (isFunction(arg)) {
<del> arg = arg.toString().replace(/ \{[\s\S]*$/, '');
<del> } else if (!isString(arg)) {
<del> arg = toJson(arg);
<del> }
<del>
<del> message = message.replace(curlyRegexp, arg);
<del> }
<del>
<del> // even if we are called as constructor we can bypass the new ngError instance and return
<del> // an instance of a real Error that contains correct stack info + extra frame for ngError call
<del> // TODO(i): can we rewrite the stack string to remove ngError frame?
<del> return new Error(message);
<del>}
<ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide>
<ide> it('should throw an exception if a Scope is being copied', inject(function($rootScope) {
<ide> expect(function() { copy($rootScope.$new()); }).
<del> toThrow("[NgErr43] Can't copy! Making copies of Window or Scope instances is not supported.");
<add> toThrow("[ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported.");
<ide> }));
<ide>
<ide> it('should throw an exception if a Window is being copied', function() {
<ide> expect(function() { copy(window); }).
<del> toThrow("[NgErr43] Can't copy! Making copies of Window or Scope instances is not supported.");
<add> toThrow("[ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported.");
<ide> });
<ide>
<ide> it('should throw an exception when source and destination are equivalent', function() {
<ide> var src, dst;
<ide> src = dst = {key: 'value'};
<del> expect(function() { copy(src, dst); }).toThrow("[NgErr44] Can't copy! Source and destination are identical.");
<add> expect(function() { copy(src, dst); }).toThrow("[ng:cpi] Can't copy! Source and destination are identical.");
<ide> src = dst = [2, 4];
<del> expect(function() { copy(src, dst); }).toThrow("[NgErr44] Can't copy! Source and destination are identical.");
<add> expect(function() { copy(src, dst); }).toThrow("[ng:cpi] Can't copy! Source and destination are identical.");
<ide> });
<ide>
<ide> it('should not copy the private $$hashKey', function() {
<ide> describe('angular', function() {
<ide>
<ide> expect(function() {
<ide> angularInit(appElement, bootstrap);
<del> }).toThrow("[NgErr47] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it.");
<add> }).toThrow("[$injector:nomod] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it.");
<ide> });
<ide> });
<ide>
<ide> describe('angular', function() {
<ide>
<ide> expect(function() {
<ide> angular.bootstrap(element, ['doesntexist']);
<del> }).toThrow("[NgErr47] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it.");
<add> }).toThrow("[$injector:nomod] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it.");
<ide>
<ide> expect(element.html()).toBe('{{1+2}}');
<ide> dealoc(element);
<ide> describe('angular', function() {
<ide>
<ide> expect(function() {
<ide> element.injector().get('foo');
<del> }).toThrow('[NgErr1] Unknown provider: fooProvider <- foo');
<add> }).toThrow('[$injector:unpr] Unknown provider: fooProvider <- foo');
<ide>
<ide> expect(element.injector().get('$http')).toBeDefined();
<ide> });
<ide><path>test/BinderSpec.js
<ide> describe('Binder', function() {
<ide> $rootScope.error['throw'] = function() {throw 'MyError';};
<ide> errorLogs.length = 0;
<ide> $rootScope.$apply();
<del> expect(errorLogs.shift().message).toBe("[NgErr48] $interpolate error! Can't interpolate: {{error.throw()}}\nMyError");
<add> expect(errorLogs.shift().message).toBe("[$interpolate:interr] Can't interpolate: {{error.throw()}}\nMyError");
<ide>
<ide> $rootScope.error['throw'] = function() {return 'ok';};
<ide> $rootScope.$apply();
<ide><path>test/auto/injectorSpec.js
<ide> describe('injector', function() {
<ide> it('should provide useful message if no provider', function() {
<ide> expect(function() {
<ide> injector.get('idontexist');
<del> }).toThrow("[NgErr1] Unknown provider: idontexistProvider <- idontexist");
<add> }).toThrow("[$injector:unpr] Unknown provider: idontexistProvider <- idontexist");
<ide> });
<ide>
<ide>
<ide> describe('injector', function() {
<ide> providers('b', function(a) {return 2;});
<ide> expect(function() {
<ide> injector.get('b');
<del> }).toThrow("[NgErr1] Unknown provider: idontexistProvider <- idontexist <- a <- b");
<add> }).toThrow("[$injector:unpr] Unknown provider: idontexistProvider <- idontexist <- a <- b");
<ide> });
<ide>
<ide>
<ide> describe('injector', function() {
<ide> it('should fail with errors if not function or array', function() {
<ide> expect(function() {
<ide> injector.invoke({});
<del> }).toThrow("[NgErr45] Argument 'fn' is not a function, got Object");
<add> }).toThrow("[ng:areq] Argument 'fn' is not a function, got Object");
<ide> expect(function() {
<ide> injector.invoke(['a', 123], {});
<del> }).toThrow("[NgErr45] Argument 'fn' is not a function, got number");
<add> }).toThrow("[ng:areq] Argument 'fn' is not a function, got number");
<ide> });
<ide> });
<ide>
<ide> describe('injector', function() {
<ide> it('should error on invalid module name', function() {
<ide> expect(function() {
<ide> createInjector(['IDontExist'], {});
<del> }).toThrow("[NgErr47] Module 'IDontExist' is not available! You either misspelled the module name or forgot to load it.");
<add> }).toThrow("[$injector:nomod] Module 'IDontExist' is not available! You either misspelled the module name or forgot to load it.");
<ide>
<ide> });
<ide>
<ide> describe('injector', function() {
<ide> createInjector([
<ide> {}
<ide> ], {});
<del> }).toThrow("[NgErr45] Argument 'module' is not a function, got Object");
<add> }).toThrow("[ng:areq] Argument 'module' is not a function, got Object");
<ide> });
<ide>
<ide>
<ide> describe('injector', function() {
<ide> angular.module('TestModule', [], function(xyzzy) {});
<ide> expect(function() {
<ide> createInjector(['TestModule']);
<del> }).toThrow('[NgErr1] Unknown provider: xyzzy from TestModule');
<add> }).toThrow('[$injector:unpr] Unknown provider: xyzzy from TestModule');
<ide> });
<ide>
<ide>
<ide> it('should decorate the missing service error with module function', function() {
<ide> function myModule(xyzzy){}
<ide> expect(function() {
<ide> createInjector([myModule]);
<del> }).toThrow('[NgErr1] Unknown provider: xyzzy from ' + myModule);
<add> }).toThrow('[$injector:unpr] Unknown provider: xyzzy from ' + myModule);
<ide> });
<ide>
<ide>
<ide> it('should decorate the missing service error with module array function', function() {
<ide> function myModule(xyzzy){}
<ide> expect(function() {
<ide> createInjector([['xyzzy', myModule]]);
<del> }).toThrow('[NgErr1] Unknown provider: xyzzy from ' + myModule);
<add> }).toThrow('[$injector:unpr] Unknown provider: xyzzy from ' + myModule);
<ide> });
<ide>
<ide>
<ide> describe('injector', function() {
<ide> $provide.factory('service', function(service){});
<ide> return function(service) {}
<ide> }])
<del> }).toThrow("[NgErr4] Circular dependency found: service");
<add> }).toThrow("[$injector:cdep] Circular dependency found: service");
<ide> });
<ide>
<ide>
<ide> describe('injector', function() {
<ide> $provide.factory('b', function(a){});
<ide> return function(a) {}
<ide> }])
<del> }).toThrow('[NgErr4] Circular dependency found: b <- a');
<add> }).toThrow('[$injector:cdep] Circular dependency found: b <- a');
<ide> });
<ide> });
<ide> });
<ide> describe('injector', function() {
<ide> it('should throw usefull error on wrong argument type]', function() {
<ide> expect(function() {
<ide> $injector.invoke({});
<del> }).toThrow("[NgErr45] Argument 'fn' is not a function, got Object");
<add> }).toThrow("[ng:areq] Argument 'fn' is not a function, got Object");
<ide> });
<ide> });
<ide>
<ide> describe('injector', function() {
<ide> }]);
<ide> expect(function() {
<ide> $injector.get('nameProvider');
<del> }).toThrow("[NgErr1] Unknown provider: nameProviderProvider <- nameProvider");
<add> }).toThrow("[$injector:unpr] Unknown provider: nameProviderProvider <- nameProvider");
<ide> });
<ide>
<ide>
<ide> it('should prevent provider configuration in app', function() {
<ide> var $injector = createInjector([]);
<ide> expect(function() {
<ide> $injector.get('$provide').value('a', 'b');
<del> }).toThrow("[NgErr1] Unknown provider: $provideProvider <- $provide");
<add> }).toThrow("[$injector:unpr] Unknown provider: $provideProvider <- $provide");
<ide> });
<ide>
<ide>
<ide> describe('injector', function() {
<ide> createInjector([function($provide) {
<ide> $provide.value('name', 'angular')
<ide> }, instanceLookupInModule]);
<del> }).toThrow('[NgErr1] Unknown provider: name from ' + String(instanceLookupInModule));
<add> }).toThrow('[$injector:unpr] Unknown provider: name from ' + String(instanceLookupInModule));
<ide> });
<ide> });
<ide> });
<ide><path>test/loaderSpec.js
<ide> describe('module loader', function() {
<ide> it('should complain of no module', function() {
<ide> expect(function() {
<ide> window.angular.module('dontExist');
<del> }).toThrow("[NgErr47] Module 'dontExist' is not available! You either misspelled the module name or forgot to load it.");
<add> }).toThrow("[$injector:nomod] Module 'dontExist' is not available! You either misspelled the module name or forgot to load it.");
<ide> });
<ide> });
<ide><path>test/matchers.js
<ide> beforeEach(function() {
<ide> angular.element(this.actual).hasClass(clazz);
<ide> },
<ide>
<del> toThrowNg: function(expected) {
<del> return jasmine.Matchers.prototype.toThrow.call(this, new RegExp('\\[NgErr\\d*\\] ' +
<del> expected.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")));
<add> toThrowMatching: function(expected) {
<add> return jasmine.Matchers.prototype.toThrow.call(this, expected);
<ide> }
<ide> });
<ide> });
<add><path>test/minErrSpec.js
<del><path>test/ngErrorSpec.js
<ide> 'use strict';
<ide>
<del>describe('ngError', function() {
<del>
<add>describe('minErr', function () {
<add>
<ide> var supportStackTraces = function() {
<ide> var e = new Error();
<ide> return isDefined(e.stack);
<ide> };
<add> var emptyTestError = minErr(),
<add> testError = minErr('test');
<ide>
<del> it('should return an Error instance', function() {
<del> var myError = ngError();
<add> it('should return an Error factory', function() {
<add> var myError = testError('test', 'Oops');
<ide> expect(myError instanceof Error).toBe(true);
<ide> });
<ide>
<del>
<del> it('should generate stack trace at the frame where ngError was called', function() {
<add> it('should generate stack trace at the frame where the minErr instance was called', function() {
<ide> var myError;
<ide>
<ide> function someFn() {
<ide> function nestedFn() {
<del> myError = ngError(0, "I fail!");
<add> myError = testError('fail', "I fail!");
<ide> }
<ide> nestedFn();
<ide> }
<ide> describe('ngError', function() {
<ide> expect(myError.stack).toMatch(/^[.\s\S]+nestedFn[.\s\S]+someFn.+/);
<ide> });
<ide>
<del>
<ide> it('should interpolate string arguments without quotes', function() {
<del> var myError = ngError(26, 'This {0} is "{1}"', 'foo', 'bar');
<del> expect(myError.message).toBe('[NgErr26] This foo is "bar"');
<add> var myError = testError('1', 'This {0} is "{1}"', 'foo', 'bar');
<add> expect(myError.message).toBe('[test:1] This foo is "bar"');
<ide> });
<ide>
<del>
<ide> it('should interpolate non-string arguments', function() {
<ide> var arr = [1, 2, 3],
<ide> obj = {a: 123, b: 'baar'},
<ide> anonFn = function(something) { return something; },
<ide> namedFn = function foo(something) { return something; },
<ide> myError;
<ide>
<del> myError = ngError(26, 'arr: {0}; obj: {1}; anonFn: {2}; namedFn: {3}',
<add> myError = testError('26', 'arr: {0}; obj: {1}; anonFn: {2}; namedFn: {3}',
<ide> arr, obj, anonFn, namedFn);
<ide>
<del> expect(myError.message).toContain('[NgErr26] arr: [1,2,3]; obj: {"a":123,"b":"baar"};');
<add> expect(myError.message).toContain('[test:26] arr: [1,2,3]; obj: {"a":123,"b":"baar"};');
<ide> // IE does not add space after "function"
<ide> expect(myError.message).toMatch(/anonFn: function\s?\(something\);/);
<ide> expect(myError.message).toContain('namedFn: function foo(something)');
<ide> });
<ide>
<del>
<ide> it('should not suppress falsy objects', function() {
<del> var myError = ngError(26, 'false: {0}; zero: {1}; null: {2}; undefined: {3}; emptyStr: {4}',
<add> var myError = testError('26', 'false: {0}; zero: {1}; null: {2}; undefined: {3}; emptyStr: {4}',
<ide> false, 0, null, undefined, '');
<ide> expect(myError.message).
<del> toBe('[NgErr26] false: false; zero: 0; null: null; undefined: undefined; emptyStr: ');
<add> toBe('[test:26] false: false; zero: 0; null: null; undefined: undefined; emptyStr: ');
<ide> });
<ide>
<ide>
<ide> it('should preserve interpolation markers when fewer arguments than needed are provided', function() {
<ide> // this way we can easily see if we are passing fewer args than needed
<ide>
<ide> var foo = 'Fooooo',
<del> myError = ngError(26, 'This {0} is {1} on {2}', foo);
<add> myError = testError('26', 'This {0} is {1} on {2}', foo);
<ide>
<del> expect(myError.message).toBe('[NgErr26] This Fooooo is {1} on {2}');
<add> expect(myError.message).toBe('[test:26] This Fooooo is {1} on {2}');
<ide> });
<ide>
<ide>
<ide> it('should pass through the message if no interpolation is needed', function() {
<del> var myError = ngError(26, 'Something horrible happened!');
<del> expect(myError.message).toBe('[NgErr26] Something horrible happened!');
<add> var myError = testError('26', 'Something horrible happened!');
<add> expect(myError.message).toBe('[test:26] Something horrible happened!');
<add> });
<add>
<add> it('should include a namespace in the message only if it is namespaced', function () {
<add> var myError = emptyTestError('26', 'This is a {0}', 'Foo');
<add> var myNamespacedError = testError('26', 'That is a {0}', 'Bar');
<add> expect(myError.message).toBe('[26] This is a Foo');
<add> expect(myNamespacedError.message).toBe('[test:26] That is a Bar');
<ide> });
<ide> });
<ide><path>test/ng/animatorSpec.js
<ide> describe("$animator", function() {
<ide> expect(function() {
<ide> var animate = $animator($rootScope, { ngAnimate: ':' });
<ide> animate.enter();
<del> }).toThrow("[NgErr24] Syntax Error: Token ':' not a primary expression at column 1 of the expression [:] starting at [:].");
<add> }).toThrow("[$parse:syntax] Syntax Error: Token ':' not a primary expression at column 1 of the expression [:] starting at [:].");
<ide> }));
<ide> });
<ide><path>test/ng/cacheFactorySpec.js
<ide> describe('$cacheFactory', function() {
<ide> it('should complain if the cache id is being reused', inject(function($cacheFactory) {
<ide> $cacheFactory('cache1');
<ide> expect(function() { $cacheFactory('cache1'); }).
<del> toThrow("[NgErr10] CacheId 'cache1' is already taken!");
<add> toThrow("[$cacheFactory:iid] CacheId 'cache1' is already taken!");
<ide> }));
<ide>
<ide>
<ide><path>test/ng/compileSpec.js
<ide> describe('$compile', function() {
<ide> inject(function($compile) {
<ide> expect(function() {
<ide> $compile('<p no-root-elem></p>');
<del> }).toThrow("[NgErr12] Template for directive 'noRootElem' must have exactly one root element.");
<add> }).toThrow("[$compile:tplrt] Template for directive 'noRootElem' must have exactly one root element. ");
<ide>
<ide> expect(function() {
<ide> $compile('<p multi-root-elem></p>');
<del> }).toThrow("[NgErr12] Template for directive 'multiRootElem' must have exactly one root element.");
<add> }).toThrow("[$compile:tplrt] Template for directive 'multiRootElem' must have exactly one root element. ");
<ide>
<ide> // ws is ok
<ide> expect(function() {
<ide> describe('$compile', function() {
<ide>
<ide> expect(function() {
<ide> $httpBackend.flush();
<del> }).toThrow('[NgErr17] Failed to load template: hello.html');
<add> }).toThrow('[$compile:tpload] Failed to load template: hello.html');
<ide> expect(sortedHtml(element)).toBe('<div><b class="hello"></b></div>');
<ide> }
<ide> ));
<ide> describe('$compile', function() {
<ide> inject(function($compile){
<ide> expect(function() {
<ide> $compile('<div><div class="sync async"></div></div>');
<del> }).toThrow('[NgErr18] Multiple directives [sync, async] asking for template on: '+
<add> }).toThrow('[$compile:multidir] Multiple directives [sync, async] asking for template on: '+
<ide> '<div class="sync async">');
<ide> });
<ide> });
<ide> describe('$compile', function() {
<ide> $compile('<p template></p>');
<ide> $rootScope.$digest();
<ide> expect($exceptionHandler.errors.pop().message).
<del> toBe("[NgErr16] Template for directive 'template' must have exactly one root element. Template: template.html");
<add> toBe("[$compile:tplrt] Template for directive 'template' must have exactly one root element. template.html");
<ide>
<ide> // multi root
<ide> $templateCache.put('template.html', '<div></div><div></div>');
<ide> $compile('<p template></p>');
<ide> $rootScope.$digest();
<ide> expect($exceptionHandler.errors.pop().message).
<del> toBe("[NgErr16] Template for directive 'template' must have exactly one root element. Template: template.html");
<add> toBe("[$compile:tplrt] Template for directive 'template' must have exactly one root element. template.html");
<ide>
<ide> // ws is ok
<ide> $templateCache.put('template.html', ' <div></div> \n');
<ide> describe('$compile', function() {
<ide> function($rootScope, $compile) {
<ide> expect(function(){
<ide> $compile('<div class="iscope-a; scope-b"></div>');
<del> }).toThrow('[NgErr18] Multiple directives [iscopeA, scopeB] asking for isolated scope on: ' +
<add> }).toThrow('[$compile:multidir] Multiple directives [iscopeA, scopeB] asking for isolated scope on: ' +
<ide> '<div class="iscope-a; scope-b ng-isolate-scope ng-scope">');
<ide> })
<ide> );
<ide> describe('$compile', function() {
<ide> function($rootScope, $compile) {
<ide> expect(function(){
<ide> $compile('<div class="iscope-a; iscope-b"></div>');
<del> }).toThrow('[NgErr18] Multiple directives [iscopeA, iscopeB] asking for isolated scope on: ' +
<add> }).toThrow('[$compile:multidir] Multiple directives [iscopeA, iscopeB] asking for isolated scope on: ' +
<ide> '<div class="iscope-a; iscope-b ng-isolate-scope ng-scope">');
<ide> })
<ide> );
<ide> describe('$compile', function() {
<ide>
<ide> componentScope.ref = 'ignore me';
<ide> expect($rootScope.$apply).
<del> toThrow("[NgErr14] Expression ''hello ' + name' used with directive 'myComponent' is non-assignable!");
<add> toThrow("[$compile:noass] Expression ''hello ' + name' used with directive 'myComponent' is non-assignable!");
<ide> expect(componentScope.ref).toBe('hello world');
<ide> // reset since the exception was rethrown which prevented phase clearing
<ide> $rootScope.$$phase = null;
<ide> describe('$compile', function() {
<ide> it('should throw on unknown definition', inject(function() {
<ide> expect(function() {
<ide> compile('<div><span bad-declaration>');
<del> }).toThrow("[NgErr15] Invalid isolate scope definition for directive 'badDeclaration'. Definition: {... attr: 'xxx' ...}");
<add> }).toThrow("[$compile:iscp] Invalid isolate scope definition for directive 'badDeclaration'. Definition: {... attr: 'xxx' ...}");
<ide> }));
<ide>
<ide> it('should expose a $$isolateBindings property onto the scope', inject(function() {
<ide> describe('$compile', function() {
<ide> inject(function(log, $compile, $rootScope) {
<ide> expect(function() {
<ide> $compile('<div main><div dep></div></div>')($rootScope);
<del> }).toThrow("[NgErr13] Controller 'main', required by directive 'dep', can't be found!");
<add> }).toThrow("[$compile:ctreq] Controller 'main', required by directive 'dep', can't be found!");
<ide> });
<ide> });
<ide>
<ide> describe('$compile', function() {
<ide> inject(function($compile) {
<ide> expect(function() {
<ide> $compile('<div class="first second"></div>');
<del> }).toThrow('[NgErr18] Multiple directives [first, second] asking for transclusion on: ' +
<add> }).toThrow('[$compile:multidir] Multiple directives [first, second] asking for transclusion on: ' +
<ide> '<div class="first second ng-isolate-scope ng-scope">');
<ide> });
<ide> });
<ide> describe('$compile', function() {
<ide> '<div>' +
<ide> '<span foo-start></span>' +
<ide> '</div>');
<del> }).toThrow("[NgErr51] Unterminated attribute, found 'foo-start' but no matching 'foo-end' found.");
<add> }).toThrow("[$compile:utrat] Unterminated attribute, found 'foo-start' but no matching 'foo-end' found.");
<ide> });
<ide> });
<ide>
<ide> describe('$compile', function() {
<ide> '<div>' +
<ide> '<span foo-start><span foo-end></span></span>' +
<ide> '</div>');
<del> }).toThrow("[NgErr51] Unterminated attribute, found 'foo-start' but no matching 'foo-end' found.");
<add> }).toThrow("[$compile:utrat] Unterminated attribute, found 'foo-start' but no matching 'foo-end' found.");
<ide> });
<ide> });
<ide>
<ide><path>test/ng/controllerSpec.js
<ide> describe('$controller', function() {
<ide>
<ide> expect(function() {
<ide> $controller('a.b.FooCtrl as foo');
<del> }).toThrow("[NgErr47] Cannot export controller 'a.b.FooCtrl' as 'foo'! No $scope object provided via `locals`.");
<add> }).toThrow("[$controller:noscp] Cannot export controller 'a.b.FooCtrl' as 'foo'! No $scope object provided via `locals`.");
<ide>
<ide> });
<ide> });
<ide><path>test/ng/directive/inputSpec.js
<ide> describe('NgModelController', function() {
<ide> }
<ide>
<ide> expect(exception.message).
<del> toMatch(/^\[NgErr6\] ngModel error! Expression '1\+2' is non\-assignable\. Element: <input( value="")? ng-model="1\+2">$/);
<add> toMatch(/^\[ngModel:noass\] Expression '1\+2' is non\-assignable\. Element: <input( value="")? ng-model="1\+2">$/);
<ide> }));
<ide>
<ide>
<ide> describe('input', function() {
<ide> expect(function() {
<ide> compileInput('<input type="text" ng-model="throw \'\'">');
<ide> scope.$digest();
<del> }).toThrow("[NgErr24] Syntax Error: Token '''' is an unexpected token at column 7 of the expression [throw ''] starting at [''].");
<add> }).toThrow("[$parse:syntax] Syntax Error: Token '''' is an unexpected token at column 7 of the expression [throw ''] starting at [''].");
<ide> });
<ide>
<ide>
<ide> describe('input', function() {
<ide> expect(function() {
<ide> compileInput('<input type="text" ng-model="foo" ng-pattern="fooRegexp" />');
<ide> scope.$apply();
<del> }).toThrowNg('ngPattern error! Expected fooRegexp to be a RegExp but was undefined.');
<add> }).toThrowMatching(/^\[ngPattern:noregexp\] Expected fooRegexp to be a RegExp but was/);
<ide> });
<ide> });
<ide>
<ide><path>test/ng/directive/ngRepeatSpec.js
<ide> describe('ngRepeat', function() {
<ide> element = jqLite('<ul><li ng-repeat="i dont parse"></li></ul>');
<ide> $compile(element)(scope);
<ide> expect($exceptionHandler.errors.shift()[0].message).
<del> toBe("[NgErr7] ngRepeat error! Expected expression in form of '_item_ in _collection_[ track by _id_]' but got 'i dont parse'.");
<add> toBe("[ngRepeat:iexp] Expected expression in form of '_item_ in _collection_[ track by _id_]' but got 'i dont parse'.");
<ide> });
<ide>
<ide>
<ide> it("should throw error when left-hand-side of ngRepeat can't be parsed", function() {
<ide> element = jqLite('<ul><li ng-repeat="i dont parse in foo"></li></ul>');
<ide> $compile(element)(scope);
<ide> expect($exceptionHandler.errors.shift()[0].message).
<del> toBe("[NgErr8] ngRepeat error! '_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got 'i dont parse'.");
<add> toBe("[ngRepeat:iidexp] '_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got 'i dont parse'.");
<ide> });
<ide>
<ide>
<ide> describe('ngRepeat', function() {
<ide> scope.items = [a, a, a];
<ide> scope.$digest();
<ide> expect($exceptionHandler.errors.shift().message).
<del> toEqual("[NgErr50] ngRepeat error! Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: item in items, Duplicate key: object:003");
<add> toEqual("[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: item in items, Duplicate key: object:003");
<ide>
<ide> // recover
<ide> scope.items = [a];
<ide> describe('ngRepeat', function() {
<ide> scope.items = [d, d, d];
<ide> scope.$digest();
<ide> expect($exceptionHandler.errors.shift().message).
<del> toEqual("[NgErr50] ngRepeat error! Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: item in items, Duplicate key: object:009");
<add> toEqual("[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: item in items, Duplicate key: object:009");
<ide>
<ide> // recover
<ide> scope.items = [a];
<ide><path>test/ng/directive/selectSpec.js
<ide> describe('select', function() {
<ide>
<ide> it('should throw when not formated "? for ? in ?"', function() {
<ide> expect(function() {
<del> compile('<select ng-model="selected" ng-options="i dont parse"></select>');
<del> }).toThrowNg("ngOptions error! Expected expression in form of '_select_ (as _label_)? for (_key_,)?_value_ in" +
<del> " _collection_' but got 'i dont parse'.");
<add> compile('<select ng-model="selected" ng-options="i dont parse"></select>');
<add> }).toThrowMatching(/^\[ngOptions:iexp\] Expected expression in form of/);
<ide> });
<ide>
<ide>
<ide><path>test/ng/interpolateSpec.js
<ide> describe('$interpolate', function() {
<ide> };
<ide> expect(function () {
<ide> $interpolate('{{err()}}')($rootScope);
<del> }).toThrow("[NgErr48] $interpolate error! Can't interpolate: {{err()}}\nError: oops");
<add> }).toThrow("[$interpolate:interr] Can't interpolate: {{err()}}\nError: oops");
<ide> }));
<ide>
<ide> it('should stop interpolation when encountering an exception', inject(function($interpolate, $compile, $rootScope) {
<ide> describe('$interpolate', function() {
<ide> $compile(dom)($rootScope);
<ide> expect(function () {
<ide> $rootScope.$apply();
<del> }).toThrow("[NgErr48] $interpolate error! Can't interpolate: {{err()}}\nError: oops");
<add> }).toThrow("[$interpolate:interr] Can't interpolate: {{err()}}\nError: oops");
<ide> expect(dom[0].innerHTML).toEqual('2');
<ide> expect(dom[1].innerHTML).toEqual('{{err()}}');
<ide> expect(dom[2].innerHTML).toEqual('{{1 + 2}}');
<ide><path>test/ng/locationSpec.js
<ide> describe('$location', function() {
<ide>
<ide> expect(function() {
<ide> url.$$parse('http://other.server.org/path#/path');
<del> }).toThrow('[NgErr21] $location error! Invalid url "http://other.server.org/path#/path", missing path prefix "http://server.org/base/".');
<add> }).toThrow('[$location:nopp] Invalid url "http://other.server.org/path#/path", missing path prefix "http://server.org/base/".');
<ide> });
<ide>
<ide>
<ide> describe('$location', function() {
<ide>
<ide> expect(function() {
<ide> url.$$parse('http://server.org/path#/path');
<del> }).toThrow('[NgErr21] $location error! Invalid url "http://server.org/path#/path", missing path prefix "http://server.org/base/".');
<add> }).toThrow('[$location:nopp] Invalid url "http://server.org/path#/path", missing path prefix "http://server.org/base/".');
<ide> });
<ide>
<ide>
<ide> describe('$location', function() {
<ide> it('should throw error when invalid server url given', function() {
<ide> expect(function() {
<ide> url.$$parse('http://server.org/path#/path');
<del> }).toThrow('[NgErr22] $location error! Invalid url "http://server.org/path#/path", does not start with "http://www.server.org:1234/base".');
<add> }).toThrow('[$location:istart] Invalid url "http://server.org/path#/path", does not start with "http://www.server.org:1234/base".');
<ide> });
<ide>
<ide>
<ide> it('should throw error when invalid hashbang prefix given', function() {
<ide> expect(function() {
<ide> url.$$parse('http://www.server.org:1234/base#/path');
<del> }).toThrow('[NgErr49] $location error! Invalid url "http://www.server.org:1234/base#/path", missing hash prefix "#!".');
<add> }).toThrow('[$location:nohash] Invalid url "http://www.server.org:1234/base#/path", missing hash prefix "#!".');
<ide> });
<ide>
<ide>
<ide><path>test/ng/parseSpec.js
<ide> describe('parser', function() {
<ide> it('should throws exception for invalid exponent', function() {
<ide> expect(function() {
<ide> lex("0.5E-");
<del> }).toThrow(new Error('[NgErr23] Lexer Error: Invalid exponent at column 4 in expression [0.5E-].'));
<add> }).toThrow(new Error('[$parse:lexerr] Lexer Error: Invalid exponent at column 4 in expression [0.5E-].'));
<ide>
<ide> expect(function() {
<ide> lex("0.5E-A");
<del> }).toThrow(new Error('[NgErr23] Lexer Error: Invalid exponent at column 4 in expression [0.5E-A].'));
<add> }).toThrow(new Error('[$parse:lexerr] Lexer Error: Invalid exponent at column 4 in expression [0.5E-A].'));
<ide> });
<ide>
<ide> it('should tokenize number starting with a dot', function() {
<ide> describe('parser', function() {
<ide> it('should throw error on invalid unicode', function() {
<ide> expect(function() {
<ide> lex("'\\u1''bla'");
<del> }).toThrow(new Error("[NgErr23] Lexer Error: Invalid unicode escape [\\u1''b] at column 2 in expression ['\\u1''bla']."));
<add> }).toThrow(new Error("[$parse:lexerr] Lexer Error: Invalid unicode escape [\\u1''b] at column 2 in expression ['\\u1''bla']."));
<ide> });
<ide> });
<ide>
<ide> describe('parser', function() {
<ide>
<ide> expect(function() {
<ide> scope.$eval("1|nonexistent");
<del> }).toThrow(new Error("[NgErr1] Unknown provider: nonexistentFilterProvider <- nonexistentFilter"));
<add> }).toThrow(new Error("[$injector:unpr] Unknown provider: nonexistentFilterProvider <- nonexistentFilter"));
<ide>
<ide> scope.offset = 3;
<ide> expect(scope.$eval("'abcd'|substring:1:offset")).toEqual("bc");
<ide> describe('parser', function() {
<ide> it('should throw exception on non-closed bracket', function() {
<ide> expect(function() {
<ide> scope.$eval('[].count(');
<del> }).toThrow('[NgErr25] Unexpected end of expression: [].count(');
<add> }).toThrow('[$parse:ueoe] Unexpected end of expression: [].count(');
<ide> });
<ide>
<ide> it('should evaluate double negation', function() {
<ide><path>test/ng/rootScopeSpec.js
<ide> describe('Scope', function() {
<ide>
<ide> expect(function() {
<ide> $rootScope.$digest();
<del> }).toThrow('[NgErr27] 100 $digest() iterations reached. Aborting!\n'+
<add> }).toThrow('[$rootScope:infdig] 100 $digest() iterations reached. Aborting!\n'+
<ide> 'Watchers fired in the last 5 iterations: ' +
<ide> '[["a; newVal: 96; oldVal: 95","b; newVal: 97; oldVal: 96"],' +
<ide> '["a; newVal: 97; oldVal: 96","b; newVal: 98; oldVal: 97"],' +
<ide> describe('Scope', function() {
<ide> $rootScope.$watch('name', function() {
<ide> expect(function() {
<ide> $rootScope.$digest();
<del> }).toThrow('[NgErr28] $digest already in progress');
<add> }).toThrow('[$rootScope:inprog] $digest already in progress');
<ide> callCount++;
<ide> });
<ide> $rootScope.name = 'a';
<ide> describe('Scope', function() {
<ide> $rootScope.$apply(function() {
<ide> $rootScope.$apply();
<ide> });
<del> }).toThrow('[NgErr28] $apply already in progress');
<add> }).toThrow('[$rootScope:inprog] $apply already in progress');
<ide> }));
<ide>
<ide>
<ide> describe('Scope', function() {
<ide> $rootScope.$apply();
<ide> });
<ide> });
<del> }).toThrow('[NgErr28] $digest already in progress');
<add> }).toThrow('[$rootScope:inprog] $digest already in progress');
<ide> }));
<ide>
<ide>
<ide> describe('Scope', function() {
<ide> childScope1.$watch('x', function() {
<ide> childScope1.$apply();
<ide> });
<del> expect(function() { childScope1.$apply(); }).toThrow('[NgErr28] $digest already in progress');
<add> expect(function() { childScope1.$apply(); }).toThrow('[$rootScope:inprog] $digest already in progress');
<ide> }));
<ide>
<ide>
<ide> describe('Scope', function() {
<ide>
<ide> expect(function() { childScope2.$apply(function() {
<ide> childScope2.x = 'something';
<del> }); }).toThrow('[NgErr28] $digest already in progress');
<add> }); }).toThrow('[$rootScope:inprog] $digest already in progress');
<ide> }));
<ide> });
<ide> }); | 35 |
Text | Text | fix internal link in collaborator-guide.md | 8dbdca8ed3f56c458436229bc0e441457860d319 | <ide><path>doc/contributing/collaborator-guide.md
<ide> * [Unintended breaking changes](#unintended-breaking-changes)
<ide> * [Reverting commits](#reverting-commits)
<ide> * [Introducing new modules](#introducing-new-modules)
<del> * [Additions to Node-API](#additions-to-n-api)
<add> * [Additions to Node-API](#additions-to-node-api)
<ide> * [Deprecations](#deprecations)
<ide> * [Involving the TSC](#involving-the-tsc)
<ide> * [Landing pull requests](#landing-pull-requests) | 1 |
Ruby | Ruby | use explicit deprecator in wrappers tests | 4fdcd3100eb6f24895c04ab40692a3f9d605b703 | <ide><path>activesupport/test/deprecation/method_wrappers_test.rb
<ide> def new_protected_method; "abc" end
<ide> def new_private_method; "abc" end
<ide> alias_method :old_private_method, :new_private_method
<ide> end
<add>
<add> @deprecator = ActiveSupport::Deprecation.new
<ide> end
<ide>
<ide> def test_deprecate_methods_without_alternate_method
<del> warning = /old_method is deprecated and will be removed from Rails \d.\d./
<del> ActiveSupport::Deprecation.deprecate_methods(@klass, :old_method)
<add> @deprecator.deprecate_methods(@klass, :old_method)
<ide>
<del> assert_deprecated(warning) { assert_equal "abc", @klass.new.old_method }
<add> assert_deprecated("old_method", @deprecator) do
<add> assert_equal @klass.new.new_method, @klass.new.old_method
<add> end
<ide> end
<ide>
<ide> def test_deprecate_methods_warning_default
<del> warning = /old_method is deprecated and will be removed from Rails \d.\d \(use new_method instead\)/
<del> ActiveSupport::Deprecation.deprecate_methods(@klass, old_method: :new_method)
<add> @deprecator.deprecate_methods(@klass, old_method: :new_method)
<ide>
<del> assert_deprecated(warning) { assert_equal "abc", @klass.new.old_method }
<add> assert_deprecated(/old_method .* \(use new_method instead\)/, @deprecator) do
<add> assert_equal @klass.new.new_method, @klass.new.old_method
<add> end
<ide> end
<ide>
<ide> def test_deprecate_methods_warning_with_optional_deprecator
<del> warning = /old_method is deprecated and will be removed from MyGem next-release \(use new_method instead\)/
<del> deprecator = ActiveSupport::Deprecation.new("next-release", "MyGem")
<del> ActiveSupport::Deprecation.deprecate_methods(@klass, old_method: :new_method, deprecator: deprecator)
<del>
<del> assert_deprecated(warning, deprecator) { assert_equal "abc", @klass.new.old_method }
<del> end
<add> @deprecator = ActiveSupport::Deprecation.new("next-release", "MyGem")
<add> ActiveSupport::Deprecation.deprecate_methods(@klass, :old_method, deprecator: @deprecator)
<ide>
<del> def test_deprecate_methods_warning_when_deprecated_with_custom_deprecator
<del> warning = /old_method is deprecated and will be removed from MyGem next-release \(use new_method instead\)/
<del> deprecator = ActiveSupport::Deprecation.new("next-release", "MyGem")
<del> deprecator.deprecate_methods(@klass, old_method: :new_method)
<del>
<del> assert_deprecated(warning, deprecator) { assert_equal "abc", @klass.new.old_method }
<add> assert_deprecated(/old_method .* MyGem next-release/, @deprecator) do
<add> assert_equal @klass.new.new_method, @klass.new.old_method
<add> end
<ide> end
<ide>
<ide> def test_deprecate_methods_protected_method
<del> ActiveSupport::Deprecation.deprecate_methods(@klass, old_protected_method: :new_protected_method)
<add> @deprecator.deprecate_methods(@klass, old_protected_method: :new_protected_method)
<ide>
<ide> assert(@klass.protected_method_defined?(:old_protected_method))
<ide> end
<ide>
<ide> def test_deprecate_methods_private_method
<del> ActiveSupport::Deprecation.deprecate_methods(@klass, old_private_method: :new_private_method)
<add> @deprecator.deprecate_methods(@klass, old_private_method: :new_private_method)
<ide>
<ide> assert(@klass.private_method_defined?(:old_private_method))
<ide> end
<ide> def old_method
<ide> "abc"
<ide> end
<ide> end
<del> ActiveSupport::Deprecation.deprecate_methods(mod, old_method: :new_method)
<add> @deprecator.deprecate_methods(mod, :old_method)
<ide>
<del> warning = /old_method is deprecated and will be removed from Rails \d.\d \(use new_method instead\)/
<del> assert_deprecated(warning) { assert_equal "abc", mod.old_method }
<add> assert_deprecated("old_method", @deprecator) do
<add> assert_equal "abc", mod.old_method
<add> end
<ide> end
<ide>
<ide> def test_deprecate_method_when_class_extends_module
<ide> def old_method
<ide> "abc"
<ide> end
<ide> end
<del> @klass.extend mod
<del> ActiveSupport::Deprecation.deprecate_methods(mod, old_method: :new_method)
<add> klass = Class.new { extend mod }
<add> @deprecator.deprecate_methods(mod, :old_method)
<ide>
<del> warning = /old_method is deprecated and will be removed from Rails \d.\d \(use new_method instead\)/
<del> assert_deprecated(warning) { assert_equal "abc", @klass.old_method }
<add> assert_deprecated("old_method", @deprecator) do
<add> assert_equal "abc", klass.old_method
<add> end
<ide> end
<ide> end
<ide><path>activesupport/test/deprecation/proxy_wrappers_test.rb
<ide> def waffle?
<ide> end
<ide> end
<ide>
<add> def setup
<add> @deprecator = ActiveSupport::Deprecation.new
<add> end
<add>
<ide> def test_deprecated_object_proxy_doesnt_wrap_falsy_objects
<ide> proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(nil, "message")
<ide> assert_not proxy
<ide> def test_deprecated_constant_proxy_doesnt_wrap_falsy_objects
<ide> end
<ide>
<ide> def test_including_proxy_module
<del> proxy = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("OldWaffleModule", WaffleModule.name)
<add> proxy = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("OldWaffleModule", WaffleModule.name, @deprecator)
<ide> klass = Class.new
<del> assert_deprecated do
<add> assert_deprecated("OldWaffleModule", @deprecator) do
<ide> klass.include proxy
<ide> end
<ide> assert klass.new.waffle?
<ide> end
<ide>
<ide> def test_prepending_proxy_module
<del> proxy = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("OldWaffleModule", WaffleModule.name)
<add> proxy = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("OldWaffleModule", WaffleModule.name, @deprecator)
<ide> klass = Class.new do
<ide> def waffle?
<ide> false
<ide> end
<ide> end
<del> assert_deprecated do
<add> assert_deprecated("OldWaffleModule", @deprecator) do
<ide> klass.prepend proxy
<ide> end
<ide> assert klass.new.waffle?
<ide> end
<ide>
<ide> def test_extending_proxy_module
<del> proxy = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("OldWaffleModule", WaffleModule.name)
<add> proxy = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("OldWaffleModule", WaffleModule.name, @deprecator)
<ide> obj = Object.new
<del> assert_deprecated do
<add> assert_deprecated("OldWaffleModule", @deprecator) do
<ide> obj.extend proxy
<ide> end
<ide> assert obj.waffle? | 2 |
PHP | PHP | apply fixes from styleci | 4e84bdcdffcdb05f5b008456a8c77d5d64233c60 | <ide><path>src/Illuminate/Auth/MustVerifyEmail.php
<ide> public function hasVerifiedEmail()
<ide> public function markEmailAsVerified()
<ide> {
<ide> return $this->forceFill([
<del> 'email_verified_at' => $this->freshTimestamp()
<add> 'email_verified_at' => $this->freshTimestamp(),
<ide> ])->save();
<ide> }
<ide> | 1 |
Javascript | Javascript | add scrolltop/left tests and fix for ie | cafd392af0a2736a33cf1528198c66a233285b3d | <ide><path>src/offset.js
<del>if ( "getBoundingClientRect" in document.documentElement ) {
<add>if ( "getBoundingClientRect" in document.documentElement )
<ide> jQuery.fn.offset = function() {
<ide> var elem = this[0];
<del> if ( !elem || !elem.ownerDocument ) { return null; }
<del> if ( elem === elem.ownerDocument.body ) {
<del> return jQuery.offset.bodyOffset( elem );
<del> }
<del>
<add> if ( !elem || !elem.ownerDocument ) return null;
<add> if ( elem === elem.ownerDocument.body ) return jQuery.offset.bodyOffset( elem );
<ide> var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement,
<ide> clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
<ide> top = box.top + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop,
<ide> left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
<ide> return { top: top, left: left };
<ide> };
<del>} else {
<add>else
<ide> jQuery.fn.offset = function() {
<ide> var elem = this[0];
<del> if ( !elem || !elem.ownerDocument ) { return null; }
<del> if ( elem === elem.ownerDocument.body ) {
<del> return jQuery.offset.bodyOffset( elem );
<del> }
<del>
<add> if ( !elem || !elem.ownerDocument ) return null;
<add> if ( elem === elem.ownerDocument.body ) return jQuery.offset.bodyOffset( elem );
<ide> jQuery.offset.initialize();
<ide>
<ide> var offsetParent = elem.offsetParent, prevOffsetParent = elem,
<ide> if ( "getBoundingClientRect" in document.documentElement ) {
<ide> top = elem.offsetTop, left = elem.offsetLeft;
<ide>
<ide> while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
<del> if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; }
<del>
<add> if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) break;
<ide> computedStyle = defaultView.getComputedStyle(elem, null);
<del> top -= elem.scrollTop;
<del> left -= elem.scrollLeft;
<del>
<add> top -= elem.scrollTop, left -= elem.scrollLeft;
<ide> if ( elem === offsetParent ) {
<del> top += elem.offsetTop;
<del> left += elem.offsetLeft;
<del>
<del> if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.nodeName)) ) {
<del> top += parseFloat( computedStyle.borderTopWidth ) || 0;
<add> top += elem.offsetTop, left += elem.offsetLeft;
<add> if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) )
<add> top += parseFloat( computedStyle.borderTopWidth ) || 0,
<ide> left += parseFloat( computedStyle.borderLeftWidth ) || 0;
<del> }
<del>
<ide> prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
<ide> }
<del>
<del> if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
<del> top += parseFloat( computedStyle.borderTopWidth ) || 0;
<add> if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" )
<add> top += parseFloat( computedStyle.borderTopWidth ) || 0,
<ide> left += parseFloat( computedStyle.borderLeftWidth ) || 0;
<del> }
<del>
<ide> prevComputedStyle = computedStyle;
<ide> }
<ide>
<del> if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
<del> top += body.offsetTop;
<add> if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" )
<add> top += body.offsetTop,
<ide> left += body.offsetLeft;
<del> }
<ide>
<del> if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
<del> top += Math.max( docElem.scrollTop, body.scrollTop );
<add> if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" )
<add> top += Math.max( docElem.scrollTop, body.scrollTop ),
<ide> left += Math.max( docElem.scrollLeft, body.scrollLeft );
<del> }
<ide>
<ide> return { top: top, left: left };
<ide> };
<del>}
<ide>
<ide> jQuery.offset = {
<ide> initialize: function() {
<ide> jQuery.offset = {
<ide>
<ide> container.innerHTML = html;
<ide> body.insertBefore( container, body.firstChild );
<del> innerDiv = container.firstChild;
<del> checkDiv = innerDiv.firstChild;
<del> td = innerDiv.nextSibling.firstChild.firstChild;
<add> innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;
<ide>
<ide> this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
<ide> this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
<ide>
<ide> checkDiv.style.position = 'fixed', checkDiv.style.top = '20px';
<del> // safari subtracts parent border width here which is 5px
<del> this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
<del> checkDiv.style.position = checkDiv.style.top = '';
<add> this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); // safari subtracts parent border width here which is 5px
<add> checkDiv.style.position = '', checkDiv.style.top = '';
<ide>
<ide> innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
<ide> this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
<ide> jQuery.offset = {
<ide> },
<ide>
<ide> bodyOffset: function(body) {
<del> var top = body.offsetTop, left = body.offsetLeft;
<del>
<ide> jQuery.offset.initialize();
<del>
<del> if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
<del> top += parseFloat( jQuery.curCSS(body, 'marginTop', true) ) || 0;
<add> var top = body.offsetTop, left = body.offsetLeft;
<add> if ( jQuery.offset.doesNotIncludeMarginInBodyOffset )
<add> top += parseFloat( jQuery.curCSS(body, 'marginTop', true) ) || 0,
<ide> left += parseFloat( jQuery.curCSS(body, 'marginLeft', true) ) || 0;
<del> }
<del>
<ide> return { top: top, left: left };
<ide> }
<ide> };
<ide>
<ide>
<ide> jQuery.fn.extend({
<ide> position: function() {
<del> if ( !this[0] ) { return null; }
<add> if ( !this[0] ) return null;
<ide>
<ide> var elem = this[0],
<ide>
<ide> jQuery.fn.extend({
<ide>
<ide> // Get correct offsets
<ide> offset = this.offset(),
<del> parentOffset = /^body|html$/i.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
<add> parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
<ide>
<ide> // Subtract element margins
<ide> // note: when an element has margin: auto the offsetLeft and marginLeft
<ide> jQuery.fn.extend({
<ide> },
<ide>
<ide> offsetParent: function() {
<del> return this.map(function(){
<del> var offsetParent = this.offsetParent || document.body;
<del> while ( offsetParent && (!/^body|html$/i.test(offsetParent.nodeName) && jQuery.css(offsetParent, 'position') === 'static') ) {
<del> offsetParent = offsetParent.offsetParent;
<del> }
<del> return offsetParent;
<del> });
<add> var offsetParent = this[0].offsetParent || document.body;
<add> while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') === 'static') )
<add> offsetParent = offsetParent.offsetParent;
<add> return jQuery( offsetParent );
<ide> }
<ide> });
<ide>
<ide> jQuery.each( ['Left', 'Top'], function(i, name) {
<ide> var method = 'scroll' + name;
<ide>
<ide> jQuery.fn[ method ] = function(val) {
<del> if ( !this[0] ) { return null; }
<add> var elem = this[0], win;
<add>
<add> if ( !elem ) return null;
<ide>
<ide> if ( val !== undefined ) {
<ide> // Set the scroll offset
<ide> return this.each(function() {
<ide> win = getWindow( this );
<ide>
<del> if ( win ) {
<add> win ?
<ide> win.scrollTo(
<ide> !i ? val : jQuery(win).scrollLeft(),
<ide> i ? val : jQuery(win).scrollTop()
<del> );
<del> } else {
<add> ) :
<ide> this[ method ] = val;
<del> }
<ide> });
<ide> } else {
<del> var elem = this[0],
<del> win = getWindow( elem );
<add> win = getWindow( elem );
<ide>
<ide> // Return the scroll offset
<del> return win && 'pageXOffset' in win ?
<del> win[ i ? 'pageYOffset' : 'pageXOffset' ] ||
<del> jQuery.support.boxModel && win.document.documentElement[ method ] ||
<add> return win ? ('pageXOffset' in win) ? win[ i ? 'pageYOffset' : 'pageXOffset' ] :
<add> jQuery.support.boxModel && win.document.documentElement[ method ] ||
<ide> win.document.body[ method ] :
<ide> elem[ method ];
<ide> }
<ide> };
<del>
<del> function getWindow( elem ) {
<del> return ("scrollTo" in elem && elem.document) ?
<del> elem :
<del> elem.nodeType === 9 ?
<del> elem.defaultView || elem.parentWindow :
<del> false;
<del> }
<ide> });
<add>
<add>function getWindow( elem ) {
<add> return ("scrollTo" in elem && elem.document) ? elem :
<add> (elem.nodeName === "#document") ? elem.defaultView || elem.parentWindow :
<add> false;
<add>}
<ide><path>test/unit/offset.js
<ide> testoffset("table", function( jQuery ) {
<ide> // equals( jQuery('#td-3').offset().left, 222, "jQuery('#td-3').offset().left" );
<ide> });
<ide>
<del>testoffset("scroll", function( jQuery ) {
<add>testoffset("scroll", function( jQuery, win ) {
<ide> var ie = jQuery.browser.msie && parseInt( jQuery.browser.version ) < 8;
<ide>
<ide> // IE is collapsing the top margin of 1px
<ide> testoffset("scroll", function( jQuery ) {
<ide> // IE is collapsing the top margin of 1px
<ide> equals( jQuery('#scroll-1-1').offset().top, ie ? 9 : 11, "jQuery('#scroll-1-1').offset().top" );
<ide> equals( jQuery('#scroll-1-1').offset().left, 11, "jQuery('#scroll-1-1').offset().left" );
<add>
<add>
<add> // scroll offset tests .scrollTop/Left
<add> equals( jQuery('#scroll-1').scrollTop(), 5, "jQuery('#scroll-1').scrollTop()" );
<add> equals( jQuery('#scroll-1').scrollLeft(), 5, "jQuery('#scroll-1').scrollLeft()" );
<add>
<add> equals( jQuery('#scroll-1-1').scrollTop(), 0, "jQuery('#scroll-1-1').scrollTop()" );
<add> equals( jQuery('#scroll-1-1').scrollLeft(), 0, "jQuery('#scroll-1-1').scrollLeft()" );
<add>
<add> // equals( jQuery('body').scrollTop(), 0, "jQuery('body').scrollTop()" );
<add> // equals( jQuery('body').scrollLeft(), 0, "jQuery('body').scrollTop()" );
<add>
<add> win.name = "test";
<add>
<add> equals( jQuery(win).scrollTop(), 1000, "jQuery(window).scrollTop()" );
<add> equals( jQuery(win).scrollLeft(), 1000, "jQuery(window).scrollLeft()" );
<add>
<add> equals( jQuery(win.document).scrollTop(), 1000, "jQuery(document).scrollTop()" );
<add> equals( jQuery(win.document).scrollLeft(), 1000, "jQuery(document).scrollLeft()" );
<ide> });
<ide>
<ide> testoffset("body", function( jQuery ) {
<ide> function testoffset(name, fn) {
<ide> // continue
<ide> start();
<ide> // call actual tests passing the correct jQuery isntance to use
<del> fn.call( this, win.jQuery );
<add> fn.call( this, win.jQuery, win );
<ide> document.body.removeChild( iframe );
<ide> iframe = null;
<ide> } | 2 |
Java | Java | remove subscribe(map<string, object>) | f8bacd49420b0a5ed3a246b4a36ee3b643478823 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> import rx.util.OnErrorNotImplementedException;
<ide> import rx.util.Range;
<ide> import rx.util.Timestamped;
<add>import rx.util.functions.Action;
<ide> import rx.util.functions.Action0;
<ide> import rx.util.functions.Action1;
<ide> import rx.util.functions.Func0;
<ide> private Subscription protectivelyWrapAndSubscribe(Observer<T> o) {
<ide> return subscription.wrap(subscribe(new SafeObserver<T>(subscription, o)));
<ide> }
<ide>
<del> @SuppressWarnings({ "rawtypes", "unchecked" })
<del> public Subscription subscribe(final Map<String, Object> callbacks) {
<del> if (callbacks == null) {
<del> throw new RuntimeException("callbacks map can not be null");
<del> }
<del> Object _onNext = callbacks.get("onNext");
<del> if (_onNext == null) {
<del> throw new RuntimeException("'onNext' key must contain an implementation");
<del> }
<del> // lookup and memoize onNext
<del> final FuncN onNext = Functions.from(_onNext);
<del>
<del> /**
<del> * Wrapping since raw functions provided by the user are being invoked.
<del> *
<del> * See https://github.com/Netflix/RxJava/issues/216 for discussion on "Guideline 6.4: Protect calls to user code from within an operator"
<del> */
<del> return protectivelyWrapAndSubscribe(new Observer() {
<del>
<del> @Override
<del> public void onCompleted() {
<del> Object onComplete = callbacks.get("onCompleted");
<del> if (onComplete != null) {
<del> Functions.from(onComplete).call();
<del> }
<del> }
<del>
<del> @Override
<del> public void onError(Throwable e) {
<del> handleError(e);
<del> Object onError = callbacks.get("onError");
<del> if (onError != null) {
<del> Functions.from(onError).call(e);
<del> } else {
<del> throw new OnErrorNotImplementedException(e);
<del> }
<del> }
<del>
<del> @Override
<del> public void onNext(Object args) {
<del> onNext.call(args);
<del> }
<del>
<del> });
<del> }
<del>
<del> public Subscription subscribe(final Map<String, Object> callbacks, Scheduler scheduler) {
<del> return subscribeOn(scheduler).subscribe(callbacks);
<del> }
<del>
<ide> public Subscription subscribe(final Action1<T> onNext) {
<ide> if (onNext == null) {
<ide> throw new IllegalArgumentException("onNext can not be null");
<ide> public static <R, T0, T1, T2, T3> Observable<R> zip(Observable<T0> w0, Observabl
<ide> * each time an event is received from one of the source observables, where the aggregation is defined by the given function.
<ide> * <p>
<ide> * <img width="640" src="https://github.com/Netflix/RxJava/wiki/images/rx-operators/combineLatest.png">
<del> *
<add> *
<ide> * @param w0
<del> * The first source observable.
<add> * The first source observable.
<ide> * @param w1
<del> * The second source observable.
<add> * The second source observable.
<ide> * @param combineFunction
<del> * The aggregation function used to combine the source observable values.
<add> * The aggregation function used to combine the source observable values.
<ide> * @return An Observable that combines the source Observables with the given combine function
<ide> */
<ide> public static <R, T0, T1> Observable<R> combineLatest(Observable<T0> w0, Observable<T1> w1, Func2<T0, T1, R> combineFunction) {
<ide> public static <R, T0, T1, T2> Observable<R> combineLatest(Observable<T0> w0, Obs
<ide> public static <R, T0, T1, T2, T3> Observable<R> combineLatest(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Observable<T3> w3, Func4<T0, T1, T2, T3, R> combineFunction) {
<ide> return create(OperationCombineLatest.combineLatest(w0, w1, w2, w3, combineFunction));
<ide> }
<del>
<add>
<ide> /**
<ide> * Creates an Observable which produces buffers of collected values.
<ide> * | 1 |
Text | Text | fix typos and clarify statement | ca7742f6982974277d7b371bad29d8b440fb4845 | <ide><path>guide/english/d3/index.md
<ide> title: D3
<ide>
<ide> ## Why D3.js?
<ide>
<del>*D3** does not introduce a new visual representation. Unlike **Processing**, **Raphaël**, or **Protovis**, *D3's* vocabulary of graphical marks comes directly from web standards: HTML, SVG, and CSS - https://d3js.org/
<add>For those already familiar with HTML and CSS, *D3* is quick to learn. Unlike **Processing**, **Raphaël**, or **Protovis**, *D3's* vocabulary of graphical marks comes directly from web standards: HTML, SVG, and CSS - https://d3js.org/
<ide>
<ide> ## Get Started
<del>There are over [20,000+ **D3.js** examples](https://github.com/d3/d3/wiki/Gallery) you could learn from, but you never know how approachable any given one will be! So, the question is - how do you build up your visualization from first principles? As you've probably seen, D3's API is massive, so lets call out a few of the utilities that will be particularly helpful early on:
<add>There are over [20,000 **D3.js** examples](https://github.com/d3/d3/wiki/Gallery) you could learn from, but you never know how approachable any given one will be! So, the question is - how do you build up your visualization from first principles? As you've probably seen, D3's API is massive, so lets call out a few of the utilities that will be particularly helpful early on:
<ide>
<ide> - **[d3-scale](https://github.com/d3/d3-scale)**
<ide>
<ide> There are over [20,000+ **D3.js** examples](https://github.com/d3/d3/wiki/Galler
<ide>
<ide> 
<ide>
<del> With just some basic knowledge of the latest HTML5 features such as SVG and Canvas, you can dive into a world where a library like **D3.js** can bring data to life!
<add>With just some basic knowledge of the latest HTML5 features such as SVG and Canvas, you can dive into a world where a library like **D3.js** can bring data to life!
<ide>
<ide> ### Contribution
<del>
<ide> - https://github.com/d3/
<ide>
<del> ### Resources
<add>### Resources
<ide> - [Wikipedia](https://en.wikipedia.org/wiki/D3.js)
<ide> - [Blockbuilder](http://blockbuilder.org/search)
<ide> - [D3 in Depth](https://d3indepth.com) | 1 |
Ruby | Ruby | accept a pathname in application#config_for | fc635b565393bd6b70be4af524934b3ea359e83c | <ide><path>railties/lib/rails/application.rb
<ide> def message_verifier(verifier_name)
<ide> # config.middleware.use ExceptionNotifier, config_for(:exception_notification)
<ide> # end
<ide> def config_for(name, env: Rails.env)
<del> yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml")
<add> if name.is_a?(Pathname)
<add> yaml = name
<add> else
<add> yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml")
<add> end
<ide>
<ide> if yaml.exist?
<ide> require "erb"
<ide><path>railties/test/application/configuration_test.rb
<ide> def index
<ide> assert_equal 'custom key', Rails.application.config.my_custom_config['key']
<ide> end
<ide>
<add> test "config_for use the Pathname object if it is provided" do
<add> app_file 'config/custom.yml', <<-RUBY
<add> development:
<add> key: 'custom key'
<add> RUBY
<add>
<add> add_to_config <<-RUBY
<add> config.my_custom_config = config_for(Pathname.new(Rails.root.join("config/custom.yml")))
<add> RUBY
<add>
<add> app 'development'
<add>
<add> assert_equal 'custom key', Rails.application.config.my_custom_config['key']
<add> end
<add>
<ide> test "config_for raises an exception if the file does not exist" do
<ide> add_to_config <<-RUBY
<ide> config.my_custom_config = config_for('custom') | 2 |
Text | Text | add v3.4.0-beta.3 to changelog | d593d86db88c595f3864ee08ad36578ddfe318f1 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.4.0-beta.3 (August 21, 2018)
<add>
<add>- [#16870](https://github.com/emberjs/ember.js/pull/16870) [BUGFIX] Enable @ember/object#get to be called with an empty string
<add>- [#16603](https://github.com/emberjs/ember.js/pull/16603) [BUGFIX] Support mouseEnter/Leave events w/o jQuery
<add>
<ide> ### v3.4.0-beta.2 (August 06, 2018)
<ide>
<ide> - [#16857](https://github.com/emberjs/ember.js/pull/16857) [BUGFIX] Prevents the recursive redefinition of root chains | 1 |
Javascript | Javascript | remove execute challenge epic | 8d2c350b3ff030c9c9d4326d1fc3606df12098c7 | <ide><path>client/src/templates/Challenges/redux/execute-challenge-epic.js
<del>import { Subject, merge, of, from } from 'rxjs';
<del>
<del>import {
<del> debounceTime,
<del> switchMap,
<del> map,
<del> filter,
<del> pluck,
<del> concat,
<del> tap,
<del> catchError,
<del> ignoreElements,
<del> startWith,
<del> delay
<del>} from 'rxjs/operators';
<del>import { ofType } from 'redux-observable';
<del>import { overEvery, isString } from 'lodash';
<del>
<del>import {
<del> types,
<del> challengeMetaSelector,
<del> challengeTestsSelector,
<del> initConsole,
<del> updateConsole,
<del> initLogs,
<del> updateLogs,
<del> logsToConsole,
<del> checkChallenge,
<del> updateTests,
<del> disableJSOnError,
<del> isJSEnabledSelector
<del>} from './';
<del>import { buildFromFiles, buildBackendChallenge } from '../utils/build';
<del>import { runTestsInTestFrame, createTestFramer } from '../utils/frame.js';
<del>
<del>import { challengeTypes } from '../../../../utils/challengeTypes';
<del>
<del>const executeDebounceTimeout = 750;
<del>
<del>function executeChallengeEpic(action$, state$, { document }) {
<del> return of(document).pipe(
<del> filter(Boolean),
<del> switchMap(() => {
<del> const frameReady = new Subject();
<del> const consoleProxy = new Subject();
<del> const frameTests = createTestFramer(
<del> document,
<del> state$,
<del> frameReady,
<del> consoleProxy
<del> );
<del> const challengeResults = frameReady.pipe(
<del> // Delay for jQuery ready code, in jQuery challenges
<del> delay(250),
<del> pluck('checkChallengePayload'),
<del> map(checkChallengePayload => ({
<del> checkChallengePayload,
<del> tests: challengeTestsSelector(state$.value)
<del> })),
<del> switchMap(({ checkChallengePayload, tests }) => {
<del> const postTests = of(
<del> updateConsole('// tests completed'),
<del> logsToConsole('// console output'),
<del> checkChallenge(checkChallengePayload)
<del> ).pipe(delay(250));
<del> return runTestsInTestFrame(document, tests).pipe(
<del> switchMap(tests => {
<del> return from(tests).pipe(
<del> map(({ message }) => message),
<del> filter(overEvery(isString, Boolean)),
<del> map(updateConsole),
<del> concat(of(updateTests(tests)))
<del> );
<del> }),
<del> concat(postTests)
<del> );
<del> })
<del> );
<del> const buildAndFrameChallenge = action$.pipe(
<del> ofType(types.executeChallenge),
<del> filter(() => false),
<del> debounceTime(executeDebounceTimeout),
<del> filter(() => isJSEnabledSelector(state$.value)),
<del> switchMap(() => {
<del> const state = state$.value;
<del> const { challengeType } = challengeMetaSelector(state);
<del> const build =
<del> challengeType === challengeTypes.backend
<del> ? buildBackendChallenge
<del> : buildFromFiles;
<del> return build(state).pipe(
<del> tap(frameTests),
<del> ignoreElements(),
<del> startWith(initLogs()),
<del> startWith(initConsole('// running tests')),
<del> catchError(err => {
<del> console.error(err);
<del> return of(disableJSOnError(err));
<del> })
<del> );
<del> })
<del> );
<del> const proxyConsole = consoleProxy.pipe(map(updateLogs));
<del> return merge(buildAndFrameChallenge, challengeResults, proxyConsole);
<del> })
<del> );
<del>}
<del>
<del>export default executeChallengeEpic;
<ide><path>client/src/templates/Challenges/redux/index.js
<ide> import { createAsyncTypes } from '../../../utils/createTypes';
<ide> import { createPoly } from '../utils/polyvinyl';
<ide> import challengeModalEpic from './challenge-modal-epic';
<ide> import completionEpic from './completion-epic';
<del>import executeChallengeEpic from './execute-challenge-epic';
<ide> import codeLockEpic from './code-lock-epic';
<ide> import createQuestionEpic from './create-question-epic';
<ide> import codeStorageEpic from './code-storage-epic';
<ide> export const epics = [
<ide> codeLockEpic,
<ide> completionEpic,
<ide> createQuestionEpic,
<del> executeChallengeEpic,
<ide> codeStorageEpic,
<ide> currentChallengeEpic
<ide> ]; | 2 |
Ruby | Ruby | handle update/delete with offset in arel | 6d40d2d3d1f3766551e74607a718a5ec97963bbf | <ide><path>activerecord/lib/active_record/relation.rb
<ide> def update_all(updates)
<ide> stmt.set Arel.sql(klass.sanitize_sql_for_assignment(updates, table.name))
<ide> end
<ide>
<del> if has_join_values? || offset_value
<add> if has_join_values?
<ide> @klass.connection.join_to_update(stmt, arel, arel_attribute(primary_key))
<ide> else
<ide> stmt.key = arel_attribute(primary_key)
<ide> stmt.take(arel.limit)
<add> stmt.offset(arel.offset)
<ide> stmt.order(*arel.orders)
<ide> stmt.wheres = arel.constraints
<ide> end
<ide> def delete_all
<ide> stmt = Arel::DeleteManager.new
<ide> stmt.from(table)
<ide>
<del> if has_join_values? || offset_value
<add> if has_join_values?
<ide> @klass.connection.join_to_delete(stmt, arel, arel_attribute(primary_key))
<ide> else
<ide> stmt.key = arel_attribute(primary_key)
<ide> stmt.take(arel.limit)
<add> stmt.offset(arel.offset)
<ide> stmt.order(*arel.orders)
<ide> stmt.wheres = arel.constraints
<ide> end
<ide><path>activerecord/lib/arel/nodes/delete_statement.rb
<ide> module Arel # :nodoc: all
<ide> module Nodes
<ide> class DeleteStatement < Arel::Nodes::Node
<del> attr_accessor :left, :right, :orders, :limit, :key
<add> attr_accessor :left, :right, :orders, :limit, :offset, :key
<ide>
<ide> alias :relation :left
<ide> alias :relation= :left=
<ide> def initialize(relation = nil, wheres = [])
<ide> @right = wheres
<ide> @orders = []
<ide> @limit = nil
<add> @offset = nil
<ide> @key = nil
<ide> end
<ide>
<ide> def initialize_copy(other)
<ide> end
<ide>
<ide> def hash
<del> [self.class, @left, @right, @orders, @limit, @key].hash
<add> [self.class, @left, @right, @orders, @limit, @offset, @key].hash
<ide> end
<ide>
<ide> def eql?(other)
<ide> def eql?(other)
<ide> self.right == other.right &&
<ide> self.orders == other.orders &&
<ide> self.limit == other.limit &&
<add> self.offset == other.offset &&
<ide> self.key == other.key
<ide> end
<ide> alias :== :eql?
<ide><path>activerecord/lib/arel/nodes/update_statement.rb
<ide> module Arel # :nodoc: all
<ide> module Nodes
<ide> class UpdateStatement < Arel::Nodes::Node
<del> attr_accessor :relation, :wheres, :values, :orders, :limit, :key
<add> attr_accessor :relation, :wheres, :values, :orders, :limit, :offset, :key
<ide>
<ide> def initialize
<ide> @relation = nil
<ide> @wheres = []
<ide> @values = []
<ide> @orders = []
<ide> @limit = nil
<add> @offset = nil
<ide> @key = nil
<ide> end
<ide>
<ide> def initialize_copy(other)
<ide> end
<ide>
<ide> def hash
<del> [@relation, @wheres, @values, @orders, @limit, @key].hash
<add> [@relation, @wheres, @values, @orders, @limit, @offset, @key].hash
<ide> end
<ide>
<ide> def eql?(other)
<ide> def eql?(other)
<ide> self.values == other.values &&
<ide> self.orders == other.orders &&
<ide> self.limit == other.limit &&
<add> self.offset == other.offset &&
<ide> self.key == other.key
<ide> end
<ide> alias :== :eql?
<ide><path>activerecord/lib/arel/tree_manager.rb
<ide> def take(limit)
<ide> self
<ide> end
<ide>
<add> def offset(offset)
<add> @ast.offset = Nodes::Offset.new(Nodes.build_quoted(offset)) if offset
<add> self
<add> end
<add>
<ide> def order(*expr)
<ide> @ast.orders = expr
<ide> self
<ide><path>activerecord/lib/arel/visitors/mysql.rb
<ide> def visit_Arel_Nodes_SelectCore(o, collector)
<ide> super
<ide> end
<ide>
<del> def visit_Arel_Nodes_UpdateStatement(o, collector)
<del> collector << "UPDATE "
<del> collector = visit o.relation, collector
<del>
<del> unless o.values.empty?
<del> collector << " SET "
<del> collector = inject_join o.values, collector, ", "
<del> end
<del>
<del> collect_where_for(o, collector)
<del> end
<del>
<ide> def visit_Arel_Nodes_Concat(o, collector)
<ide> collector << " CONCAT("
<ide> visit o.left, collector
<ide> def visit_Arel_Nodes_Concat(o, collector)
<ide> collector
<ide> end
<ide>
<add> def build_subselect(key, o)
<add> subselect = super
<add>
<add> # Materialize subquery by adding distinct
<add> # to work with MySQL 5.7.6 which sets optimizer_switch='derived_merge=on'
<add> subselect.distinct unless subselect.limit || subselect.offset || subselect.orders.any?
<add>
<add> Nodes::SelectStatement.new.tap do |stmt|
<add> core = stmt.cores.last
<add> core.froms = Nodes::Grouping.new(subselect).as("__active_record_temp")
<add> core.projections = [Arel.sql(quote_column_name(key.name))]
<add> end
<add> end
<add>
<ide> def collect_where_for(o, collector)
<add> return super if o.offset
<add>
<ide> unless o.wheres.empty?
<ide> collector << " WHERE "
<ide> collector = inject_join o.wheres, collector, " AND "
<ide><path>activerecord/lib/arel/visitors/to_sql.rb
<ide> def build_subselect(key, o)
<ide> core.wheres = o.wheres
<ide> core.projections = [key]
<ide> stmt.limit = o.limit
<add> stmt.offset = o.offset
<ide> stmt.orders = o.orders
<ide> stmt
<ide> end
<ide> def inject_join(list, collector, join_str)
<ide> end
<ide>
<ide> def collect_where_for(o, collector)
<del> if o.orders.empty? && o.limit.nil?
<add> if o.orders.empty? && o.limit.nil? && o.offset.nil?
<ide> wheres = o.wheres
<ide> else
<ide> wheres = [Nodes::In.new(o.key, [build_subselect(o.key, o)])] | 6 |
Javascript | Javascript | compute node position relative to parent | 603d86ac1a135bb73a07bd74a0cedfd5942a32be | <ide><path>d3.js
<del>(function(){d3 = {version: "1.14.0"}; // semver
<add>(function(){d3 = {version: "1.14.1"}; // semver
<ide> if (!Date.now) Date.now = function() {
<ide> return +new Date();
<ide> };
<ide><path>d3.layout.js
<ide> d3.layout.force = function() {
<ide>
<ide> function dragmove() {
<ide> if (!d3_layout_forceDragNode) return;
<add> var parent = d3_layout_forceDragElement.parentNode;
<ide>
<ide> // O NOES! The drag element was removed from the DOM.
<del> if (!d3_layout_forceDragElement.parentNode) {
<add> if (!parent) {
<ide> d3_layout_forceDragNode.fixed = false;
<ide> d3_layout_forceDragNode = d3_layout_forceDragElement = null;
<ide> return;
<ide> }
<ide>
<del> var m = d3.svg.mouse(d3_layout_forceDragElement);
<add> var m = d3.svg.mouse(parent);
<ide> d3_layout_forceDragMoved = true;
<ide> d3_layout_forceDragNode.px = m[0];
<ide> d3_layout_forceDragNode.py = m[1];
<ide><path>d3.layout.min.js
<del>(function(){function S(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function R(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function Q(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function P(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function O(a,b){return a.depth-b.depth}function N(a,b){return b.x-a.x}function M(a,b){return a.x-b.x}function L(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=L(c[f],b),a)>0&&(a=d)}return a}function K(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function J(a){return a.children?a.children[0]:a._tree.thread}function I(a,b){return a.parent==b.parent?1:2}function H(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function G(a){var b=a.children;return b?G(b[b.length-1]):a}function F(a){var b=a.children;return b?F(b[0]):a}function E(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function D(a){return 1+d3.max(a,function(a){return a.y})}function C(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function B(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)B(e[f],b,c,d)}}function A(a){var b=a.children;b?(b.forEach(A),a.r=x(b)):a.r=Math.sqrt(a.value)}function z(a){delete a._pack_next,delete a._pack_prev}function y(a){a._pack_next=a._pack_prev=a}function x(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(y),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],C(g,h,i),l(i),u(g,i),g._pack_prev=i,u(i,h),h=g._pack_next;for(var m=3;m<f;m++){C(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!=h;j=j._pack_next,o++)if(w(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!=j._pack_prev;k=k._pack_prev,p++)if(w(k,i)){p<o&&(n=-1,j=k);break}n==0?(u(g,i),h=i,l(i)):n>0?(v(g,j),h=j,m--):(v(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(z);return s}function w(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function v(a,b){a._pack_next=b,b._pack_prev=a}function u(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function t(a,b){return a.value-b.value}function s(a,b){return b.value-a.value}function r(a){return a.value}function q(a){return a.children}function p(a,b){return a+b.y}function o(a){var b=1,c=0,d=a[0].y,e,f=a.length;for(;b<f;++b)(e=a[b].y)>d&&(c=b,d=e);return c}function n(a){return a.reduce(p,0)}function k(a){var b=0,c=0;a.count=0,a.leaf||a.nodes.forEach(function(d){k(d),a.count+=d.count,b+=d.count*d.cx,c+=d.count*d.cy}),a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){d3.event.stopPropagation(),d3.event.preventDefault()}function i(){c&&(j(),c=!1)}function h(c,d){(a=c).fixed=!0,b=!1,e=this,j()}function g(b){b!==a&&(b.fixed=!1)}function f(a){a.fixed=!0}d3.layout={},d3.layout.chord=function(){function k(){b.sort(function(a,b){a=Math.min(a.source.value,a.target.value),b=Math.min(b.source.value,b.target.value);return i(a,b)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push({source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function A(){!a||(b&&(c=!0,j()),z(),a.fixed=!1,a=e=null)}function z(){if(!!a){if(!e.parentNode){a.fixed=!1,a=e=null;return}var c=d3.svg.mouse(e);b=!0,a.px=c[0],a.py=c[1],d.resume()}}function y(){var a=u.length,b=v.length,c=d3.geom.quadtree(u),d,e,f,g,h,i,j;for(d=0;d<b;++d){e=v[d],f=e.source,g=e.target,i=g.x-f.x,j=g.y-f.y;if(h=i*i+j*j)h=n*((h=Math.sqrt(h))-p)/h,i*=h,j*=h,g.x-=i,g.y-=j,f.x+=i,f.y+=j}var s=n*r;i=m[0]/2,j=m[1]/2,d=-1;while(++d<a)e=u[d],e.x+=(i-e.x)*s,e.y+=(j-e.y)*s;k(c);var t=n*q;d=-1;while(++d<a)c.visit(x(u[d],t));d=-1;while(++d<a)e=u[d],e.fixed?(e.x=e.px,e.y=e.py):(e.x-=(e.px-(e.px=e.x))*o,e.y-=(e.py-(e.py=e.y))*o);l.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function x(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<s){var k=b*c.count*j*j;a.x+=h*k,a.y+=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.x+=h*k,a.y+=i*k}}}}var d={},l=d3.dispatch("tick"),m=[1,1],n,o=.9,p=20,q=-30,r=.1,s=.8,t,u,v,w;d.on=function(a,b){l[a].add(b);return d},d.nodes=function(a){if(!arguments.length)return u;u=a;return d},d.links=function(a){if(!arguments.length)return v;v=a;return d},d.size=function(a){if(!arguments.length)return m;m=a;return d},d.distance=function(a){if(!arguments.length)return p;p=a;return d},d.drag=function(a){if(!arguments.length)return o;o=a;return d},d.charge=function(a){if(!arguments.length)return q;q=a;return d},d.gravity=function(a){if(!arguments.length)return r;r=a;return d},d.theta=function(a){if(!arguments.length)return s;s=a;return d},d.start=function(){function k(){if(!h){h=[];for(b=0;b<c;++b)h[b]=[];for(b=0;b<e;++b){var d=v[b];h[d.source.index].push(d.target),h[d.target.index].push(d.source)}}return h[a]}function j(b,c){var d=k(a),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][b]))return g;return Math.random()*c}var a,b,c=u.length,e=v.length,f=m[0],g=m[1],h,i;for(a=0;a<c;++a)(i=u[a]).index=a;for(a=0;a<e;++a)i=v[a],typeof i.source=="number"&&(i.source=u[i.source]),typeof i.target=="number"&&(i.target=u[i.target]);for(a=0;a<c;++a)i=u[a],isNaN(i.x)&&(i.x=j("x",f)),isNaN(i.y)&&(i.y=j("y",g)),isNaN(i.px)&&(i.px=i.x),isNaN(i.py)&&(i.py=i.y);return d.resume()},d.resume=function(){n=.1,d3.timer(y);return d},d.stop=function(){n=0;return d},d.drag=function(){this.on("mouseover.force",f).on("mouseout.force",g).on("mousedown.force",h),d3.select(window).on("mousemove.force",z).on("mouseup.force",A,!0).on("click.force",i,!0);return d};return d};var a,b,c,e;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d/=a.value;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.sort=d3.rebind(e,a.sort),e.children=d3.rebind(e,a.children),e.value=d3.rebind(e,a.value),e.size=function(a){if(!arguments.length)return b;b=a;return e};return e},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function c(c){var d=c.length,e=c[0].length,f,g,h,i=l[a](c);m[b](c,i);for(g=0;g<e;++g)for(f=1,h=c[i[0]][g].y0;f<d;++f)c[i[f]][g].y0=h+=c[i[f-1]][g].y;return c}var a="default",b="zero";c.order=function(b){if(!arguments.length)return a;a=b;return c},c.offset=function(a){if(!arguments.length)return b;b=a;return c};return c};var l={"inside-out":function(a){var b=a.length,c,d,e=a.map(o),f=a.map(n),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;c++)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},m={silhouette:function(a,b){var c=a.length,d=a[0].length,e=[],f=0,g,h,i;for(h=0;h<d;++h){for(g=0,i=0;g<c;g++)i+=a[g][h].y;i>f&&(f=i),e.push(i)}for(h=0,g=b[0];h<d;++h)a[g][h].y0=(f-e[h])/2},wiggle:function(a,b){var c=a.length,d=a[0],e=d.length,f=0,g,h,i,j,k,l=b[0],m,n,o,p,q,r;a[l][0].y0=q=r=0;for(h=1;h<e;++h){for(g=0,m=0;g<c;++g)m+=a[g][h].y;for(g=0,n=0,p=d[h].x-d[h-1].x;g<c;++g){for(i=0,j=b[g],o=(a[j][h].y-a[j][h-1].y)/(2*p);i<g;++i)o+=(a[k=b[i]][h].y-a[k][h-1].y)/p;n+=o*a[j][h].y}a[l][h].y0=q-=m?n/m*p:0,q<r&&(r=q)}for(h=0;h<e;++h)a[l][h].y0-=r},zero:function(a,b){var c=0,d=a[0].length,e=b[0];for(;c<d;++c)a[e][c].y0=0}};d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=c.call(g,a.data,b));c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k={depth:h,data:f};i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=c.call(g,f,h));return k}var a=s,b=q,c=r;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g},d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,A(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);B(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy(),b=[1,1];c.sort=d3.rebind(c,a.sort),c.children=d3.rebind(c,a.children),c.value=d3.rebind(c,a.value),c.size=function(a){if(!arguments.length)return b;b=a;return c};return c.sort(t)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;P(g,function(a){a.children?(a.x=E(a.children),a.y=D(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=F(g),m=G(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;P(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=I,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=H,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=K(g),e=J(e),g&&e)h=J(h),f=K(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(R(S(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!K(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!J(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d){var f=d.length,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;Q(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];P(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=L(g,N),l=L(g,M),m=L(g,O),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth;P(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=I,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=H,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.treemap=function(){function k(b){var i=e||a(b),j=i[0];j.x=0,j.y=0,j.dx=c[0],j.dy=c[1],e&&a.revalue(j),f(j,c[0]*c[1]/j.value),(e?h:g)(j),d&&(e=i);return i}function j(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=b(k.area/j);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=b(k.area/j);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function i(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,h=a.length;while(++g<h)d=a[g].area,d<f&&(f=d),d>e&&(e=d);c*=c,b*=b;return Math.max(b*e/c,c/(b*f))}function h(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=a.children.slice(),d,e=[];e.area=0;while(d=c.pop())e.push(d),e.area+=d.area,d.z!=null&&(j(e,d.z?b.dx:b.dy,b,!c.length),e.length=e.area=0);a.children.forEach(h)}}function g(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=[],d=a.children.slice(),e,f=Infinity,h,k=Math.min(b.dx,b.dy),l;c.area=0;while((l=d.length)>0)c.push(e=d[l-1]),c.area+=e.area,(h=i(c,k))<=f?(d.pop(),f=h):(c.area-=c.pop().area,j(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,f=Infinity);c.length&&(j(c,k,b,!0),c.length=c.area=0),a.children.forEach(g)}}function f(a,b){var c=a.children;a.area=a.value*b;if(c){var d=-1,e=c.length;while(++d<e)f(c[d],b)}}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=!1,e;k.sort=d3.rebind(k,a.sort),k.children=d3.rebind(k,a.children),k.value=d3.rebind(k,a.value),k.size=function(a){if(!arguments.length)return c;c=a;return k},k.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return k},k.sticky=function(a){if(!arguments.length)return d;d=a,e=null;return k};return k}})()
<ide>\ No newline at end of file
<add>(function(){function S(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function R(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function Q(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function P(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function O(a,b){return a.depth-b.depth}function N(a,b){return b.x-a.x}function M(a,b){return a.x-b.x}function L(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=L(c[f],b),a)>0&&(a=d)}return a}function K(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function J(a){return a.children?a.children[0]:a._tree.thread}function I(a,b){return a.parent==b.parent?1:2}function H(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function G(a){var b=a.children;return b?G(b[b.length-1]):a}function F(a){var b=a.children;return b?F(b[0]):a}function E(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function D(a){return 1+d3.max(a,function(a){return a.y})}function C(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function B(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)B(e[f],b,c,d)}}function A(a){var b=a.children;b?(b.forEach(A),a.r=x(b)):a.r=Math.sqrt(a.value)}function z(a){delete a._pack_next,delete a._pack_prev}function y(a){a._pack_next=a._pack_prev=a}function x(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(y),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],C(g,h,i),l(i),u(g,i),g._pack_prev=i,u(i,h),h=g._pack_next;for(var m=3;m<f;m++){C(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!=h;j=j._pack_next,o++)if(w(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!=j._pack_prev;k=k._pack_prev,p++)if(w(k,i)){p<o&&(n=-1,j=k);break}n==0?(u(g,i),h=i,l(i)):n>0?(v(g,j),h=j,m--):(v(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(z);return s}function w(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function v(a,b){a._pack_next=b,b._pack_prev=a}function u(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function t(a,b){return a.value-b.value}function s(a,b){return b.value-a.value}function r(a){return a.value}function q(a){return a.children}function p(a,b){return a+b.y}function o(a){var b=1,c=0,d=a[0].y,e,f=a.length;for(;b<f;++b)(e=a[b].y)>d&&(c=b,d=e);return c}function n(a){return a.reduce(p,0)}function k(a){var b=0,c=0;a.count=0,a.leaf||a.nodes.forEach(function(d){k(d),a.count+=d.count,b+=d.count*d.cx,c+=d.count*d.cy}),a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){d3.event.stopPropagation(),d3.event.preventDefault()}function i(){c&&(j(),c=!1)}function h(c,d){(a=c).fixed=!0,b=!1,e=this,j()}function g(b){b!==a&&(b.fixed=!1)}function f(a){a.fixed=!0}d3.layout={},d3.layout.chord=function(){function k(){b.sort(function(a,b){a=Math.min(a.source.value,a.target.value),b=Math.min(b.source.value,b.target.value);return i(a,b)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push({source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function A(){!a||(b&&(c=!0,j()),z(),a.fixed=!1,a=e=null)}function z(){if(!!a){var c=e.parentNode;if(!c){a.fixed=!1,a=e=null;return}var f=d3.svg.mouse(c);b=!0,a.px=f[0],a.py=f[1],d.resume()}}function y(){var a=u.length,b=v.length,c=d3.geom.quadtree(u),d,e,f,g,h,i,j;for(d=0;d<b;++d){e=v[d],f=e.source,g=e.target,i=g.x-f.x,j=g.y-f.y;if(h=i*i+j*j)h=n*((h=Math.sqrt(h))-p)/h,i*=h,j*=h,g.x-=i,g.y-=j,f.x+=i,f.y+=j}var s=n*r;i=m[0]/2,j=m[1]/2,d=-1;while(++d<a)e=u[d],e.x+=(i-e.x)*s,e.y+=(j-e.y)*s;k(c);var t=n*q;d=-1;while(++d<a)c.visit(x(u[d],t));d=-1;while(++d<a)e=u[d],e.fixed?(e.x=e.px,e.y=e.py):(e.x-=(e.px-(e.px=e.x))*o,e.y-=(e.py-(e.py=e.y))*o);l.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function x(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<s){var k=b*c.count*j*j;a.x+=h*k,a.y+=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.x+=h*k,a.y+=i*k}}}}var d={},l=d3.dispatch("tick"),m=[1,1],n,o=.9,p=20,q=-30,r=.1,s=.8,t,u,v,w;d.on=function(a,b){l[a].add(b);return d},d.nodes=function(a){if(!arguments.length)return u;u=a;return d},d.links=function(a){if(!arguments.length)return v;v=a;return d},d.size=function(a){if(!arguments.length)return m;m=a;return d},d.distance=function(a){if(!arguments.length)return p;p=a;return d},d.drag=function(a){if(!arguments.length)return o;o=a;return d},d.charge=function(a){if(!arguments.length)return q;q=a;return d},d.gravity=function(a){if(!arguments.length)return r;r=a;return d},d.theta=function(a){if(!arguments.length)return s;s=a;return d},d.start=function(){function k(){if(!h){h=[];for(b=0;b<c;++b)h[b]=[];for(b=0;b<e;++b){var d=v[b];h[d.source.index].push(d.target),h[d.target.index].push(d.source)}}return h[a]}function j(b,c){var d=k(a),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][b]))return g;return Math.random()*c}var a,b,c=u.length,e=v.length,f=m[0],g=m[1],h,i;for(a=0;a<c;++a)(i=u[a]).index=a;for(a=0;a<e;++a)i=v[a],typeof i.source=="number"&&(i.source=u[i.source]),typeof i.target=="number"&&(i.target=u[i.target]);for(a=0;a<c;++a)i=u[a],isNaN(i.x)&&(i.x=j("x",f)),isNaN(i.y)&&(i.y=j("y",g)),isNaN(i.px)&&(i.px=i.x),isNaN(i.py)&&(i.py=i.y);return d.resume()},d.resume=function(){n=.1,d3.timer(y);return d},d.stop=function(){n=0;return d},d.drag=function(){this.on("mouseover.force",f).on("mouseout.force",g).on("mousedown.force",h),d3.select(window).on("mousemove.force",z).on("mouseup.force",A,!0).on("click.force",i,!0);return d};return d};var a,b,c,e;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d/=a.value;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.sort=d3.rebind(e,a.sort),e.children=d3.rebind(e,a.children),e.value=d3.rebind(e,a.value),e.size=function(a){if(!arguments.length)return b;b=a;return e};return e},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function c(c){var d=c.length,e=c[0].length,f,g,h,i=l[a](c);m[b](c,i);for(g=0;g<e;++g)for(f=1,h=c[i[0]][g].y0;f<d;++f)c[i[f]][g].y0=h+=c[i[f-1]][g].y;return c}var a="default",b="zero";c.order=function(b){if(!arguments.length)return a;a=b;return c},c.offset=function(a){if(!arguments.length)return b;b=a;return c};return c};var l={"inside-out":function(a){var b=a.length,c,d,e=a.map(o),f=a.map(n),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;c++)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},m={silhouette:function(a,b){var c=a.length,d=a[0].length,e=[],f=0,g,h,i;for(h=0;h<d;++h){for(g=0,i=0;g<c;g++)i+=a[g][h].y;i>f&&(f=i),e.push(i)}for(h=0,g=b[0];h<d;++h)a[g][h].y0=(f-e[h])/2},wiggle:function(a,b){var c=a.length,d=a[0],e=d.length,f=0,g,h,i,j,k,l=b[0],m,n,o,p,q,r;a[l][0].y0=q=r=0;for(h=1;h<e;++h){for(g=0,m=0;g<c;++g)m+=a[g][h].y;for(g=0,n=0,p=d[h].x-d[h-1].x;g<c;++g){for(i=0,j=b[g],o=(a[j][h].y-a[j][h-1].y)/(2*p);i<g;++i)o+=(a[k=b[i]][h].y-a[k][h-1].y)/p;n+=o*a[j][h].y}a[l][h].y0=q-=m?n/m*p:0,q<r&&(r=q)}for(h=0;h<e;++h)a[l][h].y0-=r},zero:function(a,b){var c=0,d=a[0].length,e=b[0];for(;c<d;++c)a[e][c].y0=0}};d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=c.call(g,a.data,b));c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k={depth:h,data:f};i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=c.call(g,f,h));return k}var a=s,b=q,c=r;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g},d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,A(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);B(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy(),b=[1,1];c.sort=d3.rebind(c,a.sort),c.children=d3.rebind(c,a.children),c.value=d3.rebind(c,a.value),c.size=function(a){if(!arguments.length)return b;b=a;return c};return c.sort(t)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;P(g,function(a){a.children?(a.x=E(a.children),a.y=D(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=F(g),m=G(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;P(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=I,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=H,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=K(g),e=J(e),g&&e)h=J(h),f=K(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(R(S(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!K(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!J(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d){var f=d.length,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;Q(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];P(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=L(g,N),l=L(g,M),m=L(g,O),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth;P(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=I,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=H,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.treemap=function(){function k(b){var i=e||a(b),j=i[0];j.x=0,j.y=0,j.dx=c[0],j.dy=c[1],e&&a.revalue(j),f(j,c[0]*c[1]/j.value),(e?h:g)(j),d&&(e=i);return i}function j(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=b(k.area/j);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=b(k.area/j);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function i(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,h=a.length;while(++g<h)d=a[g].area,d<f&&(f=d),d>e&&(e=d);c*=c,b*=b;return Math.max(b*e/c,c/(b*f))}function h(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=a.children.slice(),d,e=[];e.area=0;while(d=c.pop())e.push(d),e.area+=d.area,d.z!=null&&(j(e,d.z?b.dx:b.dy,b,!c.length),e.length=e.area=0);a.children.forEach(h)}}function g(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=[],d=a.children.slice(),e,f=Infinity,h,k=Math.min(b.dx,b.dy),l;c.area=0;while((l=d.length)>0)c.push(e=d[l-1]),c.area+=e.area,(h=i(c,k))<=f?(d.pop(),f=h):(c.area-=c.pop().area,j(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,f=Infinity);c.length&&(j(c,k,b,!0),c.length=c.area=0),a.children.forEach(g)}}function f(a,b){var c=a.children;a.area=a.value*b;if(c){var d=-1,e=c.length;while(++d<e)f(c[d],b)}}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=!1,e;k.sort=d3.rebind(k,a.sort),k.children=d3.rebind(k,a.children),k.value=d3.rebind(k,a.value),k.size=function(a){if(!arguments.length)return c;c=a;return k},k.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return k},k.sticky=function(a){if(!arguments.length)return d;d=a,e=null;return k};return k}})()
<ide>\ No newline at end of file
<ide><path>d3.min.js
<del>(function(){function bS(){return"circle"}function bR(){return 64}function bP(a){return[a.x,a.y]}function bO(a){return a.endAngle}function bN(a){return a.startAngle}function bM(a){return a.radius}function bL(a){return a.target}function bK(a){return a.source}function bJ(){return 0}function bI(a,b,c){a.push("C",bE(bF,b),",",bE(bF,c),",",bE(bG,b),",",bE(bG,c),",",bE(bH,b),",",bE(bH,c))}function bE(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bD(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[bE(bH,g),",",bE(bH,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bI(b,g,h);return b.join("")}function bC(a){if(a.length<3)return bv(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),bI(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bI(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bI(b,h,i);return b.join("")}function bB(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function bA(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bv(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function bz(a,b,c){return a.length<3?bv(a):a[0]+bA(a,bB(a,b))}function by(a,b){return a.length<3?bv(a):a[0]+bA((a.push(a[0]),a),bB([a[a.length-2]].concat(a,[a[1]]),b))}function bx(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bw(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bv(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bt(a){return a[1]}function bs(a){return a[0]}function br(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bq(a){return a.endAngle}function bp(a){return a.startAngle}function bo(a){return a.outerRadius}function bn(a){return a.innerRadius}function bg(a){return function(b){return-Math.pow(-b,a)}}function bf(a){return function(b){return Math.pow(b,a)}}function be(a){return-Math.log(-a)/Math.LN10}function bd(a){return Math.log(a)/Math.LN10}function bb(){var a=null,b=Y,c=Infinity;while(b)b.flush?b=a?a.next=b.next:Y=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function ba(){var a,b=Date.now(),c=null,d=Y;while(d)a=b-d.then,a>d.delay&&(d.flush=d.callback(a)),d=(c=d).next;var e=bb()-b;e>24?(isFinite(e)&&(clearTimeout($),$=setTimeout(ba,e)),Z=0):(Z=1,bc(ba))}function _(a,b){var c=Date.now(),d=!1,e,f=Y;if(!!isFinite(b)){while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||(Y={callback:a,then:c,delay:b,next:Y}),Z||($=clearTimeout($),Z=1,bc(ba))}}function X(a){return typeof a=="function"?function(b,c,d){return d3.interpolate(d,String(a.call(this,b,c)))}:(a=String(a),function(b,c,d){return d3.interpolate(d,a)})}function W(a){function n(b){var g=!0,l=-1;a.each(function(){if(i[++l]!=2){var a=(b-j[l])/k[l],n=this.__transition__,o,p,q=e[l];if(a<1){g=!1;if(a<0)return}else a=1;if(i[l]){if(!n||n.active!=c){i[l]=2;return}}else{if(!n||n.active>c){i[l]=2;return}i[l]=1,h.start.dispatch.apply(this,arguments),q=e[l]={},n.active=c;for(p in d)if(o=d[p].apply(this,arguments))q[p]=o}o=m(a);for(p in q)q[p].call(this,o);if(a==1){i[l]=2;if(n.active==c){var r=n.owner;r==c&&(delete this.__transition__,f&&this.parentNode.removeChild(this)),V=c,h.end.dispatch.apply(this,arguments),V=0,n.owner=r}}}});return g}var b={},c=V||++U,d={},e=[],f=!1,h=d3.dispatch("start","end"),i=[],j=[],k=[],l,m=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=c}),b.delay=function(c){var d=Infinity,e=-1;typeof c=="function"?a.each(function(a,b){var f=j[++e]=+c.apply(this,arguments);f<d&&(d=f)}):(d=+c,a.each(function(a,b){j[++e]=d})),_(n,d);return b},b.duration=function(c){var d=-1;typeof c=="function"?(l=0,a.each(function(a,b){var e=k[++d]=+c.apply(this,arguments);e>l&&(l=e)})):(l=+c,a.each(function(a,b){k[++d]=l}));return b},b.ease=function(a){m=typeof a=="function"?a:d3.ease.apply(d3,arguments);return b},b.attrTween=function(a,c){function f(b,d){var e=c.call(this,b,d,this.getAttributeNS(a.space,a.local));return function(b){this.setAttributeNS(a.space,a.local,e(b))}}function e(b,d){var e=c.call(this,b,d,this.getAttribute(a));return function(b){this.setAttribute(a,e(b))}}d["attr."+a]=a.local?f:e;return b},b.attr=function(a,c){return b.attrTween(a,X(c))},b.styleTween=function(a,c,e){function f(b,d){var f=c.call(this,b,d,window.getComputedStyle(this,null).getPropertyValue(a));return function(b){this.style.setProperty(a,f(b),e)}}arguments.length<3&&(e=null),d["style."+a]=f;return b},b.style=function(a,c,d){arguments.length<3&&(d=null);return b.styleTween(a,X(c),d)},b.text=function(a){d.text=function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a};return b},b.select=function(b){var c,d=W(a.select(b)).ease(m);c=-1,d.delay(function(a,b){return j[++c]}),c=-1,d.duration(function(a,b){return k[++c]});return d},b.selectAll=function(b){var c,d=W(a.selectAll(b)).ease(m);c=-1,d.delay(function(a,b){return j[b?c:++c]}),c=-1,d.duration(function(a,b){return k[b?c:++c]});return d},b.remove=function(){f=!0;return b},b.each=function(a,c){h[a].add(c);return b},b.call=g;return b.delay(0).duration(250)}function T(a){return{__data__:a}}function S(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function R(a){function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(f.parentNode)),e.__data__=g.__data__):d.push(null)}return Q(c)}a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function Q(a){function d(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];if(h)return b.call(h,h.__data__,f)}}return null}function c(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g];for(var i=0,j=e.length;i<j;i++)if(f=e[i])c.push(d=b(f)),d.parentNode=f}return Q(c)}function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(g)),e&&"__data__"in g&&(e.__data__=g.__data__)):d.push(null)}return Q(c)}a.select=function(a){return b(function(b){return N(a,b)})},a.selectAll=function(a){return c(function(b){return O(a,b)})},a.filter=function(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g],c.push(d=[]),d.parentNode=e.parentNode;for(var i=0,j=e.length;i<j;i++)(f=e[i])&&b.call(f,f.__data__,i)&&d.push(f)}return Q(c)},a.map=function(b){var c,d;for(var e=0,f=a.length;e<f;e++){c=a[e];for(var g=0,h=c.length;g<h;g++)if(d=c[g])d.__data__=b.call(d,d.__data__,g)}return a},a.data=function(b,c){function g(a,b){var g=0,h=a.length,i=b.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(c){var q={},r=[],s,t=b.length;for(g=0;g<h;g++)s=c.call(o=a[g],o.__data__,g),s in q?n[t++]=a[g]:q[s]=o,r.push(s);for(g=0;g<i;g++)o=q[s=c.call(b,p=b[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=T(p),l[g]=n[g]=null),delete q[s];for(g=0;g<h;g++)r[g]in q&&(n[g]=a[g])}else{for(;g<j;g++)o=a[g],p=b[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=T(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=T(b[g]),l[g]=n[g]=null;for(;g<k;g++)n[g]=a[g],m[g]=l[g]=null}m.parentNode=l.parentNode=n.parentNode=a.parentNode,d.push(m),e.push(l),f.push(n)}var d=[],e=[],f=[],h=-1,i=a.length,j;if(typeof b=="function")while(++h<i)g(j=a[h],b.call(j,j.parentNode.__data__,h));else while(++h<i)g(j=a[h],b);var k=Q(e);k.enter=function(){return R(d)},k.exit=function(){return Q(f)};return k},a.each=function(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];h&&b.call(h,h.__data__,f)}}return a},a.empty=function(){return!d(function(){return!0})},a.node=function(){return d(function(){return this})},a.attr=function(b,c){function j(){var a=c.apply(this,arguments);a==null?this.removeAttributeNS(b.space,b.local):this.setAttributeNS(b.space,b.local,a)}function i(){var a=c.apply(this,arguments);a==null?this.removeAttribute(b):this.setAttribute(b,a)}function h(){this.setAttributeNS(b.space,b.local,c)}function g(){this.setAttribute(b,c)}function f(){this.removeAttributeNS(b.space,b.local)}function e(){this.removeAttribute(b)}b=d3.ns.qualify(b);if(arguments.length<2)return d(b.local?function(){return this.getAttributeNS(b.space,b.local)}:function(){return this.getAttribute(b)});return a.each(c==null?b.local?f:e:typeof c=="function"?b.local?j:i:b.local?h:g)},a.classed=function(b,c){function i(){(c.apply(this,arguments)?g:h).call(this)}function h(){var a=f(this.className.replace(e," "));this.className=a.length?a:null}function g(){var a=this.className;e.lastIndex=0,e.test(a)||(this.className=f(a+" "+b))}var e=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){e.lastIndex=0;return e.test(this.className)});return a.each(typeof c=="function"?i:c?g:h)},a.style=function(b,c,e){function h(){var a=c.apply(this,arguments);a==null?this.style.removeProperty(b):this.style.setProperty(b,a,e)}function g(){this.style.setProperty(b,c,e)}function f(){this.style.removeProperty(b)}arguments.length<3&&(e="");if(arguments.length<2)return d(function(){return window.getComputedStyle(this,null).getPropertyValue(b)});return a.each(c==null?f:typeof c=="function"?h:g)},a.property=function(b,c){function g(){var a=c.apply(this,arguments);a==null?delete this[b]:this[b]=a}function f(){this[b]=c}function e(){delete this[b]}b=d3.ns.qualify(b);if(arguments.length<2)return d(function(){return this[b]});return a.each(c==null?e:typeof c=="function"?g:f)},a.text=function(b){function e(){this.textContent=b.apply(this,arguments)}function c(){this.textContent=b}if(arguments.length<1)return d(function(){return this.textContent});return a.each(typeof b=="function"?e:c)},a.html=function(b){function e(){this.innerHTML=b.apply(this,arguments)}function c(){this.innerHTML=b}if(arguments.length<1)return d(function(){return this.innerHTML});return a.each(typeof b=="function"?e:c)},a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)},a.remove=function(){return a.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},a.sort=function(b){b=S.apply(this,arguments);for(var c=0,d=a.length;c<d;c++){var e=a[c];e.sort(b);for(var f=1,g=e.length,h=e[0];f<g;f++){var i=e[f];i&&(h&&h.parentNode.insertBefore(i,h.nextSibling),h=i)}}return a},a.on=function(b,c,d){arguments.length<3&&(d=!1);var e=b.indexOf("."),f=e==-1?b:b.substring(0,e),g="__on"+b;return a.each(function(a,b){function e(d){var e=d3.event;d3.event=d;try{c.call(this,a,b)}finally{d3.event=e}}this[g]&&this.removeEventListener(f,this[g],d),c&&this.addEventListener(f,this[g]=e,d)})},a.transition=function(){return W(a)},a.call=g;return a}function M(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);if(a<60)return d+(e-d)*a/60;if(a<180)return e;if(a<240)return d+(e-d)*(240-a)/60;return d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return C(g(a+120),g(a),g(a-120))}function L(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"}function K(a,b,c){return{h:a,s:b,l:c,toString:L}}function H(a){var b=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(b*2.55):b}function G(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return K(g,h,i)}function F(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(H(h[0]),H(h[1]),H(h[2]))}}if(i=I[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)=="#"&&(a.length==4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length==7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function E(a){return a<16?"0"+a.toString(16):a.toString(16)}function D(){return"#"+E(this.r)+E(this.g)+E(this.b)}function C(a,b,c){return{r:a,g:b,b:c,toString:D}}function B(a){return a in A||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function y(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function x(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function w(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function v(a){return 1-Math.sqrt(1-a*a)}function u(a){return a?Math.pow(2,10*(a-1))-.001:0}function t(a){return 1-Math.cos(a*Math.PI/2)}function s(a){return function(b){return Math.pow(b,a)}}function r(a){return a}function q(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function p(a){return function(b){return 1-a(1-b)}}function k(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function i(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function g(a){a.apply(this,(arguments[0]=this,arguments));return this}function f(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function e(a){return a==null}function c(a){return Array.prototype.slice.call(a)}function b(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.14.0"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b});var a=c;try{a(document.documentElement.childNodes)[0].nodeType}catch(d){a=b}d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:0},d3.descending=function(a,b){return b<a?-1:b>a?1:0},d3.min=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length==1)while(++c<d)e>(f=a[c])&&(e=f);else{e=b(a[0]);while(++c<d)e>(f=b(a[c]))&&(e=f)}return e},d3.max=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length==1)while(++c<d)e<(f=a[c])&&(e=f);else{e=b(e);while(++c<d)e<(f=b(a[c]))&&(e=f)}return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],f,g=-1,h=a.length;arguments.length<2&&(b=e);while(++g<h)b.call(d,f=a[g],g)?d=[]:(d.length||c.push(d),d.push(f));return c},d3.range=function(a,b,c){arguments.length==1&&(b=a,a=0),c==null&&(c=1);if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(h,"\\$&")};var h=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState==4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=i(c);return b},d3.format=function(a){var b=j.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9];h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4))),i=="d"&&(h="0");return function(a){var b=+a,j=b<0&&(b=-b)?"−":d;if(i=="d"&&b%1)return"";h?a=b.toFixed(h):a=""+b;if(e){var l=a.length+j.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=k(a)),a=j+a}else{g&&(a=k(a)),a=j+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}return a}};var j=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l=s(2),m=s(3),n={linear:function(){return r},poly:s,quad:function(){return l},cubic:function(){return m},sin:function(){return t},exp:function(){return u},circle:function(){return v},elastic:w,back:x,bounce:function(){return y}},o={"in":function(a){return a},out:p,"in-out":q,"out-in":function(a){return q(p(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return o[d](n[c].apply(null,Array.prototype.slice.call(arguments,1)))},d3.event=null,d3.interpolate=function(a,b){if(typeof b=="number")return d3.interpolateNumber(+a,b);if(typeof b=="string")return b in I||/^(#|rgb\(|hsl\()/.test(b)?d3.interpolateRgb(String(a),b):d3.interpolateString(String(a),b);if(b instanceof Array)return d3.interpolateArray(a,b);return d3.interpolateObject(a,b)},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;z.lastIndex=0;for(d=0;c=z.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=z.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=z.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;if(h.length==1)return h[0]==null?i[0].x:function(){return b};return function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return M(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=B(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var z=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,A={background:1,fill:1,stroke:1};d3.rgb=function(a,b,c){return arguments.length==1?F(""+a,C,M):C(~~a,~~b,~~c)};var I={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var J in I)I[J]=F(I[J],C,M);d3.hsl=function(a,b,c){return arguments.length==1?F(""+a,G,K):K(+a,+b,+c)};var N=function(a,b){return b.querySelector(a)},O=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(N=function(a,b){return Sizzle(a,b)[0]},O=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var P=Q([[document]]);P[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?P.select(a):Q([[a]])},d3.selectAll=function(b){return typeof b=="string"?P.selectAll(b):Q([a(b)])},d3.transition=P.transition;var U=0,V=0,Y=null,Z,$;d3.timer=function(a){_(a,0)};var bc=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function k(c){var d=Math.min(a,b),e=Math.max(a,b),f=e-d,g=Math.pow(10,Math.floor(Math.log(f/c)/Math.LN10)),h=c/(f/g);h<=.15?g*=10:h<=.35?g*=5:h<=.75&&(g*=2);return{start:Math.ceil(d/g)*g,stop:Math.floor(e/g)*g+g*.5,step:g}}function j(b){b=(b-a)*e;return h(i?Math.max(0,Math.min(1,b)):b)}var a=0,b=1,c=0,d=1,e=1,f=1,g=d3.interpolate,h=g(c,d),i=!1;j.invert=function(b){return(b-c)*f+a},j.domain=function(g){if(!arguments.length)return[a,b];a=+g[0],b=+g[1],e=1/(b-a),f=(b-a)/(d-c);return j},j.range=function(e){if(!arguments.length)return[c,d];c=e[0],d=e[1],f=(b-a)/(d-c),h=g(c,d);return j},j.rangeRound=function(a){return j.range(a).interpolate(d3.interpolateRound)},j.clamp=function(a){if(!arguments.length)return i;i=a;return j},j.interpolate=function(a){if(!arguments.length)return g;h=(g=a)(c,d);return j},j.ticks=function(a){var b=k(a);return d3.range(b.start,b.stop,b.step)},j.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(k(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return j},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=bd,c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=(e[0]||e[1])<0?be:bd,c=b.pow,a.domain(e.map(b));return d},d.range=d3.rebind(d,a.range),d.rangeRound=d3.rebind(d,a.rangeRound),d.interpolate=d3.rebind(d,a.interpolate),d.clamp=d3.rebind(d,a.clamp),d.ticks=function(){var d=a.domain(),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===be){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return function(a){return a.toPrecision(1)}};return d},bd.pow=function(a){return Math.pow(10,a)},be.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){function f(b){return a(d(b))}var a=d3.scale.linear(),b=d3.scale.linear(),c=1,d=Number,e=d;f.invert=function(b){return e(a.invert(b))},f.domain=function(g){if(!arguments.length)return a.domain().map(e);var h=(g[0]||g[1])<0?bg:bf;d=h(c),e=h(1/c),a.domain(g.map(d)),b.domain(g);return f},f.range=d3.rebind(f,a.range),f.rangeRound=d3.rebind(f,a.rangeRound),f.interpolate=d3.rebind(f,a.interpolate),f.clamp=d3.rebind(f,a.clamp),f.ticks=b.ticks,f.tickFormat=b.tickFormat,f.exponent=function(a){if(!arguments.length)return c;var b=f.domain();c=a;return f.domain(b)};return f},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){function e(d){var e=d in b?b[d]:b[d]=a.push(d)-1;return c[e%c.length]}var a=[],b={},c=[],d=0;e.domain=function(c){if(!arguments.length)return a;a=c,b={};var d=-1,f=-1,g=a.length;while(++d<g)c=a[d],c in b||(b[c]=++f);return e},e.range=function(a){if(!arguments.length)return c;c=a;return e},e.rangePoints=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length-1+f);c=a.length==1?[(g+h)/2]:d3.range(g+i*f/2,h+i/2,i),d=0;return e},e.rangeBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length+f);c=d3.range(g+i*f,h,i),d=i*(1-f);return e},e.rangeRoundBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=h-g,j=Math.floor(i/(a.length+f)),k=i-(a.length-f)*j;c=d3.range(g+Math.round(k/2),h,j),d=Math.round(j*(1-f));return e},e.rangeBand=function(){return d};return e},d3.scale.category10=function(){return d3.scale.ordinal().range(bh)},d3.scale.category20=function(){return d3.scale.ordinal().range(bi)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bj)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bk)};var bh=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bi=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bj=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bk=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function f(a){return b[e(a)]}function e(a){if(isNaN(a=+a))return NaN;var b=0,d=c.length-1;while(b<=d){var e=b+d>>1,f=c[e];if(f<a)b=e+1;else if(f>a)d=e-1;else return e}return d<0?0:d}function d(){var d=-1,e=c.length=b.length,f=a.length/e;while(++d<e)c[d]=a[~~(d*f)]}var a=[],b=[],c=[];f.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending),d();return f},f.range=function(a){if(!arguments.length)return b;b=a,d();return f},f.quantiles=function(){return c};return f},d3.scale.quantize=function(){function f(b){return e[Math.max(0,Math.min(d,Math.floor(c*(b-a))))]}var a=0,b=1,c=2,d=1,e=[0,1];f.domain=function(d){if(!arguments.length)return[a,b];a=d[0],b=d[1],c=e.length/(b-a);return f},f.range=function(g){if(!arguments.length)return e;e=g,c=e.length/(b-a),d=e.length-1;return f};return f},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bl,h=d.apply(this,arguments)+bl,i=h-g,j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bm?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=bn,b=bo,c=bp,d=bq;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bl;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bl=-Math.PI/2,bm=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(br(this,c,a,b),e)}var a=bs,b=bt,c="linear",d=bu[c],e=.7;f.x=function(b){if(!arguments.length)return a;a=b;return f},f.y=function(a){if(!arguments.length)return b;b=a;return f},f.interpolate=function(a){if(!arguments.length)return c;d=bu[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var bu={linear:bv,"step-before":bw,"step-after":bx,basis:bC,"basis-closed"
<add>(function(){function bS(){return"circle"}function bR(){return 64}function bP(a){return[a.x,a.y]}function bO(a){return a.endAngle}function bN(a){return a.startAngle}function bM(a){return a.radius}function bL(a){return a.target}function bK(a){return a.source}function bJ(){return 0}function bI(a,b,c){a.push("C",bE(bF,b),",",bE(bF,c),",",bE(bG,b),",",bE(bG,c),",",bE(bH,b),",",bE(bH,c))}function bE(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bD(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[bE(bH,g),",",bE(bH,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bI(b,g,h);return b.join("")}function bC(a){if(a.length<3)return bv(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),bI(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bI(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bI(b,h,i);return b.join("")}function bB(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function bA(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bv(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function bz(a,b,c){return a.length<3?bv(a):a[0]+bA(a,bB(a,b))}function by(a,b){return a.length<3?bv(a):a[0]+bA((a.push(a[0]),a),bB([a[a.length-2]].concat(a,[a[1]]),b))}function bx(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bw(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bv(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bt(a){return a[1]}function bs(a){return a[0]}function br(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bq(a){return a.endAngle}function bp(a){return a.startAngle}function bo(a){return a.outerRadius}function bn(a){return a.innerRadius}function bg(a){return function(b){return-Math.pow(-b,a)}}function bf(a){return function(b){return Math.pow(b,a)}}function be(a){return-Math.log(-a)/Math.LN10}function bd(a){return Math.log(a)/Math.LN10}function bb(){var a=null,b=Y,c=Infinity;while(b)b.flush?b=a?a.next=b.next:Y=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function ba(){var a,b=Date.now(),c=null,d=Y;while(d)a=b-d.then,a>d.delay&&(d.flush=d.callback(a)),d=(c=d).next;var e=bb()-b;e>24?(isFinite(e)&&(clearTimeout($),$=setTimeout(ba,e)),Z=0):(Z=1,bc(ba))}function _(a,b){var c=Date.now(),d=!1,e,f=Y;if(!!isFinite(b)){while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||(Y={callback:a,then:c,delay:b,next:Y}),Z||($=clearTimeout($),Z=1,bc(ba))}}function X(a){return typeof a=="function"?function(b,c,d){return d3.interpolate(d,String(a.call(this,b,c)))}:(a=String(a),function(b,c,d){return d3.interpolate(d,a)})}function W(a){function n(b){var g=!0,l=-1;a.each(function(){if(i[++l]!=2){var a=(b-j[l])/k[l],n=this.__transition__,o,p,q=e[l];if(a<1){g=!1;if(a<0)return}else a=1;if(i[l]){if(!n||n.active!=c){i[l]=2;return}}else{if(!n||n.active>c){i[l]=2;return}i[l]=1,h.start.dispatch.apply(this,arguments),q=e[l]={},n.active=c;for(p in d)if(o=d[p].apply(this,arguments))q[p]=o}o=m(a);for(p in q)q[p].call(this,o);if(a==1){i[l]=2;if(n.active==c){var r=n.owner;r==c&&(delete this.__transition__,f&&this.parentNode.removeChild(this)),V=c,h.end.dispatch.apply(this,arguments),V=0,n.owner=r}}}});return g}var b={},c=V||++U,d={},e=[],f=!1,h=d3.dispatch("start","end"),i=[],j=[],k=[],l,m=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=c}),b.delay=function(c){var d=Infinity,e=-1;typeof c=="function"?a.each(function(a,b){var f=j[++e]=+c.apply(this,arguments);f<d&&(d=f)}):(d=+c,a.each(function(a,b){j[++e]=d})),_(n,d);return b},b.duration=function(c){var d=-1;typeof c=="function"?(l=0,a.each(function(a,b){var e=k[++d]=+c.apply(this,arguments);e>l&&(l=e)})):(l=+c,a.each(function(a,b){k[++d]=l}));return b},b.ease=function(a){m=typeof a=="function"?a:d3.ease.apply(d3,arguments);return b},b.attrTween=function(a,c){function f(b,d){var e=c.call(this,b,d,this.getAttributeNS(a.space,a.local));return function(b){this.setAttributeNS(a.space,a.local,e(b))}}function e(b,d){var e=c.call(this,b,d,this.getAttribute(a));return function(b){this.setAttribute(a,e(b))}}d["attr."+a]=a.local?f:e;return b},b.attr=function(a,c){return b.attrTween(a,X(c))},b.styleTween=function(a,c,e){function f(b,d){var f=c.call(this,b,d,window.getComputedStyle(this,null).getPropertyValue(a));return function(b){this.style.setProperty(a,f(b),e)}}arguments.length<3&&(e=null),d["style."+a]=f;return b},b.style=function(a,c,d){arguments.length<3&&(d=null);return b.styleTween(a,X(c),d)},b.text=function(a){d.text=function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a};return b},b.select=function(b){var c,d=W(a.select(b)).ease(m);c=-1,d.delay(function(a,b){return j[++c]}),c=-1,d.duration(function(a,b){return k[++c]});return d},b.selectAll=function(b){var c,d=W(a.selectAll(b)).ease(m);c=-1,d.delay(function(a,b){return j[b?c:++c]}),c=-1,d.duration(function(a,b){return k[b?c:++c]});return d},b.remove=function(){f=!0;return b},b.each=function(a,c){h[a].add(c);return b},b.call=g;return b.delay(0).duration(250)}function T(a){return{__data__:a}}function S(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function R(a){function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(f.parentNode)),e.__data__=g.__data__):d.push(null)}return Q(c)}a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function Q(a){function d(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];if(h)return b.call(h,h.__data__,f)}}return null}function c(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g];for(var i=0,j=e.length;i<j;i++)if(f=e[i])c.push(d=b(f)),d.parentNode=f}return Q(c)}function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(g)),e&&"__data__"in g&&(e.__data__=g.__data__)):d.push(null)}return Q(c)}a.select=function(a){return b(function(b){return N(a,b)})},a.selectAll=function(a){return c(function(b){return O(a,b)})},a.filter=function(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g],c.push(d=[]),d.parentNode=e.parentNode;for(var i=0,j=e.length;i<j;i++)(f=e[i])&&b.call(f,f.__data__,i)&&d.push(f)}return Q(c)},a.map=function(b){var c,d;for(var e=0,f=a.length;e<f;e++){c=a[e];for(var g=0,h=c.length;g<h;g++)if(d=c[g])d.__data__=b.call(d,d.__data__,g)}return a},a.data=function(b,c){function g(a,b){var g=0,h=a.length,i=b.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(c){var q={},r=[],s,t=b.length;for(g=0;g<h;g++)s=c.call(o=a[g],o.__data__,g),s in q?n[t++]=a[g]:q[s]=o,r.push(s);for(g=0;g<i;g++)o=q[s=c.call(b,p=b[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=T(p),l[g]=n[g]=null),delete q[s];for(g=0;g<h;g++)r[g]in q&&(n[g]=a[g])}else{for(;g<j;g++)o=a[g],p=b[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=T(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=T(b[g]),l[g]=n[g]=null;for(;g<k;g++)n[g]=a[g],m[g]=l[g]=null}m.parentNode=l.parentNode=n.parentNode=a.parentNode,d.push(m),e.push(l),f.push(n)}var d=[],e=[],f=[],h=-1,i=a.length,j;if(typeof b=="function")while(++h<i)g(j=a[h],b.call(j,j.parentNode.__data__,h));else while(++h<i)g(j=a[h],b);var k=Q(e);k.enter=function(){return R(d)},k.exit=function(){return Q(f)};return k},a.each=function(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];h&&b.call(h,h.__data__,f)}}return a},a.empty=function(){return!d(function(){return!0})},a.node=function(){return d(function(){return this})},a.attr=function(b,c){function j(){var a=c.apply(this,arguments);a==null?this.removeAttributeNS(b.space,b.local):this.setAttributeNS(b.space,b.local,a)}function i(){var a=c.apply(this,arguments);a==null?this.removeAttribute(b):this.setAttribute(b,a)}function h(){this.setAttributeNS(b.space,b.local,c)}function g(){this.setAttribute(b,c)}function f(){this.removeAttributeNS(b.space,b.local)}function e(){this.removeAttribute(b)}b=d3.ns.qualify(b);if(arguments.length<2)return d(b.local?function(){return this.getAttributeNS(b.space,b.local)}:function(){return this.getAttribute(b)});return a.each(c==null?b.local?f:e:typeof c=="function"?b.local?j:i:b.local?h:g)},a.classed=function(b,c){function i(){(c.apply(this,arguments)?g:h).call(this)}function h(){var a=f(this.className.replace(e," "));this.className=a.length?a:null}function g(){var a=this.className;e.lastIndex=0,e.test(a)||(this.className=f(a+" "+b))}var e=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){e.lastIndex=0;return e.test(this.className)});return a.each(typeof c=="function"?i:c?g:h)},a.style=function(b,c,e){function h(){var a=c.apply(this,arguments);a==null?this.style.removeProperty(b):this.style.setProperty(b,a,e)}function g(){this.style.setProperty(b,c,e)}function f(){this.style.removeProperty(b)}arguments.length<3&&(e="");if(arguments.length<2)return d(function(){return window.getComputedStyle(this,null).getPropertyValue(b)});return a.each(c==null?f:typeof c=="function"?h:g)},a.property=function(b,c){function g(){var a=c.apply(this,arguments);a==null?delete this[b]:this[b]=a}function f(){this[b]=c}function e(){delete this[b]}b=d3.ns.qualify(b);if(arguments.length<2)return d(function(){return this[b]});return a.each(c==null?e:typeof c=="function"?g:f)},a.text=function(b){function e(){this.textContent=b.apply(this,arguments)}function c(){this.textContent=b}if(arguments.length<1)return d(function(){return this.textContent});return a.each(typeof b=="function"?e:c)},a.html=function(b){function e(){this.innerHTML=b.apply(this,arguments)}function c(){this.innerHTML=b}if(arguments.length<1)return d(function(){return this.innerHTML});return a.each(typeof b=="function"?e:c)},a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)},a.remove=function(){return a.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},a.sort=function(b){b=S.apply(this,arguments);for(var c=0,d=a.length;c<d;c++){var e=a[c];e.sort(b);for(var f=1,g=e.length,h=e[0];f<g;f++){var i=e[f];i&&(h&&h.parentNode.insertBefore(i,h.nextSibling),h=i)}}return a},a.on=function(b,c,d){arguments.length<3&&(d=!1);var e=b.indexOf("."),f=e==-1?b:b.substring(0,e),g="__on"+b;return a.each(function(a,b){function e(d){var e=d3.event;d3.event=d;try{c.call(this,a,b)}finally{d3.event=e}}this[g]&&this.removeEventListener(f,this[g],d),c&&this.addEventListener(f,this[g]=e,d)})},a.transition=function(){return W(a)},a.call=g;return a}function M(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);if(a<60)return d+(e-d)*a/60;if(a<180)return e;if(a<240)return d+(e-d)*(240-a)/60;return d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return C(g(a+120),g(a),g(a-120))}function L(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"}function K(a,b,c){return{h:a,s:b,l:c,toString:L}}function H(a){var b=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(b*2.55):b}function G(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return K(g,h,i)}function F(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(H(h[0]),H(h[1]),H(h[2]))}}if(i=I[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)=="#"&&(a.length==4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length==7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function E(a){return a<16?"0"+a.toString(16):a.toString(16)}function D(){return"#"+E(this.r)+E(this.g)+E(this.b)}function C(a,b,c){return{r:a,g:b,b:c,toString:D}}function B(a){return a in A||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function y(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function x(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function w(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function v(a){return 1-Math.sqrt(1-a*a)}function u(a){return a?Math.pow(2,10*(a-1))-.001:0}function t(a){return 1-Math.cos(a*Math.PI/2)}function s(a){return function(b){return Math.pow(b,a)}}function r(a){return a}function q(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function p(a){return function(b){return 1-a(1-b)}}function k(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function i(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function g(a){a.apply(this,(arguments[0]=this,arguments));return this}function f(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function e(a){return a==null}function c(a){return Array.prototype.slice.call(a)}function b(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.14.1"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b});var a=c;try{a(document.documentElement.childNodes)[0].nodeType}catch(d){a=b}d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:0},d3.descending=function(a,b){return b<a?-1:b>a?1:0},d3.min=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length==1)while(++c<d)e>(f=a[c])&&(e=f);else{e=b(a[0]);while(++c<d)e>(f=b(a[c]))&&(e=f)}return e},d3.max=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length==1)while(++c<d)e<(f=a[c])&&(e=f);else{e=b(e);while(++c<d)e<(f=b(a[c]))&&(e=f)}return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],f,g=-1,h=a.length;arguments.length<2&&(b=e);while(++g<h)b.call(d,f=a[g],g)?d=[]:(d.length||c.push(d),d.push(f));return c},d3.range=function(a,b,c){arguments.length==1&&(b=a,a=0),c==null&&(c=1);if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(h,"\\$&")};var h=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState==4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=i(c);return b},d3.format=function(a){var b=j.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9];h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4))),i=="d"&&(h="0");return function(a){var b=+a,j=b<0&&(b=-b)?"−":d;if(i=="d"&&b%1)return"";h?a=b.toFixed(h):a=""+b;if(e){var l=a.length+j.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=k(a)),a=j+a}else{g&&(a=k(a)),a=j+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}return a}};var j=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l=s(2),m=s(3),n={linear:function(){return r},poly:s,quad:function(){return l},cubic:function(){return m},sin:function(){return t},exp:function(){return u},circle:function(){return v},elastic:w,back:x,bounce:function(){return y}},o={"in":function(a){return a},out:p,"in-out":q,"out-in":function(a){return q(p(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return o[d](n[c].apply(null,Array.prototype.slice.call(arguments,1)))},d3.event=null,d3.interpolate=function(a,b){if(typeof b=="number")return d3.interpolateNumber(+a,b);if(typeof b=="string")return b in I||/^(#|rgb\(|hsl\()/.test(b)?d3.interpolateRgb(String(a),b):d3.interpolateString(String(a),b);if(b instanceof Array)return d3.interpolateArray(a,b);return d3.interpolateObject(a,b)},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;z.lastIndex=0;for(d=0;c=z.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=z.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=z.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;if(h.length==1)return h[0]==null?i[0].x:function(){return b};return function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return M(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=B(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var z=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,A={background:1,fill:1,stroke:1};d3.rgb=function(a,b,c){return arguments.length==1?F(""+a,C,M):C(~~a,~~b,~~c)};var I={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var J in I)I[J]=F(I[J],C,M);d3.hsl=function(a,b,c){return arguments.length==1?F(""+a,G,K):K(+a,+b,+c)};var N=function(a,b){return b.querySelector(a)},O=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(N=function(a,b){return Sizzle(a,b)[0]},O=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var P=Q([[document]]);P[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?P.select(a):Q([[a]])},d3.selectAll=function(b){return typeof b=="string"?P.selectAll(b):Q([a(b)])},d3.transition=P.transition;var U=0,V=0,Y=null,Z,$;d3.timer=function(a){_(a,0)};var bc=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function k(c){var d=Math.min(a,b),e=Math.max(a,b),f=e-d,g=Math.pow(10,Math.floor(Math.log(f/c)/Math.LN10)),h=c/(f/g);h<=.15?g*=10:h<=.35?g*=5:h<=.75&&(g*=2);return{start:Math.ceil(d/g)*g,stop:Math.floor(e/g)*g+g*.5,step:g}}function j(b){b=(b-a)*e;return h(i?Math.max(0,Math.min(1,b)):b)}var a=0,b=1,c=0,d=1,e=1,f=1,g=d3.interpolate,h=g(c,d),i=!1;j.invert=function(b){return(b-c)*f+a},j.domain=function(g){if(!arguments.length)return[a,b];a=+g[0],b=+g[1],e=1/(b-a),f=(b-a)/(d-c);return j},j.range=function(e){if(!arguments.length)return[c,d];c=e[0],d=e[1],f=(b-a)/(d-c),h=g(c,d);return j},j.rangeRound=function(a){return j.range(a).interpolate(d3.interpolateRound)},j.clamp=function(a){if(!arguments.length)return i;i=a;return j},j.interpolate=function(a){if(!arguments.length)return g;h=(g=a)(c,d);return j},j.ticks=function(a){var b=k(a);return d3.range(b.start,b.stop,b.step)},j.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(k(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return j},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=bd,c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=(e[0]||e[1])<0?be:bd,c=b.pow,a.domain(e.map(b));return d},d.range=d3.rebind(d,a.range),d.rangeRound=d3.rebind(d,a.rangeRound),d.interpolate=d3.rebind(d,a.interpolate),d.clamp=d3.rebind(d,a.clamp),d.ticks=function(){var d=a.domain(),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===be){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return function(a){return a.toPrecision(1)}};return d},bd.pow=function(a){return Math.pow(10,a)},be.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){function f(b){return a(d(b))}var a=d3.scale.linear(),b=d3.scale.linear(),c=1,d=Number,e=d;f.invert=function(b){return e(a.invert(b))},f.domain=function(g){if(!arguments.length)return a.domain().map(e);var h=(g[0]||g[1])<0?bg:bf;d=h(c),e=h(1/c),a.domain(g.map(d)),b.domain(g);return f},f.range=d3.rebind(f,a.range),f.rangeRound=d3.rebind(f,a.rangeRound),f.interpolate=d3.rebind(f,a.interpolate),f.clamp=d3.rebind(f,a.clamp),f.ticks=b.ticks,f.tickFormat=b.tickFormat,f.exponent=function(a){if(!arguments.length)return c;var b=f.domain();c=a;return f.domain(b)};return f},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){function e(d){var e=d in b?b[d]:b[d]=a.push(d)-1;return c[e%c.length]}var a=[],b={},c=[],d=0;e.domain=function(c){if(!arguments.length)return a;a=c,b={};var d=-1,f=-1,g=a.length;while(++d<g)c=a[d],c in b||(b[c]=++f);return e},e.range=function(a){if(!arguments.length)return c;c=a;return e},e.rangePoints=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length-1+f);c=a.length==1?[(g+h)/2]:d3.range(g+i*f/2,h+i/2,i),d=0;return e},e.rangeBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length+f);c=d3.range(g+i*f,h,i),d=i*(1-f);return e},e.rangeRoundBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=h-g,j=Math.floor(i/(a.length+f)),k=i-(a.length-f)*j;c=d3.range(g+Math.round(k/2),h,j),d=Math.round(j*(1-f));return e},e.rangeBand=function(){return d};return e},d3.scale.category10=function(){return d3.scale.ordinal().range(bh)},d3.scale.category20=function(){return d3.scale.ordinal().range(bi)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bj)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bk)};var bh=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bi=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bj=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bk=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function f(a){return b[e(a)]}function e(a){if(isNaN(a=+a))return NaN;var b=0,d=c.length-1;while(b<=d){var e=b+d>>1,f=c[e];if(f<a)b=e+1;else if(f>a)d=e-1;else return e}return d<0?0:d}function d(){var d=-1,e=c.length=b.length,f=a.length/e;while(++d<e)c[d]=a[~~(d*f)]}var a=[],b=[],c=[];f.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending),d();return f},f.range=function(a){if(!arguments.length)return b;b=a,d();return f},f.quantiles=function(){return c};return f},d3.scale.quantize=function(){function f(b){return e[Math.max(0,Math.min(d,Math.floor(c*(b-a))))]}var a=0,b=1,c=2,d=1,e=[0,1];f.domain=function(d){if(!arguments.length)return[a,b];a=d[0],b=d[1],c=e.length/(b-a);return f},f.range=function(g){if(!arguments.length)return e;e=g,c=e.length/(b-a),d=e.length-1;return f};return f},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bl,h=d.apply(this,arguments)+bl,i=h-g,j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bm?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=bn,b=bo,c=bp,d=bq;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bl;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bl=-Math.PI/2,bm=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(br(this,c,a,b),e)}var a=bs,b=bt,c="linear",d=bu[c],e=.7;f.x=function(b){if(!arguments.length)return a;a=b;return f},f.y=function(a){if(!arguments.length)return b;b=a;return f},f.interpolate=function(a){if(!arguments.length)return c;d=bu[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var bu={linear:bv,"step-before":bw,"step-after":bx,basis:bC,"basis-closed"
<ide> :bD,cardinal:bz,"cardinal-closed":by},bF=[0,2/3,1/3,0],bG=[0,1/3,2/3,0],bH=[0,1/6,2/3,1/6];d3.svg.area=function(){function g(d){return d.length<1?null:"M"+e(br(this,d,a,c),f)+"L"+e(br(this,d,a,b).reverse(),f)+"Z"}var a=bs,b=bJ,c=bt,d="linear",e=bu[d],f=.7;g.x=function(b){if(!arguments.length)return a;a=b;return g},g.y0=function(a){if(!arguments.length)return b;b=a;return g},g.y1=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=bu[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bl,k=e.call(a,h,g)+bl;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=bK,b=bL,c=bM,d=bp,e=bq;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=bK,b=bL,c=bP;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.mouse=function(a){var b=(a.ownerSVGElement||a).createSVGPoint();if(bQ<0&&(window.scrollX||window.scrollY)){var c=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),d=c[0][0].getScreenCTM();bQ=!d.f&&!d.e,c.remove()}bQ?(b.x=d3.event.pageX,b.y=d3.event.pageY):(b.x=d3.event.clientX,b.y=d3.event.clientY),b=b.matrixTransform(a.getScreenCTM().inverse());return[b.x,b.y]};var bQ=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.symbol=function(){function c(c,d){return(bT[a.call(this,c,d)]||bT.circle)(b.call(this,c,d))}var a=bS,b=bR;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c},d3.svg.symbolTypes=["circle","cross","diamond","square","triangle-down","triangle-up"];var bT={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*bV)),c=b*bV;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/bU),c=b*bU/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/bU),c=b*bU/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}},bU=Math.sqrt(3),bV=Math.tan(30*Math.PI/180)})()
<ide>\ No newline at end of file
<ide><path>src/core/core.js
<del>d3 = {version: "1.14.0"}; // semver
<add>d3 = {version: "1.14.1"}; // semver
<ide><path>src/layout/force.js
<ide> d3.layout.force = function() {
<ide>
<ide> function dragmove() {
<ide> if (!d3_layout_forceDragNode) return;
<add> var parent = d3_layout_forceDragElement.parentNode;
<ide>
<ide> // O NOES! The drag element was removed from the DOM.
<del> if (!d3_layout_forceDragElement.parentNode) {
<add> if (!parent) {
<ide> d3_layout_forceDragNode.fixed = false;
<ide> d3_layout_forceDragNode = d3_layout_forceDragElement = null;
<ide> return;
<ide> }
<ide>
<del> var m = d3.svg.mouse(d3_layout_forceDragElement);
<add> var m = d3.svg.mouse(parent);
<ide> d3_layout_forceDragMoved = true;
<ide> d3_layout_forceDragNode.px = m[0];
<ide> d3_layout_forceDragNode.py = m[1]; | 6 |
PHP | PHP | each for validation of arrays | 66cf7f89405e583efab34ffeb3e07e5095c8e579 | <ide><path>src/Illuminate/Validation/Validator.php
<ide> public function sometimes($attribute, $rules, $callback)
<ide> }
<ide> }
<ide>
<add> /**
<add> * Define a set of rules that apply to each element in an array attribute.
<add> *
<add> * @param string $attribute
<add> * @param string|array $rules
<add> * @return void
<add> */
<add> public function each($attribute, $rules)
<add> {
<add> $data = array_get($this->data, $attribute);
<add>
<add> if ( ! is_array($data))
<add> {
<add> if ($this->hasRule($attribute, 'Array')) return;
<add>
<add> throw new \InvalidArgumentException('Attribute for each() must be an array.');
<add> }
<add>
<add> foreach ($data as $dataKey => $dataValue)
<add> {
<add> foreach ($rules as $ruleKey => $ruleValue)
<add> {
<add> $key = "$attribute.$dataKey.$ruleKey";
<add> $this->mergeRules($key, $ruleValue);
<add> }
<add> }
<add> }
<add>
<ide> /**
<ide> * Merge additional rules into a given attribute.
<ide> *
<ide> protected function getRule($attribute, $rules)
<ide> {
<ide> $rules = (array) $rules;
<ide>
<add> if ( ! array_key_exists($attribute, $this->rules))
<add> {
<add> return;
<add> }
<add>
<ide> foreach ($this->rules[$attribute] as $rule)
<ide> {
<ide> list($rule, $parameters) = $this->parseRule($rule);
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testExceptionThrownOnIncorrectParameterCount()
<ide> }
<ide>
<ide>
<add> public function testValidateEach()
<add> {
<add> $trans = $this->getRealTranslator();
<add> $data = ['foo' => [['field' => 5], ['field' => 10], ['field' => 15]]];
<add>
<add> $v = new Validator($trans, $data, ['foo' => 'array']);
<add> $v->each('foo', ['field' => 'numeric|min:6|max:14']);
<add> $this->assertFalse($v->passes());
<add>
<add> $v = new Validator($trans, $data, ['foo' => 'array']);
<add> $v->each('foo', ['field' => 'numeric|min:4|max:16']);
<add> $this->assertTrue($v->passes());
<add> }
<add>
<add>
<add> public function testValidateEachWithNonArrayWithArrayRule()
<add> {
<add> $trans = $this->getRealTranslator();
<add> $v = new Validator($trans, ['foo' => 'string'], ['foo' => 'array']);
<add> $v->each('foo', ['field' => 'min:7|max:13']);
<add> $this->assertFalse($v->passes());
<add> }
<add>
<add>
<add> /**
<add> * @expectedException InvalidArgumentException
<add> */
<add> public function testValidateEachWithNonArrayWithoutArrayRule()
<add> {
<add> $trans = $this->getRealTranslator();
<add> $v = new Validator($trans, ['foo' => 'string'], ['foo' => 'numeric']);
<add> $v->each('foo', ['field' => 'min:7|max:13']);
<add> $this->assertFalse($v->passes());
<add> }
<add>
<add>
<ide> protected function getTranslator()
<ide> {
<ide> return m::mock('Symfony\Component\Translation\TranslatorInterface'); | 2 |
Ruby | Ruby | extract latest_version string to a constant | f03a400e28f82813e65b02948a61c8b6f74a1d77 | <ide><path>Library/Homebrew/formula.rb
<ide> def test(&block)
<ide> def livecheck(&block)
<ide> return @livecheck unless block
<ide>
<add> include Homebrew::Livecheck::Constants
<ide> @livecheckable = true
<ide> @livecheck.instance_eval(&block)
<ide> end
<ide><path>Library/Homebrew/livecheck.rb
<ide> # typed: true
<ide> # frozen_string_literal: true
<ide>
<add>require "livecheck/constants"
<add>
<ide> # The {Livecheck} class implements the DSL methods used in a formula's, cask's
<ide> # or resource's `livecheck` block and stores related instance variables. Most
<ide> # of these methods also return the related instance variable when no argument
<ide> def url(val = nil)
<ide> end
<ide> end
<ide>
<del> # Returns a placeholder string that will be replaced with a formula's latest
<del> # version in livecheck URLs for its resources.
<del> # @return String
<del> def latest_version
<del> "<FORMULA_LATEST_VERSION>"
<del> end
<del>
<ide> delegate version: :@package_or_resource
<ide> delegate arch: :@package_or_resource
<ide> private :version, :arch
<ide><path>Library/Homebrew/livecheck/constants.rb
<add># typed: true
<add># frozen_string_literal: true
<add>
<add>module Homebrew
<add> module Livecheck
<add> # The {Constants} module provides constants that are intended to be used
<add> # in `livecheck` block values (e.g. `url`, `regex`).
<add> module Constants
<add> # A placeholder string used in resource `livecheck` block URLs that will
<add> # be replaced with the latest version from the main formula check.
<add> LATEST_VERSION = "<FORMULA_LATEST_VERSION>"
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/livecheck/livecheck.rb
<ide> # typed: true
<ide> # frozen_string_literal: true
<ide>
<add>require "livecheck/constants"
<ide> require "livecheck/error"
<ide> require "livecheck/livecheck_version"
<ide> require "livecheck/skip_conditions"
<ide> def resource_version(
<ide> checked_urls = []
<ide> # rubocop:disable Metrics/BlockLength
<ide> urls.each_with_index do |original_url, i|
<del> url = original_url.gsub(/<FORMULA_LATEST_VERSION>/, formula_latest)
<add> url = original_url.gsub(Constants::LATEST_VERSION, formula_latest)
<ide>
<ide> # Only preprocess the URL when it's appropriate
<ide> url = preprocess_url(url) unless STRATEGY_SYMBOLS_TO_SKIP_PREPROCESS_URL.include?(livecheck_strategy) | 4 |
Javascript | Javascript | use strict comparisons for fd | 06134e3598c1b3ae89d4be84466d532c249f5d9d | <ide><path>lib/net.js
<ide> function Socket(options) {
<ide> throw errnoException(err, 'open');
<ide>
<ide> this[async_id_symbol] = this._handle.getAsyncId();
<del> // options.fd can be string (since it is user-defined),
<del> // so changing this to === would be semver-major
<del> // See: https://github.com/nodejs/node/pull/11513
<del> // eslint-disable-next-line eqeqeq
<del> if ((fd == 1 || fd == 2) &&
<add>
<add> if ((fd === 1 || fd === 2) &&
<ide> (this._handle instanceof Pipe) &&
<ide> process.platform === 'win32') {
<ide> // Make stdout and stderr blocking on Windows | 1 |
PHP | PHP | fix return value | 4d1288aed662005cd1444ade9bee0d8695a7a176 | <ide><path>src/TestSuite/Stub/ConsoleOutput.php
<ide> class ConsoleOutput extends ConsoleOutputBase
<ide> *
<ide> * @param string|array $message A string or an array of strings to output
<ide> * @param int $newlines Number of newlines to append
<del> * @return true
<add> * @return false
<ide> */
<ide> public function write($message, int $newlines = 1)
<ide> {
<ide> public function write($message, int $newlines = 1)
<ide> $newlines--;
<ide> }
<ide>
<del> return true;
<add> return false;
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | set version in source for releases | 0f5f0c981aeedf56fa5b395029cc06b40c3ac2f1 | <ide><path>build/release.js
<add>var fs = require( "fs" );
<ide>
<ide> module.exports = function( Release ) {
<ide>
<ide> module.exports = function( Release ) {
<ide> "dist/jquery.min.map",
<ide> "dist/jquery.slim.js",
<ide> "dist/jquery.slim.min.js",
<del> "dist/jquery.slim.min.map"
<add> "dist/jquery.slim.min.map",
<add> "src/core.js"
<ide> ],
<ide> cdn = require( "./release/cdn" ),
<ide> dist = require( "./release/dist" ),
<ide> module.exports = function( Release ) {
<ide> checkRepoState: function( callback ) {
<ide> ensureSizzle( Release, callback );
<ide> },
<add> /**
<add> * Set the version in the src folder for distributing AMD
<add> */
<add> _setSrcVersion: function() {
<add> var corePath = __dirname + "/../src/core.js",
<add> contents = fs.readFileSync( corePath, "utf8" );
<add> contents = contents.replace( /@VERSION/g, Release.newVersion );
<add> fs.writeFileSync( corePath, contents, "utf8" );
<add> },
<ide> /**
<ide> * Generates any release artifacts that should be included in the release.
<ide> * The callback must be invoked with an array of files that should be
<ide> module.exports = function( Release ) {
<ide> "Grunt custom failed"
<ide> );
<ide> cdn.makeReleaseCopies( Release );
<add> Release._setSrcVersion();
<ide> callback( files );
<ide> },
<ide> /**
<ide><path>build/release/dist.js
<ide> module.exports = function( Release, files, complete ) {
<ide> shell.cp( "-rf", Release.dir.repo + "/" + file, Release.dir.dist );
<ide> } );
<ide>
<add> // Remove the wrapper from the dist repo
<add> shell.rm( "-f", Release.dir.dist + "/src/wrapper.js" );
<add>
<ide> // Write generated bower file
<ide> fs.writeFileSync( Release.dir.dist + "/bower.json", generateBower() );
<ide> | 2 |
Mixed | Ruby | handle paths with trailing slashes in rails test | 326d5027147c087c6f22a075c021ead3d496995e | <ide><path>railties/CHANGELOG.md
<add>* Allow relative paths with trailing slashes to be passed to `rails test`.
<add>
<add> *Eugene Kenny*
<add>
<ide> * Add `rack-mini-profiler` gem to the default `Gemfile`.
<ide>
<ide> `rack-mini-profiler` displays performance information such as SQL time and flame graphs.
<ide><path>railties/lib/rails/test_unit/runner.rb
<ide> def compose_filter(runnable, filter)
<ide> private
<ide> def extract_filters(argv)
<ide> # Extract absolute and relative paths but skip -n /.*/ regexp filters.
<del> argv.select { |arg| %r%^/?\w+/%.match?(arg) && !arg.end_with?("/") }.map do |path|
<add> argv.select { |arg| path_argument?(arg) && !regexp_filter?(arg) }.map do |path|
<ide> case
<ide> when /(:\d+)+$/.match?(path)
<ide> file, *lines = path.split(":")
<ide> def extract_filters(argv)
<ide> end
<ide> end
<ide> end
<add>
<add> def regexp_filter?(arg)
<add> arg.start_with?("/") && arg.end_with?("/")
<add> end
<add>
<add> def path_argument?(arg)
<add> %r%^/?\w+/%.match?(arg)
<add> end
<ide> end
<ide> end
<ide>
<ide><path>railties/test/application/test_runner_test.rb
<ide> def test_run_multiple_folders_with_absolute_paths
<ide> end
<ide> end
<ide>
<add> def test_run_relative_path_with_trailing_slash
<add> create_test_file :models, "account"
<add> create_test_file :controllers, "accounts_controller"
<add>
<add> run_test_command("test/models/").tap do |output|
<add> assert_match "AccountTest", output
<add> assert_match "1 runs, 1 assertions, 0 failures, 0 errors, 0 skips", output
<add> end
<add> end
<add>
<ide> def test_run_with_ruby_command
<ide> app_file "test/models/post_test.rb", <<-RUBY
<ide> require 'test_helper' | 3 |
Javascript | Javascript | remove cruft from scrollview | 2d43663ac8d1f3cd18e7244629b71881ce353a45 | <ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> const ScrollView = React.createClass({
<ide> },
<ide>
<ide> getScrollableNode: function(): any {
<del> // console.log('getScrollableNode: ', {ref: this._scrollViewRef, node: ReactNative.findNodeHandle(this._scrollViewRef)});
<ide> return ReactNative.findNodeHandle(this._scrollViewRef);
<ide> },
<ide> | 1 |
Java | Java | add script after setting scripts in rsrcdbpopultr | b4995f7e4f707da33434ecdafa6889a252ef7930 | <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.java
<ide> public void addScripts(Resource... scripts) {
<ide> */
<ide> public void setScripts(Resource... scripts) {
<ide> assertContentsOfScriptArray(scripts);
<del> this.scripts = Arrays.asList(scripts);
<add> // Ensure that the list is modifiable
<add> this.scripts = new ArrayList<Resource>(Arrays.asList(scripts));
<ide> }
<ide>
<ide> /**
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulatorTests.java
<ide> public class ResourceDatabasePopulatorTests {
<ide>
<ide> private static final Resource script1 = resource("script1");
<ide> private static final Resource script2 = resource("script2");
<add> private static final Resource script3 = resource("script3");
<ide>
<ide>
<ide> @Test(expected = IllegalArgumentException.class)
<ide> public void constructWithMulipleResources() {
<ide> assertEquals(2, databasePopulator.getScripts().size());
<ide> }
<ide>
<add> @Test
<add> public void constructWithMulipleResourcesAndThenAddScript() {
<add> ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(script1, script2);
<add> assertEquals(2, databasePopulator.getScripts().size());
<add>
<add> databasePopulator.addScript(script3);
<add> assertEquals(3, databasePopulator.getScripts().size());
<add> }
<add>
<ide> @Test(expected = IllegalArgumentException.class)
<ide> public void addScriptsWithNullResource() {
<ide> ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
<ide> public void setScriptsWithNullResourceArray() {
<ide> databasePopulator.setScripts((Resource[]) null);
<ide> }
<ide>
<add> @Test
<add> public void setScriptsAndThenAddScript() {
<add> ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
<add> assertEquals(0, databasePopulator.getScripts().size());
<add>
<add> databasePopulator.setScripts(script1, script2);
<add> assertEquals(2, databasePopulator.getScripts().size());
<add>
<add> databasePopulator.addScript(script3);
<add> assertEquals(3, databasePopulator.getScripts().size());
<add> }
<add>
<ide> private static Resource resource(String path) {
<ide> return new ClassPathResource(path);
<ide> } | 2 |
Python | Python | simplify helper (see ) [ci skip] | dd153b2b335143dfa4ee3618d8c736bbffecd7f6 | <ide><path>examples/information_extraction/entity_relations.py
<ide> def main(model="en_core_web_sm"):
<ide> print("{:<10}\t{}\t{}".format(r1.text, r2.ent_type_, r2.text))
<ide>
<ide>
<del>def filter_spans(spans, prefer_longest=True):
<add>def filter_spans(spans):
<ide> # Filter a sequence of spans so they don't contain overlaps
<ide> get_sort_key = lambda span: (span.end - span.start, span.start)
<del> sorted_spans = sorted(spans, key=get_sort_key, reverse=prefer_longest)
<add> sorted_spans = sorted(spans, key=get_sort_key, reverse=True)
<ide> result = []
<ide> seen_tokens = set()
<ide> for span in sorted_spans: | 1 |
Java | Java | adapt tests changed in 5.1.x to master | ff6ccd0d0433ff5f192d74590a63e3b8929220b5 | <ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/HttpHeadResponseDecoratorTests.java
<ide>
<ide> import io.netty.buffer.PooledByteBufAllocator;
<ide> import org.junit.After;
<del>import org.junit.Test;
<add>import org.junit.jupiter.api.Test;
<ide> import reactor.core.publisher.Flux;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.LeakAwareDataBufferFactory;
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
<ide>
<del>import static org.junit.Assert.assertEquals;
<add>import static org.assertj.core.api.Assertions.assertThat;
<ide>
<ide> /**
<ide> * Unit tests for {@link HttpHeadResponseDecorator}.
<ide> public void tearDown() {
<ide> @Test
<ide> public void write() {
<ide> Flux<DataBuffer> body = Flux.just(toDataBuffer("data1"), toDataBuffer("data2"));
<del> response.writeWith(body).block();
<del> assertEquals(10, response.getHeaders().getContentLength());
<add> this.response.writeWith(body).block();
<add> assertThat(this.response.getHeaders().getContentLength()).isEqualTo(10);
<ide> }
<ide>
<ide> @Test // gh-23484
<ide> public void writeWithGivenContentLength() {
<ide> int length = 15;
<ide> this.response.getHeaders().setContentLength(length);
<ide> this.response.writeWith(Flux.empty()).block();
<del> assertEquals(length, this.response.getHeaders().getContentLength());
<add> assertThat(this.response.getHeaders().getContentLength()).isEqualTo(length);
<ide> }
<ide>
<ide>
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/PathResourceResolverTests.java
<ide> private void testCheckResource(Resource location, String requestPath) throws IOE
<ide> public void ignoreInvalidEscapeSequence() throws IOException {
<ide> UrlResource location = new UrlResource(getClass().getResource("./test/"));
<ide> Resource resource = location.createRelative("test%file.txt");
<del> assertTrue(this.resolver.checkResource(resource, location));
<add> assertThat(this.resolver.checkResource(resource, location)).isTrue();
<ide> }
<ide>
<ide> @Test
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/PathResourceResolverTests.java
<ide> private void testCheckResource(Resource location, String requestPath) throws IOE
<ide> public void ignoreInvalidEscapeSequence() throws IOException {
<ide> UrlResource location = new UrlResource(getClass().getResource("./test/"));
<ide> Resource resource = location.createRelative("test%file.txt");
<del> assertTrue(this.resolver.checkResource(resource, location));
<add> assertThat(this.resolver.checkResource(resource, location)).isTrue();
<ide> }
<ide>
<ide> @Test | 3 |
Text | Text | incorporate latest round of feedback | 08fab27db52aa375df85a23e89799600f785b9d4 | <ide><path>guides/source/active_storage_overview.md
<ide> per-environment basis. To use the disk service from the previous example in the
<ide> development environment, you would add the following to
<ide> config/environments/development.rb:
<ide>
<del>In your application's configuration, specify the service to use like this:
<del>
<ide> ```ruby
<ide> # Store files locally.
<ide> config.active_storage.service = :local
<ide> config.active_storage.service = :s3
<ide> Continue reading for more information on the built-in service adapters (e.g.
<ide> `Disk` and `S3`) and the configuration they require.
<ide>
<add>Mirrored services can be used to facilitate a migration between services in
<add>production. You can start mirroring to the new service, copy existing files from
<add>the old service to the new, then go all-in on the new service.
<add>
<add>If you wish to transform your images, add `mini_magick` to your Gemfile:
<add>
<add>``` ruby
<add>gem 'mini_magick'
<add>```
<add>
<ide> ### Disk Service
<del>To use the Disk service:
<add>Declare a Disk service in `config/storage.yml`:
<ide>
<ide> ``` yaml
<ide> local:
<ide> local:
<ide> ```
<ide>
<ide> ### Amazon S3 Service
<add>Declare an S3 service in `config/storage.yml`:
<ide>
<del>To use Amazon S3:
<ide> ``` yaml
<ide> s3:
<ide> service: S3
<ide> Also, add the S3 client gem to your Gemfile:
<ide> gem "aws-sdk-s3", require: false
<ide> ```
<ide> ### Microsoft Azure Storage Service
<del>
<del>To use Microsoft Azure Storage:
<add>Declare an Azure Storage service in `config/storage.yml`:
<ide>
<ide> ``` yaml
<ide> azure:
<ide> gem "azure-storage", require: false
<ide> ```
<ide>
<ide> ### Google Cloud Storage Service
<del>
<del>To use Google Cloud Storage:
<add>Declare a Google Cloud Storage service in `config/storage.yml`:
<ide>
<ide> ``` yaml
<ide> google:
<ide> production:
<ide>
<ide> NOTE: Files are served from the primary service.
<ide>
<del>Mirrored services can be used to facilitate a migration between services in
<del>production. You can start mirroring to the new service, copy existing files from
<del>the old service to the new, then go all-in on the new service.
<del>
<del>If you wish to transform your images, add `mini_magick` to your Gemfile:
<del>
<del>``` ruby
<del>gem 'mini_magick'
<del>```
<del>
<ide> Attach Files to a Model
<ide> --------------------------
<del>One or more files can be attached to a model.
<ide>
<del>One attachment:
<add>### `has_one_attached`
<ide>
<del>```ruby
<add>The `has_one_attached` macro sets up a one-to-one mapping between records and
<add>files. Each record can have one file attached to it.
<add>
<add>For example, suppose your application has a User model. If you want each user to
<add>have an avatar, define the `User` model like this:
<add>
<add>``` ruby
<ide> class User < ApplicationRecord
<del> # Associates an attachment and a blob. When the user is destroyed they are
<del> # purged by default (models destroyed, and resource files deleted).
<ide> has_one_attached :avatar
<ide> end
<add>```
<ide>
<del># Attach an avatar to the user.
<del>user.avatar.attach(io: File.open("/path/to/face.jpg"), filename: "face.jpg", content_type: "image/jpg")
<add>You can create a user with an avatar:
<ide>
<del>class AvatarsController < ApplicationController
<del> def update
<del> # params[:avatar] contains a ActionDispatch::Http::UploadedFile object
<del> Current.user.avatar.attach(params.require(:avatar))
<del> redirect_to Current.user
<add>``` ruby
<add>class SignupController < ApplicationController
<add> def create
<add> user = Users.create!(user_params)
<add> session[:user_id] = user.id
<add> redirect_to root_path
<ide> end
<add>
<add> private
<add> def user_params
<add> params.require(:user).permit(:email_address, :password, :avatar)
<add> end
<ide> end
<ide> ```
<ide>
<del>Many attachments:
<add>Call `avatar.attach` to attach an avatar to an existing user:
<add>
<add>```ruby
<add>Current.user.avatar.attach(params[:avatar])
<add>```
<add>
<add>Call `avatar.attached?` to determine whether a particular user has an avatar:
<add>
<add>```ruby
<add>Current.user.avatar.attached?
<add>```
<add>
<add>### `has_many_attached`
<add>
<add>The `has_many_attached` macro sets up a one-to-many relationship between records
<add>and files. Each record can have many files attached to it.
<add>
<add>For example, suppose your application has a `Message` model. If you want each
<add>message to have many images, define the Message model like this:
<ide>
<ide> ```ruby
<ide> class Message < ApplicationRecord
<ide> has_many_attached :images
<ide> end
<ide> ```
<ide>
<del>```erb
<del><%= form_with model: @message, local: true do |form| %>
<del> <%= form.text_field :title, placeholder: "Title" %><br>
<del> <%= form.text_area :content %><br><br>
<del>
<del> <%= form.file_field :images, multiple: true %><br>
<del> <%= form.submit %>
<del><% end %>
<del>```
<add>You can create a message with images:
<ide>
<ide> ```ruby
<ide> class MessagesController < ApplicationController
<del> def index
<del> # Use the built-in with_attached_images scope to avoid N+1
<del> @messages = Message.all.with_attached_images
<del> end
<del>
<ide> def create
<ide> message = Message.create!(message_params)
<ide> redirect_to message
<ide> end
<ide>
<del> def show
<del> @message = Message.find(params[:id])
<del> end
<del>
<ide> private
<ide> def message_params
<ide> params.require(:message).permit(:title, :content, images: [])
<ide> end
<ide> end
<ide> ```
<ide>
<add>Call `images.attach` to add new images to an existing message:
<add>
<add>```ruby
<add>@message.images.attach(params[:images])
<add>```
<add>
<add>Call `images.attached?`` to determine whether a particular message has any images:
<add>
<add>```ruby
<add>@message.images.attached?
<add>```
<add>
<ide> Remove File Attached to Model
<ide> -------------------------------
<ide>
<ide> config.active_storage.service = :local_test
<ide> Add Support Additional Cloud Service
<ide> ------------------------------------
<ide>
<del>ActiveStorage ships with support for Amazon S3, Google Cloud Storage, and Azure.
<ide> If you need to support a cloud service other these, you will need to implement
<ide> the Service. Each service extends
<ide> [`ActiveStorage::Service`](https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/service.rb)
<ide> by implementing the methods necessary to upload and download files to the cloud.
<del>
<del>The easiest way to understand what's necessary is to examine the existing
<del>implementations.
<del>
<del>Some services are supported by community maintained gems:
<del>
<del>* [OpenStack](https://github.com/jeffreyguenther/activestorage-openstack) | 1 |
Javascript | Javascript | use const in bannerplugin | 8a95bcc2f45c2bfa26ae06e5fbf7a81f6dd37e69 | <ide><path>lib/BannerPlugin.js
<ide> class BannerPlugin {
<ide> }
<ide>
<ide> apply(compiler) {
<del> let options = this.options;
<del> let banner = this.banner;
<add> const options = this.options;
<add> const banner = this.banner;
<ide>
<ide> compiler.plugin("compilation", (compilation) => {
<ide> compilation.plugin("optimize-chunk-assets", (chunks, callback) => { | 1 |
Javascript | Javascript | await ctx.renderpage() in examples for typescript | fcc4d8cd50eb2170fda9fbac6f9853799ceb9959 | <ide><path>examples/with-cxs/pages/_document.js
<ide> import cxs from 'cxs/lite'
<ide>
<ide> export default class MyDocument extends Document {
<ide> static async getInitialProps({ renderPage }) {
<del> const page = renderPage()
<add> const page = await renderPage()
<ide> const style = cxs.getCss()
<ide> return { ...page, style }
<ide> }
<ide><path>examples/with-glamor/pages/_document.js
<ide> import { renderStatic } from 'glamor/server'
<ide>
<ide> class MyDocument extends Document {
<ide> static async getInitialProps({ renderPage }) {
<del> const page = renderPage()
<add> const page = await renderPage()
<ide> const { css, ids } = renderStatic(() => page.html || page.errorHtml)
<ide> return { ...page, css, ids }
<ide> }
<ide><path>examples/with-goober/pages/_document.js
<ide> import Document, { Head, Main, NextScript } from 'next/document'
<ide> import { extractCss } from 'goober'
<ide>
<ide> export default class MyDocument extends Document {
<del> static getInitialProps({ renderPage }) {
<del> const page = renderPage()
<del>
<add> static async getInitialProps({ renderPage }) {
<add> const page = await renderPage()
<ide> // Extrach the css for each page render
<ide> const css = extractCss()
<ide> return { ...page, css }
<ide><path>examples/with-react-native-web/pages/_document.js
<ide> export default class MyDocument extends Document {
<ide> static async getInitialProps({ renderPage }) {
<ide> AppRegistry.registerComponent(config.name, () => Main)
<ide> const { getStyleElement } = AppRegistry.getApplication(config.name)
<del> const page = renderPage()
<add> const page = await renderPage()
<ide> const styles = [
<ide> <style dangerouslySetInnerHTML={{ __html: normalizeNextElements }} />,
<ide> getStyleElement(),
<ide><path>examples/with-tailwindcss-emotion/pages/_document.js
<ide> import { extractCritical } from '@emotion/server'
<ide> export default class MyDocument extends Document {
<ide> static async getInitialProps(ctx) {
<ide> const initialProps = await Document.getInitialProps(ctx)
<del> const page = ctx.renderPage()
<add> const page = await ctx.renderPage()
<ide> const styles = extractCritical(page.html)
<ide> return { ...initialProps, ...page, ...styles }
<ide> }
<ide><path>examples/with-typestyle/pages/_document.js
<ide> import Document, { Head, Main, NextScript } from 'next/document'
<ide> import { getStyles } from 'typestyle'
<ide>
<ide> export default class MyDocument extends Document {
<del> static getInitialProps({ renderPage }) {
<del> const page = renderPage()
<add> static async getInitialProps({ renderPage }) {
<add> const page = await renderPage()
<ide> const styleTags = getStyles()
<ide> return { ...page, styleTags }
<ide> } | 6 |
Ruby | Ruby | remove unused `joinkeys` | d55120e4290820a862463dcd6b92cdfeb4b75a48 | <ide><path>activerecord/lib/active_record/reflection.rb
<ide> def class_name
<ide> @class_name ||= -(options[:class_name]&.to_s || derive_class_name)
<ide> end
<ide>
<del> JoinKeys = Struct.new(:key, :foreign_key) # :nodoc:
<del>
<ide> # Returns a list of scopes that should be applied for this Reflection
<ide> # object when querying the database.
<ide> def scopes | 1 |
PHP | PHP | rename $inner to $innerengine | 5d1d7260daab110705d533a4b06adbb47fdafbd3 | <ide><path>src/Cache/SimpleCacheEngine.php
<ide> class SimpleCacheEngine implements CacheInterface
<ide> *
<ide> * @param \Cake\Cache\CacheEngine
<ide> */
<del> protected $inner;
<add> protected $innerEngine;
<ide>
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param \Cake\Cache\CacheEngine $inner The decorated engine.
<add> * @param \Cake\Cache\CacheEngine $innerEngine The decorated engine.
<ide> */
<del> public function __construct($inner)
<add> public function __construct($innerEngine)
<ide> {
<del> $this->inner = $inner;
<add> $this->innerEngine = $innerEngine;
<ide> }
<ide>
<ide> /**
<ide> protected function checkKey($key)
<ide> public function get($key, $default = null)
<ide> {
<ide> $this->checkKey($key);
<del> $result = $this->inner->read($key);
<add> $result = $this->innerEngine->read($key);
<ide> if ($result === false) {
<ide> return $default;
<ide> }
<ide> public function set($key, $value, $ttl = null)
<ide> {
<ide> $this->checkKey($key);
<ide> if ($ttl !== null) {
<del> $restore = $this->inner->getConfig('duration');
<del> $this->inner->setConfig('duration', $ttl);
<add> $restore = $this->innerEngine->getConfig('duration');
<add> $this->innerEngine->setConfig('duration', $ttl);
<ide> }
<ide> try {
<del> $result = $this->inner->write($key, $value);
<add> $result = $this->innerEngine->write($key, $value);
<ide>
<ide> return (bool)$result;
<ide> } finally {
<ide> if (isset($restore)) {
<del> $this->inner->setConfig('duration', $restore);
<add> $this->innerEngine->setConfig('duration', $restore);
<ide> }
<ide> }
<ide> }
<ide> public function delete($key)
<ide> {
<ide> $this->checkKey($key);
<ide>
<del> return $this->inner->delete($key);
<add> return $this->innerEngine->delete($key);
<ide> }
<ide>
<ide> /**
<ide> public function delete($key)
<ide> */
<ide> public function clear()
<ide> {
<del> return $this->inner->clear(false);
<add> return $this->innerEngine->clear(false);
<ide> }
<ide>
<ide> /**
<ide> public function clear()
<ide> */
<ide> public function getMultiple($keys, $default = null)
<ide> {
<del> $results = $this->inner->readMany($keys);
<add> $results = $this->innerEngine->readMany($keys);
<ide> foreach ($results as $key => $value) {
<ide> if ($value === false) {
<ide> $results[$key] = $default;
<ide> public function getMultiple($keys, $default = null)
<ide> public function setMultiple($values, $ttl = null)
<ide> {
<ide> if ($ttl !== null) {
<del> $restore = $this->inner->getConfig('duration');
<del> $this->inner->setConfig('duration', $ttl);
<add> $restore = $this->innerEngine->getConfig('duration');
<add> $this->innerEngine->setConfig('duration', $ttl);
<ide> }
<ide> try {
<del> return $this->inner->writeMany($values);
<add> return $this->innerEngine->writeMany($values);
<ide> } finally {
<ide> if (isset($restore)) {
<del> $this->inner->setConfig('duration', $restore);
<add> $this->innerEngine->setConfig('duration', $restore);
<ide> }
<ide> }
<ide> }
<ide> public function setMultiple($values, $ttl = null)
<ide> */
<ide> public function deleteMultiple($keys)
<ide> {
<del> $result = $this->inner->deleteMany($keys);
<add> $result = $this->innerEngine->deleteMany($keys);
<ide> foreach ($result as $key => $success) {
<ide> if ($success === false) {
<ide> return false; | 1 |
Python | Python | fix bug in regression test for | 4c297e11801dd9a27a35179b8ae2058a6d1c948e | <ide><path>numpy/core/tests/test_regression.py
<ide> def test_misaligned_dot_product_objects(self):
<ide>
<ide> def test_byteswap_complex_scalar(self):
<ide> """Ticket #1259"""
<del> x = np.array([-1j], '<c8')
<del> y = x[0].byteswap()
<del> assert_equal(x, np.fromstring(y.tostring(), dtype='>c8'))
<add> z = np.array([-1j], '<c8')
<add> x = z[0] # always native-endian
<add> y = x.byteswap()
<add> if x.dtype.byteorder == z.dtype.byteorder:
<add> # little-endian machine
<add> assert_equal(x, np.fromstring(y.tostring(), dtype='>c8'))
<add> else:
<add> # big-endian machine
<add> assert_equal(x, np.fromstring(y.tostring(), dtype='<c8'))
<ide>
<ide> if __name__ == "__main__":
<ide> run_module_suite() | 1 |
Python | Python | add mape objective | 47fd945cf1bf9435ae2009df3338723b438a49b0 | <ide><path>keras/objectives.py
<ide> def mean_squared_error(y_true, y_pred):
<ide> def mean_absolute_error(y_true, y_pred):
<ide> return T.abs_(y_pred - y_true).mean(axis=-1)
<ide>
<add>def mean_absolute_percentage_error(y_true, y_pred):
<add> return T.abs_((y_true - y_pred) / y_true).mean() * 100
<add>
<ide> def mean_squared_logarithmic_error(y_true, y_pred):
<ide> return T.sqr(T.log(T.clip(y_pred, epsilon, np.inf) + 1.) - T.log(T.clip(y_true, epsilon, np.inf) + 1.)).mean(axis=-1)
<ide>
<ide> def binary_crossentropy(y_true, y_pred):
<ide> # aliases
<ide> mse = MSE = mean_squared_error
<ide> mae = MAE = mean_absolute_error
<add>mape = MAPE = mean_absolute_percentage_error
<ide> msle = MSLE = mean_squared_logarithmic_error
<ide>
<ide> from .utils.generic_utils import get_from_module | 1 |
PHP | PHP | fix coding style errors | 83d11002154fbb3296aa1bd7de7492db0336331d | <ide><path>lib/Cake/Database/Schema/BaseSchema.php
<ide> protected function _convertOnClause($clause) {
<ide> return Table::ACTION_SET_NULL;
<ide> }
<ide>
<del>
<ide> /**
<ide> * Generate the SQL to drop a table.
<ide> *
<ide><path>lib/Cake/Database/Schema/PostgresSchema.php
<ide> protected function _keySql($prefix, $data) {
<ide> return $prefix . ' (' . implode(', ', $columns) . ')';
<ide> }
<ide>
<del>
<ide> /**
<ide> * Generate the SQL to create a table.
<ide> * | 2 |
Python | Python | set default backend to tf | 82318263a1e270ff5412609964bfa31a886558e9 | <ide><path>keras/backend/__init__.py
<ide> if not os.path.exists(_keras_dir):
<ide> os.makedirs(_keras_dir)
<ide>
<del>_BACKEND = 'theano'
<add>_BACKEND = 'tensorflow'
<ide> _config_path = os.path.expanduser(os.path.join(_keras_dir, 'keras.json'))
<ide> if os.path.exists(_config_path):
<ide> _config = json.load(open(_config_path))
<ide><path>keras/backend/common.py
<ide> _FLOATX = 'float32'
<ide> _EPSILON = 10e-8
<ide> _UID_PREFIXES = defaultdict(int)
<del>_IMAGE_DIM_ORDERING = 'th'
<add>_IMAGE_DIM_ORDERING = 'tf'
<ide> _LEGACY_WEIGHT_ORDERING = False
<ide>
<ide>
<ide><path>keras/backend/tensorflow_backend.py
<ide> import tensorflow as tf
<ide> from tensorflow.python.training import moving_averages
<ide> try:
<del> import tensorflow.contrib.ctc as ctc
<add> import tensorflow.contrib.ctc as ctc
<ide> except ImportError:
<del> from tensorflow.python.ops import ctc_ops as ctc
<add> from tensorflow.python.ops import ctc_ops as ctc
<ide> import numpy as np
<ide> import os
<ide> import copy
<ide> def temporal_padding(x, padding=1):
<ide> return tf.pad(x, pattern)
<ide>
<ide>
<del>def spatial_2d_padding(x, padding=(1, 1), dim_ordering='th'):
<add>def spatial_2d_padding(x, padding=(1, 1), dim_ordering=_IMAGE_DIM_ORDERING):
<ide> '''Pads the 2nd and 3rd dimensions of a 4D tensor
<ide> with "padding[0]" and "padding[1]" (resp.) zeros left and right.
<ide> '''
<ide> def spatial_2d_padding(x, padding=(1, 1), dim_ordering='th'):
<ide> return tf.pad(x, pattern)
<ide>
<ide>
<del>def spatial_3d_padding(x, padding=(1, 1, 1), dim_ordering='th'):
<add>def spatial_3d_padding(x, padding=(1, 1, 1), dim_ordering=_IMAGE_DIM_ORDERING):
<ide> '''Pads 5D tensor with zeros for the depth, height, width dimension with
<ide> "padding[0]", "padding[1]" and "padding[2]" (resp.) zeros left and right
<ide>
<ide> def ctc_batch_cost(y_true, y_pred, input_length, label_length):
<ide>
<ide> y_pred = tf.log(tf.transpose(y_pred, perm=[1, 0, 2]) + 1e-8)
<ide>
<del> return tf.expand_dims(ctc.ctc_loss(inputs=y_pred,
<del> labels=sparse_labels,
<del> sequence_length=input_length), 1)
<add> return tf.expand_dims(ctc.ctc_loss(inputs=y_pred,
<add> labels=sparse_labels,
<add> sequence_length=input_length), 1)
<ide>
<ide>
<ide> def ctc_decode(y_pred, input_length, greedy=True, beam_width=100,
<ide> def ctc_decode(y_pred, input_length, greedy=True, beam_width=100,
<ide> input_length = tf.to_int32(input_length)
<ide>
<ide> if greedy:
<del> (decoded, log_prob) = ctc.ctc_greedy_decoder(
<add> (decoded, log_prob) = ctc.ctc_greedy_decoder(
<ide> inputs=y_pred,
<ide> sequence_length=input_length)
<ide> else:
<del> (decoded, log_prob) = ctc.ctc_beam_search_decoder(
<add> (decoded, log_prob) = ctc.ctc_beam_search_decoder(
<ide> inputs=y_pred,
<ide> sequence_length=input_length, beam_width=beam_width,
<ide> top_paths=top_paths)
<ide><path>keras/backend/theano_backend.py
<ide> def temporal_padding(x, padding=1):
<ide> return T.set_subtensor(output[:, padding:x.shape[1] + padding, :], x)
<ide>
<ide>
<del>def spatial_2d_padding(x, padding=(1, 1), dim_ordering='th'):
<add>def spatial_2d_padding(x, padding=(1, 1), dim_ordering=_IMAGE_DIM_ORDERING):
<ide> '''Pad the 2nd and 3rd dimensions of a 4D tensor
<ide> with "padding[0]" and "padding[1]" (resp.) zeros left and right.
<ide> '''
<ide> def spatial_2d_padding(x, padding=(1, 1), dim_ordering='th'):
<ide> return T.set_subtensor(output[indices], x)
<ide>
<ide>
<del>def spatial_3d_padding(x, padding=(1, 1, 1), dim_ordering='th'):
<add>def spatial_3d_padding(x, padding=(1, 1, 1), dim_ordering=_IMAGE_DIM_ORDERING):
<ide> '''Pad the 2nd, 3rd and 4th dimensions of a 5D tensor
<ide> with "padding[0]", "padding[1]" and "padding[2]" (resp.) zeros left and right.
<ide> '''
<ide> def separable_conv2d(x, depthwise_kernel, pointwise_kernel, strides=(1, 1),
<ide>
<ide>
<ide> def conv3d(x, kernel, strides=(1, 1, 1),
<del> border_mode='valid', dim_ordering='th',
<add> border_mode='valid', dim_ordering=_IMAGE_DIM_ORDERING,
<ide> volume_shape=None, filter_shape=None):
<ide> '''
<ide> Run on cuDNN if available.
<ide> def conv3d(x, kernel, strides=(1, 1, 1),
<ide>
<ide>
<ide> def pool2d(x, pool_size, strides=(1, 1), border_mode='valid',
<del> dim_ordering='th', pool_mode='max'):
<add> dim_ordering=_IMAGE_DIM_ORDERING, pool_mode='max'):
<ide> if border_mode == 'same':
<ide> w_pad = pool_size[0] - 2 if pool_size[0] % 2 == 1 else pool_size[0] - 1
<ide> h_pad = pool_size[1] - 2 if pool_size[1] % 2 == 1 else pool_size[1] - 1
<ide> def pool2d(x, pool_size, strides=(1, 1), border_mode='valid',
<ide>
<ide>
<ide> def pool3d(x, pool_size, strides=(1, 1, 1), border_mode='valid',
<del> dim_ordering='th', pool_mode='max'):
<add> dim_ordering=_IMAGE_DIM_ORDERING, pool_mode='max'):
<ide> if border_mode == 'same':
<ide> # TODO: add implementation for border_mode="same"
<ide> raise Exception('border_mode="same" not supported with Theano.')
<ide><path>tests/integration_tests/test_image_data_tasks.py
<ide> def test_image_classification():
<ide> with convolutional hidden layer.
<ide> '''
<ide> np.random.seed(1337)
<del> input_shape = (3, 16, 16)
<add> input_shape = (16, 16, 3)
<ide> (X_train, y_train), (X_test, y_test) = get_test_data(nb_train=500,
<ide> nb_test=200,
<ide> input_shape=input_shape,
<ide><path>tests/keras/backend/test_backends.py
<ide> def test_conv2d(self):
<ide> kernel_th = KTH.variable(convert_kernel(kernel_val))
<ide> kernel_tf = KTF.variable(kernel_val)
<ide>
<del> zth = KTH.eval(KTH.conv2d(xth, kernel_th))
<del> ztf = KTF.eval(KTF.conv2d(xtf, kernel_tf))
<add> zth = KTH.eval(KTH.conv2d(xth, kernel_th, dim_ordering='th'))
<add> ztf = KTF.eval(KTF.conv2d(xtf, kernel_tf, dim_ordering='th'))
<ide>
<ide> assert zth.shape == ztf.shape
<ide> assert_allclose(zth, ztf, atol=1e-05)
<ide> def test_conv3d(self):
<ide> kernel_th = KTH.variable(convert_kernel(kernel_val))
<ide> kernel_tf = KTF.variable(kernel_val)
<ide>
<del> zth = KTH.eval(KTH.conv3d(xth, kernel_th))
<del> ztf = KTF.eval(KTF.conv3d(xtf, kernel_tf))
<add> zth = KTH.eval(KTH.conv3d(xth, kernel_th, dim_ordering='th'))
<add> ztf = KTF.eval(KTF.conv3d(xtf, kernel_tf, dim_ordering='th'))
<ide>
<ide> assert zth.shape == ztf.shape
<ide> assert_allclose(zth, ztf, atol=1e-05)
<ide> def test_conv3d(self):
<ide> assert_allclose(zth, ztf, atol=1e-05)
<ide>
<ide> def test_pool2d(self):
<del> check_single_tensor_operation('pool2d', (5, 3, 10, 12), pool_size=(2, 2),
<add> check_single_tensor_operation('pool2d', (5, 10, 12, 3), pool_size=(2, 2),
<ide> strides=(1, 1), border_mode='valid')
<ide>
<del> check_single_tensor_operation('pool2d', (5, 3, 9, 11), pool_size=(2, 2),
<add> check_single_tensor_operation('pool2d', (5, 9, 11, 3), pool_size=(2, 2),
<ide> strides=(1, 1), border_mode='valid')
<ide>
<del> check_single_tensor_operation('pool2d', (5, 3, 9, 11), pool_size=(2, 3),
<add> check_single_tensor_operation('pool2d', (5, 9, 11, 3), pool_size=(2, 3),
<ide> strides=(1, 1), border_mode='valid')
<ide>
<ide> def test_pool3d(self):
<del> check_single_tensor_operation('pool3d', (5, 3, 10, 12, 5), pool_size=(2, 2, 2),
<add> check_single_tensor_operation('pool3d', (5, 10, 12, 5, 3), pool_size=(2, 2, 2),
<ide> strides=(1, 1, 1), border_mode='valid')
<ide>
<del> check_single_tensor_operation('pool3d', (5, 3, 9, 11, 5), pool_size=(2, 2, 2),
<add> check_single_tensor_operation('pool3d', (5, 9, 11, 5, 3), pool_size=(2, 2, 2),
<ide> strides=(1, 1, 1), border_mode='valid')
<ide>
<del> check_single_tensor_operation('pool3d', (5, 3, 9, 11, 5), pool_size=(2, 3, 2),
<add> check_single_tensor_operation('pool3d', (5, 9, 11, 5, 3), pool_size=(2, 3, 2),
<ide> strides=(1, 1, 1), border_mode='valid')
<ide>
<ide> def test_random_normal(self):
<ide><path>tests/keras/layers/test_convolutional.py
<ide> def test_convolution_2d():
<ide> 'nb_col': 3,
<ide> 'border_mode': border_mode,
<ide> 'subsample': subsample},
<del> input_shape=(nb_samples, stack_size, nb_row, nb_col))
<add> input_shape=(nb_samples, nb_row, nb_col, stack_size))
<ide>
<ide> layer_test(convolutional.Convolution2D,
<ide> kwargs={'nb_filter': nb_filter,
<ide> def test_convolution_2d():
<ide> 'b_regularizer': 'l2',
<ide> 'activity_regularizer': 'activity_l2',
<ide> 'subsample': subsample},
<del> input_shape=(nb_samples, stack_size, nb_row, nb_col))
<add> input_shape=(nb_samples, nb_row, nb_col, stack_size))
<ide>
<ide>
<ide> @keras_test
<ide> def test_deconvolution_2d():
<ide> kwargs={'nb_filter': nb_filter,
<ide> 'nb_row': 3,
<ide> 'nb_col': 3,
<del> 'output_shape': (nb_samples, nb_filter, rows, cols),
<add> 'output_shape': (nb_samples, rows, cols, nb_filter),
<ide> 'border_mode': border_mode,
<ide> 'subsample': subsample},
<del> input_shape=(nb_samples, stack_size, nb_row, nb_col),
<add> input_shape=(nb_samples, nb_row, nb_col, stack_size),
<ide> fixed_batch_size=True)
<ide>
<ide> layer_test(convolutional.Deconvolution2D,
<ide> kwargs={'nb_filter': nb_filter,
<ide> 'nb_row': 3,
<ide> 'nb_col': 3,
<del> 'output_shape': (nb_samples, nb_filter, rows, cols),
<add> 'output_shape': (nb_samples, rows, cols, nb_filter),
<ide> 'border_mode': border_mode,
<ide> 'W_regularizer': 'l2',
<ide> 'b_regularizer': 'l2',
<ide> 'activity_regularizer': 'activity_l2',
<ide> 'subsample': subsample},
<del> input_shape=(nb_samples, stack_size, nb_row, nb_col),
<add> input_shape=(nb_samples, nb_row, nb_col, stack_size),
<ide> fixed_batch_size=True)
<ide>
<ide>
<ide> def test_atrous_conv_2d():
<ide> 'border_mode': border_mode,
<ide> 'subsample': subsample,
<ide> 'atrous_rate': atrous_rate},
<del> input_shape=(nb_samples, stack_size, nb_row, nb_col))
<add> input_shape=(nb_samples, nb_row, nb_col, stack_size))
<ide>
<ide> layer_test(convolutional.AtrousConv2D,
<ide> kwargs={'nb_filter': nb_filter,
<ide> def test_atrous_conv_2d():
<ide> 'activity_regularizer': 'activity_l2',
<ide> 'subsample': subsample,
<ide> 'atrous_rate': atrous_rate},
<del> input_shape=(nb_samples, stack_size, nb_row, nb_col))
<add> input_shape=(nb_samples, nb_row, nb_col, stack_size))
<ide>
<ide>
<ide> @pytest.mark.skipif(K._BACKEND != 'tensorflow', reason="Requires TF backend")
<ide> def test_separable_conv_2d():
<ide> 'border_mode': border_mode,
<ide> 'subsample': subsample,
<ide> 'depth_multiplier': multiplier},
<del> input_shape=(nb_samples, stack_size, nb_row, nb_col))
<add> input_shape=(nb_samples, nb_row, nb_col, stack_size))
<ide>
<ide> layer_test(convolutional.SeparableConv2D,
<ide> kwargs={'nb_filter': nb_filter,
<ide> def test_separable_conv_2d():
<ide> 'depthwise_constraint': 'unitnorm',
<ide> 'subsample': subsample,
<ide> 'depth_multiplier': multiplier},
<del> input_shape=(nb_samples, stack_size, nb_row, nb_col))
<add> input_shape=(nb_samples, nb_row, nb_col, stack_size))
<ide>
<ide>
<ide> @keras_test
<ide> def test_maxpooling_2d():
<ide> kwargs={'strides': strides,
<ide> 'border_mode': 'valid',
<ide> 'pool_size': pool_size},
<del> input_shape=(3, 4, 11, 12))
<add> input_shape=(3, 11, 12, 4))
<ide>
<ide>
<ide> @keras_test
<ide> def test_averagepooling_2d():
<ide> kwargs={'strides': strides,
<ide> 'border_mode': border_mode,
<ide> 'pool_size': pool_size},
<del> input_shape=(3, 4, 11, 12))
<add> input_shape=(3, 11, 12, 4))
<ide>
<ide>
<ide> @keras_test
<ide> def test_convolution_3d():
<ide> 'kernel_dim3': kernel_dim3,
<ide> 'border_mode': border_mode,
<ide> 'subsample': subsample},
<del> input_shape=(nb_samples, stack_size,
<del> input_len_dim1, input_len_dim2, input_len_dim3))
<add> input_shape=(nb_samples,
<add> input_len_dim1, input_len_dim2, input_len_dim3,
<add> stack_size))
<ide>
<ide> layer_test(convolutional.Convolution3D,
<ide> kwargs={'nb_filter': nb_filter,
<ide> def test_convolution_3d():
<ide> 'b_regularizer': 'l2',
<ide> 'activity_regularizer': 'activity_l2',
<ide> 'subsample': subsample},
<del> input_shape=(nb_samples, stack_size,
<del> input_len_dim1, input_len_dim2, input_len_dim3))
<add> input_shape=(nb_samples,
<add> input_len_dim1, input_len_dim2, input_len_dim3,
<add> stack_size))
<ide>
<ide>
<ide> @keras_test
<ide> def test_zero_padding_2d():
<ide> input_nb_row = 11
<ide> input_nb_col = 12
<ide>
<del> input = np.ones((nb_samples, stack_size, input_nb_row, input_nb_col))
<add> input = np.ones((nb_samples, input_nb_row, input_nb_col, stack_size))
<ide>
<ide> # basic test
<ide> layer_test(convolutional.ZeroPadding2D,
<ide> def test_zero_padding_2d():
<ide>
<ide> out = K.eval(layer.output)
<ide> for offset in [0, 1, -1, -2]:
<add> assert_allclose(out[:, offset, :, :], 0.)
<ide> assert_allclose(out[:, :, offset, :], 0.)
<del> assert_allclose(out[:, :, :, offset], 0.)
<del> assert_allclose(out[:, :, 2:-2, 2:-2], 1.)
<add> assert_allclose(out[:, 2:-2, 2:-2, :], 1.)
<ide> layer.get_config()
<ide>
<ide>
<ide> def test_zero_padding_3d():
<ide> input_len_dim2 = 11
<ide> input_len_dim3 = 12
<ide>
<del> input = np.ones((nb_samples, stack_size, input_len_dim1,
<del> input_len_dim2, input_len_dim3))
<add> input = np.ones((nb_samples,
<add> input_len_dim1, input_len_dim2, input_len_dim3,
<add> stack_size))
<ide>
<ide> # basic test
<ide> layer_test(convolutional.ZeroPadding3D,
<ide> def test_zero_padding_3d():
<ide> layer.set_input(K.variable(input), shape=input.shape)
<ide> out = K.eval(layer.output)
<ide> for offset in [0, 1, -1, -2]:
<add> assert_allclose(out[:, offset, :, :, :], 0.)
<ide> assert_allclose(out[:, :, offset, :, :], 0.)
<ide> assert_allclose(out[:, :, :, offset, :], 0.)
<del> assert_allclose(out[:, :, :, :, offset], 0.)
<del> assert_allclose(out[:, :, 2:-2, 2:-2, 2:-2], 1.)
<add> assert_allclose(out[:, 2:-2, 2:-2, 2:-2, :], 1.)
<ide> layer.get_config()
<ide>
<ide>
<ide><path>tests/keras/layers/test_wrappers.py
<ide> def test_TimeDistributed():
<ide>
<ide> # test with Convolution2D
<ide> model = Sequential()
<del> model.add(wrappers.TimeDistributed(convolutional.Convolution2D(5, 2, 2, border_mode='same'), input_shape=(2, 3, 4, 4)))
<add> model.add(wrappers.TimeDistributed(convolutional.Convolution2D(5, 2, 2, border_mode='same'), input_shape=(2, 4, 4, 3)))
<ide> model.add(core.Activation('relu'))
<ide> model.compile(optimizer='rmsprop', loss='mse')
<del> model.train_on_batch(np.random.random((1, 2, 3, 4, 4)), np.random.random((1, 2, 5, 4, 4)))
<add> model.train_on_batch(np.random.random((1, 2, 4, 4, 3)), np.random.random((1, 2, 4, 4, 5)))
<ide>
<ide> model = model_from_json(model.to_json())
<ide> model.summary() | 8 |
Go | Go | use tabwriter to display usage in mflag | 77098d5b5bf8840a1179380b34aedb26139b9d65 | <ide><path>pkg/mflag/example/example.go
<ide> package main
<ide>
<ide> import (
<ide> "fmt"
<add>
<ide> flag "github.com/dotcloud/docker/pkg/mflag"
<ide> )
<ide>
<ide> func init() {
<ide> flag.IntVar(&i, []string{"-integer", "-number"}, -1, "a simple integer")
<ide> flag.StringVar(&str, []string{"s", "#hidden", "-string"}, "", "a simple string") //-s -hidden and --string will work, but -hidden won't be in the usage
<ide> flag.BoolVar(&h, []string{"h", "#help", "-help"}, false, "display the help")
<add> flag.StringVar(&str, []string{"mode"}, "mode1", "set the mode\nmode1: use the mode1\nmode2: use the mode2\nmode3: use the mode3")
<ide> flag.Parse()
<ide> }
<ide> func main() {
<ide> if h {
<ide> flag.PrintDefaults()
<add> } else {
<add> fmt.Printf("s/#hidden/-string: %s\n", str)
<add> fmt.Printf("b: %b\n", b)
<add> fmt.Printf("-bool: %b\n", b2)
<add> fmt.Printf("s/#hidden/-string(via lookup): %s\n", flag.Lookup("s").Value.String())
<add> fmt.Printf("ARGS: %v\n", flag.Args())
<ide> }
<del> fmt.Printf("s/#hidden/-string: %s\n", str)
<del> fmt.Printf("b: %b\n", b)
<del> fmt.Printf("-bool: %b\n", b2)
<del> fmt.Printf("s/#hidden/-string(via lookup): %s\n", flag.Lookup("s").Value.String())
<del> fmt.Printf("ARGS: %v\n", flag.Args())
<ide> }
<ide><path>pkg/mflag/flag.go
<ide> import (
<ide> "sort"
<ide> "strconv"
<ide> "strings"
<add> "text/tabwriter"
<ide> "time"
<ide> )
<ide>
<ide> func Set(name, value string) error {
<ide> // PrintDefaults prints, to standard error unless configured
<ide> // otherwise, the default values of all defined flags in the set.
<ide> func (f *FlagSet) PrintDefaults() {
<add> writer := tabwriter.NewWriter(f.out(), 20, 1, 3, ' ', 0)
<ide> f.VisitAll(func(flag *Flag) {
<del> format := " -%s=%s: %s\n"
<add> format := " -%s=%s"
<ide> if _, ok := flag.Value.(*stringValue); ok {
<ide> // put quotes on the value
<del> format = " -%s=%q: %s\n"
<add> format = " -%s=%q"
<ide> }
<ide> names := []string{}
<ide> for _, name := range flag.Names {
<ide> func (f *FlagSet) PrintDefaults() {
<ide> }
<ide> }
<ide> if len(names) > 0 {
<del> fmt.Fprintf(f.out(), format, strings.Join(names, ", -"), flag.DefValue, flag.Usage)
<add> fmt.Fprintf(writer, format, strings.Join(names, ", -"), flag.DefValue)
<add> for i, line := range strings.Split(flag.Usage, "\n") {
<add> if i != 0 {
<add> line = " " + line
<add> }
<add> fmt.Fprintln(writer, "\t", line)
<add> }
<add> // start := fmt.Sprintf(format, strings.Join(names, ", -"), flag.DefValue)
<add> // fmt.Fprintln(f.out(), start, strings.Replace(flag.Usage, "\n", "\n"+strings.Repeat(" ", len(start)+1), -1))
<ide> }
<ide> })
<add> writer.Flush()
<ide> }
<ide>
<ide> // PrintDefaults prints to standard error the default values of all defined command-line flags. | 2 |
Javascript | Javascript | fix inspect to not trigger dynamic properties | 6c68a9679b7589590440eb3b80315d0f5c25945c | <ide><path>lib/sys.js
<ide> var formatter = function(value, indent, parents) {
<ide> });
<ide> } else {
<ide> return formatObject(value, indent, parents, '{}', function(x, f) {
<del> return f(x) + ': ' + f(value[x]);
<add> var child;
<add> if (value.__lookupGetter__(x)) {
<add> if (value.__lookupSetter__(x)) {
<add> child = "[Dynamic Property]";
<add> } else {
<add> child = "[Dynamic Property Read-only]";
<add> }
<add> } else {
<add> if (value.__lookupSetter__(x)) {
<add> child = "[Dynamic Property Write-only]";
<add> } else {
<add> child = f(value[x]);
<add> }
<add> }
<add> return f(x) + ': ' + child;
<ide> });
<ide> }
<ide> return buffer;
<ide> var formatter = function(value, indent, parents) {
<ide> var formatObject = function(obj, indent, parents, parenthesis, entryFormatter) {
<ide> var buffer = parenthesis[0];
<ide> var values = [];
<add> var x;
<ide>
<ide> var localFormatter = function(value) {
<ide> return formatter(value, indent + ' ', parents);
<ide><path>test/mjsunit/test-sys.js
<ide> assert.equal('{\n "a": 1,\n "b": 2\n}', inspect({a: 1, b: 2}));
<ide> assert.equal('{\n "a": {}\n}', inspect({'a': {}}));
<ide> assert.equal('{\n "a": {\n "b": 2\n }\n}', inspect({'a': {'b': 2}}));
<ide>
<add>// Dynamic properties
<add>assert.equal(
<add> "{\n \"readonly\": [Dynamic Property Read-only],\n \"readwrite\": [Dynamic Property],\n \"writeonly\": [Dynamic Property Write-only]\n}",
<add> inspect({get readonly() {return 1;},get readwrite(){return 2;},set readwrite(value){},set writeonly(val){}})
<add>);
<add>
<ide> var value = {};
<ide> value['a'] = value;
<ide> assert.equal('{\n "a": [Circular]\n}', inspect(value));
<ide> value = Object.create([]);
<ide> value.push(1);
<del>assert.equal('{\n "0": 1,\n "length": 1\n}', inspect(value));
<ide>\ No newline at end of file
<add>assert.equal('{\n "0": 1,\n "length": 1\n}', inspect(value));
<add>
<add>// Array with dynamic properties
<add>value = [1,2,3];
<add>value.__defineGetter__('growingLength', function () { this.push(true); return this.length; });
<add>assert.equal(
<add> "{\n \"0\": 1,\n \"1\": 2,\n \"2\": 3,\n \"growingLength\": [Dynamic Property Read-only]\n}",
<add> inspect(value)
<add>);
<ide>\ No newline at end of file | 2 |
Javascript | Javascript | allow custom separator | 13f31602f396bc269076ab4d389cfd8ca94b20ba | <ide><path>src/directive/input.js
<ide> var requiredDirective = [function() {
<ide> * Text input that converts between comma-seperated string into an array of strings.
<ide> *
<ide> * @element input
<add> * @param {string=} ng-list optional delimiter that should be used to split the value. If
<add> * specified in form `/something/` then the value will be converted into a regular expression.
<ide> *
<ide> * @example
<ide> <doc:example>
<ide> var ngListDirective = function() {
<ide> return {
<ide> require: 'ngModel',
<ide> link: function(scope, element, attr, ctrl) {
<add> var match = /\/(.*)\//.exec(attr.ngList),
<add> separator = match && new RegExp(match[1]) || attr.ngList || ',';
<add>
<ide> var parse = function(viewValue) {
<ide> var list = [];
<ide>
<ide> if (viewValue) {
<del> forEach(viewValue.split(/\s*,\s*/), function(value) {
<del> if (value) list.push(value);
<add> forEach(viewValue.split(separator), function(value) {
<add> if (value) list.push(trim(value));
<ide> });
<ide> }
<ide>
<ide><path>test/directive/inputSpec.js
<ide> describe('input', function() {
<ide> changeInputValueTo('');
<ide> expect(scope.list).toEqual([]);
<ide> });
<add>
<add>
<add> it('should allow custom separator', function() {
<add> compileInput('<input type="text" ng-model="list" ng-list=":" />');
<add>
<add> changeInputValueTo('a,a');
<add> expect(scope.list).toEqual(['a,a']);
<add>
<add> changeInputValueTo('a:b');
<add> expect(scope.list).toEqual(['a', 'b']);
<add> });
<add>
<add>
<add> it('should allow regexp as a separator', function() {
<add> compileInput('<input type="text" ng-model="list" ng-list="/:|,/" />');
<add>
<add> changeInputValueTo('a,b');
<add> expect(scope.list).toEqual(['a', 'b']);
<add>
<add> changeInputValueTo('a,b: c');
<add> expect(scope.list).toEqual(['a', 'b', 'c']);
<add> });
<ide> });
<ide>
<ide> describe('required', function() { | 2 |
Python | Python | remove unused check | d03f4fb6afb477c0661458b4f808258381b0acbc | <ide><path>research/object_detection/meta_architectures/faster_rcnn_meta_arch.py
<ide> def _predict_rpn_proposals(self, rpn_box_predictor_features):
<ide> """
<ide> num_anchors_per_location = (
<ide> self._first_stage_anchor_generator.num_anchors_per_location())
<del> # if len(num_anchors_per_location) != 1:
<del> # raise RuntimeError('anchor_generator is expected to generate anchors '
<del> # 'corresponding to a single feature map.')
<add>
<ide> if self._first_stage_box_predictor.is_keras_model:
<ide> box_predictions = self._first_stage_box_predictor(
<ide> rpn_box_predictor_features) | 1 |
Ruby | Ruby | exclude the cache from `brew list --unbrewed` | ff5f3f6b6da9874b79e0f6405778de91839128d0 | <ide><path>Library/Homebrew/cmd/list.rb
<ide> def list
<ide> def list_unbrewed
<ide> dirs = HOMEBREW_PREFIX.children.select{ |pn| pn.directory? }.map{ |pn| pn.basename.to_s }
<ide> dirs -= %w[Library Cellar .git]
<add>
<add> # Exclude the cache, if it has been located under the prefix
<add> cache_folder = (HOMEBREW_CACHE.relative_path_from(HOMEBREW_PREFIX)).to_s
<add> dirs -= [cache_folder]
<add>
<ide> cd HOMEBREW_PREFIX
<ide> exec 'find', *dirs + %w[-type f ( ! -iname .ds_store ! -iname brew ! -iname brew-man.1 ! -iname brew.1 )]
<ide> end | 1 |
Java | Java | fix minor javadoc mistakes | e54ea2d4906b9bcf1c4932d0f5695e5bb62d1595 | <ide><path>src/main/java/io/reactivex/rxjava3/core/Flowable.java
<ide> public static Flowable<Long> timer(long delay, @NonNull TimeUnit unit, @NonNull
<ide>
<ide> /**
<ide> * Create a {@code Flowable} by wrapping a {@link Publisher} <em>which has to be implemented according
<del> * to the <em>Reactive Streams</em> specification by handling backpressure and
<add> * to the <b>Reactive Streams</b> specification by handling backpressure and
<ide> * cancellation correctly; no safeguards are provided by the {@code Flowable} itself</em>.
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> public final <K, V> Flowable<GroupedFlowable<K, V>> groupBy(@NonNull Function<?
<ide> *
<ide> * // Emit 1000 items but ensure that the
<ide> * // internal map never has more than 3 items in it
<del> * {@code Flowable}
<add> * Flowable
<ide> * .range(1, 1000)
<ide> * // note that number of keys is 10
<ide> * .groupBy(x -> x % 10, x -> x, true, 16, evictingMapFactory)
<ide> public final Flowable<T> throttleLast(long intervalDuration, @NonNull TimeUnit u
<ide> * Returns a {@code Flowable} that emits only the last item emitted by the source {@link Publisher} during sequential
<ide> * time windows of a specified duration, where the duration is governed by a specified {@link Scheduler}.
<ide> * <p>
<del> * This differs from {@link #throttleFirst} in that this ticks along at a scheduled interval whereas
<del> * {@link #throttleFirst} does not tick, it just tracks the passage of time.
<add> * This differs from {@link #throttleFirst(long, TimeUnit, Scheduler)} in that this ticks along at a scheduled interval whereas
<add> * {@code throttleFirst} does not tick, it just tracks the passage of time.
<ide> * <p>
<ide> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleLast.s.png" alt="">
<ide> * <dl>
<ide><path>src/main/java/io/reactivex/rxjava3/core/Observable.java
<ide> public final Stream<T> blockingStream() {
<ide> * stream.limit(3).forEach(System.out::println);
<ide> * }
<ide> * </code></pre>
<add> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code blockingStream} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl> | 2 |
Javascript | Javascript | remove noinline directives from new commit phase | 1b96ee444e544cc4797bbbd8dee249ff02d62279 | <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js
<ide> function safelyCallComponentWillUnmount(current, instance) {
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function safelyDetachRef(current: Fiber) {
<ide> const ref = current.ref;
<ide> if (ref !== null) {
<ide> export function safelyCallDestroy(current: Fiber, destroy: () => void) {
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function commitHookEffectListUnmount(flags: HookFlags, finishedWork: Fiber) {
<ide> const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any);
<ide> const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
<ide> function commitHookEffectListUnmount(flags: HookFlags, finishedWork: Fiber) {
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function commitHookEffectListMount(flags: HookFlags, finishedWork: Fiber) {
<ide> const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any);
<ide> const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
<ide> function iterativelyCommitBeforeMutationEffects_complete() {
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function commitBeforeMutationEffectsOnFiber(finishedWork: Fiber) {
<ide> const current = finishedWork.alternate;
<ide> const flags = finishedWork.flags;
<ide> function commitBeforeMutationEffectsOnFiber(finishedWork: Fiber) {
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function commitBeforeMutationEffectsDeletions(deletions: Array<Fiber>) {
<ide> for (let i = 0; i < deletions.length; i++) {
<ide> const fiber = deletions[i];
<ide> function iterativelyCommitMutationEffects_complete(
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function commitMutationEffectsOnFiber(
<ide> fiber: Fiber,
<ide> root: FiberRoot,
<ide> function commitMutationEffectsOnFiber(
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function commitMutationEffectsDeletions(
<ide> deletions: Array<Fiber>,
<ide> root: FiberRoot,
<ide> function commitLayoutEffectsOnFiber(
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function commitLayoutEffectsForProfiler(
<ide> finishedWork: Fiber,
<ide> finishedRoot: FiberRoot,
<ide> function commitLayoutEffectsForProfiler(
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function commitLayoutEffectsForClassComponent(finishedWork: Fiber) {
<ide> const instance = finishedWork.stateNode;
<ide> const current = finishedWork.alternate;
<ide> function commitLayoutEffectsForClassComponent(finishedWork: Fiber) {
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function commitLayoutEffectsForHostRoot(finishedWork: Fiber) {
<ide> // TODO: I think this is now always non-null by the time it reaches the
<ide> // commit phase. Consider removing the type check.
<ide> function commitLayoutEffectsForHostRoot(finishedWork: Fiber) {
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function commitLayoutEffectsForHostComponent(finishedWork: Fiber) {
<ide> const instance: Instance = finishedWork.stateNode;
<ide> const current = finishedWork.alternate;
<ide> function commitLayoutEffectsForHostComponent(finishedWork: Fiber) {
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function hideOrUnhideAllChildren(finishedWork, isHidden) {
<ide> if (supportsMutation) {
<ide> // We only have the top Fiber that was inserted but we need to recurse down its
<ide> function commitSuspenseComponent(finishedWork: Fiber) {
<ide> }
<ide> }
<ide>
<del>/** @noinline */
<ide> function commitSuspenseHydrationCallbacks(
<ide> finishedRoot: FiberRoot,
<ide> finishedWork: Fiber, | 1 |
Javascript | Javascript | update api docs for arraycontroller and arrayproxy | f44c29a8f62eb548a3ae402f5efbf2310c469d3a | <ide><path>packages/ember-runtime/lib/controllers/array_controller.js
<ide> require('ember-runtime/system/array_proxy');
<ide> /**
<ide> @class
<ide>
<del> Ember.ArrayController provides a way for you to publish an array of objects for
<del> Ember.CollectionView or other controllers to work with. To work with an
<del> ArrayController, set the content property to the array you want the controller
<del> to manage. Then work directly with the controller object as if it were the
<del> array itself.
<add> Ember.ArrayController provides a way for you to publish a collection of objects
<add> so that you can easily bind to the collection from a Handlebars #each helper,
<add> an Ember.CollectionView, or other controllers.
<add>
<add> The advantage of using an ArrayController is that you only have to set up
<add> your view bindings once; to change what's displayed, simply swap out the
<add> `content` property on the controller.
<ide>
<ide> For example, imagine you wanted to display a list of items fetched via an XHR
<ide> request. Create an Ember.ArrayController and set its `content` property:
<ide> require('ember-runtime/system/array_proxy');
<ide>
<ide> Then, create a view that binds to your new controller:
<ide>
<del> {{#each MyApp.listController}}
<del> {{firstName}} {{lastName}}
<del> {{/each}}
<add> {{#each MyApp.listController}}
<add> {{firstName}} {{lastName}}
<add> {{/each}}
<ide>
<del> The advantage of using an array controller is that you only have to set up
<del> your view bindings once; to change what's displayed, simply swap out the
<del> `content` property on the controller.
<add> Although you are binding to the controller, the behavior of this controller
<add> is to pass through any methods or properties to the underlying array. This
<add> capability comes from `Ember.ArrayProxy`, which this class inherits from.
<add>
<add> Note: As of this writing, `ArrayController` does not add any functionality
<add> to its superclass, `ArrayProxy`. The Ember team plans to add additional
<add> controller-specific functionality in the future, e.g. single or multiple
<add> selection support. If you are creating something that is conceptually a
<add> controller, use this class.
<ide>
<ide> @extends Ember.ArrayProxy
<ide> */
<ide><path>packages/ember-runtime/lib/system/array_proxy.js
<ide> var get = Ember.get, set = Ember.set;
<ide> @class
<ide>
<ide> An ArrayProxy wraps any other object that implements Ember.Array and/or
<del> Ember.MutableArray, forwarding all requests. ArrayProxy isn't useful by itself
<del> but you can extend it to do specialized things like transforming values,
<del> etc.
<add> Ember.MutableArray, forwarding all requests. This makes it very useful for
<add> a number of binding use cases or other cases where being able to swap
<add> out the underlying array is useful.
<add>
<add> A simple example of usage:
<add>
<add> var pets = ['dog', 'cat', 'fish'];
<add> var arrayProxy = Ember.ArrayProxy.create({ content: Ember.A(pets) });
<add> ap.get('firstObject'); // => 'dog'
<add> ap.set('content', ['amoeba', 'paramecium']);
<add> ap.get('firstObject'); // => 'amoeba'
<add>
<add> This class can also be useful as a layer to transform the contents of
<add> an array, as they are accessed. This can be done by overriding
<add> `objectAtContent`:
<add>
<add> var pets = ['dog', 'cat', 'fish'];
<add> var ap = Ember.ArrayProxy.create({
<add> content: Ember.A(pets),
<add> objectAtContent: function(idx) {
<add> return this.get('content').objectAt(idx).toUpperCase();
<add> }
<add> });
<add> ap.get('firstObject'); // => 'DOG'
<add>
<ide>
<ide> @extends Ember.Object
<ide> @extends Ember.Array
<ide> Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray,
<ide> /** @scope Ember.ArrayProxy.prototype */ {
<ide>
<ide> /**
<del> The content array. Must be an object that implements Ember.Array and or
<add> The content array. Must be an object that implements Ember.Array and/or
<ide> Ember.MutableArray.
<ide>
<ide> @property {Ember.Array}
<ide> Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray,
<ide>
<ide> /**
<ide> Should actually retrieve the object at the specified index from the
<del> content. You can override this method in subclasses to transform the
<add> content. You can override this method in subclasses to transform the
<ide> content item to something new.
<ide>
<ide> This method will only be called if content is non-null.
<ide> Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray,
<ide> get(this, 'content').replace(idx, amt, objects);
<ide> },
<ide>
<add> /**
<add> Invoked when the content property is about to change. Notifies observers that the
<add> entire array content will change.
<add> */
<ide> contentWillChange: Ember.beforeObserver(function() {
<ide> var content = get(this, 'content'),
<ide> len = content ? get(content, 'length') : 0;
<ide> Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray,
<ide> this.arrayContentDidChange(idx, removedCnt, addedCnt);
<ide> },
<ide>
<add> /** @private (nodoc) */
<ide> init: function() {
<ide> this._super();
<ide> this.contentDidChange(); | 2 |
Text | Text | add guidance on testing new errors | 9ab63d61f8f8d65b0e0643c83dd7936c4cf0a309 | <ide><path>doc/guides/using-internal-errors.md
<ide> for the error code should be added to the `doc/api/errors.md` file. This will
<ide> give users a place to go to easily look up the meaning of individual error
<ide> codes.
<ide>
<add>## Testing new errors
<add>
<add>When adding a new error, corresponding test(s) for the error message
<add>formatting may also be required. If the messasge for the error is a
<add>constant string then no test is required for the error message formatting
<add>as we can trust the error helper implementation. An example of this kind of
<add>error would be:
<add>
<add>```js
<add>E('ERR_SOCKET_ALREADY_BOUND', 'Socket is already bound');
<add>```
<add>
<add>If the error message is not a constant string then tests to validate
<add>the formatting of the message based on the parameters used when
<add>creating the error should be added to
<add>`test/parallel/test-internal-errors.js`. These tests should validate
<add>all of the different ways parameters can be used to generate the final
<add>message string. A simple example is:
<add>
<add>```js
<add>// Test ERR_TLS_CERT_ALTNAME_INVALID
<add>assert.strictEqual(
<add> errors.message('ERR_TLS_CERT_ALTNAME_INVALID', ['altname']),
<add> 'Hostname/IP does not match certificate\'s altnames: altname');
<add>```
<add>
<add>In addition, there should also be tests which validate the use of the
<add>error based on where it is used in the codebase. For these tests, except in
<add>special cases, they should only validate that the expected code is received
<add>and NOT validate the message. This will reduce the amount of test change
<add>required when the message for an error changes.
<add>
<add>For example:
<add>
<add>```js
<add>assert.throws(() => {
<add> socket.bind();
<add>}, common.expectsError({
<add> code: 'ERR_SOCKET_ALREADY_BOUND',
<add> type: Error
<add>}));
<add>```
<add>
<add>Avoid changing the format of the message after the error has been created.
<add>If it does make sense to do this for some reason, then additional tests
<add>validating the formatting of the error message for those cases will
<add>likely be required.
<ide>
<ide> ## API
<ide> | 1 |
Ruby | Ruby | push key_generator into serializedcookiejars | 72889a6be4ec4afd68d3e4c3ae972099e080478a | <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> def signed_or_encrypted
<ide> def upgrade_legacy_signed_cookies?
<ide> request.secret_token.present? && request.secret_key_base.present?
<ide> end
<del>
<del> def key_generator
<del> request.key_generator
<del> end
<ide> end
<ide>
<ide> # Passing the ActiveSupport::MessageEncryptor::NullSerializer downstream
<ide> def serializer
<ide> def digest
<ide> request.cookies_digest || 'SHA1'
<ide> end
<add>
<add> def key_generator
<add> request.key_generator
<add> end
<ide> end
<ide>
<ide> class SignedCookieJar < AbstractCookieJar # :nodoc: | 1 |
Javascript | Javascript | add strict equalities in src/display/api.js | a4b06d7a0297525519e116741930d061be28d63a | <ide><path>src/display/api.js
<ide> var PDFPageProxy = (function PDFPageProxyClosure() {
<ide> // this call to render.
<ide> this.pendingDestroy = false;
<ide>
<del> var renderingIntent = ('intent' in params ?
<del> (params.intent == 'print' ? 'print' : 'display') : 'display');
<add> var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
<ide>
<ide> if (!this.intentStates[renderingIntent]) {
<ide> this.intentStates[renderingIntent] = {};
<ide> var WorkerTransport = (function WorkerTransportClosure() {
<ide> messageHandler.on('JpegDecode', function(data) {
<ide> var imageUrl = data[0];
<ide> var components = data[1];
<del> if (components != 3 && components != 1) {
<add> if (components !== 3 && components !== 1) {
<ide> return Promise.reject(
<ide> new Error('Only 3 components or 1 component can be returned'));
<ide> }
<ide> var WorkerTransport = (function WorkerTransportClosure() {
<ide> var data = tmpCtx.getImageData(0, 0, width, height).data;
<ide> var i, j;
<ide>
<del> if (components == 3) {
<add> if (components === 3) {
<ide> for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
<ide> buf[j] = data[i];
<ide> buf[j + 1] = data[i + 1];
<ide> buf[j + 2] = data[i + 2];
<ide> }
<del> } else if (components == 1) {
<add> } else if (components === 1) {
<ide> for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
<ide> buf[j] = data[i];
<ide> } | 1 |
Ruby | Ruby | remove dead code | 7a2622bcbd1937dd2862d27fa18258198de7a153 | <ide><path>actionview/lib/action_view/template.rb
<ide> def #{method_name}(local_assigns, output_buffer)
<ide> raise WrongEncodingError.new(@source, Encoding.default_internal)
<ide> end
<ide>
<del> begin
<del> mod.module_eval(source, identifier, 0)
<del> ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
<del> rescue => e # errors from template code
<del> if logger = (view && view.logger)
<del> logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
<del> logger.debug "Function body: #{source}"
<del> logger.debug "Backtrace: #{e.backtrace.join("\n")}"
<del> end
<del>
<del> raise ActionView::Template::Error.new(self, e)
<del> end
<add> mod.module_eval(source, identifier, 0)
<add> ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
<ide> end
<ide>
<ide> def handle_render_error(view, e) #:nodoc: | 1 |
Javascript | Javascript | use correct case for javascript | 6bf978404e0348ba05b1ab98307ca8c8cb9574d2 | <ide><path>src/core/xfa/som.js
<ide> function parseExpression(expr, dotDotAllowed, noExpr = true) {
<ide> return null;
<ide> }
<ide> // TODO:
<del> // Javascript expression: should be a boolean operation with a path
<add> // JavaScript expression: should be a boolean operation with a path
<ide> // so maybe we can have our own parser for that stuff or
<ide> // maybe use the formcalc one.
<ide> operator = operators.dotParen;
<ide><path>src/license_header_libre.js
<ide> /**
<ide> * @licstart The following is the entire license notice for the
<del> * Javascript code in this page
<add> * JavaScript code in this page
<ide> *
<ide> * Copyright 2022 Mozilla Foundation
<ide> *
<ide> * limitations under the License.
<ide> *
<ide> * @licend The above is the entire license notice for the
<del> * Javascript code in this page
<add> * JavaScript code in this page
<ide> */ | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.