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
write bottles with new syntax
727ac9b47f0b0726e1bc18bf5d2d4aa7817b1a14
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def keg_contain_absolute_symlink_starting_with?(string, keg, args:) <ide> !absolute_symlinks_start_with_string.empty? <ide> end <ide> <del> def generate_sha256_line(tag, digest, cellar) <add> def cellar_parameter_needed?(cellar) <ide> default_cellars = [ <ide> Homebrew::DEFAULT_MACOS_CELLAR, <ide> Homebrew::DEFAULT_MACOS_ARM_CELLAR, <ide> Homebrew::DEFAULT_LINUX_CELLAR, <ide> ] <add> cellar.present? && default_cellars.exclude?(cellar) <add> end <add> <add> def generate_sha256_line(tag, digest, cellar, tag_column, digest_column) <add> line = "sha256 " <add> tag_column += line.length <add> digest_column += line.length <ide> if cellar.is_a?(Symbol) <del> %Q(sha256 cellar: :#{cellar}, #{tag}: "#{digest}") <del> elsif cellar.present? && default_cellars.exclude?(cellar) <del> %Q(sha256 cellar: "#{cellar}", #{tag}: "#{digest}") <del> else <del> %Q(sha256 #{tag}: "#{digest}") <add> line += "cellar: :#{cellar}," <add> elsif cellar_parameter_needed?(cellar) <add> line += %Q(cellar: "#{cellar}",) <ide> end <add> line += " " * (tag_column - line.length) <add> line += "#{tag}:" <add> line += " " * (digest_column - line.length) <add> %Q(#{line}"#{digest}") <ide> end <ide> <ide> def bottle_output(bottle) <add> cellars = bottle.checksums.map do |checksum| <add> cellar = checksum["cellar"] <add> next unless cellar_parameter_needed? cellar <add> <add> case cellar <add> when String <add> %Q("#{cellar}") <add> when Symbol <add> ":#{cellar}" <add> end <add> end.compact <add> tag_column = cellars.empty? ? 0 : "cellar: #{cellars.max_by(&:length)}, ".length <add> <add> tags = bottle.checksums.map { |checksum| checksum["tag"] } <add> # Start where the tag ends, add the max length of the tag, add two for the `: ` <add> digest_column = tag_column + tags.max_by(&:length).length + 2 <add> <ide> sha256_lines = bottle.checksums.map do |checksum| <del> generate_sha256_line(checksum["tag"], checksum["digest"], checksum["cellar"]) <add> generate_sha256_line(checksum["tag"], checksum["digest"], checksum["cellar"], tag_column, digest_column) <ide> end <ide> erb_binding = bottle.instance_eval { binding } <ide> erb_binding.local_variable_set(:sha256_lines, sha256_lines) <ide><path>Library/Homebrew/test/dev-cmd/bottle_spec.rb <ide> ==> testball <ide> bottle do <ide> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <del> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <add> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <ide> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <ide> end <ide> EOS <ide> class Testball < Formula <ide> <ide> bottle do <ide> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <del> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <add> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <ide> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <ide> end <ide> <ide> def install <ide> EOS <ide> end <ide> <del> it "replaces the bottle block in a formula that already has a bottle block" do <add> it "replaces the bottle block in a formula that already has a bottle block in the old format" do <ide> core_tap.path.cd do <ide> system "git", "init" <ide> setup_test_formula "testball", bottle_block: <<~EOS <ide> def install <ide> ==> testball <ide> bottle do <ide> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <del> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <add> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <ide> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <ide> end <ide> EOS <ide> class Testball < Formula <ide> <ide> bottle do <ide> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <del> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <add> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <add> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <add> end <add> <add> def install <add> (prefix/"foo"/"test").write("test") if build.with? "foo" <add> prefix.install Dir["*"] <add> (buildpath/"test.c").write \ <add> "#include <stdio.h>\\nint main(){printf(\\"test\\");return 0;}" <add> bin.mkpath <add> system ENV.cc, "test.c", "-o", bin/"test" <add> end <add> <add> <add> <add> # something here <add> <add> end <add> EOS <add> end <add> <add> it "replaces the bottle block in a formula that already has a bottle block" do <add> core_tap.path.cd do <add> system "git", "init" <add> setup_test_formula "testball", bottle_block: <<~EOS <add> <add> bottle do <add> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <add> sha256 cellar: :any_skip_relocation, big_sur: "6b276491297d4052538bd2fd22d5129389f27d90a98f831987236a5b90511b98" <add> sha256 cellar: :any_skip_relocation, catalina: "16cf230afdfcb6306c208d169549cf8773c831c8653d2c852315a048960d7e72" <add> end <add> EOS <add> system "git", "add", "--all" <add> system "git", "commit", "-m", "testball 0.1" <add> end <add> <add> expect { <add> brew "bottle", <add> "--merge", <add> "--write", <add> "#{TEST_TMPDIR}/testball-1.0.big_sur.bottle.json", <add> "#{TEST_TMPDIR}/testball-1.0.catalina.bottle.json" <add> }.to output(<<~EOS).to_stdout <add> ==> testball <add> bottle do <add> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <add> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <add> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <add> end <add> EOS <add> <add> expect((core_tap.path/"Formula/testball.rb").read).to eq <<~EOS <add> class Testball < Formula <add> desc "Some test" <add> homepage "https://brew.sh/testball" <add> url "file://#{tarball}" <add> sha256 "#{tarball.sha256}" <add> <add> option "with-foo", "Build with foo" <add> <add> bottle do <add> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <add> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <ide> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <ide> end <ide> <ide> def install <ide> }.to output("Error: `--keep-old` was passed but there was no existing bottle block!\n").to_stderr <ide> end <ide> <del> it "updates the bottle block in a formula that already has a bottle block when using --keep-old" do <add> it "updates the bottle block in a formula that already has a bottle block (old format) when using --keep-old" do <ide> core_tap.path.cd do <ide> system "git", "init" <ide> setup_test_formula "testball", bottle_block: <<~EOS <ide> def install <ide> ==> testball <ide> bottle do <ide> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <del> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <del> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <del> sha256 cellar: :any, high_sierra: "6971b6eebf4c00eaaed72a1104a49be63861eabc95d679a0c84040398e320059" <add> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <add> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <add> sha256 cellar: :any, high_sierra: "6971b6eebf4c00eaaed72a1104a49be63861eabc95d679a0c84040398e320059" <ide> end <ide> EOS <ide> <ide> class Testball < Formula <ide> <ide> bottle do <ide> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <del> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <del> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <add> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <add> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <add> sha256 cellar: :any, high_sierra: "6971b6eebf4c00eaaed72a1104a49be63861eabc95d679a0c84040398e320059" <add> end <add> <add> def install <add> (prefix/"foo"/"test").write("test") if build.with? "foo" <add> prefix.install Dir["*"] <add> (buildpath/"test.c").write \ <add> "#include <stdio.h>\\nint main(){printf(\\"test\\");return 0;}" <add> bin.mkpath <add> system ENV.cc, "test.c", "-o", bin/"test" <add> end <add> <add> <add> <add> # something here <add> <add> end <add> EOS <add> end <add> <add> it "updates the bottle block in a formula that already has a bottle block when using --keep-old" do <add> core_tap.path.cd do <add> system "git", "init" <add> setup_test_formula "testball", bottle_block: <<~EOS <add> <add> bottle do <add> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <ide> sha256 cellar: :any, high_sierra: "6971b6eebf4c00eaaed72a1104a49be63861eabc95d679a0c84040398e320059" <ide> end <add> EOS <add> system "git", "add", "--all" <add> system "git", "commit", "-m", "testball 0.1" <add> end <add> <add> expect { <add> brew "bottle", <add> "--merge", <add> "--write", <add> "--keep-old", <add> "#{TEST_TMPDIR}/testball-1.0.big_sur.bottle.json", <add> "#{TEST_TMPDIR}/testball-1.0.catalina.bottle.json" <add> }.to output(<<~EOS).to_stdout <add> ==> testball <add> bottle do <add> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <add> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <add> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <add> sha256 cellar: :any, high_sierra: "6971b6eebf4c00eaaed72a1104a49be63861eabc95d679a0c84040398e320059" <add> end <add> EOS <add> <add> expect((core_tap.path/"Formula/testball.rb").read).to eq <<~EOS <add> class Testball < Formula <add> desc "Some test" <add> homepage "https://brew.sh/testball" <add> url "file://#{tarball}" <add> sha256 "#{tarball.sha256}" <add> <add> option "with-foo", "Build with foo" <add> <add> bottle do <add> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}" <add> sha256 cellar: :any_skip_relocation, big_sur: "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" <add> sha256 cellar: :any_skip_relocation, catalina: "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" <add> sha256 cellar: :any, high_sierra: "6971b6eebf4c00eaaed72a1104a49be63861eabc95d679a0c84040398e320059" <add> end <ide> <ide> def install <ide> (prefix/"foo"/"test").write("test") if build.with? "foo" <ide> def install <ide> <ide> describe "::generate_sha256_line" do <ide> it "generates a string without cellar" do <del> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", nil)).to eq( <add> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", nil, 0, 10)).to eq( <ide> <<~RUBY.chomp, <ide> sha256 catalina: "deadbeef" <ide> RUBY <ide> ) <ide> end <ide> <ide> it "generates a string with cellar symbol" do <del> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", :any)).to eq( <add> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", :any, 14, 24)).to eq( <ide> <<~RUBY.chomp, <ide> sha256 cellar: :any, catalina: "deadbeef" <ide> RUBY <ide> ) <ide> end <ide> <ide> it "generates a string with default cellar path" do <del> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", Homebrew::DEFAULT_LINUX_CELLAR)).to eq( <add> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", Homebrew::DEFAULT_LINUX_CELLAR, 0, 10)).to eq( <ide> <<~RUBY.chomp, <ide> sha256 catalina: "deadbeef" <ide> RUBY <ide> ) <ide> end <ide> <ide> it "generates a string with non-default cellar path" do <del> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", "/home/test")).to eq( <add> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", "/home/test", 22, 32)).to eq( <ide> <<~RUBY.chomp, <ide> sha256 cellar: "/home/test", catalina: "deadbeef" <ide> RUBY <ide> ) <ide> end <add> <add> context "with offsets" do <add> it "generates a string without cellar" do <add> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", nil, 0, 15)).to eq( <add> <<~RUBY.chomp, <add> sha256 catalina: "deadbeef" <add> RUBY <add> ) <add> end <add> <add> it "generates a string with cellar symbol" do <add> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", :any, 20, 35)).to eq( <add> <<~RUBY.chomp, <add> sha256 cellar: :any, catalina: "deadbeef" <add> RUBY <add> ) <add> end <add> <add> it "generates a string with default cellar path" do <add> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", Homebrew::DEFAULT_LINUX_CELLAR, 14, 30)).to eq( <add> <<~RUBY.chomp, <add> sha256 catalina: "deadbeef" <add> RUBY <add> ) <add> end <add> <add> it "generates a string with non-default cellar path" do <add> expect(homebrew.generate_sha256_line(:catalina, "deadbeef", "/home/test", 25, 36)).to eq( <add> <<~RUBY.chomp, <add> sha256 cellar: "/home/test", catalina: "deadbeef" <add> RUBY <add> ) <add> end <add> end <ide> end <ide> end <ide> end
2
Go
Go
join groups by writing to cgroups.procs, not tasks
9294d7f2af6ecb7c18be11fb5043fad4a61d8f09
<ide><path>pkg/cgroups/apply_raw.go <ide> func (raw *rawCgroup) join(subsystem string, pid int) (string, error) { <ide> if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) { <ide> return "", err <ide> } <del> if err := writeFile(path, "tasks", strconv.Itoa(pid)); err != nil { <add> if err := writeFile(path, "cgroup.procs", strconv.Itoa(pid)); err != nil { <ide> return "", err <ide> } <ide> return path, nil
1
Javascript
Javascript
fix aes crash when tag length too small
7a9635b094b11201c9098312c805f8f72ac775ed
<ide><path>lib/internal/crypto/aes.js <ide> const { <ide> kKeyObject, <ide> } = require('internal/crypto/util'); <ide> <add>const { PromiseReject } = primordials; <add> <ide> const { <ide> codes: { <ide> ERR_INVALID_ARG_TYPE, <ide> function asyncAesGcmCipher( <ide> data, <ide> { iv, additionalData, tagLength = 128 }) { <ide> if (!ArrayPrototypeIncludes(kTagLengths, tagLength)) { <del> throw lazyDOMException( <add> return PromiseReject(lazyDOMException( <ide> `${tagLength} is not a valid AES-GCM tag length`, <del> 'OperationError'); <add> 'OperationError')); <ide> } <ide> <ide> iv = getArrayBufferOrView(iv, 'algorithm.iv'); <ide> function asyncAesGcmCipher( <ide> const slice = ArrayBufferIsView(data) ? <ide> TypedArrayPrototypeSlice : ArrayBufferPrototypeSlice; <ide> tag = slice(data, -tagByteLength); <add> <add> // Refs: https://www.w3.org/TR/WebCryptoAPI/#aes-gcm-operations <add> // <add> // > If *plaintext* has a length less than *tagLength* bits, then `throw` <add> // > an `OperationError`. <add> if (tagByteLength > tag.byteLength) { <add> return PromiseReject(lazyDOMException( <add> 'The provided data is too small.', <add> 'OperationError')); <add> } <add> <ide> data = slice(data, 0, -tagByteLength); <ide> break; <ide> case kWebCryptoCipherEncrypt: <ide><path>test/parallel/test-crypto-webcrypto-aes-decrypt-tag-too-small.js <add>'use strict'; <add> <add>const common = require('../common'); <add> <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <add>const assert = require('assert'); <add>const crypto = require('crypto').webcrypto; <add> <add>crypto.subtle.importKey( <add> 'raw', <add> new Uint8Array(32), <add> { <add> name: 'AES-GCM' <add> }, <add> false, <add> [ 'encrypt', 'decrypt' ]) <add> .then((k) => { <add> assert.rejects(() => { <add> return crypto.subtle.decrypt({ <add> name: 'AES-GCM', <add> iv: new Uint8Array(12), <add> }, k, new Uint8Array(0)); <add> }, { <add> name: 'OperationError', <add> message: /The provided data is too small/, <add> }); <add> });
2
Ruby
Ruby
convert reinstall test to spec
20b77dfdcc4332f1d21e39571e1bbc7eefc6d4dd
<ide><path>Library/Homebrew/cask/spec/cask/cli/reinstall_spec.rb <add>require "spec_helper" <add> <add>describe Hbc::CLI::Reinstall do <add> it "allows reinstalling a Cask" do <add> shutup do <add> Hbc::CLI::Install.run("local-transmission") <add> end <add> expect(Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb")).to be_installed <add> <add> shutup do <add> Hbc::CLI::Reinstall.run("local-transmission") <add> end <add> expect(Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb")).to be_installed <add> end <add> <add> it "allows reinstalling a non installed Cask" do <add> expect(Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb")).not_to be_installed <add> <add> shutup do <add> Hbc::CLI::Reinstall.run("local-transmission") <add> end <add> expect(Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb")).to be_installed <add> end <add>end <ide><path>Library/Homebrew/cask/test/cask/cli/reinstall_test.rb <del>require "test_helper" <del> <del>describe Hbc::CLI::Reinstall do <del> it "allows reinstalling a Cask" do <del> shutup do <del> Hbc::CLI::Install.run("local-transmission") <del> end <del> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb").must_be :installed? <del> <del> shutup do <del> Hbc::CLI::Reinstall.run("local-transmission") <del> end <del> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb").must_be :installed? <del> end <del> <del> it "allows reinstalling a non installed Cask" do <del> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb").wont_be :installed? <del> <del> shutup do <del> Hbc::CLI::Reinstall.run("local-transmission") <del> end <del> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb").must_be :installed? <del> end <del>end
2
Python
Python
load the pretrained weights for encoder-decoder
1c71ecc880ae8f04c8462e1368dc0678fdb92fc9
<ide><path>examples/run_summarization_finetuning.py <ide> def evaluate(args, model, tokenizer, prefix=""): <ide> return result <ide> <ide> <add>def save_model_checkpoints(args, model, tokenizer): <add> if not os.path.exists(args.output_dir): <add> os.makedirs(args.output_dir) <add> <add> logger.info("Saving model checkpoint to %s", args.output_dir) <add> <add> # Save a trained model, configuration and tokenizer using `save_pretrained()`. <add> # They can then be reloaded using `from_pretrained()` <add> model_to_save = ( <add> model.module if hasattr(model, "module") else model <add> ) # Take care of distributed/parallel training <add> model_to_save.save_pretrained(args.output_dir, model_type='bert') <add> tokenizer.save_pretrained(args.output_dir) <add> torch.save(args, os.path.join(args.output_dir, "training_arguments.bin")) <add> <add> <ide> def main(): <ide> parser = argparse.ArgumentParser() <ide> <ide> def main(): <ide> # Train the model <ide> model.to(args.device) <ide> if args.do_train: <del> global_step, tr_loss = train(args, model, tokenizer) <del> logger.info(" global_step = %s, average loss = %s", global_step, tr_loss) <del> <del> if not os.path.exists(args.output_dir): <del> os.makedirs(args.output_dir) <add> try: <add> global_step, tr_loss = train(args, model, tokenizer) <add> except KeyboardInterrupt: <add> response = input("You interrupted the training. Do you want to save the model checkpoints? [Y/n]") <add> if response.lower() in ["", "y", "yes"]: <add> save_model_checkpoints(args, model, tokenizer) <add> sys.exit(0) <ide> <del> logger.info("Saving model checkpoint to %s", args.output_dir) <del> <del> # Save a trained model, configuration and tokenizer using `save_pretrained()`. <del> # They can then be reloaded using `from_pretrained()` <del> model_to_save = ( <del> model.module if hasattr(model, "module") else model <del> ) # Take care of distributed/parallel training <del> model_to_save.save_pretrained(args.output_dir) <del> tokenizer.save_pretrained(args.output_dir) <del> torch.save(args, os.path.join(args.output_dir, "training_arguments.bin")) <add> logger.info(" global_step = %s, average loss = %s", global_step, tr_loss) <add> save_model_checkpoints(args, model, tokenizer) <ide> <ide> # Evaluate the model <ide> results = {} <ide> if args.do_evaluate: <del> checkpoints = [] <add> checkpoints = [args.output_dir] <ide> logger.info("Evaluate the following checkpoints: %s", checkpoints) <ide> for checkpoint in checkpoints: <del> encoder_checkpoint = os.path.join(checkpoint, "encoder") <del> decoder_checkpoint = os.path.join(checkpoint, "decoder") <add> encoder_checkpoint = os.path.join(checkpoint, "bert_encoder") <add> decoder_checkpoint = os.path.join(checkpoint, "bert_decoder") <ide> model = PreTrainedEncoderDecoder.from_pretrained( <ide> encoder_checkpoint, decoder_checkpoint <ide> ) <ide> model.to(args.device) <del> results = "placeholder" <add> print("model loaded") <ide> <ide> return results <ide> <ide><path>transformers/modeling_encoder_decoder.py <ide> def from_pretrained( <ide> kwargs_common = { <ide> argument: value <ide> for argument, value in kwargs.items() <del> if not argument.startswith("encoder_") <del> and not argument.startswith("decoder_") <add> if not argument.startswith("encoder_") and not argument.startswith("decoder_") <ide> } <ide> kwargs_decoder = kwargs_common.copy() <ide> kwargs_encoder = kwargs_common.copy() <ide> def from_pretrained( <ide> <ide> return model <ide> <del> def save_pretrained(self, save_directory): <del> """ Save a Seq2Seq model and its configuration file in a format such <add> def save_pretrained(self, save_directory, model_type="bert"): <add> """ Save an EncoderDecoder model and its configuration file in a format such <ide> that it can be loaded using `:func:`~transformers.PreTrainedEncoderDecoder.from_pretrained` <ide> <ide> We save the encoder' and decoder's parameters in two separate directories. <add> <add> If we want the weight loader to function we need to preprend the model <add> type to the directories' names. As far as I know there is no simple way <add> to infer the type of the model (except maybe by parsing the class' <add> names, which is not very future-proof). For now, we ask the user to <add> specify the model type explicitly when saving the weights. <ide> """ <del> self.encoder.save_pretrained(os.path.join(save_directory, "encoder")) <del> self.decoder.save_pretrained(os.path.join(save_directory, "decoder")) <add> encoder_path = os.path.join(save_directory, "{}_encoder".format(model_type)) <add> if not os.path.exists(encoder_path): <add> os.makedirs(encoder_path) <add> self.encoder.save_pretrained(encoder_path) <add> <add> decoder_path = os.path.join(save_directory, "{}_decoder".format(model_type)) <add> if not os.path.exists(decoder_path): <add> os.makedirs(decoder_path) <add> self.decoder.save_pretrained(decoder_path) <ide> <ide> def forward(self, encoder_input_ids, decoder_input_ids, **kwargs): <ide> """ The forward pass on a seq2eq depends what we are performing: <ide> def forward(self, encoder_input_ids, decoder_input_ids, **kwargs): <ide> kwargs_common = { <ide> argument: value <ide> for argument, value in kwargs.items() <del> if not argument.startswith("encoder_") <del> and not argument.startswith("decoder_") <add> if not argument.startswith("encoder_") and not argument.startswith("decoder_") <ide> } <ide> kwargs_decoder = kwargs_common.copy() <ide> kwargs_encoder = kwargs_common.copy() <ide> def forward(self, encoder_input_ids, decoder_input_ids, **kwargs): <ide> encoder_hidden_states = kwargs_encoder.pop("hidden_states", None) <ide> if encoder_hidden_states is None: <ide> encoder_outputs = self.encoder(encoder_input_ids, **kwargs_encoder) <del> encoder_hidden_states = encoder_outputs[ <del> 0 <del> ] # output the last layer hidden state <add> encoder_hidden_states = encoder_outputs[0] # output the last layer hidden state <ide> else: <ide> encoder_outputs = () <ide>
2
Text
Text
add peter-samir to hof
7613df56e1736ae6c53fac3eaedc3570cdb636a9
<ide><path>HoF.md <ide> We appreciate any responsible disclosure of vulnerabilities that might impact the integrity of our platforms and users. While we do not offer any bounties or swags at the moment, we are grateful to these awesome people for helping us keep the platform safe for everyone: <ide> <ide> - Mehul Mohan from [codedamn](https://codedamn.com) ([@mehulmpt](https://twitter.com/mehulmpt)) - [Vulnerability Fix](https://github.com/freeCodeCamp/freeCodeCamp/blob/bb5a9e815313f1f7c91338e171bfe5acb8f3e346/client/src/components/Flash/index.js) <del> <add>- Peter Samir https://www.linkedin.com/in/peter-samir/ <ide> > ### Thank you for your contributions :pray:
1
Text
Text
add azure pipelines example to no-cache docs
bdc20c26578e40ad88335c919d78057e6ddbec65
<ide><path>errors/no-cache.md <ide> Using Heroku's [custom cache](https://devcenter.heroku.com/articles/nodejs-suppo <ide> ```javascript <ide> "cacheDirectories": [".next/cache"] <ide> ``` <add> <add>#### Azure Pipelines <add> <add>Using Azure Pipelines' [Cache task](https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/cache), add the following task to your pipeline yaml file somewhere prior to the task that executes `next build`: <add> <add>```yaml <add>- task: Cache@2 <add> displayName: 'Cache .next/cache' <add> inputs: <add> key: next | $(Agent.OS) | yarn.lock <add> path: '$(System.DefaultWorkingDirectory)/.next/cache' <add>```
1
Python
Python
use full python dot path to extension
d9d34e4886c283653bc7d9e50a414ab07ee8bb93
<ide><path>rest_framework/compat.py <ide> def apply_markdown(text): <ide> of '#' style headers to <h2>. <ide> """ <ide> <del> extensions = ['headerid(level=2)'] <add> extensions = ['markdown.extensions.headerid(level=2)'] <ide> md = markdown.Markdown(extensions=extensions) <ide> return md.convert(text) <ide> except ImportError:
1
Text
Text
add text line 7 "i" to article
9c817a6f9c274480185d24ed422ee6828140b15c
<ide><path>guide/english/mobile-app-development/cordova-ios-application-development-setup-to-deployment/index.md <ide> title: Cordova iOS Application Development Setup to Deployment <ide> # Cordova iOS Application Development Setup to Deployment <ide> <img src="https://image.ibb.co/iKCSuQ/Xz_J197k8_QI32.jpg" alt="iphone_1737513_1920" width="100%"> <ide> <del>Hybrid Application development for android is a breeze, be it for development or production configuration, however i personally find cordova iOS setup, development and deployment a bit complicated. <add>Hybrid Application development for android is a breeze, be it for development or production configuration, however I personally find cordova iOS setup, development and deployment a bit complicated. <ide> <del>Most of the Hybrid Application Developers who are in learning stage are not able to explore hybrid iOS app development process due to the simple reason that they dont own a mac, since developing iOS apps requires the iOS SDK and XCode unlike Android SDK which runs on any Desktop OS. Therefore the aim of this guide is to show the basic workflow of hybrid iOS app development on a mac, so that a developer even if he/she cannot develop iOS apps, is atleast familiar with how its done. <add>Most of the Hybrid Application Developers who are in the learning stage are not able to explore hybrid iOS app development process due to the simple reason that they dont own a mac, since developing iOS apps requires the iOS SDK and XCode unlike Android SDK which runs on any Desktop OS. Therefore the aim of this guide is to show the basic workflow of hybrid iOS app development on a mac, so that a developer, even if he/she cannot develop iOS apps, is atleast familiar with how its done. <ide> <ide> <ide> ## Creating cordova project
1
Ruby
Ruby
move common env methods to a shared module
9a5b15bb61e3c043c1121d51e12a55b8d5dba50a
<ide><path>Library/Homebrew/extend/ENV.rb <ide> require 'hardware' <add>require 'extend/ENV/shared' <ide> require 'extend/ENV/super' <ide> <ide> def superenv? <ide> def activate_extensions! <ide> ENV.extend(EnvActivation) <ide> <ide> module HomebrewEnvExtension <add> include SharedEnvExtension <add> <ide> SAFE_CFLAGS_FLAGS = "-w -pipe" <del> CC_FLAG_VARS = %w{CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS} <del> FC_FLAG_VARS = %w{FCFLAGS FFLAGS} <ide> DEFAULT_FLAGS = '-march=core2 -msse4' <ide> <ide> def self.extended(base) <ide> def ld64 <ide> append "LDFLAGS", "-B#{ld64.bin.to_s+"/"}" <ide> end <ide> end <del> <del>class << ENV <del> def remove_cc_etc <del> keys = %w{CC CXX OBJC OBJCXX LD CPP CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS LDFLAGS CPPFLAGS} <del> removed = Hash[*keys.map{ |key| [key, self[key]] }.flatten] <del> keys.each do |key| <del> delete(key) <del> end <del> removed <del> end <del> def append_to_cflags newflags <del> append(HomebrewEnvExtension::CC_FLAG_VARS, newflags) <del> end <del> def remove_from_cflags val <del> remove HomebrewEnvExtension::CC_FLAG_VARS, val <del> end <del> def append keys, value, separator = ' ' <del> value = value.to_s <del> Array(keys).each do |key| <del> unless self[key].to_s.empty? <del> self[key] = self[key] + separator + value.to_s <del> else <del> self[key] = value.to_s <del> end <del> end <del> end <del> def prepend keys, value, separator = ' ' <del> Array(keys).each do |key| <del> unless self[key].to_s.empty? <del> self[key] = value.to_s + separator + self[key] <del> else <del> self[key] = value.to_s <del> end <del> end <del> end <del> def prepend_path key, path <del> prepend key, path, ':' if File.directory? path <del> end <del> def remove keys, value <del> Array(keys).each do |key| <del> next unless self[key] <del> self[key] = self[key].sub(value, '') <del> delete(key) if self[key].to_s.empty? <del> end if value <del> end <del> <del> def cc; self['CC'] or "cc"; end <del> def cxx; self['CXX'] or "c++"; end <del> def cflags; self['CFLAGS']; end <del> def cxxflags; self['CXXFLAGS']; end <del> def cppflags; self['CPPFLAGS']; end <del> def ldflags; self['LDFLAGS']; end <del> def fc; self['FC']; end <del> def fflags; self['FFLAGS']; end <del> def fcflags; self['FCFLAGS']; end <del> <del> # Snow Leopard defines an NCURSES value the opposite of most distros <del> # See: http://bugs.python.org/issue6848 <del> # Currently only used by aalib in core <del> def ncurses_define <del> append 'CPPFLAGS', "-DNCURSES_OPAQUE=0" <del> end <del> <del> def userpaths! <del> paths = ORIGINAL_PATHS.map { |p| p.realpath.to_s rescue nil } - %w{/usr/X11/bin /opt/X11/bin} <del> self['PATH'] = paths.unshift(*self['PATH'].split(":")).uniq.join(":") <del> # XXX hot fix to prefer brewed stuff (e.g. python) over /usr/bin. <del> prepend 'PATH', HOMEBREW_PREFIX/'bin', ':' <del> end <del> <del> def with_build_environment <del> old_env = to_hash <del> setup_build_environment <del> yield <del> ensure <del> replace(old_env) <del> end <del> <del> def fortran <del> # superenv removes these PATHs, but this option needs them <del> # TODO fix better, probably by making a super-fc <del> self['PATH'] += ":#{HOMEBREW_PREFIX}/bin:/usr/local/bin" <del> <del> if self['FC'] <del> ohai "Building with an alternative Fortran compiler" <del> puts "This is unsupported." <del> self['F77'] ||= self['FC'] <del> <del> if ARGV.include? '--default-fortran-flags' <del> flags_to_set = [] <del> flags_to_set << 'FCFLAGS' unless self['FCFLAGS'] <del> flags_to_set << 'FFLAGS' unless self['FFLAGS'] <del> flags_to_set.each {|key| self[key] = cflags} <del> set_cpu_flags(flags_to_set) <del> elsif not self['FCFLAGS'] or self['FFLAGS'] <del> opoo <<-EOS.undent <del> No Fortran optimization information was provided. You may want to consider <del> setting FCFLAGS and FFLAGS or pass the `--default-fortran-flags` option to <del> `brew install` if your compiler is compatible with GCC. <del> <del> If you like the default optimization level of your compiler, ignore this <del> warning. <del> EOS <del> end <del> <del> elsif which 'gfortran' <del> ohai "Using Homebrew-provided fortran compiler." <del> puts "This may be changed by setting the FC environment variable." <del> self['FC'] = which 'gfortran' <del> self['F77'] = self['FC'] <del> <del> HomebrewEnvExtension::FC_FLAG_VARS.each {|key| self[key] = cflags} <del> set_cpu_flags(HomebrewEnvExtension::FC_FLAG_VARS) <del> end <del> end <del>end <ide><path>Library/Homebrew/extend/ENV/super.rb <ide> require 'macos' <add>require 'extend/ENV/shared' <ide> <ide> ### Why `superenv`? <ide> # 1) Only specify the environment we need (NO LDFLAGS for cmake) <ide> # 8) Build-system agnostic configuration of the tool-chain <ide> <ide> module Superenv <add> include SharedEnvExtension <add> <ide> attr_accessor :keg_only_deps, :deps, :x11 <ide> alias_method :x11?, :x11 <ide>
2
Text
Text
fix typo in relations docs
f3c5802872505c9304b1d27a7e5bc38af012816b
<ide><path>docs/api-guide/relations.md <ide> For example, given the following model for a tag, which has a generic relationsh <ide> def __unicode__(self): <ide> return self.tag_name <ide> <del>And the following two models, which may be have associated tags: <add>And the following two models, which may have associated tags: <ide> <ide> class Bookmark(models.Model): <ide> """
1
Mixed
PHP
add an "addselect" clause to the query builder
bf376dad59d4cd414bf43369e0891cdae0fa9022
<ide><path>readme.md <ide> - Changed cache stores to be implementors of a `StoreInterface` rather than extenders of a `Store` abstract class. Injected implementations into a `Cache\Repository` class. <ide> - Added `array_fetch` and `array_flatten`. Added `fetch` and `flatten` to `Collection` class. <ide> - Added `merge` method to the Collection class. <add>- Added an `addSelect` method to the query builder. <ide> <ide> ## Beta 3 <ide> <ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function select($columns = array('*')) <ide> return $this; <ide> } <ide> <add> /** <add> * Add a new select column to the query. <add> * <add> * @param mixed $column <add> * @return Illuminate\Database\Query\Builder <add> */ <add> public function addSelect($column) <add> { <add> if ( ! isset($this->columns)) $this->columns = array(); <add> <add> $this->columns = array_merge($this->columns, $column); <add> <add> return $this; <add> } <add> <ide> /** <ide> * Force the query to only return distinct results. <ide> *
2
Python
Python
fix test_fromfile_tofile_seeks to work on windows
98484bb6e3958a26d8f7a4742975e13713003c64
<ide><path>numpy/core/tests/test_regression.py <ide> def test_take_refcount(self): <ide> def test_fromfile_tofile_seeks(self): <ide> # On Python 3, tofile/fromfile used to get (#1610) the Python <ide> # file handle out of sync <del> f = tempfile.TemporaryFile() <add> f0 = tempfile.NamedTemporaryFile() <add> f = f0.file <ide> f.write(np.arange(255, dtype='u1').tostring()) <ide> <ide> f.seek(20)
1
Mixed
Ruby
deprecate unused quoted_locking_column method
bb54fcdfadcab3d69b46da384d00abfd09626031
<ide><path>activerecord/CHANGELOG.md <add>* Deprecate `quoted_locking_column` method, which isn't used anywhere. <add> <add> *kennyj* <add> <ide> * Migration dump UUID default functions to schema.rb. <ide> <ide> Fixes #10751. <ide><path>activerecord/lib/active_record/locking/optimistic.rb <ide> def locking_column <ide> <ide> # Quote the column name used for optimistic locking. <ide> def quoted_locking_column <add> ActiveSupport::Deprecation.warn "ActiveRecord::Base.quoted_locking_column is deprecated and will be removed in Rails 4.2 or later." <ide> connection.quote_column_name(locking_column) <ide> end <ide> <ide><path>activerecord/test/cases/locking_test.rb <ide> def test_removing_has_and_belongs_to_many_associations_upon_destroy <ide> assert p.treasures.empty? <ide> assert RichPerson.connection.select_all("SELECT * FROM peoples_treasures WHERE rich_person_id = 1").empty? <ide> end <add> <add> def test_quoted_locking_column_is_deprecated <add> assert_deprecated { ActiveRecord::Base.quoted_locking_column } <add> end <ide> end <ide> <ide> class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase
3
Text
Text
add a changelog entry for 165785e
5ce1f66d7ac50492f4cd1e6bd0170b2c888ec73d
<ide><path>activestorage/CHANGELOG.md <add>* Image analysis is skipped if ImageMagick returns an error. <add> <add> `ActiveStorage::Analyzer::ImageAnalyzer#metadata` would previously raise a <add> `MiniMagick::Error`, which caused persistent `ActiveStorage::AnalyzeJob` <add> failures. It now logs the error and returns `{}`, resulting in no metadata <add> being added to the offending image blob. <add> <add> *George Claghorn* <add> <ide> * Method calls on singular attachments return `nil` when no file is attached. <ide> <del> Previously, assuming the following User model, `user.avatar.filename` would <add> Previously, assuming the following User model, `user.avatar.filename` would <ide> raise a `Module::DelegationError` if no avatar was attached: <ide> <ide> ```ruby <ide> class User < ApplicationRecord <ide> has_one_attached :avatar <ide> end <ide> ``` <del> <add> <ide> They now return `nil`. <ide> <ide> *Matthew Tanous*
1
PHP
PHP
wrap method
f57b9e23ad4f8552bd5c2c958b9fbed4d2478389
<ide><path>src/Illuminate/Support/Collection.php <ide> public static function make($items = []) <ide> return new static($items); <ide> } <ide> <add> /** <add> * If the given value is not a collection, wrap it in one. <add> * <add> * @param mixed $value <add> * @return static <add> */ <add> public static function wrap($value) <add> { <add> return $value instanceof self <add> ? new static($value) <add> : new static(Arr::wrap($value)); <add> } <add> <ide> /** <ide> * Create a new collection by invoking the callback a given amount of times. <ide> * <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testMakeMethodFromArray() <ide> $this->assertEquals(['foo' => 'bar'], $collection->all()); <ide> } <ide> <add> public function testWrapWithScalar() <add> { <add> $collection = Collection::wrap('foo'); <add> $this->assertEquals(['foo'], $collection->all()); <add> } <add> <add> public function testWrapWithArray() <add> { <add> $collection = Collection::wrap(['foo']); <add> $this->assertEquals(['foo'], $collection->all()); <add> } <add> <add> public function testWrapWithArrayable() <add> { <add> $collection = Collection::wrap($o = new TestArrayableObject); <add> $this->assertEquals([$o], $collection->all()); <add> } <add> <add> public function testWrapWithJsonable() <add> { <add> $collection = Collection::wrap($o = new TestJsonableObject); <add> $this->assertEquals([$o], $collection->all()); <add> } <add> <add> public function testWrapWithJsonSerialize() <add> { <add> $collection = Collection::wrap($o = new TestJsonSerializeObject); <add> $this->assertEquals([$o], $collection->all()); <add> } <add> <add> public function testWrapWithCollectionClass() <add> { <add> $collection = Collection::wrap(Collection::make(['foo'])); <add> $this->assertEquals(['foo'], $collection->all()); <add> } <add> <add> public function testWrapWithCollectionSubclass() <add> { <add> $collection = TestCollectionSubclass::wrap(Collection::make(['foo'])); <add> $this->assertEquals(['foo'], $collection->all()); <add> $this->assertInstanceOf(TestCollectionSubclass::class, $collection); <add> } <add> <ide> public function testTimesMethod() <ide> { <ide> $two = Collection::times(2, function ($number) { <ide> public function __construct($value) <ide> $this->value = $value; <ide> } <ide> } <add> <add>class TestCollectionSubclass extends Collection <add>{ <add> // <add>}
2
Text
Text
add changelog for 1.2.16 and 1.3.0-beta.5
7227f1a47930a6af6b9e9fb37ee919257514bcd0
<ide><path>CHANGELOG.md <add><a name="1.3.0-beta.5"></a> <add># 1.3.0-beta.5 chimeric-glitterfication (2014-04-03) <add> <add> <add>## Bug Fixes <add> <add>- **$animate:** <add> - insert elements at the start of the parent container instead of at the end <add> ([1cb8584e](https://github.com/angular/angular.js/commit/1cb8584e8490ecdb1b410a8846c4478c6c2c0e53), <add> [#4934](https://github.com/angular/angular.js/issues/4934), [#6275](https://github.com/angular/angular.js/issues/6275)) <add> - ensure the CSS driver properly works with SVG elements <add> ([c67bd69c](https://github.com/angular/angular.js/commit/c67bd69c58812da82b1a3a31d430df7aad8a50a8), <add> [#6030](https://github.com/angular/angular.js/issues/6030)) <add>- **$parse:** mark constant unary minus expressions as constant <add> ([7914d346](https://github.com/angular/angular.js/commit/7914d3463b5ec560c616a0c9fd008bc0e3f7c786), <add> [#6932](https://github.com/angular/angular.js/issues/6932)) <add>- **Scope:** <add> - revert the `__proto__` cleanup as that could cause regressions <add> ([71c11e96](https://github.com/angular/angular.js/commit/71c11e96c64d5d4eb71f48c1eb778c2ba5c63377)) <add> - more scope clean up on $destroy to minimize leaks <add> ([d64d41ed](https://github.com/angular/angular.js/commit/d64d41ed992430a4fc89cd415c03acf8d56022e6), <add> [#6794](https://github.com/angular/angular.js/issues/6794), [#6856](https://github.com/angular/angular.js/issues/6856), [#6968](https://github.com/angular/angular.js/issues/6968)) <add>- **ngClass:** handle ngClassOdd/Even affecting the same classes <add> ([c9677920](https://github.com/angular/angular.js/commit/c9677920d462046710fc72ca422ab7400f551d2e), <add> [#5271](https://github.com/angular/angular.js/issues/5271)) <add> <add> <add>## Breaking Changes <add> <add>- **$animate:** due to [1cb8584e](https://github.com/angular/angular.js/commit/1cb8584e8490ecdb1b410a8846c4478c6c2c0e53), <add>`$animate` will no longer default the after parameter to the last element of the parent <add>container. Instead, when after is not specified, the new element will be inserted as the <add>first child of the parent container. <add> <add>To update existing code, change all instances of `$animate.enter()` or `$animate.move()` from: <add> <add>`$animate.enter(element, parent);` <add> <add>to: <add> <add>`$animate.enter(element, parent, angular.element(parent[0].lastChild));` <add> <add> <add><a name="1.2.16"></a> <add># 1.2.16 badger-enumeration (2014-04-03) <add> <add> <add>## Bug Fixes <add> <add>- **$animate:** <add> - prevent cancellation timestamp from being too far in the future <add> ([35d635cb](https://github.com/angular/angular.js/commit/35d635cbcbdc20f304781655f3563111afa6567f), <add> [#6748](https://github.com/angular/angular.js/issues/6748)) <add> - run CSS animations before JS animations to avoid style inheritance <add> ([0e5106ec](https://github.com/angular/angular.js/commit/0e5106ec2ccc8596c589b89074d3b27d27bf395a), <add> [#6675](https://github.com/angular/angular.js/issues/6675)) <add>- **$parse:** mark constant unary minus expressions as constant <add> ([6e420ff2](https://github.com/angular/angular.js/commit/6e420ff28d9b3e76ac2c3598bf3797540ef8a1d3), <add> [#6932](https://github.com/angular/angular.js/issues/6932)) <add>- **Scope:** <add> - more scope clean up on $destroy to minimize leaks <add> ([7e4e696e](https://github.com/angular/angular.js/commit/7e4e696ec3adf9d6fc77a7aa7e0909a9675fd43a), <add> [#6794](https://github.com/angular/angular.js/issues/6794), [#6856](https://github.com/angular/angular.js/issues/6856), [#6968](https://github.com/angular/angular.js/issues/6968)) <add> - aggressively clean up scope on $destroy to minimize leaks <add> ([8d4d437e](https://github.com/angular/angular.js/commit/8d4d437e8cd8d7cebab5d9ae5c8bcfeef2118ce9), <add> [#6794](https://github.com/angular/angular.js/issues/6794), [#6856](https://github.com/angular/angular.js/issues/6856)) <add>- **filter.ngdoc:** Check if "input" variable is defined <add> ([a275d539](https://github.com/angular/angular.js/commit/a275d539f9631d6ec64d03814b3b09420e6cf1ee), <add> [#6819](https://github.com/angular/angular.js/issues/6819)) <add>- **input:** don't perform HTML5 validation on updated model-value <add> ([b2363e31](https://github.com/angular/angular.js/commit/b2363e31023df8240113f68b4e01d942f8009b60), <add> [#6796](https://github.com/angular/angular.js/issues/6796), [#6806](https://github.com/angular/angular.js/issues/6806)) <add>- **ngClass:** handle ngClassOdd/Even affecting the same classes <add> ([55fe6d63](https://github.com/angular/angular.js/commit/55fe6d6331e501325c2658df8995dcc083fc4ffb), <add> [#5271](https://github.com/angular/angular.js/issues/5271)) <add> <add> <add>## Features <add> <add>- **$http:** add xhr statusText to completeRequest callback <add> ([32c09c1d](https://github.com/angular/angular.js/commit/32c09c1d195fcb98f6e29fc7e554a867f4762301), <add> [#2335](https://github.com/angular/angular.js/issues/2335), [#2665](https://github.com/angular/angular.js/issues/2665), [#6713](https://github.com/angular/angular.js/issues/6713)) <add> <add> <ide> <a name="1.3.0-beta.4"></a> <ide> # 1.3.0-beta.4 inconspicuous-deception (2014-03-28) <ide>
1
Javascript
Javascript
use webvr 1.1 view matrices correctly in vreffect
8d122e7777000ecb5988615a29b3045a91f1672e
<ide><path>examples/js/effects/VREffect.js <ide> THREE.VREffect = function ( renderer, onError ) { <ide> var eyeTranslationL = new THREE.Vector3(); <ide> var eyeTranslationR = new THREE.Vector3(); <ide> var renderRectL, renderRectR; <add> var headMatrix = new THREE.Matrix4(); <add> var eyeMatrixL = new THREE.Matrix4(); <add> var eyeMatrixR = new THREE.Matrix4(); <ide> <ide> var frameData = null; <ide> <ide> THREE.VREffect = function ( renderer, onError ) { <ide> <ide> } <ide> <del> var eyeParamsL = vrDisplay.getEyeParameters( 'left' ); <del> var eyeParamsR = vrDisplay.getEyeParameters( 'right' ); <del> <del> eyeTranslationL.fromArray( eyeParamsL.offset ); <del> eyeTranslationR.fromArray( eyeParamsR.offset ); <del> <ide> if ( Array.isArray( scene ) ) { <ide> <ide> console.warn( 'THREE.VREffect.render() no longer supports arrays. Use object.layers instead.' ); <ide> THREE.VREffect = function ( renderer, onError ) { <ide> cameraR.quaternion.copy( cameraL.quaternion ); <ide> cameraR.scale.copy( cameraL.scale ); <ide> <del> cameraL.translateOnAxis( eyeTranslationL, cameraL.scale.x ); <del> cameraR.translateOnAxis( eyeTranslationR, cameraR.scale.x ); <del> <ide> if ( vrDisplay.getFrameData ) { <ide> <ide> vrDisplay.depthNear = camera.near; <ide> THREE.VREffect = function ( renderer, onError ) { <ide> cameraL.projectionMatrix.elements = frameData.leftProjectionMatrix; <ide> cameraR.projectionMatrix.elements = frameData.rightProjectionMatrix; <ide> <add> getEyeMatrices( frameData ); <add> <add> cameraL.updateMatrix(); <add> cameraL.matrix.multiply( eyeMatrixL ); <add> cameraL.matrix.decompose( cameraL.position, cameraL.quaternion, cameraL.scale ); <add> <add> cameraR.updateMatrix(); <add> cameraR.matrix.multiply( eyeMatrixR ); <add> cameraR.matrix.decompose( cameraR.position, cameraR.quaternion, cameraR.scale ); <add> <ide> } else { <ide> <add> var eyeParamsL = vrDisplay.getEyeParameters( 'left' ); <add> var eyeParamsR = vrDisplay.getEyeParameters( 'right' ); <add> <ide> cameraL.projectionMatrix = fovToProjection( eyeParamsL.fieldOfView, true, camera.near, camera.far ); <ide> cameraR.projectionMatrix = fovToProjection( eyeParamsR.fieldOfView, true, camera.near, camera.far ); <ide> <add> eyeTranslationL.fromArray( eyeParamsL.offset ); <add> eyeTranslationR.fromArray( eyeParamsR.offset ); <add> <add> cameraL.translateOnAxis( eyeTranslationL, cameraL.scale.x ); <add> cameraR.translateOnAxis( eyeTranslationR, cameraR.scale.x ); <add> <ide> } <ide> <ide> // render left eye <ide> THREE.VREffect = function ( renderer, onError ) { <ide> <ide> // <ide> <add> var poseOrientation = new THREE.Quaternion(); <add> var posePosition = new THREE.Vector3(); <add> <add> // Compute model matrices of the eyes with respect to the head. <add> function getEyeMatrices( frameData ) { <add> <add> // Compute the matrix for the position of the head based on the pose <add> if ( frameData.pose.orientation ) { <add> <add> poseOrientation.fromArray( frameData.pose.orientation ); <add> headMatrix.makeRotationFromQuaternion( poseOrientation ); <add> <add> } else { <add> <add> headMatrix.identity(); <add> <add> } <add> <add> if ( frameData.pose.position ) { <add> <add> posePosition.fromArray( frameData.pose.position ); <add> headMatrix.setPosition( posePosition ); <add> <add> } <add> <add> // The view matrix transforms vertices from sitting space to eye space. As such, the view matrix can be thought of as a product of two matrices: <add> // headToEyeMatrix * sittingToHeadMatrix <add> <add> // The headMatrix that we've calculated above is the model matrix of the head in sitting space, which is the inverse of sittingToHeadMatrix. <add> // So when we multiply the view matrix with headMatrix, we're left with headToEyeMatrix: <add> // viewMatrix * headMatrix = headToEyeMatrix * sittingToHeadMatrix * headMatrix = headToEyeMatrix <add> <add> eyeMatrixL.fromArray( frameData.leftViewMatrix ); <add> eyeMatrixL.multiply( headMatrix ); <add> eyeMatrixR.fromArray( frameData.rightViewMatrix ); <add> eyeMatrixR.multiply( headMatrix ); <add> <add> // The eye's model matrix in head space is the inverse of headToEyeMatrix we calculated above. <add> <add> eyeMatrixL.getInverse( eyeMatrixL ); <add> eyeMatrixR.getInverse( eyeMatrixR ); <add> <add> } <add> <ide> function fovToNDCScaleOffset( fov ) { <ide> <ide> var pxscale = 2.0 / ( fov.leftTan + fov.rightTan );
1
PHP
PHP
replace application contract with container
5c7ece78e17b581990838f9b7b81d7c311d2f0d8
<ide><path>src/Illuminate/Hashing/HashManager.php <ide> class HashManager extends Manager implements Hasher <ide> */ <ide> public function createBcryptDriver() <ide> { <del> return new BcryptHasher($this->app['config']['hashing.bcrypt'] ?? []); <add> return new BcryptHasher($this->config->get('hashing.bcrypt') ?? []); <ide> } <ide> <ide> /** <ide> public function createBcryptDriver() <ide> */ <ide> public function createArgonDriver() <ide> { <del> return new ArgonHasher($this->app['config']['hashing.argon'] ?? []); <add> return new ArgonHasher($this->config->get('hashing.argon') ?? []); <ide> } <ide> <ide> /** <ide> public function createArgonDriver() <ide> */ <ide> public function createArgon2idDriver() <ide> { <del> return new Argon2IdHasher($this->app['config']['hashing.argon'] ?? []); <add> return new Argon2IdHasher($this->config->get('hashing.argon') ?? []); <ide> } <ide> <ide> /** <ide> public function needsRehash($hashedValue, array $options = []) <ide> */ <ide> public function getDefaultDriver() <ide> { <del> return $this->app['config']['hashing.driver'] ?? 'bcrypt'; <add> return $this->config->get('hashing.driver', 'bcrypt'); <ide> } <ide> } <ide><path>src/Illuminate/Mail/TransportManager.php <ide> class TransportManager extends Manager <ide> */ <ide> protected function createSmtpDriver() <ide> { <del> $config = $this->app->make('config')->get('mail'); <add> $config = $this->config->get('mail'); <ide> <ide> // The Swift SMTP transport instance will allow us to use any SMTP backend <ide> // for delivering mail such as Sendgrid, Amazon SES, or a custom server <ide> protected function configureSmtpDriver($transport, $config) <ide> */ <ide> protected function createSendmailDriver() <ide> { <del> return new SendmailTransport($this->app['config']['mail']['sendmail']); <add> return new SendmailTransport($this->config->get('mail.sendmail')); <ide> } <ide> <ide> /** <ide> protected function createSendmailDriver() <ide> */ <ide> protected function createSesDriver() <ide> { <del> $config = array_merge($this->app['config']->get('services.ses', []), [ <add> $config = array_merge($this->config->get('services.ses', []), [ <ide> 'version' => 'latest', 'service' => 'email', <ide> ]); <ide> <ide> protected function createMailDriver() <ide> */ <ide> protected function createMailgunDriver() <ide> { <del> $config = $this->app['config']->get('services.mailgun', []); <add> $config = $this->config->get('services.mailgun', []); <ide> <ide> return new MailgunTransport( <ide> $this->guzzle($config), <ide> protected function createMailgunDriver() <ide> protected function createPostmarkDriver() <ide> { <ide> return new PostmarkTransport( <del> $this->app['config']->get('services.postmark.token') <add> $this->config->get('services.postmark.token') <ide> ); <ide> } <ide> <ide> protected function createPostmarkDriver() <ide> */ <ide> protected function createLogDriver() <ide> { <del> $logger = $this->app->make(LoggerInterface::class); <add> $logger = $this->container->make(LoggerInterface::class); <ide> <ide> if ($logger instanceof LogManager) { <del> $logger = $logger->channel($this->app['config']['mail.log_channel']); <add> $logger = $logger->channel($this->config->get('mail.log_channel')); <ide> } <ide> <ide> return new LogTransport($logger); <ide> protected function guzzle($config) <ide> */ <ide> public function getDefaultDriver() <ide> { <del> return $this->app['config']['mail.driver']; <add> return $this->config->get('mail.driver'); <ide> } <ide> <ide> /** <ide> public function getDefaultDriver() <ide> */ <ide> public function setDefaultDriver($name) <ide> { <del> $this->app['config']['mail.driver'] = $name; <add> $this->config->set('mail.driver', $name); <ide> } <ide> } <ide><path>src/Illuminate/Notifications/ChannelManager.php <ide> class ChannelManager extends Manager implements DispatcherContract, FactoryContr <ide> public function send($notifiables, $notification) <ide> { <ide> return (new NotificationSender( <del> $this, $this->app->make(Bus::class), $this->app->make(Dispatcher::class), $this->locale) <add> $this, $this->container->make(Bus::class), $this->container->make(Dispatcher::class), $this->locale) <ide> )->send($notifiables, $notification); <ide> } <ide> <ide> public function send($notifiables, $notification) <ide> public function sendNow($notifiables, $notification, array $channels = null) <ide> { <ide> return (new NotificationSender( <del> $this, $this->app->make(Bus::class), $this->app->make(Dispatcher::class), $this->locale) <add> $this, $this->container->make(Bus::class), $this->container->make(Dispatcher::class), $this->locale) <ide> )->sendNow($notifiables, $notification, $channels); <ide> } <ide> <ide> public function channel($name = null) <ide> */ <ide> protected function createDatabaseDriver() <ide> { <del> return $this->app->make(Channels\DatabaseChannel::class); <add> return $this->container->make(Channels\DatabaseChannel::class); <ide> } <ide> <ide> /** <ide> protected function createDatabaseDriver() <ide> */ <ide> protected function createBroadcastDriver() <ide> { <del> return $this->app->make(Channels\BroadcastChannel::class); <add> return $this->container->make(Channels\BroadcastChannel::class); <ide> } <ide> <ide> /** <ide> protected function createBroadcastDriver() <ide> */ <ide> protected function createMailDriver() <ide> { <del> return $this->app->make(Channels\MailChannel::class); <add> return $this->container->make(Channels\MailChannel::class); <ide> } <ide> <ide> /** <ide> protected function createDriver($driver) <ide> return parent::createDriver($driver); <ide> } catch (InvalidArgumentException $e) { <ide> if (class_exists($driver)) { <del> return $this->app->make($driver); <add> return $this->container->make($driver); <ide> } <ide> <ide> throw $e; <ide><path>src/Illuminate/Session/SessionManager.php <ide> protected function createArrayDriver() <ide> protected function createCookieDriver() <ide> { <ide> return $this->buildSession(new CookieSessionHandler( <del> $this->app['cookie'], $this->app['config']['session.lifetime'] <add> $this->container->make('cookie'), $this->config->get('session.lifetime') <ide> )); <ide> } <ide> <ide> protected function createFileDriver() <ide> */ <ide> protected function createNativeDriver() <ide> { <del> $lifetime = $this->app['config']['session.lifetime']; <add> $lifetime = $this->config->get('session.lifetime'); <ide> <ide> return $this->buildSession(new FileSessionHandler( <del> $this->app['files'], $this->app['config']['session.files'], $lifetime <add> $this->container->make('files'), $this->config->get('session.files'), $lifetime <ide> )); <ide> } <ide> <ide> protected function createNativeDriver() <ide> */ <ide> protected function createDatabaseDriver() <ide> { <del> $table = $this->app['config']['session.table']; <add> $table = $this->config->get('session.table'); <ide> <del> $lifetime = $this->app['config']['session.lifetime']; <add> $lifetime = $this->config->get('session.lifetime'); <ide> <ide> return $this->buildSession(new DatabaseSessionHandler( <del> $this->getDatabaseConnection(), $table, $lifetime, $this->app <add> $this->getDatabaseConnection(), $table, $lifetime, $this->container <ide> )); <ide> } <ide> <ide> protected function createDatabaseDriver() <ide> */ <ide> protected function getDatabaseConnection() <ide> { <del> $connection = $this->app['config']['session.connection']; <add> $connection = $this->config->get('session.connection'); <ide> <del> return $this->app['db']->connection($connection); <add> return $this->container->make('db')->connection($connection); <ide> } <ide> <ide> /** <ide> protected function createRedisDriver() <ide> $handler = $this->createCacheHandler('redis'); <ide> <ide> $handler->getCache()->getStore()->setConnection( <del> $this->app['config']['session.connection'] <add> $this->config->get('session.connection') <ide> ); <ide> <ide> return $this->buildSession($handler); <ide> protected function createCacheBased($driver) <ide> */ <ide> protected function createCacheHandler($driver) <ide> { <del> $store = $this->app['config']->get('session.store') ?: $driver; <add> $store = $this->config->get('session.store') ?: $driver; <ide> <ide> return new CacheBasedSessionHandler( <del> clone $this->app['cache']->store($store), <del> $this->app['config']['session.lifetime'] <add> clone $this->container->make('cache')->store($store), <add> $this->config->get('session.lifetime') <ide> ); <ide> } <ide> <ide> protected function createCacheHandler($driver) <ide> */ <ide> protected function buildSession($handler) <ide> { <del> return $this->app['config']['session.encrypt'] <add> return $this->config->get('session.encrypt') <ide> ? $this->buildEncryptedSession($handler) <del> : new Store($this->app['config']['session.cookie'], $handler); <add> : new Store($this->config->get('session.cookie'), $handler); <ide> } <ide> <ide> /** <ide> protected function buildSession($handler) <ide> protected function buildEncryptedSession($handler) <ide> { <ide> return new EncryptedStore( <del> $this->app['config']['session.cookie'], $handler, $this->app['encrypter'] <add> $this->config->get('session.cookie'), $handler, $this->container['encrypter'] <ide> ); <ide> } <ide> <ide> protected function buildEncryptedSession($handler) <ide> */ <ide> public function getSessionConfig() <ide> { <del> return $this->app['config']['session']; <add> return $this->config->get('session'); <ide> } <ide> <ide> /** <ide> public function getSessionConfig() <ide> */ <ide> public function getDefaultDriver() <ide> { <del> return $this->app['config']['session.driver']; <add> return $this->config->get('session.driver'); <ide> } <ide> <ide> /** <ide> public function getDefaultDriver() <ide> */ <ide> public function setDefaultDriver($name) <ide> { <del> $this->app['config']['session.driver'] = $name; <add> $this->config->set('session.driver', $name); <ide> } <ide> } <ide><path>src/Illuminate/Support/Manager.php <ide> <ide> use Closure; <ide> use InvalidArgumentException; <add>use Illuminate\Contracts\Container\Container; <ide> <ide> abstract class Manager <ide> { <ide> /** <del> * The application instance. <add> * The container instance. <ide> * <del> * @var \Illuminate\Contracts\Container\Container|\Illuminate\Contracts\Foundation\Application <add> * @var \Illuminate\Contracts\Container\Container <ide> */ <del> protected $app; <add> protected $container; <add> <add> /** <add> * The config repository instance. <add> * <add> * @var \Illuminate\Contracts\Config\Repository <add> */ <add> protected $config; <ide> <ide> /** <ide> * The registered custom driver creators. <ide> abstract class Manager <ide> /** <ide> * Create a new manager instance. <ide> * <del> * @param \Illuminate\Contracts\Container\Container|\Illuminate\Contracts\Foundation\Application $app <add> * @param \Illuminate\Contracts\Container\Container $container <ide> * @return void <ide> */ <del> public function __construct($app) <add> public function __construct(Container $container) <ide> { <del> $this->app = $app; <add> $this->config = $container->make('config'); <add> $this->container = $container; <ide> } <ide> <ide> /** <ide> protected function createDriver($driver) <ide> */ <ide> protected function callCustomCreator($driver) <ide> { <del> return $this->customCreators[$driver]($this->app); <add> return $this->customCreators[$driver]($this->container); <ide> } <ide> <ide> /**
5
Text
Text
fix a typo
e0544300261bd6048089f887fdac3ff382da3966
<ide><path>readme.md <ide> Next.js is a minimalistic framework for server-rendered React applications. <ide> <ide> ## How to use <ide> <del>### Gettin Started <add>### Getting Started <add> <ide> A step by step interactive guide of next features is available at [learnnextjs.com](https://learnnextjs.com/) <ide> <ide> ### Setup
1
Mixed
Ruby
add `rfc3339` aliases to `xmlschema`
f0aeecda1450ba17701ccba68e5a796ce4ac4c3b
<ide><path>activesupport/CHANGELOG.md <add>* Add `rfc3339` aliases to `xmlschema` for `Time` and `ActiveSupport::TimeWithZone` <add> <add> For naming consistency when using the RFC 3339 profile of ISO 8601 in applications. <add> <add> *Andrew White* <add> <ide> * Add `Time.rfc3339` parsing method <ide> <ide> The `Time.xmlschema` and consequently its alias `iso8601` accepts timestamps <ide><path>activesupport/lib/active_support/core_ext/time/conversions.rb <ide> def to_formatted_s(format = :default) <ide> def formatted_offset(colon = true, alternate_utc_string = nil) <ide> utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon) <ide> end <add> <add> # Aliased to +xmlschema+ for compatibility with +DateTime+ <add> alias_method :rfc3339, :xmlschema <ide> end <ide><path>activesupport/lib/active_support/time_with_zone.rb <ide> def xmlschema(fraction_digits = 0) <ide> "#{time.strftime(PRECISIONS[fraction_digits.to_i])}#{formatted_offset(true, 'Z'.freeze)}" <ide> end <ide> alias_method :iso8601, :xmlschema <add> alias_method :rfc3339, :xmlschema <ide> <ide> # Coerces time to a string for JSON encoding. The default format is ISO 8601. <ide> # You can get %Y/%m/%d %H:%M:%S +offset style by setting <ide><path>activesupport/test/core_ext/time_ext_test.rb <ide> def test_custom_date_format <ide> Time::DATE_FORMATS.delete(:custom) <ide> end <ide> <add> def test_rfc3339_with_fractional_seconds <add> time = Time.new(1999, 12, 31, 19, 0, Rational(1, 8), -18000) <add> assert_equal "1999-12-31T19:00:00.125-05:00", time.rfc3339(3) <add> end <add> <ide> def test_to_date <ide> assert_equal Date.new(2005, 2, 21), Time.local(2005, 2, 21, 17, 44, 30).to_date <ide> end <ide><path>activesupport/test/core_ext/time_with_zone_test.rb <ide> def test_xmlschema_with_nil_fractional_seconds <ide> assert_equal "1999-12-31T19:00:00-05:00", @twz.xmlschema(nil) <ide> end <ide> <add> def test_iso8601_with_fractional_seconds <add> @twz += Rational(1, 8) <add> assert_equal "1999-12-31T19:00:00.125-05:00", @twz.iso8601(3) <add> end <add> <add> def test_rfc3339_with_fractional_seconds <add> @twz += Rational(1, 8) <add> assert_equal "1999-12-31T19:00:00.125-05:00", @twz.rfc3339(3) <add> end <add> <ide> def test_to_yaml <ide> yaml = <<-EOF.strip_heredoc <ide> --- !ruby/object:ActiveSupport::TimeWithZone
5
Python
Python
improve changes with upstream's advices
efe26e3a3281c4663a5e500f764fb9a7068049cd
<ide><path>mkdocs.py <ide> import shutil <ide> import sys <ide> <del>root_dir = os.path.abspath(os.path.split(__file__)[0]) <add>root_dir = os.path.abspath(os.path.dirname(__file__)) <ide> docs_dir = os.path.join(root_dir, 'docs') <ide> html_dir = os.path.join(root_dir, 'html') <ide> <ide> <ide> content = markdown.markdown(text, ['headerid']) <ide> <del> build_dir = os.path.join(html_dir, dirpath.partition(docs_dir)[2].lstrip("/")) <add> category_dir = dirpath.replace(docs_dir, '').lstrip(os.path.sep) <add> build_dir = os.path.join(html_dir, category_dir) <ide> build_file = os.path.join(build_dir, filename[:-3] + '.html') <ide> <ide> if not os.path.exists(build_dir):
1
Javascript
Javascript
convert `src/core/ps_parser.js` to use es6 classes
a963d139dc192a1bc7e3081cd68301880f0b07ee
<ide><path>src/core/ps_parser.js <ide> * limitations under the License. <ide> */ <ide> <del>import { FormatError, isSpace } from '../shared/util'; <add>import { FormatError, isSpace, shadow } from '../shared/util'; <ide> import { EOF } from './primitives'; <ide> <del>var PostScriptParser = (function PostScriptParserClosure() { <del> function PostScriptParser(lexer) { <add>class PostScriptParser { <add> constructor(lexer) { <ide> this.lexer = lexer; <ide> this.operators = []; <ide> this.token = null; <ide> this.prev = null; <ide> } <del> PostScriptParser.prototype = { <del> nextToken: function PostScriptParser_nextToken() { <del> this.prev = this.token; <del> this.token = this.lexer.getToken(); <del> }, <del> accept: function PostScriptParser_accept(type) { <del> if (this.token.type === type) { <del> this.nextToken(); <del> return true; <del> } <del> return false; <del> }, <del> expect: function PostScriptParser_expect(type) { <del> if (this.accept(type)) { <del> return true; <del> } <del> throw new FormatError( <del> `Unexpected symbol: found ${this.token.type} expected ${type}.`); <del> }, <del> parse: function PostScriptParser_parse() { <add> <add> nextToken() { <add> this.prev = this.token; <add> this.token = this.lexer.getToken(); <add> } <add> <add> accept(type) { <add> if (this.token.type === type) { <ide> this.nextToken(); <del> this.expect(PostScriptTokenTypes.LBRACE); <del> this.parseBlock(); <del> this.expect(PostScriptTokenTypes.RBRACE); <del> return this.operators; <del> }, <del> parseBlock: function PostScriptParser_parseBlock() { <del> while (true) { <del> if (this.accept(PostScriptTokenTypes.NUMBER)) { <del> this.operators.push(this.prev.value); <del> } else if (this.accept(PostScriptTokenTypes.OPERATOR)) { <del> this.operators.push(this.prev.value); <del> } else if (this.accept(PostScriptTokenTypes.LBRACE)) { <del> this.parseCondition(); <del> } else { <del> return; <del> } <del> } <del> }, <del> parseCondition: function PostScriptParser_parseCondition() { <del> // Add two place holders that will be updated later <del> var conditionLocation = this.operators.length; <del> this.operators.push(null, null); <add> return true; <add> } <add> return false; <add> } <ide> <del> this.parseBlock(); <del> this.expect(PostScriptTokenTypes.RBRACE); <del> if (this.accept(PostScriptTokenTypes.IF)) { <del> // The true block is right after the 'if' so it just falls through on <del> // true else it jumps and skips the true block. <del> this.operators[conditionLocation] = this.operators.length; <del> this.operators[conditionLocation + 1] = 'jz'; <add> expect(type) { <add> if (this.accept(type)) { <add> return true; <add> } <add> throw new FormatError( <add> `Unexpected symbol: found ${this.token.type} expected ${type}.`); <add> } <add> <add> parse() { <add> this.nextToken(); <add> this.expect(PostScriptTokenTypes.LBRACE); <add> this.parseBlock(); <add> this.expect(PostScriptTokenTypes.RBRACE); <add> return this.operators; <add> } <add> <add> parseBlock() { <add> while (true) { <add> if (this.accept(PostScriptTokenTypes.NUMBER)) { <add> this.operators.push(this.prev.value); <add> } else if (this.accept(PostScriptTokenTypes.OPERATOR)) { <add> this.operators.push(this.prev.value); <ide> } else if (this.accept(PostScriptTokenTypes.LBRACE)) { <del> var jumpLocation = this.operators.length; <del> this.operators.push(null, null); <del> var endOfTrue = this.operators.length; <del> this.parseBlock(); <del> this.expect(PostScriptTokenTypes.RBRACE); <del> this.expect(PostScriptTokenTypes.IFELSE); <del> // The jump is added at the end of the true block to skip the false <del> // block. <del> this.operators[jumpLocation] = this.operators.length; <del> this.operators[jumpLocation + 1] = 'j'; <del> <del> this.operators[conditionLocation] = endOfTrue; <del> this.operators[conditionLocation + 1] = 'jz'; <add> this.parseCondition(); <ide> } else { <del> throw new FormatError('PS Function: error parsing conditional.'); <add> return; <ide> } <del> }, <del> }; <del> return PostScriptParser; <del>})(); <add> } <add> } <ide> <del>var PostScriptTokenTypes = { <add> parseCondition() { <add> // Add two place holders that will be updated later <add> const conditionLocation = this.operators.length; <add> this.operators.push(null, null); <add> <add> this.parseBlock(); <add> this.expect(PostScriptTokenTypes.RBRACE); <add> if (this.accept(PostScriptTokenTypes.IF)) { <add> // The true block is right after the 'if' so it just falls through on true <add> // else it jumps and skips the true block. <add> this.operators[conditionLocation] = this.operators.length; <add> this.operators[conditionLocation + 1] = 'jz'; <add> } else if (this.accept(PostScriptTokenTypes.LBRACE)) { <add> const jumpLocation = this.operators.length; <add> this.operators.push(null, null); <add> const endOfTrue = this.operators.length; <add> this.parseBlock(); <add> this.expect(PostScriptTokenTypes.RBRACE); <add> this.expect(PostScriptTokenTypes.IFELSE); <add> // The jump is added at the end of the true block to skip the false block. <add> this.operators[jumpLocation] = this.operators.length; <add> this.operators[jumpLocation + 1] = 'j'; <add> <add> this.operators[conditionLocation] = endOfTrue; <add> this.operators[conditionLocation + 1] = 'jz'; <add> } else { <add> throw new FormatError('PS Function: error parsing conditional.'); <add> } <add> } <add>} <add> <add>const PostScriptTokenTypes = { <ide> LBRACE: 0, <ide> RBRACE: 1, <ide> NUMBER: 2, <ide> var PostScriptTokenTypes = { <ide> IFELSE: 5, <ide> }; <ide> <del>var PostScriptToken = (function PostScriptTokenClosure() { <del> function PostScriptToken(type, value) { <del> this.type = type; <del> this.value = value; <del> } <add>const PostScriptToken = (function PostScriptTokenClosure() { <add> const opCache = Object.create(null); <ide> <del> var opCache = Object.create(null); <add> class PostScriptToken { <add> constructor(type, value) { <add> this.type = type; <add> this.value = value; <add> } <ide> <del> PostScriptToken.getOperator = function PostScriptToken_getOperator(op) { <del> var opValue = opCache[op]; <del> if (opValue) { <del> return opValue; <add> static getOperator(op) { <add> const opValue = opCache[op]; <add> if (opValue) { <add> return opValue; <add> } <add> return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, <add> op); <ide> } <del> return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op); <del> }; <ide> <del> PostScriptToken.LBRACE = new PostScriptToken(PostScriptTokenTypes.LBRACE, <del> '{'); <del> PostScriptToken.RBRACE = new PostScriptToken(PostScriptTokenTypes.RBRACE, <del> '}'); <del> PostScriptToken.IF = new PostScriptToken(PostScriptTokenTypes.IF, 'IF'); <del> PostScriptToken.IFELSE = new PostScriptToken(PostScriptTokenTypes.IFELSE, <del> 'IFELSE'); <add> static get LBRACE() { <add> return shadow(this, 'LBRACE', <add> new PostScriptToken(PostScriptTokenTypes.LBRACE, '{')); <add> } <add> <add> static get RBRACE() { <add> return shadow(this, 'RBRACE', <add> new PostScriptToken(PostScriptTokenTypes.RBRACE, '}')); <add> } <add> <add> static get IF() { <add> return shadow(this, 'IF', <add> new PostScriptToken(PostScriptTokenTypes.IF, 'IF')); <add> } <add> <add> static get IFELSE() { <add> return shadow(this, 'IFELSE', <add> new PostScriptToken(PostScriptTokenTypes.IFELSE, 'IFELSE')); <add> } <add> } <ide> return PostScriptToken; <ide> })(); <ide> <del>var PostScriptLexer = (function PostScriptLexerClosure() { <del> function PostScriptLexer(stream) { <add>class PostScriptLexer { <add> constructor(stream) { <ide> this.stream = stream; <ide> this.nextChar(); <ide> <ide> this.strBuf = []; <ide> } <del> PostScriptLexer.prototype = { <del> nextChar: function PostScriptLexer_nextChar() { <del> return (this.currentChar = this.stream.getByte()); <del> }, <del> getToken: function PostScriptLexer_getToken() { <del> var comment = false; <del> var ch = this.currentChar; <del> <del> // skip comments <del> while (true) { <del> if (ch < 0) { <del> return EOF; <del> } <ide> <del> if (comment) { <del> if (ch === 0x0A || ch === 0x0D) { <del> comment = false; <del> } <del> } else if (ch === 0x25) { // '%' <del> comment = true; <del> } else if (!isSpace(ch)) { <del> break; <del> } <del> ch = this.nextChar(); <del> } <del> switch (ch | 0) { <del> case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4' <del> case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9' <del> case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.' <del> return new PostScriptToken(PostScriptTokenTypes.NUMBER, <del> this.getNumber()); <del> case 0x7B: // '{' <del> this.nextChar(); <del> return PostScriptToken.LBRACE; <del> case 0x7D: // '}' <del> this.nextChar(); <del> return PostScriptToken.RBRACE; <del> } <del> // operator <del> var strBuf = this.strBuf; <del> strBuf.length = 0; <del> strBuf[0] = String.fromCharCode(ch); <add> nextChar() { <add> return (this.currentChar = this.stream.getByte()); <add> } <ide> <del> while ((ch = this.nextChar()) >= 0 && // and 'A'-'Z', 'a'-'z' <del> ((ch >= 0x41 && ch <= 0x5A) || (ch >= 0x61 && ch <= 0x7A))) { <del> strBuf.push(String.fromCharCode(ch)); <del> } <del> var str = strBuf.join(''); <del> switch (str.toLowerCase()) { <del> case 'if': <del> return PostScriptToken.IF; <del> case 'ifelse': <del> return PostScriptToken.IFELSE; <del> default: <del> return PostScriptToken.getOperator(str); <add> getToken() { <add> let comment = false; <add> let ch = this.currentChar; <add> <add> // skip comments <add> while (true) { <add> if (ch < 0) { <add> return EOF; <ide> } <del> }, <del> getNumber: function PostScriptLexer_getNumber() { <del> var ch = this.currentChar; <del> var strBuf = this.strBuf; <del> strBuf.length = 0; <del> strBuf[0] = String.fromCharCode(ch); <del> <del> while ((ch = this.nextChar()) >= 0) { <del> if ((ch >= 0x30 && ch <= 0x39) || // '0'-'9' <del> ch === 0x2D || ch === 0x2E) { // '-', '.' <del> strBuf.push(String.fromCharCode(ch)); <del> } else { <del> break; <add> <add> if (comment) { <add> if (ch === 0x0A || ch === 0x0D) { <add> comment = false; <ide> } <add> } else if (ch === 0x25) { // '%' <add> comment = true; <add> } else if (!isSpace(ch)) { <add> break; <ide> } <del> var value = parseFloat(strBuf.join('')); <del> if (isNaN(value)) { <del> throw new FormatError(`Invalid floating point number: ${value}`); <add> ch = this.nextChar(); <add> } <add> switch (ch | 0) { <add> case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4' <add> case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9' <add> case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.' <add> return new PostScriptToken(PostScriptTokenTypes.NUMBER, <add> this.getNumber()); <add> case 0x7B: // '{' <add> this.nextChar(); <add> return PostScriptToken.LBRACE; <add> case 0x7D: // '}' <add> this.nextChar(); <add> return PostScriptToken.RBRACE; <add> } <add> // operator <add> const strBuf = this.strBuf; <add> strBuf.length = 0; <add> strBuf[0] = String.fromCharCode(ch); <add> <add> while ((ch = this.nextChar()) >= 0 && // and 'A'-'Z', 'a'-'z' <add> ((ch >= 0x41 && ch <= 0x5A) || (ch >= 0x61 && ch <= 0x7A))) { <add> strBuf.push(String.fromCharCode(ch)); <add> } <add> const str = strBuf.join(''); <add> switch (str.toLowerCase()) { <add> case 'if': <add> return PostScriptToken.IF; <add> case 'ifelse': <add> return PostScriptToken.IFELSE; <add> default: <add> return PostScriptToken.getOperator(str); <add> } <add> } <add> <add> getNumber() { <add> let ch = this.currentChar; <add> const strBuf = this.strBuf; <add> strBuf.length = 0; <add> strBuf[0] = String.fromCharCode(ch); <add> <add> while ((ch = this.nextChar()) >= 0) { <add> if ((ch >= 0x30 && ch <= 0x39) || // '0'-'9' <add> ch === 0x2D || ch === 0x2E) { // '-', '.' <add> strBuf.push(String.fromCharCode(ch)); <add> } else { <add> break; <ide> } <del> return value; <del> }, <del> }; <del> return PostScriptLexer; <del>})(); <add> } <add> const value = parseFloat(strBuf.join('')); <add> if (isNaN(value)) { <add> throw new FormatError(`Invalid floating point number: ${value}`); <add> } <add> return value; <add> } <add>} <ide> <ide> export { <ide> PostScriptLexer,
1
Ruby
Ruby
use the type object for quoting pg ranges
02579b56bbe0de17ce8657f453ad4f02acc4ab84
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/cast.rb <del>module ActiveRecord <del> module ConnectionAdapters <del> module PostgreSQL <del> module Cast # :nodoc: <del> def range_to_string(object) # :nodoc: <del> from = object.begin.respond_to?(:infinite?) && object.begin.infinite? ? '' : object.begin <del> to = object.end.respond_to?(:infinite?) && object.end.infinite? ? '' : object.end <del> "[#{from},#{to}#{object.exclude_end? ? ')' : ']'}" <del> end <del> end <del> end <del> end <del>end <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/column.rb <del>require 'active_record/connection_adapters/postgresql/cast' <del> <ide> module ActiveRecord <ide> module ConnectionAdapters <ide> # PostgreSQL-specific extensions to column definitions in a table. <ide> class PostgreSQLColumn < Column #:nodoc: <del> extend PostgreSQL::Cast <del> <ide> attr_accessor :array <ide> <ide> def initialize(name, default, cast_type, sql_type = nil, null = true, default_function = nil) <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb <ide> def initialize(subtype, type) <ide> @type = type <ide> end <ide> <del> def extract_bounds(value) <del> from, to = value[1..-2].split(',') <del> { <del> from: (value[1] == ',' || from == '-infinity') ? @subtype.infinity(negative: true) : from, <del> to: (value[-2] == ',' || to == 'infinity') ? @subtype.infinity : to, <del> exclude_start: (value[0] == '('), <del> exclude_end: (value[-1] == ')') <del> } <del> end <del> <del> def infinity?(value) <del> value.respond_to?(:infinite?) && value.infinite? <del> end <del> <ide> def type_cast_for_schema(value) <ide> value.inspect.gsub('Infinity', '::Float::INFINITY') <ide> end <ide> <del> def type_cast_single(value) <del> infinity?(value) ? value : @subtype.type_cast_from_database(value) <del> end <del> <ide> def cast_value(value) <ide> return if value == 'empty' <ide> return value if value.is_a?(::Range) <ide> def cast_value(value) <ide> end <ide> ::Range.new(from, to, extracted[:exclude_end]) <ide> end <add> <add> def type_cast_for_database(value) <add> if value.is_a?(::Range) <add> from = type_cast_single_for_database(value.begin) <add> to = type_cast_single_for_database(value.end) <add> "[#{from},#{to}#{value.exclude_end? ? ')' : ']'}" <add> else <add> super <add> end <add> end <add> <add> private <add> <add> def type_cast_single(value) <add> infinity?(value) ? value : @subtype.type_cast_from_database(value) <add> end <add> <add> def type_cast_single_for_database(value) <add> infinity?(value) ? '' : @subtype.type_cast_for_database(value) <add> end <add> <add> def extract_bounds(value) <add> from, to = value[1..-2].split(',') <add> { <add> from: (value[1] == ',' || from == '-infinity') ? @subtype.infinity(negative: true) : from, <add> to: (value[-2] == ',' || to == 'infinity') ? @subtype.infinity : to, <add> exclude_start: (value[0] == '('), <add> exclude_end: (value[-1] == ')') <add> } <add> end <add> <add> def infinity?(value) <add> value.respond_to?(:infinite?) && value.infinite? <add> end <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb <ide> def quote(value, column = nil) #:nodoc: <ide> sql_type = type_to_sql(column.type, column.limit, column.precision, column.scale) <ide> <ide> case value <del> when Range <del> if /range$/ =~ sql_type <del> escaped = quote_string(PostgreSQLColumn.range_to_string(value)) <del> "'#{escaped}'::#{sql_type}" <del> else <del> super <del> end <ide> when Float <ide> if value.infinite? || value.nan? <ide> "'#{value.to_s}'" <ide> def type_cast(value, column) <ide> return super unless column <ide> <ide> case value <del> when Range <del> if /range$/ =~ column.sql_type <del> PostgreSQLColumn.range_to_string(value) <del> else <del> super <del> end <ide> when NilClass <ide> if column.array <ide> value <ide><path>activerecord/test/cases/adapters/postgresql/quoting_test.rb <ide> def test_quote_time_usec <ide> def test_quote_range <ide> range = "1,2]'; SELECT * FROM users; --".."a" <ide> c = PostgreSQLColumn.new(nil, nil, OID::Range.new(Type::Integer.new, :int8range)) <del> assert_equal "'[1,2]''; SELECT * FROM users; --,a]'::int8range", @conn.quote(range, c) <add> assert_equal "'[1,0]'", @conn.quote(range, c) <ide> end <ide> <ide> def test_quote_bit_string <ide><path>activerecord/test/cases/adapters/postgresql/range_test.rb <ide> def test_update_all_with_ranges <ide> end <ide> <ide> def test_ranges_correctly_escape_input <del> e = assert_raises(ActiveRecord::StatementInvalid) do <del> range = "1,2]'; SELECT * FROM users; --".."a" <del> PostgresqlRange.update_all(int8_range: range) <del> end <add> range = "-1,2]'; DROP TABLE postgresql_ranges; --".."a" <add> PostgresqlRange.update_all(int8_range: range) <ide> <del> assert e.message.starts_with?("PG::InvalidTextRepresentation") <add> assert_nothing_raised do <add> PostgresqlRange.first <add> end <ide> end <ide> <ide> private
6
Text
Text
fix typos in fundamentals article
23a43c854d5e8c2f76d8291d1f69ef43ca9831eb
<ide><path>threejs/lessons/threejs-fundamentals.md <ide> it as easy as possible to get 3D content on a webpage. <ide> <ide> Three.js is often confused with WebGL since more often than <ide> not, but not always, three.js uses WebGL to draw 3D. <del>[WebGL is a very low-level system that only draws points, lines, and triangles](https://webglfundamentals.org). <add>[WebGL is a very low-level system that only draws points, lines, and triangles](https://webglfundamentals.org). <ide> To do anything useful with WebGL generally requires quite a bit of <ide> code and that is where three.js comes in. It handles stuff <ide> like scenes, lights, shadows, materials, textures, 3d math, all things that you'd <ide> have to write yourself if you were to use WebGL directly. <ide> <ide> These tutorials assume you already know JavaScript and, for the <ide> most part they will use ES6 style. [See here for a <del>terse list of things you're expected to already know](threejs-prerequisites.html). <add>terse list of things you're expected to already know](threejs-prerequisites.html). <ide> Most browsers that support three.js are auto-updated so most users should <ide> be able to run this code. If you'd like to make this code run <ide> on really old browsers look into a transpiler like [Babel](http://babel.io). <ide> that can't run three.js. <ide> When learning most programming languages the first thing people <ide> do is make the computer print `"Hello World!"`. For 3D one <ide> of the most common first things to do is to make a 3D cube. <del>so let's start with "Hello Cube!" <add>So let's start with "Hello Cube!" <ide> <ide> The first thing we need is a `<canvas>` tag so <ide> <ide> and passing it the scene and the camera <ide> renderer.render(scene, camera); <ide> ``` <ide> <del>Here's a working exmaple <add>Here's a working example <ide> <ide> {{{example url="../threejs-fundamentals.html" }}} <ide>
1
Text
Text
remove broken links from react art readme
56e5288b042523729d5f8b84a3e569b0b96a329a
<ide><path>packages/react-art/README.md <ide> React ART is a JavaScript library for drawing vector graphics using [React](http <ide> It provides declarative and reactive bindings to the [ART library](https://github.com/sebmarkbage/art/). <ide> <ide> Using the same declarative API you can render the output to either Canvas, SVG or VML (IE8). <del> <del>The `examples` directory contains a simple example of using React ART; you can also test out the [art branch of the react-page project](https://github.com/facebook/react-page/tree/art). <del> <del>## Contribute <del> <del>To read more about the community and guidelines for submitting pull requests, please read the [Contributing document](CONTRIBUTING.md).
1
Text
Text
update russian translation
4b0b7ba567ce8460d56f4bfddb5a7b98bf691b20
<ide><path>guide/russian/php/constants/index.md <ide> localeTitle: Константы <ide> <ide> Константы - это тип переменной в PHP. Функция `define()` для установки константы принимает три аргумента - имя ключа, значение ключа и логическое (true или false), которое определяет, не является ли имя ключа нечувствительным к регистру (по умолчанию установлено false). Значение константы не может быть изменено после его установки. Он используется для значений, которые редко меняются (например, пароль базы данных или ключ api). <ide> <del>### Объем <add>### Область видимости <ide> <del>Важно знать, что в отличие от переменных константы ALWAYS имеют глобальную область видимости и могут быть доступны из любой функции в скрипте. <add>В отличие от переменных константы ВСЕГДА доступны из любой области видимости. Вы можете использовать константы в любом месте вашего скрипта, не обращая внимания на текущую область видимости. <ide> <del>### пример <add>### Пример <ide> <ide> ```PHP <ide> <?php <ide> define("freeCodeCamp", "Learn to code and help nonprofits", false); <ide> echo freeCodeCamp; <ide> ``` <ide> <del>**Выход:** <add>**Выведет:** <ide> <ide> ```text <ide> Learn to code and help nonprofits <ide> Learn to code and help nonprofits <ide> #### Дополнительная информация: <ide> <ide> * [Руководство по константам php.net](https://secure.php.net/manual/en/language.constants.php) <del>* [Руководство по php.net define ()](https://secure.php.net/manual/en/function.define.php) <ide>\ No newline at end of file <add>* [Руководство по php.net define()](https://secure.php.net/manual/en/function.define.php)
1
Javascript
Javascript
fix challenge ordering
382393e1f2adbd8db9390930a66d3a422505bc2a
<ide><path>index.js <ide> Challenge.destroyAll(function(err, info) { <ide> .toLowerCase() <ide> .replace(/\:/g, '') <ide> .replace(/\s/g, '-'); <del> challenge.order = +('' + order + (index + 1)); <add> challenge.order = order; <add> challenge.suborder = index + 1; <ide> challenge.block = block; <ide> <ide> return challenge;
1
Mixed
Text
fix some typos!
cf0dd4a71da69cf7f39da59a992f04b3c7bcbb19
<ide><path>actionview/CHANGELOG.md <ide> * ActionView::Template.finalize_compiled_template_methods is deprecated with <ide> no replacement. <ide> <add> *tenderlove* <add> <ide> * config.action_view.finalize_compiled_template_methods is deprecated with <ide> no replacement. <ide> <add> *tenderlove* <add> <ide> * Ensure unique DOM IDs for collection inputs with float values. <ide> Fixes #34974 <ide> <ide><path>actionview/lib/action_view/base.rb <ide> def compiled_method_container <ide> raise NotImplementedError, <<~msg <ide> Subclasses of ActionView::Base must implement `compiled_method_container` <ide> or use the class method `with_empty_template_cache` for constructing <del> an ActionView::Base subclass thata has an empty cache. <add> an ActionView::Base subclass that has an empty cache. <ide> msg <ide> end <ide>
2
PHP
PHP
cover exception cases in config()/engine()
0cddc14415763b0a802d4168af86a74b8c60b03d
<ide><path>tests/TestCase/Cache/CacheTest.php <ide> public function testNullEngineWhenCacheDisable() <ide> $this->assertInstanceOf('Cake\Cache\Engine\NullEngine', $result); <ide> } <ide> <add> /** <add> * Test configuring an invalid class fails <add> * <add> * @expectedException \RuntimeException <add> * @expectedExceptionMessage Cache engines must use Cake\Cache\CacheEngine <add> * @return void <add> */ <add> public function testConfigInvalidClassType() <add> { <add> Cache::config('tests', [ <add> 'className' => '\StdClass' <add> ]); <add> Cache::engine('tests'); <add> } <add> <add> /** <add> * Test engine init failing causes an error <add> * <add> * @expectedException \RuntimeException <add> * @expectedExceptionMessage not properly configured <add> * @return void <add> */ <add> public function testConfigFailedInit() <add> { <add> $mock = $this->getMockForAbstractClass('Cake\Cache\CacheEngine', [], '', true, true, true, ['init']); <add> $mock->method('init')->will($this->returnValue(false)); <add> Cache::config('tests', [ <add> 'engine' => $mock <add> ]); <add> Cache::engine('tests'); <add> } <add> <ide> /** <ide> * test configuring CacheEngines in App/libs <ide> *
1
Python
Python
use state in api consistently over status
8432fdc5f0ccc166af6065fc7904fc3afdbf2ebb
<ide><path>celery/backends/amqp.py <ide> def destination_for(self, task_id, request): <ide> return self.rkey(task_id), request.correlation_id or task_id <ide> return self.rkey(task_id), task_id <ide> <del> def store_result(self, task_id, result, status, <add> def store_result(self, task_id, result, state, <ide> traceback=None, request=None, **kwargs): <del> """Send task return value and status.""" <add> """Send task return value and state.""" <ide> routing_key, correlation_id = self.destination_for(task_id, request) <ide> if not routing_key: <ide> return <ide> with self.app.amqp.producer_pool.acquire(block=True) as producer: <ide> producer.publish( <del> {'task_id': task_id, 'status': status, <del> 'result': self.encode_result(result, status), <add> {'task_id': task_id, 'status': state, <add> 'result': self.encode_result(result, state), <ide> 'traceback': traceback, <ide> 'children': self.current_task_children(request)}, <ide> exchange=self.exchange, <ide><path>celery/backends/base.py <ide> def prepare_persistent(self, enabled=None): <ide> p = self.app.conf.result_persistent <ide> return self.persistent if p is None else p <ide> <del> def encode_result(self, result, status): <del> if status in self.EXCEPTION_STATES and isinstance(result, Exception): <add> def encode_result(self, result, state): <add> if state in self.EXCEPTION_STATES and isinstance(result, Exception): <ide> return self.prepare_exception(result) <ide> else: <ide> return self.prepare_value(result) <ide> <ide> def is_cached(self, task_id): <ide> return task_id in self._cache <ide> <del> def store_result(self, task_id, result, status, <add> def store_result(self, task_id, result, state, <ide> traceback=None, request=None, **kwargs): <ide> """Update task state and result.""" <del> result = self.encode_result(result, status) <del> self._store_result(task_id, result, status, traceback, <add> result = self.encode_result(result, state) <add> self._store_result(task_id, result, state, traceback, <ide> request=request, **kwargs) <ide> return result <ide> <ide> def forget(self, task_id): <ide> def _forget(self, task_id): <ide> raise NotImplementedError('backend does not implement forget.') <ide> <del> def get_status(self, task_id): <del> """Get the status of a task.""" <add> def get_state(self, task_id): <add> """Get the state of a task.""" <ide> return self.get_task_meta(task_id)['status'] <add> get_status = get_state # XXX compat <ide> <ide> def get_traceback(self, task_id): <ide> """Get the traceback for a failed task.""" <ide> def get_many(self, task_ids, timeout=None, interval=0.5, no_ack=True, <ide> def _forget(self, task_id): <ide> self.delete(self.get_key_for_task(task_id)) <ide> <del> def _store_result(self, task_id, result, status, <add> def _store_result(self, task_id, result, state, <ide> traceback=None, request=None, **kwargs): <del> meta = {'status': status, 'result': result, 'traceback': traceback, <add> meta = {'status': state, 'result': result, 'traceback': traceback, <ide> 'children': self.current_task_children(request)} <ide> self.set(self.get_key_for_task(task_id), self.encode(meta)) <ide> return result <ide> def _is_disabled(self, *args, **kwargs): <ide> raise NotImplementedError( <ide> 'No result backend configured. ' <ide> 'Please see the documentation for more information.') <del> wait_for = get_status = get_result = get_traceback = _is_disabled <del> get_many = _is_disabled <add> get_state = get_status = get_result = get_traceback = _is_disabled <add> wait_for = get_many = _is_disabled <ide><path>celery/backends/cassandra.py <ide> def _get_connection(self, write=False): <ide> self._session = None <ide> raise # we did fail after all - reraise <ide> <del> def _store_result(self, task_id, result, status, <add> def _store_result(self, task_id, result, state, <ide> traceback=None, request=None, **kwargs): <del> """Store return value and status of an executed task.""" <add> """Store return value and state of an executed task.""" <ide> self._get_connection(write=True) <ide> <ide> self._session.execute(self._write_stmt, ( <ide> task_id, <del> status, <add> state, <ide> buf_t(self.encode(result)), <ide> self.app.now(), <ide> buf_t(self.encode(traceback)), <ide><path>celery/backends/database/__init__.py <ide> def ResultSession(self, session_manager=SessionManager()): <ide> ) <ide> <ide> @retry <del> def _store_result(self, task_id, result, status, <add> def _store_result(self, task_id, result, state, <ide> traceback=None, max_retries=3, **kwargs): <del> """Store return value and status of an executed task.""" <add> """Store return value and state of an executed task.""" <ide> session = self.ResultSession() <ide> with session_cleanup(session): <ide> task = list(session.query(Task).filter(Task.task_id == task_id)) <ide> def _store_result(self, task_id, result, status, <ide> session.add(task) <ide> session.flush() <ide> task.result = result <del> task.status = status <add> task.status = state <ide> task.traceback = traceback <ide> session.commit() <ide> return result <ide><path>celery/backends/mongodb.py <ide> def decode(self, data): <ide> return data <ide> return super(MongoBackend, self).decode(data) <ide> <del> def _store_result(self, task_id, result, status, <add> def _store_result(self, task_id, result, state, <ide> traceback=None, request=None, **kwargs): <del> """Store return value and status of an executed task.""" <add> """Store return value and state of an executed task.""" <ide> <ide> meta = {'_id': task_id, <del> 'status': status, <add> 'status': state, <ide> 'result': self.encode(result), <ide> 'date_done': datetime.utcnow(), <ide> 'traceback': self.encode(traceback), <ide><path>celery/contrib/abortable.py <ide> def abort(self): <ide> <ide> """ <ide> # TODO: store_result requires all four arguments to be set, <del> # but only status should be updated here <add> # but only state should be updated here <ide> return self.backend.store_result(self.id, result=None, <del> status=ABORTED, traceback=None) <add> state=ABORTED, traceback=None) <ide> <ide> <ide> class AbortableTask(Task): <ide><path>celery/result.py <ide> def get(self, timeout=None, propagate=True, interval=0.5, <ide> ) <ide> if meta: <ide> self._maybe_set_cache(meta) <del> status = meta['status'] <del> if status in PROPAGATE_STATES and propagate: <add> state = meta['status'] <add> if state in PROPAGATE_STATES and propagate: <ide> raise meta['result'] <ide> if callback is not None: <ide> callback(self.id, meta['result']) <ide> def state(self): <ide> <ide> """ <ide> return self._get_task_meta()['status'] <del> status = state <add> status = state # XXX compat <ide> <ide> @property <ide> def task_id(self): <ide><path>celery/tests/backends/test_amqp.py <ide> def test_mark_as_done(self): <ide> tid = uuid() <ide> <ide> tb1.mark_as_done(tid, 42) <del> self.assertEqual(tb2.get_status(tid), states.SUCCESS) <add> self.assertEqual(tb2.get_state(tid), states.SUCCESS) <ide> self.assertEqual(tb2.get_result(tid), 42) <ide> self.assertTrue(tb2._cache.get(tid)) <ide> self.assertTrue(tb2.get_result(tid), 42) <ide> def test_mark_as_failure(self): <ide> except KeyError as exception: <ide> einfo = ExceptionInfo() <ide> tb1.mark_as_failure(tid3, exception, traceback=einfo.traceback) <del> self.assertEqual(tb2.get_status(tid3), states.FAILURE) <add> self.assertEqual(tb2.get_state(tid3), states.FAILURE) <ide> self.assertIsInstance(tb2.get_result(tid3), KeyError) <ide> self.assertEqual(tb2.get_traceback(tid3), einfo.traceback) <ide> <ide><path>celery/tests/backends/test_base.py <ide> def test_get_store_delete_result(self): <ide> tid = uuid() <ide> self.b.mark_as_done(tid, 'Hello world') <ide> self.assertEqual(self.b.get_result(tid), 'Hello world') <del> self.assertEqual(self.b.get_status(tid), states.SUCCESS) <add> self.assertEqual(self.b.get_state(tid), states.SUCCESS) <ide> self.b.forget(tid) <del> self.assertEqual(self.b.get_status(tid), states.PENDING) <add> self.assertEqual(self.b.get_state(tid), states.PENDING) <ide> <ide> def test_strip_prefix(self): <ide> x = self.b.get_key_for_task('x1b34') <ide> def test_chord_apply_fallback(self): <ide> <ide> def test_get_missing_meta(self): <ide> self.assertIsNone(self.b.get_result('xxx-missing')) <del> self.assertEqual(self.b.get_status('xxx-missing'), states.PENDING) <add> self.assertEqual(self.b.get_state('xxx-missing'), states.PENDING) <ide> <ide> def test_save_restore_delete_group(self): <ide> tid = uuid() <ide> def test_store_result(self): <ide> <ide> def test_is_disabled(self): <ide> with self.assertRaises(NotImplementedError): <del> DisabledBackend(self.app).get_status('foo') <add> DisabledBackend(self.app).get_state('foo') <ide><path>celery/tests/backends/test_cache.py <ide> def test_no_backend(self): <ide> CacheBackend(backend=None, app=self.app) <ide> <ide> def test_mark_as_done(self): <del> self.assertEqual(self.tb.get_status(self.tid), states.PENDING) <add> self.assertEqual(self.tb.get_state(self.tid), states.PENDING) <ide> self.assertIsNone(self.tb.get_result(self.tid)) <ide> <ide> self.tb.mark_as_done(self.tid, 42) <del> self.assertEqual(self.tb.get_status(self.tid), states.SUCCESS) <add> self.assertEqual(self.tb.get_state(self.tid), states.SUCCESS) <ide> self.assertEqual(self.tb.get_result(self.tid), 42) <ide> <ide> def test_is_pickled(self): <ide> def test_mark_as_failure(self): <ide> raise KeyError('foo') <ide> except KeyError as exception: <ide> self.tb.mark_as_failure(self.tid, exception) <del> self.assertEqual(self.tb.get_status(self.tid), states.FAILURE) <add> self.assertEqual(self.tb.get_state(self.tid), states.FAILURE) <ide> self.assertIsInstance(self.tb.get_result(self.tid), KeyError) <ide> <ide> def test_apply_chord(self): <ide> def test_memcache_unicode_key(self): <ide> cache._imp = [None] <ide> task_id, result = string(uuid()), 42 <ide> b = cache.CacheBackend(backend='memcache', app=self.app) <del> b.store_result(task_id, result, status=states.SUCCESS) <add> b.store_result(task_id, result, state=states.SUCCESS) <ide> self.assertEqual(b.get_result(task_id), result) <ide> <ide> def test_memcache_bytes_key(self): <ide> def test_memcache_bytes_key(self): <ide> cache._imp = [None] <ide> task_id, result = str_to_bytes(uuid()), 42 <ide> b = cache.CacheBackend(backend='memcache', app=self.app) <del> b.store_result(task_id, result, status=states.SUCCESS) <add> b.store_result(task_id, result, state=states.SUCCESS) <ide> self.assertEqual(b.get_result(task_id), result) <ide> <ide> def test_pylibmc_unicode_key(self): <ide> def test_pylibmc_unicode_key(self): <ide> cache._imp = [None] <ide> task_id, result = string(uuid()), 42 <ide> b = cache.CacheBackend(backend='memcache', app=self.app) <del> b.store_result(task_id, result, status=states.SUCCESS) <add> b.store_result(task_id, result, state=states.SUCCESS) <ide> self.assertEqual(b.get_result(task_id), result) <ide> <ide> def test_pylibmc_bytes_key(self): <ide> def test_pylibmc_bytes_key(self): <ide> cache._imp = [None] <ide> task_id, result = str_to_bytes(uuid()), 42 <ide> b = cache.CacheBackend(backend='memcache', app=self.app) <del> b.store_result(task_id, result, status=states.SUCCESS) <add> b.store_result(task_id, result, state=states.SUCCESS) <ide> self.assertEqual(b.get_result(task_id), result) <ide><path>celery/tests/backends/test_database.py <ide> def test_missing_dburi_raises_ImproperlyConfigured(self): <ide> <ide> def test_missing_task_id_is_PENDING(self): <ide> tb = DatabaseBackend(self.uri, app=self.app) <del> self.assertEqual(tb.get_status('xxx-does-not-exist'), states.PENDING) <add> self.assertEqual(tb.get_state('xxx-does-not-exist'), states.PENDING) <ide> <ide> def test_missing_task_meta_is_dict_with_pending(self): <ide> tb = DatabaseBackend(self.uri, app=self.app) <ide> def test_mark_as_done(self): <ide> <ide> tid = uuid() <ide> <del> self.assertEqual(tb.get_status(tid), states.PENDING) <add> self.assertEqual(tb.get_state(tid), states.PENDING) <ide> self.assertIsNone(tb.get_result(tid)) <ide> <ide> tb.mark_as_done(tid, 42) <del> self.assertEqual(tb.get_status(tid), states.SUCCESS) <add> self.assertEqual(tb.get_state(tid), states.SUCCESS) <ide> self.assertEqual(tb.get_result(tid), 42) <ide> <ide> def test_is_pickled(self): <ide> def test_mark_as_started(self): <ide> tb = DatabaseBackend(self.uri, app=self.app) <ide> tid = uuid() <ide> tb.mark_as_started(tid) <del> self.assertEqual(tb.get_status(tid), states.STARTED) <add> self.assertEqual(tb.get_state(tid), states.STARTED) <ide> <ide> def test_mark_as_revoked(self): <ide> tb = DatabaseBackend(self.uri, app=self.app) <ide> tid = uuid() <ide> tb.mark_as_revoked(tid) <del> self.assertEqual(tb.get_status(tid), states.REVOKED) <add> self.assertEqual(tb.get_state(tid), states.REVOKED) <ide> <ide> def test_mark_as_retry(self): <ide> tb = DatabaseBackend(self.uri, app=self.app) <ide> def test_mark_as_retry(self): <ide> import traceback <ide> trace = '\n'.join(traceback.format_stack()) <ide> tb.mark_as_retry(tid, exception, traceback=trace) <del> self.assertEqual(tb.get_status(tid), states.RETRY) <add> self.assertEqual(tb.get_state(tid), states.RETRY) <ide> self.assertIsInstance(tb.get_result(tid), KeyError) <ide> self.assertEqual(tb.get_traceback(tid), trace) <ide> <ide> def test_mark_as_failure(self): <ide> import traceback <ide> trace = '\n'.join(traceback.format_stack()) <ide> tb.mark_as_failure(tid3, exception, traceback=trace) <del> self.assertEqual(tb.get_status(tid3), states.FAILURE) <add> self.assertEqual(tb.get_state(tid3), states.FAILURE) <ide> self.assertIsInstance(tb.get_result(tid3), KeyError) <ide> self.assertEqual(tb.get_traceback(tid3), trace) <ide> <ide><path>celery/tests/backends/test_filesystem.py <ide> def test_path_is_incorrect(self): <ide> <ide> def test_missing_task_is_PENDING(self): <ide> tb = FilesystemBackend(app=self.app, url=self.url) <del> self.assertEqual(tb.get_status('xxx-does-not-exist'), states.PENDING) <add> self.assertEqual(tb.get_state('xxx-does-not-exist'), states.PENDING) <ide> <ide> def test_mark_as_done_writes_file(self): <ide> tb = FilesystemBackend(app=self.app, url=self.url) <ide> def test_done_task_is_SUCCESS(self): <ide> tb = FilesystemBackend(app=self.app, url=self.url) <ide> tid = uuid() <ide> tb.mark_as_done(tid, 42) <del> self.assertEqual(tb.get_status(tid), states.SUCCESS) <add> self.assertEqual(tb.get_state(tid), states.SUCCESS) <ide> <ide> def test_correct_result(self): <ide> data = {'foo': 'bar'} <ide><path>celery/tests/backends/test_redis.py <ide> def test_process_cleanup(self): <ide> def test_get_set_forget(self): <ide> tid = uuid() <ide> self.b.store_result(tid, 42, states.SUCCESS) <del> self.assertEqual(self.b.get_status(tid), states.SUCCESS) <add> self.assertEqual(self.b.get_state(tid), states.SUCCESS) <ide> self.assertEqual(self.b.get_result(tid), 42) <ide> self.b.forget(tid) <del> self.assertEqual(self.b.get_status(tid), states.PENDING) <add> self.assertEqual(self.b.get_state(tid), states.PENDING) <ide> <ide> def test_set_expires(self): <ide> self.b = self.Backend(expires=512, app=self.app)
13
Python
Python
convert openapi.autoschema methods to public api
b2497fc2456c607a3c639ed2355c28dac672a70f
<ide><path>rest_framework/schemas/openapi.py <ide> from django.db import models <ide> from django.utils.encoding import force_str <ide> <del>from rest_framework import exceptions, renderers, serializers <add>from rest_framework import ( <add> RemovedInDRF314Warning, exceptions, renderers, serializers <add>) <ide> from rest_framework.compat import uritemplate <ide> from rest_framework.fields import _UnvalidatedField, empty <ide> from rest_framework.settings import api_settings <ide> def get_operation(self, path, method): <ide> operation['description'] = self.get_description(path, method) <ide> <ide> parameters = [] <del> parameters += self._get_path_parameters(path, method) <del> parameters += self._get_pagination_parameters(path, method) <del> parameters += self._get_filter_parameters(path, method) <add> parameters += self.get_path_parameters(path, method) <add> parameters += self.get_pagination_parameters(path, method) <add> parameters += self.get_filter_parameters(path, method) <ide> operation['parameters'] = parameters <ide> <del> request_body = self._get_request_body(path, method) <add> request_body = self.get_request_body(path, method) <ide> if request_body: <ide> operation['requestBody'] = request_body <del> operation['responses'] = self._get_responses(path, method) <add> operation['responses'] = self.get_responses(path, method) <ide> operation['tags'] = self.get_tags(path, method) <ide> <ide> return operation <ide> def get_components(self, path, method): <ide> if method.lower() == 'delete': <ide> return {} <ide> <del> serializer = self._get_serializer(path, method) <add> serializer = self.get_serializer(path, method) <ide> <ide> if not isinstance(serializer, serializers.Serializer): <ide> return {} <ide> <ide> component_name = self.get_component_name(serializer) <ide> <del> content = self._map_serializer(serializer) <add> content = self.map_serializer(serializer) <ide> return {component_name: content} <ide> <ide> def _to_camel_case(self, snake_str): <ide> def get_operation_id_base(self, path, method, action): <ide> name = model.__name__ <ide> <ide> # Try with the serializer class name <del> elif self._get_serializer(path, method) is not None: <del> name = self._get_serializer(path, method).__class__.__name__ <add> elif self.get_serializer(path, method) is not None: <add> name = self.get_serializer(path, method).__class__.__name__ <ide> if name.endswith('Serializer'): <ide> name = name[:-10] <ide> <ide> def get_operation_id(self, path, method): <ide> <ide> return action + name <ide> <del> def _get_path_parameters(self, path, method): <add> def get_path_parameters(self, path, method): <ide> """ <ide> Return a list of parameters from templated path variables. <ide> """ <ide> def _get_path_parameters(self, path, method): <ide> <ide> return parameters <ide> <del> def _get_filter_parameters(self, path, method): <del> if not self._allows_filters(path, method): <add> def get_filter_parameters(self, path, method): <add> if not self.allows_filters(path, method): <ide> return [] <ide> parameters = [] <ide> for filter_backend in self.view.filter_backends: <ide> parameters += filter_backend().get_schema_operation_parameters(self.view) <ide> return parameters <ide> <del> def _allows_filters(self, path, method): <add> def allows_filters(self, path, method): <ide> """ <ide> Determine whether to include filter Fields in schema. <ide> <ide> def _allows_filters(self, path, method): <ide> return self.view.action in ["list", "retrieve", "update", "partial_update", "destroy"] <ide> return method.lower() in ["get", "put", "patch", "delete"] <ide> <del> def _get_pagination_parameters(self, path, method): <add> def get_pagination_parameters(self, path, method): <ide> view = self.view <ide> <ide> if not is_list_view(path, method, view): <ide> return [] <ide> <del> paginator = self._get_paginator() <add> paginator = self.get_paginator() <ide> if not paginator: <ide> return [] <ide> <ide> return paginator.get_schema_operation_parameters(view) <ide> <del> def _map_choicefield(self, field): <add> def map_choicefield(self, field): <ide> choices = list(OrderedDict.fromkeys(field.choices)) # preserve order and remove duplicates <ide> if all(isinstance(choice, bool) for choice in choices): <ide> type = 'boolean' <ide> def _map_choicefield(self, field): <ide> mapping['type'] = type <ide> return mapping <ide> <del> def _map_field(self, field): <add> def map_field(self, field): <ide> <ide> # Nested Serializers, `many` or not. <ide> if isinstance(field, serializers.ListSerializer): <ide> return { <ide> 'type': 'array', <del> 'items': self._map_serializer(field.child) <add> 'items': self.map_serializer(field.child) <ide> } <ide> if isinstance(field, serializers.Serializer): <del> data = self._map_serializer(field) <add> data = self.map_serializer(field) <ide> data['type'] = 'object' <ide> return data <ide> <ide> # Related fields. <ide> if isinstance(field, serializers.ManyRelatedField): <ide> return { <ide> 'type': 'array', <del> 'items': self._map_field(field.child_relation) <add> 'items': self.map_field(field.child_relation) <ide> } <ide> if isinstance(field, serializers.PrimaryKeyRelatedField): <ide> model = getattr(field.queryset, 'model', None) <ide> def _map_field(self, field): <ide> if isinstance(field, serializers.MultipleChoiceField): <ide> return { <ide> 'type': 'array', <del> 'items': self._map_choicefield(field) <add> 'items': self.map_choicefield(field) <ide> } <ide> <ide> if isinstance(field, serializers.ChoiceField): <del> return self._map_choicefield(field) <add> return self.map_choicefield(field) <ide> <ide> # ListField. <ide> if isinstance(field, serializers.ListField): <ide> def _map_field(self, field): <ide> 'items': {}, <ide> } <ide> if not isinstance(field.child, _UnvalidatedField): <del> mapping['items'] = self._map_field(field.child) <add> mapping['items'] = self.map_field(field.child) <ide> return mapping <ide> <ide> # DateField and DateTimeField type is string <ide> def _map_min_max(self, field, content): <ide> if field.min_value: <ide> content['minimum'] = field.min_value <ide> <del> def _map_serializer(self, serializer): <add> def map_serializer(self, serializer): <ide> # Assuming we have a valid serializer instance. <ide> required = [] <ide> properties = {} <ide> def _map_serializer(self, serializer): <ide> if field.required: <ide> required.append(field.field_name) <ide> <del> schema = self._map_field(field) <add> schema = self.map_field(field) <ide> if field.read_only: <ide> schema['readOnly'] = True <ide> if field.write_only: <ide> def _map_serializer(self, serializer): <ide> schema['default'] = field.default <ide> if field.help_text: <ide> schema['description'] = str(field.help_text) <del> self._map_field_validators(field, schema) <add> self.map_field_validators(field, schema) <ide> <ide> properties[field.field_name] = schema <ide> <ide> def _map_serializer(self, serializer): <ide> <ide> return result <ide> <del> def _map_field_validators(self, field, schema): <add> def map_field_validators(self, field, schema): <ide> """ <ide> map field validators <ide> """ <ide> def _map_field_validators(self, field, schema): <ide> schema['maximum'] = int(digits * '9') + 1 <ide> schema['minimum'] = -schema['maximum'] <ide> <del> def _get_paginator(self): <add> def get_paginator(self): <ide> pagination_class = getattr(self.view, 'pagination_class', None) <ide> if pagination_class: <ide> return pagination_class() <ide> def map_renderers(self, path, method): <ide> media_types.append(renderer.media_type) <ide> return media_types <ide> <del> def _get_serializer(self, path, method): <add> def get_serializer(self, path, method): <ide> view = self.view <ide> <ide> if not hasattr(view, 'get_serializer'): <ide> def _get_serializer(self, path, method): <ide> def _get_reference(self, serializer): <ide> return {'$ref': '#/components/schemas/{}'.format(self.get_component_name(serializer))} <ide> <del> def _get_request_body(self, path, method): <add> def get_request_body(self, path, method): <ide> if method not in ('PUT', 'PATCH', 'POST'): <ide> return {} <ide> <ide> self.request_media_types = self.map_parsers(path, method) <ide> <del> serializer = self._get_serializer(path, method) <add> serializer = self.get_serializer(path, method) <ide> <ide> if not isinstance(serializer, serializers.Serializer): <ide> item_schema = {} <ide> def _get_request_body(self, path, method): <ide> } <ide> } <ide> <del> def _get_responses(self, path, method): <del> # TODO: Handle multiple codes and pagination classes. <add> def get_responses(self, path, method): <ide> if method == 'DELETE': <ide> return { <ide> '204': { <ide> def _get_responses(self, path, method): <ide> <ide> self.response_media_types = self.map_renderers(path, method) <ide> <del> serializer = self._get_serializer(path, method) <add> serializer = self.get_serializer(path, method) <ide> <ide> if not isinstance(serializer, serializers.Serializer): <ide> item_schema = {} <ide> def _get_responses(self, path, method): <ide> 'type': 'array', <ide> 'items': item_schema, <ide> } <del> paginator = self._get_paginator() <add> paginator = self.get_paginator() <ide> if paginator: <ide> response_schema = paginator.get_paginated_response_schema(response_schema) <ide> else: <ide> def get_tags(self, path, method): <ide> path = path[1:] <ide> <ide> return [path.split('/')[0].replace('_', '-')] <add> <add> def _get_path_parameters(self, path, method): <add> warnings.warn( <add> "Method `_get_path_parameters()` has been renamed to `get_path_parameters()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.get_path_parameters(path, method) <add> <add> def _get_filter_parameters(self, path, method): <add> warnings.warn( <add> "Method `_get_filter_parameters()` has been renamed to `get_filter_parameters()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.get_filter_parameters(path, method) <add> <add> def _get_responses(self, path, method): <add> warnings.warn( <add> "Method `_get_responses()` has been renamed to `get_responses()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.get_responses(path, method) <add> <add> def _get_request_body(self, path, method): <add> warnings.warn( <add> "Method `_get_request_body()` has been renamed to `get_request_body()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.get_request_body(path, method) <add> <add> def _get_serializer(self, path, method): <add> warnings.warn( <add> "Method `_get_serializer()` has been renamed to `get_serializer()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.get_serializer(path, method) <add> <add> def _get_paginator(self): <add> warnings.warn( <add> "Method `_get_paginator()` has been renamed to `get_paginator()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.get_paginator() <add> <add> def _map_field_validators(self, field, schema): <add> warnings.warn( <add> "Method `_map_field_validators()` has been renamed to `map_field_validators()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.map_field_validators(field, schema) <add> <add> def _map_serializer(self, serializer): <add> warnings.warn( <add> "Method `_map_serializer()` has been renamed to `map_serializer()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.map_serializer(serializer) <add> <add> def _map_field(self, field): <add> warnings.warn( <add> "Method `_map_field()` has been renamed to `map_field()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.map_field(field) <add> <add> def _map_choicefield(self, field): <add> warnings.warn( <add> "Method `_map_choicefield()` has been renamed to `map_choicefield()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.map_choicefield(field) <add> <add> def _get_pagination_parameters(self, path, method): <add> warnings.warn( <add> "Method `_get_pagination_parameters()` has been renamed to `get_pagination_parameters()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.get_pagination_parameters(path, method) <add> <add> def _allows_filters(self, path, method): <add> warnings.warn( <add> "Method `_allows_filters()` has been renamed to `allows_filters()`. " <add> "The old name will be removed in DRF v3.14.", <add> RemovedInDRF314Warning, stacklevel=2 <add> ) <add> return self.allows_filters(path, method) <ide><path>tests/schemas/test_openapi.py <ide> def test_list_field_mapping(self): <ide> ] <ide> for field, mapping in cases: <ide> with self.subTest(field=field): <del> assert inspector._map_field(field) == mapping <add> assert inspector.map_field(field) == mapping <ide> <ide> def test_lazy_string_field(self): <ide> class ItemSerializer(serializers.Serializer): <ide> text = serializers.CharField(help_text=_('lazy string')) <ide> <ide> inspector = AutoSchema() <ide> <del> data = inspector._map_serializer(ItemSerializer()) <add> data = inspector.map_serializer(ItemSerializer()) <ide> assert isinstance(data['properties']['text']['description'], str), "description must be str" <ide> <ide> def test_boolean_default_field(self): <ide> class Serializer(serializers.Serializer): <ide> <ide> inspector = AutoSchema() <ide> <del> data = inspector._map_serializer(Serializer()) <add> data = inspector.map_serializer(Serializer()) <ide> assert data['properties']['default_true']['default'] is True, "default must be true" <ide> assert data['properties']['default_false']['default'] is False, "default must be false" <ide> assert 'default' not in data['properties']['without_default'], "default must not be defined" <ide> class View(generics.GenericAPIView): <ide> inspector = AutoSchema() <ide> inspector.view = view <ide> <del> request_body = inspector._get_request_body(path, method) <add> request_body = inspector.get_request_body(path, method) <ide> print(request_body) <ide> assert request_body['content']['application/json']['schema']['$ref'] == '#/components/schemas/Item' <ide> <ide> class View(generics.GenericAPIView): <ide> inspector = AutoSchema() <ide> inspector.view = view <ide> <del> serializer = inspector._get_serializer(path, method) <add> serializer = inspector.get_serializer(path, method) <ide> <ide> with pytest.raises(Exception) as exc: <ide> inspector.get_component_name(serializer) <ide> class View(generics.GenericAPIView): <ide> # there should be no empty 'required' property, see #6834 <ide> assert 'required' not in component <ide> <del> for response in inspector._get_responses(path, method).values(): <add> for response in inspector.get_responses(path, method).values(): <ide> assert 'required' not in component <ide> <ide> def test_empty_required_with_patch_method(self): <ide> class View(generics.GenericAPIView): <ide> component = components['Item'] <ide> # there should be no empty 'required' property, see #6834 <ide> assert 'required' not in component <del> for response in inspector._get_responses(path, method).values(): <add> for response in inspector.get_responses(path, method).values(): <ide> assert 'required' not in component <ide> <ide> def test_response_body_generation(self): <ide> class View(generics.GenericAPIView): <ide> inspector = AutoSchema() <ide> inspector.view = view <ide> <del> responses = inspector._get_responses(path, method) <add> responses = inspector.get_responses(path, method) <ide> assert responses['201']['content']['application/json']['schema']['$ref'] == '#/components/schemas/Item' <ide> <ide> components = inspector.get_components(path, method) <ide> class View(generics.GenericAPIView): <ide> inspector = AutoSchema() <ide> inspector.view = view <ide> <del> responses = inspector._get_responses(path, method) <add> responses = inspector.get_responses(path, method) <ide> assert responses['201']['content']['application/json']['schema']['$ref'] == '#/components/schemas/Item' <ide> components = inspector.get_components(path, method) <ide> assert components['Item'] <ide> class View(generics.GenericAPIView): <ide> inspector = AutoSchema() <ide> inspector.view = view <ide> <del> responses = inspector._get_responses(path, method) <add> responses = inspector.get_responses(path, method) <ide> assert responses == { <ide> '200': { <ide> 'description': '', <ide> class View(generics.GenericAPIView): <ide> inspector = AutoSchema() <ide> inspector.view = view <ide> <del> responses = inspector._get_responses(path, method) <add> responses = inspector.get_responses(path, method) <ide> assert responses == { <ide> '200': { <ide> 'description': '', <ide> class View(generics.DestroyAPIView): <ide> inspector = AutoSchema() <ide> inspector.view = view <ide> <del> responses = inspector._get_responses(path, method) <add> responses = inspector.get_responses(path, method) <ide> assert responses == { <ide> '204': { <ide> 'description': '', <ide> class View(generics.CreateAPIView): <ide> inspector = AutoSchema() <ide> inspector.view = view <ide> <del> request_body = inspector._get_request_body(path, method) <add> request_body = inspector.get_request_body(path, method) <ide> <ide> assert len(request_body['content'].keys()) == 2 <ide> assert 'multipart/form-data' in request_body['content'] <ide> class View(generics.CreateAPIView): <ide> inspector = AutoSchema() <ide> inspector.view = view <ide> <del> responses = inspector._get_responses(path, method) <add> responses = inspector.get_responses(path, method) <ide> # TODO this should be changed once the multiple response <ide> # schema support is there <ide> success_response = responses['200'] <ide> class View(generics.GenericAPIView): <ide> inspector = AutoSchema() <ide> inspector.view = view <ide> <del> responses = inspector._get_responses(path, method) <add> responses = inspector.get_responses(path, method) <ide> assert responses == { <ide> '200': { <ide> 'description': '',
2
PHP
PHP
remove obsolete code
bf172272da78d9ef0ff3b6712c3ab7fe57df7c74
<ide><path>laravel/lang.php <del><?php namespace Laravel; use Closure; <add><?php namespace Laravel; <ide> <ide> class Lang { <ide>
1
Ruby
Ruby
handle additional use cases
504bdd2816815af45a62d2535265e3e41b4f61cb
<ide><path>Library/Homebrew/cask/dsl.rb <ide> class DSL <ide> :discontinued?, <ide> :livecheck, <ide> :livecheckable?, <add> :on_system_blocks_exist?, <ide> *ORDINARY_ARTIFACT_CLASSES.map(&:dsl_key), <ide> *ACTIVATABLE_ARTIFACT_CLASSES.map(&:dsl_key), <ide> *ARTIFACT_BLOCK_CLASSES.flat_map { |klass| [klass.dsl_key, klass.uninstall_dsl_key] }, <ide><path>Library/Homebrew/dev-cmd/bump-cask-pr.rb <ide> def bump_cask_pr <ide> odie "This cask's tap is not a Git repository!" unless cask.tap.git? <ide> <ide> new_version = args.version <del> new_version = :latest if ["latest", ":latest"].include?(new_version) <add> new_version = :latest if ["latest", ":latest"].include? new_version <ide> new_version = Cask::DSL::Version.new(new_version) if new_version.present? <ide> new_base_url = args.url <ide> new_hash = args.sha256 <ide> new_hash = :no_check if ["no_check", ":no_check"].include? new_hash <ide> <ide> if new_version.nil? && new_base_url.nil? && new_hash.nil? <del> raise UsageError, "No --version=/--url=/--sha256= argument specified!" <add> raise UsageError, "No `--version=`, `--url=` or `--sha256=` argument specified!" <ide> end <ide> <ide> old_version = cask.version <ide> def bump_cask_pr <ide> /version\s+#{old_version_regex}/m, <ide> "version #{new_version.latest? ? ":latest" : "\"#{new_version}\""}", <ide> ] <add> if new_version.latest? || new_hash == :no_check <add> opoo "Ignoring specified `--sha256=` argument." if new_hash.is_a? String <add> replacement_pairs << [/"#{old_hash}"/, ":no_check"] if old_hash != :no_check <add> elsif old_hash != :no_check <add> if new_hash.nil? || cask.languages.present? <add> if new_hash.present? && cask.languages.present? <add> opoo "Multiple hash replacements required; ignoring specified `--sha256=` argument." <add> end <add> tmp_contents = Utils::Inreplace.inreplace_pairs(cask.sourcefile_path, <add> replacement_pairs.uniq.compact, <add> read_only_run: true, <add> silent: true) <add> <add> tmp_cask = Cask::CaskLoader.load(tmp_contents) <add> tmp_config = tmp_cask.config <add> <add> [:arm, :intel].each do |arch| <add> Homebrew::SimulateSystem.arch = arch <add> <add> languages = cask.languages <add> languages = [nil] if languages.empty? <add> languages.each do |language| <add> new_hash_config = if language.blank? <add> tmp_config <add> else <add> tmp_config.merge(Cask::Config.new(explicit: { languages: [language] })) <add> end <add> <add> new_hash_cask = Cask::CaskLoader.load(tmp_contents) <add> new_hash_cask.config = new_hash_config <add> old_hash = new_hash_cask.sha256.to_s <add> <add> cask_download = Cask::Download.new(new_hash_cask, quarantine: true) <add> download = cask_download.fetch(verify_download_integrity: false) <add> Utils::Tar.validate_file(download) <add> <add> replacement_pairs << [new_hash_cask.sha256.to_s, download.sha256] <add> end <add> <add> Homebrew::SimulateSystem.clear <add> end <add> elsif new_hash.present? <add> opoo "Cask contains multiple hashes; only updating hash for current arch." if cask.on_system_blocks_exist? <add> replacement_pairs << [old_hash.to_s, new_hash] <add> end <add> end <ide> end <ide> <ide> if new_base_url.present? <ide> def bump_cask_pr <ide> ] <ide> end <ide> <del> if new_version.present? <del> if new_version.latest? <del> opoo "Ignoring specified `--sha256=` argument." if new_hash.present? <del> replacement_pairs << [old_hash, ":no_check"] <del> elsif old_hash != :no_check && (new_hash.nil? || cask.languages.present?) <del> tmp_contents = Utils::Inreplace.inreplace_pairs(cask.sourcefile_path, <del> replacement_pairs.uniq.compact, <del> read_only_run: true, <del> silent: true) <del> <del> tmp_cask = Cask::CaskLoader.load(tmp_contents) <del> tmp_config = tmp_cask.config <del> <del> [:arm, :intel].each do |arch| <del> Homebrew::SimulateSystem.arch = arch <del> <del> languages = cask.languages <del> languages = [nil] if languages.empty? <del> languages.each do |language| <del> new_hash_config = if language.blank? <del> tmp_config <del> else <del> tmp_config.merge(Cask::Config.new(explicit: { languages: [language] })) <del> end <del> <del> new_hash_cask = Cask::CaskLoader.load(tmp_contents) <del> new_hash_cask.config = new_hash_config <del> old_hash = new_hash_cask.sha256.to_s <del> <del> cask_download = Cask::Download.new(new_hash_cask, quarantine: true) <del> download = cask_download.fetch(verify_download_integrity: false) <del> Utils::Tar.validate_file(download) <del> <del> replacement_pairs << [new_hash_cask.sha256.to_s, download.sha256] <del> end <del> <del> Homebrew::SimulateSystem.clear <del> end <del> end <del> end <del> <ide> Utils::Inreplace.inreplace_pairs(cask.sourcefile_path, <ide> replacement_pairs.uniq.compact, <ide> read_only_run: args.dry_run?,
2
PHP
PHP
fix datetimetime breaking on timestamp values
28432272edbadd8cb01a74c71a35a264e7d62366
<ide><path>src/Database/Type/DateTimeType.php <ide> public function __construct($name = null) { <ide> /** <ide> * Convert DateTime instance into strings. <ide> * <del> * @param string|DateTime $value The value to convert. <add> * @param string|integer|DateTime $value The value to convert. <ide> * @param Driver $driver The driver instance to convert with. <ide> * @return string <ide> */ <ide> public function toDatabase($value, Driver $driver) { <ide> if ($value === null || is_string($value)) { <ide> return $value; <ide> } <add> if (is_int($value)) { <add> $value = new static::$dateTimeClass('@' . $value); <add> } <ide> return $value->format($this->_format); <ide> } <ide> <ide><path>tests/TestCase/Database/Type/DateTimeTypeTest.php <ide> public function testToDatabase() { <ide> $date = new Time('2013-08-12 15:16:17'); <ide> $result = $this->type->toDatabase($date, $this->driver); <ide> $this->assertEquals('2013-08-12 15:16:17', $result); <add> <add> $date = 1401906995; <add> $result = $this->type->toDatabase($date, $this->driver); <add> $this->assertEquals('2014-06-04 18:36:35', $result); <ide> } <ide> <ide> /**
2
PHP
PHP
include missing exception
a4a8b5c222d11b70ac53ffab7f99c54f0a318050
<ide><path>src/Core/ObjectRegistry.php <ide> abstract class ObjectRegistry implements Countable, IteratorAggregate <ide> * @param string $objectName The name/class of the object to load. <ide> * @param array $config Additional settings to use when loading the object. <ide> * @return mixed <add> * @throws \Exception If the class cannot be found. <ide> */ <ide> public function load($objectName, $config = []) <ide> {
1
Python
Python
fix siamese example
05e1d8e5f4bc3eab549fe386f4db24641acffa7b
<ide><path>examples/mnist_siamese_graph.py <ide> def euclidean_distance(vects): <ide> return K.sqrt(K.sum(K.square(x - y), axis=1, keepdims=True)) <ide> <ide> <add>def eucl_dist_output_shape(shapes): <add> shape1, shape2 = shapes <add> return shape1 <add> <add> <ide> def contrastive_loss(y_true, y_pred): <ide> '''Contrastive loss from Hadsell-et-al.'06 <ide> http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf <ide> def compute_accuracy(predictions, labels): <ide> processed_a = base_network(input_a) <ide> processed_b = base_network(input_b) <ide> <del>distance = Lambda(euclidean_distance)([processed_a, processed_b]) <add>distance = Lambda(euclidean_distance, output_shape=eucl_dist_output_shape)([processed_a, processed_b]) <ide> <ide> model = Model(input=[input_a, input_b], output=distance) <ide>
1
Javascript
Javascript
fix sprite raycast intersection distance
9d72e97f9d5e1bcffd14cb9ed0763be1260731e4
<ide><path>src/objects/Sprite.js <ide> Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { <ide> <ide> raycast: ( function () { <ide> <add> var intersectPoint = new Vector3(); <ide> var matrixPosition = new Vector3(); <ide> <ide> return function raycast( raycaster, intersects ) { <ide> <ide> matrixPosition.setFromMatrixPosition( this.matrixWorld ); <del> <del> var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition ); <add> raycaster.ray.closestPointToPoint( matrixPosition, intersectPoint ); <ide> var guessSizeSq = this.scale.x * this.scale.y / 4; <ide> <del> if ( distanceSq > guessSizeSq ) { <add> if ( matrixPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return; <ide> <del> return; <add> var distance = raycaster.ray.origin.distanceTo( intersectPoint ); <ide> <del> } <add> if ( distance < raycaster.near || distance > raycaster.far ) return; <ide> <ide> intersects.push( { <ide> <del> distance: Math.sqrt( distanceSq ), <del> point: this.position, <add> distance: distance, <add> point: intersectPoint.clone(), <ide> face: null, <ide> object: this <ide>
1
PHP
PHP
add comment in mysqlgrammar
1aca4bbde671a1f25bffc9859af34eecc98002f5
<ide><path>src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php <ide> class MySqlGrammar extends Grammar { <ide> * <ide> * @var array <ide> */ <del> protected $modifiers = array('Unsigned', 'Nullable', 'Default', 'Increment', 'After'); <add> protected $modifiers = array('Unsigned', 'Nullable', 'Default', 'Increment', 'After', 'Comment'); <ide> <ide> /** <ide> * The possible column serials <ide> protected function modifyAfter(Blueprint $blueprint, Fluent $column) <ide> } <ide> } <ide> <add> /** <add> * Get the SQL for an "comment" column modifier. <add> * <add> * @param \Illuminate\Database\Schema\Blueprint $blueprint <add> * @param \Illuminate\Support\Fluent $column <add> * @return string|null <add> */ <add> protected function modifyComment(Blueprint $blueprint, Fluent $column) <add> { <add> if ( ! is_null($column->comment)) <add> { <add> return ' comment "' . $column->comment . '"'; <add> } <add> } <add> <ide> /** <ide> * Wrap a single string in keyword identifiers. <ide> *
1
Text
Text
fix documentation links
d5de83b00868410cd82e2896d5a267457abfb65e
<ide><path>README.md <ide> If you enjoyed my course, consider supporting Egghead by [buying a subscription] <ide> <ide> ## Documentation <ide> <del>* [Introduction](http://redux.js.org/docs/introduction/index.html) <del>* [Basics](http://redux.js.org/docs/basics/index.html) <del>* [Advanced](http://redux.js.org/docs/advanced/index.html) <del>* [Recipes](http://redux.js.org/docs/recipes/index.html) <del>* [FAQ](http://redux.js.org/docs/FAQ.html) <del>* [Troubleshooting](http://redux.js.org/docs/Troubleshooting.html) <del>* [Glossary](http://redux.js.org/docs/Glossary.html) <del>* [API Reference](http://redux.js.org/docs/api/index.html) <add>* [Introduction](http://redux.js.org/introduction/index.html) <add>* [Basics](http://redux.js.org/basics/index.html) <add>* [Advanced](http://redux.js.org/advanced/index.html) <add>* [Recipes](http://redux.js.org/recipes/index.html) <add>* [FAQ](http://redux.js.org/FAQ.html) <add>* [Troubleshooting](http://redux.js.org/Troubleshooting.html) <add>* [Glossary](http://redux.js.org/Glossary.html) <add>* [API Reference](http://redux.js.org/api/index.html) <ide> <ide> For PDF, ePub, and MOBI exports for offline reading, and instructions on how to create them, please see: [paulkogel/redux-offline-docs](https://github.com/paulkogel/redux-offline-docs). <ide>
1
Text
Text
fix typos in 2.4 release notes
baceb528cb80584285592aa0160b33101cb0ca37
<ide><path>docs/topics/2.4-announcement.md <ide> The optional authtoken application now includes support for *both* Django 1.7 sc <ide> <ide> ## Deprecation of `.model` view attribute <ide> <del>The `.model` attribute on view classes is an optional shortcut for either or both of `.serializer_class` and `.queryset`. It's usage results in more implicit, less obvious behavior. <add>The `.model` attribute on view classes is an optional shortcut for either or both of `.serializer_class` and `.queryset`. Its usage results in more implicit, less obvious behavior. <ide> <ide> The documentation has previously stated that usage of the more explicit style is prefered, and we're now taking that one step further and deprecating the usage of the `.model` shortcut. <ide> <ide> There are also a number of other features and bugfixes as [listed in the release <ide> <ide> Smarter [client IP identification for throttling][client-ip-identification], with the addition of the `NUM_PROXIES` setting. <ide> <del>Added the standardized `Retry-After` header to throttled responses, as per [RFC 6585](http://tools.ietf.org/html/rfc6585). This should now be used in preference to the custom `X-Trottle-Wait-Seconds` header which will be fully deprecated in 3.0. <add>Added the standardized `Retry-After` header to throttled responses, as per [RFC 6585](http://tools.ietf.org/html/rfc6585). This should now be used in preference to the custom `X-Throttle-Wait-Seconds` header which will be fully deprecated in 3.0. <ide> <ide> ## Deprecations <ide>
1
Text
Text
fix some errors in readme
03cad7cba56a9bc924052492d4bbb68485f15a93
<ide><path>readme.md <ide> For the initial page load, `getInitialProps` will execute on the server only. `g <ide> _Note: `getInitialProps` can **not** be used in children components. Only in `pages`._ <ide> <ide> <br/> <add> <ide> > If you are using some server only modules inside `getInitialProps`, make sure to [import them properly](https://arunoda.me/blog/ssr-and-server-only-modules). <ide> > Otherwise, it'll slow down your app. <add> <ide> <br/> <ide> <ide> You can also define the `getInitialProps` lifecycle method for stateless components:
1
Ruby
Ruby
allow preload grouping of through associations
9cc8375e065a2b473f6f63c2483db9ae14d0ba0e
<ide><path>activerecord/lib/active_record/associations/preloader/association.rb <ide> def already_loaded? <ide> @already_loaded ||= owners.all? { |o| o.association(reflection.name).loaded? } <ide> end <ide> <add> def runnable_loaders <add> [self] <add> end <add> <ide> def run? <ide> @run <ide> end <ide><path>activerecord/lib/active_record/associations/preloader/batch.rb <ide> def initialize(preloaders) <ide> end <ide> <ide> def call <del> return if @preloaders.empty? <del> <ide> branches = @preloaders.flat_map(&:branches) <ide> until branches.empty? <del> loaders = branches.flat_map(&:loaders) <add> loaders = branches.flat_map(&:runnable_loaders) <add> <add> already_loaded, loaders = loaders.partition(&:already_loaded?) <add> already_loaded.each(&:run) <add> <ide> group_and_load_similar(loaders) <ide> loaders.each(&:run) <ide> <del> branches = branches.flat_map(&:children) <add> finished, in_progress = branches.partition(&:done?) <add> <add> branches = in_progress + finished.flat_map(&:children) <ide> end <ide> end <ide> <ide> def call <ide> <ide> def group_and_load_similar(loaders) <ide> loaders.grep_v(ThroughAssociation).group_by(&:grouping_key).each do |(_, _, association_key_name), similar_loaders| <del> next if similar_loaders.all? { |l| l.already_loaded? } <del> <ide> scope = similar_loaders.first.scope <ide> Association.load_records_in_batch(scope, association_key_name, similar_loaders) <ide> end <ide><path>activerecord/lib/active_record/associations/preloader/branch.rb <ide> def done? <ide> loaders.all?(&:run?) <ide> end <ide> <add> def runnable_loaders <add> loaders.flat_map(&:runnable_loaders).reject(&:run?) <add> end <add> <ide> def grouped_records <ide> h = {} <ide> source_records.each do |record| <ide><path>activerecord/lib/active_record/associations/preloader/through_association.rb <ide> def records_by_owner <ide> end <ide> end <ide> <add> def runnable_loaders <add> if already_loaded? <add> [self] <add> elsif through_preloaders.all?(&:run?) <add> [self] + source_preloaders.flat_map(&:runnable_loaders) <add> else <add> through_preloaders.flat_map(&:runnable_loaders) <add> end <add> end <add> <ide> private <ide> def source_preloaders <del> @source_preloaders ||= ActiveRecord::Associations::Preloader.new(records: middle_records, associations: source_reflection.name, scope: scope, associate_by_default: false).call <add> @source_preloaders ||= ActiveRecord::Associations::Preloader.new(records: middle_records, associations: source_reflection.name, scope: scope, associate_by_default: false).loaders <ide> end <ide> <ide> def middle_records <ide> through_preloaders.flat_map(&:preloaded_records) <ide> end <ide> <ide> def through_preloaders <del> @through_preloaders ||= ActiveRecord::Associations::Preloader.new(records: owners, associations: through_reflection.name, scope: through_scope, associate_by_default: false).call <add> @through_preloaders ||= ActiveRecord::Associations::Preloader.new(records: owners, associations: through_reflection.name, scope: through_scope, associate_by_default: false).loaders <ide> end <ide> <ide> def through_reflection <ide><path>activerecord/test/cases/associations_test.rb <ide> def test_preload_groups_queries_with_same_scope <ide> end <ide> end <ide> <add> def test_preload_grouped_queries_of_middle_records <add> comments = [ <add> comments(:eager_sti_on_associations_s_comment1), <add> comments(:eager_sti_on_associations_s_comment2), <add> ] <add> <add> assert_queries(2) do <add> ActiveRecord::Associations::Preloader.new(records: comments, associations: [:author, :ordinary_post]).call <add> end <add> end <add> <add> def test_preload_grouped_queries_of_through_records <add> author = authors(:david) <add> <add> assert_queries(3) do <add> ActiveRecord::Associations::Preloader.new(records: [author], associations: [:hello_post_comments, :comments]).call <add> end <add> end <add> <ide> def test_preload_through <ide> comments = [ <ide> comments(:eager_sti_on_associations_s_comment1), <ide><path>activerecord/test/models/comment.rb <ide> def to_s <ide> end <ide> <ide> class SpecialComment < Comment <add> belongs_to :ordinary_post, foreign_key: :post_id, class_name: "Post" <ide> has_one :author, through: :post <ide> default_scope { where(deleted_at: nil) } <ide>
6
Python
Python
update json.dumps for http_date changes
49b7341a491e01cd6a08238ca63bd46ae53a009f
<ide><path>src/flask/json/__init__.py <ide> import uuid <ide> import warnings <ide> from datetime import date <del>from datetime import datetime <ide> <ide> from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps <ide> from werkzeug.http import http_date <ide> def default(self, o): <ide> overriding how basic types like ``str`` or ``list`` are <ide> serialized, they are handled before this method. <ide> """ <del> if isinstance(o, datetime): <del> return http_date(o.utctimetuple()) <ide> if isinstance(o, date): <del> return http_date(o.timetuple()) <add> return http_date(o) <ide> if isinstance(o, uuid.UUID): <ide> return str(o) <ide> if dataclasses and dataclasses.is_dataclass(o): <ide><path>tests/test_json.py <ide> def return_array(): <ide> assert flask.json.loads(rv.data) == a_list <ide> <ide> <del>def test_jsonifytypes(app, client): <del> """Test jsonify with datetime.date and datetime.datetime types.""" <del> test_dates = ( <del> datetime.datetime(1973, 3, 11, 6, 30, 45), <del> datetime.date(1975, 1, 5), <del> ) <add>@pytest.mark.parametrize( <add> "value", [datetime.datetime(1973, 3, 11, 6, 30, 45), datetime.date(1975, 1, 5)] <add>) <add>def test_jsonify_datetime(app, client, value): <add> @app.route("/") <add> def index(): <add> return flask.jsonify(value=value) <ide> <del> for i, d in enumerate(test_dates): <del> url = f"/datetest{i}" <del> app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val)) <del> rv = client.get(url) <del> assert rv.mimetype == "application/json" <del> assert flask.json.loads(rv.data)["x"] == http_date(d.timetuple()) <add> r = client.get() <add> assert r.json["value"] == http_date(value) <ide> <ide> <ide> class FixedOffset(datetime.tzinfo): <ide><path>tests/test_json_tag.py <ide> from datetime import datetime <add>from datetime import timezone <ide> from uuid import uuid4 <ide> <ide> import pytest <ide> b"\xff", <ide> Markup("<html>"), <ide> uuid4(), <del> datetime.utcnow().replace(microsecond=0), <add> datetime.now(tz=timezone.utc).replace(microsecond=0), <ide> ), <ide> ) <ide> def test_dump_load_unchanged(data):
3
Javascript
Javascript
use entry in `yarn build ...` instead of label
051272f2012e1c2f75dc8ee9fe72a1d85cdac302
<ide><path>scripts/rollup/build.js <ide> const { <ide> RN_FB_PROFILING, <ide> } = Bundles.bundleTypes; <ide> <del>const requestedBundleTypes = (argv.type || '') <del> .split(',') <del> .map(type => type.toUpperCase()); <del>const requestedBundleNames = (argv._[0] || '') <del> .split(',') <del> .map(type => type.toLowerCase()); <add>function parseRequestedNames(names, toCase) { <add> let result = []; <add> for (let i = 0; i < names.length; i++) { <add> let splitNames = names[i].split(','); <add> for (let j = 0; j < splitNames.length; j++) { <add> let name = splitNames[j].trim(); <add> if (!name) { <add> continue; <add> } <add> if (toCase === 'uppercase') { <add> name = name.toUpperCase(); <add> } else if (toCase === 'lowercase') { <add> name = name.toLowerCase(); <add> } <add> result.push(name); <add> } <add> } <add> return result; <add>} <add> <add>const requestedBundleTypes = argv.type <add> ? parseRequestedNames([argv.type], 'uppercase') <add> : []; <add>const requestedBundleNames = parseRequestedNames(argv._, 'lowercase'); <ide> const forcePrettyOutput = argv.pretty; <ide> const syncFBSourcePath = argv['sync-fbsource']; <ide> const syncWWWPath = argv['sync-www']; <ide> function shouldSkipBundle(bundle, bundleType) { <ide> } <ide> if (requestedBundleNames.length > 0) { <ide> const isAskingForDifferentNames = requestedBundleNames.every( <del> requestedName => bundle.label.indexOf(requestedName) === -1 <add> // If the name ends with `something/index` we only match if the <add> // entry ends in something. Such as `react-dom/index` only matches <add> // `react-dom` but not `react-dom/server`. Everything else is fuzzy <add> // search. <add> requestedName => <add> (bundle.entry + '/index.js').indexOf(requestedName) === -1 <ide> ); <ide> if (isAskingForDifferentNames) { <ide> return true; <ide><path>scripts/rollup/bundles.js <ide> const NON_FIBER_RENDERER = moduleTypes.NON_FIBER_RENDERER; <ide> const bundles = [ <ide> /******* Isomorphic *******/ <ide> { <del> label: 'core', <ide> bundleTypes: [ <ide> UMD_DEV, <ide> UMD_PROD, <ide> const bundles = [ <ide> <ide> /******* React DOM *******/ <ide> { <del> label: 'dom-client', <ide> bundleTypes: [ <ide> UMD_DEV, <ide> UMD_PROD, <ide> const bundles = [ <ide> <ide> //******* Test Utils *******/ <ide> { <del> label: 'dom-test-utils', <ide> moduleType: RENDERER_UTILS, <ide> bundleTypes: [FB_WWW_DEV, NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD], <ide> entry: 'react-dom/test-utils', <ide> const bundles = [ <ide> <ide> /* React DOM internals required for react-native-web (e.g., to shim native events from react-dom) */ <ide> { <del> label: 'dom-unstable-native-dependencies', <ide> bundleTypes: [ <ide> UMD_DEV, <ide> UMD_PROD, <ide> const bundles = [ <ide> <ide> /******* React DOM Server *******/ <ide> { <del> label: 'dom-server-browser', <ide> bundleTypes: [ <ide> UMD_DEV, <ide> UMD_PROD, <ide> const bundles = [ <ide> }, <ide> <ide> { <del> label: 'dom-server-node', <ide> bundleTypes: [NODE_DEV, NODE_PROD], <ide> moduleType: NON_FIBER_RENDERER, <ide> entry: 'react-dom/server.node', <ide> const bundles = [ <ide> <ide> /******* React ART *******/ <ide> { <del> label: 'art', <ide> bundleTypes: [ <ide> UMD_DEV, <ide> UMD_PROD, <ide> const bundles = [ <ide> <ide> /******* React Native *******/ <ide> { <del> label: 'native-fb', <ide> bundleTypes: [RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING], <ide> moduleType: RENDERER, <ide> entry: 'react-native-renderer', <ide> const bundles = [ <ide> }, <ide> <ide> { <del> label: 'native', <ide> bundleTypes: [RN_OSS_DEV, RN_OSS_PROD, RN_OSS_PROFILING], <ide> moduleType: RENDERER, <ide> entry: 'react-native-renderer', <ide> const bundles = [ <ide> <ide> /******* React Native Fabric *******/ <ide> { <del> label: 'native-fabric-fb', <ide> bundleTypes: [RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING], <ide> moduleType: RENDERER, <ide> entry: 'react-native-renderer/fabric', <ide> const bundles = [ <ide> }, <ide> <ide> { <del> label: 'native-fabric', <ide> bundleTypes: [RN_OSS_DEV, RN_OSS_PROD, RN_OSS_PROFILING], <ide> moduleType: RENDERER, <ide> entry: 'react-native-renderer/fabric', <ide> const bundles = [ <ide> <ide> /******* React Test Renderer *******/ <ide> { <del> label: 'test', <ide> bundleTypes: [FB_WWW_DEV, NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD], <ide> moduleType: RENDERER, <ide> entry: 'react-test-renderer', <ide> const bundles = [ <ide> }, <ide> <ide> { <del> label: 'test-shallow', <ide> bundleTypes: [FB_WWW_DEV, NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD], <ide> moduleType: NON_FIBER_RENDERER, <ide> entry: 'react-test-renderer/shallow', <ide> const bundles = [ <ide> <ide> /******* React Noop Renderer (used for tests) *******/ <ide> { <del> label: 'noop', <ide> bundleTypes: [NODE_DEV, NODE_PROD], <ide> moduleType: RENDERER, <ide> entry: 'react-noop-renderer', <ide> const bundles = [ <ide> <ide> /******* React Noop Persistent Renderer (used for tests) *******/ <ide> { <del> label: 'noop-persistent', <ide> bundleTypes: [NODE_DEV, NODE_PROD], <ide> moduleType: RENDERER, <ide> entry: 'react-noop-renderer/persistent', <ide> const bundles = [ <ide> <ide> /******* React Reconciler *******/ <ide> { <del> label: 'react-reconciler', <ide> bundleTypes: [NODE_DEV, NODE_PROD], <ide> moduleType: RECONCILER, <ide> entry: 'react-reconciler', <ide> const bundles = [ <ide> <ide> /******* React Persistent Reconciler *******/ <ide> { <del> label: 'react-reconciler-persistent', <ide> bundleTypes: [NODE_DEV, NODE_PROD], <ide> moduleType: RECONCILER, <ide> entry: 'react-reconciler/persistent', <ide> const bundles = [ <ide> <ide> /******* Reflection *******/ <ide> { <del> label: 'reconciler-reflection', <ide> moduleType: RENDERER_UTILS, <ide> bundleTypes: [NODE_DEV, NODE_PROD], <ide> entry: 'react-reconciler/reflection', <ide> const bundles = [ <ide> <ide> /******* React Is *******/ <ide> { <del> label: 'react-is', <ide> bundleTypes: [ <ide> NODE_DEV, <ide> NODE_PROD, <ide> const bundles = [ <ide> <ide> /******* React Debug Tools *******/ <ide> { <del> label: 'react-debug-tools', <ide> bundleTypes: [NODE_DEV, NODE_PROD], <ide> moduleType: ISOMORPHIC, <ide> entry: 'react-debug-tools', <ide> const bundles = [ <ide> <ide> /******* React Cache (experimental) *******/ <ide> { <del> label: 'react-cache', <ide> bundleTypes: [ <ide> FB_WWW_DEV, <ide> FB_WWW_PROD, <ide> const bundles = [ <ide> <ide> /******* createComponentWithSubscriptions (experimental) *******/ <ide> { <del> label: 'create-subscription', <ide> bundleTypes: [NODE_DEV, NODE_PROD], <ide> moduleType: ISOMORPHIC, <ide> entry: 'create-subscription', <ide> const bundles = [ <ide> <ide> /******* React Scheduler (experimental) *******/ <ide> { <del> label: 'scheduler', <ide> bundleTypes: [NODE_DEV, NODE_PROD, FB_WWW_DEV, FB_WWW_PROD], <ide> moduleType: ISOMORPHIC, <ide> entry: 'scheduler', <ide> const bundles = [ <ide> <ide> /******* Jest React (experimental) *******/ <ide> { <del> label: 'jest-react', <ide> bundleTypes: [NODE_DEV, NODE_PROD, FB_WWW_DEV, FB_WWW_PROD], <ide> moduleType: ISOMORPHIC, <ide> entry: 'jest-react', <ide> const bundles = [ <ide> <ide> /******* ESLint Plugin for Hooks (proposal) *******/ <ide> { <del> label: 'eslint-plugin-react-hooks', <ide> // TODO: it's awkward to create a bundle for this <ide> // but if we don't, the package won't get copied. <ide> // We also can't create just DEV bundle because <ide> const bundles = [ <ide> }, <ide> <ide> { <del> label: 'scheduler-tracing', <ide> bundleTypes: [ <ide> FB_WWW_DEV, <ide> FB_WWW_PROD,
2
Go
Go
remove remaining use of deprecated pkg/mount
6d243cdf27bc9cd4caf5b33b7096f2cd1f6e735a
<ide><path>api/types/mount/mount.go <ide> type TmpfsOptions struct { <ide> // TODO(stevvooe): There are several more tmpfs flags, specified in the <ide> // daemon, that are accepted. Only the most basic are added for now. <ide> // <del> // From docker/docker/pkg/mount/flags.go: <add> // From https://github.com/moby/sys/blob/mount/v0.1.1/mount/flags.go#L47-L56 <ide> // <ide> // var validFlags = map[string]bool{ <ide> // "": true, <ide><path>testutil/daemon/daemon_unix.go <ide> import ( <ide> "syscall" <ide> "testing" <ide> <del> "github.com/docker/docker/pkg/mount" <add> "github.com/moby/sys/mount" <ide> "golang.org/x/sys/unix" <ide> "gotest.tools/v3/assert" <ide> )
2
Text
Text
standardize links in curriculum
3e3da4ec0fb48a4d343c3eda0b405159720494d5
<ide><path>curriculum/challenges/english/01-responsive-web-design/basic-css/use-hex-code-for-specific-colors.md <ide> dashedName: use-hex-code-for-specific-colors <ide> <ide> Did you know there are other ways to represent colors in CSS? One of these ways is called hexadecimal code, or hex code for short. <ide> <del>We usually use <dfn>decimals</dfn>, or base 10 numbers, which use the symbols 0 to 9 for each digit. <dfn>Hexadecimals</dfn> (or <dfn>hex</dfn>) are base 16 numbers. This means it uses sixteen distinct symbols. Like decimals, the symbols 0-9 represent the values zero to nine. Then A,B,C,D,E,F represent the values ten to fifteen. Altogether, 0 to F can represent a digit in hexadecimal, giving us 16 total possible values. You can find more information about [hexadecimal numbers here](https://www.freecodecamp.org/news/hexadecimal-number-system/). <add>We usually use <dfn>decimals</dfn>, or base 10 numbers, which use the symbols 0 to 9 for each digit. <dfn>Hexadecimals</dfn> (or <dfn>hex</dfn>) are base 16 numbers. This means it uses sixteen distinct symbols. Like decimals, the symbols 0-9 represent the values zero to nine. Then A,B,C,D,E,F represent the values ten to fifteen. Altogether, 0 to F can represent a digit in hexadecimal, giving us 16 total possible values. You can find more information about <a href="https://www.freecodecamp.org/news/hexadecimal-number-system/" target="_blank" rel="noopener noreferrer nofollow">hexadecimal numbers here</a>. <ide> <del>In CSS, we can use 6 hexadecimal digits to represent colors, two each for the red (R), green (G), and blue (B) components. For example, `#000000` is black and is also the lowest possible value. You can find more information about the [RGB color system here](https://www.freecodecamp.org/news/rgb-color-html-and-css-guide/#whatisthergbcolormodel). <add>In CSS, we can use 6 hexadecimal digits to represent colors, two each for the red (R), green (G), and blue (B) components. For example, `#000000` is black and is also the lowest possible value. You can find more information about the <a href="https://www.freecodecamp.org/news/rgb-color-html-and-css-guide/#whatisthergbcolormodel" target="_blank" rel="noopener noreferrer nofollow">RGB color system here</a>. <ide> <ide> ```css <ide> body { <ide><path>curriculum/challenges/english/01-responsive-web-design/css-flexbox/align-elements-using-the-justify-content-property.md <ide> dashedName: align-elements-using-the-justify-content-property <ide> <ide> Sometimes the flex items within a flex container do not fill all the space in the container. It is common to want to tell CSS how to align and space out the flex items a certain way. Fortunately, the `justify-content` property has several options to do this. But first, there is some important terminology to understand before reviewing those options. <ide> <del>[For more info about flex-box properties](https://www.freecodecamp.org/news/flexbox-the-ultimate-css-flex-cheatsheet/) <add><a href="https://www.freecodecamp.org/news/flexbox-the-ultimate-css-flex-cheatsheet/" target="_blank" rel="noopener noreferrer nofollow">For more info about flex-box properties read here</a> <ide> <ide> Recall that setting a flex container as a row places the flex items side-by-side from left-to-right. A flex container set as a column places the flex items in a vertical stack from top-to-bottom. For each, the direction the flex items are arranged is called the **main axis**. For a row, this is a horizontal line that cuts through each item. And for a column, the main axis is a vertical line through the items. <ide> <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value.md <ide> dashedName: assignment-with-a-returned-value <ide> <ide> # --description-- <ide> <del>If you'll recall from our discussion of [Storing Values with the Assignment Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable. <add>If you'll recall from our discussion about <a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank" rel="noopener noreferrer nofollow">Storing Values with the Assignment Operator</a>, everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable. <ide> <ide> Assume we have pre-defined a function `sum` which adds two numbers together, then: <ide> <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/create-decimal-numbers-with-javascript.md <ide> dashedName: create-decimal-numbers-with-javascript <ide> <ide> We can store decimal numbers in variables too. Decimal numbers are sometimes referred to as <dfn>floating point</dfn> numbers or <dfn>floats</dfn>. <ide> <del>**Note:** when you compute numbers, they are computed with finite precision. Operations using floating points may lead to different results than the desired outcome. If you are getting one of these results, open a topic on the [freeCodeCamp forum](https://forum.freecodecamp.org/). <add>**Note:** when you compute numbers, they are computed with finite precision. Operations using floating points may lead to different results than the desired outcome. If you are getting one of these results, open a topic on the <a href="https://forum.freecodecamp.org/" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --instructions-- <ide> <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.md <ide> Random numbers are useful for creating random behavior. <ide> <ide> JavaScript has a `Math.random()` function that generates a random decimal number between `0` (inclusive) and `1` (exclusive). Thus `Math.random()` can return a `0` but never return a `1`. <ide> <del>**Note:** Like [Storing Values with the Assignment Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), all function calls will be resolved before the `return` executes, so we can `return` the value of the `Math.random()` function. <add>**Note:** Like <a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank" rel="noopener noreferrer nofollow">Storing Values with the Assignment Operator</a>, all function calls will be resolved before the `return` executes, so we can `return` the value of the `Math.random()` function. <ide> <ide> # --instructions-- <ide> <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions.md <ide> The above will display the string `Hello` in the console, and return the string <ide> Modify the function `abTest` so that if `a` or `b` are less than `0` the function will immediately exit with a value of `undefined`. <ide> <ide> **Hint** <del>Remember that <a href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables" target="_blank" rel="noopener noreferrer nofollow">`undefined` is a keyword</a>, not a string. <add>Remember that <a href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables" target="_blank" rel="noopener noreferrer nofollow"><code>undefined</code> is a keyword</a>, not a string. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions.md <ide> dashedName: returning-boolean-values-from-functions <ide> <ide> # --description-- <ide> <del>You may recall from [Comparison with the Equality Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator) that all comparison operators return a boolean `true` or `false` value. <add>You may recall from <a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator" target="_blank" rel="noopener noreferrer nofollow">Comparison with the Equality Operator</a> that all comparison operators return a boolean `true` or `false` value. <ide> <ide> Sometimes people use an `if/else` statement to do a comparison, like this: <ide> <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown.md <ide> dashedName: use-recursion-to-create-a-countdown <ide> <ide> # --description-- <ide> <del>In a [previous challenge](/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion), you learned how to use recursion to replace a `for` loop. Now, let's look at a more complex function that returns an array of consecutive integers starting with `1` through the number passed to the function. <add>In a <a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion" target="_blank" rel="noopener noreferrer nofollow">previous challenge</a>, you learned how to use recursion to replace a `for` loop. Now, let's look at a more complex function that returns an array of consecutive integers starting with `1` through the number passed to the function. <ide> <ide> As mentioned in the previous challenge, there will be a <dfn>base case</dfn>. The base case tells the recursive function when it no longer needs to call itself. It is a simple case where the return value is already known. There will also be a <dfn>recursive call</dfn> which executes the original function with different arguments. If the function is written correctly, eventually the base case will be reached. <ide> <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords.md <ide> dashedName: compare-scopes-of-the-var-and-let-keywords <ide> <ide> # --description-- <ide> <del>If you are unfamiliar with `let`, check out [this challenge](/learn/javascript-algorithms-and-data-structures/basic-javascript/explore-differences-between-the-var-and-let-keywords). <add>If you are unfamiliar with `let`, check out <a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/explore-differences-between-the-var-and-let-keywords" target="_blank" rel="noopener noreferrer nofollow">this challenge about the difference bewteen <code>let</code> and <code>var</code></a>. <ide> <ide> When you declare a variable with the `var` keyword, it is declared globally, or locally if declared inside a function. <ide> <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.md <ide> dashedName: mutate-an-array-declared-with-const <ide> <ide> # --description-- <ide> <del>If you are unfamiliar with `const`, check out [this challenge](/learn/javascript-algorithms-and-data-structures/basic-javascript/declare-a-read-only-variable-with-the-const-keyword). <add>If you are unfamiliar with `const`, check out <a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/declare-a-read-only-variable-with-the-const-keyword" target="_blank" rel="noopener noreferrer nofollow">this challenge about the <code>const</code> keyword</a>. <ide> <ide> The `const` declaration has many use cases in modern JavaScript. <ide> <ide><path>curriculum/challenges/english/03-front-end-development-libraries/jquery/change-text-inside-an-element-using-jquery.md <ide> jQuery also has a similar function called `.text()` that only alters text withou <ide> <ide> Change the button with id `target4` by emphasizing its text. <ide> <del>[View our news article for &lt;em>](https://www.freecodecamp.org/news/html-elements-explained-what-are-html-tags/#em-element) to learn the difference between `<i>` and `<em>` and their uses. <add><a href="https://www.freecodecamp.org/news/html-elements-explained-what-are-html-tags/#em-element" target="_blank" rel="noopener noreferrer nofollow">View our news article for &lt;em&gt;</a> to learn the difference between `<i>` and `<em>` and their uses. <ide> <ide> Note that while the `<i>` tag has traditionally been used to emphasize text, it has since been adopted for use as a tag for icons. The `<em>` tag is now widely accepted as the tag for emphasis. Either will work for this challenge. <ide> <ide><path>curriculum/challenges/english/03-front-end-development-libraries/react/introducing-inline-styles.md <ide> dashedName: introducing-inline-styles <ide> <ide> # --description-- <ide> <del>There are other complex concepts that add powerful capabilities to your React code. But you may be wondering about the more simple problem of how to style those JSX elements you create in React. You likely know that it won't be exactly the same as working with HTML because of [the way you apply classes to JSX elements](/learn/front-end-development-libraries/react/define-an-html-class-in-jsx). <add>There are other complex concepts that add powerful capabilities to your React code. But you may be wondering about the more simple problem of how to style those JSX elements you create in React. You likely know that it won't be exactly the same as working with HTML because of <a href="/learn/front-end-development-libraries/react/define-an-html-class-in-jsx" target="_blank" rel="noopener noreferrer nofollow">the way you apply classes to JSX elements</a>. <ide> <ide> If you import styles from a stylesheet, it isn't much different at all. You apply a class to your JSX element using the `className` attribute, and apply styles to the class in your stylesheet. Another option is to apply inline styles, which are very common in ReactJS development. <ide> <ide><path>curriculum/challenges/english/03-front-end-development-libraries/react/use-proptypes-to-define-the-props-you-expect.md <ide> It's considered a best practice to set `propTypes` when you know the type of a p <ide> MyComponent.propTypes = { handleClick: PropTypes.func.isRequired } <ide> ``` <ide> <del>In the example above, the `PropTypes.func` part checks that `handleClick` is a function. Adding `isRequired` tells React that `handleClick` is a required property for that component. You will see a warning if that prop isn't provided. Also notice that `func` represents `function`. Among the seven JavaScript primitive types, `function` and `boolean` (written as `bool`) are the only two that use unusual spelling. In addition to the primitive types, there are other types available. For example, you can check that a prop is a React element. Please refer to the [documentation](https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes) for all of the options. <add>In the example above, the `PropTypes.func` part checks that `handleClick` is a function. Adding `isRequired` tells React that `handleClick` is a required property for that component. You will see a warning if that prop isn't provided. Also notice that `func` represents `function`. Among the seven JavaScript primitive types, `function` and `boolean` (written as `bool`) are the only two that use unusual spelling. In addition to the primitive types, there are other types available. For example, you can check that a prop is a React element. Please refer to the <a href="https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes" target="_blank" rel="noopener noreferrer nofollow">documentation</a> for all of the options. <ide> <ide> **Note:** As of React v15.5.0, `PropTypes` is imported independently from React, like this: `import PropTypes from 'prop-types';` <ide> <ide><path>curriculum/challenges/english/03-front-end-development-libraries/redux/create-a-redux-store.md <ide> The Redux `store` is an object which holds and manages application `state`. Ther <ide> <ide> Declare a `store` variable and assign it to the `createStore()` method, passing in the `reducer` as an argument. <ide> <del>**Note:** The code in the editor uses ES6 default argument syntax to initialize this state to hold a value of `5`. If you're not familiar with default arguments, you can refer to the [ES6 section in the Curriculum](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions) which covers this topic. <add>**Note:** The code in the editor uses ES6 default argument syntax to initialize this state to hold a value of `5`. If you're not familiar with default arguments, you can refer to the <a href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions" target="_blank" rel="noopener noreferrer nofollow">ES6 section in the Curriculum</a> which covers this topic. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/communicate-by-emitting.md <ide> socket.on('user count', function(data) { <ide> <ide> Now, try loading up your app, authenticate, and you should see in your client console '1' representing the current user count! Try loading more clients up, and authenticating to see the number go up. <ide> <del>Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point <a href="https://gist.github.com/camperbot/28ef7f1078f56eb48c7b1aeea35ba1f5" target="_blank" rel="noopener noreferrer nofollow">https://gist.github.com/camperbot/28ef7f1078f56eb48c7b1aeea35ba1f5</a>. <add>Submit your page when you think you've got it right. If you're running into errors, you can <a href="https://gist.github.com/camperbot/28ef7f1078f56eb48c7b1aeea35ba1f5" target="_blank" rel="noopener noreferrer nofollow">check out the project completed up to this point</a>. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/handle-a-disconnect.md <ide> To make sure clients continuously have the updated count of current users, you s <ide> <ide> **Note:** Just like `'disconnect'`, all other events that a socket can emit to the server should be handled within the connecting listener where we have 'socket' defined. <ide> <del>Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point <a href="https://gist.github.com/camperbot/ab1007b76069884fb45b215d3c4496fa" target="_blank" rel="noopener noreferrer nofollow">https://gist.github.com/camperbot/ab1007b76069884fb45b215d3c4496fa</a>. <add>Submit your page when you think you've got it right. If you're running into errors, you can <a href="https://gist.github.com/camperbot/ab1007b76069884fb45b215d3c4496fa" target="_blank" rel="noopener noreferrer nofollow">check out the project completed up to this point</a>. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/how-to-put-a-profile-together.md <ide> Also, in `profile.pug`, add a link referring to the `/logout` route, which will <ide> a(href='/logout') Logout <ide> ``` <ide> <del>Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point <a href="https://gist.github.com/camperbot/136b3ad611cc80b41cab6f74bb460f6a" target="_blank" rel="noopener noreferrer nofollow">https://gist.github.com/camperbot/136b3ad611cc80b41cab6f74bb460f6a</a>. <add>Submit your page when you think you've got it right. If you're running into errors, you can <a href="https://gist.github.com/camperbot/136b3ad611cc80b41cab6f74bb460f6a" target="_blank" rel="noopener noreferrer nofollow">check out the project completed up to this point</a>. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/implement-the-serialization-of-a-passport-user.md <ide> myDB(async client => { <ide> <ide> Be sure to uncomment the `myDataBase` code in `deserializeUser`, and edit your `done(null, null)` to include the `doc`. <ide> <del>Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point <a href="https://gist.github.com/camperbot/175f2f585a2d8034044c7e8857d5add7" target="_blank" rel="noopener noreferrer nofollow">https://gist.github.com/camperbot/175f2f585a2d8034044c7e8857d5add7</a>. <add>Submit your page when you think you've got it right. If you're running into errors, you can <a href="https://gist.github.com/camperbot/175f2f585a2d8034044c7e8857d5add7" target="_blank" rel="noopener noreferrer nofollow">check out the project completed up to this point</a>. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/registration-of-new-users.md <ide> app.route('/register') <ide> ); <ide> ``` <ide> <del>Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point <a href="https://gist.github.com/camperbot/b230a5b3bbc89b1fa0ce32a2aa7b083e" target="_blank" rel="noopener noreferrer nofollow">https://gist.github.com/camperbot/b230a5b3bbc89b1fa0ce32a2aa7b083e</a>. <add>Submit your page when you think you've got it right. If you're running into errors, you can <a href="https://gist.github.com/camperbot/b230a5b3bbc89b1fa0ce32a2aa7b083e" target="_blank" rel="noopener noreferrer nofollow">check out the project completed up to this point</a>. <ide> <ide> **NOTE:** From this point onwards, issues can arise relating to the use of the *picture-in-picture* browser. If you are using an online IDE which offers a preview of the app within the editor, it is recommended to open this preview in a new tab. <ide> <ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/serialization-of-a-user-object.md <ide> passport.deserializeUser((id, done) => { <ide> <ide> NOTE: This `deserializeUser` will throw an error until we set up the DB in the next step, so for now comment out the whole block and just call `done(null, null)` in the function `deserializeUser`. <ide> <del>Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point <a href="https://gist.github.com/camperbot/7068a0d09e61ec7424572b366751f048" target="_blank" rel="noopener noreferrer nofollow">https://gist.github.com/camperbot/7068a0d09e61ec7424572b366751f048</a>. <add>Submit your page when you think you've got it right. If you're running into errors, you can <a href="https://gist.github.com/camperbot/7068a0d09e61ec7424572b366751f048" target="_blank" rel="noopener noreferrer nofollow">check out the project completed up to this point</a>. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/set-up-a-template-engine.md <ide> Change the argument of the `res.render()` declaration in the `/` route to be the <ide> <ide> If all went as planned, your app home page will stop showing the message "`Pug template is not defined.`" and will now display a message indicating you've successfully rendered the Pug template! <ide> <del>Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point <a href="https://gist.github.com/camperbot/3515cd676ea4dfceab4e322f59a37791" target="_blank" rel="noopener noreferrer nofollow">https://gist.github.com/camperbot/3515cd676ea4dfceab4e322f59a37791</a>. <add>Submit your page when you think you've got it right. If you're running into errors, you can <a href="https://gist.github.com/camperbot/3515cd676ea4dfceab4e322f59a37791" target="_blank" rel="noopener noreferrer nofollow">check out the project completed up to this point</a>. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/set-up-the-environment.md <ide> Now try loading up your app and authenticate and you should see in your server c <ide> <ide> **Note:**`io()` works only when connecting to a socket hosted on the same url/server. For connecting to an external socket hosted elsewhere, you would use `io.connect('URL');`. <ide> <del>Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point <a href="https://gist.github.com/camperbot/aae41cf59debc1a4755c9a00ee3859d1" target="_blank" rel="noopener noreferrer nofollow">https://gist.github.com/camperbot/aae41cf59debc1a4755c9a00ee3859d1</a>. <add>Submit your page when you think you've got it right. If you're running into errors, you can <a href="https://gist.github.com/camperbot/aae41cf59debc1a4755c9a00ee3859d1" target="_blank" rel="noopener noreferrer nofollow">check out the project completed up to this point</a>. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/build-your-own-functions.md <ide> dashedName: build-your-own-functions <ide> <ide> More resources: <ide> <del>\- [Exercise](https://www.youtube.com/watch?v=ksvGhDsjtpw) <add>\- <a href="https://www.youtube.com/watch?v=ksvGhDsjtpw" target="_blank" rel="noopener noreferrer nofollow">Exercise</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/comparing-and-sorting-tuples.md <ide> dashedName: comparing-and-sorting-tuples <ide> <ide> More resources: <ide> <del>\- [Exercise](https://www.youtube.com/watch?v=EhQxwzyT16E) <add>\- <a href="https://www.youtube.com/watch?v=EhQxwzyT16E" target="_blank" rel="noopener noreferrer nofollow">Exercise</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/data-visualization-mailing-lists.md <ide> dashedName: data-visualization-mailing-lists <ide> <ide> More resources: <ide> <del>\- [Exercise: Geodata](https://www.youtube.com/watch?v=KfhslNzopxo) <add>\- <a href="https://www.youtube.com/watch?v=KfhslNzopxo" target="_blank" rel="noopener noreferrer nofollow">Exercise: Geodata</a> <ide> <del>\- [Exercise: Gmane Model](https://www.youtube.com/watch?v=wSpl1-7afAk) <add>\- <a href="https://www.youtube.com/watch?v=wSpl1-7afAk" target="_blank" rel="noopener noreferrer nofollow">Exercise: Gmane Model</a> <ide> <del>\- [Exercise: Gmane Spider](https://www.youtube.com/watch?v=H3w4lOFBUOI) <add>\- <a href="https://www.youtube.com/watch?v=H3w4lOFBUOI" target="_blank" rel="noopener noreferrer nofollow">Exercise: Gmane Spider</a> <ide> <del>\- [Exercise: Gmane Viz](https://www.youtube.com/watch?v=LRqVPMEXByw) <add>\- <a href="https://www.youtube.com/watch?v=LRqVPMEXByw" target="_blank" rel="noopener noreferrer nofollow">Exercise: Gmane Viz</a> <ide> <del>\- [Exercise: Page Rank](https://www.youtube.com/watch?v=yFRAZBkBDBs) <add>\- <a href="https://www.youtube.com/watch?v=yFRAZBkBDBs" target="_blank" rel="noopener noreferrer nofollow">Exercise: Page Rank</a> <ide> <del>\- [Exercise: Page Spider](https://www.youtube.com/watch?v=sXedPQ_AnWA) <add>\- <a href="https://www.youtube.com/watch?v=sXedPQ_AnWA" target="_blank" rel="noopener noreferrer nofollow">Exercise: Page Spider</a> <ide> <del>\- [Exercise: Page Viz](https://www.youtube.com/watch?v=Fm0hpkxsZoo) <add>\- <a href="https://www.youtube.com/watch?v=Fm0hpkxsZoo" target="_blank" rel="noopener noreferrer nofollow">Exercise: Page Viz</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/dictionaries-and-loops.md <ide> dashedName: dictionaries-and-loops <ide> <ide> More resources: <ide> <del>\- [Exercise](https://www.youtube.com/watch?v=PrhZ9qwBDD8) <add>\- <a href="https://www.youtube.com/watch?v=PrhZ9qwBDD8" target="_blank" rel="noopener noreferrer nofollow">Exercise</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/files-as-a-sequence.md <ide> dashedName: files-as-a-sequence <ide> <ide> More resources: <ide> <del>\- [Exercise](https://www.youtube.com/watch?v=il1j4wkte2E) <add>\- <a href="https://www.youtube.com/watch?v=il1j4wkte2E" target="_blank" rel="noopener noreferrer nofollow">Exercise</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/intermediate-expressions.md <ide> dashedName: intermediate-expressions <ide> <ide> More resources: <ide> <del>\- [Exercise 1](https://youtu.be/t_4DPwsaGDY) <add>\- <a href="https://youtu.be/t_4DPwsaGDY" target="_blank" rel="noopener noreferrer nofollow">Exercise 1</a> <ide> <del>\- [Exercise 2](https://youtu.be/wgkC8SxraAQ) <add>\- <a href="https://youtu.be/wgkC8SxraAQ" target="_blank" rel="noopener noreferrer nofollow">Exercise 2</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/intermediate-strings.md <ide> dashedName: intermediate-strings <ide> <ide> More resources: <ide> <del>\- [Exercise](https://www.youtube.com/watch?v=1bSqHot-KwE) <add>\- <a href="https://www.youtube.com/watch?v=1bSqHot-KwE" target="_blank" rel="noopener noreferrer nofollow">Exercise</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/introduction-why-program.md <ide> dashedName: introduction-why-program <ide> <ide> More resources: <ide> <del>\- [Install Python on Windows](https://youtu.be/F7mtLrYzZP8) <add>\- <a href="https://youtu.be/F7mtLrYzZP8" target="_blank" rel="noopener noreferrer nofollow">Install Python on Windows</a> <ide> <del>\- [Install Python on MacOS](https://youtu.be/wfLnZP-4sZw) <add>\- <a href="https://youtu.be/wfLnZP-4sZw" target="_blank" rel="noopener noreferrer nofollow">Install Python on MacOS</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/iterations-more-patterns.md <ide> dashedName: iterations-more-patterns <ide> <ide> More resources: <ide> <del>\- [Exercise](https://www.youtube.com/watch?v=kjxXZQw0uPg) <add>\- <a href="https://www.youtube.com/watch?v=kjxXZQw0uPg" target="_blank" rel="noopener noreferrer nofollow">Exercise</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/more-conditional-structures.md <ide> dashedName: more-conditional-structures <ide> <ide> More resources: <ide> <del>\- [Exercise 1](https://www.youtube.com/watch?v=crLerB4ZxMI) <add>\- <a href="https://www.youtube.com/watch?v=crLerB4ZxMI" target="_blank" rel="noopener noreferrer nofollow">Exercise 1</a> <ide> <del>\- [Exercise 2](https://www.youtube.com/watch?v=KJN3-7HH6yk) <add>\- <a href="https://www.youtube.com/watch?v=KJN3-7HH6yk" target="_blank" rel="noopener noreferrer nofollow">Exercise 2</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/networking-web-scraping-with-python.md <ide> dashedName: networking-web-scraping-with-python <ide> <ide> More resources: <ide> <del>\- [Exercise: socket1](https://www.youtube.com/watch?v=dWLdI143W-g) <add>\- <a href="https://www.youtube.com/watch?v=dWLdI143W-g" target="_blank" rel="noopener noreferrer nofollow">Exercise: socket1</a> <ide> <del>\- [Exercise: urllib](https://www.youtube.com/watch?v=8yis2DvbBkI) <add>\- <a href="https://www.youtube.com/watch?v=8yis2DvbBkI" target="_blank" rel="noopener noreferrer nofollow">Exercise: urllib</a> <ide> <del>\- [Exercise: urllinks](https://www.youtube.com/watch?v=g9flPDG9nnY) <add>\- <a href="https://www.youtube.com/watch?v=g9flPDG9nnY" target="_blank" rel="noopener noreferrer nofollow">Exercise: urllinks</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/relational-databases-and-sqlite.md <ide> dashedName: relational-databases-and-sqlite <ide> <ide> # --description-- <ide> <del>[Download SQLite](https://www.sqlite.org/download.html) <del>[Download DB Browser for SQLite](https://sqlitebrowser.org/dl/) <del>[SQLite usage](https://www.sqlite.org/famous.html) <add><a href="https://www.sqlite.org/download.html" target="_blank" rel="noopener noreferrer nofollow">Download SQLite</a> <add><a href="https://sqlitebrowser.org/dl/" target="_blank" rel="noopener noreferrer nofollow">Download DB Browser for SQLite</a> <add><a href="https://www.sqlite.org/famous.html" target="_blank" rel="noopener noreferrer nofollow">SQLite usage</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/relational-databases-many-to-many-relationships.md <ide> dashedName: relational-databases-many-to-many-relationships <ide> <ide> More resources: <ide> <del>\- [Exercise: Email](https://www.youtube.com/watch?v=uQ3Qv1z_Vao) <add>\- <a href="https://www.youtube.com/watch?v=uQ3Qv1z_Vao" target="_blank" rel="noopener noreferrer nofollow">Exercise: Email</a> <ide> <del>\- [Exercise: Roster](https://www.youtube.com/watch?v=qEkUEAz8j3o) <add>\- <a href="https://www.youtube.com/watch?v=qEkUEAz8j3o" target="_blank" rel="noopener noreferrer nofollow">Exercise: Roster</a> <ide> <del>\- [Exercise: Tracks](https://www.youtube.com/watch?v=I-E7avcPeSE) <add>\- <a href="https://www.youtube.com/watch?v=I-E7avcPeSE" target="_blank" rel="noopener noreferrer nofollow">Exercise: Tracks</a> <ide> <del>\- [Exercise: Twfriends](https://www.youtube.com/watch?v=RZRAoBFIH6A) <add>\- <a href="https://www.youtube.com/watch?v=RZRAoBFIH6A" target="_blank" rel="noopener noreferrer nofollow">Exercise: Twfriends</a> <ide> <del>\- [Exercise: Twspider](https://www.youtube.com/watch?v=xBaJddvJL4A) <add>\- <a href="https://www.youtube.com/watch?v=xBaJddvJL4A" target="_blank" rel="noopener noreferrer nofollow">Exercise: Twspider</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/strings-and-lists.md <ide> dashedName: strings-and-lists <ide> <ide> More resources: <ide> <del>\- [Exercise](https://www.youtube.com/watch?v=-9TfJF2dwHI) <add>\- <a href="https://www.youtube.com/watch?v=-9TfJF2dwHI" target="_blank" rel="noopener noreferrer nofollow">Exercise</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/web-services-api-rate-limiting-and-security.md <ide> dashedName: web-services-api-rate-limiting-and-security <ide> <ide> More resources: <ide> <del>\- [Exercise: GeoJSON](https://www.youtube.com/watch?v=TJGJN0T8tak) <add>\- <a href="https://www.youtube.com/watch?v=TJGJN0T8tak" target="_blank" rel="noopener noreferrer nofollow">Exercise: GeoJSON</a> <ide> <del>\- [Exercise: JSON](https://www.youtube.com/watch?v=vTmw5RtfGMY) <add>\- <a href="https://www.youtube.com/watch?v=vTmw5RtfGMY" target="_blank" rel="noopener noreferrer nofollow">Exercise: JSON</a> <ide> <del>\- [Exercise: Twitter](https://www.youtube.com/watch?v=2c7YwhvpCro) <add>\- <a href="https://www.youtube.com/watch?v=2c7YwhvpCro" target="_blank" rel="noopener noreferrer nofollow">Exercise: Twitter</a> <ide> <del>\- [Exercise: XML](https://www.youtube.com/watch?v=AopYOlDa-vY) <add>\- <a href="https://www.youtube.com/watch?v=AopYOlDa-vY" target="_blank" rel="noopener noreferrer nofollow">Exercise: XML</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-analysis-example-a.md <ide> dashedName: data-analysis-example-a <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/FreeCodeCamp-Pandas-Real-Life-Example) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/FreeCodeCamp-Pandas-Real-Life-Example" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-analysis-example-b.md <ide> dashedName: data-analysis-example-b <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/FreeCodeCamp-Pandas-Real-Life-Example) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/FreeCodeCamp-Pandas-Real-Life-Example"target="_blank" r <add>el="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-cleaning-and-visualizations.md <ide> dashedName: data-cleaning-and-visualizations <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/data-cleaning-rmotr-freecodecamp) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/data-cleaning-rmotr-freecodecamp" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-cleaning-duplicates.md <ide> dashedName: data-cleaning-duplicates <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/data-cleaning-rmotr-freecodecamp) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/data-cleaning-rmotr-freecodecamp" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-cleaning-introduction.md <ide> dashedName: data-cleaning-introduction <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/data-cleaning-rmotr-freecodecamp) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/data-cleaning-rmotr-freecodecamp" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/data-cleaning-with-dataframes.md <ide> dashedName: data-cleaning-with-dataframes <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/data-cleaning-rmotr-freecodecamp) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/data-cleaning-rmotr-freecodecamp" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/how-to-use-jupyter-notebooks-intro.md <ide> dashedName: how-to-use-jupyter-notebooks-intro <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/ds-content-interactive-jupyterlab-tutorial) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/ds-content-interactive-jupyterlab-tutorial" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/jupyter-notebooks-cells.md <ide> dashedName: jupyter-notebooks-cells <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/ds-content-interactive-jupyterlab-tutorial) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/ds-content-interactive-jupyterlab-tutorial" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/jupyter-notebooks-importing-and-exporting-data.md <ide> dashedName: jupyter-notebooks-importing-and-exporting-data <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/ds-content-interactive-jupyterlab-tutorial) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/ds-content-interactive-jupyterlab-tutorial" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-algebra-and-size.md <ide> dashedName: numpy-algebra-and-size <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-arrays.md <ide> dashedName: numpy-arrays <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-boolean-arrays.md <ide> dashedName: numpy-boolean-arrays <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-introduction-a.md <ide> dashedName: numpy-introduction-a <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-introduction-b.md <ide> dashedName: numpy-introduction-b <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/numpy-operations.md <ide> dashedName: numpy-operations <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-numpy" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/pandas-conditional-selection-and-modifying-dataframes.md <ide> dashedName: pandas-conditional-selection-and-modifying-dataframes <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-pandas) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-pandas" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/pandas-creating-columns.md <ide> dashedName: pandas-creating-columns <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-pandas) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-pandas" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/pandas-dataframes.md <ide> dashedName: pandas-dataframes <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-pandas) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-pandas" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/pandas-indexing-and-conditional-selection.md <ide> dashedName: pandas-indexing-and-conditional-selection <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-pandas) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-pandas" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/pandas-introduction.md <ide> dashedName: pandas-introduction <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-pandas) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-pandas" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/parsing-html-and-saving-data.md <ide> dashedName: parsing-html-and-saving-data <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/python-functions-and-collections.md <ide> dashedName: python-functions-and-collections <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/ds-content-python-under-10-minutes) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/ds-content-python-under-10-minutes" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/python-introduction.md <ide> dashedName: python-introduction <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/ds-content-python-under-10-minutes) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/ds-content-python-under-10-minutes" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/python-iteration-and-modules.md <ide> dashedName: python-iteration-and-modules <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/ds-content-python-under-10-minutes) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/ine-rmotr-curriculum/ds-content-python-under-10-minutes" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/reading-data-csv-and-txt.md <ide> dashedName: reading-data-csv-and-txt <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/reading-data-from-databases.md <ide> dashedName: reading-data-from-databases <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/reading-data-introduction.md <ide> dashedName: reading-data-introduction <ide> <ide> More resources: <ide> <del>- [Notebooks on GitHub](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas) <del>- [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) <add>- <a href="https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas" target="_blank" rel="noopener noreferrer nofollow">Notebooks on GitHub</a> <add>- <a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb" target="_blank" rel="noopener noreferrer nofollow">How to open Notebooks from GitHub using Google Colab.</a> <ide> <ide> # --question-- <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/ask-browsers-to-access-your-site-via-https-only-with-helmet.hsts.md <ide> dashedName: ask-browsers-to-access-your-site-via-https-only-with-helmet-hsts <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-infosec" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-infosec/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> HTTP Strict Transport Security (HSTS) is a web security policy which helps to protect websites against protocol downgrade attacks and cookie hijacking. If your website can be accessed via HTTPS you can ask user’s browsers to avoid using insecure HTTP. By setting the header Strict-Transport-Security, you tell the browsers to use HTTPS for the future requests in a specified amount of time. This will work for the requests coming after the initial request. <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/avoid-inferring-the-response-mime-type-with-helmet.nosniff.md <ide> dashedName: avoid-inferring-the-response-mime-type-with-helmet-nosniff <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). Browsers can use content or MIME sniffing to override response `Content-Type` headers to guess and process the data using an implicit content type. While this can be convenient in some scenarios, it can also lead to some dangerous attacks. This middleware sets the X-Content-Type-Options header to `nosniff`, instructing the browser to not bypass the provided `Content-Type`. <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-infosec" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-infosec/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. Browsers can use content or MIME sniffing to override response `Content-Type` headers to guess and process the data using an implicit content type. While this can be convenient in some scenarios, it can also lead to some dangerous attacks. This middleware sets the X-Content-Type-Options header to `nosniff`, instructing the browser to not bypass the provided `Content-Type`. <ide> <ide> # --instructions-- <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/configure-helmet-using-the-parent-helmet-middleware.md <ide> dashedName: configure-helmet-using-the-parent-helmet-middleware <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-infosec" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-infosec/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> `app.use(helmet())` will automatically include all the middleware introduced above, except `noCache()`, and `contentSecurityPolicy()`, but these can be enabled if necessary. You can also disable or configure any other middleware individually, using a configuration object. <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/disable-client-side-caching-with-helmet.nocache.md <ide> dashedName: disable-client-side-caching-with-helmet-nocache <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-infosec" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-infosec/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> If you are releasing an update for your website, and you want the users to always download the newer version, you can (try to) disable caching on client’s browser. It can be useful in development too. Caching has performance benefits, which you will lose, so only use this option when there is a real need. <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/disable-dns-prefetching-with-helmet.dnsprefetchcontrol.md <ide> dashedName: disable-dns-prefetching-with-helmet-dnsprefetchcontrol <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-infosec" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-infosec/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> To improve performance, most browsers prefetch DNS records for the links in a page. In that way the destination ip is already known when the user clicks on a link. This may lead to over-use of the DNS service (if you own a big website, visited by millions people…), privacy issues (one eavesdropper could infer that you are on a certain page), or page statistics alteration (some links may appear visited even if they are not). If you have high security needs you can disable DNS prefetching, at the cost of a performance penalty. <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/hash-and-compare-passwords-asynchronously.md <ide> dashedName: hash-and-compare-passwords-asynchronously <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-bcrypt), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-bcrypt/). <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-bcrypt" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-bcrypt/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> As hashing is designed to be computationally intensive, it is recommended to do so asynchronously on your server as to avoid blocking incoming connections while you hash. All you have to do to hash a password asynchronous is call <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/hash-and-compare-passwords-synchronously.md <ide> dashedName: hash-and-compare-passwords-synchronously <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-bcrypt), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-bcrypt/). <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-bcrypt" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-bcrypt/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> Hashing synchronously is just as easy to do but can cause lag if using it server side with a high cost or with hashing done very often. Hashing with this method is as easy as calling <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/hide-potentially-dangerous-information-using-helmet.hidepoweredby.md <ide> dashedName: hide-potentially-dangerous-information-using-helmet-hidepoweredby <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-infosec" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-infosec/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> Hackers can exploit known vulnerabilities in Express/Node if they see that your site is powered by Express. `X-Powered-By: Express` is sent in every request coming from Express by default. Use the `helmet.hidePoweredBy()` middleware to remove the X-Powered-By header. <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/install-and-require-helmet.md <ide> dashedName: install-and-require-helmet <ide> <ide> Working on these challenges will involve you writing your code using one of the following methods: <ide> <del>- Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-infosec/) and complete these challenges locally. <del>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-infosec) to complete these challenges. <add>- Clone <a href="https://github.com/freeCodeCamp/boilerplate-infosec/" target="_blank" rel="noopener noreferrer nofollow">this GitHub repo</a> and complete these challenges locally. <add>- Use <a href="https://replit.com/github/freeCodeCamp/boilerplate-infosec" target="_blank" rel="noopener noreferrer nofollow">our Replit starter project</a> to complete these challenges. <ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo. <ide> <ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/mitigate-the-risk-of-clickjacking-with-helmet.frameguard.md <ide> dashedName: mitigate-the-risk-of-clickjacking-with-helmet-frameguard <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-infosec" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-infosec/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> Your page could be put in a `<frame>` or `<iframe>` without your consent. This can result in clickjacking attacks, among other things. Clickjacking is a technique of tricking a user into interacting with a page different from what the user thinks it is. This can be obtained executing your page in a malicious context, by mean of iframing. In that context a hacker can put a hidden layer over your page. Hidden buttons can be used to run bad scripts. This middleware sets the X-Frame-Options header. It restricts who can put your site in a frame. It has three modes: DENY, SAMEORIGIN, and ALLOW-FROM. <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/mitigate-the-risk-of-cross-site-scripting-xss-attacks-with-helmet.xssfilter.md <ide> dashedName: mitigate-the-risk-of-cross-site-scripting-xss-attacks-with-helmet-xs <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-infosec" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-infosec/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> Cross-site scripting (XSS) is a frequent type of attack where malicious scripts are injected into vulnerable pages, with the purpose of stealing sensitive data like session cookies, or passwords. <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/prevent-ie-from-opening-untrusted-html-with-helmet.ienoopen.md <ide> dashedName: prevent-ie-from-opening-untrusted-html-with-helmet-ienoopen <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-infosec" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-infosec/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> Some web applications will serve untrusted HTML for download. Some versions of Internet Explorer by default open those HTML files in the context of your site. This means that an untrusted HTML page could start doing bad things in the context of your pages. This middleware sets the X-Download-Options header to noopen. This will prevent IE users from executing downloads in the trusted site’s context. <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/set-a-content-security-policy-with-helmet.contentsecuritypolicy.md <ide> dashedName: set-a-content-security-policy-with-helmet-contentsecuritypolicy <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-infosec" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-infosec/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> This challenge highlights one promising new defense that can significantly reduce the risk and impact of many type of attacks in modern browsers. By setting and configuring a Content Security Policy you can prevent the injection of anything unintended into your page. This will protect your app from XSS vulnerabilities, undesired tracking, malicious frames, and much more. CSP works by defining an allowed list of content sources which are trusted. You can configure them for each kind of resource a web page may need (scripts, stylesheets, fonts, frames, media, and so on…). There are multiple directives available, so a website owner can have a granular control. See HTML 5 Rocks, KeyCDN for more details. Unfortunately CSP is unsupported by older browser. <ide> <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/understand-bcrypt-hashes.md <ide> dashedName: understand-bcrypt-hashes <ide> <ide> # --description-- <ide> <del>For the following challenges, you will be working with a new starter project that is different from the previous one. You can find the new starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-bcrypt), or clone it from [GitHub](https://github.com/freeCodeCamp/boilerplate-bcrypt/). <add>For the following challenges, you will be working with a new starter project that is different from the previous one. You can find the new starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-bcrypt" target="_blank" rel="noopener noreferrer nofollow">Replit</a>, or clone it from <a href="https://github.com/freeCodeCamp/boilerplate-bcrypt/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> BCrypt hashes are very secure. A hash is basically a fingerprint of the original data- always unique. This is accomplished by feeding the original data into an algorithm and returning a fixed length result. To further complicate this process and make it more secure, you can also *salt* your hash. Salting your hash involves adding random data to the original data before the hashing process which makes it even harder to crack the hash. <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/data-structures/remove-elements-from-a-linked-list-by-index.md <ide> Let's write a `removeAt` method that removes the `element` at a given `index`. T <ide> <ide> A common technique used to iterate through the elements of a linked list involves a <dfn>'runner'</dfn>, or sentinel, that 'points' at the nodes that your code is comparing. In our case, starting at the `head` of our list, we start with a `currentIndex` variable that starts at `0`. The `currentIndex` should increment by one for each node we pass. <ide> <del>Just like our `remove(element)` method, which [we covered in a previous lesson](/learn/coding-interview-prep/data-structures/remove-elements-from-a-linked-list), we need to be careful not to orphan the rest of our list when we remove the node in our `removeAt(index)` method. We keep our nodes contiguous by making sure that the node that has reference to the removed node has a reference to the next node. <add>Just like our `remove(element)` method, which <a href="/learn/coding-interview-prep/data-structures/remove-elements-from-a-linked-list" target="_blank" rel="noopener noreferrer nofollow">we covered in a previous lesson</a>, we need to be careful not to orphan the rest of our list when we remove the node in our `removeAt(index)` method. We keep our nodes contiguous by making sure that the node that has reference to the removed node has a reference to the next node. <ide> <ide> # --instructions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/averages-pythagorean-means.md <ide> dashedName: averagespythagorean-means <ide> <ide> # --description-- <ide> <del>Compute all three of the [Pythagorean means](<https://en.wikipedia.org/wiki/Pythagorean means> "wp: Pythagorean means") of the set of integers $1$ through $10$ (inclusive). <add>Compute all three of the <a href="<https://en.wikipedia.org/wiki/Pythagorean means> "wp: Pythagorean means"" target="_blank" rel="noopener noreferrer nofollow">Pythagorean means</a> of the set of integers $1$ through $10$ (inclusive). <ide> <ide> Show that $A(x_1,\\ldots,x_n) \\geq G(x_1,\\ldots,x_n) \\geq H(x_1,\\ldots,x_n)$ for this set of positive integers. <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/comma-quibbling.md <ide> dashedName: comma-quibbling <ide> <ide> # --description-- <ide> <del>[Comma quibbling](https://rosettacode.org/wiki/Comma_quibbling) is a task originally set by Eric Lippert in his 2009 blog. In this challenge, you will create a `string` from an `array`. You have to account for the `array` having no items, a single item, or multiple items in it. <add><a href="https://rosettacode.org/wiki/Comma_quibbling" target="_blank" rel="noopener noreferrer nofollow">Comma quibbling</a> is a task originally set by Eric Lippert in his blog. <ide> <ide> # --instructions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/euler-method.md <ide> dashedName: euler-method <ide> <ide> # --description-- <ide> <del>Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in [this article](<https://www.freecodecamp.org/news/eulers-method-explained-with-examples/> "news: Euler's Method Explained with Examples"). <add>Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in <a href="https://www.freecodecamp.org/news/eulers-method-explained-with-examples/" title="Euler's Method Explained with Examples" target="_blank" rel="noopener noreferrer nofollow">this article</a>. <ide> <ide> The ODE has to be provided in the following form: <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/execute-brain.md <ide> dashedName: execute-brain <ide> <ide> Write a function to implement a Brain\*\*\*\* interpreter. The function will take a string as a parameter and should return a string as the output. More details are given below: <ide> <del>RCBF is a set of [Brainf\*\*\*](https://rosettacode.org/wiki/Brainf*** "Brainf\*\*\*") compilers and interpreters written for Rosetta Code in a variety of languages. <add>RCBF is a set of <a href="https://rosettacode.org/wiki/Brainf***" target="_blank" rel="noopener noreferrer nofollow">Brainf\*\*\*</a> compilers and interpreters written for Rosetta Code in a variety of languages. <ide> <ide> Below are links to each of the versions of RCBF. <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/factors-of-a-mersenne-number.md <ide> A Mersenne number is a number in the form of <code>2<sup>P</sup>-1</code>. <ide> <ide> If `P` is prime, the Mersenne number may be a Mersenne prime. (If `P` is not prime, the Mersenne number is also not prime.) <ide> <del>In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, [Lucas-Lehmer test](<https://rosettacode.org/wiki/Lucas-Lehmer test> "Lucas-Lehmer test"). <add>In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, <a href="https://rosettacode.org/wiki/Lucas-Lehmer test" target="_blank" rel="noopener noreferrer nofollow">Lucas-Lehmer test</a>. <ide> <ide> There are very efficient algorithms for determining if a number divides <code>2<sup>P</sup>-1</code> (or equivalently, if <code>2<sup>P</sup> mod (the number) = 1</code>). <ide> <ide> Further properties of Mersenne numbers allow us to refine the process even more. <ide> <ide> Any factor `q` of <code>2<sup>P</sup>-1</code> must be of the form `2kP+1`, `k` being a positive integer or zero. Furthermore, `q` must be `1` or `7 mod 8`. <ide> <del>Finally any potential factor `q` must be [prime](<https://rosettacode.org/wiki/Primality by Trial Division> "Primality by Trial Division"). <add>Finally any potential factor `q` must be <a href="<https://rosettacode.org/wiki/Primality by Trial Division> "Primality by Trial Division"" target="_blank" rel="noopener noreferrer nofollow">prime</a>. <ide> <ide> As in other trial division algorithms, the algorithm stops when `2kP+1 > sqrt(N)`.These primarily tests only work on Mersenne numbers where `P` is prime. For example, <code>M<sub>4</sub>=15</code> yields no factors using these techniques, but factors into 3 and 5, neither of which fit `2kP+1`. <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/fibonacci-word.md <ide> Form F_Word<sub>3</sub> as F_Word<sub>2</sub> concatenated with F_Word<su <ide> Form F_Word<sub>n</sub> as F_Word<sub>n-1</sub> concatenated with F_word<sub>n-2</sub> <ide> </pre> <ide> <del>Entropy calculation is required in this challenge, [as shown in this Rosetta Code challenge](https://www.freecodecamp.org/learn/coding-interview-prep/rosetta-code/entropy) <add>Entropy calculation is required in this challenge, <a href="https://www.freecodecamp.org/learn/coding-interview-prep/rosetta-code/entropy" target="_blank" rel="noopener noreferrer nofollow">as shown in this Rosetta Code challenge</a> <ide> <ide> # --instructions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/general-fizzbuzz.md <ide> dashedName: general-fizzbuzz <ide> <ide> # --description-- <ide> <del>Write a generalized version of [FizzBuzz](https://rosettacode.org/wiki/FizzBuzz) that works for any list of factors, along with their words. <add>Write a generalized version of <a href="https://rosettacode.org/wiki/FizzBuzz" target="_blank" rel="noopener noreferrer nofollow">FizzBuzz</a> that works for any list of factors, along with their words. <ide> <ide> This is basically a "fizzbuzz" implementation where the rules of the game are supplied to the user. Create a function to implement this. The function should take two parameters. <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/least-common-multiple.md <ide> dashedName: least-common-multiple <ide> <ide> # --description-- <ide> <del>The least common multiple of 12 and 18 is 36, because 12 is a factor (12 × 3 = 36), and 18 is a factor (18 × 2 = 36), and there is no positive integer less than 36 that has both factors. As a special case, if either $m$ or $n$ is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of $m$, until you find one that is also a multiple of $n$. If you already have $gcd$ for [greatest common divisor](<https://rosettacode.org/wiki/greatest common divisor>), then this formula calculates $lcm$. <add>The least common multiple of 12 and 18 is 36, because 12 is a factor (12 × 3 = 36), and 18 is a factor (18 × 2 = 36), and there is no positive integer less than 36 that has both factors. As a special case, if either $m$ or $n$ is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of $m$, until you find one that is also a multiple of $n$. If you already have $gcd$ for <a href="https://rosettacode.org/wiki/greatest" target="_blank" rel="noopener noreferrer nofollow">greatest common divisor</a>, then this formula calculates $lcm$. <ide> <ide> $$ <ide> \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)} <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/s-expressions.md <ide> dashedName: s-expressions <ide> <ide> # --description-- <ide> <del><a href="https://rosettacode.org/wiki/S-expressions" target="_blank" rel="noopener noreferrer nofollow">S-Expressions</a> present data as a binary tree structure, making it possible to reference part of the data easily. This makes it convenient to parse and store data also. <add><a href="https://rosettacode.org/wiki/S-expressions " target="_blank" rel="noopener noreferrer nofollow">S-Expressions</a> are one convenient way to parse and store data. <ide> <ide> # --instructions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/self-referential-sequence.md <ide> dashedName: self-referential-sequence <ide> <ide> # --description-- <ide> <del>There are several ways to generate a self-referential sequence. One very common one (the [Look-and-say sequence](<https://rosettacode.org/wiki/Look-and-say sequence>)) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: <add>There are several ways to generate a self-referential sequence. One very common one (the <a href="https://rosettacode.org/wiki/Look-and-say" target="_blank" rel="noopener noreferrer nofollow">Look-and-say sequence</a>) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: <ide> <ide> <pre>0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...</pre> <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/semiprime.md <ide> dashedName: semiprime <ide> <ide> # --description-- <ide> <del>Semiprime numbers are natural numbers that are products of exactly two (possibly equal) [prime numbers](https://rosettacode.org/wiki/prime_number). <add>Semiprime numbers are natural numbers that are products of exactly two (possibly equal) <a href="https://rosettacode.org/wiki/prime_number" target="_blank" rel="noopener noreferrer nofollow">prime numbers</a>. <ide> <ide> <pre>1679 = 23 x 73</pre> <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/sha-1.md <ide> BitTorrent uses SHA-1 to verify downloads. <ide> <ide> Git and Mercurial use SHA-1 digests to identify commits. <ide> <del>A US government standard, [FIPS 180-1](https://rosettacode.org/wiki/SHA-1/FIPS-180-1), defines SHA-1. <add>A US government standard, <a href="https://rosettacode.org/wiki/SHA-1/FIPS-180-1" target="_blank" rel="noopener noreferrer nofollow">FIPS 180-1</a>, defines SHA-1. <ide> <ide> # --instructions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/sort-stability.md <ide> dashedName: sort-stability <ide> <ide> # --description-- <ide> <del>When sorting records in a table by a particular column or field, a [stable sort](https://www.freecodecamp.org/news/stability-in-sorting-algorithms-a-treatment-of-equality-fa3140a5a539/) will always retain the relative order of records that have the same key. <add>When sorting records in a table by a particular column or field, a <a href="https://www.freecodecamp.org/news/stability-in-sorting-algorithms-a-treatment-of-equality-fa3140a5a539/" target="_blank" rel="noopener noreferrer nofollow">stable sort</a> will always retain the relative order of records that have the same key. <ide> <ide> For example, in this table of countries and cities, a stable sort on the **second** column, the cities, would keep the US Birmingham above the UK Birmingham. (Although an unstable sort *might*, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would *guarantee* it). <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/sorting-algorithms-cocktail-sort.md <ide> dashedName: sorting-algorithmscocktail-sort <ide> <ide> # --description-- <ide> <del>The [cocktail shaker](https://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort) sort is an improvement on the Bubble Sort. Given an array of numbers, the cocktail shaker sort will traverse the array from start to finish, moving the largest number to the end. Then, it will traverse the array backwards and move the smallest number to the start. It repeats these two passes, moving the next largest/smallest number to its correct position in the array until it is sorted. <add>The <a href="https://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort" target="_blank" rel="noopener noreferrer nofollow">cocktail shaker</a> sort is an improvement on the Bubble Sort. Given an array of numbers, the cocktail shaker sort will traverse the array from start to finish, moving the largest number to the end. Then, it will traverse the array backwards and move the smallest number to the start. It repeats these two passes, moving the next largest/smallest number to its correct position in the array until it is sorted. <ide> <ide> # --instructions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/sorting-algorithms-gnome-sort.md <ide> dashedName: sorting-algorithmsgnome-sort <ide> <ide> # --description-- <ide> <del>Gnome sort is a sorting algorithm which is similar to [Insertion sort](<https://rosettacode.org/wiki/Insertion sort>), except that moving an element to its proper place is accomplished by a series of swaps, as in [Bubble Sort](<https://rosettacode.org/wiki/Bubble Sort>). <add>Gnome sort is a sorting algorithm which is similar to <a href="https://rosettacode.org/wiki/Insertion" target="_blank" rel="noopener noreferrer nofollow">Insertion sort</a>, except that moving an element to its proper place is accomplished by a series of swaps, as in <a href="https://rosettacode.org/wiki/Bubble" target="_blank" rel="noopener noreferrer nofollow">Bubble Sort</a>. <ide> <ide> The pseudocode for the algorithm is: <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/stern-brocot-sequence.md <ide> dashedName: stern-brocot-sequence <ide> <ide> # --description-- <ide> <del>For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [Fibonacci sequence](<https://rosettacode.org/wiki/Fibonacci sequence>). <add>For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the <a href="<https://rosettacode.org/wiki/Fibonacci sequence>" target="_blank" rel="noopener noreferrer nofollow">Fibonacci sequence</a>. <ide> <ide> <ol> <ide> <li>The first and second members of the sequence are both 1:</li> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/y-combinator.md <ide> dashedName: y-combinator <ide> <ide> # --description-- <ide> <del>In strict [functional programming](<https://www.freecodecamp.org/news/the-principles-of-functional-programming/> "news: the principles of functional programming") and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. <add>In strict <a href="https://www.freecodecamp.org/news/the-principles-of-functional-programming/" target="_blank" rel="noopener noreferrer nofollow">functional programming</a> and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. <ide> <ide> The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called fixed-point combinators. <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-camper-leaderboard.md <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-light-bright-app.md <ide> dashedName: build-a-light-bright-app <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-nightlife-coordination-app.md <ide> dashedName: build-a-nightlife-coordination-app <ide> <ide> # --description-- <ide> <del>Build a full stack JavaScript app that is functionally similar to this: <https://yoyo44.herokuapp.com/>. Use a site builder of your choice to complete the project. <add>Build a full stack JavaScript app that is functionally similar to this: <a href="https://yoyo44.herokuapp.com/" target="_blank" rel="noopener noreferrer nofollow">https://yoyo44.herokuapp.com/</a>. Use a site builder of your choice to complete the project. <ide> <ide> Here are the specific user stories you should implement for this project: <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-pinterest-clone.md <ide> dashedName: build-a-pinterest-clone <ide> <ide> # --description-- <ide> <del>**Objective:** Build an app that is functionally similar to this: <https://build-a-pinterest-clone.freecodecamp.rocks/>. <add>**Objective:** Build an app that is functionally similar to this: <a href="https://build-a-pinterest-clone.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://build-a-pinterest-clone.freecodecamp.rocks/</a>. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever libraries or APIs you need. Give it your own personal style. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> Once you've finished implementing these user stories, enter the URL to your live app and, optionally, your GitHub repository. Then click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-pong-game.md <ide> dashedName: build-a-pong-game <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-recipe-box.md <ide> dashedName: build-a-recipe-box <ide> <ide> # --description-- <ide> <del>**Objective:** Build an app that is functionally similar to this: <https://codepen.io/freeCodeCamp/full/dNVazZ/>. <add>**Objective:** Build an app that is functionally similar to this: <a href="https://codepen.io/freeCodeCamp/full/dNVazZ/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/dNVazZ/</a>. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever libraries or APIs you need. Give it your own personal style. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-roguelike-dungeon-crawler-game.md <ide> dashedName: build-a-roguelike-dungeon-crawler-game <ide> <ide> # --description-- <ide> <del>**Objective:** Build an app that is functionally similar to this: <https://codepen.io/freeCodeCamp/full/apLXEJ/>. <add>**Objective:** Build an app that is functionally similar to this: <a href="https://codepen.io/freeCodeCamp/full/apLXEJ/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/apLXEJ/</a>. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever libraries or APIs you need. Give it your own personal style. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-simon-game.md <ide> dashedName: build-a-simon-game <ide> <ide> # --description-- <ide> <del>**Objective:** Build an app that is functionally similar to this: [https://codepen.io/freeCodeCamp/full/obYBjE](https://codepen.io/freeCodeCamp/full/obYBjE). <add>**Objective:** Build an app that is functionally similar to this: <a href="https://codepen.io/freeCodeCamp/full/obYBjE" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/obYBjE</a>. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever libraries or APIs you need. Give it your own personal style. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-tic-tac-toe-game.md <ide> dashedName: build-a-tic-tac-toe-game <ide> <ide> # --description-- <ide> <del>**Objective:** Build an app that is functionally similar to this: <https://codepen.io/freeCodeCamp/full/KzXQgy/>. <add>**Objective:** Build an app that is functionally similar to this: <a href="https://codepen.io/freeCodeCamp/full/KzXQgy/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/KzXQgy/</a>. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever libraries or APIs you need. Give it your own personal style. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-voting-app.md <ide> dashedName: build-a-voting-app <ide> <ide> # --description-- <ide> <del>Build a full stack JavaScript app that is functionally similar to this: <https://voting-app.freecodecamp.rocks/>. Use a site builder of your choice to complete the project. <add>Build a full stack JavaScript app that is functionally similar to this: <a href="https://voting-app.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://voting-app.freecodecamp.rocks/</a>. Use a site builder of your choice to complete the project. <ide> <ide> Here are the specific user stories you should implement for this project: <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-wikipedia-viewer.md <ide> dashedName: build-a-wikipedia-viewer <ide> <ide> # --description-- <ide> <del>**Objective:** Build an app that is functionally similar to this: <https://codepen.io/freeCodeCamp/full/wGqEga/>. <add>**Objective:** Build an app that is functionally similar to this: <a href="https://codepen.io/freeCodeCamp/full/wGqEga/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/wGqEga/</a>. <ide> <ide> The MediaWiki software powers Wikipedia, and it helps you collect and organize knowledge and make it available to people. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-an-image-search-abstraction-layer.md <ide> dashedName: build-an-image-search-abstraction-layer <ide> <ide> # --description-- <ide> <del>Build a full stack JavaScript app that allows you to search for images like this: <https://image-search-abstraction-layer.freecodecamp.rocks/query/lolcats%20funny?page=10> and browse recent search queries like this: <https://image-search-abstraction-layer.freecodecamp.rocks/recent/>. Use a site builder of your choice to complete the project. <add>Build a full stack JavaScript app that allows you to search for images like this: <a href="https://image-search-abstraction-layer.freecodecamp.rocks/query/lolcats%20funny?page=10>" target="_blank" rel="noopener noreferrer nofollow">https://image-search-abstraction-layer.freecodecamp.rocks/query/lolcats%20funny?page=10</a> and browse recent search queries like this: <a href="https://image-search-abstraction-layer.freecodecamp.rocks/recent/" target="_blank" rel="noopener noreferrer nofollow">https://image-search-abstraction-layer.freecodecamp.rocks/recent/</a>. Use a site builder of your choice to complete the project. <ide> <ide> Here are the specific user stories you should implement for this project: <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-the-game-of-life.md <ide> dashedName: build-the-game-of-life <ide> <ide> # --description-- <ide> <del>**Objective:** Build an app that is functionally similar to this: <https://codepen.io/freeCodeCamp/full/BpwMZv/>. <add>**Objective:** Build an app that is functionally similar to this: <a href="https://codepen.io/freeCodeCamp/full/BpwMZv/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/BpwMZv/</a>. <ide> <ide> The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway. It is a <em>zero-player game</em>, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> When you are finished, include a link to your project and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/chart-the-stock-market.md <ide> dashedName: chart-the-stock-market <ide> <ide> # --description-- <ide> <del>Build a full stack JavaScript app that is functionally similar to this: <https://chart-the-stock-market.freecodecamp.rocks/>. Use a site builder of your choice to complete the project. <add>Build a full stack JavaScript app that is functionally similar to this: <a href="https://chart-the-stock-market.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://chart-the-stock-market.freecodecamp.rocks/</a>. Use a site builder of your choice to complete the project. <ide> <ide> Here are the specific user stories you should implement for this project: <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/manage-a-book-trading-club.md <ide> dashedName: manage-a-book-trading-club <ide> <ide> # --description-- <ide> <del>**Objective:** Build an app that is functionally similar to this: <https://manage-a-book-trading-club.freecodecamp.rocks/>. <add>**Objective:** Build an app that is functionally similar to this: <a href="https://manage-a-book-trading-club.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://manage-a-book-trading-club.freecodecamp.rocks/</a>. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever libraries or APIs you need. Give it your own personal style. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> Once you've finished implementing these user stories, enter the URL to your live app and, optionally, your GitHub repository. Then click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/map-data-across-the-globe.md <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/p2p-video-chat-application.md <ide> dashedName: p2p-video-chat-application <ide> <ide> # --description-- <ide> <del>**Objective:** Build an app that is functionally similar to this: <https://p2p-video-chat-application.freecodecamp.rocks/>. <add>**Objective:** Build an app that is functionally similar to this: <a href="https://p2p-video-chat-application.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://p2p-video-chat-application.freecodecamp.rocks/</a>. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever libraries or APIs you need. Give it your own personal style. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> Once you've finished implementing these user stories, enter the URL to your live app and, optionally, your GitHub repository. Then click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/show-national-contiguity-with-a-force-directed-graph.md <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/show-the-local-weather.md <ide> dashedName: show-the-local-weather <ide> <ide> **User Story:** I can push a button to toggle between Fahrenheit and Celsius. <ide> <del>**Note:** Many internet browsers now require an HTTP Secure (`https://`) connection to obtain a user's locale via HTML5 Geolocation. For this reason, we recommend using HTML5 Geolocation to get user location and then use the freeCodeCamp Weather API <https://weather-proxy.freecodecamp.rocks/> which uses an HTTP Secure connection for the weather. Also, be sure to connect to [CodePen.io](https://codepen.io) via `https://`. <add>**Note:** Many internet browsers now require an HTTP Secure (`https://`) connection to obtain a user's locale via HTML5 Geolocation. For this reason, we recommend using HTML5 Geolocation to get user location and then use the freeCodeCamp Weather API <a href="https://weather-proxy.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://weather-proxy.freecodecamp.rocks/</a> which uses an HTTP Secure connection for the weather. Also, be sure to connect to <a href="https://codepen.io" target="_blank" rel="noopener noreferrer nofollow">CodePen.io</a> via `https://`. <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/use-the-twitch-json-api.md <ide> dashedName: use-the-twitch-json-api <ide> <ide> # --description-- <ide> <del>**Objective:** Build an app that is functionally similar to this: <https://codepen.io/freeCodeCamp/full/Myvqmo/>. <add>**Objective:** Build an app that is functionally similar to this: <a href="https://codepen.io/freeCodeCamp/full/Myvqmo/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/Myvqmo/</a>. <ide> <ide> The Twitch API is a RESTful API that lets developers build creative integrations for the broader Twitch community. <ide> <ide> Fulfill the below user stories and get all of the tests to pass. Use whichever l <ide> <ide> **Hint:** Here's an array of the Twitch.tv usernames of people who regularly stream: `["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]` <ide> <del>**UPDATE:** Due to a change in conditions on API usage, Twitch.tv requires an API key, but we've built a workaround. Use <https://twitch-proxy.freecodecamp.rocks/> instead of Twitch's API base URL and you'll still be able to get account information, without needing to sign up for an API key. <add>**UPDATE:** Due to a change in conditions on API usage, Twitch.tv requires an API key, but we've built a workaround. Use <a href="https://twitch-proxy.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://twitch-proxy.freecodecamp.rocks/</a> instead of Twitch's API base URL and you'll still be able to get account information, without needing to sign up for an API key. <ide> <ide> When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button. <ide> <del>You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409). <add>You can get feedback on your project by sharing it on the <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp forum</a>. <ide> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6140827cff96e906bd38fc2b.md <ide> dashedName: step-9 <ide> <ide> # --description-- <ide> <del>As described in the [freeCodeCamp Style Guide](https://design-style-guide.freecodecamp.org/), the logo should retain an aspect ratio of `35 / 4`, and have padding around the text. <add>As described in the <a href="https://design-style-guide.freecodecamp.org/" target="_blank" rel="noopener noreferrer nofollow">freeCodeCamp Style Guide</a>, the logo should retain an aspect ratio of `35 / 4`, and have padding around the text. <ide> <ide> First, change the `background-color` to `#0a0a23` so you can see the logo. Then, use the `aspect-ratio` property to set the desired aspect ratio to `35 / 4`. Finally, add a `padding` of `0.4rem` all around. <ide>
117
Python
Python
add support for generators in text preprocessing
7386dff509604d2794df3c3c9af782cbe7b31447
<ide><path>keras/preprocessing/text.py <ide> <ide> def base_filter(): <ide> f = string.punctuation <add> f = f.replace("'", '') <ide> f += '\t\n' <ide> return f <ide> <ide> def text_to_word_sequence(text, filters=base_filter(), lower=True, split=" "): <ide> ''' <ide> if lower: <ide> text = text.lower() <del> text = text.translate(string.maketrans("",""), filters) <del> return text.split(split) <add> text = text.translate(string.maketrans(filters, split*len(filters))) <add> seq = text.split(split) <add> return filter(None, seq) <ide> <ide> <ide> def one_hot(text, n): <ide> def __init__(self, filters=base_filter(), lower=True, nb_words=None): <ide> def fit_on_texts(self, texts): <ide> ''' <ide> required before using texts_to_sequences or texts_to_matrix <add> @param texts: can be a list or a generator (for memory-efficiency) <ide> ''' <add> self.document_count = 0 <ide> for text in texts: <add> self.document_count += 1 <ide> seq = text_to_word_sequence(text, self.filters, self.lower) <ide> for w in seq: <ide> if w in self.word_counts: <ide> def fit_on_texts(self, texts): <ide> self.word_docs[w] += 1 <ide> else: <ide> self.word_docs[w] = 1 <del> self.document_count = len(texts) <ide> <ide> wcounts = self.word_counts.items() <ide> wcounts.sort(key = lambda x: x[1], reverse=True) <ide> sorted_voc = [wc[0] for wc in wcounts] <del> self.word_index = dict(zip(sorted_voc, range(len(sorted_voc)))) <add> self.word_index = dict(zip(sorted_voc, range(1, len(sorted_voc)+1))) <ide> <ide> self.index_docs = {} <ide> for w, c in self.word_docs.items(): <ide> def texts_to_sequences(self, texts): <ide> ''' <ide> Transform each text in texts in a sequence of integers. <ide> Only top "nb_words" most frequent words will be taken into account. <del> Only words know by the tokenizer will be taken into account. <add> Only words known by the tokenizer will be taken into account. <add> <add> Returns a list of sequences. <ide> ''' <del> nb_words = self.nb_words <ide> res = [] <add> for vect in self.texts_to_sequences_generator(texts): <add> res.append(vect) <add> return res <add> <add> def texts_to_sequences_generator(self, texts): <add> ''' <add> Transform each text in texts in a sequence of integers. <add> Only top "nb_words" most frequent words will be taken into account. <add> Only words known by the tokenizer will be taken into account. <add> <add> Yields individual sequences. <add> ''' <add> nb_words = self.nb_words <ide> for text in texts: <ide> seq = text_to_word_sequence(text, self.filters, self.lower) <ide> vect = [] <ide> def texts_to_sequences(self, texts): <ide> pass <ide> else: <ide> vect.append(i) <del> res.append(vect) <del> return res <add> yield vect <add> <ide> <ide> def texts_to_matrix(self, texts, mode="binary"): <ide> '''
1
Text
Text
add empty focus template for week of 2018-02-19
cda838250b0968a4c1e9f1665c05ceb26a2c3d61
<ide><path>docs/focus/2018-02-19.md <add>## Highlights from the past week <add> <add>- Atom IDE <add>- @atom/watcher <add>- GitHub Package <add>- Teletype <add>- Xray <add> <add>## Focus for week ahead <add> <add>- Atom IDE <add>- @atom/watcher <add>- GitHub Package <add>- Teletype <add>- Tree-sitter <add>- Xray
1
Text
Text
fix small error
28de4b00dcea3fc54366e0e12ea4b2e9a0c0cb43
<ide><path>docs/general/options.md <ide> Options are resolved from top to bottom, using a context dependent route. <ide> <ide> ### Dataset element level options <ide> <del>Each scope is looked up with `elementType` prefix in the option name first, then wihtout the prefix. For example, `radius` for `point` element is looked up using `pointRadius` and if that does not hit, then `radius`. <add>Each scope is looked up with `elementType` prefix in the option name first, then without the prefix. For example, `radius` for `point` element is looked up using `pointRadius` and if that does not hit, then `radius`. <ide> <ide> * dataset <ide> * options.datasets[`dataset.type`]
1
Javascript
Javascript
fix error handling
acc3c770e7717673ee87fa37076fc50fcb91e4ea
<ide><path>lib/internal/fs.js <ide> function isUint32(n) { return n === (n >>> 0); } <ide> function modeNum(m, def) { <ide> if (typeof m === 'number') <ide> return m; <del> if (typeof m === 'string') <del> return parseInt(m, 8); <del> if (def) <del> return modeNum(def); <del> return undefined; <add> if (typeof m === 'string') { <add> const parsed = parseInt(m, 8); <add> if (Number.isNaN(parsed)) <add> return m; <add> return parsed; <add> } <add> // TODO(BridgeAR): Only return `def` in case `m == null` <add> if (def !== undefined) <add> return def; <add> return m; <ide> } <ide> <ide> // Check if the path contains null types if it is a string nor Uint8Array, <ide> function validateBuffer(buffer) { <ide> function validateLen(len) { <ide> let err; <ide> <del> if (!isInt32(len)) <del> err = new ERR_INVALID_ARG_TYPE('len', 'integer'); <add> if (!isInt32(len)) { <add> if (typeof value !== 'number') { <add> err = new ERR_INVALID_ARG_TYPE('len', 'number', len); <add> } else { <add> // TODO(BridgeAR): Improve this error message. <add> err = new ERR_OUT_OF_RANGE('len', 'an integer', len); <add> } <add> } <ide> <ide> if (err !== undefined) { <ide> Error.captureStackTrace(err, validateLen); <ide> function validatePath(path, propName = 'path') { <ide> } <ide> <ide> function validateUint32(value, propName) { <del> let err; <del> <del> if (!isUint32(value)) <del> err = new ERR_INVALID_ARG_TYPE(propName, 'integer'); <del> <del> if (err !== undefined) { <add> if (!isUint32(value)) { <add> let err; <add> if (typeof value !== 'number') { <add> err = new ERR_INVALID_ARG_TYPE(propName, 'number', value); <add> } else if (!Number.isInteger(value)) { <add> err = new ERR_OUT_OF_RANGE(propName, 'an integer', value); <add> } else { <add> // 2 ** 32 === 4294967296 <add> err = new ERR_OUT_OF_RANGE(propName, '>= 0 && < 4294967296', value); <add> } <ide> Error.captureStackTrace(err, validateUint32); <ide> throw err; <ide> } <ide><path>test/parallel/test-fs-chmod.js <ide> fs.open(file2, 'w', common.mustCall((err, fd) => { <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <del> message: 'The "mode" argument must be of type integer' <add> message: 'The "mode" argument must be of type number. ' + <add> 'Received type object' <ide> } <ide> ); <ide> <ide> if (fs.lchmod) { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <del> message: 'The "fd" argument must be of type integer' <add> message: 'The "fd" argument must be of type number. ' + <add> `Received type ${typeof input}` <ide> }; <ide> assert.throws(() => fs.fchmod(input, 0o000), errObj); <ide> assert.throws(() => fs.fchmodSync(input, 0o000), errObj); <ide><path>test/parallel/test-fs-close-errors.js <ide> const fs = require('fs'); <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <del> message: 'The "fd" argument must be of type integer' <add> message: 'The "fd" argument must be of type number. ' + <add> `Received type ${typeof input}` <ide> }; <ide> assert.throws(() => fs.close(input), errObj); <ide> assert.throws(() => fs.closeSync(input), errObj); <ide><path>test/parallel/test-fs-fchmod.js <ide> 'use strict'; <ide> const common = require('../common'); <add>const assert = require('assert'); <ide> const fs = require('fs'); <ide> <ide> // This test ensures that input for fchmod is valid, testing for valid <ide> // inputs for fd and mode <ide> <ide> // Check input type <del>['', false, null, undefined, {}, [], Infinity, -1].forEach((i) => { <del> common.expectsError( <del> () => fs.fchmod(i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "fd" argument must be of type integer' <del> } <del> ); <del> common.expectsError( <del> () => fs.fchmodSync(i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "fd" argument must be of type integer' <del> } <del> ); <add>[false, null, undefined, {}, [], ''].forEach((input) => { <add> const errObj = { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> message: 'The "fd" argument must be of type number. Received type ' + <add> typeof input <add> }; <add> assert.throws(() => fs.fchmod(input), errObj); <add> assert.throws(() => fs.fchmodSync(input), errObj); <add> errObj.message = errObj.message.replace('fd', 'mode'); <add> assert.throws(() => fs.fchmod(1, input), errObj); <add> assert.throws(() => fs.fchmodSync(1, input), errObj); <add>}); <add> <add>[-1, 2 ** 32].forEach((input) => { <add> const errObj = { <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> message: 'The value of "fd" is out of range. It must be >= 0 && < ' + <add> `${2 ** 32}. Received ${input}` <add> }; <add> assert.throws(() => fs.fchmod(input), errObj); <add> assert.throws(() => fs.fchmodSync(input), errObj); <add> errObj.message = errObj.message.replace('fd', 'mode'); <add> assert.throws(() => fs.fchmod(1, input), errObj); <add> assert.throws(() => fs.fchmodSync(1, input), errObj); <add>}); <ide> <del> common.expectsError( <del> () => fs.fchmod(1, i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "mode" argument must be of type integer' <del> } <del> ); <del> common.expectsError( <del> () => fs.fchmodSync(1, i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "mode" argument must be of type integer' <del> } <del> ); <add>[NaN, Infinity].forEach((input) => { <add> const errObj = { <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> message: 'The value of "fd" is out of range. It must be an integer. ' + <add> `Received ${input}` <add> }; <add> assert.throws(() => fs.fchmod(input), errObj); <add> assert.throws(() => fs.fchmodSync(input), errObj); <add> errObj.message = errObj.message.replace('fd', 'mode'); <add> assert.throws(() => fs.fchmod(1, input), errObj); <add> assert.throws(() => fs.fchmodSync(1, input), errObj); <add>}); <add> <add>[1.5].forEach((input) => { <add> const errObj = { <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> message: 'The value of "fd" is out of range. It must be an integer. ' + <add> `Received ${input}` <add> }; <add> assert.throws(() => fs.fchmod(input), errObj); <add> assert.throws(() => fs.fchmodSync(input), errObj); <add> errObj.message = errObj.message.replace('fd', 'mode'); <add> assert.throws(() => fs.fchmod(1, input), errObj); <add> assert.throws(() => fs.fchmodSync(1, input), errObj); <ide> }); <ide> <ide> // Check for mode values range <ide><path>test/parallel/test-fs-fchown.js <ide> 'use strict'; <ide> <del>const common = require('../common'); <add>require('../common'); <add>const assert = require('assert'); <ide> const fs = require('fs'); <ide> <del>['', false, null, undefined, {}, [], Infinity, -1].forEach((i) => { <del> common.expectsError( <del> () => fs.fchown(i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "fd" argument must be of type integer' <del> } <del> ); <del> common.expectsError( <del> () => fs.fchownSync(i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "fd" argument must be of type integer' <del> } <del> ); <add>function test(input, errObj) { <add> assert.throws(() => fs.fchown(input), errObj); <add> assert.throws(() => fs.fchownSync(input), errObj); <add> errObj.message = errObj.message.replace('fd', 'uid'); <add> assert.throws(() => fs.fchown(1, input), errObj); <add> assert.throws(() => fs.fchownSync(1, input), errObj); <add> errObj.message = errObj.message.replace('uid', 'gid'); <add> assert.throws(() => fs.fchown(1, 1, input), errObj); <add> assert.throws(() => fs.fchownSync(1, 1, input), errObj); <add>} <ide> <del> common.expectsError( <del> () => fs.fchown(1, i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "uid" argument must be of type integer' <del> } <del> ); <del> common.expectsError( <del> () => fs.fchownSync(1, i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "uid" argument must be of type integer' <del> } <del> ); <add>['', false, null, undefined, {}, []].forEach((input) => { <add> const errObj = { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> message: 'The "fd" argument must be of type number. Received type ' + <add> typeof input <add> }; <add> test(input, errObj); <add>}); <add> <add>[Infinity, NaN].forEach((input) => { <add> const errObj = { <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> message: 'The value of "fd" is out of range. It must be an integer. ' + <add> `Received ${input}` <add> }; <add> test(input, errObj); <add>}); <ide> <del> common.expectsError( <del> () => fs.fchown(1, 1, i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "gid" argument must be of type integer' <del> } <del> ); <del> common.expectsError( <del> () => fs.fchownSync(1, 1, i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "gid" argument must be of type integer' <del> } <del> ); <add>[-1, 2 ** 32].forEach((input) => { <add> const errObj = { <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> message: 'The value of "fd" is out of range. It must be ' + <add> `>= 0 && < 4294967296. Received ${input}` <add> }; <add> test(input, errObj); <ide> }); <ide><path>test/parallel/test-fs-fsync.js <ide> fs.open(fileTemp, 'a', 0o777, common.mustCall(function(err, fd) { <ide> })); <ide> })); <ide> <del>['', false, null, undefined, {}, []].forEach((i) => { <del> common.expectsError( <del> () => fs.fdatasync(i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "fd" argument must be of type integer' <del> } <del> ); <del> common.expectsError( <del> () => fs.fdatasyncSync(i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "fd" argument must be of type integer' <del> } <del> ); <del> common.expectsError( <del> () => fs.fsync(i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "fd" argument must be of type integer' <del> } <del> ); <del> common.expectsError( <del> () => fs.fsyncSync(i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "fd" argument must be of type integer' <del> } <del> ); <add>['', false, null, undefined, {}, []].forEach((input) => { <add> const errObj = { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> message: 'The "fd" argument must be of type number. Received type ' + <add> typeof input <add> }; <add> assert.throws(() => fs.fdatasync(input), errObj); <add> assert.throws(() => fs.fdatasyncSync(input), errObj); <add> assert.throws(() => fs.fsync(input), errObj); <add> assert.throws(() => fs.fsyncSync(input), errObj); <ide> }); <ide><path>test/parallel/test-fs-read-type.js <ide> common.expectsError( <ide> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <del> message: 'The "fd" argument must be of type integer' <add> message: 'The "fd" argument must be of type number. ' + <add> `Received type ${typeof value}` <ide> }); <ide> }); <ide> <ide> common.expectsError( <ide> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <del> message: 'The "fd" argument must be of type integer' <add> message: 'The "fd" argument must be of type number. ' + <add> `Received type ${typeof value}` <ide> }); <ide> }); <ide> <ide><path>test/parallel/test-fs-stat.js <ide> fs.stat(__filename, common.mustCall(function(err, s) { <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <del> message: 'The "fd" argument must be of type integer' <add> message: 'The "fd" argument must be of type number. ' + <add> `Received type ${typeof input}` <ide> } <ide> ); <ide> }); <ide><path>test/parallel/test-fs-symlink.js <ide> let fileTime; <ide> const tmpdir = require('../common/tmpdir'); <ide> tmpdir.refresh(); <ide> <del>// test creating and reading symbolic link <add>// Test creating and reading symbolic link <ide> const linkData = fixtures.path('/cycles/root.js'); <ide> const linkPath = path.join(tmpdir.path, 'symlink1.js'); <ide> <ide> fs.symlink(linkData, linkPath, common.mustCall(function(err) { <ide> })); <ide> })); <ide> <del>[false, 1, {}, [], null, undefined].forEach((i) => { <del> common.expectsError( <del> () => fs.symlink(i, '', common.mustNotCall()), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: <del> 'The "target" argument must be one of type string, Buffer, or URL' <del> } <del> ); <del> common.expectsError( <del> () => fs.symlink('', i, common.mustNotCall()), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: <del> 'The "path" argument must be one of type string, Buffer, or URL' <del> } <del> ); <del> common.expectsError( <del> () => fs.symlinkSync(i, ''), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: <del> 'The "target" argument must be one of type string, Buffer, or URL' <del> } <del> ); <del> common.expectsError( <del> () => fs.symlinkSync('', i), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: <del> 'The "path" argument must be one of type string, Buffer, or URL' <del> } <del> ); <add>[false, 1, {}, [], null, undefined].forEach((input) => { <add> const errObj = { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> message: 'The "target" argument must be one of type string, Buffer, or ' + <add> `URL. Received type ${typeof input}` <add> }; <add> assert.throws(() => fs.symlink(input, '', common.mustNotCall()), errObj); <add> assert.throws(() => fs.symlinkSync(input, ''), errObj); <add> <add> errObj.message = errObj.message.replace('target', 'path'); <add> assert.throws(() => fs.symlink('', input, common.mustNotCall()), errObj); <add> assert.throws(() => fs.symlinkSync('', input), errObj); <ide> }); <ide> <del>common.expectsError( <del> () => fs.symlink('', '', '🍏', common.mustNotCall()), <del> { <del> code: 'ERR_FS_INVALID_SYMLINK_TYPE', <del> type: Error, <del> message: <del> 'Symlink type must be one of "dir", "file", or "junction". Received "🍏"' <del> } <del>); <del>common.expectsError( <del> () => fs.symlinkSync('', '', '🍏'), <del> { <del> code: 'ERR_FS_INVALID_SYMLINK_TYPE', <del> type: Error, <del> message: <del> 'Symlink type must be one of "dir", "file", or "junction". Received "🍏"' <del> } <del>); <add>const errObj = { <add> code: 'ERR_FS_INVALID_SYMLINK_TYPE', <add> name: 'Error [ERR_FS_INVALID_SYMLINK_TYPE]', <add> message: <add> 'Symlink type must be one of "dir", "file", or "junction". Received "🍏"' <add>}; <add>assert.throws(() => fs.symlink('', '', '🍏', common.mustNotCall()), errObj); <add>assert.throws(() => fs.symlinkSync('', '', '🍏'), errObj); <ide> <ide> process.on('exit', function() { <ide> assert.notStrictEqual(linkTime, fileTime); <ide><path>test/parallel/test-fs-truncate.js <ide> function testFtruncate(cb) { <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <del> message: 'The "len" argument must be of type integer' <add> message: 'The "len" argument must be of type number. ' + <add> `Received type ${typeof input}` <ide> } <ide> ); <ide> }); <ide> function testFtruncate(cb) { <ide> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <del> message: 'The "fd" argument must be of type integer' <add> message: 'The "fd" argument must be of type number. ' + <add> `Received type ${typeof input}` <ide> } <ide> ); <ide> }); <ide><path>test/parallel/test-fs-utimes.js <ide> function testIt(atime, mtime, callback) { <ide> common.expectsError( <ide> () => fs.futimesSync(-1, atime, mtime), <ide> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError <add> code: 'ERR_OUT_OF_RANGE', <add> type: RangeError, <add> message: 'The value of "fd" is out of range. ' + <add> 'It must be >= 0 && < 4294967296. Received -1' <ide> } <ide> ); <ide> tests_run++; <ide> function testIt(atime, mtime, callback) { <ide> common.expectsError( <ide> () => fs.futimes(-1, atime, mtime, common.mustNotCall()), <ide> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <add> code: 'ERR_OUT_OF_RANGE', <add> type: RangeError, <add> message: 'The value of "fd" is out of range. ' + <add> 'It must be >= 0 && < 4294967296. Received -1' <ide> } <ide> ); <ide>
11
Ruby
Ruby
refine tests for assert_select failure messages
ce6f472f28715ad59be802db4280f99e517c4c39
<ide><path>actionpack/test/controller/assert_select_test.rb <ide> def assert_failure(message, &block) <ide> def test_assert_select <ide> render_html %Q{<div id="1"></div><div id="2"></div>} <ide> assert_select "div", 2 <del> assert_failure(/Expected at least 1 element matching \"p\", found 0/) { assert_select "p" } <add> assert_failure(/\AExpected at least 1 element matching \"p\", found 0\.$/) { assert_select "p" } <ide> end <ide> <ide> def test_equality_integer <ide> render_html %Q{<div id="1"></div><div id="2"></div>} <del> assert_failure(/Expected exactly 3 elements matching \"div\", found 2/) { assert_select "div", 3 } <del> assert_failure(/Expected exactly 0 elements matching \"div\", found 2/) { assert_select "div", 0 } <add> assert_failure(/\AExpected exactly 3 elements matching \"div\", found 2\.$/) { assert_select "div", 3 } <add> assert_failure(/\AExpected exactly 0 elements matching \"div\", found 2\.$/) { assert_select "div", 0 } <ide> end <ide> <ide> def test_equality_true_false <ide> def test_equality_true_false <ide> <ide> def test_equality_false_message <ide> render_html %Q{<div id="1"></div><div id="2"></div>} <del> assert_failure(/Expected exactly 0 elements matching \"div\", found 2/) { assert_select "div", false } <add> assert_failure(/\AExpected exactly 0 elements matching \"div\", found 2\.$/) { assert_select "div", false } <ide> end <ide> <ide> def test_equality_string_and_regexp <ide> render_html %Q{<div id="1">foo</div><div id="2">foo</div>} <ide> assert_nothing_raised { assert_select "div", "foo" } <ide> assert_raise(Assertion) { assert_select "div", "bar" } <add> assert_failure(/\A<bar> expected but was\n<foo>\.$/) { assert_select "div", "bar" } <ide> assert_nothing_raised { assert_select "div", :text=>"foo" } <ide> assert_raise(Assertion) { assert_select "div", :text=>"bar" } <ide> assert_nothing_raised { assert_select "div", /(foo|bar)/ } <ide> def test_equality_of_html <ide> assert_raise(Assertion) { assert_select "p", html } <ide> assert_nothing_raised { assert_select "p", :html=>html } <ide> assert_raise(Assertion) { assert_select "p", :html=>text } <add> assert_failure(/\A<#{text}> expected but was\n<#{html}>\.$/) { assert_select "p", :html=>text } <ide> # No stripping for pre. <ide> render_html %Q{<pre>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</pre>} <ide> text = "\n\"This is not a big problem,\" he said.\n" <ide> def test_strip_textarea <ide> def test_counts <ide> render_html %Q{<div id="1">foo</div><div id="2">foo</div>} <ide> assert_nothing_raised { assert_select "div", 2 } <del> assert_failure(/Expected exactly 3 elements matching \"div\", found 2/) do <add> assert_failure(/\AExpected exactly 3 elements matching \"div\", found 2\.$/) do <ide> assert_select "div", 3 <ide> end <ide> assert_nothing_raised { assert_select "div", 1..2 } <del> assert_failure(/Expected between 3 and 4 elements matching \"div\", found 2/) do <add> assert_failure(/\AExpected between 3 and 4 elements matching \"div\", found 2\.$/) do <ide> assert_select "div", 3..4 <ide> end <ide> assert_nothing_raised { assert_select "div", :count=>2 } <del> assert_failure(/Expected exactly 3 elements matching \"div\", found 2/) do <add> assert_failure(/\AExpected exactly 3 elements matching \"div\", found 2\.$/) do <ide> assert_select "div", :count=>3 <ide> end <ide> assert_nothing_raised { assert_select "div", :minimum=>1 } <ide> assert_nothing_raised { assert_select "div", :minimum=>2 } <del> assert_failure(/Expected at least 3 elements matching \"div\", found 2/) do <add> assert_failure(/\AExpected at least 3 elements matching \"div\", found 2\.$/) do <ide> assert_select "div", :minimum=>3 <ide> end <ide> assert_nothing_raised { assert_select "div", :maximum=>2 } <ide> assert_nothing_raised { assert_select "div", :maximum=>3 } <del> assert_failure(/Expected at most 1 element matching \"div\", found 2/) do <add> assert_failure(/\AExpected at most 1 element matching \"div\", found 2\.$/) do <ide> assert_select "div", :maximum=>1 <ide> end <ide> assert_nothing_raised { assert_select "div", :minimum=>1, :maximum=>2 } <del> assert_failure(/Expected between 3 and 4 elements matching \"div\", found 2/) do <add> assert_failure(/\AExpected between 3 and 4 elements matching \"div\", found 2\.$/) do <ide> assert_select "div", :minimum=>3, :maximum=>4 <ide> end <ide> end <ide> def test_nested_assert_select <ide> end <ide> end <ide> <del> assert_failure(/Expected at least 1 element matching \"#4\", found 0\./) do <add> assert_failure(/\AExpected at least 1 element matching \"#4\", found 0\.$/) do <ide> assert_select "div" do <ide> assert_select "#4" <ide> end
1
Python
Python
move linalg tests using matrix to matrixlib
121a2ee8d6ef43cde55b9f66a301c58cc9eb1623
<ide><path>numpy/linalg/tests/test_linalg.py <ide> import sys <ide> import itertools <ide> import traceback <del>import warnings <ide> import pytest <ide> <ide> import numpy as np <ide> from numpy import array, single, double, csingle, cdouble, dot, identity <del>from numpy import multiply, atleast_2d, inf, asarray, matrix <add>from numpy import multiply, atleast_2d, inf, asarray <ide> from numpy import linalg <ide> from numpy.linalg import matrix_power, norm, matrix_rank, multi_dot, LinAlgError <ide> from numpy.linalg.linalg import _multi_dot_matrix_chain_order <ide> ) <ide> <ide> <del>def ifthen(a, b): <del> return not a or b <del> <del> <del>def imply(a, b): <del> return not a or b <add>def consistent_subclass(out, in_): <add> # For ndarray subclass input, our output should have the same subclass <add> # (non-ndarray input gets converted to ndarray). <add> return type(out) is (type(in_) if isinstance(in_, np.ndarray) <add> else np.ndarray) <ide> <ide> <ide> old_assert_almost_equal = assert_almost_equal <ide> def get_rtol(dtype): <ide> 'generalized', 'size-0', 'strided' # optional additions <ide> } <ide> <add> <ide> class LinalgCase(object): <ide> def __init__(self, name, a, b, tags=set()): <ide> """ <ide> def check(self, do): <ide> def __repr__(self): <ide> return "<LinalgCase: %s>" % (self.name,) <ide> <add> <ide> def apply_tag(tag, cases): <ide> """ <ide> Add the given tag (a string) to each of the cases (a list of LinalgCase <ide> def apply_tag(tag, cases): <ide> np.empty((0, 0), dtype=double), <ide> np.empty((0,), dtype=double), <ide> tags={'size-0'}), <del> LinalgCase("0x0_matrix", <del> np.empty((0, 0), dtype=double).view(np.matrix), <del> np.empty((0, 1), dtype=double).view(np.matrix), <del> tags={'size-0'}), <ide> LinalgCase("8x8", <ide> np.random.rand(8, 8), <ide> np.random.rand(8)), <ide> def apply_tag(tag, cases): <ide> LinalgCase("nonarray", <ide> [[1, 2], [3, 4]], <ide> [2, 1]), <del> LinalgCase("matrix_b_only", <del> array([[1., 2.], [3., 4.]]), <del> matrix([2., 1.]).T), <del> LinalgCase("matrix_a_and_b", <del> matrix([[1., 2.], [3., 4.]]), <del> matrix([2., 1.]).T), <ide> ]) <ide> <ide> # non-square test-cases <ide> def apply_tag(tag, cases): <ide> LinalgCase("matrix_b_only", <ide> array([[1., 2.], [2., 1.]]), <ide> None), <del> LinalgCase("hmatrix_a_and_b", <del> matrix([[1., 2.], [2., 1.]]), <del> None), <ide> LinalgCase("hmatrix_1x1", <ide> np.random.rand(1, 1), <ide> None), <ide> def _make_generalized_cases(): <ide> <ide> return new_cases <ide> <add> <ide> CASES += _make_generalized_cases() <ide> <add> <ide> # <ide> # Generate stride combination variations of the above <ide> # <del> <ide> def _stride_comb_iter(x): <ide> """ <ide> Generate cartesian product of strides for all axes <ide> def _stride_comb_iter(x): <ide> xi = np.lib.stride_tricks.as_strided(x, strides=s) <ide> yield xi, "stride_xxx_0_0" <ide> <add> <ide> def _make_strided_cases(): <ide> new_cases = [] <ide> for case in CASES: <ide> def _make_strided_cases(): <ide> new_cases.append(new_case) <ide> return new_cases <ide> <add> <ide> CASES += _make_strided_cases() <ide> <ide> <ide> # <ide> # Test different routines against the above cases <ide> # <add>class LinalgTestCase(object): <add> TEST_CASES = CASES <ide> <del>def _check_cases(func, require=set(), exclude=set()): <del> """ <del> Run func on each of the cases with all of the tags in require, and none <del> of the tags in exclude <del> """ <del> for case in CASES: <del> # filter by require and exclude <del> if case.tags & require != require: <del> continue <del> if case.tags & exclude: <del> continue <add> def check_cases(self, require=set(), exclude=set()): <add> """ <add> Run func on each of the cases with all of the tags in require, and none <add> of the tags in exclude <add> """ <add> for case in self.TEST_CASES: <add> # filter by require and exclude <add> if case.tags & require != require: <add> continue <add> if case.tags & exclude: <add> continue <ide> <del> try: <del> case.check(func) <del> except Exception: <del> msg = "In test case: %r\n\n" % case <del> msg += traceback.format_exc() <del> raise AssertionError(msg) <add> try: <add> case.check(self.do) <add> except Exception: <add> msg = "In test case: %r\n\n" % case <add> msg += traceback.format_exc() <add> raise AssertionError(msg) <ide> <ide> <del>class LinalgSquareTestCase(object): <add>class LinalgSquareTestCase(LinalgTestCase): <ide> <ide> def test_sq_cases(self): <del> _check_cases(self.do, require={'square'}, exclude={'generalized', 'size-0'}) <add> self.check_cases(require={'square'}, <add> exclude={'generalized', 'size-0'}) <ide> <ide> def test_empty_sq_cases(self): <del> _check_cases(self.do, require={'square', 'size-0'}, exclude={'generalized'}) <add> self.check_cases(require={'square', 'size-0'}, <add> exclude={'generalized'}) <ide> <ide> <del>class LinalgNonsquareTestCase(object): <add>class LinalgNonsquareTestCase(LinalgTestCase): <ide> <ide> def test_nonsq_cases(self): <del> _check_cases(self.do, require={'nonsquare'}, exclude={'generalized', 'size-0'}) <add> self.check_cases(require={'nonsquare'}, <add> exclude={'generalized', 'size-0'}) <ide> <ide> def test_empty_nonsq_cases(self): <del> _check_cases(self.do, require={'nonsquare', 'size-0'}, exclude={'generalized'}) <add> self.check_cases(require={'nonsquare', 'size-0'}, <add> exclude={'generalized'}) <ide> <del>class HermitianTestCase(object): <add> <add>class HermitianTestCase(LinalgTestCase): <ide> <ide> def test_herm_cases(self): <del> _check_cases(self.do, require={'hermitian'}, exclude={'generalized', 'size-0'}) <add> self.check_cases(require={'hermitian'}, <add> exclude={'generalized', 'size-0'}) <ide> <ide> def test_empty_herm_cases(self): <del> _check_cases(self.do, require={'hermitian', 'size-0'}, exclude={'generalized'}) <add> self.check_cases(require={'hermitian', 'size-0'}, <add> exclude={'generalized'}) <ide> <ide> <del>class LinalgGeneralizedSquareTestCase(object): <add>class LinalgGeneralizedSquareTestCase(LinalgTestCase): <ide> <ide> @pytest.mark.slow <ide> def test_generalized_sq_cases(self): <del> _check_cases(self.do, require={'generalized', 'square'}, exclude={'size-0'}) <add> self.check_cases(require={'generalized', 'square'}, <add> exclude={'size-0'}) <ide> <ide> @pytest.mark.slow <ide> def test_generalized_empty_sq_cases(self): <del> _check_cases(self.do, require={'generalized', 'square', 'size-0'}) <add> self.check_cases(require={'generalized', 'square', 'size-0'}) <ide> <ide> <del>class LinalgGeneralizedNonsquareTestCase(object): <add>class LinalgGeneralizedNonsquareTestCase(LinalgTestCase): <ide> <ide> @pytest.mark.slow <ide> def test_generalized_nonsq_cases(self): <del> _check_cases(self.do, require={'generalized', 'nonsquare'}, exclude={'size-0'}) <add> self.check_cases(require={'generalized', 'nonsquare'}, <add> exclude={'size-0'}) <ide> <ide> @pytest.mark.slow <ide> def test_generalized_empty_nonsq_cases(self): <del> _check_cases(self.do, require={'generalized', 'nonsquare', 'size-0'}) <add> self.check_cases(require={'generalized', 'nonsquare', 'size-0'}) <ide> <ide> <del>class HermitianGeneralizedTestCase(object): <add>class HermitianGeneralizedTestCase(LinalgTestCase): <ide> <ide> @pytest.mark.slow <ide> def test_generalized_herm_cases(self): <del> _check_cases(self.do, <del> require={'generalized', 'hermitian'}, <del> exclude={'size-0'}) <add> self.check_cases(require={'generalized', 'hermitian'}, <add> exclude={'size-0'}) <ide> <ide> @pytest.mark.slow <ide> def test_generalized_empty_herm_cases(self): <del> _check_cases(self.do, <del> require={'generalized', 'hermitian', 'size-0'}, <del> exclude={'none'}) <add> self.check_cases(require={'generalized', 'hermitian', 'size-0'}, <add> exclude={'none'}) <ide> <ide> <ide> def dot_generalized(a, b): <ide> def identity_like_generalized(a): <ide> return identity(a.shape[0]) <ide> <ide> <del>class TestSolve(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <del> <add>class SolveCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <add> # kept apart from TestSolve for use for testing with matrices. <ide> def do(self, a, b, tags): <ide> x = linalg.solve(a, b) <ide> assert_almost_equal(b, dot_generalized(a, x)) <del> assert_(imply(isinstance(b, matrix), isinstance(x, matrix))) <add> assert_(consistent_subclass(x, b)) <add> <ide> <add>class TestSolve(SolveCases): <ide> def test_types(self): <ide> def check(dtype): <ide> x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) <ide> class ArraySubclass(np.ndarray): <ide> assert_(isinstance(result, ArraySubclass)) <ide> <ide> <del>class TestInv(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <add>class InvCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <ide> <ide> def do(self, a, b, tags): <ide> a_inv = linalg.inv(a) <ide> assert_almost_equal(dot_generalized(a, a_inv), <ide> identity_like_generalized(a)) <del> assert_(imply(isinstance(a, matrix), isinstance(a_inv, matrix))) <add> assert_(consistent_subclass(a_inv, a)) <ide> <add> <add>class TestInv(InvCases): <ide> def test_types(self): <ide> def check(dtype): <ide> x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) <ide> class ArraySubclass(np.ndarray): <ide> assert_(isinstance(res, ArraySubclass)) <ide> <ide> <del>class TestEigvals(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <add>class EigvalsCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <ide> <ide> def do(self, a, b, tags): <ide> ev = linalg.eigvals(a) <ide> evalues, evectors = linalg.eig(a) <ide> assert_almost_equal(ev, evalues) <ide> <add> <add>class TestEigvals(EigvalsCases): <ide> def test_types(self): <ide> def check(dtype): <ide> x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) <ide> class ArraySubclass(np.ndarray): <ide> assert_(isinstance(res, np.ndarray)) <ide> <ide> <del>class TestEig(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <add>class EigCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <ide> <ide> def do(self, a, b, tags): <ide> evalues, evectors = linalg.eig(a) <ide> assert_allclose(dot_generalized(a, evectors), <ide> np.asarray(evectors) * np.asarray(evalues)[..., None, :], <ide> rtol=get_rtol(evalues.dtype)) <del> assert_(imply(isinstance(a, matrix), isinstance(evectors, matrix))) <add> assert_(consistent_subclass(evectors, a)) <add> <ide> <add>class TestEig(EigCases): <ide> def test_types(self): <ide> def check(dtype): <ide> x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) <ide> class ArraySubclass(np.ndarray): <ide> assert_(isinstance(a, np.ndarray)) <ide> <ide> <del>class TestSVD(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <add>class SVDCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <ide> <ide> def do(self, a, b, tags): <ide> if 'size-0' in tags: <ide> def do(self, a, b, tags): <ide> assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[..., None, :], <ide> np.asarray(vt)), <ide> rtol=get_rtol(u.dtype)) <del> assert_(imply(isinstance(a, matrix), isinstance(u, matrix))) <del> assert_(imply(isinstance(a, matrix), isinstance(vt, matrix))) <add> assert_(consistent_subclass(u, a)) <add> assert_(consistent_subclass(vt, a)) <ide> <add> <add>class TestSVD(SVDCases): <ide> def test_types(self): <ide> def check(dtype): <ide> x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) <ide> def test_0_size(self): <ide> assert_raises(linalg.LinAlgError, linalg.svd, a) <ide> <ide> <del>class TestCond(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <add>class CondCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <ide> # cond(x, p) for p in (None, 2, -2) <ide> <ide> def do(self, a, b, tags): <ide> def do(self, a, b, tags): <ide> * (abs(cinv)**2).sum(-1).sum(-1)), <ide> single_decimal=5, double_decimal=11) <ide> <add> <add>class TestCond(CondCases): <ide> def test_basic_nonsvd(self): <ide> # Smoketest the non-svd norms <ide> A = array([[1., 0, 1], [0, -2., 0], [0, 0, 3.]]) <ide> def test_stacked_singular(self): <ide> assert_(np.isfinite(c[1,0])) <ide> <ide> <del>class TestPinv(LinalgSquareTestCase, <del> LinalgNonsquareTestCase, <del> LinalgGeneralizedSquareTestCase, <del> LinalgGeneralizedNonsquareTestCase): <add>class PinvCases(LinalgSquareTestCase, <add> LinalgNonsquareTestCase, <add> LinalgGeneralizedSquareTestCase, <add> LinalgGeneralizedNonsquareTestCase): <ide> <ide> def do(self, a, b, tags): <ide> a_ginv = linalg.pinv(a) <ide> # `a @ a_ginv == I` does not hold if a is singular <ide> dot = dot_generalized <ide> assert_almost_equal(dot(dot(a, a_ginv), a), a, single_decimal=5, double_decimal=11) <del> assert_(imply(isinstance(a, matrix), isinstance(a_ginv, matrix))) <add> assert_(consistent_subclass(a_ginv, a)) <add> <add> <add>class TestPinv(PinvCases): <add> pass <ide> <ide> <del>class TestDet(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <add>class DetCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): <ide> <ide> def do(self, a, b, tags): <ide> d = linalg.det(a) <ide> def do(self, a, b, tags): <ide> assert_almost_equal(np.abs(s[m]), 1) <ide> assert_equal(ld[~m], -inf) <ide> <add> <add>class TestDet(DetCases): <ide> def test_zero(self): <ide> assert_equal(linalg.det([[0.0]]), 0.0) <ide> assert_equal(type(linalg.det([[0.0]])), double) <ide> def test_0_size(self): <ide> assert_(res[1].dtype.type is np.float64) <ide> <ide> <del>class TestLstsq(LinalgSquareTestCase, LinalgNonsquareTestCase): <add>class LstsqCases(LinalgSquareTestCase, LinalgNonsquareTestCase): <ide> <ide> def do(self, a, b, tags): <ide> if 'size-0' in tags: <ide> def do(self, a, b, tags): <ide> expect_resids = np.array([]).view(type(x)) <ide> assert_almost_equal(residuals, expect_resids) <ide> assert_(np.issubdtype(residuals.dtype, np.floating)) <del> assert_(imply(isinstance(b, matrix), isinstance(x, matrix))) <del> assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) <add> assert_(consistent_subclass(x, b)) <add> assert_(consistent_subclass(residuals, b)) <add> <ide> <add>class TestLstsq(LstsqCases): <ide> def test_future_rcond(self): <ide> a = np.array([[0., 1., 0., 1., 2., 0.], <ide> [0., 2., 0., 0., 1., 0.], <ide> def test_future_rcond(self): <ide> # Warning should be raised exactly once (first command) <ide> assert_(len(w) == 1) <ide> <add> <ide> class TestMatrixPower(object): <ide> R90 = array([[0, 1], [-1, 0]]) <ide> Arb22 = array([[4, -7], [-2, 10]]) <ide> def test_square(self): <ide> assert_equal(matrix_power(A, 2), A) <ide> <ide> <del>class TestEigvalsh(HermitianTestCase, HermitianGeneralizedTestCase): <add>class TestEigvalshCases(HermitianTestCase, HermitianGeneralizedTestCase): <ide> <ide> def do(self, a, b, tags): <ide> # note that eigenvalue arrays returned by eig must be sorted since <ide> def do(self, a, b, tags): <ide> ev2 = linalg.eigvalsh(a, 'U') <ide> assert_allclose(ev2, evalues, rtol=get_rtol(ev.dtype)) <ide> <add> <add>class TestEigvalsh(object): <ide> def test_types(self): <ide> def check(dtype): <ide> x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) <ide> class ArraySubclass(np.ndarray): <ide> assert_(isinstance(res, np.ndarray)) <ide> <ide> <del>class TestEigh(HermitianTestCase, HermitianGeneralizedTestCase): <add>class TestEighCases(HermitianTestCase, HermitianGeneralizedTestCase): <ide> <ide> def do(self, a, b, tags): <ide> # note that eigenvalue arrays returned by eig must be sorted since <ide> def do(self, a, b, tags): <ide> np.asarray(ev2)[..., None, :] * np.asarray(evc2), <ide> rtol=get_rtol(ev.dtype), err_msg=repr(a)) <ide> <add> <add>class TestEigh(object): <ide> def test_types(self): <ide> def check(dtype): <ide> x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) <ide> class ArraySubclass(np.ndarray): <ide> assert_(isinstance(a, np.ndarray)) <ide> <ide> <del>class _TestNorm(object): <del> <add>class _TestNormBase(object): <ide> dt = None <ide> dec = None <ide> <add> <add>class _TestNormGeneral(_TestNormBase): <add> <ide> def test_empty(self): <ide> assert_equal(norm([]), 0.0) <ide> assert_equal(norm(array([], dtype=self.dt)), 0.0) <ide> def test_vector_return_type(self): <ide> assert_(issubclass(an.dtype.type, np.floating)) <ide> assert_almost_equal(an, 1.0) <ide> <del> def test_matrix_return_type(self): <del> a = np.array([[1, 0, 1], [0, 1, 1]]) <del> <del> exact_types = np.typecodes['AllInteger'] <del> <del> # float32, complex64, float64, complex128 types are the only types <del> # allowed by `linalg`, which performs the matrix operations used <del> # within `norm`. <del> inexact_types = 'fdFD' <del> <del> all_types = exact_types + inexact_types <del> <del> for each_inexact_types in all_types: <del> at = a.astype(each_inexact_types) <del> <del> an = norm(at, -np.inf) <del> assert_(issubclass(an.dtype.type, np.floating)) <del> assert_almost_equal(an, 2.0) <del> <del> with suppress_warnings() as sup: <del> sup.filter(RuntimeWarning, "divide by zero encountered") <del> an = norm(at, -1) <del> assert_(issubclass(an.dtype.type, np.floating)) <del> assert_almost_equal(an, 1.0) <del> <del> an = norm(at, 1) <del> assert_(issubclass(an.dtype.type, np.floating)) <del> assert_almost_equal(an, 2.0) <del> <del> an = norm(at, 2) <del> assert_(issubclass(an.dtype.type, np.floating)) <del> assert_almost_equal(an, 3.0**(1.0/2.0)) <del> <del> an = norm(at, -2) <del> assert_(issubclass(an.dtype.type, np.floating)) <del> assert_almost_equal(an, 1.0) <del> <del> an = norm(at, np.inf) <del> assert_(issubclass(an.dtype.type, np.floating)) <del> assert_almost_equal(an, 2.0) <del> <del> an = norm(at, 'fro') <del> assert_(issubclass(an.dtype.type, np.floating)) <del> assert_almost_equal(an, 2.0) <del> <del> an = norm(at, 'nuc') <del> assert_(issubclass(an.dtype.type, np.floating)) <del> # Lower bar needed to support low precision floats. <del> # They end up being off by 1 in the 7th place. <del> old_assert_almost_equal(an, 2.7320508075688772, decimal=6) <del> <ide> def test_vector(self): <ide> a = [1, 2, 3, 4] <ide> b = [-1, -2, -3, -4] <ide> def _test(v): <ide> array(c, dtype=self.dt)): <ide> _test(v) <ide> <del> def test_matrix_2x2(self): <del> A = matrix([[1, 3], [5, 7]], dtype=self.dt) <del> assert_almost_equal(norm(A), 84 ** 0.5) <del> assert_almost_equal(norm(A, 'fro'), 84 ** 0.5) <del> assert_almost_equal(norm(A, 'nuc'), 10.0) <del> assert_almost_equal(norm(A, inf), 12.0) <del> assert_almost_equal(norm(A, -inf), 4.0) <del> assert_almost_equal(norm(A, 1), 10.0) <del> assert_almost_equal(norm(A, -1), 6.0) <del> assert_almost_equal(norm(A, 2), 9.1231056256176615) <del> assert_almost_equal(norm(A, -2), 0.87689437438234041) <del> <del> assert_raises(ValueError, norm, A, 'nofro') <del> assert_raises(ValueError, norm, A, -3) <del> assert_raises(ValueError, norm, A, 0) <del> <del> def test_matrix_3x3(self): <del> # This test has been added because the 2x2 example <del> # happened to have equal nuclear norm and induced 1-norm. <del> # The 1/10 scaling factor accommodates the absolute tolerance <del> # used in assert_almost_equal. <del> A = (1 / 10) * \ <del> np.array([[1, 2, 3], [6, 0, 5], [3, 2, 1]], dtype=self.dt) <del> assert_almost_equal(norm(A), (1 / 10) * 89 ** 0.5) <del> assert_almost_equal(norm(A, 'fro'), (1 / 10) * 89 ** 0.5) <del> assert_almost_equal(norm(A, 'nuc'), 1.3366836911774836) <del> assert_almost_equal(norm(A, inf), 1.1) <del> assert_almost_equal(norm(A, -inf), 0.6) <del> assert_almost_equal(norm(A, 1), 1.0) <del> assert_almost_equal(norm(A, -1), 0.4) <del> assert_almost_equal(norm(A, 2), 0.88722940323461277) <del> assert_almost_equal(norm(A, -2), 0.19456584790481812) <del> <ide> def test_axis(self): <ide> # Vector norms. <ide> # Compare the use of `axis` with computing the norm of each row <ide> def test_keepdims(self): <ide> assert_(found.shape == expected_shape, <ide> shape_err.format(found.shape, expected_shape, order, k)) <ide> <add> <add>class _TestNorm2D(_TestNormBase): <add> # Define the part for 2d arrays separately, so we can subclass this <add> # and run the tests using np.matrix in matrixlib.tests.test_matrix_linalg. <add> array = np.array <add> <add> def test_matrix_empty(self): <add> assert_equal(norm(self.array([[]], dtype=self.dt)), 0.0) <add> <add> def test_matrix_return_type(self): <add> a = self.array([[1, 0, 1], [0, 1, 1]]) <add> <add> exact_types = np.typecodes['AllInteger'] <add> <add> # float32, complex64, float64, complex128 types are the only types <add> # allowed by `linalg`, which performs the matrix operations used <add> # within `norm`. <add> inexact_types = 'fdFD' <add> <add> all_types = exact_types + inexact_types <add> <add> for each_inexact_types in all_types: <add> at = a.astype(each_inexact_types) <add> <add> an = norm(at, -np.inf) <add> assert_(issubclass(an.dtype.type, np.floating)) <add> assert_almost_equal(an, 2.0) <add> <add> with suppress_warnings() as sup: <add> sup.filter(RuntimeWarning, "divide by zero encountered") <add> an = norm(at, -1) <add> assert_(issubclass(an.dtype.type, np.floating)) <add> assert_almost_equal(an, 1.0) <add> <add> an = norm(at, 1) <add> assert_(issubclass(an.dtype.type, np.floating)) <add> assert_almost_equal(an, 2.0) <add> <add> an = norm(at, 2) <add> assert_(issubclass(an.dtype.type, np.floating)) <add> assert_almost_equal(an, 3.0**(1.0/2.0)) <add> <add> an = norm(at, -2) <add> assert_(issubclass(an.dtype.type, np.floating)) <add> assert_almost_equal(an, 1.0) <add> <add> an = norm(at, np.inf) <add> assert_(issubclass(an.dtype.type, np.floating)) <add> assert_almost_equal(an, 2.0) <add> <add> an = norm(at, 'fro') <add> assert_(issubclass(an.dtype.type, np.floating)) <add> assert_almost_equal(an, 2.0) <add> <add> an = norm(at, 'nuc') <add> assert_(issubclass(an.dtype.type, np.floating)) <add> # Lower bar needed to support low precision floats. <add> # They end up being off by 1 in the 7th place. <add> np.testing.assert_almost_equal(an, 2.7320508075688772, decimal=6) <add> <add> def test_matrix_2x2(self): <add> A = self.array([[1, 3], [5, 7]], dtype=self.dt) <add> assert_almost_equal(norm(A), 84 ** 0.5) <add> assert_almost_equal(norm(A, 'fro'), 84 ** 0.5) <add> assert_almost_equal(norm(A, 'nuc'), 10.0) <add> assert_almost_equal(norm(A, inf), 12.0) <add> assert_almost_equal(norm(A, -inf), 4.0) <add> assert_almost_equal(norm(A, 1), 10.0) <add> assert_almost_equal(norm(A, -1), 6.0) <add> assert_almost_equal(norm(A, 2), 9.1231056256176615) <add> assert_almost_equal(norm(A, -2), 0.87689437438234041) <add> <add> assert_raises(ValueError, norm, A, 'nofro') <add> assert_raises(ValueError, norm, A, -3) <add> assert_raises(ValueError, norm, A, 0) <add> <add> def test_matrix_3x3(self): <add> # This test has been added because the 2x2 example <add> # happened to have equal nuclear norm and induced 1-norm. <add> # The 1/10 scaling factor accommodates the absolute tolerance <add> # used in assert_almost_equal. <add> A = (1 / 10) * \ <add> self.array([[1, 2, 3], [6, 0, 5], [3, 2, 1]], dtype=self.dt) <add> assert_almost_equal(norm(A), (1 / 10) * 89 ** 0.5) <add> assert_almost_equal(norm(A, 'fro'), (1 / 10) * 89 ** 0.5) <add> assert_almost_equal(norm(A, 'nuc'), 1.3366836911774836) <add> assert_almost_equal(norm(A, inf), 1.1) <add> assert_almost_equal(norm(A, -inf), 0.6) <add> assert_almost_equal(norm(A, 1), 1.0) <add> assert_almost_equal(norm(A, -1), 0.4) <add> assert_almost_equal(norm(A, 2), 0.88722940323461277) <add> assert_almost_equal(norm(A, -2), 0.19456584790481812) <add> <ide> def test_bad_args(self): <ide> # Check that bad arguments raise the appropriate exceptions. <ide> <del> A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt) <add> A = self.array([[1, 2, 3], [4, 5, 6]], dtype=self.dt) <ide> B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4) <ide> <ide> # Using `axis=<integer>` or passing in a 1-D array implies vector <ide> def test_bad_args(self): <ide> assert_raises(ValueError, norm, B, None, (0, 1, 2)) <ide> <ide> <add>class _TestNorm(_TestNorm2D, _TestNormGeneral): <add> pass <add> <add> <ide> class TestNorm_NonSystematic(object): <ide> <ide> def test_longdouble_norm(self): <ide> def test_complex_high_ord(self): <ide> old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=5) <ide> <ide> <del>class TestNormDouble(_TestNorm): <add># Separate definitions so we can use them for matrix tests. <add>class _TestNormDoubleBase(_TestNormBase): <ide> dt = np.double <ide> dec = 12 <ide> <ide> <del>class TestNormSingle(_TestNorm): <add>class _TestNormSingleBase(_TestNormBase): <ide> dt = np.float32 <ide> dec = 6 <ide> <ide> <del>class TestNormInt64(_TestNorm): <add>class _TestNormInt64Base(_TestNormBase): <ide> dt = np.int64 <ide> dec = 12 <ide> <ide> <add>class TestNormDouble(_TestNorm, _TestNormDoubleBase): <add> pass <add> <add> <add>class TestNormSingle(_TestNorm, _TestNormSingleBase): <add> pass <add> <add> <add>class TestNormInt64(_TestNorm, _TestNormInt64Base): <add> pass <add> <add> <ide> class TestMatrixRank(object): <ide> <ide> def test_matrix_rank(self): <ide> def test_reduced_rank(): <ide> <ide> <ide> class TestQR(object): <add> # Define the array class here, so run this on matrices elsewhere. <add> array = np.array <ide> <ide> def check_qr(self, a): <ide> # This test expects the argument `a` to be an ndarray or <ide> def test_mode_raw(self): <ide> # of the functions in lapack_lite. Consequently, this test is <ide> # very limited in scope. Note that the results are in FORTRAN <ide> # order, hence the h arrays are transposed. <del> a = array([[1, 2], [3, 4], [5, 6]], dtype=np.double) <add> a = self.array([[1, 2], [3, 4], [5, 6]], dtype=np.double) <ide> <ide> # Test double <ide> h, tau = linalg.qr(a, mode='raw') <ide> def test_mode_raw(self): <ide> assert_(tau.shape == (2,)) <ide> <ide> def test_mode_all_but_economic(self): <del> a = array([[1, 2], [3, 4]]) <del> b = array([[1, 2], [3, 4], [5, 6]]) <add> a = self.array([[1, 2], [3, 4]]) <add> b = self.array([[1, 2], [3, 4], [5, 6]]) <ide> for dt in "fd": <ide> m1 = a.astype(dt) <ide> m2 = b.astype(dt) <ide> self.check_qr(m1) <ide> self.check_qr(m2) <ide> self.check_qr(m2.T) <del> self.check_qr(matrix(m1)) <add> <ide> for dt in "fd": <ide> m1 = 1 + 1j * a.astype(dt) <ide> m2 = 1 + 1j * b.astype(dt) <ide> self.check_qr(m1) <ide> self.check_qr(m2) <ide> self.check_qr(m2.T) <del> self.check_qr(matrix(m1)) <ide> <ide> def test_0_size(self): <ide> # There may be good ways to do (some of this) reasonably: <ide><path>numpy/matrixlib/tests/test_matrix_linalg.py <add>""" Test functions for linalg module using the matrix class.""" <add>from __future__ import division, absolute_import, print_function <add> <add>import numpy as np <add> <add>from numpy.linalg.tests.test_linalg import ( <add> LinalgCase, apply_tag, TestQR as _TestQR, LinalgTestCase, <add> _TestNorm2D, _TestNormDoubleBase, _TestNormSingleBase, _TestNormInt64Base, <add> SolveCases, InvCases, EigvalsCases, EigCases, SVDCases, CondCases, <add> PinvCases, DetCases, LstsqCases) <add> <add> <add>CASES = [] <add> <add># square test cases <add>CASES += apply_tag('square', [ <add> LinalgCase("0x0_matrix", <add> np.empty((0, 0), dtype=np.double).view(np.matrix), <add> np.empty((0, 1), dtype=np.double).view(np.matrix), <add> tags={'size-0'}), <add> LinalgCase("matrix_b_only", <add> np.array([[1., 2.], [3., 4.]]), <add> np.matrix([2., 1.]).T), <add> LinalgCase("matrix_a_and_b", <add> np.matrix([[1., 2.], [3., 4.]]), <add> np.matrix([2., 1.]).T), <add>]) <add> <add># hermitian test-cases <add>CASES += apply_tag('hermitian', [ <add> LinalgCase("hmatrix_a_and_b", <add> np.matrix([[1., 2.], [2., 1.]]), <add> None), <add>]) <add># No need to make generalized or strided cases for matrices. <add> <add> <add>class MatrixTestCase(LinalgTestCase): <add> TEST_CASES = CASES <add> <add> <add>class TestSolveMatrix(SolveCases, MatrixTestCase): <add> pass <add> <add> <add>class TestInvMatrix(InvCases, MatrixTestCase): <add> pass <add> <add> <add>class TestEigvalsMatrix(EigvalsCases, MatrixTestCase): <add> pass <add> <add> <add>class TestEigMatrix(EigCases, MatrixTestCase): <add> pass <add> <add> <add>class TestSVDMatrix(SVDCases, MatrixTestCase): <add> pass <add> <add> <add>class TestCondMatrix(CondCases, MatrixTestCase): <add> pass <add> <add> <add>class TestPinvMatrix(PinvCases, MatrixTestCase): <add> pass <add> <add> <add>class TestDetMatrix(DetCases, MatrixTestCase): <add> pass <add> <add> <add>class TestLstsqMatrix(LstsqCases, MatrixTestCase): <add> pass <add> <add> <add>class _TestNorm2DMatrix(_TestNorm2D): <add> array = np.matrix <add> <add> <add>class TestNormDoubleMatrix(_TestNorm2DMatrix, _TestNormDoubleBase): <add> pass <add> <add> <add>class TestNormSingleMatrix(_TestNorm2DMatrix, _TestNormSingleBase): <add> pass <add> <add> <add>class TestNormInt64Matrix(_TestNorm2DMatrix, _TestNormInt64Base): <add> pass <add> <add> <add>class TestQRMatrix(_TestQR): <add> array = np.matrix
2
Python
Python
fix constraint tests
bba53793057c0cdf068e67d17ae90e39b90ae24c
<ide><path>keras/constraints.py <ide> def __call__(self, p): <ide> <ide> class UnitNorm(Constraint): <ide> def __call__(self, p): <del> return e / T.sqrt(T.sum(e**2, axis=-1, keepdims=True)) <add> return p / T.sqrt(T.sum(p**2, axis=-1, keepdims=True)) <ide> <ide> identity = Constraint <ide> maxnorm = MaxNorm <ide><path>tests/auto/test_embeddings.py <ide> def setUp(self): <ide> <ide> def test_unitnorm_constraint(self): <ide> lookup = Sequential() <del> lookup.add(Embedding(3, 2, weights=[self.W1], W_constraint=unitnorm)) <add> lookup.add(Embedding(3, 2, weights=[self.W1], W_constraint=unitnorm())) <ide> lookup.add(Flatten()) <ide> lookup.add(Dense(2, 1)) <ide> lookup.add(Activation('sigmoid'))
2
Ruby
Ruby
extract rows that should be inserted to a method
ca0501676500471981806993e7ccd7536f7943f0
<ide><path>activerecord/lib/active_record/fixtures.rb <ide> def tables <ide> }.flatten.uniq <ide> end <ide> <del> def insert_fixtures <add> # Return a hash of rows to be inserted. The key is the table, the value is <add> # a list of rows to insert to that table. <add> def rows <ide> now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now <ide> now = now.to_s(:db) <ide> <ide> # allow a standard key to be used for doing defaults in YAML <ide> fixtures.delete('DEFAULTS') <ide> <ide> # track any join tables we need to insert later <del> habtm_fixtures = Hash.new { |h,k| h[k] = [] } <add> rows = Hash.new { |h,table| h[table] = [] } <ide> <del> rows = fixtures.map do |label, fixture| <add> rows[table_name] = fixtures.map do |label, fixture| <ide> row = fixture.to_hash <ide> <ide> if model_class && model_class < ActiveRecord::Base <ide> def insert_fixtures <ide> if (targets = row.delete(association.name.to_s)) <ide> targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/) <ide> table_name = association.options[:join_table] <del> habtm_fixtures[table_name].concat targets.map { |target| <add> rows[table_name].concat targets.map { |target| <ide> { association.foreign_key => row[primary_key_name], <ide> association.association_foreign_key => Fixtures.identify(target) } <ide> } <ide> def insert_fixtures <ide> <ide> row <ide> end <add> rows <add> end <ide> <del> rows.each do |row| <del> @connection.insert_fixture(row, table_name) <del> end <del> <del> # insert any HABTM join tables we discovered <del> habtm_fixtures.each do |table, fixtures| <del> fixtures.each do |row| <del> @connection.insert_fixture(row, table) <add> def insert_fixtures <add> rows.each do |table_name, rows| <add> rows.each do |row| <add> @connection.insert_fixture(row, table_name) <ide> end <ide> end <ide> end
1
Python
Python
add tests for norm from #763
023546bfaac366615436f3daceb7d5ffc211c714
<ide><path>numpy/linalg/tests/test_linalg.py <ide> from numpy import array, single, double, csingle, cdouble, dot, identity <ide> from numpy import multiply, atleast_2d, inf, asarray, matrix <ide> from numpy import linalg <del>from numpy.linalg import matrix_power <add>from numpy.linalg import matrix_power, norm <ide> <ide> def ifthen(a, b): <ide> return not a or b <ide> def do(self, a): <ide> evalues, evectors = linalg.eig(a) <ide> assert_almost_equal(ev, evalues) <ide> <add>class TestNorm(TestCase): <add> def check_empty(self): <add> assert_equal(norm([]), 0.0) <add> assert_equal(norm(array([], dtype = double)), 0.0) <add> assert_equal(norm(atleast_2d(array([], dtype = double))), 0.0) <add> <add> def test_vector(self): <add> a = [1.0,2.0,3.0,4.0] <add> b = [-1.0,-2.0,-3.0,-4.0] <add> c = [-1.0, 2.0,-3.0, 4.0] <add> for v in (a,array(a),b,array(b),c,array(c)): <add> assert_almost_equal(norm(v), 30**0.5) <add> assert_almost_equal(norm(v,inf), 4.0) <add> assert_almost_equal(norm(v,-inf), 1.0) <add> assert_almost_equal(norm(v,1), 10.0) <add> assert_almost_equal(norm(v,-1), 12.0/25) <add> assert_almost_equal(norm(v,2), 30**0.5) <add> assert_almost_equal(norm(v,-2), (205./144)**-0.5) <add> <add> @dec.knownfailureif(True, "#786: FIXME") <add> def test_vector_badarg(self): <add> """Regression for #786: Froebenius norm for vectors raises <add> TypeError.""" <add> self.assertRaises(ValueError, norm, array([1., 2., 3.]), 'fro') <add> <add> def test_matrix(self): <add> A = matrix([[1.,3.],[5.,7.]], dtype=single) <add> A = matrix([[1.,3.],[5.,7.]], dtype=single) <add> assert_almost_equal(norm(A), 84**0.5) <add> assert_almost_equal(norm(A,'fro'), 84**0.5) <add> assert_almost_equal(norm(A,inf), 12.0) <add> assert_almost_equal(norm(A,-inf), 4.0) <add> assert_almost_equal(norm(A,1), 10.0) <add> assert_almost_equal(norm(A,-1), 6.0) <add> assert_almost_equal(norm(A,2), 9.12310563) <add> assert_almost_equal(norm(A,-2), 0.87689437) <add> <add> self.assertRaises(ValueError, norm, A, 'nofro') <add> self.assertRaises(ValueError, norm, A, -3) <add> <ide> if __name__ == "__main__": <ide> run_module_suite()
1
Javascript
Javascript
convert template to es6
3992ba3af6bf7e1fd010b478976d7d2ae96721c1
<ide><path>lib/Template.js <ide> const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; <ide> /** <ide> * @typedef {Object} HasId <ide> * @property {number | string} id <del> * */ <add> */ <ide> <ide> /** <ide> * @typedef {function(Module, number): boolean} ModuleFilterPredicate <ide> const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; <ide> * @returns {-1|0|1} the sort value <ide> */ <ide> const stringifyIdSortPredicate = (a, b) => { <del> var aId = a.id + ""; <del> var bId = b.id + ""; <add> const aId = a.id + ""; <add> const bId = b.id + ""; <ide> if (aId < bId) return -1; <ide> if (aId > bId) return 1; <ide> return 0; <ide> class Template { <ide> .replace(INDENT_MULTILINE_REGEX, "") <ide> .replace(LINE_SEPARATOR_REGEX, "\n"); <ide> } <add> <ide> /** <ide> * @param {string} str the string converted to identifier <ide> * @returns {string} created identifier <ide> class Template { <ide> <ide> /** <ide> * <del> * @param {string | string[]} str string to convert to identity <add> * @param {string | string[]} s string to convert to identity <ide> * @returns {string} converted identity <ide> */ <del> static indent(str) { <del> if (Array.isArray(str)) { <del> return str.map(Template.indent).join("\n"); <add> static indent(s) { <add> if (Array.isArray(s)) { <add> return s.map(Template.indent).join("\n"); <ide> } else { <del> str = str.trimRight(); <add> const str = s.trimRight(); <ide> if (!str) return ""; <del> var ind = str[0] === "\n" ? "" : "\t"; <add> const ind = str[0] === "\n" ? "" : "\t"; <ide> return ind + str.replace(/\n([^\n])/g, "\n\t$1"); <ide> } <ide> } <ide> <ide> /** <ide> * <del> * @param {string|string[]} str string to create prefix for <add> * @param {string|string[]} s string to create prefix for <ide> * @param {string} prefix prefix to compose <ide> * @returns {string} returns new prefix string <ide> */ <del> static prefix(str, prefix) { <del> if (Array.isArray(str)) { <del> str = str.join("\n"); <del> } <del> str = str.trim(); <add> static prefix(s, prefix) { <add> const str = Template.asString(s).trim(); <ide> if (!str) return ""; <ide> const ind = str[0] === "\n" ? "" : prefix; <ide> return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); <ide> class Template { <ide> * or false if not every module has a number based id <ide> */ <ide> static getModulesArrayBounds(modules) { <del> var maxId = -Infinity; <del> var minId = Infinity; <add> let maxId = -Infinity; <add> let minId = Infinity; <ide> for (const module of modules) { <ide> if (typeof module.id !== "number") return false; <ide> if (maxId < module.id) maxId = /** @type {number} */ (module.id); <ide> class Template { <ide> // add minId x ',' instead of 'Array(minId).concat(…)' <ide> minId = 0; <ide> } <del> var objectOverhead = modules <del> .map(module => { <del> var idLength = (module.id + "").length; <del> return idLength + 2; <del> }) <del> .reduce((a, b) => { <del> return a + b; <del> }, -1); <del> var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId; <add> const objectOverhead = modules <add> .map(module => (module.id + "").length + 2) <add> .reduce((a, b) => a + b, -1); <add> const arrayOverhead = <add> minId === 0 ? maxId : 16 + ("" + minId).length + maxId; <ide> return arrayOverhead < objectOverhead ? [minId, maxId] : false; <ide> } <ide> <ide> class Template { <ide> filterFn, <ide> moduleTemplate, <ide> dependencyTemplates, <del> prefix <add> prefix = "" <ide> ) { <del> if (!prefix) prefix = ""; <del> var source = new ConcatSource(); <add> const source = new ConcatSource(); <ide> const modules = chunk.getModules().filter(filterFn); <add> let removedModules; <ide> if (chunk instanceof HotUpdateChunk) { <del> var removedModules = chunk.removedModules; <add> removedModules = chunk.removedModules; <ide> } <ide> if ( <ide> modules.length === 0 && <ide> class Template { <ide> return source; <ide> } <ide> /** @type {{id: string|number, source: Source|string}[]} */ <del> var allModules = modules.map(module => { <add> const allModules = modules.map(module => { <ide> return { <ide> id: module.id, <ide> source: moduleTemplate.render(module, dependencyTemplates, { <ide> class Template { <ide> }); <ide> } <ide> } <del> var bounds = Template.getModulesArrayBounds(allModules); <del> <add> const bounds = Template.getModulesArrayBounds(allModules); <ide> if (bounds) { <ide> // Render a spare array <del> var minId = bounds[0]; <del> var maxId = bounds[1]; <del> if (minId !== 0) source.add("Array(" + minId + ").concat("); <add> const minId = bounds[0]; <add> const maxId = bounds[1]; <add> if (minId !== 0) { <add> source.add(`Array(${minId}).concat(`); <add> } <ide> source.add("[\n"); <ide> const modules = new Map(); <ide> for (const module of allModules) { <ide> modules.set(module.id, module); <ide> } <del> for (var idx = minId; idx <= maxId; idx++) { <del> var module = modules.get(idx); <del> if (idx !== minId) source.add(",\n"); <del> source.add("/* " + idx + " */"); <add> for (let idx = minId; idx <= maxId; idx++) { <add> const module = modules.get(idx); <add> if (idx !== minId) { <add> source.add(",\n"); <add> } <add> source.add(`/* ${idx} */`); <ide> if (module) { <ide> source.add("\n"); <ide> source.add(module.source); <ide> } <ide> } <ide> source.add("\n" + prefix + "]"); <del> if (minId !== 0) source.add(")"); <add> if (minId !== 0) { <add> source.add(")"); <add> } <ide> } else { <ide> // Render an object <ide> source.add("{\n"); <ide> allModules.sort(stringifyIdSortPredicate).forEach((module, idx) => { <del> if (idx !== 0) source.add(",\n"); <add> if (idx !== 0) { <add> source.add(",\n"); <add> } <ide> source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`); <ide> source.add(module.source); <ide> }); <del> source.add("\n\n" + prefix + "}"); <add> source.add(`\n\n${prefix}}`); <ide> } <ide> return source; <ide> }
1
PHP
PHP
fix tiny doc typo
f4fc56c1d605145e05545ec07fdb77eaf2525c73
<ide><path>src/Http/Response.php <ide> * <ide> * There are external packages such as `fig/http-message-util` that provide HTTP <ide> * status code constants. These can be used with any method that accepts or <del> * returns a status code integer. Keep in mind that these consants might <add> * returns a status code integer. Keep in mind that these constants might <ide> * include status codes that are now allowed which will throw an <ide> * `\InvalidArgumentException`. <ide> */ <ide> public function getStatusCode(): int <ide> * <ide> * There are external packages such as `fig/http-message-util` that provide HTTP <ide> * status code constants. These can be used with any method that accepts or <del> * returns a status code integer. However, keep in mind that these consants <add> * returns a status code integer. However, keep in mind that these constants <ide> * might include status codes that are now allowed which will throw an <ide> * `\InvalidArgumentException`. <ide> *
1
Javascript
Javascript
log original error
d5caafb86e0b0dbeea0713d17d1a0b62bd1792e3
<ide><path>packages/next/build/index.js <ide> function runCompiler (compiler) { <ide> return reject(err) <ide> } <ide> <del> const jsonStats = stats.toJson({ warnings: true, errors: true }) <add> let buildFailed = false <add> for (const stat of stats.stats) { <add> for (const error of stat.compilation.errors) { <add> buildFailed = true <add> console.error('ERROR', error) <add> console.error('ORIGINAL ERROR', error.error) <add> } <ide> <del> if (jsonStats.errors.length > 0) { <del> console.log() <del> console.log(...jsonStats.warnings) <del> console.error(...jsonStats.errors) <del> return reject(new Error('Soft webpack errors')) <add> for (const warning of stat.compilation.warnings) { <add> buildFailed = true <add> console.warn('WARNING', warning) <add> } <ide> } <ide> <del> if (jsonStats.warnings.length > 0) { <del> console.log() <del> console.log(...jsonStats.warnings) <add> if (buildFailed) { <add> return reject(new Error('Webpack errors')) <ide> } <ide> <ide> resolve()
1
Ruby
Ruby
remove duplicated test
21747560be42d68200060a1d90419717e0ca339e
<ide><path>railties/test/generators/model_generator_test.rb <ide> def test_database_puts_migrations_in_configured_folder_with_aliases <ide> end <ide> end <ide> <del> def test_required_polymorphic_belongs_to_generates_correct_model <del> run_generator ["account", "supplier:references{polymorphic}"] <del> <del> expected_file = <<~FILE <del> class Account < ApplicationRecord <del> belongs_to :supplier, polymorphic: true <del> end <del> FILE <del> assert_file "app/models/account.rb", expected_file <del> end <del> <del> def test_required_and_polymorphic_are_order_independent <add> def test_polymorphic_belongs_to_generates_correct_model <ide> run_generator ["account", "supplier:references{polymorphic}"] <ide> <ide> expected_file = <<~FILE
1
Text
Text
improve choco command
6aea140a331119a21d78a682027470567de59bfa
<ide><path>docs/GettingStarted.md <ide> We recommend installing Node and Python2 via [Chocolatey](https://chocolatey.org <ide> <ide> React Native also requires a recent version of the [Java SE Development Kit (JDK)](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html), as well as Python 2. Both can be installed using Chocolatey. <ide> <del>Open an Administrator Command Prompt (right click Command Prompt and select "Run as Administrator"), then run the following commands: <add>Open an Administrator Command Prompt (right click Command Prompt and select "Run as Administrator"), then run the following command: <ide> <ide> ```powershell <del>choco install nodejs.install <del>choco install python2 <del>choco install jdk8 <add>choco install -y nodejs.install python2 jdk8 <ide> ``` <ide> <ide> If you have already installed Node on your system, make sure it is version 4 or newer. If you already have a JDK on your system, make sure it is version 8 or newer.
1
Text
Text
expand documentation for --insecure-registries
c66196a9dc0cd7d19eb3535c52fdbccfa2ee628e
<ide><path>docs/sources/reference/commandline/cli.md <ide> expect an integer, and they can only be specified once. <ide> -H, --host=[] The socket(s) to bind to in daemon mode or connect to in client mode, specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd. <ide> --icc=true Enable inter-container communication <ide> --insecure-registry=[] Make these registries use http <del> --ip=0.0.0.0 Default IP address to use when binding container ports <add> --ip=0.0.0.0 Default IP address to use when binding container ports <ide> --ip-forward=true Enable net.ipv4.ip_forward <ide> --ip-masq=true Enable IP masquerading for bridge's IP range <ide> --iptables=true Enable Docker's addition of iptables rules <ide> can be disabled with --ip-masq=false. <ide> <ide> <ide> <add>By default docker will assume all registries are securied via TLS. Prior versions <add>of docker used an auto fallback if a registry did not support TLS. This introduces <add>the opportunity for MITM attacks so in Docker 1.2 the user must specify `--insecure-registries` <add>when starting the Docker daemon to state which registries are not using TLS and to communicate <add>with these registries via plain text. If you are running a local registry over plain text <add>on `127.0.0.1:5000` you will be required to specify `--insecure-registries 127.0.0.1:500` <add>when starting the docker daemon to be able to push and pull images to that registry. <add>No automatic fallback will happen after Docker 1.2 to detect if a registry is using <add>HTTP or HTTPS. <add> <ide> Docker supports softlinks for the Docker data directory <ide> (`/var/lib/docker`) and for `/var/lib/docker/tmp`. The `DOCKER_TMPDIR` and the data directory can be set like this: <ide>
1
PHP
PHP
apply geteventmanager() in tests
babd5c43e7717b19037dc6822c545b90b68bd491
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> public function testNoViewClassExtension() <ide> $event = new Event('Controller.startup', $this->Controller); <ide> $this->RequestHandler->initialize([]); <ide> $this->RequestHandler->startup($event); <del> $this->Controller->eventManager()->on('Controller.beforeRender', function () { <add> $this->Controller->getEventManager()->on('Controller.beforeRender', function () { <ide> return $this->Controller->response; <ide> }); <ide> $this->Controller->render(); <ide> public function testRespondAsWithAttachment() <ide> */ <ide> public function testRenderAsCalledTwice() <ide> { <del> $this->Controller->eventManager()->on('Controller.beforeRender', function (\Cake\Event\Event $e) { <add> $this->Controller->getEventManager()->on('Controller.beforeRender', function (\Cake\Event\Event $e) { <ide> return $e->subject()->response; <ide> }); <ide> $this->Controller->render(); <ide><path>tests/TestCase/Controller/ComponentRegistryTest.php <ide> public function testGetController() <ide> */ <ide> public function testReset() <ide> { <del> $eventManager = $this->Components->getController()->eventManager(); <add> $eventManager = $this->Components->getController()->getEventManager(); <ide> $instance = $this->Components->load('Auth'); <ide> $this->assertSame( <ide> $instance, <ide> public function testReset() <ide> */ <ide> public function testUnload() <ide> { <del> $eventManager = $this->Components->getController()->eventManager(); <add> $eventManager = $this->Components->getController()->getEventManager(); <ide> <ide> $result = $this->Components->load('Auth'); <ide> $this->Components->unload('Auth'); <ide> public function testUnloadUnknown() <ide> */ <ide> public function testSet() <ide> { <del> $eventManager = $this->Components->getController()->eventManager(); <add> $eventManager = $this->Components->getController()->getEventManager(); <ide> $this->assertCount(0, $eventManager->listeners('Controller.startup')); <ide> <ide> $auth = new AuthComponent($this->Components); <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> public function testBeforeRenderCallbackChangingViewClass() <ide> { <ide> $Controller = new Controller(new ServerRequest, new Response()); <ide> <del> $Controller->eventManager()->on('Controller.beforeRender', function (Event $event) { <add> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $event) { <ide> $controller = $event->subject(); <ide> $controller->viewClass = 'Json'; <ide> }); <ide> public function testBeforeRenderEventCancelsRender() <ide> { <ide> $Controller = new Controller(new ServerRequest, new Response()); <ide> <del> $Controller->eventManager()->on('Controller.beforeRender', function (Event $event) { <add> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $event) { <ide> return false; <ide> }); <ide> <ide> public function testRedirectBeforeRedirectModifyingUrl() <ide> { <ide> $Controller = new Controller(null, new Response()); <ide> <del> $Controller->eventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) { <add> $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) { <ide> $response->location('http://book.cakephp.org'); <ide> }); <ide> <ide> public function testRedirectBeforeRedirectModifyingStatusCode() <ide> ->getMock(); <ide> $Controller = new Controller(null, $Response); <ide> <del> $Controller->eventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) { <add> $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) { <ide> $response->statusCode(302); <ide> }); <ide> <ide> public function testRedirectBeforeRedirectListenerReturnResponse() <ide> $Controller = new Controller(null, $Response); <ide> <ide> $newResponse = new Response; <del> $Controller->eventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) use ($newResponse) { <add> $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) use ($newResponse) { <ide> return $newResponse; <ide> }); <ide> <ide> public function testViewPathConventions() <ide> ]); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> $Controller = new \TestApp\Controller\Admin\PostsController($request, $response); <del> $Controller->eventManager()->on('Controller.beforeRender', function (Event $e) { <add> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) { <ide> return $e->subject()->response; <ide> }); <ide> $Controller->render(); <ide> public function testViewPathConventions() <ide> ]); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> $Controller = new \TestApp\Controller\Admin\PostsController($request, $response); <del> $Controller->eventManager()->on('Controller.beforeRender', function (Event $e) { <add> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) { <ide> return $e->subject()->response; <ide> }); <ide> $Controller->render(); <ide> public function testViewPathConventions() <ide> 'prefix' => false <ide> ]); <ide> $Controller = new \TestApp\Controller\PagesController($request, $response); <del> $Controller->eventManager()->on('Controller.beforeRender', function (Event $e) { <add> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) { <ide> return $e->subject()->response; <ide> }); <ide> $Controller->render(); <ide> public function testBeforeRenderViewVariables() <ide> { <ide> $controller = new PostsController(); <ide> <del> $controller->eventManager()->on('Controller.beforeRender', function (Event $event) { <add> $controller->getEventManager()->on('Controller.beforeRender', function (Event $event) { <ide> /* @var Controller $controller */ <ide> $controller = $event->subject(); <ide> <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> public function testMissingLayoutPathRenderSafe() <ide> <ide> $ExceptionRenderer->controller = new Controller(); <ide> $ExceptionRenderer->controller->helpers = ['Fail', 'Boom']; <del> $ExceptionRenderer->controller->eventManager()->on( <add> $ExceptionRenderer->controller->getEventManager()->on( <ide> 'Controller.beforeRender', <ide> function (Event $event) { <ide> $this->called = true; <ide><path>tests/TestCase/Event/EventDispatcherTraitTest.php <ide> public function testSettingEventManager() <ide> <ide> $this->subject->eventManager($eventManager); <ide> <del> $this->assertSame($eventManager, $this->subject->eventManager()); <add> $this->assertSame($eventManager, $this->subject->getEventManager()); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Http/ActionDispatcherTest.php <ide> public function testDispatcherFactoryCompat() <ide> public function testAddFilter() <ide> { <ide> $this->assertCount(1, $this->dispatcher->getFilters()); <del> $events = $this->dispatcher->eventManager(); <add> $events = $this->dispatcher->getEventManager(); <ide> $this->assertCount(1, $events->listeners('Dispatcher.beforeDispatch')); <ide> $this->assertCount(1, $events->listeners('Dispatcher.afterDispatch')); <ide> <ide><path>tests/TestCase/Http/ServerTest.php <ide> public function testBuildMiddlewareEvent() <ide> $server = new Server($app); <ide> $this->called = false; <ide> <del> $server->eventManager()->on('Server.buildMiddleware', function (Event $event, $middleware) { <add> $server->getEventManager()->on('Server.buildMiddleware', function (Event $event, $middleware) { <ide> $this->assertInstanceOf('Cake\Http\MiddlewareQueue', $middleware); <ide> $middleware->add(function ($req, $res, $next) { <ide> $this->called = true; <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php <ide> public function testCascadeDeleteWithCallbacks() <ide> ->setMethods(['__invoke']) <ide> ->getMock(); <ide> $counter->expects($this->exactly(2))->method('__invoke'); <del> $articleTag->eventManager()->on('Model.beforeDelete', $counter); <add> $articleTag->getEventManager()->on('Model.beforeDelete', $counter); <ide> <ide> $this->assertEquals(2, $articleTag->find()->where(['article_id' => 1])->count()); <ide> $entity = new Entity(['id' => 1, 'name' => 'PHP']); <ide> public function testReplaceLinkFailingDomainRules() <ide> { <ide> $articles = TableRegistry::get('Articles'); <ide> $tags = TableRegistry::get('Tags'); <del> $tags->eventManager()->on('Model.buildRules', function (Event $event, $rules) { <add> $tags->getEventManager()->on('Model.buildRules', function (Event $event, $rules) { <ide> $rules->add(function () { <ide> return false; <ide> }, 'rule', ['errorField' => 'name', 'message' => 'Bad data']); <ide><path>tests/TestCase/ORM/Association/BelongsToTest.php <ide> public function testAttachToBeforeFind() <ide> $listener = $this->getMockBuilder('stdClass') <ide> ->setMethods(['__invoke']) <ide> ->getMock(); <del> $this->company->eventManager()->attach($listener, 'Model.beforeFind'); <add> $this->company->getEventManager()->attach($listener, 'Model.beforeFind'); <ide> $association = new BelongsTo('Companies', $config); <ide> $listener->expects($this->once())->method('__invoke') <ide> ->with( <ide> public function testAttachToBeforeFindExtraOptions() <ide> $listener = $this->getMockBuilder('stdClass') <ide> ->setMethods(['__invoke']) <ide> ->getMock(); <del> $this->company->eventManager()->attach($listener, 'Model.beforeFind'); <add> $this->company->getEventManager()->attach($listener, 'Model.beforeFind'); <ide> $association = new BelongsTo('Companies', $config); <ide> $options = new \ArrayObject(['something' => 'more']); <ide> $listener->expects($this->once())->method('__invoke') <ide><path>tests/TestCase/ORM/Association/HasManyTest.php <ide> public function testLinkUsesSingleTransaction() <ide> $listenerAfterSave = function ($e, $entity, $options) use ($articles) { <ide> $this->assertTrue($articles->connection()->inTransaction(), 'Multiple transactions used to save associated models.'); <ide> }; <del> $articles->eventManager()->on('Model.afterSave', $listenerAfterSave); <add> $articles->getEventManager()->on('Model.afterSave', $listenerAfterSave); <ide> <ide> $options = ['atomic' => false]; <ide> $assoc->link($entity, $articles->find('all')->toArray(), $options); <ide><path>tests/TestCase/ORM/Association/HasOneTest.php <ide> public function testAttachToBeforeFind() <ide> $query = $this->user->query(); <ide> <ide> $this->listenerCalled = false; <del> $this->profile->eventManager()->on('Model.beforeFind', function ($event, $query, $options, $primary) { <add> $this->profile->getEventManager()->on('Model.beforeFind', function ($event, $query, $options, $primary) { <ide> $this->listenerCalled = true; <ide> $this->assertInstanceOf('\Cake\Event\Event', $event); <ide> $this->assertInstanceOf('\Cake\ORM\Query', $query); <ide> public function testAttachToBeforeFindExtraOptions() <ide> ]; <ide> $this->listenerCalled = false; <ide> $opts = new \ArrayObject(['something' => 'more']); <del> $this->profile->eventManager()->on( <add> $this->profile->getEventManager()->on( <ide> 'Model.beforeFind', <ide> function ($event, $query, $options, $primary) use ($opts) { <ide> $this->listenerCalled = true; <ide> public function testCascadeDelete() <ide> ]; <ide> $association = new HasOne('Profiles', $config); <ide> <del> $this->profile->eventManager()->on('Model.beforeDelete', function () { <add> $this->profile->getEventManager()->on('Model.beforeDelete', function () { <ide> $this->fail('Callbacks should not be triggered when callbacks do not cascade.'); <ide> }); <ide> <ide><path>tests/TestCase/ORM/BehaviorRegistryTest.php <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> $this->Table = new Table(['table' => 'articles']); <del> $this->EventManager = $this->Table->eventManager(); <add> $this->EventManager = $this->Table->getEventManager(); <ide> $this->Behaviors = new BehaviorRegistry($this->Table); <ide> Configure::write('App.namespace', 'TestApp'); <ide> } <ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> public function testMergeFromIdsWithAutoAssociation() <ide> $entity->clean(); <ide> <ide> // Adding a forced join to have another table with the same column names <del> $this->articles->Tags->eventManager()->attach(function ($e, $query) { <add> $this->articles->Tags->getEventManager()->attach(function ($e, $query) { <ide> $left = new IdentifierExpression('Tags.id'); <ide> $right = new IdentifierExpression('a.id'); <ide> $query->leftJoin(['a' => 'tags'], $query->newExpr()->eq($left, $right)); <ide> public function testMergeBelongsToManyFromArrayWithConditions() <ide> 'conditions' => ['ArticleTags.article_id' => 1] <ide> ]); <ide> <del> $this->articles->Tags->eventManager() <add> $this->articles->Tags->getEventManager() <ide> ->on('Model.beforeFind', function (Event $event, $query) use (&$called) { <ide> $called = true; <ide> <ide> public function testMergeManyExistingQueryAliases() <ide> ['id' => 1, 'comment' => 'Changed 1', 'user_id' => 1], <ide> ['id' => 2, 'comment' => 'Changed 2', 'user_id' => 2], <ide> ]; <del> $this->comments->eventManager()->on('Model.beforeFind', function (Event $event, $query) { <add> $this->comments->getEventManager()->on('Model.beforeFind', function (Event $event, $query) { <ide> return $query->contain(['Articles']); <ide> }); <ide> $marshall = new Marshaller($this->comments); <ide> public function testBeforeMarshalEvent() <ide> <ide> $marshall = new Marshaller($this->articles); <ide> <del> $this->articles->eventManager()->on( <add> $this->articles->getEventManager()->on( <ide> 'Model.beforeMarshal', <ide> function ($e, $data, $options) { <ide> $this->assertArrayHasKey('validate', $options); <ide> public function testBeforeMarshalEventOnAssociations() <ide> $marshall = new Marshaller($this->articles); <ide> <ide> // Assert event options are correct <del> $this->articles->users->eventManager()->on( <add> $this->articles->users->getEventManager()->on( <ide> 'Model.beforeMarshal', <ide> function ($e, $data, $options) { <ide> $this->assertArrayHasKey('validate', $options); <ide> function ($e, $data, $options) { <ide> } <ide> ); <ide> <del> $this->articles->users->eventManager()->on( <add> $this->articles->users->getEventManager()->on( <ide> 'Model.beforeMarshal', <ide> function ($e, $data, $options) { <ide> $data['secret'] = 'h45h3d'; <ide> } <ide> ); <ide> <del> $this->articles->comments->eventManager()->on( <add> $this->articles->comments->getEventManager()->on( <ide> 'Model.beforeMarshal', <ide> function ($e, $data) { <ide> $data['comment'] .= ' (modified)'; <ide> } <ide> ); <ide> <del> $this->articles->tags->eventManager()->on( <add> $this->articles->tags->getEventManager()->on( <ide> 'Model.beforeMarshal', <ide> function ($e, $data) { <ide> $data['tag'] .= ' (modified)'; <ide> } <ide> ); <ide> <del> $this->articles->tags->junction()->eventManager()->on( <add> $this->articles->tags->junction()->getEventManager()->on( <ide> 'Model.beforeMarshal', <ide> function ($e, $data) { <ide> $data['modified_by'] = 1; <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testSaveWithCallbacks() <ide> $articles = TableRegistry::get('Articles'); <ide> $articles->belongsTo('Authors'); <ide> <del> $articles->eventManager()->on('Model.beforeFind', function (Event $event, $query) { <add> $articles->getEventManager()->on('Model.beforeFind', function (Event $event, $query) { <ide> return $query->contain('Authors'); <ide> }); <ide> <ide> public function testFormatDeepDistantAssociationRecords2() <ide> $articles->hasMany('articlesTags'); <ide> $tags = $articles->association('articlesTags')->target()->belongsTo('tags'); <ide> <del> $tags->target()->eventManager()->on('Model.beforeFind', function ($e, $query) { <add> $tags->target()->getEventManager()->on('Model.beforeFind', function ($e, $query) { <ide> return $query->formatResults(function ($results) { <ide> return $results->map(function (\Cake\ORM\Entity $tag) { <ide> $tag->name .= ' - visited'; <ide><path>tests/TestCase/ORM/QueryTest.php <ide> public function testFormatResultsBelongsToMany() <ide> $table->belongsToMany('Tags'); <ide> <ide> $articlesTags <del> ->eventManager() <add> ->getEventManager() <ide> ->on('Model.beforeFind', function (Event $event, $query) { <ide> $query->formatResults(function ($results) { <ide> foreach ($results as $result) { <ide> public function testCountBeforeFind() <ide> { <ide> $table = TableRegistry::get('Articles'); <ide> $table->hasMany('Comments'); <del> $table->eventManager() <add> $table->getEventManager() <ide> ->on('Model.beforeFind', function (Event $event, $query) { <ide> $query <ide> ->limit(1) <ide> public function testBeforeFindCalledOnce() <ide> { <ide> $callCount = 0; <ide> $table = TableRegistry::get('Articles'); <del> $table->eventManager() <add> $table->getEventManager() <ide> ->on('Model.beforeFind', function (Event $event, $query) use (&$callCount) { <ide> $valueBinder = new ValueBinder(); <ide> $query->sql($valueBinder); <ide> public function testEagerLoaded() <ide> }]); <ide> $this->assertFalse($query->eagerLoaded()); <ide> <del> $table->eventManager()->attach(function ($e, $q, $o, $primary) { <add> $table->getEventManager()->attach(function ($e, $q, $o, $primary) { <ide> $this->assertTrue($primary); <ide> }, 'Model.beforeFind'); <ide> <ide> TableRegistry::get('articles') <del> ->eventManager()->attach(function ($e, $q, $o, $primary) { <add> ->getEventManager()->attach(function ($e, $q, $o, $primary) { <ide> $this->assertFalse($primary); <ide> }, 'Model.beforeFind'); <ide> $query->all(); <ide> public function testIsEagerLoaded() <ide> }]); <ide> $this->assertFalse($query->isEagerLoaded()); <ide> <del> $table->eventManager()->attach(function ($e, $q, $o, $primary) { <add> $table->getEventManager()->attach(function ($e, $q, $o, $primary) { <ide> $this->assertTrue($primary); <ide> }, 'Model.beforeFind'); <ide> <ide> TableRegistry::get('articles') <del> ->eventManager()->attach(function ($e, $q, $o, $primary) { <add> ->getEventManager()->attach(function ($e, $q, $o, $primary) { <ide> $this->assertFalse($primary); <ide> }, 'Model.beforeFind'); <ide> $query->all(); <ide> public function testCleanCopyBeforeFind() <ide> { <ide> $table = TableRegistry::get('Articles'); <ide> $table->hasMany('Comments'); <del> $table->eventManager() <add> $table->getEventManager() <ide> ->on('Model.beforeFind', function (Event $event, $query) { <ide> $query <ide> ->limit(5) <ide><path>tests/TestCase/ORM/RulesCheckerIntegrationTest.php <ide> public function testUseBeforeRules() <ide> $rules = $table->rulesChecker(); <ide> $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope')); <ide> <del> $table->eventManager()->on( <add> $table->getEventManager()->on( <ide> 'Model.beforeRules', <ide> function (Event $event, Entity $entity, \ArrayObject $options, $operation) { <ide> $this->assertEquals( <ide> public function testUseAfterRules() <ide> $rules = $table->rulesChecker(); <ide> $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope')); <ide> <del> $table->eventManager()->on( <add> $table->getEventManager()->on( <ide> 'Model.afterRules', <ide> function (Event $event, Entity $entity, \ArrayObject $options, $result, $operation) { <ide> $this->assertEquals( <ide> public function testUseBuildRulesEvent() <ide> ]); <ide> <ide> $table = TableRegistry::get('Articles'); <del> $table->eventManager()->on('Model.buildRules', function (Event $event, RulesChecker $rules) { <add> $table->getEventManager()->on('Model.buildRules', function (Event $event, RulesChecker $rules) { <ide> $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope')); <ide> }); <ide> <ide> public function testIsUniqueAliasPrefix() <ide> $rules = $table->rulesChecker(); <ide> $rules->add($rules->isUnique(['author_id'])); <ide> <del> $table->Authors->eventManager()->on('Model.beforeFind', function (Event $event, $query) { <add> $table->Authors->getEventManager()->on('Model.beforeFind', function (Event $event, $query) { <ide> $query->leftJoin(['a2' => 'authors']); <ide> }); <ide> <ide> public function testExistsInAliasPrefix() <ide> $rules = $table->rulesChecker(); <ide> $rules->add($rules->existsIn('author_id', 'Authors')); <ide> <del> $table->Authors->eventManager()->on('Model.beforeFind', function (Event $event, $query) { <add> $table->Authors->getEventManager()->on('Model.beforeFind', function (Event $event, $query) { <ide> $query->leftJoin(['a2' => 'authors']); <ide> }); <ide> <ide><path>tests/TestCase/ORM/TableRegressionTest.php <ide> public function tearDown() <ide> public function testAfterSaveRollbackTransaction() <ide> { <ide> $table = TableRegistry::get('Authors'); <del> $table->eventManager()->on( <add> $table->getEventManager()->on( <ide> 'Model.afterSave', <ide> function () use ($table) { <ide> $table->connection()->rollback(); <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testFindBeforeFindEventMutateQuery() <ide> 'table' => 'users', <ide> 'connection' => $this->connection, <ide> ]); <del> $table->eventManager()->on( <add> $table->getEventManager()->on( <ide> 'Model.beforeFind', <ide> function (Event $event, $query, $options) { <ide> $query->limit(1); <ide> public function testFindBeforeFindEventOverrideReturn() <ide> 'connection' => $this->connection, <ide> ]); <ide> $expected = ['One', 'Two', 'Three']; <del> $table->eventManager()->on( <add> $table->getEventManager()->on( <ide> 'Model.beforeFind', <ide> function (Event $event, $query, $options) use ($expected) { <ide> $query->setResult($expected); <ide> public function testBeforeSaveModifyData() <ide> $this->assertSame($data, $entity); <ide> $entity->set('password', 'foo'); <ide> }; <del> $table->eventManager()->on('Model.beforeSave', $listener); <add> $table->getEventManager()->on('Model.beforeSave', $listener); <ide> $this->assertSame($data, $table->save($data)); <ide> $this->assertEquals($data->id, self::$nextUserId); <ide> $row = $table->find('all')->where(['id' => self::$nextUserId])->first(); <ide> public function testBeforeSaveModifyOptions() <ide> $listener2 = function ($e, $entity, $options) { <ide> $this->assertTrue($options['crazy']); <ide> }; <del> $table->eventManager()->on('Model.beforeSave', $listener1); <del> $table->eventManager()->on('Model.beforeSave', $listener2); <add> $table->getEventManager()->on('Model.beforeSave', $listener1); <add> $table->getEventManager()->on('Model.beforeSave', $listener2); <ide> $this->assertSame($data, $table->save($data)); <ide> $this->assertEquals($data->id, self::$nextUserId); <ide> <ide> public function testBeforeSaveStopEvent() <ide> <ide> return $entity; <ide> }; <del> $table->eventManager()->on('Model.beforeSave', $listener); <add> $table->getEventManager()->on('Model.beforeSave', $listener); <ide> $this->assertSame($data, $table->save($data)); <ide> $this->assertNull($data->id); <ide> $row = $table->find('all')->where(['id' => self::$nextUserId])->first(); <ide> public function testAfterSave() <ide> $this->assertTrue($entity->dirty()); <ide> $called = true; <ide> }; <del> $table->eventManager()->on('Model.afterSave', $listener); <add> $table->getEventManager()->on('Model.afterSave', $listener); <ide> <ide> $calledAfterCommit = false; <ide> $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) { <ide> public function testAfterSave() <ide> $this->assertNotSame($data->get('username'), $data->getOriginal('username')); <ide> $calledAfterCommit = true; <ide> }; <del> $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit); <add> $table->getEventManager()->on('Model.afterSaveCommit', $listenerAfterCommit); <ide> <ide> $this->assertSame($data, $table->save($data)); <ide> $this->assertTrue($called); <ide> public function testAfterSaveCommitForNonAtomic() <ide> $this->assertSame($data, $entity); <ide> $called = true; <ide> }; <del> $table->eventManager()->on('Model.afterSave', $listener); <add> $table->getEventManager()->on('Model.afterSave', $listener); <ide> <ide> $calledAfterCommit = false; <ide> $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) { <ide> $calledAfterCommit = true; <ide> }; <del> $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit); <add> $table->getEventManager()->on('Model.afterSaveCommit', $listenerAfterCommit); <ide> <ide> $this->assertSame($data, $table->save($data, ['atomic' => false])); <ide> $this->assertEquals($data->id, self::$nextUserId); <ide> public function testAfterSaveCommitWithTransactionRunning() <ide> $listener = function ($e, $entity, $options) use (&$called) { <ide> $called = true; <ide> }; <del> $table->eventManager()->on('Model.afterSaveCommit', $listener); <add> $table->getEventManager()->on('Model.afterSaveCommit', $listener); <ide> <ide> $this->connection->begin(); <ide> $this->assertSame($data, $table->save($data)); <ide> public function testAfterSaveCommitWithNonAtomicAndTransactionRunning() <ide> $listener = function ($e, $entity, $options) use (&$called) { <ide> $called = true; <ide> }; <del> $table->eventManager()->on('Model.afterSaveCommit', $listener); <add> $table->getEventManager()->on('Model.afterSaveCommit', $listener); <ide> <ide> $this->connection->begin(); <ide> $this->assertSame($data, $table->save($data, ['atomic' => false])); <ide> public function testAfterSaveNotCalled() <ide> $listener = function ($e, $entity, $options) use ($data, &$called) { <ide> $called = true; <ide> }; <del> $table->eventManager()->on('Model.afterSave', $listener); <add> $table->getEventManager()->on('Model.afterSave', $listener); <ide> <ide> $calledAfterCommit = false; <ide> $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) { <ide> $calledAfterCommit = true; <ide> }; <del> $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit); <add> $table->getEventManager()->on('Model.afterSaveCommit', $listenerAfterCommit); <ide> <ide> $this->assertFalse($table->save($data)); <ide> $this->assertFalse($called); <ide> public function testAfterSaveCommitTriggeredOnlyForPrimaryTable() <ide> $listenerForArticle = function ($e, $entity, $options) use (&$calledForArticle) { <ide> $calledForArticle = true; <ide> }; <del> $table->eventManager()->on('Model.afterSaveCommit', $listenerForArticle); <add> $table->getEventManager()->on('Model.afterSaveCommit', $listenerForArticle); <ide> <ide> $calledForAuthor = false; <ide> $listenerForAuthor = function ($e, $entity, $options) use (&$calledForAuthor) { <ide> $calledForAuthor = true; <ide> }; <del> $table->authors->eventManager()->on('Model.afterSaveCommit', $listenerForAuthor); <add> $table->authors->getEventManager()->on('Model.afterSaveCommit', $listenerForAuthor); <ide> <ide> $this->assertSame($entity, $table->save($entity)); <ide> $this->assertFalse($entity->isNew()); <ide> public function testBeforeSaveGetsCorrectPersistance() <ide> $this->assertFalse($entity->isNew()); <ide> $called = true; <ide> }; <del> $table->eventManager()->on('Model.beforeSave', $listener); <add> $table->getEventManager()->on('Model.beforeSave', $listener); <ide> $this->assertSame($entity, $table->save($entity)); <ide> $this->assertTrue($called); <ide> } <ide> public function testDeleteCallbacksNonAtomic() <ide> $this->assertSame($data, $entity); <ide> $called = true; <ide> }; <del> $table->eventManager()->on('Model.afterDelete', $listener); <add> $table->getEventManager()->on('Model.afterDelete', $listener); <ide> <ide> $calledAfterCommit = false; <ide> $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) { <ide> $calledAfterCommit = true; <ide> }; <del> $table->eventManager()->on('Model.afterDeleteCommit', $listenerAfterCommit); <add> $table->getEventManager()->on('Model.afterDeleteCommit', $listenerAfterCommit); <ide> <ide> $table->delete($data, ['atomic' => false]); <ide> $this->assertTrue($called); <ide> public function testAfterDeleteCommitTriggeredOnlyForPrimaryTable() <ide> $listener = function ($e, $entity, $options) use (&$called) { <ide> $called = true; <ide> }; <del> $table->eventManager()->on('Model.afterDeleteCommit', $listener); <add> $table->getEventManager()->on('Model.afterDeleteCommit', $listener); <ide> <ide> $called2 = false; <ide> $listener = function ($e, $entity, $options) use (&$called2) { <ide> $called2 = true; <ide> }; <del> $table->articles->eventManager()->on('Model.afterDeleteCommit', $listener); <add> $table->articles->getEventManager()->on('Model.afterDeleteCommit', $listener); <ide> <ide> $entity = $table->get(1); <ide> $this->assertTrue($table->delete($entity)); <ide> public function testOptionsBeingPassedToImplicitBelongsToManyDeletesUsingSaveRep <ide> $tags->cascadeCallbacks(true); <ide> <ide> $actualOptions = null; <del> $tags->junction()->eventManager()->on( <add> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeDelete', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> public function testOptionsBeingPassedToInternalSaveCallsUsingBelongsToManyLink( <ide> $tags = $articles->belongsToMany('Tags'); <ide> <ide> $actualOptions = null; <del> $tags->junction()->eventManager()->on( <add> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeSave', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> public function testOptionsBeingPassedToInternalSaveCallsUsingBelongsToManyUnlin <ide> $tags = $articles->belongsToMany('Tags'); <ide> <ide> $actualOptions = null; <del> $tags->junction()->eventManager()->on( <add> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeDelete', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> public function testOptionsBeingPassedToInternalSaveAndDeleteCallsUsingBelongsTo <ide> <ide> $actualSaveOptions = null; <ide> $actualDeleteOptions = null; <del> $tags->junction()->eventManager()->on( <add> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeSave', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualSaveOptions) { <ide> $actualSaveOptions = $options->getArrayCopy(); <ide> } <ide> ); <del> $tags->junction()->eventManager()->on( <add> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeDelete', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualDeleteOptions) { <ide> $actualDeleteOptions = $options->getArrayCopy(); <ide> public function testOptionsBeingPassedToImplicitHasManyDeletesUsingSaveReplace() <ide> $articles->cascadeCallbacks(true); <ide> <ide> $actualOptions = null; <del> $articles->target()->eventManager()->on( <add> $articles->target()->getEventManager()->on( <ide> 'Model.beforeDelete', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> public function testOptionsBeingPassedToInternalSaveCallsUsingHasManyLink() <ide> $articles = $authors->hasMany('Articles'); <ide> <ide> $actualOptions = null; <del> $articles->target()->eventManager()->on( <add> $articles->target()->getEventManager()->on( <ide> 'Model.beforeSave', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> public function testOptionsBeingPassedToInternalSaveCallsUsingHasManyUnlink() <ide> $articles->cascadeCallbacks(true); <ide> <ide> $actualOptions = null; <del> $articles->target()->eventManager()->on( <add> $articles->target()->getEventManager()->on( <ide> 'Model.beforeDelete', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> public function testOptionsBeingPassedToInternalSaveAndDeleteCallsUsingHasManyRe <ide> <ide> $actualSaveOptions = null; <ide> $actualDeleteOptions = null; <del> $articles->target()->eventManager()->on( <add> $articles->target()->getEventManager()->on( <ide> 'Model.beforeSave', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualSaveOptions) { <ide> $actualSaveOptions = $options->getArrayCopy(); <ide> } <ide> ); <del> $articles->target()->eventManager()->on( <add> $articles->target()->getEventManager()->on( <ide> 'Model.beforeDelete', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualDeleteOptions) { <ide> $actualDeleteOptions = $options->getArrayCopy(); <ide> public function testBackwardsCompatibilityForBelongsToManyUnlinkCleanPropertyOpt <ide> $tags = $articles->belongsToMany('Tags'); <ide> <ide> $actualOptions = null; <del> $tags->junction()->eventManager()->on( <add> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeDelete', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> public function testBackwardsCompatibilityForHasManyUnlinkCleanPropertyOption() <ide> $articles->cascadeCallbacks(true); <ide> <ide> $actualOptions = null; <del> $articles->target()->eventManager()->on( <add> $articles->target()->getEventManager()->on( <ide> 'Model.beforeDelete', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> public function testCallbackArgumentTypes() <ide> $table = TableRegistry::get('articles'); <ide> $table->belongsTo('authors'); <ide> <del> $eventManager = $table->eventManager(); <add> $eventManager = $table->getEventManager(); <ide> <ide> $associationBeforeFindCount = 0; <del> $table->association('authors')->target()->eventManager()->on( <add> $table->association('authors')->target()->getEventManager()->on( <ide> 'Model.beforeFind', <ide> function (Event $event, Query $query, ArrayObject $options, $primary) use (&$associationBeforeFindCount) { <ide> $this->assertTrue(is_bool($primary)); <ide> public function testSaveHasManyNoWasteSave() <ide> <ide> $counter = 0; <ide> $userTable->Comments <del> ->eventManager() <add> ->getEventManager() <ide> ->on('Model.afterSave', function (Event $event, $entity) use (&$counter) { <ide> if ($entity->dirty()) { <ide> $counter++; <ide> public function testSaveBelongsToManyNoWasteSave() <ide> <ide> $counter = 0; <ide> $table->Tags->junction() <del> ->eventManager() <add> ->getEventManager() <ide> ->on('Model.afterSave', function (Event $event, $entity) use (&$counter) { <ide> if ($entity->dirty()) { <ide> $counter++; <ide><path>tests/TestCase/View/HelperRegistryTest.php <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> $this->View = new View(); <del> $this->Events = $this->View->eventManager(); <add> $this->Events = $this->View->getEventManager(); <ide> $this->Helpers = new HelperRegistry($this->View); <ide> } <ide> <ide><path>tests/TestCase/View/ViewBuilderTest.php <ide> public function testBuildComplete() <ide> $this->assertEquals('TestTheme', $view->theme); <ide> $this->assertSame($request, $view->request); <ide> $this->assertSame($response, $view->response); <del> $this->assertSame($events, $view->eventManager()); <add> $this->assertSame($events, $view->getEventManager()); <ide> $this->assertSame(['one' => 'value'], $view->viewVars); <ide> $this->assertInstanceOf('Cake\View\Helper\HtmlHelper', $view->Html); <ide> $this->assertInstanceOf('Cake\View\Helper\FormHelper', $view->Form); <ide><path>tests/TestCase/View/ViewTest.php <ide> public function testElementCallbacks() <ide> $callback = function (Event $event, $file) use (&$count) { <ide> $count++; <ide> }; <del> $events = $this->View->eventManager(); <add> $events = $this->View->getEventManager(); <ide> $events->attach($callback, 'View.beforeRender'); <ide> $events->attach($callback, 'View.afterRender'); <ide> <ide> public function testViewEvent() <ide> $View->autoLayout = false; <ide> $listener = new TestViewEventListenerInterface(); <ide> <del> $View->eventManager()->attach($listener); <add> $View->getEventManager()->attach($listener); <ide> <ide> $View->render('index'); <ide> $this->assertEquals(View::TYPE_VIEW, $listener->beforeRenderViewType); <ide><path>tests/test_app/TestApp/Controller/PostsController.php <ide> class PostsController extends AppController <ide> public function beforeFilter(Event $event) <ide> { <ide> if ($this->request->param('action') !== 'securePost') { <del> $this->eventManager()->off($this->Security); <add> $this->getEventManager()->off($this->Security); <ide> } <ide> } <ide>
22
Javascript
Javascript
use react.autobind by default
c9ecbaccb365ba39bd8839f61ae245cdc295317b
<ide><path>src/core/ReactCompositeComponent.js <ide> var keyMirror = require('keyMirror'); <ide> var merge = require('merge'); <ide> var mixInto = require('mixInto'); <ide> <add>var invokedBeforeMount = function() { <add> invariant( <add> false, <add> 'You have invoked a method that is automatically bound, before the ' + <add> 'instance has been mounted. There is nothing conceptually wrong with ' + <add> 'this, but since this method will be replaced with a new version once ' + <add> 'the component is mounted - you should be aware of the fact that this ' + <add> 'method will soon be replaced.' <add> ); <add>}; <add> <ide> /** <ide> * Policies that describe methods in `ReactCompositeComponentInterface`. <ide> */ <ide> var RESERVED_SPEC_KEYS = { <ide> } <ide> }; <ide> <add>function validateMethodOverride(proto, name) { <add> var specPolicy = ReactCompositeComponentInterface[name]; <add> <add> // Disallow overriding of base class methods unless explicitly allowed. <add> if (ReactCompositeComponentMixin.hasOwnProperty(name)) { <add> invariant( <add> specPolicy === SpecPolicy.OVERRIDE_BASE, <add> 'ReactCompositeComponentInterface: You are attempting to override ' + <add> '`%s` from your class specification. Ensure that your method names ' + <add> 'do not overlap with React methods.', <add> name <add> ); <add> } <add> <add> // Disallow defining methods more than once unless explicitly allowed. <add> if (proto.hasOwnProperty(name)) { <add> invariant( <add> specPolicy === SpecPolicy.DEFINE_MANY, <add> 'ReactCompositeComponentInterface: You are attempting to define ' + <add> '`%s` on your component more than once. This conflict may be due ' + <add> 'to a mixin.', <add> name <add> ); <add> } <add>} <add> <add> <add>function validateLifeCycleOnReplaceState(instance) { <add> var compositeLifeCycleState = instance._compositeLifeCycleState; <add> invariant( <add> instance.isMounted(), <add> 'replaceState(...): Can only update a mounted component.' <add> ); <add> invariant( <add> compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE && <add> compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING, <add> 'replaceState(...): Cannot update while unmounting component or during ' + <add> 'an existing state transition (such as within `render`).' <add> ); <add>} <add> <ide> /** <ide> * Custom version of `mixInto` which handles policy validation and reserved <ide> * specification keys when building `ReactCompositeComponent` classses. <ide> */ <ide> function mixSpecIntoComponent(Constructor, spec) { <ide> var proto = Constructor.prototype; <ide> for (var name in spec) { <del> if (!spec.hasOwnProperty(name)) { <del> continue; <del> } <ide> var property = spec[name]; <del> var specPolicy = ReactCompositeComponentInterface[name]; <del> <del> // Disallow overriding of base class methods unless explicitly allowed. <del> if (ReactCompositeComponentMixin.hasOwnProperty(name)) { <del> invariant( <del> specPolicy === SpecPolicy.OVERRIDE_BASE, <del> 'ReactCompositeComponentInterface: You are attempting to override ' + <del> '`%s` from your class specification. Ensure that your method names ' + <del> 'do not overlap with React methods.', <del> name <del> ); <del> } <del> <del> // Disallow using `React.autoBind` on internal methods. <del> if (specPolicy != null) { <del> invariant( <del> !property || !property.__reactAutoBind, <del> 'ReactCompositeComponentInterface: You are attempting to use ' + <del> '`React.autoBind` on `%s`, a method that is internal to React.' + <del> 'Internal methods are called with the component as the context.', <del> name <del> ); <del> } <del> <del> // Disallow defining methods more than once unless explicitly allowed. <del> if (proto.hasOwnProperty(name)) { <del> invariant( <del> specPolicy === SpecPolicy.DEFINE_MANY, <del> 'ReactCompositeComponentInterface: You are attempting to define ' + <del> '`%s` on your component more than once. This conflict may be due ' + <del> 'to a mixin.', <del> name <del> ); <add> if (!spec.hasOwnProperty(name) || !property) { <add> continue; <ide> } <add> validateMethodOverride(proto, name); <ide> <ide> if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { <ide> RESERVED_SPEC_KEYS[name](Constructor, property); <del> } else if (property && property.__reactAutoBind) { <del> if (!proto.__reactAutoBindMap) { <del> proto.__reactAutoBindMap = {}; <del> } <del> proto.__reactAutoBindMap[name] = property.__reactAutoBind; <del> } else if (proto.hasOwnProperty(name)) { <del> // For methods which are defined more than once, call the existing methods <del> // before calling the new property. <del> proto[name] = createChainedFunction(proto[name], property); <ide> } else { <del> proto[name] = property; <add> // Setup methods on prototype: <add> // The following member methods should not be automatically bound: <add> // 1. Expected ReactCompositeComponent methods (in the "interface"). <add> // 2. Overridden methods (that were mixed in). <add> var isCompositeComponentMethod = name in ReactCompositeComponentInterface; <add> var isInherited = name in proto; <add> var markedDontBind = property.__reactDontBind; <add> var isFunction = typeof property === 'function'; <add> var shouldAutoBind = <add> isFunction && <add> !isCompositeComponentMethod && <add> !isInherited && <add> !markedDontBind; <add> <add> if (shouldAutoBind) { <add> if (!proto.__reactAutoBindMap) { <add> proto.__reactAutoBindMap = {}; <add> } <add> proto.__reactAutoBindMap[name] = property; <add> proto[name] = invokedBeforeMount; <add> } else { <add> if (isInherited) { <add> // For methods which are defined more than once, call the existing <add> // methods before calling the new property. <add> proto[name] = createChainedFunction(proto[name], property); <add> } else { <add> proto[name] = property; <add> } <add> } <ide> } <ide> } <ide> } <ide> function createChainedFunction(one, two) { <ide> * `this._compositeLifeCycleState` (which can be null). <ide> * <ide> * This is different from the life cycle state maintained by `ReactComponent` in <del> * `this._lifeCycleState`. <add> * `this._lifeCycleState`. The following diagram shows how the states overlap in <add> * time. There are times when the CompositeLifeCycle is null - at those times it <add> * is only meaningful to look at ComponentLifeCycle alone. <add> * <add> * Top Row: ReactComponent.ComponentLifeCycle <add> * Low Row: ReactComponent.CompositeLifeCycle <add> * <add> * +-------+------------------------------------------------------+--------+ <add> * | UN | MOUNTED | UN | <add> * |MOUNTED| | MOUNTED| <add> * +-------+------------------------------------------------------+--------+ <add> * | ^--------+ +------+ +------+ +------+ +--------^ | <add> * | | | | | | | | | | | | <add> * | 0--|MOUNTING|-0-|RECEIV|-0-|RECEIV|-0-|RECEIV|-0-| UN |--->0 | <add> * | | | |PROPS | | PROPS| | STATE| |MOUNTING| | <add> * | | | | | | | | | | | | <add> * | | | | | | | | | | | | <add> * | +--------+ +------+ +------+ +------+ +--------+ | <add> * | | | | <add> * +-------+------------------------------------------------------+--------+ <ide> */ <ide> var CompositeLifeCycle = keyMirror({ <ide> /** <ide> var ReactCompositeComponentMixin = { <ide> */ <ide> mountComponent: function(rootID, transaction) { <ide> ReactComponent.Mixin.mountComponent.call(this, rootID, transaction); <del> <del> // Unset `this._lifeCycleState` until after this method is finished. <del> this._lifeCycleState = ReactComponent.LifeCycle.UNMOUNTED; <ide> this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING; <del> <ide> this._processProps(this.props); <ide> <ide> if (this.__reactAutoBindMap) { <ide> var ReactCompositeComponentMixin = { <ide> <ide> // Done with mounting, `setState` will now trigger UI changes. <ide> this._compositeLifeCycleState = null; <del> this._lifeCycleState = ReactComponent.LifeCycle.MOUNTED; <del> <del> var html = this._renderedComponent.mountComponent(rootID, transaction); <del> <add> var markup = this._renderedComponent.mountComponent(rootID, transaction); <ide> if (this.componentDidMount) { <ide> transaction.getReactOnDOMReady().enqueue(this, this.componentDidMount); <ide> } <del> <del> return html; <add> return markup; <ide> }, <ide> <ide> /** <ide> var ReactCompositeComponentMixin = { <ide> */ <ide> replaceState: function(completeState) { <ide> var compositeLifeCycleState = this._compositeLifeCycleState; <del> invariant( <del> this.isMounted() || <del> compositeLifeCycleState === CompositeLifeCycle.MOUNTING, <del> 'replaceState(...): Can only update a mounted (or mounting) component.' <del> ); <del> invariant( <del> compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE && <del> compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING, <del> 'replaceState(...): Cannot update while unmounting component or during ' + <del> 'an existing state transition (such as within `render`).' <del> ); <del> <add> validateLifeCycleOnReplaceState.call(null, this); <ide> this._pendingState = completeState; <ide> <ide> // Do not trigger a state transition if we are in the middle of mounting or <ide> var ReactCompositeComponentMixin = { <ide> transaction <ide> ); <ide> ReactComponent.ReactReconcileTransaction.release(transaction); <del> <ide> this._compositeLifeCycleState = null; <ide> } <ide> }, <ide> var ReactCompositeComponentMixin = { <ide> */ <ide> _bindAutoBindMethod: function(method) { <ide> var component = this; <del> var hasWarned = false; <ide> function autoBound(a, b, c, d, e, tooMany) { <ide> invariant( <ide> typeof tooMany === 'undefined', <ide> 'React.autoBind(...): Methods can only take a maximum of 5 arguments.' <ide> ); <del> if (component._lifeCycleState === ReactComponent.LifeCycle.MOUNTED) { <del> return method.call(component, a, b, c, d, e); <del> } else if (!hasWarned) { <del> hasWarned = true; <del> if (__DEV__) { <del> console.warn( <del> 'React.autoBind(...): Attempted to invoke an auto-bound method ' + <del> 'on an unmounted instance of `%s`. You either have a memory leak ' + <del> 'or an event handler that is being run after unmounting.', <del> component.constructor.displayName || 'ReactCompositeComponent' <del> ); <del> } <del> } <add> return method.call(component, a, b, c, d, e); <ide> } <ide> return autoBound; <ide> } <ide> var ReactCompositeComponent = { <ide> }, <ide> <ide> /** <del> * Marks the provided method to be automatically bound to the component. <del> * This means the method's context will always be the component. <del> * <del> * React.createClass({ <del> * handleClick: React.autoBind(function() { <del> * this.setState({jumping: true}); <del> * }), <del> * render: function() { <del> * return <a onClick={this.handleClick}>Jump</a>; <del> * } <del> * }); <add> * TODO: Delete this when all callers have been updated to rely on this <add> * behavior being the default. <ide> * <add> * Backwards compatible stub for what is now the default behavior. <ide> * @param {function} method Method to be bound. <ide> * @public <ide> */ <ide> autoBind: function(method) { <del> function unbound() { <del> invariant( <del> false, <del> 'React.autoBind(...): Attempted to invoke an auto-bound method that ' + <del> 'was not correctly defined on the class specification.' <del> ); <del> } <del> unbound.__reactAutoBind = method; <del> return unbound; <add> return method; <ide> } <del> <ide> }; <ide> <ide> module.exports = ReactCompositeComponent; <ide><path>src/core/ReactDoNotBindDeprecated.js <add>/** <add> * Copyright 2013 Facebook, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> * <add> * @providesModule ReactDoNotBindDeprecated <add> */ <add> <add>var ReactDoNotBindDeprecated = { <add> /** <add> * Marks the method for not being automatically bound on component mounting. A <add> * couple of reasons you might want to use this: <add> * <add> * - Automatically supporting the previous behavior in components that were <add> * built with previous versions of React. <add> * - Tuning performance, by avoiding binding on initial render for methods <add> * that are always invoked while being preceded by `this.`. Such binds are <add> * unnecessary. <add> * <add> * React.createClass({ <add> * handleClick: ReactDoNotBindDeprecated.doNotBind(function() { <add> * alert(this.setState); // undefined! <add> * }), <add> * render: function() { <add> * return <a onClick={this.handleClick}>Jump</a>; <add> * } <add> * }); <add> * <add> * @param {function} method Method to avoid automatically binding. <add> * @public <add> */ <add> doNotBind: function(method) { <add> method.__reactDontBind = true; // Mutating <add> return method; <add> } <add>}; <add> <add>module.exports = ReactDoNotBindDeprecated; <ide><path>src/core/ReactID.js <ide> var nodeCache = {}; <ide> * other objects so just return '' if we're given something other than a <ide> * DOM node (such as window). <ide> * <del> * @param {DOMElement|DOMWindow|DOMDocument} node DOM node. <add> * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. <ide> * @returns {string} ID of the supplied `domNode`. <ide> */ <ide> function getID(node) { <ide><path>src/core/__tests__/ReactBind-test.js <ide> <ide> var mocks = require('mocks'); <ide> var React = require('React'); <add>var ReactDoNotBindDeprecated = require('ReactDoNotBindDeprecated'); <ide> var ReactTestUtils = require('ReactTestUtils'); <ide> var reactComponentExpect = require('reactComponentExpect'); <ide> <add>// TODO: Test render and all stock methods. <ide> describe('React.autoBind', function() { <ide> <ide> it('Holds reference to instance', function() { <ide> <ide> var mouseDidEnter = mocks.getMockFunction(); <ide> var mouseDidLeave = mocks.getMockFunction(); <ide> var mouseDidClick = mocks.getMockFunction(); <del> var didBadIdea = mocks.getMockFunction(); <ide> <ide> var TestBindComponent = React.createClass({ <del> onMouseEnter: mouseDidEnter, <del> onMouseLeave: mouseDidLeave, <add> getInitialState: function() { <add> return {something: 'hi'}; <add> }, <add> onMouseEnter: ReactDoNotBindDeprecated.doNotBind(mouseDidEnter), <add> onMouseLeave: ReactDoNotBindDeprecated.doNotBind(mouseDidLeave), <ide> onClick: React.autoBind(mouseDidClick), <ide> <del> // autoBind needs to be on the top-level spec. <add> // auto binding only occurs on top level functions in class defs. <ide> badIdeas: { <del> badBind: React.autoBind(didBadIdea) <add> badBind: function() { <add> this.state.something; <add> } <ide> }, <ide> <ide> render: function() { <ide> return ( <ide> <div <ide> onMouseEnter={this.onMouseEnter.bind(this)} <ide> onMouseLeave={this.onMouseLeave} <del> onClick={this.onClick} /> <add> onClick={this.onClick} <add> /> <ide> ); <ide> } <ide> }); <ide><path>src/core/__tests__/ReactComponentLifeCycle-test.js <ide> describe('ReactComponentLifeCycle', function() { <ide> if (isInitialRender) { <ide> this._testJournal.stateInInitialRender = clone(this.state); <ide> this._testJournal.lifeCycleInInitialRender = this._lifeCycleState; <add> this._testJournal.compositeLifeCycleInInitialRender = <add> this._compositeLifeCycleState; <ide> } else { <ide> this._testJournal.stateInLaterRender = clone(this.state); <ide> this._testJournal.lifeCycleInLaterRender = this._lifeCycleState; <ide> describe('ReactComponentLifeCycle', function() { <ide> GET_INIT_STATE_RETURN_VAL <ide> ); <ide> expect(instance._testJournal.lifeCycleAtStartOfGetInitialState) <del> .toBe(ComponentLifeCycle.UNMOUNTED); <add> .toBe(ComponentLifeCycle.MOUNTED); <ide> expect(instance._testJournal.compositeLifeCycleAtStartOfGetInitialState) <ide> .toBe(CompositeComponentLifeCycle.MOUNTING); <ide> <ide> describe('ReactComponentLifeCycle', function() { <ide> instance._testJournal.returnedFromGetInitialState <ide> ); <ide> expect(instance._testJournal.lifeCycleAtStartOfWillMount) <del> .toBe(ComponentLifeCycle.UNMOUNTED); <add> .toBe(ComponentLifeCycle.MOUNTED); <ide> expect(instance._testJournal.compositeLifeCycleAtStartOfWillMount) <ide> .toBe(CompositeComponentLifeCycle.MOUNTING); <ide> <ide> describe('ReactComponentLifeCycle', function() { <ide> expect(instance._testJournal.stateInInitialRender) <ide> .toEqual(INIT_RENDER_STATE); <ide> expect(instance._testJournal.lifeCycleInInitialRender).toBe( <del> ComponentLifeCycle.UNMOUNTED <add> ComponentLifeCycle.MOUNTED <add> ); <add> expect(instance._testJournal.compositeLifeCycleInInitialRender).toBe( <add> CompositeComponentLifeCycle.MOUNTING <ide> ); <ide> <ide> expect(instance._lifeCycleState).toBe(ComponentLifeCycle.MOUNTED); <ide> describe('ReactComponentLifeCycle', function() { <ide> expect(instance.state.stateField).toBe('goodbye'); <ide> }); <ide> <del> it('should call nested lifecycle methods in the right order', function() { <del> var log; <del> var logger = function(msg) { <del> return function() { <del> // return true for shouldComponentUpdate <del> log.push(msg); <del> return true; <del> }; <del> }; <del> var Outer = React.createClass({ <del> render: function() { <del> return <div><Inner x={this.props.x} /></div>; <del> }, <del> componentWillMount: logger('outer componentWillMount'), <del> componentDidMount: logger('outer componentDidMount'), <del> componentWillReceiveProps: logger('outer componentWillReceiveProps'), <del> shouldComponentUpdate: logger('outer shouldComponentUpdate'), <del> componentWillUpdate: logger('outer componentWillUpdate'), <del> componentDidUpdate: logger('outer componentDidUpdate'), <del> componentWillUnmount: logger('outer componentWillUnmount') <del> }); <del> var Inner = React.createClass({ <del> render: function() { <del> return <span>{this.props.x}</span>; <del> }, <del> componentWillMount: logger('inner componentWillMount'), <del> componentDidMount: logger('inner componentDidMount'), <del> componentWillReceiveProps: logger('inner componentWillReceiveProps'), <del> shouldComponentUpdate: logger('inner shouldComponentUpdate'), <del> componentWillUpdate: logger('inner componentWillUpdate'), <del> componentDidUpdate: logger('inner componentDidUpdate'), <del> componentWillUnmount: logger('inner componentWillUnmount') <del> }); <del> var instance; <del> <del> log = []; <del> instance = ReactTestUtils.renderIntoDocument(<Outer x={17} />); <del> expect(log).toEqual([ <del> 'outer componentWillMount', <del> 'inner componentWillMount', <del> 'inner componentDidMount', <del> 'outer componentDidMount' <del> ]); <del> <del> log = []; <del> instance.setProps({x: 42}); <del> expect(log).toEqual([ <del> 'outer componentWillReceiveProps', <del> 'outer shouldComponentUpdate', <del> 'outer componentWillUpdate', <del> 'inner componentWillReceiveProps', <del> 'inner shouldComponentUpdate', <del> 'inner componentWillUpdate', <del> 'inner componentDidUpdate', <del> 'outer componentDidUpdate' <del> ]); <del> <del> log = []; <del> instance.unmountComponent(); <del> expect(log).toEqual([ <del> 'outer componentWillUnmount', <del> 'inner componentWillUnmount' <del> ]); <del> }); <del> <ide> }); <ide> <ide><path>src/core/__tests__/ReactCompositeComponent-test.js <ide> var ReactCurrentOwner; <ide> var ReactProps; <ide> var ReactTestUtils; <ide> var ReactID; <add>var ReactDoNotBindDeprecated; <ide> <ide> var cx; <ide> var reactComponentExpect; <ide> describe('ReactCompositeComponent', function() { <ide> reactComponentExpect = require('reactComponentExpect'); <ide> React = require('React'); <ide> ReactCurrentOwner = require('ReactCurrentOwner'); <add> ReactDoNotBindDeprecated = require('ReactDoNotBindDeprecated'); <ide> ReactProps = require('ReactProps'); <ide> ReactTestUtils = require('ReactTestUtils'); <ide> ReactID = require('ReactID'); <ide> describe('ReactCompositeComponent', function() { <ide> }, <ide> <ide> render: function() { <del> var toggleActivatedState = this._toggleActivatedState.bind(this); <add> var toggleActivatedState = this._toggleActivatedState; <ide> return !this.state.activated ? <ide> <a ref="x" onClick={toggleActivatedState} /> : <ide> <b ref="x" onClick={toggleActivatedState} />; <ide> describe('ReactCompositeComponent', function() { <ide> return {activated: false}; <ide> }, <ide> <del> _toggleActivatedState: React.autoBind(function() { <add> _toggleActivatedState:function() { <ide> this.setState({activated: !this.state.activated}); <del> }), <add> }, <ide> <ide> render: function() { <ide> return !this.state.activated ? <ide> describe('ReactCompositeComponent', function() { <ide> }); <ide> <ide> it('should auto bind methods and values correctly', function() { <del> var RETURN_VALUE_AFTER_MOUNT = 'returnValue'; <ide> var ComponentClass = React.createClass({ <ide> getInitialState: function() { <del> return { <del> valueToReturn: RETURN_VALUE_AFTER_MOUNT <del> }; <add> return {valueToReturn: 'hi'}; <add> }, <add> methodToBeExplicitlyBound: function() { <add> return this; <ide> }, <del> methodBoundOnMount: React.autoBind(function() { <del> return this.state.valueToReturn; <add> methodAutoBound: function() { <add> return this; <add> }, <add> methodExplicitlyNotBound: ReactDoNotBindDeprecated.doNotBind(function() { <add> return this; <ide> }), <ide> render: function() { <ide> return <div> </div>; <ide> describe('ReactCompositeComponent', function() { <ide> var instance = <ComponentClass />; <ide> <ide> // Autobound methods will throw before mounting. <add> // TODO: We should actually allow component instance methods to be invoked <add> // before mounting for read-only operations. We would then update this test. <add> expect(function() { <add> instance.methodToBeExplicitlyBound.bind(instance)(); <add> }).toThrow(); <ide> expect(function() { <del> instance.methodBoundOnMount(); <add> instance.methodAutoBound(); <ide> }).toThrow(); <add> expect(function() { <add> instance.methodExplicitlyNotBound(); <add> }).not.toThrow(); <ide> <ide> // Next, prove that once mounted, the scope is bound correctly to the actual <ide> // component. <ide> ReactTestUtils.renderIntoDocument(instance); <del> var retValAfterMount = instance.methodBoundOnMount(); <del> expect(retValAfterMount).toBe(RETURN_VALUE_AFTER_MOUNT); <del> var retValAfterMountWithCrazyScope = <del> instance.methodBoundOnMount.call({thisIsACrazyScope:null}); <del> expect(retValAfterMountWithCrazyScope).toBe(RETURN_VALUE_AFTER_MOUNT); <add> var explicitlyBound = instance.methodToBeExplicitlyBound.bind(instance); <add> var autoBound = instance.methodAutoBound; <add> var explicitlyNotBound = instance.methodExplicitlyNotBound; <add> <add> expect(explicitlyBound.call(null)).toBe(instance); <add> expect(autoBound.call(null)).toBe(instance); <add> expect(explicitlyNotBound.call(null)).toBe(null); <add> <add> expect(explicitlyBound.call(instance)).toBe(instance); <add> expect(autoBound.call(instance)).toBe(instance); <add> expect(explicitlyNotBound.call(instance)).toBe(instance); <add> <ide> }); <ide> <ide> it('should normalize props with default values', function() {
6
Go
Go
fix typo in overlay's create godoc
5bac5302e59f0759545910ef748cc9a6f87db5c5
<ide><path>daemon/graphdriver/overlay/overlay.go <ide> func (d *naiveDiffDriverWithApply) ApplyDiff(id, parent string, diff archive.Arc <ide> // directory overlaid on the parents root. This is typically the <ide> // case with the init layer of a container which is based on an image. <ide> // If there is no "root" in the parent, we inherit the lower-id from <del>// the parent and start by making a copy if the parents "upper" dir. <add>// the parent and start by making a copy in the parent's "upper" dir. <ide> // This is typically the case for a container layer which copies <ide> // its parent -init upper layer. <ide>
1
Python
Python
add support for function call fixing, add tests
4cb311b9455375f6497e7ecb6c931e09b1917d60
<ide><path>scripts/flaskext_migrate.py <ide> def fix_standard_imports(red): <ide> """ <ide> Handles import modification in the form: <ide> import flask.ext.foo" --> import flask_foo <del> <del> Does not modify function calls elsewhere in the source outside of the <del> original import statement. <ide> """ <ide> imports = red.find_all("ImportNode") <ide> for x, node in enumerate(imports): <ide> try: <del> if (node.value[0].value == 'flask' and <del> node.value[1].value == 'ext'): <del> package = node.value[2].value <del> name = node.names()[0] <del> imports[x].replace("import flask_%s as %s" % (package, name)) <add> if (node.value[0].value[0].value == 'flask' and <add> node.value[0].value[1].value == 'ext'): <add> package = node.value[0].value[2] <add> name = node.names()[0].split('.')[-1] <add> node.replace("import flask_%s as %s" % (package, name)) <ide> except IndexError: <ide> pass <ide> <ide> def fix_standard_imports(red): <ide> <ide> def _get_modules(module): <ide> """ <del> Takes a list of modules and converts into a string <add> Takes a list of modules and converts into a string. <ide> <ide> The module list can include parens, this function checks each element in <ide> the list, if there is a paren then it does not add a comma before the next <ide> def _get_modules(module): <ide> return ''.join(modules_string) <ide> <ide> <add>def fix_function_calls(red): <add> """ <add> Modifies function calls in the source to reflect import changes. <add> <add> Searches the AST for AtomtrailerNodes and replaces them. <add> """ <add> atoms = red.find_all("Atomtrailers") <add> for x, node in enumerate(atoms): <add> try: <add> if (node.value[0].value == 'flask' and <add> node.value[1].value == 'ext'): <add> node.replace("flask_foo%s" % node.value[3]) <add> except IndexError: <add> pass <add> <add> return red <add> <add> <ide> def check_user_input(): <ide> """Exits and gives error message if no argument is passed in the shell.""" <ide> if len(sys.argv) < 2: <ide> sys.exit("No filename was included, please try again.") <ide> <ide> <del>def fix(ast): <add>def fix_tester(ast): <ide> """Wrapper which allows for testing when not running from shell.""" <del> return fix_imports(ast).dumps() <add> ast = fix_imports(ast) <add> ast = fix_function_calls(ast) <add> return ast.dumps() <ide> <ide> <del>if __name__ == "__main__": <add>def fix(): <add> """Wrapper for user argument checking and import fixing.""" <ide> check_user_input() <ide> input_file = sys.argv[1] <ide> ast = read_source(input_file) <ide> ast = fix_imports(ast) <add> ast = fix_function_calls(ast) <ide> write_source(ast, input_file) <add> <add> <add>if __name__ == "__main__": <add> fix() <ide><path>scripts/test_import_migration.py <ide> <ide> def test_simple_from_import(): <ide> red = RedBaron("from flask.ext import foo") <del> output = migrate.fix(red) <add> output = migrate.fix_tester(red) <ide> assert output == "import flask_foo as foo" <ide> <ide> <ide> def test_from_to_from_import(): <ide> red = RedBaron("from flask.ext.foo import bar") <del> output = migrate.fix(red) <add> output = migrate.fix_tester(red) <ide> assert output == "from flask_foo import bar as bar" <ide> <ide> <ide> def test_multiple_import(): <ide> red = RedBaron("from flask.ext.foo import bar, foobar, something") <del> output = migrate.fix(red) <add> output = migrate.fix_tester(red) <ide> assert output == "from flask_foo import bar, foobar, something" <ide> <ide> <ide> def test_multiline_import(): <ide> bar,\ <ide> foobar,\ <ide> something") <del> output = migrate.fix(red) <add> output = migrate.fix_tester(red) <ide> assert output == "from flask_foo import bar, foobar, something" <ide> <ide> <ide> def test_module_import(): <ide> red = RedBaron("import flask.ext.foo") <del> output = migrate.fix(red) <del> assert output == "import flask_foo" <add> output = migrate.fix_tester(red) <add> assert output == "import flask_foo as foo" <ide> <ide> <del>def test_module_import(): <add>def test_named_module_import(): <add> red = RedBaron("import flask.ext.foo as foobar") <add> output = migrate.fix_tester(red) <add> assert output == "import flask_foo as foobar" <add> <add> <add>def test__named_from_import(): <ide> red = RedBaron("from flask.ext.foo import bar as baz") <del> output = migrate.fix(red) <add> output = migrate.fix_tester(red) <ide> assert output == "from flask_foo import bar as baz" <ide> <ide> <ide> def test_parens_import(): <ide> red = RedBaron("from flask.ext.foo import (bar, foo, foobar)") <del> output = migrate.fix(red) <add> output = migrate.fix_tester(red) <ide> assert output == "from flask_foo import (bar, foo, foobar)" <add> <add> <add>def test_function_call_migration(): <add> red = RedBaron("flask.ext.foo(var)") <add> output = migrate.fix_tester(red) <add> assert output == "flask_foo(var)"
2
Javascript
Javascript
improve setservers() errors and performance
872c331a930df3e44e8f5db5a90a0383e8d0491b
<ide><path>lib/dns.js <ide> function setServers(servers) { <ide> // servers cares won't have any servers available for resolution <ide> const orig = this._handle.getServers(); <ide> const newSet = []; <del> const IPv6RE = /\[(.*)\]/; <add> const IPv6RE = /^\[([^[\]]*)\]/; <ide> const addrSplitRE = /(^.+?)(?::(\d+))?$/; <ide> <ide> servers.forEach((serv) => { <ide> function setServers(servers) { <ide> } <ide> } <ide> <del> const [, s, p] = serv.match(addrSplitRE); <del> ipVersion = isIP(s); <add> // addr::port <add> const addrSplitMatch = serv.match(addrSplitRE); <add> if (addrSplitMatch) { <add> const hostIP = addrSplitMatch[1]; <add> const port = addrSplitMatch[2] || IANA_DNS_PORT; <ide> <del> if (ipVersion !== 0) { <del> return newSet.push([ipVersion, s, parseInt(p)]); <add> ipVersion = isIP(hostIP); <add> if (ipVersion !== 0) { <add> return newSet.push([ipVersion, hostIP, parseInt(port)]); <add> } <ide> } <ide> <ide> throw new ERR_INVALID_IP_ADDRESS(serv); <ide><path>test/parallel/test-dns.js <ide> assert(existing.length > 0); <ide> ]); <ide> } <ide> <add>{ <add> // Various invalidities, all of which should throw a clean error. <add> const invalidServers = [ <add> ' ', <add> '\n', <add> '\0', <add> '1'.repeat(3 * 4), <add> // Check for REDOS issues. <add> ':'.repeat(100000), <add> '['.repeat(100000), <add> '['.repeat(100000) + ']'.repeat(100000) + 'a' <add> ]; <add> invalidServers.forEach((serv) => { <add> assert.throws( <add> () => { <add> dns.setServers([serv]); <add> }, <add> { <add> name: 'TypeError [ERR_INVALID_IP_ADDRESS]', <add> code: 'ERR_INVALID_IP_ADDRESS' <add> } <add> ); <add> }); <add>} <add> <ide> const goog = [ <ide> '8.8.8.8', <ide> '8.8.4.4',
2
PHP
PHP
fix another test
96f9f4280b3b5cc86677066a1f800a2ed58e48bc
<ide><path>tests/TestCase/TestSuite/Fixture/SchemaGeneratorTest.php <ide> */ <ide> class SchemaGeneratorTest extends TestCase <ide> { <add> /** <add> * @var bool|null <add> */ <add> protected $restore; <add> <add> public function setUp(): void <add> { <add> parent::setUp(); <add> $this->restore = $GLOBALS['__PHPUNIT_BOOTSTRAP']; <add> unset($GLOBALS['__PHPUNIT_BOOTSTRAP']); <add> } <add> <add> public function tearDown(): void <add> { <add> parent::tearDown(); <add> $GLOBALS['__PHPUNIT_BOOTSTRAP'] = $this->restore; <add> } <add> <ide> /** <ide> * test reload on a table subset. <ide> */
1
Go
Go
maintain container exec-inspect invariant
a09f8dbe6eabd5bf1e9740bc09a721bfaeaa2583
<ide><path>daemon/exec.go <ide> func (daemon *Daemon) ContainerExecStart(ctx context.Context, name string, optio <ide> defer func() { <ide> if err != nil { <ide> ec.Lock() <add> ec.Container.ExecCommands.Delete(ec.ID) <ide> ec.Running = false <ide> exitCode := 126 <ide> ec.ExitCode = &exitCode <ide> if err := ec.CloseStreams(); err != nil { <ide> logrus.Errorf("failed to cleanup exec %s streams: %s", ec.Container.ID, err) <ide> } <ide> ec.Unlock() <del> ec.Container.ExecCommands.Delete(ec.ID) <ide> } <ide> }() <ide> <ide> func (daemon *Daemon) ContainerExecStart(ctx context.Context, name string, optio <ide> // close the chan to notify readiness <ide> close(ec.Started) <ide> if err != nil { <del> ec.Unlock() <add> defer ec.Unlock() <ide> return translateContainerdStartErr(ec.Entrypoint, ec.SetExitCode, err) <ide> } <ide> ec.Unlock() <ide><path>daemon/health.go <ide> func (p *cmdProbe) run(ctx context.Context, d *Daemon, cntr *container.Container <ide> if err != nil { <ide> return nil, err <ide> } <del> if info.ExitCode == nil { <del> return nil, fmt.Errorf("healthcheck for container %s has no exit code", cntr.ID) <add> exitCode, err := func() (int, error) { <add> info.Lock() <add> defer info.Unlock() <add> if info.ExitCode == nil { <add> info.Unlock() <add> return 0, fmt.Errorf("healthcheck for container %s has no exit code", cntr.ID) <add> } <add> return *info.ExitCode, nil <add> }() <add> if err != nil { <add> return nil, err <ide> } <ide> // Note: Go's json package will handle invalid UTF-8 for us <ide> out := output.String() <ide> return &types.HealthcheckResult{ <ide> End: time.Now(), <del> ExitCode: *info.ExitCode, <add> ExitCode: exitCode, <ide> Output: out, <ide> }, nil <ide> } <ide><path>daemon/inspect.go <ide> func (daemon *Daemon) ContainerExecInspect(id string) (*backend.ExecInspect, err <ide> return nil, errExecNotFound(id) <ide> } <ide> <add> e.Lock() <add> defer e.Unlock() <ide> pc := inspectExecProcessConfig(e) <ide> var pid int <ide> if e.Process != nil { <ide><path>daemon/monitor.go <ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei <ide> ec := int(ei.ExitCode) <ide> execConfig.Lock() <ide> defer execConfig.Unlock() <add> <add> // Remove the exec command from the container's store only and not the <add> // daemon's store so that the exec command can be inspected. Remove it <add> // before mutating execConfig to maintain the invariant that <add> // c.ExecCommands only contain execs in the Running state. <add> c.ExecCommands.Delete(execConfig.ID) <add> <ide> execConfig.ExitCode = &ec <ide> execConfig.Running = false <ide> <ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei <ide> logrus.Errorf("failed to cleanup exec %s streams: %s", c.ID, err) <ide> } <ide> <del> // remove the exec command from the container's store only and not the <del> // daemon's store so that the exec command can be inspected. <del> c.ExecCommands.Delete(execConfig.ID) <del> <ide> exitCode = ec <ide> <ide> go func() {
4
Ruby
Ruby
remove unneccesary map chaining
3fe32c355453f517acfda48a87edf2d6928a381a
<ide><path>activesupport/lib/active_support/ordered_hash.rb <ide> require 'yaml' <ide> <ide> YAML.add_builtin_type("omap") do |type, val| <del> ActiveSupport::OrderedHash[val.map(&:to_a).map(&:first)] <add> ActiveSupport::OrderedHash[val.map{ |v| v.to_a.first }] <ide> end <ide> <ide> module ActiveSupport
1
Text
Text
add missing emitchange() to flux docs
6b1c546602dcb436942c2bb69e4ff6a32f530e84
<ide><path>docs/docs/flux-todo-list.md <ide> var TodoStore = merge(EventEmitter.prototype, { <ide> <ide> case TodoConstants.TODO_DESTROY: <ide> destroy(action.id); <add> TodoStore.emitChange(); <ide> break; <ide> <del> // add more cases for other actionTypes, like TODO_UPDATE, etc. <add> // add more cases for other actionTypes, like TODO_UPDATE, etc. <ide> } <ide> <ide> return true; // No errors. Needed by promise in Dispatcher.
1
Text
Text
add language tags to code blocks
b6b702c50b236fee662c30c9e79c570861270d2d
<ide><path>threejs/lessons/threejs-cameras.md <ide> To do that we'll make a `MinMaxGUIHelper` for the `near` and `far` settings so ` <ide> is always greater than `near`. It will have `min` and `max` properties that dat.GUI <ide> will adjust. When adjusted they'll set the 2 properties we specify. <ide> <del>```javascript <add>```js <ide> class MinMaxGUIHelper { <ide> constructor(obj, minProp, maxProp, minDif) { <ide> this.obj = obj; <ide> class MinMaxGUIHelper { <ide> <ide> Now we can setup our GUI like this <ide> <del>```javascript <add>```js <ide> function updateCamera() { <ide> camera.updateProjectionMatrix(); <ide> } <ide> the canvas <ide> <ide> Then in our code we'll add a `CameraHelper`. A `CameraHelper` draws the frustum for a `Camera` <ide> <del>```javascript <add>```js <ide> const cameraHelper = new THREE.CameraHelper(camera); <ide> <ide> ... <ide> scene.add(cameraHelper); <ide> <ide> Now let's look up the 2 view elements. <ide> <del>```javascript <add>```js <ide> const view1Elem = document.querySelector('#view1'); <ide> const view2Elem = document.querySelector('#view2'); <ide> ``` <ide> <ide> And we'll set our existing `OrbitControls` to respond to the first <ide> view element only. <ide> <del>```javascript <add>```js <ide> -const controls = new THREE.OrbitControls(camera, canvas); <ide> +const controls = new THREE.OrbitControls(camera, view1Elem); <ide> ``` <ide> Let's make a second `PerspectiveCamera` and a second `OrbitControls`. <ide> The second `OrbitControls` is tied to the second camera and gets input <ide> from the second view element. <ide> <del>``` <add>```js <ide> const camera2 = new THREE.PerspectiveCamera( <ide> 60, // fov <ide> 2, // aspect <ide> Here is a function that given an element will compute the rectangle <ide> of that element that overlaps the canvas. It will then set the scissor <ide> and viewport to that rectangle and return the aspect for that size. <ide> <del>```javascript <add>```js <ide> function setScissorForElement(elem) { <ide> const canvasRect = canvas.getBoundingClientRect(); <ide> const elemRect = elem.getBoundingClientRect(); <ide> function setScissorForElement(elem) { <ide> <ide> And now we can use that function to draw the scene twice in our `render` function <ide> <del>```javascript <add>```js <ide> function render() { <ide> <ide> - if (resizeRendererToDisplaySize(renderer)) { <ide> second view to dark blue just to make it easier to distinguish the two views. <ide> We can also remove our `updateCamera` code since we're updating everything <ide> in the `render` function. <ide> <del>```javascript <add>```js <ide> -function updateCamera() { <ide> - camera.updateProjectionMatrix(); <ide> -} <ide> and slowly expand as they approach `far`. <ide> Starting with the top example, let's change the code to insert 20 spheres in a <ide> row. <ide> <del>```javascript <add>```js <ide> { <ide> const sphereRadius = 3; <ide> const sphereWidthDivisions = 32; <ide> row. <ide> <ide> and let's set `near` to 0.00001 <ide> <del>```javascript <add>```js <ide> const fov = 45; <ide> const aspect = 2; // the canvas default <ide> -const near = 0.1; <ide> const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); <ide> <ide> We also need to tweak the GUI code a little to allow 0.00001 if the value is edited <ide> <del>```javascript <add>```js <ide> -gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera); <ide> +gui.add(minMaxGUIHelper, 'min', 0.00001, 50, 0.00001).name('near').onChange(updateCamera); <ide> ``` <ide> One solution is to tell three.js use to a different method to compute which <ide> pixels are in front and which are behind. We can do that by enabling <ide> `logarithmicDepthBuffer` when we create the `WebGLRenderer` <ide> <del>```javascript <add>```js <ide> -const renderer = new THREE.WebGLRenderer({canvas: canvas}); <ide> +const renderer = new THREE.WebGLRenderer({ <ide> + canvas: canvas, <ide> in the first view. <ide> <ide> First let's setup an `OrthographicCamera`. <ide> <del>```javascript <add>```js <ide> const left = -1; <ide> const right = 1; <ide> const top = 1; <ide> to make it easy to adjust how many units are actually shown by the camera. <ide> <ide> Let's add a GUI setting for `zoom` <ide> <del>```javascript <add>```js <ide> const gui = new dat.GUI(); <ide> +gui.add(camera, 'zoom', 0.01, 1, 0.01).listen(); <ide> ``` <ide> a mouse will zoom via the `OrbitControls`. <ide> Last we just need to change the part that renders the left <ide> side to update the `OrthographicCamera`. <ide> <del>```javascript <add>```js <ide> { <ide> const aspect = setScissorForElement(view1Elem); <ide> <ide> one unit in the camera you could do something like <ide> To put the origin at the center and have 1 pixel = 1 three.js unit <ide> something like <ide> <del>```javascript <add>```js <ide> camera.left = -canvas.width / 2; <ide> camera.right = canvas.width / 2; <ide> camera.top = canvas.heigth / 2; <ide> camera.zoom = 1; <ide> Or if we wanted the origin to be in the top left just like a <ide> 2D canvas we could use this <ide> <del>```javascript <add>```js <ide> camera.left = 0; <ide> camera.right = canvas.width; <ide> camera.top = 0; <ide> In which case the top left corner would be 0,0 just like a 2D canvas <ide> <ide> Let's try it! First let's set the camera up <ide> <del>```javascript <add>```js <ide> const left = 0; <ide> const right = 300; // default canvas size <ide> const top = 0; <ide> Then let's load 6 textures and make 6 planes, one for each texture. <ide> We'll parent each plane to a `THREE.Object3D` to make it easy to offset <ide> the plane so it's center appears to be at it's top left corner. <ide> <del>```javascript <add>```js <ide> const loader = new THREE.TextureLoader(); <ide> const textures = [ <ide> loader.load('resources/images/flower-1.jpg'), <ide> const planes = textures.map((texture) => { <ide> and we need to update the camera if the size of the canvas <ide> changes. <ide> <del>```javascript <add>```js <ide> function render() { <ide> <ide> if (resizeRendererToDisplaySize(renderer)) { <ide> function render() { <ide> `planes` is an array of `THREE.Mesh`, one for each plane. <ide> Let's move them around based on the time. <ide> <del>```javascript <add>```js <ide> function render(time) { <ide> time *= 0.001; // convert to seconds; <ide> <ide><path>threejs/lessons/threejs-debugging-javascript.md <ide> Then pick "Disable Cache (while DevTools is open)". <ide> Inside all devtools is a *console*. It shows warnings and error messages. <ide> You can print your own info to the console with with `console.log` as in <ide> <del>``` <add>```js <ide> console.log(someObject.position.x, someObject.position.y, someObject.position.z); <ide> ``` <ide> <ide> Even cooler, if you log an object you can inspect it. For example if we log <ide> the root scene object from [the gLTF article](threejs-load-gltf.html) <ide> <del>``` <add>```js <ide> { <ide> const gltfLoader = new THREE.GLTFLoader(); <ide> gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => { <ide> and put data in them. <ide> <ide> The most obvious way is to make some HTML elements <ide> <del>``` <add>```html <ide> <canvas id="c"></canvas> <ide> +<div id="debug"> <ide> + <div>x:<span id="x"></span></div> <ide> The most obvious way is to make some HTML elements <ide> Style them so they stay on top of the canvas. (assuming your canvas <ide> fills the page) <ide> <del>``` <add>```html <ide> <style> <ide> #debug { <ide> position: absolute; <ide> fills the page) <ide> <ide> And then looking the elements up and setting their content. <ide> <del>``` <add>```js <ide> // at init time <ide> const xElem = document.querySelector('#x'); <ide> const yElem = document.querySelector('#y'); <ide> than making an element per piece of data above. <ide> <ide> For example let's change the HTML from above to just this <ide> <del>``` <add>```html <ide> <canvas id="c"></canvas> <ide> <div id="debug"> <ide> <pre></pre> <ide> For example let's change the HTML from above to just this <ide> <ide> And let's make simple class to manage this *clear back buffer*. <ide> <del>``` <add>```js <ide> class ClearingLogger { <ide> constructor(elem) { <ide> this.elem = elem; <ide> one of the examples from the article on [making things responsive](threejs-respo <ide> <ide> Here's the code that adds a new `Mesh` everytime we click the mouse <ide> <del>``` <add>```js <ide> const geometry = new THREE.SphereBufferGeometry(); <ide> const material = new THREE.MeshBasicMaterial({color: 'red'}); <ide> <ide> canvas.addEventListener('click', createThing); <ide> And here's the code that moves the meshes we created, logs them, <ide> and removes them when their timer has run out <ide> <del>``` <add>```js <ide> const logger = new ClearingLogger(document.querySelector('#debug pre')); <ide> <ide> let then = 0; <ide> the debug stuff only shows up if we put `?debug=true` in the URL. <ide> <ide> First we need some code to parse the query string <ide> <del>``` <add>```js <ide> /** <ide> * Returns the query parameters as a key/value object. <ide> * Example: If the query parameters are <ide> function getQuery() { <ide> <ide> Then we might make the debug element not show by default <ide> <del>``` <add>```html <ide> <canvas id="c"></canvas> <ide> +<div id="debug" style="display: none;"> <ide> <pre></pre> <ide> Then we might make the debug element not show by default <ide> Then in the code we read the params and choose to unhide the <ide> debug info if and only if `?debug=true` is passed in <ide> <del>``` <add>```js <ide> const query = getQuery(); <ide> const debug = query.debug === 'true'; <ide> const logger = debug <ide> if (debug) { <ide> <ide> We also made a `DummyLogger` that does nothing and chose to use it if `?debug=true` has not been passed in. <ide> <del>``` <add>```js <ide> class DummyLogger { <ide> log() {} <ide> render() {} <ide> As an example when I first started making the path for the [article about loadin <ide> <ide> I then used that curve to move the cars like this <ide> <del>``` <add>```js <ide> curve.getPointAt(zeroToOnePointOnCurve, car.position); <ide> ``` <ide> <ide> THREE.js to step through the code and see what is going on. <ide> <ide> I see this pattern often <ide> <del>``` <add>```js <ide> function render() { <ide> requestAnimationFrame(render); <ide> <ide> requestAnimationFrame(render); <ide> I'd suggest that putting the call to `requestAnimationFrame` at <ide> the bottom as in <ide> <del>``` <add>```js <ide> function render() { <ide> // -- do stuff -- <ide> <ide><path>threejs/lessons/threejs-fog.md <ide> There's also `FogExp2` which grows expotentially with distance from the camera. <ide> <ide> To use either type of fog you create one and and assign it to the scene as in <ide> <del>``` <add>```js <ide> const scene = new THREE.Scene(); <ide> { <ide> const color = 0xFFFFFF; // white <ide> const scene = new THREE.Scene(); <ide> <ide> or for `FogExp2` it would be <ide> <del>``` <add>```js <ide> const scene = new THREE.Scene(); <ide> { <ide> const color = 0xFFFFFF; <ide> The background color is set using the <ide> [`scene.background`](Scene.background) <ide> property. To pick a background color you attach a `THREE.Color` to it. For example <ide> <del>``` <add>```js <ide> scene.background = new THREE.Color('#F00'); // red <ide> ``` <ide> <ide> Here is one of our previous examples with fog added. The only addition <ide> is right after setting up the scene we add the fog and set the scene's <ide> backgound color <ide> <del>``` <add>```js <ide> const scene = new THREE.Scene(); <ide> <ide> +{ <ide> the fog's `near` and `far` properties but it's invalid to have <ide> can manipulate a `near` and `far` property but we'll make sure `near` <ide> is less than or equal to `far` and `far` is greater than or equal `near`. <ide> <del>``` <add>```js <ide> // We use this class to pass to dat.gui <ide> // so when it manipulates near or far <ide> // near is never > far and far is never < near <ide> class FogGUIHelper { <ide> <ide> We can then add it like this <ide> <del>``` <add>```js <ide> { <ide> const near = 1; <ide> const far = 2; <ide> dat.GUI is only manipulating a single value. Fortunately `THREE.Color` <ide> as a [`getHexString`](Color.getHexString) method <ide> we get use to easily get such a string, we just have to prepend a '#' to the front. <ide> <del>``` <add>```js <ide> // We use this class to pass to dat.gui <ide> // so when it manipulates near or far <ide> // near is never > far and far is never < near <ide> class FogGUIHelper { <ide> <ide> We then call `gui.addColor` to add a color UI for our helper's virutal property. <ide> <del>``` <add>```js <ide> { <ide> const near = 1; <ide> const far = 2; <ide><path>threejs/lessons/threejs-fundamentals.md <ide> so let's start with "Hello Cube!" <ide> <ide> The first thing we need is a `<canvas>` tag so <ide> <del>``` <add>```html <ide> <body> <ide> <canvas id="c"></canvas> <ide> </body> <ide> The first thing we need is a `<canvas>` tag so <ide> Three.js will draw into that canvas so we need to look it up <ide> and pass it to three.js. <ide> <del>``` <add>```html <ide> <script> <ide> 'use strict'; <ide> <ide> that uses WebGL to render 3D to the canvas. <ide> <ide> Next up we need a camera. <ide> <del>``` <add>```js <ide> const fov = 75; <ide> const aspect = 2; // the canvas default <ide> const near = 0.1; <ide> The camera defaults to looking down the -Z axis with +Y up. We'll put our cube <ide> at the origin so we need to move the camera back a litte from the origin <ide> in order to see anything. <ide> <del>``` <add>```js <ide> camera.position.z = 2; <ide> ``` <ide> <ide> Next we make a `Scene`. A `Scene` in three.js is the root of a form of scene gra <ide> Anything you want three.js to draw needs to be added to the scene. We'll <ide> cover more details of [how scenes work in a future article](threejs-scenegraph.html). <ide> <del>``` <add>```js <ide> const scene = new THREE.Scene(); <ide> ``` <ide> <ide> Next up we create a `BoxGeometry` which contains the data for a box. <ide> Almost anything we want to display in Three.js needs geometry which defines <ide> the vertices that make up our 3D object. <ide> <del>``` <add>```js <ide> const boxWidth = 1; <ide> const boxHeight = 1; <ide> const boxDepth = 1; <ide> const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth); <ide> We then create a basic material and set its color. Colors can <ide> be specified using standard CSS style 6 digit hex color values. <ide> <del>``` <add>```js <ide> const material = new THREE.MeshBasicMaterial({color: 0x44aa88}); <ide> ``` <ide> <ide> the object, shiny or flat, what color, what texture(s) to apply. Etc.) <ide> as well as the position, orientation, and scale of that <ide> object in the scene. <ide> <del>``` <add>```js <ide> const cube = new THREE.Mesh(geometry, material); <ide> ``` <ide> <ide> And finally we add that mesh to the scene <ide> <del>``` <add>```js <ide> scene.add(cube); <ide> ``` <ide> <ide> We can then render the scene by calling the renderer's render function <ide> and passing it the scene and the camera <ide> <del>``` <add>```js <ide> renderer.render(scene, camera); <ide> ``` <ide> <ide> it clear it's being drawn in 3D. To animate it we'll render inside a render loop <ide> <ide> Here's our loop <ide> <del>``` <add>```js <ide> function render(time) { <ide> time *= 0.001; // convert time to seconds <ide> <ide> so let's add a light. There are many kinds of lights in three.js which <ide> we'll go over in a future article. For now let's create a directional <ide> light. <ide> <del>``` <add>```js <ide> { <ide> const color = 0xFFFFFF; <ide> const intensity = 1; <ide> toward the origin. <ide> We also need to change the material. The `MeshBasicMaterial` is not affected by <ide> lights. Let's change it to a `MeshPhongMaterial` which is affected by lights. <ide> <del>``` <add>```js <ide> -const material = new THREE.MeshBasicMaterial({color: 0x44aa88}); // greenish blue <ide> +const material = new THREE.MeshPhongMaterial({color: 0x44aa88}); // greenish blue <ide> ``` <ide> with the specified color. Then it creates a mesh using <ide> the specified geometry and adds it to the scene and <ide> sets its X position. <ide> <del>``` <add>```js <ide> function makeInstance(geometry, color, x) { <ide> const material = new THREE.MeshPhongMaterial({color}); <ide> <ide> function makeInstance(geometry, color, x) { <ide> Then we'll call it 3 times with 3 different colors and X positions <ide> saving the `Mesh` instances in an array. <ide> <del>``` <add>```js <ide> const cubes = [ <ide> makeInstance(geometry, 0x44aa88, 0), <ide> makeInstance(geometry, 0x8844aa, -2), <ide> const cubes = [ <ide> Finally we'll spin all 3 cubes in our render function. We <ide> compute a slightly different rotation for each one. <ide> <del>``` <add>```js <ide> function render(time) { <ide> time *= 0.001; // convert time to seconds <ide> <ide><path>threejs/lessons/threejs-lights.md <ide> Starting with one of our previous samples let's update the camera. <ide> We'll set the field of view to 45 degrees, the far plane to 100 units, <ide> and we'll move the camera 10 units up and 20 units back from the origin <ide> <del>```javascript <add>```js <ide> *const fov = 45; <ide> const aspect = 2; // the canvas default <ide> const near = 0.1; <ide> or *orbit* the camera around some point. The `OrbitControls` are <ide> an optional feature of three.js so first we need to include them <ide> in our page <ide> <del>```javascript <add>```html <ide> <script src="resources/threejs/r98/three.min.js"></script> <ide> +<script src="resources/threejs/r98/js/controls/OrbitControls.js"></script> <ide> ``` <ide> <ide> Then we can use them. We pass the `OrbitControls` a camera to <ide> control and the DOM element to use to get input events <ide> <del>```javascript <add>```js <ide> const controls = new THREE.OrbitControls(camera, canvas); <ide> controls.target.set(0, 5, 0); <ide> controls.update(); <ide> texture is a 2x2 pixel checkerboard, by repeating and setting the <ide> repeat to half the size of the plane each check on the checkerboard <ide> will be exactly 1 unit large; <ide> <del>```javascript <add>```js <ide> const planeSize = 40; <ide> <ide> const loader = new THREE.TextureLoader(); <ide> We then make a plane geometry, a material for the plane, and mesh <ide> to insert it in the scene. Planes default to being in the XY plane <ide> but the ground is in the XZ plane so we rotate it. <ide> <del>```javascript <add>```js <ide> const planeGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize); <ide> const planeMat = new THREE.MeshPhongMaterial({ <ide> map: texture, <ide> scene.add(mesh); <ide> <ide> Let's add a cube and a sphere so we have 3 things to light including the plane <ide> <del>```javascript <add>```js <ide> { <ide> const cubeSize = 4; <ide> const cubeGeo = new THREE.BoxBufferGeometry(cubeSize, cubeSize, cubeSize); <ide> Now that we have a scene to light up let's add lights! <ide> <ide> First let's make an `AmbientLight` <ide> <del>```javascript <add>```js <ide> const color = 0xFFFFFF; <ide> const intensity = 1; <ide> const light = new THREE.AmbientLight(color, intensity); <ide> color. <ide> <ide> Here's the helper: <ide> <del>```javascript <add>```js <ide> class ColorGUIHelper { <ide> constructor(object, prop) { <ide> this.object = object; <ide> class ColorGUIHelper { <ide> <ide> And here's our code setting up dat.GUI <ide> <del>```javascript <add>```js <ide> const gui = new dat.GUI(); <ide> gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); <ide> gui.add(light, 'intensity', 0, 2, 0.01); <ide> the surface of the object is pointing down. <ide> <ide> Here's the new code <ide> <del>```javascript <add>```js <ide> -const color = 0xFFFFFF; <ide> +const skyColor = 0xB1E1FF; // light blue <ide> +const groundColor = 0xB97A20; // brownish orange <ide> scene.add(light); <ide> <ide> Let's also update the dat.GUI code to edit both colors <ide> <del>```javascript <add>```js <ide> const gui = new dat.GUI(); <ide> -gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); <ide> +gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('skyColor'); <ide> other light or a substitute for an `AmbientLight`. <ide> Let's switch the code to a `DirectionalLight`. <ide> A `DirectionalLight` is often used to represent the sun. <ide> <del>```javascript <add>```js <ide> const color = 0xFFFFFF; <ide> const intensity = 1; <ide> const light = new THREE.DirectionalLight(color, intensity); <ide> in the direction of its target. <ide> Let's make it so we can move the target by adding it to <ide> our GUI. <ide> <del>```javascript <add>```js <ide> const gui = new dat.GUI(); <ide> gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); <ide> gui.add(light, 'intensity', 0, 2, 0.01); <ide> invisible parts of a scene. In this case we'll use the <ide> the light, and a line from the light to the target. We just <ide> pass it the light and add itd add it to the scene. <ide> <del>```javascript <add>```js <ide> const helper = new THREE.DirectionalLightHelper(light); <ide> scene.add(helper); <ide> ``` <ide> of the light and the target. To do this we'll make a function <ide> that given a `Vector3` will adjust its `x`, `y`, and `z` properties <ide> using `dat.GUI`. <ide> <del>```javascript <add>```js <ide> function makeXYZGUI(gui, vector3, name, onChangeFn) { <ide> const folder = gui.addFolder(name); <ide> folder.add(vector3, 'x', -10, 10).onChange(onChangeFn); <ide> get called anytime dat.GUI updates a value. <ide> Then we can use that for both the light's position <ide> and the target's position like this <ide> <del>```javascript <add>```js <ide> +function updateLight{ <ide> + light.target.updateMatrixWorld(); <ide> + helper.update(); <ide> shooting out parallel rays of light. <ide> A `PointLight` is a light that sits at a point and shoots light <ide> in all directions from that point. Let's change the code. <ide> <del>```javascript <add>```js <ide> const color = 0xFFFFFF; <ide> const intensity = 1; <ide> -const light = new THREE.DirectionalLight(color, intensity); <ide> scene.add(light); <ide> <ide> Let's also switch to a `PointLightHelper` <ide> <del>```javascript <add>```js <ide> -const helper = new THREE.DirectionalLightHelper(light); <ide> +const helper = new THREE.PointLightHelper(light); <ide> scene.add(helper); <ide> ``` <ide> <ide> and as there is no target the `onChange` function can be simpler. <ide> <del>```javascript <add>```js <ide> function updateLight{ <ide> - light.target.updateMatrixWorld(); <ide> helper.update(); <ide> units away from the light. <ide> <ide> Let's setup the GUI so we can adjust the distance. <ide> <del>```javascript <add>```js <ide> const gui = new dat.GUI(); <ide> gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); <ide> gui.add(light, 'intensity', 0, 2, 0.01); <ide> open toward the target. <ide> <ide> Modifying our `DirectionalLight` with helper from above <ide> <del>```javascript <add>```js <ide> const color = 0xFFFFFF; <ide> const intensity = 1; <ide> -const light = new THREE.DirectionalLight(color, intensity); <ide> property in radians. We'll use our `DegRadHelper` from the <ide> [texture artcle](threejs-textures.html) to present a UI in <ide> degrees. <ide> <del>```javascript <add>```js <ide> gui.add(new DegRadHelper(light, 'angle'), 'value', 0, 90).name('angle').onChange(updateLight); <ide> ``` <ide> <ide> inner code is the same size (0 = no difference) from the outer cone. When the <ide> outer cone. When `penumbra` is .5 then the light fades starting from 50% between <ide> the center of the outer cone. <ide> <del>```javascript <add>```js <ide> gui.add(light, 'penumbra', 0, 1, 0.01); <ide> ``` <ide> <ide> fluorescent light or maybe a frosted sky light in a ceiling. <ide> The `RectAreaLight` only works with the `MeshStandardMaterai` and the <ide> `MeshPhysicalMaterial` so let's change all our materials to `MeshStandardMaterial` <ide> <del>```javascript <add>```js <ide> ... <ide> <ide> const planeGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize); <ide> be sure to remember to include the extra data. <ide> <ide> Now we can create the light <ide> <del>```javascript <add>```js <ide> const color = 0xFFFFFF; <ide> *const intensity = 5; <ide> +const width = 12; <ide> One thing to notice is that unlike the `DirectionalLight` and the `SpotLight` th <ide> Let's also adjust the GUI. We'll make it so we can rotate the light and adjust <ide> its `width` and `height` <ide> <del>```javascript <add>```js <ide> const gui = new dat.GUI(); <ide> gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); <ide> gui.add(light, 'intensity', 0, 10, 0.01); <ide> Let's test that. <ide> <ide> First we'll turn on physically correct lights <ide> <del>```javascript <add>```js <ide> const renderer = new THREE.WebGLRenderer({canvas: canvas}); <ide> +renderer.physicallyCorrectLights = true; <ide> ``` <ide> <ide> Then we'll set the `power` to 800 lumens, the `decay` to 2, and <ide> the `distance` to `Infinity`. <ide> <del>```javascript <add>```js <ide> const color = 0xFFFFFF; <ide> const intensity = 1; <ide> const light = new THREE.PointLight(color, intensity); <ide> light.distance = Infinity; <ide> <ide> and we'll add gui so we can change the `power` and `decay` <ide> <del>```javascript <add>```js <ide> const gui = new dat.GUI(); <ide> gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); <ide> gui.add(light, 'decay', 0, 4, 0.01); <ide><path>threejs/lessons/threejs-load-gltf.md <ide> for loading .OBJ and replaced it with code for loading .GLTF <ide> <ide> The old .OBJ code was <ide> <del>``` <add>```js <ide> const objLoader = new THREE.OBJLoader2(); <ide> objLoader.loadMtl('resources/models/windmill/windmill-fixed.mtl', null, (materials) => { <ide> materials.Material.side = THREE.DoubleSide; <ide> objLoader.loadMtl('resources/models/windmill/windmill-fixed.mtl', null, (materia <ide> <ide> The new .GLTF code is <ide> <del>``` <add>```js <ide> { <ide> const gltfLoader = new THREE.GLTFLoader(); <ide> const url = 'resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf'; <ide> I kept the auto framing code as before <ide> <ide> We also need to include the `GLTFLoader` and we can get rid of the `OBJLoader2`. <ide> <del>``` <add>```html <ide> -<script src="resources/threejs/r98/js/loaders/LoaderSupport.js"></script> <ide> -<script src="resources/threejs/r98/js/loaders/OBJLoader2.js"></script> <ide> -<script src="resources/threejs/r98/js/loaders/MTLLoader.js"></script> <ide> console. <ide> <ide> Here's the code to print out the scenegraph. <ide> <del>``` <add>```js <ide> function dumpObject(obj, lines = [], isLast = true, prefix = '') { <ide> const localPrefix = isLast ? '└─' : '├─'; <ide> lines.push(`${prefix}${prefix ? localPrefix : ''}${obj.name || '*no-name*'} [${obj.type}]`); <ide> function dumpObject(obj, lines = [], isLast = true, prefix = '') { <ide> <ide> And I just called it right after loading the scene. <ide> <del>``` <add>```js <ide> const gltfLoader = new THREE.GLTFLoader(); <ide> gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => { <ide> const root = gltf.scene; <ide> gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.glt <ide> <ide> [Running that](.../threejs-load-gltf-dump-scenegraph.html) I got this listing <ide> <del>``` <add>```text <ide> OSG_Scene [Scene] <ide> └─RootNode_(gltf_orientation_matrix) [Object3D] <ide> └─RootNode_(model_correction_matrix) [Object3D] <ide> OSG_Scene [Scene] <ide> From that we can see all the cars happen to be under parent <ide> called `"Cars"` <ide> <del>``` <add>```text <ide> * ├─Cars [Object3D] <ide> │ ├─CAR_03_1 [Object3D] <ide> │ │ └─CAR_03_1_World_ap_0 [Mesh] <ide> all the children of the "Cars" node around their Y axis <ide> I looked up the "Cars" node after loading the scene <ide> and saved the result. <ide> <del>``` <add>```js <ide> +let cars; <ide> { <ide> const gltfLoader = new THREE.GLTFLoader(); <ide> and saved the result. <ide> Then in the `render` function we can just set the rotation <ide> of each child of `cars` <ide> <del>``` <add>```js <ide> +function render(time) { <ide> + time *= 0.001; // convert to seconds <ide> <ide> Each type of car will work with the same adjustments. <ide> I wrote this code to go through each car, parent it to a new `Object3D`, parent that new `Object3D` to the scene, and apply some per car *type* settings to fix its orientation, and add <ide> the new `Object3D` a `cars` array. <ide> <del>``` <add>```js <ide> -let cars; <ide> +const cars = []; <ide> { <ide> Fortunately I was able to select just my path and export .OBJ checking "write nu <ide> Opening the .OBJ file I was able to get a list of points <ide> which I formated into this <ide> <del>``` <add>```js <ide> const controlPoints = [ <ide> [1.118281, 5.115846, -3.681386], <ide> [3.948875, 5.115846, -3.641834], <ide> This will give us a curve like this <ide> <ide> Here's the code to make the curve <ide> <del>``` <add>```js <ide> let curve; <ide> let curveObject; <ide> { <ide> the lines made by connecting those 250 points. <ide> Running [the example](../threejs-load-gltf-car-path.html) I didn't see the curve. To make it <ide> visible made it ignore the depth test and render last <ide> <del>``` <add>```js <ide> curveObject = new THREE.Line(geometry, material); <ide> + material.depthTest = false; <ide> + curveObject.renderOrder = 1; <ide> is less of an issue. <ide> Going back to the function we wrote above to dump the scene graph, <ide> let's dump the position, rotation, and scale of each node. <ide> <del>``` <add>```js <ide> +function dumpVec3(v3, precision = 3) { <ide> + return `${v3.x.toFixed(precision)}, ${v3.y.toFixed(precision)}, ${v3.z.toFixed(precision)}`; <ide> +} <ide> function dumpObject(obj, lines, isLast = true, prefix = '') { <ide> <ide> And the result from [running it](.../threejs-load-gltf-dump-scenegraph-extra.html) <ide> <del>``` <add>```text <ide> OSG_Scene [Scene] <ide> │ pos: 0.000, 0.000, 0.000 <ide> │ rot: 0.000, 0.000, 0.000 <ide> all the major nodes and removed any transformations. <ide> <ide> All these nodes at the top <ide> <del>``` <add>```text <ide> OSG_Scene [Scene] <ide> │ pos: 0.000, 0.000, 0.000 <ide> │ rot: 0.000, 0.000, 0.000 <ide> Here's what I ended up with. <ide> First I adjusted the position of the curve and after I found values <ide> that seemd to work. I then hid it. <ide> <del>``` <add>```js <ide> { <ide> const points = curve.getPoints(250); <ide> const geometry = new THREE.BufferGeometry().setFromPoints(points); <ide> a position from 0 to 1 along the curve and compute a point in world space <ide> using the `curveObject` to transform the point. We then pick another point <ide> slightly further down the curve. We set the car's orientation using `lookAt` and put the car at the mid point between the 2 points. <ide> <del>``` <add>```js <ide> // create 2 Vector3s we can use for path calculations <ide> const carPosition = new THREE.Vector3(); <ide> const carTarget = new THREE.Vector3(); <ide> and when I ran it I found out for each type of car, their height above their ori <ide> are not consistently set and so I needed to offset each one <ide> a little. <ide> <del>``` <add>```js <ide> const loadedCars = root.getObjectByName('Cars'); <ide> const fixes = [ <ide> - { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI * .5], }, <ide> into our latest code. <ide> <ide> Then, after loading, we need to turn on shadows on all the objects. <ide> <del>``` <add>```js <ide> { <ide> const gltfLoader = new THREE.GLTFLoader(); <ide> gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => { <ide> Then, after loading, we need to turn on shadows on all the objects. <ide> I then spent nearly 4 hours trying to figure out why the shadow helpers <ide> were not working. It was because I forgot to enable shadows with <ide> <del>``` <add>```js <ide> renderer.shadowMap.enabled = true; <ide> ``` <ide> <ide> I then adjusted the values until our `DirectionLight`'s shadow camera <ide> had a frustum that covered the entire scene. These are the settings <ide> I ended up with. <ide> <del>``` <add>```js <ide> { <ide> const color = 0xFFFFFF; <ide> const intensity = 1; <ide> I ended up with. <ide> <ide> and I set the background color to light blue. <ide> <del>``` <add>```js <ide> const scene = new THREE.Scene(); <ide> -scene.background = new THREE.Color('black'); <ide> +scene.background = new THREE.Color('#DEFEFF'); <ide><path>threejs/lessons/threejs-load-obj.md <ide> that were being added to the scene. <ide> <ide> From that the first thing we need to do is include the `OBJLoader2` loader in our scene. The `OBJLoader2` also needs the `LoadingSupport.js` file so let's add both. <ide> <del>``` <add>```html <ide> <script src="resources/threejs/r98/js/loaders/LoadingSupport.js"></script> <ide> <script src="resources/threejs/r98/js/loaders/OBJLoader2.js"></script> <ide> ``` <ide> Then to load the .OBJ file we create an instance of `OBJLoader2`, <ide> pass it the URL of our .OBJ file, and pass in a callback that adds <ide> the loaded model to our scene. <ide> <del>``` <add>```js <ide> { <ide> const objLoader = new THREE.OBJLoader2(); <ide> objLoader.load('resources/models/windmill/windmill.obj', (event) => { <ide> Sometimes .OBJ files come with a .MTL file that defines <ide> materials. In our case the exporter also created a .MTL file. <ide> .MTL format is plain ASCII so it's easy to look at. Looking at it here <ide> <del>``` <add>```mtl <ide> # Blender MTL File: 'windmill_001.blend' <ide> # Material Count: 2 <ide> <ide> Now that we have the textures available we can load the .MTL file. <ide> <ide> First we need to include the `MTLLoader` <ide> <del>``` <add>```html <ide> <script src="resources/threejs/r98/three.min.js"></script> <ide> <script src="resources/threejs/r98/js/controls/OrbitControls.js"></script> <ide> <script src="resources/threejs/r98/js/loaders/LoaderSupport.js"></script> <ide> First we need to include the `MTLLoader` <ide> <ide> Then we first load the .MTL file. When it's finished loading we set the just loaded materials on to the `OBJLoader2` itself and then load the .OBJ file. <ide> <del>``` <add>```js <ide> { <ide> + const objLoader = new THREE.OBJLoader2(); <ide> + objLoader.loadMtl('resources/models/windmill/windmill.mtl', null, (materials) => { <ide> the surface. <ide> Looking at [the source for the MTLLoader](https://github.com/mrdoob/three.js/blob/1a560a3426e24bbfc9ca1f5fb0dfb4c727d59046/examples/js/loaders/MTLLoader.js#L432) <ide> it expects the keyword `norm` for normal maps so let's edit the .MTL file <ide> <del>``` <add>```mtl <ide> # Blender MTL File: 'windmill_001.blend' <ide> # Material Count: 2 <ide> <ide> Searching the net I found this [CC-BY-NC](https://creativecommons.org/licenses/b <ide> <ide> It had a .OBJ version already available. Let's load it up (note I removed the .MTL loader for now) <ide> <del>``` <add>```js <ide> - objLoader.load('resources/models/windmill/windmill.obj', ... <ide> + objLoader.load('resources/models/windmill-2/windmill.obj', ... <ide> ``` <ide> camera automatically. <ide> First off we can ask THREE.js to compute a box that contains the scene <ide> we just loaded and ask for its size and center <ide> <del>``` <add>```js <ide> objLoader.load('resources/models/windmill_2/windmill.obj', (event) => { <ide> const root = event.detail.loaderRootNode; <ide> scene.add(root); <ide> objLoader.load('resources/models/windmill_2/windmill.obj', (event) => { <ide> <ide> Looking in [the JavaScript console](threejs-debugging.html) I see <ide> <del>``` <add>```js <ide> size 2123.6499788469982 <ide> center p {x: -0.00006103515625, y: 770.0909731090069, z: -3.313507080078125} <ide> ``` <ide> given we know the field of view for the frustum and we know the size of the box <ide> <ide> Based on that diagram the formula for computing distance is <ide> <del>``` <add>```js <ide> distance = halfSizeToFitOnScreen / tangent(halfFovY) <ide> ``` <ide> <ide> Let's translate that to code. First let's make a function that will compute `distance` and then move the <ide> camera that `distance` units from the center of the box. We'll then point the <ide> camera at the `center` of the box. <ide> <del>``` <add>```js <ide> function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) { <ide> const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5; <ide> const halfFovY = THREE.Math.degToRad(camera.fov * .5); <ide> and used that as `sizeToFitOnScreen` then the math would make the box fit perfec <ide> the frustum. We want a little extra space above and below so we'll pass in a slightly <ide> larger size. <ide> <del>``` <add>```js <ide> { <ide> const objLoader = new THREE.OBJLoader2(); <ide> objLoader.load('resources/models/windmill_2/windmill.obj', (event) => { <ide> the camera is from the center. All we need to do to do that is zero out the `y` <ide> of the vector from the box to the camera. Then, when we normalize that vector it will <ide> become a vector parallel to the XZ plane. In otherwords parallel to the ground. <ide> <del>``` <add>```js <ide> -// compute a unit vector that points in the direction the camera is now <ide> -// from the center of the box <ide> -const direction = (new THREE.Vector3()).subVectors(camera.position, boxCenter).normalize(); <ide> Since the windmill is over 2000 units big let's change the size of the ground pl <ide> something more fitting. We also need to adjust the repeat otherwise our checkerboard <ide> will be so fine we won't even be able to see it unless we zoom way way in. <ide> <del>``` <add>```js <ide> -const planeSize = 40; <ide> +const planeSize = 4000; <ide> <ide> and now we can see this windmill <ide> Let's add the materials back. Like before there is a .MTL file that references <ide> some textures but looking at the files I quickly see an issue. <ide> <del>``` <add>```shell <ide> $ ls -l windmill <ide> -rw-r--r--@ 1 gregg staff 299 May 20 2009 windmill.mtl <ide> -rw-r--r--@ 1 gregg staff 142989 May 20 2009 windmill.obj <ide> Loading the files up they were each 2048x2048. That seemed like a waste to me bu <ide> course it depends on your use case. I made them each 1024x1024 and saved them at a <ide> 50% quality setting in Photoshop. Getting a file listing <ide> <del>``` <add>```shell <ide> $ ls -l ../threejsfundamentals.org/threejs/resources/models/windmill <ide> -rw-r--r--@ 1 gregg staff 299 May 20 2009 windmill.mtl <ide> -rw-r--r--@ 1 gregg staff 142989 May 20 2009 windmill.obj <ide> with this compression so be sure to consult with them to discuss the tradeoffs. <ide> Now, to use the .MTL file we need to edit it to reference the .JPG files <ide> instead of the .TGA files. Fortunately it's a simple text file so it's easy to edit <ide> <del>``` <add>```mtl <ide> newmtl blinn1SG <ide> Ka 0.10 0.10 0.10 <ide> <ide> illum 2 <ide> Now that the .MTL file points to some reasonable size textures we need to load it so we'll just do like we did above, first load the materials <ide> and then set them on the `OBJLoader2` <ide> <del>``` <add>```js <ide> { <ide> + const objLoader = new THREE.OBJLoader2(); <ide> + objLoader.loadMtl('resources/models/windmill_2/windmill-fixed.mtl', null, (materials) => { <ide> Issue #1: The three `MTLLoader` creates materials that multiply the material's d <ide> <ide> That's a useful feature but looking a the .MTL file above the line <ide> <del>``` <add>```mtl <ide> Kd 0.00 0.00 0.00 <ide> ``` <ide> <ide> did not multiply the diffuse texture map by the diffuse color. That's why it wor <ide> <ide> To fix this we can change the line to <ide> <del>``` <add>```mtl <ide> Kd 1.00 1.00 1.00 <ide> ``` <ide> <ide> needs a specular color set. <ide> <ide> Like above we can fix that by editing the .MTL file like this. <ide> <del>``` <add>```mtl <ide> -Ks 0.00 0.00 0.00 <ide> +Ks 1.00 1.00 1.00 <ide> ``` <ide> Issue #3: The `windmill_normal.jpg` is a normal map not a bump map. <ide> <ide> Just like above we just need to edit the .MTL file <ide> <del>``` <add>```mtl <ide> -map_bump windmill_normal.jpg <ide> -bump windmill_normal.jpg <ide> +norm windmill_normal.jpg <ide><path>threejs/lessons/threejs-materials.md <ide> accomplish. <ide> There are 2 ways to set most material properties. One at creation time which <ide> we've seen before. <ide> <del>``` <add>```js <ide> const material = new THREE.MeshPhongMaterial({ <ide> color: 0xFF0000, // red (can also use a CSS color string here) <ide> flatShading: true, <ide> const material = new THREE.MeshPhongMaterial({ <ide> <ide> The other is after creation <ide> <del>``` <add>```js <ide> const material = new THREE.MeshPhongMaterial(); <ide> material.color.setHSL(0, 1, .5); // red <ide> material.flatShading = true; <ide> ``` <ide> <ide> note that properties of type `THREE.Color` have multiple ways to be set. <ide> <del>``` <add>```js <ide> material.color.set(0x00FFFF); // same as CSS's #RRGGBB style <ide> material.color.set(cssString); // any CSS color, eg 'purple', '#F32', <ide> // 'rgb(255, 127, 64)', <ide> material.color.setRGB(r, g, b) // where r, g, and b are 0 to 1 <ide> <ide> And at creation time you can pass either a hex number or a CSS string <ide> <del>``` <add>```js <ide> const m1 = new THREE.MeshBasicMaterial({color: 0xFF0000}); // red <ide> const m2 = new THREE.MeshBasicMaterial({color: 'red'}); // red <ide> const m3 = new THREE.MeshBasicMaterial({color: '#F00'}); // red <ide><path>threejs/lessons/threejs-multiple-scenes.md <ide> issues for the same reasons. <ide> Let's start with a simple example with just 2 scenes. First we'll <ide> make the HTML <ide> <del>``` <add>```html <ide> <canvas id="c"></canvas> <ide> <p> <ide> <span id="box" class="diagram left"></span> <ide> make the HTML <ide> <ide> Then we can setup the CSS maybe something like this <ide> <del>``` <add>```css <ide> #c { <ide> position: fixed; <ide> left: 0; <ide> We set the canvsas to fill the screen and we set its `z-index` to <ide> Now we'll make 2 scenes each with a light and a camera. <ide> To one scene we'll add a cube and to another a diamond. <ide> <del>``` <add>```js <ide> function makeScene(elem) { <ide> const scene = new THREE.Scene(); <ide> <ide> only if the element is on the screen. We can tell THREE.js <ide> to only render to part of the canvas by turning on the *scissor* <ide> test with `Renderer.setScissorTest` and then setting both the scissor and the viewport with `Renderer.setViewport` and `Renderer.setScissor`. <ide> <del>``` <add>```js <ide> function rendenerSceneInfo(sceneInfo) { <ide> const {scene, camera, elem} = sceneInfo; <ide> <ide> function rendenerSceneInfo(sceneInfo) { <ide> And then our render function will just first clear the screen <ide> and then render each scene. <ide> <del>``` <add>```js <ide> function render(time) { <ide> time *= 0.001; <ide> <ide> drawn into the canvas will lag behind the rest of the page. <ide> <ide> If we give each area a border <ide> <del>``` <add>```css <ide> .diagram { <ide> display: inline-block; <ide> width: 5em; <ide> If we give each area a border <ide> <ide> And we set the background of each scene <ide> <del>``` <add>```js <ide> const scene = new THREE.Scene(); <ide> +scene.background = new THREE.Color('red'); <ide> ``` <ide> And if we <a href="../threejs-multiple-scenes-v2.html" target="_blank">quickly s <ide> <ide> We can switch to a different method which has a different tradeoff. We'll switch the canvas's CSS from `position: fixed` to `position: absolute`. <ide> <del>``` <add>```css <ide> #c { <ide> - position: fixed; <ide> + position: absolute; <ide> Then we'll set the canvas's transform to move it so <ide> the top of the canvas is at the top of whatever part <ide> the page is currently scrolled to. <ide> <del>``` <add>```js <ide> function render(time) { <ide> ... <ide> <ide> const transform = `translateY(${window.scrollY}px)`; <ide> renderer.domElement.style.transform = transform; <ide> <del>``` <add>```js <ide> <ide> `position: fixed` kept the canvas from scrolling at all <ide> while the rest of the page scrolled over it. `position: absolute` will let the canvas scroll with the rest of the page which means whatever we draw will stick with the page as it scrolls even if we're too slow to render. When we finally get a chance to render then we move the canvas so it matches where the page has been scrolled and then we re-render. This means only the edges of the window will show some un-rendered bits for a moment but <a href="../threejs-multiple-scenes-v2.html" target="_blank">the stuff in the middle of the page should match up</a> and not slide. Here's a view of the results of the new method slowed down 10x. <ide> We could make it so the main render function, the one managing the canvas, just <ide> <ide> Here's the main render function <ide> <del>``` <add>```js <ide> const sceneElements = []; <ide> function addScene(elem, fn) { <ide> sceneElements.push({elem, fn}); <ide> It checks if the element is on screen. If it is it calls `fn` and passes it the <ide> <ide> Now the setup code for each scene just adds itself to the list of scenes <ide> <del>``` <add>```js <ide> { <ide> const elem = document.querySelector('#box'); <ide> const {scene, camera} = makeScene(); <ide> With that we no longer needed `sceneInfo1` and `sceneInfo2` and the code that wa <ide> <ide> One last even more generic thing we can do is use HTML [dataset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset). This is a way to add your own data to an HTML element. Instead of using `id="..."` we'll use `data-diagram="..."` like this <ide> <del>``` <add>```html <ide> <canvas id="c"></canvas> <ide> <p> <ide> - <span id="box" class="diagram left"></span> <ide> One last even more generic thing we can do is use HTML [dataset](https://develop <ide> <ide> We can them change the CSS selector to select for that <ide> <del>``` <add>```css <ide> -.diagram <ide> +*[data-diagram] { <ide> display: inline-block; <ide> We can them change the CSS selector to select for that <ide> <ide> We'll change the scene setup code to just be a map of names to *scene initialization functions* that return a *scene render function*. <ide> <del>``` <add>```js <ide> const sceneInitFunctionsByName = { <ide> 'box': () => { <ide> const {scene, camera} = makeScene(); <ide> const sceneInitFunctionsByName = { <ide> <ide> And to init we can just use `querySelectorAll` to find all the diagrams and call the corresponding init function for that diagram. <ide> <del>``` <add>```js <ide> document.querySelectorAll('[data-diagram]').forEach((elem) => { <ide> const sceneName = elem.dataset.diagram; <ide> const sceneInitFunction = sceneInitFunctionsByName[sceneName]; <ide> No change to the visuals but the code is even more generic. <ide> <ide> Adding interactively, for example a `TrackballControls` is just as easy. First we add the script for the control. <ide> <del>``` <add>```html <ide> <script src="resources/threejs/r98/js/controls/TrackballControls.js"></script> <ide> ``` <ide> <ide> And then we can add a `TrackballControls` to each scene passing in the element associated with that scene. <ide> <del>``` <add>```js <ide> -function makeScene() { <ide> +function makeScene(elem) { <ide> const scene = new THREE.Scene(); <ide> You'll notice we added the camera to the scene and the light to the camera. This <ide> <ide> We need up update those controls in our render functions <ide> <del>``` <add>```js <ide> const sceneInitFunctionsByName = { <ide> - 'box': () => { <ide> - const {scene, camera} = makeScene(); <ide><path>threejs/lessons/threejs-picking.md <ide> A few changes <ide> <ide> We'll parent the camera to another object so we can spin that other object and the camera will move around the scene just like a selfie stick. <ide> <del>``` <add>```js <ide> *const fov = 60; <ide> const aspect = 2; // the canvas default <ide> const near = 0.1; <ide> const scene = new THREE.Scene(); <ide> <ide> and in the `render` function we'll spin the camera pole. <ide> <del>``` <add>```js <ide> cameraPole.rotation.y = time * .1; <ide> ``` <ide> <ide> Also let's put the light on the camera so the light moves with it. <ide> <del>``` <add>```js <ide> -scene.add(light); <ide> +camera.add(light); <ide> ``` <ide> <ide> Let's generate 100 cubes with random colors in random positions, orientations, <ide> and scales. <ide> <del>``` <add>```js <ide> const boxWidth = 1; <ide> const boxHeight = 1; <ide> const boxDepth = 1; <ide> And finally let's pick. <ide> <ide> Let's make a simple class to manage the picking <ide> <del>``` <add>```js <ide> class PickHelper { <ide> constructor() { <ide> this.raycaster = new THREE.Raycaster(); <ide> You can see we create a `RayCaster` and then we can call the `pick` function to <ide> Of course we could call this function only when the user pressed the mouse *down* which is probaby usually what you want but for this example we'll pick every frame whatever is under the mouse. To do this we first need to track where the mouse <ide> is <ide> <del>``` <add>```js <ide> const pickPosition = {x: 0, y: 0}; <ide> clearPickPosition(); <ide> <ide> Notice we're recording a normalized mouse position. Reguardless of the size of t <ide> <ide> While we're at it lets support mobile as well <ide> <del>``` <add>```js <ide> window.addEventListener('touchstart', (event) => { <ide> // prevent the window from scrolling <ide> event.preventDefault(); <ide> window.addEventListener('touchend', clearPickPosition); <ide> <ide> And finally in our `render` function we call call the `PickHelper`'s `pick` function. <ide> <del>``` <add>```js <ide> +const pickHelper = new PickHelper(); <ide> <ide> function render(time) { <ide> As an example let's apply this texture to the cubes. <ide> <ide> We'll just make these changes <ide> <del>``` <add>```js <ide> +const loader = new THREE.TextureLoader(); <ide> +const texture = loader.load('resources/images/frame.png'); <ide> <ide> To do this type of picking in THREE.js at the moment requires we create 2 scenes <ide> <ide> So, first create a second scene and make sure it clears to black. <ide> <del>``` <add>```js <ide> const scene = new THREE.Scene(); <ide> scene.background = new THREE.Color('white'); <ide> const pickingScene = new THREE.Scene(); <ide> pickingScene.background = new THREE.Color(0); <ide> <ide> Then, for each cube we place in the main scene we make a corresponding "picking cube" at the same position as the original cube, put it in the `pickingScene`, and set it's material to something that will draw the object's id as its color. Also we keep a map of ids to objects so when we look up an id later we can map it back to its corresponding object. <ide> <del>``` <add>```js <ide> const idToObject = {}; <ide> +const numObjects = 100; <ide> for (let i = 0; i < numObjects; ++i) { <ide> Note that abusing the `MeshPhongMaterial` might not be the best solution as it w <ide> <ide> Because we're picking from pixels instead of ray casting we can change the code that sets the pick position to just use pixels. <ide> <del>``` <add>```js <ide> function setPickPosition(event) { <ide> - pickPosition.x = (event.clientX / canvas.clientWidth ) * 2 - 1; <ide> - pickPosition.y = (event.clientY / canvas.clientHeight) * -2 + 1; // note we flip Y <ide> function setPickPosition(event) { <ide> <ide> Then let's change the `PickHelper` into a `GPUPickHelper`. It will use a `WebGLRenderTarget` like we covered the [article on render targets](threejs-rendertargets.html). Our render target here is only a single pixel in size, 1x1. <ide> <del>``` <add>```js <ide> -class PickHelper { <ide> +class GPUPickHelper { <ide> constructor() { <ide> Then let's change the `PickHelper` into a `GPUPickHelper`. It will use a `WebGLR <ide> <ide> Then we just need to use it <ide> <del>``` <add>```js <ide> -const pickHelper = new PickHelper(); <ide> +const pickHelper = new GPUPickHelper(); <ide> ``` <ide> <ide> and pass it the `pickScene` instead of the `scene`. <ide> <del>``` <add>```js <ide> - pickHelper.pick(pickPosition, scene, camera, time); <ide> + pickHelper.pick(pickPosition, pickScene, camera, time); <ide> ``` <ide><path>threejs/lessons/threejs-prerequisites.md <ide> Lots of 20yr old pages use HTML like <ide> That style is deprecated. Put your scripts <ide> at the bottom of the page. <ide> <del>``` <add>```html <ide> <html> <ide> <head> <ide> ... <ide> Put `'use strict';` at the top of every JavaScript file. It will help prevent lo <ide> <ide> ## Know how closures work <ide> <del>``` <add>```js <ide> function a(v) { <ide> const foo = v; <ide> return function() { <ide> the time. Use `let` in those cases where the value changes. This will help avoid <ide> <ide> As one example you can iterate over all the key/value pairs of an object with <ide> <del>``` <add>```js <ide> for (const [key, value] of Object.entries(someObject)) { <ide> console.log(key, value); <ide> } <ide> new code <ide> <ide> old code <ide> <del>``` <add>```js <ide> const width = 300; <ide> const height = 150; <ide> const obj = { <ide> old code <ide> <ide> new code <ide> <del>``` <add>```js <ide> const width = 300; <ide> const height = 150; <ide> const obj = { <ide> new code <ide> <ide> The spread operator has a ton of uses. Example <ide> <del>``` <add>```js <ide> function log(className, ...args) { <ide> const elem = document.createElement('div'); <ide> elem.className = className; <ide> The spread operator has a ton of uses. Example <ide> <ide> Another example <ide> <del>``` <add>```js <ide> const position = [1, 2, 3]; <ide> somemesh.position.set(...position); <ide> ``` <ide> of ES5 makes them much easier than pre ES5. <ide> <ide> This is especially useful with callbacks and promises. <ide> <del>``` <add>```js <ide> loader.load((texture) => { <ide> // use textrue <ide> }); <ide> ``` <ide> <ide> Arrow functions bind `this`. They are a shortcut for <ide> <del>``` <add>```js <ide> (function(args) {/* code */}).bind(this)) <ide> ``` <ide> <ide> Template literals are strings using backticks instead of quotes. <ide> <ide> Template literals have basically 2 features. One is they can be multi-line <ide> <del>``` <add>```js <ide> const foo = `this <ide> is <ide> a <ide> const bar = "this\nis\na\ntemplate\nliteral"; <ide> The other is that you can pop out of string mode and insert snippets of <ide> JavaScript using `${javascript-expression}`. This is the template part. Example: <ide> <del>``` <add>```js <ide> const r = 192; <ide> const g = 255; <ide> const b = 64; <ide> const rgbCSSColor = `rgb(${r},${g},${b})`; <ide> <ide> or <ide> <del>``` <add>```js <ide> const color = [192, 255, 64]; <ide> const rgbCSSColor = `rgb(${color.join(',')})`; <ide> ``` <ide> <ide> or <ide> <del>``` <add>```js <ide> const aWidth = 10; <ide> const bWidth = 20; <ide> someElement.style.width = `${aWidth + bWidth}px`; <ide><path>threejs/lessons/threejs-primitives.md <ide> with the [examples from the previous article](threejs-responsive.html). <ide> <ide> Near the top let's set a background color <ide> <del>``` <add>```js <ide> const scene = new THREE.Scene(); <ide> +scene.background = new THREE.Color(0xAAAAAA); <ide> ``` <ide> This tells three.js to clear to lightish gray. <ide> The camera needs to change position so that we can see all the <ide> objects. <ide> <del>``` <add>```js <ide> -const fov = 75; <ide> +const fov = 40; <ide> const aspect = 2; // the canvas default <ide> const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); <ide> Let's add a function, `addObject`, that takes an x, y position and an `Object3D` and adds <ide> the object to the scene. <ide> <del>``` <add>```js <ide> const objects = []; <ide> const spread = 15; <ide> <ide> as `luminance` goes from 0.0 to 0.5 the color <ide> will go from black to `hue`. From 0.5 to 1.0 <ide> the color will go from `hue` to white. <ide> <del>``` <add>```js <ide> function createMaterial() { <ide> const material = new THREE.MeshPhongMaterial({ <ide> side: THREE.DoubleSide, <ide> we pass a geometry and it creates a random colored <ide> material via `createMaterial` and adds it to the scene <ide> via `addObject`. <ide> <del>``` <add>```js <ide> function addSolidGeometry(x, y, geometry) { <ide> const mesh = new THREE.Mesh(geometry, createMaterial()); <ide> addObject(x, y, mesh); <ide> function addSolidGeometry(x, y, geometry) { <ide> Now we can use this for the majority of the primitives we create. <ide> For example creating a box <ide> <del>``` <add>```js <ide> { <ide> const width = 8; <ide> const height = 8; <ide> and a callback. The callback is called after the font loads. <ide> In the callback we create the geometry <ide> and call `addObject` to add it the scene. <ide> <del>``` <add>```js <ide> { <ide> const loader = new THREE.FontLoader(); <ide> loader.load('resources/threejs/fonts/helvetiker_regular.typeface.json', (font) => { <ide> The other exceptions are the 2 line based examples for `EdgesGeometry` <ide> and `WireframeGeometry`. Instead of calling `addSolidGeometry` they call <ide> `addLineGeomtry` which looks like this <ide> <del>``` <add>```js <ide> function addLineGeometry(x, y, geometry) { <ide> const material = new THREE.LineBasicMaterial({color: 0x000000}); <ide> const mesh = new THREE.LineSegments(geometry, material); <ide><path>threejs/lessons/threejs-rendertargets.md <ide> Let's make a simple example. We'll start with an example from [the article on re <ide> <ide> Rendering to a render target just almost exactly the same as normal rendering. First we create a `WebGLRenderTarget`. <ide> <del>``` <add>```js <ide> const rtWidth = 512; <ide> const rtHeight = 512; <ide> const renderTarget = new THREE.WebGLRenderTarget(rtWidth, rtHeight); <ide> ``` <ide> <ide> Then we need a `Camera` and a `Scene` <ide> <del>``` <add>```js <ide> const rtFov = 75; <ide> const rtAspect = rtWidth / rtHeight; <ide> const rtNear = 0.1; <ide> Notice we set the aspect to the aspect for the render target, not the canvas. <ide> <ide> We fill the scene with stuff. In this case we're using the light and the 3 cubes [from the previous article](threejs-responsive.html). <ide> <del>``` <add>```js <ide> { <ide> const color = 0xFFFFFF; <ide> const intensity = 1; <ide> We just need to add stuff to render. <ide> <ide> Let's add a cube that uses the render target's texture. <ide> <del>``` <add>```js <ide> const material = new THREE.MeshPhongMaterial({ <ide> map: renderTarget.texture, <ide> }); <ide> scene.add(cube); <ide> <ide> Now at render time first we render the render target scene to the render target. <ide> <del>``` <add>```js <ide> function render(time) { <ide> time *= 0.001; <ide> <ide> function render(time) { <ide> <ide> // draw render target scene to render target <ide> renderer.render(rtScene, rtCamera, renderTarget); <del> <ide> ``` <ide> <ide> Then we render the scene with the single cube that is using the render target's texture to the canvas. <ide> <del>``` <add>```js <ide> // rotate the cube in the scene <ide> cube.rotation.x = time; <ide> cube.rotation.y = time * 1.1; <ide><path>threejs/lessons/threejs-responsive.md <ide> in the middle of a document is another example. <ide> The last sample we had used a plain canvas with no css and <ide> no size <ide> <del>``` <add>```html <ide> <canvas id="c"></canvas> <ide> ``` <ide> <ide> of something is to use CSS. <ide> <ide> Let's make the canvas fill the page by adding CSS <ide> <del>``` <add>```html <ide> <style> <ide> html, body { <ide> margin: 0; <ide> display size. We can do that by looking at the canvas's <ide> <ide> We'll update our render loop like this <ide> <del>``` <add>```js <ide> function render(time) { <ide> time *= 0.001; <ide> <ide> number of pixels in the canvas itself. This is no different than an image. <ide> For example we might have a 128x64 pixel image and using <ide> css we might display as 400x200 pixels. <ide> <del>``` <add>```html <ide> <img src="some128x64image.jpg" style="width:400px; height:200px"> <ide> ``` <ide> <ide> attributes. <ide> Let's write a function that checks if the renderer's canvas is not <ide> already the size it is being displayed as and if so set its size. <ide> <del>``` <add>```js <ide> function resizeRendererToDisplaySize(renderer) { <ide> const canvas = renderer.domElement; <ide> const width = canvas.clientWidth; <ide> Note that our function returns true if the canvas was resized. We can use <ide> this to check if there are other things we should update. Let's modify <ide> our render loop to use the new function <ide> <del>``` <add>```js <ide> function render(time) { <ide> time *= 0.001; <ide> <ide> you passed in. <ide> <ide> The other way is to do it yourself when you resize the canvas. <ide> <del>``` <add>```js <ide> function resizeRendererToDisplaySize(renderer) { <ide> const canvas = renderer.domElement; <ide> const pixelRatio = window.devicePixelRatio; <ide><path>threejs/lessons/threejs-scenegraph.md <ide> sun, earth, moon as a demonstration of how to use a scenegraph. Of course <ide> the real sun, earth, and moon use physics but for our purposes we'll <ide> fake it with a scenegraph. <ide> <del>``` <add>```js <ide> // an array of objects who's rotation to update <ide> const objects = []; <ide> <ide> Let's also put a single point light in the center of the scene. We'll go into mo <ide> details about point lights later but for now the simple version is a point light <ide> represents light that eminates from a single point. <ide> <del>``` <add>```js <ide> { <ide> const color = 0xFFFFFF; <ide> const intensity = 3; <ide> which way the top of the camera is facing or rather which way is "up" for the <ide> camera. For most situations positive Y being up is good enough but since <ide> we are looking straight down we need to tell the camera that positive Z is up. <ide> <del>``` <add>```js <ide> const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); <ide> camera.position.set(0, 50, 0); <ide> camera.up.set(0, 0, 1); <ide> camera.lookAt(0, 0, 0); <ide> In the render loop, adapted from previous examples, we're rotating all <ide> objects in our `objects` array with this code. <ide> <del>``` <add>```js <ide> objects.forEach((obj) => { <ide> obj.rotation.y = time; <ide> }); <ide> Since we added the `sunMesh` to the `objects` array it will rotate. <ide> <ide> Now let's add an the earth. <ide> <del>``` <add>```js <ide> const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244}); <ide> const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial); <ide> earthMesh.position.x = 10; <ide> rotate too. <ide> You can see both the sun and the earth are rotating but the earth is not <ide> going around the sun. Let's make the earth a child of the sun <ide> <del>``` <add>```js <ide> -scene.add(earthMesh); <ide> +sunMesh.add(earthMesh); <ide> ``` <ide> its scale set to 5x with `sunMesh.scale.set(5, 5, 5)`. That means the <ide> To fix it let's add an empty scene graph node. We'll parent both the sun and the earth <ide> to that node. <ide> <del>``` <add>```js <ide> +const solarSystem = new THREE.Object3D(); <ide> +scene.add(solarSystem); <ide> +objects.push(solarSystem); <ide> and rotating itself. <ide> <ide> Continuing that same pattern let's add a moon. <ide> <del>``` <add>```js <ide> +const earthOrbit = new THREE.Object3D(); <ide> +earthOrbit.position.x = 10; <ide> +solarSystem.add(earthOrbit); <ide> One is called an `AxesHelper`. It draws 3 lines representing the local <ide> <span style="color:blue">Z</span> axes. Let's add one to every node we <ide> created. <ide> <del>``` <add>```js <ide> // add an AxesHelper to each node <ide> objects.forEach((node) => { <ide> const axes = new THREE.AxesHelper(); <ide> We want to make both a `GridHelper` and an `AxesHelper` for each node. We need <ide> a label for each node so we'll get rid of the old loop and switch to calling <ide> some function to add the helpers for each node <ide> <del>``` <add>```js <ide> -// add an AxesHelper to each node <ide> -objects.forEach((node) => { <ide> - const axes = new THREE.AxesHelper(); <ide> that has a getter and setter for a property. That way we can let dat.GUI <ide> think it's manipulating a single property but internally we can set <ide> the visible property of both the `AxesHelper` and `GridHelper` for a node. <ide> <del>``` <add>```js <ide> // Turns both axes and grid visible on/off <ide> // dat.GUI requires a property that returns a bool <ide> // to decide to make a checkbox so we make a setter <ide><path>threejs/lessons/threejs-shadows.md <ide> We'll use some of the code from [the previous article](threejs-cameras.html). <ide> <ide> Let's set the background color to white. <ide> <del>``` <add>```js <ide> const scene = new THREE.Scene(); <ide> +scene.background = new THREE.Color('white'); <ide> ``` <ide> <ide> Then we'll setup the same checkerboard ground but this time it's using <ide> a `MeshBasicMaterial` as we don't need lighting for the ground. <ide> <del>``` <add>```js <ide> +const loader = new THREE.TextureLoader(); <ide> <ide> { <ide> light grey checkerboard. <ide> <ide> Let's load the shadow texture <ide> <del>```javascript <add>```js <ide> const shadowTexture = loader.load('resources/images/roundshadow.png'); <ide> ``` <ide> <ide> and make an array to remember each sphere and associated objects. <ide> <del>```javascript <add>```js <ide> const sphereShadowBases = []; <ide> ``` <ide> <ide> Then we'll make a sphere geometry <ide> <del>```javascript <add>```js <ide> const sphereRadius = 1; <ide> const sphereWidthDivisions = 32; <ide> const sphereHeightDivisions = 16; <ide> const sphereGeo = new THREE.SphereBufferGeometry(sphereRadius, sphereWidthDivisi <ide> <ide> And a plane geometry for the fake shadow <ide> <del>``` <add>```js <ide> const planeSize = 1; <ide> const shadowGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize); <ide> ``` <ide> We make each sphere a different hue and then save off the base, the sphere mesh, <ide> the shadow mesh and the initial y position of each sphere. <ide> <ide> <del>```javascript <add>```js <ide> const numSpheres = 15; <ide> for (let i = 0; i < numSpheres; ++i) { <ide> // make a base for the shadow and the sphere. <ide> for (let i = 0; i < numSpheres; ++i) { <ide> We setup 2 lights. One is a `HemisphereLight` with the itensity set to 2 to really <ide> brighten things up. <ide> <del>```javascript <add>```js <ide> { <ide> const skyColor = 0xB1E1FF; // light blue <ide> const groundColor = 0xB97A20; // brownish orange <ide> brighten things up. <ide> <ide> The other is a `DirectionalLight` so the spheres get some defintion <ide> <del>```javascript <add>```js <ide> { <ide> const color = 0xFFFFFF; <ide> const intensity = 1; <ide> move the sphere up and down using `Math.abs(Math.sin(time))` <ide> which gives us a bouncy animation. And, we also set the shadow material's <ide> opacity so that as each sphere goes higher its shadow fades out. <ide> <del>```javascript <add>```js <ide> function render(time) { <ide> time *= 0.001; // convert to seconds <ide> <ide> Let's start with the `DirectionaLight` with helper example from [the lights arti <ide> <ide> The first thing we need to do is turn on shadows in the renderer. <ide> <del>``` <add>```js <ide> const renderer = new THREE.WebGLRenderer({canvas: canvas}); <ide> +renderer.shadowMap.enabled = true; <ide> ``` <ide> <ide> Then we also need to tell the light to cast a shadow <ide> <del>```javascript <add>```js <ide> const light = new THREE.DirectionalLight(color, intensity); <ide> +light.castShadow = true; <ide> ``` <ide> both cast shadows and/or receive shadows. <ide> Let's make the plane (the ground) only receive shadows since we don't <ide> really care what happens underneath. <ide> <del>```javascript <add>```js <ide> const mesh = new THREE.Mesh(planeGeo, planeMat); <ide> mesh.receiveShadow = true; <ide> ``` <ide> <ide> For the cube and the sphere let's have them both receive and cast shadows <ide> <del>```javascript <add>```js <ide> const mesh = new THREE.Mesh(cubeGeo, cubeMat); <ide> mesh.castShadow = true; <ide> mesh.receiveShadow = true; <ide> the shadows get rendered. In the example above that area is too small. <ide> In order to visualize that area we can get the light's shadow camera and add <ide> a `CameraHelper` to the scene. <ide> <del>```javascript <add>```js <ide> const cameraHelper = new THREE.CameraHelper(light.shadow.camera); <ide> scene.add(cameraHelper); <ide> ``` <ide> that we'll pass an object and 2 properties. It will present one property that da <ide> can adjust and in response will set the two properties one positive and one negative. <ide> We can use this to set `left` and `right` as `width` and `up` and `down` as `height`. <ide> <del>```javascript <add>```js <ide> class DimensionGUIHelper { <ide> constructor(obj, minProp, maxProp) { <ide> this.obj = obj; <ide> class DimensionGUIHelper { <ide> We'll also use the `MinMaxGUIHelper` we created in the [camera article](threejs-cameras.html) <ide> to adjust `near` and `far`. <ide> <del>``` <add>```js <ide> const gui = new dat.GUI(); <ide> gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); <ide> gui.add(light, 'intensity', 0, 2, 0.01); <ide> We tell the GUI to call our `updateCamera` function anytime anything changes. <ide> Let's write that function to update the light, the helper for the light, the <ide> light's shadow camera, and the helper showing the light's shadow camera. <ide> <del>``` <add>```js <ide> function updateCamera() { <ide> // update the light target's matrixWorld because it's needed by the helper <ide> light.target.updateMatrixWorld(); <ide> where we could manually set most its settings, `SpotLight`'s shadow camera is co <ide> camera is directly connected to the `SpotLight`'s `angle` setting. <ide> The `aspect` is set automatically based on the size of the shadow map. <ide> <del>```javascript <add>```js <ide> -const light = new THREE.DirectionalLight(color, intensity); <ide> +const light = new THREE.SpotLight(color, intensity); <ide> ``` <ide> we'll set it only to receive shadows. Also we'll set the position of the <ide> box so its bottom is slightly below the floor so the floor and the bottom <ide> of the box don't z-fight. <ide> <del>```javascript <add>```js <ide> { <ide> const cubeSize = 30; <ide> const cubeGeo = new THREE.BoxBufferGeometry(cubeSize, cubeSize, cubeSize); <ide> of the box don't z-fight. <ide> <ide> And of course we need to switch the light to a `PointLight`. <ide> <del>```javascript <add>```js <ide> -const light = new THREE.SpotLight(color, intensity); <ide> +const light = new THREE.PointLight(color, intensity); <ide> <ide><path>threejs/lessons/threejs-textures.md <ide> We'll modify one of our first samples. All we need to do is create a `TextureLoa <ide> [`load`](TextureLoader.load) method with the URL of an <ide> image and and set the material's `map` property to the result instead of setting its `color`. <ide> <del>``` <add>```js <ide> +const loader = new THREE.TextureLoader(); <ide> <ide> const material = new THREE.MeshBasicMaterial({ <ide> How about 6 textures, one on each face of a cube? <ide> <ide> We just make 6 materials and pass them as an array when we create the `Mesh` <ide> <del>``` <add>```js <ide> const loader = new THREE.TextureLoader(); <ide> <ide> -const material = new THREE.MeshBasicMaterial({ <ide> Most of the code on this site uses the easiest method of loading textures. <ide> We create a `TextureLoader` and then call its [`load`](TextureLoader.load) method. <ide> This returns a `Texture` object. <ide> <del>``` <add>```js <ide> const texture = loader.load('resources/images/flower-1.jpg'); <ide> ``` <ide> <ide> that will be called when the texture has finished loading. Going back to our top <ide> we can wait for the texture to load before creating our `Mesh` and adding it to scene <ide> like this <ide> <del>``` <add>```js <ide> const loader = new THREE.TextureLoader(); <ide> loader.load('resources/images/wall.jpg', (texture) => { <ide> const material = new THREE.MeshBasicMaterial({ <ide> To wait until all textures have loaded you can use a `LoadingManager`. Create on <ide> and pass it to the `TextureLoader` then set its [`onLoad`](LoadingManager.onLoad) <ide> property to a callback. <ide> <del>``` <add>```js <ide> +const loadManager = new THREE.LoadingManager(); <ide> *const loader = new THREE.TextureLoader(loadManager); <ide> <ide> we can set to another callback to show a progress indicator. <ide> <ide> First we'll add a progress bar in HTML <ide> <del>``` <add>```html <ide> <body> <ide> <canvas id="c"></canvas> <ide> + <div id="loading"> <ide> First we'll add a progress bar in HTML <ide> <ide> and the CSS for it <ide> <del>``` <add>```css <ide> #loading { <ide> position: fixed; <ide> top: 0; <ide> and the CSS for it <ide> transform-origin: top left; <ide> transform: scaleX(0); <ide> } <del> <ide> ``` <ide> <ide> Then in the code we'll update the scale of the `progressbar` in our `onProgress` callback. It gets <ide> called with the URL of the last item loaded, the number of items loaded so far, and the total <ide> number of items loaded. <ide> <del>``` <add>```js <ide> +const loadingElem = document.querySelector('#loading'); <ide> +const progressBarElem = loadingElem.querySelector('.progressbar'); <ide> <ide> They can be set to one of: <ide> <ide> For example to turn on wrapping in both directions: <ide> <del>``` <add>```js <ide> someTexture.wrapS = THREE.RepeatWrapping; <ide> someTexture.wrapT = THREE.RepeatWrapping; <ide> ``` <ide> <ide> Repeating is set with the [repeat] repeat property. <ide> <del>``` <add>```js <ide> const timesToRepeatHorizontally = 4; <ide> const timesToRepeatVertically = 2; <ide> someTexture.repeat.set(timesToRepeatHorizontally, timesToRepeatVertically); <ide> Offseting the texture can be done by setting the `offset` property. Textures <ide> are offset with units where 1 unit = 1 texture size. On other words 0 = no offset <ide> and 1 = offset one full texture amount. <ide> <del>``` <add>```js <ide> const xOffset = .5; // offset by half the texture <ide> const yOffset = .25; // offset by 1/2 the texture <ide> someTexture.offset.set(xOffset, yOffset);` <ide> It defaults to 0,0 which rotates from the bottom left corner. Like offset <ide> these units are in texture size so setting them to `.5, .5` would rotate <ide> around the center of the texture. <ide> <del>``` <add>```js <ide> someTexture.center.set(.5, .5); <ide> someTexture.rotation = THREE.Math.degToRad(45); <ide> ``` <ide> Let's modify the top sample above to play with these values <ide> <ide> First we'll keep a reference to the texture so we can manipulate it <ide> <del>``` <add>```js <ide> +const texture = loader.load('resources/images/wall.jpg'); <ide> const material = new THREE.MeshBasicMaterial({ <ide> - map: loader.load('resources/images/wall.jpg'); <ide> const material = new THREE.MeshBasicMaterial({ <ide> <ide> Then we'll use [dat.GUI](https://github.com/dataarts/dat.gui) again to provide a simple interface. <ide> <del>``` <add>```html <ide> <script src="../3rdparty/dat.gui.min.js"></script> <ide> ``` <ide> <ide> As we did in previous dat.GUI examples we'll use a simple class to <ide> give dat.GUI an object that it can manipulate in degrees <ide> but that will set a property in radians. <ide> <del>``` <add>```js <ide> class DegRadHelper { <ide> constructor(obj, prop) { <ide> this.obj = obj; <ide> We also need a class that will convert from a string like `"123"` into <ide> a number like `123` since three.js requires numbers for enum settings <ide> like `wrapS` and `wrapT` but dat.GUI only uses strings for enums. <ide> <del>``` <add>```js <ide> class StringToNumberHelper { <ide> constructor(obj, prop) { <ide> this.obj = obj; <ide> class StringToNumberHelper { <ide> <ide> Using those classes we can setup a simple GUI for the settings above <ide> <del>``` <add>```js <ide> const wrapModes = { <ide> 'ClampToEdgeWrapping': THREE.ClampToEdgeWrapping, <ide> 'RepeatWrapping': THREE.RepeatWrapping,
17
Javascript
Javascript
remove ballshooter_multivew from files
f4c0cf956a3b682b3c2d21d54b20e5cc6c0f67fa
<ide><path>examples/files.js <ide> var files = { <ide> "webgl_multiple_renderers", <ide> "webgl_multiple_scenes_comparison", <ide> "webgl_multiple_views", <del> "webgl_multiple_views_multiview", <ide> "webgl_nearestneighbour", <ide> "webgl_panorama_cube", <ide> "webgl_panorama_dualfisheye",
1
Text
Text
add changelog entry to composed_of removal
7fe0f27e2b97a2f175b31b97d14f92473688f66a
<ide><path>activerecord/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* `composed_of` has removed. You'll have to write your own accessor <add> and mutator methods if you'd like to use value objects to represent some <add> portion of your models. <add> <add> *Steve Klabnik* <add> <ide> * PostgreSQL default log level is now 'warning', to bypass the noisy notice <ide> messages. You can change the log level using the `min_messages` option <ide> available in your config/database.yml.
1
Java
Java
fix minor issue in handlermethod
b9786ccacac2cf90e7fa10a9a74a42c603376f4c
<ide><path>spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java <ide> public Method getMethod() { <ide> * Note that if the bean type is a CGLIB-generated class, the original, user-defined class is returned. <ide> */ <ide> public Class<?> getBeanType() { <del> if (bean instanceof String) { <del> String beanName = (String) bean; <del> return beanFactory.getType(beanName); <del> } <del> else { <del> return ClassUtils.getUserClass(bean.getClass()); <del> } <add> Class<?> clazz = (this.bean instanceof String) <add> ? this.beanFactory.getType((String) this.bean) : this.bean.getClass(); <add> <add> return ClassUtils.getUserClass(clazz); <ide> } <ide> <ide> /** <ide> * If the bean method is a bridge method, this method returns the bridged (user-defined) method. <ide> * Otherwise it returns the same method as {@link #getMethod()}. <ide> */ <ide> protected Method getBridgedMethod() { <del> return bridgedMethod; <add> return this.bridgedMethod; <ide> } <ide> <ide> /** <ide> public MethodParameter[] getMethodParameters() { <ide> } <ide> this.parameters = p; <ide> } <del> return parameters; <add> return this.parameters; <ide> } <ide> <ide> /** <ide> public HandlerMethod createWithResolvedBean() { <ide> String beanName = (String) this.bean; <ide> handler = this.beanFactory.getBean(beanName); <ide> } <del> return new HandlerMethod(handler, method); <add> return new HandlerMethod(handler, this.method); <ide> } <ide> <ide> @Override
1
Text
Text
add djangorestframework-features to third-party
6196e9c8cd4b8a785564310304870ab5ad2873be
<ide><path>docs/community/third-party-packages.md <ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque <ide> * [django-rest-framework-condition][django-rest-framework-condition] - Decorators for managing HTTP cache headers for Django REST framework (ETag and Last-modified). <ide> * [django-rest-witchcraft][django-rest-witchcraft] - Provides DRF integration with SQLAlchemy with SQLAlchemy model serializers/viewsets and a bunch of other goodies <ide> * [djangorestframework-mvt][djangorestframework-mvt] - An extension for creating views that serve Postgres data as Map Box Vector Tiles. <add>* [djangorestframework-features][djangorestframework-features] - Advanced schema generation and more based on named features. <ide> <ide> [cite]: http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html <ide> [cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework <ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque <ide> [django-restql]: https://github.com/yezyilomo/django-restql <ide> [djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt <ide> [django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian <add>[djangorestframework-features]: https://github.com/cloudcode-hungary/django-rest-framework-features/
1
Javascript
Javascript
pass instance handle to all fabric clone methods
f79227597202336b5a6e62642dc42646d9639cee
<ide><path>packages/react-native-renderer/src/ReactFabricHostConfig.js <ide> import invariant from 'fbjs/lib/invariant'; <ide> <ide> // Modules provided by RN: <ide> import TextInputState from 'TextInputState'; <del>import FabricUIManager from 'FabricUIManager'; <add>import { <add> createNode, <add> cloneNode, <add> cloneNodeWithNewChildren, <add> cloneNodeWithNewChildrenAndProps, <add> cloneNodeWithNewProps, <add> createChildSet, <add> appendChild, <add> appendChildToSet, <add> completeRoot, <add>} from 'FabricUIManager'; <ide> import UIManager from 'UIManager'; <ide> <ide> // Counter for uniquely identifying views. <ide> type TextInstance = { <ide> node: Node, <ide> }; <ide> <del>const ReacFabricHostConfig = { <add>const ReactFabricHostConfig = { <ide> appendInitialChild( <ide> parentInstance: Instance, <ide> child: Instance | TextInstance, <ide> ): void { <del> FabricUIManager.appendChild(parentInstance.node, child.node); <add> appendChild(parentInstance.node, child.node); <ide> }, <ide> <ide> createInstance( <ide> const ReacFabricHostConfig = { <ide> viewConfig.validAttributes, <ide> ); <ide> <del> const node = FabricUIManager.createNode( <add> const node = createNode( <ide> tag, // reactTag <ide> viewConfig.uiViewClassName, // viewName <ide> rootContainerInstance, // rootTag <ide> const ReacFabricHostConfig = { <ide> const tag = nextReactTag; <ide> nextReactTag += 2; <ide> <del> const node = FabricUIManager.createNode( <add> const node = createNode( <ide> tag, // reactTag <ide> 'RCTRawText', // viewName <ide> rootContainerInstance, // rootTag <ide> const ReacFabricHostConfig = { <ide> let clone; <ide> if (keepChildren) { <ide> if (updatePayload !== null) { <del> clone = FabricUIManager.cloneNodeWithNewProps(node, updatePayload); <add> clone = cloneNodeWithNewProps( <add> node, <add> updatePayload, <add> internalInstanceHandle, <add> ); <ide> } else { <del> clone = FabricUIManager.cloneNode(node); <add> clone = cloneNode(node, internalInstanceHandle); <ide> } <ide> } else { <ide> if (updatePayload !== null) { <del> clone = FabricUIManager.cloneNodeWithNewChildrenAndProps( <add> clone = cloneNodeWithNewChildrenAndProps( <ide> node, <ide> updatePayload, <add> internalInstanceHandle, <ide> ); <ide> } else { <del> clone = FabricUIManager.cloneNodeWithNewChildren(node); <add> clone = cloneNodeWithNewChildren(node, internalInstanceHandle); <ide> } <ide> } <ide> return { <ide> const ReacFabricHostConfig = { <ide> }, <ide> <ide> createContainerChildSet(container: Container): ChildSet { <del> return FabricUIManager.createChildSet(container); <add> return createChildSet(container); <ide> }, <ide> <ide> appendChildToContainerChildSet( <ide> childSet: ChildSet, <ide> child: Instance | TextInstance, <ide> ): void { <del> FabricUIManager.appendChildToSet(childSet, child.node); <add> appendChildToSet(childSet, child.node); <ide> }, <ide> <ide> finalizeContainerChildren( <ide> container: Container, <ide> newChildren: ChildSet, <ide> ): void { <del> FabricUIManager.completeRoot(container, newChildren); <add> completeRoot(container, newChildren); <ide> }, <ide> <ide> replaceContainerChildren( <ide> const ReacFabricHostConfig = { <ide> }, <ide> }; <ide> <del>export default ReacFabricHostConfig; <add>export default ReactFabricHostConfig; <ide><path>packages/react-native-renderer/src/__mocks__/FabricUIManager.js <ide> const RCTFabricUIManager = { <ide> children: [], <ide> }; <ide> }), <del> cloneNode: jest.fn(function cloneNode(node) { <add> cloneNode: jest.fn(function cloneNode(node, instanceHandle) { <ide> return { <ide> reactTag: node.reactTag, <ide> viewName: node.viewName, <ide> props: node.props, <ide> children: node.children, <ide> }; <ide> }), <del> cloneNodeWithNewChildren: jest.fn(function cloneNodeWithNewChildren(node) { <add> cloneNodeWithNewChildren: jest.fn(function cloneNodeWithNewChildren( <add> node, <add> instanceHandle, <add> ) { <ide> return { <ide> reactTag: node.reactTag, <ide> viewName: node.viewName, <ide> const RCTFabricUIManager = { <ide> cloneNodeWithNewProps: jest.fn(function cloneNodeWithNewProps( <ide> node, <ide> newPropsDiff, <add> instanceHandle, <ide> ) { <ide> return { <ide> reactTag: node.reactTag, <ide> const RCTFabricUIManager = { <ide> }; <ide> }), <ide> cloneNodeWithNewChildrenAndProps: jest.fn( <del> function cloneNodeWithNewChildrenAndProps(node, newPropsDiff) { <add> function cloneNodeWithNewChildrenAndProps( <add> node, <add> newPropsDiff, <add> instanceHandle, <add> ) { <ide> return { <ide> reactTag: node.reactTag, <ide> viewName: node.viewName, <ide><path>packages/react-native-renderer/src/__tests__/ReactFabric-test.internal.js <ide> describe('ReactFabric', () => { <ide> ReactFabric.render(<View foo="bar" />, 11); <ide> <ide> expect(FabricUIManager.createNode.mock.calls.length).toBe(1); <del> expect(FabricUIManager.cloneNodeWithNewProps).toBeCalledWith(firstNode, { <add> expect(FabricUIManager.cloneNodeWithNewProps.mock.calls.length).toBe(1); <add> expect(FabricUIManager.cloneNodeWithNewProps.mock.calls[0][0]).toBe( <add> firstNode, <add> ); <add> expect(FabricUIManager.cloneNodeWithNewProps.mock.calls[0][1]).toEqual({ <ide> foo: 'bar', <ide> }); <ide> }); <ide><path>scripts/flow/react-native-host-hooks.js <ide> declare module 'FabricUIManager' { <ide> props: ?Object, <ide> instanceHandle: Object, <ide> ): Object; <del> declare function cloneNode(node: Object): Object; <del> declare function cloneNodeWithNewChildren(node: Object): Object; <add> declare function cloneNode(node: Object, instanceHandle: Object): Object; <add> declare function cloneNodeWithNewChildren( <add> node: Object, <add> instanceHandle: Object, <add> ): Object; <ide> declare function cloneNodeWithNewProps( <ide> node: Object, <ide> newProps: ?Object, <add> instanceHandle: Object, <ide> ): Object; <ide> declare function cloneNodeWithNewChildrenAndProps( <ide> node: Object, <ide> newProps: ?Object, <add> instanceHandle: Object, <ide> ): Object; <ide> declare function appendChild(node: Object, childNode: Object): void; <ide>
4
Javascript
Javascript
add length check when normalizing args
a206afec7671944d5b123d207e00300a894fe0df
<ide><path>lib/net.js <ide> exports.connect = exports.createConnection = function() { <ide> function normalizeConnectArgs(args) { <ide> var options = {}; <ide> <del> if (args[0] !== null && typeof args[0] === 'object') { <add> if (args.length === 0) { <add> return [options]; <add> } else if (args[0] !== null && typeof args[0] === 'object') { <ide> // connect(options, [cb]) <ide> options = args[0]; <ide> } else if (isPipeName(args[0])) { <ide> function normalizeConnectArgs(args) { <ide> } else { <ide> // connect(port, [host], [cb]) <ide> options.port = args[0]; <del> if (typeof args[1] === 'string') { <add> if (args.length > 1 && typeof args[1] === 'string') { <ide> options.host = args[1]; <ide> } <ide> }
1
PHP
PHP
remove default $type argument
e4afd0c7b754fd5f400aaf5d9d22c076907d4a38
<ide><path>src/Datasource/EntityTrait.php <ide> public function &get($property) <ide> } <ide> <ide> $value = null; <del> $method = $this->_accessor($property); <add> $method = $this->_accessor($property, 'get'); <ide> <ide> if (isset($this->_properties[$property])) { <ide> $value =& $this->_properties[$property]; <ide> public function offsetUnset($offset) <ide> * @param string $type the accessor type ('get' or 'set') <ide> * @return string method name or empty string (no method available) <ide> */ <del> protected function _accessor($property, $type = 'get') <add> protected function _accessor($property, $type) <ide> { <ide> if (!isset(static::$_accessors[$this->_className][$type][$property])) { <ide> /* first time for this class: build all fields */
1
Text
Text
add changelog entry for partialiteration
03d77504be20fbd170a25e948f259ad4047d0d3e
<ide><path>actionview/CHANGELOG.md <add>* Add `PartialIteration` object used when rendering collections. <add> <add> The iteration object is available as the local variable <add> `#{template_name}_iteration` when rendering partials with collections. <add> <add> It gives access to the `size` of the collection being iterated over, <add> the current `index` and two convenience methods `first?` and `last?`. <add> <add> *Joel Junström*, *Lucas Uyezu* <add> <ide> * Return an absolute instead of relative path from an asset url in the case <ide> of the `asset_host` proc returning nil <ide>
1
Javascript
Javascript
add tests for order of decorations
01abe6ae5877ea754b639b6bcff0723c097b90bf
<ide><path>test/loaderSpec.js <ide> describe('module loader', function() { <ide> }); <ide> <ide> <add> it("should run decorators in order of declaration, even when mixed with provider.decorator", function() { <add> var log = ''; <add> <add> angular.module('theModule', []) <add> .factory('theProvider', function() { <add> return {api: 'provider'}; <add> }) <add> .decorator('theProvider', function($delegate) { <add> $delegate.api = $delegate.api + '-first'; <add> return $delegate; <add> }) <add> .config(function($provide) { <add> $provide.decorator('theProvider', function($delegate) { <add> $delegate.api = $delegate.api + '-second'; <add> return $delegate; <add> }); <add> }) <add> .decorator('theProvider', function($delegate) { <add> $delegate.api = $delegate.api + '-third'; <add> return $delegate; <add> }) <add> .run(function(theProvider) { <add> log = theProvider.api; <add> }) <add> <add> createInjector(['theModule']); <add> expect(log).toBe('provider-first-second-third'); <add> }); <add> <add> <add> it("should decorate the last declared provider if multiple have been declared", function() { <add> var log = ''; <add> <add> angular.module('theModule', []). <add> factory('theProvider', function() { return { <add> api: 'firstProvider' <add> }; }). <add> decorator('theProvider', function($delegate) { <add> $delegate.api = $delegate.api + '-decorator'; <add> return $delegate; }). <add> factory('theProvider', function() { return { <add> api: 'secondProvider' <add> }; }). <add> run(function(theProvider) { <add> log = theProvider.api; <add> }); <add> <add> createInjector(['theModule']); <add> expect(log).toBe('secondProvider-decorator') <add> }); <add> <add> <ide> it('should allow module redefinition', function() { <ide> expect(window.angular.module('a', [])).not.toBe(window.angular.module('a', [])); <ide> });
1
Text
Text
fix some typos
4f2b6579bf59b033e5eda27a51d4192e9c2d2623
<ide><path>docs/source/quickstart.md <ide> The library was designed with two strong goals in mind: <ide> <ide> A few other goals: <ide> <del>- expose the models internals as consistently as possible: <add>- expose the models' internals as consistently as possible: <ide> <ide> - we give access, using a single API to the full hidden-states and attention weights, <ide> - tokenizer and base model's API are standardized to easily switch between models. <ide> <del>- incorporate a subjective selection of promising tools for fine-tuning/investiguating these models: <add>- incorporate a subjective selection of promising tools for fine-tuning/investigating these models: <ide> <ide> - a simple/consistent way to add new tokens to the vocabulary and embeddings for fine-tuning, <ide> - simple ways to mask and prune transformer heads. <ide> We'll finish this quickstart tour by going through a few simple quick-start exam <ide> <ide> Here are two examples showcasing a few `Bert` and `GPT2` classes and pre-trained models. <ide> <del>See full API reference for examples for each model classe. <add>See full API reference for examples for each model class. <ide> <ide> ### BERT example <ide>
1
Ruby
Ruby
fix tests with ruby 3
9aed046be93e1d8880d39a6b0dd75a7263f4fff3
<ide><path>actionview/test/template/form_helper/form_with_test.rb <ide> def test_form_with_label_accesses_object_through_label_tag_builder <ide> form_with(model: Post.new) do |f| <ide> concat( <ide> f.label(:title) do |builder| <del> concat tag.span(builder, { <add> concat tag.span(builder, <ide> class: ("new_record" unless builder.object.persisted?) <del> }) <add> ) <ide> end <ide> ) <ide> end
1
Go
Go
fix docker load progressbar, fixes
96d7db665b06cc0bbede22d818c69dc5f6921f66
<ide><path>api/client/load.go <ide> func (cli *DockerCli) CmdLoad(args ...string) error { <ide> } <ide> defer response.Body.Close() <ide> <del> if response.JSON { <add> if response.Body != nil && response.JSON { <ide> return jsonmessage.DisplayJSONMessagesStream(response.Body, cli.out, cli.outFd, cli.isTerminalOut, nil) <ide> } <ide> <ide><path>api/server/router/image/image_routes.go <ide> func (s *imageRouter) postImagesLoad(ctx context.Context, w http.ResponseWriter, <ide> return err <ide> } <ide> quiet := httputils.BoolValueOrDefault(r, "quiet", true) <del> w.Header().Set("Content-Type", "application/json") <add> <add> if !quiet { <add> w.Header().Set("Content-Type", "application/json") <add> <add> output := ioutils.NewWriteFlusher(w) <add> defer output.Close() <add> if err := s.backend.LoadImage(r.Body, output, quiet); err != nil { <add> output.Write(streamformatter.NewJSONStreamFormatter().FormatError(err)) <add> } <add> return nil <add> } <ide> return s.backend.LoadImage(r.Body, w, quiet) <ide> } <ide> <ide><path>image/tarexport/load.go <ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer, quiet bool) <ide> ) <ide> if !quiet { <ide> progressOutput = sf.NewProgressOutput(outStream, false) <add> outStream = &streamformatter.StdoutFormatter{Writer: outStream, StreamFormatter: streamformatter.NewJSONStreamFormatter()} <ide> } <ide> <ide> tmpDir, err := ioutil.TempDir("", "docker-import-") <ide><path>integration-cli/docker_cli_save_load_unix_test.go <ide> package main <ide> <ide> import ( <add> "fmt" <ide> "io/ioutil" <ide> "os" <ide> "os/exec" <ide> func (s *DockerSuite) TestSaveAndLoadRepoStdout(c *check.C) { <ide> c.Assert(err, check.IsNil) //could not read tty output <ide> c.Assert(string(buf[:n]), checker.Contains, "Cowardly refusing", check.Commentf("help output is not being yielded", out)) <ide> } <add> <add>func (s *DockerSuite) TestSaveAndLoadWithProgressBar(c *check.C) { <add> name := "test-load" <add> _, err := buildImage(name, ` <add> FROM busybox <add> RUN touch aa <add> `, true) <add> c.Assert(err, check.IsNil) <add> <add> tmptar := name + ".tar" <add> dockerCmd(c, "save", "-o", tmptar, name) <add> defer os.Remove(tmptar) <add> <add> dockerCmd(c, "rmi", name) <add> dockerCmd(c, "tag", "busybox", name) <add> out, _ := dockerCmd(c, "load", "-i", tmptar) <add> expected := fmt.Sprintf("The image %s:latest already exists, renaming the old one with ID", name) <add> c.Assert(out, checker.Contains, expected) <add>}
4
Javascript
Javascript
add docs for angular.widget.textarea
a46f2a0db37c88465072d0eec22b0439bf003ff7
<ide><path>src/widget/input.js <ide> angularWidget('input', function(inputElement){ <ide> }); <ide> } <ide> }); <del> <ide> }); <ide> <add> <add>/** <add> * @ngdoc widget <add> * @name angular.widget.textarea <add> * <add> * @description <add> * HTML textarea element widget with angular data-binding. The data-binding and validation <add> * properties of this element are exactly the same as those of the <add> * {@link angular.widget.input input element}. <add> * <add> * @param {string} type Widget types as defined by {@link angular.inputType}. If the <add> * type is in the format of `@ScopeType` then `ScopeType` is loaded from the <add> * current scope, allowing quick definition of type. <add> * @param {string} ng:model Assignable angular expression to data-bind to. <add> * @param {string=} name Property name of the form under which the widgets is published. <add> * @param {string=} required Sets `REQUIRED` validation error key if the value is not entered. <add> * @param {number=} ng:minlength Sets `MINLENGTH` validation error key if the value is shorter than <add> * minlength. <add> * @param {number=} ng:maxlength Sets `MAXLENGTH` validation error key if the value is longer than <add> * maxlength. <add> * @param {string=} ng:pattern Sets `PATTERN` validation error key if the value does not match the <add> * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for <add> * patterns defined as scope expressions. <add> * @param {string=} ng:change Angular expression to be executed when input changes due to user <add> * interaction with the input element. <add> */ <ide> angularWidget('textarea', angularWidget('input')); <ide> <ide>
1
Text
Text
fix documentation of 'path' in tokenizer.to_disk
8df5b7f51392395a896a991732f04382b6731ead
<ide><path>website/docs/api/tokenizer.md <ide> the <ide> > tokenizer = nlp.Defaults.create_tokenizer(nlp) <ide> > ``` <ide> <del>| Name | Type | Description | <add>| Name | Type | Description | <ide> | ---------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------ | <ide> | `vocab` | `Vocab` | A storage container for lexical types. | <ide> | `rules` | dict | Exceptions and special-cases for the tokenizer. | <ide> produced are identical to `Tokenizer.__call__` except for whitespace tokens. <ide> > assert [t[1] for t in tok_exp] == ["(", "do", "n't", ")"] <ide> > ``` <ide> <del>| Name | Type | Description | <del>| ------------| -------- | --------------------------------------------------- | <del>| `string` | unicode | The string to tokenize with the debugging tokenizer | <del>| **RETURNS** | list | A list of `(pattern_string, token_string)` tuples | <add>| Name | Type | Description | <add>| ----------- | ------- | --------------------------------------------------- | <add>| `string` | unicode | The string to tokenize with the debugging tokenizer | <add>| **RETURNS** | list | A list of `(pattern_string, token_string)` tuples | <ide> <ide> ## Tokenizer.to_disk {#to_disk tag="method"} <ide> <ide> Serialize the tokenizer to disk. <ide> > tokenizer.to_disk("/path/to/tokenizer") <ide> > ``` <ide> <del>| Name | Type | Description | <del>| --------- | ---------------- | --------------------------------------------------------------------------------------------------------------------- | <del>| `path` | unicode / `Path` | A path to a directory, which will be created if it doesn't exist. Paths may be either strings or `Path`-like objects. | <del>| `exclude` | list | String names of [serialization fields](#serialization-fields) to exclude. | <add>| Name | Type | Description | <add>| --------- | ---------------- | ---------------------------------------------------------------------------------------------------------------- | <add>| `path` | unicode / `Path` | A path to a file, which will be created if it doesn't exist. Paths may be either strings or `Path`-like objects. | <add>| `exclude` | list | String names of [serialization fields](#serialization-fields) to exclude. | <ide> <ide> ## Tokenizer.from_disk {#from_disk tag="method"} <ide> <ide> it. <ide> <ide> ## Attributes {#attributes} <ide> <del>| Name | Type | Description | <del>| ---------------- | ------- | --------------------------------------------------------------------------------------------------------------------------- | <del>| `vocab` | `Vocab` | The vocab object of the parent `Doc`. | <del>| `prefix_search` | - | A function to find segment boundaries from the start of a string. Returns the length of the segment, or `None`. | <del>| `suffix_search` | - | A function to find segment boundaries from the end of a string. Returns the length of the segment, or `None`. | <del>| `infix_finditer` | - | A function to find internal segment separators, e.g. hyphens. Returns a (possibly empty) list of `re.MatchObject` objects. | <del>| `token_match` | - | A function matching the signature of `re.compile(string).match to find token matches. Returns an `re.MatchObject` or `None. | <del>| `rules` | dict | A dictionary of tokenizer exceptions and special cases. | <add>| Name | Type | Description | <add>| ---------------- | ------- | -------------------------------------------------------------------------------------------------------------------------- | <add>| `vocab` | `Vocab` | The vocab object of the parent `Doc`. | <add>| `prefix_search` | - | A function to find segment boundaries from the start of a string. Returns the length of the segment, or `None`. | <add>| `suffix_search` | - | A function to find segment boundaries from the end of a string. Returns the length of the segment, or `None`. | <add>| `infix_finditer` | - | A function to find internal segment separators, e.g. hyphens. Returns a (possibly empty) list of `re.MatchObject` objects. | <add>| `token_match` | - | A function matching the signature of `re.compile(string).match to find token matches. Returns an`re.MatchObject`or`None. | <add>| `rules` | dict | A dictionary of tokenizer exceptions and special cases. | <ide> <ide> ## Serialization fields {#serialization-fields} <ide>
1
Javascript
Javascript
add support for zero-delay intervals in tests
32f464531472ca7b5aa0dc81c5f6421096012201
<ide><path>src/ngMock/angular-mocks.js <ide> angular.mock.$IntervalProvider = function() { <ide> } <ide> <ide> repeatFns.push({ <del> nextTime:(now + delay), <del> delay: delay, <add> nextTime: (now + (delay || 0)), <add> delay: delay || 1, <ide> fn: tick, <ide> id: nextRepeatId, <ide> deferred: deferred <ide> angular.mock.$IntervalProvider = function() { <ide> * @return {number} The amount of time moved forward. <ide> */ <ide> $interval.flush = function(millis) { <add> var before = now; <ide> now += millis; <ide> while (repeatFns.length && repeatFns[0].nextTime <= now) { <ide> var task = repeatFns[0]; <ide> task.fn(); <add> if (task.nextTime === before) { <add> // this can only happen the first time <add> // a zero-delay interval gets triggered <add> task.nextTime++; <add> } <ide> task.nextTime += task.delay; <ide> repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); <ide> } <ide><path>test/ngMock/angular-mocksSpec.js <ide> describe('ngMock', function() { <ide> })); <ide> <ide> <add> it('should allow you to NOT specify the delay time', inject(function($interval) { <add> var counterA = 0; <add> var counterB = 0; <add> <add> $interval(function() { counterA++; }); <add> $interval(function() { counterB++; }, 0); <add> <add> $interval.flush(1000); <add> expect(counterA).toBe(1000); <add> expect(counterB).toBe(1000); <add> $interval.flush(1000); <add> expect(counterA).toBe(2000); <add> expect(counterB).toBe(2000); <add> })); <add> <add> <add> it('should run tasks in correct relative order', inject(function($interval) { <add> var counterA = 0; <add> var counterB = 0; <add> $interval(function() { counterA++; }, 0); <add> $interval(function() { counterB++; }, 1000); <add> <add> $interval.flush(1000); <add> expect(counterA).toBe(1000); <add> expect(counterB).toBe(1); <add> $interval.flush(999); <add> expect(counterA).toBe(1999); <add> expect(counterB).toBe(1); <add> $interval.flush(1); <add> expect(counterA).toBe(2000); <add> expect(counterB).toBe(2); <add> })); <add> <add> <add> it('should NOT trigger zero-delay interval when flush has ran before', inject(function($interval) { <add> var counterA = 0; <add> var counterB = 0; <add> <add> $interval.flush(100); <add> <add> $interval(function() { counterA++; }); <add> $interval(function() { counterB++; }, 0); <add> <add> expect(counterA).toBe(0); <add> expect(counterB).toBe(0); <add> <add> $interval.flush(100); <add> <add> expect(counterA).toBe(100); <add> expect(counterB).toBe(100); <add> })); <add> <add> <add> it('should trigger zero-delay interval only once on flush zero', inject(function($interval) { <add> var counterA = 0; <add> var counterB = 0; <add> <add> $interval(function() { counterA++; }); <add> $interval(function() { counterB++; }, 0); <add> <add> $interval.flush(0); <add> expect(counterA).toBe(1); <add> expect(counterB).toBe(1); <add> $interval.flush(0); <add> expect(counterA).toBe(1); <add> expect(counterB).toBe(1); <add> })); <add> <add> <ide> it('should allow you to specify a number of iterations', inject(function($interval) { <ide> var counter = 0; <ide> $interval(function() {counter++;}, 1000, 2);
2
Javascript
Javascript
use lowercase in function names
800fc131b8af0806c38b28ce11aff0f9194a3f98
<ide><path>crypto.js <ide> var CipherTransformFactory = (function cipherTransformFactory() { <ide> <ide> function constructor(dict, fileId, password) { <ide> var filter = dict.get('Filter'); <del> if (!IsName(filter) || filter.name != 'Standard') <add> if (!isName(filter) || filter.name != 'Standard') <ide> error('unknown encryption method'); <ide> this.dict = dict; <ide> var algorithm = dict.get('V'); <del> if (!IsInt(algorithm) || <add> if (!isInt(algorithm) || <ide> (algorithm != 1 && algorithm != 2 && algorithm != 4)) <ide> error('unsupported encryption algorithm'); <ide> this.algorithm = algorithm; <ide> var keyLength = dict.get('Length') || 40; <del> if (!IsInt(keyLength) || <add> if (!isInt(keyLength) || <ide> keyLength < 40 || (keyLength % 8) != 0) <ide> error('invalid key length'); <ide> // prepare keys <ide><path>fonts.js <ide> var Font = (function Font() { <ide> encoding[i] = { <ide> unicode: i <= 0x1f || (i >= 127 && i <= 255) ? <ide> i + kCmapGlyphOffset : i, <del> width: IsNum(width) ? width : properties.defaultWidth <add> width: isNum(width) ? width : properties.defaultWidth <ide> }; <ide> } <ide> } else { <ide> CFF.prototype = { <ide> var cmd = map[command]; <ide> assert(cmd, 'Unknow command: ' + command); <ide> <del> if (IsArray(cmd)) <add> if (isArray(cmd)) <ide> charstring.splice(i++, 1, cmd[0], cmd[1]); <ide> else <ide> charstring[i] = cmd; <ide> CFF.prototype = { <ide> continue; <ide> var value = properties.private[field]; <ide> <del> if (IsArray(value)) { <add> if (isArray(value)) { <ide> data += self.encodeNumber(value[0]); <ide> for (var i = 1; i < value.length; i++) <ide> data += self.encodeNumber(value[i] - value[i - 1]); <ide> var Type2CFF = (function type2CFF() { <ide> var width = mapping.width; <ide> properties.glyphs[glyph] = properties.encoding[index] = { <ide> unicode: code, <del> width: IsNum(width) ? width : defaultWidth <add> width: isNum(width) ? width : defaultWidth <ide> }; <ide> <ide> charstrings.push({ <ide><path>pdf.js <ide> var RefSet = (function refSet() { <ide> return constructor; <ide> })(); <ide> <del>function IsBool(v) { <add>function isBool(v) { <ide> return typeof v == 'boolean'; <ide> } <ide> <del>function IsInt(v) { <add>function isInt(v) { <ide> return typeof v == 'number' && ((v | 0) == v); <ide> } <ide> <del>function IsNum(v) { <add>function isNum(v) { <ide> return typeof v == 'number'; <ide> } <ide> <del>function IsString(v) { <add>function isString(v) { <ide> return typeof v == 'string'; <ide> } <ide> <del>function IsNull(v) { <add>function isNull(v) { <ide> return v === null; <ide> } <ide> <del>function IsName(v) { <add>function isName(v) { <ide> return v instanceof Name; <ide> } <ide> <del>function IsCmd(v, cmd) { <add>function isCmd(v, cmd) { <ide> return v instanceof Cmd && (!cmd || v.cmd == cmd); <ide> } <ide> <del>function IsDict(v, type) { <add>function isDict(v, type) { <ide> return v instanceof Dict && (!type || v.get('Type').name == type); <ide> } <ide> <del>function IsArray(v) { <add>function isArray(v) { <ide> return v instanceof Array; <ide> } <ide> <del>function IsStream(v) { <add>function isStream(v) { <ide> return typeof v == 'object' && v != null && ('getChar' in v); <ide> } <ide> <del>function IsRef(v) { <add>function isRef(v) { <ide> return v instanceof Ref; <ide> } <ide> <del>function IsPDFFunction(v) { <add>function isPDFFunction(v) { <ide> var fnDict; <ide> if (typeof v != 'object') <ide> return false; <del> else if (IsDict(v)) <add> else if (isDict(v)) <ide> fnDict = v; <del> else if (IsStream(v)) <add> else if (isStream(v)) <ide> fnDict = v.dict; <ide> else <ide> return false; <ide> function IsPDFFunction(v) { <ide> <ide> var EOF = {}; <ide> <del>function IsEOF(v) { <add>function isEOF(v) { <ide> return v == EOF; <ide> } <ide> <ide> var None = {}; <ide> <del>function IsNone(v) { <add>function isNone(v) { <ide> return v == None; <ide> } <ide> <ide> var Lexer = (function lexer() { <ide> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx <ide> ]; <ide> <del> function ToHexDigit(ch) { <add> function toHexDigit(ch) { <ide> if (ch >= '0' && ch <= '9') <ide> return ch.charCodeAt(0) - 48; <ide> ch = ch.toUpperCase(); <ide> var Lexer = (function lexer() { <ide> stream.skip(); <ide> if (ch == '#') { <ide> ch = stream.lookChar(); <del> var x = ToHexDigit(ch); <add> var x = toHexDigit(ch); <ide> if (x != -1) { <ide> stream.skip(); <del> var x2 = ToHexDigit(stream.getChar()); <add> var x2 = toHexDigit(stream.getChar()); <ide> if (x2 == -1) <ide> error('Illegal digit in hex char in name: ' + x2); <ide> str += String.fromCharCode((x << 4) | x2); <ide> var Lexer = (function lexer() { <ide> } <ide> if (specialChars[ch.charCodeAt(0)] != 1) { <ide> var x, x2; <del> if ((x = ToHexDigit(ch)) == -1) <add> if ((x = toHexDigit(ch)) == -1) <ide> error('Illegal character in hex string: ' + ch); <ide> <ide> ch = stream.getChar(); <ide> while (specialChars[ch.charCodeAt(0)] == 1) <ide> ch = stream.getChar(); <ide> <del> if ((x2 = ToHexDigit(ch)) == -1) <add> if ((x2 = toHexDigit(ch)) == -1) <ide> error('Illegal character in hex string: ' + ch); <ide> <ide> str += String.fromCharCode((x << 4) | x2); <ide> var Parser = (function parserParser() { <ide> this.buf2 = this.lexer.getObj(); <ide> }, <ide> shift: function parserShift() { <del> if (IsCmd(this.buf2, 'ID')) { <add> if (isCmd(this.buf2, 'ID')) { <ide> this.buf1 = this.buf2; <ide> this.buf2 = null; <ide> // skip byte after ID <ide> var Parser = (function parserParser() { <ide> } <ide> }, <ide> getObj: function parserGetObj(cipherTransform) { <del> if (IsCmd(this.buf1, 'BI')) { // inline image <add> if (isCmd(this.buf1, 'BI')) { // inline image <ide> this.shift(); <ide> return this.makeInlineImage(cipherTransform); <ide> } <del> if (IsCmd(this.buf1, '[')) { // array <add> if (isCmd(this.buf1, '[')) { // array <ide> this.shift(); <ide> var array = []; <del> while (!IsCmd(this.buf1, ']') && !IsEOF(this.buf1)) <add> while (!isCmd(this.buf1, ']') && !isEOF(this.buf1)) <ide> array.push(this.getObj()); <del> if (IsEOF(this.buf1)) <add> if (isEOF(this.buf1)) <ide> error('End of file inside array'); <ide> this.shift(); <ide> return array; <ide> } <del> if (IsCmd(this.buf1, '<<')) { // dictionary or stream <add> if (isCmd(this.buf1, '<<')) { // dictionary or stream <ide> this.shift(); <ide> var dict = new Dict(); <del> while (!IsCmd(this.buf1, '>>') && !IsEOF(this.buf1)) { <del> if (!IsName(this.buf1)) { <add> while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) { <add> if (!isName(this.buf1)) { <ide> error('Dictionary key must be a name object'); <ide> } else { <ide> var key = this.buf1.name; <ide> this.shift(); <del> if (IsEOF(this.buf1)) <add> if (isEOF(this.buf1)) <ide> break; <ide> dict.set(key, this.getObj(cipherTransform)); <ide> } <ide> } <del> if (IsEOF(this.buf1)) <add> if (isEOF(this.buf1)) <ide> error('End of file inside dictionary'); <ide> <ide> // stream objects are not allowed inside content streams or <ide> // object streams <del> if (IsCmd(this.buf2, 'stream')) { <add> if (isCmd(this.buf2, 'stream')) { <ide> return this.allowStreams ? <ide> this.makeStream(dict, cipherTransform) : dict; <ide> } <ide> this.shift(); <ide> return dict; <ide> } <del> if (IsInt(this.buf1)) { // indirect reference or integer <add> if (isInt(this.buf1)) { // indirect reference or integer <ide> var num = this.buf1; <ide> this.shift(); <del> if (IsInt(this.buf1) && IsCmd(this.buf2, 'R')) { <add> if (isInt(this.buf1) && isCmd(this.buf2, 'R')) { <ide> var ref = new Ref(num, this.buf1); <ide> this.shift(); <ide> this.shift(); <ide> return ref; <ide> } <ide> return num; <ide> } <del> if (IsString(this.buf1)) { // string <add> if (isString(this.buf1)) { // string <ide> var str = this.buf1; <ide> this.shift(); <ide> if (cipherTransform) <ide> var Parser = (function parserParser() { <ide> <ide> // parse dictionary <ide> var dict = new Dict(); <del> while (!IsCmd(this.buf1, 'ID') && !IsEOF(this.buf1)) { <del> if (!IsName(this.buf1)) { <add> while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) { <add> if (!isName(this.buf1)) { <ide> error('Dictionary key must be a name object'); <ide> } else { <ide> var key = this.buf1.name; <ide> this.shift(); <del> if (IsEOF(this.buf1)) <add> if (isEOF(this.buf1)) <ide> break; <ide> dict.set(key, this.getObj(cipherTransform)); <ide> } <ide> var Parser = (function parserParser() { <ide> var xref = this.xref; <ide> if (xref) <ide> length = xref.fetchIfRef(length); <del> if (!IsInt(length)) { <add> if (!isInt(length)) { <ide> error('Bad ' + length + ' attribute in stream'); <ide> length = 0; <ide> } <ide> var Parser = (function parserParser() { <ide> stream.pos = pos + length; <ide> this.shift(); // '>>' <ide> this.shift(); // 'stream' <del> if (!IsCmd(this.buf1, 'endstream')) <add> if (!isCmd(this.buf1, 'endstream')) <ide> error('Missing endstream'); <ide> this.shift(); <ide> <ide> var Parser = (function parserParser() { <ide> filter: function parserFilter(stream, dict, length) { <ide> var filter = dict.get('Filter', 'F'); <ide> var params = dict.get('DecodeParms', 'DP'); <del> if (IsName(filter)) <add> if (isName(filter)) <ide> return this.makeFilter(stream, filter.name, length, params); <del> if (IsArray(filter)) { <add> if (isArray(filter)) { <ide> var filterArray = filter; <ide> var paramsArray = params; <ide> for (var i = 0, ii = filterArray.length; i < ii; ++i) { <ide> filter = filterArray[i]; <del> if (!IsName(filter)) <add> if (!isName(filter)) <ide> error('Bad filter name: ' + filter); <ide> else { <ide> params = null; <del> if (IsArray(paramsArray) && (i in paramsArray)) <add> if (isArray(paramsArray) && (i in paramsArray)) <ide> params = paramsArray[i]; <ide> stream = this.makeFilter(stream, filter.name, length, params); <ide> // after the first stream the length variable is invalid <ide> var Linearization = (function linearizationLinearization() { <ide> var obj2 = this.parser.getObj(); <ide> var obj3 = this.parser.getObj(); <ide> this.linDict = this.parser.getObj(); <del> if (IsInt(obj1) && IsInt(obj2) && IsCmd(obj3, 'obj') && <del> IsDict(this.linDict)) { <add> if (isInt(obj1) && isInt(obj2) && isCmd(obj3, 'obj') && <add> isDict(this.linDict)) { <ide> var obj = this.linDict.get('Linearized'); <del> if (!(IsNum(obj) && obj > 0)) <add> if (!(isNum(obj) && obj > 0)) <ide> this.linDict = null; <ide> } <ide> } <ide> var Linearization = (function linearizationLinearization() { <ide> getInt: function linearizationGetInt(name) { <ide> var linDict = this.linDict; <ide> var obj; <del> if (IsDict(linDict) && <del> IsInt(obj = linDict.get(name)) && <add> if (isDict(linDict) && <add> isInt(obj = linDict.get(name)) && <ide> obj > 0) { <ide> return obj; <ide> } <ide> var Linearization = (function linearizationLinearization() { <ide> getHint: function linearizationGetHint(index) { <ide> var linDict = this.linDict; <ide> var obj1, obj2; <del> if (IsDict(linDict) && <del> IsArray(obj1 = linDict.get('H')) && <add> if (isDict(linDict) && <add> isArray(obj1 = linDict.get('H')) && <ide> obj1.length >= 2 && <del> IsInt(obj2 = obj1[index]) && <add> isInt(obj2 = obj1[index]) && <ide> obj2 > 0) { <ide> return obj2; <ide> } <ide> error('Hints table in linearization table is invalid: ' + index); <ide> return 0; <ide> }, <ide> get length() { <del> if (!IsDict(this.linDict)) <add> if (!isDict(this.linDict)) <ide> return 0; <ide> return this.getInt('L'); <ide> }, <ide> var XRef = (function xRefXRef() { <ide> } <ide> <ide> // get the root dictionary (catalog) object <del> if (!IsRef(this.root = trailerDict.get('Root'))) <add> if (!isRef(this.root = trailerDict.get('Root'))) <ide> error('Invalid root reference'); <ide> } <ide> <ide> constructor.prototype = { <ide> readXRefTable: function readXRefTable(parser) { <ide> var obj; <ide> while (true) { <del> if (IsCmd(obj = parser.getObj(), 'trailer')) <add> if (isCmd(obj = parser.getObj(), 'trailer')) <ide> break; <del> if (!IsInt(obj)) <add> if (!isInt(obj)) <ide> error('Invalid XRef table'); <ide> var first = obj; <del> if (!IsInt(obj = parser.getObj())) <add> if (!isInt(obj = parser.getObj())) <ide> error('Invalid XRef table'); <ide> var n = obj; <ide> if (first < 0 || n < 0 || (first + n) != ((first + n) | 0)) <ide> error('Invalid XRef table: ' + first + ', ' + n); <ide> for (var i = first; i < first + n; ++i) { <ide> var entry = {}; <del> if (!IsInt(obj = parser.getObj())) <add> if (!isInt(obj = parser.getObj())) <ide> error('Invalid XRef table: ' + first + ', ' + n); <ide> entry.offset = obj; <del> if (!IsInt(obj = parser.getObj())) <add> if (!isInt(obj = parser.getObj())) <ide> error('Invalid XRef table: ' + first + ', ' + n); <ide> entry.gen = obj; <ide> obj = parser.getObj(); <del> if (IsCmd(obj, 'n')) { <add> if (isCmd(obj, 'n')) { <ide> entry.uncompressed = true; <del> } else if (IsCmd(obj, 'f')) { <add> } else if (isCmd(obj, 'f')) { <ide> entry.free = true; <ide> } else { <ide> error('Invalid XRef table: ' + first + ', ' + n); <ide> var XRef = (function xRefXRef() { <ide> <ide> // read the trailer dictionary <ide> var dict; <del> if (!IsDict(dict = parser.getObj())) <add> if (!isDict(dict = parser.getObj())) <ide> error('Invalid XRef table'); <ide> <ide> // get the 'Prev' pointer <ide> var prev; <ide> obj = dict.get('Prev'); <del> if (IsInt(obj)) { <add> if (isInt(obj)) { <ide> prev = obj; <del> } else if (IsRef(obj)) { <add> } else if (isRef(obj)) { <ide> // certain buggy PDF generators generate "/Prev NNN 0 R" instead <ide> // of "/Prev NNN" <ide> prev = obj.num; <ide> var XRef = (function xRefXRef() { <ide> } <ide> <ide> // check for 'XRefStm' key <del> if (IsInt(obj = dict.get('XRefStm'))) { <add> if (isInt(obj = dict.get('XRefStm'))) { <ide> var pos = obj; <ide> // ignore previously loaded xref streams (possible infinite recursion) <ide> if (!(pos in this.xrefstms)) { <ide> var XRef = (function xRefXRef() { <ide> var i, j; <ide> while (range.length > 0) { <ide> var first = range[0], n = range[1]; <del> if (!IsInt(first) || !IsInt(n)) <add> if (!isInt(first) || !isInt(n)) <ide> error('Invalid XRef range fields: ' + first + ', ' + n); <ide> var typeFieldWidth = byteWidths[0]; <ide> var offsetFieldWidth = byteWidths[1]; <ide> var generationFieldWidth = byteWidths[2]; <del> if (!IsInt(typeFieldWidth) || !IsInt(offsetFieldWidth) || <del> !IsInt(generationFieldWidth)) { <add> if (!isInt(typeFieldWidth) || !isInt(offsetFieldWidth) || <add> !isInt(generationFieldWidth)) { <ide> error('Invalid XRef entry fields length: ' + first + ', ' + n); <ide> } <ide> for (i = 0; i < n; ++i) { <ide> var XRef = (function xRefXRef() { <ide> range.splice(0, 2); <ide> } <ide> var prev = streamParameters.get('Prev'); <del> if (IsInt(prev)) <add> if (isInt(prev)) <ide> this.readXRef(prev); <ide> return streamParameters; <ide> }, <ide> var XRef = (function xRefXRef() { <ide> stream.pos = trailers[i]; <ide> var parser = new Parser(new Lexer(stream), true); <ide> var obj = parser.getObj(); <del> if (!IsCmd(obj, 'trailer')) <add> if (!isCmd(obj, 'trailer')) <ide> continue; <ide> // read the trailer dictionary <ide> var dict; <del> if (!IsDict(dict = parser.getObj())) <add> if (!isDict(dict = parser.getObj())) <ide> continue; <ide> // taking the first one with 'ID' <ide> if (dict.has('ID')) <ide> var XRef = (function xRefXRef() { <ide> var parser = new Parser(new Lexer(stream), true); <ide> var obj = parser.getObj(); <ide> // parse an old-style xref table <del> if (IsCmd(obj, 'xref')) <add> if (isCmd(obj, 'xref')) <ide> return this.readXRefTable(parser); <ide> // parse an xref stream <del> if (IsInt(obj)) { <del> if (!IsInt(parser.getObj()) || <del> !IsCmd(parser.getObj(), 'obj') || <del> !IsStream(obj = parser.getObj())) { <add> if (isInt(obj)) { <add> if (!isInt(parser.getObj()) || <add> !isCmd(parser.getObj(), 'obj') || <add> !isStream(obj = parser.getObj())) { <ide> error('Invalid XRef stream'); <ide> } <ide> return this.readXRefStream(obj); <ide> var XRef = (function xRefXRef() { <ide> return e; <ide> }, <ide> fetchIfRef: function xRefFetchIfRef(obj) { <del> if (!IsRef(obj)) <add> if (!isRef(obj)) <ide> return obj; <ide> return this.fetch(obj); <ide> }, <ide> var XRef = (function xRefXRef() { <ide> var obj1 = parser.getObj(); <ide> var obj2 = parser.getObj(); <ide> var obj3 = parser.getObj(); <del> if (!IsInt(obj1) || obj1 != num || <del> !IsInt(obj2) || obj2 != gen || <del> !IsCmd(obj3)) { <add> if (!isInt(obj1) || obj1 != num || <add> !isInt(obj2) || obj2 != gen || <add> !isCmd(obj3)) { <ide> error('bad XRef entry'); <ide> } <del> if (!IsCmd(obj3, 'obj')) { <add> if (!isCmd(obj3, 'obj')) { <ide> // some bad pdfs use "obj1234" and really mean 1234 <ide> if (obj3.cmd.indexOf('obj') == 0) { <ide> num = parseInt(obj3.cmd.substring(3), 10); <ide> var XRef = (function xRefXRef() { <ide> e = parser.getObj(); <ide> } <ide> // Don't cache streams since they are mutable. <del> if (!IsStream(e)) <add> if (!isStream(e)) <ide> this.cache[num] = e; <ide> return e; <ide> } <ide> <ide> // compressed entry <ide> stream = this.fetch(new Ref(e.offset, 0)); <del> if (!IsStream(stream)) <add> if (!isStream(stream)) <ide> error('bad ObjStm stream'); <ide> var first = stream.parameters.get('First'); <ide> var n = stream.parameters.get('N'); <del> if (!IsInt(first) || !IsInt(n)) { <add> if (!isInt(first) || !isInt(n)) { <ide> error('invalid first and n parameters for ObjStm stream'); <ide> } <ide> parser = new Parser(new Lexer(stream), false); <ide> var i, entries = [], nums = []; <ide> // read the object numbers to populate cache <ide> for (i = 0; i < n; ++i) { <ide> num = parser.getObj(); <del> if (!IsInt(num)) { <add> if (!isInt(num)) { <ide> error('invalid object number in the ObjStm stream: ' + num); <ide> } <ide> nums.push(num); <ide> var offset = parser.getObj(); <del> if (!IsInt(offset)) { <add> if (!isInt(offset)) { <ide> error('invalid object offset in the ObjStm stream: ' + offset); <ide> } <ide> } <ide> var Page = (function pagePage() { <ide> get mediaBox() { <ide> var obj = this.inheritPageProp('MediaBox'); <ide> // Reset invalid media box to letter size. <del> if (!IsArray(obj) || obj.length !== 4) <add> if (!isArray(obj) || obj.length !== 4) <ide> obj = [0, 0, 612, 792]; <ide> return shadow(this, 'mediaBox', obj); <ide> }, <ide> var Page = (function pagePage() { <ide> width: this.width, <ide> height: this.height <ide> }; <del> if (IsArray(obj) && obj.length == 4) { <add> if (isArray(obj) && obj.length == 4) { <ide> var rotate = this.rotate; <ide> if (rotate == 0 || rotate == 180) { <ide> view.x = obj[0]; <ide> var Page = (function pagePage() { <ide> var xref = this.xref; <ide> var content = xref.fetchIfRef(this.content); <ide> var resources = xref.fetchIfRef(this.resources); <del> if (IsArray(content)) { <add> if (isArray(content)) { <ide> // fetching items <ide> var i, n = content.length; <ide> for (i = 0; i < n; ++i) <ide> var Page = (function pagePage() { <ide> var xref = this.xref; <ide> var resources = xref.fetchIfRef(this.resources); <ide> var mediaBox = xref.fetchIfRef(this.mediaBox); <del> assertWellFormed(IsDict(resources), 'invalid page resources'); <add> assertWellFormed(isDict(resources), 'invalid page resources'); <ide> gfx.beginDrawing({ x: mediaBox[0], y: mediaBox[1], <ide> width: this.width, <ide> height: this.height, <ide> var Page = (function pagePage() { <ide> var links = []; <ide> for (i = 0; i < n; ++i) { <ide> var annotation = xref.fetch(annotations[i]); <del> if (!IsDict(annotation)) <add> if (!isDict(annotation)) <ide> continue; <ide> var subtype = annotation.get('Subtype'); <del> if (!IsName(subtype) || subtype.name != 'Link') <add> if (!isName(subtype) || subtype.name != 'Link') <ide> continue; <ide> var rect = annotation.get('Rect'); <ide> var topLeftCorner = this.rotatePoint(rect[0], rect[1]); <ide> var Page = (function pagePage() { <ide> } else if (annotation.has('Dest')) { <ide> // simple destination link <ide> var dest = annotation.get('Dest'); <del> link.dest = IsName(dest) ? dest.name : dest; <add> link.dest = isName(dest) ? dest.name : dest; <ide> } <ide> links.push(link); <ide> } <ide> var Catalog = (function catalogCatalog() { <ide> function constructor(xref) { <ide> this.xref = xref; <ide> var obj = xref.getCatalogObj(); <del> assertWellFormed(IsDict(obj), 'catalog object is not a dictionary'); <add> assertWellFormed(isDict(obj), 'catalog object is not a dictionary'); <ide> this.catDict = obj; <ide> } <ide> <ide> constructor.prototype = { <ide> get toplevelPagesDict() { <ide> var pagesObj = this.catDict.get('Pages'); <del> assertWellFormed(IsRef(pagesObj), 'invalid top-level pages reference'); <add> assertWellFormed(isRef(pagesObj), 'invalid top-level pages reference'); <ide> var xrefObj = this.xref.fetch(pagesObj); <del> assertWellFormed(IsDict(xrefObj), 'invalid top-level pages dictionary'); <add> assertWellFormed(isDict(xrefObj), 'invalid top-level pages dictionary'); <ide> // shadow the prototype getter <ide> return shadow(this, 'toplevelPagesDict', xrefObj); <ide> }, <ide> get documentOutline() { <ide> var obj = this.catDict.get('Outlines'); <ide> var xref = this.xref; <ide> var root = { items: [] }; <del> if (IsRef(obj)) { <add> if (isRef(obj)) { <ide> obj = xref.fetch(obj).get('First'); <ide> var processed = new RefSet(); <del> if (IsRef(obj)) { <add> if (isRef(obj)) { <ide> var queue = [{obj: obj, parent: root}]; <ide> // to avoid recursion keeping track of the items <ide> // in the processed dictionary <ide> var Catalog = (function catalogCatalog() { <ide> dest = xref.fetchIfRef(dest).get('D'); <ide> else if (outlineDict.has('Dest')) { <ide> dest = outlineDict.get('Dest'); <del> if (IsName(dest)) <add> if (isName(dest)) <ide> dest = dest.name; <ide> } <ide> var title = xref.fetchIfRef(outlineDict.get('Title')); <ide> var Catalog = (function catalogCatalog() { <ide> }; <ide> i.parent.items.push(outlineItem); <ide> obj = outlineDict.get('First'); <del> if (IsRef(obj) && !processed.has(obj)) { <add> if (isRef(obj) && !processed.has(obj)) { <ide> queue.push({obj: obj, parent: outlineItem}); <ide> processed.put(obj); <ide> } <ide> obj = outlineDict.get('Next'); <del> if (IsRef(obj) && !processed.has(obj)) { <add> if (isRef(obj) && !processed.has(obj)) { <ide> queue.push({obj: obj, parent: i.parent}); <ide> processed.put(obj); <ide> } <ide> var Catalog = (function catalogCatalog() { <ide> get numPages() { <ide> var obj = this.toplevelPagesDict.get('Count'); <ide> assertWellFormed( <del> IsInt(obj), <add> isInt(obj), <ide> 'page count in top level pages object is not an integer' <ide> ); <ide> // shadow the prototype getter <ide> var Catalog = (function catalogCatalog() { <ide> traverseKids: function catalogTraverseKids(pagesDict) { <ide> var pageCache = this.pageCache; <ide> var kids = pagesDict.get('Kids'); <del> assertWellFormed(IsArray(kids), <add> assertWellFormed(isArray(kids), <ide> 'page dictionary kids object is not an array'); <ide> for (var i = 0; i < kids.length; ++i) { <ide> var kid = kids[i]; <del> assertWellFormed(IsRef(kid), <add> assertWellFormed(isRef(kid), <ide> 'page dictionary kid is not a reference'); <ide> var obj = this.xref.fetch(kid); <del> if (IsDict(obj, 'Page') || (IsDict(obj) && !obj.has('Kids'))) { <add> if (isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids'))) { <ide> pageCache.push(new Page(this.xref, pageCache.length, obj, kid)); <ide> } else { // must be a child page dictionary <ide> assertWellFormed( <del> IsDict(obj), <add> isDict(obj), <ide> 'page dictionary kid reference points to wrong type of object' <ide> ); <ide> this.traverseKids(obj); <ide> var Catalog = (function catalogCatalog() { <ide> get destinations() { <ide> function fetchDestination(xref, ref) { <ide> var dest = xref.fetchIfRef(ref); <del> return IsDict(dest) ? dest.get('D') : dest; <add> return isDict(dest) ? dest.get('D') : dest; <ide> } <ide> <ide> var xref = this.xref; <ide> var PartialEvaluator = (function partialEvaluator() { <ide> var parser = new Parser(new Lexer(stream), false); <ide> var args = [], argsArray = [], fnArray = [], obj; <ide> <del> while (!IsEOF(obj = parser.getObj())) { <del> if (IsCmd(obj)) { <add> while (!isEOF(obj = parser.getObj())) { <add> if (isCmd(obj)) { <ide> var cmd = obj.cmd; <ide> var fn = OP_MAP[cmd]; <ide> assertWellFormed(fn, "Unknown command '" + cmd + "'"); <ide> var PartialEvaluator = (function partialEvaluator() { <ide> // compile tiling patterns <ide> var patternName = args[args.length - 1]; <ide> // SCN/scn applies patterns along with normal colors <del> if (IsName(patternName)) { <add> if (isName(patternName)) { <ide> var pattern = xref.fetchIfRef(patterns.get(patternName.name)); <ide> if (pattern) { <del> var dict = IsStream(pattern) ? pattern.dict : pattern; <add> var dict = isStream(pattern) ? pattern.dict : pattern; <ide> var typeNum = dict.get('PatternType'); <ide> if (typeNum == 1) { <ide> patternName.code = this.evaluate(pattern, xref, <ide> var PartialEvaluator = (function partialEvaluator() { <ide> var xobj = xobjs.get(name); <ide> if (xobj) { <ide> xobj = xref.fetchIfRef(xobj); <del> assertWellFormed(IsStream(xobj), 'XObject should be a stream'); <add> assertWellFormed(isStream(xobj), 'XObject should be a stream'); <ide> <ide> var type = xobj.dict.get('Subtype'); <ide> assertWellFormed( <del> IsName(type), <add> isName(type), <ide> 'XObject should have a Name subtype' <ide> ); <ide> <ide> var PartialEvaluator = (function partialEvaluator() { <ide> if (fontRes) { <ide> fontRes = xref.fetchIfRef(fontRes); <ide> var font = xref.fetchIfRef(fontRes.get(args[0].name)); <del> assertWellFormed(IsDict(font)); <add> assertWellFormed(isDict(font)); <ide> if (!font.translated) { <ide> font.translated = this.translateFont(font, xref, resources); <ide> if (fonts && font.translated) { <ide> var PartialEvaluator = (function partialEvaluator() { <ide> var start = 0, end = 0; <ide> for (var i = 0; i < widths.length; i++) { <ide> var code = widths[i]; <del> if (IsArray(code)) { <add> if (isArray(code)) { <ide> for (var j = 0; j < code.length; j++) <ide> glyphsWidths[start++] = code[j]; <ide> start = 0; <ide> var PartialEvaluator = (function partialEvaluator() { <ide> properties.widths = glyphsWidths; <ide> <ide> var cidToGidMap = dict.get('CIDToGIDMap'); <del> if (!cidToGidMap || !IsRef(cidToGidMap)) { <add> if (!cidToGidMap || !isRef(cidToGidMap)) { <ide> return Object.create(GlyphsUnicode); <ide> } <ide> <ide> var PartialEvaluator = (function partialEvaluator() { <ide> var width = glyphsWidths[code]; <ide> encoding[code] = { <ide> unicode: glyphID, <del> width: IsNum(width) ? width : defaultWidth <add> width: isNum(width) ? width : defaultWidth <ide> }; <ide> } <ide> } else if (type == 'CIDFontType0') { <del> if (IsName(encoding)) { <add> if (isName(encoding)) { <ide> // Encoding is a predefined CMap <ide> if (encoding.name == 'Identity-H') { <ide> TODO('Need to create an identity cmap'); <ide> var PartialEvaluator = (function partialEvaluator() { <ide> var baseEncoding = null; <ide> if (dict.has('Encoding')) { <ide> encoding = xref.fetchIfRef(dict.get('Encoding')); <del> if (IsDict(encoding)) { <add> if (isDict(encoding)) { <ide> var baseName = encoding.get('BaseEncoding'); <ide> if (baseName) <ide> baseEncoding = Encodings[baseName.name].slice(); <ide> var PartialEvaluator = (function partialEvaluator() { <ide> var index = 0; <ide> for (var j = 0; j < diffEncoding.length; j++) { <ide> var data = diffEncoding[j]; <del> if (IsNum(data)) <add> if (isNum(data)) <ide> index = data; <ide> else <ide> differences[index++] = data.name; <ide> } <ide> } <del> } else if (IsName(encoding)) { <add> } else if (isName(encoding)) { <ide> baseEncoding = Encodings[encoding.name].slice(); <ide> } else { <ide> error('Encoding is not a Name nor a Dict'); <ide> var PartialEvaluator = (function partialEvaluator() { <ide> var width = widths[i] || widths[glyph]; <ide> map[i] = { <ide> unicode: index, <del> width: IsNum(width) ? width : properties.defaultWidth <add> width: isNum(width) ? width : properties.defaultWidth <ide> }; <ide> <ide> if (glyph) <ide> var PartialEvaluator = (function partialEvaluator() { <ide> <ide> if (type == 'TrueType' && dict.has('ToUnicode') && differences) { <ide> var cmapObj = dict.get('ToUnicode'); <del> if (IsRef(cmapObj)) { <add> if (isRef(cmapObj)) { <ide> cmapObj = xref.fetch(cmapObj); <ide> } <del> if (IsName(cmapObj)) { <add> if (isName(cmapObj)) { <ide> error('ToUnicode file cmap translation not implemented'); <del> } else if (IsStream(cmapObj)) { <add> } else if (isStream(cmapObj)) { <ide> var tokens = []; <ide> var token = ''; <ide> var beginArrayToken = {}; <ide> var PartialEvaluator = (function partialEvaluator() { <ide> <ide> var defaultWidth = 0; <ide> var widths = Metrics[stdFontMap[name] || name]; <del> if (IsNum(widths)) { <add> if (isNum(widths)) { <ide> defaultWidth = widths; <ide> widths = null; <ide> } <ide> var PartialEvaluator = (function partialEvaluator() { <ide> resources) { <ide> var baseDict = dict; <ide> var type = dict.get('Subtype'); <del> assertWellFormed(IsName(type), 'invalid font Subtype'); <add> assertWellFormed(isName(type), 'invalid font Subtype'); <ide> <ide> var composite = false; <ide> if (type.name == 'Type0') { <ide> var PartialEvaluator = (function partialEvaluator() { <ide> if (!df) <ide> return null; <ide> <del> if (IsRef(df)) <add> if (isRef(df)) <ide> df = xref.fetch(df); <ide> <del> dict = xref.fetch(IsRef(df) ? df : df[0]); <add> dict = xref.fetch(isRef(df) ? df : df[0]); <ide> <ide> type = dict.get('Subtype'); <del> assertWellFormed(IsName(type), 'invalid font Subtype'); <add> assertWellFormed(isName(type), 'invalid font Subtype'); <ide> composite = true; <ide> } <ide> <ide> var PartialEvaluator = (function partialEvaluator() { <ide> var descriptor = xref.fetchIfRef(dict.get('FontDescriptor')); <ide> if (!descriptor) { <ide> var baseFontName = dict.get('BaseFont'); <del> if (!IsName(baseFontName)) <add> if (!isName(baseFontName)) <ide> return null; <ide> <ide> // Using base font name as a font name. <ide> var PartialEvaluator = (function partialEvaluator() { <ide> } else { <ide> // Trying get the BaseFont metrics (see comment above). <ide> var baseFontName = dict.get('BaseFont'); <del> if (IsName(baseFontName)) { <add> if (isName(baseFontName)) { <ide> var metricsAndMap = this.getBaseFontMetricsAndMap(baseFontName.name); <ide> <ide> glyphWidths = metricsAndMap.widths; <ide> var PartialEvaluator = (function partialEvaluator() { <ide> } <ide> <ide> var fontName = xref.fetchIfRef(descriptor.get('FontName')); <del> assertWellFormed(IsName(fontName), 'invalid font name'); <add> assertWellFormed(isName(fontName), 'invalid font name'); <ide> <ide> var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3'); <ide> if (fontFile) { <ide> var PartialEvaluator = (function partialEvaluator() { <ide> subtype = subtype.name; <ide> <ide> var length1 = fontFile.dict.get('Length1'); <del> if (!IsInt(length1)) <add> if (!isInt(length1)) <ide> length1 = xref.fetchIfRef(length1); <ide> <ide> var length2 = fontFile.dict.get('Length2'); <del> if (!IsInt(length2)) <add> if (!isInt(length2)) <ide> length2 = xref.fetchIfRef(length2); <ide> } <ide> } <ide> var CanvasGraphics = (function canvasGraphics() { <ide> }, <ide> setGState: function canvasGraphicsSetGState(dictName) { <ide> var extGState = this.xref.fetchIfRef(this.res.get('ExtGState')); <del> if (IsDict(extGState) && extGState.has(dictName.name)) { <add> if (isDict(extGState) && extGState.has(dictName.name)) { <ide> var gsState = this.xref.fetchIfRef(extGState.get(dictName.name)); <ide> var self = this; <ide> gsState.forEach(function canvasGraphicsSetGStateForEach(key, value) { <ide> var CanvasGraphics = (function canvasGraphics() { <ide> setFont: function canvasGraphicsSetFont(fontRef, size) { <ide> var font; <ide> // the tf command uses a name, but graphics state uses a reference <del> if (IsName(fontRef)) { <add> if (isName(fontRef)) { <ide> font = this.xref.fetchIfRef(this.res.get('Font')); <del> if (!IsDict(font)) <add> if (!isDict(font)) <ide> return; <ide> <ide> font = font.get(fontRef.name); <del> } else if (IsRef(fontRef)) { <add> } else if (isRef(fontRef)) { <ide> font = fontRef; <ide> } <ide> font = this.xref.fetchIfRef(font); <ide> var CanvasGraphics = (function canvasGraphics() { <ide> var arrLength = arr.length; <ide> for (var i = 0; i < arrLength; ++i) { <ide> var e = arr[i]; <del> if (IsNum(e)) { <add> if (isNum(e)) { <ide> if (ctx.$addCurrentX) { <ide> ctx.$addCurrentX(-e * 0.001 * fontSize); <ide> } else { <ide> current.x -= e * 0.001 * fontSize * textHScale; <ide> } <del> } else if (IsString(e)) { <add> } else if (isString(e)) { <ide> this.showText(e); <ide> } else { <ide> malformed('TJ array element ' + e + ' is not string or num'); <ide> var CanvasGraphics = (function canvasGraphics() { <ide> if (!xobj) <ide> return; <ide> xobj = this.xref.fetchIfRef(xobj); <del> assertWellFormed(IsStream(xobj), 'XObject should be a stream'); <add> assertWellFormed(isStream(xobj), 'XObject should be a stream'); <ide> <ide> var oc = xobj.dict.get('OC'); <ide> if (oc) { <ide> var CanvasGraphics = (function canvasGraphics() { <ide> } <ide> <ide> var type = xobj.dict.get('Subtype'); <del> assertWellFormed(IsName(type), 'XObject should have a Name subtype'); <add> assertWellFormed(isName(type), 'XObject should have a Name subtype'); <ide> if ('Image' == type.name) { <ide> this.paintImageXObject(obj, xobj, false); <ide> } else if ('Form' == type.name) { <ide> var CanvasGraphics = (function canvasGraphics() { <ide> this.save(); <ide> <ide> var matrix = stream.dict.get('Matrix'); <del> if (matrix && IsArray(matrix) && 6 == matrix.length) <add> if (matrix && isArray(matrix) && 6 == matrix.length) <ide> this.transform.apply(this, matrix); <ide> <ide> var bbox = stream.dict.get('BBox'); <del> if (bbox && IsArray(bbox) && 4 == bbox.length) { <add> if (bbox && isArray(bbox) && 4 == bbox.length) { <ide> this.rectangle.apply(this, bbox); <ide> this.clip(); <ide> this.endPath(); <ide> var ColorSpace = (function colorSpaceColorSpace() { <ide> }; <ide> <ide> constructor.parse = function colorspace_parse(cs, xref, res) { <del> if (IsName(cs)) { <add> if (isName(cs)) { <ide> var colorSpaces = xref.fetchIfRef(res.get('ColorSpace')); <del> if (IsDict(colorSpaces)) { <add> if (isDict(colorSpaces)) { <ide> var refcs = colorSpaces.get(cs.name); <ide> if (refcs) <ide> cs = refcs; <ide> var ColorSpace = (function colorSpaceColorSpace() { <ide> <ide> cs = xref.fetchIfRef(cs); <ide> <del> if (IsName(cs)) { <add> if (isName(cs)) { <ide> var mode = cs.name; <ide> this.mode = mode; <ide> <ide> var ColorSpace = (function colorSpaceColorSpace() { <ide> default: <ide> error('unrecognized colorspace ' + mode); <ide> } <del> } else if (IsArray(cs)) { <add> } else if (isArray(cs)) { <ide> var mode = cs[0].name; <ide> this.mode = mode; <ide> <ide> var IndexedCS = (function indexedCS() { <ide> <ide> var length = baseNumComps * highVal; <ide> var lookupArray = new Uint8Array(length); <del> if (IsStream(lookup)) { <add> if (isStream(lookup)) { <ide> var bytes = lookup.getBytes(length); <ide> lookupArray.set(bytes); <del> } else if (IsString(lookup)) { <add> } else if (isString(lookup)) { <ide> for (var i = 0; i < length; ++i) <ide> lookupArray[i] = lookup.charCodeAt(i); <ide> } else { <ide> var Pattern = (function patternPattern() { <ide> var length = args.length; <ide> <ide> var patternName = args[length - 1]; <del> if (!IsName(patternName)) <add> if (!isName(patternName)) <ide> error('Bad args to getPattern: ' + patternName); <ide> <ide> var patternRes = xref.fetchIfRef(res.get('Pattern')); <ide> if (!patternRes) <ide> error('Unable to find pattern resource'); <ide> <ide> var pattern = xref.fetchIfRef(patternRes.get(patternName.name)); <del> var dict = IsStream(pattern) ? pattern.dict : pattern; <add> var dict = isStream(pattern) ? pattern.dict : pattern; <ide> var typeNum = dict.get('PatternType'); <ide> <ide> switch (typeNum) { <ide> var Pattern = (function patternPattern() { <ide> constructor.parseShading = function pattern_shading(shading, matrix, <ide> xref, res, ctx) { <ide> <del> var dict = IsStream(shading) ? shading.dict : shading; <add> var dict = isStream(shading) ? shading.dict : shading; <ide> var type = dict.get('ShadingType'); <ide> <ide> switch (type) { <ide> var RadialAxialShading = (function radialAxialShading() { <ide> <ide> var fnObj = dict.get('Function'); <ide> fnObj = xref.fetchIfRef(fnObj); <del> if (IsArray(fnObj)) <add> if (isArray(fnObj)) <ide> error('No support for array of functions'); <del> else if (!IsPDFFunction(fnObj)) <add> else if (!isPDFFunction(fnObj)) <ide> error('Invalid function'); <ide> var fn = new PDFFunction(xref, fnObj); <ide> <ide> var TilingPattern = (function tilingPattern() { <ide> graphics.transform.apply(graphics, tmpScale); <ide> graphics.transform.apply(graphics, tmpTranslate); <ide> <del> if (bbox && IsArray(bbox) && 4 == bbox.length) { <add> if (bbox && isArray(bbox) && 4 == bbox.length) { <ide> graphics.rectangle.apply(graphics, bbox); <ide> graphics.clip(); <ide> graphics.endPath(); <ide> var PDFFunction = (function pdfFunction() { <ide> var c1 = dict.get('C1') || [1]; <ide> var n = dict.get('N'); <ide> <del> if (!IsArray(c0) || !IsArray(c1)) <add> if (!isArray(c0) || !isArray(c1)) <ide> error('Illegal dictionary for interpolated function'); <ide> <ide> var length = c0.length; <ide><path>utils/fonts_utils.js <ide> var Type2Parser = function(aFilePath) { <ide> var count = decoded.length; <ide> for (var i = 0; i < count; i++) { <ide> var token = decoded[i]; <del> if (IsNum(token)) { <add> if (isNum(token)) { <ide> stack.push(token); <ide> } else { <ide> switch (token.operand) {
4
Mixed
Ruby
add headless firefox driver to system tests
82b974813b28748e5affcff1d8c4ad60ab2971be
<ide><path>actionpack/CHANGELOG.md <add>* Add headless firefox support to System Tests. <add> <add> *bogdanvlviv* <add> <ide> * Changed the default system test screenshot output from `inline` to `simple`. <ide> <ide> `inline` works well for iTerm2 but not everyone uses iTerm2. Some terminals like <ide><path>actionpack/lib/action_dispatch/system_test_case.rb <ide> def self.start_application # :nodoc: <ide> # <ide> # driven_by :poltergeist <ide> # <del> # driven_by :selenium, using: :firefox <add> # driven_by :selenium, screen_size: [800, 800] <add> # <add> # driven_by :selenium, using: :chrome <ide> # <ide> # driven_by :selenium, using: :headless_chrome <ide> # <del> # driven_by :selenium, screen_size: [800, 800] <add> # driven_by :selenium, using: :firefox <add> # <add> # driven_by :selenium, using: :headless_firefox <ide> def self.driven_by(driver, using: :chrome, screen_size: [1400, 1400], options: {}) <ide> self.driver = SystemTesting::Driver.new(driver, using: using, screen_size: screen_size, options: options) <ide> end <ide><path>actionpack/lib/action_dispatch/system_testing/driver.rb <ide> def browser_options <ide> browser_options.args << "--headless" <ide> browser_options.args << "--disable-gpu" <ide> <add> @options.merge(options: browser_options) <add> elsif @browser == :headless_firefox <add> browser_options = Selenium::WebDriver::Firefox::Options.new <add> browser_options.args << "-headless" <add> <ide> @options.merge(options: browser_options) <ide> else <ide> @options <ide> end <ide> end <ide> <ide> def browser <del> @browser == :headless_chrome ? :chrome : @browser <add> if @browser == :headless_chrome <add> :chrome <add> elsif @browser == :headless_firefox <add> :firefox <add> else <add> @browser <add> end <ide> end <ide> <ide> def register_selenium(app) <ide><path>actionpack/test/abstract_unit.rb <ide> class DrivenBySeleniumWithChrome < ActionDispatch::SystemTestCase <ide> class DrivenBySeleniumWithHeadlessChrome < ActionDispatch::SystemTestCase <ide> driven_by :selenium, using: :headless_chrome <ide> end <add> <add>class DrivenBySeleniumWithHeadlessFirefox < ActionDispatch::SystemTestCase <add> driven_by :selenium, using: :headless_firefox <add>end <ide><path>actionpack/test/dispatch/system_testing/driver_test.rb <ide> class DriverTest < ActiveSupport::TestCase <ide> assert_equal ({ url: "http://example.com/wd/hub" }), driver.instance_variable_get(:@options) <ide> end <ide> <add> test "initializing the driver with a headless firefox" do <add> driver = ActionDispatch::SystemTesting::Driver.new(:selenium, using: :headless_firefox, screen_size: [1400, 1400], options: { url: "http://example.com/wd/hub" }) <add> assert_equal :selenium, driver.instance_variable_get(:@name) <add> assert_equal :headless_firefox, driver.instance_variable_get(:@browser) <add> assert_equal [1400, 1400], driver.instance_variable_get(:@screen_size) <add> assert_equal ({ url: "http://example.com/wd/hub" }), driver.instance_variable_get(:@options) <add> end <add> <ide> test "initializing the driver with a poltergeist" do <ide> driver = ActionDispatch::SystemTesting::Driver.new(:poltergeist, screen_size: [1400, 1400], options: { js_errors: false }) <ide> assert_equal :poltergeist, driver.instance_variable_get(:@name) <ide><path>actionpack/test/dispatch/system_testing/system_test_case_test.rb <ide> class SetDriverToSeleniumHeadlessChromeTest < DrivenBySeleniumWithHeadlessChrome <ide> end <ide> end <ide> <add>class SetDriverToSeleniumHeadlessFirefoxTest < DrivenBySeleniumWithHeadlessFirefox <add> test "uses selenium headless firefox" do <add> assert_equal :selenium, Capybara.current_driver <add> end <add>end <add> <ide> class SetHostTest < DrivenByRackTest <ide> test "sets default host" do <ide> assert_equal "http://127.0.0.1", Capybara.app_host <ide><path>guides/source/testing.md <ide> class ApplicationSystemTestCase < ActionDispatch::SystemTestCase <ide> end <ide> ``` <ide> <del>If you want to use a headless browser, you could use Headless Chrome by adding `headless_chrome` in the `:using` argument. <add>If you want to use a headless browser, you could use Headless Chrome or Headless Firefox by adding <add>`headless_chrome` or `headless_firefox` in the `:using` argument. <ide> <ide> ```ruby <ide> require "test_helper"
7
Javascript
Javascript
increase getreport() coverage
9d44950539e51461ede6fc04b63fb97d033f5468
<ide><path>test/node-report/test-api-getreport.js <ide> const helper = require('../common/report'); <ide> common.expectWarning('ExperimentalWarning', <ide> 'report is an experimental feature. This feature could ' + <ide> 'change at any time'); <del>helper.validateContent(process.report.getReport()); <del>assert.deepStrictEqual(helper.findReports(process.pid, process.cwd()), []); <add> <add>{ <add> // Test with no arguments. <add> helper.validateContent(process.report.getReport()); <add> assert.deepStrictEqual(helper.findReports(process.pid, process.cwd()), []); <add>} <add> <add>{ <add> // Test with an error argument. <add> helper.validateContent(process.report.getReport(new Error('test error'))); <add> assert.deepStrictEqual(helper.findReports(process.pid, process.cwd()), []); <add>} <add> <add>// Test with an invalid error argument. <add>[null, 1, Symbol(), function() {}, 'foo'].forEach((error) => { <add> common.expectsError(() => { <add> process.report.getReport(error); <add> }, { code: 'ERR_INVALID_ARG_TYPE' }); <add>});
1
PHP
PHP
fix incorrect handling of url in path
6a31a7b2b31f293f9c102ac73041652bf702f392
<ide><path>src/Network/Request.php <ide> protected static function _url($config) <ide> if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '://') === false) { <ide> $uri = $_SERVER['REQUEST_URI']; <ide> } elseif (isset($_SERVER['REQUEST_URI'])) { <del> $qPosition = strpos($_SERVER['REQUEST_URI'], '?'); <del> if ($qPosition !== false && strpos($_SERVER['REQUEST_URI'], '://') > $qPosition) { <del> $uri = $_SERVER['REQUEST_URI']; <del> } else { <del> $uri = substr($_SERVER['REQUEST_URI'], strlen(Configure::read('App.fullBaseUrl'))); <add> $uri = $_SERVER['REQUEST_URI']; <add> $fullBaseUrl = Configure::read('App.fullBaseUrl'); <add> if (strpos($uri, $fullBaseUrl) === 0) { <add> $uri = substr($_SERVER['REQUEST_URI'], strlen($fullBaseUrl)); <ide> } <ide> } elseif (isset($_SERVER['PHP_SELF'], $_SERVER['SCRIPT_NAME'])) { <ide> $uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']); <ide><path>tests/TestCase/Network/RequestTest.php <ide> public function testQueryStringAndNamedParams() <ide> $this->assertEquals('other/path', $request->url); <ide> } <ide> <add> /** <add> * Test that URL in path is handled correctly. <add> */ <add> public function testUrlInPath() <add> { <add> $_SERVER['REQUEST_URI'] = '/jump/http://cakephp.org'; <add> $request = Request::createFromGlobals(); <add> $this->assertEquals('jump/http://cakephp.org', $request->url); <add> <add> $_SERVER['REQUEST_URI'] = Configure::read('App.fullBaseUrl') . '/jump/http://cakephp.org'; <add> $request = Request::createFromGlobals(); <add> $this->assertEquals('jump/http://cakephp.org', $request->url); <add> } <add> <ide> /** <ide> * Test addParams() method <ide> *
2
Javascript
Javascript
name anonymous functions
cb45374c31dc57e4610dfb1e7336a6ceb4d362b4
<ide><path>lib/_http_agent.js <ide> Agent.defaultMaxSockets = Infinity; <ide> Agent.prototype.createConnection = net.createConnection; <ide> <ide> // Get the key for a given set of request options <del>Agent.prototype.getName = function(options) { <add>Agent.prototype.getName = function getName(options) { <ide> var name = options.host || 'localhost'; <ide> <ide> name += ':'; <ide> Agent.prototype.getName = function(options) { <ide> return name; <ide> }; <ide> <del>Agent.prototype.addRequest = function(req, options) { <add>Agent.prototype.addRequest = function addRequest(req, options) { <ide> // Legacy API: addRequest(req, host, port, localAddress) <ide> if (typeof options === 'string') { <ide> options = { <ide> Agent.prototype.addRequest = function(req, options) { <ide> } <ide> }; <ide> <del>Agent.prototype.createSocket = function(req, options, cb) { <add>Agent.prototype.createSocket = function createSocket(req, options, cb) { <ide> var self = this; <ide> options = util._extend({}, options); <ide> options = util._extend(options, self.options); <ide> Agent.prototype.createSocket = function(req, options, cb) { <ide> } <ide> }; <ide> <del>Agent.prototype.removeSocket = function(s, options) { <add>Agent.prototype.removeSocket = function removeSocket(s, options) { <ide> var name = this.getName(options); <ide> debug('removeSocket', name, 'writable:', s.writable); <ide> var sets = [this.sockets]; <ide> Agent.prototype.removeSocket = function(s, options) { <ide> } <ide> }; <ide> <del>Agent.prototype.destroy = function() { <add>Agent.prototype.destroy = function destroy() { <ide> var sets = [this.freeSockets, this.sockets]; <ide> for (var s = 0; s < sets.length; s++) { <ide> var set = sets[s];
1
Javascript
Javascript
remove stray console.log statemente
a23d15ad3ad8f0eb52ffc4b0ac86ec358ae3dfa8
<ide><path>src/Angular.js <ide> function assertArg(arg, name, reason) { <ide> if (!arg) { <ide> var error = new Error("Argument '" + (name||'?') + "' is " + <ide> (reason || "required")); <del> if (window.console) window.console.log(error.stack); <ide> throw error; <ide> } <ide> }
1
Javascript
Javascript
remove unnecessary quote escaping
cd2f022d4302e7f4e4926d709f5011423c40de8c
<ide><path>lib/node/NodeMainTemplatePlugin.js <ide> module.exports = class NodeMainTemplatePlugin { <ide> "installedChunks[chunkId] = [resolve, reject];", <ide> "var filename = __dirname + " + this.applyPluginsWaterfall("asset-path", JSON.stringify(`/${chunkFilename}`), { <ide> hash: `" + ${this.renderCurrentHashCode(hash)} + "`, <del> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + \"`, <add> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`, <ide> chunk: { <ide> id: "\" + chunkId + \"", <ide> hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, <ide> module.exports = class NodeMainTemplatePlugin { <ide> } else { <ide> const request = this.applyPluginsWaterfall("asset-path", JSON.stringify(`./${chunkFilename}`), { <ide> hash: `" + ${this.renderCurrentHashCode(hash)} + "`, <del> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + \"`, <add> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`, <ide> chunk: { <ide> id: "\" + chunkId + \"", <ide> hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, <ide> module.exports = class NodeMainTemplatePlugin { <ide> const chunkMaps = chunk.getChunkMaps(); <ide> const currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), { <ide> hash: `" + ${this.renderCurrentHashCode(hash)} + "`, <del> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + \"`, <add> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`, <ide> chunk: { <ide> id: "\" + chunkId + \"", <ide> hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
1
Ruby
Ruby
add casks to default help text
f2064750f578c58335719ccf0ed33bd09c3d2ee3
<ide><path>Library/Homebrew/help.rb <ide> module Help <ide> HOMEBREW_HELP = <<~EOS <ide> Example usage: <ide> brew search [TEXT|/REGEX/] <del> brew info [FORMULA...] <del> brew install FORMULA... <add> brew info [FORMULA|CASK...] <add> brew install FORMULA|CASK... <ide> brew update <del> brew upgrade [FORMULA...] <del> brew uninstall FORMULA... <del> brew list [FORMULA...] <add> brew upgrade [FORMULA|CASK...] <add> brew uninstall FORMULA|CASK... <add> brew list [FORMULA|CASK...] <ide> <ide> Troubleshooting: <ide> brew config <ide> brew doctor <del> brew install --verbose --debug FORMULA <add> brew install --verbose --debug FORMULA|CASK <ide> <ide> Contributing: <ide> brew create [URL [--no-fetch]] <del> brew edit [FORMULA...] <add> brew edit [FORMULA|CASK...] <ide> <ide> Further help: <ide> brew commands
1
Java
Java
use assertthat from hamcrest instead of junit 4
47c39304afe43d904a5a48c8273cab187ddeebce
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java <ide> import org.springframework.expression.spel.support.StandardTypeLocator; <ide> import org.springframework.expression.spel.testresources.TestPerson; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java <ide> import org.springframework.tests.TestGroup; <ide> import org.springframework.util.StopWatch; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java <ide> import org.springframework.expression.spel.testresources.le.div.mod.reserved.Reserver; <ide> import org.springframework.util.ObjectUtils; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java <ide> import org.springframework.tests.TestGroup; <ide> <ide> import static org.hamcrest.CoreMatchers.*; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory.*; <ide> <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java <ide> import org.springframework.util.LinkedCaseInsensitiveMap; <ide> import org.springframework.util.StringUtils; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java <ide> <ide> import org.springframework.tests.sample.beans.TestBean; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> <ide> /** <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/support/SqlLobValueTests.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.jdbc.core.support; <ide> <ide> import java.io.ByteArrayInputStream; <ide> import org.springframework.jdbc.support.lob.LobCreator; <ide> import org.springframework.jdbc.support.lob.LobHandler; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTests.java <ide> <ide> import org.junit.Test; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <del>import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide> <ide> /** <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabaseInitializationTests.java <ide> import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; <ide> import org.springframework.transaction.support.TransactionSynchronizationManager; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <del>import static org.junit.Assert.*; <ide> <ide> /** <ide> * Abstract base class for integration tests involving database initialization. <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java <ide> import org.springframework.transaction.support.TransactionSynchronizationManager; <ide> <ide> import static org.hamcrest.Matchers.*; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.Mockito.*; <ide> <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/H2DatabasePopulatorTests.java <ide> import org.junit.Test; <ide> import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <del>import static org.junit.Assert.*; <ide> <ide> /** <ide> * @author Sam Brannen <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlQueryTests.java <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.StringUtils; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodesFactoryTests.java <ide> import org.springframework.core.io.Resource; <ide> <ide> import static org.hamcrest.CoreMatchers.*; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide> <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java <ide> import org.springframework.jdbc.BadSqlGrammarException; <ide> <ide> import static org.hamcrest.CoreMatchers.*; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> <ide> /** <ide><path>spring-messaging/src/test/java/org/springframework/messaging/converter/MappingJackson2MessageConverterTests.java <ide> import org.springframework.messaging.support.MessageBuilder; <ide> import org.springframework.util.MimeType; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> <ide><path>spring-messaging/src/test/java/org/springframework/messaging/converter/MarshallingMessageConverterTests.java <ide> <ide> package org.springframework.messaging.converter; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> import static org.xmlunit.diff.ComparisonType.*; <ide> import static org.xmlunit.diff.DifferenceEvaluators.*; <ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethodTests.java <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.messaging.Message; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.Mockito.*; <ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/MethodMessageHandlerTests.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.PathMatcher; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> <ide> /** <ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/MethodMessageHandlerTests.java <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.util.PathMatcher; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> <ide> /** <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/SimpAttributesTests.java <ide> import org.junit.rules.ExpectedException; <ide> import org.mockito.Mockito; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <del>import static org.junit.Assert.*; <ide> import static org.mockito.Mockito.*; <ide> <ide> /** <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/SimpSessionScopeTests.java <ide> <ide> import org.springframework.beans.factory.ObjectFactory; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <del>import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide> <ide> /** <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandlerTests.java <ide> import org.springframework.validation.Validator; <ide> import org.springframework.validation.annotation.Validated; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.any; <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java <ide> import org.springframework.validation.Validator; <ide> import org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.Mockito.*; <ide> <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/DefaultStompSessionTests.java <ide> import org.springframework.util.MimeTypeUtils; <ide> import org.springframework.util.concurrent.SettableListenableFuture; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.Mockito.any; <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java <ide> import org.springframework.util.SocketUtils; <ide> import org.springframework.util.concurrent.ListenableFuture; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java <ide> import org.springframework.util.MimeTypeUtils; <ide> import org.springframework.util.MultiValueMap; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> <ide> /** <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/user/MultiServerUserRegistryTests.java <ide> <ide> package org.springframework.messaging.simp.user; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.containsInAnyOrder; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.Mockito.*; <ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/ErrorMessageTests.java <ide> import org.junit.Test; <ide> <ide> import static org.hamcrest.CoreMatchers.*; <del>import static org.junit.Assert.*; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> <ide> /** <ide> * @author Gary Russell <ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/ExecutorSubscribableChannelTests.java <ide> import org.springframework.messaging.MessageDeliveryException; <ide> import org.springframework.messaging.MessageHandler; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java <ide> import org.springframework.util.SerializationTestUtils; <ide> <ide> import static org.hamcrest.CoreMatchers.startsWith; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertFalse; <ide> import static org.junit.Assert.assertNotEquals; <ide> import static org.junit.Assert.assertNotNull; <ide> import static org.junit.Assert.assertNull; <ide> import static org.junit.Assert.assertSame; <del>import static org.junit.Assert.assertThat; <ide> import static org.junit.Assert.assertTrue; <ide> <ide> /** <ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/SharedEntityManagerCreatorTests.java <ide> import org.mockito.junit.MockitoJUnitRunner; <ide> <ide> import static org.hamcrest.CoreMatchers.*; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide> import static org.mockito.BDDMockito.verifyNoMoreInteractions; <ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/DefaultPersistenceUnitManagerTests.java <ide> import org.springframework.core.io.DefaultResourceLoader; <ide> import org.springframework.orm.jpa.domain.Person; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <del>import static org.junit.Assert.*; <ide> <ide> /** <ide> * Tests for {@link DefaultPersistenceUnitManager}. <ide><path>spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java <ide> import java.io.ByteArrayOutputStream; <ide> import java.io.StringWriter; <ide> <del>import static org.junit.Assert.assertThat; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.assertTrue; <ide> <ide> /** <ide><path>spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java <ide> import java.lang.reflect.Type; <ide> import java.util.Collections; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertFalse; <del>import static org.junit.Assert.assertThat; <ide> import static org.junit.Assert.assertTrue; <ide> import static org.junit.Assert.fail; <ide> import static org.mockito.BDDMockito.eq; <ide><path>spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamMarshallerTests.java <ide> <ide> import org.springframework.util.xml.StaxUtils; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide> import static org.xmlunit.matchers.CompareMatcher.*; <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java <ide> <ide> import static org.hamcrest.CoreMatchers.instanceOf; <ide> import static org.hamcrest.CoreMatchers.startsWith; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.is; <ide> import static org.junit.Assert.*; <ide> import static org.springframework.http.MediaType.*; <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/config/ResourceHandlerRegistryTests.java <ide> import org.springframework.web.reactive.resource.VersionResourceResolver; <ide> import org.springframework.web.reactive.resource.WebJarsResourceResolver; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertFalse; <ide> import static org.junit.Assert.assertNull; <del>import static org.junit.Assert.assertThat; <ide> import static org.junit.Assert.assertTrue; <ide> <ide> /** <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyInsertersTests.java <ide> import org.springframework.util.MultiValueMap; <ide> <ide> import static java.nio.charset.StandardCharsets.*; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.springframework.http.codec.json.Jackson2CodecSupport.*; <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java <ide> import org.springframework.http.client.reactive.ReactorClientHttpConnector; <ide> import org.springframework.http.codec.Pojo; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> <ide> /** <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/AppCacheManifestTransformerTests.java <ide> import org.springframework.mock.web.test.server.MockServerWebExchange; <ide> import org.springframework.util.FileCopyUtils; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.*; <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java <ide> import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; <ide> import org.springframework.web.util.pattern.PathPattern; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.*; <ide> <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java <ide> import org.springframework.web.server.ResponseStatusException; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.ArgumentMatchers.any; <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/VersionResourceResolverTests.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.web.reactive.resource; <ide> <ide> import java.time.Duration; <ide> import org.springframework.mock.web.test.server.MockServerWebExchange; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/HandlerMethodMappingTests.java <ide> import org.springframework.web.util.pattern.PathPattern; <ide> import org.springframework.web.util.pattern.PathPatternParser; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> <ide> /** <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/InvocableHandlerMethodTests.java <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.UnsupportedMediaTypeStatusException; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.Mockito.any; <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMappingTests.java <ide> import org.springframework.web.util.pattern.PathPattern; <ide> <ide> import static org.hamcrest.CoreMatchers.*; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.*; <ide> import static org.springframework.web.bind.annotation.RequestMethod.*; <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java <ide> import org.springframework.web.reactive.config.CorsRegistry; <ide> import org.springframework.web.reactive.config.WebFluxConfigurationSupport; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/socket/WebSocketIntegrationTests.java <ide> import org.springframework.web.reactive.HandlerMapping; <ide> import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> <ide> /** <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/socket/server/support/HandshakeWebSocketServiceTests.java <ide> import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.Mockito.*; <ide> <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/TextMessageTests.java <ide> import org.hamcrest.Matchers; <ide> import org.junit.Test; <ide> <del>import static org.junit.Assert.*; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> <ide> /** <ide> * Test fixture for {@link TextMessage}. <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/WebSocketExtensionTests.java <ide> import org.hamcrest.Matchers; <ide> import org.junit.Test; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> <ide> /** <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/ConvertingEncoderDecoderSupportTests.java <ide> import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; <ide> import org.springframework.web.socket.ContextLoaderTestUtils; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <del>import static org.junit.Assert.*; <ide> <ide> /** <ide> * Test for {@link org.springframework.web.socket.adapter.standard.ConvertingEncoderDecoderSupport}. <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/config/HandlersBeanDefinitionParserTests.java <ide> import org.springframework.web.socket.sockjs.transport.handler.XhrReceivingTransportHandler; <ide> import org.springframework.web.socket.sockjs.transport.handler.XhrStreamingTransportHandler; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParserTests.java <ide> import org.springframework.web.socket.sockjs.transport.handler.DefaultSockJsService; <ide> import org.springframework.web.socket.sockjs.transport.handler.WebSocketTransportHandler; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/handler/WebSocketHttpHeadersTests.java <ide> import org.springframework.web.socket.WebSocketExtension; <ide> import org.springframework.web.socket.WebSocketHttpHeaders; <ide> <del>import static org.junit.Assert.*; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> <ide> /** <ide> * Unit tests for WebSocketHttpHeaders. <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompSubProtocolHandlerTests.java <ide> import org.springframework.web.socket.handler.TestWebSocketSession; <ide> import org.springframework.web.socket.sockjs.transport.SockJsSession; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.Mockito.any; <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/messaging/WebSocketStompClientIntegrationTests.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.web.socket.messaging; <ide> <del>import static org.hamcrest.Matchers.*; <del>import static org.junit.Assert.*; <add>package org.springframework.web.socket.messaging; <ide> <ide> import java.lang.reflect.Type; <ide> import java.util.ArrayList; <ide> import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy; <ide> import org.springframework.web.socket.server.support.DefaultHandshakeHandler; <ide> <add>import static org.hamcrest.MatcherAssert.assertThat; <add>import static org.hamcrest.Matchers.*; <add>import static org.junit.Assert.*; <ide> <ide> /** <ide> * Integration tests for {@link WebSocketStompClient}. <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/ClientSockJsSessionTests.java <ide> import org.springframework.web.socket.sockjs.transport.TransportType; <ide> <ide> import static org.hamcrest.CoreMatchers.*; <add>import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide> <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/SockJsUrlInfoTests.java <ide> <ide> import java.net.URI; <ide> <del>import org.junit.Assert; <ide> import org.junit.Test; <ide> <ide> import org.springframework.web.socket.sockjs.transport.TransportType; <ide> <ide> /** <ide> * Unit tests for {@code SockJsUrlInfo}. <add> * <ide> * @author Rossen Stoyanchev <ide> */ <ide> public class SockJsUrlInfoTests { <ide> <del> <ide> @Test <ide> public void serverId() throws Exception { <ide> SockJsUrlInfo info = new SockJsUrlInfo(new URI("https://example.com")); <ide> public void infoUrl() throws Exception { <ide> <ide> private void testInfoUrl(String scheme, String expectedScheme) throws Exception { <ide> SockJsUrlInfo info = new SockJsUrlInfo(new URI(scheme + "://example.com")); <del> Assert.assertThat(info.getInfoUrl(), is(equalTo(new URI(expectedScheme + "://example.com/info")))); <add> assertThat(info.getInfoUrl(), is(equalTo(new URI(expectedScheme + "://example.com/info")))); <ide> } <ide> <ide> @Test
59
Javascript
Javascript
use separate features for dev vs prod builds
00c650cc5443679ff33491be1db183c68b85429d
<ide><path>Brocfile.js <ide> var testConfig = pickFiles('tests', { <ide> testConfig = replace(testConfig, { <ide> files: [ 'tests/ember_configuration.js' ], <ide> patterns: [ <del> { match: /\{\{FEATURES\}\}/g, replacement: JSON.stringify(defeatureifyConfig().enabled) } <add> { match: /\{\{DEV_FEATURES\}\}/g, <add> replacement: function() { <add> var features = defeatureifyConfig().enabled; <add> <add> return JSON.stringify(features); <add> } <add> }, <add> { match: /\{\{PROD_FEATURES\}\}/g, <add> replacement: function() { <add> var features = defeatureifyConfig({ <add> environment: 'production' <add> }).enabled; <add> <add> return JSON.stringify(features); <add> } <add> }, <ide> ] <ide> }); <ide> <ide><path>tests/ember_configuration.js <ide> testing: true <ide> }; <ide> window.ENV = window.ENV || {}; <del> ENV.FEATURES = {{FEATURES}}; <ide> <ide> // Test for "hooks in ENV.EMBER_LOAD_HOOKS['hookName'] get executed" <ide> ENV.EMBER_LOAD_HOOKS = ENV.EMBER_LOAD_HOOKS || {}; <ide> ENV.__test_hook_count__ += object; <ide> }); <ide> <add> window.ENV.FEATURES = !!QUnit.urlParams.prod ? {{PROD_FEATURES}} : {{DEV_FEATURES}}; <add> <ide> // Handle extending prototypes <ide> ENV['EXTEND_PROTOTYPES'] = !!QUnit.urlParams.extendprototypes; <ide>
2
Text
Text
fix grammatical typo in docs
ee97bc1b206976c202d40d8f234b5a929c62dcd6
<ide><path>docs/api-reference/next/link.md <ide> export default Home <ide> <ide> ## With URL Object <ide> <del>`Link` can also receive an URL object and it will automatically format it to create the URL string. Here's how to do it: <add>`Link` can also receive a URL object and it will automatically format it to create the URL string. Here's how to do it: <ide> <ide> ```jsx <ide> import Link from 'next/link' <ide><path>docs/api-reference/next/router.md <ide> export default function Page() { <ide> <ide> #### With URL object <ide> <del>You can use an URL object in the same way you can use it for [`next/link`](/docs/api-reference/next/link.md#with-url-object). Works for both the `url` and `as` parameters: <add>You can use a URL object in the same way you can use it for [`next/link`](/docs/api-reference/next/link.md#with-url-object). Works for both the `url` and `as` parameters: <ide> <ide> ```jsx <ide> import { useRouter } from 'next/router'
2
Ruby
Ruby
add content_type to upload in azure
094fa9277d840fe2061f37b9704f81fecdbbe965
<ide><path>activestorage/lib/active_storage/service/azure_storage_service.rb <ide> def initialize(storage_account_name:, storage_access_key:, container:, **options <ide> @container = container <ide> end <ide> <del> def upload(key, io, checksum: nil, **) <add> def upload(key, io, checksum: nil, content_type: nil, **) <ide> instrument :upload, key: key, checksum: checksum do <ide> handle_errors do <del> blobs.create_block_blob(container, key, IO.try_convert(io) || io, content_md5: checksum) <add> blobs.create_block_blob(container, key, IO.try_convert(io) || io, content_md5: checksum, content_type: content_type) <ide> end <ide> end <ide> end <ide><path>activestorage/test/service/azure_storage_service_test.rb <ide> class ActiveStorage::Service::AzureStorageServiceTest < ActiveSupport::TestCase <ide> <ide> include ActiveStorage::Service::SharedServiceTests <ide> <add> test "upload with content_type" do <add> key = SecureRandom.base58(24) <add> data = "Foobar" <add> <add> @service.upload(key, StringIO.new(data), checksum: Digest::MD5.base64digest(data), filename: ActiveStorage::Filename.new("test.txt"), content_type: "text/plain") <add> <add> url = @service.url(key, expires_in: 2.minutes, disposition: :attachment, content_type: nil, filename: ActiveStorage::Filename.new("test.html")) <add> response = Net::HTTP.get_response(URI(url)) <add> assert_equal "text/plain", response.content_type <add> assert_match(/attachment;.*test\.html/, response["Content-Disposition"]) <add> ensure <add> @service.delete key <add> end <add> <ide> test "signed URL generation" do <ide> url = @service.url(@key, expires_in: 5.minutes, <ide> disposition: :inline, filename: ActiveStorage::Filename.new("avatar.png"), content_type: "image/png")
2
PHP
PHP
fix cs errors
5d0b2fa0036878f85d70122d4f275657b15a8641
<ide><path>src/Core/Configure.php <ide> public static function check($var) <ide> * possible to store `null` values in Configure. <ide> * <ide> * Acts as a wrapper around Configure::read() and Configure::check(). <del> * The configure key/value pair fetched via this method is expected to exist. <add> * The configure key/value pair fetched via this method is expected to exist. <ide> * In case it does not an exception will be thrown. <ide> * <ide> * Usage: <ide> public static function check($var) <ide> * @throws \RuntimeException if the requested configuration is not set. <ide> * @link http://book.cakephp.org/3.0/en/development/configuration.html#reading-configuration-data <ide> */ <del> public static function readOrFail($var) { <add> public static function readOrFail($var) <add> { <ide> if (static::check($var) === false) { <ide> throw new RuntimeException(sprintf('Expected configuration key "%s" not found.', $var)); <ide> }
1