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 |
|---|---|---|---|---|---|
Ruby | Ruby | allow nil return from strategy blocks | a970780851dc048be35323b4798406b82528609e | <ide><path>Library/Homebrew/livecheck/strategy/apache.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/bitbucket.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/cpan.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/electron_builder.rb
<ide> def self.match?(url)
<ide> sig {
<ide> params(
<ide> content: String,
<del> block: T.nilable(T.proc.params(arg0: Hash).returns(String)),
<add> block: T.nilable(T.proc.params(arg0: T::Hash[String, T.untyped]).returns(T.nilable(String))),
<ide> ).returns(T.nilable(String))
<ide> }
<ide> def self.version_from_content(content, &block)
<ide> require "yaml"
<ide>
<del> return unless (yaml = YAML.safe_load(content))
<add> yaml = YAML.safe_load(content)
<add> return if yaml.blank?
<ide>
<ide> if block
<del> value = block.call(yaml)
<del> return value if value.is_a?(String)
<del>
<del> raise TypeError, "Return value of `strategy :electron_builder` block must be a string."
<add> case (value = block.call(yaml))
<add> when String
<add> return value
<add> when nil
<add> return
<add> else
<add> raise TypeError, "Return value of `strategy :electron_builder` block must be a string."
<add> end
<ide> end
<ide>
<ide> yaml["version"]
<ide> def self.version_from_content(content, &block)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: Hash).returns(String)),
<add> block: T.nilable(T.proc.params(arg0: T::Hash[String, T.untyped]).returns(T.nilable(String))),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/extract_plist.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: Cask::Cask,
<del> block: T.nilable(T.proc.params(arg0: T::Hash[String, Item]).returns(String)),
<add> block: T.nilable(T.proc.params(arg0: T::Hash[String, Item]).returns(T.nilable(String))),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask:, &block)
<ide> def self.find_versions(url, regex, cask:, &block)
<ide> versions = unversioned_cask_checker.all_versions.transform_values { |v| Item.new(bundle_version: v) }
<ide>
<ide> if block
<del> match = block.call(versions)
<del>
<del> unless T.unsafe(match).is_a?(String)
<add> case (value = block.call(versions))
<add> when String
<add> match_data[:matches][value] = Version.new(value)
<add> when nil
<add> return match_data
<add> else
<ide> raise TypeError, "Return value of `strategy :extract_plist` block must be a string."
<ide> end
<del>
<del> match_data[:matches][match] = Version.new(match) if match
<ide> elsif versions.any?
<ide> versions.each_value do |item|
<ide> version = item.bundle_version.nice_version
<ide><path>Library/Homebrew/livecheck/strategy/git.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: T::Array[String])
<del> .returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: T::Array[String]).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide> value.each do |tag|
<ide> match_data[:matches][tag] = Version.new(tag)
<ide> end
<add> when nil
<add> return match_data
<ide> else
<ide> raise TypeError, "Return value of `strategy :git` block must be a string or array of strings."
<ide> end
<ide><path>Library/Homebrew/livecheck/strategy/github_latest.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/gnome.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/gnu.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/hackage.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/header_match.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: T::Hash[String, String])
<del> .returns(T.any(T::Array[String], String))),
<add> block: T.nilable(T.proc.params(arg0: T::Hash[String, String]).returns(T.nilable(String))),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide> # Merge the headers from all responses into one hash
<ide> merged_headers = headers.reduce(&:merge)
<ide>
<del> if block
<del> match = yield merged_headers, regex
<add> version = if block
<add> case (value = block.call(merged_headers, regex))
<add> when String
<add> value
<add> when nil
<add> return match_data
<add> else
<add> raise TypeError, "Return value of `strategy :header_match` block must be a string."
<add> end
<ide> else
<del> match = nil
<add> value = nil
<ide>
<ide> if (filename = merged_headers["content-disposition"])
<ide> if regex
<del> match ||= filename[regex, 1]
<add> value ||= filename[regex, 1]
<ide> else
<ide> v = Version.parse(filename, detected_from_url: true)
<del> match ||= v.to_s unless v.null?
<add> value ||= v.to_s unless v.null?
<ide> end
<ide> end
<ide>
<ide> if (location = merged_headers["location"])
<ide> if regex
<del> match ||= location[regex, 1]
<add> value ||= location[regex, 1]
<ide> else
<ide> v = Version.parse(location, detected_from_url: true)
<del> match ||= v.to_s unless v.null?
<add> value ||= v.to_s unless v.null?
<ide> end
<ide> end
<add>
<add> value
<ide> end
<ide>
<del> match_data[:matches][match] = Version.new(match) if match
<add> match_data[:matches][version] = Version.new(version) if version
<ide>
<ide> match_data
<ide> end
<ide><path>Library/Homebrew/livecheck/strategy/launchpad.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/npm.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/page_match.rb
<ide> def self.match?(url)
<ide> # @param regex [Regexp] a regex used for matching versions in the
<ide> # content
<ide> # @return [Array]
<add> sig {
<add> params(
<add> content: String,
<add> regex: Regexp,
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<add> ).returns(T::Array[String])
<add> }
<ide> def self.page_matches(content, regex, &block)
<ide> if block
<ide> case (value = block.call(content, regex))
<ide> when String
<ide> return [value]
<ide> when Array
<del> return value
<add> return value.compact.uniq
<add> when nil
<add> return []
<ide> else
<ide> raise TypeError, "Return value of `strategy :page_match` block must be a string or array of strings."
<ide> end
<ide> def self.page_matches(content, regex, &block)
<ide> case match
<ide> when String
<ide> match
<del> else
<add> when Array
<ide> match.first
<ide> end
<del> end.uniq
<add> end.compact.uniq
<ide> end
<ide>
<ide> # Checks the content at the URL for new versions, using the provided
<ide> def self.page_matches(content, regex, &block)
<ide> sig {
<ide> params(
<ide> url: String,
<del> regex: T.nilable(Regexp),
<add> regex: Regexp,
<ide> cask: T.nilable(Cask::Cask),
<ide> provided_content: T.nilable(String),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, provided_content: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/pypi.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/sourceforge.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/livecheck/strategy/sparkle.rb
<ide> def self.item_from_content(content)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: Item).returns(String)),
<add> block: T.nilable(T.proc.params(arg0: Item).returns(T.nilable(String))),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide> content = match_data.delete(:content)
<ide>
<ide> if (item = item_from_content(content))
<del> match = if block
<del> value = block.call(item)
<del>
<del> unless T.unsafe(value).is_a?(String)
<add> version = if block
<add> case (value = block.call(item))
<add> when String
<add> value
<add> when nil
<add> return match_data
<add> else
<ide> raise TypeError, "Return value of `strategy :sparkle` block must be a string."
<ide> end
<del>
<del> value
<ide> else
<ide> item.bundle_version&.nice_version
<ide> end
<ide>
<del> match_data[:matches][match] = Version.new(match) if match
<add> match_data[:matches][version] = Version.new(version) if version
<ide> end
<ide>
<ide> match_data
<ide><path>Library/Homebrew/livecheck/strategy/xorg.rb
<ide> def self.match?(url)
<ide> url: String,
<ide> regex: T.nilable(Regexp),
<ide> cask: T.nilable(Cask::Cask),
<del> block: T.nilable(T.proc.params(arg0: String).returns(T.any(T::Array[String], String))),
<add> block: T.nilable(
<add> T.proc.params(arg0: String, arg1: Regexp).returns(T.any(String, T::Array[String], NilClass)),
<add> ),
<ide> ).returns(T::Hash[Symbol, T.untyped])
<ide> }
<ide> def self.find_versions(url, regex, cask: nil, &block)
<ide><path>Library/Homebrew/test/livecheck/strategy/electron_builder_spec.rb
<ide>
<ide> expect(version).to eq "1.2.4"
<ide> end
<add>
<add> it "allows a nil return from a strategy block" do
<add> expect(electron_builder.version_from_content(electron_builder_yaml) { next }).to eq(nil)
<add> end
<add>
<add> it "errors on an invalid return type from a strategy block" do
<add> expect { electron_builder.version_from_content(electron_builder_yaml) { 123 } }
<add> .to raise_error(TypeError, "Return value of `strategy :electron_builder` block must be a string.")
<add> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/livecheck/strategy/page_match_spec.rb
<ide> end
<ide>
<ide> it "finds matching text in page content using a strategy block" do
<del> expect(page_match.page_matches(page_content, regex) { |content| content.scan(regex).map(&:first).uniq })
<add> expect(page_match.page_matches(page_content, regex) { |content, regex| content.scan(regex).map(&:first).uniq })
<ide> .to eq(page_content_matches)
<ide> end
<add>
<add> it "allows a nil return from a strategy block" do
<add> expect(page_match.page_matches(page_content, regex) { next }).to eq([])
<add> end
<ide> end
<ide>
<ide> describe "::find_versions?" do | 20 |
Python | Python | increase default logging period 5x | 793232fe762b7e7c27fd9da88596babb1721500d | <ide><path>keras/utils/generic_utils.py
<ide> class Progbar(object):
<ide> interval: Minimum visual progress update interval (in seconds).
<ide> """
<ide>
<del> def __init__(self, target, width=30, verbose=1, interval=0.01):
<add> def __init__(self, target, width=30, verbose=1, interval=0.05):
<ide> self.width = width
<ide> self.target = target
<ide> self.sum_values = {} | 1 |
Python | Python | remove dependency of roberta in blenderbot | 4824741c4cc3aeb04929a41b8c89b2b1fc57fca6 | <ide><path>src/transformers/models/blenderbot/tokenization_blenderbot.py
<ide> # limitations under the License.
<ide> """Tokenization class for Blenderbot."""
<ide>
<del>from typing import TYPE_CHECKING, List, Optional
<add>import json
<add>import os
<add>from functools import lru_cache
<add>from typing import TYPE_CHECKING, List, Optional, Tuple
<ide>
<add>import regex as re
<add>
<add>from ...tokenization_utils import AddedToken, PreTrainedTokenizer
<ide> from ...utils import logging
<del>from ..roberta.tokenization_roberta import RobertaTokenizer
<ide>
<ide>
<ide> if TYPE_CHECKING:
<ide> PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"facebook/blenderbot-3B": 128}
<ide>
<ide>
<del>class BlenderbotTokenizer(RobertaTokenizer):
<del> r"""
<del> Construct a Blenderbot tokenizer.
<add>@lru_cache()
<add># Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
<add>def bytes_to_unicode():
<add> """
<add> Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
<add> characters the bpe code barfs on.
<add>
<add> The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
<add> if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
<add> decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
<add> tables between utf-8 bytes and unicode strings.
<add> """
<add> bs = (
<add> list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
<add> )
<add> cs = bs[:]
<add> n = 0
<add> for b in range(2**8):
<add> if b not in bs:
<add> bs.append(b)
<add> cs.append(2**8 + n)
<add> n += 1
<add> cs = [chr(n) for n in cs]
<add> return dict(zip(bs, cs))
<add>
<add>
<add># Copied from transformers.models.roberta.tokenization_roberta.get_pairs
<add>def get_pairs(word):
<add> """
<add> Return set of symbol pairs in a word.
<add>
<add> Word is represented as tuple of symbols (symbols being variable-length strings).
<add> """
<add> pairs = set()
<add> prev_char = word[0]
<add> for char in word[1:]:
<add> pairs.add((prev_char, char))
<add> prev_char = char
<add> return pairs
<add>
<add>
<add>class BlenderbotTokenizer(PreTrainedTokenizer):
<add> """
<add> Constructs a Blenderbot tokenizer, derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding.
<add>
<add> This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
<add> be encoded differently whether it is at the beginning of the sentence (without space) or not:
<add>
<add> ```
<add> >>> from transformers import BlenderbotTokenizer
<add> >>> tokenizer = BlenderbotTokenizer.from_pretrained("facebook/blenderbot-3B")
<add> >>> tokenizer("Hello world")['input_ids']
<add> [6950, 1085, 2]
<add> >>> tokenizer(" Hello world")['input_ids']
<add> [6950, 1085, 2]
<add> ```
<add>
<add> You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
<add> call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
<ide>
<del> [`Blenderbot`] is nearly identical to [`RobertaTokenizer`] and runs end-to-end tokenization: punctuation splitting
<del> and wordpiece. The only difference is that it doesn't add BOS token to the beginning of sequences.
<add> <Tip>
<ide>
<del> Refer to superclass [`RobertaTokenizer`] for usage examples and documentation concerning parameters.
<add> When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
<add>
<add> </Tip>
<add>
<add> This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
<add> this superclass for more information regarding those methods.
<add>
<add> Args:
<add> vocab_file (`str`):
<add> Path to the vocabulary file.
<add> merges_file (`str`):
<add> Path to the merges file.
<add> errors (`str`, *optional*, defaults to `"replace"`):
<add> Paradigm to follow when decoding bytes to UTF-8. See
<add> [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
<add> bos_token (`str`, *optional*, defaults to `"<s>"`):
<add> The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
<add>
<add> <Tip>
<add>
<add> When building a sequence using special tokens, this is not the token that is used for the beginning of
<add> sequence. The token used is the `cls_token`.
<add>
<add> </Tip>
<add>
<add> eos_token (`str`, *optional*, defaults to `"</s>"`):
<add> The end of sequence token.
<add>
<add> <Tip>
<add>
<add> When building a sequence using special tokens, this is not the token that is used for the end of sequence.
<add> The token used is the `sep_token`.
<add>
<add> </Tip>
<add>
<add> sep_token (`str`, *optional*, defaults to `"</s>"`):
<add> The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
<add> sequence classification or for a text and a question for question answering. It is also used as the last
<add> token of a sequence built with special tokens.
<add> cls_token (`str`, *optional*, defaults to `"<s>"`):
<add> The classifier token which is used when doing sequence classification (classification of the whole sequence
<add> instead of per-token classification). It is the first token of the sequence when built with special tokens.
<add> unk_token (`str`, *optional*, defaults to `"<unk>"`):
<add> The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
<add> token instead.
<add> pad_token (`str`, *optional*, defaults to `"<pad>"`):
<add> The token used for padding, for example when batching sequences of different lengths.
<add> mask_token (`str`, *optional*, defaults to `"<mask>"`):
<add> The token used for masking values. This is the token used when training this model with masked language
<add> modeling. This is the token which the model will try to predict.
<add> add_prefix_space (`bool`, *optional*, defaults to `False`):
<add> Whether or not to add an initial space to the input. This allows to treat the leading word just as any
<add> other word. (Blenderbot tokenizer detect beginning of words by the preceding space).
<ide> """
<add>
<ide> vocab_files_names = VOCAB_FILES_NAMES
<ide> pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
<ide> max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
<add> model_input_names = ["input_ids", "attention_mask"]
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.__init__ with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def __init__(
<add> self,
<add> vocab_file,
<add> merges_file,
<add> errors="replace",
<add> bos_token="<s>",
<add> eos_token="</s>",
<add> sep_token="</s>",
<add> cls_token="<s>",
<add> unk_token="<unk>",
<add> pad_token="<pad>",
<add> mask_token="<mask>",
<add> add_prefix_space=False,
<add> **kwargs
<add> ):
<add> bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
<add> eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
<add> sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
<add> cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
<add> unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
<add> pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
<add>
<add> # Mask token behave like a normal word, i.e. include the space before it
<add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
<add>
<add> super().__init__(
<add> errors=errors,
<add> bos_token=bos_token,
<add> eos_token=eos_token,
<add> unk_token=unk_token,
<add> sep_token=sep_token,
<add> cls_token=cls_token,
<add> pad_token=pad_token,
<add> mask_token=mask_token,
<add> add_prefix_space=add_prefix_space,
<add> **kwargs,
<add> )
<add>
<add> with open(vocab_file, encoding="utf-8") as vocab_handle:
<add> self.encoder = json.load(vocab_handle)
<add> self.decoder = {v: k for k, v in self.encoder.items()}
<add> self.errors = errors # how to handle errors in decoding
<add> self.byte_encoder = bytes_to_unicode()
<add> self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
<add> with open(merges_file, encoding="utf-8") as merges_handle:
<add> bpe_merges = merges_handle.read().split("\n")[1:-1]
<add> bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
<add> self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
<add> self.cache = {}
<add> self.add_prefix_space = add_prefix_space
<add>
<add> # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
<add> self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
<add>
<add> @property
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def vocab_size(self):
<add> return len(self.encoder)
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_vocab with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def get_vocab(self):
<add> return dict(self.encoder, **self.added_tokens_encoder)
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.bpe with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def bpe(self, token):
<add> if token in self.cache:
<add> return self.cache[token]
<add> word = tuple(token)
<add> pairs = get_pairs(word)
<add>
<add> if not pairs:
<add> return token
<add>
<add> while True:
<add> bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
<add> if bigram not in self.bpe_ranks:
<add> break
<add> first, second = bigram
<add> new_word = []
<add> i = 0
<add> while i < len(word):
<add> try:
<add> j = word.index(first, i)
<add> except ValueError:
<add> new_word.extend(word[i:])
<add> break
<add> else:
<add> new_word.extend(word[i:j])
<add> i = j
<add>
<add> if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
<add> new_word.append(first + second)
<add> i += 2
<add> else:
<add> new_word.append(word[i])
<add> i += 1
<add> new_word = tuple(new_word)
<add> word = new_word
<add> if len(word) == 1:
<add> break
<add> else:
<add> pairs = get_pairs(word)
<add> word = " ".join(word)
<add> self.cache[token] = word
<add> return word
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._tokenize with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def _tokenize(self, text):
<add> """Tokenize a string."""
<add> bpe_tokens = []
<add> for token in re.findall(self.pat, text):
<add> token = "".join(
<add> self.byte_encoder[b] for b in token.encode("utf-8")
<add> ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
<add> bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
<add> return bpe_tokens
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_token_to_id with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def _convert_token_to_id(self, token):
<add> """Converts a token (str) in an id using the vocab."""
<add> return self.encoder.get(token, self.encoder.get(self.unk_token))
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_id_to_token with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def _convert_id_to_token(self, index):
<add> """Converts an index (integer) in a token (str) using the vocab."""
<add> return self.decoder.get(index)
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.convert_tokens_to_string with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def convert_tokens_to_string(self, tokens):
<add> """Converts a sequence of tokens (string) in a single string."""
<add> text = "".join(tokens)
<add> text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
<add> return text
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.save_vocabulary with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
<add> if not os.path.isdir(save_directory):
<add> logger.error(f"Vocabulary path ({save_directory}) should be a directory")
<add> return
<add> vocab_file = os.path.join(
<add> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
<add> )
<add> merge_file = os.path.join(
<add> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
<add> )
<add>
<add> with open(vocab_file, "w", encoding="utf-8") as f:
<add> f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
<add>
<add> index = 0
<add> with open(merge_file, "w", encoding="utf-8") as writer:
<add> writer.write("#version: 0.2\n")
<add> for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
<add> if index != token_index:
<add> logger.warning(
<add> f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
<add> " Please check that the tokenizer is not corrupted!"
<add> )
<add> index = token_index
<add> writer.write(" ".join(bpe_tokens) + "\n")
<add> index += 1
<add>
<add> return vocab_file, merge_file
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_special_tokens_mask with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def get_special_tokens_mask(
<add> self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
<add> ) -> List[int]:
<add> """
<add> Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
<add> special tokens using the tokenizer `prepare_for_model` method.
<add>
<add> Args:
<add> token_ids_0 (`List[int]`):
<add> List of IDs.
<add> token_ids_1 (`List[int]`, *optional*):
<add> Optional second list of IDs for sequence pairs.
<add> already_has_special_tokens (`bool`, *optional*, defaults to `False`):
<add> Whether or not the token list is already formatted with special tokens for the model.
<add>
<add> Returns:
<add> `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
<add> """
<add> if already_has_special_tokens:
<add> return super().get_special_tokens_mask(
<add> token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
<add> )
<add>
<add> if token_ids_1 is None:
<add> return [1] + ([0] * len(token_ids_0)) + [1]
<add> return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.create_token_type_ids_from_sequences with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def create_token_type_ids_from_sequences(
<add> self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
<add> ) -> List[int]:
<add> """
<add> Create a mask from the two sequences passed to be used in a sequence-pair classification task. Blenderbot does
<add> not make use of token type ids, therefore a list of zeros is returned.
<add>
<add> Args:
<add> token_ids_0 (`List[int]`):
<add> List of IDs.
<add> token_ids_1 (`List[int]`, *optional*):
<add> Optional second list of IDs for sequence pairs.
<add>
<add> Returns:
<add> `List[int]`: List of zeros.
<add> """
<add> sep = [self.sep_token_id]
<add> cls = [self.cls_token_id]
<add>
<add> if token_ids_1 is None:
<add> return len(cls + token_ids_0 + sep) * [0]
<add> return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.prepare_for_tokenization with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
<add> add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
<add> if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
<add> text = " " + text
<add> return (text, kwargs)
<ide>
<ide> def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None):
<ide> """
<ide> Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
<ide> adding special tokens. A Blenderbot sequence has the following format:
<del>
<ide> - single sequence: ` X </s>`
<del>
<ide> Args:
<ide> token_ids_0 (`List[int]`):
<ide> List of IDs to which the special tokens will be added
<ide> token_ids_1 (`List[int]`, *optional*):
<ide> Will be ignored
<del>
<ide> Returns:
<ide> `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
<ide> """
<ide> def _build_conversation_input_ids(self, conversation: "Conversation") -> List[in
<ide> input_ids = input_ids[-self.model_max_length :]
<ide> logger.warning(f"Trimmed input from conversation as it was longer than {self.model_max_length} tokens.")
<ide> return input_ids
<del>
<del>
<del>def get_pairs(word):
<del> """
<del> Return set of symbol pairs in a word.
<del>
<del> Word is represented as tuple of symbols (symbols being variable-length strings).
<del> """
<del> pairs = set()
<del> prev_char = word[0]
<del> for char in word[1:]:
<del> pairs.add((prev_char, char))
<del> prev_char = char
<del>
<del> pairs = set(pairs)
<del> return pairs
<ide><path>src/transformers/models/blenderbot/tokenization_blenderbot_fast.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide> """Fast Tokenization class for Blenderbot."""
<add>import json
<add>from typing import TYPE_CHECKING, List, Optional, Tuple
<ide>
<del>from typing import TYPE_CHECKING, List, Optional
<add>from tokenizers import pre_tokenizers, processors
<ide>
<add>from ...tokenization_utils_base import AddedToken, BatchEncoding
<add>from ...tokenization_utils_fast import PreTrainedTokenizerFast
<ide> from ...utils import logging
<del>from ..roberta.tokenization_roberta_fast import RobertaTokenizerFast
<ide> from .tokenization_blenderbot import BlenderbotTokenizer
<ide>
<ide>
<ide> PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"facebook/blenderbot-3B": 128}
<ide>
<ide>
<del>class BlenderbotTokenizerFast(RobertaTokenizerFast):
<del> r"""
<del> Construct a "fast" Blenderbot tokenizer (backed by HuggingFace's *tokenizers* library).
<add>class BlenderbotTokenizerFast(PreTrainedTokenizerFast):
<add> """
<add> Construct a "fast" Blenderbot tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2
<add> tokenizer, using byte-level Byte-Pair-Encoding.
<add>
<add> This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
<add> be encoded differently whether it is at the beginning of the sentence (without space) or not:
<add>
<add> ```
<add> >>> from transformers import BlenderbotTokenizerFast
<add> >>> tokenizer = BlenderbotTokenizerFast.from_pretrained("facebook/blenderbot-3B")
<add> >>> tokenizer("Hello world")['input_ids']
<add> [6950, 1085, 2]
<add> >>> tokenizer(" Hello world")['input_ids']
<add> [6950, 1085, 2]
<add> ```
<add>
<add> You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
<add> call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
<add>
<add> <Tip>
<add>
<add> When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
<add>
<add> </Tip>
<add>
<add> This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
<add> refer to this superclass for more information regarding those methods.
<add>
<add> Args:
<add> vocab_file (`str`):
<add> Path to the vocabulary file.
<add> merges_file (`str`):
<add> Path to the merges file.
<add> errors (`str`, *optional*, defaults to `"replace"`):
<add> Paradigm to follow when decoding bytes to UTF-8. See
<add> [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
<add> bos_token (`str`, *optional*, defaults to `"<s>"`):
<add> The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
<add>
<add> <Tip>
<add>
<add> When building a sequence using special tokens, this is not the token that is used for the beginning of
<add> sequence. The token used is the `cls_token`.
<add>
<add> </Tip>
<add>
<add> eos_token (`str`, *optional*, defaults to `"</s>"`):
<add> The end of sequence token.
<ide>
<del> [`BlenderbotFast`] is nearly identical to [`RobertaTokenizerFast`] and runs end-to-end tokenization: punctuation
<del> splitting and wordpiece. The only difference is that it doesn't add BOS token to the beginning of sequences.
<add> <Tip>
<ide>
<del> Refer to superclass [`RobertaTokenizerFast`] for usage examples and documentation concerning parameters.
<add> When building a sequence using special tokens, this is not the token that is used for the end of sequence.
<add> The token used is the `sep_token`.
<add>
<add> </Tip>
<add>
<add> sep_token (`str`, *optional*, defaults to `"</s>"`):
<add> The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
<add> sequence classification or for a text and a question for question answering. It is also used as the last
<add> token of a sequence built with special tokens.
<add> cls_token (`str`, *optional*, defaults to `"<s>"`):
<add> The classifier token which is used when doing sequence classification (classification of the whole sequence
<add> instead of per-token classification). It is the first token of the sequence when built with special tokens.
<add> unk_token (`str`, *optional*, defaults to `"<unk>"`):
<add> The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
<add> token instead.
<add> pad_token (`str`, *optional*, defaults to `"<pad>"`):
<add> The token used for padding, for example when batching sequences of different lengths.
<add> mask_token (`str`, *optional*, defaults to `"<mask>"`):
<add> The token used for masking values. This is the token used when training this model with masked language
<add> modeling. This is the token which the model will try to predict.
<add> add_prefix_space (`bool`, *optional*, defaults to `False`):
<add> Whether or not to add an initial space to the input. This allows to treat the leading word just as any
<add> other word. (Blenderbot tokenizer detect beginning of words by the preceding space).
<add> trim_offsets (`bool`, *optional*, defaults to `True`):
<add> Whether the post processing step should trim offsets to avoid including whitespaces.
<ide> """
<add>
<ide> vocab_files_names = VOCAB_FILES_NAMES
<ide> pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
<ide> max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
<add> model_input_names = ["input_ids", "attention_mask"]
<ide> slow_tokenizer_class = BlenderbotTokenizer
<ide>
<add> # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.__init__ with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def __init__(
<add> self,
<add> vocab_file=None,
<add> merges_file=None,
<add> tokenizer_file=None,
<add> errors="replace",
<add> bos_token="<s>",
<add> eos_token="</s>",
<add> sep_token="</s>",
<add> cls_token="<s>",
<add> unk_token="<unk>",
<add> pad_token="<pad>",
<add> mask_token="<mask>",
<add> add_prefix_space=False,
<add> trim_offsets=True,
<add> **kwargs
<add> ):
<add> super().__init__(
<add> vocab_file,
<add> merges_file,
<add> tokenizer_file=tokenizer_file,
<add> errors=errors,
<add> bos_token=bos_token,
<add> eos_token=eos_token,
<add> sep_token=sep_token,
<add> cls_token=cls_token,
<add> unk_token=unk_token,
<add> pad_token=pad_token,
<add> mask_token=mask_token,
<add> add_prefix_space=add_prefix_space,
<add> trim_offsets=trim_offsets,
<add> **kwargs,
<add> )
<add>
<add> pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
<add> if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
<add> pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
<add> pre_tok_state["add_prefix_space"] = add_prefix_space
<add> self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)
<add>
<add> self.add_prefix_space = add_prefix_space
<add>
<add> tokenizer_component = "post_processor"
<add> tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
<add> if tokenizer_component_instance:
<add> state = json.loads(tokenizer_component_instance.__getstate__())
<add>
<add> # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
<add> if "sep" in state:
<add> state["sep"] = tuple(state["sep"])
<add> if "cls" in state:
<add> state["cls"] = tuple(state["cls"])
<add>
<add> changes_to_apply = False
<add>
<add> if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
<add> state["add_prefix_space"] = add_prefix_space
<add> changes_to_apply = True
<add>
<add> if state.get("trim_offsets", trim_offsets) != trim_offsets:
<add> state["trim_offsets"] = trim_offsets
<add> changes_to_apply = True
<add>
<add> if changes_to_apply:
<add> component_class = getattr(processors, state.pop("type"))
<add> new_value = component_class(**state)
<add> setattr(self.backend_tokenizer, tokenizer_component, new_value)
<add>
<add> @property
<add> # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def mask_token(self) -> str:
<add> """
<add> `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
<add> having been set.
<add>
<add> Blenderbot tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will
<add> greedily comprise the space before the *<mask>*.
<add> """
<add> if self._mask_token is None:
<add> if self.verbose:
<add> logger.error("Using mask_token, but it is not set yet.")
<add> return None
<add> return str(self._mask_token)
<add>
<add> @mask_token.setter
<add> def mask_token(self, value):
<add> """
<add> Overriding the default behavior of the mask token to have it eat the space before it.
<add>
<add> This is needed to preserve backward compatibility with all the previously used models based on Roberta.
<add> """
<add> # Mask token behave like a normal word, i.e. include the space before it
<add> # So we set lstrip to True
<add> value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
<add> self._mask_token = value
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast._batch_encode_plus with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
<add> is_split_into_words = kwargs.get("is_split_into_words", False)
<add> assert self.add_prefix_space or not is_split_into_words, (
<add> f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
<add> "to use it with pretokenized inputs."
<add> )
<add>
<add> return super()._batch_encode_plus(*args, **kwargs)
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast._encode_plus with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
<add> is_split_into_words = kwargs.get("is_split_into_words", False)
<add>
<add> assert self.add_prefix_space or not is_split_into_words, (
<add> f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
<add> "to use it with pretokenized inputs."
<add> )
<add>
<add> return super()._encode_plus(*args, **kwargs)
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.save_vocabulary with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
<add> files = self._tokenizer.model.save(save_directory, name=filename_prefix)
<add> return tuple(files)
<add>
<add> # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.create_token_type_ids_from_sequences with Roberta->Blenderbot, RoBERTa->Blenderbot
<add> def create_token_type_ids_from_sequences(
<add> self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
<add> ) -> List[int]:
<add> """
<add> Create a mask from the two sequences passed to be used in a sequence-pair classification task. Blenderbot does
<add> not make use of token type ids, therefore a list of zeros is returned.
<add>
<add> Args:
<add> token_ids_0 (`List[int]`):
<add> List of IDs.
<add> token_ids_1 (`List[int]`, *optional*):
<add> Optional second list of IDs for sequence pairs.
<add>
<add> Returns:
<add> `List[int]`: List of zeros.
<add> """
<add> sep = [self.sep_token_id]
<add> cls = [self.cls_token_id]
<add>
<add> if token_ids_1 is None:
<add> return len(cls + token_ids_0 + sep) * [0]
<add> return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
<add>
<ide> def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None):
<ide> """
<ide> Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
<ide> adding special tokens. A Blenderbot sequence has the following format:
<del>
<ide> - single sequence: ` X </s>`
<del>
<ide> Args:
<ide> token_ids_0 (`List[int]`):
<ide> List of IDs to which the special tokens will be added
<ide> token_ids_1 (`List[int]`, *optional*):
<ide> Will be ignored
<del>
<ide> Returns:
<ide> `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
<ide> """ | 2 |
Python | Python | add allowany class | af96fe05d0138c34128fc3944fc2701cbad5bd01 | <ide><path>rest_framework/permissions.py
<ide> def has_permission(self, request, view, obj=None):
<ide> raise NotImplementedError(".has_permission() must be overridden.")
<ide>
<ide>
<add>class AllowAny(BasePermission):
<add> """
<add> Allow any access.
<add> This isn't strictly required, since you could use an empty
<add> permission_classes list, but it's useful because it makes the intention
<add> more explicit.
<add> """
<add> def has_permission(self, request, view, obj=None):
<add> return True
<add>
<add>
<ide> class IsAuthenticated(BasePermission):
<ide> """
<ide> Allows access only to authenticated users. | 1 |
Text | Text | add info about react-native channel on discordapp | 419549b1160aa6f9dd6ef4f05ee145b2d6bd224e | <ide><path>CONTRIBUTING.md
<ide> Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
<ide>
<ide> * IRC - [#reactnative on freenode](http://webchat.freenode.net/?channels=reactnative)
<ide> * [Facebook group](https://www.facebook.com/groups/react.native.community/)
<add>* Reactiflux — [#react-native](http://join.reactiflux.com/)
<ide>
<ide> ## Style Guide
<ide> | 1 |
PHP | PHP | make queued jobs the default | 0ad5b36932a87bd76736d763aef858d60d9f4fa7 | <ide><path>src/Illuminate/Foundation/Console/JobMakeCommand.php
<ide> class JobMakeCommand extends GeneratorCommand
<ide> */
<ide> protected function getStub()
<ide> {
<del> if ($this->option('queued')) {
<del> return __DIR__.'/stubs/job-queued.stub';
<del> } else {
<add> if ($this->option('sync')) {
<ide> return __DIR__.'/stubs/job.stub';
<add> } else {
<add> return __DIR__.'/stubs/job-queued.stub';
<ide> }
<ide> }
<ide>
<ide> protected function getDefaultNamespace($rootNamespace)
<ide> protected function getOptions()
<ide> {
<ide> return [
<del> ['queued', null, InputOption::VALUE_NONE, 'Indicates that job should be queued.'],
<add> ['sync', null, InputOption::VALUE_NONE, 'Indicates that job should be synchronous.'],
<ide> ];
<ide> }
<ide> } | 1 |
Python | Python | use openblas.sgemm in parser | 952c87409eafb9312ca62b1a940c8635d539dc74 | <ide><path>spacy/_ml.py
<ide> def __init__(self, nO=None, nI=None, nF=None, nP=None, **kwargs):
<ide> self.nF = nF
<ide>
<ide> def begin_update(self, X, drop=0.):
<del> Yf = self.ops.xp.dot(X,
<del> self.W.reshape((self.nF*self.nO*self.nP, self.nI)).T)
<add> Yf = self.ops.gemm(X,
<add> self.W.reshape((self.nF*self.nO*self.nP, self.nI)), trans2=True)
<ide> Yf = Yf.reshape((Yf.shape[0], self.nF, self.nO, self.nP))
<ide> Yf = self._add_padding(Yf)
<ide>
<ide> def backward(dY_ids, sgd=None):
<ide>
<ide> # Reuse the buffer
<ide> dWopfi = Wopfi; dWopfi.fill(0.)
<del> self.ops.xp.dot(dY.T, Xf, out=dWopfi)
<add> self.ops.gemm(dY, Xf, out=dWopfi, trans1=True)
<ide> dWopfi = dWopfi.reshape((self.nO, self.nP, self.nF, self.nI))
<ide> # (o, p, f, i) --> (f, o, p, i)
<ide> self.d_W += dWopfi.transpose((2, 0, 1, 3)) | 1 |
Javascript | Javascript | use repeat() instead of new array().join() | 58dc229d9aac29132cf038ed07b3b7e13b671dca | <ide><path>test/parallel/test-buffer-concat.js
<ide> const flatLongLen = Buffer.concat(long, 40);
<ide> assert.strictEqual(flatZero.length, 0);
<ide> assert.strictEqual(flatOne.toString(), 'asdf');
<ide>
<del>const check = new Array(10 + 1).join('asdf');
<add>const check = 'asdf'.repeat(10);
<ide>
<ide> // A special case where concat used to return the first item,
<ide> // if the length is one. This check is to make sure that we don't do that.
<ide><path>test/parallel/test-fs-long-path.js
<ide> if (!common.isWindows) {
<ide>
<ide> // make a path that will be at least 260 chars long.
<ide> const fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1);
<del>const fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x'));
<add>const fileName = path.join(common.tmpDir, 'x'.repeat(fileNameLen));
<ide> const fullPath = path.resolve(fileName);
<ide>
<ide> common.refreshTmpDir();
<ide><path>test/parallel/test-fs-readfile-pipe-large.js
<ide> if (process.argv[2] === 'child') {
<ide> }
<ide>
<ide> const filename = path.join(common.tmpDir, '/readfile_pipe_large_test.txt');
<del>const dataExpected = new Array(1000000).join('a');
<add>const dataExpected = 'a'.repeat(999999);
<ide> common.refreshTmpDir();
<ide> fs.writeFileSync(filename, dataExpected);
<ide>
<ide><path>test/parallel/test-fs-readfilesync-pipe-large.js
<ide> if (process.argv[2] === 'child') {
<ide> }
<ide>
<ide> const filename = path.join(common.tmpDir, '/readfilesync_pipe_large_test.txt');
<del>const dataExpected = new Array(1000000).join('a');
<add>const dataExpected = 'a'.repeat(999999);
<ide> common.refreshTmpDir();
<ide> fs.writeFileSync(filename, dataExpected);
<ide>
<ide><path>test/parallel/test-http-byteswritten.js
<ide> const httpServer = http.createServer(common.mustCall(function(req, res) {
<ide>
<ide> // Write 1.5mb to cause some requests to buffer
<ide> // Also, mix up the encodings a bit.
<del> const chunk = new Array(1024 + 1).join('7');
<add> const chunk = '7'.repeat(1024);
<ide> const bchunk = Buffer.from(chunk);
<ide> for (let i = 0; i < 1024; i++) {
<ide> res.write(chunk);
<ide><path>test/parallel/test-http-pipeline-flood.js
<ide> function child() {
<ide>
<ide> let req = `GET / HTTP/1.1\r\nHost: localhost:${port}\r\nAccept: */*\r\n\r\n`;
<ide>
<del> req = new Array(10241).join(req);
<add> req = req.repeat(10240);
<ide>
<ide> conn.on('connect', write);
<ide>
<ide><path>test/parallel/test-http-pipeline-regr-3332.js
<ide> const server = http.createServer(function(req, res) {
<ide> }
<ide> });
<ide> }).listen(0, function() {
<del> const req = new Array(COUNT + 1).join('GET / HTTP/1.1\r\n\r\n');
<add> const req = 'GET / HTTP/1.1\r\n\r\n'.repeat(COUNT);
<ide> client = net.connect(this.address().port, function() {
<ide> client.write(req);
<ide> });
<ide><path>test/parallel/test-stream2-writable.js
<ide> TestWriter.prototype._write = function(chunk, encoding, cb) {
<ide>
<ide> const chunks = new Array(50);
<ide> for (let i = 0; i < chunks.length; i++) {
<del> chunks[i] = new Array(i + 1).join('x');
<add> chunks[i] = 'x'.repeat(i);
<ide> }
<ide>
<ide> // tiny node-tap lookalike.
<ide><path>test/parallel/test-string-decoder-end.js
<ide> const bufs = [ '☃💩', 'asdf' ].map((b) => Buffer.from(b));
<ide>
<ide> // also test just arbitrary bytes from 0-15.
<ide> for (let i = 1; i <= 16; i++) {
<del> const bytes = new Array(i).join('.').split('.').map((_, j) => j + 0x78);
<add> const bytes = '.'.repeat(i - 1).split('.').map((_, j) => j + 0x78);
<ide> bufs.push(Buffer.from(bytes));
<ide> }
<ide>
<ide><path>test/pummel/test-tls-server-large-request.js
<ide> const fs = require('fs');
<ide> const stream = require('stream');
<ide> const util = require('util');
<ide>
<del>const request = Buffer.from(new Array(1024 * 256).join('ABCD')); // 1mb
<add>const request = Buffer.from('ABCD'.repeat(1024 * 256 - 1)); // 1mb
<ide>
<ide> const options = {
<ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), | 10 |
Javascript | Javascript | fix a bug when rendering certain arcs | 2cdaf6ad003d0390abe7b17d03b2b7f10b4b90e3 | <ide><path>d3.js
<del>d3 = {version: "0.28.2"}; // semver
<add>d3 = {version: "0.28.3"}; // semver
<ide> if (!Date.now) Date.now = function() {
<ide> return +new Date();
<ide> };
<ide> d3["svg"]["arc"] = function() {
<ide> a0 = startAngle.call(this, d, i) + d3_svg_arcOffset,
<ide> a1 = endAngle.call(this, d, i) + d3_svg_arcOffset,
<ide> da = a1 - a0,
<add> df = da < Math.PI ? "0" : "1",
<ide> c0 = Math.cos(a0),
<ide> s0 = Math.sin(a0),
<ide> c1 = Math.cos(a1),
<ide> s1 = Math.sin(a1);
<del> return "M" + r1 * c0 + "," + r1 * s0
<del> + "A" + r1 + "," + r1 + " 0 "
<del> + ((da < Math.PI) ? "0" : "1") + ",1 "
<del> + r1 * c1 + "," + r1 * s1
<del> + "L" + r0 * c1 + "," + r0 * s1
<del> + "A" + r0 + "," + r0 + " 0 "
<del> + ((da < Math.PI) ? "0" : "1") + ",0 "
<del> + r0 * c0 + "," + r0 * s0 + "Z";
<add> return da >= 2 * Math.PI
<add> ? (r0
<add> ? "M0," + r1
<add> + "A" + r1 + "," + r1 + " 0 1,1 0," + (-r1)
<add> + "A" + r1 + "," + r1 + " 0 1,1 0," + r1
<add> + "M0," + r0
<add> + "A" + r0 + "," + r0 + " 0 1,1 0," + (-r0)
<add> + "A" + r0 + "," + r0 + " 0 1,1 0," + r0
<add> + "Z"
<add> : "M0," + r1
<add> + "A" + r1 + "," + r1 + " 0 1,1 0," + (-r1)
<add> + "A" + r1 + "," + r1 + " 0 1,1 0," + r1
<add> + "Z")
<add> : (r0
<add> ? "M" + r1 * c0 + "," + r1 * s0
<add> + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1
<add> + "L" + r0 * c1 + "," + r0 * s1
<add> + "A" + r0 + "," + r0 + " 0 " + df + ",0 " + r0 * c0 + "," + r0 * s0
<add> + "Z"
<add> : "M" + r1 * c0 + "," + r1 * s0
<add> + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1
<add> + "L0,0"
<add> + "Z");
<ide> }
<ide>
<ide> arc["innerRadius"] = function(v) {
<ide><path>d3.min.js
<del>(function(){var n=null;d3={version:"0.28.2"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};function x(a){return Array.prototype.slice.call(a)}function y(a){return typeof a=="function"?a:function(){return a}}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.merge=function(a){return Array.prototype.concat.apply([],a)};
<del>d3.split=function(a,b){var c=[],f=[],d,e=-1,h=a.length;if(arguments.length<2)b=aa;for(;++e<h;)if(b.call(f,d=a[e],e)){c.push(f);f=[]}else f.push(d);c.push(f);return c};function aa(a){return a==n}function E(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function ba(a,b){b=x(arguments);b[0]=this;a.apply(this,b);return this}
<del>d3.range=function(a,b,c){if(arguments.length==1){b=a;a=0}if(c==n)c=1;if((b-a)/c==Infinity)throw Error("infinite range");var f=[],d=-1,e;if(c<0)for(;(e=a+c*++d)>b;)f.push(e);else for(;(e=a+c*++d)<b;)f.push(e);return f};d3.requote=function(a){return a.replace(ca,"\\$&")};var ca=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;
<del>d3.xhr=function(a,b,c){var f=new XMLHttpRequest;if(arguments.length<3)c=b;else b&&f.overrideMimeType(b);f.open("GET",a,true);f.onreadystatechange=function(){if(f.readyState==4)c(f.status<300?f:n)};f.send(n)};d3.text=function(a,b,c){if(arguments.length<3){c=b;b=n}d3.xhr(a,b,function(f){c(f&&f.responseText)})};d3.json=function(a,b){d3.text(a,"application/json",function(c){b(c?JSON.parse(c):n)})};
<del>d3.html=function(a,b){d3.text(a,"text/html",function(c){if(c!=n){var f=document.createRange();f.selectNode(document.body);c=f.createContextualFragment(c)}b(c)})};d3.xml=function(a,b,c){if(arguments.length<3){c=b;b=n}d3.xhr(a,b,function(f){c(f&&f.responseXML)})};
<add>(function(){var o=null;d3={version:"0.28.3"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};function x(a){return Array.prototype.slice.call(a)}function y(a){return typeof a=="function"?a:function(){return a}}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.merge=function(a){return Array.prototype.concat.apply([],a)};
<add>d3.split=function(a,b){var c=[],f=[],d,e=-1,i=a.length;if(arguments.length<2)b=aa;for(;++e<i;)if(b.call(f,d=a[e],e)){c.push(f);f=[]}else f.push(d);c.push(f);return c};function aa(a){return a==o}function E(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function ba(a,b){b=x(arguments);b[0]=this;a.apply(this,b);return this}
<add>d3.range=function(a,b,c){if(arguments.length==1){b=a;a=0}if(c==o)c=1;if((b-a)/c==Infinity)throw Error("infinite range");var f=[],d=-1,e;if(c<0)for(;(e=a+c*++d)>b;)f.push(e);else for(;(e=a+c*++d)<b;)f.push(e);return f};d3.requote=function(a){return a.replace(ca,"\\$&")};var ca=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;
<add>d3.xhr=function(a,b,c){var f=new XMLHttpRequest;if(arguments.length<3)c=b;else b&&f.overrideMimeType(b);f.open("GET",a,true);f.onreadystatechange=function(){if(f.readyState==4)c(f.status<300?f:o)};f.send(o)};d3.text=function(a,b,c){if(arguments.length<3){c=b;b=o}d3.xhr(a,b,function(f){c(f&&f.responseText)})};d3.json=function(a,b){d3.text(a,"application/json",function(c){b(c?JSON.parse(c):o)})};
<add>d3.html=function(a,b){d3.text(a,"text/html",function(c){if(c!=o){var f=document.createRange();f.selectNode(document.body);c=f.createContextualFragment(c)}b(c)})};d3.xml=function(a,b,c){if(arguments.length<3){c=b;b=o}d3.xhr(a,b,function(f){c(f&&f.responseXML)})};
<ide> 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(){for(var a={},b,c=0,f=arguments.length;c<f;c++){b=arguments[c];a[b]=da(b)}return a};
<ide> function da(){var a={},b=[];a.add=function(c){for(var f=0;f<b.length;f++)if(b[f].i==c)return a;b.push({i:c,on:true});return a};a.remove=function(c){for(var f=0;f<b.length;f++){var d=b[f];if(d.i==c){d.on=false;b=b.slice(0,f).concat(b.slice(f+1));break}}return a};a.dispatch=function(){for(var c=b,f=0,d=c.length;f<d;f++){var e=c[f];e.on&&e.i.apply(this,arguments)}};return a}
<del>d3.format=function(a){a=ea.exec(a);var b=a[1]||" ",c=a[5],f=+a[6],d=a[7],e=a[8],h=a[9];if(e)e=e.substring(1);if(c)b="0";if(h=="d")e="0";return function(g){if(h=="d"&&g%1)return"";if(e)g=(+g).toFixed(e);else g+="";if(d){for(var i=g.lastIndexOf("."),j=i>=0?g.substring(i):(i=g.length,""),l=[];i>0;)l.push(g.substring(i-=3,i+3));g=l.reverse().join(",")+j}i=g.length;if(i<f)g=Array(f-i+1).join(b)+g;return g}};
<add>d3.format=function(a){a=ea.exec(a);var b=a[1]||" ",c=a[5],f=+a[6],d=a[7],e=a[8],i=a[9];if(e)e=e.substring(1);if(c)b="0";if(i=="d")e="0";return function(g){if(i=="d"&&g%1)return"";if(e)g=(+g).toFixed(e);else g+="";if(d){for(var h=g.lastIndexOf("."),j=h>=0?g.substring(h):(h=g.length,""),l=[];h>0;)l.push(g.substring(h-=3,h+3));g=l.reverse().join(",")+j}h=g.length;if(h<f)g=Array(f-h+1).join(b)+g;return g}};
<ide> var ea=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,fa=F(2),ga=F(3),oa={linear:function(){return ha},poly:F,quad:function(){return fa},cubic:function(){return ga},sin:function(){return ia},exp:function(){return ja},circle:function(){return ka},elastic:la,back:ma,bounce:function(){return na}},ra={"in":function(a){return a},out:pa,"in-out":qa,"out-in":function(a){return qa(pa(a))}};
<del>d3.ease=function(a){var b=a.indexOf("-");return ra[b>=0?a.substring(b+1):"in"](oa[b>=0?a.substring(0,b):a].apply(n,Array.prototype.slice.call(arguments,1)))};function pa(a){return function(b){return 1-a(1-b)}}function qa(a){return function(b){return 0.5*(b<0.5?a(2*b):2-a(2-2*b))}}function ha(a){return a}function F(a){return function(b){return Math.pow(b,a)}}function ia(a){return 1-Math.cos(a*Math.PI/2)}function ja(a){return a?Math.pow(2,10*(a-1))-0.0010:0}
<del>function ka(a){return 1-Math.sqrt(1-a*a)}function la(a,b){var c;if(arguments.length<2)b=0.45;if(arguments.length<1){a=1;c=b/4}else c=b/(2*Math.PI)*Math.asin(1/a);return function(f){return 1+a*Math.pow(2,10*-f)*Math.sin((f-c)*2*Math.PI/b)}}function ma(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function na(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+0.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+0.9375:7.5625*(a-=2.625/2.75)*a+0.984375}d3.event=n;
<add>d3.ease=function(a){var b=a.indexOf("-");return ra[b>=0?a.substring(b+1):"in"](oa[b>=0?a.substring(0,b):a].apply(o,Array.prototype.slice.call(arguments,1)))};function pa(a){return function(b){return 1-a(1-b)}}function qa(a){return function(b){return 0.5*(b<0.5?a(2*b):2-a(2-2*b))}}function ha(a){return a}function F(a){return function(b){return Math.pow(b,a)}}function ia(a){return 1-Math.cos(a*Math.PI/2)}function ja(a){return a?Math.pow(2,10*(a-1))-0.0010:0}
<add>function ka(a){return 1-Math.sqrt(1-a*a)}function la(a,b){var c;if(arguments.length<2)b=0.45;if(arguments.length<1){a=1;c=b/4}else c=b/(2*Math.PI)*Math.asin(1/a);return function(f){return 1+a*Math.pow(2,10*-f)*Math.sin((f-c)*2*Math.PI/b)}}function ma(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function na(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+0.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+0.9375:7.5625*(a-=2.625/2.75)*a+0.984375}d3.event=o;
<ide> d3.interpolate=function(a,b){if(typeof b=="number")return d3.interpolateNumber(+a,b);if(typeof b=="string")return b in G||/^(#|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}};
<del>d3.interpolateString=function(a,b){var c,f,d=0,e=[],h=[],g,i;for(f=0;c=H.exec(b);++f){c.index&&e.push(b.substring(d,c.index));h.push({a:e.length,x:c[0]});e.push(n);d=H.lastIndex}d<b.length&&e.push(b.substring(d));f=0;for(g=h.length;(c=H.exec(a))&&f<g;++f){i=h[f];if(i.x==c[0]){if(i.a)if(e[i.a+1]==n){e[i.a-1]+=i.x;e.splice(i.a,1);for(c=f+1;c<g;++c)h[c].a--}else{e[i.a-1]+=i.x+e[i.a+1];e.splice(i.a,2);for(c=f+1;c<g;++c)h[c].a-=2}else if(e[i.a+1]==n)e[i.a]=i.x;else{e[i.a]=i.x+e[i.a+1];e.splice(i.a+1,1);
<del>for(c=f+1;c<g;++c)h[c].a--}h.splice(f,1);g--;f--}else i.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(i.x))}for(;f<g;){i=h.pop();if(e[i.a+1]==n)e[i.a]=i.x;else{e[i.a]=i.x+e[i.a+1];e.splice(i.a+1,1)}g--}if(e.length==1)return e[0]==n?h[0].x:function(){return b};return function(j){for(f=0;f<g;++f)e[(i=h[f]).a]=i.x(j);return e.join("")}};
<del>d3.interpolateRgb=function(a,b){a=d3.rgb(a);b=d3.rgb(b);var c=a.r,f=a.g,d=a.b,e=b.r-c,h=b.g-f,g=b.b-d;return function(i){return"rgb("+Math.round(c+e*i)+","+Math.round(f+h*i)+","+Math.round(d+g*i)+")"}};d3.interpolateArray=function(a,b){var c=[],f=[],d=a.length,e=b.length,h=Math.min(a.length,b.length),g;for(g=0;g<h;++g)c.push(d3.interpolate(a[g],b[g]));for(;g<d;++g)f[g]=a[g];for(;g<e;++g)f[g]=b[g];return function(i){for(g=0;g<h;++g)f[g]=c[g](i);return f}};
<add>d3.interpolateString=function(a,b){var c,f,d=0,e=[],i=[],g,h;for(f=0;c=H.exec(b);++f){c.index&&e.push(b.substring(d,c.index));i.push({a:e.length,x:c[0]});e.push(o);d=H.lastIndex}d<b.length&&e.push(b.substring(d));f=0;for(g=i.length;(c=H.exec(a))&&f<g;++f){h=i[f];if(h.x==c[0]){if(h.a)if(e[h.a+1]==o){e[h.a-1]+=h.x;e.splice(h.a,1);for(c=f+1;c<g;++c)i[c].a--}else{e[h.a-1]+=h.x+e[h.a+1];e.splice(h.a,2);for(c=f+1;c<g;++c)i[c].a-=2}else if(e[h.a+1]==o)e[h.a]=h.x;else{e[h.a]=h.x+e[h.a+1];e.splice(h.a+1,1);
<add>for(c=f+1;c<g;++c)i[c].a--}i.splice(f,1);g--;f--}else h.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(h.x))}for(;f<g;){h=i.pop();if(e[h.a+1]==o)e[h.a]=h.x;else{e[h.a]=h.x+e[h.a+1];e.splice(h.a+1,1)}g--}if(e.length==1)return e[0]==o?i[0].x:function(){return b};return function(j){for(f=0;f<g;++f)e[(h=i[f]).a]=h.x(j);return e.join("")}};
<add>d3.interpolateRgb=function(a,b){a=d3.rgb(a);b=d3.rgb(b);var c=a.r,f=a.g,d=a.b,e=b.r-c,i=b.g-f,g=b.b-d;return function(h){return"rgb("+Math.round(c+e*h)+","+Math.round(f+i*h)+","+Math.round(d+g*h)+")"}};d3.interpolateArray=function(a,b){var c=[],f=[],d=a.length,e=b.length,i=Math.min(a.length,b.length),g;for(g=0;g<i;++g)c.push(d3.interpolate(a[g],b[g]));for(;g<d;++g)f[g]=a[g];for(;g<e;++g)f[g]=b[g];return function(h){for(g=0;g<i;++g)f[g]=c[g](h);return f}};
<ide> d3.interpolateObject=function(a,b){var c={},f={},d;for(d in a)if(d in b)c[d]=(d in sa||/\bcolor\b/.test(d)?d3.interpolateRgb:d3.interpolate)(a[d],b[d]);else f[d]=a[d];for(d in b)d in a||(f[d]=b[d]);return function(e){for(d in c)f[d]=c[d](e);return f}};var H=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,sa={background:1,fill:1,stroke:1};d3.rgb=function(a,b,c){return arguments.length==1?I(""+a,J,ta):J(~~a,~~b,~~c)};function J(a,b,c){return{r:a,g:b,b:c,toString:ua}}
<ide> function ua(){return"#"+K(this.r)+K(this.g)+K(this.b)}function K(a){return a<16?"0"+a.toString(16):a.toString(16)}
<del>function I(a,b,c){var f,d,e,h,g;if(h=/([a-z]+)\((.*)\)/i.exec(a)){g=h[2].split(",");switch(h[1]){case "hsl":return c(parseFloat(g[0]),parseFloat(g[1])/100,parseFloat(g[2])/100);case "rgb":return b(L(g[0]),L(g[1]),L(g[2]))}}if(c=G[a])return b(c.r,c.g,c.b);if(a==n)return b(0,0,0);if(a.charAt(0)=="#"){if(a.length==4){f=a.charAt(1);f+=f;d=a.charAt(2);d+=d;e=a.charAt(3);e+=e}else if(a.length==7){f=a.substring(1,3);d=a.substring(3,5);e=a.substring(5,7)}f=parseInt(f,16);d=parseInt(d,16);e=parseInt(e,16)}return b(f,
<del>d,e)}function va(a,b,c){var f=Math.min(a/=255,b/=255,c/=255),d=Math.max(a,b,c),e=d-f,h=(d+f)/2;if(e){f=h<0.5?e/(d+f):e/(2-d-f);a=a==d?(b-c)/e+(b<c?6:0):b==d?(c-a)/e+2:(a-b)/e+4;a*=60}else f=a=0;return M(a,f,h)}function L(a){var b=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(b*2.55):b}
<add>function I(a,b,c){var f,d,e,i,g;if(i=/([a-z]+)\((.*)\)/i.exec(a)){g=i[2].split(",");switch(i[1]){case "hsl":return c(parseFloat(g[0]),parseFloat(g[1])/100,parseFloat(g[2])/100);case "rgb":return b(L(g[0]),L(g[1]),L(g[2]))}}if(c=G[a])return b(c.r,c.g,c.b);if(a==o)return b(0,0,0);if(a.charAt(0)=="#"){if(a.length==4){f=a.charAt(1);f+=f;d=a.charAt(2);d+=d;e=a.charAt(3);e+=e}else if(a.length==7){f=a.substring(1,3);d=a.substring(3,5);e=a.substring(5,7)}f=parseInt(f,16);d=parseInt(d,16);e=parseInt(e,16)}return b(f,
<add>d,e)}function va(a,b,c){var f=Math.min(a/=255,b/=255,c/=255),d=Math.max(a,b,c),e=d-f,i=(d+f)/2;if(e){f=i<0.5?e/(d+f):e/(2-d-f);a=a==d?(b-c)/e+(b<c?6:0):b==d?(c-a)/e+2:(a-b)/e+4;a*=60}else f=a=0;return M(a,f,i)}function L(a){var b=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(b*2.55):b}
<ide> var G={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",
<ide> 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",
<ide> 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",
<ide> 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",
<ide> 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",
<ide> 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"},N;for(N in G)G[N]=I(G[N],J,ta);d3.hsl=function(a,b,c){return arguments.length==1?I(""+a,va,M):M(+a,+b,+c)};
<del>function M(a,b,c){return{h:a,s:b,l:c,toString:wa}}function wa(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"}function ta(a,b,c){function f(h){if(h>360)h-=360;else if(h<0)h+=360;if(h<60)return d+(e-d)*h/60;if(h<180)return e;if(h<240)return d+(e-d)*(240-h)/60;return d}var d,e;a%=360;if(a<0)a+=360;b=b<0?0:b>1?1:b;c=c<0?0:c>1?1:c;e=c<=0.5?c*(1+b):c+b-c*b;d=2*c-e;return J(Math.round(f(a+120)*255),Math.round(f(a)*255),Math.round(f(a-120)*255))}var P=O([[document]]);P[0].parentNode=document.documentElement;
<add>function M(a,b,c){return{h:a,s:b,l:c,toString:wa}}function wa(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"}function ta(a,b,c){function f(i){if(i>360)i-=360;else if(i<0)i+=360;if(i<60)return d+(e-d)*i/60;if(i<180)return e;if(i<240)return d+(e-d)*(240-i)/60;return d}var d,e;a%=360;if(a<0)a+=360;b=b<0?0:b>1?1:b;c=c<0?0:c>1?1:c;e=c<=0.5?c*(1+b):c+b-c*b;d=2*c-e;return J(Math.round(f(a+120)*255),Math.round(f(a)*255),Math.round(f(a-120)*255))}var P=O([[document]]);P[0].parentNode=document.documentElement;
<ide> d3.select=function(a){return typeof a=="string"?P.select(a):O([[a]])};d3.selectAll=function(a){return typeof a=="string"?P.selectAll(a):O([x(a)])};
<del>function O(a){function b(d){for(var e=[],h,g,i,j,l=0,p=a.length;l<p;l++){i=a[l];e.push(h=[]);h.parentNode=i.parentNode;h.parentData=i.parentData;for(var r=0,k=i.length;r<k;r++)if(j=i[r]){h.push(g=d(j));if(g&&"__data__"in j)g.__data__=j.__data__}else h.push(n)}return O(e)}function c(d){for(var e=[],h,g,i,j=0,l=a.length;j<l;j++){g=a[j];for(var p=0,r=g.length;p<r;p++)if(i=g[p]){e.push(h=d(i));h.parentNode=i;h.parentData=i.__data__}}return O(e)}function f(d){for(var e=0,h=a.length;e<h;e++)for(var g=a[e],
<del>i=0,j=g.length;i<j;i++){var l=g[i];if(l)return d.call(l,l.__data__,i)}return n}a.select=function(d){return b(function(e){return e.querySelector(d)})};a.selectAll=function(d){return c(function(e){return x(e.querySelectorAll(d))})};a.filter=function(d){for(var e=[],h,g,i,j=0,l=a.length;j<l;j++){g=a[j];e.push(h=[]);h.parentNode=g.parentNode;h.parentData=g.parentData;for(var p=0,r=g.length;p<r;p++)if((i=g[p])&&d.call(i,i.__data__,p))h.push(i)}return O(e)};a.data=function(d,e){function h(k,o){function q(Ga){return k.parentNode.appendChild(Ga)}
<del>var m=0,t=k.length,u=o.length,s=Math.min(t,u),v=Math.max(t,u),z=[],A=[],w=[],B,C;if(e){s={};v=[];var D;C=o.length;for(m=0;m<t;m++){D=e.nodeKey(B=k[m]);if(D in s)w[C++]=k[m];else{s[D]=B;v.push(D)}}for(m=0;m<u;m++){if(B=s[D=e.dataKey(C=o[m])]){B.__data__=C;z[m]=B;A[m]=w[m]=n}else{A[m]={appendChild:q,__data__:C};z[m]=w[m]=n}delete s[D]}for(m=0;m<t;m++)if(v[m]in s)w[m]=k[m]}else{for(;m<s;m++){B=k[m];C=o[m];if(B){B.__data__=C;z[m]=B;A[m]=w[m]=n}else{A[m]={appendChild:q,__data__:C};z[m]=w[m]=n}}for(;m<
<del>u;m++){A[m]={appendChild:q,__data__:o[m]};z[m]=w[m]=n}for(;m<v;m++){w[m]=k[m];A[m]=z[m]=n}}A.parentNode=z.parentNode=w.parentNode=k.parentNode;A.parentData=z.parentData=w.parentData=k.parentData;l.push(A);p.push(z);r.push(w)}var g=-1,i=a.length,j,l=[],p=[],r=[];if(typeof e=="string")e=xa(e);if(typeof d=="function")for(;++g<i;)h(j=a[g],d.call(j,j.parentData,g));else for(;++g<i;)h(j=a[g],d);g=O(p);g.enter=function(k){return O(l).append(k)};g.exit=function(){return O(r)};return g};a.each=function(d){for(var e=
<del>0,h=a.length;e<h;e++)for(var g=a[e],i=0,j=g.length;i<j;i++){var l=g[i];l&&d.call(l,l.__data__,i)}return a};a.node=function(){return f(function(){return this})};a.attr=function(d,e){function h(){this.removeAttribute(d)}function g(){this.removeAttributeNS(d.space,d.local)}function i(){this.setAttribute(d,e)}function j(){this.setAttributeNS(d.space,d.local,e)}function l(){var r=e.apply(this,arguments);r==n?this.removeAttribute(d):this.setAttribute(d,r)}function p(){var r=e.apply(this,arguments);r==n?
<del>this.removeAttributeNS(d.space,d.local):this.setAttributeNS(d.space,d.local,r)}d=d3.ns.qualify(d);if(arguments.length<2)return f(d.local?function(){return this.getAttributeNS(d.space,d.local)}:function(){return this.getAttribute(d)});return a.each(e==n?d.local?g:h:typeof e=="function"?d.local?p:l:d.local?j:i)};a.classed=function(d,e){function h(){var l=this.className;j.lastIndex=0;if(!j.test(l))this.className=E(l+" "+d)}function g(){var l=E(this.className.replace(j," "));this.className=l.length?l:
<del>n}function i(){(e.apply(this,arguments)?h:g).call(this)}var j=RegExp("(^|\\s+)"+d3.requote(d)+"(\\s+|$)","g");if(arguments.length<2)return f(function(){j.lastIndex=0;return j.test(this.className)});return a.each(typeof e=="function"?i:e?h:g)};a.style=function(d,e,h){function g(){this.style.removeProperty(d)}function i(){this.style.setProperty(d,e,h)}function j(){var l=e.apply(this,arguments);l==n?this.style.removeProperty(d):this.style.setProperty(d,l,h)}if(arguments.length<3)h=n;if(arguments.length<
<del>2)return f(function(){return window.getComputedStyle(this,n).getPropertyValue(d)});return a.each(e==n?g:typeof e=="function"?j:i)};a.property=function(d,e){function h(){delete this[d]}function g(){this[d]=e}function i(){var j=e.apply(this,arguments);if(j==n)delete this[d];else this[d]=j}d=d3.ns.qualify(d);if(arguments.length<2)return f(function(){return this[d]});return a.each(e==n?h:typeof e=="function"?i:g)};a.text=function(d){function e(){this.appendChild(document.createTextNode(d))}function h(){var g=
<del>d.apply(this,arguments);g!=n&&this.appendChild(document.createTextNode(g))}if(arguments.length<1)return f(function(){return this.textContent});a.each(function(){for(;this.lastChild;)this.removeChild(this.lastChild)});return d==n?a:a.each(typeof d=="function"?h:e)};a.html=function(d){function e(){this.innerHTML=d}function h(){this.innerHTML=d.apply(this,arguments)}if(arguments.length<1)return f(function(){return this.innerHTML});return a.each(typeof d=="function"?h:e)};a.append=function(d){function e(g){return g.appendChild(document.createElement(d))}
<del>function h(g){return g.appendChild(document.createElementNS(d.space,d.local))}d=d3.ns.qualify(d);return b(d.local?h:e)};a.remove=function(){return b(function(d){var e=d.parentNode;e.removeChild(d);return e})};a.sort=function(d){d=ya.apply(this,arguments);for(var e=0,h=a.length;e<h;e++){var g=a[e];g.sort(d);for(var i=1,j=g.length,l=g[0];i<j;i++){var p=g[i];if(p){l&&l.parentNode.insertBefore(p,l.nextSibling);l=p}}}return a};a.on=function(d,e){d="on"+d;return a.each(function(h,g){this[d]=function(i){var j=
<del>d3.event;d3.event=i;try{e.call(this,h,g)}finally{d3.event=j}}})};a.transition=function(){return Q(a)};a.call=ba;return a}function xa(a){return{nodeKey:function(b){return b.getAttribute(a)},dataKey:function(b){return b[a]}}}function ya(a){if(!arguments.length)a=d3.u;return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}d3.transition=P.transition;var za=0,R=0;
<del>function Q(a){function b(k){var o=true,q=-1;a.each(function(){if(i[++q]!=2){var m=(k-j[q])/l[q],t=this.__transition__,u,s,v=e[q];if(m<1){o=false;if(m<0)return}else m=1;if(i[q]){if(t.d!=f){i[q]=2;return}}else if(!t||t.d>f){i[q]=2;return}else{i[q]=1;g.start.dispatch.apply(this,arguments);v=e[q]={};t.d=f;for(s in d)v[s]=d[s].apply(this,arguments)}u=r(m);for(s in d)v[s].call(this,u);if(m==1){i[q]=2;if(t.d==f){m=t.o;if(m==f){delete this.__transition__;h&&this.parentNode.removeChild(this)}R=f;g.end.dispatch.apply(this,
<del>arguments);R=0;t.o=m}}}});return o}var c={},f=R||++za,d={},e=[],h=false,g=d3.dispatch("start","end"),i=[],j=[],l=[],p,r=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).o=f});c.delay=function(k){var o=Infinity,q=-1;if(typeof k=="function")a.each(function(){var m=j[++q]=+k.apply(this,arguments);if(m<o)o=m});else{o=+k;a.each(function(){j[++q]=o})}Aa(b,o);return c};c.duration=function(k){var o=-1;if(typeof k=="function"){p=0;a.each(function(){var q=l[++o]=+k.apply(this,
<del>arguments);if(q>p)p=q})}else{p=+k;a.each(function(){l[++o]=p})}return c};c.ease=function(k){r=typeof k=="string"?d3.ease(k):k;return c};c.attrTween=function(k,o){function q(t,u){var s=o.call(this,t,u,this.getAttribute(k));return function(v){this.setAttribute(k,s(v))}}function m(t,u){var s=o.call(this,t,u,this.getAttributeNS(k.space,k.local));return function(v){this.setAttributeNS(k.space,k.local,s(v))}}d["attr."+k]=k.local?m:q;return c};c.attr=function(k,o){return c.attrTween(k,Ba(o))};c.styleTween=
<del>function(k,o,q){d["style."+k]=function(m,t){var u=o.call(this,m,t,window.getComputedStyle(this,n).getPropertyValue(k));return function(s){this.style.setProperty(k,u(s),q)}};return c};c.style=function(k,o,q){return c.styleTween(k,Ba(o),q)};c.select=function(k){var o;k=Q(a.select(k)).ease(r);o=-1;k.delay(function(){return j[++o]});o=-1;k.duration(function(){return l[++o]});return k};c.selectAll=function(k){var o;k=Q(a.selectAll(k)).ease(r);o=-1;k.delay(function(q,m){return j[m?o:++o]});o=-1;k.duration(function(q,
<del>m){return l[m?o:++o]});return k};c.remove=function(){h=true;return c};c.each=function(k,o){g[k].add(o);return c};c.call=ba;return c.delay(0).duration(250)}var S=n,T=0,U;function Aa(a,b){var c=Date.now(),f=false,d=c+b,e=S;if(isFinite(b)){for(;e;){if(e.n==a){e.j=c;e.delay=b;f=true}else{var h=e.j+e.delay;if(h<d)d=h}e=e.next}f||(S={n:a,j:c,delay:b,next:S});if(!U){clearTimeout(T);T=setTimeout(Ca,Math.max(24,d-c))}}}function Ca(){U=setInterval(Da,24);T=0}
<del>function Da(){for(var a,b=Date.now(),c=S;c;){a=b-c.j;if(a>c.delay)c.t=c.n(a);c=c.next}a=n;for(b=S;b;)b=b.t?a?a.next=b.next:S=b.next:(a=b).next;a||(U=clearInterval(U))}function Ba(a){return typeof a=="function"?function(b,c,f){return d3.interpolate(f,a.call(this,b,c))}:function(b,c,f){return d3.interpolate(f,a)}}d3.scale={};
<del>d3.scale.linear=function(){function a(j){return i((j-c)*h)}function b(j){var l=Math.min(c,f),p=Math.max(c,f),r=p-l,k=Math.pow(10,Math.floor(Math.log(r/j)/Math.LN10));j=j/(r/k);if(j<=0.15)k*=10;else if(j<=0.35)k*=5;else if(j<=0.75)k*=2;return{start:Math.ceil(l/k)*k,stop:Math.floor(p/k)*k+k*0.5,q:k}}var c=0,f=1,d=0,e=1,h=1/(f-c),g=(f-c)/(e-d),i=d3.interpolate(d,e);a.invert=function(j){return(j-d)*g+c};a.domain=function(j){if(!arguments.length)return[c,f];c=j[0];f=j[1];h=1/(f-c);g=(f-c)/(e-d);return a};
<del>a.range=function(j){if(!arguments.length)return[d,e];d=j[0];e=j[1];g=(f-c)/(e-d);i=d3.interpolate(d,e);return a};a.ticks=function(j){j=b(j);return d3.range(j.start,j.stop,j.q)};a.tickFormat=function(j){return d3.format(",."+Math.max(0,-Math.floor(Math.log(b(j).q)/Math.LN10+0.01))+"f")};return a};
<del>d3.scale.log=function(){function a(d){return Math.log(d)/Math.LN10}function b(d){return Math.pow(10,d)}function c(d){return f(a(d))}var f=d3.scale.linear();c.invert=function(d){return b(f.invert(d))};c.domain=function(d){if(!arguments.length)return f.domain().map(b);f.domain(d.map(a));return c};c.range=function(){var d=f.range.apply(f,arguments);return arguments.length?c:d};c.ticks=function(){var d=f.domain(),e=Math.floor(d[0]),h=Math.ceil(d[1]),g=[];if(d.every(isFinite)){for(;++e<=h;)for(d=1;d<10;d++)g.push(b(e)*
<add>function O(a){function b(d){for(var e=[],i,g,h,j,l=0,p=a.length;l<p;l++){h=a[l];e.push(i=[]);i.parentNode=h.parentNode;i.parentData=h.parentData;for(var q=0,k=h.length;q<k;q++)if(j=h[q]){i.push(g=d(j));if(g&&"__data__"in j)g.__data__=j.__data__}else i.push(o)}return O(e)}function c(d){for(var e=[],i,g,h,j=0,l=a.length;j<l;j++){g=a[j];for(var p=0,q=g.length;p<q;p++)if(h=g[p]){e.push(i=d(h));i.parentNode=h;i.parentData=h.__data__}}return O(e)}function f(d){for(var e=0,i=a.length;e<i;e++)for(var g=a[e],
<add>h=0,j=g.length;h<j;h++){var l=g[h];if(l)return d.call(l,l.__data__,h)}return o}a.select=function(d){return b(function(e){return e.querySelector(d)})};a.selectAll=function(d){return c(function(e){return x(e.querySelectorAll(d))})};a.filter=function(d){for(var e=[],i,g,h,j=0,l=a.length;j<l;j++){g=a[j];e.push(i=[]);i.parentNode=g.parentNode;i.parentData=g.parentData;for(var p=0,q=g.length;p<q;p++)if((h=g[p])&&d.call(h,h.__data__,p))i.push(h)}return O(e)};a.data=function(d,e){function i(k,n){function r(Ga){return k.parentNode.appendChild(Ga)}
<add>var m=0,t=k.length,u=n.length,s=Math.min(t,u),v=Math.max(t,u),z=[],A=[],w=[],B,C;if(e){s={};v=[];var D;C=n.length;for(m=0;m<t;m++){D=e.nodeKey(B=k[m]);if(D in s)w[C++]=k[m];else{s[D]=B;v.push(D)}}for(m=0;m<u;m++){if(B=s[D=e.dataKey(C=n[m])]){B.__data__=C;z[m]=B;A[m]=w[m]=o}else{A[m]={appendChild:r,__data__:C};z[m]=w[m]=o}delete s[D]}for(m=0;m<t;m++)if(v[m]in s)w[m]=k[m]}else{for(;m<s;m++){B=k[m];C=n[m];if(B){B.__data__=C;z[m]=B;A[m]=w[m]=o}else{A[m]={appendChild:r,__data__:C};z[m]=w[m]=o}}for(;m<
<add>u;m++){A[m]={appendChild:r,__data__:n[m]};z[m]=w[m]=o}for(;m<v;m++){w[m]=k[m];A[m]=z[m]=o}}A.parentNode=z.parentNode=w.parentNode=k.parentNode;A.parentData=z.parentData=w.parentData=k.parentData;l.push(A);p.push(z);q.push(w)}var g=-1,h=a.length,j,l=[],p=[],q=[];if(typeof e=="string")e=xa(e);if(typeof d=="function")for(;++g<h;)i(j=a[g],d.call(j,j.parentData,g));else for(;++g<h;)i(j=a[g],d);g=O(p);g.enter=function(k){return O(l).append(k)};g.exit=function(){return O(q)};return g};a.each=function(d){for(var e=
<add>0,i=a.length;e<i;e++)for(var g=a[e],h=0,j=g.length;h<j;h++){var l=g[h];l&&d.call(l,l.__data__,h)}return a};a.node=function(){return f(function(){return this})};a.attr=function(d,e){function i(){this.removeAttribute(d)}function g(){this.removeAttributeNS(d.space,d.local)}function h(){this.setAttribute(d,e)}function j(){this.setAttributeNS(d.space,d.local,e)}function l(){var q=e.apply(this,arguments);q==o?this.removeAttribute(d):this.setAttribute(d,q)}function p(){var q=e.apply(this,arguments);q==o?
<add>this.removeAttributeNS(d.space,d.local):this.setAttributeNS(d.space,d.local,q)}d=d3.ns.qualify(d);if(arguments.length<2)return f(d.local?function(){return this.getAttributeNS(d.space,d.local)}:function(){return this.getAttribute(d)});return a.each(e==o?d.local?g:i:typeof e=="function"?d.local?p:l:d.local?j:h)};a.classed=function(d,e){function i(){var l=this.className;j.lastIndex=0;if(!j.test(l))this.className=E(l+" "+d)}function g(){var l=E(this.className.replace(j," "));this.className=l.length?l:
<add>o}function h(){(e.apply(this,arguments)?i:g).call(this)}var j=RegExp("(^|\\s+)"+d3.requote(d)+"(\\s+|$)","g");if(arguments.length<2)return f(function(){j.lastIndex=0;return j.test(this.className)});return a.each(typeof e=="function"?h:e?i:g)};a.style=function(d,e,i){function g(){this.style.removeProperty(d)}function h(){this.style.setProperty(d,e,i)}function j(){var l=e.apply(this,arguments);l==o?this.style.removeProperty(d):this.style.setProperty(d,l,i)}if(arguments.length<3)i=o;if(arguments.length<
<add>2)return f(function(){return window.getComputedStyle(this,o).getPropertyValue(d)});return a.each(e==o?g:typeof e=="function"?j:h)};a.property=function(d,e){function i(){delete this[d]}function g(){this[d]=e}function h(){var j=e.apply(this,arguments);if(j==o)delete this[d];else this[d]=j}d=d3.ns.qualify(d);if(arguments.length<2)return f(function(){return this[d]});return a.each(e==o?i:typeof e=="function"?h:g)};a.text=function(d){function e(){this.appendChild(document.createTextNode(d))}function i(){var g=
<add>d.apply(this,arguments);g!=o&&this.appendChild(document.createTextNode(g))}if(arguments.length<1)return f(function(){return this.textContent});a.each(function(){for(;this.lastChild;)this.removeChild(this.lastChild)});return d==o?a:a.each(typeof d=="function"?i:e)};a.html=function(d){function e(){this.innerHTML=d}function i(){this.innerHTML=d.apply(this,arguments)}if(arguments.length<1)return f(function(){return this.innerHTML});return a.each(typeof d=="function"?i:e)};a.append=function(d){function e(g){return g.appendChild(document.createElement(d))}
<add>function i(g){return g.appendChild(document.createElementNS(d.space,d.local))}d=d3.ns.qualify(d);return b(d.local?i:e)};a.remove=function(){return b(function(d){var e=d.parentNode;e.removeChild(d);return e})};a.sort=function(d){d=ya.apply(this,arguments);for(var e=0,i=a.length;e<i;e++){var g=a[e];g.sort(d);for(var h=1,j=g.length,l=g[0];h<j;h++){var p=g[h];if(p){l&&l.parentNode.insertBefore(p,l.nextSibling);l=p}}}return a};a.on=function(d,e){d="on"+d;return a.each(function(i,g){this[d]=function(h){var j=
<add>d3.event;d3.event=h;try{e.call(this,i,g)}finally{d3.event=j}}})};a.transition=function(){return Q(a)};a.call=ba;return a}function xa(a){return{nodeKey:function(b){return b.getAttribute(a)},dataKey:function(b){return b[a]}}}function ya(a){if(!arguments.length)a=d3.u;return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}d3.transition=P.transition;var za=0,R=0;
<add>function Q(a){function b(k){var n=true,r=-1;a.each(function(){if(h[++r]!=2){var m=(k-j[r])/l[r],t=this.__transition__,u,s,v=e[r];if(m<1){n=false;if(m<0)return}else m=1;if(h[r]){if(t.d!=f){h[r]=2;return}}else if(!t||t.d>f){h[r]=2;return}else{h[r]=1;g.start.dispatch.apply(this,arguments);v=e[r]={};t.d=f;for(s in d)v[s]=d[s].apply(this,arguments)}u=q(m);for(s in d)v[s].call(this,u);if(m==1){h[r]=2;if(t.d==f){m=t.o;if(m==f){delete this.__transition__;i&&this.parentNode.removeChild(this)}R=f;g.end.dispatch.apply(this,
<add>arguments);R=0;t.o=m}}}});return n}var c={},f=R||++za,d={},e=[],i=false,g=d3.dispatch("start","end"),h=[],j=[],l=[],p,q=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).o=f});c.delay=function(k){var n=Infinity,r=-1;if(typeof k=="function")a.each(function(){var m=j[++r]=+k.apply(this,arguments);if(m<n)n=m});else{n=+k;a.each(function(){j[++r]=n})}Aa(b,n);return c};c.duration=function(k){var n=-1;if(typeof k=="function"){p=0;a.each(function(){var r=l[++n]=+k.apply(this,
<add>arguments);if(r>p)p=r})}else{p=+k;a.each(function(){l[++n]=p})}return c};c.ease=function(k){q=typeof k=="string"?d3.ease(k):k;return c};c.attrTween=function(k,n){function r(t,u){var s=n.call(this,t,u,this.getAttribute(k));return function(v){this.setAttribute(k,s(v))}}function m(t,u){var s=n.call(this,t,u,this.getAttributeNS(k.space,k.local));return function(v){this.setAttributeNS(k.space,k.local,s(v))}}d["attr."+k]=k.local?m:r;return c};c.attr=function(k,n){return c.attrTween(k,Ba(n))};c.styleTween=
<add>function(k,n,r){d["style."+k]=function(m,t){var u=n.call(this,m,t,window.getComputedStyle(this,o).getPropertyValue(k));return function(s){this.style.setProperty(k,u(s),r)}};return c};c.style=function(k,n,r){return c.styleTween(k,Ba(n),r)};c.select=function(k){var n;k=Q(a.select(k)).ease(q);n=-1;k.delay(function(){return j[++n]});n=-1;k.duration(function(){return l[++n]});return k};c.selectAll=function(k){var n;k=Q(a.selectAll(k)).ease(q);n=-1;k.delay(function(r,m){return j[m?n:++n]});n=-1;k.duration(function(r,
<add>m){return l[m?n:++n]});return k};c.remove=function(){i=true;return c};c.each=function(k,n){g[k].add(n);return c};c.call=ba;return c.delay(0).duration(250)}var S=o,T=0,U;function Aa(a,b){var c=Date.now(),f=false,d=c+b,e=S;if(isFinite(b)){for(;e;){if(e.n==a){e.j=c;e.delay=b;f=true}else{var i=e.j+e.delay;if(i<d)d=i}e=e.next}f||(S={n:a,j:c,delay:b,next:S});if(!U){clearTimeout(T);T=setTimeout(Ca,Math.max(24,d-c))}}}function Ca(){U=setInterval(Da,24);T=0}
<add>function Da(){for(var a,b=Date.now(),c=S;c;){a=b-c.j;if(a>c.delay)c.t=c.n(a);c=c.next}a=o;for(b=S;b;)b=b.t?a?a.next=b.next:S=b.next:(a=b).next;a||(U=clearInterval(U))}function Ba(a){return typeof a=="function"?function(b,c,f){return d3.interpolate(f,a.call(this,b,c))}:function(b,c,f){return d3.interpolate(f,a)}}d3.scale={};
<add>d3.scale.linear=function(){function a(j){return h((j-c)*i)}function b(j){var l=Math.min(c,f),p=Math.max(c,f),q=p-l,k=Math.pow(10,Math.floor(Math.log(q/j)/Math.LN10));j=j/(q/k);if(j<=0.15)k*=10;else if(j<=0.35)k*=5;else if(j<=0.75)k*=2;return{start:Math.ceil(l/k)*k,stop:Math.floor(p/k)*k+k*0.5,q:k}}var c=0,f=1,d=0,e=1,i=1/(f-c),g=(f-c)/(e-d),h=d3.interpolate(d,e);a.invert=function(j){return(j-d)*g+c};a.domain=function(j){if(!arguments.length)return[c,f];c=j[0];f=j[1];i=1/(f-c);g=(f-c)/(e-d);return a};
<add>a.range=function(j){if(!arguments.length)return[d,e];d=j[0];e=j[1];g=(f-c)/(e-d);h=d3.interpolate(d,e);return a};a.ticks=function(j){j=b(j);return d3.range(j.start,j.stop,j.q)};a.tickFormat=function(j){return d3.format(",."+Math.max(0,-Math.floor(Math.log(b(j).q)/Math.LN10+0.01))+"f")};return a};
<add>d3.scale.log=function(){function a(d){return Math.log(d)/Math.LN10}function b(d){return Math.pow(10,d)}function c(d){return f(a(d))}var f=d3.scale.linear();c.invert=function(d){return b(f.invert(d))};c.domain=function(d){if(!arguments.length)return f.domain().map(b);f.domain(d.map(a));return c};c.range=function(){var d=f.range.apply(f,arguments);return arguments.length?c:d};c.ticks=function(){var d=f.domain(),e=Math.floor(d[0]),i=Math.ceil(d[1]),g=[];if(d.every(isFinite)){for(;++e<=i;)for(d=1;d<10;d++)g.push(b(e)*
<ide> d);g.push(b(e))}return g};c.tickFormat=function(){return function(d){return d.toPrecision(1)}};return c};
<del>d3.scale.pow=function(){function a(h){return Math.pow(h,d)}function b(h){return Math.pow(h,e)}function c(h){return f(a(h))}var f=d3.scale.linear(),d=1,e=1/d;c.invert=function(h){return b(f.invert(h))};c.domain=function(h){if(!arguments.length)return f.domain().map(b);f.domain(h.map(a));return c};c.range=function(){var h=f.range.apply(f,arguments);return arguments.length?c:h};c.ticks=function(h){return d3.scale.linear().domain(c.domain()).ticks(h)};c.tickFormat=function(h){return d3.scale.linear().domain(c.domain()).tickFormat(h)};
<del>c.exponent=function(h){if(!arguments.length)return d;var g=c.domain();d=h;e=1/h;return c.domain(g)};return c};d3.scale.sqrt=function(){return d3.scale.pow().exponent(0.5)};
<del>d3.scale.ordinal=function(){function a(e){e=e in c?c[e]:c[e]=b.push(e)-1;return f[e%f.length]}var b=[],c={},f=[],d=0;a.domain=function(e){if(!arguments.length)return b;b=e;c={};for(var h=-1,g=-1,i=b.length;++h<i;){e=b[h];e in c||(c[e]=++g)}return a};a.range=function(e){if(!arguments.length)return f;f=e;return a};a.rangePoints=function(e,h){if(arguments.length<2)h=0;var g=e[0],i=e[1],j=(i-g)/(b.length-1+h);f=b.length==1?[(g+i)/2]:d3.range(g+j*h/2,i+j/2,j);d=0;return a};a.rangeBands=function(e,h){if(arguments.length<
<del>2)h=0;var g=e[0],i=e[1],j=(i-g)/(b.length+h);f=d3.range(g+j*h,i,j);d=j*(1-h);return a};a.rangeBand=function(){return d};return a};d3.scale.category10=function(){return d3.scale.ordinal().range(Ea)};d3.scale.category20=function(){return d3.scale.ordinal().range(Fa)};d3.scale.category20b=function(){return d3.scale.ordinal().range(Ha)};d3.scale.category20c=function(){return d3.scale.ordinal().range(Ia)};
<add>d3.scale.pow=function(){function a(i){return Math.pow(i,d)}function b(i){return Math.pow(i,e)}function c(i){return f(a(i))}var f=d3.scale.linear(),d=1,e=1/d;c.invert=function(i){return b(f.invert(i))};c.domain=function(i){if(!arguments.length)return f.domain().map(b);f.domain(i.map(a));return c};c.range=function(){var i=f.range.apply(f,arguments);return arguments.length?c:i};c.ticks=function(i){return d3.scale.linear().domain(c.domain()).ticks(i)};c.tickFormat=function(i){return d3.scale.linear().domain(c.domain()).tickFormat(i)};
<add>c.exponent=function(i){if(!arguments.length)return d;var g=c.domain();d=i;e=1/i;return c.domain(g)};return c};d3.scale.sqrt=function(){return d3.scale.pow().exponent(0.5)};
<add>d3.scale.ordinal=function(){function a(e){e=e in c?c[e]:c[e]=b.push(e)-1;return f[e%f.length]}var b=[],c={},f=[],d=0;a.domain=function(e){if(!arguments.length)return b;b=e;c={};for(var i=-1,g=-1,h=b.length;++i<h;){e=b[i];e in c||(c[e]=++g)}return a};a.range=function(e){if(!arguments.length)return f;f=e;return a};a.rangePoints=function(e,i){if(arguments.length<2)i=0;var g=e[0],h=e[1],j=(h-g)/(b.length-1+i);f=b.length==1?[(g+h)/2]:d3.range(g+j*i/2,h+j/2,j);d=0;return a};a.rangeBands=function(e,i){if(arguments.length<
<add>2)i=0;var g=e[0],h=e[1],j=(h-g)/(b.length+i);f=d3.range(g+j*i,h,j);d=j*(1-i);return a};a.rangeBand=function(){return d};return a};d3.scale.category10=function(){return d3.scale.ordinal().range(Ea)};d3.scale.category20=function(){return d3.scale.ordinal().range(Fa)};d3.scale.category20b=function(){return d3.scale.ordinal().range(Ha)};d3.scale.category20c=function(){return d3.scale.ordinal().range(Ia)};
<ide> var Ea=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],Fa=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],Ha=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd",
<ide> "#de9ed6"],Ia=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.svg={};
<del>d3.svg.arc=function(){function a(e,h){var g=b.call(this,e,h),i=c.call(this,e,h),j=f.call(this,e,h)+V,l=d.call(this,e,h)+V,p=l-j,r=Math.cos(j);j=Math.sin(j);var k=Math.cos(l);l=Math.sin(l);return"M"+i*r+","+i*j+"A"+i+","+i+" 0 "+(p<Math.PI?"0":"1")+",1 "+i*k+","+i*l+"L"+g*k+","+g*l+"A"+g+","+g+" 0 "+(p<Math.PI?"0":"1")+",0 "+g*r+","+g*j+"Z"}var b=Ja,c=Ka,f=La,d=Ma;a.innerRadius=function(e){if(!arguments.length)return b;b=y(e);return a};a.outerRadius=function(e){if(!arguments.length)return c;c=y(e);
<del>return a};a.startAngle=function(e){if(!arguments.length)return f;f=y(e);return a};a.endAngle=function(e){if(!arguments.length)return d;d=y(e);return a};return a};var V=-Math.PI/2;function Ja(a){return a.innerRadius}function Ka(a){return a.outerRadius}function La(a){return a.startAngle}function Ma(a){return a.endAngle}
<del>d3.svg.line=function(){function a(e){return e.length<1?n:"M"+d(W(this,e,b,c))}var b=Na,c=Oa,f="linear",d=X[f];a.x=function(e){if(!arguments.length)return b;b=e;return a};a.y=function(e){if(!arguments.length)return c;c=e;return a};a.interpolate=function(e){if(!arguments.length)return f;d=X[f=e];return a};return a};
<del>function W(a,b,c,f){var d=[],e=-1,h=b.length,g=typeof c=="function",i=typeof f=="function",j;if(g&&i)for(;++e<h;)d.push([c.call(a,j=b[e],e),f.call(a,j,e)]);else if(g)for(;++e<h;)d.push([c.call(a,b[e],e),f]);else if(i)for(;++e<h;)d.push([c,f.call(a,b[e],e)]);else for(;++e<h;)d.push([c,f]);return d}function Na(a){return a.x}function Oa(a){return a.y}var X={linear:Pa,basis:Qa};
<del>function Pa(a){if(a.length<1)return n;var b=[],c=0,f=a.length,d=a[0];for(b.push(d[0],",",d[1]);++c<f;)b.push("L",(d=a[c])[0],",",d[1]);return b.join("")}function Qa(a){if(a.length<3)return Pa(a);var b=[],c=1,f=a.length,d=a[0],e=d[0],h=d[1],g=[e,e,e,(d=a[1])[0]],i=[h,h,h,d[1]];b.push(e,",",h);for(Y(b,g,i);++c<f;){d=a[c];g.shift();g.push(d[0]);i.shift();i.push(d[1]);Y(b,g,i)}for(c=-1;++c<2;){g.shift();g.push(d[0]);i.shift();i.push(d[1]);Y(b,g,i)}return b.join("")}
<add>d3.svg.arc=function(){function a(e,i){var g=b.call(this,e,i),h=c.call(this,e,i),j=f.call(this,e,i)+V,l=d.call(this,e,i)+V,p=l-j,q=p<Math.PI?"0":"1",k=Math.cos(j);j=Math.sin(j);var n=Math.cos(l);l=Math.sin(l);return p>=2*Math.PI?g?"M0,"+h+"A"+h+","+h+" 0 1,1 0,"+-h+"A"+h+","+h+" 0 1,1 0,"+h+"M0,"+g+"A"+g+","+g+" 0 1,1 0,"+-g+"A"+g+","+g+" 0 1,1 0,"+g+"Z":"M0,"+h+"A"+h+","+h+" 0 1,1 0,"+-h+"A"+h+","+h+" 0 1,1 0,"+h+"Z":g?"M"+h*k+","+h*j+"A"+h+","+h+" 0 "+q+",1 "+h*n+","+h*l+"L"+g*n+","+g*l+"A"+g+","+
<add>g+" 0 "+q+",0 "+g*k+","+g*j+"Z":"M"+h*k+","+h*j+"A"+h+","+h+" 0 "+q+",1 "+h*n+","+h*l+"L0,0Z"}var b=Ja,c=Ka,f=La,d=Ma;a.innerRadius=function(e){if(!arguments.length)return b;b=y(e);return a};a.outerRadius=function(e){if(!arguments.length)return c;c=y(e);return a};a.startAngle=function(e){if(!arguments.length)return f;f=y(e);return a};a.endAngle=function(e){if(!arguments.length)return d;d=y(e);return a};return a};var V=-Math.PI/2;function Ja(a){return a.innerRadius}
<add>function Ka(a){return a.outerRadius}function La(a){return a.startAngle}function Ma(a){return a.endAngle}d3.svg.line=function(){function a(e){return e.length<1?o:"M"+d(W(this,e,b,c))}var b=Na,c=Oa,f="linear",d=X[f];a.x=function(e){if(!arguments.length)return b;b=e;return a};a.y=function(e){if(!arguments.length)return c;c=e;return a};a.interpolate=function(e){if(!arguments.length)return f;d=X[f=e];return a};return a};
<add>function W(a,b,c,f){var d=[],e=-1,i=b.length,g=typeof c=="function",h=typeof f=="function",j;if(g&&h)for(;++e<i;)d.push([c.call(a,j=b[e],e),f.call(a,j,e)]);else if(g)for(;++e<i;)d.push([c.call(a,b[e],e),f]);else if(h)for(;++e<i;)d.push([c,f.call(a,b[e],e)]);else for(;++e<i;)d.push([c,f]);return d}function Na(a){return a.x}function Oa(a){return a.y}var X={linear:Pa,basis:Qa};
<add>function Pa(a){if(a.length<1)return o;var b=[],c=0,f=a.length,d=a[0];for(b.push(d[0],",",d[1]);++c<f;)b.push("L",(d=a[c])[0],",",d[1]);return b.join("")}function Qa(a){if(a.length<3)return Pa(a);var b=[],c=1,f=a.length,d=a[0],e=d[0],i=d[1],g=[e,e,e,(d=a[1])[0]],h=[i,i,i,d[1]];b.push(e,",",i);for(Y(b,g,h);++c<f;){d=a[c];g.shift();g.push(d[0]);h.shift();h.push(d[1]);Y(b,g,h)}for(c=-1;++c<2;){g.shift();g.push(d[0]);h.shift();h.push(d[1]);Y(b,g,h)}return b.join("")}
<ide> function Z(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}var Ra=[0,2/3,1/3,0],Sa=[0,1/3,2/3,0],Ta=[0,1/6,2/3,1/6];function Y(a,b,c){a.push("C",Z(Ra,b),",",Z(Ra,c),",",Z(Sa,b),",",Z(Sa,c),",",Z(Ta,b),",",Z(Ta,c))}
<del>d3.svg.area=function(){function a(h){return h.length<1?n:"M"+e(W(this,h,b,f))+"L"+e(W(this,h,b,c).reverse())+"Z"}var b=Na,c=Ua,f=Oa,d="linear",e=X[d];a.x=function(h){if(!arguments.length)return b;b=h;return a};a.y0=function(h){if(!arguments.length)return c;c=h;return a};a.y1=function(h){if(!arguments.length)return f;f=h;return a};a.interpolate=function(h){if(!arguments.length)return d;e=X[d=h];return a};return a};function Ua(){return 0}
<del>d3.svg.chord=function(){function a(g,i){var j=b(this,c,g,i),l=b(this,f,g,i);return"M"+j.c+("A"+j.r+","+j.r+" 0 0,1 "+j.p)+(j.k==l.k&&j.m==l.m?"Q 0,0 "+j.c:"Q 0,0 "+l.c+("A"+l.r+","+l.r+" 0 0,1 "+l.p)+("Q 0,0 "+j.c))+"Z"}function b(g,i,j,l){var p=i.call(g,j,l);i=d.call(g,p,l);j=e.call(g,p,l)+V;g=h.call(g,p,l)+V;return{r:i,k:j,m:g,c:[i*Math.cos(j),i*Math.sin(j)],p:[i*Math.cos(g),i*Math.sin(g)]}}var c=Va,f=Wa,d=Xa,e=La,h=Ma;a.radius=function(g){if(!arguments.length)return d;d=y(g);return a};a.source=
<del>function(g){if(!arguments.length)return c;c=y(g);return a};a.target=function(g){if(!arguments.length)return f;f=y(g);return a};a.startAngle=function(g){if(!arguments.length)return e;e=y(g);return a};a.endAngle=function(g){if(!arguments.length)return h;h=y(g);return a};return a};function Va(a){return a.source}function Wa(a){return a.target}function Xa(a){return a.radius}
<add>d3.svg.area=function(){function a(i){return i.length<1?o:"M"+e(W(this,i,b,f))+"L"+e(W(this,i,b,c).reverse())+"Z"}var b=Na,c=Ua,f=Oa,d="linear",e=X[d];a.x=function(i){if(!arguments.length)return b;b=i;return a};a.y0=function(i){if(!arguments.length)return c;c=i;return a};a.y1=function(i){if(!arguments.length)return f;f=i;return a};a.interpolate=function(i){if(!arguments.length)return d;e=X[d=i];return a};return a};function Ua(){return 0}
<add>d3.svg.chord=function(){function a(g,h){var j=b(this,c,g,h),l=b(this,f,g,h);return"M"+j.c+("A"+j.r+","+j.r+" 0 0,1 "+j.p)+(j.k==l.k&&j.m==l.m?"Q 0,0 "+j.c:"Q 0,0 "+l.c+("A"+l.r+","+l.r+" 0 0,1 "+l.p)+("Q 0,0 "+j.c))+"Z"}function b(g,h,j,l){var p=h.call(g,j,l);h=d.call(g,p,l);j=e.call(g,p,l)+V;g=i.call(g,p,l)+V;return{r:h,k:j,m:g,c:[h*Math.cos(j),h*Math.sin(j)],p:[h*Math.cos(g),h*Math.sin(g)]}}var c=Va,f=Wa,d=Xa,e=La,i=Ma;a.radius=function(g){if(!arguments.length)return d;d=y(g);return a};a.source=
<add>function(g){if(!arguments.length)return c;c=y(g);return a};a.target=function(g){if(!arguments.length)return f;f=y(g);return a};a.startAngle=function(g){if(!arguments.length)return e;e=y(g);return a};a.endAngle=function(g){if(!arguments.length)return i;i=y(g);return a};return a};function Va(a){return a.source}function Wa(a){return a.target}function Xa(a){return a.radius}
<ide> d3.svg.mouse=function(a){var b=(a.ownerSVGElement||a).createSVGPoint();if($<0&&(window.scrollX||window.scrollY)){var c=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),f=c[0][0].getScreenCTM();$=!(f.f||f.e);c.remove()}if($){b.x=d3.event.pageX;b.y=d3.event.pageY}else{b.x=d3.event.clientX;b.y=d3.event.clientY}b=b.matrixTransform(a.getScreenCTM().inverse());return[b.x,b.y]};var $=/WebKit/.test(navigator.userAgent)?-1:0;})()
<ide><path>src/core/core.js
<del>d3 = {version: "0.28.2"}; // semver
<add>d3 = {version: "0.28.3"}; // semver
<ide><path>src/svg/arc.js
<ide> d3["svg"]["arc"] = function() {
<ide> a0 = startAngle.call(this, d, i) + d3_svg_arcOffset,
<ide> a1 = endAngle.call(this, d, i) + d3_svg_arcOffset,
<ide> da = a1 - a0,
<add> df = da < Math.PI ? "0" : "1",
<ide> c0 = Math.cos(a0),
<ide> s0 = Math.sin(a0),
<ide> c1 = Math.cos(a1),
<ide> s1 = Math.sin(a1);
<del> return "M" + r1 * c0 + "," + r1 * s0
<del> + "A" + r1 + "," + r1 + " 0 "
<del> + ((da < Math.PI) ? "0" : "1") + ",1 "
<del> + r1 * c1 + "," + r1 * s1
<del> + "L" + r0 * c1 + "," + r0 * s1
<del> + "A" + r0 + "," + r0 + " 0 "
<del> + ((da < Math.PI) ? "0" : "1") + ",0 "
<del> + r0 * c0 + "," + r0 * s0 + "Z";
<add> return da >= 2 * Math.PI
<add> ? (r0
<add> ? "M0," + r1
<add> + "A" + r1 + "," + r1 + " 0 1,1 0," + (-r1)
<add> + "A" + r1 + "," + r1 + " 0 1,1 0," + r1
<add> + "M0," + r0
<add> + "A" + r0 + "," + r0 + " 0 1,1 0," + (-r0)
<add> + "A" + r0 + "," + r0 + " 0 1,1 0," + r0
<add> + "Z"
<add> : "M0," + r1
<add> + "A" + r1 + "," + r1 + " 0 1,1 0," + (-r1)
<add> + "A" + r1 + "," + r1 + " 0 1,1 0," + r1
<add> + "Z")
<add> : (r0
<add> ? "M" + r1 * c0 + "," + r1 * s0
<add> + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1
<add> + "L" + r0 * c1 + "," + r0 * s1
<add> + "A" + r0 + "," + r0 + " 0 " + df + ",0 " + r0 * c0 + "," + r0 * s0
<add> + "Z"
<add> : "M" + r1 * c0 + "," + r1 * s0
<add> + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1
<add> + "L0,0"
<add> + "Z");
<ide> }
<ide>
<ide> arc["innerRadius"] = function(v) { | 4 |
Ruby | Ruby | improve dash separated version detection | e1dfafa54ccf95d6abe5de28da53ea1e6406f567 | <ide><path>Library/Homebrew/test/test_versions.rb
<ide> def test_opam_version
<ide> def test_waf_version
<ide> assert_version_detected "1.8.12", "https://waf.io/waf-1.8.12"
<ide> end
<add>
<add> def test_dash_separated_version
<add> assert_version_detected "6-20151227", "ftp://gcc.gnu.org/pub/gcc/snapshots/6-20151227/gcc-6-20151227.tar.bz2"
<add> end
<ide> end
<ide><path>Library/Homebrew/version.rb
<ide> def self._parse(spec)
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # e.g. lame-398-1
<del> m = /-((?:\d)+-\d)/.match(stem)
<add> m = /-((?:\d)+-\d+)/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # e.g. foobar-4.5.1 | 2 |
Ruby | Ruby | remove unused classes | 0d7ab973e15b476ed42471395027e329f95c8951 | <ide><path>activerecord/lib/active_record/associations.rb
<ide> class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAsso
<ide> class HasOneThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAssociateThroughHasOneOrManyReflection #:nodoc:
<ide> end
<ide>
<del> class HasManyThroughCantAssociateNewRecords < ActiveRecordError #:nodoc:
<del> def initialize(owner = nil, reflection = nil)
<del> if owner && reflection
<del> super("Cannot associate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to create the has_many :through record associating them.")
<del> else
<del> super("Cannot associate new records.")
<del> end
<del> end
<del> end
<del>
<del> class HasManyThroughCantDissociateNewRecords < ActiveRecordError #:nodoc:
<del> def initialize(owner = nil, reflection = nil)
<del> if owner && reflection
<del> super("Cannot dissociate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to delete the has_many :through record associating them.")
<del> else
<del> super("Cannot dissociate new records.")
<del> end
<del> end
<del> end
<del>
<ide> class ThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc:
<ide> def initialize(owner = nil, reflection = nil)
<ide> if owner && reflection
<ide> def initialize(reflection = nil)
<ide> end
<ide> end
<ide>
<del> class ReadOnlyAssociation < ActiveRecordError #:nodoc:
<del> def initialize(reflection = nil)
<del> if reflection
<del> super("Cannot add to a has_many :through association. Try adding to #{reflection.through_reflection.name.inspect}.")
<del> else
<del> super("Read-only reflection error.")
<del> end
<del> end
<del> end
<del>
<ide> # This error is raised when trying to destroy a parent instance in N:1 or 1:1 associations
<ide> # (has_many, has_one) when there is at least 1 child associated instance.
<ide> # ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project | 1 |
Text | Text | add example link to faq section | 5f1964885601c7d2cd38f360a87331abf3dc2ac9 | <ide><path>README.md
<ide> Atomic Flux with hot reloading.
<ide> - [Running the same code on client and server](#running-the-same-code-on-client-and-server)
<ide> - [Additional customization](#additional-customization)
<ide> - [FAQ](#faq)
<add> - [Any examples with data fetching and `react-router`?](#any-examples-with-data-fetching-and-react-router)
<ide> - [How does hot reloading work?](#how-does-hot-reloading-work)
<ide> - [Can I use this in production?](#can-i-use-this-in-production)
<ide> - [How do I do async?](#how-do-i-do-async)
<ide> When in doubt, use the shorter option!
<ide>
<ide> ## FAQ
<ide>
<add>### Any examples with data fetching and `react-router`?
<add>
<add>Besised the examples in this repo, there is an [officially supported example](https://github.com/emmenko/redux-react-router-async-example) (_still WIP_) tackling those implementations.
<add>
<ide> ### How does hot reloading work?
<ide>
<ide> * http://webpack.github.io/docs/hot-module-replacement.html | 1 |
Python | Python | improve readability of pull request 15286 | 7658bfc42984b702e9a211d0e92eef83a338eba6 | <ide><path>keras/utils/vis_utils.py
<ide> def format_shape(shape):
<ide> [format_shape(ishape) for ishape in layer.input_shapes])
<ide> else:
<ide> inputlabels = '?'
<del> label = f'{label}|{{input:|output:}}|' \
<del> + f'{{{{{inputlabels}}}|{{{outputlabels}}}}}'
<del>
<add> label = '{%s}|{input:|output:}|{{%s}}|{{%s}}' % (
<add> label, inputlabels, outputlabels)
<ide> if not expand_nested or not isinstance(
<ide> layer, functional.Functional):
<ide> node = pydot.Node(layer_id, label=label) | 1 |
Javascript | Javascript | fix view destruction inside outlets | 1fc7811a45dfb6184667364067203db4e2ff45dc | <ide><path>packages/ember-htmlbars/lib/keywords/real_outlet.js
<ide> export default {
<ide> toRender.template = topLevelViewTemplate;
<ide> }
<ide>
<del> return { outletState: selectedOutletState, hasParentOutlet: env.hasParentOutlet };
<add> return {
<add> outletState: selectedOutletState,
<add> hasParentOutlet: env.hasParentOutlet,
<add> manager: state.manager
<add> };
<ide> },
<ide>
<ide> childEnv(state, env) {
<ide> export default {
<ide> Ember.Logger.info('Rendering ' + toRender.name + ' with ' + ViewClass, { fullName: 'view:' + toRender.name });
<ide> }
<ide>
<add> if (state.manager) {
<add> state.manager.destroy();
<add> state.manager = null;
<add> }
<add>
<ide> var nodeManager = ViewNodeManager.create(renderNode, env, {}, options, parentView, null, null, template);
<ide> state.manager = nodeManager;
<ide>
<ide><path>packages/ember-htmlbars/lib/node-managers/view-node-manager.js
<ide> ViewNodeManager.prototype.rerender = function(env, attrs, visitor) {
<ide> };
<ide>
<ide> ViewNodeManager.prototype.destroy = function() {
<del> this.component.destroy();
<add> if (this.component) {
<add> this.component.destroy();
<add> this.component = null;
<add> }
<ide> };
<ide>
<ide> function getTemplate(componentOrView) {
<ide><path>packages/ember-metal-views/lib/renderer.js
<ide> Renderer.prototype.renderElementRemoval =
<ide> if (view._willRemoveElement) {
<ide> view._willRemoveElement = false;
<ide>
<del> if (view._renderNode) {
<add> if (view._renderNode && view.element && view.element.parentNode) {
<ide> view._renderNode.clear();
<ide> }
<ide> this.didDestroyElement(view); | 3 |
Python | Python | remove jinja 'autoescape' and 'with' extensions | 81ba6c24efea58dd00c093448fa2e529c0cda507 | <ide><path>src/flask/app.py
<ide> class Flask(Scaffold):
<ide> #: This is a ``dict`` instead of an ``ImmutableDict`` to allow
<ide> #: easier configuration.
<ide> #:
<del> jinja_options = {"extensions": ["jinja2.ext.autoescape", "jinja2.ext.with_"]}
<add> jinja_options = {}
<ide>
<ide> #: Default configuration parameters.
<ide> default_config = ImmutableDict( | 1 |
Text | Text | fix incorrect name in report docs | 306d240b019cc9c2fa485213d5a998fa401b7883 | <ide><path>doc/api/report.md
<ide> is provided below for reference.
<ide> "osRelease": "3.10.0-862.el7.x86_64",
<ide> "osVersion": "#1 SMP Wed Mar 21 18:14:51 EDT 2018",
<ide> "osMachine": "x86_64",
<del> "osCpus": [
<add> "cpus": [
<ide> {
<ide> "model": "Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz",
<ide> "speed": 2700, | 1 |
PHP | PHP | load appshell class | eecd91e99fd2cde8eac73554bfbe30926d5c708d | <ide><path>lib/Cake/Console/ShellDispatcher.php
<ide> protected function _getShell($shell) {
<ide> $class = Inflector::camelize($shell) . 'Shell';
<ide>
<ide> App::uses('Shell', 'Console');
<add> App::uses('AppShell', 'Console');
<ide> App::uses($class, $plugin . 'Console/Command');
<ide>
<ide> if (!class_exists($class)) { | 1 |
Text | Text | add missing semicolon | 9ae490501bbae975ac992e617ec79322764f7c9d | <ide><path>docs/advanced/ExampleRedditAPI.md
<ide> function fetchPosts(reddit) {
<ide> return fetch(`http://www.reddit.com/r/${reddit}.json`)
<ide> .then(req => req.json())
<ide> .then(json => dispatch(receivePosts(reddit, json)));
<del> }
<add> };
<ide> }
<ide>
<ide> function shouldFetchPosts(state, reddit) { | 1 |
Python | Python | improve descriptions of go_backwards parameters. | f9c9c0ab3fd2ce9613f110b5b229ac0fc0e51b82 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def rnn(step_function, inputs, initial_states,
<ide> (no time dimension),
<ide> containing the initial values for the states used in
<ide> the step function.
<del> go_backwards: boolean. If True, do the iteration over
<del> the time dimension in reverse order.
<add> go_backwards: boolean. If True, do the iteration over the time
<add> dimension in reverse order and return the reversed sequence.
<ide> mask: binary tensor with shape `(samples, time, 1)`,
<ide> with a zero for every element that is masked.
<ide> constants: a list of constant values passed at each step.
<ide><path>keras/backend/theano_backend.py
<ide> def rnn(step_function, inputs, initial_states,
<ide> initial_states: tensor with shape (samples, ...) (no time dimension),
<ide> containing the initial values for the states used in
<ide> the step function.
<del> go_backwards: boolean. If True, do the iteration over
<del> the time dimension in reverse order.
<add> go_backwards: boolean. If True, do the iteration over the time
<add> dimension in reverse order and return the reversed sequence.
<ide> mask: binary tensor with shape (samples, time),
<ide> with a zero for every element that is masked.
<ide> constants: a list of constant values passed at each step.
<ide><path>keras/layers/recurrent.py
<ide> class Recurrent(Layer):
<ide> return_sequences: Boolean. Whether to return the last output
<ide> in the output sequence, or the full sequence.
<ide> go_backwards: Boolean (default False).
<del> If True, process the input sequence backwards.
<add> If True, process the input sequence backwards and return the
<add> reversed sequence.
<ide> stateful: Boolean (default False). If True, the last state
<ide> for each sample at index i in a batch will be used as initial
<ide> state for the sample of index i in the following batch. | 3 |
Go | Go | prevent panic upon error pulling registry | e836b0064bc18300ca9213c749f464e52ca9d001 | <ide><path>registry/registry.go
<ide> func (r *Registry) GetRemoteHistory(imgID, registry string, token []string) ([]s
<ide> req.Header.Set("Authorization", "Token "+strings.Join(token, ", "))
<ide> res, err := doWithCookies(r.client, req)
<ide> if err != nil || res.StatusCode != 200 {
<del> if res.StatusCode == 401 {
<del> return nil, ErrLoginRequired
<del> }
<ide> if res != nil {
<add> if res.StatusCode == 401 {
<add> return nil, ErrLoginRequired
<add> }
<ide> return nil, utils.NewHTTPRequestError(fmt.Sprintf("Internal server error: %d trying to fetch remote history for %s", res.StatusCode, imgID), res)
<ide> }
<ide> return nil, err | 1 |
Javascript | Javascript | handle pipechunksize properly | ac5a185edf16efb7738c00f4d35f00bc2f93bf04 | <ide><path>lib/_stream_readable.js
<ide> function ReadableState(options, stream) {
<ide>
<ide> // the number of writers that are awaiting a drain event in .pipe()s
<ide> this.awaitDrain = 0;
<del> this.flowChunkSize = null;
<add> this.pipeChunkSize = null;
<ide>
<ide> this.decoder = null;
<ide> if (options.encoding) {
<ide> function howMuchToRead(n, state) {
<ide> if (state.length === 0 && state.ended)
<ide> return 0;
<ide>
<del> if (isNaN(n))
<add> if (isNaN(n) || n === null)
<ide> return state.length;
<ide>
<ide> if (n <= 0)
<ide> function onread(stream, er, chunk) {
<ide>
<ide> // if we haven't gotten enough to pass the lowWaterMark,
<ide> // and we haven't ended, then don't bother telling the user
<del> // that it's time to read more data. Otherwise, that'll
<del> // probably kick off another stream.read(), which can trigger
<add> // that it's time to read more data. Otherwise, emitting 'readable'
<add> // probably will trigger another stream.read(), which can trigger
<ide> // another _read(n,cb) before this one returns!
<ide> if (state.length <= state.lowWaterMark) {
<ide> state.reading = true;
<ide> Readable.prototype.pipe = function(dest, pipeOpts) {
<ide> }
<ide>
<ide> if (pipeOpts && pipeOpts.chunkSize)
<del> state.flowChunkSize = pipeOpts.chunkSize;
<add> state.pipeChunkSize = pipeOpts.chunkSize;
<ide>
<ide> function onend() {
<ide> dest.end();
<ide> }
<ide>
<add> // when the dest drains, it reduces the awaitDrain counter
<add> // on the source. This would be more elegant with a .once()
<add> // handler in flow(), but adding and removing repeatedly is
<add> // too slow.
<add> var ondrain = pipeOnDrain(src);
<add> dest.on('drain', ondrain);
<add> dest.on('unpipe', function(readable) {
<add> if (readable === src)
<add> dest.removeListener('drain', ondrain);
<add>
<add> // if the reader is waiting for a drain event from this
<add> // specific writer, then it would cause it to never start
<add> // flowing again.
<add> // So, if this is awaiting a drain, then we just call it now.
<add> // If we don't know, then assume that we are waiting for one.
<add> if (!dest._writableState || dest._writableState.needDrain)
<add> ondrain();
<add> });
<add>
<add> // tell the dest that it's being piped to
<ide> dest.emit('pipe', src);
<ide>
<del> // start the flow.
<add> // start the flow if it hasn't been started already.
<ide> if (!state.flowing) {
<ide> // the handler that waits for readable events after all
<ide> // the data gets sucked out in flow.
<ide> // This would be easier to follow with a .once() handler
<ide> // in flow(), but that is too slow.
<ide> this.on('readable', pipeOnReadable);
<del> var ondrain = pipeOnDrain(src);
<del> dest.on('drain', ondrain);
<del> dest.on('unpipe', function(readable) {
<del> if (readable === src)
<del> dest.removeListener('drain', ondrain);
<del>
<del> // if the reader is waiting for a drain event from this
<del> // specific writer, then it would cause it to never start
<del> // flowing again.
<del> // So, if this is awaiting a drain, then we just call it now.
<del> if (dest._writableState.needDrain)
<del> ondrain();
<del> });
<ide>
<ide> state.flowing = true;
<ide> process.nextTick(function() { | 1 |
Javascript | Javascript | add test for debug usage message | 3dfcb2e266d5e66610de077c25adc93fd552c267 | <ide><path>test/parallel/test-debug-usage.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const spawn = require('child_process').spawn;
<add>
<add>const child = spawn(process.execPath, ['debug']);
<add>child.stderr.setEncoding('utf8');
<add>
<add>const expectedUsageMessage = `Usage: node debug script.js
<add> node debug <host>:<port>
<add> node debug -p <pid>
<add>`;
<add>var actualUsageMessage = '';
<add>child.stderr.on('data', function(data) {
<add> actualUsageMessage += data.toString();
<add>});
<add>
<add>child.on('exit', common.mustCall(function(code) {
<add> assert.strictEqual(code, 1);
<add> assert.strictEqual(actualUsageMessage, expectedUsageMessage);
<add>})); | 1 |
Ruby | Ruby | autosave collection associations exactly once | 21d67f18a46d0be0e113bfd7662308535b001564 | <ide><path>activerecord/lib/active_record/autosave_association.rb
<ide> module ActiveRecord
<ide> # == Callbacks
<ide> #
<ide> # Association with autosave option defines several callbacks on your
<del> # model (before_save, after_create, after_update). Please note that
<add> # model (around_save, before_save, after_create, after_update). Please note that
<ide> # callbacks are executed in the order they were defined in
<ide> # model. You should avoid modifying the association content before
<ide> # autosave callbacks are executed. Placing your callbacks after
<ide> def add_autosave_association_callbacks(reflection)
<ide> save_method = :"autosave_associated_records_for_#{reflection.name}"
<ide>
<ide> if reflection.collection?
<del> before_save :before_save_collection_association
<del> after_save :after_save_collection_association
<add> around_save :around_save_collection_association
<ide>
<ide> define_non_cyclic_method(save_method) { save_collection_association(reflection) }
<ide> # Doesn't use after_save as that would save associations added in after_create/after_update twice
<ide> def normalize_reflection_attribute(indexed_attribute, reflection, index, attribu
<ide> end
<ide> end
<ide>
<del> # Is used as a before_save callback to check while saving a collection
<add> # Is used as an around_save callback to check while saving a collection
<ide> # association whether or not the parent was a new record before saving.
<del> def before_save_collection_association
<del> @new_record_before_save ||= new_record?
<del> end
<add> def around_save_collection_association
<add> previously_new_record_before_save = (@new_record_before_save ||= false)
<add> @new_record_before_save = !previously_new_record_before_save && new_record?
<ide>
<del> def after_save_collection_association
<del> @new_record_before_save = false
<add> yield
<add> ensure
<add> @new_record_before_save = previously_new_record_before_save
<ide> end
<ide>
<ide> # Saves any new associated records, or all loaded autosave associations if
<ide><path>activerecord/test/cases/autosave_association_test.rb
<ide> require "models/bird"
<ide> require "models/post"
<ide> require "models/comment"
<add>require "models/category"
<ide> require "models/company"
<ide> require "models/contract"
<ide> require "models/customer"
<ide> def test_autosave_new_record_with_after_create_callback
<ide>
<ide> assert_not_nil post.author_id
<ide> end
<add>
<add> def test_autosave_new_record_with_after_create_callback_and_habtm_association
<add> post = PostWithAfterCreateCallback.new(title: "Captain Murphy", body: "is back")
<add> post.comments.build(body: "foo")
<add> post.categories.build(name: "bar")
<add> post.save!
<add>
<add> assert_equal 1, post.categories.reload.length
<add> end
<ide> end
<ide>
<ide> class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
<ide><path>activerecord/test/models/post.rb
<ide> class PostWithAfterCreateCallback < ActiveRecord::Base
<ide> self.inheritance_column = :disabled
<ide> self.table_name = "posts"
<ide> has_many :comments, foreign_key: :post_id
<add> has_and_belongs_to_many :categories, foreign_key: :post_id
<ide>
<ide> after_create do |post|
<ide> update_attribute(:author_id, comments.first.id) | 3 |
Ruby | Ruby | implement json v2 | 8c5140f6e6dddcd979ad7c388252199796e4917a | <ide><path>Library/Homebrew/cmd/outdated.rb
<ide> def outdated_args
<ide> def outdated
<ide> outdated_args.parse
<ide>
<del> formula_only = args.formula?
<del> if args.json
<del> raise UsageError, "invalid JSON version: #{args.json}" unless ["v1", true].include? args.json
<add> case json_version
<add> when :v1
<add> outdated = if args.formula? || !args.cask?
<add> outdated_formulae
<add> else
<add> outdated_casks
<add> end
<ide>
<del> # When user asks for json, print json for formula only unless the user explicitly asks for casks
<del> formula_only = !args.cask?
<del> end
<add> puts JSON.generate(json_info(outdated))
<add>
<add> when :v2
<add> formulae, casks = if args.formula?
<add> [outdated_formulae, []]
<add> elsif args.cask?
<add> [[], outdated_casks]
<add> else
<add> outdated_formulae_casks
<add> end
<ide>
<del> outdated = if formula_only
<del> formulae = args.resolved_formulae.presence || Formula.installed
<add> puts JSON.generate({
<add> "formulae" => json_info(formulae),
<add> "casks" => json_info(casks),
<add> })
<ide>
<del> print_outdated_formulae(formulae)
<del> elsif args.cask?
<del> casks = args.named.presence || Cask::Caskroom.casks.presence
<add> outdated = formulae + casks
<ide>
<del> print_outdated_casks(casks)
<ide> else
<del> formulae, casks = args.resolved_formulae_casks
<del>
<del> if formulae.blank? && casks.blank?
<del> formulae = Formula.installed
<del> casks = Cask::Caskroom.casks
<add> outdated = if args.formula?
<add> outdated_formulae
<add> elsif args.cask?
<add> outdated_casks
<add> else
<add> outdated_formulae_casks.flatten
<ide> end
<ide>
<del> print_outdated_formulae(formulae) + print_outdated_casks(casks)
<add> print_outdated(outdated)
<ide> end
<ide>
<ide> Homebrew.failed = args.named.present? && outdated.present?
<ide> end
<ide>
<del> def print_outdated_formulae(formulae)
<del> return print_outdated_formulae_json(formulae) if args.json
<add> def print_outdated(formula_or_cask)
<add> return formula_or_cask.each { |f_or_c| print_outdated(f_or_c) } if formula_or_cask.is_a? Array
<ide>
<del> fetch_head = args.fetch_HEAD?
<add> if formula_or_cask.is_a?(Formula)
<add> f = formula_or_cask
<ide>
<del> outdated_formulae = formulae.select { |f| f.outdated?(fetch_head: fetch_head) }
<del> .sort
<del>
<del> outdated_formulae.each do |f|
<ide> if verbose?
<del> outdated_kegs = f.outdated_kegs(fetch_head: fetch_head)
<add> outdated_kegs = f.outdated_kegs(fetch_head: args.fetch_HEAD?)
<ide>
<ide> current_version = if f.alias_changed?
<ide> latest = f.latest_formula
<ide> def print_outdated_formulae(formulae)
<ide> else
<ide> puts f.full_installed_specified_name
<ide> end
<add> else
<add> c = formula_or_cask
<add>
<add> puts c.outdated_info(args.greedy?, verbose?, false)
<ide> end
<ide> end
<ide>
<del> def print_outdated_formulae_json(formulae)
<del> json = []
<del> fetch_head = args.fetch_HEAD?
<del> outdated_formulae = formulae.select { |f| f.outdated?(fetch_head: fetch_head) }
<add> def json_info(formula_or_cask)
<add> return formula_or_cask.map { |f_or_c| json_info(f_or_c) } if formula_or_cask.is_a? Array
<add>
<add> if formula_or_cask.is_a?(Formula)
<add> f = formula_or_cask
<ide>
<del> outdated = outdated_formulae.each do |f|
<del> outdated_versions = f.outdated_kegs(fetch_head: fetch_head).map(&:version)
<add> outdated_versions = f.outdated_kegs(fetch_head: args.fetch_HEAD?).map(&:version)
<ide> current_version = if f.head? && outdated_versions.any? { |v| v.to_s == f.pkg_version.to_s }
<ide> "HEAD"
<ide> else
<ide> f.pkg_version.to_s
<ide> end
<ide>
<del> json << { name: f.full_name,
<del> installed_versions: outdated_versions.map(&:to_s),
<del> current_version: current_version,
<del> pinned: f.pinned?,
<del> pinned_version: f.pinned_version }
<add> { name: f.full_name,
<add> installed_versions: outdated_versions.map(&:to_s),
<add> current_version: current_version,
<add> pinned: f.pinned?,
<add> pinned_version: f.pinned_version }
<add> else
<add> c = formula_or_cask
<add>
<add> c.outdated_info(args.greedy?, verbose?, true)
<ide> end
<del> puts JSON.generate(json)
<add> end
<ide>
<del> outdated
<add> def verbose?
<add> ($stdout.tty? || args.verbose?) && !args.quiet?
<ide> end
<ide>
<del> def print_outdated_casks(casks)
<del> outdated = casks.map { |cask| Cask::CaskLoader.load(cask) }.select do |cask|
<del> odebug "Checking update info of Cask #{cask}"
<del> cask.outdated?(args.greedy?)
<del> end
<add> def json_version
<add> version_hash = {
<add> nil => nil,
<add> true => :v1,
<add> "v1" => :v1,
<add> "v2" => :v2,
<add> }
<ide>
<del> output = outdated.map { |cask| cask.outdated_info(args.greedy?, verbose?, args.json) }
<del> puts args.json ? JSON.generate(output) : output
<add> raise UsageError, "invalid JSON version: #{args.json}" unless version_hash.include? args.json
<ide>
<del> outdated
<add> version_hash[args.json]
<ide> end
<ide>
<del> def verbose?
<del> ($stdout.tty? || args.verbose?) && !args.quiet?
<add> def outdated_formulae
<add> select_outdated((args.resolved_formulae.presence || Formula.installed)).sort
<add> end
<add>
<add> def outdated_casks
<add> select_outdated(
<add> args.named.present? ? args.named.uniq.map { |ref| Cask::CaskLoader.load ref } : Cask::Caskroom.casks,
<add> )
<add> end
<add>
<add> def outdated_formulae_casks
<add> formulae, casks = args.resolved_formulae_casks
<add>
<add> if formulae.blank? && casks.blank?
<add> formulae = Formula.installed
<add> casks = Cask::Caskroom.casks
<add> end
<add>
<add> [select_outdated(formulae), select_outdated(casks)]
<add> end
<add>
<add> def select_outdated(formulae_or_casks)
<add> formulae_or_casks.select do |fc|
<add> fc.is_a?(Formula) ? fc.outdated?(fetch_head: args.fetch_HEAD?) : fc.outdated?(args.greedy?)
<add> end
<ide> end
<ide> end | 1 |
Text | Text | fix typo in http.md | 6244110bb9279da107fbbc0a78b440a57edbde24 | <ide><path>doc/api/http.md
<ide> request.setHeader('Foo', 'bar');
<ide> request.setHeader('Cookie', ['foo=bar', 'bar=baz']);
<ide>
<ide> const headerNames = request.getHeaderNames();
<del>// headerNames === ['foo', 'Cookie']
<add>// headerNames === ['foo', 'cookie']
<ide> ```
<ide>
<ide> ### `request.getHeaders()` | 1 |
Javascript | Javascript | add test against unsupported worker features | 39568e39d9adca89257b44acfc76d02836099767 | <ide><path>test/parallel/test-worker-unsupported-things.js
<add>// Flags: --experimental-worker
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const { Worker, isMainThread, parentPort } = require('worker');
<add>
<add>if (isMainThread) {
<add> const w = new Worker(__filename);
<add> w.on('message', common.mustCall((message) => {
<add> assert.strictEqual(message, true);
<add> }));
<add>} else {
<add> {
<add> const before = process.title;
<add> process.title += ' in worker';
<add> assert.strictEqual(process.title, before);
<add> }
<add>
<add> {
<add> const before = process.debugPort;
<add> process.debugPort++;
<add> assert.strictEqual(process.debugPort, before);
<add> }
<add>
<add> assert.strictEqual('abort' in process, false);
<add> assert.strictEqual('chdir' in process, false);
<add> assert.strictEqual('setuid' in process, false);
<add> assert.strictEqual('seteuid' in process, false);
<add> assert.strictEqual('setgid' in process, false);
<add> assert.strictEqual('setegid' in process, false);
<add> assert.strictEqual('setgroups' in process, false);
<add> assert.strictEqual('initgroups' in process, false);
<add>
<add> assert.strictEqual('_startProfilerIdleNotifier' in process, false);
<add> assert.strictEqual('_stopProfilerIdleNotifier' in process, false);
<add> assert.strictEqual('_debugProcess' in process, false);
<add> assert.strictEqual('_debugPause' in process, false);
<add> assert.strictEqual('_debugEnd' in process, false);
<add>
<add> parentPort.postMessage(true);
<add>} | 1 |
Text | Text | fix broken link in contributing.md | 25044e34b02a43265c2499de907ad71d2434bbf1 | <ide><path>CONTRIBUTING.md
<ide> So you want to help out? Great! There's a number of ways you can get involved.
<ide>
<ide> * [File and discuss issues](#filing-issues)
<ide> * [Contribute code](#contributing-code)
<del> * [Build and share plugins](docs/plugins.md)
<add> * [Build and share plugins](docs/guides/plugins.md)
<ide> * [Answer questions on Stack Overflow](http://stackoverflow.com/questions/tagged/video.js)
<ide>
<ide> There's also other Video.js projects where you can help. (check the [video.js org](https://github.com/videojs) for an up-to-date list of projects) | 1 |
Javascript | Javascript | add process.cwd to the test process shim | 3195bcdbcb511cc218859dc6b35de8628a6fb9bc | <ide><path>src/renderers/dom/__tests__/ReactDOMProduction-test.js
<ide> describe('ReactDOMProduction', () => {
<ide> __DEV__ = false;
<ide> oldProcess = process;
<ide> global.process = {
<add> cwd: process.cwd,
<ide> env: Object.assign({}, process.env, {NODE_ENV: 'production'}),
<ide> };
<ide> | 1 |
Javascript | Javascript | remove documentation for {{template}} | 48ecdd707e226315bb4750ff0c91a6fcb56e2637 | <ide><path>packages/ember-handlebars/lib/helpers/template.js
<del>import Ember from "ember-metal/core";
<del>// var emberDeprecate = Ember.deprecate;
<add>import Ember from "ember-metal/core"; // Ember.deprecate;
<ide>
<ide> import EmberHandlebars from "ember-handlebars-compiler";
<ide> /**
<ide> import EmberHandlebars from "ember-handlebars-compiler";
<ide> */
<ide>
<ide> /**
<del> `template` allows you to render a template from inside another template.
<del> This allows you to re-use the same template in multiple places. For example:
<del>
<del> ```html
<del> <script type="text/x-handlebars" data-template-name="logged_in_user">
<del> {{#with loggedInUser}}
<del> Last Login: {{lastLogin}}
<del> User Info: {{template "user_info"}}
<del> {{/with}}
<del> </script>
<del> ```
<del>
<del> ```html
<del> <script type="text/x-handlebars" data-template-name="user_info">
<del> Name: <em>{{name}}</em>
<del> Karma: <em>{{karma}}</em>
<del> </script>
<del> ```
<del>
<del> ```handlebars
<del> {{#if isUser}}
<del> {{template "user_info"}}
<del> {{else}}
<del> {{template "unlogged_user_info"}}
<del> {{/if}}
<del> ```
<del>
<del> This helper looks for templates in the global `Ember.TEMPLATES` hash. If you
<del> add `<script>` tags to your page with the `data-template-name` attribute set,
<del> they will be compiled and placed in this hash automatically.
<del>
<del> You can also manually register templates by adding them to the hash:
<del>
<del> ```javascript
<del> Ember.TEMPLATES["my_cool_template"] = Ember.Handlebars.compile('<b>{{user}}</b>');
<del> ```
<del>
<ide> @deprecated
<ide> @method template
<ide> @for Ember.Handlebars.helpers | 1 |
Python | Python | fix typo in build script for win32 | 11a69c23a29916f0d0721108e34d758e72d56b41 | <ide><path>tools/win32build/build.py
<ide> from os.path import join as pjoin, split as psplit, dirname
<ide>
<ide> PYEXECS = {"2.5" : "C:\python25\python.exe",
<del> "2.4" : "C:\python24\python2.4.exe",
<add> "2.4" : "C:\python24\python24.exe",
<ide> "2.3" : "C:\python23\python23.exe"}
<ide>
<ide> _SSE3_CFG = r"""[atlas] | 1 |
Text | Text | use the same changelog format as 15.0 post | 6c11bb65e10f1e6fcd6e24a80f127a3627858edb | <ide><path>docs/_posts/2016-04-08-react-v15.0.1.md
<ide> As usual, you can get install the `react` package via npm or download a browser
<ide> ## Changelog
<ide>
<ide> ### React
<del>- Restore `React.__spread` API to unbreak code compiled with some tools making use of this undocumented API. It is now officially deprecated. ([@zpao](https://github.com/zpao) in [#6444](https://github.com/facebook/react/pull/6444))
<add>- Restore `React.__spread` API to unbreak code compiled with some tools making use of this undocumented API. It is now officially deprecated.
<add> <small>[@zpao](https://github.com/zpao) in [#6444](https://github.com/facebook/react/pull/6444)</small>
<ide>
<ide> ### ReactDOM
<del>- Fixed issue resulting in loss of cursor position in controlled inputs. ([@spicyj](https://github.com/spicyj) in [#6449](https://github.com/facebook/react/pull/6449))
<add>- Fixed issue resulting in loss of cursor position in controlled inputs.
<add> <small>[@spicyj](https://github.com/spicyj) in [#6449](https://github.com/facebook/react/pull/6449)</small> | 1 |
Javascript | Javascript | use fixtures.readkey in https-agent test | d36433e1b6ce070026ccd14a341f7a564d58ad4b | <ide><path>test/parallel/test-https-agent-create-connection.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<ide>
<ide> const https = require('https');
<ide>
<ide> const agent = new https.Agent();
<ide>
<del>const fs = require('fs');
<del>
<ide> const options = {
<del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`),
<del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`),
<add> key: fixtures.readKey('agent1-key.pem'),
<add> cert: fixtures.readKey('agent1-cert.pem'),
<ide> };
<ide>
<ide> const expectedHeader = /^HTTP\/1\.1 200 OK/; | 1 |
Ruby | Ruby | test that the tab round-trips through json | 07171f55275f5aee010a6b529300f2b448863642 | <ide><path>Library/Homebrew/test/test_tab.rb
<ide> def setup
<ide> @unused << Option.new("with-baz") << Option.new("without-qux")
<ide>
<ide> @tab = Tab.new({
<del> :used_options => @used,
<del> :unused_options => @unused,
<add> :used_options => @used.map(&:to_s),
<add> :unused_options => @unused.map(&:to_s),
<ide> :built_as_bottle => false,
<ide> :poured_from_bottle => true,
<ide> :tapped_from => "Homebrew/homebrew",
<ide> :time => nil,
<ide> :HEAD => TEST_SHA1,
<del> :compiler => :clang,
<del> :stdlib => :libcxx,
<add> :compiler => "clang",
<add> :stdlib => "libcxx",
<ide> })
<ide> end
<ide>
<ide> def test_with?
<ide> def test_universal?
<ide> refute_predicate @tab, :universal?
<ide> @used << "universal"
<add> @tab.used_options = @used.map(&:to_s)
<ide> assert_predicate @tab, :universal?
<ide> end
<ide>
<ide> def test_from_file
<ide> assert_equal :clang, tab.cxxstdlib.compiler
<ide> assert_equal :libcxx, tab.cxxstdlib.type
<ide> end
<add>
<add> def test_to_json
<add> assert_equal @tab, Tab.new(Utils::JSON.load(@tab.to_json))
<add> end
<ide> end
<ide>
<ide> class TabLoadingTests < Homebrew::TestCase | 1 |
Ruby | Ruby | fix rubocop warnings | 49e009df296d64edbd48a9b8ec657b735f02e89b | <ide><path>Library/Homebrew/cmd/unpack.rb
<ide> def unpack
<ide> end
<ide> ENV["VERBOSE"] = nil
<ide>
<del> if ARGV.git?
<del> ohai "Setting up git repository"
<del> cd stage_dir
<del> system "git", "init", "-q"
<del> system "git", "add", "-A"
<del> system "git", "commit", "-q", "-m", "brew-unpack"
<del> end
<add> next unless ARGV.git?
<add> ohai "Setting up git repository"
<add> cd stage_dir
<add> system "git", "init", "-q"
<add> system "git", "add", "-A"
<add> system "git", "commit", "-q", "-m", "brew-unpack"
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | add resolver result to module callback | 9afd2897a503a049543c4b020d876f21275c5c87 | <ide><path>lib/NormalModuleFactory.js
<ide> function NormalModuleFactory(context, resolvers, options) {
<ide> function(callback) {
<ide> if(resource === "" || resource[0] === "?")
<ide> return callback(null, resource);
<del> _this.resolvers.normal.resolve(resolveContextInfo, context, resource, function(err, result) {
<add> _this.resolvers.normal.resolve(resolveContextInfo, context, resource, function(err, resource, result) {
<ide> if(err) return callback(err);
<del> callback(null, result);
<add> callback(null, Object.assign({}, result, {
<add> resource: resource,
<add> }));
<ide> });
<ide> }
<ide> ], function(err, results) {
<ide> if(err) return callback(err);
<ide> var loaders = results[0];
<del> resource = results[1];
<add> var resolverResult = results[1];
<add> resource = resolverResult.resource;
<ide>
<ide> // translate option idents
<ide> try {
<ide> function NormalModuleFactory(context, resolvers, options) {
<ide> rawRequest: request,
<ide> loaders: loaders,
<ide> resource: resource,
<add> resolverResult: resolverResult,
<ide> parser: _this.getParser(settings.parser)
<ide> });
<ide> } | 1 |
Javascript | Javascript | fix symbolication outside of chrome debugging | 7dbc8051e5eec12db4d98fe658167c522c6d8275 | <ide><path>Libraries/JavaScriptAppEngine/Initialization/symbolicateStackTrace.js
<ide>
<ide> const {fetch} = require('fetch');
<ide> const getDevServer = require('getDevServer');
<add>const {SourceCode} = require('NativeModules');
<ide>
<ide> import type {StackFrame} from 'parseErrorStack';
<ide>
<ide> async function symbolicateStackTrace(stack: Array<StackFrame>): Promise<Array<St
<ide> if (!devServer.bundleLoadedFromServer) {
<ide> throw new Error('Bundle was not loaded from the packager');
<ide> }
<add> if (SourceCode.scriptURL) {
<add> for (let i = 0; i < stack.length; ++i) {
<add> // If the sources exist on disk rather than appearing to come from the packager,
<add> // replace the location with the packager URL until we reach an internal source
<add> // which does not have a path (no slashes), indicating a switch from within
<add> // the application to a surrounding debugging environment.
<add> if (/^http/.test(stack[i].file) || !/[\\/]/.test(stack[i].file)) {
<add> break;
<add> }
<add> stack[i].file = SourceCode.scriptURL;
<add> }
<add> }
<add>
<ide> const response = await fetch(devServer.url + 'symbolicate', {
<ide> method: 'POST',
<ide> body: JSON.stringify({stack}), | 1 |
Text | Text | add triagers to the table of contents | 18113969e2f4d933c273ea64607ee75d8c2d2edb | <ide><path>README.md
<ide> The Node.js project uses an [open governance model](./GOVERNANCE.md). The
<ide> * [Current project team members](#current-project-team-members)
<ide> * [TSC (Technical Steering Committee)](#tsc-technical-steering-committee)
<ide> * [Collaborators](#collaborators)
<add> * [Triagers](#triagers)
<ide> * [Release keys](#release-keys)
<ide> * [License](#license)
<ide> | 1 |
Text | Text | add change of previous commit to changelog.md | 54b3f417411097f7404d15355858f56ad66e8294 | <ide><path>activerecord/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* PostgreSQL adapter correctly fetches default values when using multiple schemas and domains in a db. Fixes #7914
<add>
<add> *Arturo Pie*
<add>
<ide> * Learn ActiveRecord::QueryMethods#order work with hash arguments
<ide>
<ide> When symbol or hash passed we convert it to Arel::Nodes::Ordering. | 1 |
Ruby | Ruby | ask the fixture set for the sql statements | 026d0555685087845b74dd87a0417b5a164b1c13 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
<ide> def reset_sequence!(table, column, sequence = nil)
<ide> # Inserts the given fixture into the table. Overridden in adapters that require
<ide> # something beyond a simple insert (eg. Oracle).
<ide> def insert_fixture(fixture, table_name)
<add> execute fixture_sql(fixture, table_name), 'Fixture Insert'
<add> end
<add>
<add> def fixture_sql(fixture, table_name)
<ide> columns = schema_cache.columns_hash(table_name)
<ide>
<ide> key_list = []
<ide> def insert_fixture(fixture, table_name)
<ide> quote(value, columns[name])
<ide> end
<ide>
<del> execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert'
<add> "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})"
<ide> end
<ide>
<ide> def empty_insert_statement_value
<ide><path>activerecord/lib/active_record/fixtures.rb
<ide> def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {}
<ide> connection.transaction(:requires_new => true) do
<ide> fixture_sets.each do |fs|
<ide> conn = fs.model_class.respond_to?(:connection) ? fs.model_class.connection : connection
<del> table_rows = fs.table_rows
<del>
<del> table_rows.keys.each do |table|
<del> conn.delete "DELETE FROM #{conn.quote_table_name(table)}", 'Fixture Delete'
<del> end
<del>
<del> table_rows.each do |fixture_set_name, rows|
<del> rows.each do |row|
<del> conn.insert_fixture(row, fixture_set_name)
<del> end
<add> fs.fixture_sql(conn).each do |stmt|
<add> conn.execute stmt
<ide> end
<ide> end
<ide>
<ide> def size
<ide> fixtures.size
<ide> end
<ide>
<add> def fixture_sql(conn)
<add> table_rows = self.table_rows
<add>
<add> table_rows.keys.map { |table|
<add> "DELETE FROM #{conn.quote_table_name(table)}"
<add> }.concat table_rows.flat_map { |fixture_set_name, rows|
<add> rows.map { |row| conn.fixture_sql(row, fixture_set_name) }
<add> }
<add> end
<add>
<ide> # Return a hash of rows to be inserted. The key is the table, the value is
<ide> # a list of rows to insert to that table.
<ide> def table_rows | 2 |
Python | Python | use ndarray in the array api creation functions | 587613f056299766be2da00a64b5fa0ac31c84aa | <ide><path>numpy/_array_api/_creation_functions.py
<ide> def arange(start: Union[int, float], /, *, stop: Optional[Union[int, float]] = N
<ide>
<ide> See its docstring for more information.
<ide> """
<add> from ._array_object import ndarray
<ide> if device is not None:
<ide> # Note: Device support is not yet implemented on ndarray
<ide> raise NotImplementedError("Device support is not yet implemented")
<del> return np.arange(start, stop=stop, step=step, dtype=dtype)
<add> return ndarray._new(np.arange(start, stop=stop, step=step, dtype=dtype))
<ide>
<ide> def empty(shape: Union[int, Tuple[int, ...]], /, *, dtype: Optional[dtype] = None, device: Optional[device] = None) -> array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.empty <numpy.empty>`.
<ide>
<ide> See its docstring for more information.
<ide> """
<add> from ._array_object import ndarray
<ide> if device is not None:
<ide> # Note: Device support is not yet implemented on ndarray
<ide> raise NotImplementedError("Device support is not yet implemented")
<del> return np.empty(shape, dtype=dtype)
<add> return ndarray._new(np.empty(shape, dtype=dtype))
<ide>
<ide> def empty_like(x: array, /, *, dtype: Optional[dtype] = None, device: Optional[device] = None) -> array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.empty_like <numpy.empty_like>`.
<ide>
<ide> See its docstring for more information.
<ide> """
<add> from ._array_object import ndarray
<ide> if device is not None:
<ide> # Note: Device support is not yet implemented on ndarray
<ide> raise NotImplementedError("Device support is not yet implemented")
<del> return np.empty_like._implementation(x, dtype=dtype)
<add> return ndarray._new(np.empty_like._implementation(x._array, dtype=dtype))
<ide>
<ide> def eye(N: int, /, *, M: Optional[int] = None, k: Optional[int] = 0, dtype: Optional[dtype] = None, device: Optional[device] = None) -> array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.eye <numpy.eye>`.
<ide>
<ide> See its docstring for more information.
<ide> """
<add> from ._array_object import ndarray
<ide> if device is not None:
<ide> # Note: Device support is not yet implemented on ndarray
<ide> raise NotImplementedError("Device support is not yet implemented")
<del> return np.eye(N, M=M, k=k, dtype=dtype)
<add> return ndarray._new(np.eye(N, M=M, k=k, dtype=dtype))
<ide>
<ide> def from_dlpack(x: object, /) -> array:
<ide> # Note: dlpack support is not yet implemented on ndarray
<ide> def full(shape: Union[int, Tuple[int, ...]], fill_value: Union[int, float], /, *
<ide>
<ide> See its docstring for more information.
<ide> """
<add> from ._array_object import ndarray
<ide> if device is not None:
<ide> # Note: Device support is not yet implemented on ndarray
<ide> raise NotImplementedError("Device support is not yet implemented")
<del> return np.full(shape, fill_value, dtype=dtype)
<add> return ndarray._new(np.full(shape, fill_value, dtype=dtype))
<ide>
<ide> def full_like(x: array, fill_value: Union[int, float], /, *, dtype: Optional[dtype] = None, device: Optional[device] = None) -> array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.full_like <numpy.full_like>`.
<ide>
<ide> See its docstring for more information.
<ide> """
<add> from ._array_object import ndarray
<ide> if device is not None:
<ide> # Note: Device support is not yet implemented on ndarray
<ide> raise NotImplementedError("Device support is not yet implemented")
<del> return np.full_like._implementation(x, fill_value, dtype=dtype)
<add> return ndarray._new(np.full_like._implementation(x._array, fill_value, dtype=dtype))
<ide>
<ide> def linspace(start: Union[int, float], stop: Union[int, float], num: int, /, *, dtype: Optional[dtype] = None, device: Optional[device] = None, endpoint: bool = True) -> array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.linspace <numpy.linspace>`.
<ide>
<ide> See its docstring for more information.
<ide> """
<add> from ._array_object import ndarray
<ide> if device is not None:
<ide> # Note: Device support is not yet implemented on ndarray
<ide> raise NotImplementedError("Device support is not yet implemented")
<del> return np.linspace(start, stop, num, dtype=dtype, endpoint=endpoint)
<add> return ndarray._new(np.linspace(start, stop, num, dtype=dtype, endpoint=endpoint))
<ide>
<ide> def ones(shape: Union[int, Tuple[int, ...]], /, *, dtype: Optional[dtype] = None, device: Optional[device] = None) -> array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.ones <numpy.ones>`.
<ide>
<ide> See its docstring for more information.
<ide> """
<add> from ._array_object import ndarray
<ide> if device is not None:
<ide> # Note: Device support is not yet implemented on ndarray
<ide> raise NotImplementedError("Device support is not yet implemented")
<del> return np.ones(shape, dtype=dtype)
<add> return ndarray._new(np.ones(shape, dtype=dtype))
<ide>
<ide> def ones_like(x: array, /, *, dtype: Optional[dtype] = None, device: Optional[device] = None) -> array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.ones_like <numpy.ones_like>`.
<ide>
<ide> See its docstring for more information.
<ide> """
<add> from ._array_object import ndarray
<ide> if device is not None:
<ide> # Note: Device support is not yet implemented on ndarray
<ide> raise NotImplementedError("Device support is not yet implemented")
<del> return np.ones_like._implementation(x, dtype=dtype)
<add> return ndarray._new(np.ones_like._implementation(x._array, dtype=dtype))
<ide>
<ide> def zeros(shape: Union[int, Tuple[int, ...]], /, *, dtype: Optional[dtype] = None, device: Optional[device] = None) -> array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.zeros <numpy.zeros>`.
<ide>
<ide> See its docstring for more information.
<ide> """
<add> from ._array_object import ndarray
<ide> if device is not None:
<ide> # Note: Device support is not yet implemented on ndarray
<ide> raise NotImplementedError("Device support is not yet implemented")
<del> return np.zeros(shape, dtype=dtype)
<add> return ndarray._new(np.zeros(shape, dtype=dtype))
<ide>
<ide> def zeros_like(x: array, /, *, dtype: Optional[dtype] = None, device: Optional[device] = None) -> array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.zeros_like <numpy.zeros_like>`.
<ide>
<ide> See its docstring for more information.
<ide> """
<add> from ._array_object import ndarray
<ide> if device is not None:
<ide> # Note: Device support is not yet implemented on ndarray
<ide> raise NotImplementedError("Device support is not yet implemented")
<del> return np.zeros_like._implementation(x, dtype=dtype)
<add> return ndarray._new(np.zeros_like._implementation(x._array, dtype=dtype)) | 1 |
Go | Go | fix flaky test testimportfilewithmessage | 9d6989bbb61cc009262ed6cf2ada92e7350a58af | <ide><path>cmd/dockerd/hack/malformed_host_override.go
<ide> func (l *MalformedHostHeaderOverrideConn) Read(b []byte) (n int, err error) {
<ide> firstLineFeed = -1
<ide> buf []byte
<ide> )
<del> for i, bb := range b[:c] {
<del> if bb == '\n' && firstLineFeed == -1 {
<add> for i := 0; i <= c-1-7; i++ {
<add> if b[i] == '\n' && firstLineFeed == -1 {
<ide> firstLineFeed = i
<ide> }
<del> if bb != '\n' {
<add> if b[i] != '\n' {
<ide> continue
<ide> }
<add>
<add> if b[i+1] == '\r' && b[i+2] == '\n' {
<add> return c, nil
<add> }
<add>
<ide> if b[i+1] != 'H' {
<ide> continue
<ide> }
<ide><path>cmd/dockerd/hack/malformed_host_override_test.go
<ide> import (
<ide> "testing"
<ide> )
<ide>
<add>type bufConn struct {
<add> net.Conn
<add> buf *bytes.Buffer
<add>}
<add>
<add>func (bc *bufConn) Read(b []byte) (int, error) {
<add> return bc.buf.Read(b)
<add>}
<add>
<ide> func TestHeaderOverrideHack(t *testing.T) {
<del> client, srv := net.Pipe()
<ide> tests := [][2][]byte{
<ide> {
<ide> []byte("GET /foo\nHost: /var/run/docker.sock\nUser-Agent: Docker\r\n\r\n"),
<ide> func TestHeaderOverrideHack(t *testing.T) {
<ide> []byte("GET /foo\nFoo: Bar\nHost: /var/run/docker.sock\nUser-Agent: Docker\r\n\r\n"),
<ide> },
<ide> }
<del> l := MalformedHostHeaderOverrideConn{client, true}
<del> read := make([]byte, 4096)
<add>
<add> // Test for https://github.com/docker/docker/issues/23045
<add> h0 := "GET /foo\nUser-Agent: Docker\r\n\r\n"
<add> h0 = h0 + strings.Repeat("a", 4096-len(h0)-1) + "\n"
<add> tests = append(tests, [2][]byte{[]byte(h0), []byte(h0)})
<ide>
<ide> for _, pair := range tests {
<del> go func(x []byte) {
<del> srv.Write(x)
<del> }(pair[0])
<add> read := make([]byte, 4096)
<add> client := &bufConn{
<add> buf: bytes.NewBuffer(pair[0]),
<add> }
<add> l := MalformedHostHeaderOverrideConn{client, true}
<add>
<ide> n, err := l.Read(read)
<ide> if err != nil && err != io.EOF {
<ide> t.Fatalf("read: %d - %d, err: %v\n%s", n, len(pair[0]), err, string(read[:n]))
<ide> }
<ide> if !bytes.Equal(read[:n], pair[1][:n]) {
<ide> t.Fatalf("\n%s\n%s\n", read[:n], pair[1][:n])
<ide> }
<del> l.first = true
<del> // clean out the slice
<del> read = read[:0]
<ide> }
<del> srv.Close()
<del> l.Close()
<ide> }
<ide>
<ide> func BenchmarkWithHack(b *testing.B) { | 2 |
Javascript | Javascript | simplify numbertoidentifer method | d74491d3f1fc2f770980a4670a64bb33ba43c6c0 | <ide><path>lib/Template.js
<ide> Template.toIdentifier = function(str) {
<ide> return str.replace(/^[^a-zA-Z$_]/, "_").replace(/[^a-zA-Z0-9$_]/g, "_");
<ide> };
<ide>
<del>var A_CODE = "a".charCodeAt(0);
<del>var Z_CODE = "z".charCodeAt(0);
<del>var AZ_COUNT = Z_CODE - A_CODE + 1;
<del>var A2_CODE = "A".charCodeAt(0);
<del>var Z2_CODE = "Z".charCodeAt(0);
<del>var AZ2_COUNT = Z2_CODE - A2_CODE + 1;
<add>var START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
<add>var START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
<add>var DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
<add>// map number to a single character a-z, A-Z or <_ + number> if number is too big
<ide> Template.numberToIdentifer = function numberToIdentifer(n) {
<del> if(n < AZ_COUNT) return String.fromCharCode(A_CODE + n);
<del> if(n < AZ_COUNT + AZ2_COUNT) return String.fromCharCode(A2_CODE + n - AZ_COUNT);
<del> return "_" + (n - AZ_COUNT - AZ2_COUNT);
<add> // lower case
<add> if(n < DELTA_A_TO_Z) return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
<add>
<add> // upper case
<add> n -= DELTA_A_TO_Z;
<add> if(n < DELTA_A_TO_Z) return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
<add>
<add> // fall back to _ + number
<add> n -= DELTA_A_TO_Z;
<add> return "_" + n;
<ide> };
<ide>
<ide> Template.prototype = Object.create(Tapable.prototype); | 1 |
Ruby | Ruby | add python_pth_files_installed? helper | daabf4f5dc3effbaa1efe7275615f6541b65906c | <ide><path>Library/Homebrew/keg.rb
<ide> def python_site_packages_installed?
<ide> path.join("lib", "python2.7", "site-packages").directory?
<ide> end
<ide>
<add> def python_pth_files_installed?
<add> Dir["#{path}/lib/python2.7/site-packages/*.pth"].any?
<add> end
<add>
<ide> def app_installed?
<ide> Dir["#{path}/{,libexec/}*.app"].any?
<ide> end | 1 |
Javascript | Javascript | add note that isobject returns true for arrays | 3193a3a5af731a4773feadc23d91c5ab63ef9fda | <ide><path>src/Angular.js
<ide> function isDefined(value){return typeof value !== 'undefined';}
<ide> *
<ide> * @description
<ide> * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
<del> * considered to be objects.
<add> * considered to be objects. Note that JavaScript arrays are objects.
<ide> *
<ide> * @param {*} value Reference to check.
<ide> * @returns {boolean} True if `value` is an `Object` but not `null`. | 1 |
Ruby | Ruby | fix all rubocop violations | 600ff9abfccb6e4f44421534602f3eae224cecff | <ide><path>actionview/lib/action_view/helpers/javascript_helper.rb
<ide> module ActionView
<ide> module Helpers #:nodoc:
<ide> module JavaScriptHelper
<ide> JS_ESCAPE_MAP = {
<del> '\\' => '\\\\',
<add> "\\" => "\\\\",
<ide> "</" => '<\/',
<ide> "\r\n" => '\n',
<ide> "\n" => '\n',
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
<ide> def lookup_cast_type_from_column(column) # :nodoc:
<ide> # Quotes a string, escaping any ' (single quote) and \ (backslash)
<ide> # characters.
<ide> def quote_string(s)
<del> s.gsub('\\', '\&\&').gsub("'", "''") # ' (for ruby-mode)
<add> s.gsub("\\", '\&\&').gsub("'", "''") # ' (for ruby-mode)
<ide> end
<ide>
<ide> # Quotes the column name. Defaults to no quoting.
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb
<ide> def deserialize(value)
<ide> end
<ide>
<ide> key.gsub!('\"', '"')
<del> key.gsub!('\\\\', '\\')
<add> key.gsub!("\\\\", "\\")
<ide>
<ide> if value
<ide> value.gsub!('\"', '"')
<del> value.gsub!('\\\\', '\\')
<add> value.gsub!("\\\\", "\\")
<ide> end
<ide>
<ide> hash[key] = value
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb
<ide> def unquote(value)
<ide> if value.start_with?('"') && value.end_with?('"')
<ide> unquoted_value = value[1..-2]
<ide> unquoted_value.gsub!('""', '"')
<del> unquoted_value.gsub!('\\\\', '\\')
<add> unquoted_value.gsub!("\\\\", "\\")
<ide> unquoted_value
<ide> else
<ide> value | 4 |
Python | Python | use 0-vector for oov lexemes | f9fd2889b79495d2c4607ad3c89438aacb5d24ec | <ide><path>spacy/ml/models/multi_task.py
<ide> from thinc.api import MultiSoftmax, list2array
<ide> from thinc.api import to_categorical, CosineDistance, L2Distance
<ide>
<del>from ...util import registry
<add>from ...util import registry, OOV_RANK
<ide> from ...errors import Errors
<ide> from ...attrs import ID
<ide>
<ide> def get_vectors_loss(ops, docs, prediction, distance):
<ide> # and look them up all at once. This prevents data copying.
<ide> ids = ops.flatten([doc.to_array(ID).ravel() for doc in docs])
<ide> target = docs[0].vocab.vectors.data[ids]
<add> target[ids == OOV_RANK] = 0
<ide> d_target, loss = distance(prediction, target)
<ide> return loss, d_target
<ide> | 1 |
Java | Java | improve application of styles for `value` prop | f6f8b092f9dac03e81cb01a73e748f3df85ea519 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactBaseTextShadowNode.java
<ide> public void execute(SpannableStringBuilder sb, int priority) {
<ide> private static void buildSpannedFromShadowNode(
<ide> ReactBaseTextShadowNode textShadowNode,
<ide> SpannableStringBuilder sb,
<del> List<SetSpanOperation> ops) {
<del>
<del> int start = sb.length();
<add> List<SetSpanOperation> ops,
<add> int start) {
<ide>
<ide> for (int i = 0, length = textShadowNode.getChildCount(); i < length; i++) {
<ide> ReactShadowNode child = textShadowNode.getChildAt(i);
<ide>
<ide> if (child instanceof ReactRawTextShadowNode) {
<ide> sb.append(((ReactRawTextShadowNode) child).getText());
<ide> } else if (child instanceof ReactBaseTextShadowNode) {
<del> buildSpannedFromShadowNode((ReactBaseTextShadowNode) child, sb, ops);
<add> buildSpannedFromShadowNode((ReactBaseTextShadowNode) child, sb, ops, sb.length());
<ide> } else if (child instanceof ReactTextInlineImageShadowNode) {
<ide> // We make the image take up 1 character in the span and put a corresponding character into
<ide> // the text so that the image doesn't run over any following text.
<ide> protected static Spannable spannedFromShadowNode(
<ide> // a new spannable will be wiped out
<ide> List<SetSpanOperation> ops = new ArrayList<>();
<ide>
<del> buildSpannedFromShadowNode(textShadowNode, sb, ops);
<del>
<ide> if (text != null) {
<add> // Handle text that is provided via a prop (e.g. the `value` and `defaultValue` props on
<add> // TextInput).
<ide> sb.append(text);
<ide> }
<ide>
<add> buildSpannedFromShadowNode(textShadowNode, sb, ops, 0);
<add>
<ide> if (textShadowNode.mFontSize == UNSET) {
<ide> int defaultFontSize = textShadowNode.getDefaultFontSize();
<ide> | 1 |
Python | Python | fix failing static check | 8240a447ae8296d904b5661a9bff182f4aa55d06 | <ide><path>dev/breeze/src/airflow_breeze/prod/prod_params.py
<ide> def docker_cache_prod_directive(self) -> List:
<ide> docker_cache_prod_directive = []
<ide>
<ide> if self.prepare_buildx_cache:
<del> docker_cache_prod_directive.extend([f"--cache-to=type=inline,mode=max", "--push"])
<add> docker_cache_prod_directive.extend(["--cache-to=type=inline,mode=max", "--push"])
<ide> if is_multi_platform(self.platform):
<ide> console.print("\nSkip loading docker image on multi-platform build")
<ide> else: | 1 |
Text | Text | add a note about loading source with amd | e0c25abb435db6e210d00407af2ba40e5f0b56ad | <ide><path>CONTRIBUTING.md
<ide> Run the build script
<ide> $ npm run build
<ide> ```
<ide>
<del>Run the Grunt tools:
<del>
<del>```bash
<del>$ grunt && grunt watch
<del>```
<del>
<ide> Now open the jQuery test suite in a browser at http://localhost/test. If there is a port, be sure to include it.
<ide>
<ide> Success! You just built and tested jQuery!
<ide> During the process of writing your patch, you will run the test suite MANY times
<ide>
<ide> Example:
<ide>
<del>http://localhost/test/?filter=css
<add>http://localhost/test/?module=css
<ide>
<ide> This will only run the "css" module tests. This will significantly speed up your development and debugging.
<ide>
<ide> **ALWAYS RUN THE FULL SUITE BEFORE COMMITTING AND PUSHING A PATCH!**
<ide>
<ide>
<add>#### Loading changes on the test page
<add>
<add>Rather than rebuilding jQuery with `grunt` every time you make a change, you can use the included `grunt watch` task to rebuild distribution files whenever a file is saved.
<add>
<add>```bash
<add>$ grunt watch
<add>```
<add>
<add>Alternatively, you can **load tests in AMD** to avoid the need for rebuilding altogether.
<add>
<add>Click "Load with AMD" after loading the test page.
<add>
<add>
<ide> ### Browser support
<ide>
<ide> Remember that jQuery supports multiple browsers and their versions; any contributed code must work in all of them. You can refer to the [browser support page](http://jquery.com/browser-support/) for the current list of supported browsers. | 1 |
Ruby | Ruby | add tests for new rake tasks | bb9e5540c8fd3f48d461362c652cb86c17d9c5f3 | <ide><path>activerecord/test/cases/tasks/database_tasks_test.rb
<ide> def test_creates_test_and_development_databases_when_rails_env_is_development
<ide> ENV["RAILS_ENV"] = old_env
<ide> end
<ide>
<del> def test_establishes_connection_for_the_given_environment
<add> def test_establishes_connection_for_the_given_environments
<add> ActiveRecord::Tasks::DatabaseTasks.stubs(:create).returns true
<add>
<add> ActiveRecord::Base.expects(:establish_connection).with(:development)
<add>
<add> ActiveRecord::Tasks::DatabaseTasks.create_current(
<add> ActiveSupport::StringInquirer.new("development")
<add> )
<add> end
<add> end
<add>
<add> class DatabaseTasksCreateCurrentThreeTierTest < ActiveRecord::TestCase
<add> def setup
<add> @configurations = {
<add> "development" => { "primary" => { "database" => "dev-db" }, "secondary" => { "database" => "secondary-dev-db" } },
<add> "test" => { "primary" => { "database" => "test-db" }, "secondary" => { "database" => "secondary-test-db" } },
<add> "production" => { "primary" => { "database" => "prod-db" }, "secondary" => { "database" => "secondary-prod-db" } }
<add> }
<add>
<add> ActiveRecord::Base.stubs(:configurations).returns(@configurations)
<add> ActiveRecord::Base.stubs(:establish_connection).returns(true)
<add> end
<add>
<add> def test_creates_current_environment_database
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:create).
<add> with("database" => "prod-db")
<add>
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:create).
<add> with("database" => "secondary-prod-db")
<add>
<add> ActiveRecord::Tasks::DatabaseTasks.create_current(
<add> ActiveSupport::StringInquirer.new("production")
<add> )
<add> end
<add>
<add> def test_creates_test_and_development_databases_when_env_was_not_specified
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:create).
<add> with("database" => "dev-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:create).
<add> with("database" => "secondary-dev-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:create).
<add> with("database" => "test-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:create).
<add> with("database" => "secondary-test-db")
<add>
<add> ActiveRecord::Tasks::DatabaseTasks.create_current(
<add> ActiveSupport::StringInquirer.new("development")
<add> )
<add> end
<add>
<add> def test_creates_test_and_development_databases_when_rails_env_is_development
<add> old_env = ENV["RAILS_ENV"]
<add> ENV["RAILS_ENV"] = "development"
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:create).
<add> with("database" => "dev-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:create).
<add> with("database" => "secondary-dev-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:create).
<add> with("database" => "test-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:create).
<add> with("database" => "secondary-test-db")
<add>
<add> ActiveRecord::Tasks::DatabaseTasks.create_current(
<add> ActiveSupport::StringInquirer.new("development")
<add> )
<add> ensure
<add> ENV["RAILS_ENV"] = old_env
<add> end
<add>
<add> def test_establishes_connection_for_the_given_environments_config
<ide> ActiveRecord::Tasks::DatabaseTasks.stubs(:create).returns true
<ide>
<ide> ActiveRecord::Base.expects(:establish_connection).with(:development)
<ide> def test_drops_testand_development_databases_when_rails_env_is_development
<ide> end
<ide> end
<ide>
<add> class DatabaseTasksDropCurrentThreeTierTest < ActiveRecord::TestCase
<add> def setup
<add> @configurations = {
<add> "development" => { "primary" => { "database" => "dev-db" }, "secondary" => { "database" => "secondary-dev-db" } },
<add> "test" => { "primary" => { "database" => "test-db" }, "secondary" => { "database" => "secondary-test-db" } },
<add> "production" => { "primary" => { "database" => "prod-db" }, "secondary" => { "database" => "secondary-prod-db" } }
<add> }
<add>
<add> ActiveRecord::Base.stubs(:configurations).returns(@configurations)
<add> end
<add>
<add> def test_drops_current_environment_database
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
<add> with("database" => "prod-db")
<add>
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
<add> with("database" => "secondary-prod-db")
<add>
<add> ActiveRecord::Tasks::DatabaseTasks.drop_current(
<add> ActiveSupport::StringInquirer.new("production")
<add> )
<add> end
<add>
<add> def test_drops_test_and_development_databases_when_env_was_not_specified
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
<add> with("database" => "dev-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
<add> with("database" => "secondary-dev-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
<add> with("database" => "test-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
<add> with("database" => "secondary-test-db")
<add>
<add> ActiveRecord::Tasks::DatabaseTasks.drop_current(
<add> ActiveSupport::StringInquirer.new("development")
<add> )
<add> end
<add>
<add> def test_drops_testand_development_databases_when_rails_env_is_development
<add> old_env = ENV["RAILS_ENV"]
<add> ENV["RAILS_ENV"] = "development"
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
<add> with("database" => "dev-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
<add> with("database" => "secondary-dev-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
<add> with("database" => "test-db")
<add> ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
<add> with("database" => "secondary-test-db")
<add>
<add> ActiveRecord::Tasks::DatabaseTasks.drop_current(
<add> ActiveSupport::StringInquirer.new("development")
<add> )
<add> ensure
<add> ENV["RAILS_ENV"] = old_env
<add> end
<add> end
<add>
<ide> if current_adapter?(:SQLite3Adapter) && !in_memory_db?
<ide> class DatabaseTasksMigrateTest < ActiveRecord::TestCase
<ide> self.use_transactional_tests = false | 1 |
Python | Python | enable v2 layers for resnet_model | 3dee3b86713ae25f5da9aa8238e059c7f30cf021 | <ide><path>official/vision/image_classification/resnet_model.py
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<del>import tensorflow as tf
<del>
<ide> from tensorflow.python.keras import backend
<ide> from tensorflow.python.keras import initializers
<add>from tensorflow.python.keras import layers
<ide> from tensorflow.python.keras import models
<ide> from tensorflow.python.keras import regularizers
<ide> from official.vision.image_classification import imagenet_preprocessing
<ide>
<del>layers = tf.keras.layers
<del>
<ide> L2_WEIGHT_DECAY = 1e-4
<ide> BATCH_NORM_DECAY = 0.9
<ide> BATCH_NORM_EPSILON = 1e-5 | 1 |
Go | Go | add _ping endpoint | cf0076b92dd11b3bda9ac7982e374d4531925ff9 | <ide><path>api/server/server.go
<ide> package server
<ide> import (
<ide> "bufio"
<ide> "bytes"
<del> "code.google.com/p/go.net/websocket"
<ide> "crypto/tls"
<ide> "crypto/x509"
<ide> "encoding/base64"
<ide> import (
<ide> "strings"
<ide> "syscall"
<ide>
<add> "code.google.com/p/go.net/websocket"
<add>
<ide> "github.com/dotcloud/docker/api"
<ide> "github.com/dotcloud/docker/engine"
<ide> "github.com/dotcloud/docker/pkg/listenbuffer"
<ide> func writeCorsHeaders(w http.ResponseWriter, r *http.Request) {
<ide> w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
<ide> }
<ide>
<add>func ping(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> w.Write([]byte{'O', 'K'})
<add> return nil
<add>}
<add>
<ide> func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, enableCors bool, dockerVersion version.Version) http.HandlerFunc {
<ide> return func(w http.ResponseWriter, r *http.Request) {
<ide> // log the request
<ide> func createRouter(eng *engine.Engine, logging, enableCors bool, dockerVersion st
<ide> }
<ide> m := map[string]map[string]HttpApiFunc{
<ide> "GET": {
<add> "/_ping": ping,
<ide> "/events": getEvents,
<ide> "/info": getInfo,
<ide> "/version": getVersion, | 1 |
Javascript | Javascript | fix scrollview documentation markup | 48156b7967c78fb2e24282614d0617acb3814c06 | <ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> const ScrollView = React.createClass({
<ide> * These styles will be applied to the scroll view content container which
<ide> * wraps all of the child views. Example:
<ide> *
<del> * return (
<del> * <ScrollView contentContainerStyle={styles.contentContainer}>
<del> * </ScrollView>
<del> * );
<del> * ...
<del> * const styles = StyleSheet.create({
<del> * contentContainer: {
<del> * paddingVertical: 20
<del> * }
<del> * });
<add> * ```
<add> * return (
<add> * <ScrollView contentContainerStyle={styles.contentContainer}>
<add> * </ScrollView>
<add> * );
<add> * ...
<add> * const styles = StyleSheet.create({
<add> * contentContainer: {
<add> * paddingVertical: 20
<add> * }
<add> * });
<add> * ```
<ide> */
<ide> contentContainerStyle: StyleSheetPropType(ViewStylePropTypes),
<ide> /**
<ide> const ScrollView = React.createClass({
<ide> * shortcuts `"normal"` and `"fast"` which match the underlying iOS settings
<ide> * for `UIScrollViewDecelerationRateNormal` and
<ide> * `UIScrollViewDecelerationRateFast` respectively.
<del> * - normal: 0.998 (the default)
<del> * - fast: 0.99
<add> *
<add> * - `'normal'`: 0.998 (the default)
<add> * - `'fast'`: 0.99
<add> *
<ide> * @platform ios
<ide> */
<ide> decelerationRate: PropTypes.oneOfType([
<ide> const ScrollView = React.createClass({
<ide> horizontal: PropTypes.bool,
<ide> /**
<ide> * The style of the scroll indicators.
<del> * - `default` (the default), same as `black`.
<del> * - `black`, scroll indicator is black. This style is good against a light background.
<del> * - `white`, scroll indicator is white. This style is good against a dark background.
<add> *
<add> * - `'default'` (the default), same as `black`.
<add> * - `'black'`, scroll indicator is black. This style is good against a light background.
<add> * - `'white'`, scroll indicator is white. This style is good against a dark background.
<add> *
<ide> * @platform ios
<ide> */
<ide> indicatorStyle: PropTypes.oneOf([
<ide> const ScrollView = React.createClass({
<ide> canCancelContentTouches: PropTypes.bool,
<ide> /**
<ide> * Determines whether the keyboard gets dismissed in response to a drag.
<del> * - 'none' (the default), drags do not dismiss the keyboard.
<del> * - 'on-drag', the keyboard is dismissed when a drag begins.
<del> * - 'interactive', the keyboard is dismissed interactively with the drag and moves in
<add> *
<add> * - `'none'` (the default), drags do not dismiss the keyboard.
<add> * - `'on-drag'`, the keyboard is dismissed when a drag begins.
<add> * - `'interactive'`, the keyboard is dismissed interactively with the drag and moves in
<ide> * synchrony with the touch; dragging upwards cancels the dismissal.
<ide> * On android this is not supported and it will have the same behavior as 'none'.
<ide> */
<ide> const ScrollView = React.createClass({
<ide> /**
<ide> * Determines when the keyboard should stay visible after a tap.
<ide> *
<del> * - 'never' (the default), tapping outside of the focused text input when the keyboard
<add> * - `'never'` (the default), tapping outside of the focused text input when the keyboard
<ide> * is up dismisses the keyboard. When this happens, children won't receive the tap.
<del> * - 'always', the keyboard will not dismiss automatically, and the scroll view will not
<add> * - `'always'`, the keyboard will not dismiss automatically, and the scroll view will not
<ide> * catch taps, but children of the scroll view can catch taps.
<del> * - 'handled', the keyboard will not dismiss automatically when the tap was handled by
<add> * - `'handled'`, the keyboard will not dismiss automatically when the tap was handled by
<ide> * a children, (or captured by an ancestor).
<del> * - false, deprecated, use 'never' instead
<del> * - true, deprecated, use 'always' instead
<add> * - `false`, deprecated, use 'never' instead
<add> * - `true`, deprecated, use 'always' instead
<ide> */
<ide> keyboardShouldPersistTaps: PropTypes.oneOf(['always', 'never', 'handled', false, true]),
<ide> /**
<ide> const ScrollView = React.createClass({
<ide> /**
<ide> * When `snapToInterval` is set, `snapToAlignment` will define the relationship
<ide> * of the snapping to the scroll view.
<del> * - `start` (the default) will align the snap at the left (horizontal) or top (vertical)
<del> * - `center` will align the snap in the center
<del> * - `end` will align the snap at the right (horizontal) or bottom (vertical)
<add> *
<add> * - `'start'` (the default) will align the snap at the left (horizontal) or top (vertical)
<add> * - `'center'` will align the snap in the center
<add> * - `'end'` will align the snap at the right (horizontal) or bottom (vertical)
<add> *
<ide> * @platform ios
<ide> */
<ide> snapToAlignment: PropTypes.oneOf([ | 1 |
PHP | PHP | apply fixes from styleci | 47bc923605d0230a29ce2be878548a830347a9cd | <ide><path>src/Illuminate/Console/Scheduling/Event.php
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Carbon;
<ide> use Illuminate\Support\Facades\Date;
<del>use Illuminate\Support\Stringable;
<ide> use Illuminate\Support\Reflector;
<add>use Illuminate\Support\Stringable;
<ide> use Illuminate\Support\Traits\Macroable;
<ide> use Illuminate\Support\Traits\ReflectsClosures;
<ide> use Psr\Http\Client\ClientExceptionInterface;
<ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Facades\Auth;
<ide> use Illuminate\Support\Facades\View;
<del>use Illuminate\Support\Traits\ReflectsClosures;
<ide> use Illuminate\Support\Reflector;
<add>use Illuminate\Support\Traits\ReflectsClosures;
<ide> use Illuminate\Support\ViewErrorBag;
<ide> use Illuminate\Validation\ValidationException;
<ide> use InvalidArgumentException; | 2 |
PHP | PHP | apply fixes from styleci | 64e28ba7dc83291ade23da5c337ab3ddda105bdb | <ide><path>tests/Integration/Queue/JobEncryptionTest.php
<ide> namespace Illuminate\Tests\Integration\Queue;
<ide>
<ide> use Illuminate\Bus\Queueable;
<del>use Illuminate\Contracts\Queue\ShouldQueue;
<ide> use Illuminate\Contracts\Queue\ShouldBeEncrypted;
<add>use Illuminate\Contracts\Queue\ShouldQueue;
<ide> use Illuminate\Database\Schema\Blueprint;
<ide> use Illuminate\Foundation\Bus\Dispatchable;
<ide> use Illuminate\Support\Facades\Bus;
<ide> public function handle()
<ide> }
<ide> }
<ide>
<del>
<ide> class JobEncryptionTestNonEncryptedJob implements ShouldQueue
<ide> {
<ide> use Dispatchable, Queueable; | 1 |
PHP | PHP | improve union all queries in postgres grammar | e7aa0e9785214aaeefb3c2822e35b84a2d944ba5 | <ide><path>src/Illuminate/Database/Query/Grammars/PostgresGrammar.php
<ide>
<ide> class PostgresGrammar extends Grammar
<ide> {
<add> /**
<add> * The components that make up a select clause.
<add> *
<add> * @var array
<add> */
<add> protected $selectComponents = [
<add> 'aggregate',
<add> 'columns',
<add> 'from',
<add> 'joins',
<add> 'wheres',
<add> 'groups',
<add> 'havings',
<add> 'orders',
<add> 'limit',
<add> 'offset',
<add> 'lock',
<add> ];
<add>
<ide> /**
<ide> * All of the available clause operators.
<ide> *
<ide> protected function dateBasedWhere($type, Builder $query, $where)
<ide> return 'extract('.$type.' from '.$this->wrap($where['column']).') '.$where['operator'].' '.$value;
<ide> }
<ide>
<add> /**
<add> * Compile a select query into SQL.
<add> *
<add> * @param \Illuminate\Database\Query\Builder $query
<add> * @return string
<add> */
<add> public function compileSelect(Builder $query)
<add> {
<add> if ($query->unions && $query->aggregate) {
<add> return $this->compileUnionAggregate($query);
<add> }
<add>
<add> $sql = parent::compileSelect($query);
<add>
<add> if ($query->unions) {
<add> $sql = '('.$sql.') '.$this->compileUnions($query);
<add> }
<add>
<add> return $sql;
<add> }
<add>
<add> /**
<add> * Compile a single union statement.
<add> *
<add> * @param array $union
<add> * @return string
<add> */
<add> protected function compileUnion(array $union)
<add> {
<add> $conjunction = $union['all'] ? ' union all ' : ' union ';
<add>
<add> return $conjunction.'('.$union['query']->toSql().')';
<add> }
<add>
<ide> /**
<ide> * Compile a "JSON contains" statement into SQL.
<ide> * | 1 |
Text | Text | add blue-yonder to airflow users | c32452aba65695fea8f6dc5cd4835ac23d703960 | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> * [allegro.pl](http://allegro.tech/) [[@kretes](https://github.com/kretes)]
<ide> * [Bellhops](https://github.com/bellhops)
<ide> * BlueApron [[@jasonjho](https://github.com/jasonjho) & [@matthewdavidhauser](https://github.com/matthewdavidhauser)]
<add>* [Blue Yonder](http://www.blue-yonder.com) [[@blue-yonder](https://github.com/blue-yonder)]
<ide> * [Clairvoyant] (https://clairvoyantsoft.com) [@shekharv](https://github.com/shekharv)
<ide> * [Clover Health] (https://www.cloverhealth.com) [[@gwax](https://github.com/gwax) & [@vansivallab](https://github.com/vansivallab)]
<ide> * Chartboost [[@cgelman](https://github.com/cgelman) & [@dclubb](https://github.com/dclubb)] | 1 |
PHP | PHP | add strict typing to association related files | 7de7f1974e460dfe29cbc50f1b3ac0d339421278 | <ide><path>src/ORM/Association.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> use Cake\Datasource\ResultSetDecorator;
<ide> use Cake\ORM\Locator\LocatorAwareTrait;
<ide> use Cake\Utility\Inflector;
<add>use Closure;
<ide> use InvalidArgumentException;
<ide> use RuntimeException;
<ide>
<ide> abstract class Association
<ide> * @param string $alias The name given to the association
<ide> * @param array $options A list of properties to be set on this object
<ide> */
<del> public function __construct($alias, array $options = [])
<add> public function __construct(string $alias, array $options = [])
<ide> {
<ide> $defaults = [
<ide> 'cascadeCallbacks',
<ide> public function __construct($alias, array $options = [])
<ide> * @param string $name Name to be assigned
<ide> * @return $this
<ide> */
<del> public function setName($name)
<add> public function setName(string $name)
<ide> {
<ide> if ($this->_targetTable !== null) {
<ide> $alias = $this->_targetTable->getAlias();
<ide> public function setName($name)
<ide> *
<ide> * @return string
<ide> */
<del> public function getName()
<add> public function getName(): string
<ide> {
<ide> return $this->_name;
<ide> }
<ide> public function getName()
<ide> * @param bool $cascadeCallbacks cascade callbacks switch value
<ide> * @return $this
<ide> */
<del> public function setCascadeCallbacks($cascadeCallbacks)
<add> public function setCascadeCallbacks(bool $cascadeCallbacks)
<ide> {
<ide> $this->_cascadeCallbacks = $cascadeCallbacks;
<ide>
<ide> public function setCascadeCallbacks($cascadeCallbacks)
<ide> *
<ide> * @return bool
<ide> */
<del> public function getCascadeCallbacks()
<add> public function getCascadeCallbacks(): bool
<ide> {
<ide> return $this->_cascadeCallbacks;
<ide> }
<ide> public function getCascadeCallbacks()
<ide> *
<ide> * @return string
<ide> */
<del> public function className()
<add> public function className(): string
<ide> {
<ide> return $this->_className;
<ide> }
<ide> public function setSource(Table $table)
<ide> *
<ide> * @return \Cake\ORM\Table
<ide> */
<del> public function getSource()
<add> public function getSource(): Table
<ide> {
<ide> return $this->_sourceTable;
<ide> }
<ide> public function setTarget(Table $table)
<ide> *
<ide> * @return \Cake\ORM\Table
<ide> */
<del> public function getTarget()
<add> public function getTarget(): Table
<ide> {
<ide> if (!$this->_targetTable) {
<del> if (strpos($this->_className, '.')) {
<add> if (strpos((string)$this->_className, '.')) {
<ide> list($plugin) = pluginSplit($this->_className, true);
<ide> $registryAlias = $plugin . $this->_name;
<ide> } else {
<ide> public function setForeignKey($key)
<ide> * @param bool $dependent Set the dependent mode. Use null to read the current state.
<ide> * @return $this
<ide> */
<del> public function setDependent($dependent)
<add> public function setDependent(bool $dependent)
<ide> {
<ide> $this->_dependent = $dependent;
<ide>
<ide> public function setDependent($dependent)
<ide> *
<ide> * @return bool
<ide> */
<del> public function getDependent()
<add> public function getDependent(): bool
<ide> {
<ide> return $this->_dependent;
<ide> }
<ide> public function getDependent()
<ide> * @param array $options custom options key that could alter the return value
<ide> * @return bool
<ide> */
<del> public function canBeJoined(array $options = [])
<add> public function canBeJoined(array $options = []): bool
<ide> {
<ide> $strategy = $options['strategy'] ?? $this->getStrategy();
<ide>
<ide> public function canBeJoined(array $options = [])
<ide> * @param string $type the join type to be used (e.g. INNER)
<ide> * @return $this
<ide> */
<del> public function setJoinType($type)
<add> public function setJoinType(string $type)
<ide> {
<ide> $this->_joinType = $type;
<ide>
<ide> public function setJoinType($type)
<ide> *
<ide> * @return string
<ide> */
<del> public function getJoinType()
<add> public function getJoinType(): string
<ide> {
<ide> return $this->_joinType;
<ide> }
<ide> public function getJoinType()
<ide> * @param string $name The name of the association property. Use null to read the current value.
<ide> * @return $this
<ide> */
<del> public function setProperty($name)
<add> public function setProperty(string $name)
<ide> {
<ide> $this->_propertyName = $name;
<ide>
<ide> public function setProperty($name)
<ide> *
<ide> * @return string
<ide> */
<del> public function getProperty()
<add> public function getProperty(): string
<ide> {
<ide> if (!$this->_propertyName) {
<ide> $this->_propertyName = $this->_propertyName();
<ide> public function getProperty()
<ide> *
<ide> * @return string
<ide> */
<del> protected function _propertyName()
<add> protected function _propertyName(): string
<ide> {
<ide> list(, $name) = pluginSplit($this->_name);
<ide>
<ide> protected function _propertyName()
<ide> * @return $this
<ide> * @throws \InvalidArgumentException When an invalid strategy is provided.
<ide> */
<del> public function setStrategy($name)
<add> public function setStrategy(string $name)
<ide> {
<ide> if (!in_array($name, $this->_validStrategies)) {
<ide> throw new InvalidArgumentException(
<ide> public function setStrategy($name)
<ide> *
<ide> * @return string
<ide> */
<del> public function getStrategy()
<add> public function getStrategy(): string
<ide> {
<ide> return $this->_strategy;
<ide> }
<ide> public function getStrategy()
<ide> *
<ide> * @return string
<ide> */
<del> public function getFinder()
<add> public function getFinder(): string
<ide> {
<ide> return $this->_finder;
<ide> }
<ide> public function getFinder()
<ide> * @param string $finder the finder name to use
<ide> * @return $this
<ide> */
<del> public function setFinder($finder)
<add> public function setFinder(string $finder)
<ide> {
<ide> $this->_finder = $finder;
<ide>
<ide> public function setFinder($finder)
<ide> * @param array $options List of options used for initialization
<ide> * @return void
<ide> */
<del> protected function _options(array $options)
<add> protected function _options(array $options): void
<ide> {
<ide> }
<ide>
<ide> protected function _options(array $options)
<ide> * @throws \RuntimeException if the query builder passed does not return a query
<ide> * object
<ide> */
<del> public function attachTo(Query $query, array $options = [])
<add> public function attachTo(Query $query, array $options = []): void
<ide> {
<ide> $target = $this->getTarget();
<ide> $joinType = empty($options['joinType']) ? $this->getJoinType() : $options['joinType'];
<ide> public function attachTo(Query $query, array $options = [])
<ide> * @param array $options Options array containing the `negateMatch` key.
<ide> * @return void
<ide> */
<del> protected function _appendNotMatching($query, $options)
<add> protected function _appendNotMatching(QueryInterface $query, array $options): void
<ide> {
<ide> $target = $this->_targetTable;
<ide> if (!empty($options['negateMatch'])) {
<ide> protected function _appendNotMatching($query, $options)
<ide> * data shuld be nested in. Will use the default one if not provided.
<ide> * @return array
<ide> */
<del> public function transformRow($row, $nestKey, $joined, $targetProperty = null)
<add> public function transformRow(array $row, string $nestKey, bool $joined, ?string $targetProperty = null): array
<ide> {
<ide> $sourceAlias = $this->getSource()->getAlias();
<ide> $nestKey = $nestKey ?: $this->_name;
<ide> public function transformRow($row, $nestKey, $joined, $targetProperty = null)
<ide> * with this association
<ide> * @return array
<ide> */
<del> public function defaultRowValue($row, $joined)
<add> public function defaultRowValue(array $row, bool $joined): array
<ide> {
<ide> $sourceAlias = $this->getSource()->getAlias();
<ide> if (isset($row[$sourceAlias])) {
<ide> public function defaultRowValue($row, $joined)
<ide> * @see \Cake\ORM\Table::find()
<ide> * @return \Cake\ORM\Query
<ide> */
<del> public function find($type = null, array $options = [])
<add> public function find($type = null, array $options = []): \Cake\ORM\Query
<ide> {
<ide> $type = $type ?: $this->getFinder();
<ide> list($type, $opts) = $this->_extractFinder($type);
<ide> public function find($type = null, array $options = [])
<ide> * @see \Cake\ORM\Table::exists()
<ide> * @return bool
<ide> */
<del> public function exists($conditions)
<add> public function exists($conditions): bool
<ide> {
<ide> if ($this->_conditions) {
<ide> $conditions = $this
<ide> public function exists($conditions)
<ide> * @see \Cake\ORM\Table::updateAll()
<ide> * @return int Count Returns the affected rows.
<ide> */
<del> public function updateAll($fields, $conditions)
<add> public function updateAll(array $fields, $conditions): int
<ide> {
<ide> $target = $this->getTarget();
<ide> $expression = $target->query()
<ide> public function updateAll($fields, $conditions)
<ide> * @return int Returns the number of affected rows.
<ide> * @see \Cake\ORM\Table::deleteAll()
<ide> */
<del> public function deleteAll($conditions)
<add> public function deleteAll($conditions): int
<ide> {
<ide> $target = $this->getTarget();
<ide> $expression = $target->query()
<ide> public function deleteAll($conditions)
<ide> * @param array $options The options containing the strategy to be used.
<ide> * @return bool true if a list of keys will be required
<ide> */
<del> public function requiresKeys(array $options = [])
<add> public function requiresKeys(array $options = []): bool
<ide> {
<ide> $strategy = $options['strategy'] ?? $this->getStrategy();
<ide>
<ide> public function requiresKeys(array $options = [])
<ide> * @param \Cake\ORM\Query $query the query this association is attaching itself to
<ide> * @return void
<ide> */
<del> protected function _dispatchBeforeFind($query)
<add> protected function _dispatchBeforeFind(Query $query): void
<ide> {
<ide> $query->triggerBeforeFind();
<ide> }
<ide> protected function _dispatchBeforeFind($query)
<ide> * @param array $options options passed to the method `attachTo`
<ide> * @return void
<ide> */
<del> protected function _appendFields($query, $surrogate, $options)
<add> protected function _appendFields(Query $query, Query $surrogate, array $options): void
<ide> {
<ide> if ($query->getEagerLoader()->isAutoFieldsEnabled() === false) {
<ide> return;
<ide> protected function _appendFields($query, $surrogate, $options)
<ide> * @param array $options options passed to the method `attachTo`
<ide> * @return void
<ide> */
<del> protected function _formatAssociationResults($query, $surrogate, $options)
<add> protected function _formatAssociationResults(Query $query, Query $surrogate, array $options): void
<ide> {
<ide> $formatters = $surrogate->getResultFormatters();
<ide>
<ide> protected function _formatAssociationResults($query, $surrogate, $options)
<ide> * @param array $options options passed to the method `attachTo`
<ide> * @return void
<ide> */
<del> protected function _bindNewAssociations($query, $surrogate, $options)
<add> protected function _bindNewAssociations(Query $query, Query $surrogate, array $options): void
<ide> {
<ide> $loader = $surrogate->getEagerLoader();
<ide> $contain = $loader->getContain();
<ide> protected function _bindNewAssociations($query, $surrogate, $options)
<ide> * @throws \RuntimeException if the number of columns in the foreignKey do not
<ide> * match the number of columns in the source table primaryKey
<ide> */
<del> protected function _joinCondition($options)
<add> protected function _joinCondition(array $options): array
<ide> {
<ide> $conditions = [];
<ide> $tAlias = $this->_name;
<ide> protected function _joinCondition($options)
<ide> * and options as value.
<ide> * @return array
<ide> */
<del> protected function _extractFinder($finderData)
<add> protected function _extractFinder($finderData): array
<ide> {
<ide> $finderData = (array)$finderData;
<ide>
<ide> protected function _extractFinder($finderData)
<ide> * @param array $options Table options array.
<ide> * @return string
<ide> */
<del> protected function _getClassName($alias, array $options = [])
<add> protected function _getClassName(string $alias, array $options = []): string
<ide> {
<ide> if (empty($options['className'])) {
<ide> $options['className'] = Inflector::camelize($alias);
<ide> public function __call($method, $argument)
<ide> *
<ide> * @return string Constant of either ONE_TO_ONE, MANY_TO_ONE, ONE_TO_MANY or MANY_TO_MANY.
<ide> */
<del> abstract public function type();
<add> abstract public function type(): string;
<ide>
<ide> /**
<ide> * Eager loads a list of records in the target table that are related to another
<ide> abstract public function type();
<ide> * @param array $options The options for eager loading.
<ide> * @return \Closure
<ide> */
<del> abstract public function eagerLoader(array $options);
<add> abstract public function eagerLoader(array $options): Closure;
<ide>
<ide> /**
<ide> * Handles cascading a delete from an associated model.
<ide> abstract public function eagerLoader(array $options);
<ide> * @param array $options The options for the original delete.
<ide> * @return bool Success
<ide> */
<del> abstract public function cascadeDelete(EntityInterface $entity, array $options = []);
<add> abstract public function cascadeDelete(EntityInterface $entity, array $options = []): bool;
<ide>
<ide> /**
<ide> * Returns whether or not the passed table is the owning side for this
<ide> abstract public function cascadeDelete(EntityInterface $entity, array $options =
<ide> * @param \Cake\ORM\Table $side The potential Table with ownership
<ide> * @return bool
<ide> */
<del> abstract public function isOwningSide(Table $side);
<add> abstract public function isOwningSide(Table $side): bool;
<ide>
<ide> /**
<ide> * Extract the target's association data our from the passed entity and proxies
<ide><path>src/ORM/Association/BelongsTo.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> use Cake\ORM\Association\Loader\SelectLoader;
<ide> use Cake\ORM\Table;
<ide> use Cake\Utility\Inflector;
<add>use Closure;
<ide> use RuntimeException;
<ide>
<ide> /**
<ide> class BelongsTo extends Association
<ide> /**
<ide> * Gets the name of the field representing the foreign key to the target table.
<ide> *
<del> * @return string
<add> * @return string|array
<ide> */
<ide> public function getForeignKey()
<ide> {
<ide> public function getForeignKey()
<ide> * @param array $options The options for the original delete.
<ide> * @return bool Success.
<ide> */
<del> public function cascadeDelete(EntityInterface $entity, array $options = [])
<add> public function cascadeDelete(EntityInterface $entity, array $options = []): bool
<ide> {
<ide> return true;
<ide> }
<ide> public function cascadeDelete(EntityInterface $entity, array $options = [])
<ide> *
<ide> * @return string
<ide> */
<del> protected function _propertyName()
<add> protected function _propertyName(): string
<ide> {
<ide> list(, $name) = pluginSplit($this->_name);
<ide>
<ide> protected function _propertyName()
<ide> * @param \Cake\ORM\Table $side The potential Table with ownership
<ide> * @return bool
<ide> */
<del> public function isOwningSide(Table $side)
<add> public function isOwningSide(Table $side): bool
<ide> {
<ide> return $side === $this->getTarget();
<ide> }
<ide> public function isOwningSide(Table $side)
<ide> *
<ide> * @return string
<ide> */
<del> public function type()
<add> public function type(): string
<ide> {
<ide> return self::MANY_TO_ONE;
<ide> }
<ide> public function saveAssociated(EntityInterface $entity, array $options = [])
<ide> * @throws \RuntimeException if the number of columns in the foreignKey do not
<ide> * match the number of columns in the target table primaryKey
<ide> */
<del> protected function _joinCondition($options)
<add> protected function _joinCondition(array $options): array
<ide> {
<ide> $conditions = [];
<ide> $tAlias = $this->_name;
<ide> protected function _joinCondition($options)
<ide> *
<ide> * @return \Closure
<ide> */
<del> public function eagerLoader(array $options)
<add> public function eagerLoader(array $options): Closure
<ide> {
<ide> $loader = new SelectLoader([
<ide> 'alias' => $this->getAlias(),
<ide><path>src/ORM/Association/BelongsToMany.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> use Cake\ORM\Query;
<ide> use Cake\ORM\Table;
<ide> use Cake\Utility\Inflector;
<add>use Closure;
<ide> use InvalidArgumentException;
<ide> use SplObjectStorage;
<ide> use Traversable;
<ide> class BelongsToMany extends Association
<ide> /**
<ide> * Sets the name of the field representing the foreign key to the target table.
<ide> *
<del> * @param string $key the key to be used to link both tables together
<add> * @param string|array $key the key to be used to link both tables together
<ide> * @return $this
<ide> */
<ide> public function setTargetForeignKey($key)
<ide> public function setTargetForeignKey($key)
<ide> /**
<ide> * Gets the name of the field representing the foreign key to the target table.
<ide> *
<del> * @return string
<add> * @return string|array
<ide> */
<ide> public function getTargetForeignKey()
<ide> {
<ide> public function getTargetForeignKey()
<ide> * @return bool if the 'matching' key in $option is true then this function
<ide> * will return true, false otherwise
<ide> */
<del> public function canBeJoined(array $options = [])
<add> public function canBeJoined(array $options = []): bool
<ide> {
<ide> return !empty($options['matching']);
<ide> }
<ide>
<ide> /**
<ide> * Gets the name of the field representing the foreign key to the source table.
<ide> *
<del> * @return string
<add> * @return string|array
<ide> */
<ide> public function getForeignKey()
<ide> {
<ide> public function getSort()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function defaultRowValue($row, $joined)
<add> public function defaultRowValue(array $row, bool $joined): array
<ide> {
<ide> $sourceAlias = $this->getSource()->getAlias();
<ide> if (isset($row[$sourceAlias])) {
<ide> public function defaultRowValue($row, $joined)
<ide> * @param string|\Cake\ORM\Table|null $table Name or instance for the join table
<ide> * @return \Cake\ORM\Table
<ide> */
<del> public function junction($table = null)
<add> public function junction($table = null): Table
<ide> {
<ide> if ($table === null && $this->_junctionTable) {
<ide> return $this->_junctionTable;
<ide> public function junction($table = null)
<ide> * @param \Cake\ORM\Table $target The target table.
<ide> * @return void
<ide> */
<del> protected function _generateTargetAssociations($junction, $source, $target)
<add> protected function _generateTargetAssociations(Table $junction, Table $source, Table $target): void
<ide> {
<ide> $junctionAlias = $junction->getAlias();
<ide> $sAlias = $source->getAlias();
<ide> protected function _generateTargetAssociations($junction, $source, $target)
<ide> * @param \Cake\ORM\Table $source The source table.
<ide> * @return void
<ide> */
<del> protected function _generateSourceAssociations($junction, $source)
<add> protected function _generateSourceAssociations(Table $junction, Table $source): void
<ide> {
<ide> $junctionAlias = $junction->getAlias();
<ide> if (!$source->hasAssociation($junctionAlias)) {
<ide> protected function _generateSourceAssociations($junction, $source)
<ide> * @param \Cake\ORM\Table $target The target table.
<ide> * @return void
<ide> */
<del> protected function _generateJunctionAssociations($junction, $source, $target)
<add> protected function _generateJunctionAssociations(Table $junction, Table $source, Table $target): void
<ide> {
<ide> $tAlias = $target->getAlias();
<ide> $sAlias = $source->getAlias();
<ide> protected function _generateJunctionAssociations($junction, $source, $target)
<ide> * @param array $options Any extra options or overrides to be taken in account
<ide> * @return void
<ide> */
<del> public function attachTo(Query $query, array $options = [])
<add> public function attachTo(Query $query, array $options = []): void
<ide> {
<ide> if (!empty($options['negateMatch'])) {
<ide> $this->_appendNotMatching($query, $options);
<ide> public function attachTo(Query $query, array $options = [])
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> protected function _appendNotMatching($query, $options)
<add> protected function _appendNotMatching(QueryInterface $query, array $options): void
<ide> {
<ide> if (empty($options['negateMatch'])) {
<ide> return;
<ide> protected function _appendNotMatching($query, $options)
<ide> *
<ide> * @return string
<ide> */
<del> public function type()
<add> public function type(): string
<ide> {
<ide> return self::MANY_TO_MANY;
<ide> }
<ide> public function type()
<ide> * Return false as join conditions are defined in the junction table
<ide> *
<ide> * @param array $options list of options passed to attachTo method
<del> * @return bool false
<add> * @return array
<ide> */
<del> protected function _joinCondition($options)
<add> protected function _joinCondition(array $options): array
<ide> {
<del> return false;
<add> return [];
<ide> }
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> *
<ide> * @return \Closure
<ide> */
<del> public function eagerLoader(array $options)
<add> public function eagerLoader(array $options): Closure
<ide> {
<ide> $name = $this->_junctionAssociationName();
<ide> $loader = new SelectWithPivotLoader([
<ide> public function eagerLoader(array $options)
<ide> * @param array $options The options for the original delete.
<ide> * @return bool Success.
<ide> */
<del> public function cascadeDelete(EntityInterface $entity, array $options = [])
<add> public function cascadeDelete(EntityInterface $entity, array $options = []): bool
<ide> {
<ide> if (!$this->getDependent()) {
<ide> return true;
<ide> public function cascadeDelete(EntityInterface $entity, array $options = [])
<ide> * @param \Cake\ORM\Table $side The potential Table with ownership
<ide> * @return bool
<ide> */
<del> public function isOwningSide(Table $side)
<add> public function isOwningSide(Table $side): bool
<ide> {
<ide> return true;
<ide> }
<ide> public function isOwningSide(Table $side)
<ide> * @throws \InvalidArgumentException if an invalid strategy name is passed
<ide> * @return $this
<ide> */
<del> public function setSaveStrategy($strategy)
<add> public function setSaveStrategy(string $strategy): self
<ide> {
<ide> if (!in_array($strategy, [self::SAVE_APPEND, self::SAVE_REPLACE])) {
<ide> $msg = sprintf('Invalid save strategy "%s"', $strategy);
<ide> public function setSaveStrategy($strategy)
<ide> *
<ide> * @return string the strategy to be used for saving
<ide> */
<del> public function getSaveStrategy()
<add> public function getSaveStrategy(): string
<ide> {
<ide> return $this->_saveStrategy;
<ide> }
<ide> protected function _saveTarget(EntityInterface $parentEntity, $entities, $option
<ide> * @param array $options list of options accepted by `Table::save()`
<ide> * @return bool success
<ide> */
<del> protected function _saveLinks(EntityInterface $sourceEntity, $targetEntities, $options)
<add> protected function _saveLinks(EntityInterface $sourceEntity, array $targetEntities, array $options): bool
<ide> {
<ide> $target = $this->getTarget();
<ide> $junction = $this->junction();
<ide> protected function _saveLinks(EntityInterface $sourceEntity, $targetEntities, $o
<ide> * detected to not be already persisted
<ide> * @return bool true on success, false otherwise
<ide> */
<del> public function link(EntityInterface $sourceEntity, array $targetEntities, array $options = [])
<add> public function link(EntityInterface $sourceEntity, array $targetEntities, array $options = []): bool
<ide> {
<ide> $this->_checkPersistenceStatus($sourceEntity, $targetEntities);
<ide> $property = $this->getProperty();
<ide> function () use ($sourceEntity, $targetEntities, $options) {
<ide> * any of them is lacking a primary key value.
<ide> * @return bool Success
<ide> */
<del> public function unlink(EntityInterface $sourceEntity, array $targetEntities, $options = [])
<add> public function unlink(EntityInterface $sourceEntity, array $targetEntities, $options = []): bool
<ide> {
<ide> if (is_bool($options)) {
<ide> $options = [
<ide> public function unlink(EntityInterface $sourceEntity, array $targetEntities, $op
<ide> $property = $this->getProperty();
<ide>
<ide> $this->junction()->getConnection()->transactional(
<del> function () use ($sourceEntity, $targetEntities, $options) {
<add> function () use ($sourceEntity, $targetEntities, $options): void {
<ide> $links = $this->_collectJointEntities($sourceEntity, $targetEntities);
<ide> foreach ($links as $entity) {
<ide> $this->_junctionTable->delete($entity, $options);
<ide> public function setConditions($conditions)
<ide> * @param string|\Cake\ORM\Table $through Name of the Table instance or the instance itself
<ide> * @return $this
<ide> */
<del> public function setThrough($through)
<add> public function setThrough($through): self
<ide> {
<ide> $this->_through = $through;
<ide>
<ide> protected function targetConditions()
<ide> *
<ide> * @return array
<ide> */
<del> protected function junctionConditions()
<add> protected function junctionConditions(): array
<ide> {
<ide> if ($this->_junctionConditions !== null) {
<ide> return $this->_junctionConditions;
<ide> protected function junctionConditions()
<ide> * @see \Cake\ORM\Table::find()
<ide> * @return \Cake\ORM\Query
<ide> */
<del> public function find($type = null, array $options = [])
<add> public function find($type = null, array $options = []): Query
<ide> {
<ide> $type = $type ?: $this->getFinder();
<ide> list($type, $opts) = $this->_extractFinder($type);
<ide> public function find($type = null, array $options = [])
<ide> * @param string|array $conditions The query conditions to use.
<ide> * @return \Cake\ORM\Query The modified query.
<ide> */
<del> protected function _appendJunctionJoin($query, $conditions)
<add> protected function _appendJunctionJoin(Query $query, $conditions): Query
<ide> {
<ide> $name = $this->_junctionAssociationName();
<ide> $joins = $query->clause('join');
<ide> protected function _appendJunctionJoin($query, $conditions)
<ide> * any of them is lacking a primary key value
<ide> * @return bool success
<ide> */
<del> public function replaceLinks(EntityInterface $sourceEntity, array $targetEntities, array $options = [])
<add> public function replaceLinks(EntityInterface $sourceEntity, array $targetEntities, array $options = []): bool
<ide> {
<ide> $bindingKey = (array)$this->getBindingKey();
<ide> $primaryValue = $sourceEntity->extract($bindingKey);
<ide> function () use ($sourceEntity, $targetEntities, $primaryValue, $options) {
<ide> * @param array $options list of options accepted by `Table::delete()`
<ide> * @return array
<ide> */
<del> protected function _diffLinks($existing, $jointEntities, $targetEntities, $options = [])
<add> protected function _diffLinks(Query $existing, array $jointEntities, array $targetEntities, array $options = []): array
<ide> {
<ide> $junction = $this->junction();
<ide> $target = $this->getTarget();
<ide> protected function _diffLinks($existing, $jointEntities, $targetEntities, $optio
<ide> * @return bool
<ide> * @throws \InvalidArgumentException
<ide> */
<del> protected function _checkPersistenceStatus($sourceEntity, array $targetEntities)
<add> protected function _checkPersistenceStatus(EntityInterface $sourceEntity, array $targetEntities): bool
<ide> {
<ide> if ($sourceEntity->isNew()) {
<ide> $error = 'Source entity needs to be persisted before links can be created or removed.';
<ide> protected function _checkPersistenceStatus($sourceEntity, array $targetEntities)
<ide> * key value
<ide> * @return array
<ide> */
<del> protected function _collectJointEntities($sourceEntity, $targetEntities)
<add> protected function _collectJointEntities(EntityInterface $sourceEntity, array $targetEntities): array
<ide> {
<ide> $target = $this->getTarget();
<ide> $source = $this->getSource();
<ide> protected function _collectJointEntities($sourceEntity, $targetEntities)
<ide> *
<ide> * @return string
<ide> */
<del> protected function _junctionAssociationName()
<add> protected function _junctionAssociationName(): string
<ide> {
<ide> if (!$this->_junctionAssociationName) {
<ide> $this->_junctionAssociationName = $this->getTarget()
<ide> protected function _junctionAssociationName()
<ide> * @param string|null $name The name of the junction table.
<ide> * @return string
<ide> */
<del> protected function _junctionTableName($name = null)
<add> protected function _junctionTableName(?string $name = null): string
<ide> {
<ide> if ($name === null) {
<ide> if (empty($this->_junctionTableName)) {
<ide> protected function _junctionTableName($name = null)
<ide> * @param array $opts original list of options passed in constructor
<ide> * @return void
<ide> */
<del> protected function _options(array $opts)
<add> protected function _options(array $opts): void
<ide> {
<ide> if (!empty($opts['targetForeignKey'])) {
<ide> $this->setTargetForeignKey($opts['targetForeignKey']);
<ide><path>src/ORM/Association/DependentDeleteHelper.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> class DependentDeleteHelper
<ide> * @param array $options The options for the original delete.
<ide> * @return bool Success.
<ide> */
<del> public function cascadeDelete(Association $association, EntityInterface $entity, array $options = [])
<add> public function cascadeDelete(Association $association, EntityInterface $entity, array $options = []): bool
<ide> {
<ide> if (!$association->getDependent()) {
<ide> return true;
<ide><path>src/ORM/Association/HasMany.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> *
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> use Cake\ORM\Association;
<ide> use Cake\ORM\Association\Loader\SelectLoader;
<ide> use Cake\ORM\Table;
<add>use Closure;
<ide> use InvalidArgumentException;
<ide> use Traversable;
<ide>
<ide> class HasMany extends Association
<ide> * @param \Cake\ORM\Table $side The potential Table with ownership
<ide> * @return bool
<ide> */
<del> public function isOwningSide(Table $side)
<add> public function isOwningSide(Table $side): bool
<ide> {
<ide> return $side === $this->getSource();
<ide> }
<ide> public function isOwningSide(Table $side)
<ide> * @throws \InvalidArgumentException if an invalid strategy name is passed
<ide> * @return $this
<ide> */
<del> public function setSaveStrategy($strategy)
<add> public function setSaveStrategy(string $strategy)
<ide> {
<ide> if (!in_array($strategy, [self::SAVE_APPEND, self::SAVE_REPLACE])) {
<ide> $msg = sprintf('Invalid save strategy "%s"', $strategy);
<ide> public function setSaveStrategy($strategy)
<ide> *
<ide> * @return string the strategy to be used for saving
<ide> */
<del> public function getSaveStrategy()
<add> public function getSaveStrategy(): string
<ide> {
<ide> return $this->_saveStrategy;
<ide> }
<ide> public function saveAssociated(EntityInterface $entity, array $options = [])
<ide> * @param array $options list of options accepted by `Table::save()`.
<ide> * @return bool `true` on success, `false` otherwise.
<ide> */
<del> protected function _saveTarget(array $foreignKeyReference, EntityInterface $parentEntity, $entities, array $options)
<add> protected function _saveTarget(array $foreignKeyReference, EntityInterface $parentEntity, $entities, array $options): bool
<ide> {
<ide> $foreignKey = array_keys($foreignKeyReference);
<ide> $table = $this->getTarget();
<ide> protected function _saveTarget(array $foreignKeyReference, EntityInterface $pare
<ide> * @param array $options list of options to be passed to the internal `save` call
<ide> * @return bool true on success, false otherwise
<ide> */
<del> public function link(EntityInterface $sourceEntity, array $targetEntities, array $options = [])
<add> public function link(EntityInterface $sourceEntity, array $targetEntities, array $options = []): bool
<ide> {
<ide> $saveStrategy = $this->getSaveStrategy();
<ide> $this->setSaveStrategy(self::SAVE_APPEND);
<ide> public function link(EntityInterface $sourceEntity, array $targetEntities, array
<ide> * this association
<ide> * @param array $targetEntities list of entities persisted in the target table for
<ide> * this association
<del> * @param array $options list of options to be passed to the internal `delete` call
<add> * @param array|bool $options list of options to be passed to the internal `delete` call.
<add> * If boolean it will be used a value for "cleanProperty" option.
<ide> * @throws \InvalidArgumentException if non persisted entities are passed or if
<ide> * any of them is lacking a primary key value
<ide> * @return void
<ide> */
<del> public function unlink(EntityInterface $sourceEntity, array $targetEntities, $options = [])
<add> public function unlink(EntityInterface $sourceEntity, array $targetEntities, $options = []): void
<ide> {
<ide> if (is_bool($options)) {
<ide> $options = [
<ide> function ($assoc) use ($targetEntities) {
<ide> * any of them is lacking a primary key value
<ide> * @return bool success
<ide> */
<del> public function replace(EntityInterface $sourceEntity, array $targetEntities, array $options = [])
<add> public function replace(EntityInterface $sourceEntity, array $targetEntities, array $options = []): bool
<ide> {
<ide> $property = $this->getProperty();
<ide> $sourceEntity->set($property, $targetEntities);
<ide> public function replace(EntityInterface $sourceEntity, array $targetEntities, ar
<ide> * @param array $options list of options accepted by `Table::delete()`
<ide> * @return bool success
<ide> */
<del> protected function _unlinkAssociated(array $foreignKeyReference, EntityInterface $entity, Table $target, array $remainingEntities = [], array $options = [])
<add> protected function _unlinkAssociated(array $foreignKeyReference, EntityInterface $entity, Table $target, array $remainingEntities = [], array $options = []): bool
<ide> {
<ide> $primaryKey = (array)$target->getPrimaryKey();
<ide> $exclusions = new Collection($remainingEntities);
<ide> function ($v) {
<ide> * @param array $options list of options accepted by `Table::delete()`
<ide> * @return bool success
<ide> */
<del> protected function _unlink(array $foreignKey, Table $target, array $conditions = [], array $options = [])
<add> protected function _unlink(array $foreignKey, Table $target, array $conditions = [], array $options = []): bool
<ide> {
<ide> $mustBeDependent = (!$this->_foreignKeyAcceptsNull($target, $foreignKey) || $this->getDependent());
<ide>
<ide> if ($mustBeDependent) {
<ide> if ($this->_cascadeCallbacks) {
<ide> $conditions = new QueryExpression($conditions);
<del> $conditions->traverse(function ($entry) use ($target) {
<add> $conditions->traverse(function ($entry) use ($target): void {
<ide> if ($entry instanceof FieldInterface) {
<ide> $entry->setField($target->aliasField($entry->getField()));
<ide> }
<ide> protected function _unlink(array $foreignKey, Table $target, array $conditions =
<ide> * @param array $properties the list of fields that compose the foreign key
<ide> * @return bool
<ide> */
<del> protected function _foreignKeyAcceptsNull(Table $table, array $properties)
<add> protected function _foreignKeyAcceptsNull(Table $table, array $properties): bool
<ide> {
<ide> return !in_array(
<ide> false,
<ide> function ($prop) use ($table) {
<ide> *
<ide> * @return string
<ide> */
<del> public function type()
<add> public function type(): string
<ide> {
<ide> return self::ONE_TO_MANY;
<ide> }
<ide> public function type()
<ide> * @return bool if the 'matching' key in $option is true then this function
<ide> * will return true, false otherwise
<ide> */
<del> public function canBeJoined(array $options = [])
<add> public function canBeJoined(array $options = []): bool
<ide> {
<ide> return !empty($options['matching']);
<ide> }
<ide>
<ide> /**
<ide> * Gets the name of the field representing the foreign key to the source table.
<ide> *
<del> * @return string
<add> * @return string|array
<ide> */
<ide> public function getForeignKey()
<ide> {
<ide> public function getSort()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function defaultRowValue($row, $joined)
<add> public function defaultRowValue(array $row, bool $joined): array
<ide> {
<ide> $sourceAlias = $this->getSource()->getAlias();
<ide> if (isset($row[$sourceAlias])) {
<ide> public function defaultRowValue($row, $joined)
<ide> * @param array $opts original list of options passed in constructor
<ide> * @return void
<ide> */
<del> protected function _options(array $opts)
<add> protected function _options(array $opts): void
<ide> {
<ide> if (!empty($opts['saveStrategy'])) {
<ide> $this->setSaveStrategy($opts['saveStrategy']);
<ide> protected function _options(array $opts)
<ide> *
<ide> * @return \Closure
<ide> */
<del> public function eagerLoader(array $options)
<add> public function eagerLoader(array $options): Closure
<ide> {
<ide> $loader = new SelectLoader([
<ide> 'alias' => $this->getAlias(),
<ide> public function eagerLoader(array $options)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function cascadeDelete(EntityInterface $entity, array $options = [])
<add> public function cascadeDelete(EntityInterface $entity, array $options = []): bool
<ide> {
<ide> $helper = new DependentDeleteHelper();
<ide>
<ide><path>src/ORM/Association/HasOne.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> use Cake\ORM\Association\Loader\SelectLoader;
<ide> use Cake\ORM\Table;
<ide> use Cake\Utility\Inflector;
<add>use Closure;
<ide>
<ide> /**
<ide> * Represents an 1 - 1 relationship where the source side of the relation is
<ide> class HasOne extends Association
<ide> /**
<ide> * Gets the name of the field representing the foreign key to the target table.
<ide> *
<del> * @return string
<add> * @return string|array
<ide> */
<ide> public function getForeignKey()
<ide> {
<ide> public function getForeignKey()
<ide> *
<ide> * @return string
<ide> */
<del> protected function _propertyName()
<add> protected function _propertyName(): string
<ide> {
<ide> list(, $name) = pluginSplit($this->_name);
<ide>
<ide> protected function _propertyName()
<ide> * @param \Cake\ORM\Table $side The potential Table with ownership
<ide> * @return bool
<ide> */
<del> public function isOwningSide(Table $side)
<add> public function isOwningSide(Table $side): bool
<ide> {
<ide> return $side === $this->getSource();
<ide> }
<ide> public function isOwningSide(Table $side)
<ide> *
<ide> * @return string
<ide> */
<del> public function type()
<add> public function type(): string
<ide> {
<ide> return self::ONE_TO_ONE;
<ide> }
<ide> public function saveAssociated(EntityInterface $entity, array $options = [])
<ide> *
<ide> * @return \Closure
<ide> */
<del> public function eagerLoader(array $options)
<add> public function eagerLoader(array $options): Closure
<ide> {
<ide> $loader = new SelectLoader([
<ide> 'alias' => $this->getAlias(),
<ide> public function eagerLoader(array $options)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function cascadeDelete(EntityInterface $entity, array $options = [])
<add> public function cascadeDelete(EntityInterface $entity, array $options = []): bool
<ide> {
<ide> $helper = new DependentDeleteHelper();
<ide>
<ide><path>src/ORM/Association/Loader/SelectLoader.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> use Cake\Database\Expression\TupleComparison;
<ide> use Cake\Database\ValueBinder;
<ide> use Cake\ORM\Association;
<add>use Cake\ORM\Query;
<add>use Closure;
<ide> use InvalidArgumentException;
<ide> use RuntimeException;
<ide>
<ide> public function __construct(array $options)
<ide> * @param array $options Same options as `Association::eagerLoader()`
<ide> * @return \Closure
<ide> */
<del> public function buildEagerLoader(array $options)
<add> public function buildEagerLoader(array $options): Closure
<ide> {
<ide> $options += $this->_defaultOptions();
<ide> $fetchQuery = $this->_buildQuery($options);
<ide> public function buildEagerLoader(array $options)
<ide> *
<ide> * @return array
<ide> */
<del> protected function _defaultOptions()
<add> protected function _defaultOptions(): array
<ide> {
<ide> return [
<ide> 'foreignKey' => $this->foreignKey,
<ide> protected function _defaultOptions()
<ide> * @return \Cake\ORM\Query
<ide> * @throws \InvalidArgumentException When a key is required for associations but not selected.
<ide> */
<del> protected function _buildQuery($options)
<add> protected function _buildQuery(array $options): Query
<ide> {
<ide> $key = $this->_linkField($options);
<ide> $filter = $options['keys'];
<ide> protected function _buildQuery($options)
<ide> * and options as value.
<ide> * @return array
<ide> */
<del> protected function _extractFinder($finderData)
<add> protected function _extractFinder($finderData): array
<ide> {
<ide> $finderData = (array)$finderData;
<ide>
<ide> protected function _extractFinder($finderData)
<ide> * @return void
<ide> * @throws \InvalidArgumentException
<ide> */
<del> protected function _assertFieldsPresent($fetchQuery, $key)
<add> protected function _assertFieldsPresent(Query $fetchQuery, array $key): void
<ide> {
<ide> $select = $fetchQuery->aliasFields($fetchQuery->clause('select'));
<ide> if (empty($select)) {
<ide> protected function _assertFieldsPresent($fetchQuery, $key)
<ide> * @param \Cake\ORM\Query $subquery The Subquery to use for filtering
<ide> * @return \Cake\ORM\Query
<ide> */
<del> protected function _addFilteringJoin($query, $key, $subquery)
<add> protected function _addFilteringJoin(Query $query, $key, $subquery): Query
<ide> {
<ide> $filter = [];
<ide> $aliasedTable = $this->sourceAlias;
<ide> protected function _addFilteringJoin($query, $key, $subquery)
<ide> * @param mixed $filter The value that should be used to match for $key
<ide> * @return \Cake\ORM\Query
<ide> */
<del> protected function _addFilteringCondition($query, $key, $filter)
<add> protected function _addFilteringCondition(Query $query, $key, $filter): Query
<ide> {
<ide> if (is_array($key)) {
<ide> $conditions = $this->_createTupleCondition($query, $key, $filter, 'IN');
<ide> protected function _addFilteringCondition($query, $key, $filter)
<ide> * @param string $operator The operator for comparing the tuples
<ide> * @return \Cake\Database\Expression\TupleComparison
<ide> */
<del> protected function _createTupleCondition($query, $keys, $filter, $operator)
<add> protected function _createTupleCondition(Query $query, array $keys, $filter, $operator): TupleComparison
<ide> {
<ide> $types = [];
<ide> $defaults = $query->getDefaultTypes();
<ide> protected function _createTupleCondition($query, $keys, $filter, $operator)
<ide> * @param array $options The options for getting the link field.
<ide> * @return string|array
<ide> */
<del> protected function _linkField($options)
<add> protected function _linkField(array $options)
<ide> {
<ide> $links = [];
<ide> $name = $this->alias;
<ide> protected function _linkField($options)
<ide> * @param \Cake\ORM\Query $query the original query used to load source records
<ide> * @return \Cake\ORM\Query
<ide> */
<del> protected function _buildSubquery($query)
<add> protected function _buildSubquery(Query $query): Query
<ide> {
<ide> $filterQuery = clone $query;
<ide> $filterQuery->enableAutoFields(false);
<ide> protected function _buildSubquery($query)
<ide> * @param \Cake\ORM\Query $query The query to get fields from.
<ide> * @return array The list of fields for the subquery.
<ide> */
<del> protected function _subqueryFields($query)
<add> protected function _subqueryFields(Query $query): array
<ide> {
<ide> $keys = (array)$this->bindingKey;
<ide>
<ide> protected function _subqueryFields($query)
<ide> $order = $query->clause('order');
<ide> if ($order) {
<ide> $columns = $query->clause('select');
<del> $order->iterateParts(function ($direction, $field) use (&$fields, $columns) {
<add> $order->iterateParts(function ($direction, $field) use (&$fields, $columns): void {
<ide> if (isset($columns[$field])) {
<ide> $fields[$field] = $columns[$field];
<ide> }
<ide> protected function _subqueryFields($query)
<ide> * @param array $options The options passed to the eager loader
<ide> * @return array
<ide> */
<del> protected function _buildResultMap($fetchQuery, $options)
<add> protected function _buildResultMap(Query $fetchQuery, array $options): array
<ide> {
<ide> $resultMap = [];
<ide> $singleResult = in_array($this->associationType, [Association::MANY_TO_ONE, Association::ONE_TO_ONE]);
<ide> protected function _buildResultMap($fetchQuery, $options)
<ide> * @param array $options The options passed to the eagerLoader method
<ide> * @return \Closure
<ide> */
<del> protected function _resultInjector($fetchQuery, $resultMap, $options)
<add> protected function _resultInjector(Query $fetchQuery, array $resultMap, array $options): Closure
<ide> {
<ide> $keys = $this->associationType === Association::MANY_TO_ONE ?
<ide> $this->foreignKey :
<ide> protected function _resultInjector($fetchQuery, $resultMap, $options)
<ide> * @param string $nestKey The key under which results should be nested
<ide> * @return \Closure
<ide> */
<del> protected function _multiKeysInjector($resultMap, $sourceKeys, $nestKey)
<add> protected function _multiKeysInjector(array $resultMap, array $sourceKeys, string $nestKey): Closure
<ide> {
<ide> return function ($row) use ($resultMap, $sourceKeys, $nestKey) {
<ide> $values = [];
<ide><path>src/ORM/Association/Loader/SelectWithPivotLoader.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> */
<ide> namespace Cake\ORM\Association\Loader;
<ide>
<add>use Cake\ORM\Query;
<ide> use RuntimeException;
<ide>
<ide> /**
<ide> public function __construct(array $options)
<ide> * @return \Cake\ORM\Query
<ide> * @throws \InvalidArgumentException When a key is required for associations but not selected.
<ide> */
<del> protected function _buildQuery($options)
<add> protected function _buildQuery(array $options): Query
<ide> {
<ide> $name = $this->junctionAssociationName;
<ide> $assoc = $this->junctionAssoc;
<ide> protected function _buildQuery($options)
<ide> * @param array $options the options to use for getting the link field.
<ide> * @return array|string
<ide> */
<del> protected function _linkField($options)
<add> protected function _linkField(array $options)
<ide> {
<ide> $links = [];
<ide> $name = $this->junctionAssociationName;
<ide> protected function _linkField($options)
<ide> * @return array
<ide> * @throws \RuntimeException when the association property is not part of the results set.
<ide> */
<del> protected function _buildResultMap($fetchQuery, $options)
<add> protected function _buildResultMap(Query $fetchQuery, array $options): array
<ide> {
<ide> $resultMap = [];
<ide> $key = (array)$options['foreignKey'];
<ide><path>src/ORM/AssociationCollection.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct(?LocatorInterface $tableLocator = null)
<ide> * @param \Cake\ORM\Association $association The association to add.
<ide> * @return \Cake\ORM\Association The association object being added.
<ide> */
<del> public function add($alias, Association $association)
<add> public function add(string $alias, Association $association): Association
<ide> {
<ide> list(, $alias) = pluginSplit($alias);
<ide>
<ide> public function add($alias, Association $association)
<ide> * @return \Cake\ORM\Association
<ide> * @throws \InvalidArgumentException
<ide> */
<del> public function load($className, $associated, array $options = [])
<add> public function load(string $className, string $associated, array $options = []): Association
<ide> {
<ide> $options += [
<ide> 'tableLocator' => $this->getTableLocator(),
<ide> public function load($className, $associated, array $options = [])
<ide> * @param string $alias The association alias to get.
<ide> * @return \Cake\ORM\Association|null Either the association or null.
<ide> */
<del> public function get($alias)
<add> public function get(string $alias): ?Association
<ide> {
<ide> $alias = strtolower($alias);
<ide> if (isset($this->_items[$alias])) {
<ide> public function get($alias)
<ide> * @param string $prop The property to find an association by.
<ide> * @return \Cake\ORM\Association|null Either the association or null.
<ide> */
<del> public function getByProperty($prop)
<add> public function getByProperty(string $prop): ?Association
<ide> {
<ide> foreach ($this->_items as $assoc) {
<ide> if ($assoc->getProperty() === $prop) {
<ide> public function getByProperty($prop)
<ide> * @param string $alias The association alias to get.
<ide> * @return bool Whether or not the association exists.
<ide> */
<del> public function has($alias)
<add> public function has(string $alias): bool
<ide> {
<ide> return isset($this->_items[strtolower($alias)]);
<ide> }
<ide> public function has($alias)
<ide> *
<ide> * @return array
<ide> */
<del> public function keys()
<add> public function keys(): array
<ide> {
<ide> return array_keys($this->_items);
<ide> }
<ide> public function keys()
<ide> * @return array An array of Association objects.
<ide> * @since 3.5.3
<ide> */
<del> public function getByType($class)
<add> public function getByType($class): array
<ide> {
<ide> $class = array_map('strtolower', (array)$class);
<ide>
<ide> public function getByType($class)
<ide> * @param string $alias The alias name.
<ide> * @return void
<ide> */
<del> public function remove($alias)
<add> public function remove(string $alias): void
<ide> {
<ide> unset($this->_items[strtolower($alias)]);
<ide> }
<ide> public function remove($alias)
<ide> *
<ide> * @return void
<ide> */
<del> public function removeAll()
<add> public function removeAll(): void
<ide> {
<ide> foreach ($this->_items as $alias => $object) {
<ide> $this->remove($alias);
<ide> public function removeAll()
<ide> * @param array $options The options for the save operation.
<ide> * @return bool Success
<ide> */
<del> public function saveParents(Table $table, EntityInterface $entity, $associations, array $options = [])
<add> public function saveParents(Table $table, EntityInterface $entity, array $associations, array $options = []): bool
<ide> {
<ide> if (empty($associations)) {
<ide> return true;
<ide> public function saveParents(Table $table, EntityInterface $entity, $associations
<ide> * @param array $options The options for the save operation.
<ide> * @return bool Success
<ide> */
<del> public function saveChildren(Table $table, EntityInterface $entity, array $associations, array $options)
<add> public function saveChildren(Table $table, EntityInterface $entity, array $associations, array $options): bool
<ide> {
<ide> if (empty($associations)) {
<ide> return true;
<ide> public function saveChildren(Table $table, EntityInterface $entity, array $assoc
<ide> * @return bool Success
<ide> * @throws \InvalidArgumentException When an unknown alias is used.
<ide> */
<del> protected function _saveAssociations($table, $entity, $associations, $options, $owningSide)
<add> protected function _saveAssociations(Table $table, EntityInterface $entity, array $associations, array $options, bool $owningSide): bool
<ide> {
<ide> unset($options['associated']);
<ide> foreach ($associations as $alias => $nested) {
<ide> protected function _saveAssociations($table, $entity, $associations, $options, $
<ide> * @param array $options Original options
<ide> * @return bool Success
<ide> */
<del> protected function _save($association, $entity, $nested, $options)
<add> protected function _save(Association $association, EntityInterface $entity, array $nested, array $options): bool
<ide> {
<ide> if (!$entity->isDirty($association->getProperty())) {
<ide> return true;
<ide> protected function _save($association, $entity, $nested, $options)
<ide> * @param array $options The options used in the delete operation.
<ide> * @return void
<ide> */
<del> public function cascadeDelete(EntityInterface $entity, array $options)
<add> public function cascadeDelete(EntityInterface $entity, array $options): void
<ide> {
<ide> $noCascade = $this->_getNoCascadeItems($entity, $options);
<ide> foreach ($noCascade as $assoc) {
<ide> public function cascadeDelete(EntityInterface $entity, array $options)
<ide> * @param array $options The options used in the delete operation.
<ide> * @return \Cake\ORM\Association[]
<ide> */
<del> protected function _getNoCascadeItems($entity, $options)
<add> protected function _getNoCascadeItems(EntityInterface $entity, array $options)
<ide> {
<ide> $noCascade = [];
<ide> foreach ($this->_items as $assoc) {
<ide> protected function _getNoCascadeItems($entity, $options)
<ide> * @param bool|array $keys the list of association names to normalize
<ide> * @return array
<ide> */
<del> public function normalizeKeys($keys)
<add> public function normalizeKeys($keys): array
<ide> {
<ide> if ($keys === true) {
<ide> $keys = $this->keys();
<ide> public function normalizeKeys($keys)
<ide> *
<ide> * @return \ArrayIterator
<ide> */
<del> public function getIterator()
<add> public function getIterator(): ArrayIterator
<ide> {
<ide> return new ArrayIterator($this->_items);
<ide> }
<ide><path>src/ORM/AssociationsNormalizerTrait.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> trait AssociationsNormalizerTrait
<ide> * Returns an array out of the original passed associations list where dot notation
<ide> * is transformed into nested arrays so that they can be parsed by other routines
<ide> *
<del> * @param array $associations The array of included associations.
<add> * @param array|string $associations The array of included associations.
<ide> * @return array An array having dot notation transformed into nested arrays
<ide> */
<del> protected function _normalizeAssociations($associations)
<add> protected function _normalizeAssociations($associations): array
<ide> {
<ide> $result = [];
<ide> foreach ((array)$associations as $table => $options) {
<ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/ORM/Association/BelongsToTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/ORM/Association/HasManyTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/ORM/Association/HasOneTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/ORM/AssociationCollectionTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/ORM/AssociationProxyTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/ORM/AssociationTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) | 17 |
Python | Python | apply patch for unique from #154 | 50831666840ec2ee065569c3e3c9fbc5461fc918 | <ide><path>numpy/lib/function_base.py
<ide> def trim_zeros(filt, trim='fb'):
<ide> else: last = last - 1
<ide> return filt[first:last]
<ide>
<del>def unique(inseq):
<del> """Return unique items (in sorted order) from a 1-dimensional sequence.
<del> """
<del> # Dictionary setting is quite fast.
<del> set = {}
<del> for item in inseq:
<del> set[item] = None
<del> val = asarray(set.keys())
<del> val.sort()
<del> return val
<ide>
<add>import sys
<add>if sys.hexversion < 0x2040000:
<add> from sets import Set as set
<add>
<add>def unique(x):
<add> """Return sorted unique items from an array or sequence.
<add>
<add> Example:
<add> >>> unique([5,2,4,0,4,4,2,2,1])
<add> array([0,1,2,4,5])
<add> """
<add> try:
<add> tmp = x.flatten()
<add> tmp.sort()
<add> idx = concatenate(([True],tmp[1:]!=tmp[:-1]))
<add> return tmp[idx]
<add> except AttributeError:
<add> items = list(set(x))
<add> items.sort()
<add> return asarray(items)
<add>
<ide> def extract(condition, arr):
<ide> """Return the elements of ravel(arr) where ravel(condition) is True
<ide> (in 1D).
<ide><path>numpy/lib/tests/test_function_base.py
<ide> def check_simple(self):
<ide> (a,b)=histogram(linspace(0,10,100))
<ide> assert(all(a==10))
<ide>
<del>
<add>class test_unique(NumpyTestCase):
<add> def check_simple(self):
<add> x = array([4,3,2,1,1,2,3,4, 0])
<add> assert(all(unique(x) == [0,1,2,3,4]))
<add> assert(unique(array([1,1,1,1,1])) == array([1]))
<add> x = ['widget', 'ham', 'foo', 'bar', 'foo', 'ham']
<add> assert(all(unique(x) == ['bar', 'foo', 'ham', 'widget']))
<add> x = array([5+6j, 1+1j, 1+10j, 10, 5+6j])
<add> assert(all(unique(x) == [1+1j, 1+10j, 5+6j, 10]))
<ide>
<ide> def compare_results(res,desired):
<ide> for i in range(len(desired)): | 2 |
Javascript | Javascript | add blob benchmark | 6adaf23c20acc48b836134ea660dc8c16f028117 | <ide><path>benchmark/blob/blob.js
<add>'use strict';
<add>const common = require('../common.js');
<add>const { Blob } = require('buffer');
<add>
<add>const bench = common.createBenchmark(main, {
<add> bytes: [128, 1024, 1024 ** 2],
<add> n: [1e6],
<add> operation: ['text', 'arrayBuffer']
<add>});
<add>
<add>async function run(n, bytes, operation) {
<add> const buff = Buffer.allocUnsafe(bytes);
<add> const source = new Blob(buff);
<add> bench.start();
<add> for (let i = 0; i < n; i++) {
<add> switch (operation) {
<add> case 'text':
<add> await source.text();
<add> break;
<add> case 'arrayBuffer':
<add> await source.arrayBuffer();
<add> break;
<add> }
<add> }
<add> bench.end(n);
<add>}
<add>
<add>function main(conf) {
<add> run(conf.n, conf.bytes, conf.operation).catch(console.log);
<add>}
<ide><path>test/benchmark/test-benchmark-blob.js
<add>'use strict';
<add>
<add>require('../common');
<add>
<add>const runBenchmark = require('../common/benchmark');
<add>
<add>runBenchmark('blob', { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); | 2 |
Javascript | Javascript | add test for process.stdin.setrawmode() | 3ae09001426bbb018bdeae39747225256e370f3d | <ide><path>test/pseudo-tty/stdin-setrawmode.js
<add>'use strict';
<add>require('../common');
<add>const assert = require('assert');
<add>
<add>process.stdin.setRawMode(true);
<add>assert.strictEqual(process.stdin.isRaw, true);
<add>
<add>process.stdin.setRawMode(false);
<add>assert.strictEqual(process.stdin.isRaw, false); | 1 |
Python | Python | fix python 3 related issues | 4be89d24b3f8cb5376f476437bda2342baf42043 | <ide><path>libcloud/storage/drivers/backblaze_b2.py
<ide> def upload_object(self, file_path, container, object_name, extra=None,
<ide> headers['Content-Type'] = content_type
<ide>
<ide> sha1 = hashlib.sha1()
<del> sha1.update(data.encode())
<add> sha1.update(b(data))
<ide> headers['X-Bz-Content-Sha1'] = sha1.hexdigest()
<ide>
<ide> # Include optional meta-data (up to 10 items)
<ide><path>libcloud/test/storage/test_backblaze_b2.py
<ide> def test_download_object_as_stream(self):
<ide> container = self.driver.list_containers()[0]
<ide> obj = self.driver.list_container_objects(container=container)[0]
<ide> result = self.driver.download_object_as_stream(obj=obj)
<del> result = ''.join(list(result))
<add> result = ''.join([x.decode('utf-8') for x in list(result)])
<ide> self.assertEqual(result, 'ab')
<ide>
<ide> def test_upload_object(self): | 2 |
PHP | PHP | use json_extract instead of json_merge | 5c7ac297994994fd6d3a804ac9729f4fca61e479 | <ide><path>src/Illuminate/Database/Query/JsonExpression.php
<ide> protected function getJsonBindingParameter($value)
<ide> return '?';
<ide> case 'object':
<ide> case 'array':
<del> return 'json_merge(?, "[]")';
<add> return 'json_extract(?, "$")';
<ide> }
<ide>
<ide> throw new InvalidArgumentException("JSON value is of illegal type: {$type}");
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testMySqlUpdateWrappingJsonArray()
<ide> $connection->expects($this->once())
<ide> ->method('update')
<ide> ->with(
<del> 'update `users` set `meta` = json_set(`meta`, \'$."tags"\', json_merge(?, "[]")) where `active` = ?',
<add> 'update `users` set `meta` = json_set(`meta`, \'$."tags"\', json_extract(?, "$")) where `active` = ?',
<ide> [['white', 'black', 'yellow'], 1]
<ide> );
<ide>
<ide> public function testMySqlUpdateWrappingJsonObject()
<ide> $connection->expects($this->once())
<ide> ->method('update')
<ide> ->with(
<del> 'update `users` set `meta` = json_set(`meta`, \'$."tags"\', json_merge(?, "[]")) where `active` = ?',
<add> 'update `users` set `meta` = json_set(`meta`, \'$."tags"\', json_extract(?, "$")) where `active` = ?',
<ide> [['color' => 'white', 'size' => 'large'], 1]
<ide> );
<ide> | 2 |
Text | Text | add table of contents to contributing doc | 6bc521815aa68e3296935dec3f292d64dba65e6c | <ide><path>CONTRIBUTING.md
<ide> # Contributor's Guide
<ide>
<add>## Table of Contents
<add>
<add>- [I want to help!](#i-want-to-help)
<add>- [Contribution Guidelines](#contribution-guidelines)
<add>- [Prerequisites](#prerequisites)
<add>- [Getting Started](#getting-started)
<add>- [Linting Setup](#linting-setup)
<add>- [Found a bug?](#found-a-bug)
<add>- [Creating Pull Requests](#creating-pull-requests)
<add>- [Common Steps](#common-steps)
<add>- [Next Steps](#next-steps)
<add>
<ide> ## I want to help!
<del>We welcome pull requests from Free Code Camp campers (our students) and seasoned JavaScript developers alike! Follow these steps to contribute:
<ide>
<add>We welcome pull requests from Free Code Camp campers (our students) and seasoned JavaScript developers alike! Follow these steps to contribute:
<ide>
<ide> 1. Find an issue that needs assistance by searching for the [Help Wanted](https://github.com/FreeCodeCamp/FreeCodeCamp/labels/help%20wanted) tag.
<ide> 2. Let us know you are working on it by posting a comment on the issue.
<ide> If you've found a bug that is not on the board, [follow these steps](#found-a-bu
<ide> 5. Squash your Commits. Ref: [rebasing](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/git-rebase)
<ide> 6. Submit a [pull request](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Pull-Request-Contribute) from your branch to Free Code Camp's `staging` branch. [Travis CI](https://travis-ci.org/FreeCodeCamp/FreeCodeCamp) will then take your code and run `npm test`. Make sure this passes, then we'll do a quick code review and give you feedback, then iterate from there.
<ide>
<del>
<del>Prerequisites
<del>-------------
<add>## Prerequisites
<ide>
<ide> - [MongoDB](http://www.mongodb.org/downloads)
<ide> - [Node.js](http://nodejs.org)
<ide>
<del>Getting Started
<del>---------------
<add>## Getting Started
<add>
<ide> Note: If this is your first time working with a node-gyp dependent module, please follow the [node-gyp installation guide](https://github.com/nodejs/node-gyp#installation) to ensure a working npm build.
<ide>
<ide> The easiest way to get started is to clone the repository:
<ide> Now navigate to your browser and open http://localhost:3001
<ide> If the app loads, congratulations - you're all set. Otherwise, let us know by opening a GitHub issue and with your error.
<ide>
<ide> ## Linting Setup
<add>
<ide> You should have [ESLint running in your editor](http://eslint.org/docs/user-guide/integrations.html), and it will highlight anything doesn't conform to [Free Code Camp's JavaScript Style Guide](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Free-Code-Camp-JavaScript-Style-Guide) (you can find a summary of those rules [here](https://github.com/FreeCodeCamp/FreeCodeCamp/blob/staging/.eslintrc). Please do not ignore any linting errors, as they are meant to **help** you and to ensure a clean and simple code base. Make sure none of your JavaScript is longer than 80 characters per line. The reason we enforce this is because one of our dependent NPM modules, [jsonlint](https://github.com/zaach/jsonlint), does not fully support wildcard paths in Windows.
<ide>
<ide> ## Found a bug?
<ide> Do not file an issue until you have followed these steps:
<ide> 2. Asked for confirmation in the appropriate [Help Room](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Help-Rooms)
<ide> 3. Please *do not* open an issue without a 3rd party confirmation of your problem.
<ide>
<del>
<ide> ## Creating Pull Requests
<ide> **What is a Pull Request?**
<ide>
<ide> If you have a local copy of the repo, you can make the requested changes and ame
<ide>
<ide> Be sure to post in the PR conversation that you have made the requested changes.
<ide>
<del>##Other resources
<add>## Other resources
<add>
<ide> - [Searching for Your Issue on GitHub](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Searching-for-Your-Issue-on-GitHub)
<ide> - [Creating a New GitHub Issue](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Creating-a-New-GitHub-Issue)
<ide> - [Select Issues for Contributing Using Labels](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Select-Issues-for-Contributing-Using-Labels) | 1 |
Java | Java | make systrace less noisy in java | 523a103108d7ae7073653233a35ed678bf844848 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> public void recreateReactContextInBackground() {
<ide> private void recreateReactContextInBackgroundInner() {
<ide> UiThreadUtil.assertOnUiThread();
<ide>
<del> if (mUseDeveloperSupport && mJSMainModuleName != null) {
<add> if (mUseDeveloperSupport && mJSMainModuleName != null &&
<add> !Systrace.isTracing(TRACE_TAG_REACT_APPS | TRACE_TAG_REACT_JSC_CALLS)) {
<ide> final DeveloperSettings devSettings = mDevSupportManager.getDevSettings();
<ide>
<ide> // If remote JS debugging is enabled, load from dev server. | 1 |
Javascript | Javascript | remove peculiar web language | 843ad50296c0a19d3e342c5be9ea92e37fac109a | <ide><path>Libraries/Components/Touchable/TouchableWithoutFeedback.js
<ide> const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
<ide>
<ide> /**
<ide> * Do not use unless you have a very good reason. All the elements that
<del> * respond to press should have a visual feedback when touched. This is
<del> * one of the primary reasons a "web" app doesn't feel "native".
<add> * respond to press should have a visual feedback when touched.
<ide> *
<ide> * > **NOTE**: TouchableWithoutFeedback supports only one child
<ide> * > | 1 |
Javascript | Javascript | add feature test for blend mode | ed1fa5a9192bfd82559807dfeab43c11340c75a0 | <ide><path>test/features/tests.js
<ide> var tests = [
<ide> },
<ide> impact: 'Important',
<ide> area: 'Core'
<add> },
<add> {
<add> id: 'Canvas Blend Mode',
<add> name: 'Canvas supports extended blend modes',
<add> run: function () {
<add> var fail = { output: 'Failed', emulated: 'No' };
<add> var ctx = document.createElement('canvas').getContext('2d');
<add> ctx.canvas.width = 1;
<add> ctx.canvas.height = 1;
<add> var mode = 'difference';
<add> ctx.globalCompositeOperation = mode;
<add> if (ctx.globalCompositeOperation !== mode) {
<add> return fail;
<add> }
<add> // Chrome supports setting the value, but it may not actually be
<add> // implemented, so we have to actually test the blend mode.
<add> ctx.fillStyle = 'red';
<add> ctx.fillRect(0, 0, 1, 1);
<add> ctx.fillStyle = 'blue';
<add> ctx.fillRect(0, 0, 1, 1);
<add> var pix = ctx.getImageData(0, 0, 1, 1).data;
<add> if (pix[0] !== 255 || pix[1] !== 0 || pix[2] !== 255) {
<add> return fail;
<add> }
<add> return { output: 'Success', emulated: '' };
<add> },
<add> impact: 'Important',
<add> area: 'Core'
<ide> }
<ide> ];
<ide> | 1 |
Python | Python | rethrow original exception in generatorenqueuer. | 4a58b178073f0ba3b166220f7ebd7d56149bfb20 | <ide><path>keras/utils/data_utils.py
<ide> import tarfile
<ide> import threading
<ide> import time
<add>import traceback
<ide> import zipfile
<ide> from abc import abstractmethod
<ide> from multiprocessing.pool import ThreadPool
<ide> def get(self):
<ide> yield inputs
<ide> except Exception as e:
<ide> self.stop()
<del> raise StopIteration(e)
<add> six.raise_from(StopIteration(e), e)
<ide>
<ide> def _send_sequence(self):
<ide> """Send current Sequence to all workers."""
<ide> def __init__(self, generator,
<ide> self._use_multiprocessing = use_multiprocessing
<ide> self._threads = []
<ide> self._stop_event = None
<add> self._manager = None
<ide> self.queue = None
<ide> self.seed = seed
<ide>
<ide> def data_generator_task():
<ide> try:
<ide> if self._use_multiprocessing or self.queue.qsize() < max_queue_size:
<ide> generator_output = next(self._generator)
<del> self.queue.put(generator_output)
<add> self.queue.put((True, generator_output))
<ide> else:
<ide> time.sleep(self.wait_time)
<ide> except StopIteration:
<ide> break
<del> except Exception:
<add> except Exception as e:
<add> # Can't pick tracebacks.
<add> # As a compromise, print the traceback and pickle None instead.
<add> if self._use_multiprocessing:
<add> traceback.print_exc()
<add> setattr(e, '__traceback__', None)
<add> elif not hasattr(e, '__traceback__'):
<add> setattr(e, '__traceback__', sys.exc_info()[2])
<add> self.queue.put((False, e))
<ide> self._stop_event.set()
<del> raise
<add> break
<ide>
<ide> try:
<ide> if self._use_multiprocessing:
<del> self.queue = multiprocessing.Queue(maxsize=max_queue_size)
<add> self._manager = multiprocessing.Manager()
<add> self.queue = self._manager.Queue(maxsize=max_queue_size)
<ide> self._stop_event = multiprocessing.Event()
<ide> else:
<ide> self.queue = queue.Queue()
<ide> def stop(self, timeout=None):
<ide> else:
<ide> thread.join(timeout)
<ide>
<del> if self._use_multiprocessing:
<del> if self.queue is not None:
<del> self.queue.close()
<add> if self._manager:
<add> self._manager.shutdown()
<ide>
<ide> self._threads = []
<ide> self._stop_event = None
<ide> def get(self):
<ide> """
<ide> while self.is_running():
<ide> if not self.queue.empty():
<del> inputs = self.queue.get()
<del> if inputs is not None:
<del> yield inputs
<add> success, value = self.queue.get()
<add> # Rethrow any exceptions found in the queue
<add> if not success:
<add> six.reraise(value.__class__, value, value.__traceback__)
<add> # Yield regular values
<add> if value is not None:
<add> yield value
<ide> else:
<ide> all_finished = all([not thread.is_alive() for thread in self._threads])
<ide> if all_finished and self.queue.empty():
<ide> raise StopIteration()
<ide> else:
<ide> time.sleep(self.wait_time)
<add>
<add> # Make sure to rethrow the first exception in the queue, if any
<add> while not self.queue.empty():
<add> success, value = self.queue.get()
<add> if not success:
<add> six.reraise(value.__class__, value, value.__traceback__)
<ide><path>tests/keras/utils/data_utils_test.py
<ide> def test_generator_enqueuer_fail_threads():
<ide> FaultSequence()), use_multiprocessing=False)
<ide> enqueuer.start(3, 10)
<ide> gen_output = enqueuer.get()
<del> with pytest.raises(StopIteration):
<add> with pytest.raises(IndexError):
<ide> next(gen_output)
<ide>
<ide>
<ide> def test_generator_enqueuer_fail_processes():
<ide> FaultSequence()), use_multiprocessing=True)
<ide> enqueuer.start(3, 10)
<ide> gen_output = enqueuer.get()
<del> with pytest.raises(StopIteration):
<add> with pytest.raises(IndexError):
<ide> next(gen_output)
<ide>
<ide>
<ide><path>tests/test_multiprocessing.py
<ide> def custom_generator():
<ide> """Raises an exception after a few good batches"""
<ide> for i in range(good_batches):
<ide> yield (np.random.randint(batch_size, 256, (50, 2)),
<del> np.random.randint(batch_size, 2, 50))
<add> np.random.randint(batch_size, 12, 50))
<ide> raise RuntimeError
<ide>
<ide> model = Sequential()
<ide> def custom_generator():
<ide>
<ide> samples = batch_size * (good_batches + 1)
<ide>
<del> with pytest.raises(StopIteration):
<add> with pytest.raises(RuntimeError):
<ide> model.fit_generator(
<ide> custom_generator(), samples, 1,
<ide> workers=4, use_multiprocessing=True,
<ide> )
<ide>
<del> with pytest.raises(StopIteration):
<add> with pytest.raises(RuntimeError):
<ide> model.fit_generator(
<ide> custom_generator(), samples, 1,
<ide> use_multiprocessing=False,
<ide> def custom_generator():
<ide> def test_multiprocessing_evaluate_error():
<ide> batch_size = 10
<ide> good_batches = 3
<add> workers = 4
<ide>
<ide> def custom_generator():
<ide> """Raises an exception after a few good batches"""
<ide> for i in range(good_batches):
<ide> yield (np.random.randint(batch_size, 256, (50, 2)),
<del> np.random.randint(batch_size, 2, 50))
<add> np.random.randint(batch_size, 12, 50))
<ide> raise RuntimeError
<ide>
<ide> model = Sequential()
<ide> model.add(Dense(1, input_shape=(2, )))
<ide> model.compile(loss='mse', optimizer='adadelta')
<ide>
<del> with pytest.raises(StopIteration):
<add> with pytest.raises(RuntimeError):
<ide> model.evaluate_generator(
<del> custom_generator(), good_batches + 1, 1,
<del> workers=4, use_multiprocessing=True,
<add> custom_generator(), good_batches * workers + 1, 1,
<add> workers=workers, use_multiprocessing=True,
<ide> )
<ide>
<del> with pytest.raises(StopIteration):
<add> with pytest.raises(RuntimeError):
<ide> model.evaluate_generator(
<ide> custom_generator(), good_batches + 1, 1,
<ide> use_multiprocessing=False,
<ide> def custom_generator():
<ide> model.add(Dense(1, input_shape=(5,)))
<ide> model.compile(loss='mse', optimizer='adadelta')
<ide>
<del> with pytest.raises(StopIteration):
<add> with pytest.raises(RuntimeError):
<ide> model.predict_generator(
<ide> custom_generator(), good_batches * workers + 1, 1,
<ide> workers=workers, use_multiprocessing=True,
<ide> )
<ide>
<del> with pytest.raises(StopIteration):
<add> with pytest.raises(RuntimeError):
<ide> model.predict_generator(
<ide> custom_generator(), good_batches + 1, 1,
<ide> use_multiprocessing=False, | 3 |
Python | Python | add more extension methods to the libvirt driver | aec5d33791ce6626612acd51a53589f474e7dcd1 | <ide><path>libcloud/compute/drivers/libvirt_driver.py
<ide> # limitations under the License.
<ide>
<ide> import re
<add>import os
<add>import time
<ide> import platform
<ide> import subprocess
<add>import mimetypes
<ide>
<add>from os.path import join as pjoin
<ide> from collections import defaultdict
<ide> from xml.etree import ElementTree as ET
<ide>
<ide> class LibvirtNodeDriver(NodeDriver):
<ide> """
<ide> Libvirt (http://libvirt.org/) node driver.
<ide>
<del> Usage: LibvirtNodeDriver(uri='vbox:///session').
<ide> To enable debug mode, set LIBVIR_DEBUG environment variable.
<ide> """
<ide>
<ide> def ex_shutdown_node(self, node):
<ide> """
<ide> Shutdown a running node.
<ide>
<add> Note: Usually this will result in sending an ACPI event to the node.
<add>
<ide> :param node: Node which should be used
<ide> :type node: :class:`Node`
<ide>
<ide> def ex_resume_node(self, node):
<ide> domain = self._get_domain_for_node(node=node)
<ide> return domain.resume() == 0
<ide>
<add> def ex_take_node_screenshot(self, node, directory, screen=0):
<add> """
<add> Take a screenshot of a monitoring of a running instance.
<add>
<add> :param node: Node to take the screenshot of.
<add> :type node: :class:`libcloud.compute.base.Node`
<add>
<add> :param directory: Path where the screenshot will be saved.
<add> :type directory: ``str``
<add>
<add> :param screen: ID of the monitor to take the screenshot of.
<add> :type screen: ``int``
<add>
<add> :return: Full path where the screenshot has been saved.
<add> :rtype: ``str``
<add> """
<add> if not os.path.exists(directory) or not os.path.isdir(directory):
<add> raise ValueError('Invalid value for directory argument')
<add>
<add> domain = self._get_domain_for_node(node=node)
<add> stream = self.connection.newStream()
<add> mime_type = domain.screenshot(stream=stream, screen=0)
<add> extensions = mimetypes.guess_all_extensions(type=mime_type)
<add>
<add> if extensions:
<add> extension = extensions[0]
<add> else:
<add> extension = '.png'
<add>
<add> name = 'screenshot-%s%s' % (int(time.time()), extension)
<add> file_path = pjoin(directory, name)
<add>
<add> with open(file_path, 'wb') as fp:
<add> def write(stream, buf, opaque):
<add> fp.write(buf)
<add>
<add> stream.recvAll(write, None)
<add>
<add> try:
<add> stream.finish()
<add> except Exception:
<add> # Finish is not supported by all backends
<add> pass
<add>
<add> return file_path
<add>
<add> def ex_get_hypervisor_hostname(self):
<add> """
<add> Return a system hostname on which the hypervisor is running.
<add> """
<add> hostname = self.connection.getHostname()
<add> return hostname
<add>
<add> def ex_get_hypervisor_sysinfo(self):
<add> """
<add> Retrieve hypervisor system information.
<add>
<add> :rtype: ``dict``
<add> """
<add> xml = self.connection.getSysinfo()
<add> etree = ET.XML(xml)
<add>
<add> attributes = ['bios', 'system', 'processor', 'memory_device']
<add>
<add> sysinfo = {}
<add> for attribute in attributes:
<add> element = etree.find(attribute)
<add> entries = self._get_entries(element=element)
<add> sysinfo[attribute] = entries
<add>
<add> return sysinfo
<add>
<ide> def _to_nodes(self, domains):
<ide> nodes = [self._to_node(domain=domain) for domain in domains]
<ide> return nodes
<ide> def _get_domain_for_node(self, node):
<ide> domain = self.connection.lookupByUUIDString(node.uuid)
<ide> return domain
<ide>
<add> def _get_entries(self, element):
<add> """
<add> Parse entries dictionary.
<add>
<add> :rtype: ``dict``
<add> """
<add> elements = element.findall('entry')
<add>
<add> result = {}
<add> for element in elements:
<add> name = element.get('name')
<add> value = element.text
<add> result[name] = value
<add>
<add> return result
<add>
<ide> def _parse_arp_table(self, arp_output):
<ide> """
<ide> Parse arp command output and return a dictionary which maps mac address | 1 |
Ruby | Ruby | run readall when tapping. (#396) | 4da990587f723a563e602a665403393f67fc8e70 | <ide><path>Library/Homebrew/cmd/readall.rb
<ide> # when making significant changes to formula.rb,
<ide> # or to determine if any current formulae have Ruby issues
<ide>
<del>require "formula"
<del>require "tap"
<del>require "thread"
<add>require "readall"
<ide>
<ide> module Homebrew
<ide> def readall
<del> if ARGV.delete("--syntax")
<del> ruby_files = Queue.new
<add> if ARGV.include?("--syntax")
<add> ruby_files = []
<ide> scan_files = %W[
<ide> #{HOMEBREW_LIBRARY}/*.rb
<ide> #{HOMEBREW_LIBRARY}/Homebrew/**/*.rb
<ide> def readall
<ide> ruby_files << rb
<ide> end
<ide>
<del> failed = false
<del> workers = (0...Hardware::CPU.cores).map do
<del> Thread.new do
<del> begin
<del> while rb = ruby_files.pop(true)
<del> # As a side effect, print syntax errors/warnings to `$stderr`.
<del> failed = true if syntax_errors_or_warnings?(rb)
<del> end
<del> rescue ThreadError # ignore empty queue error
<del> end
<del> end
<del> end
<del> workers.each(&:join)
<del> Homebrew.failed = failed
<add> Homebrew.failed = true unless Readall.valid_ruby_syntax?(ruby_files)
<ide> end
<ide>
<del> formulae = []
<del> alias_dirs = []
<del> if ARGV.named.empty?
<del> formulae = Formula.files
<del> alias_dirs = Tap.map(&:alias_dir)
<add> options = { :aliases => ARGV.include?("--aliases") }
<add> taps = if ARGV.named.any?
<add> [Tap.fetch(ARGV.named.first)]
<ide> else
<del> tap = Tap.fetch(ARGV.named.first)
<del> raise TapUnavailableError, tap.name unless tap.installed?
<del> formulae = tap.formula_files
<del> alias_dirs = [tap.alias_dir]
<add> Tap
<ide> end
<del>
<del> if ARGV.delete("--aliases")
<del> alias_dirs.each do |alias_dir|
<del> next unless alias_dir.directory?
<del> Pathname.glob("#{alias_dir}/*").each do |f|
<del> next unless f.symlink?
<del> next if f.file?
<del> onoe "Broken alias: #{f}"
<del> Homebrew.failed = true
<del> end
<del> end
<del> end
<del>
<del> formulae.each do |file|
<del> begin
<del> Formulary.factory(file)
<del> rescue Interrupt
<del> raise
<del> rescue Exception => e
<del> onoe "problem in #{file}"
<del> puts e
<del> Homebrew.failed = true
<del> end
<add> taps.each do |tap|
<add> Homebrew.failed = true unless Readall.valid_tap?(tap, options)
<ide> end
<ide> end
<del>
<del> private
<del>
<del> def syntax_errors_or_warnings?(rb)
<del> # Retrieve messages about syntax errors/warnings printed to `$stderr`, but
<del> # discard a `Syntax OK` printed to `$stdout` (in absence of syntax errors).
<del> messages = Utils.popen_read("#{RUBY_PATH} -c -w #{rb} 2>&1 >/dev/null")
<del> $stderr.print messages
<del>
<del> # Only syntax errors result in a non-zero status code. To detect syntax
<del> # warnings we also need to inspect the output to `$stderr`.
<del> !$?.success? || !messages.chomp.empty?
<del> end
<ide> end
<ide><path>Library/Homebrew/readall.rb
<add>require "formula"
<add>require "tap"
<add>require "thread"
<add>require "readall"
<add>
<add>module Readall
<add> class << self
<add> def valid_ruby_syntax?(ruby_files)
<add> ruby_files_queue = Queue.new
<add> ruby_files.each { |f| ruby_files_queue << f }
<add> failed = false
<add> workers = (0...Hardware::CPU.cores).map do
<add> Thread.new do
<add> begin
<add> while rb = ruby_files_queue.pop(true)
<add> # As a side effect, print syntax errors/warnings to `$stderr`.
<add> failed = true if syntax_errors_or_warnings?(rb)
<add> end
<add> rescue ThreadError # ignore empty queue error
<add> end
<add> end
<add> end
<add> workers.each(&:join)
<add> !failed
<add> end
<add>
<add> def valid_aliases?(alias_dirs)
<add> failed = false
<add> alias_dirs.each do |alias_dir|
<add> next unless alias_dir.directory?
<add> alias_dir.children.each do |f|
<add> next unless f.symlink?
<add> next if f.file?
<add> onoe "Broken alias: #{f}"
<add> failed = true
<add> end
<add> end
<add> !failed
<add> end
<add>
<add> def valid_formulae?(formulae)
<add> failed = false
<add> formulae.each do |file|
<add> begin
<add> Formulary.factory(file)
<add> rescue Interrupt
<add> raise
<add> rescue Exception => e
<add> onoe "Invalid formula: #{file}"
<add> puts e
<add> failed = true
<add> end
<add> end
<add> !failed
<add> end
<add>
<add> def valid_tap?(tap, options = {})
<add> failed = false
<add> if options[:aliases]
<add> valid_aliases = valid_aliases?([tap.alias_dir])
<add> failed = true unless valid_aliases
<add> end
<add> valid_formulae = valid_formulae?(tap.formula_files)
<add> failed = true unless valid_formulae
<add> !failed
<add> end
<add>
<add> private
<add>
<add> def syntax_errors_or_warnings?(rb)
<add> # Retrieve messages about syntax errors/warnings printed to `$stderr`, but
<add> # discard a `Syntax OK` printed to `$stdout` (in absence of syntax errors).
<add> messages = Utils.popen_read("#{RUBY_PATH} -c -w #{rb} 2>&1 >/dev/null")
<add> $stderr.print messages
<add>
<add> # Only syntax errors result in a non-zero status code. To detect syntax
<add> # warnings we also need to inspect the output to `$stderr`.
<add> !$?.success? || !messages.chomp.empty?
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/tap.rb
<ide> require "extend/string"
<add>require "readall"
<ide>
<ide> # a {Tap} is used to extend the formulae provided by Homebrew core.
<ide> # Usually, it's synced with a remote git repository. And it's likely
<ide> def install(options = {})
<ide>
<ide> begin
<ide> safe_system "git", *args
<del> rescue Interrupt, ErrorDuringExecution
<add> unless Readall.valid_tap?(self, :aliases => true)
<add> raise "Cannot tap #{name}: invalid syntax in tap!"
<add> end
<add> rescue Interrupt, ErrorDuringExecution, RuntimeError
<ide> ignore_interrupts do
<del> sleep 0.1 # wait for git to cleanup the top directory when interrupt happens.
<add> # wait for git to possibly cleanup the top directory when interrupt happens.
<add> sleep 0.1
<add> FileUtils.rm_rf path
<ide> path.parent.rmdir_if_possible
<ide> end
<ide> raise
<ide><path>Library/Homebrew/test/test_tap.rb
<ide> def test_remote
<ide> end
<ide> refute_predicate version_tap, :private?
<ide> ensure
<del> version_tap.path.rmtree
<add> version_tap.path.rmtree if version_tap
<ide> end
<ide>
<ide> def test_remote_not_git_repo
<ide> def test_install_and_uninstall
<ide> refute_predicate HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1", :exist?
<ide> refute_predicate HOMEBREW_PREFIX/"share/man/man1", :exist?
<ide> ensure
<del> (HOMEBREW_PREFIX/"share").rmtree
<add> (HOMEBREW_PREFIX/"share").rmtree if (HOMEBREW_PREFIX/"share").exist?
<ide> end
<ide>
<ide> def test_pin_and_unpin | 4 |
PHP | PHP | set a message for suspiciousoperationexception | 1b3f26dd0b722ac55b0b04d2a603a967271f82e9 | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> protected function prepareException(Exception $e)
<ide> } elseif ($e instanceof TokenMismatchException) {
<ide> $e = new HttpException(419, $e->getMessage(), $e);
<ide> } elseif ($e instanceof SuspiciousOperationException) {
<del> $e = new NotFoundHttpException(null, $e);
<add> $e = new NotFoundHttpException('Bad hostname provided', $e);
<ide> }
<ide>
<ide> return $e; | 1 |
Ruby | Ruby | use utils.popen_read in xquartz version codepath | 677cd519778ab66e19699d847b03a2f3d958bd2a | <ide><path>Library/Homebrew/os/mac.rb
<ide> def app_with_bundle_id(*ids)
<ide> def mdfind(*ids)
<ide> return [] unless OS.mac?
<ide> (@mdfind ||= {}).fetch(ids) do
<del> @mdfind[ids] = `/usr/bin/mdfind "#{mdfind_query(*ids)}"`.split("\n")
<add> @mdfind[ids] = Utils.popen_read("/usr/bin/mdfind", mdfind_query(*ids), &:read).split("\n")
<ide> end
<ide> end
<ide>
<ide> def pkgutil_info(id)
<ide> (@pkginfo ||= {}).fetch(id) do |key|
<del> @pkginfo[key] = `/usr/sbin/pkgutil --pkg-info "#{key}" 2>/dev/null`.strip
<add> @pkginfo[key] = Utils.popen_read("/usr/sbin/pkgutil", "--pkg-info", key, &:read).strip
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/os/mac/xquartz.rb
<ide> def bundle_path
<ide> end
<ide>
<ide> def version_from_mdls(path)
<del> version = `mdls -raw -nullMarker "" -name kMDItemVersion "#{path}" 2>/dev/null`.strip
<add> version = Utils.popen_read(
<add> "/usr/bin/mdls", "-raw", "-nullMarker", "", "-name", "kMDItemVersion", path.to_s, &:read
<add> ).strip
<ide> version unless version.empty?
<ide> end
<ide> | 2 |
Javascript | Javascript | add tests for moduledependencyerror | 11991719ecfd2a44144399bf9f97868d8fe57e15 | <ide><path>test/ModuleDependencyError.test.js
<add>var path = require("path");
<add>var should = require("should");
<add>var sinon = require("sinon");
<add>var ModuleDependencyError = require("../lib/ModuleDependencyError");
<add>
<add>describe("ModuleDependencyError", function() {
<add> var env;
<add>
<add> beforeEach(function() {
<add> env = {};
<add> });
<add>
<add> it("is a function", function() {
<add> ModuleDependencyError.should.be.a.Function();
<add> });
<add>
<add> describe("when new error created", function() {
<add> beforeEach(function() {
<add> env.error = new Error("Error Message");
<add> env.moduleDependencyError = new ModuleDependencyError("myModule", env.error, "Location");
<add> });
<add>
<add> it("is an error", function() {
<add> env.moduleDependencyError.should.be.an.Error();
<add> });
<add>
<add> it("has a name property", function() {
<add> env.moduleDependencyError.name.should.be.exactly("ModuleDependencyError");
<add> });
<add>
<add> it("has a message property", function() {
<add> env.moduleDependencyError.message.should.be.exactly("Location Error Message");
<add> });
<add>
<add> it("has a details property", function() {
<add> env.moduleDependencyError.details.should.containEql(path.join("test", "ModuleDependencyError.test.js:"));
<add> });
<add>
<add> it("has an origin property", function() {
<add> env.moduleDependencyError.origin.should.be.exactly("myModule");
<add> });
<add>
<add> it("has an error property", function() {
<add> env.moduleDependencyError.error.should.be.exactly(env.error);
<add> });
<add>
<add> });
<add>}); | 1 |
Javascript | Javascript | add parent to err_unknown_file_extension | 7ab21b2f5702ae0b2a5fe5d30ec356f83a95f698 | <ide><path>lib/internal/errors.js
<ide> E('ERR_UNHANDLED_ERROR',
<ide> E('ERR_UNKNOWN_BUILTIN_MODULE', 'No such built-in module: %s', Error);
<ide> E('ERR_UNKNOWN_CREDENTIAL', '%s identifier does not exist: %s', Error);
<ide> E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError);
<del>E('ERR_UNKNOWN_FILE_EXTENSION', 'Unknown file extension: %s', TypeError);
<add>E('ERR_UNKNOWN_FILE_EXTENSION',
<add> 'Unknown file extension "%s" for %s imported from %s',
<add> TypeError);
<ide> E('ERR_UNKNOWN_MODULE_FORMAT', 'Unknown module format: %s', RangeError);
<ide> E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s', TypeError);
<ide>
<ide><path>lib/internal/modules/esm/default_resolve.js
<ide> function resolve(specifier, parentURL) {
<ide> 'ExperimentalWarning');
<ide> format = legacyExtensionFormatMap[ext];
<ide> } else {
<del> throw new ERR_UNKNOWN_FILE_EXTENSION(fileURLToPath(url));
<add> throw new ERR_UNKNOWN_FILE_EXTENSION(
<add> ext,
<add> fileURLToPath(url),
<add> fileURLToPath(parentURL));
<ide> }
<ide> }
<ide> return { url: `${url}`, format };
<ide><path>test/es-module/test-esm-invalid-extension.js
<ide> const { spawnSync } = require('child_process');
<ide> const fixture = fixtures.path('/es-modules/import-invalid-ext.mjs');
<ide> const child = spawnSync(process.execPath, [fixture]);
<ide> const errMsg = 'TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension';
<add>const importMsg = `imported from ${fixture}`;
<ide>
<ide> assert.strictEqual(child.status, 1);
<ide> assert.strictEqual(child.signal, null);
<ide> assert.strictEqual(child.stdout.toString().trim(), '');
<ide> assert(child.stderr.toString().includes(errMsg));
<add>assert(child.stderr.toString().includes(importMsg)); | 3 |
Java | Java | trim decoded sse data | 5dcde9e7d7876f2100a54893fb158fcf61be159f | <ide><path>spring-web/src/main/java/org/springframework/http/codec/ServerSentEventHttpMessageReader.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> private Mono<?> buildEvent(List<String> lines, ResolvableType valueType, boolean
<ide> for (String line : lines) {
<ide> if (line.startsWith("data:")) {
<ide> data = (data != null ? data : new StringBuilder());
<del> data.append(line.substring(5)).append("\n");
<add> data.append(line.substring(5).trim()).append("\n");
<ide> }
<ide> if (shouldWrap) {
<ide> if (line.startsWith("id:")) {
<del> sseBuilder.id(line.substring(3));
<add> sseBuilder.id(line.substring(3).trim());
<ide> }
<ide> else if (line.startsWith("event:")) {
<del> sseBuilder.event(line.substring(6));
<add> sseBuilder.event(line.substring(6).trim());
<ide> }
<ide> else if (line.startsWith("retry:")) {
<del> sseBuilder.retry(Duration.ofMillis(Long.valueOf(line.substring(6))));
<add> sseBuilder.retry(Duration.ofMillis(Long.valueOf(line.substring(6).trim())));
<ide> }
<ide> else if (line.startsWith(":")) {
<ide> comment = (comment != null ? comment : new StringBuilder());
<del> comment.append(line.substring(1)).append("\n");
<add> comment.append(line.substring(1).trim()).append("\n");
<ide> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | avoid validation warning when inputs change type | 08a0895887c82e379d7717439c7a8d0b015e0696 | <ide><path>src/renderers/dom/client/wrappers/__tests__/ReactDOMInput-test.js
<ide> describe('ReactDOMInput', function() {
<ide> );
<ide> expect(input.value).toBe('hi');
<ide> });
<add>
<add> it('does not raise a validation warning when it switches types', function() {
<add> var Input = React.createClass({
<add> getInitialState() {
<add> return { type: 'number', value: 1000 };
<add> },
<add> render() {
<add> var { value, type } = this.state;
<add> return (<input onChange={() => {}} type={type} value={value} />);
<add> },
<add> });
<add>
<add> var input = ReactTestUtils.renderIntoDocument(<Input />);
<add> var node = ReactDOM.findDOMNode(input);
<add>
<add> // If the value is set before the type, a validation warning will raise and
<add> // the value will not be assigned.
<add> input.setState({ type: 'text', value: 'Test' });
<add> expect(node.value).toEqual('Test');
<add> });
<add>
<ide> });
<ide><path>src/renderers/dom/shared/ReactDOMComponent.js
<ide> ReactDOMComponent.Mixin = {
<ide> nextProps = ReactDOMButton.getHostProps(this, nextProps);
<ide> break;
<ide> case 'input':
<del> ReactDOMInput.updateWrapper(this);
<ide> lastProps = ReactDOMInput.getHostProps(this, lastProps);
<ide> nextProps = ReactDOMInput.getHostProps(this, nextProps);
<ide> break;
<ide> ReactDOMComponent.Mixin = {
<ide> nextProps = ReactDOMSelect.getHostProps(this, nextProps);
<ide> break;
<ide> case 'textarea':
<del> ReactDOMTextarea.updateWrapper(this);
<ide> lastProps = ReactDOMTextarea.getHostProps(this, lastProps);
<ide> nextProps = ReactDOMTextarea.getHostProps(this, nextProps);
<ide> break;
<ide> ReactDOMComponent.Mixin = {
<ide> context
<ide> );
<ide>
<del> if (this._tag === 'select') {
<del> // <select> value update needs to occur after <option> children
<del> // reconciliation
<del> transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
<add> switch (this._tag) {
<add> case 'input':
<add> // Update the wrapper around inputs *after* updating props. This has to
<add> // happen after `_updateDOMProperties`. Otherwise HTML5 input validations
<add> // raise warnings and prevent the new value from being assigned.
<add> ReactDOMInput.updateWrapper(this);
<add> break;
<add> case 'textarea':
<add> ReactDOMTextarea.updateWrapper(this);
<add> break;
<add> case 'select':
<add> // <select> value update needs to occur after <option> children
<add> // reconciliation
<add> transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
<add> break;
<ide> }
<ide>
<ide> if (__DEV__) { | 2 |
Python | Python | raise error on group.apply_async(link=). closes | d47739c0d8156b876a588e6d5705f1af58a1871d | <ide><path>celery/canvas.py
<ide> def skew(self, start=1.0, stop=None, step=1.0):
<ide> return self
<ide>
<ide> def apply_async(self, args=(), kwargs=None, add_to_parent=True,
<del> producer=None, **options):
<add> producer=None, link=None, link_error=None, **options):
<add> if link is not None:
<add> raise TypeError('Cannot add link to group: use a chord')
<add> if link_error is not None:
<add> raise TypeError(
<add> 'Cannot add link to group: do that on individual tasks')
<ide> app = self.app
<ide> if app.conf.task_always_eager:
<ide> return self.apply(args, kwargs, **options)
<ide><path>t/unit/tasks/test_canvas.py
<ide> def test_reverse(self):
<ide> assert isinstance(signature(x), group)
<ide> assert isinstance(signature(dict(x)), group)
<ide>
<add> def test_cannot_link_on_group(self):
<add> x = group([self.add.s(2, 2), self.add.s(4, 4)])
<add> with pytest.raises(TypeError):
<add> x.apply_async(link=self.add.s(2, 2))
<add>
<add> def test_cannot_link_error_on_group(self):
<add> x = group([self.add.s(2, 2), self.add.s(4, 4)])
<add> with pytest.raises(TypeError):
<add> x.apply_async(link_error=self.add.s(2, 2))
<add>
<ide> def test_group_with_group_argument(self):
<ide> g1 = group(self.add.s(2, 2), self.add.s(4, 4), app=self.app)
<ide> g2 = group(g1, app=self.app) | 2 |
Javascript | Javascript | remove unnecessary usage of .hasownproperty() | 4d0329ebeb5d58702be9450e0706e0f2c404848d | <ide><path>lib/fs.js
<ide> function ReadStream(path, options) {
<ide> return new ReadStream(path, options);
<ide>
<ide> // a little bit bigger buffer and water marks by default
<del> options = util._extend({
<del> highWaterMark: 64 * 1024
<del> }, options || {});
<add> options = Object.create(options || {});
<add> if (options.highWaterMark === undefined)
<add> options.highWaterMark = 64 * 1024;
<ide>
<ide> Readable.call(this, options);
<ide>
<ide> this.path = path;
<del> this.fd = options.hasOwnProperty('fd') ? options.fd : null;
<del> this.flags = options.hasOwnProperty('flags') ? options.flags : 'r';
<del> this.mode = options.hasOwnProperty('mode') ? options.mode : 0o666;
<del>
<del> this.start = options.hasOwnProperty('start') ? options.start : undefined;
<del> this.end = options.hasOwnProperty('end') ? options.end : undefined;
<del> this.autoClose = options.hasOwnProperty('autoClose') ?
<del> options.autoClose : true;
<add> this.fd = options.fd === undefined ? null : options.fd;
<add> this.flags = options.flags === undefined ? 'r' : options.flags;
<add> this.mode = options.mode === undefined ? 0o666 : options.mode;
<add>
<add> this.start = options.start === undefined ? undefined : options.start;
<add> this.end = options.end === undefined ? undefined : options.end;
<add> this.autoClose = options.autoClose === undefined ? true : options.autoClose;
<ide> this.pos = undefined;
<ide>
<ide> if (this.start !== undefined) {
<ide> function WriteStream(path, options) {
<ide> Writable.call(this, options);
<ide>
<ide> this.path = path;
<del> this.fd = null;
<del>
<del> this.fd = options.hasOwnProperty('fd') ? options.fd : null;
<del> this.flags = options.hasOwnProperty('flags') ? options.flags : 'w';
<del> this.mode = options.hasOwnProperty('mode') ? options.mode : 0o666;
<add> this.fd = options.fd === undefined ? null : options.fd;
<add> this.flags = options.flags === undefined ? 'w' : options.flags;
<add> this.mode = options.mode === undefined ? 0o666 : options.mode;
<ide>
<del> this.start = options.hasOwnProperty('start') ? options.start : undefined;
<add> this.start = options.start === undefined ? undefined : options.start;
<ide> this.pos = undefined;
<ide> this.bytesWritten = 0;
<ide>
<ide> function SyncWriteStream(fd, options) {
<ide> this.fd = fd;
<ide> this.writable = true;
<ide> this.readable = false;
<del> this.autoClose = options.hasOwnProperty('autoClose') ?
<del> options.autoClose : true;
<add> this.autoClose = options.autoClose === undefined ? true : options.autoClose;
<ide> }
<ide>
<ide> util.inherits(SyncWriteStream, Stream);
<ide><path>test/parallel/test-fs-read-stream-inherit.js
<add>var common = require('../common');
<add>var assert = require('assert');
<add>
<add>// TODO Improved this test. test_ca.pem is too small. A proper test would
<add>// great a large utf8 (with multibyte chars) file and stream it in,
<add>// performing sanity checks throughout.
<add>
<add>var path = require('path');
<add>var fs = require('fs');
<add>var fn = path.join(common.fixturesDir, 'elipses.txt');
<add>var rangeFile = path.join(common.fixturesDir, 'x.txt');
<add>
<add>var callbacks = { open: 0, end: 0, close: 0 };
<add>
<add>var paused = false;
<add>
<add>var file = fs.ReadStream(fn);
<add>
<add>file.on('open', function(fd) {
<add> file.length = 0;
<add> callbacks.open++;
<add> assert.equal('number', typeof fd);
<add> assert.ok(file.readable);
<add>
<add> // GH-535
<add> file.pause();
<add> file.resume();
<add> file.pause();
<add> file.resume();
<add>});
<add>
<add>file.on('data', function(data) {
<add> assert.ok(data instanceof Buffer);
<add> assert.ok(!paused);
<add> file.length += data.length;
<add>
<add> paused = true;
<add> file.pause();
<add>
<add> setTimeout(function() {
<add> paused = false;
<add> file.resume();
<add> }, 10);
<add>});
<add>
<add>
<add>file.on('end', function(chunk) {
<add> callbacks.end++;
<add>});
<add>
<add>
<add>file.on('close', function() {
<add> callbacks.close++;
<add>
<add> //assert.equal(fs.readFileSync(fn), fileContent);
<add>});
<add>
<add>var file3 = fs.createReadStream(fn, Object.create({encoding: 'utf8'}));
<add>file3.length = 0;
<add>file3.on('data', function(data) {
<add> assert.equal('string', typeof(data));
<add> file3.length += data.length;
<add>
<add> for (var i = 0; i < data.length; i++) {
<add> // http://www.fileformat.info/info/unicode/char/2026/index.htm
<add> assert.equal('\u2026', data[i]);
<add> }
<add>});
<add>
<add>file3.on('close', function() {
<add> callbacks.close++;
<add>});
<add>
<add>process.on('exit', function() {
<add> assert.equal(1, callbacks.open);
<add> assert.equal(1, callbacks.end);
<add> assert.equal(2, callbacks.close);
<add> assert.equal(30000, file.length);
<add> assert.equal(10000, file3.length);
<add> console.error('ok');
<add>});
<add>
<add>var file4 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1, start: 1, end: 2}));
<add>assert.equal(file4.start, 1);
<add>assert.equal(file4.end, 2);
<add>var contentRead = '';
<add>file4.on('data', function(data) {
<add> contentRead += data.toString('utf-8');
<add>});
<add>file4.on('end', function(data) {
<add> assert.equal(contentRead, 'yz');
<add>});
<add>
<add>var file5 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1, start: 1}));
<add>assert.equal(file5.start, 1);
<add>file5.data = '';
<add>file5.on('data', function(data) {
<add> file5.data += data.toString('utf-8');
<add>});
<add>file5.on('end', function() {
<add> assert.equal(file5.data, 'yz\n');
<add>});
<add>
<add>// https://github.com/joyent/node/issues/2320
<add>var file6 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1.23, start: 1}));
<add>assert.equal(file6.start, 1);
<add>file6.data = '';
<add>file6.on('data', function(data) {
<add> file6.data += data.toString('utf-8');
<add>});
<add>file6.on('end', function() {
<add> assert.equal(file6.data, 'yz\n');
<add>});
<add>
<add>assert.throws(function() {
<add> fs.createReadStream(rangeFile, Object.create({start: 10, end: 2}));
<add>}, /start must be <= end/);
<add>
<add>var stream = fs.createReadStream(rangeFile, Object.create({ start: 0, end: 0 }));
<add>assert.equal(stream.start, 0);
<add>assert.equal(stream.end, 0);
<add>stream.data = '';
<add>
<add>stream.on('data', function(chunk) {
<add> stream.data += chunk;
<add>});
<add>
<add>stream.on('end', function() {
<add> assert.equal('x', stream.data);
<add>});
<add>
<add>// pause and then resume immediately.
<add>var pauseRes = fs.createReadStream(rangeFile);
<add>pauseRes.pause();
<add>pauseRes.resume();
<add>
<add>var file7 = fs.createReadStream(rangeFile, Object.create({autoClose: false }));
<add>assert.equal(file7.autoClose, false);
<add>file7.on('data', function() {});
<add>file7.on('end', function() {
<add> process.nextTick(function() {
<add> assert(!file7.closed);
<add> assert(!file7.destroyed);
<add> file7Next();
<add> });
<add>});
<add>
<add>function file7Next(){
<add> // This will tell us if the fd is usable again or not.
<add> file7 = fs.createReadStream(null, Object.create({fd: file7.fd, start: 0 }));
<add> file7.data = '';
<add> file7.on('data', function(data) {
<add> file7.data += data;
<add> });
<add> file7.on('end', function(err) {
<add> assert.equal(file7.data, 'xyz\n');
<add> });
<add>}
<add>
<add>// Just to make sure autoClose won't close the stream because of error.
<add>var file8 = fs.createReadStream(null, Object.create({fd: 13337, autoClose: false }));
<add>file8.on('data', function() {});
<add>file8.on('error', common.mustCall(function() {}));
<add>
<add>// Make sure stream is destroyed when file does not exist.
<add>var file9 = fs.createReadStream('/path/to/file/that/does/not/exist');
<add>file9.on('data', function() {});
<add>file9.on('error', common.mustCall(function() {}));
<add>
<add>process.on('exit', function() {
<add> assert(file7.closed);
<add> assert(file7.destroyed);
<add>
<add> assert(!file8.closed);
<add> assert(!file8.destroyed);
<add> assert(file8.fd);
<add>
<add> assert(!file9.closed);
<add> assert(file9.destroyed);
<add>}); | 2 |
Java | Java | protect methods from proguard | 7008ffb663d59c34e94b6abe5b63e0bc9ad89b04 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.java
<ide> import android.os.Bundle;
<ide> import android.os.Parcelable;
<ide> import androidx.annotation.Nullable;
<add>import com.facebook.proguard.annotations.DoNotStrip;
<ide> import java.lang.reflect.Array;
<ide> import java.util.AbstractList;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<add>@DoNotStrip
<ide> public class Arguments {
<ide> private static Object makeNativeObject(Object object) {
<ide> if (object == null) {
<ide> private static void addEntry(WritableNativeMap nativeMap, String key, Object val
<ide> * The best way to think of this is a way to generate a Java representation of a json object, from
<ide> * Java types which have a natural representation in json.
<ide> */
<add> @DoNotStrip
<ide> public static WritableNativeMap makeNativeMap(Map<String, Object> objects) {
<ide> WritableNativeMap nativeMap = new WritableNativeMap();
<ide> if (objects == null) {
<ide> public static WritableNativeMap makeNativeMap(Map<String, Object> objects) {
<ide> }
<ide>
<ide> /** Like the above, but takes a Bundle instead of a Map. */
<add> @DoNotStrip
<ide> public static WritableNativeMap makeNativeMap(Bundle bundle) {
<ide> WritableNativeMap nativeMap = new WritableNativeMap();
<ide> if (bundle == null) { | 1 |
Ruby | Ruby | place x11 ahead of opengl when x11 is active | c90247aa44272b60df247c6c83512e2a6bd23395 | <ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> def determine_isystem_paths
<ide> paths << "#{HOMEBREW_PREFIX}/include"
<ide> paths << "#{effective_sysroot}/usr/include/libxml2" unless deps.include? "libxml2"
<ide> paths << "#{effective_sysroot}/usr/include/apache2" if MacOS::Xcode.without_clt?
<del> paths << "#{effective_sysroot}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Headers"
<ide> paths << MacOS::X11.include.to_s << "#{MacOS::X11.include}/freetype2" if x11?
<add> paths << "#{effective_sysroot}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Headers"
<ide> paths.to_path_s
<ide> end
<ide>
<ide> def determine_include_paths
<ide> def determine_library_paths
<ide> paths = keg_only_deps.map { |dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/lib" }
<ide> paths << "#{HOMEBREW_PREFIX}/lib"
<del> paths << "#{effective_sysroot}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Libraries"
<ide> paths << MacOS::X11.lib.to_s if x11?
<add> paths << "#{effective_sysroot}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Libraries"
<ide> paths.to_path_s
<ide> end
<ide>
<ide> def determine_cmake_include_path
<ide> paths = []
<ide> paths << "#{effective_sysroot}/usr/include/libxml2" unless deps.include? "libxml2"
<ide> paths << "#{effective_sysroot}/usr/include/apache2" if MacOS::Xcode.without_clt?
<del> paths << "#{effective_sysroot}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Headers"
<ide> paths << MacOS::X11.include.to_s << "#{MacOS::X11.include}/freetype2" if x11?
<add> paths << "#{effective_sysroot}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Headers"
<ide> paths.to_path_s
<ide> end
<ide>
<ide> def determine_cmake_library_path
<ide> paths = []
<del> paths << "#{effective_sysroot}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Libraries"
<ide> paths << MacOS::X11.lib.to_s if x11?
<add> paths << "#{effective_sysroot}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Libraries"
<ide> paths.to_path_s
<ide> end
<ide> | 1 |
Javascript | Javascript | fix the order of events in onmousewheel | 6ab03f44db9b492444e55b9481543165dee1da36 | <ide><path>examples/js/controls/OrbitControls.js
<ide> THREE.OrbitControls = function ( object, domElement ) {
<ide> event.preventDefault();
<ide> event.stopPropagation();
<ide>
<add> scope.dispatchEvent( startEvent );
<add>
<ide> handleMouseWheel( event );
<ide>
<del> scope.dispatchEvent( startEvent ); // not sure why these are here...
<ide> scope.dispatchEvent( endEvent );
<ide>
<ide> } | 1 |
Mixed | Python | add pretraining option to init config | ddfc1fc146ec35dab19f835602345de91342eeee | <ide><path>spacy/cli/init_config.py
<ide> def init_config_cli(
<ide> pipeline: Optional[str] = Opt("tagger,parser,ner", "--pipeline", "-p", help="Comma-separated names of trainable pipeline components to include (without 'tok2vec' or 'transformer')"),
<ide> optimize: Optimizations = Opt(Optimizations.efficiency.value, "--optimize", "-o", help="Whether to optimize for efficiency (faster inference, smaller model, lower memory consumption) or higher accuracy (potentially larger and slower model). This will impact the choice of architecture, pretrained weights and related hyperparameters."),
<ide> cpu: bool = Opt(False, "--cpu", "-C", help="Whether the model needs to run on CPU. This will impact the choice of architecture, pretrained weights and related hyperparameters."),
<add> pretraining: bool = Opt(False, "--pretraining", "-pt", help="Include config for pretraining (with 'spacy pretrain')"),
<ide> # fmt: on
<ide> ):
<ide> """
<ide> def init_config_cli(
<ide> if isinstance(optimize, Optimizations): # instance of enum from the CLI
<ide> optimize = optimize.value
<ide> pipeline = string_to_list(pipeline)
<del> init_config(output_file, lang=lang, pipeline=pipeline, optimize=optimize, cpu=cpu)
<add> init_config(output_file, lang=lang, pipeline=pipeline, optimize=optimize, cpu=cpu, pretraining=pretraining)
<ide>
<ide>
<ide> @init_cli.command("fill-config")
<ide> def fill_config(
<ide>
<ide>
<ide> def init_config(
<del> output_file: Path, *, lang: str, pipeline: List[str], optimize: str, cpu: bool
<add> output_file: Path, *, lang: str, pipeline: List[str], optimize: str, cpu: bool, pretraining: bool = False,
<ide> ) -> None:
<ide> is_stdout = str(output_file) == "-"
<ide> msg = Printer(no_print=is_stdout)
<ide> def init_config(
<ide> with show_validation_error(hint_fill=False):
<ide> config = util.load_config_from_str(base_template)
<ide> nlp, _ = util.load_model_from_config(config, auto_fill=True)
<add> config = nlp.config
<add> if pretraining:
<add> validate_config_for_pretrain(config, msg)
<add> pretrain_config = util.load_config(DEFAULT_CONFIG_PRETRAIN_PATH)
<add> config = pretrain_config.merge(config)
<ide> msg.good("Auto-filled config with all values")
<del> save_config(nlp.config, output_file, is_stdout=is_stdout)
<add> save_config(config, output_file, is_stdout=is_stdout)
<ide>
<ide>
<ide> def save_config(
<ide><path>website/docs/api/cli.md
<ide> customize those settings in your config file later.
<ide> $ python -m spacy init config [output_file] [--lang] [--pipeline] [--optimize] [--cpu]
<ide> ```
<ide>
<del>| Name | Description |
<del>| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<del>| `output_file` | Path to output `.cfg` file or `-` to write the config to stdout (so you can pipe it forward to a file). Note that if you're writing to stdout, no additional logging info is printed. ~~Path (positional)~~ |
<del>| `--lang`, `-l` | Optional code of the [language](/usage/models#languages) to use. Defaults to `"en"`. ~~str (option)~~ |
<del>| `--pipeline`, `-p` | Comma-separated list of trainable [pipeline components](/usage/processing-pipelines#built-in) to include. Defaults to `"tagger,parser,ner"`. ~~str (option)~~ |
<del>| `--optimize`, `-o` | `"efficiency"` or `"accuracy"`. Whether to optimize for efficiency (faster inference, smaller model, lower memory consumption) or higher accuracy (potentially larger and slower model). This will impact the choice of architecture, pretrained weights and related hyperparameters. Defaults to `"efficiency"`. ~~str (option)~~ |
<del>| `--cpu`, `-C` | Whether the model needs to run on CPU. This will impact the choice of architecture, pretrained weights and related hyperparameters. ~~bool (flag)~~ |
<del>| `--help`, `-h` | Show help message and available arguments. ~~bool (flag)~~ |
<del>| **CREATES** | The config file for training. |
<add>| Name | Description |
<add>| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `output_file` | Path to output `.cfg` file or `-` to write the config to stdout (so you can pipe it forward to a file). Note that if you're writing to stdout, no additional logging info is printed. ~~Path (positional)~~ |
<add>| `--lang`, `-l` | Optional code of the [language](/usage/models#languages) to use. Defaults to `"en"`. ~~str (option)~~ |
<add>| `--pipeline`, `-p` | Comma-separated list of trainable [pipeline components](/usage/processing-pipelines#built-in) to include. Defaults to `"tagger,parser,ner"`. ~~str (option)~~ |
<add>| `--pretraining`, `-p` | Include config for pretraining (with 'spacy pretrain'). Default False. ~~bool~~ |
<add>| `--optimize`, `-o` | `"efficiency"` or `"accuracy"`. Whether to optimize for efficiency (faster inference, smaller model, lower memory consumption) or higher accuracy (potentially larger and slower model). This will impact the choice of architecture, pretrained weights and related hyperparameters. Defaults to `"efficiency"`. ~~str (option)~~ |
<add>| `--cpu`, `-C` | Whether the model needs to run on CPU. This will impact the choice of architecture, pretrained weights and related hyperparameters. ~~bool (flag)~~ |
<add>| `--help`, `-h` | Show help message and available arguments. ~~bool (flag)~~ |
<add>| **CREATES** | The config file for training. |
<ide>
<ide> ### init fill-config {#init-fill-config new="3"}
<ide>
<ide> validation error with more details.
<ide> $ python -m spacy init fill-config [base_path] [output_file] [--diff]
<ide> ```
<ide>
<del>| Name | Description |
<del>| -------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
<del>| `base_path` | Path to base config to fill, e.g. generated by the [quickstart widget](/usage/training#quickstart). ~~Path (positional)~~ |
<del>| `output_file` | Path to output `.cfg` file. If not set, the config is written to stdout so you can pipe it forward to a file. ~~Path (positional)~~ |
<del>| `--diff`, `-D` | Print a visual diff highlighting the changes. ~~bool (flag)~~ |
<del>| `--help`, `-h` | Show help message and available arguments. ~~bool (flag)~~ |
<del>| **CREATES** | Complete and auto-filled config file for training. |
<add>| Name | Description |
<add>| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
<add>| `base_path` | Path to base config to fill, e.g. generated by the [quickstart widget](/usage/training#quickstart). ~~Path (positional)~~ |
<add>| `output_file` | Path to output `.cfg` file. If not set, the config is written to stdout so you can pipe it forward to a file. ~~Path (positional)~~ |
<add>| `--pretraining`, `-p` | Include config for pretraining (with 'spacy pretrain'). Default False. ~~bool~~ |
<add>| `--diff`, `-D` | Print a visual diff highlighting the changes. ~~bool (flag)~~ |
<add>| `--help`, `-h` | Show help message and available arguments. ~~bool (flag)~~ |
<add>| **CREATES** | Complete and auto-filled config file for training. |
<ide>
<ide> ### init vocab {#init-vocab new="3" tag="command"}
<ide> | 2 |
Javascript | Javascript | clarify assertion failure | 92d326994da55f19db0e011aabcdbeb672c1fa4a | <ide><path>test/pummel/test-tls-connect-memleak.js
<ide> const fixtures = require('../common/fixtures');
<ide> assert.strictEqual(
<ide> typeof global.gc,
<ide> 'function',
<del> 'Run this test with --expose-gc'
<add> `Type of global.gc is not a function. Type: ${typeof global.gc}.` +
<add> ' Run this test with --expose-gc'
<ide> );
<ide>
<ide> tls.createServer({ | 1 |
Python | Python | fix a docstring | 091685954504fb46cd77f6f40bd5a780bddbb06f | <ide><path>keras/preprocessing/text.py
<ide> def one_hot(text, n,
<ide> """One-hot encodes a text into a list of word indexes of size n.
<ide>
<ide> This is a wrapper to the `hashing_trick` function using `hash` as the
<del> hashing function, unicity of word to index mapping non-guaranteed.
<add> hashing function; unicity of word to index mapping non-guaranteed.
<add>
<add> # Arguments
<add> text: Input text (string).
<add> n: Dimension of the hashing space.
<add> filters: Sequence of characters to filter out.
<add> lower: Whether to convert the input to lowercase.
<add> split: Sentence split marker (string).
<add>
<add> # Returns
<add> A list of integer word indices (unicity non-guaranteed).
<ide> """
<ide> return hashing_trick(text, n,
<ide> hash_function=hash, | 1 |
Javascript | Javascript | add example for how to use `style` properly | 1c5443175cf55addb63ee04a00a0939e9bbb0db6 | <ide><path>src/browser/ui/ReactDOMComponent.js
<ide> function assertValidProps(props) {
<ide> invariant(
<ide> props.style == null || typeof props.style === 'object',
<ide> 'The `style` prop expects a mapping from style properties to values, ' +
<del> 'not a string.'
<add> 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' +
<add> 'using JSX.'
<ide> );
<ide> }
<ide>
<ide><path>src/browser/ui/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', function() {
<ide> mountComponent({ style: 'display: none' });
<ide> }).toThrow(
<ide> 'Invariant Violation: The `style` prop expects a mapping from style ' +
<del> 'properties to values, not a string.'
<add> 'properties to values, not a string. For example, ' +
<add> 'style={{marginRight: spacing + \'em\'}} when using JSX.'
<ide> );
<ide> });
<ide> });
<ide> describe('ReactDOMComponent', function() {
<ide> React.render(<div style={1}></div>, container);
<ide> }).toThrow(
<ide> 'Invariant Violation: The `style` prop expects a mapping from style ' +
<del> 'properties to values, not a string.'
<add> 'properties to values, not a string. For example, ' +
<add> 'style={{marginRight: spacing + \'em\'}} when using JSX.'
<ide> );
<ide> });
<ide> }); | 2 |
Go | Go | update ovmanager to support maximum vni | d3b8412ac6014962852b12128e2067626bf69482 | <ide><path>libnetwork/drivers/overlay/ovmanager/ovmanager.go
<ide> import (
<ide> const (
<ide> networkType = "overlay"
<ide> vxlanIDStart = 256
<del> vxlanIDEnd = 1000
<add> vxlanIDEnd = (1 << 24) - 1
<ide> )
<ide>
<ide> type networkTable map[string]*network | 1 |
Go | Go | remove the redundant 'if' statements | 98c036943794383094e00cfb0c16d460593375bf | <ide><path>daemon/cluster/secrets.go
<ide> func (c *Cluster) RemoveSecret(id string) error {
<ide> SecretID: id,
<ide> }
<ide>
<del> if _, err := state.controlClient.RemoveSecret(ctx, req); err != nil {
<del> return err
<del> }
<del> return nil
<add> _, err := state.controlClient.RemoveSecret(ctx, req)
<add> return err
<ide> }
<ide>
<ide> // UpdateSecret updates a secret in a managed swarm cluster.
<ide> func (c *Cluster) UpdateSecret(id string, version uint64, spec types.SecretSpec)
<ide>
<ide> secretSpec := convert.SecretSpecToGRPC(spec)
<ide>
<del> if _, err := state.controlClient.UpdateSecret(ctx,
<add> _, err := state.controlClient.UpdateSecret(ctx,
<ide> &swarmapi.UpdateSecretRequest{
<ide> SecretID: id,
<ide> SecretVersion: &swarmapi.Version{
<ide> Index: version,
<ide> },
<ide> Spec: &secretSpec,
<del> }); err != nil {
<del> return err
<del> }
<del>
<del> return nil
<add> })
<add> return err
<ide> } | 1 |
Java | Java | update javadoc for testcontextbootstrapper | c84c1cfd1b5846e1ce13b8209d88df36a96085aa | <ide><path>spring-test/src/main/java/org/springframework/test/context/TestContextBootstrapper.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2016 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> *
<ide> * <p>A custom bootstrapping strategy can be configured for a test class (or
<ide> * test class hierarchy) via {@link BootstrapWith @BootstrapWith}, either
<del> * directly or as a meta-annotation. See
<del> * {@link org.springframework.test.context.web.WebAppConfiguration @WebAppConfiguration}
<del> * for an example.
<add> * directly or as a meta-annotation.
<ide> *
<del> * <p>If a bootstrapper is not explicitly configured via {@code @BootstrapWith}, the
<del> * {@link org.springframework.test.context.support.DefaultTestContextBootstrapper DefaultTestContextBootstrapper}
<del> * will be used.
<add> * <p>If a bootstrapper is not explicitly configured via {@code @BootstrapWith},
<add> * either the {@link org.springframework.test.context.support.DefaultTestContextBootstrapper
<add> * DefaultTestContextBootstrapper} or the
<add> * {@link org.springframework.test.context.web.WebTestContextBootstrapper
<add> * WebTestContextBootstrapper} will be used, depending on the presence of
<add> * {@link org.springframework.test.context.web.WebAppConfiguration @WebAppConfiguration}.
<ide> *
<ide> * <h3>Implementation Notes</h3>
<ide> * | 1 |
PHP | PHP | expand tests and remove unreachable code | 4a6f5982259f64d716fbb0a8a9b0b7bb24c87572 | <ide><path>src/View/Form/EntityContext.php
<ide> public function val($field) {
<ide> }
<ide> $parts = explode('.', $field);
<ide> list($entity, $prop) = $this->_getEntity($parts);
<del> if (!$entity) {
<del> return null;
<del> }
<ide> return $entity->get(array_pop($parts));
<ide> }
<ide>
<ide> protected function _getEntity($path) {
<ide> }
<ide> $entity = $next;
<ide> }
<del> return [false, false];
<add> throw \RuntimeException(sprintf(
<add> 'Unable to fetch property "%s"',
<add> implode(".", $path)
<add> ));
<ide> }
<ide>
<ide> /**
<ide> public function isRequired($field) {
<ide> }
<ide> $parts = explode('.', $field);
<ide> list($entity, $prop) = $this->_getEntity($parts);
<del> if (!$entity) {
<del> return false;
<del> }
<ide>
<ide> $validator = $this->_getValidator($prop);
<del> if (!$validator) {
<del> return false;
<del> }
<del>
<ide> $field = array_pop($parts);
<ide> if (!$validator->hasField($field)) {
<ide> return false;
<ide> public function isRequired($field) {
<ide> * conventions.
<ide> *
<ide> * @param string $entity The entity name to get a validator for.
<del> * @return Validator|false
<add> * @return Validator
<ide> */
<ide> protected function _getValidator($entity) {
<ide> $table = $this->_getTable($entity);
<ide> protected function _getTable($prop) {
<ide> public function type($field) {
<ide> $parts = explode('.', $field);
<ide> list($entity, $prop) = $this->_getEntity($parts);
<del> if (!$entity) {
<del> return null;
<del> }
<ide> $table = $this->_getTable($prop);
<ide> $column = array_pop($parts);
<ide> return $table->schema()->columnType($column);
<ide> public function type($field) {
<ide> public function attributes($field) {
<ide> $parts = explode('.', $field);
<ide> list($entity, $prop) = $this->_getEntity($parts);
<del> if (!$entity) {
<del> return [];
<del> }
<ide> $table = $this->_getTable($prop);
<ide> $column = $table->schema()->column(array_pop($parts));
<ide> $whitelist = ['length' => null, 'precision' => null];
<ide> public function hasError($field) {
<ide> public function error($field) {
<ide> $parts = explode('.', $field);
<ide> list($entity, $prop) = $this->_getEntity($parts);
<del> if (!$entity) {
<del> return [];
<del> }
<ide> return $entity->errors(array_pop($parts));
<ide> }
<ide>
<ide><path>tests/TestCase/View/Form/EntityContextTest.php
<ide> public function setUp() {
<ide> $this->request = new Request();
<ide> }
<ide>
<add>/**
<add> * Test an invalid table scope throws an error.
<add> *
<add> * @expectedException \RuntimeException
<add> * @expectedExceptionMessage Unable to find table class for current entity
<add> */
<add> public function testInvalidTable() {
<add> $row = new \StdClass();
<add> $context = new EntityContext($this->request, [
<add> 'entity' => $row,
<add> ]);
<add> }
<add>
<ide> /**
<ide> * Test operations that lack a table argument.
<ide> *
<ide> public function testIsRequiredStringValidator() {
<ide>
<ide> $this->assertFalse($context->isRequired('Herp.derp.derp'));
<ide> $this->assertFalse($context->isRequired('nope'));
<add> $this->assertFalse($context->isRequired(''));
<ide> }
<ide>
<ide> /**
<ide> public function testIsRequiredAssociatedHasMany() {
<ide>
<ide> $this->assertTrue($context->isRequired('comments.0.user_id'));
<ide> $this->assertFalse($context->isRequired('comments.0.other'));
<add> $this->assertFalse($context->isRequired('user.0.other'));
<add> $this->assertFalse($context->isRequired(''));
<ide> }
<ide>
<ide> /** | 2 |
Ruby | Ruby | use git to do the diff filtering | 6cad17caef241b93fc0218e39e4f889d158c7e9c | <ide><path>Library/Contributions/cmd/brew-test-bot.rb
<ide> def single_commit? start_revision, end_revision
<ide> return unless diff_start_sha1 != diff_end_sha1
<ide> return if @url and not steps.last.passed?
<ide>
<del> diff_stat = git "diff-tree", "-r", "--name-status",
<add> git(
<add> "diff-tree", "-r", "--name-only", "--diff-filter=AM",
<ide> diff_start_sha1, diff_end_sha1, "--", "Library/Formula"
<del>
<del> diff_stat.each_line do |line|
<del> status, filename = line.split
<del> # Don't try and do anything to removed files.
<del> if status == "A" || status == "M"
<del> @formulae << File.basename(filename, ".rb")
<del> end
<add> ).each_line do |line|
<add> @formulae << File.basename(line.chomp, ".rb")
<ide> end
<ide> end
<ide> | 1 |
PHP | PHP | clarify delay time | ed8d75bfa193415986495016e89aac5f9ef0d96b | <ide><path>src/Illuminate/Bus/Queueable.php
<ide> public function allOnQueue($queue)
<ide> }
<ide>
<ide> /**
<del> * Set the desired delay for the job.
<add> * Set the desired delay in seconds for the job.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int|null $delay
<ide> * @return $this
<ide><path>src/Illuminate/Contracts/Mail/Mailable.php
<ide> public function send($mailer);
<ide> public function queue(Queue $queue);
<ide>
<ide> /**
<del> * Deliver the queued message after the given delay.
<add> * Deliver the queued message after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param \Illuminate\Contracts\Queue\Factory $queue
<ide><path>src/Illuminate/Contracts/Queue/Job.php
<ide> public function payload();
<ide> public function fire();
<ide>
<ide> /**
<del> * Release the job back into the queue.
<del> *
<del> * Accepts a delay specified in seconds.
<add> * Release the job back into the queue after (n) seconds.
<ide> *
<ide> * @param int $delay
<ide> * @return void
<ide><path>src/Illuminate/Contracts/Queue/Queue.php
<ide> public function pushOn($queue, $job, $data = '');
<ide> public function pushRaw($payload, $queue = null, array $options = []);
<ide>
<ide> /**
<del> * Push a new job onto the queue after a delay.
<add> * Push a new job onto the queue after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param string|object $job
<ide> public function pushRaw($payload, $queue = null, array $options = []);
<ide> public function later($delay, $job, $data = '', $queue = null);
<ide>
<ide> /**
<del> * Push a new job onto the queue after a delay.
<add> * Push a new job onto a specific queue after (n) seconds.
<ide> *
<ide> * @param string $queue
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide><path>src/Illuminate/Events/QueuedClosure.php
<ide> public function onQueue($queue)
<ide> }
<ide>
<ide> /**
<del> * Set the desired delay for the job.
<add> * Set the desired delay in seconds for the job.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int|null $delay
<ide> * @return $this
<ide><path>src/Illuminate/Foundation/Bus/PendingChain.php
<ide> public function onQueue($queue)
<ide> }
<ide>
<ide> /**
<del> * Set the desired delay for the chain.
<add> * Set the desired delay in seconds for the chain.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int|null $delay
<ide> * @return $this
<ide><path>src/Illuminate/Foundation/Bus/PendingDispatch.php
<ide> public function allOnQueue($queue)
<ide> }
<ide>
<ide> /**
<del> * Set the desired delay for the job.
<add> * Set the desired delay in seconds for the job.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int|null $delay
<ide> * @return $this
<ide><path>src/Illuminate/Mail/Mailable.php
<ide> public function queue(Queue $queue)
<ide> }
<ide>
<ide> /**
<del> * Deliver the queued message after the given delay.
<add> * Deliver the queued message after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param \Illuminate\Contracts\Queue\Factory $queue
<ide><path>src/Illuminate/Mail/PendingMail.php
<ide> public function queue(MailableContract $mailable)
<ide> }
<ide>
<ide> /**
<del> * Deliver the queued message after the given delay.
<add> * Deliver the queued message after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param \Illuminate\Contracts\Mail\Mailable $mailable
<ide><path>src/Illuminate/Queue/BeanstalkdQueue.php
<ide> public function pushRaw($payload, $queue = null, array $options = [])
<ide> }
<ide>
<ide> /**
<del> * Push a new job onto the queue after a delay.
<add> * Push a new job onto the queue after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param string $job
<ide><path>src/Illuminate/Queue/Capsule/Manager.php
<ide> public static function bulk($jobs, $data = '', $queue = null, $connection = null
<ide> }
<ide>
<ide> /**
<del> * Push a new job onto the queue after a delay.
<add> * Push a new job onto the queue after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param string $job
<ide><path>src/Illuminate/Queue/DatabaseQueue.php
<ide> public function pushRaw($payload, $queue = null, array $options = [])
<ide> }
<ide>
<ide> /**
<del> * Push a new job onto the queue after a delay.
<add> * Push a new job onto the queue after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param string $job
<ide> function ($job) use ($queue, $data, $availableAt) {
<ide> }
<ide>
<ide> /**
<del> * Release a reserved job back onto the queue.
<add> * Release a reserved job back onto the queue after (n) seconds.
<ide> *
<ide> * @param string $queue
<ide> * @param \Illuminate\Queue\Jobs\DatabaseJobRecord $job
<ide> public function release($queue, $job, $delay)
<ide> }
<ide>
<ide> /**
<del> * Push a raw payload to the database with a given delay.
<add> * Push a raw payload to the database with a given delay of (n) seconds.
<ide> *
<ide> * @param string|null $queue
<ide> * @param string $payload
<ide><path>src/Illuminate/Queue/InteractsWithQueue.php
<ide> public function fail($exception = null)
<ide> }
<ide>
<ide> /**
<del> * Release the job back into the queue.
<add> * Release the job back into the queue after (n) seconds.
<ide> *
<ide> * @param int $delay
<ide> * @return void
<ide><path>src/Illuminate/Queue/Jobs/BeanstalkdJob.php
<ide> public function __construct(Container $container, Pheanstalk $pheanstalk, Pheans
<ide> }
<ide>
<ide> /**
<del> * Release the job back into the queue.
<add> * Release the job back into the queue after (n) seconds.
<ide> *
<ide> * @param int $delay
<ide> * @return void
<ide><path>src/Illuminate/Queue/Jobs/DatabaseJob.php
<ide> public function __construct(Container $container, DatabaseQueue $database, $job,
<ide> }
<ide>
<ide> /**
<del> * Release the job back into the queue.
<add> * Release the job back into the queue after (n) seconds.
<ide> *
<ide> * @param int $delay
<ide> * @return void
<ide><path>src/Illuminate/Queue/Jobs/Job.php
<ide> public function isDeleted()
<ide> }
<ide>
<ide> /**
<del> * Release the job back into the queue.
<add> * Release the job back into the queue after (n) seconds.
<ide> *
<ide> * @param int $delay
<ide> * @return void
<ide><path>src/Illuminate/Queue/Jobs/RedisJob.php
<ide> public function delete()
<ide> }
<ide>
<ide> /**
<del> * Release the job back into the queue.
<add> * Release the job back into the queue after (n) seconds.
<ide> *
<ide> * @param int $delay
<ide> * @return void
<ide><path>src/Illuminate/Queue/Jobs/SqsJob.php
<ide> public function __construct(Container $container, SqsClient $sqs, array $job, $c
<ide> }
<ide>
<ide> /**
<del> * Release the job back into the queue.
<add> * Release the job back into the queue after (n) seconds.
<ide> *
<ide> * @param int $delay
<ide> * @return void
<ide><path>src/Illuminate/Queue/Jobs/SyncJob.php
<ide> public function __construct(Container $container, $payload, $connectionName, $qu
<ide> }
<ide>
<ide> /**
<del> * Release the job back into the queue.
<add> * Release the job back into the queue after (n) seconds.
<ide> *
<ide> * @param int $delay
<ide> * @return void
<ide><path>src/Illuminate/Queue/NullQueue.php
<ide> public function pushRaw($payload, $queue = null, array $options = [])
<ide> }
<ide>
<ide> /**
<del> * Push a new job onto the queue after a delay.
<add> * Push a new job onto the queue after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param string $job
<ide><path>src/Illuminate/Queue/Queue.php
<ide> public function pushOn($queue, $job, $data = '')
<ide> }
<ide>
<ide> /**
<del> * Push a new job onto the queue after a delay.
<add> * Push a new job onto a specific queue after (n) seconds.
<ide> *
<ide> * @param string $queue
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide><path>src/Illuminate/Queue/RedisQueue.php
<ide> function ($payload, $queue, $delay) {
<ide> }
<ide>
<ide> /**
<del> * Push a raw job onto the queue after a delay.
<add> * Push a raw job onto the queue after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param string $payload
<ide><path>src/Illuminate/Queue/SqsQueue.php
<ide> public function pushRaw($payload, $queue = null, array $options = [])
<ide> }
<ide>
<ide> /**
<del> * Push a new job onto the queue after a delay.
<add> * Push a new job onto the queue after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param string $job
<ide><path>src/Illuminate/Queue/SyncQueue.php
<ide> public function pushRaw($payload, $queue = null, array $options = [])
<ide> }
<ide>
<ide> /**
<del> * Push a new job onto the queue after a delay.
<add> * Push a new job onto the queue after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param string $job
<ide><path>src/Illuminate/Support/Testing/Fakes/QueueFake.php
<ide> public function pushRaw($payload, $queue = null, array $options = [])
<ide> }
<ide>
<ide> /**
<del> * Push a new job onto the queue after a delay.
<add> * Push a new job onto the queue after (n) seconds.
<ide> *
<ide> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param string $job
<ide> public function pushOn($queue, $job, $data = '')
<ide> }
<ide>
<ide> /**
<del> * Push a new job onto the queue after a delay.
<add> * Push a new job onto a specific queue after (n) seconds.
<ide> *
<ide> * @param string $queue
<ide> * @param \DateTimeInterface|\DateInterval|int $delay | 25 |
Ruby | Ruby | add coreformularepository singleton class | 9f7a383017d3ed3cb4aedfbcdb58fd03eaa4599c | <ide><path>Library/Homebrew/tap.rb
<ide> def self.clear_cache
<ide> CACHE.clear
<ide> end
<ide>
<del> def self.fetch(user, repo)
<add> def self.fetch(*args)
<add> case args.length
<add> when 1
<add> user, repo = args.first.split("/", 2)
<add> when 2
<add> user = args[0]
<add> repo = args[1]
<add> end
<add>
<add> raise "Invalid tap name" unless user && repo
<add>
<ide> # we special case homebrew so users don't have to shift in a terminal
<ide> user = "Homebrew" if user == "homebrew"
<ide> repo = repo.strip_prefix "homebrew-"
<add>
<add> if user == "Homebrew" && repo == "homebrew"
<add> return CoreFormulaRepository.instance
<add> end
<add>
<ide> cache_key = "#{user}/#{repo}".downcase
<ide> CACHE.fetch(cache_key) { |key| CACHE[key] = Tap.new(user, repo) }
<ide> end
<ide> def alias_file_to_name(file)
<ide> "#{name}/#{file.basename}"
<ide> end
<ide> end
<add>
<add># A specialized {Tap} class to mimic the core formula file system, which shares many
<add># similarities with normal {Tap}.
<add># TODO Separate core formulae with core codes. See discussion below for future plan:
<add># https://github.com/Homebrew/homebrew/pull/46735#discussion_r46820565
<add>class CoreFormulaRepository < Tap
<add> # @private
<add> def initialize
<add> @user = "Homebrew"
<add> @repo = "homebrew"
<add> @name = "Homebrew/homebrew"
<add> @path = HOMEBREW_REPOSITORY
<add> end
<add>
<add> def self.instance
<add> @instance ||= CoreFormulaRepository.new
<add> end
<add>
<add> # @private
<add> def uninstall
<add> raise "Tap#uninstall is not available for CoreFormulaRepository"
<add> end
<add>
<add> # @private
<add> def pin
<add> raise "Tap#pin is not available for CoreFormulaRepository"
<add> end
<add>
<add> # @private
<add> def unpin
<add> raise "Tap#unpin is not available for CoreFormulaRepository"
<add> end
<add>
<add> # @private
<add> def pinned?
<add> false
<add> end
<add>
<add> # @private
<add> def command_files
<add> []
<add> end
<add>
<add> # @private
<add> def custom_remote?
<add> remote != "https://github.com/#{user}/#{repo}.git"
<add> end
<add>
<add> # @private
<add> def formula_dir
<add> HOMEBREW_LIBRARY/"Formula"
<add> end
<add>
<add> # @private
<add> def alias_dir
<add> HOMEBREW_LIBRARY/"Aliases"
<add> end
<add>
<add> # @private
<add> def formula_renames
<add> require "formula_renames"
<add> FORMULA_RENAMES
<add> end
<add>
<add> private
<add>
<add> def formula_file_to_name(file)
<add> file.basename(".rb").to_s
<add> end
<add>
<add> def alias_file_to_name(file)
<add> file.basename.to_s
<add> end
<add>end | 1 |
Javascript | Javascript | name anonymous functions for debugging purposes | 0d5efbe9fec1a81b1b08ecf1308b4e20299d1c66 | <ide><path>fonts.js
<ide> var serifFonts = {
<ide> var FontLoader = {
<ide> listeningForFontLoad: false,
<ide>
<del> bind: function(fonts, callback) {
<add> bind: function fontLoaderBind(fonts, callback) {
<ide> function checkFontsLoaded() {
<ide> for (var i = 0; i < objs.length; i++) {
<ide> var fontObj = objs[i];
<ide> var FontLoader = {
<ide> // loaded in a subdocument. It's expected that the load of |rules|
<ide> // has already started in this (outer) document, so that they should
<ide> // be ordered before the load in the subdocument.
<del> prepareFontLoadEvent: function(rules, names, objs) {
<add> prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, names, objs) {
<ide> /** Hack begin */
<ide> // There's no event when a font has finished downloading so the
<ide> // following code is a dirty hack to 'guess' when a font is
<ide> var FontLoader = {
<ide> if (!this.listeningForFontLoad) {
<ide> window.addEventListener(
<ide> 'message',
<del> function(e) {
<add> function fontLoaderMessage(e) {
<ide> var fontNames = JSON.parse(e.data);
<ide> for (var i = 0; i < objs.length; ++i) {
<ide> var font = objs[i];
<ide> var FontLoader = {
<ide> fontNamesArray += '"' + names[i] + '", ';
<ide> }
<ide> src += ' var fontNames=[' + fontNamesArray + '];\n';
<del> src += ' window.onload = function () {\n';
<add> src += ' window.onload = function fontLoaderOnload() {\n';
<ide> src += ' parent.postMessage(JSON.stringify(fontNames), "*");\n';
<ide> src += ' }';
<ide> src += '</script></head><body>';
<ide> var Font = (function Font() {
<ide> var length = glyphs.length;
<ide> for (var n = 0; n < length; ++n)
<ide> codes.push({ unicode: glyphs[n].unicode, code: n });
<del> codes.sort(function(a, b) {
<add> codes.sort(function fontGetRangesSort(a, b) {
<ide> return a.unicode - b.unicode;
<ide> });
<ide>
<ide> var Font = (function Font() {
<ide> }
<ide>
<ide> // Check that table are sorted by platformID then encodingID,
<del> records.sort(function(a, b) {
<add> records.sort(function fontReplaceCMapTableSort(a, b) {
<ide> return ((a.platformID << 16) + a.encodingID) -
<ide> ((b.platformID << 16) + b.encodingID);
<ide> });
<ide> var Font = (function Font() {
<ide> var itemSize, itemDecode, itemEncode;
<ide> if (isGlyphLocationsLong) {
<ide> itemSize = 4;
<del> itemDecode = function(data, offset) {
<add> itemDecode = function fontItemDecodeLong(data, offset) {
<ide> return (data[offset] << 24) | (data[offset + 1] << 16) |
<ide> (data[offset + 2] << 8) | data[offset + 3];
<ide> };
<del> itemEncode = function(data, offset, value) {
<add> itemEncode = function fontItemEncodeLong(data, offset, value) {
<ide> data[offset] = (value >>> 24) & 0xFF;
<ide> data[offset + 1] = (value >> 16) & 0xFF;
<ide> data[offset + 2] = (value >> 8) & 0xFF;
<ide> data[offset + 3] = value & 0xFF;
<ide> };
<ide> } else {
<ide> itemSize = 2;
<del> itemDecode = function(data, offset) {
<add> itemDecode = function fontItemDecode(data, offset) {
<ide> return (data[offset] << 9) | (data[offset + 1] << 1);
<ide> };
<del> itemEncode = function(data, offset, value) {
<add> itemEncode = function fontItemEncode(data, offset, value) {
<ide> data[offset] = (value >> 9) & 0xFF;
<ide> data[offset + 1] = (value >> 1) & 0xFF;
<ide> };
<ide> var Font = (function Font() {
<ide> 'cmap': createCMapTable(charstrings.slice(), font.glyphIds),
<ide>
<ide> // Font header
<del> 'head': (function() {
<add> 'head': (function fontFieldsHead() {
<ide> return stringToArray(
<ide> '\x00\x01\x00\x00' + // Version number
<ide> '\x00\x00\x10\x00' + // fontRevision
<ide> var Font = (function Font() {
<ide> })(),
<ide>
<ide> // Horizontal header
<del> 'hhea': (function() {
<add> 'hhea': (function fontFieldsHhea() {
<ide> return stringToArray(
<ide> '\x00\x01\x00\x00' + // Version number
<ide> string16(properties.ascent) + // Typographic Ascent
<ide> var Font = (function Font() {
<ide> })(),
<ide>
<ide> // Horizontal metrics
<del> 'hmtx': (function() {
<add> 'hmtx': (function fontFieldsHmtx() {
<ide> var hmtx = '\x00\x00\x00\x00'; // Fake .notdef
<ide> for (var i = 0; i < charstrings.length; i++) {
<ide> hmtx += string16(charstrings[i].width) + string16(0);
<ide> var Font = (function Font() {
<ide> })(),
<ide>
<ide> // Maximum profile
<del> 'maxp': (function() {
<add> 'maxp': (function fontFieldsMaxp() {
<ide> return stringToArray(
<ide> '\x00\x00\x50\x00' + // Version number
<ide> string16(charstrings.length + 1)); // Num of glyphs
<ide> var Font = (function Font() {
<ide> * program. Some of its logic depends on the Type2 charstrings
<ide> * structure.
<ide> */
<del>var Type1Parser = function() {
<add>var Type1Parser = function type1Parser() {
<ide> /*
<ide> * Decrypt a Sequence of Ciphertext Bytes to Produce the Original Sequence
<ide> * of Plaintext Bytes. The function took a key as a parameter which can be
<ide> var CFFStrings = [
<ide>
<ide> var type1Parser = new Type1Parser();
<ide>
<del>var CFF = function(name, file, properties) {
<add>var CFF = function cFF(name, file, properties) {
<ide> // Get the data block containing glyphs and subrs informations
<ide> var headerBlock = file.getBytes(properties.length1);
<ide> type1Parser.extractFontHeader(headerBlock, properties);
<ide> CFF.prototype = {
<ide> 'names': this.createCFFIndexHeader([name]),
<ide>
<ide> 'topDict': (function topDict(self) {
<del> return function() {
<add> return function cFFWrapTopDict() {
<ide> var header = '\x00\x01\x01\x01';
<ide> var dict =
<ide> '\xf8\x1b\x00' + // version
<ide> CFF.prototype = {
<ide> 'charstrings': this.createCFFIndexHeader([[0x8B, 0x0E]].concat(glyphs),
<ide> true),
<ide>
<del> 'private': (function(self) {
<add> 'private': (function cFFWrapPrivate(self) {
<ide> var data =
<ide> '\x8b\x14' + // defaultWidth
<ide> '\x8b\x15'; // nominalWidth
<ide> CFF.prototype = {
<ide> }
<ide> };
<ide>
<del>var Type2CFF = (function() {
<add>var Type2CFF = (function type2CFF() {
<ide> // TODO: replace parsing code with the Type2Parser in font_utils.js
<ide> function constructor(file, properties) {
<ide> var bytes = file.getBytes();
<ide> var Type2CFF = (function() {
<ide> }
<ide>
<ide> // sort the array by the unicode value
<del> charstrings.sort(function(a, b) {return a.unicode - b.unicode});
<add> charstrings.sort(function type2CFFGetCharStringsSort(a, b) {
<add> return a.unicode - b.unicode
<add> });
<ide> return charstrings;
<ide> },
<ide> | 1 |
PHP | PHP | fix cs errors | 9b1d999a5bc85988e0d25049170b0af02fb1fb66 | <ide><path>src/Console/Command.php
<ide> use Cake\Log\LogTrait;
<ide> use Cake\ORM\Locator\LocatorAwareTrait;
<ide> use InvalidArgumentException;
<del>use RuntimeException;
<ide>
<ide> /**
<ide> * Base class for console commands.
<ide><path>src/Http/Server.php
<ide> use InvalidArgumentException;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> use Psr\Http\Message\ServerRequestInterface;
<del>use RuntimeException;
<ide> use Zend\HttpHandlerRunner\Emitter\EmitterInterface;
<ide>
<ide> /**
<ide><path>src/View/Helper/PaginatorHelper.php
<ide> use Cake\View\StringTemplate;
<ide> use Cake\View\StringTemplateTrait;
<ide> use Cake\View\View;
<del>use InvalidArgumentException;
<ide>
<ide> /**
<ide> * Pagination Helper class for easy generation of pagination links. | 3 |
Ruby | Ruby | pass argv to each method that mutates it | 82f59a98035c8e9e4151ff0272f1a81fe9ec288c | <ide><path>railties/lib/rails/generators/rails/app/app_generator.rb
<ide> def get_builder_class
<ide> # This class should be called before the AppGenerator is required and started
<ide> # since it configures and mutates ARGV correctly.
<ide> class ARGVScrubber # :nodoc
<del> attr_reader :argv
<del>
<ide> def initialize(argv = ARGV)
<ide> @argv = argv.dup
<ide> end
<ide>
<ide> def prepare!
<del> handle_version_request!(argv.first)
<del> unless handle_invalid_command!(argv.first)
<del> argv.shift
<del> handle_rails_rc!
<add> handle_version_request!(@argv.first)
<add> unless handle_invalid_command!(@argv.first, @argv)
<add> @argv.shift
<add> handle_rails_rc!(@argv)
<ide> end
<del> argv
<add> @argv
<ide> end
<ide>
<ide> def self.default_rc_file
<ide> def handle_version_request!(argument)
<ide> end
<ide> end
<ide>
<del> def handle_invalid_command!(argument)
<add> def handle_invalid_command!(argument, argv)
<ide> if argument != "new"
<ide> argv[0] = "--help"
<ide> end
<ide> end
<ide>
<del> def handle_rails_rc!
<add> def handle_rails_rc!(argv)
<ide> unless argv.delete("--no-rc")
<del> insert_railsrc_into_argv!(railsrc)
<add> insert_railsrc_into_argv!(argv, railsrc(argv))
<ide> end
<ide> end
<ide>
<del> def railsrc
<add> def railsrc(argv)
<ide> if (customrc = argv.index{ |x| x.include?("--rc=") })
<ide> File.expand_path(argv.delete_at(customrc).gsub(/--rc=/, ""))
<ide> else
<ide> self.class.default_rc_file
<ide> end
<ide> end
<ide>
<del> def insert_railsrc_into_argv!(railsrc)
<add> def insert_railsrc_into_argv!(argv, railsrc)
<ide> if File.exist?(railsrc)
<ide> extra_args_string = File.read(railsrc)
<ide> extra_args = extra_args_string.split(/\n+/).map {|l| l.split}.flatten | 1 |
Ruby | Ruby | remove unnecessary use of dir[] | 0133afe6f8565ae84ab6267eb8e773abaad827cd | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def stage
<ide> # FIXME: The export command doesn't work on checkouts
<ide> # See https://bugs.launchpad.net/bzr/+bug/897511
<ide> FileUtils.cp_r Dir[@clone+"{.}"], Dir.pwd
<del> FileUtils.rm_r Dir[Dir.pwd+"/.bzr"]
<add> FileUtils.rm_r ".bzr"
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | allow define scope for ruby reserved keywords | 8589e8c236a58bb3755bae02d1eb2b6fac995956 | <ide><path>activerecord/lib/active_record/relation/delegation.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "mutex_m"
<add>require "active_support/core_ext/module/delegation"
<ide>
<ide> module ActiveRecord
<ide> module Delegation # :nodoc:
<ide> def generate_method(method)
<ide> synchronize do
<ide> return if method_defined?(method)
<ide>
<del> if /\A[a-zA-Z_]\w*[!?]?\z/.match?(method)
<add> if /\A[a-zA-Z_]\w*[!?]?\z/.match?(method) && !DELEGATION_RESERVED_METHOD_NAMES.include?(method.to_s)
<ide> definition = RUBY_VERSION >= "2.7" ? "..." : "*args, &block"
<ide> module_eval <<-RUBY, __FILE__, __LINE__ + 1
<ide> def #{method}(#{definition})
<ide><path>activerecord/test/cases/scoping/named_scoping_test.rb
<ide> def test_method_missing_priority_when_delegating
<ide> assert_equal klazz.to.since.to_a, klazz.since.to.to_a
<ide> end
<ide>
<add> def test_define_scope_for_reserved_words
<add> assert Topic.true.all?(&:approved?), "all objects should be approved"
<add> assert Topic.false.none?(&:approved?), "all objects should not be approved"
<add> end
<add>
<ide> def test_scope_should_respond_to_own_methods_and_methods_of_the_proxy
<ide> assert_respond_to Topic.approved, :limit
<ide> assert_respond_to Topic.approved, :count
<ide><path>activerecord/test/models/topic.rb
<ide> class Topic < ActiveRecord::Base
<ide> scope :approved, -> { where(approved: true) }
<ide> scope :rejected, -> { where(approved: false) }
<ide>
<add> scope :true, -> { where(approved: true) }
<add> scope :false, -> { where(approved: false) }
<add>
<ide> scope :scope_with_lambda, lambda { all }
<ide>
<ide> scope :by_lifo, -> { where(author_name: "lifo") } | 3 |
Text | Text | fix a broken link | 75f2290d2d9ad4f5e7ec77b1deeee3a0a98242b8 | <ide><path>docs/upgrading/upgrading-your-package.md
<ide> atom.workspaceView.command 'core:close core:cancel', ->
<ide>
<ide> ## Upgrading your stylesheet's selectors
<ide>
<del>Many selectors have changed, and we have introduced the [Shadow DOM][shadowdom] to the editor. See [Upgrading Your Package Selectors guide][upgrading-selectors] for more information in upgrading your package stylesheets.
<add>Many selectors have changed, and we have introduced the [Shadow DOM][shadowdom] to the editor. See [Upgrading Your UI Theme Or Package Selectors guide][upgrading-selectors] for more information in upgrading your package stylesheets.
<ide>
<ide> ## Help us improve this guide!
<ide>
<ide> Did you hit something painful that wasn't in here? Want to reword some bit of it
<ide> [texteditor]:https://atom.io/docs/api/latest/TextEditor
<ide> [disposable]:https://atom.io/docs/api/latest/Disposable
<ide> [commands-add]:https://atom.io/docs/api/latest/CommandRegistry#instance-add
<del>[upgrading-selectors]:upgrading-your-ui-theme
<add>[upgrading-selectors]:https://atom.io/docs/latest/upgrading/upgrading-your-ui-theme
<ide> [shadowdom]:http://blog.atom.io/2014/11/18/avoiding-style-pollution-with-the-shadow-dom.html
<ide> [guide]:https://github.com/atom/atom/blob/master/docs/upgrading/upgrading-your-package.md | 1 |
Java | Java | rewrite concat operation to not block on subscribe | cfa7155c24089a2fbfd2e9481b56ad953079acf3 | <ide><path>rxjava-core/src/main/java/rx/operators/OperationConcat.java
<ide> import java.util.Arrays;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<add>import java.util.Queue;
<ide> import java.util.concurrent.CountDownLatch;
<ide> import java.util.concurrent.atomic.AtomicBoolean;
<ide> import java.util.concurrent.atomic.AtomicReference;
<add>import java.util.concurrent.ConcurrentLinkedQueue;
<ide>
<ide> import org.junit.Test;
<ide>
<ide> public final class OperationConcat {
<ide>
<ide> /**
<ide> * Combine the observable sequences from the list of Observables into one
<del> * observable sequence without any transformation. If either the outer
<add> * observable sequence without any transformation. If either the outer
<ide> * observable or an inner observable calls onError, we will call onError.
<del> *
<del> * <p/>
<del> *
<del> * The outer observable might run on a separate thread from (one of) the
<del> * inner observables; in this case care must be taken to avoid a deadlock.
<del> * The Concat operation may block the outer thread while servicing an inner
<del> * thread in order to ensure a well-defined ordering of elements; therefore
<del> * none of the inner threads must be implemented in a way that might wait on
<del> * the outer thread.
<del> *
<ide> * <p/>
<ide> *
<del> * Beware that concat(o1,o2).subscribe() is a blocking call from
<del> * which it is impossible to unsubscribe if observables are running on same thread.
<del> *
<ide> * @param sequences An observable sequence of elements to project.
<ide> * @return An observable sequence whose elements are the result of combining the output from the list of Observables.
<ide> */
<ide> public static <T> Func1<Observer<T>, Subscription> concat(final List<Observable<
<ide> }
<ide>
<ide> public static <T> Func1<Observer<T>, Subscription> concat(final Observable<Observable<T>> sequences) {
<del> return new Func1<Observer<T>, Subscription>() {
<del>
<del> @Override
<del> public Subscription call(Observer<T> observer) {
<del> return new ConcatSubscription<T>(sequences, observer);
<del> }
<del> };
<add> return new Concat<T>(sequences);
<ide> }
<ide>
<del> private static class ConcatSubscription<T> extends BooleanSubscription {
<del> // Might be updated by an inner thread's onError during the outer
<del> // thread's onNext, then read in the outer thread's onComplete.
<del> final AtomicBoolean innerError = new AtomicBoolean(false);
<add> private static class Concat<T> implements Func1<Observer<T>, Subscription> {
<add> private Observable<Observable<T>> sequences;
<add> private AtomicObservableSubscription innerSubscription = null;
<add>
<add> public Concat(Observable<Observable<T>> sequences) {
<add> this.sequences = sequences;
<add> }
<ide>
<del> public ConcatSubscription(Observable<Observable<T>> sequences, final Observer<T> observer) {
<add> public Subscription call(final Observer<T> observer) {
<add> final AtomicBoolean completedOrErred = new AtomicBoolean(false);
<add> final AtomicBoolean allSequencesReceived = new AtomicBoolean(false);
<add> final Queue<Observable<T>> nextSequences = new ConcurrentLinkedQueue<Observable<T>>();
<ide> final AtomicObservableSubscription outerSubscription = new AtomicObservableSubscription();
<del> outerSubscription.wrap(sequences.subscribe(new Observer<Observable<T>>() {
<add>
<add> final Observer<T> reusableObserver = new Observer<T>() {
<ide> @Override
<del> public void onNext(Observable<T> nextSequence) {
<del> // We will not return from onNext until the inner observer completes.
<del> // NB: while we are in onNext, the well-behaved outer observable will not call onError or onCompleted.
<del> final CountDownLatch latch = new CountDownLatch(1);
<del> final AtomicObservableSubscription innerSubscription = new AtomicObservableSubscription();
<del> innerSubscription.wrap(nextSequence.subscribe(new Observer<T>() {
<del> @Override
<del> public void onNext(T item) {
<del> // Make our best-effort to release resources in the face of unsubscribe.
<del> if (isUnsubscribed()) {
<del> innerSubscription.unsubscribe();
<del> outerSubscription.unsubscribe();
<del> } else {
<del> observer.onNext(item);
<add> public void onNext(T item) {
<add> observer.onNext(item);
<add> }
<add> @Override
<add> public void onError(Exception e) {
<add> if (completedOrErred.compareAndSet(false, true)) {
<add> outerSubscription.unsubscribe();
<add> observer.onError(e);
<add> }
<add> }
<add> @Override
<add> public void onCompleted() {
<add> synchronized (nextSequences) {
<add> if (nextSequences.isEmpty()) {
<add> // No new sequences available at the moment
<add> innerSubscription = null;
<add> if (allSequencesReceived.get()) {
<add> // No new sequences are coming, we are finished
<add> if (completedOrErred.compareAndSet(false, true)) {
<add> observer.onCompleted();
<add> }
<ide> }
<del> }
<del> @Override
<del> public void onError(Exception e) {
<del> outerSubscription.unsubscribe();
<del> innerError.set(true);
<del> observer.onError(e);
<del> latch.countDown();
<del> }
<del> @Override
<del> public void onCompleted() {
<add> } else {
<ide> // Continue on to the next sequence
<del> latch.countDown();
<add> innerSubscription = new AtomicObservableSubscription();
<add> innerSubscription.wrap(nextSequences.poll().subscribe(this));
<add> }
<add> }
<add> }
<add> };
<add>
<add> outerSubscription.wrap(sequences.subscribe(new Observer<Observable<T>>() {
<add> @Override
<add> public void onNext(Observable<T> nextSequence) {
<add> synchronized (nextSequences) {
<add> if (innerSubscription == null) {
<add> // We are currently not subscribed to any sequence
<add> innerSubscription = new AtomicObservableSubscription();
<add> innerSubscription.wrap(nextSequence.subscribe(reusableObserver));
<add> } else {
<add> // Put this sequence at the end of the queue
<add> nextSequences.add(nextSequence);
<ide> }
<del> }));
<del> try {
<del> latch.await();
<del> } catch (InterruptedException e) {
<del> Thread.currentThread().interrupt();
<del> throw Exceptions.propagate(e);
<ide> }
<ide> }
<ide> @Override
<ide> public void onError(Exception e) {
<del> // NB: a well-behaved observable will not interleave on{Next,Error,Completed} calls.
<del> observer.onError(e);
<add> if (completedOrErred.compareAndSet(false, true)) {
<add> if (innerSubscription != null) {
<add> innerSubscription.unsubscribe();
<add> }
<add> observer.onError(e);
<add> }
<ide> }
<ide> @Override
<ide> public void onCompleted() {
<del> // NB: a well-behaved observable will not interleave on{Next,Error,Completed} calls.
<del> if (!innerError.get()) {
<del> observer.onCompleted();
<add> allSequencesReceived.set(true);
<add> if (innerSubscription == null) {
<add> // We are not subscribed to any sequence, and none are coming anymore
<add> if (completedOrErred.compareAndSet(false, true)) {
<add> observer.onCompleted();
<add> }
<ide> }
<ide> }
<ide> }));
<add>
<add> return new Subscription() {
<add> @Override
<add> public void unsubscribe() {
<add> synchronized (nextSequences) {
<add> if (innerSubscription != null)
<add> innerSubscription.unsubscribe();
<add> outerSubscription.unsubscribe();
<add> }
<add> }
<add> };
<ide> }
<ide> }
<ide>
<ide> public void testConcatConcurrentWithInfinity() {
<ide>
<ide>
<ide> /**
<del> * The outer observable is running on the same thread and subscribe() in this case is a blocking call. Calling unsubscribe() is no-op because the sequence is complete.
<add> * Test unsubscribing the concatenated Observable in a single thread.
<ide> */
<ide> @Test
<ide> public void testConcatUnsubscribe() {
<ide> public void testConcatUnsubscribe() {
<ide> @SuppressWarnings("unchecked")
<ide> final Observable<String> concat = Observable.create(concat(w1, w2));
<ide> final AtomicObservableSubscription s1 = new AtomicObservableSubscription();
<del> Thread t = new Thread() {
<del> @Override
<del> public void run() {
<del> // NB: this statement does not complete until after "six" has been delivered.
<del> s1.wrap(concat.subscribe(aObserver));
<del> }
<del> };
<del> t.start();
<add>
<ide> try {
<add> // Subscribe
<add> s1.wrap(concat.subscribe(aObserver));
<ide> //Block main thread to allow observable "w1" to complete and observable "w2" to call onNext once.
<ide> callOnce.await();
<del> // NB: This statement has no effect, since s1 cannot possibly
<del> // wrap anything until "six" has been delivered, which cannot
<del> // happen until we okToContinue.countDown()
<add> // Unsubcribe
<ide> s1.unsubscribe();
<ide> //Unblock the observable to continue.
<ide> okToContinue.countDown();
<ide> public void run() {
<ide> inOrder.verify(aObserver, times(1)).onNext("two");
<ide> inOrder.verify(aObserver, times(1)).onNext("three");
<ide> inOrder.verify(aObserver, times(1)).onNext("four");
<del> // NB: you might hope that five and six are not delivered, but see above.
<del> inOrder.verify(aObserver, times(1)).onNext("five");
<del> inOrder.verify(aObserver, times(1)).onNext("six");
<del> inOrder.verify(aObserver, times(1)).onCompleted();
<add> inOrder.verify(aObserver, never()).onNext("five");
<add> inOrder.verify(aObserver, never()).onNext("six");
<add> inOrder.verify(aObserver, never()).onCompleted();
<ide>
<ide> }
<ide> | 1 |
Javascript | Javascript | create service for issuing reflows in animations | fc7d2d273748847ef6ce69df2dd522419aee7d72 | <ide><path>angularFiles.js
<ide> var angularFiles = {
<ide> 'src/ng/controller.js',
<ide> 'src/ng/document.js',
<ide> 'src/ng/exceptionHandler.js',
<add> 'src/ng/forceReflow.js',
<ide> 'src/ng/http.js',
<ide> 'src/ng/httpBackend.js',
<ide> 'src/ng/interpolate.js',
<ide><path>src/AngularPublic.js
<ide> $DocumentProvider,
<ide> $ExceptionHandlerProvider,
<ide> $FilterProvider,
<add> $$ForceReflowProvider,
<ide> $InterpolateProvider,
<ide> $IntervalProvider,
<ide> $$HashMapProvider,
<ide> function publishExternalAPI(angular) {
<ide> $document: $DocumentProvider,
<ide> $exceptionHandler: $ExceptionHandlerProvider,
<ide> $filter: $FilterProvider,
<add> $$forceReflow: $$ForceReflowProvider,
<ide> $interpolate: $InterpolateProvider,
<ide> $interval: $IntervalProvider,
<ide> $http: $HttpProvider,
<ide><path>src/ng/forceReflow.js
<add>'use strict';
<add>
<add>var $$ForceReflowProvider = function() {
<add> this.$get = ['$document', function($document) {
<add> return function(domNode) {
<add> //the line below will force the browser to perform a repaint so
<add> //that all the animated elements within the animation frame will
<add> //be properly updated and drawn on screen. This is required to
<add> //ensure that the preparation animation is properly flushed so that
<add> //the active state picks up from there. DO NOT REMOVE THIS LINE.
<add> //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
<add> //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
<add> //WILL TAKE YEARS AWAY FROM YOUR LIFE.
<add> if (domNode) {
<add> if (!domNode.nodeType && domNode instanceof jqLite) {
<add> domNode = domNode[0];
<add> }
<add> } else {
<add> domNode = $document[0].body;
<add> }
<add> return domNode.offsetWidth + 1;
<add> };
<add> }];
<add>};
<ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.animate = angular.module('ngAnimateMock', ['ng'])
<ide>
<ide> .config(['$provide', function($provide) {
<ide>
<del> $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF',
<del> function($delegate, $timeout, $browser, $$rAF) {
<add> $provide.factory('$$forceReflow', function() {
<add> function reflowFn() {
<add> reflowFn.totalReflows++;
<add> }
<add> reflowFn.totalReflows = 0;
<add> return reflowFn;
<add> });
<add>
<add> $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF', '$$forceReflow',
<add> function($delegate, $timeout, $browser, $$rAF, $$forceReflow) {
<add>
<ide> var animate = {
<ide> queue: [],
<ide> cancel: $delegate.cancel,
<add> get reflows() {
<add> return $$forceReflow.totalReflows;
<add> },
<ide> enabled: $delegate.enabled,
<ide> triggerCallbackEvents: function() {
<ide> $$rAF.flush();
<ide><path>test/ng/forceReflowSpec.js
<add>'use strict';
<add>
<add>describe('$$forceReflow', function() {
<add> it('should issue a reflow by touching the `document.body.client` when no param is provided', function() {
<add> module(function($provide) {
<add> var doc = jqLite('<div></div>');
<add> doc[0].body = {};
<add> doc[0].body.offsetWidth = 10;
<add> $provide.value('$document', doc);
<add> });
<add> inject(function($$forceReflow) {
<add> var value = $$forceReflow();
<add> expect(value).toBe(11);
<add> });
<add> });
<add>
<add> it('should issue a reflow by touching the `domNode.offsetWidth` when a domNode param is provided',
<add> inject(function($$forceReflow) {
<add>
<add> var elm = {};
<add> elm.offsetWidth = 100;
<add> expect($$forceReflow(elm)).toBe(101);
<add> }));
<add>
<add> it('should issue a reflow by touching the `jqLiteNode[0].offsetWidth` when a jqLite node param is provided',
<add> inject(function($$forceReflow) {
<add>
<add> var elm = {};
<add> elm.offsetWidth = 200;
<add> elm = jqLite(elm);
<add> expect($$forceReflow(elm)).toBe(201);
<add> }));
<add>
<add> describe('$animate with ngAnimateMock', function() {
<add> beforeEach(module('ngAnimateMock'));
<add>
<add> it('should keep track of how many reflows have been issued',
<add> inject(function($$forceReflow, $animate) {
<add>
<add> var elm = {};
<add> elm.offsetWidth = 10;
<add>
<add> expect($animate.reflows).toBe(0);
<add>
<add> $$forceReflow(elm);
<add> $$forceReflow(elm);
<add> $$forceReflow(elm);
<add>
<add> expect($animate.reflows).toBe(3);
<add> }));
<add> });
<add>}); | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.