content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Ruby | Ruby | add comment for in-source style exception | 2599cccc81782e45517dae03ba093f2d74f22f7f | <ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> def refurbish_args
<ide> end
<ide>
<ide> # rubocop: disable Naming/MethodName
<add> # Fixes style error `Naming/MethodName: Use snake_case for method names.`
<ide> sig { params(block: T.nilable(T.proc.void)).void }
<ide> def O0(&block)
<ide> if block | 1 |
Java | Java | update javadoc for mockmvc | 18bf860c273179f95719d80b14d17c0c9ba99c38 | <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvc.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> *
<ide> * WebApplicationContext wac = ...;
<ide> *
<del> * MockMvc mockMvc = webAppContextSetup(wac).configureWarRootDir("src/main/webapp", false).build()
<add> * MockMvc mockMvc = webAppContextSetup(wac).build();
<ide> *
<ide> * mockMvc.perform(get("/form"))
<ide> * .andExpect(status().isOk()) | 1 |
Javascript | Javascript | stop sharing of uniforms() in filmpass | effcd4402a20e60222dabe9e861ddd805ae4dfd5 | <ide><path>examples/js/postprocessing/FilmPass.js
<ide> THREE.FilmPass = function ( noiseIntensity, scanlinesIntensity, scanlinesCount,
<ide>
<ide> } );
<ide>
<del> if ( grayscale !== undefined ) this.uniforms.grayscale.value = grayscale;
<del> if ( noiseIntensity !== undefined ) this.uniforms.nIntensity.value = noiseIntensity;
<del> if ( scanlinesIntensity !== undefined ) this.uniforms.sIntensity.value = scanlinesIntensity;
<del> if ( scanlinesCount !== undefined ) this.uniforms.sCount.value = scanlinesCount;
<add> this.uniforms[ "tDiffuse" ] = new THREE.Uniform();
<add> this.uniforms[ "time" ] = new THREE.Uniform();
<add>
<add> if ( grayscale !== undefined ) this.uniforms.grayscale = new THREE.Uniform( grayscale );
<add> if ( noiseIntensity !== undefined ) this.uniforms.nIntensity = new THREE.Uniform( noiseIntensity );
<add> if ( scanlinesIntensity !== undefined ) this.uniforms.sIntensity = new THREE.Uniform( scanlinesIntensity );
<add> if ( scanlinesCount !== undefined ) this.uniforms.sCount = new THREE.Uniform( scanlinesCount );
<ide>
<ide> this.camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
<ide> this.scene = new THREE.Scene(); | 1 |
Ruby | Ruby | remove trailing whitespace. [ci skip] | 16329d3901190a28fa88571079adf01322bee4fa | <ide><path>activerecord/lib/active_record/persistence.rb
<ide> def reload(options = nil)
<ide> self
<ide> end
<ide>
<del> # Saves the record with the updated_at/on attributes set to the current time
<add> # Saves the record with the updated_at/on attributes set to the current time
<ide> # or the time specified.
<ide> # Please note that no validation is performed and only the +after_touch+,
<ide> # +after_commit+ and +after_rollback+ callbacks are executed. | 1 |
Ruby | Ruby | change migration to loop through formulae | 888a7073bccc476fa5e14ca074c5d7ca0a0be5cf | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def migrate_legacy_cache_if_necessary
<ide> def migrate_cache_entries_to_double_dashes(initial_version)
<ide> return if initial_version > "1.7.1"
<ide>
<del> HOMEBREW_CACHE.children.each do |child|
<del> next unless child.file?
<add> Formula.each do |formula|
<add> specs = [*formula.stable, *formula.devel, *formula.head]
<add>
<add> resources = [*formula.bottle&.resource] + specs.flat_map do |spec|
<add> [
<add> spec,
<add> *spec.resources.values,
<add> *spec.patches.select(&:external?).map(&:resource),
<add> ]
<add> end
<ide>
<del> next unless /^(?<prefix>[^\.]+[^\-])\-(?<suffix>[^\-].*)/ =~ child.basename.to_s
<del> target = HOMEBREW_CACHE/"#{prefix}--#{suffix}"
<add> resources.each do |resource|
<add> downloader = resource.downloader
<ide>
<del> next if suffix.include?("--") && !suffix.start_with?("patch")
<add> name = resource.download_name
<add> version = resource.version
<ide>
<del> if target.exist?
<del> begin
<del> FileUtils.rm_rf child
<del> rescue Errno::EACCES
<del> opoo "Could not remove #{child}, please do so manually."
<del> end
<del> else
<del> begin
<del> FileUtils.mv child, target
<del> rescue Errno::EACCES
<del> opoo "Could not move #{child} to #{target}, please do so manually."
<add> new_location = downloader.cached_location
<add> extname = new_location.extname
<add> old_location = downloader.cached_location.dirname/"#{name}-#{version}#{extname}"
<add>
<add> next unless old_location.file?
<add>
<add> if new_location.exist?
<add> begin
<add> FileUtils.rm_rf old_location
<add> rescue Errno::EACCES
<add> opoo "Could not remove #{old_location}, please do so manually."
<add> end
<add> else
<add> begin
<add> FileUtils.mv old_location, new_location
<add> rescue Errno::EACCES
<add> opoo "Could not move #{old_location} to #{new_location}, please do so manually."
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/software_spec.rb
<ide> class SoftwareSpec
<ide> attr_reader :compiler_failures
<ide>
<ide> def_delegators :@resource, :stage, :fetch, :verify_download_integrity, :source_modified_time
<del> def_delegators :@resource, :cached_download, :clear_cache
<add> def_delegators :@resource, :download_name, :cached_download, :clear_cache
<ide> def_delegators :@resource, :checksum, :mirrors, :specs, :using
<ide> def_delegators :@resource, :version, :mirror, *Checksum::TYPES
<ide> def_delegators :@resource, :downloader
<ide><path>Library/Homebrew/test/cmd/update-report_spec.rb
<ide>
<ide> describe "brew update-report" do
<ide> describe "::migrate_cache_entries_to_double_dashes" do
<del> let(:legacy_cache_file) { HOMEBREW_CACHE/"foo-1.2.3.tar.gz" }
<del> let(:renamed_cache_file) { HOMEBREW_CACHE/"foo--1.2.3.tar.gz" }
<add> let(:formula_name) { "foo" }
<add> let(:f) {
<add> formula formula_name do
<add> url "https://example.com/foo-1.2.3.tar.gz"
<add> version "1.2.3"
<add> end
<add> }
<add> let(:old_cache_file) { HOMEBREW_CACHE/"#{formula_name}-1.2.3.tar.gz" }
<add> let(:new_cache_file) { HOMEBREW_CACHE/"#{formula_name}--1.2.3.tar.gz" }
<ide>
<ide> before(:each) do
<del> FileUtils.touch legacy_cache_file
<add> FileUtils.touch old_cache_file
<add> allow(Formula).to receive(:each).and_yield(f)
<ide> end
<ide>
<ide> it "moves old files to use double dashes when upgrading from <= 1.7.1" do
<ide> Homebrew.migrate_cache_entries_to_double_dashes(Version.new("1.7.1"))
<ide>
<del> expect(legacy_cache_file).not_to exist
<del> expect(renamed_cache_file).to exist
<add> expect(old_cache_file).not_to exist
<add> expect(new_cache_file).to exist
<ide> end
<ide>
<ide> context "when the formula name contains dashes" do
<del> let(:legacy_cache_file) { HOMEBREW_CACHE/"foo-bar-1.2.3.tar.gz" }
<del> let(:renamed_cache_file) { HOMEBREW_CACHE/"foo-bar--1.2.3.tar.gz" }
<del>
<del> it "does not introduce extra double dashes when called multiple times" do
<del> Homebrew.migrate_cache_entries_to_double_dashes(Version.new("1.7.1"))
<del> Homebrew.migrate_cache_entries_to_double_dashes(Version.new("1.7.1"))
<del>
<del> expect(legacy_cache_file).not_to exist
<del> expect(renamed_cache_file).to exist
<del> end
<del> end
<del>
<del> context "when the file is a patch and the formula name contains dashes" do
<del> let(:legacy_cache_file) { HOMEBREW_CACHE/"foo-bar-patch--1.2.3.tar.gz" }
<del> let(:renamed_cache_file) { HOMEBREW_CACHE/"foo-bar--patch--1.2.3.tar.gz" }
<add> let(:formula_name) { "foo-bar" }
<ide>
<ide> it "does not introduce extra double dashes when called multiple times" do
<ide> Homebrew.migrate_cache_entries_to_double_dashes(Version.new("1.7.1"))
<ide> Homebrew.migrate_cache_entries_to_double_dashes(Version.new("1.7.1"))
<ide>
<del> expect(legacy_cache_file).not_to exist
<del> expect(renamed_cache_file).to exist
<add> expect(old_cache_file).not_to exist
<add> expect(new_cache_file).to exist
<ide> end
<ide> end
<ide>
<ide> it "does not move files if upgrading from > 1.7.1" do
<ide> Homebrew.migrate_cache_entries_to_double_dashes(Version.new("1.7.2"))
<ide>
<del> expect(legacy_cache_file).to exist
<del> expect(renamed_cache_file).not_to exist
<add> expect(old_cache_file).to exist
<add> expect(new_cache_file).not_to exist
<ide> end
<ide> end
<ide> end | 3 |
Mixed | Javascript | handle uncaughtexception properly | 422e8f762873aef4a37185f3237c0d666c929d8e | <ide><path>doc/api/errors.md
<ide> An invalid `options.protocol` was passed to `http.request()`.
<ide> <a id="ERR_INVALID_REPL_EVAL_CONFIG"></a>
<ide> ### ERR_INVALID_REPL_EVAL_CONFIG
<ide>
<del>Both `breakEvalOnSigint` and `eval` options were set in the REPL config, which
<del>is not supported.
<add>Both `breakEvalOnSigint` and `eval` options were set in the [`REPL`][] config,
<add>which is not supported.
<add>
<add><a id="ERR_INVALID_REPL_INPUT"></a>
<add>### ERR_INVALID_REPL_INPUT
<add>
<add>The input may not be used in the [`REPL`][]. All prohibited inputs are
<add>documented in the [`REPL`][]'s documentation.
<ide>
<ide> <a id="ERR_INVALID_RETURN_PROPERTY"></a>
<ide> ### ERR_INVALID_RETURN_PROPERTY
<ide> such as `process.stdout.on('data')`.
<ide> [`Class: assert.AssertionError`]: assert.html#assert_class_assert_assertionerror
<ide> [`ERR_INVALID_ARG_TYPE`]: #ERR_INVALID_ARG_TYPE
<ide> [`EventEmitter`]: events.html#events_class_eventemitter
<add>[`REPL`]: repl.html
<ide> [`Writable`]: stream.html#stream_class_stream_writable
<ide> [`child_process`]: child_process.html
<ide> [`cipher.getAuthTag()`]: crypto.html#crypto_cipher_getauthtag
<ide><path>doc/api/repl.md
<ide> global or scoped variable, the input `fs` will be evaluated on-demand as
<ide> ```
<ide>
<ide> #### Global Uncaught Exceptions
<add><!-- YAML
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/27151
<add> description: The `'uncaughtException'` event is from now on triggered if the
<add> repl is used as standalone program.
<add>-->
<ide>
<ide> The REPL uses the [`domain`][] module to catch all uncaught exceptions for that
<ide> REPL session.
<ide>
<ide> This use of the [`domain`][] module in the REPL has these side effects:
<ide>
<del>* Uncaught exceptions do not emit the [`'uncaughtException'`][] event.
<add>* Uncaught exceptions only emit the [`'uncaughtException'`][] event if the
<add> `repl` is used as standalone program. If the `repl` is included anywhere in
<add> another application, adding a listener for this event will throw an
<add> [`ERR_INVALID_REPL_INPUT`][] exception.
<ide> * Trying to use [`process.setUncaughtExceptionCaptureCallback()`][] throws
<ide> an [`ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`][] error.
<ide>
<add>As standalone program:
<add>
<add>```js
<add>process.on('uncaughtException', () => console.log('Uncaught'));
<add>
<add>throw new Error('foobar');
<add>// Uncaught
<add>```
<add>
<add>When used in another application:
<add>
<add>```js
<add>process.on('uncaughtException', () => console.log('Uncaught'));
<add>// TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`
<add>// cannot be used in the REPL
<add>
<add>throw new Error('foobar');
<add>// Thrown:
<add>// Error: foobar
<add>```
<add>
<ide> #### Assignment of the `_` (underscore) variable
<ide> <!-- YAML
<ide> changes:
<ide> For an example of running a REPL instance over [curl(1)][], see:
<ide> [`'uncaughtException'`]: process.html#process_event_uncaughtexception
<ide> [`--experimental-repl-await`]: cli.html#cli_experimental_repl_await
<ide> [`ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`]: errors.html#errors_err_domain_cannot_set_uncaught_exception_capture
<add>[`ERR_INVALID_REPL_INPUT`]: errors.html#errors_err_invalid_repl_input
<ide> [`domain`]: domain.html
<ide> [`process.setUncaughtExceptionCaptureCallback()`]: process.html#process_process_setuncaughtexceptioncapturecallback_fn
<ide> [`readline.InterfaceCompleter`]: readline.html#readline_use_of_the_completer_function
<ide><path>lib/internal/errors.js
<ide> E('ERR_INVALID_PROTOCOL',
<ide> TypeError);
<ide> E('ERR_INVALID_REPL_EVAL_CONFIG',
<ide> 'Cannot specify both "breakEvalOnSigint" and "eval" for REPL', TypeError);
<add>E('ERR_INVALID_REPL_INPUT', '%s', TypeError);
<ide> E('ERR_INVALID_RETURN_PROPERTY', (input, name, prop, value) => {
<ide> return `Expected a valid ${input} to be returned for the "${prop}" from the` +
<ide> ` "${name}" function but got ${value}.`;
<ide><path>lib/repl.js
<ide> const {
<ide> ERR_CANNOT_WATCH_SIGINT,
<ide> ERR_INVALID_ARG_TYPE,
<ide> ERR_INVALID_REPL_EVAL_CONFIG,
<add> ERR_INVALID_REPL_INPUT,
<ide> ERR_SCRIPT_EXECUTION_INTERRUPTED
<ide> } = require('internal/errors').codes;
<ide> const { sendInspectorCommand } = require('internal/util/inspector');
<ide> let processTopLevelAwait;
<ide>
<ide> const parentModule = module;
<ide> const replMap = new WeakMap();
<add>const domainSet = new WeakSet();
<ide>
<ide> const kBufferedCommandSymbol = Symbol('bufferedCommand');
<ide> const kContextId = Symbol('contextId');
<ide>
<add>let addedNewListener = false;
<add>
<ide> try {
<ide> // Hack for require.resolve("./relative") to work properly.
<ide> module.filename = path.resolve('repl');
<ide> function REPLServer(prompt,
<ide> throw new ERR_INVALID_REPL_EVAL_CONFIG();
<ide> }
<ide>
<add> // Add this listener only once and use a WeakSet that contains the REPLs
<add> // domains. Otherwise we'd have to add a single listener to each REPL instance
<add> // and that could trigger the `MaxListenersExceededWarning`.
<add> if (!options[kStandaloneREPL] && !addedNewListener) {
<add> process.prependListener('newListener', (event, listener) => {
<add> if (event === 'uncaughtException' &&
<add> process.domain &&
<add> listener.name !== 'domainUncaughtExceptionClear' &&
<add> domainSet.has(process.domain)) {
<add> // Throw an error so that the event will not be added and the current
<add> // domain takes over. That way the user is notified about the error
<add> // and the current code evaluation is stopped, just as any other code
<add> // that contains an error.
<add> throw new ERR_INVALID_REPL_INPUT(
<add> 'Listeners for `uncaughtException` cannot be used in the REPL');
<add> }
<add> });
<add> addedNewListener = true;
<add> }
<add>
<add> domainSet.add(this._domain);
<add>
<ide> let rli = this;
<ide> Object.defineProperty(this, 'rli', {
<ide> get: deprecate(() => rli,
<ide> function REPLServer(prompt,
<ide> // statement rather than an object literal. So, we first try
<ide> // to wrap it in parentheses, so that it will be interpreted as
<ide> // an expression. Note that if the above condition changes,
<del> // lib/internal/repl/recoverable.js needs to be changed to match.
<add> // lib/internal/repl/utils.js needs to be changed to match.
<ide> code = `(${code.trim()})\n`;
<ide> wrappedCmd = true;
<ide> }
<ide> function REPLServer(prompt,
<ide> }
<ide> }
<ide>
<del> if (errStack === '') {
<del> errStack = `Thrown: ${self.writer(e)}\n`;
<del> } else {
<del> const ln = errStack.endsWith('\n') ? '' : '\n';
<del> errStack = `Thrown:\n${errStack}${ln}`;
<del> }
<del>
<ide> if (!self.underscoreErrAssigned) {
<ide> self.lastError = e;
<ide> }
<ide>
<ide> const top = replMap.get(self);
<del> top.outputStream.write(errStack);
<del> top.clearBufferedCommand();
<del> top.lines.level = [];
<del> top.displayPrompt();
<add> if (options[kStandaloneREPL] &&
<add> process.listenerCount('uncaughtException') !== 0) {
<add> process.nextTick(() => {
<add> process.emit('uncaughtException', e);
<add> top.clearBufferedCommand();
<add> top.lines.level = [];
<add> top.displayPrompt();
<add> });
<add> } else {
<add> if (errStack === '') {
<add> errStack = `Thrown: ${self.writer(e)}\n`;
<add> } else {
<add> const ln = errStack.endsWith('\n') ? '' : '\n';
<add> errStack = `Thrown:\n${errStack}${ln}`;
<add> }
<add> top.outputStream.write(errStack);
<add> top.clearBufferedCommand();
<add> top.lines.level = [];
<add> top.displayPrompt();
<add> }
<ide> });
<ide>
<ide> self.resetContext();
<ide><path>test/parallel/test-repl-pretty-custom-stack.js
<ide> process.on('uncaughtException', (e) => {
<ide> throw e;
<ide> });
<ide>
<del>process.on('exit', () => (Error.prepareStackTrace = origPrepareStackTrace));
<del>
<ide> const tests = [
<ide> {
<ide> // test .load for a file that throws
<ide><path>test/parallel/test-repl-uncaught-exception-async.js
<add>'use strict';
<add>
<add>// This verifies that adding an `uncaughtException` listener in an REPL instance
<add>// does not suppress errors in the whole application. Adding such listener
<add>// should throw.
<add>
<add>require('../common');
<add>const ArrayStream = require('../common/arraystream');
<add>const repl = require('repl');
<add>const assert = require('assert');
<add>
<add>let accum = '';
<add>
<add>const output = new ArrayStream();
<add>output.write = (data) => accum += data.replace('\r', '');
<add>
<add>const r = repl.start({
<add> prompt: '',
<add> input: new ArrayStream(),
<add> output,
<add> terminal: false,
<add> useColors: false,
<add> global: false
<add>});
<add>
<add>r.write(
<add> 'process.nextTick(() => {\n' +
<add> ' process.on("uncaughtException", () => console.log("Foo"));\n' +
<add> ' throw new TypeError("foobar");\n' +
<add> '});\n'
<add>);
<add>r.write(
<add> 'setTimeout(() => {\n' +
<add> ' throw new RangeError("abc");\n' +
<add> '}, 1);console.log()\n'
<add>);
<add>r.close();
<add>
<add>setTimeout(() => {
<add> const len = process.listenerCount('uncaughtException');
<add> process.removeAllListeners('uncaughtException');
<add> assert.strictEqual(len, 0);
<add> assert(/ERR_INVALID_REPL_INPUT.*(?!Type)RangeError: abc/s.test(accum));
<add>}, 2);
<ide><path>test/parallel/test-repl-uncaught-exception-standalone.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const cp = require('child_process');
<add>const child = cp.spawn(process.execPath, ['-i']);
<add>let output = '';
<add>
<add>child.stdout.setEncoding('utf8');
<add>child.stdout.on('data', (data) => {
<add> output += data;
<add>});
<add>
<add>child.on('exit', common.mustCall(() => {
<add> const results = output.split('\n');
<add> results.shift();
<add> assert.deepStrictEqual(
<add> results,
<add> [
<add> 'Type ".help" for more information.',
<add> // x\n
<add> '> Thrown:',
<add> 'ReferenceError: x is not defined',
<add> // Added `uncaughtException` listener.
<add> '> short',
<add> 'undefined',
<add> // x\n
<add> '> Foobar',
<add> '> '
<add> ]
<add> );
<add>}));
<add>
<add>child.stdin.write('x\n');
<add>child.stdin.write(
<add> 'process.on("uncaughtException", () => console.log("Foobar"));' +
<add> 'console.log("short")\n');
<add>child.stdin.write('x\n');
<add>child.stdin.end();
<ide><path>test/parallel/test-repl-uncaught-exception.js
<add>'use strict';
<add>require('../common');
<add>const ArrayStream = require('../common/arraystream');
<add>const assert = require('assert');
<add>const repl = require('repl');
<add>
<add>let count = 0;
<add>
<add>function run({ command, expected }) {
<add> let accum = '';
<add>
<add> const output = new ArrayStream();
<add> output.write = (data) => accum += data.replace('\r', '');
<add>
<add> const r = repl.start({
<add> prompt: '',
<add> input: new ArrayStream(),
<add> output,
<add> terminal: false,
<add> useColors: false
<add> });
<add>
<add> r.write(`${command}\n`);
<add> if (typeof expected === 'string') {
<add> assert.strictEqual(accum, expected);
<add> } else {
<add> assert(expected.test(accum), accum);
<add> }
<add>
<add> // Verify that the repl is still working as expected.
<add> accum = '';
<add> r.write('1 + 1\n');
<add> assert.strictEqual(accum, '2\n');
<add> r.close();
<add> count++;
<add>}
<add>
<add>const tests = [
<add> {
<add> command: 'x',
<add> expected: 'Thrown:\n' +
<add> 'ReferenceError: x is not defined\n'
<add> },
<add> {
<add> command: 'process.on("uncaughtException", () => console.log("Foobar"));\n',
<add> expected: /^Thrown:\nTypeError \[ERR_INVALID_REPL_INPUT]: Listeners for `/
<add> },
<add> {
<add> command: 'x;\n',
<add> expected: 'Thrown:\n' +
<add> 'ReferenceError: x is not defined\n'
<add> },
<add> {
<add> command: 'process.on("uncaughtException", () => console.log("Foobar"));' +
<add> 'console.log("Baz");\n',
<add> expected: /^Thrown:\nTypeError \[ERR_INVALID_REPL_INPUT]: Listeners for `/
<add> },
<add> {
<add> command: 'console.log("Baz");' +
<add> 'process.on("uncaughtException", () => console.log("Foobar"));\n',
<add> expected: /^Baz\nThrown:\nTypeError \[ERR_INVALID_REPL_INPUT]:.*uncaughtException/
<add> }
<add>];
<add>
<add>process.on('exit', () => {
<add> // To actually verify that the test passed we have to make sure no
<add> // `uncaughtException` listeners exist anymore.
<add> process.removeAllListeners('uncaughtException');
<add> assert.strictEqual(count, tests.length);
<add>});
<add>
<add>tests.forEach(run); | 8 |
Go | Go | fix default gw logic for internal networks | ff2200b3972d58d66d5377130225c09f35a9b2d0 | <ide><path>libnetwork/sandbox.go
<ide> func (eh epHeap) Less(i, j int) bool {
<ide> return true
<ide> }
<ide>
<add> if epi.getNetwork().Internal() {
<add> return false
<add> }
<add>
<add> if epj.getNetwork().Internal() {
<add> return true
<add> }
<add>
<ide> if ci != nil {
<ide> cip, ok = ci.epPriority[eh[i].ID()]
<ide> if !ok { | 1 |
Javascript | Javascript | copy file.icns on os x | 7914409a489f84594f37fcf5c6a1763ef39a6375 | <ide><path>build/lib/package-application.js
<ide> module.exports = function () {
<ide> throw new Error('TODO: handle this case!')
<ide> }
<ide>
<del> copyShellCommands(bundledResourcesPath)
<add> copyNonASARResources(bundledResourcesPath)
<ide> console.log(`Application bundle(s) created on ${packagedAppPath}`)
<ide> })
<ide> }
<ide>
<del>function copyShellCommands (bundledResourcesPath) {
<add>function copyNonASARResources (bundledResourcesPath) {
<ide> const bundledShellCommandsPath = path.join(bundledResourcesPath, 'app')
<ide> console.log(`Copying shell commands to ${bundledShellCommandsPath}...`);
<ide> fs.copySync(
<ide> function copyShellCommands (bundledResourcesPath) {
<ide> fs.symlinkSync(path.join('..', '..', 'bin', 'apm'), path.join(bundledShellCommandsPath, 'apm', 'node_modules', '.bin', 'apm'))
<ide> fs.copySync(path.join(CONFIG.repositoryRootPath, 'atom.sh'), path.join(bundledShellCommandsPath, 'atom.sh'))
<ide> }
<add> if (process.platform === 'darwin') {
<add> fs.copySync(path.join(CONFIG.repositoryRootPath, 'resources', 'mac', 'file.icns'), path.join(bundledResourcesPath, 'file.icns'))
<add> }
<ide> }
<ide>
<ide> function buildAsarUnpackGlobExpression () { | 1 |
Go | Go | add extension() method to compresison type | 54db18625aa7154c9dd230907444676fa3079b99 | <ide><path>api.go
<ide> import (
<ide> "io"
<ide> "log"
<ide> "net/http"
<del> "os"
<ide> "strconv"
<ide> "strings"
<ide> )
<ide><path>archive.go
<ide> package docker
<ide>
<ide> import (
<ide> "errors"
<add> "fmt"
<ide> "io"
<ide> "io/ioutil"
<ide> "os"
<ide> func (compression *Compression) Flag() string {
<ide> return ""
<ide> }
<ide>
<add>func (compression *Compression) Extension() string {
<add> switch *compression {
<add> case Uncompressed:
<add> return "tar"
<add> case Bzip2:
<add> return "tar.bz2"
<add> case Gzip:
<add> return "tar.gz"
<add> case Xz:
<add> return "tar.xz"
<add> }
<add> return ""
<add>}
<add>
<ide> func Tar(path string, compression Compression) (io.Reader, error) {
<ide> cmd := exec.Command("bsdtar", "-f", "-", "-C", path, "-c"+compression.Flag(), ".")
<ide> return CmdStream(cmd)
<ide> func Untar(archive io.Reader, path string) error {
<ide> cmd.Stdin = archive
<ide> output, err := cmd.CombinedOutput()
<ide> if err != nil {
<del> return errors.New(err.Error() + ": " + string(output))
<add> return fmt.Errorf("%s: %s", err, output)
<ide> }
<ide> return nil
<ide> }
<ide><path>buildfile.go
<ide> import (
<ide> "fmt"
<ide> "github.com/dotcloud/docker/utils"
<ide> "io"
<add> "io/ioutil"
<ide> "os"
<add> "path"
<ide> "reflect"
<ide> "strings"
<ide> ) | 3 |
Text | Text | improve grammar for the 1st paragraph | 510e6519cbf91bc8b0bb1bff67b9f7378170321c | <ide><path>curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements.spanish.md
<ide> localeTitle: Introduciendo Else If Sentencias
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Si tiene múltiples condiciones que deben abordarse, puede encadenar <code>if</code> sentencias junto con <code>else if</code> sent. <blockquote> if (num> 15) { <br> devuelve "Más grande que 15"; <br> } else if (num <5) { <br> devuelve "Menor de 5"; <br> } else { <br> volver "Entre 5 y 15"; <br> } </blockquote></section>
<add><section id="description"> Si tienes múltiples condiciones que deben abordarse, puedes encadenarlas usando una sentencia <code>if</code> junto con otra sentencia <code>else if</code>. <blockquote> if (num> 15) { <br> devuelve "Más grande que 15"; <br> } else if (num <5) { <br> devuelve "Menor de 5"; <br> } else { <br> volver "Entre 5 y 15"; <br> } </blockquote></section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> Convierte la lógica para usar <code>else if</code> . </section> | 1 |
Python | Python | add means to duplicate connections from ui | 2011da25a50edfcdf7657ec172f57ae6e43ca216 | <ide><path>airflow/www/views.py
<ide> import json
<ide> import logging
<ide> import math
<add>import re
<ide> import socket
<ide> import sys
<ide> import traceback
<ide> from pygments import highlight, lexers
<ide> from pygments.formatters import HtmlFormatter # noqa pylint: disable=no-name-in-module
<ide> from sqlalchemy import Date, and_, desc, func, or_, union_all
<add>from sqlalchemy.exc import IntegrityError
<ide> from sqlalchemy.orm import joinedload
<ide> from wtforms import SelectField, validators
<ide> from wtforms.validators import InputRequired
<ide> class ConnectionModelView(AirflowModelView):
<ide> 'edit': 'edit',
<ide> 'delete': 'delete',
<ide> 'action_muldelete': 'delete',
<add> 'action_mulduplicate': 'create',
<ide> }
<ide>
<ide> base_permissions = [
<ide> def action_muldelete(self, items):
<ide> self.update_redirect()
<ide> return redirect(self.get_redirect())
<ide>
<add> @action(
<add> 'mulduplicate',
<add> 'Duplicate',
<add> 'Are you sure you want to duplicate the selected connections?',
<add> single=False,
<add> )
<add> @provide_session
<add> @auth.has_access(
<add> [
<add> (permissions.ACTION_CAN_CREATE, permissions.RESOURCE_CONNECTION),
<add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_CONNECTION),
<add> ]
<add> )
<add> def action_mulduplicate(self, connections, session=None):
<add> """Duplicate Multiple connections"""
<add> for selected_conn in connections:
<add> new_conn_id = selected_conn.conn_id
<add> match = re.search(r"_copy(\d+)$", selected_conn.conn_id)
<add> if match:
<add> conn_id_prefix = selected_conn.conn_id[: match.start()]
<add> new_conn_id = f"{conn_id_prefix}_copy{int(match.group(1)) + 1}"
<add> else:
<add> new_conn_id += '_copy1'
<add>
<add> dup_conn = Connection(
<add> new_conn_id,
<add> selected_conn.conn_type,
<add> selected_conn.description,
<add> selected_conn.host,
<add> selected_conn.login,
<add> selected_conn.password,
<add> selected_conn.schema,
<add> selected_conn.port,
<add> selected_conn.extra,
<add> )
<add>
<add> try:
<add> session.add(dup_conn)
<add> session.commit()
<add> flash(f"Connection {new_conn_id} added successfully.", "success")
<add> except IntegrityError:
<add> flash(
<add> f"Connection {new_conn_id} can't be added. Integrity error, probably unique constraint.",
<add> "warning",
<add> )
<add> session.rollback()
<add>
<add> self.update_redirect()
<add> return redirect(self.get_redirect())
<add>
<ide> def process_form(self, form, is_created):
<ide> """Process form data."""
<ide> conn_type = form.data['conn_type']
<ide><path>tests/www/views/test_views_connection.py
<ide> def test_prefill_form_null_extra():
<ide>
<ide> cmv = ConnectionModelView()
<ide> cmv.prefill_form(form=mock_form, pk=1)
<add>
<add>
<add>def test_duplicate_connection(admin_client):
<add> """Test Duplicate multiple connection with suffix"""
<add> conn1 = Connection(
<add> conn_id='test_duplicate_gcp_connection',
<add> conn_type='Google Cloud',
<add> description='Google Cloud Connection',
<add> )
<add> conn2 = Connection(
<add> conn_id='test_duplicate_mysql_connection',
<add> conn_type='FTP',
<add> description='MongoDB2',
<add> host='localhost',
<add> schema='airflow',
<add> port=3306,
<add> )
<add> conn3 = Connection(
<add> conn_id='test_duplicate_postgres_connection_copy1',
<add> conn_type='FTP',
<add> description='Postgres',
<add> host='localhost',
<add> schema='airflow',
<add> port=3306,
<add> )
<add> with create_session() as session:
<add> session.query(Connection).delete()
<add> session.add_all([conn1, conn2, conn3])
<add> session.commit()
<add>
<add> data = {"action": "mulduplicate", "rowid": [conn1.id, conn3.id]}
<add> resp = admin_client.post('/connection/action_post', data=data, follow_redirects=True)
<add> expected_result = {
<add> 'test_duplicate_gcp_connection',
<add> 'test_duplicate_gcp_connection_copy1',
<add> 'test_duplicate_mysql_connection',
<add> 'test_duplicate_postgres_connection_copy1',
<add> 'test_duplicate_postgres_connection_copy2',
<add> }
<add> response = {conn[0] for conn in session.query(Connection.conn_id).all()}
<add> assert resp.status_code == 200
<add> assert expected_result == response | 2 |
Text | Text | fix wrong hash syntax | 1371b24cce71cb8e5a2c9f7cf82f5448188249f6 | <ide><path>guides/source/form_helpers.md
<ide> end
<ide> The corresponding view `app/views/articles/new.html.erb` using `form_for` looks like this:
<ide>
<ide> ```erb
<del><%= form_for @article, url: {action: "create"}, html => {class: "nifty_form"} do |f| %>
<add><%= form_for @article, url: {action: "create"}, html: {class: "nifty_form"} do |f| %>
<ide> <%= f.text_field :title %>
<ide> <%= f.text_area :body, size: "60x12" %>
<ide> <%= f.submit "Create" %> | 1 |
Javascript | Javascript | avoid webpack build dependencies in test | 6bb2808fc0d4067ad85f6dac4861d79e29fd8ae1 | <ide><path>test/TestCasesCachePack.test.js
<ide> describe("TestCases", () => {
<ide> describeCases({
<ide> name: "cache pack",
<ide> cache: {
<del> type: "filesystem"
<add> type: "filesystem",
<add> buildDependencies: {
<add> defaultWebpack: []
<add> }
<ide> },
<ide> snapshot: {
<ide> managedPaths: [path.resolve(__dirname, "../node_modules")] | 1 |
Javascript | Javascript | fix issues with test cleanup | 632ecdb07826f16cb1e7cf7a5afecc9d6ae71414 | <ide><path>packages/ember-runtime/tests/ext/rsvp_test.js
<ide> import { setOnerror, getOnerror } from 'ember-metal/error_handler';
<ide> import run from 'ember-metal/run_loop';
<ide> import RSVP from 'ember-runtime/ext/rsvp';
<ide>
<del>QUnit.module('Ember.RSVP');
<add>const ORIGINAL_ONERROR = getOnerror();
<add>
<add>QUnit.module('Ember.RSVP', {
<add> teardown() {
<add> setOnerror(ORIGINAL_ONERROR);
<add> }
<add>});
<ide>
<ide> QUnit.test('Ensure that errors thrown from within a promise are sent to the console', function() {
<ide> let error = new Error('Error thrown in a promise for testing purposes.');
<ide><path>packages/ember-runtime/tests/mixins/promise_proxy_test.js
<ide> QUnit.test('present on ember namespace', function() {
<ide> QUnit.module('Ember.PromiseProxy - ObjectProxy', {
<ide> setup() {
<ide> ObjectPromiseProxy = ObjectProxy.extend(PromiseProxyMixin);
<add> },
<add>
<add> teardown() {
<add> RSVP.on('error', onerrorDefault);
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-runtime/tests/system/lazy_load_test.js
<ide> import run from 'ember-metal/run_loop';
<del>import {onLoad, runLoadHooks} from 'ember-runtime/system/lazy_load';
<add>import {onLoad, runLoadHooks, _loaded } from 'ember-runtime/system/lazy_load';
<ide>
<del>QUnit.module('Lazy Loading');
<add>QUnit.module('Lazy Loading', {
<add> teardown() {
<add> let keys = Object.keys(_loaded);
<add> for (let i = 0; i < keys.length; i++) {
<add> delete _loaded[keys[i]];
<add> }
<add> }
<add>});
<ide>
<ide> QUnit.test('if a load hook is registered, it is executed when runLoadHooks are exected', function() {
<ide> let count = 0;
<ide><path>packages/ember-testing/tests/acceptance_test.js
<ide> QUnit.module('ember-testing Acceptance', {
<ide> setup() {
<ide> jQuery('<style>#ember-testing-container { position: absolute; background: white; bottom: 0; right: 0; width: 640px; height: 384px; overflow: auto; z-index: 9999; border: 1px solid #ccc; } #ember-testing { zoom: 50%; }</style>').appendTo('head');
<ide> jQuery('<div id="ember-testing-container"><div id="ember-testing"></div></div>').appendTo('body');
<add>
<add> originalAdapter = Test.adapter;
<add>
<ide> run(function() {
<ide> indexHitCount = 0;
<ide>
<ide> QUnit.module('ember-testing Acceptance', {
<ide> visit = window.visit;
<ide> andThen = window.andThen;
<ide> currentURL = window.currentURL;
<del>
<del> originalAdapter = Test.adapter;
<ide> },
<ide>
<ide> teardown() {
<ide><path>packages/ember-testing/tests/helpers_test.js
<ide> QUnit.module('can override built-in helpers', {
<ide> },
<ide>
<ide> teardown() {
<del> App.removeTestHelpers();
<del> jQuery('#ember-testing-container, #ember-testing').remove();
<del> run(App, App.destroy);
<del> App = null;
<add> cleanup();
<ide>
<ide> Test._helpers.visit = originalVisitHelper;
<ide> Test._helpers.find = originalFindHelper; | 5 |
Python | Python | fix typo in documentation | a2d2e4d6b5e2bd7257232c2156b78240452e9991 | <ide><path>sorts/bogosort.py
<ide> import random
<ide>
<ide> def bogosort(collection):
<del> """Pure implementation of quick sort algorithm in Python
<add> """Pure implementation of bogosort algorithm in Python
<ide> :param collection: some mutable ordered collection with heterogeneous
<ide> comparable items inside
<ide> :return: the same collection ordered by ascending | 1 |
Ruby | Ruby | add test for `macos.languages` | 929c594f41437f3a0a6d13fed2d596a0ba60435b | <ide><path>Library/Homebrew/test/test_os_mac_language.rb
<ide> require "os/mac"
<ide>
<ide> class OSMacLanguageTests < Homebrew::TestCase
<add> LANGUAGE_REGEX = /\A[a-z]{2}(-[A-Z]{2})?(-[A-Z][a-z]{3})?\Z/
<add>
<add> def test_languages_format
<add> OS::Mac.languages.each do |language|
<add> assert_match LANGUAGE_REGEX, language
<add> end
<add> end
<add>
<ide> def test_language_format
<del> assert_match(/\A[a-z]{2}(-[A-Z]{2})?\Z/, OS::Mac.language)
<add> assert_match LANGUAGE_REGEX, OS::Mac.language
<ide> end
<ide> end | 1 |
Go | Go | provide a struct to configure cli streaming | d9639409fd54ee6955793474fa9a5bac1e583c77 | <ide><path>api/client/build.go
<ide> func (cli *DockerCli) CmdBuild(args ...string) error {
<ide> if context != nil {
<ide> headers.Set("Content-Type", "application/tar")
<ide> }
<del> err = cli.stream("POST", fmt.Sprintf("/build?%s", v.Encode()), body, cli.out, headers)
<add> sopts := &streamOpts{
<add> rawTerminal: true,
<add> in: body,
<add> out: cli.out,
<add> headers: headers,
<add> }
<add> err = cli.stream("POST", fmt.Sprintf("/build?%s", v.Encode()), sopts)
<ide> if jerr, ok := err.(*jsonmessage.JSONError); ok {
<ide> // If no error code is set, default to 1
<ide> if jerr.Code == 0 {
<ide><path>api/client/create.go
<ide> func (cli *DockerCli) pullImageCustomOut(image string, out io.Writer) error {
<ide> registryAuthHeader := []string{
<ide> base64.URLEncoding.EncodeToString(buf),
<ide> }
<del> if err = cli.stream("POST", "/images/create?"+v.Encode(), nil, out, map[string][]string{"X-Registry-Auth": registryAuthHeader}); err != nil {
<add> sopts := &streamOpts{
<add> rawTerminal: true,
<add> out: out,
<add> headers: map[string][]string{"X-Registry-Auth": registryAuthHeader},
<add> }
<add> if err := cli.stream("POST", "/images/create?"+v.Encode(), sopts); err != nil {
<ide> return err
<ide> }
<ide> return nil
<ide><path>api/client/events.go
<ide> func (cli *DockerCli) CmdEvents(args ...string) error {
<ide> }
<ide> v.Set("filters", filterJSON)
<ide> }
<del> if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
<add> sopts := &streamOpts{
<add> rawTerminal: true,
<add> out: cli.out,
<add> }
<add> if err := cli.stream("GET", "/events?"+v.Encode(), sopts); err != nil {
<ide> return err
<ide> }
<ide> return nil
<ide><path>api/client/export.go
<ide> func (cli *DockerCli) CmdExport(args ...string) error {
<ide> }
<ide>
<ide> image := cmd.Arg(0)
<del> if err := cli.stream("GET", "/containers/"+image+"/export", nil, output, nil); err != nil {
<add> sopts := &streamOpts{
<add> rawTerminal: true,
<add> out: output,
<add> }
<add> if err := cli.stream("GET", "/containers/"+image+"/export", sopts); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/import.go
<ide> func (cli *DockerCli) CmdImport(args ...string) error {
<ide> in = cli.in
<ide> }
<ide>
<del> return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
<add> sopts := &streamOpts{
<add> rawTerminal: true,
<add> in: in,
<add> out: cli.out,
<add> }
<add>
<add> return cli.stream("POST", "/images/create?"+v.Encode(), sopts)
<ide> }
<ide><path>api/client/load.go
<ide> func (cli *DockerCli) CmdLoad(args ...string) error {
<ide> return err
<ide> }
<ide> }
<del> if err := cli.stream("POST", "/images/load", input, cli.out, nil); err != nil {
<add> sopts := &streamOpts{
<add> rawTerminal: true,
<add> in: input,
<add> out: cli.out,
<add> }
<add> if err := cli.stream("POST", "/images/load", sopts); err != nil {
<ide> return err
<ide> }
<ide> return nil
<ide><path>api/client/logs.go
<ide> func (cli *DockerCli) CmdLogs(args ...string) error {
<ide> }
<ide> v.Set("tail", *tail)
<ide>
<del> return cli.streamHelper("GET", "/containers/"+name+"/logs?"+v.Encode(), c.Config.Tty, nil, cli.out, cli.err, nil)
<add> sopts := &streamOpts{
<add> rawTerminal: c.Config.Tty,
<add> out: cli.out,
<add> err: cli.err,
<add> }
<add>
<add> return cli.stream("GET", "/containers/"+name+"/logs?"+v.Encode(), sopts)
<ide> }
<ide><path>api/client/save.go
<ide> func (cli *DockerCli) CmdSave(args ...string) error {
<ide> return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.")
<ide> }
<ide>
<add> sopts := &streamOpts{
<add> rawTerminal: true,
<add> out: output,
<add> }
<add>
<ide> if len(cmd.Args()) == 1 {
<ide> image := cmd.Arg(0)
<del> if err := cli.stream("GET", "/images/"+image+"/get", nil, output, nil); err != nil {
<add> if err := cli.stream("GET", "/images/"+image+"/get", sopts); err != nil {
<ide> return err
<ide> }
<ide> } else {
<ide> v := url.Values{}
<ide> for _, arg := range cmd.Args() {
<ide> v.Add("names", arg)
<ide> }
<del> if err := cli.stream("GET", "/images/get?"+v.Encode(), nil, output, nil); err != nil {
<add> if err := cli.stream("GET", "/images/get?"+v.Encode(), sopts); err != nil {
<ide> return err
<ide> }
<ide> }
<ide><path>api/client/utils.go
<ide> func (cli *DockerCli) call(method, path string, data interface{}, headers map[st
<ide> return body, statusCode, err
<ide> }
<ide>
<del>func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
<del> return cli.streamHelper(method, path, true, in, out, nil, headers)
<add>type streamOpts struct {
<add> rawTerminal bool
<add> in io.Reader
<add> out io.Writer
<add> err io.Writer
<add> headers map[string][]string
<ide> }
<ide>
<del>func (cli *DockerCli) streamHelper(method, path string, setRawTerminal bool, in io.Reader, stdout, stderr io.Writer, headers map[string][]string) error {
<del> body, contentType, _, err := cli.clientRequest(method, path, in, headers)
<add>func (cli *DockerCli) stream(method, path string, opts *streamOpts) error {
<add> body, contentType, _, err := cli.clientRequest(method, path, opts.in, opts.headers)
<ide> if err != nil {
<ide> return err
<ide> }
<del> return cli.streamBody(body, contentType, setRawTerminal, stdout, stderr)
<add> return cli.streamBody(body, contentType, opts.rawTerminal, opts.out, opts.err)
<ide> }
<ide>
<del>func (cli *DockerCli) streamBody(body io.ReadCloser, contentType string, setRawTerminal bool, stdout, stderr io.Writer) error {
<add>func (cli *DockerCli) streamBody(body io.ReadCloser, contentType string, rawTerminal bool, stdout, stderr io.Writer) error {
<ide> defer body.Close()
<ide>
<ide> if api.MatchesContentType(contentType, "application/json") {
<ide> func (cli *DockerCli) streamBody(body io.ReadCloser, contentType string, setRawT
<ide> if stdout != nil || stderr != nil {
<ide> // When TTY is ON, use regular copy
<ide> var err error
<del> if setRawTerminal {
<add> if rawTerminal {
<ide> _, err = io.Copy(stdout, body)
<ide> } else {
<ide> _, err = stdcopy.StdCopy(stdout, stderr, body) | 9 |
Ruby | Ruby | make an internal command | 706e8abe290c0c04185d62e29e2551dd8999b982 | <ide><path>Library/Contributions/cmd/brew-gist-logs.rb
<del>require 'formula'
<del>require 'cmd/config'
<del>require 'net/http'
<del>require 'net/https'
<del>require 'stringio'
<del>
<del>def gist_logs f
<del> if ARGV.include? '--new-issue'
<del> unless HOMEBREW_GITHUB_API_TOKEN
<del> puts 'You need to create an API token: https://github.com/settings/applications'
<del> puts 'and then set HOMEBREW_GITHUB_API_TOKEN to use --new-issue option.'
<del> exit 1
<del> end
<del> end
<del>
<del> files = load_logs(f.name)
<del>
<del> s = StringIO.new
<del> Homebrew.dump_verbose_config(s)
<del> files["config.out"] = { :content => s.string }
<del> files["doctor.out"] = { :content => `brew doctor 2>&1` }
<del>
<del> url = create_gist(files)
<del>
<del> if ARGV.include? '--new-issue'
<del> url = new_issue(f.tap, "#{f.name} failed to build on #{MACOS_FULL_VERSION}", url)
<del> end
<del>
<del> ensure puts url if url
<del>end
<del>
<del>def load_logs name
<del> logs = {}
<del> dir = HOMEBREW_LOGS/name
<del> dir.children.sort.each do |file|
<del> contents = file.size? ? file.read : "empty log"
<del> logs[file.basename.to_s] = { :content => contents }
<del> end if dir.exist?
<del> raise 'No logs.' if logs.empty?
<del> logs
<del>end
<del>
<del>def create_gist files
<del> post("/gists", "public" => true, "files" => files)["html_url"]
<del>end
<del>
<del>def new_issue repo, title, body
<del> post("/repos/#{repo}/issues", "title" => title, "body" => body)["html_url"]
<del>end
<del>
<del>def http
<del> @http ||= begin
<del> uri = URI.parse('https://api.github.com')
<del> p = ENV['http_proxy'] ? URI.parse(ENV['http_proxy']) : nil
<del> if p.class == URI::HTTP or p.class == URI::HTTPS
<del> @http = Net::HTTP.new(uri.host, uri.port, p.host, p.port, p.user, p.password)
<del> else
<del> @http = Net::HTTP.new(uri.host, uri.port)
<del> end
<del> @http.use_ssl = true
<del> @http
<del> end
<del>end
<del>
<del>def make_request(path, data)
<del> headers = {
<del> "User-Agent" => HOMEBREW_USER_AGENT,
<del> "Accept" => "application/vnd.github.v3+json",
<del> "Content-Type" => "application/json",
<del> }
<del>
<del> if HOMEBREW_GITHUB_API_TOKEN
<del> headers["Authorization"] = "token #{HOMEBREW_GITHUB_API_TOKEN}"
<del> end
<del>
<del> request = Net::HTTP::Post.new(path, headers)
<del> request.body = Utils::JSON.dump(data)
<del> request
<del>end
<del>
<del>def post(path, data)
<del> request = make_request(path, data)
<del>
<del> case response = http.request(request)
<del> when Net::HTTPCreated
<del> Utils::JSON.load get_body(response)
<del> else
<del> raise "HTTP #{response.code} #{response.message} (expected 201)"
<del> end
<del>end
<del>
<del>def get_body(response)
<del> if !response.body.respond_to?(:force_encoding)
<del> response.body
<del> elsif response["Content-Type"].downcase == "application/json; charset=utf-8"
<del> response.body.dup.force_encoding(Encoding::UTF_8)
<del> else
<del> response.body.encode(Encoding::UTF_8, :undef => :replace)
<del> end
<del>end
<del>
<del>if ARGV.formulae.length != 1
<del> puts "usage: brew gist-logs [--new-issue] <formula>"
<del> exit 1
<del>end
<del>
<del>gist_logs(ARGV.formulae[0])
<ide><path>Library/Homebrew/cmd/gist-logs.rb
<add>require 'formula'
<add>require 'cmd/config'
<add>require 'net/http'
<add>require 'net/https'
<add>require 'stringio'
<add>
<add>module Homebrew
<add> def gistify_logs f
<add> if ARGV.include? '--new-issue'
<add> unless HOMEBREW_GITHUB_API_TOKEN
<add> puts 'You need to create an API token: https://github.com/settings/applications'
<add> puts 'and then set HOMEBREW_GITHUB_API_TOKEN to use --new-issue option.'
<add> exit 1
<add> end
<add> end
<add>
<add> files = load_logs(f.name)
<add>
<add> s = StringIO.new
<add> Homebrew.dump_verbose_config(s)
<add> files["config.out"] = { :content => s.string }
<add> files["doctor.out"] = { :content => `brew doctor 2>&1` }
<add>
<add> url = create_gist(files)
<add>
<add> if ARGV.include? '--new-issue'
<add> url = new_issue(f.tap, "#{f.name} failed to build on #{MACOS_FULL_VERSION}", url)
<add> end
<add>
<add> ensure puts url if url
<add> end
<add>
<add> def load_logs name
<add> logs = {}
<add> dir = HOMEBREW_LOGS/name
<add> dir.children.sort.each do |file|
<add> contents = file.size? ? file.read : "empty log"
<add> logs[file.basename.to_s] = { :content => contents }
<add> end if dir.exist?
<add> raise 'No logs.' if logs.empty?
<add> logs
<add> end
<add>
<add> def create_gist files
<add> post("/gists", "public" => true, "files" => files)["html_url"]
<add> end
<add>
<add> def new_issue repo, title, body
<add> post("/repos/#{repo}/issues", "title" => title, "body" => body)["html_url"]
<add> end
<add>
<add> def http
<add> @http ||= begin
<add> uri = URI.parse('https://api.github.com')
<add> p = ENV['http_proxy'] ? URI.parse(ENV['http_proxy']) : nil
<add> if p.class == URI::HTTP or p.class == URI::HTTPS
<add> @http = Net::HTTP.new(uri.host, uri.port, p.host, p.port, p.user, p.password)
<add> else
<add> @http = Net::HTTP.new(uri.host, uri.port)
<add> end
<add> @http.use_ssl = true
<add> @http
<add> end
<add> end
<add>
<add> def make_request(path, data)
<add> headers = {
<add> "User-Agent" => HOMEBREW_USER_AGENT,
<add> "Accept" => "application/vnd.github.v3+json",
<add> "Content-Type" => "application/json",
<add> }
<add>
<add> if HOMEBREW_GITHUB_API_TOKEN
<add> headers["Authorization"] = "token #{HOMEBREW_GITHUB_API_TOKEN}"
<add> end
<add>
<add> request = Net::HTTP::Post.new(path, headers)
<add> request.body = Utils::JSON.dump(data)
<add> request
<add> end
<add>
<add> def post(path, data)
<add> request = make_request(path, data)
<add>
<add> case response = http.request(request)
<add> when Net::HTTPCreated
<add> Utils::JSON.load get_body(response)
<add> else
<add> raise "HTTP #{response.code} #{response.message} (expected 201)"
<add> end
<add> end
<add>
<add> def get_body(response)
<add> if !response.body.respond_to?(:force_encoding)
<add> response.body
<add> elsif response["Content-Type"].downcase == "application/json; charset=utf-8"
<add> response.body.dup.force_encoding(Encoding::UTF_8)
<add> else
<add> response.body.encode(Encoding::UTF_8, :undef => :replace)
<add> end
<add> end
<add>
<add> def gist_logs
<add> if ARGV.formulae.length != 1
<add> puts "usage: brew gist-logs [--new-issue] <formula>"
<add> Homebrew.failed = true
<add> return
<add> end
<add>
<add> gistify_logs(ARGV.formulae[0])
<add> end
<add>end | 2 |
Text | Text | fix broken wikipedia link | 3335fe26a7f0e509dfbf7482d413ae12cd7123f7 | <ide><path>guide/english/java/swing/index.md
<ide> Swing comprises of numerous number of packages.Please go through the [official d
<ide> #### More Information:
<ide>
<ide> - [Oracle docs](https://docs.oracle.com/javase/7/docs/api/javax/swing/package-use.html)
<del>- [Wikipedia](https://en.wikipedia.org/wiki/Swing_(Java)
<add>- [Wikipedia](https://en.wikipedia.org/wiki/Swing_(Java)) | 1 |
PHP | PHP | add stricter array typehint | 3b49033e9d8a0627b76db739fcebeadb5db03688 | <ide><path>src/Routing/RouteBuilder.php
<ide> public function resources($name, $options = [], $callback = null)
<ide> * @throws \InvalidArgumentException
<ide> * @throws \BadMethodCallException
<ide> */
<del> public function connect($route, array $defaults = [], $options = [])
<add> public function connect($route, array $defaults = [], array $options = [])
<ide> {
<ide> if (empty($options['action'])) {
<ide> $defaults += ['action' => 'index']; | 1 |
Ruby | Ruby | utilize modern dependency api | 18836d93d8f9f99c1e4d4fbaf9843e9f223f1742 | <ide><path>Library/Homebrew/cmd/uses.rb
<ide> def uses
<ide> uses = Formula.select do |f|
<ide> ARGV.formulae.all? do |ff|
<ide> if ARGV.flag? '--recursive'
<del> f.recursive_deps.include? ff
<add> f.recursive_dependencies.any? { |dep| dep.name == ff.name }
<ide> else
<del> f.deps.include? ff
<add> f.deps.any? { |dep| dep.name == ff.name }
<ide> end
<ide> end
<ide> end
<ide>
<ide> if ARGV.include? "--installed"
<del> uses = uses.select do |f|
<del> keg = HOMEBREW_CELLAR/f
<del> keg.directory? and not keg.subdirs.empty?
<del> end
<add> uses = uses.select { |f| Formula.installed.include? f }
<ide> end
<ide>
<del> puts_columns uses.map{|f| f.to_s}.sort
<add> puts_columns uses.map(&:to_s).sort
<ide> end
<ide> end | 1 |
Javascript | Javascript | take safari 9.1 into account | 234a2d828021b6eb36d83d83cc30c5a09045e781 | <ide><path>test/unit/support.js
<ide> testIframe(
<ide> "radioValue": true,
<ide> "reliableMarginLeft": true
<ide> };
<del> } else if ( /9\.0(\.\d+|) safari/i.test( userAgent ) ) {
<add> } else if ( /9(\.\d+|) safari/i.test( userAgent ) ) {
<ide> expected = {
<ide> "ajax": true,
<ide> "boxSizingReliable": true, | 1 |
Ruby | Ruby | add keyward argument `inplace` to run_shfmt | 03c7a142be52a909ceea0adac03071b059cf76a5 | <ide><path>Library/Homebrew/style.rb
<ide> def check_style_impl(files, output_type,
<ide> run_shellcheck(shell_files, output_type)
<ide> end
<ide>
<del> run_shfmt(shell_files) if ruby_files.none? || shell_files.any?
<add> run_shfmt(shell_files, inplace: fix) if ruby_files.none? || shell_files.any?
<ide>
<ide> if output_type == :json
<ide> Offenses.new(rubocop_result + shellcheck_result)
<ide> def run_shellcheck(files, output_type)
<ide> end
<ide> end
<ide>
<del> def run_shfmt(files)
<add> def run_shfmt(files, inplace: false)
<ide> files = shell_scripts if files.empty?
<add> # Do not format completions and Dockerfile
<add> files.delete(HOMEBREW_REPOSITORY/"completions/bash/brew")
<add> files.delete(HOMEBREW_REPOSITORY/"Dockerfile")
<ide>
<ide> args = ["-i", "2", "-ci", "-ln", "bash", "--", *files]
<ide>
<add> args.unshift("-w") if inplace
<add>
<ide> system shfmt, *args
<ide> $CHILD_STATUS.success?
<ide> end | 1 |
Javascript | Javascript | remove deprecated methods since 0.12 shipped | c46dadea55728a5c782861c15ed4989221c0674e | <ide><path>src/browser/ui/React.js
<ide> var ReactRef = require('ReactRef');
<ide> var ReactServerRendering = require('ReactServerRendering');
<ide>
<ide> var assign = require('Object.assign');
<del>var deprecated = require('deprecated');
<ide> var onlyChild = require('onlyChild');
<ide>
<ide> ReactDefaultInjection.inject();
<ide> var React = {
<ide> withContext: ReactContext.withContext,
<ide>
<ide> // Hook for JSX spread, don't use this for anything else.
<del> __spread: assign,
<del>
<del> // Deprecations (remove for 0.13)
<del> renderComponent: deprecated(
<del> 'React',
<del> 'renderComponent',
<del> 'render',
<del> this,
<del> render
<del> ),
<del> renderComponentToString: deprecated(
<del> 'React',
<del> 'renderComponentToString',
<del> 'renderToString',
<del> this,
<del> ReactServerRendering.renderToString
<del> ),
<del> renderComponentToStaticMarkup: deprecated(
<del> 'React',
<del> 'renderComponentToStaticMarkup',
<del> 'renderToStaticMarkup',
<del> this,
<del> ReactServerRendering.renderToStaticMarkup
<del> ),
<del> isValidComponent: deprecated(
<del> 'React',
<del> 'isValidComponent',
<del> 'isValidElement',
<del> this,
<del> ReactElement.isValidElement
<del> )
<add> __spread: assign
<ide> };
<ide>
<ide> // Inject the runtime into a devtools global hook regardless of browser.
<ide><path>src/browser/ui/ReactMount.js
<ide> var ReactUpdates = require('ReactUpdates');
<ide>
<ide> var emptyObject = require('emptyObject');
<ide> var containsNode = require('containsNode');
<del>var deprecated = require('deprecated');
<ide> var getReactRootElementInContainer = require('getReactRootElementInContainer');
<ide> var instantiateReactComponent = require('instantiateReactComponent');
<ide> var invariant = require('invariant');
<ide> ReactPerf.measureMethods(ReactMount, 'ReactMount', {
<ide> _mountImageIntoNode: '_mountImageIntoNode'
<ide> });
<ide>
<del>// Deprecations (remove for 0.13)
<del>ReactMount.renderComponent = deprecated(
<del> 'ReactMount',
<del> 'renderComponent',
<del> 'render',
<del> this,
<del> ReactMount.render
<del>);
<del>
<ide> module.exports = ReactMount;
<ide><path>src/classic/propTypes/ReactPropTypes.js
<ide> var ReactElement = require('ReactElement');
<ide> var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
<ide>
<del>var deprecated = require('deprecated');
<ide> var emptyFunction = require('emptyFunction');
<ide>
<ide> /**
<ide> var ReactPropTypes = {
<ide> objectOf: createObjectOfTypeChecker,
<ide> oneOf: createEnumTypeChecker,
<ide> oneOfType: createUnionTypeChecker,
<del> shape: createShapeTypeChecker,
<del>
<del> component: deprecated(
<del> 'React.PropTypes',
<del> 'component',
<del> 'element',
<del> this,
<del> elementTypeChecker
<del> ),
<del> renderable: deprecated(
<del> 'React.PropTypes',
<del> 'renderable',
<del> 'node',
<del> this,
<del> nodeTypeChecker
<del> )
<add> shape: createShapeTypeChecker
<ide> };
<ide>
<ide> function createChainableTypeChecker(validate) {
<ide><path>src/classic/propTypes/__tests__/ReactPropTypes-test.js
<ide> describe('ReactPropTypes', function() {
<ide> it('should accept empty array for required props', function() {
<ide> typeCheckPass(PropTypes.node.isRequired, []);
<ide> });
<del>
<del> it('should still work for deprecated typechecks', function() {
<del> // We can't use typeCheckPass here because the warning module may do
<del> // something different in some environments. Luckily they should be fine
<del> // if they detect that console.warn is spied upon.
<del> spyOn(console, 'warn');
<del>
<del> // typeCheckPass(PropTypes.renderable, []);
<del> var error = PropTypes.renderable(
<del> {testProp: []},
<del> 'testProp',
<del> 'testComponent',
<del> ReactPropTypeLocations.prop
<del> );
<del>
<del> expect(error).toBe(undefined);
<del> expect(console.warn.calls.length).toBe(1);
<del>
<del> // typeCheckPass(PropTypes.renderable.isRequired, []);
<del> error = PropTypes.renderable.isRequired(
<del> {testProp: []},
<del> 'testProp',
<del> 'testComponent',
<del> ReactPropTypeLocations.prop
<del> );
<del>
<del> expect(error).toBe(undefined);
<del> expect(console.warn.calls.length).toBe(1);
<del> });
<ide> });
<ide>
<ide> describe('ObjectOf Type', function() { | 4 |
Java | Java | remove reference to fluxion | a8c777b35facc210caf8bf32d19f01f296aa9bea | <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/handler/SimpleHandlerResultHandlerTests.java
<ide> public void supports() throws NoSuchMethodException {
<ide>
<ide> hm = new HandlerMethod(controller, TestController.class.getMethod("streamVoid"));
<ide> type = ResolvableType.forMethodParameter(hm.getReturnType());
<del> // Reactor Fluxion is a Publisher
<add> // Reactor Flux is a Publisher
<ide> assertTrue(resultHandler.supports(createHandlerResult(hm, type)));
<ide>
<ide> hm = new HandlerMethod(controller, TestController.class.getMethod("observableVoid")); | 1 |
PHP | PHP | add new `case` expression | 10bc708e9195760a608aca6413a2fb9ed3c964b8 | <ide><path>src/Database/Expression/CaseExpressionInterface.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.3.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Database\Expression;
<add>
<add>use Cake\Database\ExpressionInterface;
<add>use Cake\Database\TypedResultInterface;
<add>use Cake\Database\TypeMap;
<add>
<add>interface CaseExpressionInterface extends ExpressionInterface, TypedResultInterface
<add>{
<add> /**
<add> * Returns the case value for a `CASE case_value WHEN ...` expression.
<add> *
<add> * @return \Cake\Database\ExpressionInterface|object|scalar|null
<add> */
<add> public function getValue();
<add>
<add> /**
<add> * Sets the value for the case expression.
<add> *
<add> * When a value is set, the syntax generated is
<add> * `CASE case_value WHEN when_value ... END`, where the
<add> * `when_value`'s are compared against the `case_value`.
<add> *
<add> * When no value is set, the syntax generated is
<add> * `CASE WHEN when_conditions ... END`, where the conditions
<add> * hold the comparisons.
<add> *
<add> * @param \Cake\Database\ExpressionInterface|object|scalar|null $value The case value.
<add> * @param string|null $valueType The case value type.
<add> * @return $this
<add> */
<add> public function value($value, ?string $valueType = null);
<add>
<add> /**
<add> * Returns the case value type.
<add> *
<add> * @return string|null
<add> */
<add> public function getValueType(): ?string;
<add>
<add> /**
<add> * Returns the `WHEN ... THEN ...` statement expressions.
<add> *
<add> * @return \Cake\Database\Expression\WhenThenExpressionInterface[]
<add> */
<add> public function getWhen(): array;
<add>
<add> /**
<add> * Sets the `WHEN` value for a `WHEN ... THEN ...` expression, or a
<add> * self-contained expression that holds both the value for `WHEN`
<add> * and the value for `THEN`.
<add> *
<add> * ### Order based syntax
<add> *
<add> * When passing a value other than a self-contained
<add> * `\Cake\Database\Expression\WhenThenExpressionInterface`,
<add> * instance, the `WHEN ... THEN ...` statement must be closed off with
<add> * a call to `then()` before invoking `when()` again or `else()`:
<add> *
<add> * ```
<add> * $case
<add> * ->value($query->identifier('Table.column'))
<add> * ->when(true)
<add> * ->then('Yes')
<add> * ->when(false)
<add> * ->then('No')
<add> * ->else('Maybe');
<add> * ```
<add> *
<add> * ### Self-contained expressions
<add> *
<add> * When passing an instance of `\Cake\Database\Expression\WhenThenExpressionInterface`,
<add> * being it directly, or via a callable, then there is no need to close
<add> * using `then()` on this object, instead the statement will be closed
<add> * on the `\Cake\Database\Expression\WhenThenExpressionInterface`
<add> * object using
<add> * `\Cake\Database\Expression\WhenThenExpressionInterface::then()`.
<add> *
<add> * Callables will receive an instance of `\Cake\Database\Expression\WhenThenExpressionInterface`,
<add> * and must return one, being it the same object, or a custom one:
<add> *
<add> * ```
<add> * $case
<add> * ->when(function (\Cake\Database\Expression\WhenThenExpressionInterface $whenThen) {
<add> * return $whenThen
<add> * ->when(['Table.column' => true])
<add> * ->then('Yes');
<add> * })
<add> * ->when(function (\Cake\Database\Expression\WhenThenExpressionInterface $whenThen) {
<add> * return $whenThen
<add> * ->when(['Table.column' => false])
<add> * ->then('No');
<add> * })
<add> * ->else('Maybe');
<add> * ```
<add> *
<add> * ### Type handling
<add> *
<add> * The types provided via the `$type` argument will be merged with the
<add> * type map set for this expression. When using callables for `$when`,
<add> * the `\Cake\Database\Expression\WhenThenExpressionInterface`
<add> * instance received by the callables will inherit that type map, however
<add> * the types passed here will _not_ be merged in case of using callables,
<add> * instead the types must be passed in
<add> * `\Cake\Database\Expression\WhenThenExpressionInterface::when()`:
<add> *
<add> * ```
<add> * $case
<add> * ->when(function (\Cake\Database\Expression\WhenThenExpressionInterface $whenThen) {
<add> * return $whenThen
<add> * ->when(['unmapped_column' => true], ['unmapped_column' => 'bool'])
<add> * ->then('Yes');
<add> * })
<add> * ->when(function (\Cake\Database\Expression\WhenThenExpressionInterface $whenThen) {
<add> * return $whenThen
<add> * ->when(['unmapped_column' => false], ['unmapped_column' => 'bool'])
<add> * ->then('No');
<add> * })
<add> * ->else('Maybe');
<add> * ```
<add> *
<add> * ### User data safety
<add> *
<add> * When passing user data, be aware that allowing a user defined array
<add> * to be passed, is a potential SQL injection vulnerability, as it
<add> * allows for raw SQL to slip in!
<add> *
<add> * The following is _unsafe_ usage that must be avoided:
<add> *
<add> * ```
<add> * $case
<add> * ->when($userData)
<add> * ```
<add> *
<add> * A safe variant for the above would be to define a single type for
<add> * the value:
<add> *
<add> * ```
<add> * $case
<add> * ->when($userData, 'integer')
<add> * ```
<add> *
<add> * This way an exception would be triggered when an array is passed for
<add> * the value, thus preventing raw SQL from slipping in, and all other
<add> * types of values would be forced to be bound as an integer.
<add> *
<add> * Another way to safely pass user data is when using a conditions
<add> * array, and passing user data only on the value side of the array
<add> * entries, which will cause them to be bound:
<add> *
<add> * ```
<add> * $case
<add> * ->when([
<add> * 'Table.column' => $userData,
<add> * ])
<add> * ```
<add> *
<add> * Lastly, data can also be bound manually:
<add> *
<add> * ```
<add> * $query
<add> * ->select([
<add> * 'val' => $query->newExpr()
<add> * ->case()
<add> * ->when($query->newExpr(':userData'))
<add> * ->then(123)
<add> * ])
<add> * ->bind(':userData', $userData, 'integer')
<add> * ```
<add> *
<add> * @param \Cake\Database\ExpressionInterface|\Closure|array|object|scalar $when The `WHEN` value. When using an
<add> * array of conditions, it must be compatible with `\Cake\Database\Query::where()`. Note that this argument is
<add> * _not_ completely safe for use with user data, as a user supplied array would allow for raw SQL to slip in! If
<add> * you plan to use user data, either pass a single type for the `$type` argument (which forces the `$when` value to
<add> * be a non-array, and then always binds the data), use a conditions array where the user data is only passed on
<add> * the value side of the array entries, or custom bindings!
<add> * @param array|string|null $type The when value type. Either an associative array when using array style
<add> * conditions, or else a string. If no type is provided, the type will be tried to be inferred from the value.
<add> * @return $this
<add> * @throws \LogicException In case this a closing `then()` call is required before calling this method.
<add> * @throws \LogicException In case the callable doesn't return an instance of
<add> * `\Cake\Database\Expression\WhenThenExpressionInterface`.
<add> * @see then()
<add> */
<add> public function when($when, $type = []);
<add>
<add> /**
<add> * Sets the `THEN` result value for the last `WHEN ... THEN ...`
<add> * statement that was opened using `when()`.
<add> *
<add> * ### Order based syntax
<add> *
<add> * This method can only be invoked in case `when()` was previously
<add> * used with a value other than a closure or an instance of
<add> * `\Cake\Database\Expression\WhenThenExpressionInterface`:
<add> *
<add> * ```
<add> * $case
<add> * ->when(['Table.column' => true])
<add> * ->then('Yes')
<add> * ->when(['Table.column' => false])
<add> * ->then('No')
<add> * ->else('Maybe');
<add> * ```
<add> *
<add> * The following would all fail with an exception:
<add> *
<add> * ```
<add> * $case
<add> * ->when(['Table.column' => true])
<add> * ->when(['Table.column' => false])
<add> * // ...
<add> * ```
<add> *
<add> * ```
<add> * $case
<add> * ->when(['Table.column' => true])
<add> * ->else('Maybe')
<add> * // ...
<add> * ```
<add> *
<add> * ```
<add> * $case
<add> * ->then('Yes')
<add> * // ...
<add> * ```
<add> *
<add> * ```
<add> * $case
<add> * ->when(['Table.column' => true])
<add> * ->then('Yes')
<add> * ->then('No')
<add> * // ...
<add> * ```
<add> *
<add> * @param \Cake\Database\ExpressionInterface|object|scalar|null $result The result value.
<add> * @param string|null $type The result type. If no type is provided, the type will be tried to be inferred from the
<add> * value.
<add> * @return $this
<add> * @throws \LogicException In case `when()` wasn't previously called with a value other than a closure or an
<add> * instance of `\Cake\Database\Expression\WhenThenExpressionInterface`.
<add> * @see when()
<add> */
<add> public function then($result, ?string $type = null);
<add>
<add> /**
<add> * Returns the `ELSE` result value.
<add> *
<add> * @return \Cake\Database\ExpressionInterface|object|scalar|null The result value, or `null` if none has been set
<add> * yet.
<add> */
<add> public function getElse();
<add>
<add> /**
<add> * Sets the `ELSE` result value.
<add> *
<add> * @param \Cake\Database\ExpressionInterface|object|scalar|null $result The result value.
<add> * @param string|null $type The result type. If no type is provided, the type will be tried to be inferred from the
<add> * value.
<add> * @return $this
<add> * @throws \LogicException In case a closing `then()` call is required before calling this method.
<add> * @throws \InvalidArgumentException In case the `$result` argument is neither a scalar value, nor an object, an
<add> * instance of `\Cake\Database\ExpressionInterface`, or `null`.
<add> * @see then()
<add> */
<add> public function else($result, ?string $type = null);
<add>
<add> /**
<add> * Returns the type of the `ELSE` result value.
<add> *
<add> * @return string|null The result type, or `null` if none has been set yet.
<add> */
<add> public function getElseType(): ?string;
<add>
<add> /**
<add> * Returns the abstract type that this expression will return.
<add> *
<add> * If no type has been explicitly set via `setReturnType()`, this
<add> * method will try to obtain the type from the result types of the
<add> * `then()` and `else() `calls. All types must be identical in order
<add> * for this to work, otherwise the type will default to `string`.
<add> *
<add> * @return string
<add> * @see setReturnType()
<add> */
<add> public function getReturnType(): string;
<add>
<add> /**
<add> * Sets the abstract type that this expression will return.
<add> *
<add> * If no type is being explicitly set via this method, then the
<add> * `getReturnType()` method will try to infer the type from the
<add> * result types of the `then()` and `else() `calls.
<add> *
<add> * @param string $type The type name to use.
<add> * @return $this
<add> * @see getReturnType()
<add> */
<add> public function setReturnType(string $type);
<add>
<add> /**
<add> * Sets the type map to use when using an array of conditions
<add> * for the `WHEN` value.
<add> *
<add> * @param array|\Cake\Database\TypeMap $typeMap Either an array that is used to create a new
<add> * `\Cake\Database\TypeMap` instance, or an instance of `\Cake\Database\TypeMap`.
<add> * @return $this
<add> */
<add> public function setTypeMap($typeMap);
<add>
<add> /**
<add> * Returns the type map.
<add> *
<add> * @return \Cake\Database\TypeMap
<add> */
<add> public function getTypeMap(): TypeMap;
<add>}
<ide><path>src/Database/Expression/CaseExpressionTrait.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.3.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Database\Expression;
<add>
<add>use Cake\Chronos\Date;
<add>use Cake\Chronos\MutableDate;
<add>use Cake\Database\ExpressionInterface;
<add>use Cake\Database\Query;
<add>use Cake\Database\ValueBinder;
<add>use DateTimeInterface;
<add>
<add>trait CaseExpressionTrait
<add>{
<add> /**
<add> * Infers the abstract type for the given value.
<add> *
<add> * @param mixed $value The value for which to infer the type.
<add> * @return string|null The abstract type, or `null` if it could not be inferred.
<add> */
<add> protected function _inferType($value): ?string
<add> {
<add> $type = null;
<add>
<add> if (is_string($value)) {
<add> $type = 'string';
<add> } elseif (is_int($value)) {
<add> $type = 'integer';
<add> } elseif (is_float($value)) {
<add> $type = 'float';
<add> } elseif (is_bool($value)) {
<add> $type = 'boolean';
<add> } elseif (
<add> $value instanceof Date ||
<add> $value instanceof MutableDate
<add> ) {
<add> $type = 'date';
<add> } elseif ($value instanceof DateTimeInterface) {
<add> $type = 'datetime';
<add> } elseif (
<add> is_object($value) &&
<add> method_exists($value, '__toString')
<add> ) {
<add> $type = 'string';
<add> } elseif ($value instanceof IdentifierExpression) {
<add> $type = $this->getTypeMap()->type($value->getIdentifier());
<add> }
<add>
<add> return $type;
<add> }
<add>
<add> /**
<add> * Compiles a nullable value to SQL.
<add> *
<add> * @param \Cake\Database\ValueBinder $binder The value binder to use.
<add> * @param \Cake\Database\ExpressionInterface|object|scalar|null $value The value to compile.
<add> * @param string|null $type The value type.
<add> * @return string
<add> */
<add> protected function _compileNullableValue(ValueBinder $binder, $value, ?string $type = null): string
<add> {
<add> if (
<add> $type !== null &&
<add> !($value instanceof ExpressionInterface)
<add> ) {
<add> $value = $this->_castToExpression($value, $type);
<add> }
<add>
<add> if ($value === null) {
<add> $value = 'NULL';
<add> } elseif ($value instanceof Query) {
<add> $value = sprintf('(%s)', $value->sql($binder));
<add> } elseif ($value instanceof ExpressionInterface) {
<add> $value = $value->sql($binder);
<add> } else {
<add> $placeholder = $binder->placeholder('c');
<add> $binder->bind($placeholder, $value, $type);
<add> $value = $placeholder;
<add> }
<add>
<add> return $value;
<add> }
<add>}
<ide><path>src/Database/Expression/CaseStatementExpression.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.3.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Database\Expression;
<add>
<add>use Cake\Database\ExpressionInterface;
<add>use Cake\Database\Type\ExpressionTypeCasterTrait;
<add>use Cake\Database\TypeMap;
<add>use Cake\Database\TypeMapTrait;
<add>use Cake\Database\ValueBinder;
<add>use Closure;
<add>use InvalidArgumentException;
<add>use LogicException;
<add>
<add>class CaseStatementExpression implements CaseExpressionInterface
<add>{
<add> use CaseExpressionTrait;
<add> use ExpressionTypeCasterTrait;
<add> use TypeMapTrait;
<add>
<add> /**
<add> * Whether this is a simple case expression.
<add> *
<add> * @var bool
<add> */
<add> protected $_isSimpleVariant = false;
<add>
<add> /**
<add> * The case value.
<add> *
<add> * @var \Cake\Database\ExpressionInterface|object|scalar|null
<add> */
<add> protected $_value = null;
<add>
<add> /**
<add> * The case value type.
<add> *
<add> * @var string|null
<add> */
<add> protected $_valueType = null;
<add>
<add> /**
<add> * The `WHEN ... THEN ...` expressions.
<add> *
<add> * @var \Cake\Database\Expression\WhenThenExpressionInterface[]
<add> */
<add> protected $_when = [];
<add>
<add> /**
<add> * Buffer that holds values and types for use with `then()`.
<add> *
<add> * @var array|null
<add> */
<add> protected $_whenBuffer = null;
<add>
<add> /**
<add> * The else part result value.
<add> *
<add> * @var mixed|null
<add> */
<add> protected $_else = null;
<add>
<add> /**
<add> * The else part result type.
<add> *
<add> * @var string|null
<add> */
<add> protected $_elseType = null;
<add>
<add> /**
<add> * The return type.
<add> *
<add> * @var string|null
<add> */
<add> protected $_returnType = null;
<add>
<add> /**
<add> * Constructor.
<add> *
<add> * @param \Cake\Database\TypeMap|null $typeMap The type map to use when using an array of conditions for the `WHEN`
<add> * value.
<add> */
<add> public function __construct(?TypeMap $typeMap = null)
<add> {
<add> if ($typeMap !== null) {
<add> $this->setTypeMap($typeMap);
<add> }
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function getValue()
<add> {
<add> return $this->_value;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function value($value, ?string $valueType = null)
<add> {
<add> if (
<add> $value !== null &&
<add> !is_scalar($value) &&
<add> !(is_object($value) && !($value instanceof Closure))
<add> ) {
<add> throw new InvalidArgumentException(sprintf(
<add> 'The `$value` argument must be either `null`, a scalar value, an object, ' .
<add> 'or an instance of `\%s`, `%s` given.',
<add> ExpressionInterface::class,
<add> getTypeName($value)
<add> ));
<add> }
<add>
<add> $this->_value = $value;
<add>
<add> if (
<add> $value !== null &&
<add> $valueType === null
<add> ) {
<add> $valueType = $this->_inferType($value);
<add> }
<add> $this->_valueType = $valueType;
<add>
<add> $this->_isSimpleVariant = true;
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function getValueType(): ?string
<add> {
<add> return $this->_valueType;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function getWhen(): array
<add> {
<add> return $this->_when;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function when($when, $type = null)
<add> {
<add> if ($this->_whenBuffer !== null) {
<add> throw new LogicException(
<add> 'Cannot add new `WHEN` value while an open `when()` buffer is present, ' .
<add> 'it must first be closed using `then()`.'
<add> );
<add> }
<add>
<add> if ($when instanceof Closure) {
<add> $when = $when(new WhenThenExpression($this->getTypeMap()));
<add> if (!($when instanceof WhenThenExpressionInterface)) {
<add> throw new LogicException(sprintf(
<add> '`when()` callables must return an instance of `\%s`, `%s` given.',
<add> WhenThenExpressionInterface::class,
<add> getTypeName($when)
<add> ));
<add> }
<add> }
<add>
<add> if ($when instanceof WhenThenExpressionInterface) {
<add> $this->_when[] = $when;
<add> } else {
<add> $this->_whenBuffer = ['when' => $when, 'type' => $type];
<add> }
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function then($result, ?string $type = null)
<add> {
<add> if ($this->_whenBuffer === null) {
<add> throw new LogicException(
<add> 'There is no `when()` buffer present, ' .
<add> 'you must first open one before calling `then()`.'
<add> );
<add> }
<add>
<add> $whenThen = (new WhenThenExpression($this->getTypeMap()))
<add> ->when($this->_whenBuffer['when'], $this->_whenBuffer['type'])
<add> ->then($result, $type);
<add>
<add> $this->_whenBuffer = null;
<add>
<add> $this->when($whenThen);
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function getElse()
<add> {
<add> return $this->_else;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function else($result, ?string $type = null)
<add> {
<add> if ($this->_whenBuffer !== null) {
<add> throw new LogicException(
<add> 'Cannot set `ELSE` value when an open `when()` buffer is present, ' .
<add> 'it must first be closed using `then()`.'
<add> );
<add> }
<add>
<add> if (
<add> $result !== null &&
<add> !is_scalar($result) &&
<add> !(is_object($result) && !($result instanceof Closure))
<add> ) {
<add> throw new InvalidArgumentException(sprintf(
<add> 'The `$result` argument must be either `null`, a scalar value, an object, ' .
<add> 'or an instance of `\%s`, `%s` given.',
<add> ExpressionInterface::class,
<add> getTypeName($result)
<add> ));
<add> }
<add>
<add> if ($type === null) {
<add> $type = $this->_inferType($result);
<add> }
<add>
<add> $this->_whenBuffer = null;
<add>
<add> $this->_else = $result;
<add> $this->_elseType = $type;
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function getElseType(): ?string
<add> {
<add> return $this->_elseType;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function getReturnType(): string
<add> {
<add> if ($this->_returnType !== null) {
<add> return $this->_returnType;
<add> }
<add>
<add> $types = [];
<add> foreach ($this->_when as $when) {
<add> $type = $when->getThenType();
<add> if ($type !== null) {
<add> $types[] = $type;
<add> }
<add> }
<add>
<add> if ($this->_elseType !== null) {
<add> $types[] = $this->_elseType;
<add> }
<add>
<add> $types = array_unique($types);
<add> if (count($types) === 1) {
<add> return $types[0];
<add> }
<add>
<add> return 'string';
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function setReturnType(string $type)
<add> {
<add> $this->_returnType = $type;
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function sql(ValueBinder $binder): string
<add> {
<add> if ($this->_whenBuffer !== null) {
<add> throw new LogicException(
<add> sprintf(
<add> 'Cannot compile incomplete `\%s` expression, there is an open `when()` buffer present ' .
<add> 'that must be closed using `then()`.',
<add> CaseExpressionInterface::class
<add> )
<add> );
<add> }
<add>
<add> if (empty($this->_when)) {
<add> throw new LogicException(
<add> sprintf(
<add> 'Cannot compile incomplete `\%s` expression, there are no `WHEN ... THEN ...` statements.',
<add> CaseExpressionInterface::class
<add> )
<add> );
<add> }
<add>
<add> $value = '';
<add> if ($this->_isSimpleVariant) {
<add> $value = $this->_compileNullableValue($binder, $this->_value, $this->_valueType) . ' ';
<add> }
<add>
<add> $whenThenExpressions = [];
<add> foreach ($this->_when as $whenThen) {
<add> $whenThenExpressions[] = $whenThen->sql($binder);
<add> }
<add> $whenThen = implode(' ', $whenThenExpressions);
<add>
<add> $else = $this->_compileNullableValue($binder, $this->_else, $this->_elseType);
<add>
<add> return "CASE {$value}{$whenThen} ELSE $else END";
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function traverse(Closure $callback)
<add> {
<add> if ($this->_whenBuffer !== null) {
<add> throw new LogicException(
<add> sprintf(
<add> 'Cannot traverse incomplete `\%s` expression, there is an open `when()` buffer present ' .
<add> 'that must be closed using `then()`.',
<add> CaseExpressionInterface::class
<add> )
<add> );
<add> }
<add>
<add> if ($this->_value instanceof ExpressionInterface) {
<add> $callback($this->_value);
<add> $this->_value->traverse($callback);
<add> }
<add>
<add> foreach ($this->_when as $when) {
<add> $callback($when);
<add> $when->traverse($callback);
<add> }
<add>
<add> if ($this->_else instanceof ExpressionInterface) {
<add> $callback($this->_else);
<add> $this->_else->traverse($callback);
<add> }
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Clones the inner expression objects.
<add> *
<add> * @return void
<add> */
<add> public function __clone()
<add> {
<add> if ($this->_whenBuffer !== null) {
<add> throw new LogicException(
<add> sprintf(
<add> 'Cannot clone incomplete `\%s` expression, there is an open `when()` buffer present ' .
<add> 'that must be closed using `then()`.',
<add> CaseExpressionInterface::class
<add> )
<add> );
<add> }
<add>
<add> if ($this->_value instanceof ExpressionInterface) {
<add> $this->_value = clone $this->_value;
<add> }
<add>
<add> foreach ($this->_when as $key => $when) {
<add> $this->_when[$key] = clone $this->_when[$key];
<add> }
<add>
<add> if ($this->_else instanceof ExpressionInterface) {
<add> $this->_else = clone $this->_else;
<add> }
<add> }
<add>}
<ide><path>src/Database/Expression/QueryExpression.php
<ide> public function in($field, $values, $type = null)
<ide> */
<ide> public function addCase($conditions, $values = [], $types = [])
<ide> {
<add> deprecationWarning('QueryExpression::addCase() is deprecated, use case() instead.');
<add>
<ide> return $this->add(new CaseExpression($conditions, $values, $types));
<ide> }
<ide>
<add> /**
<add> * Returns a new case expression object.
<add> *
<add> * @return \Cake\Database\Expression\CaseExpressionInterface
<add> */
<add> public function case(): CaseExpressionInterface
<add> {
<add> return new CaseStatementExpression($this->getTypeMap());
<add> }
<add>
<ide> /**
<ide> * Adds a new condition to the expression object in the form
<ide> * "field NOT IN (value1, value2)".
<ide><path>src/Database/Expression/WhenThenExpression.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.3.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Database\Expression;
<add>
<add>use Cake\Database\ExpressionInterface;
<add>use Cake\Database\Query;
<add>use Cake\Database\Type\ExpressionTypeCasterTrait;
<add>use Cake\Database\TypeMap;
<add>use Cake\Database\ValueBinder;
<add>use Closure;
<add>use InvalidArgumentException;
<add>use LogicException;
<add>
<add>class WhenThenExpression implements WhenThenExpressionInterface
<add>{
<add> use CaseExpressionTrait;
<add> use ExpressionTypeCasterTrait;
<add>
<add> /**
<add> * The type map to use when using an array of conditions for the
<add> * `WHEN` value.
<add> *
<add> * @var \Cake\Database\TypeMap
<add> */
<add> protected $_typeMap;
<add>
<add> /**
<add> * Then `WHEN` value.
<add> *
<add> * @var \Cake\Database\ExpressionInterface|object|scalar|null
<add> */
<add> protected $_when = null;
<add>
<add> /**
<add> * The `WHEN` value type.
<add> *
<add> * @var array|string|null
<add> */
<add> protected $_whenType = null;
<add>
<add> /**
<add> * The `THEN` value.
<add> *
<add> * @var mixed
<add> */
<add> protected $_then = null;
<add>
<add> /**
<add> * Whether the `THEN` value has been defined, eg whether `then()`
<add> * has been invoked.
<add> *
<add> * @var bool
<add> */
<add> protected $_hasThenBeenDefined = false;
<add>
<add> /**
<add> * The `THEN` result type.
<add> *
<add> * @var string|null
<add> */
<add> protected $_thenType = null;
<add>
<add> /**
<add> * Constructor.
<add> *
<add> * @param \Cake\Database\TypeMap|null $typeMap The type map to use when using an array of conditions for the `WHEN`
<add> * value.
<add> */
<add> public function __construct(?TypeMap $typeMap = null)
<add> {
<add> if ($typeMap === null) {
<add> $typeMap = new TypeMap();
<add> }
<add> $this->_typeMap = $typeMap;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function getWhen()
<add> {
<add> return $this->_when;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function when($when, $type = null)
<add> {
<add> if (
<add> !(is_array($when) && !empty($when)) &&
<add> !is_scalar($when) &&
<add> !is_object($when)
<add> ) {
<add> throw new InvalidArgumentException(sprintf(
<add> 'The `$when` argument must be either a non-empty array, a scalar value, an object, ' .
<add> 'or an instance of `\%s`, `%s` given.',
<add> ExpressionInterface::class,
<add> is_array($when) ? '[]' : getTypeName($when)
<add> ));
<add> }
<add>
<add> if (
<add> $type !== null &&
<add> !is_array($type) &&
<add> !is_string($type)
<add> ) {
<add> throw new InvalidArgumentException(sprintf(
<add> 'The `$type` argument must be either an array, a string, or `null`, `%s` given.',
<add> getTypeName($type)
<add> ));
<add> }
<add>
<add> if (is_array($when)) {
<add> if (
<add> $type !== null &&
<add> !is_array($type)
<add> ) {
<add> throw new InvalidArgumentException(sprintf(
<add> 'When using an array for the `$when` argument, the `$type` argument must be an ' .
<add> 'array too, `%s` given.',
<add> getTypeName($type)
<add> ));
<add> }
<add>
<add> // avoid dirtying the type map for possible consecutive `when()` calls
<add> $typeMap = clone $this->_typeMap;
<add> if (
<add> is_array($type) &&
<add> count($type) > 0
<add> ) {
<add> $typeMap = $typeMap->setTypes($type);
<add> }
<add>
<add> $when = new QueryExpression($when, $typeMap);
<add> } else {
<add> if (
<add> $type !== null &&
<add> !is_string($type)
<add> ) {
<add> throw new InvalidArgumentException(sprintf(
<add> 'When using a non-array value for the `$when` argument, the `$type` argument must ' .
<add> 'be a string, `%s` given.',
<add> getTypeName($type)
<add> ));
<add> }
<add>
<add> if ($type === null) {
<add> $type = $this->_inferType($when);
<add> }
<add> }
<add>
<add> $this->_when = $when;
<add> $this->_whenType = $type;
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function getWhenType()
<add> {
<add> return $this->_whenType;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function getThen()
<add> {
<add> return $this->_then;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function then($result, ?string $type = null)
<add> {
<add> if (
<add> $result !== null &&
<add> !is_scalar($result) &&
<add> !(is_object($result) && !($result instanceof Closure))
<add> ) {
<add> throw new InvalidArgumentException(sprintf(
<add> 'The `$result` argument must be either `null`, a scalar value, an object, ' .
<add> 'or an instance of `\%s`, `%s` given.',
<add> ExpressionInterface::class,
<add> getTypeName($result)
<add> ));
<add> }
<add>
<add> $this->_then = $result;
<add>
<add> if ($type === null) {
<add> $type = $this->_inferType($result);
<add> }
<add>
<add> $this->_thenType = $type;
<add>
<add> $this->_hasThenBeenDefined = true;
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function getThenType(): ?string
<add> {
<add> return $this->_thenType;
<add> }
<add>
<add> /**
<add> * Returns the type map.
<add> *
<add> * @return \Cake\Database\TypeMap
<add> */
<add> protected function getTypeMap(): TypeMap
<add> {
<add> return $this->_typeMap;
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function sql(ValueBinder $binder): string
<add> {
<add> if ($this->_when === null) {
<add> throw new LogicException(
<add> sprintf(
<add> 'Cannot compile incomplete `\%s`, the value for `WHEN` is missing.',
<add> WhenThenExpressionInterface::class
<add> )
<add> );
<add> }
<add>
<add> if (!$this->_hasThenBeenDefined) {
<add> throw new LogicException(
<add> sprintf(
<add> 'Cannot compile incomplete `\%s`, the value for `THEN` is missing.',
<add> WhenThenExpressionInterface::class
<add> )
<add> );
<add> }
<add>
<add> $when = $this->_when;
<add> if (
<add> is_string($this->_whenType) &&
<add> !($when instanceof ExpressionInterface)
<add> ) {
<add> $when = $this->_castToExpression($when, $this->_whenType);
<add> }
<add> if ($when instanceof Query) {
<add> $when = sprintf('(%s)', $when->sql($binder));
<add> } elseif ($when instanceof ExpressionInterface) {
<add> $when = $when->sql($binder);
<add> } else {
<add> $placeholder = $binder->placeholder('c');
<add> if (is_string($this->_whenType)) {
<add> $whenType = $this->_whenType;
<add> } else {
<add> $whenType = null;
<add> }
<add> $binder->bind($placeholder, $when, $whenType);
<add> $when = $placeholder;
<add> }
<add>
<add> $then = $this->_compileNullableValue($binder, $this->_then, $this->_thenType);
<add>
<add> return "WHEN $when THEN $then";
<add> }
<add>
<add> /**
<add> * @inheritDoc
<add> */
<add> public function traverse(Closure $callback)
<add> {
<add> if ($this->_when instanceof ExpressionInterface) {
<add> $callback($this->_when);
<add> $this->_when->traverse($callback);
<add> }
<add>
<add> if ($this->_then instanceof ExpressionInterface) {
<add> $callback($this->_then);
<add> $this->_then->traverse($callback);
<add> }
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Clones the inner expression objects.
<add> *
<add> * @return void
<add> */
<add> public function __clone()
<add> {
<add> if ($this->_when instanceof ExpressionInterface) {
<add> $this->_when = clone $this->_when;
<add> }
<add>
<add> if ($this->_then instanceof ExpressionInterface) {
<add> $this->_then = clone $this->_then;
<add> }
<add> }
<add>}
<ide><path>src/Database/Expression/WhenThenExpressionInterface.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.3.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Database\Expression;
<add>
<add>use Cake\Database\ExpressionInterface;
<add>
<add>interface WhenThenExpressionInterface extends ExpressionInterface
<add>{
<add> /**
<add> * Returns the `WHEN` value.
<add> *
<add> * @return \Cake\Database\ExpressionInterface|object|scalar|null
<add> */
<add> public function getWhen();
<add>
<add> /**
<add> * Sets the `WHEN` value.
<add> *
<add> * @param \Cake\Database\ExpressionInterface|array|object|scalar $when The `WHEN` value. When using an array of
<add> * conditions, it must be compatible with `\Cake\Database\Query::where()`. Note that this argument is _not_
<add> * completely safe for use with user data, as a user supplied array would allow for raw SQL to slip in! If you
<add> * plan to use user data, either pass a single type for the `$type` argument (which forces the `$when` value to be
<add> * a non-array, and then always binds the data), use a conditions array where the user data is only passed on the
<add> * value side of the array entries, or custom bindings!
<add> * @param array|string|null $type The when value type. Either an associative array when using array style
<add> * conditions, or else a string. If no type is provided, the type will be tried to be inferred from the value.
<add> * @return $this
<add> * @throws \InvalidArgumentException In case the `$when` argument is neither a non-empty array, nor a scalar value,
<add> * an object, or an instance of `\Cake\Database\ExpressionInterface`.
<add> * @throws \InvalidArgumentException In case the `$type` argument is neither an array, a string, nor null.
<add> * @throws \InvalidArgumentException In case the `$when` argument is an array, and the `$type` argument is neither
<add> * an array, nor null.
<add> * @throws \InvalidArgumentException In case the `$when` argument is a non-array value, and the `$type` argument is
<add> * neither a string, nor null.
<add> * @see CaseExpressionInterface::when() for a more detailed usage explanation.
<add> */
<add> public function when($when, $type = null);
<add>
<add> /**
<add> * Returns the `WHEN` value type.
<add> *
<add> * @return array|string|null
<add> * @see when()
<add> */
<add> public function getWhenType();
<add>
<add> /**
<add> * Returns the `THEN` result value.
<add> *
<add> * @return \Cake\Database\ExpressionInterface|object|scalar|null The result value.
<add> */
<add> public function getThen();
<add>
<add> /**
<add> * Sets the `THEN` result value.
<add> *
<add> * @param \Cake\Database\ExpressionInterface|object|scalar|null $result The result value.
<add> * @param string|null $type The result type. If no type is provided, the type will be inferred from the given
<add> * result value.
<add> * @return $this
<add> */
<add> public function then($result, ?string $type = null);
<add>
<add> /**
<add> * Returns the `THEN` result value type.
<add> *
<add> * @return string|null
<add> * @see then()
<add> */
<add> public function getThenType(): ?string;
<add>}
<ide><path>tests/TestCase/Database/Expression/CaseStatementExpressionTest.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.3.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Test\TestCase\Database\Expression;
<add>
<add>use Cake\Chronos\Chronos;
<add>use Cake\Chronos\Date as ChronosDate;
<add>use Cake\Chronos\MutableDate as ChronosMutableDate;
<add>use Cake\Database\Expression\CaseStatementExpression;
<add>use Cake\Database\Expression\ComparisonExpression;
<add>use Cake\Database\Expression\IdentifierExpression;
<add>use Cake\Database\Expression\QueryExpression;
<add>use Cake\Database\Expression\WhenThenExpression;
<add>use Cake\Database\Expression\WhenThenExpressionInterface;
<add>use Cake\Database\TypeFactory;
<add>use Cake\Database\TypeMap;
<add>use Cake\Database\ValueBinder;
<add>use Cake\Datasource\ConnectionManager;
<add>use Cake\I18n\Date;
<add>use Cake\I18n\FrozenDate;
<add>use Cake\I18n\FrozenTime;
<add>use Cake\I18n\Time;
<add>use Cake\Test\test_app\TestApp\Database\Expression\CustomWhenThenExpression;
<add>use Cake\TestSuite\TestCase;
<add>use InvalidArgumentException;
<add>use LogicException;
<add>use stdClass;
<add>use TestApp\Database\Type\CustomExpressionType;
<add>use TestApp\View\Object\TestObjectWithToString;
<add>use TypeError;
<add>
<add>class CaseStatementExpressionTest extends TestCase
<add>{
<add> // region Type handling
<add>
<add> public function testExpressionTypeCastingSimpleCase(): void
<add> {
<add> TypeFactory::map('custom', CustomExpressionType::class);
<add>
<add> $expression = (new CaseStatementExpression())
<add> ->value(1, 'custom')
<add> ->when(1, 'custom')
<add> ->then(2, 'custom')
<add> ->else(3, 'custom');
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE CUSTOM(:param0) WHEN CUSTOM(:param1) THEN CUSTOM(:param2) ELSE CUSTOM(:param3) END',
<add> $sql
<add> );
<add> }
<add>
<add> public function testExpressionTypeCastingNullValues(): void
<add> {
<add> TypeFactory::map('custom', CustomExpressionType::class);
<add>
<add> $expression = (new CaseStatementExpression())
<add> ->value(null, 'custom')
<add> ->when(1, 'custom')
<add> ->then(null, 'custom')
<add> ->else(null, 'custom');
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE CUSTOM(:param0) WHEN CUSTOM(:param1) THEN CUSTOM(:param2) ELSE CUSTOM(:param3) END',
<add> $sql
<add> );
<add> }
<add>
<add> public function testExpressionTypeCastingSearchedCase(): void
<add> {
<add> TypeFactory::map('custom', CustomExpressionType::class);
<add>
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column' => true], ['Table.column' => 'custom'])
<add> ->then(1, 'custom')
<add> ->else(2, 'custom');
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE WHEN Table.column = (CUSTOM(:param0)) THEN CUSTOM(:param1) ELSE CUSTOM(:param2) END',
<add> $sql
<add> );
<add> }
<add>
<add> public function testGetReturnType(): void
<add> {
<add> // all provided `then` and `else` types are the same, return
<add> // type can be inferred
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column_a' => true])
<add> ->then(1, 'integer')
<add> ->when(['Table.column_b' => true])
<add> ->then(2, 'integer')
<add> ->else(3, 'integer');
<add> $this->assertSame('integer', $expression->getReturnType());
<add>
<add> // all provided `then` an `else` types are the same, one `then`
<add> // type is `null`, return type can be inferred
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column_a' => true])
<add> ->then(1)
<add> ->when(['Table.column_b' => true])
<add> ->then(2, 'integer')
<add> ->else(3, 'integer');
<add> $this->assertSame('integer', $expression->getReturnType());
<add>
<add> // all `then` types are null, an `else` type was provided,
<add> // return type can be inferred
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column_a' => true])
<add> ->then(1)
<add> ->when(['Table.column_b' => true])
<add> ->then(2)
<add> ->else(3, 'integer');
<add> $this->assertSame('integer', $expression->getReturnType());
<add>
<add> // all provided `then` types are the same, the `else` type is
<add> // `null`, return type can be inferred
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column_a' => true])
<add> ->then(1, 'integer')
<add> ->when(['Table.column_b' => true])
<add> ->then(2, 'integer')
<add> ->else(3);
<add> $this->assertSame('integer', $expression->getReturnType());
<add>
<add> // no `then` or `else` types were provided, they are all `null`,
<add> // and will be derived from the passed value, return type can be
<add> // inferred
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column_a' => true])
<add> ->then(1)
<add> ->when(['Table.column_b' => true])
<add> ->then(2)
<add> ->else(3);
<add> $this->assertSame('integer', $expression->getReturnType());
<add>
<add> // all `then` and `else` point to columns of the same type,
<add> // return type can be inferred
<add> $typeMap = new TypeMap([
<add> 'Table.column_a' => 'boolean',
<add> 'Table.column_b' => 'boolean',
<add> 'Table.column_c' => 'boolean',
<add> ]);
<add> $expression = (new CaseStatementExpression($typeMap))
<add> ->when(['Table.column_a' => true])
<add> ->then(new IdentifierExpression('Table.column_a'))
<add> ->when(['Table.column_b' => true])
<add> ->then(new IdentifierExpression('Table.column_b'))
<add> ->else(new IdentifierExpression('Table.column_c'));
<add> $this->assertSame('boolean', $expression->getReturnType());
<add>
<add> // all `then` and `else` use the same custom type, return type
<add> // can be inferred
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column_a' => true])
<add> ->then(1, 'custom')
<add> ->when(['Table.column_b' => true])
<add> ->then(2, 'custom')
<add> ->else(3, 'custom');
<add> $this->assertSame('custom', $expression->getReturnType());
<add>
<add> // all `then` and `else` types were provided, but an explicit
<add> // return type was set, return type will be overwritten
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column_a' => true])
<add> ->then(1, 'integer')
<add> ->when(['Table.column_b' => true])
<add> ->then(2, 'integer')
<add> ->else(3, 'integer')
<add> ->setReturnType('string');
<add> $this->assertSame('string', $expression->getReturnType());
<add>
<add> // all `then` and `else` types are different, return type
<add> // cannot be inferred
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column_a' => true])
<add> ->then(true)
<add> ->when(['Table.column_b' => true])
<add> ->then(1)
<add> ->else(null);
<add> $this->assertSame('string', $expression->getReturnType());
<add> }
<add>
<add> public function testSetReturnType(): void
<add> {
<add> $expression = (new CaseStatementExpression())->else('1');
<add> $this->assertSame('string', $expression->getReturnType());
<add>
<add> $expression->setReturnType('float');
<add> $this->assertSame('float', $expression->getReturnType());
<add> }
<add>
<add> public function typeInferenceDataProvider(): array
<add> {
<add> return [
<add> ['1', 'string'],
<add> [1, 'integer'],
<add> [1.0, 'float'],
<add> [true, 'boolean'],
<add> [ChronosDate::now(), 'date'],
<add> [Chronos::now(), 'datetime'],
<add> [new IdentifierExpression('Table.column'), 'boolean'],
<add> [new stdClass(), null],
<add> [null, null],
<add> ];
<add> }
<add>
<add> /**
<add> * @dataProvider typeInferenceDataProvider
<add> * @param mixed $value The value from which to infer the type.
<add> * @param string|null $type The expected type.
<add> */
<add> public function testInferValueType($value, ?string $type): void
<add> {
<add> $expression = (new CaseStatementExpression(new TypeMap(['Table.column' => 'boolean'])))
<add> ->value($value)
<add> ->when(1)
<add> ->then(2);
<add> $this->assertSame($type, $expression->getValueType());
<add> }
<add>
<add> /**
<add> * @dataProvider typeInferenceDataProvider
<add> * @param mixed $value The value from which to infer the type.
<add> * @param string|null $type The expected type.
<add> */
<add> public function testInferWhenType($value, ?string $type): void
<add> {
<add> $this->skipIf(
<add> $value === null,
<add> '`\Cake\Database\Expression\CaseExpression::when()` does not accept `null`'
<add> );
<add>
<add> $expression = (new CaseStatementExpression(new TypeMap(['Table.column' => 'boolean'])))
<add> ->when($value)
<add> ->then(1);
<add> $this->assertSame($type, $expression->getWhen()[0]->getWhenType());
<add> }
<add>
<add> /**
<add> * @dataProvider typeInferenceDataProvider
<add> * @param mixed $value The value from which to infer the type.
<add> * @param string|null $type The expected type.
<add> */
<add> public function testInferThenType($value, ?string $type): void
<add> {
<add> $expression = (new CaseStatementExpression(new TypeMap(['Table.column' => 'boolean'])))
<add> ->when(['Table.column' => true])
<add> ->then($value);
<add> $this->assertSame($type, $expression->getWhen()[0]->getThenType());
<add> }
<add>
<add> /**
<add> * @dataProvider typeInferenceDataProvider
<add> * @param mixed $value The value from which to infer the type.
<add> * @param string|null $type The expected type.
<add> */
<add> public function testInferElseType($value, ?string $type): void
<add> {
<add> $expression = (new CaseStatementExpression(new TypeMap(['Table.column' => 'boolean'])))
<add> ->else($value);
<add> $this->assertSame($type, $expression->getElseType());
<add> }
<add>
<add> public function testWhenArrayValueInheritTypeMap(): void
<add> {
<add> $typeMap = new TypeMap([
<add> 'Table.column_a' => 'boolean',
<add> 'Table.column_b' => 'string',
<add> ]);
<add>
<add> $expression = (new CaseStatementExpression($typeMap))
<add> ->when(['Table.column_a' => true])
<add> ->then(1)
<add> ->when(['Table.column_b' => 'foo'])
<add> ->then(2)
<add> ->else(3);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE WHEN Table.column_a = :c0 THEN :c1 WHEN Table.column_b = :c2 THEN :c3 ELSE :c4 END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => true,
<add> 'type' => 'boolean',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 'foo',
<add> 'type' => 'string',
<add> 'placeholder' => 'c2',
<add> ],
<add> ':c3' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c3',
<add> ],
<add> ':c4' => [
<add> 'value' => 3,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c4',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testWhenArrayValueWithExplicitTypes(): void
<add> {
<add> $typeMap = new TypeMap([
<add> 'Table.column_a' => 'boolean',
<add> 'Table.column_b' => 'string',
<add> ]);
<add>
<add> $expression = (new CaseStatementExpression($typeMap))
<add> ->when(['Table.column_a' => 123], ['Table.column_a' => 'integer'])
<add> ->then(1)
<add> ->when(['Table.column_b' => 'foo'])
<add> ->then(2)
<add> ->else(3);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE WHEN Table.column_a = :c0 THEN :c1 WHEN Table.column_b = :c2 THEN :c3 ELSE :c4 END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 123,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 'foo',
<add> 'type' => 'string',
<add> 'placeholder' => 'c2',
<add> ],
<add> ':c3' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c3',
<add> ],
<add> ':c4' => [
<add> 'value' => 3,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c4',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testWhenCallableArrayValueInheritTypeMap(): void
<add> {
<add> $typeMap = new TypeMap([
<add> 'Table.column_a' => 'boolean',
<add> 'Table.column_b' => 'string',
<add> ]);
<add>
<add> $expression = (new CaseStatementExpression($typeMap))
<add> ->when(function (WhenThenExpressionInterface $whenThen) {
<add> return $whenThen
<add> ->when(['Table.column_a' => true])
<add> ->then(1);
<add> })
<add> ->when(function (WhenThenExpressionInterface $whenThen) {
<add> return $whenThen
<add> ->when(['Table.column_b' => 'foo'])
<add> ->then(2);
<add> })
<add> ->else(3);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE WHEN Table.column_a = :c0 THEN :c1 WHEN Table.column_b = :c2 THEN :c3 ELSE :c4 END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => true,
<add> 'type' => 'boolean',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 'foo',
<add> 'type' => 'string',
<add> 'placeholder' => 'c2',
<add> ],
<add> ':c3' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c3',
<add> ],
<add> ':c4' => [
<add> 'value' => 3,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c4',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testWhenCallableArrayValueWithExplicitTypes(): void
<add> {
<add> $typeMap = new TypeMap([
<add> 'Table.column_a' => 'boolean',
<add> 'Table.column_b' => 'string',
<add> ]);
<add>
<add> $expression = (new CaseStatementExpression($typeMap))
<add> ->when(function (WhenThenExpressionInterface $whenThen) {
<add> return $whenThen
<add> ->when(['Table.column_a' => 123], ['Table.column_a' => 'integer'])
<add> ->then(1);
<add> })
<add> ->when(function (WhenThenExpressionInterface $whenThen) {
<add> return $whenThen
<add> ->when(['Table.column_b' => 'foo'])
<add> ->then(2);
<add> })
<add> ->else(3);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE WHEN Table.column_a = :c0 THEN :c1 WHEN Table.column_b = :c2 THEN :c3 ELSE :c4 END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 123,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 'foo',
<add> 'type' => 'string',
<add> 'placeholder' => 'c2',
<add> ],
<add> ':c3' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c3',
<add> ],
<add> ':c4' => [
<add> 'value' => 3,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c4',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testWhenArrayValueRequiresArrayTypeValue(): void
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage(
<add> 'When using an array for the `$when` argument, the `$type` ' .
<add> 'argument must be an array too, `string` given.'
<add> );
<add>
<add> (new CaseStatementExpression())
<add> ->when(['Table.column' => 123], 'integer')
<add> ->then(1);
<add> }
<add>
<add> public function testWhenNonArrayValueRequiresStringTypeValue(): void
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage(
<add> 'When using a non-array value for the `$when` argument, ' .
<add> 'the `$type` argument must be a string, `array` given.'
<add> );
<add>
<add> (new CaseStatementExpression())
<add> ->when(123, ['Table.column' => 'integer'])
<add> ->then(1);
<add> }
<add>
<add> public function testInternalTypeMapChangesAreNonPersistent(): void
<add> {
<add> $typeMap = new TypeMap([
<add> 'Table.column' => 'integer',
<add> ]);
<add>
<add> $expression = (new CaseStatementExpression($typeMap))
<add> ->when(['Table.column' => 123])
<add> ->then(1)
<add> ->when(['Table.column' => 'foo'], ['Table.column' => 'string'])
<add> ->then('bar')
<add> ->when(['Table.column' => 456])
<add> ->then(2);
<add>
<add> $valueBinder = new ValueBinder();
<add> $expression->sql($valueBinder);
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 123,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 'foo',
<add> 'type' => 'string',
<add> 'placeholder' => 'c2',
<add> ],
<add> ':c3' => [
<add> 'value' => 'bar',
<add> 'type' => 'string',
<add> 'placeholder' => 'c3',
<add> ],
<add> ':c4' => [
<add> 'value' => 456,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c4',
<add> ],
<add> ':c5' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c5',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add>
<add> $this->assertSame($typeMap, $expression->getTypeMap());
<add> }
<add>
<add> // endregion
<add>
<add> // region SQL injections
<add>
<add> public function testSqlInjectionViaTypedCaseValueIsNotPossible(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->value('1 THEN 1 END; DELETE * FROM foo; --', 'integer')
<add> ->when(1)
<add> ->then(2);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c2',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testSqlInjectionViaUntypedCaseValueIsNotPossible(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->value('1 THEN 1 END; DELETE * FROM foo; --')
<add> ->when(1)
<add> ->then(2);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
<add> 'type' => 'string',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c2',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testSqlInjectionViaTypedWhenValueIsNotPossible(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when('1 THEN 1 END; DELETE * FROM foo; --', 'integer')
<add> ->then(1);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE WHEN :c0 THEN :c1 ELSE NULL END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testSqlInjectionViaTypedWhenArrayValueIsNotPossible(): void
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage(
<add> 'When using an array for the `$when` argument, the `$type` ' .
<add> 'argument must be an array too, `string` given.'
<add> );
<add>
<add> (new CaseStatementExpression())
<add> ->when(['1 THEN 1 END; DELETE * FROM foo; --' => '123'], 'integer')
<add> ->then(1);
<add> }
<add>
<add> public function testSqlInjectionViaUntypedWhenValueIsNotPossible()
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when('1 THEN 1 END; DELETE * FROM foo; --')
<add> ->then(1);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE WHEN :c0 THEN :c1 ELSE NULL END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
<add> 'type' => 'string',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testSqlInjectionViaUntypedWhenArrayValueIsPossible(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(['1 THEN 1 END; DELETE * FROM foo; --' => '123'])
<add> ->then(1);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE WHEN 1 THEN 1 END; DELETE * FROM foo; -- :c0 THEN :c1 ELSE NULL END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => '123',
<add> 'type' => null,
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testSqlInjectionViaTypedThenValueIsNotPossible(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->value(1)
<add> ->when(2)
<add> ->then('1 THEN 1 END; DELETE * FROM foo; --', 'integer');
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
<add> 'type' => 'integer',
<add> 'placeholder' => 'c2',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testSqlInjectionViaUntypedThenValueIsNotPossible(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->value(1)
<add> ->when(2)
<add> ->then('1 THEN 1 END; DELETE * FROM foo; --');
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
<add> 'type' => 'string',
<add> 'placeholder' => 'c2',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testSqlInjectionViaTypedElseValueIsNotPossible(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->value(1)
<add> ->when(2)
<add> ->then(3)
<add> ->else('1 THEN 1 END; DELETE * FROM foo; --', 'integer');
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE :c0 WHEN :c1 THEN :c2 ELSE :c3 END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 3,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c2',
<add> ],
<add> ':c3' => [
<add> 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
<add> 'type' => 'integer',
<add> 'placeholder' => 'c3',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> public function testSqlInjectionViaUntypedElseValueIsNotPossible(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->value(1)
<add> ->when(2)
<add> ->then(3)
<add> ->else('1 THEN 1 END; DELETE * FROM foo; --');
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE :c0 WHEN :c1 THEN :c2 ELSE :c3 END',
<add> $sql
<add> );
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 3,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c2',
<add> ],
<add> ':c3' => [
<add> 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
<add> 'type' => 'string',
<add> 'placeholder' => 'c3',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add>
<add> // endregion
<add>
<add> // region Getters
<add>
<add> public function testGetValue(): void
<add> {
<add> $expression = new CaseStatementExpression();
<add>
<add> $this->assertNull($expression->getValue());
<add>
<add> $expression
<add> ->value(1)
<add> ->when(1)
<add> ->then(2);
<add>
<add> $this->assertSame(1, $expression->getValue());
<add> }
<add>
<add> public function testGetValueType(): void
<add> {
<add> $expression = new CaseStatementExpression();
<add>
<add> $this->assertNull($expression->getValueType());
<add>
<add> $expression->value(1);
<add>
<add> $this->assertSame('integer', $expression->getValueType());
<add> }
<add>
<add> public function testGetWhen(): void
<add> {
<add> $when = ['Table.column' => true];
<add>
<add> $expression = new CaseStatementExpression();
<add> $this->assertSame([], $expression->getWhen());
<add>
<add> $expression
<add> ->when($when)
<add> ->then(1);
<add>
<add> $this->assertCount(1, $expression->getWhen());
<add> $this->assertInstanceOf(WhenThenExpressionInterface::class, $expression->getWhen()[0]);
<add> }
<add>
<add> public function testWhenArrayValueGetWhen(): void
<add> {
<add> $when = ['Table.column' => true];
<add>
<add> $expression = new CaseStatementExpression();
<add> $this->assertSame([], $expression->getWhen());
<add>
<add> $expression
<add> ->when($when)
<add> ->then(1);
<add>
<add> $this->assertEquals(
<add> new QueryExpression($when),
<add> $expression->getWhen()[0]->getWhen()
<add> );
<add> }
<add>
<add> public function testWhenNonArrayValueGetWhen(): void
<add> {
<add> $expression = new CaseStatementExpression();
<add> $this->assertSame([], $expression->getWhen());
<add>
<add> $expression
<add> ->when(1)
<add> ->then(2);
<add>
<add> $this->assertSame(1, $expression->getWhen()[0]->getWhen());
<add> }
<add>
<add> public function testWhenGetWhenType(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(function (WhenThenExpressionInterface $whenThen) {
<add> return $whenThen;
<add> });
<add>
<add> $this->assertNull($expression->getWhen()[0]->getWhenType());
<add>
<add> $expression->getWhen()[0]->when(1);
<add>
<add> $this->assertSame('integer', $expression->getWhen()[0]->getWhenType());
<add>
<add> $types = [
<add> 'Table.column' => 'boolean',
<add> ];
<add> $expression->getWhen()[0]->when(['Table.column' => true], $types);
<add>
<add> $this->assertSame($types, $expression->getWhen()[0]->getWhenType());
<add> }
<add>
<add> public function testWhenGetThen(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(function (WhenThenExpressionInterface $whenThen) {
<add> return $whenThen;
<add> });
<add>
<add> $this->assertNull($expression->getWhen()[0]->getThen());
<add>
<add> $expression->getWhen()[0]->then(1);
<add>
<add> $this->assertSame(1, $expression->getWhen()[0]->getThen());
<add> }
<add>
<add> public function testWhenGetThenType(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(function (WhenThenExpressionInterface $whenThen) {
<add> return $whenThen;
<add> });
<add>
<add> $this->assertNull($expression->getWhen()[0]->getThenType());
<add>
<add> $expression->getWhen()[0]->then(1);
<add>
<add> $this->assertSame('integer', $expression->getWhen()[0]->getThenType());
<add> }
<add>
<add> public function testGetElse(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column' => true])
<add> ->then(1)
<add> ->else(2);
<add>
<add> $this->assertSame(2, $expression->getElse());
<add> }
<add>
<add> public function testGetElseType(): void
<add> {
<add> $expression = new CaseStatementExpression();
<add>
<add> $this->assertNull($expression->getElseType());
<add>
<add> $expression->else(1);
<add>
<add> $this->assertSame('integer', $expression->getElseType());
<add> }
<add>
<add> // endregion
<add>
<add> // region Order based syntax
<add>
<add> public function testWhenThenElse(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column_a' => true, 'Table.column_b IS' => null])
<add> ->then(1)
<add> ->when(['Table.column_c' => true, 'Table.column_d IS NOT' => null])
<add> ->then(2)
<add> ->else(3);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE ' .
<add> 'WHEN (Table.column_a = :c0 AND (Table.column_b) IS NULL) THEN :c1 ' .
<add> 'WHEN (Table.column_c = :c2 AND (Table.column_d) IS NOT NULL) THEN :c3 ' .
<add> 'ELSE :c4 ' .
<add> 'END',
<add> $sql
<add> );
<add> }
<add>
<add> public function testWhenBeforeClosingThenFails(): void
<add> {
<add> $this->expectException(LogicException::class);
<add> $this->expectExceptionMessage(
<add> 'Cannot add new `WHEN` value while an open `when()` buffer is present, ' .
<add> 'it must first be closed using `then()`.'
<add> );
<add>
<add> (new CaseStatementExpression())
<add> ->when(['Table.column_a' => true])
<add> ->when(['Table.column_b' => true]);
<add> }
<add>
<add> public function testElseBeforeClosingThenFails(): void
<add> {
<add> $this->expectException(LogicException::class);
<add> $this->expectExceptionMessage(
<add> 'Cannot set `ELSE` value when an open `when()` buffer is present, ' .
<add> 'it must first be closed using `then()`.'
<add> );
<add>
<add> (new CaseStatementExpression())
<add> ->when(['Table.column' => true])
<add> ->else(1);
<add> }
<add>
<add> public function testThenBeforeOpeningWhenFails(): void
<add> {
<add> $this->expectException(LogicException::class);
<add> $this->expectExceptionMessage(
<add> 'There is no `when()` buffer present, ' .
<add> 'you must first open one before calling `then()`.'
<add> );
<add>
<add> (new CaseStatementExpression())
<add> ->then(1);
<add> }
<add>
<add> // endregion
<add>
<add> // region Callable syntax
<add>
<add> public function testWhenCallables(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(function (WhenThenExpressionInterface $whenThen) {
<add> return $whenThen
<add> ->when([
<add> 'Table.column_a' => true,
<add> 'Table.column_b IS' => null,
<add> ])
<add> ->then(1);
<add> })
<add> ->when(function (WhenThenExpressionInterface $whenThen) {
<add> return $whenThen
<add> ->when([
<add> 'Table.column_c' => true,
<add> 'Table.column_d IS NOT' => null,
<add> ])
<add> ->then(2);
<add> })
<add> ->else(3);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE ' .
<add> 'WHEN (Table.column_a = :c0 AND (Table.column_b) IS NULL) THEN :c1 ' .
<add> 'WHEN (Table.column_c = :c2 AND (Table.column_d) IS NOT NULL) THEN :c3 ' .
<add> 'ELSE :c4 ' .
<add> 'END',
<add> $sql
<add> );
<add> }
<add>
<add> public function testWhenCallablesWithCustomWhenThenExpressions(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(function () {
<add> return (new CustomWhenThenExpression())
<add> ->when([
<add> 'Table.column_a' => true,
<add> 'Table.column_b IS' => null,
<add> ])
<add> ->then(1);
<add> })
<add> ->when(function () {
<add> return (new CustomWhenThenExpression())
<add> ->when([
<add> 'Table.column_c' => true,
<add> 'Table.column_d IS NOT' => null,
<add> ])
<add> ->then(2);
<add> })
<add> ->else(3);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE ' .
<add> 'WHEN (Table.column_a = :c0 AND (Table.column_b) IS NULL) THEN :c1 ' .
<add> 'WHEN (Table.column_c = :c2 AND (Table.column_d) IS NOT NULL) THEN :c3 ' .
<add> 'ELSE :c4 ' .
<add> 'END',
<add> $sql
<add> );
<add> }
<add>
<add> public function testWhenCallablesWithInvalidReturnTypeFails(): void
<add> {
<add> $this->expectException(LogicException::class);
<add> $this->expectExceptionMessage(
<add> '`when()` callables must return an instance of ' .
<add> '`\Cake\Database\Expression\WhenThenExpressionInterface`, `NULL` given.'
<add> );
<add>
<add> $this->deprecated(function () {
<add> (new CaseStatementExpression())
<add> ->when(function () {
<add> return null;
<add> });
<add> });
<add> }
<add>
<add> // endregion
<add>
<add> // region Self-contained values
<add>
<add> public function testSelfContainedWhenThenExpressions(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(
<add> (new WhenThenExpression())
<add> ->when([
<add> 'Table.column_a' => true,
<add> 'Table.column_b IS' => null,
<add> ])
<add> ->then(1)
<add> )
<add> ->when(
<add> (new WhenThenExpression())
<add> ->when([
<add> 'Table.column_c' => true,
<add> 'Table.column_d IS NOT' => null,
<add> ])
<add> ->then(2)
<add> )
<add> ->else(3);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE ' .
<add> 'WHEN (Table.column_a = :c0 AND (Table.column_b) IS NULL) THEN :c1 ' .
<add> 'WHEN (Table.column_c = :c2 AND (Table.column_d) IS NOT NULL) THEN :c3 ' .
<add> 'ELSE :c4 ' .
<add> 'END',
<add> $sql
<add> );
<add> }
<add>
<add> public function testSelfContainedCustomWhenThenExpressions(): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(
<add> (new CustomWhenThenExpression())
<add> ->when([
<add> 'Table.column_a' => true,
<add> 'Table.column_b IS' => null,
<add> ])
<add> ->then(1)
<add> )
<add> ->when(
<add> (new CustomWhenThenExpression())
<add> ->when([
<add> 'Table.column_c' => true,
<add> 'Table.column_d IS NOT' => null,
<add> ])
<add> ->then(2)
<add> )
<add> ->else(3);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add> $this->assertSame(
<add> 'CASE ' .
<add> 'WHEN (Table.column_a = :c0 AND (Table.column_b) IS NULL) THEN :c1 ' .
<add> 'WHEN (Table.column_c = :c2 AND (Table.column_d) IS NOT NULL) THEN :c3 ' .
<add> 'ELSE :c4 ' .
<add> 'END',
<add> $sql
<add> );
<add> }
<add>
<add> // endregion
<add>
<add> // region Incomplete states
<add>
<add> public function testCompilingEmptyCaseExpressionFails(): void
<add> {
<add> $this->expectException(LogicException::class);
<add> $this->expectExceptionMessage(
<add> 'Cannot compile incomplete `\Cake\Database\Expression\CaseExpressionInterface` ' .
<add> 'expression, there are no `WHEN ... THEN ...` statements.'
<add> );
<add>
<add> $this->deprecated(function () {
<add> (new CaseStatementExpression())->sql(new ValueBinder());
<add> });
<add> }
<add>
<add> public function testCompilingNonClosedWhenFails(): void
<add> {
<add> $this->expectException(LogicException::class);
<add> $this->expectExceptionMessage(
<add> 'Cannot compile incomplete `\Cake\Database\Expression\CaseExpressionInterface` ' .
<add> 'expression, there is an open `when()` buffer present that must be closed using `then()`.'
<add> );
<add>
<add> $this->deprecated(function () {
<add> (new CaseStatementExpression())
<add> ->when(['Table.column' => true])
<add> ->sql(new ValueBinder());
<add> });
<add> }
<add>
<add> public function testCompilingWhenThenExpressionWithMissingWhenFails(): void
<add> {
<add> $this->expectException(LogicException::class);
<add> $this->expectExceptionMessage(
<add> 'Cannot compile incomplete `\Cake\Database\Expression\WhenThenExpressionInterface`, ' .
<add> 'the value for `WHEN` is missing.'
<add> );
<add>
<add> $this->deprecated(function () {
<add> (new CaseStatementExpression())
<add> ->when(function (WhenThenExpressionInterface $whenThen) {
<add> return $whenThen->then(1);
<add> })
<add> ->sql(new ValueBinder());
<add> });
<add> }
<add>
<add> public function testCompilingWhenThenExpressionWithMissingThenFails(): void
<add> {
<add> $this->expectException(LogicException::class);
<add> $this->expectExceptionMessage(
<add> 'Cannot compile incomplete `\Cake\Database\Expression\WhenThenExpressionInterface`, ' .
<add> 'the value for `THEN` is missing.'
<add> );
<add>
<add> $this->deprecated(function () {
<add> (new CaseStatementExpression())
<add> ->when(function (WhenThenExpressionInterface $whenThen) {
<add> return $whenThen->when(1);
<add> })
<add> ->sql(new ValueBinder());
<add> });
<add> }
<add>
<add> // endregion
<add>
<add> // region Valid values
<add>
<add> public function validCaseValuesDataProvider(): array
<add> {
<add> $values = [];
<add> $this->deprecated(function () use (&$values) {
<add> $values = [
<add> [null, 'NULL', null],
<add> ['0', null, 'string'],
<add> [0, null, 'integer'],
<add> [0.0, null, 'float'],
<add> ['foo', null, 'string'],
<add> [true, null, 'boolean'],
<add> [Date::now(), null, 'date'],
<add> [FrozenDate::now(), null, 'date'],
<add> [ChronosDate::now(), null, 'date'],
<add> [ChronosMutableDate::now(), null, 'date'],
<add> [Time::now(), null, 'datetime'],
<add> [FrozenTime::now(), null, 'datetime'],
<add> [Chronos::now(), null, 'datetime'],
<add> [new IdentifierExpression('Table.column'), 'Table.column', null],
<add> [new QueryExpression('Table.column'), 'Table.column', null],
<add> [ConnectionManager::get('test')->newQuery()->select('a'), '(SELECT a)', null],
<add> [new TestObjectWithToString(), null, 'string'],
<add> [new stdClass(), null, null],
<add> ];
<add> });
<add>
<add> return $values;
<add> }
<add>
<add> /**
<add> * @dataProvider validCaseValuesDataProvider
<add> * @param mixed $value The case value.
<add> * @param string|null $sqlValue The expected SQL string value.
<add> * @param string|null $type The expected bound type.
<add> */
<add> public function testValidCaseValue($value, ?string $sqlValue, ?string $type): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->value($value)
<add> ->when(1)
<add> ->then(2);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add>
<add> if ($sqlValue) {
<add> $this->assertEqualsSql(
<add> "CASE $sqlValue WHEN :c0 THEN :c1 ELSE NULL END",
<add> $sql
<add> );
<add>
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> } else {
<add> $this->assertEqualsSql(
<add> 'CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END',
<add> $sql
<add> );
<add>
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => $value,
<add> 'type' => $type,
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c2',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add> }
<add>
<add> public function validWhenValuesSimpleCaseDataProvider(): array
<add> {
<add> $values = [];
<add> $this->deprecated(function () use (&$values) {
<add> $values = [
<add> ['0', null, 'string'],
<add> [0, null, 'integer'],
<add> [0.0, null, 'float'],
<add> ['foo', null, 'string'],
<add> [true, null, 'boolean'],
<add> [new stdClass(), null, null],
<add> [new TestObjectWithToString(), null, 'string'],
<add> [Date::now(), null, 'date'],
<add> [FrozenDate::now(), null, 'date'],
<add> [ChronosDate::now(), null, 'date'],
<add> [ChronosMutableDate::now(), null, 'date'],
<add> [Time::now(), null, 'datetime'],
<add> [FrozenTime::now(), null, 'datetime'],
<add> [Chronos::now(), null, 'datetime'],
<add> [
<add> new IdentifierExpression('Table.column'),
<add> 'CASE :c0 WHEN Table.column THEN :c1 ELSE NULL END',
<add> [
<add> ':c0' => [
<add> 'value' => true,
<add> 'type' => 'boolean',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ],
<add> ],
<add> [
<add> new QueryExpression('Table.column'),
<add> 'CASE :c0 WHEN Table.column THEN :c1 ELSE NULL END',
<add> [
<add> ':c0' => [
<add> 'value' => true,
<add> 'type' => 'boolean',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ],
<add> ],
<add> [
<add> ConnectionManager::get('test')->newQuery()->select('a'),
<add> 'CASE :c0 WHEN (SELECT a) THEN :c1 ELSE NULL END',
<add> [
<add> ':c0' => [
<add> 'value' => true,
<add> 'type' => 'boolean',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ],
<add> ],
<add> [
<add> [
<add> 'Table.column_a' => 1,
<add> 'Table.column_b' => 'foo',
<add> ],
<add> 'CASE :c0 WHEN (Table.column_a = :c1 AND Table.column_b = :c2) THEN :c3 ELSE NULL END',
<add> [
<add> ':c0' => [
<add> 'value' => true,
<add> 'type' => 'boolean',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 'foo',
<add> 'type' => 'string',
<add> 'placeholder' => 'c2',
<add> ],
<add> ':c3' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c3',
<add> ],
<add> ],
<add> ],
<add> ];
<add> });
<add>
<add> return $values;
<add> }
<add>
<add> /**
<add> * @dataProvider validWhenValuesSimpleCaseDataProvider
<add> * @param mixed $value The when value.
<add> * @param string|null $expectedSql The expected SQL string.
<add> * @param array|string|null $typeOrBindings The expected bound type(s).
<add> */
<add> public function testValidWhenValueSimpleCase($value, ?string $expectedSql, $typeOrBindings = null): void
<add> {
<add> $typeMap = new TypeMap([
<add> 'Table.column_a' => 'integer',
<add> 'Table.column_b' => 'string',
<add> ]);
<add> $expression = (new CaseStatementExpression($typeMap))
<add> ->value(true)
<add> ->when($value)
<add> ->then(2);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add>
<add> if ($expectedSql) {
<add> $this->assertEqualsSql($expectedSql, $sql);
<add> $this->assertSame($typeOrBindings, $valueBinder->bindings());
<add> } else {
<add> $this->assertEqualsSql('CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END', $sql);
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => true,
<add> 'type' => 'boolean',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => $value,
<add> 'type' => $typeOrBindings,
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c2',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add> }
<add>
<add> public function validWhenValuesSearchedCaseDataProvider(): array
<add> {
<add> $values = [];
<add> $this->deprecated(function () use (&$values) {
<add> $values = [
<add> ['0', null, 'string'],
<add> [0, null, 'integer'],
<add> [0.0, null, 'float'],
<add> ['foo', null, 'string'],
<add> [true, null, 'boolean'],
<add> [new stdClass(), null, null],
<add> [new TestObjectWithToString(), null, 'string'],
<add> [Date::now(), null, 'date'],
<add> [FrozenDate::now(), null, 'date'],
<add> [ChronosDate::now(), null, 'date'],
<add> [ChronosMutableDate::now(), null, 'date'],
<add> [Time::now(), null, 'datetime'],
<add> [FrozenTime::now(), null, 'datetime'],
<add> [Chronos::now(), null, 'datetime'],
<add> [
<add> new IdentifierExpression('Table.column'),
<add> 'CASE WHEN Table.column THEN :c0 ELSE NULL END',
<add> [
<add> ':c0' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ],
<add> ],
<add> [
<add> new QueryExpression('Table.column'),
<add> 'CASE WHEN Table.column THEN :c0 ELSE NULL END',
<add> [
<add> ':c0' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ],
<add> ],
<add> [
<add> ConnectionManager::get('test')->newQuery()->select('a'),
<add> 'CASE WHEN (SELECT a) THEN :c0 ELSE NULL END',
<add> [
<add> ':c0' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ],
<add> ],
<add> [
<add> [
<add> 'Table.column_a' => 1,
<add> 'Table.column_b' => 'foo',
<add> ],
<add> 'CASE WHEN (Table.column_a = :c0 AND Table.column_b = :c1) THEN :c2 ELSE NULL END',
<add> [
<add> ':c0' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 'foo',
<add> 'type' => 'string',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c2',
<add> ],
<add> ],
<add> ],
<add> ];
<add> });
<add>
<add> return $values;
<add> }
<add>
<add> /**
<add> * @dataProvider validWhenValuesSearchedCaseDataProvider
<add> * @param mixed $value The when value.
<add> * @param string|null $expectedSql The expected SQL string.
<add> * @param array|string|null $typeOrBindings The expected bound type(s).
<add> */
<add> public function testValidWhenValueSearchedCase($value, ?string $expectedSql, $typeOrBindings = null): void
<add> {
<add> $typeMap = new TypeMap([
<add> 'Table.column_a' => 'integer',
<add> 'Table.column_b' => 'string',
<add> ]);
<add> $expression = (new CaseStatementExpression($typeMap))
<add> ->when($value)
<add> ->then(2);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add>
<add> if ($expectedSql) {
<add> $this->assertEqualsSql($expectedSql, $sql);
<add> $this->assertSame($typeOrBindings, $valueBinder->bindings());
<add> } else {
<add> $this->assertEqualsSql('CASE WHEN :c0 THEN :c1 ELSE NULL END', $sql);
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => $value,
<add> 'type' => $typeOrBindings,
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add> }
<add>
<add> public function validThenValuesDataProvider(): array
<add> {
<add> $values = [];
<add> $this->deprecated(function () use (&$values) {
<add> $values = [
<add> [null, 'NULL', null],
<add> ['0', null, 'string'],
<add> [0, null, 'integer'],
<add> [0.0, null, 'float'],
<add> ['foo', null, 'string'],
<add> [true, null, 'boolean'],
<add> [Date::now(), null, 'date'],
<add> [FrozenDate::now(), null, 'date'],
<add> [ChronosDate::now(), null, 'date'],
<add> [ChronosMutableDate::now(), null, 'date'],
<add> [Time::now(), null, 'datetime'],
<add> [FrozenTime::now(), null, 'datetime'],
<add> [Chronos::now(), null, 'datetime'],
<add> [new IdentifierExpression('Table.column'), 'Table.column', null],
<add> [new QueryExpression('Table.column'), 'Table.column', null],
<add> [ConnectionManager::get('test')->newQuery()->select('a'), '(SELECT a)', null],
<add> [new TestObjectWithToString(), null, 'string'],
<add> [new stdClass(), null, null],
<add> ];
<add> });
<add>
<add> return $values;
<add> }
<add>
<add> /**
<add> * @dataProvider validThenValuesDataProvider
<add> * @param mixed $value The then value.
<add> * @param string|null $sqlValue The expected SQL string value.
<add> * @param string|null $type The expected bound type.
<add> */
<add> public function testValidThenValue($value, ?string $sqlValue, ?string $type): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(1)
<add> ->then($value);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add>
<add> if ($sqlValue) {
<add> $this->assertEqualsSql(
<add> "CASE WHEN :c0 THEN $sqlValue ELSE NULL END",
<add> $sql
<add> );
<add>
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> } else {
<add> $this->assertEqualsSql(
<add> 'CASE WHEN :c0 THEN :c1 ELSE NULL END',
<add> $sql
<add> );
<add>
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => $value,
<add> 'type' => $type,
<add> 'placeholder' => 'c1',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add> }
<add>
<add> public function validElseValuesDataProvider(): array
<add> {
<add> $values = [];
<add> $this->deprecated(function () use (&$values) {
<add> $values = [
<add> [null, 'NULL', null],
<add> ['0', null, 'string'],
<add> [0, null, 'integer'],
<add> [0.0, null, 'float'],
<add> ['foo', null, 'string'],
<add> [true, null, 'boolean'],
<add> [Date::now(), null, 'date'],
<add> [FrozenDate::now(), null, 'date'],
<add> [ChronosDate::now(), null, 'date'],
<add> [ChronosMutableDate::now(), null, 'date'],
<add> [Time::now(), null, 'datetime'],
<add> [FrozenTime::now(), null, 'datetime'],
<add> [Chronos::now(), null, 'datetime'],
<add> [new IdentifierExpression('Table.column'), 'Table.column', null],
<add> [new QueryExpression('Table.column'), 'Table.column', null],
<add> [ConnectionManager::get('test')->newQuery()->select('a'), '(SELECT a)', null],
<add> [new TestObjectWithToString(), null, 'string'],
<add> [new stdClass(), null, null],
<add> ];
<add> });
<add>
<add> return $values;
<add> }
<add>
<add> /**
<add> * @dataProvider validElseValuesDataProvider
<add> * @param mixed $value The else value.
<add> * @param string|null $sqlValue The expected SQL string value.
<add> * @param string|null $type The expected bound type.
<add> */
<add> public function testValidElseValue($value, ?string $sqlValue, ?string $type): void
<add> {
<add> $expression = (new CaseStatementExpression())
<add> ->when(1)
<add> ->then(2)
<add> ->else($value);
<add>
<add> $valueBinder = new ValueBinder();
<add> $sql = $expression->sql($valueBinder);
<add>
<add> if ($sqlValue) {
<add> $this->assertEqualsSql(
<add> "CASE WHEN :c0 THEN :c1 ELSE $sqlValue END",
<add> $sql
<add> );
<add>
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> } else {
<add> $this->assertEqualsSql(
<add> 'CASE WHEN :c0 THEN :c1 ELSE :c2 END',
<add> $sql
<add> );
<add>
<add> $this->assertSame(
<add> [
<add> ':c0' => [
<add> 'value' => 1,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c0',
<add> ],
<add> ':c1' => [
<add> 'value' => 2,
<add> 'type' => 'integer',
<add> 'placeholder' => 'c1',
<add> ],
<add> ':c2' => [
<add> 'value' => $value,
<add> 'type' => $type,
<add> 'placeholder' => 'c2',
<add> ],
<add> ],
<add> $valueBinder->bindings()
<add> );
<add> }
<add> }
<add>
<add> // endregion
<add>
<add> // region Invalid values
<add>
<add> public function invalidCaseValuesDataProvider(): array
<add> {
<add> $res = fopen('data:text/plain,123', 'rb');
<add> fclose($res);
<add>
<add> return [
<add> [[], 'array'],
<add> [
<add> function () {
<add> },
<add> 'Closure',
<add> ],
<add> [$res, 'resource (closed)'],
<add> ];
<add> }
<add>
<add> /**
<add> * @dataProvider invalidCaseValuesDataProvider
<add> * @param mixed $value The case value.
<add> * @param string $typeName The expected error type name.
<add> */
<add> public function testInvalidCaseValue($value, string $typeName): void
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage(
<add> 'The `$value` argument must be either `null`, a scalar value, an object, ' .
<add> "or an instance of `\\Cake\\Database\\ExpressionInterface`, `$typeName` given."
<add> );
<add>
<add> (new CaseStatementExpression())
<add> ->value($value);
<add> }
<add>
<add> public function invalidWhenValueDataProvider(): array
<add> {
<add> $res = fopen('data:text/plain,123', 'rb');
<add> fclose($res);
<add>
<add> return [
<add> [null, 'NULL'],
<add> [[], '[]'],
<add> [$res, 'resource (closed)'],
<add> ];
<add> }
<add>
<add> /**
<add> * @dataProvider invalidWhenValueDataProvider
<add> * @param mixed $value The when value.
<add> * @param string $typeName The expected error type name.
<add> */
<add> public function testInvalidWhenValue($value, string $typeName): void
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage(
<add> 'The `$when` argument must be either a non-empty array, a scalar value, an object, ' .
<add> "or an instance of `\\Cake\\Database\\ExpressionInterface`, `$typeName` given."
<add> );
<add>
<add> (new CaseStatementExpression())
<add> ->when($value)
<add> ->then(1);
<add> }
<add>
<add> public function invalidWhenTypeDataProvider(): array
<add> {
<add> $res = fopen('data:text/plain,123', 'rb');
<add> fclose($res);
<add>
<add> return [
<add> [1, 'integer'],
<add> [1.0, 'double'],
<add> [new stdClass(), 'stdClass'],
<add> [
<add> function () {
<add> },
<add> 'Closure',
<add> ],
<add> [$res, 'resource (closed)'],
<add> ];
<add> }
<add>
<add> /**
<add> * @dataProvider invalidWhenTypeDataProvider
<add> * @param mixed $type The when type.
<add> * @param string $typeName The expected error type name.
<add> */
<add> public function testInvalidWhenType($type, string $typeName): void
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage(
<add> "The `\$type` argument must be either an array, a string, or `null`, `$typeName` given."
<add> );
<add>
<add> (new CaseStatementExpression())
<add> ->when(1, $type)
<add> ->then(1);
<add> }
<add>
<add> public function invalidThenValueDataProvider(): array
<add> {
<add> $res = fopen('data:text/plain,123', 'rb');
<add> fclose($res);
<add>
<add> return [
<add> [[], 'array'],
<add> [
<add> function () {
<add> },
<add> 'Closure',
<add> ],
<add> [$res, 'resource (closed)'],
<add> ];
<add> }
<add>
<add> /**
<add> * @dataProvider invalidThenValueDataProvider
<add> * @param mixed $value The then value.
<add> * @param string $typeName The expected error type name.
<add> */
<add> public function testInvalidThenValue($value, string $typeName): void
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage(
<add> 'The `$result` argument must be either `null`, a scalar value, an object, ' .
<add> "or an instance of `\\Cake\\Database\\ExpressionInterface`, `$typeName` given."
<add> );
<add>
<add> (new CaseStatementExpression())
<add> ->when(1)
<add> ->then($value);
<add> }
<add>
<add> public function invalidThenTypeDataProvider(): array
<add> {
<add> $res = fopen('data:text/plain,123', 'rb');
<add> fclose($res);
<add>
<add> return [
<add> [1],
<add> [1.0],
<add> [new stdClass()],
<add> [
<add> function () {
<add> },
<add> ],
<add> [$res, 'resource (closed)'],
<add> ];
<add> }
<add>
<add> /**
<add> * @dataProvider invalidThenTypeDataProvider
<add> * @param mixed $type The then type.
<add> */
<add> public function testInvalidThenType($type): void
<add> {
<add> $this->expectException(TypeError::class);
<add>
<add> (new CaseStatementExpression())
<add> ->when(1)
<add> ->then(1, $type);
<add> }
<add>
<add> public function invalidElseValueDataProvider(): array
<add> {
<add> $res = fopen('data:text/plain,123', 'rb');
<add> fclose($res);
<add>
<add> return [
<add> [[], 'array'],
<add> [
<add> function () {
<add> },
<add> 'Closure',
<add> ],
<add> [$res, 'resource (closed)'],
<add> ];
<add> }
<add>
<add> /**
<add> * @dataProvider invalidElseValueDataProvider
<add> * @param mixed $value The else value.
<add> * @param string $typeName The expected error type name.
<add> */
<add> public function testInvalidElseValue($value, string $typeName): void
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage(
<add> 'The `$result` argument must be either `null`, a scalar value, an object, ' .
<add> "or an instance of `\\Cake\\Database\\ExpressionInterface`, `$typeName` given."
<add> );
<add>
<add> (new CaseStatementExpression())
<add> ->when(1)
<add> ->then(1)
<add> ->else($value);
<add> }
<add>
<add> public function invalidElseTypeDataProvider(): array
<add> {
<add> $res = fopen('data:text/plain,123', 'rb');
<add> fclose($res);
<add>
<add> return [
<add> [1],
<add> [1.0],
<add> [new stdClass()],
<add> [
<add> function () {
<add> },
<add> 'Closure',
<add> ],
<add> [$res, 'resource (closed)'],
<add> ];
<add> }
<add>
<add> /**
<add> * @dataProvider invalidElseTypeDataProvider
<add> * @param mixed $type The else type.
<add> */
<add> public function testInvalidElseType($type): void
<add> {
<add> $this->expectException(TypeError::class);
<add>
<add> (new CaseStatementExpression())
<add> ->when(1)
<add> ->then(1)
<add> ->else(1, $type);
<add> }
<add>
<add> // endregion
<add>
<add> // region Traversal
<add>
<add> public function testTraverse(): void
<add> {
<add> $value = new IdentifierExpression('Table.column');
<add> $conditionsA = ['Table.column_a' => true, 'Table.column_b IS' => null];
<add> $resultA = new QueryExpression('1');
<add> $conditionsB = ['Table.column_c' => true, 'Table.column_d IS NOT' => null];
<add> $resultB = new QueryExpression('2');
<add> $else = new QueryExpression('3');
<add>
<add> $expression = (new CaseStatementExpression())
<add> ->value($value)
<add> ->when($conditionsA)
<add> ->then($resultA)
<add> ->when($conditionsB)
<add> ->then($resultB)
<add> ->else($else);
<add>
<add> $expressions = [];
<add> $expression->traverse(function ($expression) use (&$expressions) {
<add> $expressions[] = $expression;
<add> });
<add>
<add> $this->assertCount(14, $expressions);
<add> $this->assertInstanceOf(IdentifierExpression::class, $expressions[0]);
<add> $this->assertSame($value, $expressions[0]);
<add> $this->assertInstanceOf(WhenThenExpressionInterface::class, $expressions[1]);
<add> $this->assertEquals(new QueryExpression($conditionsA), $expressions[2]);
<add> $this->assertEquals(new ComparisonExpression('Table.column_a', true), $expressions[3]);
<add> $this->assertSame($resultA, $expressions[6]);
<add> $this->assertInstanceOf(WhenThenExpressionInterface::class, $expressions[7]);
<add> $this->assertEquals(new QueryExpression($conditionsB), $expressions[8]);
<add> $this->assertEquals(new ComparisonExpression('Table.column_c', true), $expressions[9]);
<add> $this->assertSame($resultB, $expressions[12]);
<add> $this->assertSame($else, $expressions[13]);
<add> }
<add>
<add> public function testTraverseBeforeClosingThenFails(): void
<add> {
<add> $this->expectException(LogicException::class);
<add> $this->expectExceptionMessage(
<add> 'Cannot traverse incomplete `\Cake\Database\Expression\CaseExpressionInterface` ' .
<add> 'expression, there is an open `when()` buffer present that must be closed using `then()`.'
<add> );
<add>
<add> $this->deprecated(function () {
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column' => true]);
<add>
<add> $expression->traverse(
<add> function () {
<add> }
<add> );
<add> });
<add> }
<add>
<add> // endregion
<add>
<add> // region Cloning
<add>
<add> public function testClone(): void
<add> {
<add> $value = new IdentifierExpression('Table.column');
<add> $conditionsA = ['Table.column_a' => true, 'Table.column_b IS' => null];
<add> $resultA = new QueryExpression('1');
<add> $conditionsB = ['Table.column_c' => true, 'Table.column_d IS NOT' => null];
<add> $resultB = new QueryExpression('2');
<add> $else = new QueryExpression('3');
<add>
<add> $expression = (new CaseStatementExpression())
<add> ->value($value)
<add> ->when($conditionsA)
<add> ->then($resultA)
<add> ->when($conditionsB)
<add> ->then($resultB)
<add> ->else($else);
<add> $clone = clone $expression;
<add>
<add> $this->assertEquals($clone, $expression);
<add> $this->assertNotSame($clone, $expression);
<add> }
<add>
<add> public function testCloneBeforeClosingThenFails(): void
<add> {
<add> $this->expectException(LogicException::class);
<add> $this->expectExceptionMessage(
<add> 'Cannot clone incomplete `\Cake\Database\Expression\CaseExpressionInterface` ' .
<add> 'expression, there is an open `when()` buffer present that must be closed using `then()`.'
<add> );
<add>
<add> $this->deprecated(function () {
<add> $expression = (new CaseStatementExpression())
<add> ->when(['Table.column' => true]);
<add>
<add> clone $expression;
<add> });
<add> }
<add>
<add> // endregion
<add>}
<ide><path>tests/TestCase/Database/Expression/QueryExpressionTest.php
<ide> public function testNotInOrNull(): void
<ide> $expr->sql(new ValueBinder())
<ide> );
<ide> }
<add>
<add> /**
<add> * Test deprecated adding of case statement.
<add> */
<add> public function testDeprecatedAddCaseStatement(): void
<add> {
<add> $this->expectDeprecation();
<add> $this->expectDeprecationMessage('QueryExpression::addCase() is deprecated, use case() instead.');
<add>
<add> (new QueryExpression())->addCase([]);
<add> }
<ide> }
<ide><path>tests/TestCase/Database/QueryTest.php
<ide> public function testSelectOrderAsc(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $query = new Query($this->connection);
<del> $query->select(['id'])
<del> ->from('articles')
<del> ->orderAsc(function (QueryExpression $exp, Query $query) {
<del> return $exp->addCase(
<del> [$query->newExpr()->add(['author_id' => 1])],
<del> [1, $query->identifier('id')],
<del> ['integer', null]
<del> );
<del> })
<del> ->orderAsc('id');
<add> $this->deprecated(function () use ($query) {
<add> $query->select(['id'])
<add> ->from('articles')
<add> ->orderAsc(function (QueryExpression $exp, Query $query) {
<add> return $exp->addCase(
<add> [$query->newExpr()->add(['author_id' => 1])],
<add> [1, $query->identifier('id')],
<add> ['integer', null]
<add> );
<add> })
<add> ->orderAsc('id');
<add> });
<ide> $sql = $query->sql();
<ide> $result = $query->execute()->fetchAll('assoc');
<ide> $expected = [
<ide> public function testSelectOrderDesc(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $query = new Query($this->connection);
<del> $query->select(['id'])
<del> ->from('articles')
<del> ->orderDesc(function (QueryExpression $exp, Query $query) {
<del> return $exp->addCase(
<del> [$query->newExpr()->add(['author_id' => 1])],
<del> [1, $query->identifier('id')],
<del> ['integer', null]
<del> );
<del> })
<del> ->orderDesc('id');
<add> $this->deprecated(function () use ($query) {
<add> $query->select(['id'])
<add> ->from('articles')
<add> ->orderDesc(function (QueryExpression $exp, Query $query) {
<add> return $exp->addCase(
<add> [$query->newExpr()->add(['author_id' => 1])],
<add> [1, $query->identifier('id')],
<add> ['integer', null]
<add> );
<add> })
<add> ->orderDesc('id');
<add> });
<ide> $sql = $query->sql();
<ide> $result = $query->execute()->fetchAll('assoc');
<ide> $expected = [
<ide> public function testRowCountAndClose(): void
<ide> public function testSqlCaseStatement(): void
<ide> {
<ide> $query = new Query($this->connection);
<del> $publishedCase = $query
<del> ->newExpr()
<del> ->addCase(
<del> $query
<add> $publishedCase = null;
<add> $notPublishedCase = null;
<add> $this->deprecated(function () use ($query, &$publishedCase, &$notPublishedCase) {
<add> $publishedCase = $query
<ide> ->newExpr()
<del> ->add(['published' => 'Y']),
<del> 1,
<del> 'integer'
<del> );
<del> $notPublishedCase = $query
<del> ->newExpr()
<del> ->addCase(
<del> $query
<del> ->newExpr()
<del> ->add(['published' => 'N']),
<del> 1,
<del> 'integer'
<del> );
<add> ->addCase(
<add> $query
<add> ->newExpr()
<add> ->add(['published' => 'Y']),
<add> 1,
<add> 'integer'
<add> );
<add> $notPublishedCase = $query
<add> ->newExpr()
<add> ->addCase(
<add> $query
<add> ->newExpr()
<add> ->add(['published' => 'N']),
<add> 1,
<add> 'integer'
<add> );
<add> });
<ide>
<ide> // Postgres requires the case statement to be cast to a integer
<ide> if ($this->connection->getDriver() instanceof Postgres) {
<ide> public function testSqlCaseStatement(): void
<ide> 'Not published',
<ide> 'None',
<ide> ];
<add> $this->deprecated(function () use ($query, $conditions, $values) {
<add> $query
<add> ->select([
<add> 'id',
<add> 'comment',
<add> 'status' => $query->newExpr()->addCase($conditions, $values),
<add> ])
<add> ->from(['comments']);
<add> });
<ide> $results = $query
<del> ->select([
<del> 'id',
<del> 'comment',
<del> 'status' => $query->newExpr()->addCase($conditions, $values),
<del> ])
<del> ->from(['comments'])
<ide> ->execute()
<ide> ->fetchAll('assoc');
<ide>
<ide> public function testOrderBySubquery(): void
<ide> $stmt->closeCursor();
<ide>
<ide> $subquery = new Query($connection);
<del> $subquery
<del> ->select(
<del> $subquery->newExpr()->addCase(
<del> [$subquery->newExpr()->add(['a.published' => 'N'])],
<del> [1, 0],
<del> ['integer', 'integer']
<add> $this->deprecated(function () use ($subquery) {
<add> $subquery
<add> ->select(
<add> $subquery->newExpr()->addCase(
<add> [$subquery->newExpr()->add(['a.published' => 'N'])],
<add> [1, 0],
<add> ['integer', 'integer']
<add> )
<ide> )
<del> )
<del> ->from(['a' => 'articles'])
<del> ->where([
<del> 'a.id = articles.id',
<del> ]);
<add> ->from(['a' => 'articles'])
<add> ->where([
<add> 'a.id = articles.id',
<add> ]);
<add> });
<ide>
<ide> $query
<ide> ->select(['id'])
<ide><path>tests/TestCase/Database/QueryTests/CaseExpressionQueryTest.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.3.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Test\TestCase\Database\QueryTests;
<add>
<add>use Cake\Database\Driver\Postgres;
<add>use Cake\Database\Expression\QueryExpression;
<add>use Cake\ORM\Query;
<add>use Cake\Test\Fixture\ArticlesFixture;
<add>use Cake\Test\Fixture\CommentsFixture;
<add>use Cake\Test\Fixture\ProductsFixture;
<add>use Cake\TestSuite\TestCase;
<add>
<add>class CaseExpressionQueryTest extends TestCase
<add>{
<add> protected $fixtures = [
<add> ArticlesFixture::class,
<add> CommentsFixture::class,
<add> ProductsFixture::class,
<add> ];
<add>
<add> public function testSimpleCase(): void
<add> {
<add> $query = $this->getTableLocator()->get('Products')
<add> ->find()
<add> ->select(function (Query $query) {
<add> return [
<add> 'name',
<add> 'category_name' => $query->newExpr()
<add> ->case()
<add> ->value($query->identifier('Products.category'))
<add> ->when(1)
<add> ->then('Touring')
<add> ->when(2)
<add> ->then('Urban')
<add> ->else('Other'),
<add> ];
<add> })
<add> ->orderAsc('category')
<add> ->orderAsc('name')
<add> ->disableHydration();
<add>
<add> $expected = [
<add> [
<add> 'name' => 'First product',
<add> 'category_name' => 'Touring',
<add> ],
<add> [
<add> 'name' => 'Second product',
<add> 'category_name' => 'Urban',
<add> ],
<add> [
<add> 'name' => 'Third product',
<add> 'category_name' => 'Other',
<add> ],
<add> ];
<add> $this->assertSame($expected, $query->toArray());
<add> }
<add>
<add> public function testSearchedCase(): void
<add> {
<add> $query = $this->getTableLocator()->get('Products')
<add> ->find()
<add> ->select(function (Query $query) {
<add> return [
<add> 'name',
<add> 'price',
<add> 'price_range' => $query->newExpr()
<add> ->case()
<add> ->when(['price <' => 20])
<add> ->then('Under $20')
<add> ->when(['price >=' => 20, 'price <' => 30])
<add> ->then('Under $30')
<add> ->else('$30 and above'),
<add> ];
<add> })
<add> ->orderAsc('price')
<add> ->orderAsc('name')
<add> ->disableHydration();
<add>
<add> $expected = [
<add> [
<add> 'name' => 'First product',
<add> 'price' => 10,
<add> 'price_range' => 'Under $20',
<add> ],
<add> [
<add> 'name' => 'Second product',
<add> 'price' => 20,
<add> 'price_range' => 'Under $30',
<add> ],
<add> [
<add> 'name' => 'Third product',
<add> 'price' => 30,
<add> 'price_range' => '$30 and above',
<add> ],
<add> ];
<add> $this->assertSame($expected, $query->toArray());
<add> }
<add>
<add> public function testOrderByCase(): void
<add> {
<add> $query = $this->getTableLocator()->get('Comments')
<add> ->find()
<add> ->select(['article_id', 'user_id'])
<add> ->orderAsc('Comments.article_id')
<add> ->orderDesc(function (QueryExpression $exp, Query $query) {
<add> return $query->newExpr()
<add> ->case()
<add> ->value($query->identifier('Comments.article_id'))
<add> ->when(1)
<add> ->then($query->identifier('Comments.user_id'));
<add> })
<add> ->orderAsc(function (QueryExpression $exp, Query $query) {
<add> return $query->newExpr()
<add> ->case()
<add> ->value($query->identifier('Comments.article_id'))
<add> ->when(2)
<add> ->then($query->identifier('Comments.user_id'));
<add> })
<add> ->disableHydration();
<add>
<add> $expected = [
<add> [
<add> 'article_id' => 1,
<add> 'user_id' => 4,
<add> ],
<add> [
<add> 'article_id' => 1,
<add> 'user_id' => 2,
<add> ],
<add> [
<add> 'article_id' => 1,
<add> 'user_id' => 1,
<add> ],
<add> [
<add> 'article_id' => 1,
<add> 'user_id' => 1,
<add> ],
<add> [
<add> 'article_id' => 2,
<add> 'user_id' => 1,
<add> ],
<add> [
<add> 'article_id' => 2,
<add> 'user_id' => 2,
<add> ],
<add> ];
<add> $this->assertSame($expected, $query->toArray());
<add> }
<add>
<add> public function testHavingByCase(): void
<add> {
<add> $articlesTable = $this->getTableLocator()->get('Articles');
<add> $articlesTable->hasMany('Comments');
<add>
<add> $query = $articlesTable
<add> ->find()
<add> ->select(['Articles.title'])
<add> ->leftJoinWith('Comments')
<add> ->group(['Articles.id', 'Articles.title'])
<add> ->having(function (QueryExpression $exp, Query $query) {
<add> $expression = $query->newExpr()
<add> ->case()
<add> ->when(['Comments.published' => 'Y'])
<add> ->then(1);
<add>
<add> if ($query->getConnection()->getDriver() instanceof Postgres) {
<add> $expression = $query->func()->cast($expression, 'integer');
<add> }
<add>
<add> return $exp->gt(
<add> $query->func()->sum($expression),
<add> 2,
<add> 'integer'
<add> );
<add> })
<add> ->disableHydration();
<add>
<add> $expected = [
<add> [
<add> 'title' => 'First Article',
<add> ],
<add> ];
<add> $this->assertSame($expected, $query->toArray());
<add> }
<add>
<add> public function testUpdateFromCase(): void
<add> {
<add> $commentsTable = $this->getTableLocator()->get('Comments');
<add>
<add> $this->assertSame(5, $commentsTable->find()->where(['Comments.published' => 'Y'])->count());
<add> $this->assertSame(1, $commentsTable->find()->where(['Comments.published' => 'N'])->count());
<add>
<add> $commentsTable->updateAll(
<add> [
<add> 'published' =>
<add> $commentsTable->query()->newExpr()
<add> ->case()
<add> ->when(['published' => 'Y'])
<add> ->then('N')
<add> ->else('Y'),
<add> ],
<add> '1 = 1'
<add> );
<add>
<add> $this->assertSame(1, $commentsTable->find()->where(['Comments.published' => 'Y'])->count());
<add> $this->assertSame(5, $commentsTable->find()->where(['Comments.published' => 'N'])->count());
<add> }
<add>
<add> public function testInferredReturnType(): void
<add> {
<add> $query = $this->getTableLocator()->get('Products')
<add> ->find()
<add> ->select(function (Query $query) {
<add> $expression = $query->newExpr()
<add> ->case()
<add> ->when(['Products.price <' => 20])
<add> ->then(true)
<add> ->else(false);
<add>
<add> if ($query->getConnection()->getDriver() instanceof Postgres) {
<add> $expression = $query->func()->cast($expression, 'boolean');
<add> }
<add>
<add> return [
<add> 'Products.name',
<add> 'Products.price',
<add> 'is_cheap' => $expression,
<add> ];
<add> })
<add> ->disableHydration();
<add>
<add> $expected = [
<add> [
<add> 'name' => 'First product',
<add> 'price' => 10,
<add> 'is_cheap' => true,
<add> ],
<add> [
<add> 'name' => 'Second product',
<add> 'price' => 20,
<add> 'is_cheap' => false,
<add> ],
<add> [
<add> 'name' => 'Third product',
<add> 'price' => 30,
<add> 'is_cheap' => false,
<add> ],
<add> ];
<add> $this->assertSame($expected, $query->toArray());
<add> }
<add>
<add> public function testOverwrittenReturnType(): void
<add> {
<add> $query = $this->getTableLocator()->get('Products')
<add> ->find()
<add> ->select(function (Query $query) {
<add> return [
<add> 'name',
<add> 'price',
<add> 'is_cheap' => $query->newExpr()
<add> ->case()
<add> ->when(['price <' => 20])
<add> ->then(1)
<add> ->else(0)
<add> ->setReturnType('boolean'),
<add> ];
<add> })
<add> ->orderAsc('price')
<add> ->orderAsc('name')
<add> ->disableHydration();
<add>
<add> $expected = [
<add> [
<add> 'name' => 'First product',
<add> 'price' => 10,
<add> 'is_cheap' => true,
<add> ],
<add> [
<add> 'name' => 'Second product',
<add> 'price' => 20,
<add> 'is_cheap' => false,
<add> ],
<add> [
<add> 'name' => 'Third product',
<add> 'price' => 30,
<add> 'is_cheap' => false,
<add> ],
<add> ];
<add> $this->assertSame($expected, $query->toArray());
<add> }
<add>
<add> public function bindingValueDataProvider(): array
<add> {
<add> return [
<add> ['1', 3],
<add> ['2', 4],
<add> ];
<add> }
<add>
<add> /**
<add> * @dataProvider bindingValueDataProvider
<add> * @param string $when The `WHEN` value.
<add> * @param int $result The result value.
<add> */
<add> public function testBindValues(string $when, int $result): void
<add> {
<add> $value = '1';
<add> $then = '3';
<add> $else = '4';
<add>
<add> $query = $this->getTableLocator()->get('Products')
<add> ->find()
<add> ->select(function (Query $query) {
<add> return [
<add> 'val' => $query->newExpr()
<add> ->case()
<add> ->value($query->newExpr(':value'))
<add> ->when($query->newExpr(':when'))
<add> ->then($query->newExpr(':then'))
<add> ->else($query->newExpr(':else'))
<add> ->setReturnType('integer'),
<add> ];
<add> })
<add> ->bind(':value', $value, 'integer')
<add> ->bind(':when', $when, 'integer')
<add> ->bind(':then', $then, 'integer')
<add> ->bind(':else', $else, 'integer')
<add> ->disableHydration();
<add>
<add> $expected = [
<add> 'val' => $result,
<add> ];
<add> $this->assertSame($expected, $query->first());
<add> }
<add>}
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php
<ide> public function testCountWithComplexOrderBy(): void
<ide> {
<ide> $table = $this->getTableLocator()->get('Articles');
<ide> $query = $table->find();
<del> $query->orderDesc($query->newExpr()->addCase(
<del> [$query->newExpr()->add(['id' => 3])],
<del> [1, 0]
<del> ));
<add> $this->deprecated(function () use ($query) {
<add> $query->orderDesc($query->newExpr()->addCase(
<add> [$query->newExpr()->add(['id' => 3])],
<add> [1, 0]
<add> ));
<add> });
<ide> $query->order(['title' => 'desc']);
<ide> // Executing the normal query before getting the count
<ide> $query->all();
<ide> $this->assertSame(3, $query->count());
<ide>
<ide> $table = $this->getTableLocator()->get('Articles');
<ide> $query = $table->find();
<del> $query->orderDesc($query->newExpr()->addCase(
<del> [$query->newExpr()->add(['id' => 3])],
<del> [1, 0]
<del> ));
<add> $this->deprecated(function () use ($query) {
<add> $query->orderDesc($query->newExpr()->addCase(
<add> [$query->newExpr()->add(['id' => 3])],
<add> [1, 0]
<add> ));
<add> });
<ide> $query->orderDesc($query->newExpr()->add(['id' => 3]));
<ide> // Not executing the query first, just getting the count
<ide> $this->assertSame(3, $query->count());
<ide><path>tests/test_app/TestApp/Database/Expression/CustomWhenThenExpression.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.3.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Test\test_app\TestApp\Database\Expression;
<add>
<add>use Cake\Database\Expression\WhenThenExpression;
<add>
<add>class CustomWhenThenExpression extends WhenThenExpression
<add>{
<add>}
<ide><path>tests/test_app/TestApp/Database/Type/CustomExpressionType.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.3.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace TestApp\Database\Type;
<add>
<add>use Cake\Database\Expression\FunctionExpression;
<add>use Cake\Database\ExpressionInterface;
<add>use Cake\Database\Type\ExpressionTypeInterface;
<add>use Cake\Database\Type\StringType;
<add>
<add>class CustomExpressionType extends StringType implements ExpressionTypeInterface
<add>{
<add> public function toExpression($value): ExpressionInterface
<add> {
<add> return new FunctionExpression('CUSTOM', [$value]);
<add> }
<add>} | 13 |
Javascript | Javascript | remove passive flag from "before mutation" phase | 8df7b7911aa7fc3a896fb29da29e09f574e931aa | <ide><path>packages/react-reconciler/src/ReactFiberFlags.js
<ide> export const ForceUpdateForLegacySuspense = /* */ 0b000100000000000000;
<ide> export const PassiveStatic = /* */ 0b001000000000000000;
<ide>
<ide> // Union of side effect groupings as pertains to subtreeFlags
<del>export const BeforeMutationMask = /* */ 0b000000001100001010;
<add>// TODO: Don't need to visit Placement during BeforeMutation phase
<add>// TODO: Only need to visit Deletions during BeforeMutation phase if an element
<add>// is focused.
<add>export const BeforeMutationMask = /* */ 0b000000000100001010;
<ide> export const MutationMask = /* */ 0b000000010010011110;
<ide> export const LayoutMask = /* */ 0b000000000010100100;
<ide> export const PassiveMask = /* */ 0b000000001000001000;
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> NoFlags;
<ide>
<ide> if (subtreeHasEffects || rootHasEffect) {
<add> // If there are pending passive effects, schedule a callback to process them.
<add> if (
<add> (finishedWork.subtreeFlags & PassiveMask) !== NoFlags ||
<add> (finishedWork.flags & PassiveMask) !== NoFlags
<add> ) {
<add> if (!rootDoesHavePassiveEffects) {
<add> rootDoesHavePassiveEffects = true;
<add> scheduleCallback(NormalSchedulerPriority, () => {
<add> flushPassiveEffects();
<add> return null;
<add> });
<add> }
<add> }
<add>
<ide> let previousLanePriority;
<ide> if (decoupleUpdatePriorityFromScheduler) {
<ide> previousLanePriority = getCurrentUpdateLanePriority();
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> markLayoutEffectsStopped();
<ide> }
<ide>
<del> // If there are pending passive effects, schedule a callback to process them.
<del> if (
<del> (finishedWork.subtreeFlags & PassiveMask) !== NoFlags ||
<del> (finishedWork.flags & PassiveMask) !== NoFlags
<del> ) {
<del> if (!rootDoesHavePassiveEffects) {
<del> rootDoesHavePassiveEffects = true;
<del> scheduleCallback(NormalSchedulerPriority, () => {
<del> flushPassiveEffects();
<del> return null;
<del> });
<del> }
<del> }
<del>
<ide> // Tell Scheduler to yield at the end of the frame, so the browser has an
<ide> // opportunity to paint.
<ide> requestPaint();
<ide> function commitBeforeMutationEffectsImpl(fiber: Fiber) {
<ide> commitBeforeMutationEffectOnFiber(current, fiber);
<ide> resetCurrentDebugFiberInDEV();
<ide> }
<del>
<del> if ((flags & Passive) !== NoFlags) {
<del> // If there are passive effects, schedule a callback to flush at
<del> // the earliest opportunity.
<del> if (!rootDoesHavePassiveEffects) {
<del> rootDoesHavePassiveEffects = true;
<del> scheduleCallback(NormalSchedulerPriority, () => {
<del> flushPassiveEffects();
<del> return null;
<del> });
<del> }
<del> }
<ide> }
<ide>
<ide> function commitBeforeMutationEffectsDeletions(deletions: Array<Fiber>) { | 2 |
Text | Text | apply suggestions from code review | 6d3d88d33e4c0ee16b1e955f05adf889f221f8dc | <ide><path>docs/External-Commands.md
<ide> Install any `gem` package into a self-contained Homebrew Cellar location: <https
<ide> Note this can also be installed with `brew install brew-gem`.
<ide>
<ide> ## External commands in taps
<del>External commands can be hosted in a [tap](Taps.md) to allow users to easy install and use the command. See [How to Create and Maintain a Tap](How-to-Create-and-Maintain-a-Tap.md) for more details about creating and maintaining a tap.
<add>External commands can be hosted in a [tap](Taps.md) to allow users to easily install and use them. See [How to Create and Maintain a Tap](How-to-Create-and-Maintain-a-Tap.md) for more details about creating and maintaining a tap.
<ide>
<ide> External commands should be added to a `cmd` directory in the tap. An external command `extcmd` implemented as a Ruby command should live in `cmd/extcmd.rb` (don't forget to `chmod +x`).
<ide>
<ide> module Homebrew
<ide> end
<ide> ```
<ide>
<del>Using the above will generate the appropriate help text:
<add>Using the above will generate appropriate help text:
<ide>
<ide> ```console
<ide> $ brew foo --help
<ide> Do something. Place a description here.
<ide> -h, --help Show this message.
<ide> ```
<ide>
<del>Use the `named_args` method to specify the type and number of named arguments that are expected. Pass a symbol to indicate the type of argument expected. Pass an array of symbols to indicate that multiple types should be expected. Pass an array of strings to specify the specific options that should be expected (see the [`brew analytics`](https://github.com/Homebrew/brew/blob/HEAD/Library/Homebrew/cmd/analytics.rb) command for an example of this).
<add>Use the `named_args` method to specify the type and number of named arguments that are expected. Pass either a symbol to indicate the type of argument expected, an array of symbols to indicate that multiple types should be expected, or an array of strings to specify which specific options should be expected (see the [`brew analytics`](https://github.com/Homebrew/brew/blob/HEAD/Library/Homebrew/cmd/analytics.rb) command for an example of this).
<ide>
<ide> Pass an integer to the `number`, `min`, or `max` parameter of `named_args` to specify the number of named arguments that are expected. See the following examples:
<ide> | 1 |
Python | Python | fix customdata on azure arm | 64fb493249e8f5a31212195f2d6fd682e39a2b1c | <ide><path>libcloud/compute/drivers/azure_arm.py
<ide> def create_node(self,
<ide>
<ide> if ex_customdata:
<ide> data["properties"]["osProfile"]["customData"] = \
<del> base64.b64encode(ex_customdata)
<add> base64.b64encode(ex_customdata.encode()).decode()
<ide>
<ide> data["properties"]["osProfile"]["adminUsername"] = ex_user_name
<ide> | 1 |
Text | Text | add v4.0.0-beta.4 to changelog` | e53d6bb4bbb5230829eb589fdba2388de3cd28cf | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v4.0.0-beta.4 (September 13, 2021)
<add>
<add>- [#19733](https://github.com/emberjs/ember.js/pull/19733) [BUGFIX] Ensure that using `routerService.urlFor(...)` and `routerService.recognize(...)` does not error if the router is not fully initialized
<add>
<ide> ### v4.0.0-beta.3 (August 30, 2021)
<ide>
<ide> - [#19708](https://github.com/emberjs/ember.js/pull/19708) [CLEANUP] Remove class-binding-and-class-name-bindings-in-templates | 1 |
PHP | PHP | add selectcount tests for eloquent builder | 8d64b76dd9d820551c7b5b2d9b83fb292bd8b150 | <ide><path>tests/Database/DatabaseEloquentBuilderTest.php
<ide> public function testDeleteOverride()
<ide> $this->assertEquals(['foo' => $builder], $builder->delete());
<ide> }
<ide>
<add> public function testSelectCount()
<add> {
<add> $model = new EloquentBuilderTestModelParentStub;
<add>
<add> $builder = $model->selectCount('foo', 'fooCount');
<add>
<add> $this->assertEquals('select (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "fooCount" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
<add> }
<add>
<add> public function testSelectCountWithSelectAndContraintsAndHaving()
<add> {
<add> $model = new EloquentBuilderTestModelParentStub;
<add>
<add> $builder = $model->where('bar', 'baz')->select('*');
<add> $builder->selectCount('foo', 'fooCount', function ($q) {
<add> $q->where('bam', '>', 'qux');
<add> })->having('fooCount', '>=', 1);
<add>
<add> $this->assertEquals('select *, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bam" > ?) as "fooCount" from "eloquent_builder_test_model_parent_stubs" where "bar" = ? having "fooCount" >= ?', $builder->toSql());
<add> $this->assertEquals(['qux', 'baz', 1], $builder->getBindings());
<add> }
<add>
<ide> public function testHasWithContraintsAndHavingInSubquery()
<ide> {
<ide> $model = new EloquentBuilderTestModelParentStub; | 1 |
Go | Go | fix issue with add | f03ebc20aa33dbb9b468fe476ce26467eb328060 | <ide><path>buildfile.go
<ide> func (b *buildFile) CmdAdd(args string) error {
<ide> cmd := b.config.Cmd
<ide> b.config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) ADD %s in %s", orig, dest)}
<ide>
<add> b.config.Image = b.image
<ide> // Create the container and start it
<ide> container, err := b.builder.Create(b.config)
<ide> if err != nil {
<ide> func (b *buildFile) commit(id string, autoCmd []string, comment string) error {
<ide> } else {
<ide> utils.Debugf("[BUILDER] Cache miss")
<ide> }
<del>
<ide> container, err := b.builder.Create(b.config)
<ide> if err != nil {
<ide> return err | 1 |
PHP | PHP | remove extra newline | 825eab3a27337238e3192144a9dccdd8436f6131 | <ide><path>src/View/Helper/FormHelper.php
<ide> class FormHelper extends Helper {
<ide>
<ide> use IdGeneratorTrait;
<del>
<ide> use StringTemplateTrait;
<ide>
<ide> /** | 1 |
Go | Go | debug output specifics | 4cfe9df0a9c206c368a90f460fea8fab197265d9 | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func (devices *DeviceSet) initDevmapper(doInit bool) error {
<ide>
<ide> func (devices *DeviceSet) AddDevice(hash, baseHash string) error {
<ide> log.Debugf("[deviceset] AddDevice() hash=%s basehash=%s", hash, baseHash)
<del> defer log.Debugf("[deviceset] AddDevice END")
<add> defer log.Debugf("[deviceset] AddDevice(hash=%s basehash=%s) END", hash, baseHash)
<ide>
<ide> baseInfo, err := devices.lookupDevice(baseHash)
<ide> if err != nil {
<ide> func (devices *DeviceSet) deactivatePool() error {
<ide>
<ide> func (devices *DeviceSet) deactivateDevice(info *DevInfo) error {
<ide> log.Debugf("[devmapper] deactivateDevice(%s)", info.Hash)
<del> defer log.Debugf("[devmapper] deactivateDevice END")
<add> defer log.Debugf("[devmapper] deactivateDevice END(%s)", info.Hash)
<ide>
<ide> // Wait for the unmount to be effective,
<ide> // by watching the value of Info.OpenCount for the device
<ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error {
<ide>
<ide> func (devices *DeviceSet) UnmountDevice(hash string) error {
<ide> log.Debugf("[devmapper] UnmountDevice(hash=%s)", hash)
<del> defer log.Debugf("[devmapper] UnmountDevice END")
<add> defer log.Debugf("[devmapper] UnmountDevice(hash=%s) END", hash)
<ide>
<ide> info, err := devices.lookupDevice(hash)
<ide> if err != nil {
<ide><path>pkg/devicemapper/devmapper.go
<ide> func UdevSetSyncSupport(enable bool) bool {
<ide>
<ide> // Useful helper for cleanup
<ide> func RemoveDevice(name string) error {
<del> log.Debugf("[devmapper] RemoveDevice START")
<del> defer log.Debugf("[devmapper] RemoveDevice END")
<add> log.Debugf("[devmapper] RemoveDevice START(%s)", name)
<add> defer log.Debugf("[devmapper] RemoveDevice END(%s)", name)
<ide> task, err := TaskCreateNamed(DeviceRemove, name)
<ide> if task == nil {
<ide> return err | 2 |
Javascript | Javascript | add tests to check error in dns.lookupservice | 0623aabbe12cd288d82ef330654193a5edfcc3fa | <ide><path>test/parallel/test-dns-lookupService.js
<add>// Flags: --expose-internals
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const { internalBinding } = require('internal/test/binding');
<add>const cares = internalBinding('cares_wrap');
<add>const { UV_ENOENT } = internalBinding('uv');
<add>const dns = require('dns');
<add>
<add>// Stub `getnameinfo` to *always* error.
<add>cares.getnameinfo = () => UV_ENOENT;
<add>
<add>assert.throws(
<add> () => dns.lookupService('127.0.0.1', 80, common.mustNotCall()),
<add> {
<add> code: 'ENOENT',
<add> message: 'getnameinfo ENOENT 127.0.0.1',
<add> syscall: 'getnameinfo'
<add> }
<add>); | 1 |
Javascript | Javascript | remove outdated originalevent hack | 6df669f0fb87cd9975a18bf6bbe3c3548afa4fee | <ide><path>src/event.js
<ide> jQuery.event = {
<ide> }
<ide> },
<ide>
<add> // Piggyback on a donor event to simulate a different one
<ide> simulate: function( type, elem, event, bubble ) {
<del> // Piggyback on a donor event to simulate a different one.
<del> // Fake originalEvent to avoid donor's stopPropagation, but if the
<del> // simulated event prevents default then we do the same on the donor.
<ide> var e = jQuery.extend(
<ide> new jQuery.Event(),
<ide> event,
<ide> {
<ide> type: type,
<ide> isSimulated: true
<add> // Previously, `originalEvent: {}` was set here, so stopPropagation call
<add> // would not be triggered on donor event, since in our own
<add> // jQuery.event.stopPropagation function we had a check for existence of
<add> // originalEvent.stopPropagation method, so, consequently it would be a noop.
<add> //
<add> // But now, this "simulate" function is used only for events
<add> // for which stopPropagation() is noop, so there is no need for that anymore.
<add> //
<add> // For the compat branch though, guard for "click" and "submit"
<add> // events is still used, but was moved to jQuery.event.stopPropagation function
<add> // because `originalEvent` should point to the original event for the constancy
<add> // with other events and for more focused logic
<ide> }
<ide> );
<ide>
<del> // This prevents stopPropagation(), stopImmediatePropagation(), and preventDefault() from
<del> // preventing default on the donor event.
<del> delete e.originalEvent;
<del>
<ide> if ( bubble ) {
<ide> jQuery.event.trigger( e, null, elem );
<ide> } else {
<ide><path>test/unit/event.js
<ide> test( "preventDefault() on focusin does not throw exception", function( assert )
<ide> .focus();
<ide> } );
<ide>
<del>test( "jQuery.event.simulate() event has no originalEvent", function( assert ) {
<del> expect( 1 );
<add>test( "Donor event interference", function( assert ) {
<add> assert.expect( 10 );
<ide>
<del> var done = assert.async(),
<del> input = jQuery( "<input>" )
<del> .on( "click", function( event ) {
<del> assert.strictEqual( "originalEvent" in event, false,
<del> "originalEvent not present on simulated event" );
<del> done();
<del> } );
<del>
<del> jQuery.event.simulate( "click", input[ 0 ], new jQuery.Event(), true );
<del>} );
<add> var html = "<div id='donor-outer'>" +
<add> "<form id='donor-form'>" +
<add> "<input id='donor-input' type='radio' />" +
<add> "</form>" +
<add> "</div>";
<ide>
<del>test( "Donor event interference", function( assert ) {
<del> assert.expect( 4 );
<add> jQuery( "#qunit-fixture" ).append( html );
<ide>
<del> jQuery( "#donor-outer" ).on( "click", function() {
<add> jQuery( "#donor-outer" ).on( "click", function( event ) {
<ide> assert.ok( true, "click bubbled to outer div" );
<add> assert.equal( typeof event.originalEvent, "object", "make sure originalEvent exist" );
<add> assert.equal( event.type, "click", "make sure event type is correct" );
<ide> } );
<ide> jQuery( "#donor-input" ).on( "click", function( event ) {
<ide> assert.ok( true, "got a click event from the input" );
<ide> assert.ok( !event.isPropagationStopped(), "propagation says it's not stopped" );
<add> assert.equal( event.type, "click", "make sure event type is correct" );
<add> assert.equal( typeof event.originalEvent, "object", "make sure originalEvent exist" );
<ide> } );
<ide> jQuery( "#donor-input" ).on( "change", function( event ) {
<add> assert.equal( typeof event.originalEvent, "object", "make sure originalEvent exist" );
<add> assert.equal( event.type, "change", "make sure event type is correct" );
<ide> assert.ok( true, "got a change event from the input" );
<ide> event.stopPropagation();
<ide> } );
<del> jQuery( "#donor-input" )[0].click();
<add> jQuery( "#donor-input" )[ 0 ].click();
<add>} );
<add>
<add>test( "originalEvent property for Chrome, Safari and FF of simualted event", function( assert ) {
<add> var userAgent = window.navigator.userAgent;
<add>
<add> if ( !(/chrome/i.test( userAgent ) ||
<add> /firefox/i.test( userAgent ) ||
<add> /safari/i.test( userAgent ) ) ) {
<add> assert.expect( 1 );
<add> assert.ok( true, "Assertions should run only in Chrome, Safari and FF" );
<add> return;
<add> }
<add>
<add> assert.expect( 4 );
<add>
<add> var html = "<div id='donor-outer'>" +
<add> "<form id='donor-form'>" +
<add> "<input id='donor-input' type='radio' />" +
<add> "</form>" +
<add> "</div>";
<add>
<add> jQuery( "#qunit-fixture" ).append( html );
<add>
<add> jQuery( "#donor-outer" ).on( "focusin", function( event ) {
<add> assert.ok( true, "focusin bubbled to outer div" );
<add> assert.equal( event.originalEvent.type, "focus",
<add> "make sure originalEvent type is correct" );
<add> assert.equal( event.type, "focusin", "make sure type is correct" );
<add> } );
<add> jQuery( "#donor-input" ).on( "focus", function() {
<add> assert.ok( true, "got a focus event from the input" );
<add> } );
<add> jQuery( "#donor-input" ).trigger( "focus" );
<ide> } );
<ide>
<ide> // This tests are unreliable in Firefox | 2 |
Text | Text | update webpack according to brand guidelines | bc23cc31de672121f395f904652e41116d0060bc | <ide><path>docs/_posts/2015-02-18-react-conf-roundup-2015.md
<ide> It was a privilege to welcome the React community to Facebook HQ on January 28
<ide> <div class="skinny-col">
<ide> <h3 style="margin-top:0"><a class="anchor" name="talk-tweak"></a>Tweaking in real time <a class="hash-link" href="#talk-tweak">#</a></h3>
<ide> <p>
<del> <strong>Brenton Simpson</strong> showed us how eBay brings Bret Victor’s feedback loop to your favorite editor using Webpack, react-hot-loader, and <a href="https://github.com/appsforartists/ambidex">Ambidex</a>.
<add> <strong>Brenton Simpson</strong> showed us how eBay brings Bret Victor’s feedback loop to your favorite editor using webpack, react-hot-loader, and <a href="https://github.com/appsforartists/ambidex">Ambidex</a>.
<ide> </p>
<ide> </div>
<ide> <div class="skinny-col">
<ide><path>docs/_posts/2015-03-30-community-roundup-26.md
<ide> Jay Garcia spent a lot of time during the beta working on a NES music player wit
<ide> </center>
<ide>
<ide>
<del>## React Native with Babel and Webpack
<add>## React Native with Babel and webpack
<ide>
<del>React Native ships with a custom packager and custom ES6 transforms instead of using what the open source community settled on such as Webpack and Babel. The main reason for this is performance – we couldn't get those tools to have sub-second reload time on a large codebase.
<add>React Native ships with a custom packager and custom ES6 transforms instead of using what the open source community settled on such as webpack and Babel. The main reason for this is performance – we couldn't get those tools to have sub-second reload time on a large codebase.
<ide>
<del>Roman Liutikov found a way to [use Webpack and Babel to run on React Native](https://github.com/roman01la/react-native-babel)! In the future, we want to work with those projects to provide cleaner extension mechanisms.
<add>Roman Liutikov found a way to [use webpack and Babel to run on React Native](https://github.com/roman01la/react-native-babel)! In the future, we want to work with those projects to provide cleaner extension mechanisms.
<ide>
<ide>
<ide> ## A Dynamic, Crazy, Native Mobile Future—Powered by JavaScript
<ide><path>docs/_posts/2015-08-13-reacteurope-roundup.md
<ide> And there were lots of great talks from the React community:
<ide> * [Michael Chan](https://www.youtube.com/watch?v=ERB1TJBn32c&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD&index=2) looks at how to solve problems like CSS theming and media queries with contexts and plain old JavaScript. He also looks at the role of container-components and when it's better to "just use CSS.".
<ide> * [Elie Rotenberg](https://www.youtube.com/watch?v=JSjhhUvB9DY&index=3&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD) talks about Flux over the Wire, building isomorphic, real-time React apps using a novel interpretation of Flux.
<ide> * [Ryan Florence](https://www.youtube.com/watch?v=BF58ZJ1ZQxY&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD&index=6) says “Your front and back ends are already successfully in production but you don't have to miss out on the productivity that React brings. Forget the rewrites, this is brownfield!”.
<del>* [Dan Abramov](https://www.youtube.com/watch?v=xsSnOQynTHs&index=7&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD) demonstrates how React can be used together with Webpack Hot Module Replacement to create a live editing environment with time travel that supercharges your debugging experience and transforms the way you work on real apps every day.
<add>* [Dan Abramov](https://www.youtube.com/watch?v=xsSnOQynTHs&index=7&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD) demonstrates how React can be used together with webpack Hot Module Replacement to create a live editing environment with time travel that supercharges your debugging experience and transforms the way you work on real apps every day.
<ide> * [Mikhail Davydov](https://www.youtube.com/watch?v=ee_U2t-8L48&index=10&list=PLCC436JpVnK0Phxld2dD4tM4xPMxJCiRD) shows you how to ask the browser layout engine for help, how to avoid slavery of DSL, and build declarative Text UI using only web-technologies like HTML, JS, CSS and React.
<ide> * [Kevin Robinson](https://www.youtube.com/watch?v=EOz4D_714R8&list=PLCC436JpVnK3HvUSAHpt-LRJkIK8pQG6R&index=3) shares how user experience choices are a primary influence on how Twitter design the data layer, especially for teams developing new products with full-stack capabilities.
<ide> * [Jed Watson](https://www.youtube.com/watch?v=ctwmd5L1U_Q&list=PLCC436JpVnK3HvUSAHpt-LRJkIK8pQG6R&index=4) shares what Thinkmill have learned about React and mobile app development, and how they've approached the unique challenges of mobile web apps - with tools that are useful to all developers building touch interfaces with React, as well as a walkthrough of their development process and framework.
<ide><path>docs/_posts/2016-07-22-create-apps-with-no-configuration.md
<ide> Run `npm start` to launch the development server. The browser will open automati
<ide>
<ide> 
<ide>
<del>Create React App uses both Webpack and Babel under the hood.
<add>Create React App uses both webpack and Babel under the hood.
<ide> The console output is tuned to be minimal to help you focus on the problems:
<ide>
<ide> 
<ide> Your `package.json` contains only a single build dependency and a few scripts:
<ide> }
<ide> ```
<ide>
<del>We take care of updating Babel, ESLint, and Webpack to stable compatible versions so you can update a single dependency to get them all.
<add>We take care of updating Babel, ESLint, and webpack to stable compatible versions so you can update a single dependency to get them all.
<ide>
<ide> ### Zero Configuration
<ide>
<ide><path>docs/_posts/2016-09-28-our-first-50000-stars.md
<ide> As the project was about to be open sourced, [Lee Byron](https://twitter.com/lee
<ide>
<ide> In 2012, Instagram got acquired by Facebook. [Pete Hunt](https://twitter.com/floydophone), who was working on Facebook photos and videos at the time, joined their newly formed web team. He wanted to build their website completely in React, which was in stark contrast with the incremental adoption model that had been used at Facebook.
<ide>
<del>To make this happen, React had to be decoupled from Facebook's infrastructure, since Instagram didn't use any of it. This project acted as a forcing function to do the work needed to open source React. In the process, Pete also discovered and promoted a little project called Webpack. He also implemented the `renderToString` primitive which was needed to do server-side rendering.
<add>To make this happen, React had to be decoupled from Facebook's infrastructure, since Instagram didn't use any of it. This project acted as a forcing function to do the work needed to open source React. In the process, Pete also discovered and promoted a little project called webpack. He also implemented the `renderToString` primitive which was needed to do server-side rendering.
<ide>
<ide> As we started to prepare for the open source launch, [Maykel Loomans](https://twitter.com/miekd), a designer on Instagram, made a mock of what the website could look like. The header ended up defining the visual identity of React: its logo and the electric blue color!
<ide>
<ide><path>docs/contributing/codebase-overview.md
<ide> React itself was extracted from Facebook's codebase and uses Haste for historica
<ide> * When you add a new file, make sure you include a [license header](https://github.com/facebook/react/blob/87724bd87506325fcaf2648c70fc1f43411a87be/src/renderers/dom/client/utils/setInnerHTML.js#L1-L10). You can copy it from any existing file. A license header always includes [a line like this](https://github.com/facebook/react/blob/87724bd87506325fcaf2648c70fc1f43411a87be/src/renderers/dom/client/utils/setInnerHTML.js#L9). Change it to match the name of the file you created.
<ide> * Don’t use relative paths when importing. Instead of `require('./setInnerHTML')`, write `require('setInnerHTML')`.
<ide>
<del>When we compile React for npm, a script copies all the modules into [a single flat directory called `lib`](https://unpkg.com/react@15/lib/) and prepends all `require()` paths with `./`. This way Node, Browserify, Webpack, and other tools can understand React build output without being aware of Haste.
<add>When we compile React for npm, a script copies all the modules into [a single flat directory called `lib`](https://unpkg.com/react@15/lib/) and prepends all `require()` paths with `./`. This way Node, Browserify, webpack, and other tools can understand React build output without being aware of Haste.
<ide>
<ide> **If you're reading React source on GitHub and want to jump to a file, press "t".**
<ide>
<ide> ReactRef.detachRefs = function(
<ide> }
<ide> ```
<ide>
<del>When possible, new code should use Flow annotations.
<add>When possible, new code should use Flow annotations.
<ide> You can run `npm run flow` locally to check your code with Flow.
<ide>
<ide> ### Classes and Mixins
<ide><path>docs/docs/installation.md
<ide> Learn [how to tell if your website is serving the right version of React](/react
<ide> * [Creating a Production Build with Brunch](/react/docs/optimizing-performance.html#brunch)
<ide> * [Creating a Production Build with Browserify](/react/docs/optimizing-performance.html#browserify)
<ide> * [Creating a Production Build with Rollup](/react/docs/optimizing-performance.html#rollup)
<del>* [Creating a Production Build with Webpack](/react/docs/optimizing-performance.html#webpack)
<add>* [Creating a Production Build with webpack](/react/docs/optimizing-performance.html#webpack)
<ide>
<ide> ### Using a CDN
<ide>
<ide><path>docs/docs/optimizing-performance.md
<ide> For a complete setup example [see this gist](https://gist.github.com/Rich-Harris
<ide>
<ide> Remember that you only need to do this for production builds. You shouldn't apply the `uglify` plugin or the `replace` plugin with `'production'` value in development because they will hide useful React warnings, and make the builds much slower.
<ide>
<del>### Webpack
<add>### webpack
<ide>
<ide> >**Note:**
<ide> >
<ide> >If you're using Create React App, please follow [the instructions above](#create-react-app).<br>
<del>>This section is only relevant if you configure Webpack directly.
<add>>This section is only relevant if you configure webpack directly.
<ide>
<del>For the most efficient Webpack production build, make sure to include these plugins in your production configuration:
<add>For the most efficient webpack production build, make sure to include these plugins in your production configuration:
<ide>
<ide> ```js
<ide> new webpack.DefinePlugin({
<ide> new webpack.DefinePlugin({
<ide> new webpack.optimize.UglifyJsPlugin()
<ide> ```
<ide>
<del>You can learn more about this in [Webpack documentation](https://webpack.js.org/guides/production-build/).
<add>You can learn more about this in [webpack documentation](https://webpack.js.org/guides/production-build/).
<ide>
<ide> Remember that you only need to do this for production builds. You shouldn't apply `UglifyJsPlugin` or `DefinePlugin` with `'production'` value in development because they will hide useful React warnings, and make the builds much slower.
<ide> | 8 |
PHP | PHP | fix some formatting | 83a9eebab62897388de56f2bdceb03e844ba5d0a | <ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function getValue($attribute)
<ide> protected function isValidatable($rule, $attribute, $value)
<ide> {
<ide> return $this->presentOrRuleIsImplicit($rule, $attribute, $value) &&
<del> $this->passesOptionalCheck($attribute);
<add> $this->passesOptionalCheck($attribute);
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | expand test on disk attributes | e69a7cb93a1077646786e447887bf31a0c9f9916 | <ide><path>libcloud/test/compute/test_dimensiondata.py
<ide> def test_list_nodes_response_strings_ALLFILTERS(self):
<ide> ex_started=True, ex_state='fake_state',
<ide> ex_network='fake_network', ex_network_domain='fake_network_domain')
<ide> self.assertTrue(isinstance(ret, list))
<add> self.assertEqual(len(ret), 7)
<add>
<add> node = ret[3]
<add> self.assertTrue(isinstance(node.extra['disks'], list))
<add> self.assertTrue(isinstance(node.extra['disks'][0], DimensionDataServerDisk))
<add> disk = node.extra['disks'][0]
<add> self.assertEqual(disk.id, "c2e1f199-116e-4dbc-9960-68720b832b0a")
<add> self.assertEqual(disk.scsi_id, 0)
<add> self.assertEqual(disk.size_gb, 50)
<add> self.assertEqual(disk.speed, "STANDARD")
<add> self.assertEqual(disk.state, "NORMAL")
<ide>
<ide> def test_list_nodes_response_LOCATION(self):
<ide> DimensionDataMockHttp.type = None | 1 |
Ruby | Ruby | use strings for the table names | 6ebc8ca36c1840969cd5d003d9eb97bcad106d1c | <ide><path>activerecord/test/cases/migration/create_join_table_test.rb
<ide> def setup
<ide>
<ide> def teardown
<ide> super
<del> [:artists_musics, :musics_videos, :catalog].each do |table_name|
<add> %w(artists_musics musics_videos catalog).each do |table_name|
<ide> connection.drop_table table_name if connection.tables.include?(table_name)
<ide> end
<ide> end | 1 |
Ruby | Ruby | contemplate unsupported metrics | 0d1f7584ba25e7289871b5503f010874bc2aef49 | <ide><path>activesupport/lib/active_support/testing/performance.rb
<ide> class Performer
<ide> delegate :run_test, :full_profile_options, :full_test_name, :to => :@harness
<ide>
<ide> def initialize(harness, metric)
<del> @harness, @metric = harness, metric
<add> @harness, @metric, @supported = harness, metric, false
<ide> end
<ide>
<ide> def report
<del> rate = @total / full_profile_options[:runs]
<del> '%20s: %s' % [@metric.name, @metric.format(rate)]
<add> if @supported
<add> rate = @total / full_profile_options[:runs]
<add> '%20s: %s' % [@metric.name, @metric.format(rate)]
<add> else
<add> '%20s: unsupported' % @metric.name
<add> end
<ide> end
<ide>
<ide> protected
<ide> def output_filename
<ide>
<ide> # overridden by each implementation
<ide> class Profiler < Performer
<del> def initialize(*args)
<del> super
<del> @supported = false
<del> end
<del>
<del> def report
<del> if @supported
<del> super
<del> else
<del> '%20s: unsupported' % @metric.name
<del> end
<del> end
<del>
<ide> def time_with_block
<ide> before = Time.now
<ide> yield
<ide> def run; end
<ide> def record; end
<ide> end
<ide>
<del> class Benchmarker < Performer
<add> class Benchmarker < Performer
<add> def initialize(*args)
<add> super
<add> @supported = @metric.respond_to?('measure')
<add> end
<add>
<ide> def run
<add> return unless @supported
<add>
<ide> full_profile_options[:runs].to_i.times { run_test(@metric, :benchmark) }
<ide> @total = @metric.total
<ide> end
<ide> def name
<ide> end
<ide>
<ide> def benchmark
<add> @unsureturn if measure.nil?
<add>
<ide> with_gc_stats do
<ide> before = measure
<ide> yield
<ide><path>activesupport/lib/active_support/testing/performance/ruby.rb
<ide> def measure
<ide>
<ide> class Memory < DigitalInformationUnit
<ide> Mode = RubyProf::MEMORY if RubyProf.const_defined?(:MEMORY)
<del>
<del> # overridden by each implementation
<del> def measure; end
<ide> end
<ide>
<ide> class Objects < Amount
<ide> Mode = RubyProf::ALLOCATIONS if RubyProf.const_defined?(:ALLOCATIONS)
<del>
<del> # overridden by each implementation
<del> def measure; end
<ide> end
<ide>
<ide> class GcRuns < Amount
<ide> Mode = RubyProf::GC_RUNS if RubyProf.const_defined?(:GC_RUNS)
<del>
<del> # overridden by each implementation
<del> def measure; end
<ide> end
<ide>
<ide> class GcTime < Time
<ide> Mode = RubyProf::GC_TIME if RubyProf.const_defined?(:GC_TIME)
<del>
<del> # overridden by each implementation
<del> def measure; end
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/testing/performance/ruby/yarv.rb
<ide> def with_gc_stats
<ide> end
<ide>
<ide> class Memory < DigitalInformationUnit
<del> # Ruby 1.9 + GCdata patch
<add> # Ruby 1.9 + GCdata patch
<ide> if GC.respond_to?(:malloc_allocated_size)
<ide> def measure
<ide> GC.malloc_allocated_size | 3 |
Python | Python | handle compiler checks for pyf | 2d6341542d6888cd9811961de296dbacee6cc4be | <ide><path>numpy/f2py/tests/util.py
<ide> def setup(self):
<ide> # Check compiler availability first
<ide> if not has_c_compiler():
<ide> pytest.skip("No C compiler available")
<del> if not has_f77_compiler():
<del> pytest.skip("No Fortran 77 compiler available")
<del> if not has_f90_compiler():
<del> pytest.skip("No Fortran 90 compiler available")
<ide>
<ide> codes = []
<ide> if self.sources:
<ide> def setup(self):
<ide>
<ide> needs_f77 = False
<ide> needs_f90 = False
<add> needs_pyf = False
<ide> for fn in codes:
<ide> if str(fn).endswith(".f"):
<ide> needs_f77 = True
<ide> elif str(fn).endswith(".f90"):
<ide> needs_f90 = True
<add> elif str(fn).endswith(".pyf"):
<add> needs_pyf = True
<add> if needs_f77 and not has_f77_compiler():
<add> pytest.skip("No Fortran 77 compiler available")
<add> if needs_f90 and not has_f90_compiler():
<add> pytest.skip("No Fortran 90 compiler available")
<add> if needs_pyf and not (has_f90_compiler() or has_f77_compiler()):
<add> pytest.skip("No Fortran compiler available")
<ide>
<ide> # Build the module
<ide> if self.code is not None: | 1 |
Python | Python | fix coding style for feature extractor | 1cf70ed77c0cbd0b8f7114d86337474ed199f877 | <ide><path>research/object_detection/models/faster_rcnn_resnet_v1_fpn_keras_feature_extractor.py
<ide> from object_detection.meta_architectures import faster_rcnn_meta_arch
<ide> from object_detection.models import feature_map_generators
<ide> from object_detection.models.keras_models import resnet_v1
<del>from object_detection.models.keras_models import model_utils
<del>from object_detection.utils import ops
<del>from object_detection.utils import shape_utils
<add>
<ide>
<ide> _RESNET_MODEL_OUTPUT_LAYERS = {
<ide> 'resnet_v1_50': ['conv2_block3_out', 'conv3_block4_out',
<ide>
<ide>
<ide> class FasterRCNNResnetV1FPNKerasFeatureExtractor(
<del> faster_rcnn_meta_arch.FasterRCNNFeatureExtractor):
<add> faster_rcnn_meta_arch.FasterRCNNKerasFeatureExtractor):
<ide> """Faster RCNN Feature Extractor using Keras-based Resnet V1 FPN features."""
<ide>
<ide> def __init__(self,
<ide> def __init__(self,
<ide> fpn_max_level=7,
<ide> additional_layer_depth=256,
<ide> override_base_feature_extractor_hyperparams=False):
<del> # FIXME: fix doc string for fpn min level and fpn max level
<ide> """Constructor.
<ide>
<ide> Args:
<ide> is_training: See base class.
<add> resnet_v1_base_model: base resnet v1 network to use. One of
<add> the resnet_v1.resnet_v1_{50,101,152} models.
<add> resnet_v1_base_model_name: model name under which to construct resnet v1.
<ide> first_stage_features_stride: See base class.
<del>
<ide> conv_hyperparameters: a `hyperparams_builder.KerasLayerHyperparams` object
<ide> containing convolution hyperparameters for the layers added on top of
<ide> the base feature extractor.
<ide> min_depth: Minimum number of filters in the convolutional layers.
<ide> depth_multiplier: The depth multiplier to modify the number of filters
<ide> in the convolutional layers.
<del> resnet_v1_base_model: base resnet v1 network to use. One of
<del> the resnet_v1.resnet_v1_{50,101,152} models.
<del> resnet_v1_base_model_name: model name under which to construct resnet v1.
<del>
<ide> batch_norm_trainable: See base class.
<ide> weight_decay: See base class.
<del>
<ide> fpn_min_level: the highest resolution feature map to use in FPN. The valid
<del> values are {2, 3, 4, 5} which map to MobileNet v1 layers
<del> {Conv2d_3_pointwise, Conv2d_5_pointwise, Conv2d_11_pointwise,
<del> Conv2d_13_pointwise}, respectively.
<add> values are {2, 3, 4, 5} which map to Resnet v1 layers.
<ide> fpn_max_level: the smallest resolution feature map to construct or use in
<ide> FPN. FPN constructions uses features maps starting from fpn_min_level
<ide> upto the fpn_max_level. In the case that there are not enough feature
<ide> def __init__(self,
<ide> """
<ide> if first_stage_features_stride != 8 and first_stage_features_stride != 16:
<ide> raise ValueError('`first_stage_features_stride` must be 8 or 16.')
<add>
<ide> super(FasterRCNNResnetV1FPNKerasFeatureExtractor, self).__init__(
<del> is_training=is_training,
<del> first_stage_features_stride=first_stage_features_stride,
<del> batch_norm_trainable=batch_norm_trainable,
<del> weight_decay=weight_decay)
<add> is_training=is_training,
<add> first_stage_features_stride=first_stage_features_stride,
<add> batch_norm_trainable=batch_norm_trainable,
<add> weight_decay=weight_decay)
<add>
<add> self._resnet_v1_base_model = resnet_v1_base_model
<add> self._resnet_v1_base_model_name = resnet_v1_base_model_name
<ide> self._conv_hyperparams = conv_hyperparams
<ide> self._min_depth = min_depth
<ide> self._depth_multiplier = depth_multiplier
<add> self._fpn_min_level = fpn_min_level
<add> self._fpn_max_level = fpn_max_level
<ide> self._additional_layer_depth = additional_layer_depth
<ide> self._freeze_batchnorm = (not batch_norm_trainable)
<ide> self._override_base_feature_extractor_hyperparams = \
<ide> override_base_feature_extractor_hyperparams
<del> self._fpn_min_level = fpn_min_level
<del> self._fpn_max_level = fpn_max_level
<del> self._resnet_v1_base_model = resnet_v1_base_model
<del> self._resnet_v1_base_model_name = resnet_v1_base_model_name
<ide> self._resnet_block_names = ['block1', 'block2', 'block3', 'block4']
<ide> self.classification_backbone = None
<ide> self._fpn_features_generator = None
<ide> def preprocess(self, resized_inputs):
<ide> return resized_inputs - [[channel_means]]
<ide> else:
<ide> return resized_inputs
<del>
<add>
<ide> def get_proposal_feature_extractor_model(self, name=None):
<ide> """Returns a model that extracts first stage RPN features.
<ide>
<del> Extracts features using the first half of the Resnet v1 network.
<add> Extracts features using the Resnet v1 FPN network.
<ide>
<ide> Args:
<ide> name: A scope name to construct all variables within.
<ide> def get_proposal_feature_extractor_model(self, name=None):
<ide> A Keras model that takes preprocessed_inputs:
<ide> A [batch, height, width, channels] float32 tensor
<ide> representing a batch of images.
<add>
<add> And returns rpn_feature_map:
<add> A list of tensors with shape [batch, height, width, depth]
<ide> """
<ide> with tf.name_scope(name):
<ide> with tf.name_scope('ResnetV1FPN'):
<ide> def get_proposal_feature_extractor_model(self, name=None):
<ide> include_top=False)
<ide> output_layers = _RESNET_MODEL_OUTPUT_LAYERS[self._resnet_v1_base_model_name]
<ide> outputs = [full_resnet_v1_model.get_layer(output_layer_name).output
<del> for output_layer_name in output_layers]
<add> for output_layer_name in output_layers]
<ide> self.classification_backbone = tf.keras.Model(
<ide> inputs=full_resnet_v1_model.inputs,
<ide> outputs=outputs)
<ide> def get_proposal_feature_extractor_model(self, name=None):
<ide> conv_hyperparams=self._conv_hyperparams,
<ide> freeze_batchnorm=self._freeze_batchnorm,
<ide> name='FeatureMaps'))
<del>
<add>
<ide> feature_block_list = []
<ide> for level in range(self._fpn_min_level, self._base_fpn_max_level + 1):
<ide> feature_block_list.append('block{}'.format(level - 1))
<ide> def get_proposal_feature_extractor_model(self, name=None):
<ide> def get_box_classifier_feature_extractor_model(self, name=None):
<ide> """Returns a model that extracts second stage box classifier features.
<ide>
<del> TODO: doc
<add> Construct two fully connected layer to extract the box classifier features.
<ide>
<ide> Args:
<ide> name: A scope name to construct all variables within.
<ide> def get_box_classifier_feature_extractor_model(self, name=None):
<ide> A 4-D float tensor with shape
<ide> [batch_size * self.max_num_proposals, crop_height, crop_width, depth]
<ide> representing the feature map cropped to each proposal.
<add>
<ide> And returns proposal_classifier_features:
<ide> A 4-D float tensor with shape
<del> [batch_size * self.max_num_proposals, height, width, depth]
<add> [batch_size * self.max_num_proposals, 1024]
<ide> representing box classifier features for each proposal.
<ide> """
<ide> with tf.name_scope(name):
<ide> with tf.name_scope('ResnetV1FPN'):
<ide> feature_extractor_model = tf.keras.models.Sequential([
<del> tf.keras.layers.Flatten(),
<del> tf.keras.layers.Dense(units=1024, activation='relu'),
<del> tf.keras.layers.Dense(units=1024, activation='relu')
<add> tf.keras.layers.Flatten(),
<add> tf.keras.layers.Dense(units=1024, activation='relu'),
<add> tf.keras.layers.Dense(units=1024, activation='relu')
<ide> ])
<ide> return feature_extractor_model
<ide>
<ide>
<ide> class FasterRCNNResnet50FPNKerasFeatureExtractor(
<ide> FasterRCNNResnetV1FPNKerasFeatureExtractor):
<ide> """Faster RCNN with Resnet50 FPN feature extractor implementation."""
<del>
<add>
<ide> def __init__(self,
<ide> is_training,
<ide> first_stage_features_stride=16,
<ide> def __init__(self,
<ide> additional_layer_depth=additional_layer_depth,
<ide> override_base_feature_extractor_hyperparams=override_base_feature_extractor_hyperparams)
<ide>
<add>
<ide> class FasterRCNNResnet101FPNKerasFeatureExtractor(
<ide> FasterRCNNResnetV1FPNKerasFeatureExtractor):
<ide> """Faster RCNN with Resnet101 FPN feature extractor implementation.""" | 1 |
Java | Java | fix checkstyle errors | bd910fc62b87b052968cd5a52458159d9fb6333e | <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/view/AbstractViewTests.java
<ide> import org.springframework.web.reactive.BindingContext;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide>
<del>import static org.junit.Assert.*;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertNotNull;
<add>import static org.junit.Assert.assertNull;
<ide>
<ide> /**
<ide> * Unit tests for {@link AbstractView}. | 1 |
Go | Go | add authentification to all registry call | 4307b7dd8ea8d2cdfdf749383f514e656ae8a408 | <ide><path>commands.go
<ide> func (srv *Server) CmdPush(stdin io.ReadCloser, stdout io.Writer, args ...string
<ide> }
<ide> // If it fails, try to get the repository
<ide> if repo, exists := srv.runtime.repositories.Repositories[cmd.Arg(0)]; exists {
<del> if err := srv.runtime.graph.PushRepository(*user, cmd.Arg(0), repo); err != nil {
<add> if err := srv.runtime.graph.PushRepository(*user, cmd.Arg(0), repo, srv.runtime.authConfig); err != nil {
<ide> return err
<ide> }
<ide> } else {
<ide> return err
<ide> }
<ide> return nil
<ide> }
<del> return srv.runtime.graph.PushImage(img)
<add> return srv.runtime.graph.PushImage(img, srv.runtime.authConfig)
<ide> }
<ide>
<ide> func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
<ide> func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string
<ide> return nil
<ide> }
<ide>
<del> if srv.runtime.graph.LookupRemoteImage(cmd.Arg(0)) {
<del> return srv.runtime.graph.PullImage(cmd.Arg(0))
<add> if srv.runtime.graph.LookupRemoteImage(cmd.Arg(0), srv.runtime.authConfig) {
<add> return srv.runtime.graph.PullImage(cmd.Arg(0), srv.runtime.authConfig)
<ide> }
<ide> if *user == "" {
<ide> return fmt.Errorf("Not loggin and no user specified\n")
<ide><path>registry.go
<ide> func NewMultipleImgJson(src []byte) ([]*Image, error) {
<ide>
<ide> // Retrieve the history of a given image from the Registry.
<ide> // Return a list of the parent's json (requested image included)
<del>func (graph *Graph) getRemoteHistory(imgId string) ([]*Image, error) {
<del> res, err := http.Get(REGISTRY_ENDPOINT + "/images/" + imgId + "/history")
<add>func (graph *Graph) getRemoteHistory(imgId string, authConfig *auth.AuthConfig) ([]*Image, error) {
<add> client := &http.Client{}
<add>
<add> req, err := http.NewRequest("GET", REGISTRY_ENDPOINT+"/images/"+imgId+"/history", nil)
<add> if err != nil {
<add> return nil, err
<add> }
<add> req.SetBasicAuth(authConfig.Username, authConfig.Password)
<add> res, err := client.Do(req)
<ide> if err != nil {
<del> return nil, fmt.Errorf("Error while getting from the server: %s\n", err)
<add> return nil, err
<ide> }
<ide> defer res.Body.Close()
<ide>
<ide> func (graph *Graph) getRemoteHistory(imgId string) ([]*Image, error) {
<ide> }
<ide>
<ide> // Check if an image exists in the Registry
<del>func (graph *Graph) LookupRemoteImage(imgId string) bool {
<del> res, err := http.Get(REGISTRY_ENDPOINT + "/images/" + imgId + "/json")
<add>func (graph *Graph) LookupRemoteImage(imgId string, authConfig *auth.AuthConfig) bool {
<add> client := &http.Client{}
<add>
<add> req, err := http.NewRequest("GET", REGISTRY_ENDPOINT+"/images/"+imgId+"/json", nil)
<add> if err != nil {
<add> return false
<add> }
<add> req.SetBasicAuth(authConfig.Username, authConfig.Password)
<add> res, err := client.Do(req)
<ide> if err != nil {
<ide> return false
<ide> }
<ide> func (graph *Graph) LookupRemoteImage(imgId string) bool {
<ide>
<ide> // Retrieve an image from the Registry.
<ide> // Returns the Image object as well as the layer as an Archive (io.Reader)
<del>func (graph *Graph) getRemoteImage(imgId string) (*Image, Archive, error) {
<add>func (graph *Graph) getRemoteImage(imgId string, authConfig *auth.AuthConfig) (*Image, Archive, error) {
<add> client := &http.Client{}
<add>
<ide> // Get the Json
<del> res, err := http.Get(REGISTRY_ENDPOINT + "/images/" + imgId + "/json")
<add> req, err := http.NewRequest("GET", REGISTRY_ENDPOINT+"/images/"+imgId+"/json", nil)
<ide> if err != nil {
<ide> return nil, nil, fmt.Errorf("Error while getting from the server: %s\n", err)
<ide> }
<add> req.SetBasicAuth(authConfig.Username, authConfig.Password)
<add> res, err := client.Do(req)
<add> if err != nil {
<add> return nil, nil, err
<add> }
<ide> defer res.Body.Close()
<ide>
<ide> jsonString, err := ioutil.ReadAll(res.Body)
<ide> func (graph *Graph) getRemoteImage(imgId string) (*Image, Archive, error) {
<ide> return img, res.Body, nil
<ide> }
<ide>
<del>func (graph *Graph) PullImage(imgId string) error {
<del> history, err := graph.getRemoteHistory(imgId)
<add>func (graph *Graph) PullImage(imgId string, authConfig *auth.AuthConfig) error {
<add> history, err := graph.getRemoteHistory(imgId, authConfig)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> // FIXME: Try to stream the images?
<ide> // FIXME: Lunch the getRemoteImage() in goroutines
<ide> for _, j := range history {
<ide> if !graph.Exists(j.Id) {
<del> img, layer, err := graph.getRemoteImage(j.Id)
<add> img, layer, err := graph.getRemoteImage(j.Id, authConfig)
<ide> if err != nil {
<ide> // FIXME: Keep goging in case of error?
<ide> return err
<ide> func (graph *Graph) PullRepository(user, repoName, askedTag string, repositories
<ide> if err != nil {
<ide> return err
<ide> }
<del>
<ide> req.SetBasicAuth(authConfig.Username, authConfig.Password)
<ide> res, err := client.Do(req)
<ide> if err != nil {
<ide> return err
<ide> }
<add> defer res.Body.Close()
<ide> rawJson, err := ioutil.ReadAll(res.Body)
<ide> if err != nil {
<ide> return err
<ide> func (graph *Graph) PullRepository(user, repoName, askedTag string, repositories
<ide> return err
<ide> }
<ide> for tag, rev := range t {
<del> if err = graph.PullImage(rev); err != nil {
<add> if err = graph.PullImage(rev, authConfig); err != nil {
<ide> return err
<ide> }
<ide> if err = repositories.Set(repoName, tag, rev); err != nil {
<ide> func (graph *Graph) PullRepository(user, repoName, askedTag string, repositories
<ide> }
<ide>
<ide> // Push a local image to the registry with its history if needed
<del>func (graph *Graph) PushImage(imgOrig *Image) error {
<add>func (graph *Graph) PushImage(imgOrig *Image, authConfig *auth.AuthConfig) error {
<ide> client := &http.Client{}
<ide>
<ide> // FIXME: Factorize the code
<ide> func (graph *Graph) PushImage(imgOrig *Image) error {
<ide> if err != nil {
<ide> return err
<ide> }
<add> req.SetBasicAuth(authConfig.Username, authConfig.Password)
<ide> res, err := client.Do(req)
<ide> if err != nil || res.StatusCode != 200 {
<ide> if res == nil {
<ide> func (graph *Graph) PushImage(imgOrig *Image) error {
<ide> }
<ide>
<ide> req2, err := http.NewRequest("PUT", REGISTRY_ENDPOINT+"/images/"+img.Id+"/layer", nil)
<add> req2.SetBasicAuth(authConfig.Username, authConfig.Password)
<ide> res2, err := client.Do(req2)
<ide> if err != nil || res2.StatusCode != 307 {
<ide> return fmt.Errorf(
<ide> func (graph *Graph) PushImage(imgOrig *Image) error {
<ide> img.Id, err)
<ide> }
<ide> req3, err := http.NewRequest("PUT", url.String(), layerData)
<del> tmp, _ := ioutil.ReadAll(layerData2)
<add> if err != nil {
<add> return err
<add> }
<add> tmp, err := ioutil.ReadAll(layerData2)
<add> if err != nil {
<add> return err
<add> }
<ide> req3.ContentLength = int64(len(tmp))
<ide>
<ide> req3.TransferEncoding = []string{"none"}
<ide> func (graph *Graph) PushImage(imgOrig *Image) error {
<ide> return nil
<ide> }
<ide>
<del>func (graph *Graph) pushTag(user, repo, revision, tag string) error {
<add>func (graph *Graph) pushTag(user, repo, revision, tag string, authConfig *auth.AuthConfig) error {
<ide>
<ide> if tag == "" {
<ide> tag = "lastest"
<ide> func (graph *Graph) pushTag(user, repo, revision, tag string) error {
<ide> client := &http.Client{}
<ide> req, err := http.NewRequest("PUT", REGISTRY_ENDPOINT+"/users/"+user+"/"+repo+"/"+tag, strings.NewReader(revision))
<ide> req.Header.Add("Content-type", "application/json")
<add> req.SetBasicAuth(authConfig.Username, authConfig.Password)
<ide> res, err := client.Do(req)
<ide> if err != nil {
<ide> return err
<ide> func (graph *Graph) pushTag(user, repo, revision, tag string) error {
<ide> return nil
<ide> }
<ide>
<del>func (graph *Graph) PushRepository(user, repoName string, repo Repository) error {
<add>func (graph *Graph) PushRepository(user, repoName string, repo Repository, authConfig *auth.AuthConfig) error {
<ide> for tag, imgId := range repo {
<ide> fmt.Printf("tag: %s, imgId: %s\n", tag, imgId)
<ide> img, err := graph.Get(imgId)
<ide> if err != nil {
<ide> return err
<ide> }
<del> if err = graph.PushImage(img); err != nil {
<add> if err = graph.PushImage(img, authConfig); err != nil {
<ide> return err
<ide> }
<del> if err = graph.pushTag(user, repoName, imgId, tag); err != nil {
<add> if err = graph.pushTag(user, repoName, imgId, tag, authConfig); err != nil {
<ide> return err
<ide> }
<ide> } | 2 |
Javascript | Javascript | remove duplicate `$digest()` | 4f9ac078d561b45deb1ca44dfb04fb58f97c7f27 | <ide><path>src/ng/rootScope.js
<ide> function $RootScopeProvider(){
<ide> * @description
<ide> * Creates a new child {@link ng.$rootScope.Scope scope}.
<ide> *
<del> * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
<del> * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the
<del> * scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
<add> * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
<add> * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
<ide> *
<ide> * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
<ide> * desired for the scope and its child scopes to be permanently detached from the parent and | 1 |
Javascript | Javascript | fix @param type for `ngchange` | 21a2f4bb2310f5cea69d637568ca6c21f2815270 | <ide><path>src/ng/directive/input.js
<ide> var inputType = {
<ide> * Can be interpolated.
<ide> * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
<ide> * Can be interpolated.
<del> * @param {string=} ngChange AngularJS expression to be executed when the ngModel value changes due
<del> * to user interaction with the input element.
<add> * @param {expression=} ngChange AngularJS expression to be executed when the ngModel value changes due
<add> * to user interaction with the input element.
<ide> * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
<ide> * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
<ide> * Checkout {@link ng.directive:ngChecked ngChecked} for usage. | 1 |
Javascript | Javascript | fix mixed whitespace | 2e4bb1899f32db31b48291a7755d461ca0af0072 | <ide><path>src/Chart.Core.js
<ide> // Boolean - whether or not the chart should be responsive and resize when the browser does.
<ide> responsive: false,
<ide>
<del> // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
<del> maintainAspectRatio: true,
<add> // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
<add> maintainAspectRatio: true,
<ide>
<ide> // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
<ide> showTooltips: true,
<ide> //Templating methods
<ide> //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
<ide> template = helpers.template = function(templateString, valuesObject){
<del> // If templateString is function rather than string-template - call the function for valuesObject
<add>
<add> // If templateString is function rather than string-template - call the function for valuesObject
<add>
<ide> if(templateString instanceof Function){
<ide> return templateString(valuesObject);
<ide> }
<ide> newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas);
<ide>
<ide> canvas.width = this.chart.width = newWidth;
<del> canvas.height = this.chart.height = newHeight;
<add> canvas.height = this.chart.height = newHeight;
<ide>
<ide> retinaScale(this.chart);
<ide> | 1 |
Python | Python | use roberta model and update doc strings | b92d68421dee75c3a078b26b78a05bd59007d855 | <ide><path>transformers/modeling_roberta.py
<ide> class RobertaForTokenClassification(BertPreTrainedModel):
<ide>
<ide> tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
<ide> model = RobertaForTokenClassification.from_pretrained('roberta-base')
<del> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
<add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
<ide> labels = torch.tensor([1] * input_ids.size(1)).unsqueeze(0) # Batch size 1
<ide> outputs = model(input_ids, labels=labels)
<ide> loss, scores = outputs[:2]
<ide>
<ide> """
<add> config_class = RobertaConfig
<add> pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP
<add> base_model_prefix = "roberta"
<add>
<ide> def __init__(self, config):
<ide> super(RobertaForTokenClassification, self).__init__(config)
<ide> self.num_labels = config.num_labels
<ide><path>transformers/modeling_tf_roberta.py
<ide> class TFRobertaForTokenClassification(TFRobertaPreTrainedModel):
<ide>
<ide> tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
<ide> model = TFRobertaForTokenClassification.from_pretrained('roberta-base')
<del> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute"))[None, :] # Batch size 1
<add> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True))[None, :] # Batch size 1
<ide> outputs = model(input_ids)
<ide> scores = outputs[0]
<ide> | 2 |
Javascript | Javascript | remove manual clamping code in `src/core/jpx.js` | 563b68e74d82fec352783f2b54dac90228b59a72 | <ide><path>src/core/jpx.js
<ide> var JpxImage = (function JpxImageClosure() {
<ide> };
<ide>
<ide> // Section G.2.2 Inverse multi component transform
<del> var shift, offset, max, min, maxK;
<del> var pos = 0, j, jj, y0, y1, y2, r, g, b, k, val;
<add> var shift, offset;
<add> var pos = 0, j, jj, y0, y1, y2;
<ide> if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
<ide> var fourComponents = componentsCount === 4;
<ide> var y0items = transformedTiles[0].items;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> // compute shift and offset only once.
<ide> shift = components[0].precision - 8;
<ide> offset = (128 << shift) + 0.5;
<del> max = 255 * (1 << shift);
<del> maxK = max * 0.5;
<del> min = -maxK;
<ide>
<ide> var component0 = tile.components[0];
<ide> var alpha01 = componentsCount - 3;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> y0 = y0items[j] + offset;
<ide> y1 = y1items[j];
<ide> y2 = y2items[j];
<del> r = y0 + 1.402 * y2;
<del> g = y0 - 0.34413 * y1 - 0.71414 * y2;
<del> b = y0 + 1.772 * y1;
<del> out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
<del> out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
<del> out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
<add> out[pos++] = (y0 + 1.402 * y2) >> shift;
<add> out[pos++] = (y0 - 0.34413 * y1 - 0.71414 * y2) >> shift;
<add> out[pos++] = (y0 + 1.772 * y1) >> shift;
<ide> }
<ide> } else {
<ide> // inverse reversible multiple component transform
<ide> for (j = 0; j < jj; j++, pos += alpha01) {
<ide> y0 = y0items[j] + offset;
<ide> y1 = y1items[j];
<ide> y2 = y2items[j];
<del> g = y0 - ((y2 + y1) >> 2);
<del> r = g + y2;
<del> b = g + y1;
<del> out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
<del> out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
<del> out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
<add> let g = y0 - ((y2 + y1) >> 2);
<add>
<add> out[pos++] = (g + y2) >> shift;
<add> out[pos++] = g >> shift;
<add> out[pos++] = (g + y1) >> shift;
<ide> }
<ide> }
<ide> if (fourComponents) {
<ide> for (j = 0, pos = 3; j < jj; j++, pos += 4) {
<del> k = y3items[j];
<del> out[pos] = k <= min ? 0 : k >= maxK ? 255 : (k + offset) >> shift;
<add> out[pos] = (y3items[j] + offset) >> shift;
<ide> }
<ide> }
<ide> } else { // no multi-component transform
<ide> for (c = 0; c < componentsCount; c++) {
<ide> var items = transformedTiles[c].items;
<ide> shift = components[c].precision - 8;
<ide> offset = (128 << shift) + 0.5;
<del> max = (127.5 * (1 << shift));
<del> min = -max;
<ide> for (pos = c, j = 0, jj = items.length; j < jj; j++) {
<del> val = items[j];
<del> out[pos] = val <= min ? 0 :
<del> val >= max ? 255 : (val + offset) >> shift;
<add> out[pos] = (items[j] + offset) >> shift;
<ide> pos += componentsCount;
<ide> }
<ide> } | 1 |
Python | Python | add tests for inputs set dynamically | 52f608cbe7cf685bd9f92fcedc3ef02ba4292dc6 | <ide><path>tests/keras/engine/test_training.py
<ide>
<ide> import keras
<ide> from keras import losses
<del>from keras.layers import Activation, Dense, Dropout, Conv2D
<add>from keras.layers import Activation, Dense, Dropout, Conv2D, Concatenate
<ide> from keras.engine import Input
<ide> from keras.engine.training import Model
<ide> from keras.engine import training_utils
<ide> def test_dynamic_set_inputs():
<ide> assert preds2.shape == (1, 8)
<ide>
<ide> model3 = Model(inputs=model.inputs, outputs=model.outputs)
<add> with pytest.raises(ValueError):
<add> model3._set_inputs(model.inputs)
<add>
<ide> model3.inputs = None
<ide> model3._set_inputs(model.inputs)
<ide> preds3 = model3.predict([np.random.random((1, 32))])
<ide> assert preds3.shape == (1, 16)
<ide>
<add> model3.inputs = None
<add> model3._set_inputs(model.input)
<add> preds3 = model3.predict(np.random.random((1, 32)))
<add> assert preds3.shape == (1, 16)
<add>
<add> aux_input = Input(shape=(5,), name='aux_input')
<add> aux_model = Dense(3)(aux_input)
<add> model4 = Model(inputs=model.inputs + [aux_input],
<add> outputs=Concatenate()(model.outputs + [aux_model]))
<add> model4.inputs = None
<add> model4._set_inputs(model.inputs + [aux_input])
<add> preds4 = model4.predict([np.random.random((1, 32)),
<add> np.random.random((1, 5))])
<add> assert preds4.shape == (1, 19)
<add>
<ide>
<ide> if __name__ == '__main__':
<ide> pytest.main([__file__]) | 1 |
Python | Python | prevent bert weights from being downloaded twice | 076602bdc4b186e715538f437f2bce4b1ee5020e | <ide><path>examples/summarization/modeling_bertabs.py
<ide> class Bert(nn.Module):
<ide>
<ide> def __init__(self):
<ide> super(Bert, self).__init__()
<del> self.model = BertModel.from_pretrained("bert-base-uncased")
<add> config = BertConfig.from_pretrained("bert-base-uncased")
<add> self.model = BertModel(config)
<ide>
<ide> def forward(self, input_ids, attention_mask=None, token_type_ids=None, **kwargs):
<ide> self.eval() | 1 |
Ruby | Ruby | fix typo in comment [ci skip] | c1ae3d7731e55ac5966500d4f2da6057c71c9510 | <ide><path>activesupport/lib/active_support/test_case.rb
<ide> class << self
<ide>
<ide> def self.__run reporter, options # :nodoc:
<ide> # FIXME: MT5's runnables is not ordered. This is needed because
<del> # we have have tests have cross-class order-dependent bugs.
<add> # we have tests with cross-class order-dependent bugs.
<ide> suites = Runnable.runnables.sort_by { |ts| ts.name.to_s }
<ide>
<ide> parallel, serial = suites.partition { |s| s.test_order == :parallel } | 1 |
Ruby | Ruby | fix patching when patch already fetched | 2ffb87cb0312c28db8c04afa89736b1fed6a805c | <ide><path>Library/Homebrew/resource.rb
<ide> def prepare_patches
<ide> end
<ide>
<ide> def fetch_patches(skip_downloaded: false)
<del> patches.select!(&:external?)
<del> patches.reject!(&:downloaded?) if skip_downloaded
<del> patches.each(&:fetch)
<add> patches.each do |p|
<add> next unless p.external?
<add> next if p.downloaded? && skip_downloaded
<add>
<add> p.fetch
<add> end
<ide> end
<ide>
<ide> def apply_patches | 1 |
Python | Python | implement cors for the restful api | 89eee581dbb4dcb59c151f6efa637e100beb3c9a | <ide><path>glances/outputs/glances_bottle.py
<ide>
<ide> # Import mandatory Bottle lib
<ide> try:
<del> from bottle import Bottle, template, static_file, TEMPLATE_PATH, abort, response
<add> from bottle import Bottle, template, static_file, TEMPLATE_PATH, abort, response, request
<ide> except ImportError:
<ide> logger.critical('Bottle module not found. Glances cannot start in web server mode.')
<ide> sys.exit(2)
<ide> def __init__(self, args=None):
<ide>
<ide> # Init Bottle
<ide> self._app = Bottle()
<add> # Enable CORS (issue #479)
<add> self._app.install(EnableCors())
<add> # Define routes
<ide> self._route()
<ide>
<ide> # Update the template path (glances/outputs/bottle)
<ide> def _favicon(self):
<ide> # Return the static file
<ide> return static_file('favicon.ico', root=self.STATIC_PATH)
<ide>
<add> def enable_cors(self):
<add> """Enable CORS"""
<add> response.headers['Access-Control-Allow-Origin'] = '*'
<add> response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
<add> response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
<add>
<ide> def _api_plugins(self):
<ide> """
<ide> Glances API RESTFul implementation
<ide> def display(self, stats, refresh_time=None):
<ide> }
<ide>
<ide> return template('base', refresh_time=refresh_time, stats=stats)
<add>
<add>
<add>class EnableCors(object):
<add> name = 'enable_cors'
<add> api = 2
<add>
<add> def apply(self, fn, context):
<add> def _enable_cors(*args, **kwargs):
<add> # set CORS headers
<add> response.headers['Access-Control-Allow-Origin'] = '*'
<add> response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
<add> response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
<add>
<add> if request.method != 'OPTIONS':
<add> # actual request; reply with the actual response
<add> return fn(*args, **kwargs)
<add>
<add> return _enable_cors | 1 |
Javascript | Javascript | remove unused argument | c697618e1141e40bcd61fb82e38490a274664c62 | <ide><path>server/read.js
<ide> import resolve from './resolve'
<ide> * and read and cache the file content
<ide> */
<ide>
<del>async function read (path, opts = {}) {
<add>async function read (path) {
<ide> const f = await resolve(path)
<ide> if (cache.hasOwnProperty(f)) {
<ide> return cache[f] | 1 |
Python | Python | fix static checks on main | 82f2ad3cb1ea1f1e5e2b0ef2c8c0c816a49f6465 | <ide><path>tests/charts/test_pod_template_file.py
<ide> def test_logs_persistence_changes_volume(self, log_persistence_values, expected)
<ide>
<ide> def test_should_set_a_custom_image_in_pod_template(self):
<ide> docs = render_chart(
<del> values={"images": {"pod_template": {"repository": "dummy_image", "tag": "latest", "pullPolicy": "Always"}}},
<add> values={
<add> "images": {
<add> "pod_template": {"repository": "dummy_image", "tag": "latest", "pullPolicy": "Always"}
<add> }
<add> },
<ide> show_only=["templates/pod-template-file.yaml"],
<ide> chart_dir=self.temp_chart_dir,
<ide> ) | 1 |
Javascript | Javascript | replace common.fixturesdir with fixtures module | 4de10273bbe7c4772bf142100945ed84dfc5e65d | <ide><path>test/parallel/test-fs-realpath-buffer-encoding.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide>
<del>const string_dir = fs.realpathSync(common.fixturesDir);
<add>const string_dir = fs.realpathSync(fixtures.fixturesDir);
<ide> const buffer_dir = Buffer.from(string_dir);
<ide>
<ide> const encodings = ['ascii', 'utf8', 'utf16le', 'ucs2', | 1 |
Text | Text | fix comma splice | 0bafe6dd219a62c5f8426e37be9807b88a62ecad | <ide><path>doc/api/http.md
<ide> added: v0.9.12
<ide>
<ide> * `msesc` {number}
<ide> * `callback` {Function} Optional function to be called when a timeout
<del>occurs, Same as binding to the `timeout` event.
<add> occurs. Same as binding to the `timeout` event.
<ide> * Returns: {this}
<ide>
<ide> Once a socket is associated with the message and is connected, | 1 |
Text | Text | add some basics | 41353e635f0b4301b7b0f1f024ef50c28ca9d8ad | <ide><path>SUMMARY.md
<ide> ## Summary
<ide>
<del>* [Glossary](docs/Glossary.md)
<add>* [Basics](/docs/basics/README.md)
<add> * [Motivation](/docs/basics/Motivation.md)
<add> * [Three Principles](/docs/basics/ThreePrinciples.md)
<add> * [Prior Art](/docs/basics/PriorArt.md)
<ide> * [API Reference](docs/api/README.md)
<ide> * [createStore](docs/api/createStore.md)
<ide> * [Store](docs/api/Store.md)
<ide> * [combineReducers](docs/api/combineReducers.md)
<ide> * [applyMiddleware](docs/api/applyMiddleware.md)
<ide> * [bindActionCreators](docs/api/bindActionCreators.md)
<del> * [compose](docs/api/compose.md)
<ide>\ No newline at end of file
<add> * [compose](docs/api/compose.md)
<add>* [Glossary](docs/Glossary.md)
<ide><path>docs/basics/Motivation.md
<add># Motivation
<add>
<add>As the requirements to JavaScript single-page applications get more sophisticated, more state than ever before needs to be managed by the JavaScript code. This state may include server responses, cached data, and data created locally and not yet persisted to the server. It also includes the UI state, such as the active route, the selected tab, whether to show a spinner or pagination controls, and so on.
<add>
<add>Managing an ever-changing state is hard. If a model can update another model, then a view can update a model that updates another model, and this, in turn, might cause another view to update… At some point you no longer know what happens in your app. You no longer control when, why, and how the state is updated. When the system is opaque and non-deterministic, it's hard to reproduce bugs or add new features.
<add>
<add>As if this wasn’t bad enough, consider the new requirements that are becoming common in front-end product development, such as handling optimistic updates, rendering on the server, fetching the data before performing route transitions, and so on. We the front-end developers are finding ourselves surrounded by the complexity we never had to deal with before. [Is it time we give up?](http://www.quirksmode.org/blog/archives/2015/07/stop_pushing_th.html)
<add>
<add>A lot of this complexity comes from the fact that we’re mixing two concepts that are very hard for the human mind to reason about: mutation and asynchronicity. I call them [Mentos and Coke](https://en.wikipedia.org/wiki/Diet_Coke_and_Mentos_eruption). Both can be great in separation, but together, they are a mess. Libraries like [React](http://facebook.github.io/react) attempt to solve this problem in the view layer by removing asynchrony and direct DOM manipulation. However, React leaves managing the state up to you.
<add>
<add>Following the steps of [Flux](http://facebook.github.io/flux), [CQRS](http://martinfowler.com/bliki/CQRS.html), and [Event Sourcing](http://martinfowler.com/eaaDev/EventSourcing.html), Redux attempts to make state mutations predictable by imposing certain restrictions on how and when they can happen. These restrictions are reflected in the [three principles](ThreePrinciples.md) of Redux.
<ide><path>docs/basics/PriorArt.md
<add># Prior Art
<add>
<add>Redux has a mixed heritage. It is similar to some patterns and technologies, but is also different from them in important ways. We explore some of the similarities and the differences below.
<add>
<add>### Flux
<add>
<add>Can Redux be considered a [Flux](https://facebook.github.io/flux/) implementation?
<add>[Yes](https://twitter.com/fisherwebdev/status/616278911886884864), and [no](https://twitter.com/andrestaltz/status/616270755605708800).
<add>
<add>(Don’t worry, [Flux creators](https://twitter.com/jingc/status/616608251463909376) [approve of it](https://twitter.com/fisherwebdev/status/616286955693682688), if that’s all you wanted to know.)
<add>
<add>Redux was inspired by several important qualities of Flux. Like Flux, Redux prescribes you to concentrate your model update logic in a certain layer of your application (“stores” in Flux, “reducers” in Redux). Instead of letting the application code directly mutate the data, both tell you to describe every mutation as a plain object called “action”.
<add>
<add>Unlike Flux, **Redux does not have a concept of Dispatcher**. This is because it relies on pure functions instead of event emitters, and pure functions are easy to compose and don’t need an additional entity managing them. Depending on how you view Flux, you may see this as a deviation or an implementation detail. Flux has often been [described as `(state, action) => state`](https://speakerdeck.com/jmorrell/jsconf-uy-flux-those-who-forget-the-past-dot-dot-dot). In this sense, Redux is true to the Flux architecture, but makes it simpler thanks to pure functions.
<add>
<add>Another important difference from Flux is that **Redux assumes you never mutate your data**. You can use plain objects and arrays for your state just fine, but mutating them inside the reducers is severely discouraged. You should always return a new object, which is easy with the [object spread syntax proposed for ES7](https://github.com/sebmarkbage/ecmascript-rest-spread) and implemented in [Babel](http://babeljs.io), or with a library like [Immutable](https://facebook.github.io/immutable-js).
<add>
<add>While it is technically *possible* to [write impure reducers](https://github.com/gaearon/redux/issues/328#issuecomment-125035516) that mutate the data for performance corner cases, we actively discourage you from doing this. Development features like time travel, record/replay, or hot reloading will break. Moreover it doesn’t seem like immutability poses performance problems in most of the real apps, because, as [Om](https://github.com/omcljs/om) demonstrates, even if you lose out on object allocation, you still win by avoiding expensive re-renders and re-calculations, as you know exactly what changed thanks to reducer purity.
<add>
<add>### Elm
<add>
<add>[Elm](http://elm-lang.org/) is a functional programming language created by [Evan Czaplicki](https://twitter.com/czaplic). It encourages using [an architecture that can be described as `(state, action) => state`](http://elm-lang.org/guide/architecture). Technically, Elm “updaters” are equivalent to the reducers in Redux.
<add>
<add>Unlike Redux, Elm is a language, so it is able to benefit from statical typing for actions, and pattern matching. Even if you don’t plan to use Elm, you should read about the Elm architecture, and play with it. There is an interesting [JavaScript library playground implementing similar ideas](https://github.com/paldepind/noname-functional-frontend-framework). We should look there for inspiration on Redux! One way how we can get closer to the static typing of Elm is by [using a gradual typing solution like Flow](https://github.com/gaearon/redux/issues/290).
<add>
<add>### Immutable
<add>
<add>[Immutable](https://facebook.github.io/immutable-js) is a JavaScript library implementing persistent data structures. It is performant and has an idiomatic JavaScript API.
<add>
<add>Immutable and most similar libraries are orthogonal to Redux. Feel free to use them together!
<add>
<add>**Redux doesn’t care *how* you store the state—it can be a plain object, an Immutable object, or anything else.** You’ll probably want a (de)serialization mechanism for writing universal apps and hydrating their state from the server, but other than that, you can use any data storage library *as long as it supports immutability*. For example, it doesn’t make sense to use Backbone for Redux state, because Backbone models are mutable.
<add>
<add>Note that, even if your immutable library supports cursors, you shouldn’t use them in a Redux app. The whole state tree should be considered read-only, and you should use Redux for updating the state, and subscribing to the updates. Therefore writing via cursor doesn’t make sense for Redux. **If your only use case for cursors is decoupling the state tree from the UI tree and gradually refining the cursors, you should look at selectors instead.** Selectors are composable getter functions. See [reselect](http://github.com/faassen/reselect) for a really great and concise implementation of composable selectors.
<add>
<add>### Baobab
<add>
<add>[Baobab](https://github.com/Yomguithereal/baobab) is another popular library implementing immutable API for updating plain JavaScript objects. While you can use it with Redux, there is little benefit to them together.
<add>
<add>Most of the functionality Baobab provides is related to updating the data with cursors, but Redux enforces that the only way to update the data is to dispatch the action. Therefore they solve the same problem differently, and don’t complement each other.
<add>
<add>Unlike Immutable, Baobab doesn’t yet implement any special efficient data structures under the hood, so you don’t really win anything from using it together with Redux. It’s easier to just use plain objects in this case.
<add>
<add>### Rx
<add>
<add>[Reactive Extensions](https://github.com/Reactive-Extensions/RxJS) (and their undergoing [modern rewrite](https://github.com/ReactiveX/RxJS)) are a superb way to manage the complexity of asynchronous apps. In fact [there is an effort to create a library that models human-computer interaction as interdependent observables](http://cycle.js.org).
<add>
<add>Does it make sense to use Redux together with Rx? Sure! They work great together. For example, it is easy to expose a Redux store as an observable:
<add>
<add>```js
<add>function toObservable(store) {
<add> return {
<add> subscribe({ onNext }) {
<add> let dispose = store.subscribe(() => onNext(store.getState()));
<add> onNext(store.getState());
<add> return { dispose };
<add> }
<add> }
<add>}
<add>```
<add>
<add>Similarly, you can compose different asynchronous streams to turn them into actions before feeding them to `store.dispatch()`.
<add>
<add>The question is: do you really need Redux if you already use Rx? Maybe not. It's not hard to [re-implement Redux in Rx](https://github.com/jas-chen/rx-redux). Some say it's a two-liner using Rx `.scan()` method. It may very well be!
<add>
<add>If you’re in doubt, check out the Redux source code (there isn’t much going on there), as well as its ecosystem (for example, [the developer tools](github.com/gaearon/redux-devtools)). If you don’t care too much about it and want to go with the reactive data flow all the way, you might want to explore something like [Cycle](http://cycle.js.org) instead, or even combine it with Redux. Let us know how it goes!
<ide><path>docs/basics/README.md
<add>## Basics
<add>
<ide><path>docs/basics/ThreePrinciples.md
<add># Three Principles
<add>
<add>Redux can be described in three fundamental principles:
<add>
<add>### Single source of truth
<add>
<add>**The [state](../Glossary.md#state) of your whole application is stored in an object tree inside a single store.**
<add>
<add>This makes it easy to create universal apps. The state from the server can be serialized and hydrated into the client with no extra coding effort. It is easier to debug an application when there is a single state tree. You can also persist your app’s state in development for a faster development cycle. And of course, with a single state tree, you get the previously difficult functionality like Undo/Redo for free.
<add>
<add>```js
<add>console.log(store.getState());
<add>
<add>{
<add> visibleTodoFilter: 'SHOW_ALL',
<add> todos: [{
<add> text: 'Consider using Redux',
<add> completed: true,
<add> }, {
<add> text: 'Keep all state in a single tree',
<add> completed: false
<add> }]
<add>}
<add>```
<add>
<add>### State is read-only
<add>
<add>**The only way to mutate the state is to emit an [action](../Glossary.md#action), an object describing what happened.**
<add>
<add>This ensures that the views or the network callbacks never write directly to the state, and instead express the intent to mutate. Because all mutations are centralized and happen one by one in a strict order, there are no subtle race conditions to watch out for. Actions are just plain objects, so they can be logged, serialized, stored, and later replayed for debugging or testing purposes.
<add>
<add>```js
<add>store.dispatch({
<add> type: 'COMPLETE_TODO',
<add> index: 1
<add>});
<add>
<add>store.dispatch({
<add> type: 'CHANGE_VISIBLE_FILTER',
<add> filter: 'SHOW_COMPLETED'
<add>});
<add>```
<add>
<add>### Mutations are written as pure functions
<add>
<add>**To specify how the state tree is transformed by the actions, you write pure [reducers](../Glossary.md#reducer).**
<add>
<add>Reducers are just pure functions that take the previous state and the action, and return the next state. You can start with a single reducer, but as your app grows, you can split it into smaller reducers that manage the specific parts of the state tree. Because reducers are just functions, you can control the order in which they are called, pass additional data, or even make reusable reducers for common tasks such as pagination.
<add>
<add>```js
<add>function visibleTodoFilter(state = 'SHOW_ALL', action) {
<add> switch (action.type) {
<add> case 'CHANGE_VISIBLE_FILTER':
<add> return action.filter;
<add> default:
<add> return state;
<add> }
<add>}
<add>
<add>function todos(state = [], action) {
<add> switch (action.type) {
<add> case 'ADD_TODO':
<add> return state.concat([action.text]);
<add> default:
<add> return state;
<add> }
<add>}
<add>
<add>import { combineReducers, createStore } from 'redux';
<add>let reducer = combineReducers({ visibleTodoFilter, todos });
<add>let store = createStore(reducer);
<add>```
<add>
<add>This is it! Now you know what Redux is all about.
<ide>\ No newline at end of file | 5 |
PHP | PHP | remove trailing white-space | 22471ae267f35311b0f2ff4fd7ba4cbf32c3577d | <ide><path>src/Illuminate/Auth/EloquentUserProvider.php
<ide> public function retrieveByToken($identifier, $token)
<ide> $model = $this->createModel()->newQuery()
<ide> ->where($model->getAuthIdentifierName(), $identifier)
<ide> ->first();
<del>
<add>
<ide> return $model && hash_equals($model->getRememberToken(), $token) ? $model : null;
<ide> }
<ide> | 1 |
Ruby | Ruby | ensure column names on reflection as a string | c0750fe2304de2c7bae028cbc465b6bf7e7d253e | <ide><path>activerecord/lib/active_record/associations/association.rb
<ide> def invertible_for?(record)
<ide>
<ide> # Returns true if record contains the foreign_key
<ide> def foreign_key_for?(record)
<del> record._has_attribute?(reflection.foreign_key.to_s)
<add> record._has_attribute?(reflection.foreign_key)
<ide> end
<ide>
<ide> # This should be implemented to return the values of the relevant key(s) on the owner,
<ide><path>activerecord/lib/active_record/autosave_association.rb
<ide> def record_changed?(reflection, record, key)
<ide> def association_foreign_key_changed?(reflection, record, key)
<ide> return false if reflection.through_reflection?
<ide>
<del> record._has_attribute?(reflection.foreign_key.to_s) && record._read_attribute(reflection.foreign_key) != key
<add> record._has_attribute?(reflection.foreign_key) && record._read_attribute(reflection.foreign_key) != key
<ide> end
<ide>
<ide> # Saves the associated record if it's new or <tt>:autosave</tt> is enabled.
<ide><path>activerecord/lib/active_record/reflection.rb
<ide> def build_association(attributes, &block)
<ide> # <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>'Money'</tt>
<ide> # <tt>has_many :clients</tt> returns <tt>'Client'</tt>
<ide> def class_name
<del> @class_name ||= (options[:class_name] || derive_class_name).to_s
<add> @class_name ||= -(options[:class_name]&.to_s || derive_class_name)
<ide> end
<ide>
<ide> JoinKeys = Struct.new(:key, :foreign_key) # :nodoc:
<ide> def constraints
<ide> end
<ide>
<ide> def counter_cache_column
<del> if belongs_to?
<add> @counter_cache_column ||= if belongs_to?
<ide> if options[:counter_cache] == true
<del> "#{active_record.name.demodulize.underscore.pluralize}_count"
<add> -"#{active_record.name.demodulize.underscore.pluralize}_count"
<ide> elsif options[:counter_cache]
<del> options[:counter_cache].to_s
<add> -options[:counter_cache].to_s
<ide> end
<ide> else
<del> options[:counter_cache] ? options[:counter_cache].to_s : "#{name}_count"
<add> -(options[:counter_cache]&.to_s || "#{name}_count")
<ide> end
<ide> end
<ide>
<ide> def compute_class(name)
<ide>
<ide> def initialize(name, scope, options, active_record)
<ide> super
<del> @type = options[:as] && (options[:foreign_type] || "#{options[:as]}_type")
<del> @foreign_type = options[:polymorphic] && (options[:foreign_type] || "#{name}_type")
<add> @type = -(options[:foreign_type]&.to_s || "#{options[:as]}_type") if options[:as]
<add> @foreign_type = -(options[:foreign_type]&.to_s || "#{name}_type") if options[:polymorphic]
<ide> @constructable = calculate_constructable(macro, options)
<ide>
<ide> if options[:class_name] && options[:class_name].class == Class
<ide> def constructable? # :nodoc:
<ide> end
<ide>
<ide> def join_table
<del> @join_table ||= options[:join_table] || derive_join_table
<add> @join_table ||= -(options[:join_table]&.to_s || derive_join_table)
<ide> end
<ide>
<ide> def foreign_key
<del> @foreign_key ||= options[:foreign_key] || derive_foreign_key.freeze
<add> @foreign_key ||= -(options[:foreign_key]&.to_s || derive_foreign_key)
<ide> end
<ide>
<ide> def association_foreign_key
<del> @association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key
<add> @association_foreign_key ||= -(options[:association_foreign_key]&.to_s || class_name.foreign_key)
<ide> end
<ide>
<ide> # klass option is necessary to support loading polymorphic associations
<ide> def association_primary_key(klass = nil)
<del> options[:primary_key] || primary_key(klass || self.klass)
<add> if primary_key = options[:primary_key]
<add> @association_primary_key ||= -primary_key.to_s
<add> else
<add> primary_key(klass || self.klass)
<add> end
<ide> end
<ide>
<ide> def active_record_primary_key
<del> @active_record_primary_key ||= options[:primary_key] || primary_key(active_record)
<add> @active_record_primary_key ||= -(options[:primary_key]&.to_s || primary_key(active_record))
<ide> end
<ide>
<ide> def check_validity!
<ide> def nested?
<ide> def association_primary_key(klass = nil)
<ide> # Get the "actual" source reflection if the immediate source reflection has a
<ide> # source reflection itself
<del> actual_source_reflection.options[:primary_key] || primary_key(klass || self.klass)
<add> if primary_key = actual_source_reflection.options[:primary_key]
<add> @association_primary_key ||= -primary_key.to_s
<add> else
<add> primary_key(klass || self.klass)
<add> end
<ide> end
<ide>
<ide> # Gets an array of possible <tt>:through</tt> source reflection names in both singular and plural form.
<ide><path>activerecord/lib/active_record/relation.rb
<ide> def many?
<ide> # last updated record.
<ide> #
<ide> # Product.where("name like ?", "%Game%").cache_key(:last_reviewed_at)
<del> def cache_key(timestamp_column = :updated_at)
<add> def cache_key(timestamp_column = "updated_at")
<ide> @cache_keys ||= {}
<ide> @cache_keys[timestamp_column] ||= klass.collection_cache_key(self, timestamp_column)
<ide> end
<ide><path>activerecord/lib/active_record/relation/predicate_builder/association_query_value.rb
<ide> def initialize(associated_table, value)
<ide> end
<ide>
<ide> def queries
<del> [associated_table.association_join_foreign_key.to_s => ids]
<add> [associated_table.association_join_foreign_key => ids]
<ide> end
<ide>
<ide> private
<ide><path>activerecord/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb
<ide> def initialize(associated_table, values)
<ide> def queries
<ide> type_to_ids_mapping.map do |type, ids|
<ide> {
<del> associated_table.association_foreign_type.to_s => type,
<del> associated_table.association_foreign_key.to_s => ids
<add> associated_table.association_foreign_type => type,
<add> associated_table.association_foreign_key => ids
<ide> }
<ide> end
<ide> end | 6 |
Ruby | Ruby | fix argv and bottles circular dependency | d5b954ebd4c3c8c43584e04976da071c6ac76cf4 | <ide><path>Library/Homebrew/bottles.rb
<ide> def bottle_filename f, bottle_version=nil
<ide> "#{name}-#{version}#{bottle_native_suffix(bottle_version)}"
<ide> end
<ide>
<del>def bottles_supported?
<del> HOMEBREW_PREFIX.to_s == '/usr/local' and HOMEBREW_CELLAR.to_s == '/usr/local/Cellar' and Hardware.is_64_bit? || !MacOS.snow_leopard?
<del>end
<del>
<ide> def install_bottle? f
<ide> return true if ARGV.include? '--install-bottle'
<del> not ARGV.build_from_source? and bottle_current?(f)
<add> not ARGV.build_from_source? \
<add> and ARGV.bottles_supported? \
<add> and ARGV.options_only.empty? \
<add> and bottle_current?(f)
<ide> end
<ide>
<ide> def built_as_bottle? f
<ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def build_32_bit?
<ide> include? '--32-bit'
<ide> end
<ide>
<add> def bottles_supported?
<add> # Snow Leopard was the only version of OS X that supported
<add> # both 64-bit and 32-bit processors and kernels.
<add> (Hardware.is_64_bit? or not MacOS.snow_leopard?) \
<add> and HOMEBREW_PREFIX.to_s == '/usr/local' \
<add> and HOMEBREW_CELLAR.to_s == '/usr/local/Cellar' \
<add> end
<add>
<ide> def build_bottle?
<del> require 'bottles'
<del> bottles_supported? and include? '--build-bottle'
<add> include? '--build-bottle' and bottles_supported?
<ide> end
<ide>
<ide> def build_from_source?
<del> require 'bottles'
<del> flag? '--build-from-source' or ENV['HOMEBREW_BUILD_FROM_SOURCE'] \
<del> or not bottles_supported? or not options_only.empty?
<add> include? '--build-from-source' or ENV['HOMEBREW_BUILD_FROM_SOURCE']
<ide> end
<ide>
<ide> def flag? flag | 2 |
Text | Text | add v3.1.0-beta.4 to changelog | 777bfd860d2ea30bd65d8070e3cf2c29e022c0a6 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.1.0-beta.4 (March 5, 2018)
<add>- [#16294](https://github.com/emberjs/ember.js/pull/16294) [BUGFIX] Fix input macro params handling
<add>- [#16297](https://github.com/emberjs/ember.js/pull/16297) [BUGFIX] Revert "Update to [email protected]."
<add>- [#16299](https://github.com/emberjs/ember.js/pull/16299) [BUGFIX] Revert "[CLEANUP] Remove ':change' suffix on change events"
<add>- [#16307](https://github.com/emberjs/ember.js/pull/16307) [BUGFIX] Ensure proper .toString() of default components.
<add>
<ide> ### v3.1.0-beta.3 (February 26, 2018)
<ide> - [#16271](https://github.com/emberjs/ember.js/pull/16271) [BUGFIX] Fix ChainNode unchaining
<ide> - [#16274](https://github.com/emberjs/ember.js/pull/16274) [BUGFIX] Ensure accessing a "proxy" itself does not error. | 1 |
Text | Text | update contributing guidelines for examples | 6ad8c338d8cdc26e66759d1838886093cd45a80f | <ide><path>contributing.md
<ide> When you add an example to the [examples](examples) directory, don’t forget to
<ide>
<ide> - Replace `DIRECTORY_NAME` with the directory name you’re adding.
<ide> - Fill in `Example Name` and `Description`.
<add>- Examples should be TypeScript first, if possible.
<add>- You don’t need to add `name` or `version` in your `package.json`.
<add>- Ensure all your dependencies are up to date.
<add>- Ensure you’re using [`next/image`](https://nextjs.org/docs/api-reference/next/image).
<ide> - To add additional installation instructions, please add it where appropriate.
<ide> - To add additional notes, add `## Notes` section at the end.
<ide> - Remove the `Deploy your own` section if your example can’t be immediately deployed to Vercel.
<del>- Remove the `Preview` section if the example doesn't work on [StackBlitz](http://stackblitz.com/) and file an issue [here](https://github.com/stackblitz/webcontainer-core).
<ide>
<ide> ````markdown
<ide> # Example Name
<ide>
<ide> Description
<ide>
<del>## Preview
<del>
<del>Preview the example live on [StackBlitz](http://stackblitz.com/):
<del>
<del>[](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/DIRECTORY_NAME)
<del>
<ide> ## Deploy your own
<ide>
<ide> Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example): | 1 |
Javascript | Javascript | use reactversions module as package allowlist | 44cdfd6b7a0f5a4949866a24f65179760b3767d1 | <ide><path>ReactVersions.js
<ide> const experimentalPackages = [
<ide> 'react-fs',
<ide> 'react-pg',
<ide> 'react-server-dom-webpack',
<del> 'react-server',
<ide> ];
<ide>
<ide> // TODO: Export a map of every package and its version.
<ide><path>scripts/release/utils.js
<ide> const {join} = require('path');
<ide> const createLogger = require('progress-estimator');
<ide> const prompt = require('prompt-promise');
<ide> const theme = require('./theme');
<add>const {stablePackages, experimentalPackages} = require('../../ReactVersions');
<ide>
<ide> // https://www.npmjs.com/package/progress-estimator#configuration
<ide> const logger = createLogger({
<ide> const getCommitFromCurrentBuild = async () => {
<ide> };
<ide>
<ide> const getPublicPackages = isExperimental => {
<del> // TODO: Use ReactVersions.js as source of truth.
<add> const packageNames = Object.keys(stablePackages);
<ide> if (isExperimental) {
<del> return [
<del> 'create-subscription',
<del> 'eslint-plugin-react-hooks',
<del> 'jest-react',
<del> 'react',
<del> 'react-art',
<del> 'react-dom',
<del> 'react-is',
<del> 'react-reconciler',
<del> 'react-refresh',
<del> 'react-test-renderer',
<del> 'use-subscription',
<del> 'scheduler',
<del> 'react-fetch',
<del> 'react-fs',
<del> 'react-pg',
<del> 'react-server-dom-webpack',
<del> ];
<del> } else {
<del> return [
<del> 'create-subscription',
<del> 'eslint-plugin-react-hooks',
<del> 'jest-react',
<del> 'react',
<del> 'react-art',
<del> 'react-dom',
<del> 'react-is',
<del> 'react-reconciler',
<del> 'react-refresh',
<del> 'react-test-renderer',
<del> 'use-subscription',
<del> 'scheduler',
<del> ];
<add> packageNames.push(...experimentalPackages);
<ide> }
<add> return packageNames;
<ide> };
<ide>
<ide> const handleError = error => { | 2 |
PHP | PHP | move ast, context and formatter to debug namespace | aa949aa94405a82d8ed34d7cad1d2f35b02cb2e7 | <add><path>src/Error/Debug/ArrayNode.php
<del><path>src/Error/DumpNode/ArrayNode.php
<ide> * @since 4.1.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Error\DumpNode;
<add>namespace Cake\Error\Debug;
<ide>
<ide> /**
<ide> * Dump node for Array values.
<ide> */
<ide> class ArrayNode implements NodeInterface
<ide> {
<ide> /**
<del> * @var \Cake\Error\DumpNode\ItemNode[]
<add> * @var \Cake\Error\Debug\ItemNode[]
<ide> */
<ide> private $items;
<ide>
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param \Cake\Error\DumpNode\ItemNode[] $items The items for the array
<add> * @param \Cake\Error\Debug\ItemNode[] $items The items for the array
<ide> */
<ide> public function __construct(array $items = [])
<ide> {
<ide> public function __construct(array $items = [])
<ide> /**
<ide> * Add an item
<ide> *
<del> * @param \Cake\Error\DumpNode\ItemNode
<add> * @param \Cake\Error\Debug\ItemNode $node The item to add.
<ide> * @return void
<ide> */
<ide> public function add(ItemNode $node): void
<ide> public function add(ItemNode $node): void
<ide> /**
<ide> * Get the contained items
<ide> *
<del> * @return \Cake\Error\DumpNode\ItemNode[]
<add> * @return \Cake\Error\Debug\ItemNode[]
<ide> */
<ide> public function getValue(): array
<ide> {
<ide> return $this->items;
<ide> }
<ide>
<ide> /**
<del> * @inheritDoc
<add> * Get Item nodes
<add> *
<add> * @return \Cake\Error\Debug\ItemNode[]
<ide> */
<ide> public function getChildren(): array
<ide> {
<add><path>src/Error/Debug/ClassNode.php
<del><path>src/Error/DumpNode/ClassNode.php
<ide> * @since 4.1.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Error\DumpNode;
<add>namespace Cake\Error\Debug;
<ide>
<ide> /**
<ide> * Dump node for objects/class instances.
<ide> class ClassNode implements NodeInterface
<ide> private $id;
<ide>
<ide> /**
<del> * @var \Cake\Error\DumpNode\PropertyNode[]
<add> * @var \Cake\Error\Debug\PropertyNode[]
<ide> */
<ide> private $properties = [];
<ide>
<ide> public function __construct(string $class, int $id)
<ide> /**
<ide> * Add a property
<ide> *
<del> * @param \Cake\Error\DumpNode\PropertyNode $node The property to add.
<add> * @param \Cake\Error\Debug\PropertyNode $node The property to add.
<ide> * @return void
<ide> */
<ide> public function addProperty(PropertyNode $node): void
<ide> public function getId(): int
<ide> }
<ide>
<ide> /**
<del> * @inheritDoc
<add> * Get property nodes
<add> *
<add> * @return \Cake\Error\Debug\PropertyNode[]
<ide> */
<ide> public function getChildren(): array
<ide> {
<add><path>src/Error/Debug/DebugContext.php
<del><path>src/Error/DumpContext.php
<ide> * @since 4.1.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Error;
<add>namespace Cake\Error\Debug;
<ide>
<ide> use SplObjectStorage;
<ide>
<ide> *
<ide> * @internal
<ide> */
<del>class DumpContext
<add>class DebugContext
<ide> {
<ide> /**
<ide> * @var int
<add><path>src/Error/Debug/ItemNode.php
<del><path>src/Error/DumpNode/ItemNode.php
<ide> * @since 4.1.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Error\DumpNode;
<add>namespace Cake\Error\Debug;
<ide>
<ide> /**
<ide> * Dump node for Array Items.
<ide> */
<ide> class ItemNode implements NodeInterface
<ide> {
<ide> /**
<del> * @var \Cake\Error\DumpNode\NodeInterface
<add> * @var \Cake\Error\Debug\NodeInterface
<ide> */
<ide> private $key;
<ide>
<ide> /**
<del> * @var \Cake\Error\DumpNode\NodeInterface
<add> * @var \Cake\Error\Debug\NodeInterface
<ide> */
<ide> private $value;
<ide>
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param \Cake\Error\DumpNode\NodeInterface $key The node for the item key
<del> * @param \Cake\Error\DumpNode\NodeInterface $value The node for the array value
<add> * @param \Cake\Error\Debug\NodeInterface $key The node for the item key
<add> * @param \Cake\Error\Debug\NodeInterface $value The node for the array value
<ide> */
<ide> public function __construct(NodeInterface $key, NodeInterface $value)
<ide> {
<ide> public function __construct(NodeInterface $key, NodeInterface $value)
<ide> /**
<ide> * Get the value
<ide> *
<del> * @return \Cake\Error\DumpNode\NodeInterface
<add> * @return \Cake\Error\Debug\NodeInterface
<ide> */
<ide> public function getValue()
<ide> {
<ide> public function getValue()
<ide> /**
<ide> * Get the key
<ide> *
<del> * @return \Cake\Error\DumpNode\NodeInterface
<add> * @return \Cake\Error\Debug\NodeInterface
<ide> */
<ide> public function getKey()
<ide> {
<add><path>src/Error/Debug/NodeInterface.php
<del><path>src/Error/DumpNode/NodeInterface.php
<ide> * @since 4.1.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Error\DumpNode;
<add>namespace Cake\Error\Debug;
<ide>
<ide> /**
<del> * Interface for DumpNodes
<add> * Interface for Debugs
<ide> *
<ide> * Provides methods to look at contained value and iterate child nodes in the tree.
<ide> */
<ide> interface NodeInterface
<ide> /**
<ide> * Get the child nodes of this node.
<ide> *
<del> * @return \Cake\Error\DumpNode\NodeInterface[]
<add> * @return \Cake\Error\Debug\NodeInterface[]
<ide> */
<ide> public function getChildren(): array;
<ide>
<add><path>src/Error/Debug/PropertyNode.php
<del><path>src/Error/DumpNode/PropertyNode.php
<ide> * @since 4.1.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Error\DumpNode;
<add>namespace Cake\Error\Debug;
<ide>
<ide> /**
<ide> * Dump node for object properties.
<ide> class PropertyNode implements NodeInterface
<ide> private $name;
<ide>
<ide> /**
<del> * @var string
<add> * @var string|null
<ide> */
<ide> private $visibility;
<ide>
<ide> /**
<del> * @var \Cake\Error\DumpNode\NodeInterface
<add> * @var \Cake\Error\Debug\NodeInterface
<ide> */
<ide> private $value;
<ide>
<ide> class PropertyNode implements NodeInterface
<ide> *
<ide> * @param string $name The property name
<ide> * @param string $visibility The visibility of the property.
<del> * @param \Cake\Error\DumpNode\NodeInterface $value The property value node.
<add> * @param \Cake\Error\Debug\NodeInterface $value The property value node.
<ide> */
<ide> public function __construct(string $name, ?string $visibility, NodeInterface $value)
<ide> {
<ide> public function __construct(string $name, ?string $visibility, NodeInterface $va
<ide> /**
<ide> * Get the value
<ide> *
<del> * @return \Cake\Error\DumpNode\NodeInterface
<add> * @return \Cake\Error\Debug\NodeInterface
<ide> */
<ide> public function getValue(): NodeInterface
<ide> {
<add><path>src/Error/Debug/ReferenceNode.php
<del><path>src/Error/DumpNode/ReferenceNode.php
<ide> * @since 4.1.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Error\DumpNode;
<add>namespace Cake\Error\Debug;
<ide>
<ide> /**
<ide> * Dump node for class references.
<add><path>src/Error/Debug/ScalarNode.php
<del><path>src/Error/DumpNode/ScalarNode.php
<ide> * @since 4.1.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Error\DumpNode;
<add>namespace Cake\Error\Debug;
<ide>
<ide> /**
<ide> * Dump node for scalar values.
<add><path>src/Error/Debug/SpecialNode.php
<del><path>src/Error/DumpNode/SpecialNode.php
<ide> * @since 4.1.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Error\DumpNode;
<add>namespace Cake\Error\Debug;
<ide>
<ide> /**
<del> * Dump node for special messages like errors or recursion warnings.
<add> * Debug node for special messages like errors or recursion warnings.
<ide> */
<ide> class SpecialNode implements NodeInterface
<ide> {
<add><path>src/Error/Debug/TextFormatter.php
<del><path>src/Error/DumpFormatter/TextFormatter.php
<ide> * @since 4.1.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Error\DumpFormatter;
<add>namespace Cake\Error\Debug;
<ide>
<del>use Cake\Error\DumpNode\ArrayNode;
<del>use Cake\Error\DumpNode\ClassNode;
<del>use Cake\Error\DumpNode\NodeInterface;
<del>use Cake\Error\DumpNode\ReferenceNode;
<del>use Cake\Error\DumpNode\ScalarNode;
<del>use Cake\Error\DumpNode\SpecialNode;
<add>use Cake\Error\Debug\ArrayNode;
<add>use Cake\Error\Debug\ClassNode;
<add>use Cake\Error\Debug\NodeInterface;
<add>use Cake\Error\Debug\ReferenceNode;
<add>use Cake\Error\Debug\ScalarNode;
<add>use Cake\Error\Debug\SpecialNode;
<ide> use RuntimeException;
<ide>
<ide> /**
<ide> class TextFormatter
<ide> /**
<ide> * Convert a tree of NodeInterface objects into a plain text string.
<ide> *
<del> * @param \Cake\Error\DumpNode\NodeInterface $node The node tree to dump.
<add> * @param \Cake\Error\Debug\NodeInterface $node The node tree to dump.
<ide> * @return string
<ide> */
<ide> public function dump(NodeInterface $node): string
<ide> public function dump(NodeInterface $node): string
<ide> /**
<ide> * Convert a tree of NodeInterface objects into a plain text string.
<ide> *
<del> * @param \Cake\Error\DumpNode\NodeInterface $node The node tree to dump.
<add> * @param \Cake\Error\Debug\NodeInterface $node The node tree to dump.
<ide> * @param int $indent The current indentation level.
<ide> * @return string
<ide> */
<ide> protected function _export(NodeInterface $var, int $indent): string
<ide> case 'null':
<ide> return 'null';
<ide> case 'string':
<del> return "'" . $var->getValue() . "'";
<add> return "'" . (string)$var->getValue() . "'";
<ide> default:
<ide> return "({$var->getType()}) {$var->getValue()}";
<ide> }
<ide> protected function _export(NodeInterface $var, int $indent): string
<ide> /**
<ide> * Export an array type object
<ide> *
<del> * @param \Cake\Error\DumpNode\ArrayNode $var The array to export.
<add> * @param \Cake\Error\Debug\ArrayNode $var The array to export.
<ide> * @param int $context The current dump context.
<ide> * @return string Exported array.
<ide> */
<ide> protected function _object($var, int $indent): string
<ide> return "object({$var->getValue()}) id:{$var->getId()} {}";
<ide> }
<ide>
<del> /* @var \Cake\Error\DumpNode\ClassNode $var */
<add> /* @var \Cake\Error\Debug\ClassNode $var */
<ide> $out .= "object({$var->getValue()}) id:{$var->getId()} {";
<ide> $break = "\n" . str_repeat(" ", $indent);
<ide> $end = "\n" . str_repeat(" ", $indent - 1) . '}';
<ide><path>src/Error/Debugger.php
<ide> namespace Cake\Error;
<ide>
<ide> use Cake\Core\InstanceConfigTrait;
<del>use Cake\Error\DumpFormatter\TextFormatter;
<del>use Cake\Error\DumpNode\ArrayNode;
<del>use Cake\Error\DumpNode\ClassNode;
<del>use Cake\Error\DumpNode\ItemNode;
<del>use Cake\Error\DumpNode\NodeInterface;
<del>use Cake\Error\DumpNode\PropertyNode;
<del>use Cake\Error\DumpNode\ReferenceNode;
<del>use Cake\Error\DumpNode\ScalarNode;
<del>use Cake\Error\DumpNode\SpecialNode;
<add>use Cake\Error\Debug\ArrayNode;
<add>use Cake\Error\Debug\ClassNode;
<add>use Cake\Error\Debug\DebugContext;
<add>use Cake\Error\Debug\ItemNode;
<add>use Cake\Error\Debug\NodeInterface;
<add>use Cake\Error\Debug\PropertyNode;
<add>use Cake\Error\Debug\ReferenceNode;
<add>use Cake\Error\Debug\ScalarNode;
<add>use Cake\Error\Debug\SpecialNode;
<add>use Cake\Error\Debug\TextFormatter;
<ide> use Cake\Log\Log;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Security;
<ide> /**
<ide> * Provide custom logging and error handling.
<ide> *
<del> * Debugger overrides PHP's default error handling to provide stack traces and enhanced logging
<add> * Debugger extends PHP's default error handling and gives
<add> * simpler to use more powerful interfaces.
<ide> *
<ide> * @link https://book.cakephp.org/4/en/development/debugging.html#namespace-Cake\Error
<ide> */
<ide> protected static function _highlight(string $str): string
<ide> */
<ide> public static function exportVar($var, int $maxDepth = 3): string
<ide> {
<del> $context = new DumpContext($maxDepth);
<add> $context = new DebugContext($maxDepth);
<ide> $node = static::export($var, $context);
<ide>
<ide> $formatter = new TextFormatter();
<ide> public static function exportVar($var, int $maxDepth = 3): string
<ide> * Protected export function used to keep track of indentation and recursion.
<ide> *
<ide> * @param mixed $var The variable to dump.
<del> * @param \Cake\Error\DumpContext $context Dump context
<del> * @return \Cake\Error\DumpNode\NodeInterface The dumped variable.
<add> * @param \Cake\Error\Debug\DebugContext $context Dump context
<add> * @return \Cake\Error\Debug\NodeInterface The dumped variable.
<ide> */
<del> protected static function export($var, DumpContext $context): NodeInterface
<add> protected static function export($var, DebugContext $context): NodeInterface
<ide> {
<ide> switch (static::getType($var)) {
<ide> case 'boolean':
<ide> protected static function export($var, DumpContext $context): NodeInterface
<ide> * - schema
<ide> *
<ide> * @param array $var The array to export.
<del> * @param \Cake\Error\DumpContext $context The current dump context.
<del> * @return \Cake\Error\DumpNode\ArrayNode Exported array.
<add> * @param \Cake\Error\Debug\DebugContext $context The current dump context.
<add> * @return \Cake\Error\Debug\ArrayNode Exported array.
<ide> */
<del> protected static function exportArray(array $var, DumpContext $context): ArrayNode
<add> protected static function exportArray(array $var, DebugContext $context): ArrayNode
<ide> {
<ide> $items = [];
<ide>
<ide> protected static function exportArray(array $var, DumpContext $context): ArrayNo
<ide> * Handles object to node conversion.
<ide> *
<ide> * @param object $var Object to convert.
<del> * @param \Cake\Error\DumpContext $context The dump context.
<del> * @return \Cake\Error\DumpNode\NodeInterface
<add> * @param \Cake\Error\Debug\DebugContext $context The dump context.
<add> * @return \Cake\Error\Debug\NodeInterface
<ide> * @see \Cake\Error\Debugger::exportVar()
<ide> */
<del> protected static function exportObject(object $var, DumpContext $context): NodeInterface
<add> protected static function exportObject(object $var, DebugContext $context): NodeInterface
<ide> {
<ide> $isRef = $context->hasReference($var);
<ide> $refNum = $context->getReferenceId($var); | 11 |
Ruby | Ruby | improve documentation for connectionpool, again | f261cd2a94fc128f37f85e86326868341cbfdf3d | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
<ide> module ConnectionAdapters
<ide> # Connection pool base class for managing ActiveRecord database
<ide> # connections.
<ide> #
<add> # == Introduction
<add> #
<ide> # A connection pool synchronizes thread access to a limited number of
<ide> # database connections. The basic idea is that each thread checks out a
<ide> # database connection from the pool, uses that connection, and checks the
<ide> module ConnectionAdapters
<ide> # connection anyway, then ConnectionPool will wait until some other thread
<ide> # has checked in a connection.
<ide> #
<add> # == Obtaining (checking out) a connection
<add> #
<ide> # Connections can be obtained and used from a connection pool in several
<ide> # ways:
<ide> #
<ide> module ConnectionAdapters
<ide> # obtains a connection, yields it as the sole argument to the block,
<ide> # and returns it to the pool after the block completes.
<ide> #
<add> # Connections in the pool are actually AbstractAdapter objects (or objects
<add> # compatible with AbstractAdapter's interface).
<add> #
<add> # == Options
<add> #
<ide> # There are two connection-pooling-related options that you can add to
<ide> # your database connection configuration:
<ide> #
<ide> # * +pool+: number indicating size of connection pool (default 5)
<ide> # * +wait_timeout+: number of seconds to block and wait for a connection
<ide> # before giving up and raising a timeout error (default 5 seconds).
<del> #
<del> # *Note*: connections in the pool are AbstractAdapter objects.
<ide> class ConnectionPool
<ide> attr_reader :spec
<ide>
<ide> def connected?
<ide> [email protected]?
<ide> end
<ide>
<del> # Disconnect all connections in the pool.
<add> # Disconnects all connections in the pool, and clears the pool.
<ide> def disconnect!
<ide> @reserved_connections.each do |name,conn|
<ide> checkin conn
<ide> def clear_stale_cached_connections!
<ide> # a new connection. If the maximum number of connections for this pool has
<ide> # already been reached, but the pool is empty (i.e. they're all being used),
<ide> # then this method will wait until a thread has checked in a connection.
<add> # The wait time is bounded however: if no connection can be checked out
<add> # within the timeout specified for this pool, then a ConnectionTimeoutError
<add> # exception will be raised.
<add> #
<add> # Returns: an AbstractAdapter object.
<add> #
<add> # Raises:
<add> # - ConnectionTimeoutError: no connection can be obtained from the pool
<add> # within the timeout period.
<ide> def checkout
<ide> # Checkout an available connection
<ide> conn = @connection_mutex.synchronize do
<ide> def checkout
<ide>
<ide> # Check-in a database connection back into the pool, indicating that you
<ide> # no longer need this connection.
<add> #
<add> # +conn+: an AbstractAdapter object, which was obtained by earlier by
<add> # calling +checkout+ on this pool.
<ide> def checkin(conn)
<ide> @connection_mutex.synchronize do
<ide> conn.run_callbacks :checkin | 1 |
Javascript | Javascript | add comment to explain the implementation | 5985d4069aa08a32729f6e01e8641d577cad06e8 | <ide><path>src/display/pattern_helper.js
<ide> var TilingPattern = (function TilingPatternClosure() {
<ide>
<ide> info('TilingType: ' + tilingType);
<ide>
<add> // A tiling pattern as defined by PDF spec 8.7.2 is a cell whose size is
<add> // described by bbox, and may repeat regularly by shifting the cell by
<add> // xstep and ystep.
<add> // Because the HTML5 canvas API does not support pattern repetition with
<add> // gaps in between, we use the xstep/ystep instead of the bbox's size.
<add> //
<add> // This has the following consequences (similarly for ystep):
<add> //
<add> // - If xstep is the same as bbox, then there is no observable difference.
<add> //
<add> // - If xstep is larger than bbox, then the pattern canvas is partially
<add> // empty: the area bounded by bbox is painted, the outside area is void.
<add> //
<add> // - If xstep is smaller than bbox, then the pixels between xstep and the
<add> // bbox boundary will be missing. This is INCORRECT behavior.
<add> // "Figures on adjacent tiles should not overlap" (PDF spec 8.7.3.1),
<add> // but overlapping cells without common pixels are still valid.
<add> // TODO: Fix the implementation, to allow this scenario to be painted
<add> // correctly.
<add>
<ide> var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
<ide>
<ide> // Obtain scale from matrix and current transformation matrix. | 1 |
PHP | PHP | fix more usage of deprecated methods | 15e61cb9fbe1b1197d0ca71a96a99cb81d0a7d4f | <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> public function testNoViewClassExtension()
<ide> return $this->Controller->response;
<ide> });
<ide> $this->Controller->render();
<del> $this->assertEquals('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->templatePath());
<del> $this->assertEquals('csv', $this->Controller->viewBuilder()->layoutPath());
<add> $this->assertEquals('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath());
<add> $this->assertEquals('csv', $this->Controller->viewBuilder()->getLayoutPath());
<ide> }
<ide>
<ide> /**
<ide> public function testRenderAs()
<ide> {
<ide> $this->RequestHandler->renderAs($this->Controller, 'rss');
<ide>
<del> $this->Controller->viewBuilder()->templatePath('request_handler_test\\rss');
<add> $this->Controller->viewBuilder()->setTemplatePath('request_handler_test\\rss');
<ide> $this->RequestHandler->renderAs($this->Controller, 'js');
<del> $this->assertEquals('request_handler_test' . DS . 'js', $this->Controller->viewBuilder()->templatePath());
<add> $this->assertEquals('request_handler_test' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
<ide> }
<ide>
<ide> /**
<ide> public function testRenderAsCalledTwice()
<ide> $this->Controller->render();
<ide>
<ide> $this->RequestHandler->renderAs($this->Controller, 'print');
<del> $this->assertEquals('RequestHandlerTest' . DS . 'print', $this->Controller->viewBuilder()->templatePath());
<del> $this->assertEquals('print', $this->Controller->viewBuilder()->layoutPath());
<add> $this->assertEquals('RequestHandlerTest' . DS . 'print', $this->Controller->viewBuilder()->getTemplatePath());
<add> $this->assertEquals('print', $this->Controller->viewBuilder()->getLayoutPath());
<ide>
<ide> $this->RequestHandler->renderAs($this->Controller, 'js');
<del> $this->assertEquals('RequestHandlerTest' . DS . 'js', $this->Controller->viewBuilder()->templatePath());
<del> $this->assertEquals('js', $this->Controller->viewBuilder()->layoutPath());
<add> $this->assertEquals('RequestHandlerTest' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
<add> $this->assertEquals('js', $this->Controller->viewBuilder()->getLayoutPath());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> public function testRender()
<ide> ]);
<ide>
<ide> $Controller = new Controller($request, new Response());
<del> $Controller->viewBuilder()->templatePath('Posts');
<add> $Controller->viewBuilder()->setTemplatePath('Posts');
<ide>
<ide> $result = $Controller->render('index');
<ide> $this->assertRegExp('/posts index/', (string)$result);
<ide>
<del> $Controller->viewBuilder()->template('index');
<add> $Controller->viewBuilder()->setTemplate('index');
<ide> $result = $Controller->render();
<ide> $this->assertRegExp('/posts index/', (string)$result);
<ide>
<ide> public function testRenderViewChangesResponse()
<ide> ]);
<ide>
<ide> $controller = new Controller($request, new Response());
<del> $controller->viewBuilder()->templatePath('Posts');
<add> $controller->viewBuilder()->setTemplatePath('Posts');
<ide>
<ide> $result = $controller->render('header');
<ide> $this->assertContains('header template', (string)$result);
<ide> public function testViewPathConventions()
<ide> return $e->getSubject()->response;
<ide> });
<ide> $Controller->render();
<del> $this->assertEquals('Admin' . DS . 'Posts', $Controller->viewBuilder()->templatePath());
<add> $this->assertEquals('Admin' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
<ide>
<ide> $request = $request->withParam('prefix', 'admin/super');
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> public function testViewPathConventions()
<ide> return $e->getSubject()->response;
<ide> });
<ide> $Controller->render();
<del> $this->assertEquals('Admin' . DS . 'Super' . DS . 'Posts', $Controller->viewBuilder()->templatePath());
<add> $this->assertEquals('Admin' . DS . 'Super' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
<ide>
<ide> $request = new ServerRequest([
<ide> 'url' => 'pages/home',
<ide> public function testViewPathConventions()
<ide> return $e->getSubject()->response;
<ide> });
<ide> $Controller->render();
<del> $this->assertEquals('Pages', $Controller->viewBuilder()->templatePath());
<add> $this->assertEquals('Pages', $Controller->viewBuilder()->getTemplatePath());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> function (Event $event) {
<ide> $this->assertEquals('text/html', $response->getType());
<ide> $this->assertContains('Not Found', (string)$response->getBody());
<ide> $this->assertTrue($this->called, 'Listener added was not triggered.');
<del> $this->assertEquals('', $ExceptionRenderer->controller->viewBuilder()->layoutPath());
<del> $this->assertEquals('Error', $ExceptionRenderer->controller->viewBuilder()->templatePath());
<add> $this->assertEquals('', $ExceptionRenderer->controller->viewBuilder()->getLayoutPath());
<add> $this->assertEquals('Error', $ExceptionRenderer->controller->viewBuilder()->getTemplatePath());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Mailer/EmailTest.php
<ide> public function testJsonSerialize()
<ide>
<ide> $this->Email->viewBuilder()
<ide> ->setTemplate('default')
<del> ->layout('test');
<add> ->setLayout('test');
<ide>
<ide> $result = json_decode(json_encode($this->Email), true);
<ide> $this->assertContains('test', $result['viewVars']['exception']);
<ide><path>tests/TestCase/Mailer/MailerTest.php
<ide> public function testDefaultProfileRestoration()
<ide> ->with('foo', 'bar');
<ide>
<ide> $mailer->send('test', ['foo', 'bar']);
<del> $this->assertEquals('cakephp', $mailer->viewBuilder()->template());
<add> $this->assertEquals('cakephp', $mailer->viewBuilder()->getTemplate());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php
<ide> public function testRcptWithReturnPath()
<ide> $email = new Email();
<ide> $email->setFrom('[email protected]', 'CakePHP Test');
<ide> $email->setTo('[email protected]', 'CakePHP');
<del> $email->returnPath('[email protected]', 'CakePHP Return');
<add> $email->setReturnPath('[email protected]', 'CakePHP Return');
<ide>
<ide> $this->socket->expects($this->at(0))->method('write')->with("MAIL FROM:<[email protected]>\r\n");
<ide> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("250 OK\r\n"));
<ide><path>tests/test_app/TestApp/Error/TestAppsExceptionRenderer.php
<ide> protected function _getController()
<ide> $response = new Response();
<ide> try {
<ide> $controller = new TestAppsErrorController($request, $response);
<del> $controller->viewBuilder()->layout('banana');
<add> $controller->viewBuilder()->setLayout('banana');
<ide> } catch (\Exception $e) {
<ide> $controller = new Controller($request, $response);
<del> $controller->viewBuilder()->templatePath('Error');
<add> $controller->viewBuilder()->setTemplatePath('Error');
<ide> }
<ide>
<ide> return $controller;
<ide><path>tests/test_app/TestApp/Mailer/TestMailer.php
<ide> public function getEmailForAssertion()
<ide>
<ide> public function reset()
<ide> {
<del> $this->template = $this->viewBuilder()->template();
<add> $this->template = $this->viewBuilder()->getTemplate();
<ide>
<ide> return parent::reset();
<ide> } | 8 |
Mixed | Javascript | remove unstable_ prefix in various internal uses | 68fb58029d818979804677a4d1063eb71f2934f4 | <ide><path>packages/react-devtools-core/src/standalone.js
<ide> import {
<ide> // $FlowFixMe Flow does not yet know about flushSync()
<ide> flushSync,
<ide> // $FlowFixMe Flow does not yet know about createRoot()
<del> unstable_createRoot as createRoot,
<add> createRoot,
<ide> } from 'react-dom';
<ide> import Bridge from 'react-devtools-shared/src/bridge';
<ide> import Store from 'react-devtools-shared/src/devtools/store';
<ide><path>packages/react-devtools-extensions/src/main.js
<ide> /* global chrome */
<ide>
<ide> import {createElement} from 'react';
<del>import {unstable_createRoot as createRoot, flushSync} from 'react-dom';
<add>import {createRoot, flushSync} from 'react-dom';
<ide> import Bridge from 'react-devtools-shared/src/bridge';
<ide> import Store from 'react-devtools-shared/src/devtools/store';
<ide> import {
<ide><path>packages/react-devtools-inline/README.md
<ide> const contentWindow = iframe.contentWindow;
<ide> const DevTools = initialize(contentWindow);
<ide> ```
<ide>
<del><sup>3</sup> Because the DevTools interface makes use of several new React APIs (e.g. suspense, concurrent mode) it should be rendered using either `ReactDOM.unstable_createRoot` or `ReactDOM.unstable_createSyncRoot`. **It should not be rendered with `ReactDOM.render`.**
<add><sup>3</sup> Because the DevTools interface makes use of several new React APIs (e.g. suspense, concurrent mode) it should be rendered using either `ReactDOM.createRoot` or `ReactDOM.createSyncRoot`. **It should not be rendered with `ReactDOM.render`.**
<ide>
<ide> ## Examples
<ide>
<ide> initializeBackend(contentWindow);
<ide> const DevTools = initializeFrontend(contentWindow);
<ide>
<ide> // <DevTools /> interface can be rendered in the parent window at any time now...
<del>// Be sure to use either ReactDOM.unstable_createRoot()
<del>// or ReactDOM.unstable_createSyncRoot() to render this component.
<add>// Be sure to use either ReactDOM.createRoot()
<add>// or ReactDOM.createSyncRoot() to render this component.
<ide>
<ide> // Let the backend know the frontend is ready and listening.
<ide> activateBackend(contentWindow);
<ide> const { contentWindow } = iframe;
<ide>
<ide> // Initialize DevTools UI to listen to the iframe.
<ide> // This returns a React component we can render anywhere in the main window.
<del>// Be sure to use either ReactDOM.unstable_createRoot()
<del>// or ReactDOM.unstable_createSyncRoot() to render this component.
<add>// Be sure to use either ReactDOM.createRoot()
<add>// or ReactDOM.createSyncRoot() to render this component.
<ide> const DevTools = initialize(contentWindow);
<ide>
<ide> // Let the backend know to initialize itself.
<ide><path>packages/react-devtools-shell/src/app/index.js
<ide> import {createElement} from 'react';
<ide> import {
<ide> // $FlowFixMe Flow does not yet know about createRoot()
<del> unstable_createRoot as createRoot,
<add> createRoot,
<ide> } from 'react-dom';
<ide> import DeeplyNestedComponents from './DeeplyNestedComponents';
<ide> import Iframe from './Iframe';
<ide><path>packages/react-devtools-shell/src/devtools.js
<ide>
<ide> import {createElement} from 'react';
<ide> // $FlowFixMe Flow does not yet know about createRoot()
<del>import {unstable_createRoot as createRoot} from 'react-dom';
<add>import {createRoot} from 'react-dom';
<ide> import {
<ide> activate as activateBackend,
<ide> initialize as initializeBackend,
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerPartialHydration-test.internal.js
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> }).toWarnDev(
<ide> 'Warning: Cannot hydrate Suspense in legacy mode. Switch from ' +
<ide> 'ReactDOM.hydrate(element, container) to ' +
<del> 'ReactDOM.unstable_createSyncRoot(container, { hydrate: true })' +
<add> 'ReactDOM.createSyncRoot(container, { hydrate: true })' +
<ide> '.render(element) or remove the Suspense components from the server ' +
<ide> 'rendered components.' +
<ide> '\n in Suspense (at **)' +
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js
<ide> function mountDehydratedSuspenseComponent(
<ide> false,
<ide> 'Cannot hydrate Suspense in legacy mode. Switch from ' +
<ide> 'ReactDOM.hydrate(element, container) to ' +
<del> 'ReactDOM.unstable_createSyncRoot(container, { hydrate: true })' +
<add> 'ReactDOM.createSyncRoot(container, { hydrate: true })' +
<ide> '.render(element) or remove the Suspense components from ' +
<ide> 'the server rendered components.',
<ide> ); | 7 |
Ruby | Ruby | use clear_cache where appropriate | 6d7a3d7fa435edf1e0731e5f7a0121ec156ece48 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def fetch
<ide>
<ide> if @clone.exist? and not repo_valid?
<ide> puts "Removing invalid SVN repo from cache"
<del> @clone.rmtree
<add> clear_cache
<ide> end
<ide>
<ide> case @ref_type
<ide> def fetch
<ide> end
<ide> elsif @clone.exist?
<ide> puts "Removing invalid .git repo from cache"
<del> FileUtils.rm_rf @clone
<add> clear_cache
<ide> clone_repo
<ide> else
<ide> clone_repo
<ide> def fetch
<ide> @clone.cd { quiet_safe_system hgpath, 'pull', '--update' }
<ide> elsif @clone.exist?
<ide> puts "Removing invalid hg repo from cache"
<del> @clone.rmtree
<add> clear_cache
<ide> clone_repo
<ide> else
<ide> clone_repo
<ide> def fetch
<ide> @clone.cd { safe_system bzrpath, 'update' }
<ide> elsif @clone.exist?
<ide> puts "Removing invalid bzr repo from cache"
<del> @clone.rmtree
<add> clear_cache
<ide> clone_repo
<ide> else
<ide> clone_repo | 1 |
Ruby | Ruby | raise a useful message | e7ee57d5e5cf0502aaff8ad03cec195a723f43c5 | <ide><path>Library/Homebrew/superenv.rb
<ide> def determine_cc
<ide> when 'gcc', 'gcc-4.2' then 'gcc-4.2'
<ide> when 'llvm', 'llvm-gcc' then 'llvm-gcc'
<ide> else
<del> opoo "Invalid value for HOMEBREW_CC: #{ENV['HOMEBREW_CC']}"
<add> opoo "Invalid value for HOMEBREW_CC: #{ENV['HOMEBREW_CC'].inspect}"
<ide> raise # use default
<ide> end
<ide> else
<ide> def compiler
<ide> when "gcc-4.2" then :gcc
<ide> when "gcc", "clang" then ENV['HOMEBREW_CC'].to_sym
<ide> else
<del> raise
<add> raise "Invalid value for HOMEBREW_CC: #{ENV['HOMEBREW_CC'].inspect}"
<ide> end
<ide> end
<ide> def deparallelize | 1 |
Javascript | Javascript | use const where applicable in dllentryplugin | 575ca696e2c8bf4d6711b02b626a3b95f791974d | <ide><path>lib/DllEntryPlugin.js
<ide> class DllEntryPlugin {
<ide>
<ide> apply(compiler) {
<ide> compiler.plugin("compilation", (compilation, params) => {
<del> let dllModuleFactory = new DllModuleFactory();
<del> let normalModuleFactory = params.normalModuleFactory;
<add> const dllModuleFactory = new DllModuleFactory();
<add> const normalModuleFactory = params.normalModuleFactory;
<ide>
<ide> compilation.dependencyFactories.set(DllEntryDependency, dllModuleFactory);
<ide>
<ide> compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory);
<ide> });
<ide> compiler.plugin("make", (compilation, callback) => {
<ide> compilation.addEntry(this.context, new DllEntryDependency(this.entries.map((e, idx) => {
<del> let dep = new SingleEntryDependency(e);
<add> const dep = new SingleEntryDependency(e);
<ide> dep.loc = `${this.name}:${idx}`;
<ide> return dep;
<ide> }), this.name), this.name, callback); | 1 |
Ruby | Ruby | check respond_to? instead of inline rescue | 1d265e5a0acbc6fa92d4684bcbc9bc2abcf0155a | <ide><path>Library/Homebrew/caveats.rb
<ide> def initialize(f)
<ide> def caveats
<ide> caveats = []
<ide> caveats << f.caveats
<del> caveats << f.keg_only_text rescue nil if f.keg_only?
<add> caveats << f.keg_only_text if f.keg_only? && f.respond_to?(:keg_only_text)
<ide> caveats << bash_completion_caveats
<ide> caveats << zsh_completion_caveats
<ide> caveats << plist_caveats | 1 |
PHP | PHP | add tests and update transaction logic | 7a0832bb44057f1060c96c2e01652aae7c583323 | <ide><path>src/Illuminate/Database/Connection.php
<ide> public function transaction(Closure $callback, $attempts = 1)
<ide> */
<ide> public function beginTransaction()
<ide> {
<del> ++$this->transactions;
<del>
<del> if ($this->transactions == 1) {
<add> if ($this->transactions == 0) {
<ide> try {
<del> $this->getPdo()->beginTransaction();
<add> $this->pdo->beginTransaction();
<ide> } catch (Exception $e) {
<del> --$this->transactions;
<del>
<del> throw $e;
<add> if ($this->causedByLostConnection($e)) {
<add> $this->reconnect();
<add> $this->pdo->beginTransaction();
<add> } else {
<add> throw $e;
<add> }
<ide> }
<del> } elseif ($this->transactions > 1 && $this->queryGrammar->supportsSavepoints()) {
<del> $this->getPdo()->exec(
<del> $this->queryGrammar->compileSavepoint('trans'.$this->transactions)
<add> } elseif ($this->transactions >= 1 && $this->queryGrammar->supportsSavepoints()) {
<add> $this->pdo->exec(
<add> $this->queryGrammar->compileSavepoint('trans'.($this->transactions + 1))
<ide> );
<ide> }
<ide>
<add> ++$this->transactions;
<add>
<ide> $this->fireConnectionEvent('beganTransaction');
<ide> }
<ide>
<ide><path>tests/Database/DatabaseConnectionTest.php
<ide> public function testAffectingStatementProperlyCallsPDO()
<ide> $this->assertTrue(is_numeric($log[0]['time']));
<ide> }
<ide>
<del> public function testTransactionsDecrementedOnTransactionException()
<add> public function testTransactionLevelNotIncrementedOnTransactionException()
<ide> {
<ide> $pdo = $this->createMock('DatabaseConnectionTestMockPDO');
<del> $pdo->expects($this->once())->method('beginTransaction')->will($this->throwException(new ErrorException('MySQL server has gone away')));
<add> $pdo->expects($this->once())->method('beginTransaction')->will($this->throwException(new Exception));
<ide> $connection = $this->getMockConnection([], $pdo);
<del> $this->setExpectedException('ErrorException', 'MySQL server has gone away');
<add> try {
<add> $connection->beginTransaction();
<add> } catch (Exception $e) {
<add> $this->assertEquals(0, $connection->transactionLevel());
<add> }
<add> }
<add>
<add> public function testBeginTransactionMethodRetriesOnFailure()
<add> {
<add> $pdo = $this->createMock('DatabaseConnectionTestMockPDO');
<add> $pdo->expects($this->exactly(2))->method('beginTransaction');
<add> $pdo->expects($this->at(0))->method('beginTransaction')->will($this->throwException(new ErrorException('server has gone away')));
<add> $connection = $this->getMockConnection(['reconnect'], $pdo);
<add> $connection->expects($this->once())->method('reconnect');
<ide> $connection->beginTransaction();
<del> $connection->disconnect();
<del> $this->assertNull($connection->getPdo());
<add> $this->assertEquals(1, $connection->transactionLevel());
<add> }
<add>
<add> public function testBeginTransactionMethodNeverRetriesIfWithinTransaction()
<add> {
<add> $pdo = $this->createMock('DatabaseConnectionTestMockPDO');
<add> $pdo->expects($this->once())->method('beginTransaction');
<add> $pdo->expects($this->once())->method('exec')->will($this->throwException(new Exception));
<add> $connection = $this->getMockConnection(['reconnect'], $pdo);
<add> $queryGrammar = $this->createMock('Illuminate\Database\Query\Grammars\Grammar');
<add> $queryGrammar->expects($this->once())->method('supportsSavepoints')->will($this->returnValue(true));
<add> $connection->setQueryGrammar($queryGrammar);
<add> $connection->expects($this->never())->method('reconnect');
<add> $connection->beginTransaction();
<add> $this->assertEquals(1, $connection->transactionLevel());
<add> try {
<add> $connection->beginTransaction();
<add> } catch (Exception $e) {
<add> $this->assertEquals(1, $connection->transactionLevel());
<add> }
<ide> }
<ide>
<ide> public function testCantSwapPDOWithOpenTransaction() | 2 |
Ruby | Ruby | handle pazpar2 style | e4f291084aaa97cad176f13268420b2fbc899ab0 | <ide><path>Library/Homebrew/bottle_version.rb
<ide> def self._parse spec
<ide>
<ide> # e.g. x264-r2197.4.mavericks.bottle.tar.gz
<ide> # e.g. lz4-r114.mavericks.bottle.tar.gz
<del> m = /(r\d+\.?\d*)/.match(stem)
<add> m = /-(r\d+\.?\d*)/.match(stem)
<add> return m.captures.first unless m.nil?
<add>
<add> # e.g. 1.6.39 from pazpar2-1.6.39.mavericks.bottle.tar.gz
<add> m = /-(\d+\.\d+(\.\d+)+)/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # e.g. ssh-copy-id-6.2p2.mountain_lion.bottle.tar.gz
<ide> # e.g. icu4c-52.1.mountain_lion.bottle.tar.gz
<del> m = /(\d+\.(\d)+(p(\d)+)?)/.match(stem)
<add> m = /-(\d+\.(\d)+(p(\d)+)?)/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<ide> super
<ide><path>Library/Homebrew/test/test_bottle_versions.rb
<ide> def test_lz4_style
<ide> assert_version_detected 'r114',
<ide> '/usr/local/lz4-r114.mavericks.bottle.tar.gz'
<ide> end
<add>
<add> def test_pazpar2_style
<add> assert_version_detected '1.6.39',
<add> '/usr/local/pazpar2-1.6.39.mavericks.bottle.tar.gz'
<add> end
<ide> end | 2 |
Ruby | Ruby | avoid the need to defensively flatten tags array | 3df31557c8a378e8a13d2ce36391a7e1c0152acb | <ide><path>Library/Homebrew/dependency_collector.rb
<ide> def parse_string_spec(spec, tags)
<ide> elsif (tag = tags.first) && LANGUAGE_MODULES.include?(tag)
<ide> # Next line only for legacy support of `depends_on 'module' => :python`
<ide> # It should be replaced by `depends_on :python => 'module'`
<del> return PythonDependency.new("2", spec) if tag == :python
<add> return PythonDependency.new("2", Array(spec)) if tag == :python
<ide> LanguageModuleDependency.new(tag, spec)
<ide> else
<ide> Dependency.new(spec, tags)
<ide><path>Library/Homebrew/requirements/python_dependency.rb
<ide> def minor
<ide> end
<ide>
<ide> def initialize(default_version="2.6", tags=[])
<del> tags = [tags].flatten
<ide> # Extract the min_version if given. Default to default_version else
<ide> if /(\d+\.)*\d+/ === tags.first.to_s
<ide> @min_version = PythonVersion.new(tags.shift) | 2 |
Text | Text | es6ify the docs a little | 8e3b50c56418b9070e22bc59fc9346ae4a7726c9 | <ide><path>COOKBOOK.md
<ide> $ npm install axios promise --save
<ide> ```
<ide>
<ide> ```js
<del>var axios = require('axios');
<add>const axios = require('axios');
<ide> require('promise/polyfill-done');
<ide>
<ide> axios
<ide> .get('http://www.example.com/user')
<del> .then(function (response) {
<add> .then((response) => {
<ide> console.log(response.data);
<ide> return response;
<ide> })
<ide> $ npm install axios promise.prototype.finally --save
<ide> ```
<ide>
<ide> ```js
<del>var axios = require('axios');
<add>const axios = require('axios');
<ide> require('promise.prototype.finally').shim();
<ide>
<ide> axios
<ide> .get('http://www.example.com/user')
<del> .then(function (response) {
<add> .then((response) => {
<ide> console.log(response.data);
<ide> return response;
<ide> })
<del> .finally(function () {
<add> .finally(() => {
<ide> console.log('this will always be called');
<ide> });
<ide> ```
<ide> $ npm install axios pako --save
<ide>
<ide> ```js
<ide> // client.js
<del>var axios = require('axios');
<del>var pako = require('pako');
<add>const axios = require('axios');
<add>const pako = require('pako');
<ide>
<del>var user = {
<add>const user = {
<ide> firstName: 'Fred',
<ide> lastName: 'Flintstone'
<ide> };
<ide>
<del>var data = pako.deflate(JSON.stringify(user), { to: 'string' });
<add>const data = pako.deflate(JSON.stringify(user), { to: 'string' });
<ide>
<ide> axios
<ide> .post('http://127.0.0.1:3333/user', data)
<del> .then(function (response) {
<add> .then((response) => {
<ide> response.data = JSON.parse(pako.inflate(response.data, { to: 'string' }));
<ide> console.log(response.data);
<ide> return response;
<ide> axios
<ide>
<ide> ```js
<ide> // server.js
<del>var pako = require('pako');
<del>var http = require('http');
<del>var url = require('url');
<del>var server;
<add>const pako = require('pako');
<add>const http = require('http');
<add>const url = require('url');
<ide>
<del>server = http.createServer(function (req, res) {
<add>const server = http.createServer((req, res) => {
<ide> req.setEncoding('utf8');
<ide>
<del> var parsed = url.parse(req.url, true);
<del> var pathname = parsed.pathname;
<add> const parsed = url.parse(req.url, true);
<add> const pathname = parsed.pathname;
<ide>
<ide> if (pathname === '/user') {
<del> var data = '';
<del> req.on('data', function (chunk) {
<add> let data = '';
<add> req.on('data', (chunk) => {
<ide> data += chunk;
<ide> });
<ide>
<del> req.on('end', function () {
<del> var user = JSON.parse(pako.inflate(data, { to: 'string' }));
<add> req.on('end', () => {
<add> const user = JSON.parse(pako.inflate(data, { to: 'string' }));
<ide> console.log(user);
<ide>
<ide> res.writeHead(200, {
<ide> $ npm install jsonp --save
<ide> ```
<ide>
<ide> ```js
<del>var jsonp = require('jsonp');
<add>const jsonp = require('jsonp');
<ide>
<del>jsonp('http://www.example.com/foo', null, function (err, data) {
<add>jsonp('http://www.example.com/foo', null, (err, data) => {
<ide> if (err) {
<ide> console.error(err.message);
<ide> } else {
<ide><path>README.md
<ide> You can create a new instance of axios with a custom config.
<ide> ##### axios.create([config])
<ide>
<ide> ```js
<del>var instance = axios.create({
<add>const instance = axios.create({
<ide> baseURL: 'https://some-domain.com/api/',
<ide> timeout: 1000,
<ide> headers: {'X-Custom-Header': 'foobar'}
<ide> axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded
<ide>
<ide> ```js
<ide> // Set config defaults when creating the instance
<del>var instance = axios.create({
<add>const instance = axios.create({
<ide> baseURL: 'https://api.example.com'
<ide> });
<ide>
<ide> Config will be merged with an order of precedence. The order is library defaults
<ide> ```js
<ide> // Create an instance using the config defaults provided by the library
<ide> // At this point the timeout config value is `0` as is the default for the library
<del>var instance = axios.create();
<add>const instance = axios.create();
<ide>
<ide> // Override timeout default for the library
<ide> // Now all requests using this instance will wait 2.5 seconds before timing out
<ide> axios.interceptors.response.use(function (response) {
<ide> If you may need to remove an interceptor later you can.
<ide>
<ide> ```js
<del>var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
<add>const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
<ide> axios.interceptors.request.eject(myInterceptor);
<ide> ```
<ide>
<ide> You can add interceptors to a custom instance of axios.
<ide>
<ide> ```js
<del>var instance = axios.create();
<add>const instance = axios.create();
<ide> instance.interceptors.request.use(function () {/*...*/});
<ide> ```
<ide>
<ide> You can cancel a request using a *cancel token*.
<ide> You can create a cancel token using the `CancelToken.source` factory as shown below:
<ide>
<ide> ```js
<del>var CancelToken = axios.CancelToken;
<del>var source = CancelToken.source();
<add>const CancelToken = axios.CancelToken;
<add>const source = CancelToken.source();
<ide>
<ide> axios.get('/user/12345', {
<ide> cancelToken: source.token
<ide> source.cancel('Operation canceled by the user.');
<ide> You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
<ide>
<ide> ```js
<del>var CancelToken = axios.CancelToken;
<del>var cancel;
<add>const CancelToken = axios.CancelToken;
<add>let cancel;
<ide>
<ide> axios.get('/user/12345', {
<ide> cancelToken: new CancelToken(function executor(c) {
<ide> By default, axios serializes JavaScript objects to `JSON`. To send data in the `
<ide> In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows:
<ide>
<ide> ```js
<del>var params = new URLSearchParams();
<add>const params = new URLSearchParams();
<ide> params.append('param1', 'value1');
<ide> params.append('param2', 'value2');
<ide> axios.post('/foo', params);
<ide> axios.post('/foo', params);
<ide> Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
<ide>
<ide> ```js
<del>var qs = require('qs');
<add>const qs = require('qs');
<ide> axios.post('/foo', qs.stringify({ 'bar': 123 }));
<ide> ```
<ide>
<ide> axios(options);
<ide> In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
<ide>
<ide> ```js
<del>var querystring = require('querystring');
<add>const querystring = require('querystring');
<ide> axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
<ide> ```
<ide> | 2 |
Text | Text | update readme with for 0.14 | be90351add34c2a47328a2b7a0786c5c00d991c8 | <ide><path>README.md
<ide> The fastest way to get started is to serve JavaScript from the CDN (also availab
<ide>
<ide> ```html
<ide> <!-- The core React library -->
<del><script src="https://fb.me/react-0.13.3.js"></script>
<del><!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
<del><script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<add><script src="https://fb.me/react-0.14.0.js"></script>
<add><!-- The ReactDOM Library -->
<add><script src="https://fb.me/react-dom-0.14.0.js"></script>
<ide> ```
<ide>
<del>We've also built a [starter kit](https://facebook.github.io/react/downloads/react-0.13.3.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
<add>We've also built a [starter kit](https://facebook.github.io/react/downloads/react-0.14.0.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
<ide>
<ide> If you'd like to use [bower](http://bower.io), it's as easy as:
<ide> | 1 |
Text | Text | fix minor typo | ce1a0b612d300210fadf12556e1b38885f098197 | <ide><path>daemon/graphdriver/devmapper/README.md
<ide> Here is the list of supported options:
<ide> If using a block device for device mapper storage, ideally lvm2
<ide> would be used to create/manage the thin-pool volume that is then
<ide> handed to docker to exclusively create/manage the thin and thin
<del> snapshot volumes needed for it's containers. Managing the thin-pool
<add> snapshot volumes needed for its containers. Managing the thin-pool
<ide> outside of docker makes for the most feature-rich method of having
<ide> docker utilize device mapper thin provisioning as the backing
<ide> storage for docker's containers. lvm2-based thin-pool management | 1 |
Ruby | Ruby | fix broken nodocs | 72486005dd906939ced0fd69659b2fae2ee0ee01 | <ide><path>actionpack/lib/action_dispatch/middleware/flash.rb
<ide> def commit_flash # :nodoc:
<ide> end
<ide> end
<ide>
<del> def reset_session # :nodoc
<add> def reset_session # :nodoc:
<ide> super
<ide> self.flash = nil
<ide> end
<ide><path>activerecord/lib/active_record/associations.rb
<ide> def association(name) #:nodoc:
<ide> association
<ide> end
<ide>
<del> def association_cached?(name) # :nodoc
<add> def association_cached?(name) # :nodoc:
<ide> @association_cache.key?(name)
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/attribute_methods/read.rb
<ide> def read_attribute(attr_name, &block)
<ide> if defined?(JRUBY_VERSION)
<ide> # This form is significantly faster on JRuby, and this is one of our biggest hotspots.
<ide> # https://github.com/jruby/jruby/pull/2562
<del> def _read_attribute(attr_name, &block) # :nodoc
<add> def _read_attribute(attr_name, &block) # :nodoc:
<ide> @attributes.fetch_value(attr_name.to_s, &block)
<ide> end
<ide> else | 3 |
Ruby | Ruby | ignore callstacks from ruby stdlib in deprecation | ba004484cd3456fc8cb6391e7927f3ddc8e32dad | <ide><path>activesupport/lib/active_support/deprecation/reporting.rb
<add>require 'rbconfig'
<add>
<ide> module ActiveSupport
<ide> class Deprecation
<ide> module Reporting
<ide> def deprecation_caller_message(callstack)
<ide> def extract_callstack(callstack)
<ide> return _extract_callstack(callstack) if callstack.first.is_a? String
<ide>
<del> rails_gem_root = File.expand_path("../../../../..", __FILE__) + "/"
<ide> offending_line = callstack.find { |frame|
<del> frame.absolute_path && !frame.absolute_path.start_with?(rails_gem_root)
<add> frame.absolute_path && !ignored_callstack(frame.absolute_path)
<ide> } || callstack.first
<add>
<ide> [offending_line.path, offending_line.lineno, offending_line.label]
<ide> end
<ide>
<ide> def _extract_callstack(callstack)
<ide> warn "Please pass `caller_locations` to the deprecation API" if $VERBOSE
<del> rails_gem_root = File.expand_path("../../../../..", __FILE__) + "/"
<del> offending_line = callstack.find { |line| !line.start_with?(rails_gem_root) } || callstack.first
<add> offending_line = callstack.find { |line| !ignored_callstack(path) } || callstack.first
<add>
<ide> if offending_line
<ide> if md = offending_line.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
<ide> md.captures
<ide> def _extract_callstack(callstack)
<ide> end
<ide> end
<ide> end
<add>
<add> RAILS_GEM_ROOT = File.expand_path("../../../../..", __FILE__) + "/"
<add>
<add> def ignored_callstack(path)
<add> path.start_with?(RAILS_GEM_ROOT) || path.start_with?(RbConfig::CONFIG['rubylibdir'])
<add> end
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | remove generated file | fd2b1341f6abca876dc1bc21d0966c7026f0fad1 | <ide><path>src/time/format-en_GB.js
<del>// The date and time format (%c), date format (%x) and time format (%X).
<del>var d3_time_formatDateTime = "%a %b %e %H:%M:%S %Y",
<del> d3_time_formatDate = "%d/%m/%y",
<del> d3_time_formatTime = "%H:%M:%S";
<del>
<del>// The weekday and month names.
<del>var d3_time_days = d3_time_daySymbols,
<del> d3_time_dayAbbreviations = d3_time_days.map(d3_time_formatAbbreviate),
<del> d3_time_months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
<del> d3_time_monthAbbreviations = d3_time_months.map(d3_time_formatAbbreviate);
<del>
<del>function d3_time_formatAbbreviate(name) {
<del> return name.substring(0, 3);
<del>} | 1 |
Ruby | Ruby | recognize amd cpus on linux | 97c9a952d3a78f532a2caaa5efdad743513018ff | <ide><path>Library/Homebrew/extend/os/linux/hardware/cpu.rb
<ide> def family
<ide> # See https://software.intel.com/en-us/articles/intel-architecture-and-processor-identification-with-cpuid-model-and-family-numbers
<ide> # and https://github.com/llvm-mirror/llvm/blob/HEAD/lib/Support/Host.cpp
<ide> # and https://en.wikipedia.org/wiki/List_of_Intel_CPU_microarchitectures#Roadmap
<add> vendor_id = cpuinfo[/^vendor_id\s*: (.*)/, 1]
<ide> cpu_family = cpuinfo[/^cpu family\s*: ([0-9]+)/, 1].to_i
<ide> cpu_model = cpuinfo[/^model\s*: ([0-9]+)/, 1].to_i
<ide> unknown = :"unknown_0x#{cpu_family.to_s(16)}_0x#{cpu_model.to_s(16)}"
<del> case cpu_family
<add> case vendor_id
<add> when "GenuineIntel"
<add> intel_family(cpu_family, cpu_model) || unknown
<add> when "AuthenticAMD"
<add> amd_family(cpu_family) || unknown
<add> else
<add> unknown
<add> end
<add> end
<add>
<add> def intel_family(family, model)
<add> case family
<ide> when 0x06
<del> case cpu_model
<add> case model
<ide> when 0x3a, 0x3e
<ide> :ivybridge
<ide> when 0x2a, 0x2d
<ide> def family
<ide> :cannonlake
<ide> when 0x6a, 0x6c, 0x7d, 0x7e
<ide> :icelake
<del> else
<del> unknown
<ide> end
<ide> when 0x0f
<del> case cpu_model
<add> case model
<ide> when 0x06
<ide> :presler
<ide> when 0x03, 0x04
<ide> :prescott
<del> else
<del> unknown
<ide> end
<del> else
<del> unknown
<add> end
<add> end
<add>
<add> def amd_family(family)
<add> case family
<add> when 0x06
<add> :amd_k7
<add> when 0x0f
<add> :amd_k8
<add> when 0x10
<add> :amd_k10
<add> when 0x11
<add> :amd_k8_k10_hybrid
<add> when 0x12
<add> :amd_k12
<add> when 0x14
<add> :bobcat
<add> when 0x15
<add> :bulldozer
<add> when 0x16
<add> :jaguar
<add> when 0x17
<add> :zen
<add> when 0x19
<add> :zen3
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | use the source returned from encode! | 916b74d16a5ed369ba58c17630f593470ca502a8 | <ide><path>actionview/lib/action_view/template.rb
<ide> def inspect
<ide> # before passing the source on to the template engine, leaving a
<ide> # blank line in its stead.
<ide> def encode!
<del> return unless source.encoding == Encoding::BINARY
<add> source = self.source
<add>
<add> return source unless source.encoding == Encoding::BINARY
<ide>
<ide> # Look for # encoding: *. If we find one, we'll encode the
<ide> # String in that encoding, otherwise, we'll use the
<ide> def compile!(view)
<ide> # In general, this means that templates will be UTF-8 inside of Rails,
<ide> # regardless of the original source encoding.
<ide> def compile(mod)
<del> encode!
<add> source = encode!
<ide> code = @handler.call(self)
<ide>
<ide> # Make sure that the resulting String to be eval'd is in the
<ide> def #{method_name}(local_assigns, output_buffer)
<ide> # handler is valid in the default_internal. This is for handlers
<ide> # that handle encoding but screw up
<ide> unless source.valid_encoding?
<del> raise WrongEncodingError.new(@source, Encoding.default_internal)
<add> raise WrongEncodingError.new(source, Encoding.default_internal)
<ide> end
<ide>
<ide> mod.module_eval(source, identifier, 0) | 1 |
Python | Python | remove trailing whitespace | 121c310566da7e3853d76afbac102154975fa4e5 | <ide><path>spacy/tests/regression/test_issue595.py
<ide> def test_not_lemmatize_base_forms(vocab, lemmatizer):
<ide> feed.tag_ = u'VB'
<ide> assert feed.text == u'feed'
<ide> assert feed.lemma_ == u'feed'
<del> | 1 |
Javascript | Javascript | improve code, remove unneeded old stuff | f9846f1f91f1827fa351febad788f0d38b8e6115 | <ide><path>lib/NormalModule.js
<ide> const makeSerializable = require("./util/makeSerializable");
<ide> /** @typedef {import("./util/Hash")} Hash */
<ide> /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
<ide>
<add>/**
<add> * @typedef {Object} LoaderItem
<add> * @property {string} loader
<add> * @property {any} options
<add> * @property {string?} ident
<add> */
<add>
<ide> /**
<ide> * @param {string} context absolute context path
<ide> * @param {string} source a source path
<ide> class NormalModule extends Module {
<ide> * @param {string} options.request request string
<ide> * @param {string} options.userRequest request intented by user (without loaders from config)
<ide> * @param {string} options.rawRequest request without resolving
<del> * @param {TODO[]} options.loaders list of loaders
<add> * @param {LoaderItem[]} options.loaders list of loaders
<ide> * @param {string} options.resource path + query of the real resource
<ide> * @param {string | undefined} options.matchResource path + query of the matched resource (virtuel
<ide> * @param {Parser} options.parser the parser used
<ide> class NormalModule extends Module {
<ide> this.resource = resource;
<ide> /** @type {string | undefined} */
<ide> this.matchResource = matchResource;
<del> /** @type {TODO[]} */
<add> /** @type {LoaderItem[]} */
<ide> this.loaders = loaders;
<ide> if (resolveOptions !== undefined) {
<ide> // already declared in super class
<ide> class NormalModule extends Module {
<ide> };
<ide> const loaderContext = {
<ide> version: 2,
<del> getOptions: (loaderName, schema) => {
<del> const loader = loaderContext.loaders[loaderContext.loaderIndex];
<del> let options = {};
<del>
<del> if (loader.options && typeof loader.options === "object") {
<del> ({ options } = loader);
<del> } else if (loader.query) {
<del> let { query } = loader;
<del>
<del> if (query.substr(0, 1) !== "?") {
<del> throw new WebpackError(
<del> "A valid query string should begin with '?'"
<del> );
<del> }
<add> getOptions: schema => {
<add> const loader = this.getCurrentLoader(loaderContext);
<ide>
<del> query = query.substr(1);
<add> let { options } = loader;
<ide>
<del> // Allow to use `?foo=bar` in `options`
<del> if (query.substr(0, 1) === "?") {
<del> query = query.substr(1);
<del> }
<del>
<del> if (query.substr(0, 1) === "{" && query.substr(-1) === "}") {
<add> if (typeof options === "string") {
<add> if (options.substr(0, 1) === "{" && options.substr(-1) === "}") {
<ide> try {
<del> options = parseJson(query);
<add> options = parseJson(options);
<ide> } catch (e) {
<del> throw new WebpackError(`Cannot parse query string: ${e.message}`);
<add> throw new Error(`Cannot parse string options: ${e.message}`);
<ide> }
<ide> } else {
<del> options = querystring.parse(query);
<add> options = querystring.parse(options, "&", "=", {
<add> maxKeys: 0
<add> });
<ide> }
<ide> }
<ide>
<del> if (!schema) {
<del> return options;
<add> if (options === null || options === undefined) {
<add> options = {};
<ide> }
<ide>
<del> validateOptions(schema, options, {
<del> name: loaderName || "Unknown Loader",
<del> baseDataPath: "options"
<del> });
<add> if (schema) {
<add> validateOptions(schema, options, {
<add> name: getCurrentLoaderName(),
<add> baseDataPath: "options"
<add> });
<add> }
<ide>
<ide> return options;
<ide> },
<ide><path>test/configCases/loaders/options/deprecations.js
<add>module.exports = [
<add> { code: /DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING/ },
<add> { code: /DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING/ },
<add> { code: /DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING/ },
<add> { code: /DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING/ },
<add> { code: /DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING/ },
<add> { code: /DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING/ },
<add> { code: /DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING/ }
<add>];
<ide><path>test/configCases/loaders/options/loader-1.js
<del>const schema = require('./loader-1.options');
<add>const schema = require("./loader-1.options");
<ide>
<ide> module.exports = function() {
<del> const options = this.getOptions('Loader Name', schema);
<add> const options = this.getOptions(schema);
<ide>
<ide> const json = JSON.stringify(options)
<del> .replace(/\u2028/g, '\\u2028')
<del> .replace(/\u2029/g, '\\u2029');
<del>
<add> .replace(/\u2028/g, "\\u2028")
<add> .replace(/\u2029/g, "\\u2029");
<ide>
<ide> return `module.exports = ${json}`;
<ide> };
<ide><path>test/configCases/loaders/options/webpack.config.js
<ide> module.exports = {
<ide> {
<ide> test: /d\.js$/,
<ide> loader: "./loader",
<del> options: "?"
<add> options: ""
<ide> },
<ide> {
<ide> test: /f\.js$/,
<ide> module.exports = {
<ide> {
<ide> test: /h\.js$/,
<ide> loader: "./loader",
<del> options: "?foo=bar"
<add> options: "foo=bar"
<ide> },
<ide> {
<ide> test: /i\.js$/,
<ide> loader: "./loader",
<del> options: `?${JSON.stringify({
<add> options: `${JSON.stringify({
<ide> foo: "bar"
<ide> })}`
<ide> } | 4 |
Javascript | Javascript | append whitespace divs so matches still line up | 5ba674c9961976e991820b5adac730c6260847e3 | <ide><path>web/text_layer_builder.js
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide> this.appendText = function textLayerBuilderAppendText(geom, styles) {
<ide> var style = styles[geom.fontName];
<ide> var textDiv = document.createElement('div');
<add> this.textDivs.push(textDiv);
<ide> if (!/\S/.test(geom.str)) {
<ide> textDiv.dataset.isWhitespace = true;
<ide> return;
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide> textDiv.dataset.canvasWidth = geom.width * this.viewport.scale;
<ide> }
<ide>
<del> this.textDivs.push(textDiv);
<ide> };
<ide>
<ide> this.setTextContent = function textLayerBuilderSetTextContent(textContent) { | 1 |
Text | Text | update chat server to discord server | 3ab1e4be7142b988c5bfc1bde8855f20f6ee2432 | <ide><path>README.md
<ide> Our community also has:
<ide> - A [forum](https://forum.freecodecamp.org) where you can usually get programming help or project feedback within hours.
<ide> - A [YouTube channel](https://youtube.com/freecodecamp) with free courses on Python, SQL, Android, and a wide variety of other technologies.
<ide> - A [technical publication](https://www.freecodecamp.org/news) with thousands of programming tutorials and articles about math and computer science.
<del>- A [chat server](https://chat.freecodecamp.org/home) where you can hang out and talk with developers and people who are learning to code.
<add>- A [Discord server](https://discord.gg/Z7Fm39aNtZ) where you can hang out and talk with developers and people who are learning to code.
<ide>
<ide> > #### [Join the community here](https://www.freecodecamp.org/signin).
<ide> | 1 |
PHP | PHP | add mergerecursive() method on collections | 9add84a72d5337adfe245553ca20da94ed08eedf | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function merge($items)
<ide> return new static(array_merge($this->items, $this->getArrayableItems($items)));
<ide> }
<ide>
<add> /**
<add> * Recursively merge the collection with the given items.
<add> *
<add> * @param mixed $items
<add> * @return static
<add> */
<add> public function mergeRecursive($items)
<add> {
<add> return new static(array_merge_recursive($this->items, $this->getArrayableItems($items)));
<add> }
<add>
<ide> /**
<ide> * Create a collection by using this collection for keys and another for its values.
<ide> *
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testMergeCollection()
<ide> $this->assertEquals(['name' => 'World', 'id' => 1], $c->merge(new Collection(['name' => 'World', 'id' => 1]))->all());
<ide> }
<ide>
<add> public function testMergeRecursiveNull()
<add> {
<add> $c = new Collection(['name' => 'Hello']);
<add> $this->assertEquals(['name' => 'Hello'], $c->mergeRecursive(null)->all());
<add> }
<add>
<add> public function testMergeRecursiveArray()
<add> {
<add> $c = new Collection(['name' => 'Hello', 'id' => 1]);
<add> $this->assertEquals(['name' => 'Hello', 'id' => [1, 2]], $c->mergeRecursive(['id' => 2])->all());
<add> }
<add>
<add> public function testMergeRecursiveCollection()
<add> {
<add> $c = new Collection(['name' => 'Hello', 'id' => 1]);
<add> $this->assertEquals(
<add> ['name' => ['Hello', 'World'], 'id' => [1, 2]],
<add> $c->mergeRecursive(new Collection(['name' => 'World', 'id' => 2]))->all()
<add> );
<add> }
<add>
<ide> public function testUnionNull()
<ide> {
<ide> $c = new Collection(['name' => 'Hello']); | 2 |
Java | Java | fix scrollview contentoffset | be260b9f479a3b55ee43d2959d2c49fd3c1eb4ac | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java
<ide> protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
<ide> @Override
<ide> protected void onLayout(boolean changed, int l, int t, int r, int b) {
<ide> // Call with the present values in order to re-layout if necessary
<del> // If a "pending" value has been set, we restore that value.
<del> // That value gets cleared by reactScrollTo.
<add> // If a "pending" content offset value has been set, we restore that value.
<add> // Upon call to scrollTo, the "pending" values will be re-set.
<ide> int scrollToX =
<ide> pendingContentOffsetX != UNSET_CONTENT_OFFSET ? pendingContentOffsetX : getScrollX();
<ide> int scrollToY =
<ide> public void reactSmoothScrollTo(int x, int y) {
<ide> }
<ide>
<ide> /**
<del> * Calls `reactScrollTo` and updates state.
<add> * Calls `updateFabricScrollState` and updates state.
<ide> *
<del> * <p>`reactScrollTo` changes `contentOffset` and we need to keep `contentOffset` in sync between
<del> * scroll view and state. Calling raw `reactScrollTo` doesn't update state.
<del> *
<del> * <p>Note that while we can override scrollTo, we *cannot* override `smoothScrollTo` because it
<del> * is final. See `reactSmoothScrollTo`.
<add> * <p>`scrollTo` changes `contentOffset` and we need to keep `contentOffset` in sync between
<add> * scroll view and state. Calling ScrollView's `scrollTo` doesn't update state.
<ide> */
<ide> @Override
<ide> public void scrollTo(int x, int y) {
<ide> super.scrollTo(x, y);
<del> // The final scroll position might be different from (x, y). For example, we may need to scroll
<del> // to the last item in the list, but that item cannot be move to the start position of the view.
<del> final int actualX = getScrollX();
<del> final int actualY = getScrollY();
<del> ReactScrollViewHelper.updateFabricScrollState(this, actualX, actualY);
<del> setPendingContentOffsets(actualX, actualY);
<add> ReactScrollViewHelper.updateFabricScrollState(this);
<add> setPendingContentOffsets(x, y);
<add> }
<add>
<add> private boolean isContentReady() {
<add> View child = getChildAt(0);
<add> return child != null && child.getWidth() != 0 && child.getHeight() != 0;
<ide> }
<ide>
<ide> /**
<ide> public void scrollTo(int x, int y) {
<ide> * @param y
<ide> */
<ide> private void setPendingContentOffsets(int x, int y) {
<del> View child = getChildAt(0);
<del> if (child != null && child.getWidth() != 0 && child.getHeight() != 0) {
<add> if (isContentReady()) {
<ide> pendingContentOffsetX = UNSET_CONTENT_OFFSET;
<ide> pendingContentOffsetY = UNSET_CONTENT_OFFSET;
<ide> } else { | 1 |
Javascript | Javascript | verify input flags | 240065fd8bef51e55a4f65fbe54d7cfc8b98cd40 | <ide><path>test/common/index.js
<ide> const isMainThread = (() => {
<ide> }
<ide> })();
<ide>
<add>// Check for flags. Skip this for workers (both, the `cluster` module and
<add>// `worker_threads`) and child processes.
<add>if (process.argv.length === 2 &&
<add> isMainThread &&
<add> module.parent &&
<add> require('cluster').isMaster) {
<add> // The copyright notice is relatively big and the flags could come afterwards.
<add> const bytesToRead = 1500;
<add> const buffer = Buffer.allocUnsafe(bytesToRead);
<add> const fd = fs.openSync(module.parent.filename, 'r');
<add> fs.readSync(fd, buffer, 0, bytesToRead);
<add> fs.closeSync(fd);
<add> const source = buffer.toString();
<add>
<add> const flagStart = source.indexOf('// Flags: --') + 10;
<add> if (flagStart !== 9) {
<add> let flagEnd = source.indexOf('\n', flagStart);
<add> // Normalize different EOL.
<add> if (source[flagEnd - 1] === '\r') {
<add> flagEnd--;
<add> }
<add> const flags = source
<add> .substring(flagStart, flagEnd)
<add> .replace(/_/g, '-')
<add> .split(' ');
<add> const args = process.execArgv.map((arg) => arg.replace(/_/g, '-'));
<add> for (const flag of flags) {
<add> if (!args.includes(flag) &&
<add> // If the binary is build without `intl` the inspect option is
<add> // invalid. The test itself should handle this case.
<add> (process.config.variables.v8_enable_inspector !== 0 ||
<add> !flag.startsWith('--inspect'))) {
<add> throw new Error(`Test has to be started with the flag: '${flag}'`);
<add> }
<add> }
<add> }
<add>}
<add>
<ide> const isWindows = process.platform === 'win32';
<ide> const isAIX = process.platform === 'aix';
<ide> const isLinuxPPCBE = (process.platform === 'linux') && | 1 |
PHP | PHP | limit backtrace frames to return | 2af75c10a5cb8ef73bce708be0ec240a1b33780d | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat
<ide> // of the time this will be what we desire to use for the relationships.
<ide> if (is_null($relation))
<ide> {
<del> list(, $caller) = debug_backtrace(false);
<add> list(, $caller) = debug_backtrace(false, 2);
<ide>
<ide> $relation = $caller['function'];
<ide> }
<ide> public function morphTo($name = null, $type = null, $id = null)
<ide> // use that to get both the class and foreign key that will be utilized.
<ide> if (is_null($name))
<ide> {
<del> list(, $caller) = debug_backtrace(false);
<add> list(, $caller) = debug_backtrace(false, 2);
<ide>
<ide> $name = snake_case($caller['function']);
<ide> } | 1 |
Javascript | Javascript | use binary search for interpolations | 9fda5ec667848f12d732a4ca1e89088ac30f2a69 | <ide><path>src/core/core.datasetController.js
<ide> helpers.extend(DatasetController.prototype, {
<ide> * @private
<ide> */
<ide> _getSharedOptions: function(mode, el, options) {
<add> if (!mode) {
<add> // store element option sharing status for usage in interactions
<add> this._sharedOptions = options && options.$shared;
<add> }
<ide> if (mode !== 'reset' && options && options.$shared && el && el.options && el.options.$shared) {
<ide> return {target: el.options, options};
<ide> }
<ide><path>src/core/core.interaction.js
<ide> 'use strict';
<ide>
<ide> import helpers from '../helpers/index';
<del>import {isNumber} from '../helpers/helpers.math';
<ide> import {_isPointInArea} from '../helpers/helpers.canvas';
<add>import {_lookup, _rlookup} from '../helpers/helpers.collection';
<ide>
<ide> /**
<ide> * Helper function to get relative position for an event
<ide> function evaluateAllVisibleItems(chart, handler) {
<ide> }
<ide>
<ide> /**
<del> * Helper function to check the items at the hovered index on the index scale
<add> * Helper function to do binary search when possible
<add> * @param {object} metaset - the dataset meta
<add> * @param {string} axis - the axis mide. x|y|xy
<add> * @param {number} value - the value to find
<add> * @param {boolean} intersect - should the element intersect
<add> * @returns {lo, hi} indices to search data array between
<add> */
<add>function binarySearch(metaset, axis, value, intersect) {
<add> const {controller, data, _sorted} = metaset;
<add> const iScale = controller._cachedMeta.iScale;
<add> if (iScale && axis === iScale.axis && _sorted) {
<add> const lookupMethod = iScale._reversePixels ? _rlookup : _lookup;
<add> if (!intersect) {
<add> return lookupMethod(data, axis, value);
<add> } else if (controller._sharedOptions) {
<add> // _sharedOptions indicates that each element has equal options -> equal proportions
<add> // So we can do a ranged binary search based on the range of first element and
<add> // be confident to get the full range of indices that can intersect with the value.
<add> const el = data[0];
<add> const range = typeof el.getRange === 'function' && el.getRange(axis);
<add> if (range) {
<add> const start = lookupMethod(data, axis, value - range);
<add> const end = lookupMethod(data, axis, value + range);
<add> return {lo: start.lo, hi: end.hi};
<add> }
<add> }
<add> }
<add> // Default to all elements, when binary search can not be used.
<add> return {lo: 0, hi: data.length - 1};
<add>}
<add>
<add>/**
<add> * Helper function to get items using binary search, when the data is sorted.
<ide> * @param {Chart} chart - the chart
<ide> * @param {string} axis - the axis mode. x|y|xy
<ide> * @param {object} position - the point to be nearest to
<ide> * @param {function} handler - the callback to execute for each visible item
<del> * @return whether all scales were of a suitable type
<add> * @param {boolean} intersect - consider intersecting items
<ide> */
<del>function evaluateItemsAtIndex(chart, axis, position, handler) {
<add>function optimizedEvaluateItems(chart, axis, position, handler, intersect) {
<ide> const metasets = chart._getSortedVisibleDatasetMetas();
<del> const indices = [];
<del> for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
<del> const metaset = metasets[i];
<del> const iScale = metaset.controller._cachedMeta.iScale;
<del> if (!iScale || axis !== iScale.axis || !iScale.getIndexForPixel) {
<del> return false;
<del> }
<del> const index = iScale.getIndexForPixel(position[axis]);
<del> if (!isNumber(index)) {
<del> return false;
<del> }
<del> indices.push(index);
<del> }
<del> // do this only after checking whether all scales are of a suitable type
<add> const value = position[axis];
<ide> for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
<del> const metaset = metasets[i];
<del> const index = indices[i];
<del> const element = metaset.data[index];
<del> if (!element.skip) {
<del> handler(element, metaset.index, index);
<add> const {index, data} = metasets[i];
<add> let {lo, hi} = binarySearch(metasets[i], axis, value, intersect);
<add> for (let j = lo; j <= hi; ++j) {
<add> const element = data[j];
<add> if (!element.skip) {
<add> handler(element, index, j);
<add> }
<ide> }
<ide> }
<del> return true;
<ide> }
<ide>
<ide> /**
<ide> function getIntersectItems(chart, position, axis) {
<ide> }
<ide> };
<ide>
<del> const optimized = evaluateItemsAtIndex(chart, axis, position, evaluationFunc);
<del> if (optimized) {
<del> return items;
<del> }
<del>
<del> evaluateAllVisibleItems(chart, evaluationFunc);
<add> optimizedEvaluateItems(chart, axis, position, evaluationFunc, true);
<ide> return items;
<ide> }
<ide>
<ide> function getNearestItems(chart, position, axis, intersect) {
<ide> }
<ide> };
<ide>
<del> const optimized = evaluateItemsAtIndex(chart, axis, position, evaluationFunc);
<del> if (optimized) {
<del> return items;
<del> }
<del>
<del> evaluateAllVisibleItems(chart, evaluationFunc);
<add> optimizedEvaluateItems(chart, axis, position, evaluationFunc);
<ide> return items;
<ide> }
<ide>
<ide><path>src/elements/element.point.js
<ide> class Point extends Element {
<ide> helpers.canvas.drawPoint(ctx, options, me.x, me.y);
<ide> }
<ide> }
<add>
<add> getRange() {
<add> const options = this.options || {};
<add> return options.radius + options.hitRadius;
<add> }
<ide> }
<ide>
<ide> Point.prototype._type = 'point';
<ide><path>src/elements/element.rectangle.js
<ide> class Rectangle extends Element {
<ide> y: this.y
<ide> };
<ide> }
<add>
<add> getRange(axis) {
<add> return axis === 'x' ? this.width / 2 : this.height / 2;
<add> }
<ide> }
<ide>
<ide> Rectangle.prototype._type = 'rectangle';
<ide><path>src/helpers/helpers.collection.js
<add>'use strict';
<add>
<add>/**
<add> * Binary search
<add> * @param {array} table - the table search. must be sorted!
<add> * @param {string} key - property name for the value in each entry
<add> * @param {number} value - value to find
<add> * @private
<add> */
<add>export function _lookup(table, key, value) {
<add> let hi = table.length - 1;
<add> let lo = 0;
<add> let mid;
<add>
<add> while (hi - lo > 1) {
<add> mid = (lo + hi) >> 1;
<add> if (table[mid][key] < value) {
<add> lo = mid;
<add> } else {
<add> hi = mid;
<add> }
<add> }
<add>
<add> return {lo, hi};
<add>}
<add>
<add>/**
<add> * Reverse binary search
<add> * @param {array} table - the table search. must be sorted!
<add> * @param {string} key - property name for the value in each entry
<add> * @param {number} value - value to find
<add> * @private
<add> */
<add>export function _rlookup(table, key, value) {
<add> let hi = table.length - 1;
<add> let lo = 0;
<add> let mid;
<add>
<add> while (hi - lo > 1) {
<add> mid = (lo + hi) >> 1;
<add> if (table[mid][key] < value) {
<add> hi = mid;
<add> } else {
<add> lo = mid;
<add> }
<add> }
<add>
<add> return {lo, hi};
<add>}
<ide><path>src/scales/scale.time.js
<ide> import defaults from '../core/core.defaults';
<ide> import helpers from '../helpers/index';
<ide> import {toRadians} from '../helpers/helpers.math';
<ide> import Scale from '../core/core.scale';
<add>import {_lookup} from '../helpers/helpers.collection';
<ide>
<ide> const resolve = helpers.options.resolve;
<ide> const valueOrDefault = helpers.valueOrDefault;
<ide> function buildLookupTable(timestamps, min, max, distribution) {
<ide> return table;
<ide> }
<ide>
<del>// @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
<del>function lookup(table, key, value) {
<del> let lo = 0;
<del> let hi = table.length - 1;
<del> let mid, i0, i1;
<del>
<del> while (lo >= 0 && lo <= hi) {
<del> mid = (lo + hi) >> 1;
<del> i0 = mid > 0 && table[mid - 1] || null;
<del> i1 = table[mid];
<del>
<del> if (!i0) {
<del> // given value is outside table (before first item)
<del> return {lo: null, hi: i1};
<del> } else if (i1[key] < value) {
<del> lo = mid + 1;
<del> } else if (i0[key] > value) {
<del> hi = mid - 1;
<del> } else {
<del> return {lo: i0, hi: i1};
<del> }
<del> }
<del>
<del> // given value is outside table (after last item)
<del> return {lo: i1, hi: null};
<del>}
<del>
<ide> /**
<ide> * Linearly interpolates the given source `value` using the table items `skey` values and
<ide> * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
<ide> * returns the position for a timestamp equal to 42. If value is out of bounds, values at
<ide> * index [0, 1] or [n - 1, n] are used for the interpolation.
<ide> */
<ide> function interpolate(table, skey, sval, tkey) {
<del> const range = lookup(table, skey, sval);
<add> const {lo, hi} = _lookup(table, skey, sval);
<ide>
<ide> // Note: the lookup table ALWAYS contains at least 2 items (min and max)
<del> const prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
<del> const next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
<add> const prev = table[lo];
<add> const next = table[hi];
<ide>
<ide> const span = next[skey] - prev[skey];
<ide> const ratio = span ? (sval - prev[skey]) / span : 0;
<ide> class TimeScale extends Scale {
<ide> return interpolate(me._table, 'pos', pos, 'time');
<ide> }
<ide>
<del> getIndexForPixel(pixel) {
<del> const me = this;
<del> if (me.options.distribution !== 'series') {
<del> return null; // not implemented
<del> }
<del> const index = Math.round(me._numIndices * me.getDecimalForPixel(pixel));
<del> return index < 0 || index >= me.numIndices ? null : index;
<del> }
<del>
<ide> /**
<ide> * @private
<ide> */ | 6 |
Text | Text | complete the list of entity name | dedabdf89f5fd29c9e7528e7c17b5d4991664918 | <ide><path>guide/english/html/html-entities/index.md
<ide> This is by no means an exhaustive list but the links below will be able to give
<ide>
<ide> | Character | Entity Name | Entity Number | Description |
<ide> |-------|-----------|-----------|-------|
<del>| | | ` ` | Space |
<del>| ! | | `!` | Exclamation mark |
<del>| " | | `"` | Quotation mark |
<del>| # | | `#` | Number sign |
<del>| $ | | `$` | Dollar sign |
<add>| | ` ` | ` ` | Space |
<add>| ! | `!` | `!` | Exclamation mark |
<add>| " | `"` | `"` | Quotation mark |
<add>| # | `#` | `#` | Number sign |
<add>| $ | `$`| `$` | Dollar sign |
<ide> | ¢ | `¢` | `¢` | Cent sign |
<ide> | € | `€` | `€` | Euro sign |
<ide> | £ | `£` | `£` | GBP sign |
<ide> | ¥ | `¥` | `¥` | Yen sign |
<del>| % | | `%` | Percent sign |
<add>| % | `%`| `%` | Percent sign |
<ide> | & | `&` | `&` | Ampersand |
<del>| ' | | `'` | Apostrophe |
<del>| ( | | `(` | Opening/Left Parenthesis |
<del>| ) | | `)` | Closing/Right Parenthesis |
<del>| * | | `*` | Asterisk |
<del>| + | | `+` | Plus sign|
<del>| , | | `,` | Comma |
<del>| - | | `-` | Hyphen |
<del>| . | | `.` | Period |
<del>| / | | `/` | Slash |
<add>| ' | `'` | `'` | Apostrophe |
<add>| ( | `(` | `(` | Opening/Left Parenthesis |
<add>| ) | `)` | `)` | Closing/Right Parenthesis |
<add>| * | `*` | `*` | Asterisk |
<add>| + | `+` | `+` | Plus sign|
<add>| , | `,` | `,` | Comma |
<add>| - | `‐` | `-` | Hyphen |
<add>| . | `.`| `.` | Period |
<add>| / | `/` | `/` | Slash |
<ide> | © | `©` | `©` | Copyright |
<ide> | ® | `®` | `®` | Registered Trademark |
<ide> | " | `"` | `"` | double quotation mark | | 1 |
Python | Python | fix module order | 7996ef74ddd913256eaf84ba740bc9da6f5e2ef5 | <ide><path>src/transformers/models/bloom/modeling_bloom.py
<ide> def __init__(self, config):
<ide> self.pretraining_tp = config.pretraining_tp
<ide> self.slow_but_exact = config.slow_but_exact
<ide> self.dense_h_to_4h = nn.Linear(hidden_size, 4 * hidden_size)
<add> self.gelu_impl = BloomGelu()
<ide> self.dense_4h_to_h = nn.Linear(4 * hidden_size, hidden_size)
<ide> self.hidden_dropout = config.hidden_dropout
<del> self.gelu_impl = BloomGelu()
<ide>
<ide> def forward(self, hidden_states, residual):
<ide> hidden_states = self.gelu_impl(self.dense_h_to_4h(hidden_states)) | 1 |
Python | Python | use float32 activation in transformer | 94b1efc1bc7b0c0d6572f52e5b023dac7ee827fc | <ide><path>official/nlp/modeling/layers/transformer.py
<ide> def build(self, input_shape):
<ide> kernel_constraint=self._kernel_constraint,
<ide> bias_constraint=self._bias_constraint,
<ide> name="intermediate")
<add> policy = tf.keras.mixed_precision.experimental.global_policy()
<add> if policy.name == "mixed_bfloat16":
<add> # bfloat16 causes BERT with the LAMB optimizer to not converge
<add> # as well, so we use float32.
<add> # TODO(b/154538392): Investigate this.
<add> policy = tf.float32
<ide> self._intermediate_activation_layer = tf.keras.layers.Activation(
<del> self._intermediate_activation)
<add> self._intermediate_activation, dtype=policy)
<ide> self._output_dense = dense_einsum.DenseEinsum(
<ide> output_shape=hidden_size,
<ide> kernel_initializer=self._kernel_initializer, | 1 |
Text | Text | fix duplicate gwt link | c83ad1642bec092367a5d019f79f71b106bbb284 | <ide><path>README.md
<ide> src="https://static.monei.net/monei-logo.svg" height="30" alt="MONEI"></a>
<ide> * @medikoo for [modules-webmake](https://github.com/medikoo/modules-webmake), which is a similar project. webpack was born because I wanted Code Splitting for modules-webmake. Interestingly the [Code Splitting issue is still open](https://github.com/medikoo/modules-webmake/issues/7) (thanks also to @Phoscur for the discussion).
<ide> * @substack for [browserify](http://browserify.org/), which is a similar project and source for many ideas.
<ide> * @jrburke for [require.js](http://requirejs.org/), which is a similar project and source for many ideas.
<del>* @defunctzombie for the [browser-field spec](https://gist.github.com/defunctzombie/4339901), which makes modules available for node.js, browserify and webpack.http://www.gwtproject.org/
<add>* @defunctzombie for the [browser-field spec](https://gist.github.com/defunctzombie/4339901), which makes modules available for node.js, browserify and webpack.
<ide> * Every early webpack user, which contributed to webpack by writing issues or PRs. You influenced the direction...
<ide> * @shama, @jhnns and @sokra for maintaining this project
<ide> * Everyone who has written a loader for webpack. You are the ecosystem... | 1 |
PHP | PHP | fix binary log conversation | 8be4f212b5ad4e0e5e4db2c769b78e967bc257a2 | <ide><path>src/Database/Log/LoggedQuery.php
<ide> protected function interpolate(): string
<ide> }
<ide>
<ide> if (is_string($p)) {
<del> // Likely binary data.
<del> if (!ctype_print($p)) {
<add> // Likely binary UUID.
<add> if (strlen($p) === 16 && !ctype_print($p)) {
<ide> $p = bin2hex($p);
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Log/LoggedQueryTest.php
<ide> public function testBinaryInterpolation()
<ide> $this->assertEquals($expected, (string)$query);
<ide> }
<ide>
<add> /**
<add> * Tests that unknown possible binary data is not replaced to hex.
<add> *
<add> * @return void
<add> */
<add> public function testBinaryInterpolationIgnored()
<add> {
<add> $query = new LoggedQuery();
<add> $query->query = 'SELECT a FROM b where a = :p1';
<add> $query->params = ['p1' => "a\tz"];
<add>
<add> $expected = "duration=0 rows=0 SELECT a FROM b where a = 'a\tz'";
<add> $this->assertEquals($expected, (string)$query);
<add> }
<add>
<add> /**
<add> * @return void
<add> */
<ide> public function testJsonSerialize()
<ide> {
<ide> $query = new LoggedQuery(); | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.