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 |
|---|---|---|---|---|---|
Text | Text | remove azure pipelines badge | eeaadc114823d4c130079536da1a3ecae030adc5 | <ide><path>README.md
<ide> Second, read the [Troubleshooting Checklist](https://docs.brew.sh/Troubleshootin
<ide> **If you don't read these it will take us far longer to help you with your problem.**
<ide>
<ide> ## Contributing
<del>[](https://dev.azure.com/Homebrew/Homebrew/_build/latest?definitionId=1)
<del>
<ide> We'd love you to contribute to Homebrew. First, please read our [Contribution Guide](CONTRIBUTING.md) and [Code of Conduct](https://github.com/Homebrew/.github/blob/master/CODE_OF_CONDUCT.md#code-of-conduct).
<ide>
<ide> We explicitly welcome contributions from people who have never contributed to open-source before: we were all beginners once! We can help build on a partially working pull request with the aim of getting it merged. We are also actively seeking to diversify our contributors and especially welcome contributions from women from all backgrounds and people of colour. | 1 |
PHP | PHP | remove cloud option | 82213fbf40fc4ec687781d0b93ff60a7de536913 | <ide><path>config/filesystems.php
<ide>
<ide> 'default' => env('FILESYSTEM_DRIVER', 'local'),
<ide>
<del> /*
<del> |--------------------------------------------------------------------------
<del> | Default Cloud Filesystem Disk
<del> |--------------------------------------------------------------------------
<del> |
<del> | Many applications store files both locally and in the cloud. For this
<del> | reason, you may specify a default "cloud" driver here. This driver
<del> | will be bound as the Cloud disk implementation in the container.
<del> |
<del> */
<del>
<del> 'cloud' => env('FILESYSTEM_CLOUD', 's3'),
<del>
<ide> /*
<ide> |--------------------------------------------------------------------------
<ide> | Filesystem Disks | 1 |
Go | Go | fix filemode permissions | 0a6d42e2085b9cd1d057779a5b0a80cd49292c37 | <ide><path>server/server.go
<ide> func (srv *Server) ImageExport(job *engine.Job) engine.Status {
<ide> rootRepoMap[name] = rootRepo
<ide> rootRepoJson, _ := json.Marshal(rootRepoMap)
<ide>
<del> if err := ioutil.WriteFile(path.Join(tempdir, "repositories"), rootRepoJson, os.ModeAppend); err != nil {
<add> if err := ioutil.WriteFile(path.Join(tempdir, "repositories"), rootRepoJson, os.FileMode(0644)); err != nil {
<ide> return job.Error(err)
<ide> }
<ide> } else {
<ide> func (srv *Server) exportImage(img *image.Image, tempdir string) error {
<ide> for i := img; i != nil; {
<ide> // temporary directory
<ide> tmpImageDir := path.Join(tempdir, i.ID)
<del> if err := os.Mkdir(tmpImageDir, os.ModeDir); err != nil {
<add> if err := os.Mkdir(tmpImageDir, os.FileMode(0755)); err != nil {
<ide> if os.IsExist(err) {
<ide> return nil
<ide> }
<ide> func (srv *Server) exportImage(img *image.Image, tempdir string) error {
<ide> var version = "1.0"
<ide> var versionBuf = []byte(version)
<ide>
<del> if err := ioutil.WriteFile(path.Join(tmpImageDir, "VERSION"), versionBuf, os.ModeAppend); err != nil {
<add> if err := ioutil.WriteFile(path.Join(tmpImageDir, "VERSION"), versionBuf, os.FileMode(0644)); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (srv *Server) exportImage(img *image.Image, tempdir string) error {
<ide> if err != nil {
<ide> return err
<ide> }
<del> if err := ioutil.WriteFile(path.Join(tmpImageDir, "json"), b, os.ModeAppend); err != nil {
<add> if err := ioutil.WriteFile(path.Join(tmpImageDir, "json"), b, os.FileMode(0644)); err != nil {
<ide> return err
<ide> }
<ide> | 1 |
Text | Text | add the link for swarm reference document | ee23a8e124ef4801bcd0d044578da8daf63cba6f | <ide><path>docs/reference/commandline/swarm_init.md
<ide> frequently.
<ide> ## Related information
<ide>
<ide> * [swarm join](swarm_join.md)
<add>* [swarm join-token](swarm_join_token.md)
<ide> * [swarm leave](swarm_leave.md)
<add>* [swarm unlock](swarm_unlock.md)
<add>* [swarm unlock-key](swarm_unlock_key.md)
<ide> * [swarm update](swarm_update.md)
<del>* [swarm join-token](swarm_join_token.md)
<del>* [node rm](node_rm.md)
<ide><path>docs/reference/commandline/swarm_join.md
<ide> Secret value required for nodes to join the swarm
<ide> ## Related information
<ide>
<ide> * [swarm init](swarm_init.md)
<add>* [swarm join-token](swarm_join_token.md)
<ide> * [swarm leave](swarm_leave.md)
<add>* [swarm unlock](swarm_unlock.md)
<add>* [swarm unlock-key](swarm_unlock_key.md)
<ide> * [swarm update](swarm_update.md)
<ide><path>docs/reference/commandline/swarm_join_token.md
<ide> Only print the token. Do not print a complete command for joining.
<ide>
<ide> ## Related information
<ide>
<add>* [swarm init](swarm_init.md)
<ide> * [swarm join](swarm_join.md)
<add>* [swarm leave](swarm_leave.md)
<add>* [swarm unlock](swarm_unlock.md)
<add>* [swarm unlock-key](swarm_unlock_key.md)
<add>* [swarm update](swarm_update.md)
<ide><path>docs/reference/commandline/swarm_leave.md
<ide> To remove an inactive node, use the [`node rm`](node_rm.md) command instead.
<ide> * [node rm](node_rm.md)
<ide> * [swarm init](swarm_init.md)
<ide> * [swarm join](swarm_join.md)
<add>* [swarm join-token](swarm_join_token.md)
<add>* [swarm unlock](swarm_unlock.md)
<add>* [swarm unlock-key](swarm_unlock_key.md)
<ide> * [swarm update](swarm_update.md)
<ide><path>docs/reference/commandline/swarm_unlock.md
<ide> Please enter unlock key:
<ide> ## Related information
<ide>
<ide> * [swarm init](swarm_init.md)
<add>* [swarm join](swarm_join.md)
<add>* [swarm join-token](swarm_join_token.md)
<add>* [swarm leave](swarm_leave.md)
<add>* [swarm unlock-key](swarm_unlock_key.md)
<ide> * [swarm update](swarm_update.md)
<ide><path>docs/reference/commandline/swarm_unlock_key.md
<ide> Only print the unlock key, without instructions.
<ide>
<ide> ## Related information
<ide>
<del>* [swarm unlock](swarm_unlock.md)
<ide> * [swarm init](swarm_init.md)
<add>* [swarm join](swarm_join.md)
<add>* [swarm join-token](swarm_join_token.md)
<add>* [swarm leave](swarm_leave.md)
<add>* [swarm unlock](swarm_unlock.md)
<ide> * [swarm update](swarm_update.md)
<ide><path>docs/reference/commandline/swarm_update.md
<ide> $ docker swarm update --cert-expiry 720h
<ide>
<ide> * [swarm init](swarm_init.md)
<ide> * [swarm join](swarm_join.md)
<add>* [swarm join-token](swarm_join_token.md)
<ide> * [swarm leave](swarm_leave.md)
<add>* [swarm unlock](swarm_unlock.md)
<add>* [swarm unlock-key](swarm_unlock_key.md) | 7 |
Ruby | Ruby | deprecate the block argument to migrator#migrate | 5e616379ccabce7196820ff517d34ed56ef2a160 | <ide><path>activerecord/lib/active_record/migration.rb
<ide> def forward(migrations_paths, steps=1)
<ide> move(:up, migrations_paths, steps)
<ide> end
<ide>
<del> def up(migrations_paths, target_version = nil, &block)
<del> self.new(:up, migrations(migrations_paths), target_version).migrate(&block)
<add> def up(migrations_paths, target_version = nil)
<add> migrations = migrations(migrations_paths)
<add> migrations.select! { |m| yield m } if block_given?
<add>
<add> self.new(:up, migrations, target_version).migrate
<ide> end
<ide>
<ide> def down(migrations_paths, target_version = nil, &block)
<del> self.new(:down, migrations(migrations_paths), target_version).migrate(&block)
<add> migrations = migrations(migrations_paths)
<add> migrations.select! { |m| yield m } if block_given?
<add>
<add> self.new(:down, migrations, target_version).migrate
<ide> end
<ide>
<ide> def run(direction, migrations_paths, target_version)
<ide> def run
<ide> end
<ide> end
<ide>
<del> def migrate(&block)
<add> def migrate
<ide> if !target && @target_version && @target_version > 0
<ide> raise UnknownMigrationVersionError.new(@target_version)
<ide> end
<ide>
<del> runnable.each do |migration|
<del> if block && !block.call(migration)
<del> next
<del> end
<add> running = runnable
<add>
<add> if block_given?
<add> ActiveSupport::Deprecation.warn(<<-eomsg)
<add>block argument to migrate is deprecated, please filter migrations before constructing the migrator
<add> eomsg
<add> running.select! { |m| yield m }
<add> end
<ide>
<add> running.each do |migration|
<ide> Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger
<ide>
<ide> begin | 1 |
Text | Text | add code example to subprocess.stdout | 0df3ea09faccd04dc0f0c3022e970e60403b9a6b | <ide><path>doc/api/child_process.md
<ide> then this will be `null`.
<ide> `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will
<ide> refer to the same value.
<ide>
<add>```js
<add>const { spawn } = require('child_process');
<add>
<add>const subprocess = spawn('ls');
<add>
<add>subprocess.stdout.on('data', (data) => {
<add> console.log(`Received chunk ${data}`);
<add>});
<add>```
<add>
<ide> ### subprocess.unref()
<ide> <!-- YAML
<ide> added: v0.7.10 | 1 |
Ruby | Ruby | use version objects | fc2d403a825b187f9979e7808344aab7ed533900 | <ide><path>Library/Homebrew/requirements/x11_dependency.rb
<ide> class X11Dependency < Requirement
<ide>
<ide> def initialize(name="x11", tags=[])
<ide> @name = name
<del> @min_version = tags.shift if /(\d\.)+\d/ === tags.first
<add> if /(\d\.)+\d/ === tags.first
<add> @min_version = Version.new(tags.shift)
<add> else
<add> @min_version = Version.new("0.0.0")
<add> end
<ide> super(tags)
<ide> end
<ide>
<ide> satisfy :build_env => false do
<del> MacOS::XQuartz.installed? && (@min_version.nil? || @min_version <= MacOS::XQuartz.version)
<add> MacOS::XQuartz.installed? && min_version <= Version.new(MacOS::Quartz.version)
<ide> end
<ide>
<ide> def message; <<-EOS.undent
<ide> def message; <<-EOS.undent
<ide> end
<ide>
<ide> def <=> other
<del> return nil unless X11Dependency === other
<del>
<del> if min_version.nil? && other.min_version.nil?
<del> 0
<del> elsif other.min_version.nil?
<del> 1
<del> elsif min_version.nil?
<del> -1
<del> else
<del> min_version <=> other.min_version
<del> end
<add> return unless X11Dependency === other
<add> min_version <=> other.min_version
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/test_dependency_collector.rb
<ide> def test_x11_no_tag
<ide>
<ide> def test_x11_min_version
<ide> @d.add :x11 => '2.5.1'
<del> assert_equal "2.5.1", find_requirement(X11Dependency).min_version
<add> assert_equal "2.5.1", find_requirement(X11Dependency).min_version.to_s
<ide> end
<ide>
<ide> def test_x11_tag
<ide> def test_x11_tag
<ide> def test_x11_min_version_and_tag
<ide> @d.add :x11 => ['2.5.1', :optional]
<ide> dep = find_requirement(X11Dependency)
<del> assert_equal '2.5.1', dep.min_version
<add> assert_equal '2.5.1', dep.min_version.to_s
<ide> assert_predicate dep, :optional?
<ide> end
<ide> | 2 |
Ruby | Ruby | improve handling of sigint | 3db55d13d6996df22a0169df4dbbc8f854b2f051 | <ide><path>Library/Homebrew/dev-cmd/ruby.rb
<ide> def ruby
<ide> ruby_sys_args << "-e #{args.e}" if args.e
<ide> ruby_sys_args += args.named
<ide>
<del> begin
<del> safe_system RUBY_PATH,
<del> ENV["HOMEBREW_RUBY_WARNINGS"],
<del> "-I", $LOAD_PATH.join(File::PATH_SEPARATOR),
<del> "-rglobal", "-rdev-cmd/irb",
<del> *ruby_sys_args
<del> rescue ErrorDuringExecution => e
<del> exit e.status.exitstatus
<del> end
<add> exec RUBY_PATH,
<add> ENV["HOMEBREW_RUBY_WARNINGS"],
<add> "-I", $LOAD_PATH.join(File::PATH_SEPARATOR),
<add> "-rglobal", "-rdev-cmd/irb",
<add> *ruby_sys_args
<ide> end
<ide> end
<ide><path>Library/Homebrew/exceptions.rb
<ide> def initialize(cmd, status:, output: nil, secrets: [])
<ide> @status = status
<ide> @output = output
<ide>
<del> exitstatus = if status.respond_to?(:exitstatus)
<del> status.exitstatus
<del> else
<add> exitstatus = case status
<add> when Integer
<ide> status
<add> else
<add> status.exitstatus
<ide> end
<ide>
<ide> redacted_cmd = redact_secrets(cmd.shelljoin.gsub('\=', "="), secrets)
<del> s = +"Failure while executing; `#{redacted_cmd}` exited with #{exitstatus}."
<add>
<add> reason = if exitstatus
<add> "exited with #{exitstatus}"
<add> elsif (uncaught_signal = status.termsig)
<add> "was terminated by uncaught signal #{Signal.signame(uncaught_signal)}"
<add> else
<add> raise ArgumentError, "Status does neither have `exitstatus` nor `termsig`."
<add> end
<add>
<add> s = +"Failure while executing; `#{redacted_cmd}` #{reason}."
<ide>
<ide> if Array(output).present?
<ide> format_output_line = lambda do |type_line|
<ide><path>Library/Homebrew/system_command.rb
<ide> class SystemCommand
<ide>
<ide> # Helper functions for calling {SystemCommand.run}.
<ide> module Mixin
<add> extend T::Sig
<add>
<ide> def system_command(*args)
<ide> T.unsafe(SystemCommand).run(*args)
<ide> end
<ide> def system_command!(*args)
<ide> include Context
<ide> extend Predicable
<ide>
<del> attr_reader :pid
<del>
<ide> def self.run(executable, **options)
<ide> T.unsafe(self).new(executable, **options).run!
<ide> end
<ide> def self.run!(command, **options)
<ide>
<ide> sig { returns(SystemCommand::Result) }
<ide> def run!
<del> puts redact_secrets(command.shelljoin.gsub('\=', "="), @secrets) if verbose? || debug?
<add> $stderr.puts redact_secrets(command.shelljoin.gsub('\=', "="), @secrets) if verbose? || debug?
<ide>
<ide> @output = []
<ide>
<ide> def expanded_args
<ide> end
<ide> end
<ide>
<del> def each_output_line(&b)
<add> sig { params(block: T.proc.params(type: Symbol, line: String).void).void }
<add> def each_output_line(&block)
<ide> executable, *args = command
<del>
<del> raw_stdin, raw_stdout, raw_stderr, raw_wait_thr =
<del> T.unsafe(Open3).popen3(env, [executable, executable], *args, **{ chdir: chdir }.compact)
<del> @pid = raw_wait_thr.pid
<add> options = {
<add> # Create a new process group so that we can send `SIGINT` from
<add> # parent to child rather than the child receiving `SIGINT` directly.
<add> pgroup: true,
<add> }
<add> options[:chdir] = chdir if chdir
<add>
<add> pid = T.let(nil, T.nilable(Integer))
<add> raw_stdin, raw_stdout, raw_stderr, raw_wait_thr = ignore_interrupts do
<add> T.unsafe(Open3).popen3(env, [executable, executable], *args, **options)
<add> .tap { |*, wait_thr| pid = wait_thr.pid }
<add> end
<ide>
<ide> write_input_to(raw_stdin)
<ide> raw_stdin.close_write
<del> each_line_from [raw_stdout, raw_stderr], &b
<add> each_line_from [raw_stdout, raw_stderr], &block
<ide>
<ide> @status = raw_wait_thr.value
<add> rescue Interrupt
<add> Process.kill("INT", pid) if pid
<add> raise Interrupt
<ide> rescue SystemCallError => e
<ide> @status = $CHILD_STATUS
<ide> @output << [:stderr, e.message]
<ide> end
<ide>
<add> sig { params(raw_stdin: IO).void }
<ide> def write_input_to(raw_stdin)
<ide> input.each(&raw_stdin.method(:write))
<ide> end
<ide>
<del> def each_line_from(sources)
<add> sig { params(sources: T::Array[IO], _block: T.proc.params(type: Symbol, line: String).void).void }
<add> def each_line_from(sources, &_block)
<ide> loop do
<ide> readable_sources, = IO.select(sources)
<ide>
<ide><path>Library/Homebrew/test/system_command_spec.rb
<ide> it "includes the given variables explicitly" do
<ide> expect(Open3)
<ide> .to receive(:popen3)
<del> .with(an_instance_of(Hash), ["/usr/bin/env", "/usr/bin/env"], "A=1", "B=2", "C=3", "env", *env_args, {})
<add> .with(
<add> an_instance_of(Hash), ["/usr/bin/env", "/usr/bin/env"], "A=1", "B=2", "C=3",
<add> "env", *env_args,
<add> pgroup: true
<add> )
<ide> .and_call_original
<ide>
<ide> command.run!
<ide> it "includes the given variables explicitly" do
<ide> expect(Open3)
<ide> .to receive(:popen3)
<del> .with(an_instance_of(Hash), ["/usr/bin/sudo", "/usr/bin/sudo"], "-E", "--",
<del> "/usr/bin/env", "A=1", "B=2", "C=3", "env", *env_args, {})
<add> .with(
<add> an_instance_of(Hash), ["/usr/bin/sudo", "/usr/bin/sudo"], "-E", "--",
<add> "/usr/bin/env", "A=1", "B=2", "C=3", "env", *env_args, pgroup: true
<add> )
<ide> .and_wrap_original do |original_popen3, *_, &block|
<ide> original_popen3.call("true", &block)
<ide> end
<ide> context "when given arguments with secrets" do
<ide> it "does not leak the secrets" do
<ide> redacted_msg = /#{Regexp.escape("username:******")}/
<del> expect do
<add> expect {
<ide> described_class.run! "curl",
<ide> args: %w[--user username:hunter2],
<ide> verbose: true,
<ide> secrets: %w[hunter2]
<del> end.to raise_error.with_message(redacted_msg).and output(redacted_msg).to_stdout
<add> }.to raise_error.with_message(redacted_msg).and output(redacted_msg).to_stderr
<ide> end
<ide>
<ide> it "does not leak the secrets set by environment" do
<ide> redacted_msg = /#{Regexp.escape("username:******")}/
<del> expect do
<add> expect {
<ide> ENV["PASSWORD"] = "hunter2"
<ide> described_class.run! "curl",
<ide> args: %w[--user username:hunter2],
<ide> verbose: true
<del> ensure
<del> ENV.delete "PASSWORD"
<del> end.to raise_error.with_message(redacted_msg).and output(redacted_msg).to_stdout
<add> }.to raise_error.with_message(redacted_msg).and output(redacted_msg).to_stderr
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/utils.rb
<ide> def archs_for_command(cmd)
<ide> Pathname.new(cmd).archs
<ide> end
<ide>
<del> def ignore_interrupts(opt = nil)
<del> std_trap = trap("INT") do
<del> puts "One sec, just cleaning up" unless opt == :quietly
<add> def ignore_interrupts(_opt = nil)
<add> # rubocop:disable Style/GlobalVars
<add> $ignore_interrupts_nesting_level = 0 unless defined?($ignore_interrupts_nesting_level)
<add> $ignore_interrupts_nesting_level += 1
<add>
<add> $ignore_interrupts_interrupted = false unless defined?($ignore_interrupts_interrupted)
<add> old_sigint_handler = trap(:INT) do
<add> $ignore_interrupts_interrupted = true
<add> $stderr.print "\n"
<add> $stderr.puts "One sec, cleaning up..."
<ide> end
<del> yield
<del> ensure
<del> trap("INT", std_trap)
<add>
<add> begin
<add> yield
<add> ensure
<add> trap(:INT, old_sigint_handler)
<add>
<add> $ignore_interrupts_nesting_level -= 1
<add> if $ignore_interrupts_nesting_level == 0 && $ignore_interrupts_interrupted
<add> $ignore_interrupts_interrupted = false
<add> raise Interrupt
<add> end
<add> end
<add> # rubocop:enable Style/GlobalVars
<ide> end
<ide>
<ide> sig { returns(String) } | 5 |
Ruby | Ruby | avoid race condition in aj integration tests | 0e97cd1a0d3e7dbe2b99eb111e005d7c9d7002b7 | <ide><path>activejob/test/support/integration/dummy_app_template.rb
<ide> class TestJob < ActiveJob::Base
<ide> queue_as :integration_tests
<ide>
<ide> def perform(x)
<del> File.open(Rails.root.join("tmp/\#{x}"), "wb+") do |f|
<add> File.open(Rails.root.join("tmp/\#{x}.new"), "wb+") do |f|
<ide> f.write Marshal.dump({
<ide> "locale" => I18n.locale.to_s || "en",
<ide> "executed_at" => Time.now.to_r
<ide> })
<ide> end
<add> File.rename(Rails.root.join("tmp/\#{x}.new"), Rails.root.join("tmp/\#{x}"))
<ide> end
<ide> end
<ide> CODE
<ide><path>activejob/test/support/integration/helper.rb
<ide>
<ide> require "rails/generators/rails/app/app_generator"
<ide>
<add>require "tmpdir"
<ide> dummy_app_path = Dir.mktmpdir + "/dummy"
<ide> dummy_app_template = File.expand_path("../dummy_app_template.rb", __FILE__)
<ide> args = Rails::Generators::ARGVScrubber.new(["new", dummy_app_path, "--skip-gemfile", "--skip-bundle", | 2 |
Python | Python | add support for squad bert export | 282adff5f9bfce2196f5902bdb6ad53eb6de55f3 | <ide><path>official/nlp/bert/export_tfhub.py
<ide> flags.DEFINE_string("export_path", None, "TF-Hub SavedModel destination path.")
<ide> flags.DEFINE_string("vocab_file", None,
<ide> "The vocabulary file that the BERT model was trained on.")
<del>flags.DEFINE_bool("do_lower_case", None, "Whether to lowercase. If None, "
<del> "do_lower_case will be enabled if 'uncased' appears in the "
<del> "name of --vocab_file")
<add>flags.DEFINE_bool(
<add> "do_lower_case", None, "Whether to lowercase. If None, "
<add> "do_lower_case will be enabled if 'uncased' appears in the "
<add> "name of --vocab_file")
<add>flags.DEFINE_enum("model_type", "encoder", ["encoder", "squad"],
<add> "What kind of BERT model to export.")
<ide>
<ide>
<ide> def create_bert_model(bert_config: configs.BertConfig) -> tf.keras.Model:
<ide> def create_bert_model(bert_config: configs.BertConfig) -> tf.keras.Model:
<ide>
<ide>
<ide> def export_bert_tfhub(bert_config: configs.BertConfig,
<del> model_checkpoint_path: Text, hub_destination: Text,
<del> vocab_file: Text, do_lower_case: bool = None):
<add> model_checkpoint_path: Text,
<add> hub_destination: Text,
<add> vocab_file: Text,
<add> do_lower_case: bool = None):
<ide> """Restores a tf.keras.Model and saves for TF-Hub."""
<ide> # If do_lower_case is not explicit, default to checking whether "uncased" is
<ide> # in the vocab file name
<ide> def export_bert_tfhub(bert_config: configs.BertConfig,
<ide> logging.info("Using do_lower_case=%s based on name of vocab_file=%s",
<ide> do_lower_case, vocab_file)
<ide> core_model, encoder = create_bert_model(bert_config)
<del> checkpoint = tf.train.Checkpoint(model=encoder, # Legacy checkpoints.
<del> encoder=encoder)
<add> checkpoint = tf.train.Checkpoint(
<add> model=encoder, # Legacy checkpoints.
<add> encoder=encoder)
<ide> checkpoint.restore(model_checkpoint_path).assert_existing_objects_matched()
<ide> core_model.vocab_file = tf.saved_model.Asset(vocab_file)
<ide> core_model.do_lower_case = tf.Variable(do_lower_case, trainable=False)
<ide> core_model.save(hub_destination, include_optimizer=False, save_format="tf")
<ide>
<ide>
<add>def export_bert_squad_tfhub(bert_config: configs.BertConfig,
<add> model_checkpoint_path: Text,
<add> hub_destination: Text,
<add> vocab_file: Text,
<add> do_lower_case: bool = None):
<add> """Restores a tf.keras.Model for BERT with SQuAD and saves for TF-Hub."""
<add> # If do_lower_case is not explicit, default to checking whether "uncased" is
<add> # in the vocab file name
<add> if do_lower_case is None:
<add> do_lower_case = "uncased" in vocab_file
<add> logging.info("Using do_lower_case=%s based on name of vocab_file=%s",
<add> do_lower_case, vocab_file)
<add> span_labeling, _ = bert_models.squad_model(bert_config, max_seq_length=None)
<add> checkpoint = tf.train.Checkpoint(model=span_labeling)
<add> checkpoint.restore(model_checkpoint_path).assert_existing_objects_matched()
<add> span_labeling.vocab_file = tf.saved_model.Asset(vocab_file)
<add> span_labeling.do_lower_case = tf.Variable(do_lower_case, trainable=False)
<add> span_labeling.save(hub_destination, include_optimizer=False, save_format="tf")
<add>
<add>
<ide> def main(_):
<ide> bert_config = configs.BertConfig.from_json_file(FLAGS.bert_config_file)
<del> export_bert_tfhub(bert_config, FLAGS.model_checkpoint_path, FLAGS.export_path,
<del> FLAGS.vocab_file, FLAGS.do_lower_case)
<add> if FLAGS.model_type == "encoder":
<add> export_bert_tfhub(bert_config, FLAGS.model_checkpoint_path,
<add> FLAGS.export_path, FLAGS.vocab_file, FLAGS.do_lower_case)
<add> elif FLAGS.model_type == "squad":
<add> export_bert_squad_tfhub(bert_config, FLAGS.model_checkpoint_path,
<add> FLAGS.export_path, FLAGS.vocab_file,
<add> FLAGS.do_lower_case)
<add> else:
<add> raise ValueError("Unsupported model_type %s." % FLAGS.model_type)
<ide>
<ide>
<ide> if __name__ == "__main__": | 1 |
PHP | PHP | use user-agent set in php.ini if available | 206358c9fd490d51b8665e8a7db814bdf00349a1 | <ide><path>src/Http/Client/Request.php
<ide> public function __construct(string $url = '', string $method = self::METHOD_GET,
<ide> $this->uri = $this->createUri($url);
<ide> $headers += [
<ide> 'Connection' => 'close',
<del> 'User-Agent' => 'CakePHP',
<add> 'User-Agent' => ini_get('user_agent') ?: 'CakePHP',
<ide> ];
<ide> $this->addHeaders($headers);
<ide> | 1 |
Javascript | Javascript | remove common.port from test-cluster*.js | 415098f4997c014b4f9b7b33fc0c7f9588e1e090 | <ide><path>test/parallel/test-cluster-disconnect-leak.js
<ide> if (cluster.isMaster) {
<ide>
<ide> const server = net.createServer();
<ide>
<del>server.listen(common.PORT);
<add>server.listen(0);
<ide><path>test/parallel/test-cluster-disconnect-race.js
<ide> if (cluster.isMaster) {
<ide>
<ide> const server = net.createServer();
<ide>
<del>server.listen(common.PORT, function() {
<add>server.listen(0, function() {
<ide> process.send('listening');
<ide> });
<ide><path>test/parallel/test-cluster-process-disconnect.js
<ide> if (cluster.isMaster) {
<ide> } else {
<ide> const net = require('net');
<ide> const server = net.createServer();
<del> server.listen(common.PORT, common.mustCall(() => {
<add> server.listen(0, common.mustCall(() => {
<ide> process.disconnect();
<ide> }));
<ide> } | 3 |
Javascript | Javascript | use structured cloning | 7176da7614fb3b457497e639908795948df5dc64 | <ide><path>src/state-store.js
<ide> class StateStore {
<ide> }
<ide>
<ide> save (key, value) {
<del> // Serialize values using JSON.stringify, as it seems way faster than IndexedDB structured clone.
<del> // (Ref.: https://bugs.chromium.org/p/chromium/issues/detail?id=536620)
<del> let jsonValue = JSON.stringify(value)
<ide> return new Promise((resolve, reject) => {
<ide> this.dbPromise.then(db => {
<ide> if (db == null) resolve()
<ide>
<ide> var request = db.transaction(['states'], 'readwrite')
<ide> .objectStore('states')
<del> .put({value: jsonValue, storedAt: new Date().toString(), isJSON: true}, key)
<add> .put({value: value, storedAt: new Date().toString()}, key)
<ide>
<ide> request.onsuccess = resolve
<ide> request.onerror = reject
<ide> class StateStore {
<ide>
<ide> request.onsuccess = (event) => {
<ide> let result = event.target.result
<del> if (result) {
<del> // TODO: remove this when state will be serialized only via JSON.
<del> resolve(result.isJSON ? JSON.parse(result.value) : result.value)
<add> if (result && !result.isJSON) {
<add> resolve(result.value)
<ide> } else {
<ide> resolve(null)
<ide> } | 1 |
PHP | PHP | fix misaligned comment | fb49cd2d1d604ccc7d33b34f6b7aa70d16aabbba | <ide><path>src/Mailer/Transport/SmtpTransport.php
<ide> public function __destruct()
<ide> try {
<ide> $this->disconnect();
<ide> } catch (Exception $e) {
<del>// avoid fatal error on script termination
<add> // avoid fatal error on script termination
<ide> }
<ide> }
<ide> | 1 |
Text | Text | update create theme guide based on feedback | 647dcd59884a0f4828c0400b07a875f6d2e0718d | <ide><path>docs/creating-a-theme.md
<ide> * Git - to track and distribute your themes
<ide> * What do I need to know?
<ide> * CSS/LESS - as that's what themes are written in
<add> * Devtools - so you can find the selector you're looking for.
<ide> * Is there an example I can start from?
<ide> * Yes, you can clone https://github.com/atom/solarized-dark-syntax
<ide>
<ide> mkdir my-theme
<ide> cd my-theme
<ide> git init
<ide> mkdir stylesheets
<del>cat > package.json <<END
<del>{
<del> "name": "theme-rainbow",
<del> "theme": true,
<del> "stylesheets": [
<del> 'included-first.less',
<del> 'included-second.less'
<del> ]
<del> "version": "0.0.1",
<del> "description": "Rainbows are beautiful",
<del> "repository": {
<del> "type": "git",
<del> "url": "https://github.com/atom/theme-rainbow.git"
<del> },
<del> "bugs": {
<del> "url": "https://github.com/atom/theme-rainbow/issues"
<del> },
<del> "engines": {
<del> "atom": "~>1.0"
<del> }
<del>}
<add>apm init --theme
<add>cat > index.less <<END
<add>@import "./stylesheets/base.less";
<add>@import "./stylesheets/overrides.less";
<ide> END
<del>
<del>cat > stylesheets/included-first.less <<END
<add>cat > stylesheets/base.less <<END
<ide> @import "ui-variables";
<ide>
<ide> .editor {
<ide> color: fade(@text-color, 20%);
<ide> }
<ide> END
<del>
<del>cat > stylesheets/included-second.less <<END
<del>@import "ui-colors";
<add>cat > stylesheets/overrides.less <<END
<add>@import "ui-variables";
<ide>
<ide> .editor {
<ide> color: fade(@text-color, 80%);
<ide> END
<ide>
<ide> ### Important points
<ide>
<del>* Notice the theme attribute in the package.json file. This is specific to Atom
<del> and required for all theme packages. Otherwise they won't be displayed in the
<del> theme chooser.
<del>* Notice the stylesheets attribute. If have multiple stylesheets and their order
<del> is meaningful than you should specify their relative pathnames here. Otherwise
<del> all css or less files will be loaded alphabetically from the stylesheets
<del> folder.
<add>* Notice the theme attribute in the package.json file (generated by apm). This
<add> is specific to Atom and required for all theme packages. Otherwise they won't
<add> be displayed in the theme chooser.
<ide> * Notice the ui-variables require. If you'd like to make your theme adapt to the
<ide> users choosen ui theme, these variables allow you to create your own colors
<ide> based on them.
<ide>
<del>## Create a minimal ui theme
<add>## How to create a UI theme
<ide>
<ide> * Needs to have a file called ui-variables and it must contain the following
<ide> variables:
<ide> * A list of variables from @benogle's theme refactor.
<add>
<add>## How to just override UI colors
<add>
<add>* Not interested in making an entire theme? Not to worry, you can override just
<add> the colors.
<add>* Create a theme as above but just include a single file in your `stylesheets`
<add> directory called `ui-variables.less`
<add>* IMPORTANT: This theme must come before
<add>
<add>## How to create a syntax theme
<add>
<add>* Explain the idea behind grammars/tokens and classes you'd want to override. | 1 |
Javascript | Javascript | add new line to default preferences | 0aa31a493b7d39118321ed319938ad47e312f102 | <ide><path>gulpfile.js
<ide> function preprocessDefaultPreferences(content) {
<ide> defines: DEFINES,
<ide> }, content);
<ide>
<del> return licenseHeader + '\n' + MODIFICATION_WARNING + '\n' + content;
<add> return licenseHeader + '\n' + MODIFICATION_WARNING + '\n' + content + '\n';
<ide> }
<ide>
<ide> gulp.task('firefox-pre', ['buildnumber', 'locale'], function () { | 1 |
Python | Python | fix tests for complex power function | 1dec6da92fa355620acfccd8e18a6fe80e06054e | <ide><path>numpy/core/tests/test_umath.py
<ide> def test_power_complex(self):
<ide> x = np.array([1+2j, 2+3j, 3+4j])
<ide> assert_equal(x**0, [1., 1., 1.])
<ide> assert_equal(x**1, x)
<del> assert_equal(x**2, [-3+4j, -5+12j, -7+24j])
<del> assert_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3])
<del> assert_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4])
<add> assert_almost_equal(x**2, [-3+4j, -5+12j, -7+24j])
<add> assert_almost_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3])
<add> assert_almost_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4])
<ide> assert_almost_equal(x**(-1), [1/(1+2j), 1/(2+3j), 1/(3+4j)])
<ide> assert_almost_equal(x**(-2), [1/(1+2j)**2, 1/(2+3j)**2, 1/(3+4j)**2])
<ide> assert_almost_equal(x**(-3), [(-11+2j)/125, (-46-9j)/2197,
<ide> (-117-44j)/15625])
<ide> assert_almost_equal(x**(0.5), [ncu.sqrt(1+2j), ncu.sqrt(2+3j),
<ide> ncu.sqrt(3+4j)])
<del> assert_almost_equal(x**14, [-76443+16124j, 23161315+58317492j,
<del> 5583548873 + 2465133864j])
<add> norm = 1./((x**14)[0])
<add> assert_almost_equal(x**14 * norm,
<add> [i * norm for i in [-76443+16124j, 23161315+58317492j,
<add> 5583548873 + 2465133864j]])
<ide>
<ide> # Ticket #836
<ide> def assert_complex_equal(x, y): | 1 |
Ruby | Ruby | return matches from open pull requests | 79439626b5e7564566bdf8736916342e2bb5e1a7 | <ide><path>Library/Homebrew/cmd/search.rb
<ide> def search
<ide> exec "open", "http://pdb.finkproject.org/pdb/browse.php?summary=#{ARGV.next}"
<ide> else
<ide> query = ARGV.first
<del> search_results = search_brews query
<add> rx = if query =~ %r{^/(.*)/$}
<add> Regexp.new($1)
<add> else
<add> /.*#{Regexp.escape query}.*/i
<add> end
<add>
<add> search_results = search_brews rx
<ide> puts_columns search_results
<ide>
<ide> if not query.to_s.empty? and $stdout.tty? and msg = blacklisted?(query)
<ide> def search
<ide> end
<ide> puts msg
<ide> end
<add>
<add> if search_results.empty? and not blacklisted? query
<add> pulls = GitHub.find_pull_requests rx
<add> unless pulls.empty?
<add> puts "Open pull requests matching \"#{query}\":", *pulls.map { |p| " #{p}" }
<add> end
<add> end
<ide> end
<ide> end
<ide>
<del> def search_brews text
<del> if text.to_s.empty?
<add> def search_brews rx
<add> if rx.to_s.empty?
<ide> Formula.names
<ide> else
<del> rx = if text =~ %r{^/(.*)/$}
<del> Regexp.new($1)
<del> else
<del> /.*#{Regexp.escape text}.*/i
<del> end
<del>
<ide> aliases = Formula.aliases
<ide> results = (Formula.names+aliases).grep rx
<ide>
<ide> def search_brews text
<ide> end
<ide> end
<ide> end
<del>
<ide> end
<ide><path>Library/Homebrew/utils.rb
<ide> def issues_for_formula name
<ide> rescue
<ide> []
<ide> end
<add>
<add> def find_pull_requests rx
<add> require 'open-uri'
<add> require 'vendor/multi_json'
<add>
<add> pulls = []
<add> uri = URI.parse("https://api.github.com/repos/mxcl/homebrew/pulls")
<add> uri.query = "per_page=100"
<add>
<add> open uri do |f|
<add> MultiJson.decode((f.read)).each do |pull|
<add> pulls << pull['html_url'] if rx.match pull['title']
<add> end
<add>
<add> uri = if f.meta['link'] =~ /rel="next"/
<add> f.meta['link'].slice(URI.regexp)
<add> else
<add> nil
<add> end
<add> end while uri
<add> pulls
<add> rescue
<add> []
<add> end
<ide> end | 2 |
Text | Text | add redux-form to ecosystem | bcf4faf1fd085608e387e6f4097f94979adbb283 | <ide><path>docs/introduction/Ecosystem.md
<ide> On this page we will only feature a few of them that the Redux maintainers have
<ide> * [redux-batched-updates](https://github.com/acdlite/redux-batched-updates) — Batch React updates that occur as a result of Redux dispatches
<ide> * [redux-logger](https://github.com/fcomb/redux-logger) — Log every Redux action and the next state
<ide>
<add>## Components
<add>
<add>* [redux-form](https://github.com/erikras/redux-form) — Keep React form state in Redux
<add>
<ide> ## Utilities
<ide>
<ide> * [reselect](https://github.com/faassen/reselect) — Efficient derived data selectors inspired by NuclearJS | 1 |
Python | Python | rnn unit tests touch-ups | 23afa3f3b6cc56be419ef1e8459565578ab5cc6f | <ide><path>keras/backend/theano_backend.py
<ide> def rnn(step_function, inputs, initial_states,
<ide> '''
<ide> inputs = inputs.dimshuffle((1, 0, 2))
<ide>
<del> def _step(ins, *states):
<del> output, new_states = step_function(ins, states)
<add> def _step(input, *states):
<add> output, new_states = step_function(input, states)
<ide> if masking:
<ide> # if all-zero input timestep, return
<ide> # all-zero output and unchanged states
<del> switch = T.any(ins)
<add> switch = T.any(input)
<ide> output = T.switch(switch, output, 0. * output)
<ide> return_states = []
<ide> for state, new_state in zip(states, new_states):
<ide><path>tests/keras/layers/test_recurrent.py
<ide> def _runner(layer_class):
<ide> out3 = model.predict(np.ones((nb_samples, timesteps, input_dim)))
<ide> assert(out2.max() != out3.max())
<ide>
<del> # check that we stay stateful during predictions
<del> out4 = model.predict(np.ones((nb_samples, timesteps, input_dim)))
<del> assert(out3.max() != out4.max())
<del>
<ide> # check that container-level reset_states() works
<ide> model.reset_states()
<add> out4 = model.predict(np.ones((nb_samples, timesteps, input_dim)))
<add> assert_allclose(out3, out4, atol=1e-5)
<add>
<add> # check that the call to `predict` updated the states
<ide> out5 = model.predict(np.ones((nb_samples, timesteps, input_dim)))
<ide> assert(out4.max() != out5.max())
<ide> | 2 |
Python | Python | fix is_cython_func for additional imported code | e9f7f9a4bc38fb490a43b46d3d70234a9ee44039 | <ide><path>spacy/tests/test_misc.py
<ide> from spacy import prefer_gpu, require_gpu, require_cpu
<ide> from spacy.ml._precomputable_affine import PrecomputableAffine
<ide> from spacy.ml._precomputable_affine import _backprop_precomputable_affine_padding
<del>from spacy.util import dot_to_object, SimpleFrozenList
<add>from spacy.util import dot_to_object, SimpleFrozenList, import_file
<ide> from thinc.api import Config, Optimizer, ConfigValidationError
<ide> from spacy.training.batchers import minibatch_by_words
<ide> from spacy.lang.en import English
<ide>
<ide> from thinc.api import get_current_ops, NumpyOps, CupyOps
<ide>
<del>from .util import get_random_doc
<add>from .util import get_random_doc, make_named_tempfile
<ide>
<ide>
<ide> @pytest.fixture
<ide> def test_resolve_dot_names():
<ide> errors = e.value.errors
<ide> assert len(errors) == 1
<ide> assert errors[0]["loc"] == ["training", "xyz"]
<add>
<add>
<add>def test_import_code():
<add> code_str = """
<add>from spacy import Language
<add>
<add>class DummyComponent:
<add> def __init__(self, vocab, name):
<add> pass
<add>
<add> def initialize(self, get_examples, *, nlp, dummy_param: int):
<add> pass
<add>
<add>@Language.factory(
<add> "dummy_component",
<add>)
<add>def make_dummy_component(
<add> nlp: Language, name: str
<add>):
<add> return DummyComponent(nlp.vocab, name)
<add>"""
<add>
<add> with make_named_tempfile(mode="w", suffix=".py") as fileh:
<add> fileh.write(code_str)
<add> fileh.flush()
<add>
<add> import_file("python_code", fileh.name)
<add> config = {"initialize": {"components": {"dummy_component": {"dummy_param": 1}}}}
<add> nlp = English.from_config(config)
<add> nlp.add_pipe("dummy_component")
<add> nlp.initialize()
<ide><path>spacy/tests/util.py
<ide> def make_tempfile(mode="r"):
<ide> f.close()
<ide>
<ide>
<add>@contextlib.contextmanager
<add>def make_named_tempfile(mode="r", suffix=None):
<add> f = tempfile.NamedTemporaryFile(mode=mode, suffix=suffix)
<add> yield f
<add> f.close()
<add>
<add>
<ide> def get_batch(batch_size):
<ide> vocab = Vocab()
<ide> docs = []
<ide><path>spacy/util.py
<ide> def is_cython_func(func: Callable) -> bool:
<ide> if hasattr(func, attr): # function or class instance
<ide> return True
<ide> # https://stackoverflow.com/a/55767059
<del> if hasattr(func, "__qualname__") and hasattr(func, "__module__"): # method
<del> cls_func = vars(sys.modules[func.__module__])[func.__qualname__.split(".")[0]]
<del> return hasattr(cls_func, attr)
<add> if hasattr(func, "__qualname__") and hasattr(func, "__module__") \
<add> and func.__module__ in sys.modules: # method
<add> cls_func = vars(sys.modules[func.__module__])[func.__qualname__.split(".")[0]]
<add> return hasattr(cls_func, attr)
<ide> return False
<ide>
<ide> | 3 |
Ruby | Ruby | teach detailskey how to clear the template cache | f369b63ad69ac8bb29811e145a148dd109de777c | <ide><path>actionview/lib/action_view/lookup_context.rb
<ide> def self.details_cache_key(details)
<ide> end
<ide>
<ide> def self.clear
<add> ActionView::ViewPaths.all_view_paths.each do |path_set|
<add> path_set.each(&:clear_cache)
<add> end
<add> ActionView::LookupContext.fallbacks.each(&:clear_cache)
<ide> @view_context_class = nil
<ide> @details_keys.clear
<ide> @digest_cache.clear
<ide><path>actionview/lib/action_view/view_paths.rb
<ide> module ViewPaths
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :_view_paths, default: ActionView::PathSet.new.freeze
<add> ViewPaths.set_view_paths(self, ActionView::PathSet.new.freeze)
<ide> end
<ide>
<ide> delegate :template_exists?, :any_templates?, :view_paths, :formats, :formats=,
<ide> :locale, :locale=, to: :lookup_context
<ide>
<ide> module ClassMethods
<add> def _view_paths
<add> ViewPaths.get_view_paths(self)
<add> end
<add>
<add> def _view_paths=(paths)
<add> ViewPaths.set_view_paths(self, paths)
<add> end
<add>
<ide> def _prefixes # :nodoc:
<ide> @_prefixes ||= begin
<ide> return local_prefixes if superclass.abstract?
<ide> def local_prefixes
<ide> end
<ide> end
<ide>
<add> # :stopdoc:
<add> @all_view_paths = {}
<add>
<add> def self.get_view_paths(klass)
<add> @all_view_paths[klass] || get_view_paths(klass.superclass)
<add> end
<add>
<add> def self.set_view_paths(klass, paths)
<add> @all_view_paths[klass] = paths
<add> end
<add>
<add> def self.all_view_paths
<add> @all_view_paths.values.uniq
<add> end
<add> # :startdoc:
<add>
<ide> # The prefixes used in render "foo" shortcuts.
<ide> def _prefixes # :nodoc:
<ide> self.class._prefixes
<ide><path>actionview/test/template/log_subscriber_test.rb
<ide> class AVLogSubscriberTest < ActiveSupport::TestCase
<ide> def setup
<ide> super
<ide>
<add> ActionView::LookupContext::DetailsKey.clear
<add>
<ide> view_paths = ActionController::Base.view_paths
<del> view_paths.each(&:clear_cache)
<del> ActionView::LookupContext.fallbacks.each(&:clear_cache)
<ide>
<ide> lookup_context = ActionView::LookupContext.new(view_paths, {}, ["test"])
<ide> renderer = ActionView::Renderer.new(lookup_context)
<ide><path>actionview/test/template/render_test.rb
<ide> class CachedViewRenderTest < ActiveSupport::TestCase
<ide>
<ide> # Ensure view path cache is primed
<ide> def setup
<add> ActionView::LookupContext::DetailsKey.clear
<ide> view_paths = ActionController::Base.view_paths
<del> view_paths.each(&:clear_cache)
<del> ActionView::LookupContext.fallbacks.each(&:clear_cache)
<ide> assert_equal ActionView::OptimizedFileSystemResolver, view_paths.first.class
<ide> setup_view(view_paths)
<ide> end
<ide> class LazyViewRenderTest < ActiveSupport::TestCase
<ide> # Test the same thing as above, but make sure the view path
<ide> # is not eager loaded
<ide> def setup
<add> ActionView::LookupContext::DetailsKey.clear
<add>
<ide> view_paths = ActionController::Base.view_paths
<del> view_paths.each(&:clear_cache)
<del> ActionView::LookupContext.fallbacks.each(&:clear_cache)
<ide> path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH)
<ide> view_paths = ActionView::PathSet.new([path])
<ide> assert_equal ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH), view_paths.first
<ide> class CachedCustomer < Customer; end
<ide>
<ide> # Ensure view path cache is primed
<ide> setup do
<add> ActionView::LookupContext::DetailsKey.clear
<add>
<ide> view_paths = ActionController::Base.view_paths
<ide> assert_equal ActionView::OptimizedFileSystemResolver, view_paths.first.class
<del> view_paths.each(&:clear_cache)
<del> ActionView::LookupContext.fallbacks.each(&:clear_cache)
<ide>
<ide> ActionView::PartialRenderer.collection_cache = ActiveSupport::Cache::MemoryStore.new
<ide>
<ide><path>actionview/test/template/streaming_render_test.rb
<ide> class TestController < ActionController::Base
<ide>
<ide> class SetupFiberedBase < ActiveSupport::TestCase
<ide> def setup
<add> ActionView::LookupContext::DetailsKey.clear
<add>
<ide> view_paths = ActionController::Base.view_paths
<del> view_paths.each(&:clear_cache)
<del> ActionView::LookupContext.fallbacks.each(&:clear_cache)
<ide>
<ide> @assigns = { secret: "in the sauce", name: nil }
<ide> @view = ActionView::Base.with_empty_template_cache.with_view_paths(view_paths, @assigns) | 5 |
Javascript | Javascript | add testing for monkeypatching of console stdio | 6913bd183b5ffaa08fe71c9f3cb9ed1c964eab05 | <ide><path>test/parallel/test-console-stdio-setters.js
<add>'use strict';
<add>
<add>// Test that monkeypatching console._stdout and console._stderr works.
<add>const common = require('../common');
<add>
<add>const { Writable } = require('stream');
<add>const { Console } = require('console');
<add>
<add>const streamToNowhere = new Writable({ write: common.mustCall() });
<add>const anotherStreamToNowhere = new Writable({ write: common.mustCall() });
<add>const myConsole = new Console(process.stdout);
<add>
<add>// Overriding the _stdout and _stderr properties this way is what we are
<add>// testing. Don't change this to be done via arguments passed to the constructor
<add>// above.
<add>myConsole._stdout = streamToNowhere;
<add>myConsole._stderr = anotherStreamToNowhere;
<add>
<add>myConsole.log('fhqwhgads');
<add>myConsole.error('fhqwhgads'); | 1 |
Python | Python | add exhaust_iterator function and tests for it | be8993df81d165164d9171e79169462fac02e17d | <ide><path>libcloud/utils.py
<ide> def read_in_chunks(iterator, chunk_size=None, fill_size=False):
<ide> yield data
<ide> data = ''
<ide>
<add>def exhaust_iterator(iterator):
<add> """
<add> Exhaust an iterator and return all data returned by it.
<add>
<add> @type iterator: C{Iterator}
<add> @param response: An object which implements an iterator interface
<add> or a File like object with read method.
<add>
<add> @rtype C{str}
<add> @return Data returned by the iterator.
<add> """
<add> data = ''
<add>
<add> try:
<add> chunk = str(iterator.next())
<add> except StopIteration:
<add> chunk = ''
<add>
<add> while len(chunk) > 0:
<add> data += chunk
<add>
<add> try:
<add> chunk = str(iterator.next())
<add> except StopIteration:
<add> chunk = ''
<add>
<add> return data
<add>
<ide> def guess_file_mime_type(file_path):
<ide> filename = os.path.basename(file_path)
<ide> (mimetype, encoding) = mimetypes.guess_type(filename)
<ide><path>test/test_utils.py
<ide> import unittest
<ide> import warnings
<ide> import os.path
<add>from StringIO import StringIO
<ide>
<ide> # In Python > 2.7 DeprecationWarnings are disabled by default
<ide> warnings.simplefilter('default')
<ide> def read(self, size):
<ide>
<ide> self.assertEqual(index, 548)
<ide>
<add> def test_exhaust_iterator(self):
<add> def iterator_func():
<add> for x in range(0, 1000):
<add> yield 'aa'
<add>
<add> data = 'aa' * 1000
<add> iterator = libcloud.utils.read_in_chunks(iterator=iterator_func())
<add> result = libcloud.utils.exhaust_iterator(iterator=iterator)
<add> self.assertEqual(result, data)
<add>
<add> result = libcloud.utils.exhaust_iterator(iterator=iterator_func())
<add> self.assertEqual(result, data)
<add>
<add>
<add> data = '12345678990'
<add> iterator = StringIO(data)
<add> result = libcloud.utils.exhaust_iterator(iterator=iterator)
<add> self.assertEqual(result, data)
<add>
<add> def test_exhaust_iterator_empty_iterator(self):
<add> data = ''
<add> iterator = StringIO(data)
<add> result = libcloud.utils.exhaust_iterator(iterator=iterator)
<add> self.assertEqual(result, data)
<add>
<add>
<ide> if __name__ == '__main__':
<ide> sys.exit(unittest.main()) | 2 |
PHP | PHP | update doc blocks | 8ed08add54e924c219e559b946247e9c11418193 | <ide><path>src/View/Helper/FormHelper.php
<ide> public function isFieldError($field) {
<ide> /**
<ide> * Returns a formatted error message for given form field, '' if no errors.
<ide> *
<del> * Uses the `error`, `errorList` and `errorItem` templates. The errorList and
<del> * errorItem templates are used to format multiple error messages per field.
<add> * Uses the `error`, `errorList` and `errorItem` templates. The `errorList` and
<add> * `errorItem` templates are used to format multiple error messages per field.
<ide> *
<ide> * ### Options:
<ide> * | 1 |
PHP | PHP | use a ternary instead of if/else | 2737bb477e3507d2264dd2596d711a2a58f3ccd4 | <ide><path>src/Http/Client.php
<ide> public function buildUrl(string $url, $query = [], array $options = []): string
<ide> if ($query) {
<ide> $q = strpos($url, '?') === false ? '?' : '&';
<ide> $url .= $q;
<del> if (is_string($query)) {
<del> $url .= $query;
<del> } else {
<del> $url .= http_build_query($query, '', '&', PHP_QUERY_RFC3986);
<del> }
<add> $url .= is_string($query) ? $query : http_build_query($query, '', '&', PHP_QUERY_RFC3986);
<ide> }
<ide>
<ide> if ($options['protocolRelative'] && preg_match('#^//#', $url)) { | 1 |
Python | Python | add support for the --modules-list | 13e4652bf11f8c1e13dfb397608c3eca1c3f4fc4 | <ide><path>glances/exports/glances_csv.py
<ide> def update(self, stats):
<ide> """Update stats in the CSV output file."""
<ide> # Get the stats
<ide> all_stats = stats.getAllExports()
<del> plugins = stats.getAllPlugins()
<add> plugins = stats.getPluginsList()
<ide>
<ide> # Init data with timestamp (issue#708)
<ide> if self.first_line:
<ide><path>glances/exports/graph.py
<ide> def reset(self, stats):
<ide> """Reset all the history."""
<ide> if not self.graph_enabled():
<ide> return False
<del> for p in stats.getAllPlugins():
<add> for p in stats.getPluginsList():
<ide> h = stats.get_plugin(p).get_stats_history()
<ide> if h is not None:
<ide> stats.get_plugin(p).reset_stats_history()
<ide> def generate_graph(self, stats):
<ide> return 0
<ide>
<ide> index_all = 0
<del> for p in stats.getAllPlugins():
<add> for p in stats.getPluginsList():
<ide> # History
<ide> h = stats.get_plugin(p).get_export_history()
<ide> # Current plugin item history list
<ide><path>glances/main.py
<ide> def init_args(self):
<ide> parser.add_argument('-C', '--config', dest='conf_file',
<ide> help='path to the configuration file')
<ide> # Disable plugin
<add> parser.add_argument('--modules-list', '--module-list',
<add> action='store_true', default=False,
<add> dest='modules_list',
<add> help='display modules (plugins & exports) list and exit')
<ide> parser.add_argument('--disable-plugin', dest='disable_plugin',
<ide> help='disable plugin (comma separed list)')
<ide> parser.add_argument('--disable-process', action='store_true', default=False,
<ide><path>glances/outputs/glances_bottle.py
<ide> def start(self, stats):
<ide> self.stats = stats
<ide>
<ide> # Init plugin list
<del> self.plugins_list = self.stats.getAllPlugins()
<add> self.plugins_list = self.stats.getPluginsList()
<ide>
<ide> # Bind the Bottle TCP address/port
<ide> if self.args.open_web_browser:
<ide><path>glances/outputs/glances_curses.py
<ide> def __get_stat_display(self, stats, layer):
<ide> """
<ide> ret = {}
<ide>
<del> for p in stats.getAllPlugins(enable=False):
<add> for p in stats.getPluginsList(enable=False):
<ide> if p == 'quicklook' or p == 'processlist':
<ide> # processlist is done later
<ide> # because we need to know how many processes could be displayed
<ide><path>glances/server.py
<ide> def getAll(self):
<ide>
<ide> def getAllPlugins(self):
<ide> # Return the plugins list
<del> return json.dumps(self.stats.getAllPlugins())
<add> return json.dumps(self.stats.getPluginsList())
<ide>
<ide> def getAllLimits(self):
<ide> # Return all the plugins limits
<ide><path>glances/standalone.py
<ide>
<ide> """Manage the Glances standalone session."""
<ide>
<add>import sys
<ide>
<ide> from glances.globals import WINDOWS
<ide> from glances.logger import logger
<ide> def __init__(self, config=None, args=None):
<ide> # Init stats
<ide> self.stats = GlancesStats(config=config, args=args)
<ide>
<add> # Modules (plugins and exporters) are loaded at this point
<add> # Glances can display the list if asked...
<add> if args.modules_list:
<add> self.display_modules_list()
<add> sys.exit(0)
<add>
<ide> # If process extended stats is disabled by user
<ide> if not args.enable_process_extended:
<ide> logger.debug("Extended stats for top process are disabled")
<ide> def __init__(self, config=None, args=None):
<ide> def quiet(self):
<ide> return self._quiet
<ide>
<add> def display_modules_list(self):
<add> """Display modules list"""
<add> print("Plugins list: {}".format(
<add> ', '.join(sorted(self.stats.getPluginsList(enable=False)))))
<add> print("Exporters list: {}".format(
<add> ', '.join(sorted(self.stats.getExportsList(enable=False)))))
<add>
<ide> def __serve_forever(self):
<ide> """Main loop for the CLI."""
<ide> # Start a counter used to compute the time needed for
<ide><path>glances/stats.py
<ide> def load_modules(self, args):
<ide> """Wrapper to load: plugins and export modules."""
<ide>
<ide> # Init the plugins dict
<add> # Active plugins dictionnary
<ide> self._plugins = collections.defaultdict(dict)
<del>
<ide> # Load the plugins
<ide> self.load_plugins(args=args)
<ide>
<ide> # Init the export modules dict
<add> # Active exporters dictionnary
<ide> self._exports = collections.defaultdict(dict)
<del>
<add> # All available exporters dictionnary
<add> self._exports_all = collections.defaultdict(dict)
<ide> # Load the export modules
<ide> self.load_exports(args=args)
<ide>
<ide> # Restoring system path
<ide> sys.path = sys_path
<ide>
<ide> def _load_plugin(self, plugin_script, args=None, config=None):
<del> """Load the plugin (script), init it and add to the _plugin dict"""
<add> """Load the plugin (script), init it and add to the _plugin dict."""
<ide> # The key is the plugin name
<ide> # for example, the file glances_xxx.py
<ide> # generate self._plugins_list["xxx"] = ...
<ide> def load_plugins(self, args=None):
<ide> args=args, config=self.config)
<ide>
<ide> # Log plugins list
<del> logger.debug("Available plugins list: {}".format(self.getAllPlugins()))
<add> logger.debug("Active plugins list: {}".format(self.getPluginsList()))
<ide>
<ide> def load_exports(self, args=None):
<ide> """Load all export modules in the 'exports' folder."""
<ide> if args is None:
<ide> return False
<ide> header = "glances_"
<del> # Transform the arguments list into a dict
<del> # The aim is to chec if the export module should be loaded
<add> # Build the export module available list
<ide> args_var = vars(locals()['args'])
<ide> for item in os.listdir(exports_path):
<ide> export_name = os.path.basename(item)[len(header):-3].lower()
<ide> if (item.startswith(header) and
<ide> item.endswith(".py") and
<ide> item != (header + "export.py") and
<del> item != (header + "history.py") and
<del> args_var['export_' + export_name] is not None and
<add> item != (header + "history.py")):
<add> self._exports_all[export_name] = None
<add>
<add> # Aim is to check if the export module should be loaded
<add> for export_name in self._exports_all:
<add> if (args_var['export_' + export_name] is not None and
<ide> args_var['export_' + export_name] is not False):
<ide> # Import the export module
<ide> export_module = __import__(os.path.basename(item)[:-3])
<ide> # Add the export to the dictionary
<ide> # The key is the module name
<ide> # for example, the file glances_xxx.py
<ide> # generate self._exports_list["xxx"] = ...
<del> self._exports[export_name] = export_module.Export(args=args, config=self.config)
<add> self._exports[export_name] = export_module.Export(args=args,
<add> config=self.config)
<add> self._exports_all[export_name] = self._exports[export_name]
<ide> # Log plugins list
<del> logger.debug("Available exports modules list: {}".format(self.getExportList()))
<add> logger.debug("Active exports modules list: {}".format(self.getExportsList()))
<ide> return True
<ide>
<del> def getAllPlugins(self, enable=True):
<del> """Return the enable plugins list.
<del> if enable is False, return the list of all the plugins"""
<add> def getPluginsList(self, enable=True):
<add> """Return the plugins list.
<add>
<add> if enable is True, only return the active plugins (default)
<add> if enable is False, return all the plugins
<add>
<add> Return: list of plugin name
<add> """
<ide> if enable:
<ide> return [p for p in self._plugins if self._plugins[p].is_enable()]
<ide> else:
<ide> return [p for p in self._plugins]
<ide>
<del> def getExportList(self):
<del> """Return the exports modules list."""
<del> return [e for e in self._exports]
<add> def getExportsList(self, enable=True):
<add> """Return the export module list.
<add>
<add> if enable is True, only return the active exporters (default)
<add> if enable is False, return all the exporters
<add>
<add> Return: list of export module name
<add> """
<add> if enable:
<add> return [e for e in self._exports]
<add> else:
<add> return [e for e in self._exports_all]
<ide>
<ide> def load_limits(self, config=None):
<ide> """Load the stats limits (except the one in the exclude list).""" | 8 |
Mixed | Text | add mem to csv output and manage flush | 0bfbaf2d3c0a52cf651663edbe36f53111d00844 | <ide><path>README.md
<del>[](https://flattr.com/submit/auto?user_id=nicolargo&url=https://github.com/nicolargo/glances&title=Glances&language=&tags=github&category=software)
<del>
<del>=============================
<del>Glances -- Eye on your system
<del>=============================
<del>
<del>## Description
<del>
<del>Glances is a CLI curses based monitoring tool for GNU/Linux and BSD OS.
<del>
<del>Glances uses the PsUtil library to get information from your system.
<del>
<del>It is developed in Python.
<del>
<del>
<del>
<del>## Installation
<del>
<del>### From package manager (very easy way)
<del>
<del>Packages exist for Arch, Fedora, Redhat, FreeBSD...
<del>
<del>### From PPA (easy way for Ubuntu/Mint...)
<del>
<del>Arnaud Hartmann (thanks to him !) maintains a PPA with the latest Glances version:
<del>
<del>To install the PPA just enter:
<del>
<del> $ sudo add-apt-repository ppa:arnaud-hartmann/glances-dev
<del> $ sudo apt-get update
<del>
<del>Then install Glances:
<del>
<del> $ sudo apt-get install glances
<del>
<del>### From PyPi (easy way)
<del>
<del>PyPi is an official Python package manager.
<del>
<del>You first need to install pypi on your system. For exemple on Debian/Ubuntu:
<del>
<del> $ sudo apt-get install python-pip
<del>
<del>Then install the latest Glances version:
<del>
<del> $ sudo pip install glances
<del>
<del>### From source
<del>
<del>Get the latest version:
<del>
<del> $ wget https://github.com/downloads/nicolargo/glances/glances-1.4.tar.gz
<del>
<del>Glances use a standard GNU style installer:
<del>
<del> $ tar zxvf glances-1.4.tar.gz
<del> $ cd glances-1.4
<del> $ sudo python setup.py install
<del>
<del>Pre-requisites:
<del>
<del>* Python 2.6+ (not tested with Python 3+)
<del>
<del>## Running
<del>
<del>Easy way (that's all folks !):
<del>
<del> $ glances.py
<del>
<del>## User guide
<del>
<del>By default, stats are refreshed every second, to change this setting, you can
<del>use the -t option. For exemple to set the refrech rate to 5 seconds:
<del>
<del> $ glances.py -t 5
<del>
<del>Importants stats are colored:
<del>
<del>* GREEN: stat counter is "OK"
<del>* BLUE: stat counter is "CAREFUL"
<del>* MAGENTA: stat counter is "WARNING"
<del>* RED: stat counter is "CRITICAL"
<del>
<del>When Glances is running, you can press:
<del>
<del>* 'h' to display an help message whith the keys you can press
<del>* 'a' to set the automatic mode. The processes are sorted automatically
<del>
<del> If CPU > 70%, sort by process "CPU consumption"
<del>
<del> If MEM > 70%, sort by process "memory size"
<del>
<del>* 'c' to sort the processes list by CPU consumption
<del>* 'd' Disable or enable the disk IO stats
<del>* 'f' Disable or enable the file system stats
<del>* 'l' Disable or enable the logs
<del>* 'm' to sort the processes list by process size
<del>* 'n' Disable or enable the network interfaces stats
<del>* 'q' Exit
<del>
<del>### Header
<del>
<del>
<del>
<del>The header shows the Glances version, the host name and the operating
<del>system name, version and architecture.
<del>
<del>### CPU
<del>
<del>
<del>
<del>The CPU states are shown as a percentage and for the configured refresh
<del>time.
<del>
<del>If user|kernel|nice CPU is < 50%, then status is set to "OK".
<del>
<del>If user|kernel|nice CPU is > 50%, then status is set to "CAREFUL".
<del>
<del>If user|kernel|nice CPU is > 70%, then status is set to "WARNING".
<del>
<del>If user|kernel|nice CPU is > 90%, then status is set to "CRITICAL".
<del>
<del>### Load
<del>
<del>
<del>
<del>On the Nosheep blog, Zach defines the average load: "In short it is the
<del>average sum of the number of processes waiting in the run-queue plus the
<del>number currently executing over 1, 5, and 15 minute time periods."
<del>
<del>Glances gets the number of CPU cores to adapt the alerts. With Glances,
<del>alerts on average load are only set on 5 and 15 mins.
<del>
<del>If average load is < O.7*Core, then status is set to "OK".
<del>
<del>If average load is > O.7*Core, then status is set to "CAREFUL".
<del>
<del>If average load is > 1*Core, then status is set to "WARNING".
<del>
<del>If average load is > 5*Core, then status is set to "CRITICAL".
<del>
<del>### Memory
<del>
<del>
<del>
<del>Glances uses tree columns: memory (RAM), swap and "real".
<del>
<del>Real used memory is: used - cache.
<del>
<del>Real free memory is: free + cache.
<del>
<del>With Glances, alerts are only set for on used swap and real memory.
<del>
<del>If memory is < 50%, then status is set to "OK".
<del>
<del>If memory is > 50%, then status is set to "CAREFUL".
<del>
<del>If memory is > 70%, then status is set to "WARNING".
<del>
<del>If memory is > 90%, then status is set to "CRITICAL".
<del>
<del>### Network bit rate
<del>
<del>
<del>
<del>Glances display the network interface bit rate. The unit is adapted
<del>dynamicaly (bits per second, Kbits per second, Mbits per second...).
<del>
<del>Alerts are set only if the network interface maximum speed is available.
<del>
<del>If bitrate is < 50%, then status is set to "OK".
<del>
<del>If bitrate is > 50%, then status is set to "CAREFUL".
<del>
<del>If bitrate is > 70%, then status is set to "WARNING".
<del>
<del>If bitrate is > 90%, then status is set to "CRITICAL".
<del>
<del>For exemple, on a 100 Mbps Ethernet interface, the warning status is set
<del>if the bit rate is higher than 70 Mbps.
<del>
<del>### Disk I/O
<del>
<del>
<del>
<del>Glances display the disk I/O throughput. The unit is adapted dynamicaly
<del>(bytes per second, Kbytes per second, Mbytes per second...).
<del>
<del>There is no alert on this information.
<del>
<del>### Filesystem
<del>
<del>
<del>
<del>Glances display the total and used filesytem disk space. The unit is
<del>adapted dynamicaly (bytes per second, Kbytes per second, Mbytes per
<del>second...).
<del>
<del>Alerts are set for used disk space:
<del>
<del>If disk used is < 50%, then status is set to "OK".
<del>
<del>If disk used is > 50%, then status is set to "CAREFUL".
<del>
<del>If disk used is > 70%, then status is set to "WARNING".
<del>
<del>If disk used is > 90%, then status is set to "CRITICAL".
<del>
<del>### Processes
<del>
<del>
<del>
<del>Glances displays a summary and a list of processes.
<del>
<del>By default (or if you hit the 'a' key) the process list is automaticaly
<del>sorted by CPU of memory consumption.
<del>
<del>The number of processes in the list is adapted to the screen size.
<del>
<del>### Logs
<del>
<del>
<del>
<del>A logs list is displayed in the bottom of the screen if (an only if):
<del>
<del>* at least one WARNING or CRITICAL alert was occured.
<del>* space is available in the bottom of the console/terminal
<del>
<del>There is one line per alert with the following information:
<del>
<del>* start date
<del>* end date
<del>* alert name
<del>* (min/avg/max) values
<del>
<del>### Footer
<del>
<del>
<del>
<del>Glances displays a caption and the current time/date.
<del>
<del>## Localisation
<del>
<del>To generate french locale execute as root or sudo :
<del>i18n_francais_generate.sh
<del>
<del>To generate spanish locale execute as root or sudo :
<del>i18n_espanol_generate.sh
<del>
<del>## Todo
<del>
<del>You are welcome to contribute to this software.
<del>
<del>* Packaging for Debian, Ubuntu, BSD...
<del>* Check the needed Python library in the configure.ac
<del>* Add file system stats when the python-statgrab is corrected
<ide><path>README.md
<add>README
<ide>\ No newline at end of file
<ide><path>glances/glances.py
<ide> from __future__ import generators
<ide>
<ide> __appname__ = 'glances'
<del>__version__ = "1.4b16"
<add>__version__ = "1.4b17"
<ide> __author__ = "Nicolas Hennion <nicolas@nicolargo.com>"
<ide> __licence__ = "LGPL"
<ide>
<ide> # Classes
<ide> #========
<ide>
<del>class Timer():
<add>class Timer:
<ide> """
<ide> The timer class
<ide> """
<ide> def finished(self):
<ide> return time.time() > self.target
<ide>
<ide>
<del>class glancesLimits():
<add>class glancesLimits:
<ide> """
<ide> Manage the limit OK,CAREFUL,WARNING,CRITICAL for each stats
<ide> """
<ide> def getLOADCritical(self, core=1):
<ide> return self.__limits_list['LOAD'][2] * core
<ide>
<ide>
<del>class glancesLogs():
<add>class glancesLogs:
<ide> """
<ide> The main class to manage logs inside the Glances software
<ide> Logs is a list of list:
<ide> def add(self, item_state, item_type, item_value):
<ide> return self.len()
<ide>
<ide>
<del>class glancesGrabFs():
<add>class glancesGrabFs:
<ide> """
<ide> Get FS stats
<ide> """
<ide> def get(self):
<ide> return self.fs_list
<ide>
<ide>
<del>class glancesStats():
<add>class glancesStats:
<ide> """
<ide> This class store, update and give stats
<ide> """
<ide> def getNow(self):
<ide> return self.now
<ide>
<ide>
<del>class glancesScreen():
<add>class glancesScreen:
<ide> """
<ide> This class manage the screen (display and key pressed)
<ide> """
<ide> def __init__(self, refresh_time=1):
<ide>
<ide> curses.start_color()
<ide> if hasattr(curses, 'use_default_colors'):
<del> curses.use_default_colors()
<add> try:
<add> curses.use_default_colors()
<add> except:
<add> pass
<ide> if hasattr(curses, 'noecho'):
<del> curses.noecho()
<add> try:
<add> curses.noecho()
<add> except:
<add> pass
<ide> if hasattr(curses, 'cbreak'):
<del> curses.cbreak()
<add> try:
<add> curses.cbreak()
<add> except:
<add> pass
<ide> if hasattr(curses, 'curs_set'):
<del> curses.curs_set(0)
<add> try:
<add> curses.curs_set(0)
<add> except:
<add> pass
<ide>
<ide> # Init colors
<ide> self.hascolors = False
<ide> def displayNow(self, now):
<ide> len(now_msg))
<ide>
<ide>
<del>class glancesHtml():
<add>class glancesHtml:
<ide> """
<ide> This class manages the HTML output
<ide> """
<ide> def update(self, stats):
<ide> f.close()
<ide>
<ide>
<del>class glancesCsv():
<add>class glancesCsv:
<ide> """
<ide> This class manages the Csv output
<ide> """
<del>
<add>
<ide> def __init__(self, cvsfile="./glances.csv", refresh_time=1):
<ide> # Global information to display
<ide>
<ide> def __init__(self, cvsfile="./glances.csv", refresh_time=1):
<ide>
<ide> # Set the ouput (CSV) path
<ide> try:
<del> self.__csvfile = csv.writer(open("%s" % cvsfile, "wb"))
<add> self.__cvsfile_fd = open("%s" % cvsfile, "wb")
<add> self.__csvfile = csv.writer(self.__cvsfile_fd)
<ide> except IOError, error:
<ide> print "Can not create the output CSV file: ", error[1]
<ide> sys.exit(0)
<ide>
<add> def exit(self):
<add> self.__cvsfile_fd.close()
<add>
<ide> def update(self, stats):
<ide> if (stats.getCpu()):
<ide> # Update CSV with the CPU stats
<ide> def update(self, stats):
<ide> load = stats.getLoad()
<ide> self.__csvfile.writerow(["load", load['min1'], \
<ide> load['min5'], load['min15']])
<add> if (stats.getMem() and stats.getMemSwap()):
<add> # Update CSV with the MEM stats
<add> mem = stats.getMem()
<add> self.__csvfile.writerow(["mem", mem['total'], \
<add> mem['used'], mem['free']])
<add> memswap = stats.getMemSwap()
<add> self.__csvfile.writerow(["swap", memswap['total'], \
<add> memswap['used'], memswap['free']])
<add> self.__cvsfile_fd.flush()
<ide>
<ide> # Global def
<ide> #===========
<ide> def main():
<ide>
<ide> def end():
<ide> screen.end()
<del>
<add>
<add> if (csv_tag):
<add> csvoutput.exit()
<add>
<ide> sys.exit(0)
<ide>
<ide> | 3 |
Ruby | Ruby | require some developer tools | 634efba2615db158adeba1d56fc0ebf873b4c71b | <ide><path>Library/Homebrew/homebrew_bootsnap.rb
<ide> # typed: false
<ide> # frozen_string_literal: true
<ide>
<del>if !ENV["HOMEBREW_NO_BOOTSNAP"] &&
<del> ENV["HOMEBREW_BOOTSNAP"] &&
<del> # portable ruby doesn't play nice with bootsnap
<del> !ENV["HOMEBREW_FORCE_VENDOR_RUBY"] &&
<del> (!ENV["HOMEBREW_MACOS_VERSION"] || ENV["HOMEBREW_MACOS_SYSTEM_RUBY_NEW_ENOUGH"]) &&
<del> # Apple Silicon doesn't play nice with bootsnap
<del> (ENV["HOMEBREW_PROCESSOR"] == "Intel")
<add>homebrew_bootsnap_enabled = !ENV["HOMEBREW_NO_BOOTSNAP"] &&
<add> ENV["HOMEBREW_BOOTSNAP"] &&
<add> # portable ruby doesn't play nice with bootsnap
<add> !ENV["HOMEBREW_FORCE_VENDOR_RUBY"] &&
<add> (!ENV["HOMEBREW_MACOS_VERSION"] || ENV["HOMEBREW_MACOS_SYSTEM_RUBY_NEW_ENOUGH"]) &&
<add> # Apple Silicon doesn't play nice with bootsnap
<add> (ENV["HOMEBREW_PROCESSOR"] == "Intel")
<ide>
<add># we need some development tools to build bootsnap native code
<add>development_tools_installed = if !homebrew_bootsnap_enabled
<add> false
<add>elsif RbConfig::CONFIG["host_os"].include? "darwin"
<add> File.directory?("/Applications/Xcode.app") || File.directory?("/Library/Developer/CommandLineTools")
<add>else
<add> File.executable?("/usr/bin/clang") || File.executable?("/usr/bin/gcc")
<add>end
<add>
<add>if homebrew_bootsnap_enabled && development_tools_installed
<ide> require "rubygems"
<ide>
<ide> begin | 1 |
Text | Text | add v3.9.0-beta.1 to changelog | aa0579b5dbc3e9568ebeaa034cf665e2f3c3a2ee | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.9.0-beta.1 (February 18, 2019)
<add>
<add>- [#17470](https://github.com/emberjs/ember.js/pull/17470) [DEPRECATION] Implements the Computed Property Modifier deprecation RFCs
<add> * Deprecates `.property()` (see [emberjs/rfcs#0375](https://github.com/emberjs/rfcs/blob/master/text/0375-deprecate-computed-property-modifier.md)
<add> * Deprecates `.volatile()` (see [emberjs/rfcs#0370](https://github.com/emberjs/rfcs/blob/master/text/0370-deprecate-computed-volatile.md)
<add> * Deprecates computed overridability (see [emberjs/rfcs#0369](https://github.com/emberjs/rfcs/blob/master/text/0369-deprecate-computed-clobberability.md)
<add>- [#17488](https://github.com/emberjs/ember.js/pull/17488) [DEPRECATION] Deprecate this.$() in curly components (see [emberjs/rfcs#0386](https://github.com/emberjs/rfcs/blob/master/text/0386-remove-jquery.md))
<add>- [#17489](https://github.com/emberjs/ember.js/pull/17489) [DEPRECATION] Deprecate Ember.$() (see [emberjs/rfcs#0386](https://github.com/emberjs/rfcs/blob/master/text/0386-remove-jquery.md))
<add>- [#17540](https://github.com/emberjs/ember.js/pull/17540) [DEPRECATION] Deprecate aliasMethod
<add>- [#17487](https://github.com/emberjs/ember.js/pull/17487) [BUGFIX] Fix scenario where aliased properties did not update in production mode
<add>
<ide> ### v3.8.0 (February 18, 2019)
<ide>
<ide> - [#17143](https://github.com/emberjs/ember.js/pull/17143) / [#17375](https://github.com/emberjs/ember.js/pull/17375) [FEATURE] Implement Element Modifier Manager RFC (see [emberjs/rfcs#0373](https://github.com/emberjs/rfcs/blob/master/text/0373-Element-Modifier-Managers.md)). | 1 |
Ruby | Ruby | handle the empty array correctly | efe4cbe5f273dc5eb16dda9a9363a8dd7c6b3bad | <ide><path>activemodel/lib/active_model/errors.rb
<ide> def clear
<ide>
<ide> # Do the error messages include an error with key +error+?
<ide> def include?(error)
<del> messages.include? error
<add> (v = messages[error]) && v.any?
<ide> end
<ide>
<ide> # Get messages for +key+
<ide><path>activemodel/test/cases/errors_test.rb
<ide> def test_include?
<ide> person.errors[:foo]
<ide> assert person.errors.empty?
<ide> assert person.errors.blank?
<add> assert !person.errors.include?(:foo)
<ide> end
<ide>
<ide> test "method validate! should work" do | 2 |
Text | Text | add el cap doc link | 6e5bef5ee167b6ed635ebd845cffa61339fa989b | <ide><path>share/doc/homebrew/Troubleshooting.md
<ide> Thank you!
<ide> * If you’re installing something Java-related, maybe you need the [Java Developer Update][] or [JDK 7][]?
<ide> * Check that **Command Line Tools for Xcode (CLT)** and/or **Xcode** are up to date.
<ide> * If things fail with permissions errors, check the permissions in `/usr/local`. If you’re unsure what to do, you can `sudo chown -R $(whoami) /usr/local`.
<add>* If you see permission errors after upgrading to El Capitan please see the [El Capitan and Homebrew](El_Capitan_and_Homebrew.md) document.
<ide>
<ide> #### Listen to Dr. Brew
<ide> | 1 |
Javascript | Javascript | address feedback for accumulatetwophaselisteners | d3ec42020d220777bf589bec36c9cd8300ec9742 | <ide><path>packages/legacy-events/EventPropagators.js
<ide> *
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<ide> */
<ide>
<del>import {
<del> getParentInstance,
<del> traverseTwoPhase,
<del> traverseEnterLeave,
<del>} from 'shared/ReactTreeTraversal';
<add>import type {Fiber} from 'react-reconciler/src/ReactFiber';
<add>import type {ReactSyntheticEvent} from 'legacy-events/ReactSyntheticEventType';
<ide>
<ide> import getListener from 'legacy-events/getListener';
<add>
<add>import {traverseEnterLeave} from 'shared/ReactTreeTraversal';
<ide> import accumulateInto from './accumulateInto';
<ide> import forEachAccumulated from './forEachAccumulated';
<ide>
<del>type PropagationPhases = 'bubbled' | 'captured';
<del>
<del>/**
<del> * Some event types have a notion of different registration names for different
<del> * "phases" of propagation. This finds listeners by a given phase.
<del> */
<del>function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) {
<del> const registrationName =
<del> event.dispatchConfig.phasedRegistrationNames[propagationPhase];
<del> return getListener(inst, registrationName);
<del>}
<del>
<ide> /**
<ide> * A small set of propagation patterns, each of which will accept a small amount
<ide> * of information, and generate a set of "dispatch ready event objects" - which
<ide> function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) {
<ide> * single one.
<ide> */
<ide>
<del>/**
<del> * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
<del> * here, allows us to not have to bind or create functions for each event.
<del> * Mutating the event's members allows us to not have to create a wrapping
<del> * "dispatch" object that pairs the event with the listener.
<del> */
<del>function accumulateDirectionalDispatches(inst, phase, event) {
<del> if (__DEV__) {
<del> if (!inst) {
<del> console.error('Dispatching inst must not be null');
<del> }
<del> }
<del> const listener = listenerAtPhase(inst, event, phase);
<del> if (listener) {
<del> event._dispatchListeners = accumulateInto(
<del> event._dispatchListeners,
<del> listener,
<del> );
<del> event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
<del> }
<del>}
<del>
<del>/**
<del> * Collect dispatches (must be entirely collected before dispatching - see unit
<del> * tests). Lazily allocate the array to conserve memory. We must loop through
<del> * each event and perform the traversal for each one. We cannot perform a
<del> * single traversal for the entire collection of events because each event may
<del> * have a different target.
<del> */
<del>export function accumulateTwoPhaseDispatchesSingle(event) {
<del> if (event && event.dispatchConfig.phasedRegistrationNames) {
<del> traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
<del> }
<del>}
<del>
<del>/**
<del> * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
<del> */
<del>function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
<del> if (event && event.dispatchConfig.phasedRegistrationNames) {
<del> const targetInst = event._targetInst;
<del> const parentInst = targetInst ? getParentInstance(targetInst) : null;
<del> traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
<del> }
<del>}
<del>
<ide> /**
<ide> * Accumulates without regard to direction, does not look for phased
<ide> * registration names. Same as `accumulateDirectDispatchesSingle` but without
<ide> * requiring that the `dispatchMarker` be the same as the dispatched ID.
<ide> */
<del>function accumulateDispatches(inst, ignoredDirection, event) {
<add>function accumulateDispatches(
<add> inst: Fiber,
<add> ignoredDirection: ?boolean,
<add> event: ReactSyntheticEvent,
<add>): void {
<ide> if (inst && event && event.dispatchConfig.registrationName) {
<ide> const registrationName = event.dispatchConfig.registrationName;
<ide> const listener = getListener(inst, registrationName);
<ide> function accumulateDispatches(inst, ignoredDirection, event) {
<ide> * `dispatchMarker`.
<ide> * @param {SyntheticEvent} event
<ide> */
<del>function accumulateDirectDispatchesSingle(event) {
<add>function accumulateDirectDispatchesSingle(event: ReactSyntheticEvent) {
<ide> if (event && event.dispatchConfig.registrationName) {
<ide> accumulateDispatches(event._targetInst, null, event);
<ide> }
<ide> }
<ide>
<del>export function accumulateTwoPhaseDispatches(events) {
<del> forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
<del>}
<del>
<del>export function accumulateTwoPhaseDispatchesSkipTarget(events) {
<del> forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
<del>}
<del>
<del>export function accumulateEnterLeaveDispatches(leave, enter, from, to) {
<add>export function accumulateEnterLeaveDispatches(
<add> leave: ReactSyntheticEvent,
<add> enter: ReactSyntheticEvent,
<add> from: Fiber,
<add> to: Fiber,
<add>) {
<ide> traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
<ide> }
<ide>
<del>export function accumulateDirectDispatches(events) {
<add>export function accumulateDirectDispatches(
<add> events: ?(Array<ReactSyntheticEvent> | ReactSyntheticEvent),
<add>) {
<ide> forEachAccumulated(events, accumulateDirectDispatchesSingle);
<ide> }
<ide><path>packages/legacy-events/ReactSyntheticEventType.js
<ide> export type ReactSyntheticEvent = {|
<ide> nativeEventTarget: EventTarget,
<ide> ) => ReactSyntheticEvent,
<ide> isPersistent: () => boolean,
<del> _dispatchInstances: null | Array<Fiber>,
<del> _dispatchListeners: null | Array<Function>,
<del> _targetInst: null | Fiber,
<add> _dispatchInstances: null | Array<Fiber> | Fiber,
<add> _dispatchListeners: null | Array<Function> | Function,
<add> _targetInst: Fiber,
<ide> type: string,
<ide> |};
<ide><path>packages/legacy-events/ResponderEventPlugin.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> */
<ide>
<del>import {getLowestCommonAncestor, isAncestor} from 'shared/ReactTreeTraversal';
<add>import {
<add> getLowestCommonAncestor,
<add> isAncestor,
<add> getParentInstance,
<add> traverseTwoPhase,
<add>} from 'shared/ReactTreeTraversal';
<ide>
<ide> import {
<ide> executeDirectDispatch,
<ide> hasDispatches,
<ide> executeDispatchesInOrderStopAtTrue,
<ide> getInstanceFromNode,
<ide> } from './EventPluginUtils';
<del>import {
<del> accumulateDirectDispatches,
<del> accumulateTwoPhaseDispatches,
<del> accumulateTwoPhaseDispatchesSkipTarget,
<del>} from './EventPropagators';
<add>import {accumulateDirectDispatches} from './EventPropagators';
<ide> import ResponderSyntheticEvent from './ResponderSyntheticEvent';
<ide> import ResponderTouchHistoryStore from './ResponderTouchHistoryStore';
<ide> import accumulate from './accumulate';
<ide> import {
<ide> moveDependencies,
<ide> endDependencies,
<ide> } from './ResponderTopLevelEventTypes';
<add>import getListener from './getListener';
<add>import accumulateInto from './accumulateInto';
<add>import forEachAccumulated from './forEachAccumulated';
<ide>
<ide> /**
<ide> * Instance of element that should respond to touch/move types of interactions,
<ide> const eventTypes = {
<ide> },
<ide> };
<ide>
<add>// Start of inline: the below functions were inlined from
<add>// EventPropagator.js, as they deviated from ReactDOM's newer
<add>// implementations.
<add>function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) {
<add> const registrationName =
<add> event.dispatchConfig.phasedRegistrationNames[propagationPhase];
<add> return getListener(inst, registrationName);
<add>}
<add>
<add>function accumulateDirectionalDispatches(inst, phase, event) {
<add> if (__DEV__) {
<add> if (!inst) {
<add> console.error('Dispatching inst must not be null');
<add> }
<add> }
<add> const listener = listenerAtPhase(inst, event, phase);
<add> if (listener) {
<add> event._dispatchListeners = accumulateInto(
<add> event._dispatchListeners,
<add> listener,
<add> );
<add> event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
<add> }
<add>}
<add>
<add>function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
<add> if (event && event.dispatchConfig.phasedRegistrationNames) {
<add> const targetInst = event._targetInst;
<add> const parentInst = targetInst ? getParentInstance(targetInst) : null;
<add> traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
<add> }
<add>}
<add>
<add>function accumulateTwoPhaseDispatchesSkipTarget(events) {
<add> forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
<add>}
<add>
<add>function accumulateTwoPhaseDispatchesSingle(event) {
<add> if (event && event.dispatchConfig.phasedRegistrationNames) {
<add> traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
<add> }
<add>}
<add>
<add>function accumulateTwoPhaseDispatches(events) {
<add> forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
<add>}
<add>// End of inline
<add>
<ide> /**
<ide> *
<ide> * Responder System:
<ide><path>packages/react-dom/src/client/ReactDOM.js
<ide> import {
<ide> eventNameDispatchConfigs,
<ide> injectEventPluginsByName,
<ide> } from 'legacy-events/EventPluginRegistry';
<del>import {
<del> accumulateTwoPhaseDispatches,
<del> accumulateDirectDispatches,
<del>} from 'legacy-events/EventPropagators';
<ide> import ReactVersion from 'shared/ReactVersion';
<ide> import invariant from 'shared/invariant';
<ide> import {warnUnstableRenderSubtreeIntoContainer} from 'shared/ReactFeatureFlags';
<ide> const Internals = {
<ide> getFiberCurrentPropsFromNode,
<ide> injectEventPluginsByName,
<ide> eventNameDispatchConfigs,
<del> accumulateTwoPhaseDispatches,
<del> accumulateDirectDispatches,
<ide> enqueueStateRestore,
<ide> restoreStateIfNeeded,
<ide> dispatchEvent,
<ide><path>packages/react-dom/src/events/BeforeInputEventPlugin.js
<ide> import {
<ide> } from './FallbackCompositionState';
<ide> import SyntheticCompositionEvent from './SyntheticCompositionEvent';
<ide> import SyntheticInputEvent from './SyntheticInputEvent';
<del>import {accumulateTwoPhaseListeners} from './DOMModernPluginEventSystem';
<add>import accumulateTwoPhaseListeners from './accumulateTwoPhaseListeners';
<ide>
<ide> const END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
<ide> const START_KEYCODE = 229;
<ide><path>packages/react-dom/src/events/ChangeEventPlugin.js
<ide> import isEventSupported from './isEventSupported';
<ide> import {getNodeFromInstance} from '../client/ReactDOMComponentTree';
<ide> import {updateValueIfChanged} from '../client/inputValueTracking';
<ide> import {setDefaultValue} from '../client/ReactDOMInput';
<del>import {accumulateTwoPhaseListeners} from './DOMModernPluginEventSystem';
<ide>
<ide> import {disableInputAttributeSyncing} from 'shared/ReactFeatureFlags';
<add>import accumulateTwoPhaseListeners from './accumulateTwoPhaseListeners';
<ide>
<ide> const eventTypes = {
<ide> change: {
<ide><path>packages/react-dom/src/events/DOMModernPluginEventSystem.js
<ide> import {registrationNameDependencies} from 'legacy-events/EventPluginRegistry';
<ide> import {batchedEventUpdates} from 'legacy-events/ReactGenericBatching';
<ide> import {executeDispatchesInOrder} from 'legacy-events/EventPluginUtils';
<ide> import {plugins} from 'legacy-events/EventPluginRegistry';
<del>import getListener from 'legacy-events/getListener';
<ide>
<del>import {HostRoot, HostPortal, HostComponent} from 'shared/ReactWorkTags';
<add>import {HostRoot, HostPortal} from 'shared/ReactWorkTags';
<ide>
<ide> import {addTrappedEventListener} from './ReactDOMEventListener';
<ide> import getEventTarget from './getEventTarget';
<ide> export function attachElementListener(listener: ReactDOMListener): void {
<ide> export function detachElementListener(listener: ReactDOMListener): void {
<ide> // TODO
<ide> }
<del>
<del>export function accumulateTwoPhaseListeners(event: ReactSyntheticEvent): void {
<del> const phasedRegistrationNames = event.dispatchConfig.phasedRegistrationNames;
<del> if (phasedRegistrationNames == null) {
<del> return;
<del> }
<del> const {bubbled, captured} = phasedRegistrationNames;
<del> const dispatchListeners = [];
<del> const dispatchInstances = [];
<del> let node = event._targetInst;
<del> let hasListeners = false;
<del>
<del> // Accumulate all instances and listeners via the target -> root path.
<del> while (node !== null) {
<del> // We only care for listeners that are on HostComponents (i.e. <div>)
<del> if (node.tag === HostComponent) {
<del> // Standard React on* listeners, i.e. onClick prop
<del> const captureListener = getListener(node, captured);
<del> if (captureListener != null) {
<del> hasListeners = true;
<del> // Capture listeners/instances should go at the start, so we
<del> // unshift them to the start of the array.
<del> dispatchListeners.unshift(captureListener);
<del> dispatchInstances.unshift(node);
<del> }
<del> const bubbleListener = getListener(node, bubbled);
<del> if (bubbleListener != null) {
<del> hasListeners = true;
<del> // Bubble listeners/instances should go at the end, so we
<del> // push them to the end of the array.
<del> dispatchListeners.push(bubbleListener);
<del> dispatchInstances.push(node);
<del> }
<del> }
<del> node = node.return;
<del> }
<del> // To prevent allocation to the event unless we actually
<del> // have listeners we use the flag we would have set above.
<del> if (hasListeners) {
<del> event._dispatchListeners = dispatchListeners;
<del> event._dispatchInstances = dispatchInstances;
<del> }
<del>}
<ide><path>packages/react-dom/src/events/SelectEventPlugin.js
<ide> import {getNodeFromInstance} from '../client/ReactDOMComponentTree';
<ide> import {hasSelectionCapabilities} from '../client/ReactInputSelection';
<ide> import {DOCUMENT_NODE} from '../shared/HTMLNodeType';
<ide> import {isListeningToAllDependencies} from './DOMEventListenerMap';
<del>import {accumulateTwoPhaseListeners} from './DOMModernPluginEventSystem';
<add>import accumulateTwoPhaseListeners from './accumulateTwoPhaseListeners';
<ide>
<ide> const skipSelectionChangeEvent =
<ide> canUseDOM && 'documentMode' in document && document.documentMode <= 11;
<ide><path>packages/react-dom/src/events/SimpleEventPlugin.js
<ide> import SyntheticTransitionEvent from './SyntheticTransitionEvent';
<ide> import SyntheticUIEvent from './SyntheticUIEvent';
<ide> import SyntheticWheelEvent from './SyntheticWheelEvent';
<ide> import getEventCharCode from './getEventCharCode';
<del>import {accumulateTwoPhaseListeners} from './DOMModernPluginEventSystem';
<add>import accumulateTwoPhaseListeners from './accumulateTwoPhaseListeners';
<ide>
<ide> // Only used in DEV for exhaustiveness validation.
<ide> const knownHTMLTopLevelTypes: Array<DOMTopLevelEventType> = [
<ide><path>packages/react-dom/src/events/accumulateTwoPhaseListeners.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> */
<add>
<add>import type {ReactSyntheticEvent} from 'legacy-events/ReactSyntheticEventType';
<add>
<add>import getListener from 'legacy-events/getListener';
<add>import {HostComponent} from 'shared/ReactWorkTags';
<add>
<add>export default function accumulateTwoPhaseListeners(
<add> event: ReactSyntheticEvent,
<add> skipTarget?: boolean,
<add>): void {
<add> const phasedRegistrationNames = event.dispatchConfig.phasedRegistrationNames;
<add> if (phasedRegistrationNames == null) {
<add> return;
<add> }
<add> const {bubbled, captured} = phasedRegistrationNames;
<add> const dispatchListeners = [];
<add> const dispatchInstances = [];
<add> let node = event._targetInst;
<add>
<add> // If we skip the target, then start the node at the parent
<add> // of the target.
<add> if (skipTarget) {
<add> node = node.return;
<add> }
<add>
<add> // Accumulate all instances and listeners via the target -> root path.
<add> while (node !== null) {
<add> // We only care for listeners that are on HostComponents (i.e. <div>)
<add> if (node.tag === HostComponent) {
<add> // Standard React on* listeners, i.e. onClick prop
<add> const captureListener = getListener(node, captured);
<add> if (captureListener != null) {
<add> // Capture listeners/instances should go at the start, so we
<add> // unshift them to the start of the array.
<add> dispatchListeners.unshift(captureListener);
<add> dispatchInstances.unshift(node);
<add> }
<add> const bubbleListener = getListener(node, bubbled);
<add> if (bubbleListener != null) {
<add> // Bubble listeners/instances should go at the end, so we
<add> // push them to the end of the array.
<add> dispatchListeners.push(bubbleListener);
<add> dispatchInstances.push(node);
<add> }
<add> }
<add> node = node.return;
<add> }
<add> // To prevent allocation to the event unless we actually
<add> // have listeners we check the length of one of the arrays.
<add> if (dispatchListeners.length > 0) {
<add> event._dispatchListeners = dispatchListeners;
<add> event._dispatchInstances = dispatchInstances;
<add> }
<add>}
<ide><path>packages/react-dom/src/test-utils/ReactTestUtils.js
<ide> import {ELEMENT_NODE} from '../shared/HTMLNodeType';
<ide> import * as DOMTopLevelEventTypes from '../events/DOMTopLevelEventTypes';
<ide> import {PLUGIN_EVENT_SYSTEM} from 'legacy-events/EventSystemFlags';
<ide> import act from './ReactTestUtilsAct';
<add>import forEachAccumulated from 'legacy-events/forEachAccumulated';
<add>import accumulateInto from 'legacy-events/accumulateInto';
<add>import {traverseTwoPhase} from 'shared/ReactTreeTraversal';
<ide>
<ide> const {findDOMNode} = ReactDOM;
<ide> // Keep in sync with ReactDOMUnstableNativeDependencies.js
<ide> const [
<ide> injectEventPluginsByName,
<ide> /* eslint-enable no-unused-vars */
<ide> eventNameDispatchConfigs,
<del> accumulateTwoPhaseDispatches,
<del> accumulateDirectDispatches,
<ide> enqueueStateRestore,
<ide> restoreStateIfNeeded,
<ide> dispatchEvent,
<ide> function nativeTouchData(x, y) {
<ide> };
<ide> }
<ide>
<add>// Start of inline: the below functions were inlined from
<add>// EventPropagator.js, as they deviated from ReactDOM's newer
<add>// implementations.
<add>function isInteractive(tag) {
<add> return (
<add> tag === 'button' ||
<add> tag === 'input' ||
<add> tag === 'select' ||
<add> tag === 'textarea'
<add> );
<add>}
<add>
<add>function shouldPreventMouseEvent(name, type, props) {
<add> switch (name) {
<add> case 'onClick':
<add> case 'onClickCapture':
<add> case 'onDoubleClick':
<add> case 'onDoubleClickCapture':
<add> case 'onMouseDown':
<add> case 'onMouseDownCapture':
<add> case 'onMouseMove':
<add> case 'onMouseMoveCapture':
<add> case 'onMouseUp':
<add> case 'onMouseUpCapture':
<add> case 'onMouseEnter':
<add> return !!(props.disabled && isInteractive(type));
<add> default:
<add> return false;
<add> }
<add>}
<add>
<add>/**
<add> * @param {object} inst The instance, which is the source of events.
<add> * @param {string} registrationName Name of listener (e.g. `onClick`).
<add> * @return {?function} The stored callback.
<add> */
<add>function getListener(inst: Fiber, registrationName: string) {
<add> let listener;
<add>
<add> // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
<add> // live here; needs to be moved to a better place soon
<add> const stateNode = inst.stateNode;
<add> if (!stateNode) {
<add> // Work in progress (ex: onload events in incremental mode).
<add> return null;
<add> }
<add> const props = getFiberCurrentPropsFromNode(stateNode);
<add> if (!props) {
<add> // Work in progress.
<add> return null;
<add> }
<add> listener = props[registrationName];
<add> if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
<add> return null;
<add> }
<add> invariant(
<add> !listener || typeof listener === 'function',
<add> 'Expected `%s` listener to be a function, instead got a value of `%s` type.',
<add> registrationName,
<add> typeof listener,
<add> );
<add> return listener;
<add>}
<add>
<add>function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) {
<add> const registrationName =
<add> event.dispatchConfig.phasedRegistrationNames[propagationPhase];
<add> return getListener(inst, registrationName);
<add>}
<add>
<add>function accumulateDispatches(inst, ignoredDirection, event) {
<add> if (inst && event && event.dispatchConfig.registrationName) {
<add> const registrationName = event.dispatchConfig.registrationName;
<add> const listener = getListener(inst, registrationName);
<add> if (listener) {
<add> event._dispatchListeners = accumulateInto(
<add> event._dispatchListeners,
<add> listener,
<add> );
<add> event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
<add> }
<add> }
<add>}
<add>
<add>function accumulateDirectionalDispatches(inst, phase, event) {
<add> if (__DEV__) {
<add> if (!inst) {
<add> console.error('Dispatching inst must not be null');
<add> }
<add> }
<add> const listener = listenerAtPhase(inst, event, phase);
<add> if (listener) {
<add> event._dispatchListeners = accumulateInto(
<add> event._dispatchListeners,
<add> listener,
<add> );
<add> event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
<add> }
<add>}
<add>
<add>function accumulateDirectDispatchesSingle(event) {
<add> if (event && event.dispatchConfig.registrationName) {
<add> accumulateDispatches(event._targetInst, null, event);
<add> }
<add>}
<add>
<add>function accumulateDirectDispatches(events) {
<add> forEachAccumulated(events, accumulateDirectDispatchesSingle);
<add>}
<add>
<add>function accumulateTwoPhaseDispatchesSingle(event) {
<add> if (event && event.dispatchConfig.phasedRegistrationNames) {
<add> traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
<add> }
<add>}
<add>
<add>function accumulateTwoPhaseDispatches(events) {
<add> forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
<add>}
<add>// End of inline
<add>
<ide> const Simulate = {};
<ide> const SimulateNative = {};
<ide>
<ide><path>packages/react-dom/src/test-utils/ReactTestUtilsAct.js
<ide> const [
<ide> getFiberCurrentPropsFromNode,
<ide> injectEventPluginsByName,
<ide> eventNameDispatchConfigs,
<del> accumulateTwoPhaseDispatches,
<del> accumulateDirectDispatches,
<ide> enqueueStateRestore,
<ide> restoreStateIfNeeded,
<ide> dispatchEvent,
<ide><path>packages/react-native-renderer/src/ReactNativeBridgeEventPlugin.js
<ide>
<ide> import type {AnyNativeEvent} from 'legacy-events/PluginModuleType';
<ide> import type {EventSystemFlags} from 'legacy-events/EventSystemFlags';
<del>import {
<del> accumulateTwoPhaseDispatches,
<del> accumulateDirectDispatches,
<del>} from 'legacy-events/EventPropagators';
<add>import {accumulateDirectDispatches} from 'legacy-events/EventPropagators';
<ide> import type {TopLevelType} from 'legacy-events/TopLevelEventTypes';
<ide> import SyntheticEvent from 'legacy-events/SyntheticEvent';
<ide> import invariant from 'shared/invariant';
<ide>
<ide> // Module provided by RN:
<ide> import {ReactNativeViewConfigRegistry} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface';
<add>import accumulateInto from 'legacy-events/accumulateInto';
<add>import getListener from 'legacy-events/getListener';
<add>import {traverseTwoPhase} from 'shared/ReactTreeTraversal';
<add>import forEachAccumulated from 'legacy-events/forEachAccumulated';
<ide>
<ide> const {
<ide> customBubblingEventTypes,
<ide> customDirectEventTypes,
<ide> } = ReactNativeViewConfigRegistry;
<ide>
<add>// Start of inline: the below functions were inlined from
<add>// EventPropagator.js, as they deviated from ReactDOM's newer
<add>// implementations.
<add>function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) {
<add> const registrationName =
<add> event.dispatchConfig.phasedRegistrationNames[propagationPhase];
<add> return getListener(inst, registrationName);
<add>}
<add>
<add>function accumulateDirectionalDispatches(inst, phase, event) {
<add> if (__DEV__) {
<add> if (!inst) {
<add> console.error('Dispatching inst must not be null');
<add> }
<add> }
<add> const listener = listenerAtPhase(inst, event, phase);
<add> if (listener) {
<add> event._dispatchListeners = accumulateInto(
<add> event._dispatchListeners,
<add> listener,
<add> );
<add> event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
<add> }
<add>}
<add>
<add>function accumulateTwoPhaseDispatchesSingle(event) {
<add> if (event && event.dispatchConfig.phasedRegistrationNames) {
<add> traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
<add> }
<add>}
<add>
<add>function accumulateTwoPhaseDispatches(events) {
<add> forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
<add>}
<add>// End of inline
<add>type PropagationPhases = 'bubbled' | 'captured';
<add>
<ide> const ReactNativeBridgeEventPlugin = {
<ide> eventTypes: {},
<ide> | 13 |
Python | Python | add tests for record array indexing | 2eb9610acab872538742ce7db5cbbae6cb23360e | <ide><path>numpy/core/tests/test_multiarray.py
<ide> def test_unicode_field_names(self):
<ide> def test_field_names(self):
<ide> # Test unicode and 8-bit / byte strings can be used
<ide> a = np.zeros((1,), dtype=[('f1', 'i4'),
<del> ('f2', [('sf1', 'i4')])])
<add> ('f2', 'i4'),
<add> ('f3', [('sf1', 'i4')])])
<ide> is_py3 = sys.version_info[0] >= 3
<ide> if is_py3:
<ide> funcs = (str,)
<ide> def test_field_names(self):
<ide> assert_raises(IndexError, b[0].__setitem__, fnn, 1)
<ide> assert_raises(IndexError, b[0].__getitem__, fnn)
<ide> # Subfield
<del> fn2 = func('f2')
<add> fn3 = func('f3')
<ide> sfn1 = func('sf1')
<del> b[fn2][sfn1] = 1
<del> assert_equal(b[fn2][sfn1], 1)
<del> assert_raises(ValueError, b[fn2].__setitem__, fnn, 1)
<del> assert_raises(ValueError, b[fn2].__getitem__, fnn)
<add> b[fn3][sfn1] = 1
<add> assert_equal(b[fn3][sfn1], 1)
<add> assert_raises(ValueError, b[fn3].__setitem__, fnn, 1)
<add> assert_raises(ValueError, b[fn3].__getitem__, fnn)
<add> # multiple Subfields
<add> fn2 = func('f2')
<add> b[fn2] = 3
<add> assert_equal(b[['f1','f2']][0].tolist(), (2, 3))
<add> assert_equal(b[['f2','f1']][0].tolist(), (3, 2))
<add> assert_equal(b[['f1','f3']][0].tolist(), (2, (1,)))
<ide> # non-ascii unicode field indexing is well behaved
<ide> if not is_py3:
<ide> raise SkipTest('non ascii unicode field indexing skipped; '
<ide> def test_field_names(self):
<ide> assert_raises(ValueError, a.__setitem__, u'\u03e0', 1)
<ide> assert_raises(ValueError, a.__getitem__, u'\u03e0')
<ide>
<add> def test_field_names_deprecation(self):
<add> import warnings
<add> from numpy.testing.utils import WarningManager
<add> def collect_warning_types(f, *args, **kwargs):
<add> ctx = WarningManager(record=True)
<add> warning_log = ctx.__enter__()
<add> warnings.simplefilter("always")
<add> try:
<add> f(*args, **kwargs)
<add> finally:
<add> ctx.__exit__()
<add> return [w.category for w in warning_log]
<add> a = np.zeros((1,), dtype=[('f1', 'i4'),
<add> ('f2', 'i4'),
<add> ('f3', [('sf1', 'i4')])])
<add> a['f1'][0] = 1
<add> a['f2'][0] = 2
<add> a['f3'][0] = (3,)
<add> b = np.zeros((1,), dtype=[('f1', 'i4'),
<add> ('f2', 'i4'),
<add> ('f3', [('sf1', 'i4')])])
<add> b['f1'][0] = 1
<add> b['f2'][0] = 2
<add> b['f3'][0] = (3,)
<add>
<add> # All the different functions raise a warning, but not an error, and
<add> # 'a' is not modified:
<add> assert_equal(collect_warning_types(a[['f1','f2']].__setitem__, 0, (10,20)),
<add> [DeprecationWarning])
<add> assert_equal(a, b)
<add> # Views also warn
<add> subset = a[['f1','f2']]
<add> subset_view = subset.view()
<add> assert_equal(collect_warning_types(subset_view['f1'].__setitem__, 0, 10),
<add> [DeprecationWarning])
<add> # But the write goes through:
<add> assert_equal(subset['f1'][0], 10)
<add> # Only one warning per multiple field indexing, though (even if there are
<add> # multiple views involved):
<add> assert_equal(collect_warning_types(subset['f1'].__setitem__, 0, 10),
<add> [])
<ide>
<ide> class TestView(TestCase):
<ide> def test_basic(self): | 1 |
Text | Text | add some documentation of the masking feature | 337f39bd026f88a8408e0449a45b9495dcfab434 | <ide><path>docs/sources/examples.md
<ide> from keras.layers.embeddings import Embedding
<ide> from keras.layers.recurrent import LSTM
<ide>
<ide> model = Sequential()
<add># Add a mask_zero=True to the Embedding connstructor if 0 is a left-padding value in your data
<ide> model.add(Embedding(max_features, 256))
<ide> model.add(LSTM(256, 128, activation='sigmoid', inner_activation='hard_sigmoid'))
<ide> model.add(Dropout(0.5))
<ide><path>docs/sources/layers/embeddings.md
<ide> ## Embedding
<ide>
<ide> ```python
<del>keras.layers.embeddings.Embedding(input_dim, output_dim, init='uniform', weights=None, W_regularizer=None, W_constraint=None)
<add>keras.layers.embeddings.Embedding(input_dim, output_dim, init='uniform', weights=None, W_regularizer=None, W_constraint=None, mask_zero=False)
<ide> ```
<ide>
<ide> Turn positive integers (indexes) into denses vectors of fixed size,
<ide> eg. `[[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]`
<ide> - __weights__: list of numpy arrays to set as initial weights. The list should have 1 element, of shape `(input_dim, output_dim)`.
<ide> - __W_regularizer__: instance of the [regularizers](../regularizers.md) module (eg. L1 or L2 regularization), applied to the embedding matrix.
<ide> - __W_constraint__: instance of the [constraints](../constraints.md) module (eg. maxnorm, nonneg), applied to the embedding matrix.
<add> - __mask_zero__: Whether or not the input value 0 is a special "padding" value that should be masked out. This is useful for [recurrent layers](recurrent.md) which may take variable length input. If this is `True` then all subsequent layers in the model need to support masking or an exception will be raised.
<ide>
<ide>
<ide> ## WordContextProduct
<ide><path>docs/sources/layers/recurrent.md
<ide> keras.layers.recurrent.SimpleRNN(input_dim, output_dim,
<ide> init='glorot_uniform', inner_init='orthogonal', activation='sigmoid', weights=None,
<ide> truncate_gradient=-1, return_sequences=False)
<ide> ```
<del>Fully connected RNN where output is to fed back to input. Not a particularly useful model, included for demonstration purposes.
<add>Fully connected RNN where output is to fed back to input.
<ide>
<ide> - __Input shape__: 3D tensor with shape: `(nb_samples, timesteps, input_dim)`.
<ide>
<ide> - __Output shape__:
<ide> - if `return_sequences`: 3D tensor with shape: `(nb_samples, timesteps, ouput_dim)`.
<ide> - else: 2D tensor with shape: `(nb_samples, output_dim)`.
<ide>
<add>- __Masking__: This layer supports masking for input data with a variable number of timesteps To introduce masks to your data, use an [Embedding](embeddings.md) layer with the `mask_zero` parameter set to `True`.
<add>
<add>
<ide> - __Arguments__:
<ide> - __input_dim__: dimension of the input.
<ide> - __output_dim__: dimension of the internal projections and the final output.
<ide> Not a particularly useful model, included for demonstration purposes.
<ide> - if `return_sequences`: 3D tensor with shape: `(nb_samples, timesteps, ouput_dim)`.
<ide> - else: 2D tensor with shape: `(nb_samples, output_dim)`.
<ide>
<add>- __Masking__: This layer supports masking for input data with a variable number of timesteps To introduce masks to your data, use an [Embedding](embeddings.md) layer with the `mask_zero` parameter set to `True`.
<add>
<add>
<ide> - __Arguments__:
<ide> - __input_dim__: dimension of the input.
<ide> - __output_dim__: dimension of the internal projections and the final output.
<ide> Gated Recurrent Unit - Cho et al. 2014.
<ide> - if `return_sequences`: 3D tensor with shape: `(nb_samples, timesteps, ouput_dim)`.
<ide> - else: 2D tensor with shape: `(nb_samples, output_dim)`.
<ide>
<add>- __Masking__: This layer supports masking for input data with a variable number of timesteps To introduce masks to your data, use an [Embedding](embeddings.md) layer with the `mask_zero` parameter set to true.
<add>
<ide> - __Arguments__:
<ide> - __input_dim__: dimension of the input.
<ide> - __output_dim__: dimension of the internal projections and the final output.
<ide> Long-Short Term Memory unit - Hochreiter 1997.
<ide> - if `return_sequences`: 3D tensor with shape: `(nb_samples, timesteps, ouput_dim)`.
<ide> - else: 2D tensor with shape: `(nb_samples, output_dim)`.
<ide>
<add>- __Masking__: This layer supports masking for input data with a variable number of timesteps To introduce masks to your data, use an [Embedding](embeddings.md) layer with the `mask_zero` parameter set to true.
<add>
<ide> - __Arguments__:
<ide> - __input_dim__: dimension of the input.
<ide> - __output_dim__: dimension of the internal projections and the final output.
<ide> Top 3 RNN architectures evolved from the evaluation of thousands of models. Serv
<ide> - if `return_sequences`: 3D tensor with shape: `(nb_samples, timesteps, ouput_dim)`.
<ide> - else: 2D tensor with shape: `(nb_samples, output_dim)`.
<ide>
<add>- __Masking__: This layer supports masking for input data with a variable number of timesteps To introduce masks to your data, use an [Embedding](embeddings.md) layer with the `mask_zero` parameter set to true.
<add>
<ide> - __Arguments__:
<ide> - __input_dim__: dimension of the input.
<ide> - __output_dim__: dimension of the internal projections and the final output.
<ide> Top 3 RNN architectures evolved from the evaluation of thousands of models. Serv
<ide> - [An Empirical Exploration of Recurrent Network Architectures](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)
<ide>
<ide>
<del>
<ide>\ No newline at end of file
<add>
<ide><path>docs/sources/objectives.md
<ide> An objective function (or loss function, or optimization score function) is one
<ide> model.compile(loss='mean_squared_error', optimizer='sgd')
<ide> ```
<ide>
<del>You can either pass the name of an existing objective, or pass a Theano symbolic function that returns a scalar and takes the following two arguments:
<add>You can either pass the name of an existing objective, or pass a Theano symbolic function that returns a scalar for each data-point and takes the following two arguments:
<ide>
<ide> - __y_true__: True labels. Theano tensor.
<ide> - __y_pred__: Predictions. Theano tensor of the same shape as y_true.
<ide>
<add>The actual optimized objective is the mean of the output array across all datapoints.
<add>
<ide> For a few examples of such functions, check out the [objectives source](https://github.com/fchollet/keras/blob/master/keras/objectives.py).
<ide>
<ide> ## Available objectives
<ide> For a few examples of such functions, check out the [objectives source](https://
<ide> - __squared_hinge__
<ide> - __hinge__
<ide> - __binary_crossentropy__: Also known as logloss.
<del>- __categorical_crossentropy__: Also known as multiclass logloss. __Note__: using this objective requires that your labels are binary arrays of shape `(nb_samples, nb_classes)`.
<ide>\ No newline at end of file
<add>- __categorical_crossentropy__: Also known as multiclass logloss. __Note__: using this objective requires that your labels are binary arrays of shape `(nb_samples, nb_classes)`. | 4 |
Ruby | Ruby | change the default `null` value for timestamps | ea3ba34506c72d636096245016b5ef9cfe27c566 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
<ide> def default_primary_key
<ide> end
<ide> end
<ide>
<add> module TimestampDefaultDeprecation # :nodoc:
<add> def emit_warning_if_null_unspecified(options)
<add> return if options.key?(:null)
<add>
<add> ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
<add> `timestamp` was called without specifying an option for `null`. In Rails
<add> 5.0, this behavior will change to `null: false`. You should manually
<add> specify `null: true` to prevent the behavior of your existing migrations
<add> from changing.
<add> MESSAGE
<add> end
<add> end
<add>
<ide> # Represents the schema of an SQL table in an abstract way. This class
<ide> # provides methods for manipulating the schema representation.
<ide> #
<ide> def default_primary_key
<ide> # The table definitions
<ide> # The Columns are stored as a ColumnDefinition in the +columns+ attribute.
<ide> class TableDefinition
<add> include TimestampDefaultDeprecation
<add>
<ide> # An array of ColumnDefinition objects, representing the column changes
<ide> # that have been defined.
<ide> attr_accessor :indexes
<ide> def index(column_name, options = {})
<ide> # <tt>:updated_at</tt> to the table.
<ide> def timestamps(*args)
<ide> options = args.extract_options!
<add> emit_warning_if_null_unspecified(options)
<ide> column(:created_at, :datetime, options)
<ide> column(:updated_at, :datetime, options)
<ide> end
<ide> def add_column(name, type, options)
<ide> # end
<ide> #
<ide> class Table
<add> include TimestampDefaultDeprecation
<add>
<ide> def initialize(table_name, base)
<ide> @table_name = table_name
<ide> @base = base
<ide> def rename_index(index_name, new_index_name)
<ide> # Adds timestamps (+created_at+ and +updated_at+) columns to the table. See SchemaStatements#add_timestamps
<ide> #
<ide> # t.timestamps
<del> def timestamps
<del> @base.add_timestamps(@table_name)
<add> def timestamps(options = {})
<add> emit_warning_if_null_unspecified(options)
<add> @base.add_timestamps(@table_name, options)
<ide> end
<ide>
<ide> # Changes the column's definition according to the new options.
<ide> def native
<ide> @base.native_database_types
<ide> end
<ide> end
<del>
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def columns_for_distinct(columns, orders) #:nodoc:
<ide> #
<ide> # add_timestamps(:suppliers)
<ide> #
<del> def add_timestamps(table_name)
<del> add_column table_name, :created_at, :datetime
<del> add_column table_name, :updated_at, :datetime
<add> def add_timestamps(table_name, options = {})
<add> add_column table_name, :created_at, :datetime, options
<add> add_column table_name, :updated_at, :datetime, options
<ide> end
<ide>
<ide> # Removes the timestamp columns (+created_at+ and +updated_at+) from the table definition.
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def remove_index_sql(table_name, options = {})
<ide> "DROP INDEX #{index_name}"
<ide> end
<ide>
<del> def add_timestamps_sql(table_name)
<del> [add_column_sql(table_name, :created_at, :datetime), add_column_sql(table_name, :updated_at, :datetime)]
<add> def add_timestamps_sql(table_name, options = {})
<add> [add_column_sql(table_name, :created_at, :datetime, options), add_column_sql(table_name, :updated_at, :datetime, options)]
<ide> end
<ide>
<ide> def remove_timestamps_sql(table_name)
<ide><path>activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb
<ide> def change
<ide> <% end -%>
<ide> <% end -%>
<ide> <% if options[:timestamps] %>
<del> t.timestamps
<add> t.timestamps null: false
<ide> <% end -%>
<ide> end
<ide> <% attributes_with_index.each do |attribute| -%>
<ide><path>activerecord/test/cases/adapters/mysql/active_schema_test.rb
<ide> def test_remove_timestamps
<ide> with_real_execute do
<ide> begin
<ide> ActiveRecord::Base.connection.create_table :delete_me do |t|
<del> t.timestamps
<add> t.timestamps null: true
<ide> end
<ide> ActiveRecord::Base.connection.remove_timestamps :delete_me
<ide> assert !column_present?('delete_me', 'updated_at', 'datetime')
<ide><path>activerecord/test/cases/adapters/mysql2/active_schema_test.rb
<ide> def test_remove_timestamps
<ide> with_real_execute do
<ide> begin
<ide> ActiveRecord::Base.connection.create_table :delete_me do |t|
<del> t.timestamps
<add> t.timestamps null: true
<ide> end
<ide> ActiveRecord::Base.connection.remove_timestamps :delete_me
<ide> assert !column_present?('delete_me', 'updated_at', 'datetime')
<ide><path>activerecord/test/cases/adapters/postgresql/timestamp_test.rb
<ide> def test_timestamp_data_type_with_precision
<ide>
<ide> def test_timestamps_helper_with_custom_precision
<ide> ActiveRecord::Base.connection.create_table(:foos) do |t|
<del> t.timestamps :precision => 4
<add> t.timestamps :null => true, :precision => 4
<ide> end
<ide> assert_equal 4, activerecord_column_option('foos', 'created_at', 'precision')
<ide> assert_equal 4, activerecord_column_option('foos', 'updated_at', 'precision')
<ide> end
<ide>
<ide> def test_passing_precision_to_timestamp_does_not_set_limit
<ide> ActiveRecord::Base.connection.create_table(:foos) do |t|
<del> t.timestamps :precision => 4
<add> t.timestamps :null => true, :precision => 4
<ide> end
<ide> assert_nil activerecord_column_option("foos", "created_at", "limit")
<ide> assert_nil activerecord_column_option("foos", "updated_at", "limit")
<ide> def test_passing_precision_to_timestamp_does_not_set_limit
<ide> def test_invalid_timestamp_precision_raises_error
<ide> assert_raises ActiveRecord::ActiveRecordError do
<ide> ActiveRecord::Base.connection.create_table(:foos) do |t|
<del> t.timestamps :precision => 7
<add> t.timestamps :null => true, :precision => 7
<ide> end
<ide> end
<ide> end
<ide>
<ide> def test_postgres_agrees_with_activerecord_about_precision
<ide> ActiveRecord::Base.connection.create_table(:foos) do |t|
<del> t.timestamps :precision => 4
<add> t.timestamps :null => true, :precision => 4
<ide> end
<ide> assert_equal '4', pg_datetime_precision('foos', 'created_at')
<ide> assert_equal '4', pg_datetime_precision('foos', 'updated_at')
<ide><path>activerecord/test/cases/ar_schema_test.rb
<ide> def setup
<ide> @connection.drop_table :fruits rescue nil
<ide> @connection.drop_table :nep_fruits rescue nil
<ide> @connection.drop_table :nep_schema_migrations rescue nil
<add> @connection.drop_table :has_timestamps rescue nil
<ide> ActiveRecord::SchemaMigration.delete_all rescue nil
<ide> end
<ide>
<ide> def test_normalize_version
<ide> assert_equal "017", ActiveRecord::SchemaMigration.normalize_migration_number("0017")
<ide> assert_equal "20131219224947", ActiveRecord::SchemaMigration.normalize_migration_number("20131219224947")
<ide> end
<add>
<add> def test_timestamps_without_null_is_deprecated_on_create_table
<add> assert_deprecated do
<add> ActiveRecord::Schema.define do
<add> create_table :has_timestamps do |t|
<add> t.timestamps
<add> end
<add> end
<add> end
<add> end
<add>
<add> def test_timestamps_without_null_is_deprecated_on_change_table
<add> assert_deprecated do
<add> ActiveRecord::Schema.define do
<add> create_table :has_timestamps
<add>
<add> change_table :has_timestamps do |t|
<add> t.timestamps
<add> end
<add> end
<add> end
<add> end
<add>
<add> def test_no_deprecation_warning_from_timestamps_on_create_table
<add> assert_not_deprecated do
<add> ActiveRecord::Schema.define do
<add> create_table :has_timestamps do |t|
<add> t.timestamps null: true
<add> end
<add>
<add> drop_table :has_timestamps
<add>
<add> create_table :has_timestamps do |t|
<add> t.timestamps null: false
<add> end
<add> end
<add> end
<add> end
<add>
<add> def test_no_deprecation_warning_from_timestamps_on_change_table
<add> assert_not_deprecated do
<add> ActiveRecord::Schema.define do
<add> create_table :has_timestamps
<add> change_table :has_timestamps do |t|
<add> t.timestamps null: true
<add> end
<add>
<add> drop_table :has_timestamps
<add>
<add> create_table :has_timestamps
<add> change_table :has_timestamps do |t|
<add> t.timestamps null: false, default: Time.now
<add> end
<add> end
<add> end
<add> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/migration/change_schema_test.rb
<ide> def test_create_table_raises_when_redefining_custom_primary_key_column
<ide> end
<ide>
<ide> def test_create_table_with_timestamps_should_create_datetime_columns
<del> connection.create_table table_name do |t|
<del> t.timestamps
<add> # FIXME: Remove the silence when we change the default `null` behavior
<add> ActiveSupport::Deprecation.silence do
<add> connection.create_table table_name do |t|
<add> t.timestamps
<add> end
<ide> end
<ide> created_columns = connection.columns(table_name)
<ide>
<ide><path>activerecord/test/cases/migration/change_table_test.rb
<ide> def test_remove_references_column_type_with_polymorphic_and_type
<ide>
<ide> def test_timestamps_creates_updated_at_and_created_at
<ide> with_change_table do |t|
<del> @connection.expect :add_timestamps, nil, [:delete_me]
<del> t.timestamps
<add> @connection.expect :add_timestamps, nil, [:delete_me, null: true]
<add> t.timestamps null: true
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/migration/helper.rb
<ide> def setup
<ide> super
<ide> @connection = ActiveRecord::Base.connection
<ide> connection.create_table :test_models do |t|
<del> t.timestamps
<add> t.timestamps null: true
<ide> end
<ide>
<ide> TestModel.reset_column_information
<ide><path>activerecord/test/cases/migration_test.rb
<ide> def test_adding_multiple_columns
<ide> t.string :qualification, :experience
<ide> t.integer :age, :default => 0
<ide> t.date :birthdate
<del> t.timestamps
<add> t.timestamps null: true
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/schema/schema.rb
<ide> def except(adapter_names_to_exclude)
<ide> t.integer :engines_count
<ide> t.integer :wheels_count
<ide> t.column :lock_version, :integer, null: false, default: 0
<del> t.timestamps
<add> t.timestamps null: false
<ide> end
<ide>
<ide> create_table :categories, force: true do |t|
<ide> def except(adapter_names_to_exclude)
<ide> t.references :best_friend_of
<ide> t.integer :insures, null: false, default: 0
<ide> t.timestamp :born_at
<del> t.timestamps
<add> t.timestamps null: false
<ide> end
<ide>
<ide> create_table :peoples_treasures, id: false, force: true do |t|
<ide> def except(adapter_names_to_exclude)
<ide> create_table :pets, primary_key: :pet_id, force: true do |t|
<ide> t.string :name
<ide> t.integer :owner_id, :integer
<del> t.timestamps
<add> t.timestamps null: false
<ide> end
<ide>
<ide> create_table :pirates, force: true do |t|
<ide> def except(adapter_names_to_exclude)
<ide> t.string :parent_title
<ide> t.string :type
<ide> t.string :group
<del> t.timestamps
<add> t.timestamps null: true
<ide> end
<ide>
<ide> create_table :toys, primary_key: :toy_id, force: true do |t|
<ide> t.string :name
<ide> t.integer :pet_id, :integer
<del> t.timestamps
<add> t.timestamps null: false
<ide> end
<ide>
<ide> create_table :traffic_lights, force: true do |t|
<ide><path>railties/test/generators/model_generator_test.rb
<ide> def test_model_with_polymorphic_belongs_to_attribute_generates_belongs_to_associ
<ide>
<ide> def test_migration_with_timestamps
<ide> run_generator
<del> assert_migration "db/migrate/create_accounts.rb", /t.timestamps/
<add> assert_migration "db/migrate/create_accounts.rb", /t.timestamps null: false/
<ide> end
<ide>
<ide> def test_migration_timestamps_are_skipped | 14 |
Javascript | Javascript | extract creation of usedchunks | 063c54f546b2298096ac2c1e06b443d16ed161a7 | <ide><path>lib/optimize/CommonsChunkPlugin.js
<ide> The available options are:
<ide> throw new Error("Invalid chunkNames argument");
<ide> }
<ide>
<add> getUsedChunks(compilation, allChunks, commonChunk, commonChunks, currentIndex, selectedChunks, isAsync) {
<add> const asyncOrNoSelectedChunk = selectedChunks === false || isAsync;
<add>
<add> if(Array.isArray(selectedChunks)) {
<add> return allChunks.filter(chunk => {
<add> const notCommmonChunk = chunk !== commonChunk;
<add> const isSelectedChunk = selectedChunks.indexOf(chunk.name) > -1;
<add> return notCommmonChunk && isSelectedChunk;
<add> });
<add> }
<add>
<add> if(asyncOrNoSelectedChunk) {
<add> // nothing to do here
<add> if(!commonChunk.chunks) {
<add> return [];
<add> }
<add>
<add> return commonChunk.chunks.filter((chunk) => {
<add> // we can only move modules from this chunk if the "commonChunk" is the only parent
<add> return isAsync || chunk.parents.length === 1;
<add> });
<add> }
<add>
<add> // this is an entry point - bad
<add> if(commonChunk.parents.length > 0) {
<add> compilation.errors.push(new Error("CommonsChunkPlugin: While running in normal mode it's not allowed to use a non-entry chunk (" + commonChunk.name + ")"));
<add> return;
<add> }
<add>
<add> return allChunks.filter((chunk) => {
<add> const found = commonChunks.indexOf(chunk);
<add> if(found >= currentIndex) return false;
<add> return chunk.hasRuntime();
<add> });
<add> }
<add>
<ide> apply(compiler) {
<ide> const filenameTemplate = this.filenameTemplate;
<ide> const minChunks = this.minChunks;
<ide> The available options are:
<ide>
<ide> const commonChunks = this.formCommonChunks(chunks, compilation);
<ide>
<del> commonChunks.forEach(function processCommonChunk(commonChunk, idx) {
<del> let usedChunks;
<del> if(Array.isArray(selectedChunks)) {
<del> usedChunks = chunks.filter(chunk => chunk !== commonChunk && selectedChunks.indexOf(chunk.name) >= 0);
<del> } else if(selectedChunks === false || asyncOption) {
<del> usedChunks = (commonChunk.chunks || []).filter((chunk) => {
<del> // we can only move modules from this chunk if the "commonChunk" is the only parent
<del> return asyncOption || chunk.parents.length === 1;
<del> });
<del> } else {
<del> if(commonChunk.parents.length > 0) {
<del> compilation.errors.push(new Error("CommonsChunkPlugin: While running in normal mode it's not allowed to use a non-entry chunk (" + commonChunk.name + ")"));
<del> return;
<del> }
<del> usedChunks = chunks.filter((chunk) => {
<del> const found = commonChunks.indexOf(chunk);
<del> if(found >= idx) return false;
<del> return chunk.hasRuntime();
<del> });
<add> commonChunks.forEach((commonChunk, idx) => {
<add> const usedChunks = this.getUsedChunks(compilation, chunks, commonChunk, commonChunks, idx, this.selectedChunks, this.async);
<add> // bail as this is an erronous state
<add> if(!usedChunks) {
<add> return;
<ide> }
<ide> let asyncChunk;
<ide> if(asyncOption) { | 1 |
Text | Text | add github package | ef6e720761f7f2c3aab70e1b390fa78d680a3b42 | <ide><path>docs/build-instructions/build-status.md
<ide> | [Exception Reporting](https://github.com/atom/exception-reporting) | [](https://travis-ci.org/atom/exception-reporting) | [](https://ci.appveyor.com/project/Atom/exception-reporting/branch/master) | [](https://david-dm.org/atom/exception-reporting) |
<ide> | [Find and Replace](https://github.com/atom/find-and-replace) | [](https://travis-ci.org/atom/find-and-replace) | [](https://ci.appveyor.com/project/Atom/find-and-replace/branch/master) | [](https://david-dm.org/atom/find-and-replace) |
<ide> | [Fuzzy Finder](https://github.com/atom/fuzzy-finder) | [](https://travis-ci.org/atom/fuzzy-finder) | [](https://ci.appveyor.com/project/Atom/fuzzy-finder/branch/master) | [](https://david-dm.org/atom/fuzzy-finder) |
<add>| [Github](https://github.com/atom/github) | [](https://travis-ci.com/atom/github) | [](https://ci.appveyor.com/project/Atom/github/branch/master) | [](https://david-dm.org/atom/github) |
<ide> | [Git Diff](https://github.com/atom/git-diff) | [](https://travis-ci.org/atom/git-diff) | [](https://ci.appveyor.com/project/Atom/git-diff/branch/master) | [](https://david-dm.org/atom/git-diff) |
<ide> | [Go to Line](https://github.com/atom/go-to-line) | [](https://travis-ci.org/atom/go-to-line) | [](https://ci.appveyor.com/project/Atom/go-to-line/branch/master) | [](https://david-dm.org/atom/go-to-line) |
<ide> | [Grammar Selector](https://github.com/atom/grammar-selector) | [](https://travis-ci.org/atom/grammar-selector) | [](https://ci.appveyor.com/project/Atom/grammar-selector/branch/master) | [](https://david-dm.org/atom/grammar-selector) | | 1 |
Mixed | Ruby | add signed ids to active record | 1a3dc42c172863fc2db24e9813203d2e793a9e2a | <ide><path>activerecord/CHANGELOG.md
<add>* Add support for finding records based on signed ids, which are tamper-proof, verified ids that can be
<add> set to expire and scoped with a purpose. This is particularly useful for things like password reset
<add> or email verification, where you want the bearer of the signed id to be able to interact with the
<add> underlying record, but usually only within a certain time period.
<add>
<add> ```ruby
<add> signed_id = User.first.signed_id expires_in: 15.minutes, purpose: :password_reset
<add>
<add> User.find_signed signed_id # => nil, since the purpose does not match
<add>
<add> travel 16.minutes
<add> User.find_signed signed_id, purpose: :password_reset # => nil, since the signed id has expired
<add>
<add> travel_back
<add> User.find_signed signed_id, purpose: :password_reset # => User.first
<add>
<add> User.find_signed! "bad data" # => ActiveSupport::MessageVerifier::InvalidSignature
<add> ```
<add>
<add> *DHH*
<add>
<ide> * Support `ALGORITHM = INSTANT` DDL option for index operations on MySQL.
<ide>
<ide> *Ryuta Kamizono*
<ide><path>activerecord/lib/active_record.rb
<ide> module ActiveRecord
<ide> autoload :Serialization
<ide> autoload :StatementCache
<ide> autoload :Store
<add> autoload :SignedId
<ide> autoload :Suppressor
<ide> autoload :Timestamp
<ide> autoload :Transactions
<ide><path>activerecord/lib/active_record/base.rb
<ide> class Base
<ide> include Serialization
<ide> include Store
<ide> include SecureToken
<add> include SignedId
<ide> include Suppressor
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/railtie.rb
<ide> class Railtie < Rails::Railtie # :nodoc:
<ide> self.filter_attributes += Rails.application.config.filter_parameters
<ide> end
<ide> end
<add>
<add> initializer "active_record.set_signed_id_verifier_secret" do
<add> ActiveSupport.on_load(:active_record) do
<add> self.signed_id_verifier_secret ||= Rails.application.key_generator.generate_key("active_record/signed_id")
<add> end
<add> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/signed_id.rb
<add># frozen_string_literal: true
<add>
<add>module ActiveRecord
<add> # = Active Record Signed Id
<add> module SignedId
<add> extend ActiveSupport::Concern
<add>
<add> included do
<add> ##
<add> # :singleton-method:
<add> # Set the secret used for the signed id verifier instance when using Active Record outside of Rails.
<add> # Within Rails, this is automatically set using the Rails application key generator.
<add> mattr_accessor :signed_id_verifier_secret, instance_writer: false
<add> end
<add>
<add> module ClassMethods
<add> # Lets you find a record based on a signed id that's safe to put into the world without risk of tampering.
<add> # This is particularly useful for things like password reset or email verification, where you want
<add> # the bearer of the signed id to be able to interact with the underlying record, but usually only within
<add> # a certain time period.
<add> #
<add> # You set the time period that the signed id is valid for during generation, using the instance method
<add> # +signed_id(expires_in: 15.minutes)+. If the time has elapsed before a signed find is attempted,
<add> # the signed id will no longer be valid, and nil is returned.
<add> #
<add> # It's possible to further restrict the use of a signed id with a purpose. This helps when you have a
<add> # general base model, like a User, which might have signed ids for several things, like password reset
<add> # or email verification. The purpose that was set during generation must match the purpose set when
<add> # finding. If there's a mismatch, nil is again returned.
<add> #
<add> # ==== Examples
<add> #
<add> # signed_id = User.first.signed_id expires_in: 15.minutes, purpose: :password_reset
<add> #
<add> # User.find_signed signed_id # => nil, since the purpose does not match
<add> #
<add> # travel 16.minutes
<add> # User.find_signed signed_id, purpose: :password_reset # => nil, since the signed id has expired
<add> #
<add> # travel_back
<add> # User.find_signed signed_id, purpose: :password_reset # => User.first
<add> def find_signed(signed_id, purpose: nil)
<add> if id = signed_id_verifier.verified(signed_id, purpose: combine_signed_id_purposes(purpose))
<add> find_by id: id
<add> end
<add> end
<add>
<add> # Works like +find_signed+, but will raise a +ActiveSupport::MessageVerifier::InvalidSignature+
<add> # exception if the +signed_id+ has either expired, has a purpose mismatch, is for another record,
<add> # or has been tampered with. It will also raise a +ActiveRecord::RecordNotFound+ exception if
<add> # the valid signed id can't find a record.
<add> #
<add> # === Examples
<add> #
<add> # User.find_signed! "bad data" # => ActiveSupport::MessageVerifier::InvalidSignature
<add> #
<add> # signed_id = User.first.signed_id
<add> # User.first.destroy
<add> # User.find_signed! signed_id # => ActiveRecord::RecordNotFound
<add> def find_signed!(signed_id, purpose: nil)
<add> if id = signed_id_verifier.verify(signed_id, purpose: combine_signed_id_purposes(purpose))
<add> find(id)
<add> end
<add> end
<add>
<add> # The verifier instance that all signed ids are generated and verified from. By default, it'll be initialized
<add> # with the class-level +signed_id_verifier_secret+, which within Rails comes from the
<add> # Rails.application.key_generator. By default, it's SHA256 for the digest and JSON for the serialization.
<add> def signed_id_verifier
<add> @signed_id_verifier ||= begin
<add> if signed_id_verifier_secret.nil?
<add> raise ArgumentError, "You must set ActiveRecord::Base.signed_id_verifier_secret to use signed ids"
<add> else
<add> ActiveSupport::MessageVerifier.new signed_id_verifier_secret, digest: "SHA256", serializer: JSON
<add> end
<add> end
<add> end
<add>
<add> # Allows you to pass in a custom verifier used for the signed ids. This also allows you to use different
<add> # verifiers for different classes. This is also helpful if you need to rotate keys, as you can prepare
<add> # your custom verifier for that in advance. See +ActiveSupport::MessageVerifier+ for details.
<add> def signed_id_verifier=(verifier)
<add> @signed_id_verifier = verifier
<add> end
<add>
<add> # :nodoc:
<add> def combine_signed_id_purposes(purpose)
<add> [ name.underscore, purpose.to_s ].compact_blank.join("/")
<add> end
<add> end
<add>
<add>
<add> # Returns a signed id that's generated using a preconfigured +ActiveSupport::MessageVerifier+ instance.
<add> # This signed id is tamper proof, so it's safe to send in an email or otherwise share with the outside world.
<add> # It can further more be set to expire (the default is not to expire), and scoped down with a specific purpose.
<add> # If the expiration date has been exceeded before +find_signed+ is called, the id won't find the designated
<add> # record. If a purpose is set, this too must match.
<add> #
<add> # If you accidentally let a signed id out in the wild that you wish to retract sooner than its expiration date
<add> # (or maybe you forgot to set an expiration date while meaning to!), you can use the purpose to essentially
<add> # version the signed_id, like so:
<add> #
<add> # user.signed_id purpose: :v2
<add> #
<add> # And you then change your +find_signed+ calls to require this new purpose. Any old signed ids that were not
<add> # created with the purpose will no longer find the record.
<add> def signed_id(expires_in: nil, purpose: nil)
<add> self.class.signed_id_verifier.generate id, expires_in: expires_in, purpose: self.class.combine_signed_id_purposes(purpose)
<add> end
<add> end
<add>end
<ide><path>activerecord/test/cases/signed_id_test.rb
<add># frozen_string_literal: true
<add>
<add>require "cases/helper"
<add>require "models/account"
<add>require "models/company"
<add>
<add>SIGNED_ID_VERIFIER_TEST_SECRET = "This is normally set by the railtie initializer when used with Rails!"
<add>
<add>ActiveRecord::Base.signed_id_verifier_secret = SIGNED_ID_VERIFIER_TEST_SECRET
<add>
<add>class SignedIdTest < ActiveRecord::TestCase
<add> fixtures :accounts
<add>
<add> setup { @account = Account.first }
<add>
<add> test "find signed record" do
<add> assert_equal @account, Account.find_signed(@account.signed_id)
<add> end
<add>
<add> test "find signed record with a bang" do
<add> assert_equal @account, Account.find_signed!(@account.signed_id)
<add> end
<add>
<add> test "fail to find record from broken signed id" do
<add> assert_nil Account.find_signed("this won't find anything")
<add> end
<add>
<add> test "find signed record within expiration date" do
<add> assert_equal @account, Account.find_signed(@account.signed_id(expires_in: 1.minute))
<add> end
<add>
<add> test "fail to find signed record within expiration date" do
<add> signed_id = @account.signed_id(expires_in: 1.minute)
<add> travel 2.minutes
<add> assert_nil Account.find_signed(signed_id)
<add> end
<add>
<add> test "fail to find record from that has since been destroyed" do
<add> signed_id = @account.signed_id(expires_in: 1.minute)
<add> @account.destroy
<add> assert_nil Account.find_signed signed_id
<add> end
<add>
<add> test "finding record from broken signed id raises on the bang" do
<add> assert_raises(ActiveSupport::MessageVerifier::InvalidSignature) do
<add> Account.find_signed! "this will blow up"
<add> end
<add> end
<add>
<add> test "finding signed record outside expiration date raises on the bang" do
<add> signed_id = @account.signed_id(expires_in: 1.minute)
<add> travel 2.minutes
<add>
<add> assert_raises(ActiveSupport::MessageVerifier::InvalidSignature) do
<add> Account.find_signed!(signed_id)
<add> end
<add> end
<add>
<add> test "finding signed record that has been destroyed raises on the bang" do
<add> signed_id = @account.signed_id(expires_in: 1.minute)
<add> @account.destroy
<add>
<add> assert_raises(ActiveRecord::RecordNotFound) do
<add> Account.find_signed!(signed_id)
<add> end
<add> end
<add>
<add> test "fail to work without a signed_id_verifier_secret" do
<add> ActiveRecord::Base.signed_id_verifier_secret = nil
<add> Account.instance_variable_set :@signed_id_verifier, nil
<add>
<add> assert_raises(ArgumentError) do
<add> @account.signed_id
<add> end
<add> ensure
<add> ActiveRecord::Base.signed_id_verifier_secret = SIGNED_ID_VERIFIER_TEST_SECRET
<add> end
<add>
<add> test "use a custom verifier" do
<add> old_verifier = Account.signed_id_verifier
<add> Account.signed_id_verifier = ActiveSupport::MessageVerifier.new("sekret")
<add> assert_not_equal ActiveRecord::Base.signed_id_verifier, Account.signed_id_verifier
<add> assert_equal @account, Account.find_signed(@account.signed_id)
<add> ensure
<add> Account.signed_id_verifier = old_verifier
<add> end
<add>end | 6 |
Ruby | Ruby | fix version misdetections for urls with os/archs | a9e8dfb9960b6d3c75f7152a16f7496b41679943 | <ide><path>Library/Homebrew/test/test_versions.rb
<ide> def test_aespipe_version_style
<ide> assert_version_detected '2.4c',
<ide> 'http://loop-aes.sourceforge.net/aespipe/aespipe-v2.4c.tar.bz2'
<ide> end
<add>
<add> def test_win_style
<add> assert_version_detected '0.9.17',
<add> 'http://ftpmirror.gnu.org/libmicrohttpd/libmicrohttpd-0.9.17-w32.zip'
<add> assert_version_detected '1.29',
<add> 'http://ftpmirror.gnu.org/libidn/libidn-1.29-win64.zip'
<add> end
<add>
<add> def test_with_arch
<add> assert_version_detected '4.0.18-1',
<add> 'http://ftpmirror.gnu.org/mtools/mtools-4.0.18-1.i686.rpm'
<add> assert_version_detected '2.8',
<add> 'http://ftpmirror.gnu.org/libtasn1/libtasn1-2.8-x86.zip'
<add> end
<ide> end
<ide><path>Library/Homebrew/version.rb
<ide> def self._parse spec
<ide> m = /-((?:\d+\.)*\d+-beta\d*)$/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<add> # e.g. http://ftpmirror.gnu.org/libidn/libidn-1.29-win64.zip
<add> # e.g. http://ftpmirror.gnu.org/libmicrohttpd/libmicrohttpd-0.9.17-w32.zip
<add> m = /-(\d+\.\d+(?:\.\d+)?)-w(?:in)?(?:32|64)$/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. http://ftpmirror.gnu.org/mtools/mtools-4.0.18-1.i686.rpm
<add> # e.g. http://ftpmirror.gnu.org/libtasn1/libtasn1-2.8-x86.zip
<add> m = /-(\d+\.\d+(?:\.\d+)?(?:-\d+)?)[-_.](?:i686|x86(?:[-_](?:32|64))?)$/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<ide> # e.g. foobar4.5.1
<ide> m = /((?:\d+\.)*\d+)$/.match(stem)
<ide> return m.captures.first unless m.nil? | 2 |
Ruby | Ruby | remove dead test | 19e68e9d472f81f9856cd10fba4ba75f653c90e4 | <ide><path>actionpack/test/controller/streaming_test.rb
<ide> def test_write_to_stream
<ide> get :basic_stream
<ide> assert_equal "hello\nworld\n", @response.body
<ide> end
<del>
<del> def test_write_after_close
<del> @response.stream
<del> end
<ide> end
<ide> end | 1 |
PHP | PHP | expand path before is_file check | 8db9bcaddbf18c56213d10afcb06593405ddaf6a | <ide><path>src/Core/Configure/FileConfigTrait.php
<ide> protected function _getFilePath($key, $checkExists = false)
<ide>
<ide> $file .= $this->_extension;
<ide>
<del> if ($checkExists && !is_file($file)) {
<add> if ($checkExists && !is_file(realpath($file))) {
<ide> throw new Exception(sprintf('Could not load configuration file: %s', $file));
<ide> }
<ide> | 1 |
Python | Python | add tag_map argument to cli debug-data and train | a4cacd3402848299444c477cb2f1a292425b29af | <ide><path>spacy/cli/debug_data.py
<ide> lang=("model language", "positional", None, str),
<ide> train_path=("location of JSON-formatted training data", "positional", None, Path),
<ide> dev_path=("location of JSON-formatted development data", "positional", None, Path),
<add> tag_map_path=("Location of JSON-formatted tag map", "option", "tm", Path),
<ide> base_model=("name of model to update (optional)", "option", "b", str),
<ide> pipeline=(
<ide> "Comma-separated names of pipeline components to train",
<ide> def debug_data(
<ide> lang,
<ide> train_path,
<ide> dev_path,
<add> tag_map_path=None,
<ide> base_model=None,
<ide> pipeline="tagger,parser,ner",
<ide> ignore_warnings=False,
<ide> def debug_data(
<ide> if not dev_path.exists():
<ide> msg.fail("Development data not found", dev_path, exits=1)
<ide>
<add> tag_map = {}
<add> if tag_map_path is not None:
<add> tag_map = srsly.read_json(tag_map_path)
<add>
<ide> # Initialize the model and pipeline
<ide> pipeline = [p.strip() for p in pipeline.split(",")]
<ide> if base_model:
<ide> nlp = load_model(base_model)
<ide> else:
<ide> lang_cls = get_lang_class(lang)
<ide> nlp = lang_cls()
<add> # Update tag map with provided mapping
<add> nlp.vocab.morphology.tag_map.update(tag_map)
<ide>
<ide> msg.divider("Data format validation")
<ide>
<ide> def debug_data(
<ide> if "tagger" in pipeline:
<ide> msg.divider("Part-of-speech Tagging")
<ide> labels = [label for label in gold_train_data["tags"]]
<del> tag_map = nlp.Defaults.tag_map
<add> tag_map = nlp.vocab.morphology.tag_map
<ide> msg.info(
<ide> "{} {} in data ({} {} in tag map)".format(
<ide> len(labels),
<ide><path>spacy/cli/train.py
<ide> textcat_multilabel=("Textcat classes aren't mutually exclusive (multilabel)", "flag", "TML", bool),
<ide> textcat_arch=("Textcat model architecture", "option", "ta", str),
<ide> textcat_positive_label=("Textcat positive label for binary classes with two labels", "option", "tpl", str),
<add> tag_map_path=("Location of JSON-formatted tag map", "option", "tm", Path),
<ide> verbose=("Display more information for debug", "flag", "VV", bool),
<ide> debug=("Run data diagnostics before training", "flag", "D", bool),
<ide> # fmt: on
<ide> def train(
<ide> textcat_multilabel=False,
<ide> textcat_arch="bow",
<ide> textcat_positive_label=None,
<add> tag_map_path=None,
<ide> verbose=False,
<ide> debug=False,
<ide> ):
<ide> def train(
<ide> if not output_path.exists():
<ide> output_path.mkdir()
<ide>
<add> tag_map = {}
<add> if tag_map_path is not None:
<add> tag_map = srsly.read_json(tag_map_path)
<ide> # Take dropout and batch size as generators of values -- dropout
<ide> # starts high and decays sharply, to force the optimizer to explore.
<ide> # Batch size starts at 1 and grows, so that we make updates quickly
<ide> def train(
<ide> pipe_cfg = {}
<ide> nlp.add_pipe(nlp.create_pipe(pipe, config=pipe_cfg))
<ide>
<add> # Update tag map with provided mapping
<add> nlp.vocab.morphology.tag_map.update(tag_map)
<add>
<ide> if vectors:
<ide> msg.text("Loading vector from model '{}'".format(vectors))
<ide> _load_vectors(nlp, vectors) | 2 |
Text | Text | fix subtitle translation | d259580de47f6e6e1a53db99cb66155b073d89e6 | <ide><path>curriculum/challenges/portuguese/01-responsive-web-design/applied-accessibility/avoid-colorblindness-issues-by-using-sufficient-contrast.portuguese.md
<ide> tests:
<ide> ## Solução
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><head>
<add> <style>
<add> body {
<add> color: hsl(0, 55%, 15%);
<add> background-color: hsl(120, 25%, 55%);
<add> }
<add> </style>
<add></head>
<add><body>
<add> <header>
<add> <h1>Deep Thoughts with Master Camper Cat</h1>
<add> </header>
<add> <article>
<add> <h2>A Word on the Recent Catnip Doping Scandal</h2>
<add> <p>The influence that catnip has on feline behavior is well-documented, and its use as an herbal supplement in competitive ninja circles remains controversial. Once again, the debate to ban the substance is brought to the public's attention after the high-profile win of Kittytron, a long-time proponent and user of the green stuff, at the Claw of Fury tournament.</p>
<add> <p>As I've stated in the past, I firmly believe a true ninja's skills must come from within, with no external influences. My own catnip use shall continue as purely recreational.</p>
<add> </article>
<add></body>
<ide> ```
<ide> </section> | 1 |
Text | Text | fix a small typo | 64e9f4d9c89a6c557fd1f182d238f280111f9e02 | <ide><path>docs/recipes/WritingTests.md
<ide> First, we will install [Enzyme](http://airbnb.io/enzyme/). Enzyme uses the [Reac
<ide> npm install --save-dev enzyme
<ide> ```
<ide>
<del>We will also need to install Enzyme adapter for our version of React. Enzyme has adapters that provide compatability with `React 16.x`, `React 15.x`, `React 0.14.x` and `React 0.13.x`. If you are using React 16 you can run:
<add>We will also need to install Enzyme adapter for our version of React. Enzyme has adapters that provide compatibility with `React 16.x`, `React 15.x`, `React 0.14.x` and `React 0.13.x`. If you are using React 16 you can run:
<ide>
<ide> ```
<ide> npm install --save-dev enzyme-adapter-react-16 | 1 |
Java | Java | use port scanning for jmx tests | b1485420b689a74722ad93a78f93334b57d023f7 | <ide><path>spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java
<ide> import javax.management.remote.JMXConnectorServerFactory;
<ide> import javax.management.remote.JMXServiceURL;
<ide>
<add>import org.junit.Before;
<ide> import org.junit.Test;
<ide> import org.springframework.aop.support.AopUtils;
<ide> import org.springframework.jmx.AbstractMBeanServerTests;
<ide> import org.springframework.tests.Assume;
<ide> import org.springframework.tests.TestGroup;
<add>import org.springframework.util.SocketUtils;
<ide>
<ide> import static org.junit.Assert.*;
<ide>
<ide> */
<ide> public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTests {
<ide>
<del> private static final String SERVICE_URL = "service:jmx:jmxmp://localhost:9878";
<ide>
<del> private JMXServiceURL getServiceUrl() throws MalformedURLException {
<del> return new JMXServiceURL(SERVICE_URL);
<add> private String serviceUrl;
<add>
<add>
<add> @Before
<add> public void getUrl() {
<add> int port = SocketUtils.findAvailableTcpPort(9800, 9900);
<add> this.serviceUrl = "service:jmx:jmxmp://localhost:" + port;
<add> System.out.println(port);
<add> }
<add>
<add>
<add> private JMXServiceURL getJMXServiceUrl() throws MalformedURLException {
<add> return new JMXServiceURL(serviceUrl);
<ide> }
<ide>
<ide> private JMXConnectorServer getConnectorServer() throws Exception {
<del> return JMXConnectorServerFactory.newJMXConnectorServer(getServiceUrl(), null, getServer());
<add> return JMXConnectorServerFactory.newJMXConnectorServer(getJMXServiceUrl(), null, getServer());
<ide> }
<ide>
<add>
<ide> @Test
<ide> public void testTestValidConnection() throws Exception {
<ide> Assume.group(TestGroup.JMXMP);
<ide> public void testTestValidConnection() throws Exception {
<ide>
<ide> try {
<ide> MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean();
<del> bean.setServiceUrl(SERVICE_URL);
<add> bean.setServiceUrl(serviceUrl);
<ide> bean.afterPropertiesSet();
<ide>
<ide> try {
<ide> public void testWithNoServiceUrl() throws Exception {
<ide> public void testTestWithLazyConnection() throws Exception {
<ide> Assume.group(TestGroup.JMXMP);
<ide> MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean();
<del> bean.setServiceUrl(SERVICE_URL);
<add> bean.setServiceUrl(serviceUrl);
<ide> bean.setConnectOnStartup(false);
<ide> bean.afterPropertiesSet();
<ide>
<ide> public void testTestWithLazyConnection() throws Exception {
<ide> @Test
<ide> public void testWithLazyConnectionAndNoAccess() throws Exception {
<ide> MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean();
<del> bean.setServiceUrl(SERVICE_URL);
<add> bean.setServiceUrl(serviceUrl);
<ide> bean.setConnectOnStartup(false);
<ide> bean.afterPropertiesSet();
<ide> | 1 |
Ruby | Ruby | require tag since we need it for this test | 2b4de6621f75b49c30c03ddd78076f7204cc9577 | <ide><path>activerecord/test/cases/associations/eager_load_nested_include_test.rb
<ide> require 'cases/helper'
<ide> require 'models/post'
<add>require 'models/tag'
<ide> require 'models/author'
<ide> require 'models/comment'
<ide> require 'models/category' | 1 |
Go | Go | sd_notify stopping=1 when shutting down | f3d0f7054dbc2e2bcd959cd4c7fc3a8fa097d525 | <ide><path>cmd/dockerd/daemon.go
<ide> func (cli *DaemonCli) start(opts *daemonOptions) (err error) {
<ide> }, logrus.StandardLogger())
<ide>
<ide> // Notify that the API is active, but before daemon is set up.
<del> preNotifySystem()
<add> preNotifyReady()
<ide>
<ide> pluginStore := plugin.NewStore()
<ide>
<ide> func (cli *DaemonCli) start(opts *daemonOptions) (err error) {
<ide> go cli.api.Wait(serveAPIWait)
<ide>
<ide> // after the daemon is done setting up we can notify systemd api
<del> notifySystem()
<add> notifyReady()
<ide>
<ide> // Daemon is fully initialized and handling API traffic
<ide> // Wait for serve API to complete
<ide> errAPI := <-serveAPIWait
<ide> c.Cleanup()
<ide>
<add> // notify systemd that we're shutting down
<add> notifyStopping()
<ide> shutdownDaemon(d)
<ide>
<ide> // Stop notification processing and any background processes
<ide><path>cmd/dockerd/daemon_freebsd.go
<ide> package main
<ide>
<del>// preNotifySystem sends a message to the host when the API is active, but before the daemon is
<del>func preNotifySystem() {
<add>// preNotifyReady sends a message to the host when the API is active, but before the daemon is
<add>func preNotifyReady() {
<ide> }
<ide>
<del>// notifySystem sends a message to the host when the server is ready to be used
<del>func notifySystem() {
<add>// notifyReady sends a message to the host when the server is ready to be used
<add>func notifyReady() {
<add>}
<add>
<add>// notifyStopping sends a message to the host when the server is shutting down
<add>func notifyStopping() {
<ide> }
<ide><path>cmd/dockerd/daemon_linux.go
<ide> package main
<ide>
<ide> import systemdDaemon "github.com/coreos/go-systemd/v22/daemon"
<ide>
<del>// preNotifySystem sends a message to the host when the API is active, but before the daemon is
<del>func preNotifySystem() {
<add>// preNotifyReady sends a message to the host when the API is active, but before the daemon is
<add>func preNotifyReady() {
<ide> }
<ide>
<del>// notifySystem sends a message to the host when the server is ready to be used
<del>func notifySystem() {
<add>// notifyReady sends a message to the host when the server is ready to be used
<add>func notifyReady() {
<ide> // Tell the init daemon we are accepting requests
<ide> go systemdDaemon.SdNotify(false, systemdDaemon.SdNotifyReady)
<ide> }
<add>
<add>// notifyStopping sends a message to the host when the server is shutting down
<add>func notifyStopping() {
<add> go systemdDaemon.SdNotify(false, systemdDaemon.SdNotifyStopping)
<add>}
<ide><path>cmd/dockerd/daemon_windows.go
<ide> func getDaemonConfDir(root string) (string, error) {
<ide> return filepath.Join(root, `\config`), nil
<ide> }
<ide>
<del>// preNotifySystem sends a message to the host when the API is active, but before the daemon is
<del>func preNotifySystem() {
<add>// preNotifyReady sends a message to the host when the API is active, but before the daemon is
<add>func preNotifyReady() {
<ide> // start the service now to prevent timeouts waiting for daemon to start
<ide> // but still (eventually) complete all requests that are sent after this
<ide> if service != nil {
<ide> func preNotifySystem() {
<ide> }
<ide> }
<ide>
<del>// notifySystem sends a message to the host when the server is ready to be used
<del>func notifySystem() {
<add>// notifyReady sends a message to the host when the server is ready to be used
<add>func notifyReady() {
<add>}
<add>
<add>// notifyStopping sends a message to the host when the server is shutting down
<add>func notifyStopping() {
<ide> }
<ide>
<ide> // notifyShutdown is called after the daemon shuts down but before the process exits. | 4 |
Javascript | Javascript | set lc_all to known good value | 2bb93e11085ea582aea1636f544d900520d479ed | <ide><path>test/parallel/test-process-env-tz.js
<ide> 'use strict';
<ide>
<add>// Set the locale to a known good value because it affects ICU's date string
<add>// formatting. Setting LC_ALL needs to happen before the first call to
<add>// `icu::Locale::getDefault()` because ICU caches the result.
<add>process.env.LC_ALL = 'C';
<add>
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> | 1 |
PHP | PHP | add register name | 269521ec9702c320e1f9928e19bfe694759589a3 | <ide><path>src/Illuminate/Routing/Router.php
<ide> public function auth()
<ide> $this->post('logout', 'Auth\LoginController@logout')->name('logout');
<ide>
<ide> // Registration Routes...
<del> $this->get('register', 'Auth\RegisterController@showRegistrationForm');
<add> $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
<ide> $this->post('register', 'Auth\RegisterController@register');
<ide>
<ide> // Password Reset Routes... | 1 |
Java | Java | optimize systemenvpropertysource when possible | 752574de1d529eb9eff413b0bffc2c51b5180012 | <ide><path>spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java
<ide> */
<ide> public class SystemEnvironmentPropertySource extends MapPropertySource {
<ide>
<add> /** if SecurityManager scenarios mean that property access should be via getPropertyNames() */
<add> private boolean usePropertyNames;
<add>
<ide> /**
<ide> * Create a new {@code SystemEnvironmentPropertySource} with the given name and
<ide> * delegating to the given {@code MapPropertySource}.
<ide> public Object getProperty(String name) {
<ide> */
<ide> private String resolvePropertyName(String name) {
<ide> Assert.notNull(name, "Property name must not be null");
<del> if (ObjectUtils.containsElement(getPropertyNames(), name)) {
<del> return name;
<del> }
<add> try {
<add> String[] propertyNames = (this.usePropertyNames ? getPropertyNames() : null);
<add> if (containsProperty(propertyNames, name)) {
<add> return name;
<add> }
<ide>
<del> String usName = name.replace('.', '_');
<del> if (!name.equals(usName) && ObjectUtils.containsElement(getPropertyNames(), usName)) {
<del> return usName;
<del> }
<add> String usName = name.replace('.', '_');
<add> if (!name.equals(usName) && containsProperty(propertyNames, usName)) {
<add> return usName;
<add> }
<ide>
<del> String ucName = name.toUpperCase();
<del> if (!name.equals(ucName)) {
<del> if (ObjectUtils.containsElement(getPropertyNames(), ucName)) {
<del> return ucName;
<add> String ucName = name.toUpperCase();
<add> if (!name.equals(ucName)) {
<add> if (containsProperty(propertyNames, ucName)) {
<add> return ucName;
<add> }
<add> else {
<add> String usUcName = ucName.replace('.', '_');
<add> if (!ucName.equals(usUcName) && containsProperty(propertyNames, usUcName)) {
<add> return usUcName;
<add> }
<add> }
<add> }
<add>
<add> return name;
<add> }
<add> catch (RuntimeException ex) {
<add> if (this.usePropertyNames) {
<add> throw ex;
<ide> }
<ide> else {
<del> String usUcName = ucName.replace('.', '_');
<del> if (!ucName.equals(usUcName) && ObjectUtils.containsElement(getPropertyNames(), usUcName)) {
<del> return usUcName;
<del> }
<add> this.usePropertyNames = true;
<add> return resolvePropertyName(name);
<ide> }
<ide> }
<add> }
<ide>
<del> return name;
<add> private boolean containsProperty(String[] propertyNames, String name) {
<add> if (propertyNames == null) {
<add> return super.containsProperty(name);
<add> }
<add> return ObjectUtils.containsElement(propertyNames, name);
<ide> }
<ide>
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/core/env/SystemEnvironmentPropertySourceTests.java
<ide>
<ide> package org.springframework.core.env;
<ide>
<del>import static org.hamcrest.CoreMatchers.equalTo;
<del>import static org.junit.Assert.assertThat;
<del>
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<add>import static org.hamcrest.CoreMatchers.*;
<add>import static org.junit.Assert.*;
<add>
<ide> /**
<ide> * Unit tests for {@link SystemEnvironmentPropertySource}.
<ide> *
<ide> public void withUppercase() {
<ide> assertThat(ps.getProperty("a.key"), equalTo((Object)"a_value"));
<ide> }
<ide>
<add> @Test
<add> public void withSecurityConstraints() throws Exception {
<add> envMap = new HashMap<String, Object>() {
<add> @Override
<add> public boolean containsKey(Object key) {
<add> throw new UnsupportedOperationException();
<add> }
<add> };
<add> ps = new SystemEnvironmentPropertySource("sysEnv", envMap);
<add> envMap.put("A_KEY", "a_value");
<add> assertThat(ps.containsProperty("A_KEY"), equalTo(true));
<add> assertThat(ps.getProperty("A_KEY"), equalTo((Object)"a_value"));
<add> }
<add>
<ide> } | 2 |
PHP | PHP | fix security component failing on csrf tokens | a33058405b344dd580d14dbd3816b7fb6ef883dd | <ide><path>src/Controller/Component/SecurityComponent.php
<ide> protected function _validatePost(Controller $controller) {
<ide> if (strpos($token, ':')) {
<ide> list($token, $locked) = explode(':', $token, 2);
<ide> }
<del> unset($check['_Token']);
<add> unset($check['_Token'], $check['_csrfToken']);
<ide>
<ide> $locked = explode('|', $locked);
<ide> $unlocked = explode('|', $unlocked);
<ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php
<ide> public function testValidatePostObjectDeserialize() {
<ide> $this->assertFalse($result, 'validatePost passed when key was missing. %s');
<ide> }
<ide>
<add>/**
<add> * Tests validation post data ignores `_csrfToken`.
<add> *
<add> * @return void
<add> */
<add> public function testValidatePostIgnoresCsrfToken() {
<add> $event = new Event('Controller.startup', $this->Controller);
<add> $this->Controller->Security->startup($event);
<add>
<add> $fields = '8e26ef05379e5402c2c619f37ee91152333a0264%3A';
<add> $unlocked = '';
<add>
<add> $this->Controller->request->data = array(
<add> '_csrfToken' => 'abc123',
<add> 'Model' => array('multi_field' => array('1', '3')),
<add> '_Token' => compact('fields', 'unlocked')
<add> );
<add> $this->assertTrue($this->Controller->Security->validatePost($this->Controller));
<add> }
<add>
<ide> /**
<ide> * Tests validation of checkbox arrays
<ide> * | 2 |
Python | Python | add setup directions for data dir | d105771a07f886fbcc9f3eefd47d2c8e8a56182e | <ide><path>examples/nn_text_class.py
<add>"""This script expects something like a binary sentiment data set, such as
<add> that available here: `http://www.cs.cornell.edu/people/pabo/movie-review-data/`
<add>
<add>It expects a directory structure like: `data_dir/train/{pos|neg}`
<add> and `data_dir/test/{pos|neg}`. Put (say) 90% of the files in the former
<add> and the remainder in the latter.
<add>"""
<add>
<ide> from __future__ import unicode_literals
<ide> from __future__ import print_function
<ide> from __future__ import division | 1 |
Python | Python | remove broken divmod o->oo loop until it is fixed | 2adb9298e4bad5b961143293d9ba19dbd10a2786 | <ide><path>numpy/core/code_generators/generate_umath.py
<ide> def english_upper(s):
<ide> docstrings.get('numpy.core.umath.divmod'),
<ide> None,
<ide> TD(intflt),
<del> TD(O, f='PyNumber_Divmod'),
<add> # TD(O, f='PyNumber_Divmod'), # gh-9730
<ide> ),
<ide> 'hypot':
<ide> Ufunc(2, 1, Zero,
<ide> def make_arrays(funcdict):
<ide> k = 0
<ide> sub = 0
<ide>
<del> if uf.nin > 1:
<del> assert uf.nin == 2
<del> thedict = chartotype2 # two inputs and one output
<del> else:
<del> thedict = chartotype1 # one input and one output
<del>
<ide> for t in uf.type_descriptions:
<ide> if t.func_data is FullTypeDescr:
<ide> tname = english_upper(chartoname[t.type])
<ide> def make_arrays(funcdict):
<ide> ))
<ide> else:
<ide> funclist.append('NULL')
<add> if (uf.nin, uf.nout) == (2, 1):
<add> thedict = chartotype2
<add> elif (uf.nin, uf.nout) == (1, 1):
<add> thedict = chartotype1
<add> else:
<add> raise ValueError("Could not handle {}[{}]".format(name, t.type))
<add>
<ide> astype = ''
<ide> if not t.astype is None:
<ide> astype = '_As_%s' % thedict[t.astype] | 1 |
Text | Text | update cross compiler machine for linux armv7 | f22a9cac36f731d5bdbf1b7c542b36fa4c13f4de | <ide><path>BUILDING.md
<ide> Binaries at <https://nodejs.org/download/release/> are produced on:
<ide> | aix-ppc64 | AIX 7.1 TL05 on PPC64BE with GCC 6 |
<ide> | darwin-x64 (and .pkg) | macOS 10.15, Xcode Command Line Tools 11 with -mmacosx-version-min=10.13 |
<ide> | linux-arm64 | CentOS 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> |
<del>| linux-armv7l | Cross-compiled on Ubuntu 16.04 x64 with [custom GCC toolchain](https://github.com/rvagg/rpi-newer-crosstools) |
<add>| linux-armv7l | Cross-compiled on Ubuntu 18.04 x64 with [custom GCC toolchain](https://github.com/rvagg/rpi-newer-crosstools) |
<ide> | linux-ppc64le | CentOS 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> |
<ide> | linux-s390x | RHEL 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> |
<ide> | linux-x64 | CentOS 7 with devtoolset-8 / GCC 8 <sup>[8](#fn8)</sup> | | 1 |
Java | Java | add error filter to webclient integration test | ea85431ac55acf9e3b8dfca51879727c99c2d5f7 | <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java
<ide> public void retrieveToEntityNotFound() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void buildFilter() throws Exception {
<add> public void filter() throws Exception {
<ide> this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain").setBody("Hello Spring!"));
<ide>
<ide> WebClient filteredClient = this.webClient.filter(
<ide> public void buildFilter() throws Exception {
<ide>
<ide> Mono<String> result = filteredClient.get()
<ide> .uri("/greeting?name=Spring")
<del> .exchange()
<del> .flatMap(response -> response.bodyToMono(String.class));
<add> .retrieve()
<add> .bodyToMono(String.class);
<ide>
<ide> StepVerifier.create(result)
<ide> .expectNext("Hello Spring!")
<ide> public void buildFilter() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void filter() throws Exception {
<del> this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain").setBody("Hello Spring!"));
<add> public void errorHandlingFilter() throws Exception {
<ide>
<del> WebClient filteredClient = this.webClient.filter(
<del> (request, next) -> {
<del> ClientRequest filteredRequest = ClientRequest.from(request).header("foo", "bar").build();
<del> return next.exchange(filteredRequest);
<del> });
<add> ExchangeFilterFunction filter = ExchangeFilterFunction.ofResponseProcessor(
<add> clientResponse -> {
<add> List<String> headerValues = clientResponse.headers().header("Foo");
<add> return headerValues.isEmpty() ? Mono.error(
<add> new MyException("Response does not contain Foo header")) :
<add> Mono.just(clientResponse);
<add> }
<add> );
<add>
<add> WebClient filteredClient = this.webClient.filter(filter);
<add>
<add> // header not present
<add> this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain").setBody("Hello Spring!"));
<ide>
<ide> Mono<String> result = filteredClient.get()
<ide> .uri("/greeting?name=Spring")
<del> .exchange()
<del> .flatMap(response -> response.bodyToMono(String.class));
<add> .retrieve()
<add> .bodyToMono(String.class);
<add>
<add> StepVerifier.create(result)
<add> .expectError(MyException.class)
<add> .verify(Duration.ofSeconds(3));
<add>
<add> // header present
<add>
<add> this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain")
<add> .setHeader("Foo", "Bar")
<add> .setBody("Hello Spring!"));
<add>
<add> result = filteredClient.get()
<add> .uri("/greeting?name=Spring")
<add> .retrieve()
<add> .bodyToMono(String.class);
<ide>
<ide> StepVerifier.create(result)
<ide> .expectNext("Hello Spring!")
<ide> .expectComplete()
<ide> .verify(Duration.ofSeconds(3));
<ide>
<del> RecordedRequest recordedRequest = server.takeRequest();
<del> Assert.assertEquals(1, server.getRequestCount());
<del> Assert.assertEquals("bar", recordedRequest.getHeader("foo"));
<add> Assert.assertEquals(2, server.getRequestCount());
<add> }
<add>
<add> @SuppressWarnings("serial")
<add> private static class MyException extends RuntimeException {
<add>
<add> public MyException(String message) {
<add> super(message);
<add> }
<ide> }
<ide>
<ide> } | 1 |
Java | Java | remove unnecessary static imports from unit tests | 335ee341a32afcdcc16ea3b69c76230bafbce077 | <ide><path>src/test/java/io/reactivex/completable/CompletableTest.java
<ide> package io.reactivex.completable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/disposables/DisposablesTest.java
<ide> package io.reactivex.disposables;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.anyInt;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/flowable/FlowableTests.java
<ide> package io.reactivex.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java
<ide> package io.reactivex.internal.operators.completable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.*;
<ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableFromSupplierTest.java
<ide> package io.reactivex.internal.operators.completable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.CountDownLatch;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableAllTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableAnyTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableAsObservableTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertFalse;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import org.junit.Test;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.lang.reflect.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.lang.reflect.Method;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDefaultIfEmptyTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import org.junit.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDeferTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import org.junit.Test;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDelayTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChangedTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnEachTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableFlatMapTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableFromCallableTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableFromSupplierTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertFalse;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import org.junit.Test;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableJoinTest.java
<ide> */
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableMapTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertNull;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.lang.reflect.Method;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java
<ide>
<ide> import static java.util.Arrays.asList;
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.lang.reflect.Method;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFlowableTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.fail;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaFlowableTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.fail;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeLongTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableReduceTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayEagerTruncateTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.lang.management.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.lang.management.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryWithPredicateTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertFalse;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqualTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.isA;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.Arrays;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTimedTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.Arrays;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipWhileTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import org.junit.Test;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilPredicateTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.fail;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java
<ide>
<ide> import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage;
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTimerTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertTrue;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableToMapTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableToMultimapTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableToSortedListTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithFlowableTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableZipIterableTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.lang.reflect.*;
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCallableTest.java
<ide> package io.reactivex.internal.operators.maybe;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeFromSupplierTest.java
<ide> package io.reactivex.internal.operators.maybe;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableAllTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableAnyTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableCombineLatestTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableConcatTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDeferTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import org.junit.Test;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDelayTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChangedTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDoOnEachTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableFilterTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import org.junit.Test;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableFlatMapTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableFromCallableTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableFromIterableTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableFromSupplierTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableJoinTest.java
<ide> */
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableLastTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.NoSuchElementException;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableMapTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.assertNull;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableMergeDelayErrorTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableMergeTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaFunctionTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorResumeNextViaObservableTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.fail;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableOnErrorReturnTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableOnExceptionResumeNextViaObservableTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.fail;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableRangeLongTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.ArrayList;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableRangeTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.ArrayList;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableReduceTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableReplayEagerTruncateTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.lang.management.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableReplayTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.lang.management.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableRetryWithPredicateTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableScanTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableSequenceEqualTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.isA;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import org.junit.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.Arrays;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTimedTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.Arrays;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableSkipWhileTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import org.junit.Test;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableSwitchTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTakeLastTimedTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTakeTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilPredicateTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTakeWhileTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.fail;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import org.junit.Test;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutTests.java
<ide>
<ide> import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage;
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.io.IOException;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.assertTrue;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableToMapTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableToMultimapTest.java
<ide>
<ide> package io.reactivex.internal.operators.observable;
<ide>
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableWithLatestFromTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableZipIterableTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableZipTest.java
<ide> package io.reactivex.internal.operators.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/single/SingleFromCallableTest.java
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertTrue;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> public class SingleFromCallableTest {
<ide><path>src/test/java/io/reactivex/internal/operators/single/SingleFromSupplierTest.java
<ide> package io.reactivex.internal.operators.single;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/observable/ObservableTest.java
<ide> package io.reactivex.observable;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/observers/SerializedObserverTest.java
<ide> package io.reactivex.observers;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/processors/AsyncProcessorTest.java
<ide> package io.reactivex.processors;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/processors/BehaviorProcessorTest.java
<ide> package io.reactivex.processors;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/processors/PublishProcessorTest.java
<ide> package io.reactivex.processors;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.ArrayList;
<ide><path>src/test/java/io/reactivex/processors/ReplayProcessorTest.java
<ide> package io.reactivex.processors;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.lang.management.*;
<ide><path>src/test/java/io/reactivex/single/SingleNullTests.java
<ide> import org.reactivestreams.*;
<ide>
<ide> import io.reactivex.*;
<del>import io.reactivex.SingleOperator;
<ide> import io.reactivex.exceptions.*;
<ide> import io.reactivex.functions.*;
<ide> import io.reactivex.internal.functions.Functions;
<ide><path>src/test/java/io/reactivex/subjects/AsyncSubjectTest.java
<ide> package io.reactivex.subjects;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide><path>src/test/java/io/reactivex/subjects/BehaviorSubjectTest.java
<ide> package io.reactivex.subjects;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/subjects/PublishSubjectTest.java
<ide> package io.reactivex.subjects;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.ArrayList;
<ide><path>src/test/java/io/reactivex/subjects/ReplaySubjectTest.java
<ide> package io.reactivex.subjects;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.lang.management.*;
<ide><path>src/test/java/io/reactivex/subscribers/SafeSubscriberTest.java
<ide> package io.reactivex.subscribers;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List;
<ide><path>src/test/java/io/reactivex/subscribers/SerializedSubscriberTest.java
<ide> package io.reactivex.subscribers;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.List; | 149 |
Javascript | Javascript | remove pagenotfound key from the error | 6f9b51fce6e7024a1701946c0cd52beb12f99c0c | <ide><path>lib/error.js
<ide> import Head from './head'
<ide> export default class Error extends React.Component {
<ide> static getInitialProps ({ res, err }) {
<ide> const statusCode = res ? res.statusCode : (err ? err.statusCode : null)
<del> const pageNotFound = statusCode === 404 || (err ? err.pageNotFound : false)
<del> return { statusCode, pageNotFound }
<add> return { statusCode }
<ide> }
<ide>
<ide> render () {
<del> const { statusCode, pageNotFound } = this.props
<del> const title = pageNotFound
<add> const { statusCode } = this.props
<add> const title = statusCode === 404
<ide> ? 'This page could not be found'
<ide> : HTTPStatus[statusCode] || 'An unexpected error has occurred'
<ide>
<ide><path>lib/router/router.js
<ide> export default class Router {
<ide> return { error: err }
<ide> }
<ide>
<del> if (err.pageNotFound) {
<add> if (err.statusCode === 404) {
<ide> // Indicate main error display logic to
<ide> // ignore rendering this error as a runtime error.
<ide> err.ignore = true
<ide><path>server/render.js
<ide> export async function renderScriptError (req, res, page, error, customFields, op
<ide> res.end(`
<ide> function loadPage () {
<ide> var error = new Error('Page not exists: ${page}')
<del> error.pageNotFound = true
<ide> error.statusCode = 404
<ide> __NEXT_PAGE_LOADER__.registerPage('${page}', function(cb) {
<ide> cb(error) | 3 |
Ruby | Ruby | remove superfluous condition | e7f0d37c91c91a6b2f2a1232c1a670e59165dc19 | <ide><path>actionpack/lib/action_view/helpers/form_tag_helper.rb
<ide> def submit_tag(value = "Save changes", options = {})
<ide> options.stringify_keys!
<ide>
<ide> if disable_with = options.delete("disable_with")
<del> options["data-disable-with"] = disable_with if disable_with
<add> options["data-disable-with"] = disable_with
<ide> end
<ide>
<ide> if confirm = options.delete("confirm") | 1 |
Javascript | Javascript | fix style in net.js | d89f8dce28601a3414dd28a02bf181cf9cfa0979 | <ide><path>lib/net.js
<ide> var END_OF_FILE = 42;
<ide> try {
<ide> var SecureContext = process.binding('crypto').SecureContext;
<ide> var SecureStream = process.binding('crypto').SecureStream;
<del> var have_crypto = true;
<add> var haveCrypto = true;
<ide> } catch (e) {
<del> var have_crypto = false;
<add> var haveCrypto = false;
<ide> }
<ide>
<ide> // IDLE TIMEOUTS
<ide> var ioWatchers = new FreeList("iowatcher", 100, function () {
<ide>
<ide> exports.isIP = binding.isIP;
<ide>
<del>exports.isIPv4 = function(input) {
<add>exports.isIPv4 = function (input) {
<ide> if (binding.isIP(input) === 4) {
<ide> return true;
<ide> }
<ide> return false;
<ide> };
<ide>
<del>exports.isIPv6 = function(input) {
<add>exports.isIPv6 = function (input) {
<ide> if (binding.isIP(input) === 6) {
<ide> return true;
<ide> }
<ide> function setImplmentationMethods (self) {
<ide> };
<ide>
<ide> if (self.type == 'unix') {
<del> self._writeImpl = function(buf, off, len, fd, flags) {
<add> self._writeImpl = function (buf, off, len, fd, flags) {
<ide> // Detect and disallow zero-byte writes wth an attached file
<ide> // descriptor. This is an implementation limitation of sendmsg(2).
<ide> if (fd && noData(buf, off, len)) {
<ide> function setImplmentationMethods (self) {
<ide> return sendMsg(self.fd, buf, off, len, fd, flags);
<ide> };
<ide>
<del> self._readImpl = function(buf, off, len, calledByIOWatcher) {
<add> self._readImpl = function (buf, off, len, calledByIOWatcher) {
<ide> var bytesRead = recvMsg(self.fd, buf, off, len);
<ide>
<ide> // Do not emit this in the same stack, otherwise we risk corrupting our
<ide> function setImplmentationMethods (self) {
<ide> if (recvMsg.fd !== null) {
<ide> (function () {
<ide> var fd = recvMsg.fd;
<del> process.nextTick(function() {
<add> process.nextTick(function () {
<ide> self.emit('fd', fd);
<ide> });
<ide> })();
<ide> function setImplmentationMethods (self) {
<ide> return bytesRead;
<ide> };
<ide> } else {
<del> self._writeImpl = function(buf, off, len, fd, flags) {
<add> self._writeImpl = function (buf, off, len, fd, flags) {
<ide> // XXX: TLS support requires that 0-byte writes get processed
<ide> // by the kernel for some reason. Otherwise, we'd just
<ide> // fast-path return here.
<ide> function setImplmentationMethods (self) {
<ide> return write(self.fd, buf, off, len);
<ide> };
<ide>
<del> self._readImpl = function(buf, off, len, calledByIOWatcher) {
<add> self._readImpl = function (buf, off, len, calledByIOWatcher) {
<ide> return read(self.fd, buf, off, len);
<ide> };
<ide> }
<ide>
<del> self._shutdownImpl = function() {
<add> self._shutdownImpl = function () {
<ide> shutdown(self.fd, 'write')
<ide> };
<ide>
<ide> if (self.secure) {
<ide> var oldWrite = self._writeImpl;
<del> self._writeImpl = function(buf, off, len, fd, flags) {
<add> self._writeImpl = function (buf, off, len, fd, flags) {
<ide> assert(buf);
<ide> assert(self.secure);
<ide>
<ide> function setImplmentationMethods (self) {
<ide> allocNewSecurePool();
<ide> }
<ide>
<del> var secureLen = self.secureStream.writeExtract(
<del> securePool, 0, securePool.length
<del> );
<add> var secureLen = self.secureStream.writeExtract(securePool,
<add> 0,
<add> securePool.length);
<ide>
<ide> if (secureLen == -1) {
<ide> // Check our read again for secure handshake
<ide> function setImplmentationMethods (self) {
<ide> };
<ide>
<ide> var oldRead = self._readImpl;
<del> self._readImpl = function(buf, off, len, calledByIOWatcher) {
<add> self._readImpl = function (buf, off, len, calledByIOWatcher) {
<ide> assert(self.secure);
<ide>
<ide> var bytesRead = 0;
<ide> function setImplmentationMethods (self) {
<ide>
<ide> var chunkBytes;
<ide> do {
<del> chunkBytes = self.secureStream.readExtract(
<del> pool,
<del> pool.used + bytesRead,
<del> pool.length - pool.used - bytesRead
<del> );
<del>
<add> chunkBytes =
<add> self.secureStream.readExtract(pool,
<add> pool.used + bytesRead,
<add> pool.length - pool.used - bytesRead);
<ide> bytesRead += chunkBytes;
<ide> } while ((chunkBytes > 0) && (pool.used + bytesRead < pool.length));
<ide>
<ide> function setImplmentationMethods (self) {
<ide>
<ide> if (self.secureStream.readPending()) {
<ide> process.nextTick(function () {
<del> if(self._readWatcher)
<del> self._readWatcher.callback();
<add> if (self._readWatcher) self._readWatcher.callback();
<ide> });
<ide> }
<ide>
<ide> function setImplmentationMethods (self) {
<ide> };
<ide>
<ide> var oldShutdown = self._shutdownImpl;
<del> self._shutdownImpl = function() {
<add> self._shutdownImpl = function () {
<ide> self.secureStream.shutdown();
<ide>
<ide> if (!securePool) {
<ide> function initStream (self) {
<ide> var bytesRead;
<ide>
<ide> try {
<del> bytesRead = self._readImpl(pool, pool.used, pool.length - pool.used, (arguments.length > 0));
<add> bytesRead = self._readImpl(pool,
<add> pool.used,
<add> pool.length - pool.used,
<add> (arguments.length > 0));
<ide> } catch (e) {
<ide> self.destroy(e);
<ide> return;
<ide> function Stream (fd, type) {
<ide> sys.inherits(Stream, events.EventEmitter);
<ide> exports.Stream = Stream;
<ide>
<del>Stream.prototype.setSecure = function(credentials) {
<del> if (!have_crypto) {
<add>Stream.prototype.setSecure = function (credentials) {
<add> if (!haveCrypto) {
<ide> throw new Error('node.js not compiled with openssl crypto support.');
<ide> }
<ide> var crypto= require("crypto");
<ide> Stream.prototype.setSecure = function(credentials) {
<ide> this.credentials = credentials;
<ide> }
<ide> if (!this.server) {
<del> // For clients, we will always have either a given ca list or the default one;
<add> // For clients, we will always have either a given ca list or the default on
<ide> this.credentials.shouldVerify = true;
<ide> }
<del> this.secureStream = new SecureStream(this.credentials.context, this.server ? 1 : 0, this.credentials.shouldVerify ? 1 : 0);
<add> this.secureStream = new SecureStream(this.credentials.context,
<add> this.server ? 1 : 0,
<add> this.credentials.shouldVerify ? 1 : 0);
<ide>
<ide> setImplmentationMethods(this);
<ide>
<ide> Stream.prototype.setSecure = function(credentials) {
<ide> }
<ide>
<ide>
<del>Stream.prototype.verifyPeer = function() {
<add>Stream.prototype.verifyPeer = function () {
<ide> if (!this.secure) {
<ide> throw new Error('Stream is not a secure stream.');
<ide> }
<ide> return this.secureStream.verifyPeer(this.credentials.context);
<ide> }
<ide>
<ide>
<del>Stream.prototype._checkForSecureHandshake = function() {
<add>Stream.prototype._checkForSecureHandshake = function () {
<ide> if (!this.writable) {
<ide> return;
<ide> }
<ide> Stream.prototype._checkForSecureHandshake = function() {
<ide> }
<ide>
<ide>
<del>Stream.prototype.getPeerCertificate = function(credentials) {
<add>Stream.prototype.getPeerCertificate = function (credentials) {
<ide> if (!this.secure) {
<ide> throw new Error('Stream is not a secure stream.');
<ide> }
<ide> return this.secureStream.getPeerCertificate();
<ide> }
<ide>
<ide>
<del>Stream.prototype.getCipher = function() {
<add>Stream.prototype.getCipher = function () {
<ide> if (!this.secure) {
<ide> throw new Error('Stream is not a secure stream.');
<ide> } | 1 |
Python | Python | use consistent imports and exports | fa3b8512dab5547955202a618acc8b7b8fa59386 | <ide><path>spacy/fr/__init__.py
<ide>
<ide> from .language_data import *
<ide> from .punctuation import TOKENIZER_INFIXES, TOKENIZER_SUFFIXES
<del>from .tokenizer_exceptions import get_tokenizer_exceptions, TOKEN_MATCH
<ide>
<ide>
<ide> class FrenchDefaults(BaseDefaults):
<ide> class FrenchDefaults(BaseDefaults):
<ide>
<ide> @classmethod
<ide> def create_tokenizer(cls, nlp=None):
<del> cls.tokenizer_exceptions = get_tokenizer_exceptions()
<add> cls.tokenizer_exceptions = TOKENIZER_EXCEPTIONS
<ide> return super(FrenchDefaults, cls).create_tokenizer(nlp)
<ide>
<ide>
<ide><path>spacy/fr/language_data.py
<ide> from __future__ import unicode_literals
<ide>
<ide> from .stop_words import STOP_WORDS
<add>from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS, TOKEN_MATCH
<ide>
<ide>
<ide> STOP_WORDS = set(STOP_WORDS)
<ide>
<ide>
<del>__all__ = ["STOP_WORDS"]
<add>__all__ = ["STOP_WORDS", "TOKENIZER_EXCEPTIONS", "TOKEN_MATCH"]
<ide><path>spacy/fr/tokenizer_exceptions.py
<ide> def get_tokenizer_exceptions():
<ide>
<ide> TOKEN_MATCH = re.compile('|'.join('({})'.format(m) for m in REGULAR_EXP), re.IGNORECASE).match
<ide>
<del>__all__ = ("get_tokenizer_exceptions", "TOKEN_MATCH")
<add>TOKENIZER_EXCEPTIONS = get_tokenizer_exceptions()
<add>
<add>__all__ = ["TOKENIZER_EXCEPTIONS", "TOKEN_MATCH"] | 3 |
Ruby | Ruby | transform the symbol into a constant lookup | 139a9f7011687d5bb9df940957cd726c75e361cc | <ide><path>activemodel/lib/active_model/mass_assignment_security.rb
<ide> module MassAssignmentSecurity
<ide> class_attribute :_protected_attributes
<ide> class_attribute :_active_authorizer
<ide>
<del> class_attribute :mass_assignment_sanitizer, :mass_assignment_sanitizers
<add> class_attribute :_mass_assignment_sanitizer
<ide> self.mass_assignment_sanitizer = :logger
<del> self.mass_assignment_sanitizers = {
<del> :logger => LoggerSanitizer.new(self.respond_to?(:logger) && self.logger),
<del> :strict => StrictSanitizer.new
<del> }
<ide> end
<ide>
<ide> # Mass assignment security provides an interface for protecting attributes
<ide> def attr_accessible(*args)
<ide> options = args.extract_options!
<ide> role = options[:as] || :default
<ide>
<del> self._accessible_attributes = accessible_attributes_configs.dup
<add> self._accessible_attributes = accessible_attributes_configs.dup
<ide> self._accessible_attributes[role] = self.accessible_attributes(role) + args
<ide>
<ide> self._active_authorizer = self._accessible_attributes
<ide> def attributes_protected_by_default
<ide> []
<ide> end
<ide>
<add> def mass_assignment_sanitizer=(value)
<add> self._mass_assignment_sanitizer = if value.is_a?(Symbol)
<add> const_get(:"#{value.to_s.camelize}Sanitizer").new(self)
<add> else
<add> value
<add> end
<add> end
<add>
<ide> private
<ide>
<ide> def protected_attributes_configs
<ide> self._protected_attributes ||= begin
<del> default_black_list = BlackList.new(attributes_protected_by_default)
<del> Hash.new(default_black_list)
<add> Hash.new { |h,k| h[k] = BlackList.new(attributes_protected_by_default) }
<ide> end
<ide> end
<ide>
<ide> def accessible_attributes_configs
<ide> self._accessible_attributes ||= begin
<del> default_white_list = WhiteList.new
<del> Hash.new(default_white_list)
<add> Hash.new { |h,k| h[k] = WhiteList.new }
<ide> end
<ide> end
<ide> end
<ide>
<ide> protected
<ide>
<ide> def sanitize_for_mass_assignment(attributes, role = :default)
<del> sanitizer = case mass_assignment_sanitizer
<del> when Symbol
<del> self.mass_assignment_sanitizers[mass_assignment_sanitizer]
<del> else
<del> mass_assignment_sanitizer
<del> end
<del> sanitizer.sanitize(attributes, mass_assignment_authorizer(role))
<add> _mass_assignment_sanitizer.sanitize(attributes, mass_assignment_authorizer(role))
<ide> end
<ide>
<ide> def mass_assignment_authorizer(role = :default)
<ide><path>activemodel/lib/active_model/mass_assignment_security/sanitizer.rb
<add>require 'active_support/core_ext/module/delegation'
<add>
<ide> module ActiveModel
<ide> module MassAssignmentSecurity
<ide> class Sanitizer
<add> def initialize(target=nil)
<add> end
<add>
<ide> # Returns all attributes not denied by the authorizer.
<ide> def sanitize(attributes, authorizer)
<ide> sanitized_attributes = attributes.reject { |key, value| authorizer.deny?(key) }
<ide> def debug_protected_attribute_removal(attributes, sanitized_attributes)
<ide> def process_removed_attributes(attrs)
<ide> raise NotImplementedError, "#process_removed_attributes(attrs) suppose to be overwritten"
<ide> end
<del>
<ide> end
<add>
<ide> class LoggerSanitizer < Sanitizer
<add> delegate :logger, :to => :@target
<ide>
<del> attr_accessor :logger
<add> def initialize(target)
<add> @target = target
<add> super
<add> end
<ide>
<del> def initialize(logger = nil)
<del> self.logger = logger
<del> super()
<add> def logger?
<add> @target.respond_to?(:logger) && @target.logger
<ide> end
<del>
<add>
<ide> def process_removed_attributes(attrs)
<del> self.logger.debug "WARNING: Can't mass-assign protected attributes: #{attrs.join(', ')}" if self.logger
<add> logger.debug "WARNING: Can't mass-assign protected attributes: #{attrs.join(', ')}" if logger?
<ide> end
<ide> end
<ide>
<ide> def process_removed_attributes(attrs)
<ide>
<ide> class Error < StandardError
<ide> end
<del>
<ide> end
<ide> end
<ide><path>activemodel/test/cases/mass_assignment_security/sanitizer_test.rb
<ide> require 'active_support/core_ext/object/inclusion'
<ide>
<ide> class SanitizerTest < ActiveModel::TestCase
<del>
<add> attr_accessor :logger
<ide>
<ide> class Authorizer < ActiveModel::MassAssignmentSecurity::PermissionSet
<ide> def deny?(key)
<ide> def deny?(key)
<ide> end
<ide>
<ide> def setup
<del> @logger_sanitizer = ActiveModel::MassAssignmentSecurity::LoggerSanitizer.new
<del> @strict_sanitizer = ActiveModel::MassAssignmentSecurity::StrictSanitizer.new
<add> @logger_sanitizer = ActiveModel::MassAssignmentSecurity::LoggerSanitizer.new(self)
<add> @strict_sanitizer = ActiveModel::MassAssignmentSecurity::StrictSanitizer.new(self)
<ide> @authorizer = Authorizer.new
<ide> end
<ide>
<ide> def setup
<ide> test "debug mass assignment removal with LoggerSanitizer" do
<ide> original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' }
<ide> log = StringIO.new
<del> @logger_sanitizer.logger = Logger.new(log)
<add> self.logger = Logger.new(log)
<ide> @logger_sanitizer.sanitize(original_attributes, @authorizer)
<ide> assert_match(/admin/, log.string, "Should log removed attributes: #{log.string}")
<ide> end | 3 |
Javascript | Javascript | remove unecessary maps_lights_pars in examples | 33bd1a3d29997791a9d4d51870e082135bcbf32b | <ide><path>examples/js/ShaderSkin.js
<ide> THREE.ShaderSkin = {
<ide> THREE.ShaderChunk[ "bsdfs" ],
<ide> THREE.ShaderChunk[ "packing" ],
<ide> THREE.ShaderChunk[ "begin_lights_pars" ],
<del> THREE.ShaderChunk[ 'maps_lights_pars' ],
<ide> THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
<ide> THREE.ShaderChunk[ "fog_pars_fragment" ],
<ide> THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
<ide> THREE.ShaderSkin = {
<ide>
<ide> THREE.ShaderChunk[ "common" ],
<ide> THREE.ShaderChunk[ "begin_lights_pars" ],
<del> THREE.ShaderChunk[ 'maps_lights_pars' ],
<ide> THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
<ide> THREE.ShaderChunk[ "fog_pars_vertex" ],
<ide>
<ide> THREE.ShaderSkin = {
<ide>
<ide> THREE.ShaderChunk[ "common" ],
<ide> THREE.ShaderChunk[ "begin_lights_pars" ],
<del> THREE.ShaderChunk[ 'maps_lights_pars' ],
<ide> THREE.ShaderChunk[ "fog_pars_fragment" ],
<ide>
<ide> "float fresnelReflectance( vec3 H, vec3 V, float F0 ) {",
<ide><path>examples/js/ShaderTerrain.js
<ide> THREE.ShaderTerrain = {
<ide> THREE.ShaderChunk[ "common" ],
<ide> THREE.ShaderChunk[ "bsdfs" ],
<ide> THREE.ShaderChunk[ "begin_lights_pars" ],
<del> THREE.ShaderChunk[ 'maps_lights_pars' ],
<ide> THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
<ide> THREE.ShaderChunk[ "fog_pars_fragment" ],
<ide>
<ide><path>examples/js/objects/Water.js
<ide> THREE.Water = function ( geometry, options ) {
<ide> THREE.ShaderChunk[ 'bsdfs' ],
<ide> THREE.ShaderChunk[ 'fog_pars_fragment' ],
<ide> THREE.ShaderChunk[ 'begin_lights_pars' ],
<del> THREE.ShaderChunk[ 'maps_lights_pars' ],
<ide> THREE.ShaderChunk[ 'shadowmap_pars_fragment' ],
<ide> THREE.ShaderChunk[ 'shadowmask_pars_fragment' ],
<ide> | 3 |
PHP | PHP | fix empty usem. fix test cases | eed02ac5091f44b3d0064978b17a597a596754b6 | <ide><path>src/Database/Schema/MysqlSchema.php
<ide> public function columnSql(Table $table, $name)
<ide> }
<ide>
<ide> $hasCollate = ['text', 'string'];
<del> if (in_array($data['type'], $hasCollate, true) && isset($data['collate'])) {
<add> if (in_array($data['type'], $hasCollate, true) && isset($data['collate']) && $data['collate'] !== '') {
<ide> $out .= ' COLLATE ' . $data['collate'];
<ide> }
<ide>
<ide><path>src/Database/Schema/PostgresSchema.php
<ide> public function convertColumnDescription(Table $table, $row)
<ide> $field += [
<ide> 'default' => $this->_defaultValue($row['default']),
<ide> 'null' => $row['null'] === 'YES' ? true : false,
<del> 'collate' => !empty($row['collation_name']) ? $row['collation_name'] : null,
<add> 'collate' => $row['collation_name'],
<ide> 'comment' => $row['comment']
<ide> ];
<ide> $field['length'] = $row['char_length'] ?: $field['length'];
<ide> public function columnSql(Table $table, $name)
<ide> }
<ide>
<ide> $hasCollate = ['text', 'string'];
<del> if (in_array($data['type'], $hasCollate, true) && isset($data['collate'])) {
<add> if (in_array($data['type'], $hasCollate, true) && isset($data['collate']) && $data['collate'] !== '') {
<ide> $out .= ' COLLATE "' . $data['collate'] . '"';
<ide> }
<ide>
<ide><path>src/Database/Schema/SqlserverSchema.php
<ide> public function convertColumnDescription(Table $table, $row)
<ide> $field += [
<ide> 'null' => $row['null'] === '1' ? true : false,
<ide> 'default' => $this->_defaultValue($row['default']),
<del> 'collate' => !empty($row['collation_name']) ? $row['collation_name'] : null,
<add> 'collate' => $row['collation_name'],
<ide> ];
<ide> $table->addColumn($row['name'], $field);
<ide> }
<ide> public function columnSql(Table $table, $name)
<ide> }
<ide>
<ide> $hasCollate = ['text', 'string'];
<del> if (in_array($data['type'], $hasCollate, true) && isset($data['collate'])) {
<add> if (in_array($data['type'], $hasCollate, true) && isset($data['collate']) && $data['collate'] !== '') {
<ide> $out .= ' COLLATE ' . $data['collate'];
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public function testConvertColumn($type, $expected)
<ide> 'Type' => $type,
<ide> 'Null' => 'YES',
<ide> 'Default' => 'Default value',
<del> 'Collation' => 'Collate information',
<add> 'Collation' => 'utf8_general_ci',
<ide> 'Comment' => 'Comment section',
<ide> ];
<ide> $expected += [
<ide> 'null' => true,
<ide> 'default' => 'Default value',
<del> 'collate' => 'Collate information',
<add> 'collate' => 'utf8_general_ci',
<ide> 'comment' => 'Comment section',
<ide> ];
<ide>
<ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> public function testConvertColumn($type, $expected)
<ide> 'default' => 'Default value',
<ide> 'comment' => 'Comment section',
<ide> 'char_length' => null,
<del> 'collation_name' => 'Collate information',
<add> 'collation_name' => 'ja_JP.utf8',
<ide> ];
<ide> $expected += [
<ide> 'null' => true,
<ide> 'default' => 'Default value',
<ide> 'comment' => 'Comment section',
<del> 'collate' => 'Collate information',
<add> 'collate' => 'ja_JP.utf8',
<ide> ];
<ide>
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Postgres')->getMock();
<ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php
<ide> public function testConvertColumn($type, $length, $precision, $scale, $expected)
<ide> 'char_length' => $length,
<ide> 'precision' => $precision,
<ide> 'scale' => $scale,
<del> 'collation_name' => 'Collate information',
<add> 'collation_name' => 'Japanese_Unicode_CI_AI',
<ide> ];
<ide> $expected += [
<ide> 'null' => true,
<ide> 'default' => 'Default value',
<del> 'collate' => 'Collate information',
<add> 'collate' => 'Japanese_Unicode_CI_AI',
<ide> ];
<ide>
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')->getMock();
<ide> public static function columnSqlProvider()
<ide> ['type' => 'string'],
<ide> '[title] NVARCHAR(255)'
<ide> ],
<add> [
<add> 'title',
<add> ['type' => 'string', 'length' => 25, 'null' => false, 'collate' => 'Japanese_Unicode_CI_AI'],
<add> '[title] NVARCHAR(25) COLLATE Japanese_Unicode_CI_AI NOT NULL'
<add> ],
<ide> // Text
<ide> [
<ide> 'body',
<ide> public static function columnSqlProvider()
<ide> ['type' => 'text', 'length' => Table::LENGTH_LONG, 'null' => false],
<ide> '[body] NVARCHAR(MAX) NOT NULL'
<ide> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'null' => false, 'collate' => 'Japanese_Unicode_CI_AI'],
<add> '[body] NVARCHAR(MAX) COLLATE Japanese_Unicode_CI_AI NOT NULL'
<add> ],
<ide> // Integers
<ide> [
<ide> 'post_id', | 6 |
Python | Python | update pypi release to 0.3.1 | f447644900fd1c7653ce4c9a3728ce20ba20f610 | <ide><path>keras/__init__.py
<del>__version__ = '0.3.0'
<add>__version__ = '0.3.1'
<ide><path>setup.py
<ide>
<ide>
<ide> setup(name='Keras',
<del> version='0.3.0',
<add> version='0.3.1',
<ide> description='Theano-based Deep Learning library',
<ide> author='Francois Chollet',
<ide> author_email='francois.chollet@gmail.com',
<ide> url='https://github.com/fchollet/keras',
<del> download_url='https://github.com/fchollet/keras/tarball/0.3.0',
<add> download_url='https://github.com/fchollet/keras/tarball/0.3.1',
<ide> license='MIT',
<ide> install_requires=['theano', 'pyyaml', 'six'],
<ide> extras_require={ | 2 |
Javascript | Javascript | remove `common.port` from test-tlswrap | ddbf07ab89b501e0ee41c69655920757fb561ca0 | <ide><path>test/async-hooks/test-tlswrap.js
<ide> const server = tls
<ide> })
<ide> .on('listening', common.mustCall(onlistening))
<ide> .on('secureConnection', common.mustCall(onsecureConnection))
<del> .listen(common.PORT);
<add> .listen(0);
<ide>
<ide> let svr, client;
<ide> function onlistening() {
<ide> //
<ide> // Creating client and connecting it to server
<ide> //
<ide> tls
<del> .connect(common.PORT, { rejectUnauthorized: false })
<add> .connect(server.address().port, { rejectUnauthorized: false })
<ide> .on('secureConnect', common.mustCall(onsecureConnect));
<ide>
<ide> const as = hooks.activitiesOfTypes('TLSWRAP'); | 1 |
Text | Text | adjust assignment in condition in stream doc | 8cba65f61afe35228938c04b2c8527897366f689 | <ide><path>doc/api/stream.md
<ide> readable.on('readable', function() {
<ide> // There is some data to read now.
<ide> let data;
<ide>
<del> while (data = this.read()) {
<add> while ((data = this.read()) !== null) {
<ide> console.log(data);
<ide> }
<ide> }); | 1 |
Ruby | Ruby | remove duplicate insertion spec | bfcb7ca25d86491fb4e1edeb463a99006f6c7151 | <ide><path>spec/active_relation/unit/relations/insertion_spec.rb
<ide> module ActiveRelation
<ide> ")
<ide> end
<ide> end
<del>
<del> describe 'when given values whose types correspond to the type of the attribtues' do
<del> before do
<del> @insertion = Insertion.new(@relation, @relation[:name] => "nick")
<del> end
<del>
<del> it 'manufactures sql inserting data' do
<del> @insertion.to_sql.should be_like("
<del> INSERT
<del> INTO `users`
<del> (`users`.`name`) VALUES ('nick')
<del> ")
<del> end
<del> end
<ide> end
<ide>
<ide> describe '#call' do | 1 |
Text | Text | add the text "printer" to article | 2787e6aac68653f78321d555a684bd22596be39b | <ide><path>guide/english/computer-hardware/index.md
<ide> Input/Output device is any hardware used by a human operator or other systems to
<ide> A computer monitor is an output device which displays information in pictorial form.
<ide>
<ide> 
<add>
<add>### Printer
<add>A Printer is also an output device which print information on paper and you will get hard copy of your information.
<add>
<add>
<add>
<add>
<add> | 1 |
Text | Text | update euler-51 with faster solution | 64cb47e1348d63e38a60d78646c1234f1257ecfd | <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-51-prime-digit-replacements.md
<ide> primeDigitReplacements(6);
<ide> # --solutions--
<ide>
<ide> ```js
<add>const NUM_PRIMES = 1000000;
<add>const PRIME_SEIVE = Array(Math.floor((NUM_PRIMES-1)/2)).fill(true);
<add>(function initPrimes(num) {
<add> const upper = Math.floor((num - 1) / 2);
<add> const sqrtUpper = Math.floor((Math.sqrt(num) - 1) / 2);
<add> for (let i = 0; i <= sqrtUpper; i++) {
<add> if (PRIME_SEIVE[i]) {
<add> // Mark value in PRIMES array
<add> const prime = 2 * i + 3;
<add> // Mark all multiples of this number as false (not prime)
<add> const primeSqaredIndex = 2 * i ** 2 + 6 * i + 3;
<add> for (let j = primeSqaredIndex; j < upper; j += prime) {
<add> PRIME_SEIVE[j] = false;
<add> }
<add> }
<add> }
<add>})(NUM_PRIMES);
<add>
<add>function isPrime(num) {
<add> if (num === 2) return true;
<add> else if (num % 2 === 0) return false
<add> else return PRIME_SEIVE[(num - 3) / 2];
<add>}
<add>
<ide> function primeDigitReplacements(n) {
<del> function isNFamily(number, primesMap, n) {
<add> function isNFamily(number, n) {
<ide> const prime = number.toString();
<ide> const lastDigit = prime[prime.length - 1];
<del> return (
<del> doesReplacingMakeFamily(prime, '0', primesMap, n) ||
<del> (lastDigit !== '1' &&
<del> doesReplacingMakeFamily(prime, '1', primesMap, n)) ||
<del> doesReplacingMakeFamily(prime, '2', primesMap, n)
<del> );
<add> return doesReplacingMakeFamily(prime, '0', n) ||
<add> doesReplacingMakeFamily(prime, '2', n) ||
<add> (lastDigit !== '1' && doesReplacingMakeFamily(prime, '1', n));
<ide> }
<ide>
<del> function doesReplacingMakeFamily(prime, digitToReplace, primesMap, family) {
<del> let count = 0;
<del> const replaceWith = '0123456789';
<del>
<del> for (let i = 0; i < replaceWith.length; i++) {
<del> const nextNumber = parseInt(
<del> prime.replace(new RegExp(digitToReplace, 'g'), replaceWith[i]),
<del> 10
<del> );
<del>
<del> if (isPartOfFamily(nextNumber, prime, primesMap)) {
<del> count++;
<del> }
<add> function doesReplacingMakeFamily(prime, digitToReplace, family) {
<add> let miss = 0;
<add> const base = parseInt(
<add> prime
<add> .split('')
<add> .map(digit => digit == digitToReplace ? '0' : digit)
<add> .join('')
<add> );
<add> const replacements = parseInt(
<add> prime
<add> .split('')
<add> .map(digit => digit === digitToReplace ? '1' : '0')
<add> .join('')
<add> );
<add> const start = prime[0] === digitToReplace ? 1 : 0;
<add> for (let i = start; i < 10; i++) {
<add> const nextNumber = base + i * replacements;
<add> if (!isPartOfFamily(nextNumber, prime)) miss++;
<add> if (10 - start - miss < family) break;
<ide> }
<del> return count === family;
<add> return 10 - start - miss === family;
<ide> }
<ide>
<del> function isPartOfFamily(number, prime, primesMap) {
<add> function isPartOfFamily(number, prime) {
<ide> return (
<del> isPrime(number, primesMap) && number.toString().length === prime.length
<add> isPrime(number) && number.toString().length === prime.length
<ide> );
<ide> }
<ide>
<del> function getSievePrimes(max) {
<del> const primesMap = new Array(max).fill(true);
<del> primesMap[0] = false;
<del> primesMap[1] = false;
<del>
<del> for (let i = 2; i < max; i++) {
<del> if (primesMap[i]) {
<del> let j = i * i;
<del> for (j; j < max; j += i) {
<del> primesMap[j] = false;
<del> }
<del> }
<del> }
<del> return primesMap;
<del> }
<del>
<del> function isPrime(num, primesMap) {
<del> return primesMap[num];
<del> }
<del>
<del> const primesMap = getSievePrimes(1000000);
<del>
<del> for (let number = 1; number < 300000; number++) {
<del> if (primesMap[number]) {
<del> if (isNFamily(number, primesMap, n)) {
<del> return number;
<del> }
<add> for (let number = 1; number < 125000; number++) {
<add> if (isPrime(number) && isNFamily(number, n)) {
<add> return number;
<ide> }
<ide> }
<ide> return -1; | 1 |
Javascript | Javascript | improve error message when deserialization failed | 83c5305872a7a48b2264982a2522404724a1ec24 | <ide><path>lib/serialization/ObjectMiddleware.js
<ide> class ObjectMiddleware extends SerializerMiddleware {
<ide>
<ide> objectTypeLookup.set(currentPosTypeLookup++, serializer);
<ide> }
<del> const item = serializer.deserialize(ctx);
<del> const end1 = read();
<add> try {
<add> const item = serializer.deserialize(ctx);
<add> const end1 = read();
<ide>
<del> if (end1 !== ESCAPE) {
<del> throw new Error("Expected end of object");
<del> }
<add> if (end1 !== ESCAPE) {
<add> throw new Error("Expected end of object");
<add> }
<ide>
<del> const end2 = read();
<add> const end2 = read();
<ide>
<del> if (end2 !== ESCAPE_END_OBJECT) {
<del> throw new Error("Expected end of object");
<del> }
<del>
<del> addReferenceable(item);
<add> if (end2 !== ESCAPE_END_OBJECT) {
<add> throw new Error("Expected end of object");
<add> }
<ide>
<del> return item;
<add> addReferenceable(item);
<add>
<add> return item;
<add> } catch (err) {
<add> // As this is only for error handling, we omit creating a Map for
<add> // faster access to this information, as this would affect performance
<add> // in the good case
<add> let serializerEntry;
<add> for (const entry of serializers) {
<add> if (entry[1].serializer === serializer) {
<add> serializerEntry = entry;
<add> break;
<add> }
<add> }
<add> const name = !serializerEntry
<add> ? "unknown"
<add> : !serializerEntry[1].request
<add> ? serializerEntry[0].name
<add> : serializerEntry[1].name
<add> ? `${serializerEntry[1].request} ${serializerEntry[1].name}`
<add> : serializerEntry[1].request;
<add> err.message += `\n(during deserialization of ${name})`;
<add> throw err;
<add> }
<ide> }
<ide> } else if (typeof item === "string") {
<ide> if (item !== "") { | 1 |
Python | Python | add better test for inexact numbers | 620653b708d24c457256dc9c10996172cc4811d9 | <ide><path>numpy/core/tests/test_scalarmath.py
<ide> def check_large_types(self):
<ide> for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]:
<ide> a = t(51)
<ide> b = a ** 4
<del> assert b == 6765201, "error with %r: got %r" % (t,b)
<add> msg = "error with %r: got %r" % (t,b)
<add> if issubdtype(t, np.integer):
<add> assert b == 6765201, msg
<add> else:
<add> assert_almost_equal(b, 6765201, err_msg=msg)
<ide>
<ide> class TestConversion(NumpyTestCase):
<ide> def test_int_from_long(self): | 1 |
Java | Java | fix observable.delay & flowable.delay javadoc | 15fea59b8d890174d1339818f98fb391b5647cfe | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public final Flowable<T> delay(long delay, TimeUnit unit) {
<ide>
<ide> /**
<ide> * Returns a Flowable that emits the items emitted by the source Publisher shifted forward in time by a
<del> * specified delay. Error notifications from the source Publisher are not delayed.
<add> * specified delay. If {@code delayError} is true, error notifications will also be delayed.
<ide> * <p>
<ide> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.png" alt="">
<ide> * <dl>
<ide> public final Flowable<T> delay(long delay, TimeUnit unit, Scheduler scheduler) {
<ide>
<ide> /**
<ide> * Returns a Flowable that emits the items emitted by the source Publisher shifted forward in time by a
<del> * specified delay. Error notifications from the source Publisher are not delayed.
<add> * specified delay. If {@code delayError} is true, error notifications will also be delayed.
<ide> * <p>
<ide> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.s.png" alt="">
<ide> * <dl>
<ide><path>src/main/java/io/reactivex/Observable.java
<ide> public final Observable<T> delay(long delay, TimeUnit unit) {
<ide>
<ide> /**
<ide> * Returns an Observable that emits the items emitted by the source ObservableSource shifted forward in time by a
<del> * specified delay. Error notifications from the source ObservableSource are not delayed.
<add> * specified delay. If {@code delayError} is true, error notifications will also be delayed.
<ide> * <p>
<ide> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.png" alt="">
<ide> * <dl>
<ide> public final Observable<T> delay(long delay, TimeUnit unit, Scheduler scheduler)
<ide>
<ide> /**
<ide> * Returns an Observable that emits the items emitted by the source ObservableSource shifted forward in time by a
<del> * specified delay. Error notifications from the source ObservableSource are not delayed.
<add> * specified delay. If {@code delayError} is true, error notifications will also be delayed.
<ide> * <p>
<ide> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.s.png" alt="">
<ide> * <dl> | 2 |
Python | Python | add test for small percentile | 159714bd258645d82a0e511c44a9fc60b0837bc2 | <ide><path>benchmarks/benchmarks/bench_function_base.py
<ide> def time_wide(self):
<ide> class Percentile(Benchmark):
<ide> def setup(self):
<ide> self.e = np.arange(10000, dtype=np.float32)
<del> self.o = np.arange(10001, dtype=np.float32)
<add> self.o = np.arange(21, dtype=np.float32)
<ide>
<ide> def time_quartile(self):
<ide> np.percentile(self.e, [25, 75])
<ide>
<ide> def time_percentile(self):
<ide> np.percentile(self.e, [25, 35, 55, 65, 75])
<ide>
<add> def time_percentile_small(self):
<add> np.percentile(self.o, [25, 75])
<add>
<ide>
<ide> class Select(Benchmark):
<ide> def setup(self): | 1 |
Python | Python | remove the minifying logic | 0e2b25034edce829c1bd584c538199be98d0be50 | <ide><path>tools/js2c.py
<ide> # library.
<ide>
<ide> import os
<del>from os.path import dirname
<ide> import re
<ide> import sys
<ide> import string
<ide>
<del>sys.path.append(dirname(__file__) + "/../deps/v8/tools");
<del>import jsmin
<del>
<ide>
<ide> def ToCArray(filename, lines):
<ide> return ','.join(str(ord(c)) for c in lines)
<ide>
<ide>
<del>def CompressScript(lines, do_jsmin):
<del> # If we're not expecting this code to be user visible, we can run it through
<del> # a more aggressive minifier.
<del> if do_jsmin:
<del> minifier = JavaScriptMinifier()
<del> return minifier.JSMinify(lines)
<del>
<del> # Remove stuff from the source that we don't want to appear when
<del> # people print the source code using Function.prototype.toString().
<del> # Note that we could easily compress the scripts mode but don't
<del> # since we want it to remain readable.
<del> #lines = re.sub('//.*\n', '\n', lines) # end-of-line comments
<del> #lines = re.sub(re.compile(r'/\*.*?\*/', re.DOTALL), '', lines) # comments.
<del> #lines = re.sub('\s+\n+', '\n', lines) # trailing whitespace
<del> return lines
<del>
<del>
<ide> def ReadFile(filename):
<ide> file = open(filename, "rt")
<ide> try:
<ide> def JS2C(source, target):
<ide> for s in modules:
<ide> delay = str(s).endswith('-delay.js')
<ide> lines = ReadFile(str(s))
<del> do_jsmin = lines.find('// jsminify this file, js2c: jsmin') != -1
<ide>
<ide> lines = ExpandConstants(lines, consts)
<ide> lines = ExpandMacros(lines, macros)
<del> lines = CompressScript(lines, do_jsmin)
<ide> data = ToCArray(s, lines)
<ide>
<ide> # On Windows, "./foo.bar" in the .gyp file is passed as "foo.bar" | 1 |
Java | Java | add callback for uiimplementation layout updates | 91372e8f9aafcad2b5594175b1a3ce6f9c8f3b8e | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java
<ide> public class UIImplementation {
<ide> private final int[] mMeasureBuffer = new int[4];
<ide>
<ide> private long mLastCalculateLayoutTime = 0;
<add> protected @Nullable LayoutUpdateListener mLayoutUpdateListener;
<add>
<add> /** Interface definition for a callback to be invoked when the layout has been updated */
<add> public interface LayoutUpdateListener {
<add>
<add> /** Called when the layout has been updated */
<add> void onLayoutUpdated(ReactShadowNode root);
<add> }
<ide>
<ide> public UIImplementation(
<ide> ReactApplicationContext reactContext,
<ide> protected void updateViewHierarchy() {
<ide> } finally {
<ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<ide> }
<add>
<add> if (mLayoutUpdateListener != null) {
<add> mLayoutUpdateListener.onLayoutUpdated(cssRoot);
<add> }
<ide> }
<ide> }
<ide> } finally {
<ide> public int resolveRootTagFromReactTag(int reactTag) {
<ide> public void enableLayoutCalculationForRootNode(int rootViewTag) {
<ide> this.mMeasuredRootNodes.add(rootViewTag);
<ide> }
<add>
<add> public void setLayoutUpdateListener(LayoutUpdateListener listener) {
<add> mLayoutUpdateListener = listener;
<add> }
<add>
<add> public void removeLayoutUpdateListener() {
<add> mLayoutUpdateListener = null;
<add> }
<ide> } | 1 |
PHP | PHP | apply fixes from styleci | 737b639580598bc77f53f38e2f84431ed5b514ff | <ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testNestedErrorMessagesAreRetrievedFromLocalArray()
<ide> 'posts' => [
<ide> [
<ide> 'name' => '',
<del> ]
<add> ],
<ide> ],
<ide> ],
<ide> ], | 1 |
PHP | PHP | add cache global helper | f53291b2b6e2d3032b4254e83ca03708dae1ec26 | <ide><path>src/Illuminate/Foundation/helpers.php
<ide> function session($key = null, $default = null)
<ide> }
<ide> }
<ide>
<add>if (! function_exists('cache')) {
<add> /**
<add> * Get / set the specified cache value.
<add> *
<add> * If an array is passed, we'll assume you want to put to the cache.
<add> *
<add> * @param dynamic key|key,default|data,expiration|null
<add> * @return mixed
<add> */
<add> function cache()
<add> {
<add> $arguments = func_get_args();
<add>
<add> if (empty($arguments)) {
<add> return app('cache');
<add> }
<add>
<add> if (is_string($arguments[0])) {
<add> return app('cache')->get($arguments[0], isset($arguments[1]) ? $arguments[1]: null);
<add> }
<add>
<add> if (is_array($arguments[0])) {
<add> if (! isset($arguments[1])) {
<add> throw new Exception(
<add> 'You must set an expiration time when putting to the cache.'
<add> );
<add> }
<add>
<add> return app('cache')->put(key($arguments[0]), reset($arguments[0]), $arguments[1]);
<add> }
<add> }
<add>}
<add>
<ide> if (! function_exists('storage_path')) {
<ide> /**
<ide> * Get the path to the storage folder.
<ide><path>tests/Foundation/FoundationHelpersTest.php
<add><?php
<add>
<add>use Mockery as m;
<add>use Illuminate\Foundation\Application;
<add>
<add>class FoundationHelpersTest extends PHPUnit_Framework_TestCase
<add>{
<add> public function tearDown()
<add> {
<add> m::close();
<add> }
<add>
<add> public function testCache()
<add> {
<add> $app = new Application;
<add> $app['cache'] = $cache = m::mock('StdClass');
<add>
<add> // 1. cache()
<add> $this->assertInstanceOf('StdClass', cache());
<add>
<add> // 2. cache(['foo' => 'bar'], 1);
<add> $cache->shouldReceive('put')->once()->with('foo', 'bar', 1);
<add> cache(['foo' => 'bar'], 1);
<add>
<add> // 3. cache('foo');
<add> $cache->shouldReceive('get')->once()->andReturn('bar');
<add> $this->assertEquals('bar', cache('foo'));
<add>
<add> // 4. cache('baz', 'default');
<add> $cache->shouldReceive('get')->once()->with('baz', 'default')->andReturn('default');
<add> $this->assertEquals('default', cache('baz', 'default'));
<add> }
<add>
<add> public function testCacheThrowsAnExceptionIfAnExpirationIsNotProvided()
<add> {
<add> $this->setExpectedException('Exception');
<add>
<add> cache(['foo' => 'bar']);
<add> }
<add>} | 2 |
Javascript | Javascript | help the gc | 5a80ba12f1e05e6afa6359ed36d881ea419009ee | <ide><path>lib/serialization/ObjectMiddleware.js
<ide> class ObjectMiddleware extends SerializerMiddleware {
<ide> throw new Error("Version mismatch, serializer changed");
<ide>
<ide> let currentPos = 0;
<del> const referenceable = [];
<add> let referenceable = [];
<ide> const addReferenceable = item => {
<ide> referenceable.push(item);
<ide> currentPos++;
<ide> };
<ide> let currentPosTypeLookup = 0;
<del> const objectTypeLookup = [];
<add> let objectTypeLookup = [];
<ide> const result = [];
<ide> const ctx = {
<ide> read() {
<ide> class ObjectMiddleware extends SerializerMiddleware {
<ide> result.push(decodeValue());
<ide> }
<ide>
<add> // Help the GC, as functions above might be cached in inline caches
<add> referenceable = undefined;
<add> objectTypeLookup = undefined;
<add> data = undefined;
<add>
<ide> return result;
<ide> }
<ide> } | 1 |
Python | Python | fix some rest errors in core/defchararray.py | 2411b7b0f1bee1472db260728de38f0dba4baf7b | <ide><path>numpy/core/defchararray.py
<ide> def add(x1, x2):
<ide> Returns
<ide> -------
<ide> out : ndarray
<del> Output array of string_ or unicode_, depending on input types
<add> Output array of `string_` or `unicode_`, depending on input types
<ide> """
<ide> arr1 = numpy.asarray(x1)
<ide> arr2 = numpy.asarray(x2)
<ide> def __add__(self, other):
<ide> def __radd__(self, other):
<ide> """
<ide> Return (other + self), that is string concatenation,
<del> element-wise for a pair of array_likes of string_ or unicode_.
<add> element-wise for a pair of array_likes of `string_` or `unicode_`.
<ide>
<ide> See also
<ide> --------
<ide> def __rmul__(self, i):
<ide> def __mod__(self, i):
<ide> """
<ide> Return (self % i), that is pre-Python 2.6 string formatting
<del> (iterpolation), element-wise for a pair of array_likes of string_
<del> or unicode_.
<add> (iterpolation), element-wise for a pair of array_likes of `string_`
<add> or `unicode_`.
<ide>
<ide> See also
<ide> --------
<ide> def array(obj, itemsize=None, copy=True, unicode=None, order=None):
<ide> .. note::
<ide> This class is provided for numarray backward-compatibility.
<ide> New code (not concerned with numarray compatibility) should use
<del> arrays of type string_ or unicode_ and use the free functions
<add> arrays of type `string_` or `unicode_` and use the free functions
<ide> in :mod:`numpy.char <numpy.core.defchararray>` for fast
<ide> vectorized string operations instead.
<ide>
<ide> class adds the following functionality:
<ide> end when comparing values
<ide>
<ide> 3) vectorized string operations are provided as methods
<del> (e.g. `str.endswith`) and infix operators (e.g. +, *, %)
<add> (e.g. `str.endswith`) and infix operators (e.g. ``+, *, %``)
<ide>
<ide> Parameters
<ide> ---------- | 1 |
Java | Java | remove extra synchronization | d107ebaa37de645529e2512bfbe51153a96e9ee1 | <ide><path>rxjava-core/src/main/java/rx/operators/OperationParallel.java
<ide> public Integer call(T t) {
<ide> return i.incrementAndGet() % s.degreeOfParallelism();
<ide> }
<ide>
<del> }).flatMap(new Func1<GroupedObservable<Integer, T>, Observable<R>>() {
<add> }).mergeMap(new Func1<GroupedObservable<Integer, T>, Observable<R>>() {
<ide>
<ide> @Override
<ide> public Observable<R> call(GroupedObservable<Integer, T> group) {
<ide> return f.call(group.observeOn(s));
<ide> }
<del> }).synchronize();
<add> });
<ide> }
<ide> });
<ide> } | 1 |
Text | Text | add 2.13.2 to changelog.md | 787e0894144fb498f5350d25a72559217b227403 | <ide><path>CHANGELOG.md
<ide> - [#15178](https://github.com/emberjs/ember.js/pull/15178) Refactor route to lookup controller for QPs.
<ide> - [#15129](https://github.com/emberjs/ember.js/pull/15129) Fix access to service:-document in ember-engines
<ide>
<add>### 2.13.2 (May 18, 2017)
<add>
<add>- Revert over eager dependency upgrades in 2.13.1.
<add>
<ide> ### 2.13.1 (May 17, 2017)
<ide>
<ide> - [#15129](https://github.com/emberjs/ember.js/pull/15129) Fix access to document service in `ember-engines`. | 1 |
Java | Java | update copyright year of changed file | ca6911a532925e8f2a4d8c0901e5536dd60d1841 | <ide><path>spring-core/src/main/java/org/springframework/util/CollectionUtils.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License. | 1 |
Go | Go | set default memoryswap on docker side | 7e0dfbf4cdbb8694a90818b5cd746b92e11a78c7 | <ide><path>daemon/create.go
<ide> func (daemon *Daemon) ContainerCreate(name string, config *runconfig.Config, hos
<ide> return "", nil, fmt.Errorf("Config cannot be empty in order to create a container")
<ide> }
<ide>
<add> daemon.adaptContainerSettings(hostConfig)
<ide> warnings, err := daemon.verifyContainerSettings(hostConfig, config)
<ide> if err != nil {
<ide> return "", warnings, err
<ide><path>daemon/daemon_unix.go
<ide> func checkKernel() error {
<ide> return nil
<ide> }
<ide>
<add>func (daemon *Daemon) adaptContainerSettings(hostConfig *runconfig.HostConfig) {
<add> if hostConfig == nil {
<add> return
<add> }
<add> if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
<add> // By default, MemorySwap is set to twice the size of Memory.
<add> hostConfig.MemorySwap = hostConfig.Memory * 2
<add> }
<add>}
<add>
<ide> func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) {
<ide> var warnings []string
<ide>
<ide><path>daemon/daemon_windows.go
<ide> func checkKernel() error {
<ide> return nil
<ide> }
<ide>
<add>func (daemon *Daemon) adaptContainerSettings(hostConfig *runconfig.HostConfig) {
<add> // TODO Windows.
<add>}
<add>
<ide> func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) {
<ide> // TODO Windows. Verifications TBC
<ide> return nil, nil | 3 |
Python | Python | fix some misspellings | f23c328e0d992f07ba811a86dca5a542a43918ce | <ide><path>glances/core/glances_processes.py
<ide> def __init__(self, cache_timeout=60):
<ide> self.processcount = {
<ide> 'total': 0, 'running': 0, 'sleeping': 0, 'thread': 0}
<ide>
<del> # Tag to enable/disable the processes stats (to reduce the Glances CPU comsumption)
<add> # Tag to enable/disable the processes stats (to reduce the Glances CPU consumption)
<ide> # Default is to enable the processes stats
<ide> self.disable_tag = False
<ide>
<ide><path>glances/core/glances_standalone.py
<ide> def __init__(self, config=None, args=None):
<ide>
<ide> # If process extended stats is disabled by user
<ide> if not args.enable_process_extended:
<del> logger.info(_("Extended stats for top process is disabled (default behavor)"))
<add> logger.info(_("Extended stats for top process are disabled (default behavior)"))
<ide> glances_processes.disable_extended()
<ide> else:
<del> logger.debug(_("Extended stats for top process is enabled"))
<add> logger.debug(_("Extended stats for top process are enabled"))
<ide> glances_processes.enable_extended()
<ide>
<ide> # Manage optionnal process filter | 2 |
Javascript | Javascript | improve ember.logger setup - fixes | f20bf0599d8185aaa7d154081d0b41336d7d85e2 | <ide><path>packages/ember-metal/lib/core.js
<ide> Ember.uuid = 0;
<ide> //
<ide>
<ide> function consoleMethod(name) {
<del> if (imports.console && imports.console[name]) {
<add> var console = imports.console,
<add> method = typeof console === 'object' ? console[name] : null;
<add>
<add> if (method) {
<ide> // Older IE doesn't support apply, but Chrome needs it
<del> if (imports.console[name].apply) {
<add> if (method.apply) {
<ide> return function() {
<del> imports.console[name].apply(imports.console, arguments);
<add> method.apply(console, arguments);
<ide> };
<ide> } else {
<ide> return function() {
<ide> var message = Array.prototype.join.call(arguments, ', ');
<del> imports.console[name](message);
<add> method(message);
<ide> };
<ide> }
<ide> } | 1 |
PHP | PHP | fix issues with model bake | 30590ba4239bdda0b96692c2a158325c1eae6e15 | <ide><path>src/Console/Command/Task/ModelTask.php
<ide> public function generate($name) {
<ide> );
<ide> $this->bakeTable($model, $data);
<ide> $this->bakeEntity($model, $data);
<del> $this->bakeFixture($model, $table);
<del> $this->bakeTest($model);
<add> $this->bakeFixture($model->alias(), $table);
<add> $this->bakeTest($model->alias());
<ide> }
<ide>
<ide> /**
<ide> public function findBelongsTo($model, $associations) {
<ide> $tmpModelName = $this->_modelNameFromKey($fieldName);
<ide> $associations['belongsTo'][] = [
<ide> 'alias' => $tmpModelName,
<del> 'className' => $tmpModelName,
<ide> 'foreignKey' => $fieldName,
<ide> ];
<ide> } elseif ($fieldName === 'parent_id') {
<ide> $associations['belongsTo'][] = [
<ide> 'alias' => 'Parent' . $model->alias(),
<del> 'className' => $model->alias(),
<ide> 'foreignKey' => $fieldName,
<ide> ];
<ide> }
<ide> public function findHasMany($model, $associations) {
<ide> if (!in_array($fieldName, $primaryKey) && $fieldName == $foreignKey) {
<ide> $assoc = [
<ide> 'alias' => $otherModel->alias(),
<del> 'className' => $otherModel->alias(),
<ide> 'foreignKey' => $fieldName
<ide> ];
<ide> } elseif ($otherTable == $tableName && $fieldName === 'parent_id') {
<ide> $assoc = [
<ide> 'alias' => 'Child' . $model->alias(),
<del> 'className' => $model->alias(),
<ide> 'foreignKey' => $fieldName
<ide> ];
<ide> }
<ide> public function findBelongsToMany($model, $associations) {
<ide> $habtmName = $this->_modelName($assocTable);
<ide> $associations['belongsToMany'][] = [
<ide> 'alias' => $habtmName,
<del> 'className' => $habtmName,
<ide> 'foreignKey' => $foreignKey,
<ide> 'targetForeignKey' => $this->_modelKey($habtmName),
<ide> 'joinTable' => $otherTable
<ide><path>tests/TestCase/Console/Command/Task/ModelTaskTest.php
<ide> public function testGetAssociations() {
<ide> 'belongsTo' => [
<ide> [
<ide> 'alias' => 'BakeUsers',
<del> 'className' => 'BakeUsers',
<ide> 'foreignKey' => 'bake_user_id',
<ide> ],
<ide> ],
<ide> 'hasMany' => [
<ide> [
<ide> 'alias' => 'BakeComments',
<del> 'className' => 'BakeComments',
<ide> 'foreignKey' => 'bake_article_id',
<ide> ],
<ide> ],
<ide> 'belongsToMany' => [
<ide> [
<ide> 'alias' => 'BakeTags',
<del> 'className' => 'BakeTags',
<ide> 'foreignKey' => 'bake_article_id',
<ide> 'joinTable' => 'bake_articles_bake_tags',
<ide> 'targetForeignKey' => 'bake_tag_id',
<ide> public function testBelongsToGeneration() {
<ide> 'belongsTo' => [
<ide> [
<ide> 'alias' => 'BakeArticles',
<del> 'className' => 'BakeArticles',
<ide> 'foreignKey' => 'bake_article_id',
<ide> ],
<ide> [
<ide> 'alias' => 'BakeUsers',
<del> 'className' => 'BakeUsers',
<ide> 'foreignKey' => 'bake_user_id',
<ide> ],
<ide> ]
<ide> public function testBelongsToGeneration() {
<ide> 'belongsTo' => [
<ide> [
<ide> 'alias' => 'ParentCategoryThreads',
<del> 'className' => 'CategoryThreads',
<ide> 'foreignKey' => 'parent_id',
<ide> ],
<ide> ]
<ide> public function testHasManyGeneration() {
<ide> 'hasMany' => [
<ide> [
<ide> 'alias' => 'BakeComments',
<del> 'className' => 'BakeComments',
<ide> 'foreignKey' => 'bake_article_id',
<ide> ],
<ide> ],
<ide> public function testHasManyGeneration() {
<ide> 'hasMany' => [
<ide> [
<ide> 'alias' => 'ChildCategoryThreads',
<del> 'className' => 'CategoryThreads',
<ide> 'foreignKey' => 'parent_id',
<ide> ],
<ide> ]
<ide> public function testHasAndBelongsToManyGeneration() {
<ide> 'belongsToMany' => [
<ide> [
<ide> 'alias' => 'BakeTags',
<del> 'className' => 'BakeTags',
<ide> 'foreignKey' => 'bake_article_id',
<ide> 'joinTable' => 'bake_articles_bake_tags',
<ide> 'targetForeignKey' => 'bake_tag_id',
<ide> public function testBakeTableRelations() {
<ide> 'belongsTo' => [
<ide> [
<ide> 'alias' => 'SomethingElse',
<del> 'className' => 'SomethingElse',
<ide> 'foreignKey' => 'something_else_id',
<ide> ],
<ide> [
<ide> 'alias' => 'BakeUser',
<del> 'className' => 'BakeUser',
<ide> 'foreignKey' => 'bake_user_id',
<ide> ],
<ide> ],
<ide> 'hasMany' => [
<ide> [
<ide> 'alias' => 'BakeComment',
<del> 'className' => 'BakeComment',
<ide> 'foreignKey' => 'parent_id',
<ide> ],
<ide> ],
<ide> 'belongsToMany' => [
<ide> [
<ide> 'alias' => 'BakeTag',
<del> 'className' => 'BakeTag',
<ide> 'foreignKey' => 'bake_article_id',
<ide> 'joinTable' => 'bake_articles_bake_tags',
<ide> 'targetForeignKey' => 'bake_tag_id', | 2 |
Mixed | Python | add validate option to entityruler | 69aca7d8391e0bbc551fe588e1f3b06f1d68a3f2 | <ide><path>spacy/pipeline/entityruler.py
<ide> class EntityRuler(object):
<ide>
<ide> name = "entity_ruler"
<ide>
<del> def __init__(self, nlp, phrase_matcher_attr=None, **cfg):
<add> def __init__(self, nlp, phrase_matcher_attr=None, validate=False, **cfg):
<ide> """Initialize the entitiy ruler. If patterns are supplied here, they
<ide> need to be a list of dictionaries with a `"label"` and `"pattern"`
<ide> key. A pattern can either be a token pattern (list) or a phrase pattern
<ide> def __init__(self, nlp, phrase_matcher_attr=None, **cfg):
<ide> and process phrase patterns.
<ide> phrase_matcher_attr (int / unicode): Token attribute to match on, passed
<ide> to the internal PhraseMatcher as `attr`
<add> validate (bool): Whether patterns should be validated, passed to
<add> Matcher and PhraseMatcher as `validate`
<ide> patterns (iterable): Optional patterns to load in.
<ide> overwrite_ents (bool): If existing entities are present, e.g. entities
<ide> added by the model, overwrite them by matches if necessary.
<ide> def __init__(self, nlp, phrase_matcher_attr=None, **cfg):
<ide> self.overwrite = cfg.get("overwrite_ents", False)
<ide> self.token_patterns = defaultdict(list)
<ide> self.phrase_patterns = defaultdict(list)
<del> self.matcher = Matcher(nlp.vocab)
<add> self.matcher = Matcher(nlp.vocab, validate=validate)
<ide> if phrase_matcher_attr is not None:
<ide> self.phrase_matcher_attr = phrase_matcher_attr
<ide> self.phrase_matcher = PhraseMatcher(
<del> nlp.vocab, attr=self.phrase_matcher_attr
<add> nlp.vocab, attr=self.phrase_matcher_attr, validate=validate
<ide> )
<ide> else:
<ide> self.phrase_matcher_attr = None
<del> self.phrase_matcher = PhraseMatcher(nlp.vocab)
<add> self.phrase_matcher = PhraseMatcher(nlp.vocab, validate=validate)
<ide> self.ent_id_sep = cfg.get("ent_id_sep", DEFAULT_ENT_ID_SEP)
<ide> patterns = cfg.get("patterns")
<ide> if patterns is not None:
<ide><path>spacy/tests/pipeline/test_entity_ruler.py
<ide> from spacy.tokens import Span
<ide> from spacy.language import Language
<ide> from spacy.pipeline import EntityRuler
<add>from spacy.errors import MatchPatternError
<ide>
<ide>
<ide> @pytest.fixture
<ide> def test_entity_ruler_serialize_phrase_matcher_attr_bytes(nlp, patterns):
<ide> assert len(new_ruler) == len(patterns)
<ide> assert len(new_ruler.labels) == 4
<ide> assert new_ruler.phrase_matcher_attr == "LOWER"
<add>
<add>
<add>def test_entity_ruler_validate(nlp):
<add> ruler = EntityRuler(nlp)
<add> validated_ruler = EntityRuler(nlp, validate=True)
<add>
<add> valid_pattern = {"label": "HELLO", "pattern": [{"LOWER": "HELLO"}]}
<add> invalid_pattern = {"label": "HELLO", "pattern": [{"ASDF": "HELLO"}]}
<add>
<add> # invalid pattern is added without errors without validate
<add> ruler.add_patterns([invalid_pattern])
<add>
<add> # valid pattern is added without errors with validate
<add> validated_ruler.add_patterns([valid_pattern])
<add>
<add> # invalid pattern raises error with validate
<add> with pytest.raises(MatchPatternError):
<add> validated_ruler.add_patterns([invalid_pattern])
<ide><path>website/docs/api/entityruler.md
<ide> be a token pattern (list) or a phrase pattern (string). For example:
<ide> | `nlp` | `Language` | The shared nlp object to pass the vocab to the matchers and process phrase patterns. |
<ide> | `patterns` | iterable | Optional patterns to load in. |
<ide> | `phrase_matcher_attr` | int / unicode | Optional attr to pass to the internal [`PhraseMatcher`](/api/phtasematcher). defaults to `None` |
<add>| `validate` | bool | Whether patterns should be validated, passed to Matcher and PhraseMatcher as `validate`. Defaults to `False`. |
<ide> | `overwrite_ents` | bool | If existing entities are present, e.g. entities added by the model, overwrite them by matches if necessary. Defaults to `False`. |
<ide> | `**cfg` | - | Other config parameters. If pipeline component is loaded as part of a model pipeline, this will include all keyword arguments passed to `spacy.load`. |
<ide> | **RETURNS** | `EntityRuler` | The newly constructed object. |
<ide><path>website/docs/usage/rule-based-matching.md
<ide> character, but no whitespace – so you'll know it will be handled as one token.
<ide> [{"ORTH": "User"}, {"ORTH": "name"}, {"ORTH": ":"}, {}]
<ide> ```
<ide>
<add>#### Validating and debugging patterns {#pattern-validation new="2.1"}
<add>
<add>The `Matcher` can validate patterns against a JSON schema with the option
<add>`validate=True`. This is useful for debugging patterns during development, in
<add>particular for catching unsupported attributes.
<add>
<add>```python
<add>### {executable="true"}
<add>import spacy
<add>from spacy.matcher import Matcher
<add>
<add>nlp = spacy.load("en_core_web_sm")
<add>matcher = Matcher(nlp.vocab, validate=True)
<add># Add match ID "HelloWorld" with unsupported attribute CASEINSENSITIVE
<add>pattern = [{"LOWER": "hello"}, {"IS_PUNCT": True}, {"CASEINSENSITIVE": "world"}]
<add>matcher.add("HelloWorld", None, pattern)
<add>
<add># Raises an error:
<add>#
<add># spacy.errors.MatchPatternError: Invalid token patterns for matcher rule 'HelloWorld'
<add># Pattern 0:
<add># - Additional properties are not allowed ('CASEINSENSITIVE' was unexpected) [2]
<add>
<add>```
<add>
<ide> ### Adding on_match rules {#on_match}
<ide>
<ide> To move on to a more realistic example, let's say you're working with a large
<ide> doc = nlp(u"MyCorp Inc. is a company in the U.S.")
<ide> print([(ent.text, ent.label_) for ent in doc.ents])
<ide> ```
<ide>
<add>#### Validating and debugging EntityRuler patterns {#entityruler-pattern-validation}
<add>
<add>The `EntityRuler` can validate patterns against a JSON schema with the option
<add>`validate=True`. See details under [Validating and debugging
<add>patterns](#pattern-validation).
<add>
<add>```python
<add>ruler = EntityRuler(nlp, validate=True)
<add>```
<add>
<ide> ### Using pattern files {#entityruler-files}
<ide>
<ide> The [`to_disk`](/api/entityruler#to_disk) and | 4 |
Javascript | Javascript | use charat for ie7 support | 318ad59c2a738688826b12c7de48be13b5342fe5 | <ide><path>packages/sproutcore-metal/lib/accessors.js
<ide> function getPath(target, path) {
<ide> var len = path.length, idx, next, key;
<ide>
<ide> idx = path.indexOf('*');
<del> if (idx>0 && path[idx-1]!=='.') {
<add> if (idx>0 && path.charAt(idx-1)!=='.') {
<ide> return getPath(getPath(target, path.slice(0, idx)), path.slice(idx+1));
<ide> }
<ide> | 1 |
Python | Python | fix experimental api client | f4067b65a55f7b46e991e1fa3af5a1c82bd8915c | <ide><path>airflow/api/auth/backend/default.py
<ide> # under the License.
<ide> """Default authentication backend - everything is allowed"""
<ide> from functools import wraps
<del>from typing import Callable, TypeVar, cast
<add>from typing import Callable, Optional, Tuple, TypeVar, Union, cast
<ide>
<del>from airflow.typing_compat import Protocol
<add>from requests.auth import AuthBase
<ide>
<del>
<del>class ClientAuthProtocol(Protocol):
<del> """
<del> Protocol type for CLIENT_AUTH
<del> """
<del> def handle_response(self, _):
<del> """
<del> CLIENT_AUTH.handle_response method
<del> """
<del> ...
<add>CLIENT_AUTH: Optional[Union[Tuple[str, str], AuthBase]] = None
<ide>
<ide>
<ide> def init_app(_):
<ide><path>airflow/api/auth/backend/deny_all.py
<ide> # under the License.
<ide> """Authentication backend that denies all requests"""
<ide> from functools import wraps
<del>from typing import Callable, Optional, TypeVar, cast
<add>from typing import Callable, Optional, Tuple, TypeVar, Union, cast
<ide>
<ide> from flask import Response
<add>from requests.auth import AuthBase
<ide>
<del>from airflow.api.auth.backend.default import ClientAuthProtocol
<del>
<del>CLIENT_AUTH = None # type: Optional[ClientAuthProtocol]
<add>CLIENT_AUTH: Optional[Union[Tuple[str, str], AuthBase]] = None
<ide>
<ide>
<ide> def init_app(_):
<ide><path>airflow/api/auth/backend/kerberos_auth.py
<ide> import os
<ide> from functools import wraps
<ide> from socket import getfqdn
<del>from typing import Callable, TypeVar, cast
<add>from typing import Callable, Optional, Tuple, TypeVar, Union, cast
<ide>
<ide> import kerberos
<ide> # noinspection PyProtectedMember
<ide> from flask import Response, _request_ctx_stack as stack, g, make_response, request # type: ignore
<add>from requests.auth import AuthBase
<ide> from requests_kerberos import HTTPKerberosAuth
<ide>
<ide> from airflow.configuration import conf
<ide>
<ide> log = logging.getLogger(__name__)
<ide>
<ide> # pylint: disable=c-extension-no-member
<del>CLIENT_AUTH = HTTPKerberosAuth(service='airflow')
<add>CLIENT_AUTH: Optional[Union[Tuple[str, str], AuthBase]] = HTTPKerberosAuth(service='airflow')
<ide>
<ide>
<ide> class KerberosService: # pylint: disable=too-few-public-methods
<ide><path>airflow/api/client/__init__.py
<ide> def get_current_api_client() -> Client:
<ide> api_module = import_module(conf.get('cli', 'api_client')) # type: Any
<ide> api_client = api_module.Client(
<ide> api_base_url=conf.get('cli', 'endpoint_url'),
<del> auth=api.load_auth()
<add> auth=api.load_auth().CLIENT_AUTH
<ide> )
<ide> return api_client
<ide><path>tests/api/auth/__init__.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. 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,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<ide><path>tests/api/auth/test_client.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. 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,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>import unittest
<add>from unittest import mock
<add>
<add>from airflow.api.client import get_current_api_client
<add>from tests.test_utils.config import conf_vars
<add>
<add>
<add>class TestGetCurrentApiClient(unittest.TestCase):
<add>
<add> @mock.patch("airflow.api.client.json_client.Client")
<add> @mock.patch("airflow.api.auth.backend.default.CLIENT_AUTH", "CLIENT_AUTH")
<add> @conf_vars({
<add> ("api", 'auth_backend'): 'airflow.api.auth.backend.default',
<add> ("cli", 'api_client'): 'airflow.api.client.json_client',
<add> ("cli", 'endpoint_url'): 'http://localhost:1234',
<add> })
<add> def test_should_create_cllient(self, mock_client):
<add> result = get_current_api_client()
<add>
<add> mock_client.assert_called_once_with(
<add> api_base_url='http://localhost:1234', auth='CLIENT_AUTH'
<add> )
<add> self.assertEqual(mock_client.return_value, result) | 6 |
Text | Text | update korean translation to 991c437 | b2caf1e4e31281b317be6a3ff6f5106faf971304 | <ide><path>docs/docs/10.4-test-utils.ko-KR.md
<ide> object mockComponent(function componentClass, string? mockTagName)
<ide> boolean isElement(ReactElement element)
<ide> ```
<ide>
<del>`element`가 ReactElement면 true를 리턴합니다.
<add>`element`가 ReactElement면 `true`를 리턴합니다.
<ide>
<ide> ### isElementOfType
<ide>
<ide> ```javascript
<ide> boolean isElementOfType(ReactElement element, function componentClass)
<ide> ```
<ide>
<del>`element`가 React `componentClass` 타입인 ReactElement면 true를 리턴합니다.
<add>`element`가 React `componentClass` 타입인 ReactElement면 `true`를 리턴합니다.
<ide>
<ide> ### isDOMComponent
<ide>
<ide> ```javascript
<ide> boolean isDOMComponent(ReactComponent instance)
<ide> ```
<ide>
<del>`instance`가 (`<div>`나 `<span>`같은) DOM 컴포넌트면 true를 리턴합니다.
<add>`instance`가 (`<div>`나 `<span>`같은) DOM 컴포넌트면 `true`를 리턴합니다.
<ide>
<ide> ### isCompositeComponent
<ide>
<ide> ```javascript
<ide> boolean isCompositeComponent(ReactComponent instance)`
<ide> ```
<ide>
<del>`instance`가 (`React.createClass()`로 생성된) 복합 컴포넌트면 true를 리턴합니다.
<add>`instance`가 (`React.createClass()`로 생성된) 복합 컴포넌트면 `true`를 리턴합니다.
<ide>
<ide> ### isCompositeComponentWithType
<ide>
<ide> ```javascript
<ide> boolean isCompositeComponentWithType(ReactComponent instance, function componentClass)
<ide> ```
<ide>
<del>`instance`가 (`React.createClass()`로 생성된) 복합 컴포넌트고 React `componentClass` 타입이면 true를 리턴합니다.
<add>`instance`가 (`React.createClass()`로 생성된) 복합 컴포넌트고 React `componentClass` 타입이면 `true`를 리턴합니다.
<ide>
<ide> ### findAllInRenderedTree
<ide>
<ide> ```javascript
<ide> array findAllInRenderedTree(ReactComponent tree, function test)
<ide> ```
<ide>
<del>`tree`안의 모든 컴포넌트에서 `test(component)`가 true인 모든 컴포넌트를 모읍니다. 이것만으로는 그렇게 유용하지 않습니다만, 다른 테스트 유틸와 같이 사용합니다.
<add>`tree`안의 모든 컴포넌트에서 `test(component)`가 `true`인 모든 컴포넌트를 모읍니다. 이것만으로는 그렇게 유용하지 않습니다만, 다른 테스트 유틸와 같이 사용합니다.
<ide>
<ide> ### scryRenderedDOMComponentsWithClass
<ide>
<ide> shallowRenderer.render(ReactElement element)
<ide> ReactComponent shallowRenderer.getRenderOutput()
<ide> ```
<ide>
<del>렌더가 호출 된 후, 얕게 렌더된 결과물을 반환합니다. 그 후엔 결과물에 대한 검증을 시작할 수 있습니다. 예를 들어 컴포넌트의 렌더 메소드가 다음을 반환한다면:
<add>`render`가 호출 된 후, 얕게 렌더된 결과물을 반환합니다. 그 후엔 결과물에 대한 검증을 시작할 수 있습니다. 예를 들어 컴포넌트의 렌더 메소드가 다음을 반환한다면:
<ide>
<ide> ```javascript
<ide> <div>
<ide><path>docs/docs/getting-started.ko-KR.md
<ide> React.render(
<ide> <script type="text/jsx" src="src/helloworld.js"></script>
<ide> ```
<ide>
<del>크롬 같은 몇몇 브라우저에서는 HTTP을 통해 제공되는 파일이 아니면 로드에 실패하므로 주의하세요.
<add>크롬 같은 몇몇 브라우저에서는 HTTP를 통해 제공되는 파일이 아니면 로드에 실패하므로 주의하세요.
<ide>
<ide> ### 오프라인 변환
<ide>
<ide><path>docs/docs/tutorial.ko-KR.md
<ide> next: thinking-in-react-ko-KR.html
<ide>
<ide> ### 시작하기
<ide>
<del>이 튜토리얼에서는 CDN에 있는 미리 빌드된 JavaScript 파일들을 사용합니다. 선호하는 에디터를 열어, 새로운 HTML 문서를 만드세요:
<add>이 튜토리얼에서는 CDN에 있는 미리 빌드된 JavaScript 파일들을 사용합니다. 선호하는 에디터에서 `public/index.html`을 열어, 아래의 내용을 채우세요:
<ide>
<ide> ```html
<ide> <!-- index.html -->
<ide><path>docs/docs/videos.ko-KR.md
<ide> next: complementary-tools-ko-KR.html
<ide>
<ide> <iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe>
<ide>
<del>"페이스북과 인스타그램에서, 우리는 React 를 이용해 웹에서 벌어질 수 있는 한계를 뛰어넘으려 노력하고 있습니다. 저는 프레임워크에 대한 짤막한 소개로 시작해서, 논쟁이 벌어질 수 있는 다음의 세가지 주제로 넘어갈겁니다. 템플릿의 개념을 버리고 Javascript 를 이용해 View 를 구축하기, 자료가 변할때 전체 어플리케이션을 다시 그리기(“re-rendering”), 그리고 DOM과 events의 경량화된 구현 입니다." -- [Pete Hunt](http://www.petehunt.net/)
<add>"페이스북과 인스타그램에서, 우리는 React 를 이용해 웹에서 벌어질 수 있는 한계를 뛰어넘으려 노력하고 있습니다. 저는 프레임워크에 대한 짤막한 소개로 시작해서, 논쟁이 벌어질 수 있는 다음의 세가지 주제로 넘어갈겁니다. 템플릿의 개념을 버리고 JavaScript 를 이용해 View 를 구축하기, 자료가 변할때 전체 어플리케이션을 다시 그리기(“re-rendering”), 그리고 DOM과 events의 경량화된 구현 입니다." -- [Pete Hunt](http://www.petehunt.net/)
<ide>
<ide> * * *
<ide>
<ide> next: complementary-tools-ko-KR.html
<ide>
<ide> ### Going big with React
<ide>
<del>"이 발표에서, 이 모든 JS 프레임워크가 다음을 약속하는것처럼 보입니다: 꺠끗한 구현들, 빠른 코드 디자인, 완전한 수행. 그런데 당신이 Javascript 스트레스 테스트를 할때, 어떤 일이 발생합니까? 혹은 6MB의 코드를 던지면 무슨일이 발생합니까? 이번에는 높은 스트레스 환경에서 React가 어떻게 작동하는지, 그리고 이것이 우리 팀이 방대한 크기의 코드를 안전하게 구성하는데 어떻게 도움이 되어줄지를 조사해 볼겁니다."
<add>"이 발표에서, 이 모든 JS 프레임워크가 다음을 약속하는것처럼 보입니다: 깨끗한 구현들, 빠른 코드 디자인, 완전한 수행. 그런데 당신이 JavaScript 스트레스 테스트를 할때, 어떤 일이 발생합니까? 혹은 6MB의 코드를 던지면 무슨일이 발생합니까? 이번에는 높은 스트레스 환경에서 React가 어떻게 작동하는지, 그리고 이것이 우리 팀이 방대한 크기의 코드를 안전하게 구성하는데 어떻게 도움이 되어줄지를 조사해 볼겁니다."
<ide> [](https://skillsmatter.com/skillscasts/5429-going-big-with-react#video)
<ide>
<ide> * * *
<ide> CodeWinds Episode 4 에서 [Pete Hunt](http://www.petehunt.net/)와 [Jeff Barcze
<ide>
<ide> ### JavaScript Jabber
<ide>
<del>Javascript Jabber 73에서 [Pete Hunt](http://www.petehunt.net/)와 [Jordan Walke](https://github.com/jordwalke)가 React에 대해서 이야기했습니다.
<add>JavaScript Jabber 73에서 [Pete Hunt](http://www.petehunt.net/)와 [Jordan Walke](https://github.com/jordwalke)가 React에 대해서 이야기했습니다.
<ide>
<ide> <figure>[](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/#content)</figure>
<ide> | 4 |
Ruby | Ruby | avoid unnecessary matchdata objects | 0c15b85d5d0fada21306ec6da8b2bb0470fefc68 | <ide><path>actionpack/lib/action_dispatch/http/filter_redirect.rb
<ide> def location_filter_match?(filters)
<ide> if String === filter
<ide> location.include?(filter)
<ide> elsif Regexp === filter
<del> location.match(filter)
<add> location =~ filter
<ide> end
<ide> end
<ide> end | 1 |
PHP | PHP | fix plural calculation for icelandic | d9f3e866a19b966e15298de180bc810cb27f862d | <ide><path>src/I18n/PluralRules.php
<ide> class PluralRules {
<ide> 'hr' => 3,
<ide> 'hu' => 1,
<ide> 'id' => 0,
<del> 'is' => 1,
<add> 'is' => 15,
<ide> 'it' => 1,
<ide> 'ja' => 0,
<ide> 'jv' => 0,
<ide> public static function calculate($locale, $n) {
<ide> return $n == 1 ? 0 :
<ide> ($n == 2 ? 1 :
<ide> ($n != 8 && $n != 11 ? 2 : 3));
<add> case 15:
<add> return ($n % 10 != 1 || $n % 100 == 11) ? 1 : 0;
<ide> }
<ide> }
<ide>
<ide><path>tests/TestCase/I18n/PluralRulesTest.php
<ide> public function localesProvider() {
<ide> ['ga', 2, 1],
<ide> ['ga', 7, 3],
<ide> ['ga', 11, 4],
<add> ['is', 1, 0],
<add> ['is', 2, 1],
<add> ['is', 3, 1],
<add> ['is', 11, 1],
<add> ['is', 21, 0],
<ide> ['lt', 0, 2],
<ide> ['lt', 1, 0],
<ide> ['lt', 2, 1], | 2 |
Ruby | Ruby | fix typo in go regex | e69fbaf3575a2a4aec529927b190815eb2fbb64d | <ide><path>Library/Homebrew/dev-cmd/bottle.rb
<ide> def formula_ignores(f)
<ide> end
<ide> if any_go_deps
<ide> go_regex = Version.formula_optionally_versioned_regex(:go, full: false)
<del> ignores << %r{#{cellar_regex}/#{go_regex}/[\d.]+/libexec]}
<add> ignores << %r{#{cellar_regex}/#{go_regex}/[\d.]+/libexec}
<ide> end
<ide>
<ide> ignores << case f.name | 1 |
Python | Python | determine labels by factory name in debug data | a55212fca01f97beaf6f07e8ff3fc6e81a0b7de4 | <ide><path>spacy/cli/debug_data.py
<ide> from ..schemas import ConfigSchemaTraining
<ide> from ..pipeline._parser_internals import nonproj
<ide> from ..pipeline._parser_internals.nonproj import DELIMITER
<del>from ..pipeline import Morphologizer
<add>from ..pipeline import Morphologizer, SpanCategorizer
<ide> from ..morphology import Morphology
<ide> from ..language import Language
<ide> from ..util import registry, resolve_dot_names
<ide> def _get_examples_without_label(data: Sequence[Example], label: str) -> int:
<ide> return count
<ide>
<ide>
<del>def _get_labels_from_model(nlp: Language, pipe_name: str) -> Set[str]:
<del> if pipe_name not in nlp.pipe_names:
<del> return set()
<del> pipe = nlp.get_pipe(pipe_name)
<del> return set(pipe.labels)
<add>def _get_labels_from_model(
<add> nlp: Language, factory_name: str
<add>) -> Set[str]:
<add> pipe_names = [
<add> pipe_name
<add> for pipe_name in nlp.pipe_names
<add> if nlp.get_pipe_meta(pipe_name).factory == factory_name
<add> ]
<add> labels: Set[str] = set()
<add> for pipe_name in pipe_names:
<add> pipe = nlp.get_pipe(pipe_name)
<add> labels.update(pipe.labels)
<add> return labels
<add>
<add>
<add>def _get_labels_from_spancat(
<add> nlp: Language
<add>) -> Dict[str, Set[str]]:
<add> pipe_names = [
<add> pipe_name
<add> for pipe_name in nlp.pipe_names
<add> if nlp.get_pipe_meta(pipe_name).factory == "spancat"
<add> ]
<add> labels: Dict[str, Set[str]] = {}
<add> for pipe_name in pipe_names:
<add> pipe = nlp.get_pipe(pipe_name)
<add> assert isinstance(pipe, SpanCategorizer)
<add> if pipe.key not in labels:
<add> labels[pipe.key] = set()
<add> labels[pipe.key].update(pipe.labels)
<add> return labels
<ide><path>spacy/tests/test_cli.py
<ide> from spacy.cli._util import parse_config_overrides, string_to_list
<ide> from spacy.cli._util import substitute_project_variables
<ide> from spacy.cli._util import validate_project_commands
<add>from spacy.cli.debug_data import _get_labels_from_model
<add>from spacy.cli.debug_data import _get_labels_from_spancat
<ide> from spacy.cli.download import get_compatibility, get_version
<ide> from spacy.cli.init_config import RECOMMENDATIONS, init_config, fill_config
<ide> from spacy.cli.package import get_third_party_dependencies
<ide> def test_factory(nlp, name):
<ide> )
<ide> def test_is_subpath_of(parent, child, expected):
<ide> assert is_subpath_of(parent, child) == expected
<add>
<add>
<add>@pytest.mark.slow
<add>@pytest.mark.parametrize(
<add> "factory_name,pipe_name",
<add> [
<add> ("ner", "ner"),
<add> ("ner", "my_ner"),
<add> ("spancat", "spancat"),
<add> ("spancat", "my_spancat"),
<add> ],
<add>)
<add>def test_get_labels_from_model(factory_name, pipe_name):
<add> labels = ("A", "B")
<add>
<add> nlp = English()
<add> pipe = nlp.add_pipe(factory_name, name=pipe_name)
<add> for label in labels:
<add> pipe.add_label(label)
<add> nlp.initialize()
<add> assert nlp.get_pipe(pipe_name).labels == labels
<add> if factory_name == "spancat":
<add> assert _get_labels_from_spancat(nlp)[pipe.key] == set(labels)
<add> else:
<add> assert _get_labels_from_model(nlp, factory_name) == set(labels) | 2 |
Javascript | Javascript | upgrade chunkmoduleidrangeplugin to es6 | d7b97e86a1589af5f656e3bc3153219c7bd396d3 | <ide><path>lib/optimize/ChunkModuleIdRangePlugin.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>function ChunkModuleIdRangePlugin(options) {
<del> this.options = options;
<del>}
<del>module.exports = ChunkModuleIdRangePlugin;
<del>ChunkModuleIdRangePlugin.prototype.apply = function(compiler) {
<del> var options = this.options;
<del> compiler.plugin("compilation", function(compilation) {
<del> compilation.plugin("module-ids", function(modules) {
<del> var chunk = this.chunks.filter(function(chunk) {
<del> return chunk.name === options.name;
<del> })[0];
<del> if(!chunk) throw new Error("ChunkModuleIdRangePlugin: Chunk with name '" + options.name + "' was not found");
<del> var currentId = options.start;
<del> var chunkModules;
<del> if(options.order) {
<del> chunkModules = chunk.modules.slice();
<del> switch(options.order) {
<del> case "index":
<del> chunkModules.sort(function(a, b) {
<del> return a.index - b.index;
<del> });
<del> break;
<del> case "index2":
<del> chunkModules.sort(function(a, b) {
<del> return a.index2 - b.index2;
<del> });
<del> break;
<del> default:
<del> throw new Error("ChunkModuleIdRangePlugin: unexpected value of order");
<del> }
<add>"use strict"
<add>class ChunkModuleIdRangePlugin {
<add> constructor(options) {
<add> this.options = options;
<add> }
<add> apply(compiler) {
<add> let options = this.options;
<add> compiler.plugin("compilation", (compilation) => {
<add> compilation.plugin("module-ids", (modules) => {
<add> let chunk = this.chunks.filter((chunk) => {
<add> return chunk.name === options.name;
<add> })[0];
<add> if(!chunk) throw new Error("ChunkModuleIdRangePlugin: Chunk with name '" + options.name + "' was not found");
<add> let currentId = options.start;
<add> let chunkModules;
<add> if(options.order) {
<add> chunkModules = chunk.modules.slice();
<add> switch(options.order) {
<add> case "index":
<add> chunkModules.sort((a, b) => {
<add> return a.index - b.index;
<add> });
<add> break;
<add> case "index2":
<add> chunkModules.sort((a, b) => {
<add> return a.index2 - b.index2;
<add> });
<add> break;
<add> default:
<add> throw new Error("ChunkModuleIdRangePlugin: unexpected value of order");
<add> }
<ide>
<del> } else {
<del> chunkModules = modules.filter(function(m) {
<del> return m.chunks.indexOf(chunk) >= 0;
<del> });
<del> }
<del> console.log(chunkModules);
<del> for(var i = 0; i < chunkModules.length; i++) {
<del> var m = chunkModules[i];
<del> if(m.id === null) {
<del> m.id = currentId++;
<add> } else {
<add> chunkModules = modules.filter((m) => {
<add> return m.chunks.indexOf(chunk) >= 0;
<add> });
<ide> }
<del> if(options.end && currentId > options.end)
<del> break;
<del> }
<add> console.log(chunkModules);
<add> for(let i = 0; i < chunkModules.length; i++) {
<add> let m = chunkModules[i];
<add> if(m.id === null) {
<add> m.id = currentId++;
<add> }
<add> if(options.end && currentId > options.end)
<add> break;
<add> }
<add> });
<ide> });
<del> });
<del>};
<add> }
<add>}
<add>module.exports = ChunkModuleIdRangePlugin; | 1 |
Ruby | Ruby | check all our bash code for syntax errors | c016aedaab3a5b10207eb05d6b53199e6fcdb761 | <ide><path>Library/Homebrew/test/test_bash.rb
<ide> require "testing_env"
<ide>
<ide> class BashTests < Homebrew::TestCase
<del> def assert_valid_bash_syntax(files)
<del> output = Utils.popen_read("/bin/bash -n #{files} 2>&1")
<add> def assert_valid_bash_syntax(file)
<add> output = Utils.popen_read("/bin/bash -n #{file} 2>&1")
<ide> assert $?.success?, output
<ide> end
<ide>
<ide> def test_bin_brew
<del> assert_valid_bash_syntax "#{HOMEBREW_LIBRARY_PATH.parent.parent}/bin/brew"
<add> assert_valid_bash_syntax HOMEBREW_LIBRARY_PATH.parent.parent/"bin/brew"
<ide> end
<ide>
<del> def test_bash_cmds
<del> %w[cmd dev-cmd].each do |dir|
<del> Dir["#{HOMEBREW_LIBRARY_PATH}/#{dir}/*.sh"].each do |cmd|
<del> assert_valid_bash_syntax cmd
<del> end
<add> def test_bash_code
<add> Pathname.glob("#{HOMEBREW_LIBRARY_PATH}/**/*.sh").each do |pn|
<add> pn_relative = pn.relative_path_from(HOMEBREW_LIBRARY_PATH)
<add> next if pn_relative.to_s.start_with?("shims/", "test/", "vendor/")
<add> assert_valid_bash_syntax pn
<add> end
<add> end
<add>
<add> def test_bash_completion
<add> script = HOMEBREW_LIBRARY_PATH.parent.parent/"etc/bash_completion.d/brew"
<add> assert_valid_bash_syntax script
<add> end
<add>
<add> def test_bash_shims
<add> # These have no file extension, but can be identified by their shebang.
<add> (HOMEBREW_LIBRARY_PATH/"shims").find do |pn|
<add> next if pn.directory? || pn.symlink?
<add> next unless pn.executable? && pn.read(12) == "#!/bin/bash\n"
<add> assert_valid_bash_syntax pn
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | make map copyable | 857a614babd82f3cbf03fefc0b336a44918f5b0e | <ide><path>packages/ember-metal/lib/map.js
<ide>
<ide> require('ember-metal/array');
<ide> require('ember-metal/utils');
<add>require('ember-metal/core');
<ide>
<ide> /** @private */
<ide> var guidFor = Ember.guidFor,
<ide> indexOf = Ember.ArrayPolyfills.indexOf;
<ide>
<add>var copy = function(obj) {
<add> var output = {};
<add>
<add> for (var prop in obj) {
<add> if (obj.hasOwnProperty(prop)) { output[prop] = obj[prop]; }
<add> }
<add>
<add> return output;
<add>};
<add>
<add>var copyMap = function(original, newObject) {
<add> var keys = original.keys.copy(),
<add> values = copy(original.values);
<add>
<add> newObject.keys = keys;
<add> newObject.values = values;
<add>
<add> return newObject;
<add>};
<add>
<ide> // This class is used internally by Ember.js and Ember Data.
<ide> // Please do not use it at this time. We plan to clean it up
<ide> // and add many tests soon.
<ide> OrderedSet.prototype = {
<ide>
<ide> toArray: function() {
<ide> return this.list.slice();
<add> },
<add>
<add> copy: function() {
<add> var set = new OrderedSet();
<add>
<add> set.presenceSet = copy(this.presenceSet);
<add> set.list = this.list.slice();
<add>
<add> return set;
<ide> }
<ide> };
<ide>
<ide> Map.prototype = {
<ide> var guid = guidFor(key);
<ide> callback.call(self, key, values[guid]);
<ide> });
<add> },
<add>
<add> copy: function() {
<add> return copyMap(this, new Map());
<ide> }
<ide> };
<ide>
<ide> MapWithDefault.prototype.get = function(key) {
<ide> return defaultValue;
<ide> }
<ide> };
<add>
<add>MapWithDefault.prototype.copy = function() {
<add> return copyMap(this, new MapWithDefault({
<add> defaultValue: this.defaultValue
<add> }));
<add>};
<ide><path>packages/ember-metal/tests/map_test.js
<ide> function testMap(variety) {
<ide> }
<ide> });
<ide>
<del> var mapHasLength = function(expected) {
<add> var mapHasLength = function(expected, theMap) {
<add> theMap = theMap || map;
<add>
<ide> var length = 0;
<del> map.forEach(function() {
<add> theMap.forEach(function() {
<ide> length++;
<ide> });
<ide>
<ide> equal(length, expected, "map should contain " + expected + " items");
<ide> };
<ide>
<del> var mapHasEntries = function(entries) {
<add> var mapHasEntries = function(entries, theMap) {
<add> theMap = theMap || map;
<add>
<ide> for (var i = 0, l = entries.length; i < l; i++) {
<del> equal(map.get(entries[i][0]), entries[i][1]);
<del> equal(map.has(entries[i][0]), true);
<add> equal(theMap.get(entries[i][0]), entries[i][1]);
<add> equal(theMap.has(entries[i][0]), true);
<ide> }
<ide>
<del> mapHasLength(entries.length);
<add> mapHasLength(entries.length, theMap);
<ide> };
<ide>
<ide> test("add", function() {
<ide> function testMap(variety) {
<ide>
<ide> mapHasEntries([]);
<ide> });
<add>
<add> test("copy and then update", function() {
<add> map.set(object, "winning");
<add> map.set(number, "winning");
<add> map.set(string, "winning");
<add>
<add> var map2 = map.copy();
<add>
<add> map2.set(object, "losing");
<add> map2.set(number, "losing");
<add> map2.set(string, "losing");
<add>
<add> mapHasEntries([
<add> [ object, "winning" ],
<add> [ number, "winning" ],
<add> [ string, "winning" ]
<add> ]);
<add>
<add> mapHasEntries([
<add> [ object, "losing" ],
<add> [ number, "losing" ],
<add> [ string, "losing" ]
<add> ], map2);
<add> });
<add>
<add> test("copy and then remove", function() {
<add> map.set(object, "winning");
<add> map.set(number, "winning");
<add> map.set(string, "winning");
<add>
<add> var map2 = map.copy();
<add>
<add> map2.remove(object);
<add> map2.remove(number);
<add> map2.remove(string);
<add>
<add> mapHasEntries([
<add> [ object, "winning" ],
<add> [ number, "winning" ],
<add> [ string, "winning" ]
<add> ]);
<add>
<add> mapHasEntries([ ], map2);
<add> });
<ide> }
<ide>
<ide> for (var i = 0; i < varieties.length; i++) {
<ide> test("Retrieving a value that has not been set returns and sets a default value"
<ide>
<ide> strictEqual(value, map.get('ohai'));
<ide> });
<add>
<add>test("Copying a MapWithDefault copies the default value", function() {
<add> var map = Ember.MapWithDefault.create({
<add> defaultValue: function(key) {
<add> return [key];
<add> }
<add> });
<add>
<add> map.set('ohai', 1);
<add> map.get('bai');
<add>
<add> var map2 = map.copy();
<add>
<add> equal(map2.get('ohai'), 1);
<add> deepEqual(map2.get('bai'), ['bai']);
<add>
<add> map2.set('kthx', 3);
<add>
<add> deepEqual(map.get('kthx'), ['kthx']);
<add> equal(map2.get('kthx'), 3);
<add>
<add> deepEqual(map2.get('default'), ['default']);
<add>
<add> map2.defaultValue = function(key) {
<add> return ['tom is on', key];
<add> };
<add>
<add> deepEqual(map2.get('drugs'), ['tom is on', 'drugs']);
<add>}); | 2 |
Go | Go | solve an issue with the -dns in daemon mode | afd325a8845ad7c4846747fb9561df12ebf9963a | <ide><path>docker/docker.go
<ide> func main() {
<ide> bridgeName := flag.String("b", "", "Attach containers to a pre-existing network bridge")
<ide> pidfile := flag.String("p", "/var/run/docker.pid", "File containing process PID")
<ide> flHost := flag.String("H", fmt.Sprintf("%s:%d", host, port), "Host:port to bind/connect to")
<del>
<del> flags := flag.NewFlagSet("docker", flag.ContinueOnError)
<del> var flDns docker.ListOpts
<del> flags.Var(&flDns, "dns", "Set custom dns servers")
<add> flDns := flag.String("dns", "", "Set custom dns servers")
<ide>
<ide> flag.Parse()
<ide> if *bridgeName != "" {
<ide> func main() {
<ide> flag.Usage()
<ide> return
<ide> }
<del> if err := daemon(*pidfile, host, port, *flAutoRestart, flDns); err != nil {
<add> if err := daemon(*pidfile, host, port, *flAutoRestart, *flDns); err != nil {
<ide> log.Fatal(err)
<ide> os.Exit(-1)
<ide> }
<ide> func removePidFile(pidfile string) {
<ide> }
<ide> }
<ide>
<del>func daemon(pidfile, addr string, port int, autoRestart bool, flDns docker.ListOpts) error {
<add>func daemon(pidfile, addr string, port int, autoRestart bool, flDns string) error {
<ide> if addr != "127.0.0.1" {
<ide> log.Println("/!\\ DON'T BIND ON ANOTHER IP ADDRESS THAN 127.0.0.1 IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\")
<ide> }
<ide> func daemon(pidfile, addr string, port int, autoRestart bool, flDns docker.ListO
<ide> removePidFile(pidfile)
<ide> os.Exit(0)
<ide> }()
<del>
<del> server, err := docker.NewServer(autoRestart, flDns)
<add> var dns []string
<add> if flDns != "" {
<add> dns = []string{flDns}
<add> }
<add> server, err := docker.NewServer(autoRestart, dns)
<ide> if err != nil {
<ide> return err
<ide> } | 1 |
PHP | PHP | add note about php's include_path | bc689151a41607d20d5088082e76892469e670f1 | <ide><path>lib/Cake/TestSuite/templates/phpunit.php
<ide> <li><code>pear channel-discover pear.symfony-project.com</code></li>
<ide> <li><code>pear install phpunit/PHPUnit-3.5.15</code></li>
<ide> </ul>
<add> <p>Once PHPUnit is installed make sure its located on PHP's <code>include_path</code> by checking your php.ini</p>
<ide> <p>For full instructions on how to <a href="http://www.phpunit.de/manual/current/en/installation.html">install PHPUnit, see the PHPUnit installation guide</a>.</p>
<ide> <p><a href="http://github.com/sebastianbergmann/phpunit" target="_blank">Download PHPUnit</a></p>
<ide> </div> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.