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 |
|---|---|---|---|---|---|
PHP | PHP | fix failing tests in postgres | 552bc0234a703af4799e2a54219afffad982c65b | <ide><path>tests/TestCase/ORM/QueryRegressionTest.php
<ide> public function testComplexNestedTypesInJoinedWhere()
<ide>
<ide> $result = $query->first();
<ide> $this->assertNotEmpty($result);
<del> $this->assertInstanceOf('Cake\I18n\Time', $result->comment->article->author->updated);
<add> $this->assertInstanceOf(FrozenTime::class, $result->comment->article->author->updated);
<ide> }
<ide>
<ide> /**
<ide> public function testComplexTypesInJoinedWhereWithMatching()
<ide>
<ide> $result = $query->first();
<ide> $this->assertNotEmpty($result);
<del> $this->assertInstanceOf(Time::class, $result->_matchingData['Authors']->updated);
<add> $this->assertInstanceOf(FrozenTime::class, $result->_matchingData['Authors']->updated);
<ide> }
<ide>
<ide> /**
<ide> public function testComplexTypesInJoinedWhereWithInnerJoinWith()
<ide>
<ide> $result = $query->first();
<ide> $this->assertNotEmpty($result);
<del> $this->assertInstanceOf('Cake\I18n\Time', $result->updated);
<add> $this->assertInstanceOf(FrozenTime::class, $result->updated);
<ide>
<ide> $query = $table->find()
<ide> ->innerJoinWith('Comments.Articles.Authors')
<ide> public function testComplexTypesInJoinedWhereWithInnerJoinWith()
<ide>
<ide> $result = $query->first();
<ide> $this->assertNotEmpty($result);
<del> $this->assertInstanceOf('Cake\I18n\Time', $result->updated);
<add> $this->assertInstanceOf(FrozenTime::class, $result->updated);
<ide> }
<ide>
<ide> /**
<ide> public function testComplexTypesInJoinedWhereWithLeftJoinWith()
<ide>
<ide> $result = $query->first();
<ide> $this->assertNotEmpty($result);
<del> $this->assertInstanceOf('Cake\I18n\Time', $result->updated);
<add> $this->assertInstanceOf(FrozenTime::class, $result->updated);
<ide>
<ide> $query = $table->find()
<ide> ->leftJoinWith('Comments.Articles.Authors')
<ide> public function testComplexTypesInJoinedWhereWithLeftJoinWith()
<ide>
<ide> $result = $query->first();
<ide> $this->assertNotEmpty($result);
<del> $this->assertInstanceOf('Cake\I18n\Time', $result->updated);
<add> $this->assertInstanceOf(FrozenTime::class, $result->updated);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | remove unnecessary assertions | 9b292272ff3d71a0ebabe46d040346dbd34585db | <ide><path>test/parallel/test-handle-wrap-isrefed.js
<ide> const { internalBinding } = require('internal/test/binding');
<ide> const spawn = require('child_process').spawn;
<ide> const cmd = common.isWindows ? 'rundll32' : 'ls';
<ide> const cp = spawn(cmd);
<del> strictEqual(Object.getPrototypeOf(cp._handle).hasOwnProperty('hasRef'),
<del> true, 'process_wrap: hasRef() missing');
<ide> strictEqual(cp._handle.hasRef(),
<ide> true, 'process_wrap: not initially refed');
<ide> cp.unref();
<ide> const { kStateSymbol } = require('internal/dgram');
<ide> const sock4 = dgram.createSocket('udp4');
<ide> const handle = sock4[kStateSymbol].handle;
<ide>
<del> strictEqual(Object.getPrototypeOf(handle).hasOwnProperty('hasRef'),
<del> true, 'udp_wrap: ipv4: hasRef() missing');
<ide> strictEqual(handle.hasRef(),
<ide> true, 'udp_wrap: ipv4: not initially refed');
<ide> sock4.unref();
<ide> const { kStateSymbol } = require('internal/dgram');
<ide> const sock6 = dgram.createSocket('udp6');
<ide> const handle = sock6[kStateSymbol].handle;
<ide>
<del> strictEqual(Object.getPrototypeOf(handle).hasOwnProperty('hasRef'),
<del> true, 'udp_wrap: ipv6: hasRef() missing');
<ide> strictEqual(handle.hasRef(),
<ide> true, 'udp_wrap: ipv6: not initially refed');
<ide> sock6.unref();
<ide> const { kStateSymbol } = require('internal/dgram');
<ide> {
<ide> const { Pipe, constants: PipeConstants } = internalBinding('pipe_wrap');
<ide> const handle = new Pipe(PipeConstants.SOCKET);
<del> strictEqual(Object.getPrototypeOf(handle).hasOwnProperty('hasRef'),
<del> true, 'pipe_wrap: hasRef() missing');
<ide> strictEqual(handle.hasRef(),
<ide> true, 'pipe_wrap: not initially refed');
<ide> handle.unref();
<ide> const { kStateSymbol } = require('internal/dgram');
<ide> {
<ide> const net = require('net');
<ide> const server = net.createServer(() => {}).listen(0);
<del> strictEqual(Object.getPrototypeOf(server._handle).hasOwnProperty('hasRef'),
<del> true, 'tcp_wrap: hasRef() missing');
<ide> strictEqual(server._handle.hasRef(),
<ide> true, 'tcp_wrap: not initially refed');
<ide> strictEqual(server._unref,
<ide><path>test/pseudo-tty/test-handle-wrap-isrefed-tty.js
<ide> const tty = new ReadStream(0);
<ide> const { internalBinding } = require('internal/test/binding');
<ide> const isTTY = internalBinding('tty_wrap').isTTY;
<ide> strictEqual(isTTY(0), true, 'tty_wrap: stdin is not a TTY');
<del>strictEqual(Object.getPrototypeOf(tty._handle).hasOwnProperty('hasRef'),
<del> true, 'tty_wrap: hasRef() missing');
<ide> strictEqual(tty._handle.hasRef(),
<ide> true, 'tty_wrap: not initially refed');
<ide> tty.unref(); | 2 |
Ruby | Ruby | pass sdk_path in std_cmake_args | 2af64920fac8b892cc55cbfe9f6cd064def5a267 | <ide><path>Library/Homebrew/formula.rb
<ide> def std_cmake_args
<ide> -DCMAKE_BUILD_TYPE=Release
<ide> -DCMAKE_FIND_FRAMEWORK=LAST
<ide> -DCMAKE_VERBOSE_MAKEFILE=ON
<add> -DCMAKE_OSX_SYSROOT=#{MacOS.sdk_path}
<ide> -Wno-dev
<ide> ]
<ide> end | 1 |
Text | Text | add req.body to custom express server example | daa7f821a956e1d0e8cf954d648b768a92e6fcb2 | <ide><path>examples/custom-server-express/README.md
<ide> npm run dev
<ide> yarn
<ide> yarn dev
<ide> ```
<add>
<add>### Populate body property
<add>
<add>Without the use of the body-parser package `req.body` will return undefined. To get express to populate `req.body` you need to install the body parser package and call the package within server.js.
<add>
<add>Install the package:
<add>
<add>```bash
<add>npm install body-parser
<add>```
<add>
<add>Use the package within server.js:
<add>
<add>```bash
<add>const bodyParser = require('body-parser');
<add>
<add>app.prepare().then(() => {
<add> const server = express();
<add> server.use(bodyParser.urlencoded({ extended: true }))
<add> server.use(bodyParser.json())
<add>})
<add>``` | 1 |
Python | Python | use data_validation context manager | cc2f58a1b06773bb8ee6aed5ec05f231737e1777 | <ide><path>spacy/cli/debug_model.py
<ide> from pathlib import Path
<ide> from wasabi import msg
<ide> from thinc.api import require_gpu, fix_random_seed, set_dropout_rate, Adam, Config
<del>from thinc.api import Model, DATA_VALIDATION
<add>from thinc.api import Model, data_validation
<ide> import typer
<ide>
<ide> from ._util import Arg, Opt, debug_cli, show_validation_error, parse_config_overrides
<ide> def debug_model(model: Model, *, print_settings: Optional[Dict[str, Any]] = None
<ide> # STEP 1: Initializing the model and printing again
<ide> Y = _get_output(model.ops.xp)
<ide> _set_output_dim(nO=Y.shape[-1], model=model)
<del> DATA_VALIDATION.set(False) # The output vector might differ from the official type of the output layer
<del> model.initialize(X=_get_docs(), Y=Y)
<del> DATA_VALIDATION.set(True)
<add> # The output vector might differ from the official type of the output layer
<add> with data_validation(False):
<add> model.initialize(X=_get_docs(), Y=Y)
<ide> if print_settings.get("print_after_init"):
<ide> msg.info(f"After initialization:")
<ide> _print_model(model, print_settings) | 1 |
Javascript | Javascript | fix a small lint error in fonts_utils.js | 826e0baf14df507665daff37e5dcce37ffdc69d6 | <ide><path>utils/fonts_utils.js
<ide> function readCharset(aStream, aCharstrings) {
<ide> */
<ide> function readCharstringEncoding(aString) {
<ide> if (!aString)
<del> return "";
<add> return '';
<ide>
<ide> var charstringTokens = [];
<ide> | 1 |
Javascript | Javascript | add another way to detect cmyk images | 8d52a1e92a450f5b43049b3f1527bad8aaf79bfe | <ide><path>src/parser.js
<ide> var Parser = (function parserParser() {
<ide> return new LZWStream(stream, earlyChange);
<ide> } else if (name == 'DCTDecode' || name == 'DCT') {
<ide> var bytes = stream.getBytes(length);
<del> return new JpegStream(bytes, stream.dict);
<add> return new JpegStream(bytes, stream.dict, this.xref);
<ide> } else if (name == 'ASCII85Decode' || name == 'A85') {
<ide> return new Ascii85Stream(stream);
<ide> } else if (name == 'ASCIIHexDecode' || name == 'AHx') {
<ide><path>src/stream.js
<ide> var JpegStream = (function jpegStream() {
<ide> return false;
<ide> }
<ide>
<add> function isCmykAdobe(bytes) {
<add> var maxBytesScanned = Math.max(bytes.length - 16, 1024);
<add> // Looking for APP14, 'Adobe'
<add> for (var i = 0; i < maxBytesScanned; ++i) {
<add> if (bytes[i] == 0xFF && bytes[i + 1] == 0xEE &&
<add> bytes[i + 2] == 0x00 && bytes[i + 3] == 0x0E &&
<add> bytes[i + 4] == 0x41 && bytes[i + 5] == 0x64 &&
<add> bytes[i + 6] == 0x6F && bytes[i + 7] == 0x62 &&
<add> bytes[i + 8] == 0x65 && bytes[i + 9] == 0 &&
<add> bytes[i + 15] == 2 ) {
<add> return true;
<add> }
<add> // scanning until frame tag
<add> if (bytes[i] == 0xFF && bytes[i + 1] == 0xC0)
<add> break;
<add> }
<add> return false;
<add> }
<add>
<ide> function fixAdobeImage(bytes) {
<ide> // Inserting 'EMBED' marker after JPEG signature
<ide> var embedMarker = new Uint8Array([0xFF, 0xEC, 0, 8, 0x45, 0x4D, 0x42, 0x45,
<ide> var JpegStream = (function jpegStream() {
<ide> return newBytes;
<ide> }
<ide>
<del> function constructor(bytes, dict) {
<add> function constructor(bytes, dict, xref) {
<ide> // TODO: per poppler, some images may have 'junk' before that
<ide> // need to be removed
<ide> this.dict = dict;
<del>
<add>
<ide> // Flag indicating wether the image can be natively loaded.
<ide> this.isNative = true;
<ide>
<ide> if (isAdobeImage(bytes)) {
<ide> // when bug 674619 land, let's check if browser can do
<ide> // normal cmyk and then we won't have to the following
<del> var cs = dict.get('ColorSpace');
<add> var cs = xref.fetchIfRef(dict.get('ColorSpace'));
<ide> if (isName(cs) && cs.name === 'DeviceCMYK') {
<add> //if (isCmykAdobe(bytes)) {
<ide> this.isNative = false;
<ide> this.bytes = bytes;
<ide> } else {
<ide> var JpegStream = (function jpegStream() {
<ide> var height = jpegImage.height;
<ide> var dataLength = width * height * 4;
<ide> var data = new Uint8Array(dataLength);
<del> jpegImage.getData(data, width, height);
<add> jpegImage.getData(data, width, height, true);
<ide> this.buffer = data;
<ide> this.bufferLength = data.length;
<ide> };
<ide><path>src/worker_loader.js
<ide> function onMessageLoader(evt) {
<ide> 'parser.js',
<ide> 'pattern.js',
<ide> 'stream.js',
<del> 'worker.js'
<add> 'worker.js',
<add> '../external/jpgjs/jpg.js'
<ide> ];
<ide>
<ide> // Load all the files. | 3 |
Javascript | Javascript | remove side effect from atomwindow constructor | cf3d272e47b7e9cd218a0425646497c30b9a43ed | <ide><path>src/main-process/atom-application.js
<ide> class AtomApplication extends EventEmitter {
<ide> options.window = window
<ide> this.openPaths(options)
<ide> } else {
<del> new AtomWindow(this, this.fileRecoveryService, options)
<add> this.addWindow(new AtomWindow(this, this.fileRecoveryService, options))
<ide> }
<ide> } else {
<ide> this.promptForPathToOpen('all', {window})
<ide> class AtomApplication extends EventEmitter {
<ide> clearWindowState,
<ide> env
<ide> })
<add> this.addWindow(openedWindow)
<ide> openedWindow.focus()
<del> this.windowStack.addWindow(openedWindow)
<ide> }
<ide>
<ide> if (pidToKillWhenClosed != null) {
<ide> class AtomApplication extends EventEmitter {
<ide> windowDimensions,
<ide> env
<ide> })
<del> this.windowStack.addWindow(window)
<add> this.addWindow(window)
<ide> window.on('window:loaded', () => window.sendURIMessage(url))
<add> return window
<ide> }
<ide> }
<ide>
<ide> class AtomApplication extends EventEmitter {
<ide> const packagePath = this.getPackageManager(devMode).resolvePackagePath(packageName)
<ide> const windowInitializationScript = path.resolve(packagePath, packageUrlMain)
<ide> const windowDimensions = this.getDimensionsForNewWindow()
<del> return new AtomWindow(this, this.fileRecoveryService, {
<add> const window = new AtomWindow(this, this.fileRecoveryService, {
<ide> windowInitializationScript,
<ide> resourcePath: this.resourcePath,
<ide> devMode,
<ide> class AtomApplication extends EventEmitter {
<ide> windowDimensions,
<ide> env
<ide> })
<add> this.addWindow(window)
<add> return window
<ide> }
<ide>
<ide> getPackageManager (devMode) {
<ide> class AtomApplication extends EventEmitter {
<ide> if (safeMode == null) {
<ide> safeMode = false
<ide> }
<del> return new AtomWindow(this, this.fileRecoveryService, {
<add> const window = new AtomWindow(this, this.fileRecoveryService, {
<ide> windowInitializationScript,
<ide> resourcePath,
<ide> headless,
<ide> class AtomApplication extends EventEmitter {
<ide> safeMode,
<ide> env
<ide> })
<add> this.addWindow(window)
<add> return window
<ide> }
<ide>
<ide> runBenchmarks ({headless, test, resourcePath, executedFrom, pathsToOpen, env}) {
<ide> class AtomApplication extends EventEmitter {
<ide> const devMode = true
<ide> const isSpec = true
<ide> const safeMode = false
<del> return new AtomWindow(this, this.fileRecoveryService, {
<add> const window = new AtomWindow(this, this.fileRecoveryService, {
<ide> windowInitializationScript,
<ide> resourcePath,
<ide> headless,
<ide> class AtomApplication extends EventEmitter {
<ide> safeMode,
<ide> env
<ide> })
<add> this.addWindow(window)
<add> return window
<ide> }
<ide>
<ide> resolveTestRunnerPath (testPath) {
<ide><path>src/main-process/atom-window.js
<ide> class AtomWindow extends EventEmitter {
<ide>
<ide> const hasPathToOpen = !(locationsToOpen.length === 1 && locationsToOpen[0].pathToOpen == null)
<ide> if (hasPathToOpen && !this.isSpecWindow()) this.openLocations(locationsToOpen)
<del> this.atomApplication.addWindow(this)
<ide> }
<ide>
<ide> hasProjectPath () { | 2 |
Ruby | Ruby | skip the test if test data download fails | c245ca30f248367e07d5d831195b12c93a1e3137 | <ide><path>activesupport/test/multibyte_conformance_test.rb
<ide> class MultibyteConformanceTest < ActiveSupport::TestCase
<ide> include MultibyteTestHelpers
<ide>
<del> UNIDATA_URL = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::Unicode::UNICODE_VERSION}/ucd"
<ide> UNIDATA_FILE = '/NormalizationTest.txt'
<del> CACHE_DIR = "#{Dir.tmpdir}/cache/unicode_conformance"
<ide> FileUtils.mkdir_p(CACHE_DIR)
<ide> RUN_P = begin
<ide> Downloader.download(UNIDATA_URL + UNIDATA_FILE, CACHE_DIR + UNIDATA_FILE)
<ide><path>activesupport/test/multibyte_grapheme_break_conformance_test.rb
<ide> class MultibyteGraphemeBreakConformanceTest < ActiveSupport::TestCase
<ide> include MultibyteTestHelpers
<ide>
<del> TEST_DATA_URL = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::Unicode::UNICODE_VERSION}/ucd/auxiliary"
<del> TEST_DATA_FILE = '/GraphemeBreakTest.txt'
<del> CACHE_DIR = "#{Dir.tmpdir}/cache/unicode_conformance"
<add> UNIDATA_FILE = '/auxiliary/GraphemeBreakTest.txt'
<add> RUN_P = begin
<add> Downloader.download(UNIDATA_URL + UNIDATA_FILE, CACHE_DIR + UNIDATA_FILE)
<add> rescue
<add> end
<ide>
<ide> def setup
<del> FileUtils.mkdir_p(CACHE_DIR)
<del> Downloader.download(TEST_DATA_URL + TEST_DATA_FILE, CACHE_DIR + TEST_DATA_FILE)
<add> skip "Unable to download test data" unless RUN_P
<ide> end
<ide>
<ide> def test_breaks
<ide> def test_breaks
<ide> def each_line_of_break_tests(&block)
<ide> lines = 0
<ide> max_test_lines = 0 # Don't limit below 21, because that's the header of the testfile
<del> File.open(File.join(CACHE_DIR, TEST_DATA_FILE), 'r') do | f |
<add> File.open(File.join(CACHE_DIR, UNIDATA_FILE), 'r') do | f |
<ide> until f.eof? || (max_test_lines > 21 and lines > max_test_lines)
<ide> lines += 1
<ide> line = f.gets.chomp!
<ide><path>activesupport/test/multibyte_normalization_conformance_test.rb
<ide> class MultibyteNormalizationConformanceTest < ActiveSupport::TestCase
<ide> include MultibyteTestHelpers
<ide>
<del> UNIDATA_URL = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::Unicode::UNICODE_VERSION}/ucd"
<ide> UNIDATA_FILE = '/NormalizationTest.txt'
<del> CACHE_DIR = "#{Dir.tmpdir}/cache/unicode_conformance"
<add> RUN_P = begin
<add> Downloader.download(UNIDATA_URL + UNIDATA_FILE, CACHE_DIR + UNIDATA_FILE)
<add> rescue
<add> end
<ide>
<ide> def setup
<del> FileUtils.mkdir_p(CACHE_DIR)
<del> Downloader.download(UNIDATA_URL + UNIDATA_FILE, CACHE_DIR + UNIDATA_FILE)
<ide> @proxy = ActiveSupport::Multibyte::Chars
<add> skip "Unable to download test data" unless RUN_P
<ide> end
<ide>
<ide> def test_normalizations_C
<ide><path>activesupport/test/multibyte_test_helpers.rb
<ide> def self.download(from, to)
<ide> end
<ide> end
<ide>
<add> UNIDATA_URL = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::Unicode::UNICODE_VERSION}/ucd"
<add> CACHE_DIR = "#{Dir.tmpdir}/cache/unicode_conformance"
<add> FileUtils.mkdir_p(CACHE_DIR)
<add>
<ide> UNICODE_STRING = 'こにちわ'.freeze
<ide> ASCII_STRING = 'ohayo'.freeze
<ide> BYTE_STRING = "\270\236\010\210\245".force_encoding("ASCII-8BIT").freeze | 4 |
Mixed | Ruby | add migrations_paths option to model generator | 77aaeced89cb84404cf69f8b23834520de3214a9 | <ide><path>activerecord/lib/rails/generators/active_record/model/model_generator.rb
<ide> class ModelGenerator < Base # :nodoc:
<ide> class_option :parent, type: :string, desc: "The parent class for the generated model"
<ide> class_option :indexes, type: :boolean, default: true, desc: "Add indexes for references and belongs_to columns"
<ide> class_option :primary_key_type, type: :string, desc: "The type for primary key"
<add> class_option :migrations_paths, type: :string, desc: "The migration path for your generated migrations. If this is not set it will default to db/migrate"
<ide>
<ide> # creates the migration file for the model.
<ide> def create_migration_file
<ide><path>railties/CHANGELOG.md
<add>* Adds an option to the model generator to allow setting the
<add> migrations paths for that migration. This is useful for
<add> applications that use multiple databases and put migrations
<add> per database in their own directories.
<add>
<add> ```
<add> bin/rails g model Room capacity:integer --migrations-paths=db/kingston_migrate
<add> invoke active_record
<add> create db/kingston_migrate/20180830151055_create_rooms.rb
<add> ```
<add>
<add> Because rails scaffolding uses the model generator, you can
<add> also specify migrations paths with the scaffold generator.
<add>
<add> *Gannon McGibbon*
<add>
<ide> * Raise an error when "recyclable cache keys" are being used by a cache store
<ide> that does not explicitly support it. Custom cache keys that do support this feature
<ide> can bypass this error by implementing the `supports_cache_versioning?` method on their
<ide><path>railties/test/generators/model_generator_test.rb
<ide> def test_add_uuid_to_create_table_migration
<ide> end
<ide> end
<ide>
<add> def test_migrations_paths_puts_migrations_in_that_folder
<add> run_generator ["account", "--migrations_paths=db/test_migrate"]
<add> assert_migration "db/test_migrate/create_accounts.rb" do |content|
<add> assert_method :change, content do |change|
<add> assert_match(/create_table :accounts/, change)
<add> end
<add> end
<add> end
<add>
<ide> def test_required_belongs_to_adds_required_association
<ide> run_generator ["account", "supplier:references{required}"]
<ide>
<ide><path>railties/test/generators/scaffold_generator_test.rb
<ide> def test_scaffold_generator_belongs_to
<ide> end
<ide> end
<ide>
<add> def test_scaffold_generator_migrations_paths
<add> run_generator ["posts", "--migrations-paths=db/kingston_migrate"]
<add>
<add> assert_migration "db/kingston_migrate/create_posts.rb"
<add> end
<add>
<ide> def test_scaffold_generator_password_digest
<ide> run_generator ["user", "name", "password:digest"]
<ide> | 4 |
Go | Go | add validation for ref | a588898f99d697e5ff481ecb3b273f45410f10e6 | <ide><path>builder/remotecontext/git/gitutils.go
<ide> func parseRemoteURL(remoteURL string) (gitRepo, error) {
<ide> u.Fragment = ""
<ide> repo.remote = u.String()
<ide> }
<add>
<add> if strings.HasPrefix(repo.ref, "-") {
<add> return gitRepo{}, errors.Errorf("invalid refspec: %s", repo.ref)
<add> }
<add>
<ide> return repo, nil
<ide> }
<ide>
<ide> func fetchArgs(remoteURL string, ref string) []string {
<ide> args = append(args, "--depth", "1")
<ide> }
<ide>
<del> return append(args, "origin", ref)
<add> return append(args, "origin", "--", ref)
<ide> }
<ide>
<ide> // Check if a given git URL supports a shallow git clone,
<ide><path>builder/remotecontext/git/gitutils_test.go
<ide> func TestCloneArgsSmartHttp(t *testing.T) {
<ide> })
<ide>
<ide> args := fetchArgs(serverURL.String(), "master")
<del> exp := []string{"fetch", "--depth", "1", "origin", "master"}
<add> exp := []string{"fetch", "--depth", "1", "origin", "--", "master"}
<ide> assert.Check(t, is.DeepEqual(exp, args))
<ide> }
<ide>
<ide> func TestCloneArgsDumbHttp(t *testing.T) {
<ide> })
<ide>
<ide> args := fetchArgs(serverURL.String(), "master")
<del> exp := []string{"fetch", "origin", "master"}
<add> exp := []string{"fetch", "origin", "--", "master"}
<ide> assert.Check(t, is.DeepEqual(exp, args))
<ide> }
<ide>
<ide> func TestCloneArgsGit(t *testing.T) {
<ide> args := fetchArgs("git://github.com/docker/docker", "master")
<del> exp := []string{"fetch", "--depth", "1", "origin", "master"}
<add> exp := []string{"fetch", "--depth", "1", "origin", "--", "master"}
<ide> assert.Check(t, is.DeepEqual(exp, args))
<ide> }
<ide>
<ide> func TestValidGitTransport(t *testing.T) {
<ide> }
<ide> }
<ide> }
<add>
<add>func TestGitInvalidRef(t *testing.T) {
<add> gitUrls := []string{
<add> "git://github.com/moby/moby#--foo bar",
<add> "git@github.com/moby/moby#--upload-pack=sleep;:",
<add> "git@g.com:a/b.git#-B",
<add> "git@g.com:a/b.git#with space",
<add> }
<add>
<add> for _, url := range gitUrls {
<add> _, err := Clone(url)
<add> assert.Assert(t, err != nil)
<add> assert.Check(t, is.Contains(strings.ToLower(err.Error()), "invalid refspec"))
<add> }
<add>} | 2 |
Go | Go | fix alphabetisation of possible names | 1db286c5e855a91df446a76c6d79122dad498d8e | <ide><path>pkg/namesgenerator/names-generator.go
<ide> var (
<ide> "hungry",
<ide> "infallible",
<ide> "inspiring",
<del> "interesting",
<ide> "intelligent",
<add> "interesting",
<ide> "jolly",
<ide> "jovial",
<ide> "keen", | 1 |
Javascript | Javascript | enable createroot api in www | dc48cc38ea3c7bfa9c90ec00492cb7d13d996ab4 | <ide><path>scripts/rollup/shims/rollup/ReactFeatureFlags-www.js
<ide> export const {
<ide> // The rest of the flags are static for better dead code elimination.
<ide> export const enableAsyncSubtreeAPI = true;
<ide> export const enableReactFragment = false;
<del>export const enableCreateRoot = false;
<add>export const enableCreateRoot = true;
<ide>
<ide> // The www bundles only use the mutating reconciler.
<ide> export const enableMutatingReconciler = true; | 1 |
PHP | PHP | remove singularization on schema class names | 7718d473c4e17aef89129c90d96c7eca60799d09 | <ide><path>lib/Cake/Console/Command/SchemaShell.php
<ide> public function startup() {
<ide> $name = $plugin;
<ide> }
<ide> }
<del> $name = Inflector::classify($name);
<add> $name = Inflector::camelize($name);
<ide> $this->Schema = new CakeSchema(compact('name', 'path', 'file', 'connection', 'plugin'));
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Console/Command/SchemaShellTest.php
<ide> public function testName() {
<ide> $this->Shell->params = array(
<ide> 'plugin' => 'TestPlugin',
<ide> 'connection' => 'test',
<del> 'name' => 'custom_name',
<add> 'name' => 'custom_names',
<ide> 'force' => false,
<ide> 'overwrite' => true,
<ide> );
<ide> $this->Shell->startup();
<del> if (file_exists($this->Shell->Schema->path . DS . 'custom_name.php')) {
<del> unlink($this->Shell->Schema->path . DS . 'custom_name.php');
<add> if (file_exists($this->Shell->Schema->path . DS . 'custom_names.php')) {
<add> unlink($this->Shell->Schema->path . DS . 'custom_names.php');
<ide> }
<ide> $this->Shell->generate();
<ide>
<del> $contents = file_get_contents($this->Shell->Schema->path . DS . 'custom_name.php');
<del> $this->assertRegExp('/class CustomNameSchema/', $contents);
<del> unlink($this->Shell->Schema->path . DS . 'custom_name.php');
<add> $contents = file_get_contents($this->Shell->Schema->path . DS . 'custom_names.php');
<add> $this->assertRegExp('/class CustomNamesSchema/', $contents);
<add> unlink($this->Shell->Schema->path . DS . 'custom_names.php');
<ide> CakePlugin::unload();
<ide> }
<ide> | 2 |
Javascript | Javascript | favor strict equality in pummel net tests | 8ff3d61d8ba90fde01827643db3d87ee97f502e6 | <ide><path>test/pummel/test-net-connect-econnrefused.js
<ide> function pummel() {
<ide> net.createConnection(common.PORT).on('error', function(err) {
<ide> assert.equal(err.code, 'ECONNREFUSED');
<ide> if (--pending > 0) return;
<del> if (rounds == ROUNDS) return check();
<add> if (rounds === ROUNDS) return check();
<ide> rounds++;
<ide> pummel();
<ide> });
<ide><path>test/pummel/test-net-connect-memleak.js
<ide> var before = 0;
<ide> before = process.memoryUsage().rss;
<ide>
<ide> net.createConnection(common.PORT, '127.0.0.1', function() {
<del> assert(junk.length != 0); // keep reference alive
<add> assert.notStrictEqual(junk.length, 0); // keep reference alive
<ide> setTimeout(done, 10);
<ide> global.gc();
<ide> });
<ide><path>test/pummel/test-net-many-clients.js
<ide> server.listen(common.PORT, function() {
<ide> var finished_clients = 0;
<ide> for (var i = 0; i < concurrency; i++) {
<ide> runClient(function() {
<del> if (++finished_clients == concurrency) server.close();
<add> if (++finished_clients === concurrency) server.close();
<ide> });
<ide> }
<ide> });
<ide><path>test/pummel/test-net-timeout.js
<ide> echo_server.listen(common.PORT, function() {
<ide> client.write('hello\r\n');
<ide> }, 500);
<ide>
<del> if (exchanges == 5) {
<add> if (exchanges === 5) {
<ide> console.log('wait for timeout - should come in ' + timeout + ' ms');
<ide> starttime = new Date();
<ide> console.dir(starttime);
<ide><path>test/pummel/test-net-timeout2.js
<ide> var server = net.createServer(function(socket) {
<ide> var interval = setInterval(function() {
<ide> counter++;
<ide>
<del> if (counter == seconds) {
<add> if (counter === seconds) {
<ide> clearInterval(interval);
<ide> server.close();
<ide> socket.destroy(); | 5 |
Text | Text | add the text article infinite loop to my article | 3f6a61fbcad1da241268b9137ae67bd5d2ebeea1 | <ide><path>guide/english/java/loops/infinite-loops/index.md
<ide> The loop above runs infinitely because every time i approaches 49, it is set to
<ide>
<ide> But a program stuck in such a loop will keep using computer resources indefinitely. This is undesirable, and is a type of 'run-time error'.
<ide>
<del>To prevent the error, programmers use a break statement to break out of the loop. The break executes only under a particular condition. Use of a selection statement like if-else ensures the same.
<add>
<add>#### Infinite Loop by opposite iteration
<add>Another example of an Infinite Loop can be seen below:
<add>```java
<add>for(int i=0;i<=10;i--)
<add> System.out.println(i);
<add>```
<add>
<add>In the above example, the initial value of `i` is 0. Since value of `i` is less than equal to 10, we decrement the value of `i` by 1, so `i` will now be -1. Hence, the loop will be infinite.
<add>
<add>Similarly, an example of an infinite while loop example can be seen below:
<add>
<add>```java
<add>int i=1;
<add>while(i>=1)
<add>{
<add> System.out.println(i);
<add> i+=1;
<add>}
<add>```
<add>
<add>Here, `i` will always be greater than 1, so the program will be in an infinite loop.
<add>
<add>To prevent the error, programmers use a `break` statement to break out of the loop. The `break` executes only under a particular condition. Use of a selection statement like `if-else` ensures the same.
<ide>
<ide> ```java
<ide> while (true)
<ide> while (true)
<ide> The main advantage of using an infinite loop over a regular loop is readability.
<ide>
<ide> Sometimes, the body of a loop is easier to understand if the loop ends in the middle, and not at the end/beginning. In such a situation, an infinite loop will be a better choice.
<del> | 1 |
Python | Python | add insert_args for support transfer replace | 636625fdb99e6b7beb1375c5df52b06c09e6bafb | <ide><path>airflow/operators/generic_transfer.py
<ide> class GenericTransfer(BaseOperator):
<ide> :param preoperator: sql statement or list of statements to be
<ide> executed prior to loading the data. (templated)
<ide> :type preoperator: str or list[str]
<add> :param insert_args: extra params for `insert_rows` method.
<add> :type insert_args: dict
<ide> """
<ide>
<ide> template_fields = ('sql', 'destination_table', 'preoperator')
<ide> def __init__(
<ide> source_conn_id: str,
<ide> destination_conn_id: str,
<ide> preoperator: Optional[Union[str, List[str]]] = None,
<add> insert_args: Optional[dict] = None,
<ide> **kwargs,
<ide> ) -> None:
<ide> super().__init__(**kwargs)
<ide> def __init__(
<ide> self.source_conn_id = source_conn_id
<ide> self.destination_conn_id = destination_conn_id
<ide> self.preoperator = preoperator
<add> self.insert_args = insert_args or {}
<ide>
<ide> def execute(self, context):
<ide> source_hook = BaseHook.get_hook(self.source_conn_id)
<ide> def execute(self, context):
<ide> destination_hook.run(self.preoperator)
<ide>
<ide> self.log.info("Inserting rows into %s", self.destination_conn_id)
<del> destination_hook.insert_rows(table=self.destination_table, rows=results)
<add> destination_hook.insert_rows(table=self.destination_table, rows=results, **self.insert_args)
<ide><path>tests/operators/test_generic_transfer.py
<ide>
<ide> import unittest
<ide> from contextlib import closing
<add>from unittest import mock
<ide>
<ide> import pytest
<ide> from parameterized import parameterized
<ide> def test_mysql_to_mysql(self, client):
<ide> )
<ide> op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
<ide>
<add> @mock.patch('airflow.hooks.dbapi.DbApiHook.insert_rows')
<add> def test_mysql_to_mysql_replace(self, mock_insert):
<add> sql = "SELECT * FROM connection LIMIT 10;"
<add> op = GenericTransfer(
<add> task_id='test_m2m',
<add> preoperator=[
<add> "DROP TABLE IF EXISTS test_mysql_to_mysql",
<add> "CREATE TABLE IF NOT EXISTS test_mysql_to_mysql LIKE connection",
<add> ],
<add> source_conn_id='airflow_db',
<add> destination_conn_id='airflow_db',
<add> destination_table="test_mysql_to_mysql",
<add> sql=sql,
<add> dag=self.dag,
<add> insert_args={'replace': True},
<add> )
<add> op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
<add> assert mock_insert.called
<add> _, kwargs = mock_insert.call_args
<add> assert 'replace' in kwargs
<add>
<ide>
<ide> @pytest.mark.backend("postgres")
<ide> class TestPostgres(unittest.TestCase):
<ide> def test_postgres_to_postgres(self):
<ide> dag=self.dag,
<ide> )
<ide> op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
<add>
<add> @mock.patch('airflow.hooks.dbapi.DbApiHook.insert_rows')
<add> def test_postgres_to_postgres_replace(self, mock_insert):
<add> sql = "SELECT id, conn_id, conn_type FROM connection LIMIT 10;"
<add> op = GenericTransfer(
<add> task_id='test_p2p',
<add> preoperator=[
<add> "DROP TABLE IF EXISTS test_postgres_to_postgres",
<add> "CREATE TABLE IF NOT EXISTS test_postgres_to_postgres (LIKE connection INCLUDING INDEXES)",
<add> ],
<add> source_conn_id='postgres_default',
<add> destination_conn_id='postgres_default',
<add> destination_table="test_postgres_to_postgres",
<add> sql=sql,
<add> dag=self.dag,
<add> insert_args={
<add> 'replace': True,
<add> 'target_fields': ('id', 'conn_id', 'conn_type'),
<add> 'replace_index': 'id',
<add> },
<add> )
<add> op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
<add> assert mock_insert.called
<add> _, kwargs = mock_insert.call_args
<add> assert 'replace' in kwargs | 2 |
Text | Text | add v3.22.0-beta.4 to changelog | 984c9adaa2e863fd2f8dd919600f364e84c6a9a4 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.22.0-beta.4 (September 30, 2020)
<add>
<add>- [#19138](https://github.com/emberjs/ember.js/pull/19138) [BUGFIX] Fix tag cycles in query parameters
<add>- [#19094](https://github.com/emberjs/ember.js/pull/19094) [BUGFIX] Fix RouterService#isActive() to work with tracking
<add>- [#19163](https://github.com/emberjs/ember.js/pull/19163) [BUGFIX] Use args proxy for modifier managers.
<add>- [#19164](https://github.com/emberjs/ember.js/pull/19164) [BUGFIX] Entangles custom EmberArray implementations when accessed with `Ember.get`
<add>- [#19170](https://github.com/emberjs/ember.js/pull/19170) [BUGFIX] Make modifier manager 3.22 accept the resolved value directly.
<add>
<ide> ### v3.22.0-beta.3 (September 09, 2020)
<ide>
<ide> - [#19124](https://github.com/emberjs/ember.js/pull/19124) Fix rendering engine usage within a `fastboot` sandbox | 1 |
Javascript | Javascript | add ref comment to test-regress-gh-814 | 6ea3bf93a4c06c6086b8546e88a4ae5a3bba5596 | <ide><path>test/pummel/test-regress-GH-814.js
<ide> // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<add>// Refs: https://github.com/nodejs/node-v0.x-archive/issues/814
<add>
<ide> 'use strict';
<ide> // Flags: --expose_gc
<ide> | 1 |
Ruby | Ruby | add mdfind method to macos module | 8f6ee310046589680962805f58bcc07b0a064095 | <ide><path>Library/Homebrew/macos.rb
<ide> module MacOS extend self
<add>
<add> MDITEM_BUNDLE_ID_KEY = "kMDItemCFBundleIdentifier"
<add> XCODE_4_BUNDLE_ID = "com.apple.dt.Xcode"
<add> XCODE_3_BUNDLE_ID = "com.apple.Xcode"
<add> CLT_STANDALONE_PKG_ID = "com.apple.pkg.DeveloperToolsCLILeo"
<add> CLT_FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI"
<add>
<ide> def version
<ide> MACOS_VERSION
<ide> end
<ide> def clt_version
<ide> # Note, that different ways to install the CLTs lead to different
<ide> # version numbers.
<ide> @clt_version ||= begin
<del> # CLT installed via stand-alone website download
<del> clt_pkginfo_stand_alone = `pkgutil --pkg-info com.apple.pkg.DeveloperToolsCLILeo 2>/dev/null`.strip
<del> # CLT installed via preferences from within Xcode
<del> clt_pkginfo_from_xcode = `pkgutil --pkg-info com.apple.pkg.DeveloperToolsCLI 2>/dev/null`.strip
<del> if not clt_pkginfo_stand_alone.empty?
<del> clt_pkginfo_stand_alone =~ /version: (.*)$/
<add> standalone = pkgutil_info(CLT_STANDALONE_PKG_ID)
<add> from_xcode = pkgutil_info(CLT_FROM_XCODE_PKG_ID)
<add>
<add> if not standalone.empty?
<add> standalone =~ /version: (.*)$/
<ide> $1
<del> elsif not clt_pkginfo_from_xcode.empty?
<del> clt_pkginfo_from_xcode =~ /version: (.*)$/
<add> elsif not from_xcode.empty?
<add> from_xcode =~ /version: (.*)$/
<ide> $1
<ide> else
<ide> # We return "" instead of nil because we want clt_installed? to be true on older Macs.
<ide> def xcode_prefix
<ide> # Ask Spotlight where Xcode is. If the user didn't install the
<ide> # helper tools and installed Xcode in a non-conventional place, this
<ide> # is our only option. See: http://superuser.com/questions/390757
<del> path = `mdfind "kMDItemCFBundleIdentifier == 'com.apple.dt.Xcode'"`.strip
<del> if path.empty?
<del> # Xcode 3 had a different identifier
<del> path = `mdfind "kMDItemCFBundleIdentifier == 'com.apple.Xcode'"`.strip
<del> end
<del> path = "#{path}/Contents/Developer"
<del> if !path.empty? and File.executable? "#{path}/usr/bin/make"
<del> Pathname.new path
<del> else
<del> nil
<add> path = app_with_bundle_id(XCODE_4_BUNDLE_ID) or app_with_bundle_id(XCODE_3_BUNDLE_ID)
<add>
<add> unless path.nil?
<add> path += "Contents/Developer"
<add> path if File.executable? "#{path}/usr/bin/make"
<ide> end
<ide> end
<ide> end
<ide> end
<ide>
<ide> def xcode_installed?
<ide> # Telling us whether the Xcode.app is installed or not.
<del> @xcode_installed ||= begin
<del> if File.directory? '/Applications/Xcode.app'
<del> true
<del> elsif File.directory? '/Developer/Applications/Xcode.app' # old style
<del> true
<del> elsif not `mdfind "kMDItemCFBundleIdentifier == 'com.apple.dt.Xcode'"`.strip.empty?
<del> # Xcode 4
<del> true
<del> elsif not `mdfind "kMDItemCFBundleIdentifier == 'com.apple.Xcode'"`.strip.empty?
<del> # Xcode 3
<del> true
<del> else
<del> false
<del> end
<del> end
<add> @xcode_installed ||= File.directory?('/Applications/Xcode.app') ||
<add> File.directory?('/Developer/Applications/Xcode.app') ||
<add> app_with_bundle_id(XCODE_4_BUNDLE_ID) ||
<add> app_with_bundle_id(XCODE_3_BUNDLE_ID) ||
<add> false
<ide> end
<ide>
<del> def xcode_version
<add> def xcode_version
<ide> # may return a version string
<ide> # that is guessed based on the compiler, so do not
<ide> # use it in order to check if Xcode is installed.
<ide> def compilers_standard?
<ide>
<ide> StandardCompilers[xcode].all? {|k,v| MacOS.send(k) == v}
<ide> end
<add>
<add> def app_with_bundle_id id
<add> mdfind(MDITEM_BUNDLE_ID_KEY, id)
<add> end
<add>
<add> private
<add>
<add> def mdfind attribute, id
<add> path = `mdfind "#{attribute} == '#{id}'"`.strip
<add> Pathname.new(path) unless path.empty?
<add> end
<add>
<add> def pkgutil_info id
<add> `pkgutil --pkg-info #{id} 2>/dev/null`.strip
<add> end
<ide> end | 1 |
PHP | PHP | cosolidate doc block headers | c364e5eb61dc2ccd6afeef17fb16ad0cec0b84dd | <ide><path>src/Collection/CollectionInterface.php
<ide> public function each(callable $c);
<ide> * in the current iteration, the key of the element and this collection as
<ide> * arguments, in that order.
<ide> *
<del> * ##Example:
<add> * ## Example:
<ide> *
<ide> * Filtering odd numbers in an array, at the end only the value 2 will
<ide> * be present in the resulting collection:
<ide> public function filter(callable $c = null);
<ide> * in the current iteration, the key of the element and this collection as
<ide> * arguments, in that order.
<ide> *
<del> * ##Example:
<add> * ## Example:
<ide> *
<ide> * Filtering even numbers in an array, at the end only values 1 and 3 will
<ide> * be present in the resulting collection:
<ide> public function contains($value);
<ide> * in the current iteration, the key of the element and this collection as
<ide> * arguments, in that order.
<ide> *
<del> * ##Example:
<add> * ## Example:
<ide> *
<ide> * Getting a collection of booleans where true indicates if a person is female:
<ide> *
<ide><path>src/Collection/Iterator/TreeIterator.php
<ide> public function __construct(RecursiveIterator $items, $mode = RecursiveIteratorI
<ide> * the current element as first parameter, the current iteration key as second
<ide> * parameter, and the iterator instance as third argument.
<ide> *
<del> * ##Example
<add> * ## Example
<ide> *
<ide> * {{{
<ide> * $printer = (new Collection($treeStructure))->listNested()->printer('name');
<ide><path>src/Database/Query.php
<ide> public function select($fields = [], $overwrite = false) {
<ide> * or set of fields, you may pass an array of fields to filter on. Beware that
<ide> * this option might not be fully supported in all database systems.
<ide> *
<del> * ##Examples:
<add> * ## Examples:
<ide> *
<ide> * {{{
<ide> * // Filters products with the same name and city
<ide> public function modifier($modifiers, $overwrite = false) {
<ide> *
<ide> * This method can be used for select, update and delete statements.
<ide> *
<del> * ##Examples:
<add> * ## Examples:
<ide> *
<ide> * {{{
<ide> * $query->from(['p' => 'posts']); // Produces FROM posts p
<ide> public function where($conditions = null, $types = [], $overwrite = false) {
<ide> * that each array entry will be joined to the other using the AND operator, unless
<ide> * you nest the conditions in the array using other operator.
<ide> *
<del> * ##Examples:
<add> * ## Examples:
<ide> *
<ide> * {{{
<ide> * $query->where(['title' => 'Hello World')->andWhere(['author_id' => 1]);
<ide> public function andWhere($conditions, $types = []) {
<ide> * that each array entry will be joined to the other using the OR operator, unless
<ide> * you nest the conditions in the array using other operator.
<ide> *
<del> * ##Examples:
<add> * ## Examples:
<ide> *
<ide> * {{{
<ide> * $query->where(['title' => 'Hello World')->orWhere(['title' => 'Foo']);
<ide> public function orWhere($conditions, $types = []) {
<ide> * By default this function will append any passed argument to the list of fields
<ide> * to be selected, unless the second argument is set to true.
<ide> *
<del> * ##Examples:
<add> * ## Examples:
<ide> *
<ide> * {{{
<ide> * $query->order(['title' => 'DESC', 'author_id' => 'ASC']);
<ide> public function order($fields, $overwrite = false) {
<ide> * By default this function will append any passed argument to the list of fields
<ide> * to be grouped, unless the second argument is set to true.
<ide> *
<del> * ##Examples:
<add> * ## Examples:
<ide> *
<ide> * {{{
<ide> * // Produces GROUP BY id, title | 3 |
Ruby | Ruby | add nodes for boolean constants | 11f929b5c485adab60ea2d8b515ef2abcf5400f4 | <ide><path>lib/arel/factory_methods.rb
<ide> module Arel
<ide> ###
<ide> # Methods for creating various nodes
<ide> module FactoryMethods
<add> def create_true
<add> Arel::Nodes::True.new
<add> end
<add>
<add> def create_false
<add> Arel::Nodes::False.new
<add> end
<add>
<ide> def create_table_alias relation, name
<ide> Nodes::TableAlias.new(relation, name)
<ide> end
<ide><path>lib/arel/nodes.rb
<ide> # terminal
<ide>
<ide> require 'arel/nodes/terminal'
<add>require 'arel/nodes/true'
<add>require 'arel/nodes/false'
<ide>
<ide> # unary
<ide> require 'arel/nodes/unary'
<ide><path>lib/arel/nodes/false.rb
<add>module Arel
<add> module Nodes
<add> class False < Arel::Nodes::Node
<add> def not
<add> True.new
<add> end
<add>
<add> def or right
<add> right
<add> end
<add>
<add> def and right
<add> self
<add> end
<add> end
<add> end
<add>end
<ide><path>lib/arel/nodes/true.rb
<add>module Arel
<add> module Nodes
<add> class True < Arel::Nodes::Node
<add> def not
<add> False.new
<add> end
<add>
<add> def or right
<add> self
<add> end
<add>
<add> def and right
<add> right
<add> end
<add> end
<add> end
<add>end
<ide><path>lib/arel/predications.rb
<ide> module Arel
<ide> module Predications
<del>
<ide> def not_eq other
<ide> Nodes::NotEqual.new self, other
<ide> end
<ide><path>lib/arel/visitors/to_sql.rb
<ide> def visit_Arel_Nodes_Exists o
<ide> o.alias ? " AS #{visit o.alias}" : ''}"
<ide> end
<ide>
<add> def visit_Arel_Nodes_True o
<add> "TRUE"
<add> end
<add>
<add> def visit_Arel_Nodes_False o
<add> "FALSE"
<add> end
<add>
<ide> def table_exists? name
<ide> @pool.table_exists? name
<ide> end
<ide><path>test/test_factory_methods.rb
<ide> def test_create_on
<ide> assert_equal :one, on.expr
<ide> end
<ide>
<add> def test_create_true
<add> true_node = @factory.create_true
<add> assert_instance_of Nodes::True, true_node
<add> end
<add>
<add> def test_create_false
<add> false_node = @factory.create_false
<add> assert_instance_of Nodes::False, false_node
<add> end
<add>
<ide> def test_lower
<ide> lower = @factory.lower :one
<ide> assert_instance_of Nodes::NamedFunction, lower
<ide><path>test/visitors/test_to_sql.rb
<ide> def quote value, column = nil
<ide> end
<ide> end
<ide>
<add> describe 'Constants' do
<add> it "should handle true" do
<add> test = Table.new(:users).create_true
<add> @visitor.accept(test).must_be_like %{
<add> TRUE
<add> }
<add> end
<add>
<add> it "should handle false" do
<add> test = Table.new(:users).create_false
<add> @visitor.accept(test).must_be_like %{
<add> FALSE
<add> }
<add> end
<add> end
<add>
<ide> describe 'TableAlias' do
<ide> it "should use the underlying table for checking columns" do
<ide> test = Table.new(:users).alias('zomgusers')[:id].eq '3' | 8 |
Java | Java | add code examples to and polish @bean javadoc | 6b4ef0237c147a3fe02b446bdc831a228c5a8da7 | <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/Bean.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2011 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> * Indicates that a method produces a bean to be managed by the Spring container. The
<ide> * names and semantics of the attributes to this annotation are intentionally similar
<del> * to those of the {@code <bean/>} element in the Spring XML schema.
<del> *
<del> * <p>Note that the {@code @Bean} annotation does not provide attributes for scope,
<del> * primary or lazy. Rather, it should be used in conjunction with {@link Scope @Scope},
<del> * {@link Primary @Primary}, and {@link Lazy @Lazy} annotations to achieve
<del> * those semantics. The same annotations can also be used at the type level, e.g. for
<del> * component scanning.
<add> * to those of the {@code <bean/>} element in the Spring XML schema. For example:
<add> * <pre class="code">
<add> * @Bean
<add> * public MyBean myBean() {
<add> * // instantiate and configure MyBean obj
<add> * return obj;
<add> * }</pre>
<ide> *
<ide> * <p>While a {@link #name()} attribute is available, the default strategy for determining
<ide> * the name of a bean is to use the name of the Bean method. This is convenient and
<ide> * intuitive, but if explicit naming is desired, the {@code name()} attribute may be used.
<ide> * Also note that {@code name()} accepts an array of Strings. This is in order to allow
<ide> * for specifying multiple names (i.e., aliases) for a single bean.
<add> * <pre class="code">
<add> * @Bean(name={"b1","b2"}) // bean available as 'b1' and 'b2', but not 'myBean'
<add> * public MyBean myBean() {
<add> * // instantiate and configure MyBean obj
<add> * return obj;
<add> * }</pre>
<ide> *
<del> * <p>The <code>@Bean</code> annotation may be used on any methods in an <code>@Component</code>
<del> * class, in which case they will get processed in a configuration class 'lite' mode where
<add> * <p>Note that the {@code @Bean} annotation does not provide attributes for scope,
<add> * primary or lazy. Rather, it should be used in conjunction with {@link Scope @Scope},
<add> * {@link Primary @Primary}, and {@link Lazy @Lazy} annotations to achieve
<add> * those semantics. For example:
<add> * <pre class="code">
<add> * @Bean
<add> * @Scope("prototype")
<add> * public MyBean myBean() {
<add> * // instantiate and configure MyBean obj
<add> * return obj;
<add> * }</pre>
<add> *
<add> * <p>Typically, {@code @Bean} methods are declared within {@code @Configuration}
<add> * classes. In this case, bean methods may reference other <code>@Bean</code> methods
<add> * on the same class by calling them <i>directly</i>. This ensures that references between
<add> * beans are strongly typed and navigable. Such so-called 'inter-bean references' are
<add> * guaranteed to respect scoping and AOP semantics, just like <code>getBean</code> lookups
<add> * would. These are the semantics known from the original 'Spring JavaConfig' project
<add> * which require CGLIB subclassing of each such configuration class at runtime. As a
<add> * consequence, {@code @Configuration} classes and their factory methods must not be
<add> * marked as final or private in this mode. For example:
<add> * <pre class="code">
<add> * @Configuration
<add> * public class AppConfig {
<add> * @Bean
<add> * public FooService fooService() {
<add> * return new FooService(fooRepository());
<add> * }
<add> * @Bean
<add> * public FooRepository fooRepository() {
<add> * return new JdbcFooRepository(dataSource());
<add> * }
<add> * // ...
<add> * }</pre>
<add> *
<add> * <p>{@code @Bean} methods may also be declared wihtin any {@code @Component} class, in
<add> * which case they will get processed in a configuration class 'lite' mode in which
<ide> * they will simply be called as plain factory methods from the container (similar to
<del> * <code>factory-method</code> declarations in XML). The containing component classes remain
<del> * unmodified in this case, and there are no unusual constraints for factory methods.
<add> * {@code factory-method} declarations in XML). The containing component classes remain
<add> * unmodified in this case, and there are no unusual constraints for factory methods,
<add> * however, scoping semantics are not respected as described above for inter-bean method
<add> * invocations in this mode. For example:
<add> * <pre class="code">
<add> * @Component
<add> * public class Calculator {
<add> * public int sum(int a, int b) {
<add> * return a+b;
<add> * }
<add> *
<add> * @Bean
<add> * public MyBean myBean() {
<add> * return new MyBean();
<add> * }
<add> * }</pre>
<ide> *
<del> * <p>As an advanced mode, <code>@Bean</code> may also be used within <code>@Configuration</code>
<del> * component classes. In this case, bean methods may reference other <code>@Bean</code> methods
<del> * on the same class by calling them <i>directly</i>. This ensures that references between beans
<del> * are strongly typed and navigable. Such so-called 'inter-bean references' are guaranteed to
<del> * respect scoping and AOP semantics, just like <code>getBean</code> lookups would. These are
<del> * the semantics known from the original 'Spring JavaConfig' project which require CGLIB
<del> * subclassing of each such configuration class at runtime. As a consequence, configuration
<del> * classes and their factory methods must not be marked as final or private in this mode.
<add> * <p>See @{@link Configuration} Javadoc for further details including how to bootstrap
<add> * the container using {@link AnnotationConfigApplicationContext} and friends.
<ide> *
<ide> * <h3>A note on {@code BeanFactoryPostProcessor}-returning {@code @Bean} methods</h3>
<ide> * <p>Special consideration must be taken for {@code @Bean} methods that return Spring
<ide> * @author Chris Beams
<ide> * @author Juergen Hoeller
<ide> * @since 3.0
<del> * @see org.springframework.stereotype.Component
<ide> * @see Configuration
<ide> * @see Scope
<ide> * @see DependsOn
<ide> * @see Lazy
<ide> * @see Primary
<add> * @see org.springframework.stereotype.Component
<ide> * @see org.springframework.beans.factory.annotation.Autowired
<ide> * @see org.springframework.beans.factory.annotation.Value
<ide> */
<ide> /**
<ide> * The optional name of a method to call on the bean instance during initialization.
<ide> * Not commonly used, given that the method may be called programmatically directly
<del> * within the body of a Bean-annotated method.
<add> * within the body of a Bean-annotated method. Default value is {@code ""}, indicating
<add> * that no init method should be called.
<ide> */
<ide> String initMethod() default "";
<ide> | 1 |
Ruby | Ruby | fix iconv dylib name | d88158b9fe80f479d4b499ba95c3e3e77c3cc585 | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_for_gettext
<ide> end
<ide>
<ide> def check_for_iconv
<del> unless find_relative_paths("lib/iconv.dylib", "include/iconv.h").empty?
<add> unless find_relative_paths("lib/libiconv.dylib", "include/iconv.h").empty?
<ide> if (f = Formula.factory("libiconv") rescue nil) and f.linked_keg.directory?
<ide> if not f.keg_only? then <<-EOS.undent
<ide> A libiconv formula is installed and linked | 1 |
Ruby | Ruby | define the delegate methods on one line. fixes | 44c51fc9cc7a0cdcf8b657e1900eb141083ef683 | <ide><path>activesupport/lib/active_support/core_ext/module/delegation.rb
<ide> def delegate(*methods)
<ide> # whereas conceptually, from the user point of view, the delegator should
<ide> # be doing one call.
<ide> if allow_nil
<del> module_eval(<<-EOS, file, line - 3)
<del> def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block)
<del> _ = #{to} # _ = client
<del> if !_.nil? || nil.respond_to?(:#{method}) # if !_.nil? || nil.respond_to?(:name)
<del> _.#{method}(#{definition}) # _.name(*args, &block)
<del> end # end
<del> end # end
<del> EOS
<add> method_def = [
<add> "def #{method_prefix}#{method}(#{definition})", # def customer_name(*args, &block)
<add> "_ = #{to}", # _ = client
<add> "if !_.nil? || nil.respond_to?(:#{method})", # if !_.nil? || nil.respond_to?(:name)
<add> " _.#{method}(#{definition})", # _.name(*args, &block)
<add> "end", # end
<add> "end" # end
<add> ].join ';'
<ide> else
<ide> exception = %(raise DelegationError, "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
<ide>
<del> module_eval(<<-EOS, file, line - 2)
<del> def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block)
<del> _ = #{to} # _ = client
<del> _.#{method}(#{definition}) # _.name(*args, &block)
<del> rescue NoMethodError => e # rescue NoMethodError => e
<del> if _.nil? && e.name == :#{method} # if _.nil? && e.name == :name
<del> #{exception} # # add helpful message to the exception
<del> else # else
<del> raise # raise
<del> end # end
<del> end # end
<del> EOS
<add> method_def = [
<add> "def #{method_prefix}#{method}(#{definition})", # def customer_name(*args, &block)
<add> " _ = #{to}", # _ = client
<add> " _.#{method}(#{definition})", # _.name(*args, &block)
<add> "rescue NoMethodError => e", # rescue NoMethodError => e
<add> " if _.nil? && e.name == :#{method}", # if _.nil? && e.name == :name
<add> " #{exception}", # # add helpful message to the exception
<add> " else", # else
<add> " raise", # raise
<add> " end", # end
<add> "end" # end
<add> ].join ';'
<ide> end
<add>
<add> module_eval(method_def, file, line)
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/test/core_ext/module_test.rb
<ide> class << self
<ide> end
<ide> end
<ide>
<add> def test_delegation_line_number
<add> file, line = Someone.instance_method(:foo).source_location
<add> assert_equal Someone::FAILED_DELEGATE_LINE, line
<add> end
<add>
<add> def test_delegate_line_with_nil
<add> file, line = Someone.instance_method(:bar).source_location
<add> assert_equal Someone::FAILED_DELEGATE_LINE_2, line
<add> end
<add>
<ide> def test_delegation_exception_backtrace
<ide> someone = Someone.new("foo", "bar")
<ide> someone.foo | 2 |
Javascript | Javascript | use es5 .trim() | b34c55cc3cdaecd7aad66a7fbf613f90637b48d7 | <ide><path>src/fonts.js
<ide> var Type1Parser = function type1Parser() {
<ide>
<ide> str = str.substr(start, count);
<ide>
<del> // Trim
<del> str = str.replace(/^\s+/, '');
<del> str = str.replace(/\s+$/, '');
<add> str = str.trim();
<ide> // Remove adjacent spaces
<ide> str = str.replace(/\s+/g, ' ');
<ide> | 1 |
PHP | PHP | fix bug in request uri parsing | 527340d793f2ac0de3d61938770b9407b61ec8c7 | <ide><path>laravel/request.php
<ide> public static function uri()
<ide> {
<ide> if ( ! is_null(static::$uri)) return static::$uri;
<ide>
<del> $uri = $_SERVER['REQUEST_URI'];
<add> $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
<ide>
<ide> // Remove the root application URL from the request URI. If the application
<ide> // is nested within a sub-directory of the web document root, this will get | 1 |
PHP | PHP | fix windows tests | e2b0963018c00b2a55754a0bd0f23c3436c88ed6 | <ide><path>tests/Foundation/FoundationApplicationTest.php
<ide> public function testCachePathsResolveToBootstrapCacheDirectory()
<ide> {
<ide> $app = new Application('/base/path');
<ide>
<del> $this->assertSame('/base/path/bootstrap/cache/services.php', $app->getCachedServicesPath());
<del> $this->assertSame('/base/path/bootstrap/cache/packages.php', $app->getCachedPackagesPath());
<del> $this->assertSame('/base/path/bootstrap/cache/config.php', $app->getCachedConfigPath());
<del> $this->assertSame('/base/path/bootstrap/cache/routes-v7.php', $app->getCachedRoutesPath());
<del> $this->assertSame('/base/path/bootstrap/cache/events.php', $app->getCachedEventsPath());
<add> $ds = DIRECTORY_SEPARATOR;
<add> $this->assertSame('/base/path'.$ds.'bootstrap'.$ds.'cache/services.php', $app->getCachedServicesPath());
<add> $this->assertSame('/base/path'.$ds.'bootstrap'.$ds.'cache/packages.php', $app->getCachedPackagesPath());
<add> $this->assertSame('/base/path'.$ds.'bootstrap'.$ds.'cache/config.php', $app->getCachedConfigPath());
<add> $this->assertSame('/base/path'.$ds.'bootstrap'.$ds.'cache/routes-v7.php', $app->getCachedRoutesPath());
<add> $this->assertSame('/base/path'.$ds.'bootstrap'.$ds.'cache/events.php', $app->getCachedEventsPath());
<ide> }
<ide>
<ide> public function testEnvPathsAreUsedForCachePathsWhenSpecified()
<ide> public function testEnvPathsAreUsedAndMadeAbsoluteForCachePathsWhenSpecifiedAsRe
<ide> $_SERVER['APP_ROUTES_CACHE'] = 'relative/path/routes.php';
<ide> $_SERVER['APP_EVENTS_CACHE'] = 'relative/path/events.php';
<ide>
<del> $this->assertSame('/base/path/relative/path/services.php', $app->getCachedServicesPath());
<del> $this->assertSame('/base/path/relative/path/packages.php', $app->getCachedPackagesPath());
<del> $this->assertSame('/base/path/relative/path/config.php', $app->getCachedConfigPath());
<del> $this->assertSame('/base/path/relative/path/routes.php', $app->getCachedRoutesPath());
<del> $this->assertSame('/base/path/relative/path/events.php', $app->getCachedEventsPath());
<add> $ds = DIRECTORY_SEPARATOR;
<add> $this->assertSame('/base/path'.$ds.'relative/path/services.php', $app->getCachedServicesPath());
<add> $this->assertSame('/base/path'.$ds.'relative/path/packages.php', $app->getCachedPackagesPath());
<add> $this->assertSame('/base/path'.$ds.'relative/path/config.php', $app->getCachedConfigPath());
<add> $this->assertSame('/base/path'.$ds.'relative/path/routes.php', $app->getCachedRoutesPath());
<add> $this->assertSame('/base/path'.$ds.'relative/path/events.php', $app->getCachedEventsPath());
<ide>
<ide> unset(
<ide> $_SERVER['APP_SERVICES_CACHE'],
<ide> public function testEnvPathsAreUsedAndMadeAbsoluteForCachePathsWhenSpecifiedAsRe
<ide> $_SERVER['APP_ROUTES_CACHE'] = 'relative/path/routes.php';
<ide> $_SERVER['APP_EVENTS_CACHE'] = 'relative/path/events.php';
<ide>
<del> $this->assertSame('/relative/path/services.php', $app->getCachedServicesPath());
<del> $this->assertSame('/relative/path/packages.php', $app->getCachedPackagesPath());
<del> $this->assertSame('/relative/path/config.php', $app->getCachedConfigPath());
<del> $this->assertSame('/relative/path/routes.php', $app->getCachedRoutesPath());
<del> $this->assertSame('/relative/path/events.php', $app->getCachedEventsPath());
<add> $ds = DIRECTORY_SEPARATOR;
<add> $this->assertSame($ds.'relative/path/services.php', $app->getCachedServicesPath());
<add> $this->assertSame($ds.'relative/path/packages.php', $app->getCachedPackagesPath());
<add> $this->assertSame($ds.'relative/path/config.php', $app->getCachedConfigPath());
<add> $this->assertSame($ds.'relative/path/routes.php', $app->getCachedRoutesPath());
<add> $this->assertSame($ds.'relative/path/events.php', $app->getCachedEventsPath());
<ide>
<ide> unset(
<ide> $_SERVER['APP_SERVICES_CACHE'], | 1 |
Python | Python | add __array__ to the array_api array object | 74a3ee7a8b75bf6dc271c9a1a4b55d2ad9758420 | <ide><path>numpy/array_api/_array_object.py
<ide> def __repr__(self: Array, /) -> str:
<ide> mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix)
<ide> return prefix + mid + suffix
<ide>
<add> # This function is not required by the spec, but we implement it here for
<add> # convenience so that np.asarray(np.array_api.Array) will work.
<add> def __array__(self, dtype=None):
<add> """
<add> Warning: this method is NOT part of the array API spec. Implementers
<add> of other libraries need not include it, and users should not assume it
<add> will be present in other implementations.
<add>
<add> """
<add> return np.asarray(self._array, dtype=dtype)
<add>
<ide> # These are various helper functions to make the array behavior match the
<ide> # spec in places where it either deviates from or is more strict than
<ide> # NumPy behavior
<ide><path>numpy/array_api/tests/test_array_object.py
<ide> def test_array_properties():
<ide> assert a.mT.shape == (1, 3, 2)
<ide> assert isinstance(b.mT, Array)
<ide> assert b.mT.shape == (3, 2)
<add>
<add>def test___array__():
<add> a = ones((2, 3), dtype=int16)
<add> assert np.asarray(a) is a._array
<add> b = np.asarray(a, dtype=np.float64)
<add> assert np.all(np.equal(b, np.ones((2, 3), dtype=np.float64)))
<add> assert b.dtype == np.float64 | 2 |
Javascript | Javascript | improve crypto hmac test assertions | fe38ace643701507ce0fa6b3903d4adce14b7255 | <ide><path>test/parallel/test-crypto-hmac.js
<ide> if (!common.hasCrypto)
<ide> const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<del>// Test HMAC
<del>const h1 = crypto.createHmac('sha1', 'Node')
<del> .update('some data')
<del> .update('to hmac')
<del> .digest('hex');
<del>assert.strictEqual(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC');
<add>{
<add> // Test HMAC
<add> const actual = crypto.createHmac('sha1', 'Node')
<add> .update('some data')
<add> .update('to hmac')
<add> .digest('hex');
<add> const expected = '19fd6e1ba73d9ed2224dd5094a71babe85d9a892';
<add> assert.strictEqual(actual,
<add> expected,
<add> `Test HMAC: ${actual} must be ${expected}`);
<add>}
<ide>
<ide> // Test HMAC (Wikipedia Test Cases)
<ide> const wikipedia = [
<ide> for (let i = 0, l = wikipedia.length; i < l; i++) {
<ide> // FIPS does not support MD5.
<ide> if (common.hasFipsCrypto && hash === 'md5')
<ide> continue;
<del> const result = crypto.createHmac(hash, wikipedia[i]['key'])
<add> const expected = wikipedia[i]['hmac'][hash];
<add> const actual = crypto.createHmac(hash, wikipedia[i]['key'])
<ide> .update(wikipedia[i]['data'])
<ide> .digest('hex');
<del> assert.strictEqual(wikipedia[i]['hmac'][hash],
<del> result,
<del> `Test HMAC-${hash}: Test case ${i + 1} wikipedia`);
<add> assert.strictEqual(
<add> actual,
<add> expected,
<add> `Test HMAC-${hash} wikipedia case ${i + 1}: ${actual} must be ${expected}`
<add> );
<ide> }
<ide> }
<ide>
<ide> for (let i = 0, l = rfc4231.length; i < l; i++) {
<ide> const str = crypto.createHmac(hash, rfc4231[i].key);
<ide> str.end(rfc4231[i].data);
<ide> let strRes = str.read().toString('hex');
<del> let result = crypto.createHmac(hash, rfc4231[i]['key'])
<add> let actual = crypto.createHmac(hash, rfc4231[i]['key'])
<ide> .update(rfc4231[i]['data'])
<ide> .digest('hex');
<ide> if (rfc4231[i]['truncate']) {
<del> result = result.substr(0, 32); // first 128 bits == 32 hex chars
<add> actual = actual.substr(0, 32); // first 128 bits == 32 hex chars
<ide> strRes = strRes.substr(0, 32);
<ide> }
<del> assert.strictEqual(rfc4231[i]['hmac'][hash],
<del> result,
<del> `Test HMAC-${hash}: Test case ${i + 1} rfc 4231`);
<del> assert.strictEqual(strRes, result, 'Should get same result from stream');
<add> const expected = rfc4231[i]['hmac'][hash];
<add> assert.strictEqual(
<add> actual,
<add> expected,
<add> `Test HMAC-${hash} rfc 4231 case ${i + 1}: ${actual} must be ${expected}`
<add> );
<add> assert.strictEqual(actual, strRes, 'Should get same result from stream');
<ide> }
<ide> }
<ide>
<ide> const rfc2202_sha1 = [
<ide>
<ide> if (!common.hasFipsCrypto) {
<ide> for (let i = 0, l = rfc2202_md5.length; i < l; i++) {
<add> const actual = crypto.createHmac('md5', rfc2202_md5[i]['key'])
<add> .update(rfc2202_md5[i]['data'])
<add> .digest('hex');
<add> const expected = rfc2202_md5[i]['hmac'];
<ide> assert.strictEqual(
<del> rfc2202_md5[i]['hmac'],
<del> crypto.createHmac('md5', rfc2202_md5[i]['key'])
<del> .update(rfc2202_md5[i]['data'])
<del> .digest('hex'),
<del> `Test HMAC-MD5 : Test case ${i + 1} rfc 2202`
<add> actual,
<add> expected,
<add> `Test HMAC-MD5 rfc 2202 case ${i + 1}: ${actual} must be ${expected}`
<ide> );
<ide> }
<ide> }
<ide> for (let i = 0, l = rfc2202_sha1.length; i < l; i++) {
<add> const actual = crypto.createHmac('sha1', rfc2202_sha1[i]['key'])
<add> .update(rfc2202_sha1[i]['data'])
<add> .digest('hex');
<add> const expected = rfc2202_sha1[i]['hmac'];
<ide> assert.strictEqual(
<del> rfc2202_sha1[i]['hmac'],
<del> crypto.createHmac('sha1', rfc2202_sha1[i]['key'])
<del> .update(rfc2202_sha1[i]['data'])
<del> .digest('hex'),
<del> `Test HMAC-SHA1 : Test case ${i + 1} rfc 2202`
<add> actual,
<add> expected,
<add> `Test HMAC-SHA1 rfc 2202 case ${i + 1}: ${actual} must be ${expected}`
<ide> );
<ide> }
<ide> | 1 |
Python | Python | specify unicode strings for python 2.7 | 9751312aff48b70a28a8e52c553d749666675d9c | <ide><path>spacy/tests/pipeline/test_el.py
<ide> def test_kb_valid_entities(nlp):
<ide> mykb = KnowledgeBase(nlp.vocab)
<ide>
<ide> # adding entities
<del> mykb.add_entity(entity_id="Q1", prob=0.9)
<del> mykb.add_entity(entity_id="Q2", prob=0.2)
<del> mykb.add_entity(entity_id="Q3", prob=0.5)
<add> mykb.add_entity(entity_id=u'Q1', prob=0.9)
<add> mykb.add_entity(entity_id=u'Q2', prob=0.2)
<add> mykb.add_entity(entity_id=u'Q3', prob=0.5)
<ide>
<ide> # adding aliases
<del> mykb.add_alias(alias="douglas", entities=["Q2", "Q3"], probabilities=[0.8, 0.2])
<del> mykb.add_alias(alias="adam", entities=["Q2"], probabilities=[0.9])
<add> mykb.add_alias(alias=u'douglas', entities=[u'Q2', u'Q3'], probabilities=[0.8, 0.2])
<add> mykb.add_alias(alias=u'adam', entities=[u'Q2'], probabilities=[0.9])
<ide>
<ide> # test the size of the corresponding KB
<ide> assert(mykb.get_size_entities() == 3)
<ide> def test_kb_invalid_entities(nlp):
<ide> mykb = KnowledgeBase(nlp.vocab)
<ide>
<ide> # adding entities
<del> mykb.add_entity(entity_id="Q1", prob=0.9)
<del> mykb.add_entity(entity_id="Q2", prob=0.2)
<del> mykb.add_entity(entity_id="Q3", prob=0.5)
<add> mykb.add_entity(entity_id=u'Q1', prob=0.9)
<add> mykb.add_entity(entity_id=u'Q2', prob=0.2)
<add> mykb.add_entity(entity_id=u'Q3', prob=0.5)
<ide>
<ide> # adding aliases - should fail because one of the given IDs is not valid
<ide> with pytest.raises(ValueError):
<del> mykb.add_alias(alias="douglas", entities=["Q2", "Q342"], probabilities=[0.8, 0.2])
<add> mykb.add_alias(alias=u'douglas', entities=[u'Q2', u'Q342'], probabilities=[0.8, 0.2])
<ide>
<ide>
<ide> def test_kb_invalid_probabilities(nlp):
<ide> """Test the invalid construction of a KB with wrong prior probabilities"""
<ide> mykb = KnowledgeBase(nlp.vocab)
<ide>
<ide> # adding entities
<del> mykb.add_entity(entity_id="Q1", prob=0.9)
<del> mykb.add_entity(entity_id="Q2", prob=0.2)
<del> mykb.add_entity(entity_id="Q3", prob=0.5)
<add> mykb.add_entity(entity_id=u'Q1', prob=0.9)
<add> mykb.add_entity(entity_id=u'Q2', prob=0.2)
<add> mykb.add_entity(entity_id=u'Q3', prob=0.5)
<ide>
<ide> # adding aliases - should fail because the sum of the probabilities exceeds 1
<ide> with pytest.raises(ValueError):
<del> mykb.add_alias(alias="douglassss", entities=["Q2", "Q3"], probabilities=[0.8, 0.4])
<add> mykb.add_alias(alias=u'douglas', entities=[u'Q2', u'Q3'], probabilities=[0.8, 0.4])
<ide>
<ide>
<ide> def test_kb_invalid_combination(nlp):
<ide> """Test the invalid construction of a KB with non-matching entity and probability lists"""
<ide> mykb = KnowledgeBase(nlp.vocab)
<ide>
<ide> # adding entities
<del> mykb.add_entity(entity_id="Q1", prob=0.9)
<del> mykb.add_entity(entity_id="Q2", prob=0.2)
<del> mykb.add_entity(entity_id="Q3", prob=0.5)
<add> mykb.add_entity(entity_id=u'Q1', prob=0.9)
<add> mykb.add_entity(entity_id=u'Q2', prob=0.2)
<add> mykb.add_entity(entity_id=u'Q3', prob=0.5)
<ide>
<ide> # adding aliases - should fail because the entities and probabilities vectors are not of equal length
<ide> with pytest.raises(ValueError):
<del> mykb.add_alias(alias="douglassss", entities=["Q2", "Q3"], probabilities=[0.3, 0.4, 0.1])
<add> mykb.add_alias(alias=u'douglas', entities=[u'Q2', u'Q3'], probabilities=[0.3, 0.4, 0.1])
<ide>
<ide>
<ide> def test_candidate_generation(nlp):
<ide> """Test correct candidate generation"""
<ide> mykb = KnowledgeBase(nlp.vocab)
<ide>
<ide> # adding entities
<del> mykb.add_entity(entity_id="Q1", prob=0.9)
<del> mykb.add_entity(entity_id="Q2", prob=0.2)
<del> mykb.add_entity(entity_id="Q3", prob=0.5)
<add> mykb.add_entity(entity_id=u'Q1', prob=0.9)
<add> mykb.add_entity(entity_id=u'Q2', prob=0.2)
<add> mykb.add_entity(entity_id=u'Q3', prob=0.5)
<ide>
<ide> # adding aliases
<del> mykb.add_alias(alias="douglas", entities=["Q2", "Q3"], probabilities=[0.8, 0.2])
<del> mykb.add_alias(alias="adam", entities=["Q2"], probabilities=[0.9])
<add> mykb.add_alias(alias=u'douglas', entities=[u'Q2', u'Q3'], probabilities=[0.8, 0.2])
<add> mykb.add_alias(alias=u'adam', entities=[u'Q2'], probabilities=[0.9])
<ide>
<ide> # test the size of the relevant candidates
<del> assert(len(mykb.get_candidates("douglas")) == 2)
<del> assert(len(mykb.get_candidates("adam")) == 1)
<del> assert(len(mykb.get_candidates("shrubbery")) == 0)
<add> assert(len(mykb.get_candidates(u'douglas')) == 2)
<add> assert(len(mykb.get_candidates(u'adam')) == 1)
<add> assert(len(mykb.get_candidates(u'shrubbery')) == 0) | 1 |
Javascript | Javascript | add keyword in email support for passwordless | af433600273eb8423fdf2ecb5de12e1fe3496130 | <ide><path>common/models/user.js
<ide> module.exports = function(User) {
<ide> .flatMap(token => {
<ide>
<ide> const { id: loginToken } = token;
<del> const loginEmail = user.email;
<add> const loginEmail = new Buffer(user.email).toString('base64');
<ide> const host = getServerFullURL();
<ide> const mailOptions = {
<ide> type: 'email',
<ide><path>server/boot/user.js
<ide> module.exports = function(app) {
<ide> }
<ide>
<ide> const authTokenId = req.query.token;
<del> const authEmailId = req.query.email;
<add> const authEmailId = new Buffer(req.query.email, 'base64').toString();
<ide>
<ide> return AccessToken.findOne$({ where: {id: authTokenId} })
<ide> .map(authToken => {
<ide> module.exports = function(app) {
<ide> return res.redirect('/email-signin');
<ide> }
<ide>
<del> const email = req.query.email;
<add> const email = new Buffer(req.query.email, 'base64').toString();
<ide>
<ide> return User.findOne$({ where: { email }})
<ide> .map(user => { | 2 |
Javascript | Javascript | update message on the success | 38160d6dd73442085f8ce4314b5ddf166465da81 | <ide><path>client/src/components/Donation/components/DonateCompletion.js
<ide> function DonateCompletion({ processing, reset, success, error = null }) {
<ide> Your donation will support free technology education for people
<ide> all over the world.
<ide> </p>
<del> <p>
<del> You can update your supporter status at any time from the 'manage
<del> your existing donation' section below on this page.
<del> </p>
<ide> </div>
<ide> )}
<ide> {error && <p>{error}</p>} | 1 |
Python | Python | fix example_emr_serverless system test | 1bbd8fe3ef4ca0362f033c99016f857329870dd1 | <ide><path>airflow/providers/amazon/aws/hooks/s3.py
<ide> def check_for_bucket(self, bucket_name: str | None = None) -> bool:
<ide> # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.head_bucket
<ide> return_code = int(e.response["Error"]["Code"])
<ide> if return_code == 404:
<del> self.log.error('Bucket "%s" does not exist', bucket_name)
<add> self.log.info('Bucket "%s" does not exist', bucket_name)
<ide> elif return_code == 403:
<ide> self.log.error(
<ide> 'Access to bucket "%s" is forbidden or there was an error with the request', bucket_name
<ide><path>tests/system/providers/amazon/aws/example_emr_serverless.py
<ide>
<ide> from datetime import datetime
<ide>
<add>import boto3
<add>
<ide> from airflow.models.baseoperator import chain
<ide> from airflow.models.dag import DAG
<ide> from airflow.providers.amazon.aws.operators.emr import (
<ide> env_id = test_context[ENV_ID_KEY]
<ide> role_arn = test_context[ROLE_ARN_KEY]
<ide> bucket_name = f"{env_id}-emr-serverless-bucket"
<del> entryPoint = "s3://us-east-1.elasticmapreduce/emr-containers/samples/wordcount/scripts/wordcount.py"
<add> region = boto3.session.Session().region_name
<add> entryPoint = f"s3://{region}.elasticmapreduce/emr-containers/samples/wordcount/scripts/wordcount.py"
<ide> create_s3_bucket = S3CreateBucketOperator(task_id="create_s3_bucket", bucket_name=bucket_name)
<ide>
<ide> SPARK_JOB_DRIVER = { | 2 |
Javascript | Javascript | add konkani devanagari | 79fc3a9509aca42f19cff43041d8f9b058b5aa48 | <ide><path>src/locale/gom-deva.js
<add>//! moment.js locale configuration
<add>//! locale : Konkani Devanagari script [gom-deva]
<add>//! author : The Discoverer : https://github.com/WikiDiscoverer
<add>
<add>import moment from '../moment';
<add>
<add>function processRelativeTime(number, withoutSuffix, key, isFuture) {
<add> var format = {
<add> s: ['थोडया सॅकंडांनी', 'थोडे सॅकंड'],
<add> ss: [number + ' सॅकंडांनी', number + ' सॅकंड'],
<add> m: ['एका मिणटान', 'एक मिनूट'],
<add> mm: [number + ' मिणटांनी', number + ' मिणटां'],
<add> h: ['एका वरान', 'एक वर'],
<add> hh: [number + ' वरांनी', number + ' वरां'],
<add> d: ['एका दिसान', 'एक दीस'],
<add> dd: [number + ' दिसांनी', number + ' दीस'],
<add> M: ['एका म्हयन्यान', 'एक म्हयनो'],
<add> MM: [number + ' म्हयन्यानी', number + ' म्हयने'],
<add> y: ['एका वर्सान', 'एक वर्स'],
<add> yy: [number + ' वर्सांनी', number + ' वर्सां'],
<add> };
<add> return isFuture ? format[key][0] : format[key][1];
<add>}
<add>
<add>export default moment.defineLocale('gom-deva', {
<add> months: {
<add> standalone: 'जानेवारी_फेब्रुवारी_मार्च_एप्रील_मे_जून_जुलय_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split(
<add> '_'
<add> ),
<add> format: 'जानेवारीच्या_फेब्रुवारीच्या_मार्चाच्या_एप्रीलाच्या_मेयाच्या_जूनाच्या_जुलयाच्या_ऑगस्टाच्या_सप्टेंबराच्या_ऑक्टोबराच्या_नोव्हेंबराच्या_डिसेंबराच्या'.split(
<add> '_'
<add> ),
<add> isFormat: /MMMM(\s)+D[oD]?/,
<add> },
<add> monthsShort: 'जाने._फेब्रु._मार्च_एप्री._मे_जून_जुल._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split(
<add> '_'
<add> ),
<add> monthsParseExact: true,
<add> weekdays: 'आयतार_सोमार_मंगळार_बुधवार_बिरेस्तार_सुक्रार_शेनवार'.split('_'),
<add> weekdaysShort: 'आयत._सोम._मंगळ._बुध._ब्रेस्त._सुक्र._शेन.'.split('_'),
<add> weekdaysMin: 'आ_सो_मं_बु_ब्रे_सु_शे'.split('_'),
<add> weekdaysParseExact: true,
<add> longDateFormat: {
<add> LT: 'A h:mm [वाजतां]',
<add> LTS: 'A h:mm:ss [वाजतां]',
<add> L: 'DD-MM-YYYY',
<add> LL: 'D MMMM YYYY',
<add> LLL: 'D MMMM YYYY A h:mm [वाजतां]',
<add> LLLL: 'dddd, MMMM Do, YYYY, A h:mm [वाजतां]',
<add> llll: 'ddd, D MMM YYYY, A h:mm [वाजतां]',
<add> },
<add> calendar: {
<add> sameDay: '[आयज] LT',
<add> nextDay: '[फाल्यां] LT',
<add> nextWeek: '[फुडलो] dddd[,] LT',
<add> lastDay: '[काल] LT',
<add> lastWeek: '[फाटलो] dddd[,] LT',
<add> sameElse: 'L',
<add> },
<add> relativeTime: {
<add> future: '%s',
<add> past: '%s आदीं',
<add> s: processRelativeTime,
<add> ss: processRelativeTime,
<add> m: processRelativeTime,
<add> mm: processRelativeTime,
<add> h: processRelativeTime,
<add> hh: processRelativeTime,
<add> d: processRelativeTime,
<add> dd: processRelativeTime,
<add> M: processRelativeTime,
<add> MM: processRelativeTime,
<add> y: processRelativeTime,
<add> yy: processRelativeTime,
<add> },
<add> dayOfMonthOrdinalParse: /\d{1,2}(वेर)/,
<add> ordinal: function (number, period) {
<add> switch (period) {
<add> // the ordinal 'वेर' only applies to day of the month
<add> case 'D':
<add> return number + 'वेर';
<add> default:
<add> case 'M':
<add> case 'Q':
<add> case 'DDD':
<add> case 'd':
<add> case 'w':
<add> case 'W':
<add> return number;
<add> }
<add> },
<add> week: {
<add> dow: 1, // Monday is the first day of the week.
<add> doy: 4, // The week that contains Jan 4th is the first week of the year.
<add> },
<add> meridiemParse: /राती|सकाळीं|दनपारां|सांजे/,
<add> meridiemHour: function (hour, meridiem) {
<add> if (hour === 12) {
<add> hour = 0;
<add> }
<add> if (meridiem === 'राती') {
<add> return hour < 4 ? hour : hour + 12;
<add> } else if (meridiem === 'सकाळीं') {
<add> return hour;
<add> } else if (meridiem === 'दनपारां') {
<add> return hour > 12 ? hour : hour + 12;
<add> } else if (meridiem === 'सांजे') {
<add> return hour + 12;
<add> }
<add> },
<add> meridiem: function (hour, minute, isLower) {
<add> if (hour < 4) {
<add> return 'राती';
<add> } else if (hour < 12) {
<add> return 'सकाळीं';
<add> } else if (hour < 16) {
<add> return 'दनपारां';
<add> } else if (hour < 20) {
<add> return 'सांजे';
<add> } else {
<add> return 'राती';
<add> }
<add> },
<add>});
<ide><path>src/test/locale/gom-deva.js
<add>import { test } from '../qunit';
<add>import { localeModule } from '../qunit-locale';
<add>import moment from '../../moment';
<add>localeModule('gom-deva');
<add>
<add>test('parse', function (assert) {
<add> var i,
<add> tests = 'जानेवारी जाने._फेब्रुवारी फेब्रु._मार्च मार्च_एप्रील एप्री._मे मे_जून जून_जुलय जुल._ऑगस्ट ऑग._सप्टेंबर सप्टें._ऑक्टोबर ऑक्टो._नोव्हेंबर नोव्हें._डिसेंबर डिसें.'.split(
<add> '_'
<add> );
<add>
<add> function equalTest(input, mmm, i) {
<add> assert.equal(
<add> moment(input, mmm).month(),
<add> i,
<add> input + ' should be month ' + (i + 1)
<add> );
<add> }
<add>
<add> for (i = 0; i < 12; i++) {
<add> tests[i] = tests[i].split(' ');
<add> equalTest(tests[i][0], 'MMM', i);
<add> equalTest(tests[i][1], 'MMM', i);
<add> equalTest(tests[i][0], 'MMMM', i);
<add> equalTest(tests[i][1], 'MMMM', i);
<add> equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
<add> equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
<add> }
<add>});
<add>
<add>test('format', function (assert) {
<add> var a = [
<add> [
<add> 'dddd, MMMM Do YYYY, h:mm:ss a',
<add> 'आयतार, फेब्रुवारीच्या 14वेर 2010, 3:25:50 दनपारां',
<add> ],
<add> ['ddd, h A', 'आयत., 3 दनपारां'],
<add> ['M Mo MM MMMM MMM', '2 2 02 फेब्रुवारी फेब्रु.'],
<add> ['YYYY YY', '2010 10'],
<add> ['D Do DD', '14 14वेर 14'],
<add> ['d do dddd ddd dd', '0 0 आयतार आयत. आ'],
<add> ['DDD DDDo DDDD', '45 45 045'],
<add> ['w wo ww', '6 6 06'],
<add> ['h hh', '3 03'],
<add> ['H HH', '15 15'],
<add> ['m mm', '25 25'],
<add> ['s ss', '50 50'],
<add> ['a A', 'दनपारां दनपारां'],
<add> ['[वर्साचो] DDDo[वो दीस]', 'वर्साचो 45वो दीस'],
<add> ['LTS', 'दनपारां 3:25:50 वाजतां'],
<add> ['L', '14-02-2010'],
<add> ['LL', '14 फेब्रुवारी 2010'],
<add> ['LLL', '14 फेब्रुवारी 2010 दनपारां 3:25 वाजतां'],
<add> ['LLLL', 'आयतार, फेब्रुवारीच्या 14वेर, 2010, दनपारां 3:25 वाजतां'],
<add> ['l', '14-2-2010'],
<add> ['ll', '14 फेब्रु. 2010'],
<add> ['lll', '14 फेब्रु. 2010 दनपारां 3:25 वाजतां'],
<add> ['llll', 'आयत., 14 फेब्रु. 2010, दनपारां 3:25 वाजतां'],
<add> ],
<add> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
<add> i;
<add>
<add> for (i = 0; i < a.length; i++) {
<add> assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
<add> }
<add>});
<add>
<add>test('format ordinal', function (assert) {
<add> assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1');
<add> assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2');
<add> assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3');
<add> assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4');
<add> assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5');
<add> assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6');
<add> assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7');
<add> assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8');
<add> assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9');
<add> assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10');
<add>
<add> assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11');
<add> assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12');
<add> assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13');
<add> assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14');
<add> assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15');
<add> assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16');
<add> assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17');
<add> assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18');
<add> assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19');
<add> assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20');
<add>
<add> assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21');
<add> assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22');
<add> assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23');
<add> assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24');
<add> assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25');
<add> assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26');
<add> assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27');
<add> assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28');
<add> assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29');
<add> assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30');
<add>
<add> assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31');
<add>});
<add>
<add>test('format month', function (assert) {
<add> var i,
<add> expected = 'जानेवारी जाने._फेब्रुवारी फेब्रु._मार्च मार्च_एप्रील एप्री._मे मे_जून जून_जुलय जुल._ऑगस्ट ऑग._सप्टेंबर सप्टें._ऑक्टोबर ऑक्टो._नोव्हेंबर नोव्हें._डिसेंबर डिसें.'.split(
<add> '_'
<add> );
<add>
<add> for (i = 0; i < expected.length; i++) {
<add> assert.equal(
<add> moment([2011, i, 1]).format('MMMM MMM'),
<add> expected[i],
<add> expected[i]
<add> );
<add> }
<add>});
<add>
<add>test('format week', function (assert) {
<add> var i,
<add> expected = 'आयतार आयत. आ_सोमार सोम. सो_मंगळार मंगळ. मं_बुधवार बुध. बु_बिरेस्तार ब्रेस्त. ब्रे_सुक्रार सुक्र. सु_शेनवार शेन. शे'.split(
<add> '_'
<add> );
<add>
<add> for (i = 0; i < expected.length; i++) {
<add> assert.equal(
<add> moment([2011, 0, 2 + i]).format('dddd ddd dd'),
<add> expected[i],
<add> expected[i]
<add> );
<add> }
<add>});
<add>
<add>test('from', function (assert) {
<add> var start = moment([2007, 1, 28]);
<add>
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ s: 44 }), true),
<add> 'थोडे सॅकंड',
<add> '44 seconds = a few seconds'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ s: 45 }), true),
<add> 'एक मिनूट',
<add> '45 seconds = a minute'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ s: 89 }), true),
<add> 'एक मिनूट',
<add> '89 seconds = a minute'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ s: 90 }), true),
<add> '2 मिणटां',
<add> '90 seconds = 2 minutes'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ m: 44 }), true),
<add> '44 मिणटां',
<add> '44 minutes = 44 minutes'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ m: 45 }), true),
<add> 'एक वर',
<add> '45 minutes = an hour'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ m: 89 }), true),
<add> 'एक वर',
<add> '89 minutes = an hour'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ m: 90 }), true),
<add> '2 वरां',
<add> '90 minutes = 2 hours'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ h: 5 }), true),
<add> '5 वरां',
<add> '5 hours = 5 hours'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ h: 21 }), true),
<add> '21 वरां',
<add> '21 hours = 21 hours'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ h: 22 }), true),
<add> 'एक दीस',
<add> '22 hours = a day'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ h: 35 }), true),
<add> 'एक दीस',
<add> '35 hours = a day'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ h: 36 }), true),
<add> '2 दीस',
<add> '36 hours = 2 days'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ d: 1 }), true),
<add> 'एक दीस',
<add> '1 day = a day'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ d: 5 }), true),
<add> '5 दीस',
<add> '5 days = 5 days'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ d: 25 }), true),
<add> '25 दीस',
<add> '25 days = 25 days'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ d: 26 }), true),
<add> 'एक म्हयनो',
<add> '26 days = a month'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ d: 30 }), true),
<add> 'एक म्हयनो',
<add> '30 days = a month'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ d: 43 }), true),
<add> 'एक म्हयनो',
<add> '43 days = a month'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ d: 46 }), true),
<add> '2 म्हयने',
<add> '46 days = 2 months'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ d: 74 }), true),
<add> '2 म्हयने',
<add> '75 days = 2 months'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ d: 76 }), true),
<add> '3 म्हयने',
<add> '76 days = 3 months'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ M: 1 }), true),
<add> 'एक म्हयनो',
<add> '1 month = a month'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ M: 5 }), true),
<add> '5 म्हयने',
<add> '5 months = 5 months'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ d: 345 }), true),
<add> 'एक वर्स',
<add> '345 days = a year'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ d: 548 }), true),
<add> '2 वर्सां',
<add> '548 days = 2 years'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ y: 1 }), true),
<add> 'एक वर्स',
<add> '1 year = a year'
<add> );
<add> assert.equal(
<add> start.from(moment([2007, 1, 28]).add({ y: 5 }), true),
<add> '5 वर्सां',
<add> '5 years = 5 years'
<add> );
<add>});
<add>
<add>test('suffix', function (assert) {
<add> assert.equal(moment(30000).from(0), 'थोडया सॅकंडांनी', 'prefix');
<add> assert.equal(moment(0).from(30000), 'थोडे सॅकंड आदीं', 'suffix');
<add>});
<add>
<add>test('now from now', function (assert) {
<add> assert.equal(
<add> moment().fromNow(),
<add> 'थोडे सॅकंड आदीं',
<add> 'now from now should display as in the past'
<add> );
<add>});
<add>
<add>test('fromNow', function (assert) {
<add> assert.equal(
<add> moment().add({ s: 30 }).fromNow(),
<add> 'थोडया सॅकंडांनी',
<add> 'in a few seconds'
<add> );
<add> assert.equal(moment().add({ d: 5 }).fromNow(), '5 दिसांनी', 'in 5 days');
<add>});
<add>
<add>test('ago', function (assert) {
<add> assert.equal(
<add> moment().subtract({ h: 3 }).fromNow(),
<add> '3 वरां आदीं',
<add> '3 hours ago'
<add> );
<add>});
<add>
<add>test('calendar day', function (assert) {
<add> var a = moment().hours(12).minutes(0).seconds(0);
<add>
<add> assert.equal(
<add> moment(a).calendar(),
<add> 'आयज दनपारां 12:00 वाजतां',
<add> 'today at the same time'
<add> );
<add> assert.equal(
<add> moment(a).add({ m: 25 }).calendar(),
<add> 'आयज दनपारां 12:25 वाजतां',
<add> 'Now plus 25 min'
<add> );
<add> assert.equal(
<add> moment(a).add({ h: 1 }).calendar(),
<add> 'आयज दनपारां 1:00 वाजतां',
<add> 'Now plus 1 hour'
<add> );
<add> assert.equal(
<add> moment(a).add({ d: 1 }).calendar(),
<add> 'फाल्यां दनपारां 12:00 वाजतां',
<add> 'tomorrow at the same time'
<add> );
<add> assert.equal(
<add> moment(a).subtract({ h: 1 }).calendar(),
<add> 'आयज सकाळीं 11:00 वाजतां',
<add> 'Now minus 1 hour'
<add> );
<add> assert.equal(
<add> moment(a).subtract({ d: 1 }).calendar(),
<add> 'काल दनपारां 12:00 वाजतां',
<add> 'yesterday at the same time'
<add> );
<add>});
<add>
<add>test('calendar next week', function (assert) {
<add> var i, m;
<add>
<add> for (i = 2; i < 7; i++) {
<add> m = moment().add({ d: i });
<add> assert.equal(
<add> m.calendar(),
<add> m.format('[फुडलो] dddd[,] LT'),
<add> 'Today + ' + i + ' days current time'
<add> );
<add> m.hours(0).minutes(0).seconds(0).milliseconds(0);
<add> assert.equal(
<add> m.calendar(),
<add> m.format('[फुडलो] dddd[,] LT'),
<add> 'Today + ' + i + ' days beginning of day'
<add> );
<add> m.hours(23).minutes(59).seconds(59).milliseconds(999);
<add> assert.equal(
<add> m.calendar(),
<add> m.format('[फुडलो] dddd[,] LT'),
<add> 'Today + ' + i + ' days end of day'
<add> );
<add> }
<add>});
<add>
<add>test('calendar last week', function (assert) {
<add> var i, m;
<add>
<add> for (i = 2; i < 7; i++) {
<add> m = moment().subtract({ d: i });
<add> assert.equal(
<add> m.calendar(),
<add> m.format('[फाटलो] dddd[,] LT'),
<add> 'Today - ' + i + ' days current time'
<add> );
<add> m.hours(0).minutes(0).seconds(0).milliseconds(0);
<add> assert.equal(
<add> m.calendar(),
<add> m.format('[फाटलो] dddd[,] LT'),
<add> 'Today - ' + i + ' days beginning of day'
<add> );
<add> m.hours(23).minutes(59).seconds(59).milliseconds(999);
<add> assert.equal(
<add> m.calendar(),
<add> m.format('[फाटलो] dddd[,] LT'),
<add> 'Today - ' + i + ' days end of day'
<add> );
<add> }
<add>});
<add>
<add>test('calendar all else', function (assert) {
<add> var weeksAgo = moment().subtract({ w: 1 }),
<add> weeksFromNow = moment().add({ w: 1 });
<add>
<add> assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago');
<add> assert.equal(
<add> weeksFromNow.calendar(),
<add> weeksFromNow.format('L'),
<add> 'in 1 week'
<add> );
<add>
<add> weeksAgo = moment().subtract({ w: 2 });
<add> weeksFromNow = moment().add({ w: 2 });
<add>
<add> assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago');
<add> assert.equal(
<add> weeksFromNow.calendar(),
<add> weeksFromNow.format('L'),
<add> 'in 2 weeks'
<add> );
<add>});
<add>
<add>test('weeks year starting sunday format', function (assert) {
<add> assert.equal(
<add> moment([2012, 0, 1]).format('w ww wo'),
<add> '52 52 52',
<add> 'Jan 1 2012 should be week 52'
<add> );
<add> assert.equal(
<add> moment([2012, 0, 2]).format('w ww wo'),
<add> '1 01 1',
<add> 'Jan 2 2012 should be week 1'
<add> );
<add> assert.equal(
<add> moment([2012, 0, 8]).format('w ww wo'),
<add> '1 01 1',
<add> 'Jan 8 2012 should be week 1'
<add> );
<add> assert.equal(
<add> moment([2012, 0, 14]).format('w ww wo'),
<add> '2 02 2',
<add> 'Jan 14 2012 should be week 2'
<add> );
<add> assert.equal(
<add> moment([2012, 0, 15]).format('w ww wo'),
<add> '2 02 2',
<add> 'Jan 15 2012 should be week 2'
<add> );
<add>}); | 2 |
Ruby | Ruby | fix bug with rolling back frozen attributes | 237165feb3e5f7b117b05353bd64d756b9f18f74 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
<ide> def rollback_transaction_records(rollback) #:nodoc
<ide> begin
<ide> record.rolledback!(rollback)
<ide> rescue Exception => e
<del> record.logger.error(e) if record.respond_to?(:logger)
<add> record.logger.error(e) if record.respond_to?(:logger) && record.logger
<ide> end
<ide> end
<ide> end
<ide> def commit_transaction_records #:nodoc
<ide> begin
<ide> record.committed!
<ide> rescue Exception => e
<del> record.logger.error(e) if record.respond_to?(:logger)
<add> record.logger.error(e) if record.respond_to?(:logger) && record.logger
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/transactions.rb
<ide> def restore_transaction_record_state(force = false) #:nodoc
<ide> if @_start_transaction_state[:level] < 1
<ide> restore_state = remove_instance_variable(:@_start_transaction_state)
<ide> if restore_state
<add> @attributes = @attributes.dup if @attributes.frozen?
<ide> @new_record = restore_state[:new_record]
<ide> @destroyed = restore_state[:destroyed]
<ide> if restore_state[:id]
<ide><path>activerecord/test/cases/autosave_association_test.rb
<ide> def destroy(*args)
<ide> end
<ide>
<ide> assert_raise(RuntimeError) { assert !@pirate.save }
<del> assert before.first.frozen? # the first child was indeed destroyed
<ide> assert_equal before, @pirate.reload.send(association_name)
<ide> end
<ide>
<ide><path>activerecord/test/cases/transaction_callbacks_test.rb
<ide> def @first.commits(i=0); @commits ||= 0; @commits += i if i; end
<ide> assert_equal 2, @first.rollbacks
<ide> end
<ide>
<del> def test_after_transaction_callbacks_should_not_raise_errors
<add> def test_after_transaction_callbacks_should_prevent_callbacks_from_being_called
<ide> def @first.last_after_transaction_error=(e); @last_transaction_error = e; end
<ide> def @first.last_after_transaction_error; @last_transaction_error; end
<ide> @first.after_commit_block{|r| r.last_after_transaction_error = :commit; raise "fail!";}
<ide> @first.after_rollback_block{|r| r.last_after_transaction_error = :rollback; raise "fail!";}
<add> @second.after_commit_block{|r| r.history << :after_commit}
<add> @second.after_rollback_block{|r| r.history << :after_rollback}
<ide>
<del> @first.save!
<add> Topic.transaction do
<add> @first.save!
<add> @second.save!
<add> end
<ide> assert_equal :commit, @first.last_after_transaction_error
<add> assert_equal [:after_commit], @second.history
<ide>
<add> @second.history.clear
<ide> Topic.transaction do
<ide> @first.save!
<add> @second.save!
<ide> raise ActiveRecord::Rollback
<ide> end
<del>
<ide> assert_equal :rollback, @first.last_after_transaction_error
<add> assert_equal [:after_rollback], @second.history
<ide> end
<ide> end | 4 |
Python | Python | fix build by changing call signature | f20d90cc2598c95dbcf7e0246f83499f4f4c5c27 | <ide><path>numpy/f2py/tests/test_callback.py
<ide> def callback(cu, lencu):
<ide>
<ide> f = getattr(self.module, "string_callback_array")
<ide> for cu in [cu1, cu2, cu3]:
<del> res = f(callback, cu, len(cu))
<add> res = f(callback, cu, cu.size)
<ide> assert res == 0
<ide>
<ide> def test_threadsafety(self): | 1 |
Ruby | Ruby | use tab/space when finding vars (and not newlines) | 098b97801bbc237dc9a4105c5a016478dfdcdb9c | <ide><path>Library/Homebrew/test/test_inreplace.rb
<ide> def test_change_make_var_empty
<ide> assert_equal "FLAG=def\nFLAG2=abc", s1
<ide> end
<ide>
<add> def test_change_make_var_empty_2
<add> # Replace empty flag
<add> s1="FLAG = \nmv file_a file_b"
<add> s1.extend(HomebrewInreplaceExtension)
<add> s1.change_make_var! "FLAG", "def"
<add> assert_equal "FLAG=def\nmv file_a file_b", s1
<add> end
<add>
<ide> def test_change_make_var_append
<ide> # Append to flag
<ide> s1="FLAG = abc"
<ide><path>Library/Homebrew/utils.rb
<ide> module HomebrewInreplaceExtension
<ide> # value with "new_value", or removes the definition entirely.
<ide> def change_make_var! flag, new_value
<ide> new_value = "#{flag}=#{new_value}"
<del> gsub! Regexp.new("^#{flag}\\s*=[ \\t]*(.*)$"), new_value
<add> gsub! Regexp.new("^#{flag}[ \\t]*=[ \\t]*(.*)$"), new_value
<ide> end
<ide> # Removes variable assignments completely.
<ide> def remove_make_var! flags
<ide> flags.each do |flag|
<ide> # Also remove trailing \n, if present.
<del> gsub! Regexp.new("^#{flag}\\s*=(.*)$\n?"), ""
<add> gsub! Regexp.new("^#{flag}[ \\t]*=(.*)$\n?"), ""
<ide> end
<ide> end
<ide> end | 2 |
Javascript | Javascript | improve docs for keyboardavoidingview | cb6ec7c32141ef5bdde837d7f9d71b7adb83b751 | <ide><path>Libraries/Components/Keyboard/KeyboardAvoidingView.js
<ide> type KeyboardChangeEvent = {
<ide> const viewRef = 'VIEW';
<ide>
<ide> /**
<del> * It is a component to solve the common problem of views that need to move out of the way of the virtual keyboard.
<del> * It can automatically adjust either its position or bottom padding based on the position of the keyboard.
<add> * This is a component to solve the common problem of views that need to move out of the way of the virtual keyboard.
<add> * It can automatically adjust either its height, position or bottom padding based on the position of the keyboard.
<ide> */
<ide> const KeyboardAvoidingView = createReactClass({
<ide> displayName: 'KeyboardAvoidingView',
<ide> mixins: [TimerMixin],
<ide>
<ide> propTypes: {
<ide> ...ViewPropTypes,
<add> /**
<add> * Specify how the `KeyboardAvoidingView` will react to the presence of
<add> * the keyboard. It can adjust the height, position or bottom padding of the view
<add> */
<ide> behavior: PropTypes.oneOf(['height', 'position', 'padding']),
<ide>
<ide> /**
<ide> const KeyboardAvoidingView = createReactClass({
<ide>
<ide> /**
<ide> * This is the distance between the top of the user screen and the react native view,
<del> * may be non-zero in some use cases.
<add> * may be non-zero in some use cases. The default value is 0.
<ide> */
<ide> keyboardVerticalOffset: PropTypes.number.isRequired,
<ide> },
<ide> const KeyboardAvoidingView = createReactClass({
<ide> subscriptions: ([]: Array<EmitterSubscription>),
<ide> frame: (null: ?ViewLayout),
<ide>
<del> relativeKeyboardHeight(keyboardFrame: ScreenRect): number {
<add> _relativeKeyboardHeight(keyboardFrame: ScreenRect): number {
<ide> const frame = this.frame;
<ide> if (!frame || !keyboardFrame) {
<ide> return 0;
<ide> const KeyboardAvoidingView = createReactClass({
<ide> return Math.max(frame.y + frame.height - keyboardY, 0);
<ide> },
<ide>
<del> onKeyboardChange(event: ?KeyboardChangeEvent) {
<add> _onKeyboardChange(event: ?KeyboardChangeEvent) {
<ide> if (!event) {
<ide> this.setState({bottom: 0});
<ide> return;
<ide> }
<ide>
<ide> const {duration, easing, endCoordinates} = event;
<del> const height = this.relativeKeyboardHeight(endCoordinates);
<add> const height = this._relativeKeyboardHeight(endCoordinates);
<ide>
<ide> if (duration && easing) {
<ide> LayoutAnimation.configureNext({
<ide> const KeyboardAvoidingView = createReactClass({
<ide> this.setState({bottom: height});
<ide> },
<ide>
<del> onLayout(event: ViewLayoutEvent) {
<add> _onLayout(event: ViewLayoutEvent) {
<ide> this.frame = event.nativeEvent.layout;
<ide> },
<ide>
<ide> const KeyboardAvoidingView = createReactClass({
<ide> componentWillMount() {
<ide> if (Platform.OS === 'ios') {
<ide> this.subscriptions = [
<del> Keyboard.addListener('keyboardWillChangeFrame', this.onKeyboardChange),
<add> Keyboard.addListener('keyboardWillChangeFrame', this._onKeyboardChange),
<ide> ];
<ide> } else {
<ide> this.subscriptions = [
<del> Keyboard.addListener('keyboardDidHide', this.onKeyboardChange),
<del> Keyboard.addListener('keyboardDidShow', this.onKeyboardChange),
<add> Keyboard.addListener('keyboardDidHide', this._onKeyboardChange),
<add> Keyboard.addListener('keyboardDidShow', this._onKeyboardChange),
<ide> ];
<ide> }
<ide> },
<ide> const KeyboardAvoidingView = createReactClass({
<ide> heightStyle = {height: this.frame.height - this.state.bottom, flex: 0};
<ide> }
<ide> return (
<del> <View ref={viewRef} style={[style, heightStyle]} onLayout={this.onLayout} {...props}>
<add> <View ref={viewRef} style={[style, heightStyle]} onLayout={this._onLayout} {...props}>
<ide> {children}
<ide> </View>
<ide> );
<ide> const KeyboardAvoidingView = createReactClass({
<ide> const { contentContainerStyle } = this.props;
<ide>
<ide> return (
<del> <View ref={viewRef} style={style} onLayout={this.onLayout} {...props}>
<add> <View ref={viewRef} style={style} onLayout={this._onLayout} {...props}>
<ide> <View style={[contentContainerStyle, positionStyle]}>
<ide> {children}
<ide> </View>
<ide> const KeyboardAvoidingView = createReactClass({
<ide> case 'padding':
<ide> const paddingStyle = {paddingBottom: this.state.bottom};
<ide> return (
<del> <View ref={viewRef} style={[style, paddingStyle]} onLayout={this.onLayout} {...props}>
<add> <View ref={viewRef} style={[style, paddingStyle]} onLayout={this._onLayout} {...props}>
<ide> {children}
<ide> </View>
<ide> );
<ide>
<ide> default:
<ide> return (
<del> <View ref={viewRef} onLayout={this.onLayout} style={style} {...props}>
<add> <View ref={viewRef} onLayout={this._onLayout} style={style} {...props}>
<ide> {children}
<ide> </View>
<ide> ); | 1 |
Python | Python | add nested loops to the template processor | 99f7707f80dafab4709fd4e833766a24a40ecfc7 | <ide><path>numpy/distutils/conv_template.py
<ide> def parse_structure(astr):
<ide> _special_names = {}
<ide>
<ide> template_re = re.compile(r"@([\w]+)@")
<del>named_re = re.compile(r"#([\w]*)=([^#]*?)#")
<add>named_re = re.compile(r"#\s*([\w]*)\s*=\s*([^#]*)#")
<ide>
<ide> parenrep = re.compile(r"[(]([^)]*?)[)]\*(\d+)")
<ide> def paren_repl(obj):
<ide> def paren_repl(obj):
<ide> return ','.join([torep]*int(numrep))
<ide>
<ide> plainrep = re.compile(r"([^*]+)\*(\d+)")
<del>
<ide> def conv(astr):
<ide> # replaces all occurrences of '(a,b,c)*4' in astr
<del> # with 'a,b,c,a,b,c,a,b,c,a,b,c'
<add> # with 'a,b,c,a,b,c,a,b,c,a,b,c'. The result is
<add> # split at ',' and a list of values returned.
<ide> astr = parenrep.sub(paren_repl,astr)
<ide> # replaces occurences of xxx*3 with xxx, xxx, xxx
<ide> astr = ','.join([plainrep.sub(paren_repl,x.strip())
<ide> for x in astr.split(',')])
<del> return astr
<add> return astr.split(',')
<ide>
<ide> def unique_key(adict):
<ide> # this obtains a unique key given a dictionary
<ide> def unique_key(adict):
<ide> return newkey
<ide>
<ide> def expand_sub(substr, namestr, line):
<del> # find all named replacements
<add> # find all named replacements in the various loops.
<ide> reps = named_re.findall(namestr)
<add> nsubs = None
<add> loops = []
<ide> names = {}
<ide> names.update(_special_names)
<del> numsubs = None
<ide> for rep in reps:
<ide> name = rep[0].strip()
<del> thelist = conv(rep[1])
<del> names[name] = thelist
<del>
<del> # make lists out of string entries in name dictionary
<del> for name in names.keys():
<del> entry = names[name]
<del> entrylist = entry.split(',')
<del> names[name] = entrylist
<del> num = len(entrylist)
<del> if numsubs is None:
<del> numsubs = num
<del> elif numsubs != num:
<del> print namestr
<del> print substr
<add> vals = conv(rep[1])
<add> size = len(vals)
<add> if name == "repeat" :
<add> names[None] = nsubs
<add> loops.append(names)
<add> nsubs = None
<add> names = {}
<add> continue
<add> if nsubs is None :
<add> nsubs = size
<add> elif nsubs != size :
<add> print name
<add> print vals
<ide> raise ValueError, "Mismatch in number to replace"
<del>
<del> # now replace all keys for each of the lists
<del> mystr = ''
<del> thissub = [None]
<add> names[name] = vals
<add> names[None] = nsubs
<add> loops.append(names)
<add>
<add> # generate list of dictionaries, one for each template iteration
<add> def merge(d1,d2) :
<add> tmp = d1.copy()
<add> tmp.update(d2)
<add> return tmp
<add>
<add> dlist = [{}]
<add> for d in loops :
<add> nsubs = d.pop(None)
<add> tmp = [{} for i in range(nsubs)]
<add> for name, item in d.items() :
<add> for i in range(nsubs) :
<add> tmp[i][name] = item[i]
<add> dlist = [merge(d1,d2) for d1 in dlist for d2 in tmp]
<add>
<add> # now replace all keys for each of the dictionaries
<ide> def namerepl(match):
<ide> name = match.group(1)
<del> return names[name][thissub[0]]
<del> for k in range(numsubs):
<del> thissub[0] = k
<del> mystr += ("#line %d\n%s\n\n"
<del> % (line, template_re.sub(namerepl, substr)))
<add> return d[name]
<add>
<add> mystr = []
<add> header = "#line %d\n"%line
<add> for d in dlist :
<add> code = ''.join((header, template_re.sub(namerepl, substr), '\n'))
<add> mystr.append(code)
<add>
<ide> return mystr
<ide>
<ide>
<del>_head = \
<del>"""/* This file was autogenerated from a template DO NOT EDIT!!!!
<del> Changes should be made to the original source (.src) file
<del>*/
<add>header =\
<add>"""
<add>/*
<add> *****************************************************************************
<add> ** This file was autogenerated from a template DO NOT EDIT!!!! **
<add> ** Changes should be made to the original source (.src) file **
<add> *****************************************************************************
<add> */
<ide>
<ide> """
<ide>
<ide> def get_line_header(str,beg):
<ide> extra = []
<del> ind = beg-1
<add> ind = beg - 1
<ide> char = str[ind]
<ide> while (ind > 0) and (char != '\n'):
<ide> extra.insert(0,char)
<ide> def get_line_header(str,beg):
<ide> return ''.join(extra)
<ide>
<ide> def process_str(allstr):
<del> newstr = allstr
<del> writestr = _head
<add> code = [header]
<add> struct = parse_structure(allstr)
<ide>
<del> struct = parse_structure(newstr)
<ide> # return a (sorted) list of tuples for each begin repeat section
<ide> # each tuple is the start and end of a region to be template repeated
<del>
<ide> oldend = 0
<ide> for sub in struct:
<del> writestr += newstr[oldend:sub[0]]
<del> expanded = expand_sub(newstr[sub[1]:sub[2]],
<del> newstr[sub[0]:sub[1]], sub[4])
<del> writestr += expanded
<add> pref = allstr[oldend:sub[0]]
<add> head = allstr[sub[0]:sub[1]]
<add> text = allstr[sub[1]:sub[2]]
<add> line = sub[4]
<ide> oldend = sub[3]
<add> code.append(pref)
<add> code.extend(expand_sub(text,head,line))
<add> code.append(allstr[oldend:])
<add> return ''.join(code)
<ide>
<ide>
<del> writestr += newstr[oldend:]
<del> return writestr
<del>
<ide> include_src_re = re.compile(r"(\n|\A)#include\s*['\"]"
<ide> r"(?P<name>[\w\d./\\]+[.]src)['\"]", re.I)
<ide>
<ide> def process_file(source):
<ide> return ('#line 1 "%s"\n%s'
<ide> % (sourcefile, process_str(''.join(lines))))
<ide>
<add>
<ide> if __name__ == "__main__":
<ide>
<ide> try:
<ide> def process_file(source):
<ide> allstr = fid.read()
<ide> writestr = process_str(allstr)
<ide> outfile.write(writestr)
<add> | 1 |
PHP | PHP | add deprecation warnings to the database package | 46de16e00f9789cf6d93c0be73e8e5c69e18cdc8 | <ide><path>src/Database/Connection.php
<ide> public function getDriver()
<ide> */
<ide> public function driver($driver = null, $config = [])
<ide> {
<add> deprecationWarning('Connection::driver() is deprecated. Use Connection::setDriver()/getDriver() instead.');
<ide> if ($driver !== null) {
<ide> $this->setDriver($driver, $config);
<ide> }
<ide> public function getSchemaCollection()
<ide> */
<ide> public function schemaCollection(SchemaCollection $collection = null)
<ide> {
<add> deprecationWarning(
<add> 'Connection::schemaCollection() is deprecated. ' .
<add> 'Use Connection::setSchemaCollection()/getSchemaCollection() instead.'
<add> );
<ide> if ($collection !== null) {
<ide> $this->setSchemaCollection($collection);
<ide> }
<ide> public function isSavePointsEnabled()
<ide> */
<ide> public function useSavePoints($enable = null)
<ide> {
<add> deprecationWarning(
<add> 'Connection::useSavePoints() is deprecated. ' .
<add> 'Use Connection::enableSavePoints()/isSavePointsEnabled() instead.'
<add> );
<ide> if ($enable !== null) {
<ide> $this->enableSavePoints($enable);
<ide> }
<ide> public function logQueries($enable = null)
<ide> */
<ide> public function logger($instance = null)
<ide> {
<add> deprecationWarning(
<add> 'Connection::logger() is deprecated. ' .
<add> 'Use Connection::setLogger()/getLogger() instead.'
<add> );
<ide> if ($instance === null) {
<ide> return $this->getLogger();
<ide> }
<ide><path>src/Database/Driver.php
<ide> public function isAutoQuotingEnabled()
<ide> */
<ide> public function autoQuoting($enable = null)
<ide> {
<add> deprecationWarning(
<add> 'Driver::autoQuoting() is deprecated. ' .
<add> 'Use Driver::enableAutoQuoting()/isAutoQuotingEnabled() instead.'
<add> );
<ide> if ($enable !== null) {
<ide> $this->enableAutoQuoting($enable);
<ide> }
<ide><path>src/Database/Expression/FunctionExpression.php
<ide> public function getName()
<ide> */
<ide> public function name($name = null)
<ide> {
<add> deprecationWarning(
<add> 'FunctionExpression::name() is deprecated. ' .
<add> 'Use FunctionExpression::setName()/getName() instead.'
<add> );
<ide> if ($name !== null) {
<ide> return $this->setName($name);
<ide> }
<ide><path>src/Database/Expression/QueryExpression.php
<ide> public function getConjunction()
<ide> */
<ide> public function tieWith($conjunction = null)
<ide> {
<add> deprecationWarning(
<add> 'QueryExpression::tieWith() is deprecated. ' .
<add> 'Use QueryExpression::setConjunction()/getConjunction() instead.'
<add> );
<ide> if ($conjunction !== null) {
<ide> return $this->setConjunction($conjunction);
<ide> }
<ide> public function tieWith($conjunction = null)
<ide> * @param string|null $conjunction value to be used for joining conditions. If null it
<ide> * will not set any value, but return the currently stored one
<ide> * @return string|$this
<del> * @deprecated 3.2.0 Use tieWith() instead
<add> * @deprecated 3.2.0 Use setConjunction()/getConjunction() instead
<ide> */
<ide> public function type($conjunction = null)
<ide> {
<add> deprecationWarning(
<add> 'QueryExpression::type() is deprecated. ' .
<add> 'Use QueryExpression::setConjunction()/getConjunction() instead.'
<add> );
<ide> return $this->tieWith($conjunction);
<ide> }
<ide>
<ide><path>src/Database/Expression/ValuesExpression.php
<ide> public function getColumns()
<ide> */
<ide> public function columns($cols = null)
<ide> {
<add> deprecationWarning(
<add> 'ValuesExpression::columns() is deprecated. ' .
<add> 'Use ValuesExpression::setColumns()/getColumns() instead.'
<add> );
<ide> if ($cols !== null) {
<ide> return $this->setColumns($cols);
<ide> }
<ide> public function getValues()
<ide> */
<ide> public function values($values = null)
<ide> {
<add> deprecationWarning(
<add> 'ValuesExpression::values() is deprecated. ' .
<add> 'Use ValuesExpression::setValues()/getValues() instead.'
<add> );
<ide> if ($values !== null) {
<ide> return $this->setValues($values);
<ide> }
<ide> public function getQuery()
<ide> */
<ide> public function query(Query $query = null)
<ide> {
<add> deprecationWarning(
<add> 'ValuesExpression::query() is deprecated. ' .
<add> 'Use ValuesExpression::setQuery()/getQuery() instead.'
<add> );
<ide> if ($query !== null) {
<ide> return $this->setQuery($query);
<ide> }
<ide><path>src/Database/IdentifierQuoter.php
<ide> public function __construct(Driver $driver)
<ide> public function quote(Query $query)
<ide> {
<ide> $binder = $query->getValueBinder();
<del> $query->valueBinder(false);
<add> $query->setValueBinder(false);
<ide>
<ide> if ($query->type() === 'insert') {
<ide> $this->_quoteInsert($query);
<ide> public function quote(Query $query)
<ide> }
<ide>
<ide> $query->traverseExpressions([$this, 'quoteExpression']);
<del> $query->valueBinder($binder);
<add> $query->setValueBinder($binder);
<ide>
<ide> return $query;
<ide> }
<ide><path>src/Database/Log/LoggingStatement.php
<ide> public function bindValue($column, $value, $type = 'string')
<ide> */
<ide> public function logger($instance = null)
<ide> {
<add> deprecationWarning(
<add> 'LoggingStatement::logger() is deprecated. ' .
<add> 'Use LoggingStatement::setLogger()/getLogger() instead.'
<add> );
<ide> if ($instance === null) {
<ide> return $this->getLogger();
<ide> }
<ide><path>src/Database/Query.php
<ide> public function getConnection()
<ide> */
<ide> public function connection($connection = null)
<ide> {
<add> deprecationWarning(
<add> 'Query::connection() is deprecated. ' .
<add> 'Use Query::setConnection()/getConnection() instead.'
<add> );
<ide> if ($connection !== null) {
<ide> return $this->setConnection($connection);
<ide> }
<ide> public function andWhere($conditions, $types = [])
<ide> */
<ide> public function orWhere($conditions, $types = [])
<ide> {
<add> deprecationWarning('Query::orWhere() is deprecated. Use Query::where() instead.');
<ide> $this->_conjugate('where', $conditions, 'OR', $types);
<ide>
<ide> return $this;
<ide> public function andHaving($conditions, $types = [])
<ide> */
<ide> public function orHaving($conditions, $types = [])
<ide> {
<add> deprecationWarning('Query::orHaving() is deprecated. Use Query::having() instead.');
<ide> $this->_conjugate('having', $conditions, 'OR', $types);
<ide>
<ide> return $this;
<ide> public function getValueBinder()
<ide> return $this->_valueBinder;
<ide> }
<ide>
<add> /**
<add> * Overwrite the current value binder
<add> *
<add> * A ValueBinder is responsible for generating query placeholders and temporarily
<add> * associate values to those placeholders so that they can be passed correctly
<add> * to the statement object.
<add> *
<add> * @param \Cake\Database\ValueBinder|bool $binder The binder or false to disable binding.
<add> * @return $this
<add> */
<add> public function setValueBinder($binder)
<add> {
<add> $this->_valueBinder = $binder;
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Returns the currently used ValueBinder instance. If a value is passed,
<ide> * it will be set as the new instance to be used.
<ide> public function getValueBinder()
<ide> * associate values to those placeholders so that they can be passed correctly
<ide> * to the statement object.
<ide> *
<del> * @deprecated 3.5.0 Use getValueBinder() for the getter part instead.
<add> * @deprecated 3.5.0 Use setValueBinder()/getValueBinder() instead.
<ide> * @param \Cake\Database\ValueBinder|null $binder new instance to be set. If no value is passed the
<ide> * default one will be returned
<ide> * @return $this|\Cake\Database\ValueBinder
<ide> */
<ide> public function valueBinder($binder = null)
<ide> {
<add> deprecationWarning('Query::valueBinder() is deprecated. Use Query::getValueBinder()/setValueBinder() instead.');
<ide> if ($binder === null) {
<ide> if ($this->_valueBinder === null) {
<ide> $this->_valueBinder = new ValueBinder();
<ide> public function isBufferedResultsEnabled()
<ide> */
<ide> public function bufferResults($enable = null)
<ide> {
<add> deprecationWarning(
<add> 'Query::bufferResults() is deprecated. ' .
<add> 'Use Query::enableBufferedResults()/isBufferedResultsEnabled() instead.'
<add> );
<ide> if ($enable !== null) {
<ide> return $this->enableBufferedResults($enable);
<ide> }
<ide> public function getSelectTypeMap()
<ide> */
<ide> public function selectTypeMap(TypeMap $typeMap = null)
<ide> {
<add> deprecationWarning(
<add> 'Query::selectTypeMap() is deprecated. ' .
<add> 'Use Query::setSelectTypeMap()/getSelectTypeMap() instead.'
<add> );
<ide> if ($typeMap !== null) {
<ide> return $this->setSelectTypeMap($typeMap);
<ide> }
<ide><path>src/Database/Schema/CachedCollection.php
<ide> public function getCacheMetadata()
<ide> */
<ide> public function cacheMetadata($enable = null)
<ide> {
<add> deprecationWarning(
<add> 'CachedCollection::cacheMetadata() is deprecated. ' .
<add> 'Use CachedCollection::setCacheMetadata()/getCacheMetadata() instead.'
<add> );
<ide> if ($enable !== null) {
<ide> $this->setCacheMetadata($enable);
<ide> }
<ide><path>src/Database/Schema/TableSchema.php
<ide> public function isTemporary()
<ide> */
<ide> public function temporary($temporary = null)
<ide> {
<add> deprecationWarning(
<add> 'TableSchema::temporary() is deprecated. ' .
<add> 'Use TableSchema::setTemporary()/getTemporary() instead.'
<add> );
<ide> if ($temporary !== null) {
<ide> return $this->setTemporary($temporary);
<ide> }
<ide><path>src/Database/Type.php
<ide> public function toPHP($value, Driver $driver)
<ide> */
<ide> protected function _basicTypeCast($value)
<ide> {
<add> deprecationWarning('Type::_basicTypeCast() is deprecated.');
<ide> if ($value === null) {
<ide> return null;
<ide> }
<ide> public function toStatement($value, Driver $driver)
<ide> */
<ide> public static function boolval($value)
<ide> {
<add> deprecationWarning('Type::boolval() is deprecated.');
<ide> if (is_string($value) && !is_numeric($value)) {
<ide> return strtolower($value) === 'true';
<ide> }
<ide> public static function boolval($value)
<ide> */
<ide> public static function strval($value)
<ide> {
<add> deprecationWarning('Type::strval() is deprecated.');
<ide> if (is_array($value)) {
<ide> $value = '';
<ide> }
<ide><path>src/Database/TypeMap.php
<ide> public function getDefaults()
<ide> */
<ide> public function defaults(array $defaults = null)
<ide> {
<add> deprecationWarning(
<add> 'TypeMap::defaults() is deprecated. ' .
<add> 'Use TypeMap::setDefaults()/getDefaults() instead.'
<add> );
<ide> if ($defaults !== null) {
<ide> return $this->setDefaults($defaults);
<ide> }
<ide> public function getTypes()
<ide> */
<ide> public function types(array $types = null)
<ide> {
<add> deprecationWarning(
<add> 'TypeMap::types() is deprecated. ' .
<add> 'Use TypeMap::setTypes()/getTypes() instead.'
<add> );
<ide> if ($types !== null) {
<ide> return $this->setTypes($types);
<ide> }
<ide><path>src/Database/TypeMapTrait.php
<ide> public function getTypeMap()
<ide> */
<ide> public function typeMap($typeMap = null)
<ide> {
<add> deprecationWarning(
<add> 'TypeMapTrait::typeMap() is deprecated. ' .
<add> 'Use TypeMapTrait::setTypeMap()/getTypeMap() instead.'
<add> );
<ide> if ($typeMap !== null) {
<ide> return $this->setTypeMap($typeMap);
<ide> }
<ide> public function getDefaultTypes()
<ide> */
<ide> public function defaultTypes(array $types = null)
<ide> {
<add> deprecationWarning(
<add> 'TypeMapTrait::defaultTypes() is deprecated. ' .
<add> 'Use TypeMapTrait::setDefaultTypes()/getDefaultTypes() instead.'
<add> );
<ide> if ($types !== null) {
<ide> return $this->setDefaultTypes($types);
<ide> }
<ide><path>src/Database/TypedResultTrait.php
<ide> public function setReturnType($type)
<ide> */
<ide> public function returnType($type = null)
<ide> {
<add> deprecationWarning(
<add> 'TypedResultTrait::returnType() is deprecated. ' .
<add> 'Use TypedResultTrait::setReturnType()/getReturnType() instead.'
<add> );
<ide> if ($type !== null) {
<ide> $this->_returnType = $type;
<ide>
<ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> public function load($test)
<ide>
<ide> try {
<ide> $createTables = function ($db, $fixtures) use ($test) {
<del> $tables = $db->schemaCollection()->listTables();
<add> $tables = $db->getSchemaCollection()->listTables();
<ide> $configName = $db->configName();
<ide> if (!isset($this->_insertionMap[$configName])) {
<ide> $this->_insertionMap[$configName] = [];
<ide> public function loadSingle($name, $db = null, $dropTables = true)
<ide> }
<ide>
<ide> if (!$this->isFixtureSetup($db->configName(), $fixture)) {
<del> $sources = $db->schemaCollection()->listTables();
<add> $sources = $db->getSchemaCollection()->listTables();
<ide> $this->_setupTable($fixture, $db, $sources, $dropTables);
<ide> }
<ide>
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> public function setUp()
<ide> public function tearDown()
<ide> {
<ide> Log::reset();
<del> $this->connection->useSavePoints(false);
<add> $this->connection->enableSavePoints(false);
<ide> unset($this->connection);
<ide> parent::tearDown();
<ide> }
<ide> public function testVirtualNestedTransaction3()
<ide> */
<ide> public function testSavePoints()
<ide> {
<del> $this->skipIf(!$this->connection->useSavePoints(true));
<add> $this->skipIf(!$this->connection->enableSavePoints(true));
<ide>
<ide> $this->connection->begin();
<ide> $this->connection->delete('things', ['id' => 1]);
<ide> public function testSavePoints()
<ide>
<ide> public function testSavePoints2()
<ide> {
<del> $this->skipIf(!$this->connection->useSavePoints(true));
<add> $this->skipIf(!$this->connection->enableSavePoints(true));
<ide> $this->connection->begin();
<ide> $this->connection->delete('things', ['id' => 1]);
<ide>
<ide> public function testInTransaction()
<ide> public function testInTransactionWithSavePoints()
<ide> {
<ide> $this->skipIf(
<del> $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
<add> $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver,
<ide> 'SQLServer fails when this test is included.'
<ide> );
<del> $this->skipIf(!$this->connection->useSavePoints(true));
<add> $this->skipIf(!$this->connection->enableSavePoints(true));
<ide> $this->connection->begin();
<ide> $this->assertTrue($this->connection->inTransaction());
<ide>
<ide> public function testQuoteIdentifier()
<ide> *
<ide> * @return void
<ide> */
<del> public function testLoggerDefault()
<add> public function testGetLoggerDefault()
<ide> {
<del> $logger = $this->connection->logger();
<add> $logger = $this->connection->getLogger();
<ide> $this->assertInstanceOf('Cake\Database\Log\QueryLogger', $logger);
<del> $this->assertSame($logger, $this->connection->logger());
<add> $this->assertSame($logger, $this->connection->getLogger());
<ide> }
<ide>
<ide> /**
<ide> * Tests that a custom logger object can be set
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> */
<ide> public function testSetLogger()
<ide> {
<del> $logger = new QueryLogger;
<del> $this->connection->logger($logger);
<del> $this->assertSame($logger, $this->connection->logger());
<add> $this->deprecated(function () {
<add> $logger = new QueryLogger;
<add> $this->connection->logger($logger);
<add> $this->assertSame($logger, $this->connection->logger());
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testLoggerDecorator()
<ide> {
<ide> $logger = new QueryLogger;
<ide> $this->connection->logQueries(true);
<del> $this->connection->logger($logger);
<add> $this->connection->setLogger($logger);
<ide> $st = $this->connection->prepare('SELECT 1');
<ide> $this->assertInstanceOf(LoggingStatement::class, $st);
<del> $this->assertSame($logger, $st->logger());
<add> $this->assertSame($logger, $st->getLogger());
<ide>
<ide> $this->connection->logQueries(false);
<ide> $st = $this->connection->prepare('SELECT 1');
<ide> public function testLogQueries()
<ide> public function testLogFunction()
<ide> {
<ide> $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
<del> $this->connection->logger($logger);
<add> $this->connection->setLogger($logger);
<ide> $logger->expects($this->once())->method('log')
<ide> ->with($this->logicalAnd(
<ide> $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
<ide> public function testLogBeginRollbackTransaction()
<ide> $connection->logQueries(true);
<ide>
<ide> $driver = $this->getMockFormDriver();
<del> $connection->driver($driver);
<add> $connection->setDriver($driver);
<ide>
<ide> $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
<del> $connection->logger($logger);
<add> $connection->setLogger($logger);
<ide> $logger->expects($this->at(0))->method('log')
<ide> ->with($this->logicalAnd(
<ide> $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
<ide> public function testLogCommitTransaction()
<ide> ->getMock();
<ide>
<ide> $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
<del> $connection->logger($logger);
<add> $connection->setLogger($logger);
<ide>
<ide> $logger->expects($this->at(1))->method('log')
<ide> ->with($this->logicalAnd(
<ide> public function testTransactionalWithException()
<ide> *
<ide> * @return void
<ide> */
<del> public function testSchemaCollection()
<add> public function testSetSchemaCollection()
<ide> {
<ide> $driver = $this->getMockFormDriver();
<ide> $connection = $this->getMockBuilder(Connection::class)
<ide> ->setMethods(['connect'])
<ide> ->setConstructorArgs([['driver' => $driver]])
<ide> ->getMock();
<ide>
<del> $schema = $connection->schemaCollection();
<add> $schema = $connection->getSchemaCollection();
<ide> $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
<ide>
<ide> $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
<ide> ->setConstructorArgs([$connection])
<ide> ->getMock();
<del> $connection->schemaCollection($schema);
<del> $this->assertSame($schema, $connection->schemaCollection());
<add> $connection->setSchemaCollection($schema);
<add> $this->assertSame($schema, $connection->getSchemaCollection());
<add> }
<add>
<add> /**
<add> * Tests it is possible to set a schema collection object
<add> *
<add> * @group deprecated
<add> * @return void
<add> */
<add> public function testSchemaCollection()
<add> {
<add> $this->deprecated(function () {
<add> $driver = $this->getMockFormDriver();
<add> $connection = $this->getMockBuilder(Connection::class)
<add> ->setMethods(['connect'])
<add> ->setConstructorArgs([['driver' => $driver]])
<add> ->getMock();
<add>
<add> $schema = $connection->schemaCollection();
<add> $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
<add>
<add> $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
<add> ->setConstructorArgs([$connection])
<add> ->getMock();
<add> $connection->schemaCollection($schema);
<add> $this->assertSame($schema, $connection->schemaCollection());
<add> });
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/DriverTest.php
<ide> public function testConstructor()
<ide> $arg = ['quoteIdentifiers' => true];
<ide> $driver = $this->getMockForAbstractClass(Driver::class, [$arg]);
<ide>
<del> $this->assertTrue($driver->autoQuoting());
<add> $this->assertTrue($driver->isAutoQuotingEnabled());
<ide>
<ide> $arg = ['username' => 'GummyBear'];
<ide> $driver = $this->getMockForAbstractClass(Driver::class, [$arg]);
<ide>
<del> $this->assertFalse($driver->autoQuoting());
<add> $this->assertFalse($driver->isAutoQuotingEnabled());
<ide> }
<ide>
<ide> /**
<ide> public function testIsConnected()
<ide> */
<ide> public function testAutoQuoting()
<ide> {
<del> $this->assertFalse($this->driver->autoQuoting());
<add> $this->assertFalse($this->driver->isAutoQuotingEnabled());
<ide>
<del> $this->driver->autoQuoting(true);
<del> $this->assertTrue($this->driver->autoQuoting());
<add> $this->assertSame($this->driver, $this->driver->enableAutoQuoting(true));
<add> $this->assertTrue($this->driver->isAutoQuotingEnabled());
<ide>
<del> $this->assertTrue($this->driver->autoQuoting(true));
<del> $this->assertFalse($this->driver->autoQuoting(false));
<add> $this->driver->enableAutoQuoting(false);
<add> $this->assertFalse($this->driver->isAutoQuotingEnabled());
<ide>
<del> $this->assertTrue($this->driver->autoQuoting('string'));
<del> $this->assertFalse($this->driver->autoQuoting('0'));
<add> $this->driver->enableAutoQuoting('string');
<add> $this->assertTrue($this->driver->isAutoQuotingEnabled());
<ide>
<del> $this->assertTrue($this->driver->autoQuoting(1));
<del> $this->assertFalse($this->driver->autoQuoting(0));
<add> $this->driver->enableAutoQuoting('0');
<add> $this->assertFalse($this->driver->isAutoQuotingEnabled());
<add>
<add> $this->driver->enableAutoQuoting(1);
<add> $this->assertTrue($this->driver->isAutoQuotingEnabled());
<add>
<add> $this->driver->enableAutoQuoting(0);
<add> $this->assertFalse($this->driver->isAutoQuotingEnabled());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Expression/QueryExpressionTest.php
<ide> public function testConjunction()
<ide> /**
<ide> * Test tieWith() works.
<ide> *
<add> * @group deprecated
<ide> * @return
<ide> */
<ide> public function testTieWith()
<ide> {
<del> $expr = new QueryExpression(['1', '2']);
<del> $binder = new ValueBinder();
<add> $this->deprecated(function () {
<add> $expr = new QueryExpression(['1', '2']);
<add> $binder = new ValueBinder();
<ide>
<del> $this->assertSame($expr, $expr->tieWith('+'));
<del> $this->assertSame('+', $expr->tieWith());
<add> $this->assertSame($expr, $expr->tieWith('+'));
<add> $this->assertSame('+', $expr->tieWith());
<ide>
<del> $result = $expr->sql($binder);
<del> $this->assertEquals('(1 + 2)', $result);
<add> $result = $expr->sql($binder);
<add> $this->assertEquals('(1 + 2)', $result);
<add> });
<ide> }
<ide>
<ide> /**
<ide> * Test type() works.
<ide> *
<add> * @group deprecated
<ide> * @return
<ide> */
<ide> public function testType()
<ide> {
<del> $expr = new QueryExpression(['1', '2']);
<del> $binder = new ValueBinder();
<add> $this->deprecated(function () {
<add> $expr = new QueryExpression(['1', '2']);
<add> $binder = new ValueBinder();
<ide>
<del> $this->assertSame($expr, $expr->type('+'));
<del> $this->assertSame('+', $expr->type());
<add> $this->assertSame($expr, $expr->type('+'));
<add> $this->assertSame('+', $expr->type());
<ide>
<del> $result = $expr->sql($binder);
<del> $this->assertEquals('(1 + 2)', $result);
<add> $result = $expr->sql($binder);
<add> $this->assertEquals('(1 + 2)', $result);
<add> });
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/ExpressionTypeCastingIntegrationTest.php
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<ide> $this->connection = ConnectionManager::get('test');
<del> $this->skipIf($this->connection->driver() instanceof Sqlserver, 'This tests uses functions specific to other drivers');
<add> $this->skipIf($this->connection->getDriver() instanceof Sqlserver, 'This tests uses functions specific to other drivers');
<ide> Type::map('ordered_uuid', OrderedUuidType::class);
<ide> }
<ide>
<ide> public function testInsert()
<ide> ->select('id')
<ide> ->from('ordered_uuid_items')
<ide> ->order('id')
<del> ->defaultTypes(['id' => 'ordered_uuid']);
<add> ->setDefaultTypes(['id' => 'ordered_uuid']);
<ide>
<del> $query->selectTypeMap($query->typeMap());
<add> $query->setSelectTypeMap($query->getTypeMap());
<ide> $results = $query->execute()->fetchAll('assoc');
<ide>
<ide> $this->assertEquals(new UuidValue('419a8da0482b7756b21f27da40cf8569'), $results[0]['id']);
<ide><path>tests/TestCase/Database/FunctionsBuilderTest.php
<ide> public function testArbitrary()
<ide> {
<ide> $function = $this->functions->MyFunc(['b' => 'literal']);
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<del> $this->assertEquals('MyFunc', $function->name());
<add> $this->assertEquals('MyFunc', $function->getName());
<ide> $this->assertEquals('MyFunc(b)', $function->sql(new ValueBinder));
<ide>
<ide> $function = $this->functions->MyFunc(['b'], ['string'], 'integer');
<del> $this->assertEquals('integer', $function->returnType());
<add> $this->assertEquals('integer', $function->getReturnType());
<ide> }
<ide>
<ide> /**
<ide> public function testSum()
<ide> $function = $this->functions->sum('total');
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('SUM(total)', $function->sql(new ValueBinder));
<del> $this->assertEquals('float', $function->returnType());
<add> $this->assertEquals('float', $function->getReturnType());
<ide>
<ide> $function = $this->functions->sum('total', ['integer']);
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('SUM(total)', $function->sql(new ValueBinder));
<del> $this->assertEquals('integer', $function->returnType());
<add> $this->assertEquals('integer', $function->getReturnType());
<ide> }
<ide>
<ide> /**
<ide> public function testAvg()
<ide> $function = $this->functions->avg('salary');
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('AVG(salary)', $function->sql(new ValueBinder));
<del> $this->assertEquals('float', $function->returnType());
<add> $this->assertEquals('float', $function->getReturnType());
<ide> }
<ide>
<ide> /**
<ide> public function testMAX()
<ide> $function = $this->functions->max('created', ['datetime']);
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('MAX(created)', $function->sql(new ValueBinder));
<del> $this->assertEquals('datetime', $function->returnType());
<add> $this->assertEquals('datetime', $function->getReturnType());
<ide> }
<ide>
<ide> /**
<ide> public function testMin()
<ide> $function = $this->functions->min('created', ['date']);
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('MIN(created)', $function->sql(new ValueBinder));
<del> $this->assertEquals('date', $function->returnType());
<add> $this->assertEquals('date', $function->getReturnType());
<ide> }
<ide>
<ide> /**
<ide> public function testCount()
<ide> $function = $this->functions->count('*');
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('COUNT(*)', $function->sql(new ValueBinder));
<del> $this->assertEquals('integer', $function->returnType());
<add> $this->assertEquals('integer', $function->getReturnType());
<ide> }
<ide>
<ide> /**
<ide> public function testConcat()
<ide> $function = $this->functions->concat(['title' => 'literal', ' is a string']);
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('CONCAT(title, :param0)', $function->sql(new ValueBinder));
<del> $this->assertEquals('string', $function->returnType());
<add> $this->assertEquals('string', $function->getReturnType());
<ide> }
<ide>
<ide> /**
<ide> public function testCoalesce()
<ide> $function = $this->functions->coalesce(['NULL' => 'literal', '1', 'a'], ['a' => 'date']);
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('COALESCE(NULL, :param0, :param1)', $function->sql(new ValueBinder));
<del> $this->assertEquals('date', $function->returnType());
<add> $this->assertEquals('date', $function->getReturnType());
<ide> }
<ide>
<ide> /**
<ide> public function testNow()
<ide> $function = $this->functions->now();
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('NOW()', $function->sql(new ValueBinder));
<del> $this->assertEquals('datetime', $function->returnType());
<add> $this->assertEquals('datetime', $function->getReturnType());
<ide>
<ide> $function = $this->functions->now('date');
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('CURRENT_DATE()', $function->sql(new ValueBinder));
<del> $this->assertEquals('date', $function->returnType());
<add> $this->assertEquals('date', $function->getReturnType());
<ide>
<ide> $function = $this->functions->now('time');
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('CURRENT_TIME()', $function->sql(new ValueBinder));
<del> $this->assertEquals('time', $function->returnType());
<add> $this->assertEquals('time', $function->getReturnType());
<ide> }
<ide>
<ide> /**
<ide> public function testExtract()
<ide> $function = $this->functions->extract('day', 'created');
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('EXTRACT(day FROM created)', $function->sql(new ValueBinder));
<del> $this->assertEquals('integer', $function->returnType());
<add> $this->assertEquals('integer', $function->getReturnType());
<ide>
<ide> $function = $this->functions->datePart('year', 'modified');
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('EXTRACT(year FROM modified)', $function->sql(new ValueBinder));
<del> $this->assertEquals('integer', $function->returnType());
<add> $this->assertEquals('integer', $function->getReturnType());
<ide> }
<ide>
<ide> /**
<ide> public function testDateAdd()
<ide> $function = $this->functions->dateAdd('created', -3, 'day');
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('DATE_ADD(created, INTERVAL -3 day)', $function->sql(new ValueBinder));
<del> $this->assertEquals('datetime', $function->returnType());
<add> $this->assertEquals('datetime', $function->getReturnType());
<ide> }
<ide>
<ide> /**
<ide> public function testDayOfWeek()
<ide> $function = $this->functions->dayOfWeek('created');
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('DAYOFWEEK(created)', $function->sql(new ValueBinder));
<del> $this->assertEquals('integer', $function->returnType());
<add> $this->assertEquals('integer', $function->getReturnType());
<ide>
<ide> $function = $this->functions->weekday('created');
<ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function);
<ide> $this->assertEquals('DAYOFWEEK(created)', $function->sql(new ValueBinder));
<del> $this->assertEquals('integer', $function->returnType());
<add> $this->assertEquals('integer', $function->getReturnType());
<ide> }
<ide> }
<ide><path>tests/TestCase/Database/Log/LoggingStatementTest.php
<ide> public function testExecuteNoParams()
<ide> ));
<ide> $st = new LoggingStatement($inner);
<ide> $st->queryString = 'SELECT bar FROM foo';
<del> $st->logger($logger);
<add> $st->setLogger($logger);
<ide> $st->execute();
<ide> }
<ide>
<ide> public function testExecuteWithParams()
<ide> ));
<ide> $st = new LoggingStatement($inner);
<ide> $st->queryString = 'SELECT bar FROM foo';
<del> $st->logger($logger);
<add> $st->setLogger($logger);
<ide> $st->execute(['a' => 1, 'b' => 2]);
<ide> }
<ide>
<ide> public function testExecuteWithBinding()
<ide> $driver = $this->getMockBuilder('\Cake\Database\Driver')->getMock();
<ide> $st = new LoggingStatement($inner, $driver);
<ide> $st->queryString = 'SELECT bar FROM foo';
<del> $st->logger($logger);
<add> $st->setLogger($logger);
<ide> $st->bindValue('a', 1);
<ide> $st->bindValue('b', $date, 'date');
<ide> $st->execute();
<ide> public function testExecuteWithError()
<ide> ));
<ide> $st = new LoggingStatement($inner);
<ide> $st->queryString = 'SELECT bar FROM foo';
<del> $st->logger($logger);
<add> $st->setLogger($logger);
<ide> $st->execute();
<ide> }
<ide>
<add> /**
<add> * Tests setting and getting the logger
<add> *
<add> * @group deprecated
<add> * @return void
<add> */
<add> public function testLoggerCompat()
<add> {
<add> $this->deprecated(function () {
<add> $logger = $this->getMockBuilder('\Cake\Database\Log\QueryLogger')->getMock();
<add> $st = new LoggingStatement();
<add>
<add> $this->assertNull($st->logger());
<add>
<add> $st->logger($logger);
<add> $this->assertSame($logger, $st->logger());
<add> });
<add> }
<add>
<ide> /**
<ide> * Tests setting and getting the logger
<ide> *
<ide><path>tests/TestCase/Database/QueryTest.php
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<ide> $this->connection = ConnectionManager::get('test');
<del> $this->autoQuote = $this->connection->driver()->autoQuoting();
<add> $this->autoQuote = $this->connection->getDriver()->isAutoQuotingEnabled();
<ide> }
<ide>
<ide> public function tearDown()
<ide> {
<ide> parent::tearDown();
<del> $this->connection->driver()->autoQuoting($this->autoQuote);
<add> $this->connection->getDriver()->enableAutoQuoting($this->autoQuote);
<ide> unset($this->connection);
<ide> }
<ide>
<ide> public function testDefaultType()
<ide> */
<ide> public function testSelectFieldsOnly()
<ide> {
<del> $this->connection->driver()->autoQuoting(false);
<add> $this->connection->getDriver()->enableAutoQuoting(false);
<ide> $query = new Query($this->connection);
<ide> $result = $query->select('1 + 1')->execute();
<ide> $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
<ide> public function testSelectFieldsOnly()
<ide> */
<ide> public function testSelectClosure()
<ide> {
<del> $this->connection->driver()->autoQuoting(false);
<add> $this->connection->getDriver()->enableAutoQuoting(false);
<ide> $query = new Query($this->connection);
<ide> $result = $query->select(function ($q) use ($query) {
<ide> $this->assertSame($query, $q);
<ide> public function testSelectRightJoin()
<ide> {
<ide> $this->loadFixtures('Articles', 'Comments');
<ide> $this->skipIf(
<del> $this->connection->driver() instanceof \Cake\Database\Driver\Sqlite,
<add> $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlite,
<ide> 'SQLite does not support RIGHT joins'
<ide> );
<ide> $query = new Query($this->connection);
<ide> public function testSelectWhereArrayTypeEmptyWithExpression()
<ide> /**
<ide> * Tests that Query::orWhere() can be used to concatenate conditions with OR
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> */
<ide> public function testSelectOrWhere()
<ide> {
<del> $this->loadFixtures('Comments');
<del> $query = new Query($this->connection);
<del> $result = $query
<del> ->select(['id'])
<del> ->from('comments')
<del> ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
<del> ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
<del> ->execute();
<del> $this->assertCount(2, $result);
<del> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<del> $this->assertEquals(['id' => 2], $result->fetch('assoc'));
<del> $result->closeCursor();
<add> $this->deprecated(function () {
<add> $this->loadFixtures('Comments');
<add> $query = new Query($this->connection);
<add> $result = $query
<add> ->select(['id'])
<add> ->from('comments')
<add> ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
<add> ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
<add> ->execute();
<add> $this->assertCount(2, $result);
<add> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<add> $this->assertEquals(['id' => 2], $result->fetch('assoc'));
<add> $result->closeCursor();
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testSelectAndWhere()
<ide> * Tests that combining Query::andWhere() and Query::orWhere() produces
<ide> * correct conditions nesting
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> */
<ide> public function testSelectExpressionNesting()
<ide> {
<del> $this->loadFixtures('Comments');
<del> $query = new Query($this->connection);
<del> $result = $query
<del> ->select(['id'])
<del> ->from('comments')
<del> ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
<del> ->orWhere(['id' => 2])
<del> ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
<del> ->execute();
<del> $this->assertCount(2, $result);
<del> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<del> $this->assertEquals(['id' => 2], $result->fetch('assoc'));
<del> $result->closeCursor();
<add> $this->deprecated(function () {
<add> $this->loadFixtures('Comments');
<add> $query = new Query($this->connection);
<add> $result = $query
<add> ->select(['id'])
<add> ->from('comments')
<add> ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
<add> ->orWhere(['id' => 2])
<add> ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
<add> ->execute();
<add> $this->assertCount(2, $result);
<add> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<add> $this->assertEquals(['id' => 2], $result->fetch('assoc'));
<add> $result->closeCursor();
<ide>
<del> $query = new Query($this->connection);
<del> $result = $query
<del> ->select(['id'])
<del> ->from('comments')
<del> ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
<del> ->orWhere(['id' => 2])
<del> ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
<del> ->orWhere(['created' => new \DateTime('2007-03-18 10:49:23')], ['created' => 'datetime'])
<del> ->execute();
<del> $this->assertCount(3, $result);
<del> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<del> $this->assertEquals(['id' => 2], $result->fetch('assoc'));
<del> $this->assertEquals(['id' => 3], $result->fetch('assoc'));
<del> $result->closeCursor();
<add> $query = new Query($this->connection);
<add> $result = $query
<add> ->select(['id'])
<add> ->from('comments')
<add> ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
<add> ->orWhere(['id' => 2])
<add> ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
<add> ->orWhere(['created' => new \DateTime('2007-03-18 10:49:23')], ['created' => 'datetime'])
<add> ->execute();
<add> $this->assertCount(3, $result);
<add> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<add> $this->assertEquals(['id' => 2], $result->fetch('assoc'));
<add> $this->assertEquals(['id' => 3], $result->fetch('assoc'));
<add> $result->closeCursor();
<add> });
<ide> }
<ide>
<ide> /**
<ide> * Tests that Query::orWhere() can be used without calling where() before
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> */
<ide> public function testSelectOrWhereNoPreviousCondition()
<ide> {
<del> $this->loadFixtures('Comments');
<del> $query = new Query($this->connection);
<del> $result = $query
<del> ->select(['id'])
<del> ->from('comments')
<del> ->orWhere(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
<del> ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
<del> ->execute();
<del> $this->assertCount(2, $result);
<del> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<del> $this->assertEquals(['id' => 2], $result->fetch('assoc'));
<del> $result->closeCursor();
<add> $this->deprecated(function () {
<add> $this->loadFixtures('Comments');
<add> $query = new Query($this->connection);
<add> $result = $query
<add> ->select(['id'])
<add> ->from('comments')
<add> ->orWhere(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
<add> ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
<add> ->execute();
<add> $this->assertCount(2, $result);
<add> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<add> $this->assertEquals(['id' => 2], $result->fetch('assoc'));
<add> $result->closeCursor();
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testSelectAndWhereUsingClosure()
<ide> * Tests that it is possible to pass a closure to orWhere() to build a set of
<ide> * conditions and return the expression to be used
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> */
<ide> public function testSelectOrWhereUsingClosure()
<ide> {
<del> $this->loadFixtures('Comments');
<del> $query = new Query($this->connection);
<del> $result = $query
<del> ->select(['id'])
<del> ->from('comments')
<del> ->where(['id' => '1'])
<del> ->orWhere(function ($exp) {
<del> return $exp->eq('created', new \DateTime('2007-03-18 10:47:23'), 'datetime');
<del> })
<del> ->execute();
<del> $this->assertCount(2, $result);
<del> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<del> $this->assertEquals(['id' => 2], $result->fetch('assoc'));
<del> $result->closeCursor();
<add> $this->deprecated(function () {
<add> $this->loadFixtures('Comments');
<add> $query = new Query($this->connection);
<add> $result = $query
<add> ->select(['id'])
<add> ->from('comments')
<add> ->where(['id' => '1'])
<add> ->orWhere(function ($exp) {
<add> return $exp->eq('created', new \DateTime('2007-03-18 10:47:23'), 'datetime');
<add> })
<add> ->execute();
<add> $this->assertCount(2, $result);
<add> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<add> $this->assertEquals(['id' => 2], $result->fetch('assoc'));
<add> $result->closeCursor();
<ide>
<del> $query = new Query($this->connection);
<del> $result = $query
<del> ->select(['id'])
<del> ->from('comments')
<del> ->where(['id' => '1'])
<del> ->orWhere(function ($exp) {
<del> return $exp
<del> ->eq('created', new \DateTime('2012-12-22 12:00'), 'datetime')
<del> ->eq('id', 3);
<del> })
<del> ->execute();
<del> $this->assertCount(1, $result);
<del> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<del> $result->closeCursor();
<add> $query = new Query($this->connection);
<add> $result = $query
<add> ->select(['id'])
<add> ->from('comments')
<add> ->where(['id' => '1'])
<add> ->orWhere(function ($exp) {
<add> return $exp
<add> ->eq('created', new \DateTime('2012-12-22 12:00'), 'datetime')
<add> ->eq('id', 3);
<add> })
<add> ->execute();
<add> $this->assertCount(1, $result);
<add> $this->assertEquals(['id' => 1], $result->fetch('assoc'));
<add> $result->closeCursor();
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testInClausePlaceholderGeneration()
<ide> ->from('comments')
<ide> ->where(['id IN' => [1, 2]])
<ide> ->sql();
<del> $bindings = $query->valueBinder()->bindings();
<add> $bindings = $query->getValueBinder()->bindings();
<ide> $this->assertArrayHasKey(':c0', $bindings);
<ide> $this->assertEquals('c0', $bindings[':c0']['placeholder']);
<ide> $this->assertArrayHasKey(':c1', $bindings);
<ide> public function testSelectHaving()
<ide> * Tests that Query::orHaving() can be used to concatenate conditions with OR
<ide> * in the having clause
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> */
<ide> public function testSelectOrHaving()
<ide> {
<del> $this->loadFixtures('Authors', 'Articles');
<del> $query = new Query($this->connection);
<del> $result = $query
<del> ->select(['total' => 'count(author_id)', 'author_id'])
<del> ->from('articles')
<del> ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
<del> ->group('author_id')
<del> ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
<del> ->orHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
<del> ->execute();
<del> $expected = [['total' => 1, 'author_id' => 3]];
<del> $this->assertEquals($expected, $result->fetchAll('assoc'));
<del>
<del> $query = new Query($this->connection);
<del> $result = $query
<del> ->select(['total' => 'count(author_id)', 'author_id'])
<del> ->from('articles')
<del> ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
<del> ->group('author_id')
<del> ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
<del> ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
<del> ->execute();
<del> $expected = [['total' => 2, 'author_id' => 1], ['total' => 1, 'author_id' => 3]];
<del> $this->assertEquals($expected, $result->fetchAll('assoc'));
<del>
<del> $query = new Query($this->connection);
<del> $result = $query
<del> ->select(['total' => 'count(author_id)', 'author_id'])
<del> ->from('articles')
<del> ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
<del> ->group('author_id')
<del> ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
<del> ->orHaving(function ($e) {
<del> return $e->add('count(author_id) = 1 + 1');
<del> })
<del> ->execute();
<del> $expected = [['total' => 2, 'author_id' => 1]];
<del> $this->assertEquals($expected, $result->fetchAll('assoc'));
<add> $this->deprecated(function () {
<add> $this->loadFixtures('Authors', 'Articles');
<add> $query = new Query($this->connection);
<add> $result = $query
<add> ->select(['total' => 'count(author_id)', 'author_id'])
<add> ->from('articles')
<add> ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
<add> ->group('author_id')
<add> ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
<add> ->orHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
<add> ->execute();
<add> $expected = [['total' => 1, 'author_id' => 3]];
<add> $this->assertEquals($expected, $result->fetchAll('assoc'));
<add>
<add> $query = new Query($this->connection);
<add> $result = $query
<add> ->select(['total' => 'count(author_id)', 'author_id'])
<add> ->from('articles')
<add> ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
<add> ->group('author_id')
<add> ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
<add> ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
<add> ->execute();
<add> $expected = [['total' => 2, 'author_id' => 1], ['total' => 1, 'author_id' => 3]];
<add> $this->assertEquals($expected, $result->fetchAll('assoc'));
<add>
<add> $query = new Query($this->connection);
<add> $result = $query
<add> ->select(['total' => 'count(author_id)', 'author_id'])
<add> ->from('articles')
<add> ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
<add> ->group('author_id')
<add> ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
<add> ->orHaving(function ($e) {
<add> return $e->add('count(author_id) = 1 + 1');
<add> })
<add> ->execute();
<add> $expected = [['total' => 2, 'author_id' => 1]];
<add> $this->assertEquals($expected, $result->fetchAll('assoc'));
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testUnionOrderBy()
<ide> {
<ide> $this->loadFixtures('Articles', 'Comments');
<ide> $this->skipIf(
<del> ($this->connection->driver() instanceof \Cake\Database\Driver\Sqlite ||
<del> $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver),
<add> ($this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlite ||
<add> $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver),
<ide> 'Driver does not support ORDER BY in UNIONed queries.'
<ide> );
<ide> $union = (new Query($this->connection))
<ide> public function testInsertSimple()
<ide> $result->closeCursor();
<ide>
<ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
<del> if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
<add> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
<ide> $this->assertCount(1, $result, '1 row should be inserted');
<ide> }
<ide>
<ide> public function testInsertSparseRow()
<ide> $result->closeCursor();
<ide>
<ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
<del> if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
<add> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
<ide> $this->assertCount(1, $result, '1 row should be inserted');
<ide> }
<ide>
<ide> public function testInsertMultipleRowsSparse()
<ide> $result->closeCursor();
<ide>
<ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
<del> if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
<add> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
<ide> $this->assertCount(2, $result, '2 rows should be inserted');
<ide> }
<ide>
<ide> public function testInsertFromSelect()
<ide> $result->closeCursor();
<ide>
<ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
<del> if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
<add> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
<ide> $this->assertCount(1, $result);
<ide> }
<ide>
<ide> public function testInsertExpressionValues()
<ide> $result->closeCursor();
<ide>
<ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
<del> if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
<add> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
<ide> $this->assertCount(1, $result);
<ide> }
<ide>
<ide> public function testInsertExpressionValues()
<ide> $result = $query->execute();
<ide> $result->closeCursor();
<ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
<del> if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
<add> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) {
<ide> $this->assertCount(1, $result);
<ide> }
<ide>
<ide> public function testDefaultTypes()
<ide> {
<ide> $this->loadFixtures('Comments');
<ide> $query = new Query($this->connection);
<del> $this->assertEquals([], $query->defaultTypes());
<add> $this->assertEquals([], $query->getDefaultTypes());
<ide> $types = ['id' => 'integer', 'created' => 'datetime'];
<del> $this->assertSame($query, $query->defaultTypes($types));
<del> $this->assertSame($types, $query->defaultTypes());
<add> $this->assertSame($query, $query->setDefaultTypes($types));
<add> $this->assertSame($types, $query->getDefaultTypes());
<ide>
<ide> $results = $query->select(['id', 'comment'])
<ide> ->from('comments')
<ide> public function testAppendDelete()
<ide> */
<ide> public function testQuotingSelectFieldsAndAlias()
<ide> {
<del> $this->connection->driver()->autoQuoting(true);
<add> $this->connection->getDriver()->enableAutoQuoting(true);
<ide> $query = new Query($this->connection);
<ide> $sql = $query->select(['something'])->sql();
<ide> $this->assertQuotedQuery('SELECT <something>$', $sql);
<ide> public function testQuotingSelectFieldsAndAlias()
<ide> */
<ide> public function testQuotingFromAndAlias()
<ide> {
<del> $this->connection->driver()->autoQuoting(true);
<add> $this->connection->getDriver()->enableAutoQuoting(true);
<ide> $query = new Query($this->connection);
<ide> $sql = $query->select('*')->from(['something'])->sql();
<ide> $this->assertQuotedQuery('FROM <something>', $sql);
<ide> public function testQuotingFromAndAlias()
<ide> */
<ide> public function testQuotingDistinctOn()
<ide> {
<del> $this->connection->driver()->autoQuoting(true);
<add> $this->connection->getDriver()->enableAutoQuoting(true);
<ide> $query = new Query($this->connection);
<ide> $sql = $query->select('*')->distinct(['something'])->sql();
<ide> $this->assertQuotedQuery('<something>', $sql);
<ide> public function testQuotingDistinctOn()
<ide> */
<ide> public function testQuotingJoinsAndAlias()
<ide> {
<del> $this->connection->driver()->autoQuoting(true);
<add> $this->connection->getDriver()->enableAutoQuoting(true);
<ide> $query = new Query($this->connection);
<ide> $sql = $query->select('*')->join(['something'])->sql();
<ide> $this->assertQuotedQuery('JOIN <something>', $sql);
<ide> public function testQuotingJoinsAndAlias()
<ide> */
<ide> public function testQuotingGroupBy()
<ide> {
<del> $this->connection->driver()->autoQuoting(true);
<add> $this->connection->getDriver()->enableAutoQuoting(true);
<ide> $query = new Query($this->connection);
<ide> $sql = $query->select('*')->group(['something'])->sql();
<ide> $this->assertQuotedQuery('GROUP BY <something>', $sql);
<ide> public function testQuotingGroupBy()
<ide> */
<ide> public function testQuotingExpressions()
<ide> {
<del> $this->connection->driver()->autoQuoting(true);
<add> $this->connection->getDriver()->enableAutoQuoting(true);
<ide> $query = new Query($this->connection);
<ide> $sql = $query->select('*')
<ide> ->where(['something' => 'value'])
<ide> public function testQuotingExpressions()
<ide> */
<ide> public function testQuotingInsert()
<ide> {
<del> $this->connection->driver()->autoQuoting(true);
<add> $this->connection->getDriver()->enableAutoQuoting(true);
<ide> $query = new Query($this->connection);
<ide> $sql = $query->insert(['bar', 'baz'])
<ide> ->into('foo')
<ide> public function testDebugInfo()
<ide> {
<ide> $query = (new Query($this->connection))->select('*')
<ide> ->from('articles')
<del> ->defaultTypes(['id' => 'integer'])
<add> ->setDefaultTypes(['id' => 'integer'])
<ide> ->where(['id' => '1']);
<ide>
<ide> $expected = [
<ide> public function testIsNullWithExpressions()
<ide> */
<ide> public function testIsNullAutoQuoting()
<ide> {
<del> $this->connection->driver()->autoQuoting(true);
<add> $this->connection->getDriver()->enableAutoQuoting(true);
<ide> $query = new Query($this->connection);
<ide> $query->select('*')->from('things')->where(function ($exp) {
<ide> return $exp->isNull('field');
<ide> public function testSqlCaseStatement()
<ide> );
<ide>
<ide> //Postgres requires the case statement to be cast to a integer
<del> if ($this->connection->driver() instanceof \Cake\Database\Driver\Postgres) {
<add> if ($this->connection->getDriver() instanceof \Cake\Database\Driver\Postgres) {
<ide> $publishedCase = $query->func()->cast([$publishedCase, 'integer' => 'literal'])->type(' AS ');
<ide> $notPublishedCase = $query->func()->cast([$notPublishedCase, 'integer' => 'literal'])->type(' AS ');
<ide> }
<ide> public function testUnbufferedQuery()
<ide> $query = new Query($this->connection);
<ide> $result = $query->select(['body', 'author_id'])
<ide> ->from('articles')
<del> ->bufferResults(false)
<add> ->enableBufferedResults(false)
<ide> ->execute();
<ide>
<ide> if (!method_exists($result, 'bufferResults')) {
<ide> public function testDeepClone()
<ide> $this->assertNotEquals($query->clause('order'), $dupe->clause('order'));
<ide>
<ide> $this->assertNotSame(
<del> $query->selectTypeMap(),
<del> $dupe->selectTypeMap()
<add> $query->getSelectTypeMap(),
<add> $dupe->getSelectTypeMap()
<ide> );
<ide> }
<ide>
<ide> public function testDeepClone()
<ide> public function testSelectTypeMap()
<ide> {
<ide> $query = new Query($this->connection);
<del> $typeMap = $query->selectTypeMap();
<add> $typeMap = $query->getSelectTypeMap();
<ide> $this->assertInstanceOf(TypeMap::class, $typeMap);
<ide> $another = clone $typeMap;
<del> $query->selectTypeMap($another);
<del> $this->assertSame($another, $query->selectTypeMap());
<add> $query->setSelectTypeMap($another);
<add> $this->assertSame($another, $query->getSelectTypeMap());
<ide> }
<ide>
<ide> /**
<ide> public function testSelectTypeConversion()
<ide> ->select(['id', 'comment', 'the_date' => 'created'])
<ide> ->from('comments')
<ide> ->limit(1)
<del> ->selectTypeMap()->types(['id' => 'integer', 'the_date' => 'datetime']);
<add> ->getSelectTypeMap()->setTypes(['id' => 'integer', 'the_date' => 'datetime']);
<ide> $result = $query->execute()->fetchAll('assoc');
<ide> $this->assertInternalType('integer', $result[0]['id']);
<ide> $this->assertInstanceOf('DateTime', $result[0]['the_date']);
<ide> public function testSymmetricJsonType()
<ide> ->select(['comment'])
<ide> ->from('comments')
<ide> ->where(['id' => $id])
<del> ->selectTypeMap()->types(['comment' => 'json']);
<add> ->getSelectTypeMap()->setTypes(['comment' => 'json']);
<ide>
<ide> $result = $query->execute();
<ide> $comment = $result->fetchAll('assoc')[0]['comment'];
<ide> public function testBetweenExpressionAndTypeMap()
<ide> $query = new Query($this->connection);
<ide> $query->select('id')
<ide> ->from('comments')
<del> ->defaultTypes(['created' => 'datetime'])
<add> ->setDefaultTypes(['created' => 'datetime'])
<ide> ->where(function ($expr) {
<ide> $from = new \DateTime('2007-03-18 10:45:00');
<ide> $to = new \DateTime('2007-03-18 10:48:00');
<ide><path>tests/TestCase/Database/Schema/CollectionTest.php
<ide> public function testDescribeIncorrectTable()
<ide> */
<ide> public function testDescribeCache()
<ide> {
<del> $schema = $this->connection->schemaCollection();
<add> $schema = $this->connection->getSchemaCollection();
<ide> $table = $schema->describe('users');
<ide>
<ide> Cache::delete('test_users', '_cake_model_');
<ide> $this->connection->cacheMetadata(true);
<del> $schema = $this->connection->schemaCollection();
<add> $schema = $this->connection->getSchemaCollection();
<ide>
<ide> $result = $schema->describe('users');
<ide> $this->assertEquals($table, $result);
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public function testCreateTemporary()
<ide> 'type' => 'integer',
<ide> 'null' => false
<ide> ]);
<del> $table->temporary(true);
<add> $table->setTemporary(true);
<ide> $sql = $table->createSql($connection);
<ide> $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
<ide> }
<ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> public function testCreateTemporary()
<ide> 'type' => 'integer',
<ide> 'null' => false
<ide> ]);
<del> $table->temporary(true);
<add> $table->setTemporary(true);
<ide> $sql = $table->createSql($connection);
<ide> $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
<ide> }
<ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> public function testCreateTemporary()
<ide> 'type' => 'integer',
<ide> 'null' => false
<ide> ]);
<del> $table->temporary(true);
<add> $table->setTemporary(true);
<ide> $sql = $table->createSql($connection);
<ide> $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
<ide> }
<ide><path>tests/TestCase/Database/Schema/TableTest.php
<ide> public function testAddConstraintForeignKeyBadData($data)
<ide> * @return void
<ide> */
<ide> public function testTemporary()
<add> {
<add> $this->deprecated(function () {
<add> $table = new Table('articles');
<add> $this->assertFalse($table->temporary());
<add> $this->assertSame($table, $table->temporary(true));
<add> $this->assertTrue($table->temporary());
<add> $table->temporary(false);
<add> $this->assertFalse($table->temporary());
<add> });
<add> }
<add>
<add> /**
<add> * Tests the setTemporary() & isTemporary() method
<add> *
<add> * @return void
<add> */
<add> public function testSetTemporary()
<ide> {
<ide> $table = new Table('articles');
<del> $this->assertFalse($table->temporary());
<del> $this->assertSame($table, $table->temporary(true));
<del> $this->assertTrue($table->temporary());
<del> $table->temporary(false);
<del> $this->assertFalse($table->temporary());
<add> $this->assertFalse($table->isTemporary());
<add> $this->assertSame($table, $table->setTemporary(true));
<add> $this->assertTrue($table->isTemporary());
<add>
<add> $table->setTemporary(false);
<add> $this->assertFalse($table->isTemporary());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/SchemaCacheTest.php
<ide> public function testClearEnablesMetadataCache()
<ide> $ormCache = new SchemaCache($ds);
<ide> $ormCache->clear();
<ide>
<del> $this->assertInstanceOf('Cake\Database\Schema\CachedCollection', $ds->schemaCollection());
<add> $this->assertInstanceOf(CachedCollection::class, $ds->getSchemaCollection());
<ide> }
<ide>
<ide> /**
<ide> public function testBuildEnablesMetadataCache()
<ide> $ormCache = new SchemaCache($ds);
<ide> $ormCache->build();
<ide>
<del> $this->assertInstanceOf('Cake\Database\Schema\CachedCollection', $ds->schemaCollection());
<add> $this->assertInstanceOf(CachedCollection::class, $ds->getSchemaCollection());
<ide> }
<ide>
<ide> /** | 28 |
Javascript | Javascript | fix premature destroy | 7b6c4283d26079bb6fd3d300d0ac952a087d8a7b | <ide><path>lib/internal/http2/core.js
<ide> class Http2Stream extends Duplex {
<ide> }
<ide>
<ide> // TODO(mcollina): remove usage of _*State properties
<del> if (!this.writable) {
<add> if (this._writableState.finished) {
<ide> if (!this.readable && this.closed) {
<ide> this.destroy();
<ide> return; | 1 |
PHP | PHP | commit file missed earlier | 7cd2d245c476b7345bad782ef28934fd18dadaa9 | <ide><path>tests/test_app/TestApp/View/Widget/TestUsingViewWidget.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> * 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.0.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace TestApp\View\Widget;
<add>
<add>use Cake\View\Form\ContextInterface;
<add>use Cake\View\StringTemplate;
<add>use Cake\View\View;
<add>use Cake\View\Widget\WidgetInterface;
<add>
<add>class TestUsingViewWidget implements WidgetInterface
<add>{
<add> protected $_templates;
<add>
<add> protected $_view;
<add>
<add> public function __construct(StringTemplate $templates, View $view)
<add> {
<add> $this->_templates = $templates;
<add> $this->_view = $view;
<add> }
<add>
<add> public function getView(): View
<add> {
<add> return $this->_view;
<add> }
<add>
<add> public function render(array $data, ContextInterface $context): string
<add> {
<add> return '<success></success>';
<add> }
<add>
<add> public function secureFields(array $data): array
<add> {
<add> if (!isset($data['name']) || $data['name'] === '') {
<add> return [];
<add> }
<add>
<add> return [$data['name']];
<add> }
<add>} | 1 |
Go | Go | prevent journald from being built on arm | 6f6f10a75f8b447637e8a89d685452871899e9c0 | <ide><path>daemon/logger/journald/journald.go
<del>// +build linux
<add>// +build linux,!arm
<ide>
<ide> // Package journald provides the log driver for forwarding server logs
<ide> // to endpoints that receive the systemd format.
<ide><path>daemon/logger/journald/journald_unsupported.go
<del>// +build !linux
<add>// +build !linux linux,arm
<ide>
<ide> package journald
<ide>
<ide><path>daemon/logger/journald/read.go
<del>// +build linux,cgo,!static_build,journald
<add>// +build linux,cgo,!static_build,journald,!arm
<ide>
<ide> package journald
<ide>
<ide><path>daemon/logger/journald/read_unsupported.go
<del>// +build !linux !cgo static_build !journald
<add>// +build !linux !cgo static_build !journald linux,arm
<ide>
<ide> package journald
<ide> | 4 |
Python | Python | add tests for complexwarning in astype | b4397571d9a43ccd9ae237294e41384442b3e71b | <ide><path>numpy/core/tests/test_api.py
<ide> import sys
<ide>
<ide> import numpy as np
<add>import pytest
<ide> from numpy.testing import (
<del> assert_, assert_equal, assert_array_equal, assert_raises, HAS_REFCOUNT
<add> assert_, assert_equal, assert_array_equal, assert_raises, assert_warns,
<add> HAS_REFCOUNT
<ide> )
<ide>
<ide> # Switch between new behaviour when NPY_RELAXED_STRIDES_CHECKING is set.
<ide> class MyNDArray(np.ndarray):
<ide> a = np.array(1000, dtype='i4')
<ide> assert_raises(TypeError, a.astype, 'U1', casting='safe')
<ide>
<add>@pytest.mark.parametrize("t",
<add> np.sctypes['uint'] + np.sctypes['int'] + np.sctypes['float']
<add>)
<add>def test_array_astype_warning(t):
<add> # test ComplexWarning when casting from complex to float or int
<add> a = np.array(10, dtype=np.complex)
<add> assert_warns(np.ComplexWarning, a.astype, t)
<add>
<ide> def test_copyto_fromscalar():
<ide> a = np.arange(6, dtype='f4').reshape(2, 3)
<ide> | 1 |
Java | Java | delete unused imports in spring-test | 2f039454107ad0ed67f31a38d7b11a4f9318a5b1 | <ide><path>spring-test/src/test/java/org/springframework/test/context/testng/transaction/programmatic/ProgrammaticTxMgmtTestNGTests.java
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.List;
<del>import javax.sql.DataSource;
<ide>
<del>import org.testng.IHookCallBack;
<del>import org.testng.ITestResult;
<del>import org.testng.annotations.Test;
<add>import javax.sql.DataSource;
<ide>
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.transaction.PlatformTransactionManager;
<ide> import org.springframework.transaction.annotation.Propagation;
<ide> import org.springframework.transaction.annotation.Transactional;
<add>import org.testng.IHookCallBack;
<add>import org.testng.ITestResult;
<add>import org.testng.annotations.Test;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.junit.Assert.fail;
<ide> import static org.springframework.test.transaction.TransactionTestUtils.*;
<ide>
<ide> /**
<ide><path>spring-test/src/test/java/org/springframework/test/context/transaction/programmatic/ProgrammaticTxMgmtTests.java
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.List;
<add>
<ide> import javax.sql.DataSource;
<ide>
<ide> import org.junit.Rule;
<ide> import org.junit.Test;
<ide> import org.junit.rules.TestName;
<del>
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.jdbc.datasource.DataSourceTransactionManager;
<ide> import org.springframework.transaction.annotation.Transactional;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.junit.Assert.fail;
<ide> import static org.springframework.test.transaction.TransactionTestUtils.*;
<ide>
<ide> /**
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java
<ide>
<ide> import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
<ide> import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
<del>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
<ide> import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
<ide>
<ide> /** | 3 |
Ruby | Ruby | fix regexp encoding under 1.9/2.0 | b38d555030ea8c09fd3fd0bba9c11f458908ec99 | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def compression_type
<ide>
<ide> # Get enough of the file to detect common file types
<ide> # POSIX tar magic has a 257 byte offset
<del> magic_bytes = nil
<del> File.open(self) { |f| magic_bytes = f.read(262) }
<del>
<ide> # magic numbers stolen from /usr/share/file/magic/
<del> case magic_bytes
<del> when /^PK\003\004/ then :zip
<del> when /^\037\213/ then :gzip
<del> when /^BZh/ then :bzip2
<del> when /^\037\235/ then :compress
<del> when /^.{257}ustar/ then :tar
<del> when /^\xFD7zXZ\x00/ then :xz
<del> when /^Rar!/ then :rar
<add> case open { |f| f.read(262) }
<add> when /^PK\003\004/n then :zip
<add> when /^\037\213/n then :gzip
<add> when /^BZh/n then :bzip2
<add> when /^\037\235/n then :compress
<add> when /^.{257}ustar/n then :tar
<add> when /^\xFD7zXZ\x00/n then :xz
<add> when /^Rar!/n then :rar
<ide> else
<ide> # This code so that bad-tarballs and zips produce good error messages
<ide> # when they don't unarchive properly. | 1 |
Python | Python | add test for interval timetable catchup=false | 205219c522b77abe9d36d51807c32189c900cfd4 | <ide><path>airflow/timetables/interval.py
<ide> def next_dagrun_info(
<ide> earliest = restriction.earliest
<ide> if not restriction.catchup:
<ide> earliest = self._skip_to_latest(earliest)
<add> elif earliest is not None:
<add> earliest = self._align(earliest)
<ide> if last_automated_data_interval is None:
<ide> # First run; schedule the run at the first available time matching
<ide> # the schedule, and retrospectively create a data interval for it.
<ide> if earliest is None:
<ide> return None
<del> start = self._align(earliest)
<del> else:
<del> # There's a previous run.
<add> start = earliest
<add> else: # There's a previous run.
<ide> if earliest is not None:
<ide> # Catchup is False or DAG has new start date in the future.
<del> # Make sure we get the latest start date
<add> # Make sure we get the later one.
<ide> start = max(last_automated_data_interval.end, earliest)
<ide> else:
<del> # Create a data interval starting from when the end of the previous interval.
<add> # Data interval starts from the end of the previous interval.
<ide> start = last_automated_data_interval.end
<del>
<ide> if restriction.latest is not None and start > restriction.latest:
<ide> return None
<ide> end = self._get_next(start)
<ide> def _get_prev(self, current: DateTime) -> DateTime:
<ide> def _align(self, current: DateTime) -> DateTime:
<ide> """Get the next scheduled time.
<ide>
<del> This is ``current + interval``, unless ``current`` is first interval,
<del> then ``current`` is returned.
<add> This is ``current + interval``, unless ``current`` falls right on the
<add> interval boundary, when ``current`` is returned.
<ide> """
<ide> next_time = self._get_next(current)
<ide> if self._get_prev(next_time) != current:
<ide> def _skip_to_latest(self, earliest: Optional[DateTime]) -> DateTime:
<ide>
<ide> This is slightly different from the delta version at terminal values.
<ide> If the next schedule should start *right now*, we want the data interval
<del> that start right now now, not the one that ends now.
<add> that start now, not the one that ends now.
<ide> """
<ide> current_time = DateTime.utcnow()
<del> next_start = self._get_next(current_time)
<ide> last_start = self._get_prev(current_time)
<del> if next_start == current_time:
<add> next_start = self._get_next(last_start)
<add> if next_start == current_time: # Current time is on interval boundary.
<ide> new_start = last_start
<del> elif next_start > current_time:
<add> elif next_start > current_time: # Current time is between boundaries.
<ide> new_start = self._get_prev(last_start)
<ide> else:
<ide> raise AssertionError("next schedule shouldn't be earlier")
<ide><path>tests/jobs/test_scheduler_job.py
<ide> def test_should_mark_dummy_task_as_success(self):
<ide> assert start_date is None
<ide> assert end_date is None
<ide> assert duration is None
<add>
<add> def test_catchup_works_correctly(self, dag_maker):
<add> """Test that catchup works correctly"""
<add> session = settings.Session()
<add> with dag_maker(
<add> dag_id='test_catchup_schedule_dag',
<add> schedule_interval=timedelta(days=1),
<add> start_date=DEFAULT_DATE,
<add> catchup=True,
<add> max_active_runs=1,
<add> session=session,
<add> ) as dag:
<add> DummyOperator(task_id='dummy')
<add>
<add> self.scheduler_job = SchedulerJob(subdir=os.devnull)
<add> self.scheduler_job.executor = MockExecutor()
<add> self.scheduler_job.processor_agent = mock.MagicMock(spec=DagFileProcessorAgent)
<add>
<add> self.scheduler_job._create_dag_runs([dag_maker.dag_model], session)
<add> self.scheduler_job._start_queued_dagruns(session)
<add> # first dagrun execution date is DEFAULT_DATE 2016-01-01T00:00:00+00:00
<add> dr = DagRun.find(execution_date=DEFAULT_DATE, session=session)[0]
<add> ti = dr.get_task_instance(task_id='dummy')
<add> ti.state = State.SUCCESS
<add> session.merge(ti)
<add> session.flush()
<add>
<add> self.scheduler_job._schedule_dag_run(dr, session)
<add> session.flush()
<add>
<add> # Run the second time so _update_dag_next_dagrun will run
<add> self.scheduler_job._schedule_dag_run(dr, session)
<add> session.flush()
<add>
<add> dag.catchup = False
<add> dag.sync_to_db()
<add> assert not dag.catchup
<add>
<add> dm = DagModel.get_dagmodel(dag.dag_id)
<add> self.scheduler_job._create_dag_runs([dm], session)
<add>
<add> # Check catchup worked correctly by ensuring execution_date is quite new
<add> # Our dag is a daily dag
<add> assert (
<add> session.query(DagRun.execution_date)
<add> .filter(DagRun.execution_date != DEFAULT_DATE) # exclude the first run
<add> .scalar()
<add> ) > (timezone.utcnow() - timedelta(days=2))
<ide><path>tests/timetables/test_interval_timetable.py
<add>#
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>import datetime
<add>from typing import Optional
<add>
<add>import freezegun
<add>import pendulum
<add>import pytest
<add>
<add>from airflow.settings import TIMEZONE
<add>from airflow.timetables.base import DagRunInfo, DataInterval, TimeRestriction, Timetable
<add>from airflow.timetables.interval import CronDataIntervalTimetable, DeltaDataIntervalTimetable
<add>
<add>START_DATE = pendulum.DateTime(2021, 9, 4, tzinfo=TIMEZONE)
<add>
<add>PREV_DATA_INTERVAL_START = START_DATE
<add>PREV_DATA_INTERVAL_END = START_DATE + datetime.timedelta(days=1)
<add>PREV_DATA_INTERVAL = DataInterval(start=PREV_DATA_INTERVAL_START, end=PREV_DATA_INTERVAL_END)
<add>
<add>CURRENT_TIME = pendulum.DateTime(2021, 9, 7, tzinfo=TIMEZONE)
<add>
<add>HOURLY_CRON_TIMETABLE = CronDataIntervalTimetable("@hourly", TIMEZONE)
<add>HOURLY_DELTA_TIMETABLE = DeltaDataIntervalTimetable(datetime.timedelta(hours=1))
<add>
<add>
<add>@pytest.mark.parametrize(
<add> "timetable",
<add> [pytest.param(HOURLY_CRON_TIMETABLE, id="cron"), pytest.param(HOURLY_DELTA_TIMETABLE, id="delta")],
<add>)
<add>@pytest.mark.parametrize(
<add> "last_automated_data_interval",
<add> [pytest.param(None, id="first-run"), pytest.param(PREV_DATA_INTERVAL, id="subsequent")],
<add>)
<add>@freezegun.freeze_time(CURRENT_TIME)
<add>def test_no_catchup_next_info_starts_at_current_time(
<add> timetable: Timetable,
<add> last_automated_data_interval: Optional[DataInterval],
<add>) -> None:
<add> """If ``catchup=False``, the next data interval ends at the current time."""
<add> next_info = timetable.next_dagrun_info(
<add> last_automated_data_interval=last_automated_data_interval,
<add> restriction=TimeRestriction(earliest=START_DATE, latest=None, catchup=False),
<add> )
<add> expected_start = CURRENT_TIME - datetime.timedelta(hours=1)
<add> assert next_info == DagRunInfo.interval(start=expected_start, end=CURRENT_TIME)
<add>
<add>
<add>@pytest.mark.parametrize(
<add> "timetable",
<add> [pytest.param(HOURLY_CRON_TIMETABLE, id="cron"), pytest.param(HOURLY_DELTA_TIMETABLE, id="delta")],
<add>)
<add>def test_catchup_next_info_starts_at_previous_interval_end(timetable: Timetable) -> None:
<add> """If ``catchup=True``, the next interval starts at the previous's end."""
<add> next_info = timetable.next_dagrun_info(
<add> last_automated_data_interval=PREV_DATA_INTERVAL,
<add> restriction=TimeRestriction(earliest=START_DATE, latest=None, catchup=True),
<add> )
<add> expected_end = PREV_DATA_INTERVAL_END + datetime.timedelta(hours=1)
<add> assert next_info == DagRunInfo.interval(start=PREV_DATA_INTERVAL_END, end=expected_end) | 3 |
PHP | PHP | add a test for mapping not-test files to nothing | 230d67976d8824247900db6e715f534cb76c4999 | <ide><path>lib/Cake/Test/Case/Console/Command/TestShellTest.php
<ide> public function testMapPluginTestToCase() {
<ide> $this->assertSame('Controller/ExampleController', $return);
<ide> }
<ide>
<add>/**
<add> * testMapNotTestToNothing
<add> *
<add> * @return void
<add> */
<add> public function testMapNotTestToNothing() {
<add> $this->Shell->startup();
<add>
<add> $return = $this->Shell->mapFileToCategory(APP . 'Test/Case/NotATestFile.php', false);
<add> $this->assertFalse($return);
<add>
<add> $return = $this->Shell->mapFileToCase(APP . 'Test/Case/NotATestFile.php', false, false);
<add> $this->assertFalse($return);
<add> }
<add>
<ide> /**
<ide> * test available list of test cases for an empty category
<ide> * | 1 |
Text | Text | add lookup to http.request() options | 5bd6f516d82d069ff8710b86108dedc333b2b580 | <ide><path>doc/api/http.md
<ide> changes:
<ide> * `hostname` {string} Alias for `host`. To support [`url.parse()`][],
<ide> `hostname` will be used if both `host` and `hostname` are specified.
<ide> * `localAddress` {string} Local interface to bind for network connections.
<add> * `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].
<ide> * `method` {string} A string specifying the HTTP request method. **Default:**
<ide> `'GET'`.
<ide> * `path` {string} Request path. Should include query string if any.
<ide> not abort the request or do anything besides add a `'timeout'` event.
<ide> [`agent.createConnection()`]: #http_agent_createconnection_options_callback
<ide> [`agent.getName()`]: #http_agent_getname_options
<ide> [`destroy()`]: #http_agent_destroy
<add>[`dns.lookup()`]: dns.html#dns_dns_lookup_hostname_options_callback
<ide> [`'finish'`]: #http_event_finish
<ide> [`getHeader(name)`]: #http_request_getheader_name
<ide> [`http.Agent`]: #http_class_http_agent | 1 |
Java | Java | add problemdetail and `@exceptionhandler` support | 714d4512607d87a1d187d57b10ca9d1e336dbd84 | <ide><path>spring-web/src/main/java/org/springframework/http/ProblemDetail.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http;
<add>
<add>import java.net.URI;
<add>
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<add>
<add>/**
<add> * Representation of an RFC 7807 problem detail, including all RFC-defined
<add> * fields. For an extended response with more fields, create a subclass that
<add> * exposes the additional fields.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 6.0
<add> *
<add> * @see <a href="https://datatracker.ietf.org/doc/html/rfc7807">RFC 7807</a>
<add> * @see org.springframework.web.ErrorResponse
<add> * @see org.springframework.web.ErrorResponseException
<add> */
<add>public class ProblemDetail {
<add>
<add> private static final URI BLANK_TYPE = URI.create("about:blank");
<add>
<add>
<add> private URI type = BLANK_TYPE;
<add>
<add> @Nullable
<add> private String title;
<add>
<add> private int status;
<add>
<add> @Nullable
<add> private String detail;
<add>
<add> @Nullable
<add> private URI instance;
<add>
<add>
<add> /**
<add> * Protected constructor for subclasses.
<add> * <p>To create a {@link ProblemDetail} instance, use static factory methods,
<add> * {@link #forStatus(HttpStatus)} or {@link #forRawStatusCode(int)}.
<add> * @param rawStatusCode the response status to use
<add> */
<add> protected ProblemDetail(int rawStatusCode) {
<add> this.status = rawStatusCode;
<add> }
<add>
<add> /**
<add> * Copy constructor that could be used from a subclass to re-create a
<add> * {@code ProblemDetail} in order to extend it with more fields.
<add> */
<add> protected ProblemDetail(ProblemDetail other) {
<add> this.type = other.type;
<add> this.title = other.title;
<add> this.status = other.status;
<add> this.detail = other.detail;
<add> this.instance = other.instance;
<add> }
<add>
<add>
<add> /**
<add> * Variant of {@link #setType(URI)} for chained initialization.
<add> * @param type the problem type
<add> * @return the same instance
<add> */
<add> public ProblemDetail withType(URI type) {
<add> setType(type);
<add> return this;
<add> }
<add>
<add> /**
<add> * Variant of {@link #setTitle(String)} for chained initialization.
<add> * @param title the problem title
<add> * @return the same instance
<add> */
<add> public ProblemDetail withTitle(@Nullable String title) {
<add> setTitle(title);
<add> return this;
<add> }
<add>
<add> /**
<add> * Variant of {@link #setStatus(int)} for chained initialization.
<add> * @param status the response status for the problem
<add> * @return the same instance
<add> */
<add> public ProblemDetail withStatus(HttpStatus status) {
<add> Assert.notNull(status, "HttpStatus is required");
<add> setStatus(status.value());
<add> return this;
<add> }
<add>
<add> /**
<add> * Variant of {@link #setStatus(int)} for chained initialization.
<add> * @param status the response status value for the problem
<add> * @return the same instance
<add> */
<add> public ProblemDetail withRawStatusCode(int status) {
<add> setStatus(status);
<add> return this;
<add> }
<add>
<add> /**
<add> * Variant of {@link #setDetail(String)} for chained initialization.
<add> * @param detail the problem detail
<add> * @return the same instance
<add> */
<add> public ProblemDetail withDetail(@Nullable String detail) {
<add> setDetail(detail);
<add> return this;
<add> }
<add>
<add> /**
<add> * Variant of {@link #setInstance(URI)} for chained initialization.
<add> * @param instance the problem instance URI
<add> * @return the same instance
<add> */
<add> public ProblemDetail withInstance(@Nullable URI instance) {
<add> setInstance(instance);
<add> return this;
<add> }
<add>
<add>
<add> // Setters for deserialization
<add>
<add> /**
<add> * Setter for the {@link #getType() problem type}.
<add> * <p>By default, this is {@link #BLANK_TYPE}.
<add> * @param type the problem type
<add> * @see #withType(URI)
<add> */
<add> public void setType(URI type) {
<add> Assert.notNull(type, "'type' is required");
<add> this.type = type;
<add> }
<add>
<add> /**
<add> * Setter for the {@link #getTitle() problem title}.
<add> * <p>By default, if not explicitly set and the status is well-known, this
<add> * is sourced from the {@link HttpStatus#getReasonPhrase()}.
<add> * @param title the problem title
<add> * @see #withTitle(String)
<add> */
<add> public void setTitle(@Nullable String title) {
<add> this.title = title;
<add> }
<add>
<add> /**
<add> * Setter for the {@link #getStatus() problem status}.
<add> * @param status the problem status
<add> * @see #withStatus(HttpStatus)
<add> * @see #withRawStatusCode(int)
<add> */
<add> public void setStatus(int status) {
<add> this.status = status;
<add> }
<add>
<add> /**
<add> * Setter for the {@link #getDetail() problem detail}.
<add> * <p>By default, this is not set.
<add> * @param detail the problem detail
<add> * @see #withDetail(String)
<add> */
<add> public void setDetail(@Nullable String detail) {
<add> this.detail = detail;
<add> }
<add>
<add> /**
<add> * Setter for the {@link #getInstance() problem instance}.
<add> * <p>By default, when {@code ProblemDetail} is returned from an
<add> * {@code @ExceptionHandler} method, this is initialized to the request path.
<add> * @param instance the problem instance
<add> * @see #withInstance(URI)
<add> */
<add> public void setInstance(@Nullable URI instance) {
<add> this.instance = instance;
<add> }
<add>
<add>
<add> // Getters
<add>
<add> /**
<add> * Return the configured {@link #setType(URI) problem type}.
<add> */
<add> public URI getType() {
<add> return this.type;
<add> }
<add>
<add> /**
<add> * Return the configured {@link #setTitle(String) problem title}.
<add> */
<add> @Nullable
<add> public String getTitle() {
<add> if (this.title == null) {
<add> HttpStatus httpStatus = HttpStatus.resolve(this.status);
<add> if (httpStatus != null) {
<add> return httpStatus.getReasonPhrase();
<add> }
<add> }
<add> return this.title;
<add> }
<add>
<add> /**
<add> * Return the status associated with the problem, provided either to the
<add> * constructor or configured via {@link #setStatus(int)}.
<add> */
<add> public int getStatus() {
<add> return this.status;
<add> }
<add>
<add> /**
<add> * Return the configured {@link #setDetail(String) problem detail}.
<add> */
<add> @Nullable
<add> public String getDetail() {
<add> return this.detail;
<add> }
<add>
<add> /**
<add> * Return the configured {@link #setInstance(URI) problem instance}.
<add> */
<add> @Nullable
<add> public URI getInstance() {
<add> return this.instance;
<add> }
<add>
<add>
<add> @Override
<add> public String toString() {
<add> return getClass().getSimpleName() + "[" + initToStringContent() + "]";
<add> }
<add>
<add> /**
<add> * Return a String representation of the {@code ProblemDetail} fields.
<add> * Subclasses can override this to append additional fields.
<add> */
<add> protected String initToStringContent() {
<add> return "type='" + this.type + "'" +
<add> ", title='" + getTitle() + "'" +
<add> ", status=" + getStatus() +
<add> ", detail='" + getDetail() + "'" +
<add> ", instance='" + getInstance() + "'";
<add> }
<add>
<add>
<add> // Static factory methods
<add>
<add> /**
<add> * Create a {@code ProblemDetail} instance with the given status code.
<add> */
<add> public static ProblemDetail forStatus(HttpStatus status) {
<add> Assert.notNull(status, "HttpStatus is required");
<add> return forRawStatusCode(status.value());
<add> }
<add>
<add> /**
<add> * Create a {@code ProblemDetail} instance with the given status value.
<add> */
<add> public static ProblemDetail forRawStatusCode(int status) {
<add> return new ProblemDetail(status);
<add> }
<add>
<add>}
<ide><path>spring-web/src/main/java/org/springframework/http/ResponseEntity.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 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> public static <T> ResponseEntity<T> of(Optional<T> body) {
<ide> return body.map(ResponseEntity::ok).orElseGet(() -> notFound().build());
<ide> }
<ide>
<add> /**
<add> * Create a builder for a {@code ResponseEntity} with the given
<add> * {@link ProblemDetail} as the body, also matching to its
<add> * {@link ProblemDetail#getStatus() status}. An {@code @ExceptionHandler}
<add> * method can use to add response headers, or otherwise it can return
<add> * {@code ProblemDetail}.
<add> * @param body the details for an HTTP error response
<add> * @return the created builder
<add> * @since 6.0
<add> */
<add> public static HeadersBuilder<?> of(ProblemDetail body) {
<add> return new DefaultBuilder(body.getStatus()) {
<add>
<add> @SuppressWarnings("unchecked")
<add> @Override
<add> public <T> ResponseEntity<T> build() {
<add> return (ResponseEntity<T>) body(body);
<add> }
<add> };
<add> }
<add>
<ide> /**
<ide> * Create a new builder with a {@linkplain HttpStatus#CREATED CREATED} status
<ide> * and a location header set to the given URI.
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandler.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 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> package org.springframework.web.reactive.result.method.annotation;
<ide>
<add>import java.net.URI;
<ide> import java.time.Instant;
<ide> import java.util.List;
<ide> import java.util.Set;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<add>import org.springframework.http.ProblemDetail;
<ide> import org.springframework.http.RequestEntity;
<ide> import org.springframework.http.ResponseEntity;
<ide> import org.springframework.http.codec.HttpMessageWriter;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<del> * Handles {@link HttpEntity} and {@link ResponseEntity} return values.
<add> * Handles return values of type {@link HttpEntity}, {@link ResponseEntity},
<add> * {@link HttpHeaders}, and {@link ProblemDetail}.
<ide> *
<ide> * <p>By default the order for this result handler is set to 0. It is generally
<ide> * safe to place it early in the order as it looks for a concrete return type.
<ide> private static Class<?> resolveReturnValueType(HandlerResult result) {
<ide> return valueType;
<ide> }
<ide>
<del> private boolean isSupportedType(@Nullable Class<?> clazz) {
<del> return (clazz != null && ((HttpEntity.class.isAssignableFrom(clazz) &&
<del> !RequestEntity.class.isAssignableFrom(clazz)) ||
<del> HttpHeaders.class.isAssignableFrom(clazz)));
<add> private boolean isSupportedType(@Nullable Class<?> type) {
<add> if (type == null) {
<add> return false;
<add> }
<add> return ((HttpEntity.class.isAssignableFrom(type) && !RequestEntity.class.isAssignableFrom(type)) ||
<add> HttpHeaders.class.isAssignableFrom(type) || ProblemDetail.class.isAssignableFrom(type));
<ide> }
<ide>
<ide>
<ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result)
<ide> else if (returnValue instanceof HttpHeaders) {
<ide> httpEntity = new ResponseEntity<>((HttpHeaders) returnValue, HttpStatus.OK);
<ide> }
<add> else if (returnValue instanceof ProblemDetail detail) {
<add> httpEntity = new ResponseEntity<>(returnValue, HttpHeaders.EMPTY, detail.getStatus());
<add> }
<ide> else {
<ide> throw new IllegalArgumentException(
<ide> "HttpEntity or HttpHeaders expected but got: " + returnValue.getClass());
<ide> }
<ide>
<add> if (httpEntity.getBody() instanceof ProblemDetail detail) {
<add> if (detail.getInstance() == null) {
<add> URI path = URI.create(exchange.getRequest().getPath().value());
<add> detail.setInstance(path);
<add> }
<add> }
<add>
<ide> if (httpEntity instanceof ResponseEntity) {
<ide> exchange.getResponse().setRawStatusCode(
<ide> ((ResponseEntity<?>) httpEntity).getStatusCodeValue());
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandlerTests.java
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<add>import org.springframework.http.ProblemDetail;
<ide> import org.springframework.http.ResponseEntity;
<ide> import org.springframework.http.codec.EncoderHttpMessageWriter;
<ide> import org.springframework.http.codec.HttpMessageWriter;
<ide> public void supports() throws Exception {
<ide> returnType = on(TestController.class).resolveReturnType(HttpHeaders.class);
<ide> assertThat(this.resultHandler.supports(handlerResult(value, returnType))).isTrue();
<ide>
<add> returnType = on(TestController.class).resolveReturnType(ProblemDetail.class);
<add> assertThat(this.resultHandler.supports(handlerResult(value, returnType))).isTrue();
<add>
<ide> // SPR-15785
<ide> value = ResponseEntity.ok("testing");
<ide> returnType = on(TestController.class).resolveReturnType(Object.class);
<ide> public void handleReturnTypes() {
<ide> testHandle(returnValue, returnType);
<ide> }
<ide>
<add> @Test
<add> public void handleProblemDetail() {
<add> ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
<add> MethodParameter returnType = on(TestController.class).resolveReturnType(ProblemDetail.class);
<add> HandlerResult result = handlerResult(problemDetail, returnType);
<add> MockServerWebExchange exchange = MockServerWebExchange.from(get("/path"));
<add> exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_PROBLEM_JSON);
<add> this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
<add>
<add> assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
<add> assertThat(exchange.getResponse().getHeaders().size()).isEqualTo(2);
<add> assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
<add> assertResponseBody(exchange,
<add> "{\"type\":\"about:blank\"," +
<add> "\"title\":\"Bad Request\"," +
<add> "\"status\":400," +
<add> "\"detail\":null," +
<add> "\"instance\":\"/path\"}");
<add> }
<add>
<ide> @Test
<ide> public void handleReturnValueLastModified() throws Exception {
<ide> Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
<ide> private static class TestController {
<ide>
<ide> ResponseEntity<Person> responseEntityPerson() { return null; }
<ide>
<add> ProblemDetail problemDetail() { return null; }
<add>
<ide> HttpHeaders httpHeaders() { return null; }
<ide>
<ide> Mono<ResponseEntity<String>> mono() { return null; }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 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> import java.io.IOException;
<ide> import java.lang.reflect.ParameterizedType;
<ide> import java.lang.reflect.Type;
<add>import java.net.URI;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> import org.springframework.http.HttpEntity;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<add>import org.springframework.http.ProblemDetail;
<ide> import org.springframework.http.RequestEntity;
<ide> import org.springframework.http.ResponseEntity;
<ide> import org.springframework.http.converter.HttpMessageConverter;
<ide> import org.springframework.web.servlet.support.RequestContextUtils;
<ide>
<ide> /**
<del> * Resolves {@link HttpEntity} and {@link RequestEntity} method argument values
<del> * and also handles {@link HttpEntity} and {@link ResponseEntity} return values.
<add> * Resolves {@link HttpEntity} and {@link RequestEntity} method argument values,
<add> * as well as return values of type {@link HttpEntity}, {@link ResponseEntity},
<add> * and {@link ProblemDetail}.
<ide> *
<del> * <p>An {@link HttpEntity} return type has a specific purpose. Therefore this
<add> * <p>An {@link HttpEntity} return type has a specific purpose. Therefore, this
<ide> * handler should be configured ahead of handlers that support any return
<ide> * value type annotated with {@code @ModelAttribute} or {@code @ResponseBody}
<ide> * to ensure they don't take over.
<ide> public HttpEntityMethodProcessor(List<HttpMessageConverter<?>> converters) {
<ide> * Suitable for resolving {@code HttpEntity} and handling {@code ResponseEntity}
<ide> * without {@code Request~} or {@code ResponseBodyAdvice}.
<ide> */
<del> public HttpEntityMethodProcessor(List<HttpMessageConverter<?>> converters,
<del> ContentNegotiationManager manager) {
<del>
<add> public HttpEntityMethodProcessor(List<HttpMessageConverter<?>> converters, ContentNegotiationManager manager) {
<ide> super(converters, manager);
<ide> }
<ide>
<ide> public boolean supportsParameter(MethodParameter parameter) {
<ide>
<ide> @Override
<ide> public boolean supportsReturnType(MethodParameter returnType) {
<del> return (HttpEntity.class.isAssignableFrom(returnType.getParameterType()) &&
<del> !RequestEntity.class.isAssignableFrom(returnType.getParameterType()));
<add> Class<?> type = returnType.getParameterType();
<add> return ((HttpEntity.class.isAssignableFrom(type) && !RequestEntity.class.isAssignableFrom(type)) ||
<add> ProblemDetail.class.isAssignableFrom(type));
<ide> }
<ide>
<ide> @Override
<ide> public void handleReturnValue(@Nullable Object returnValue, MethodParameter retu
<ide> ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
<ide> ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);
<ide>
<del> Assert.isInstanceOf(HttpEntity.class, returnValue);
<del> HttpEntity<?> httpEntity = (HttpEntity<?>) returnValue;
<add> HttpEntity<?> httpEntity;
<add> if (returnValue instanceof ProblemDetail detail) {
<add> httpEntity = new ResponseEntity<>(returnValue, HttpHeaders.EMPTY, detail.getStatus());
<add> }
<add> else {
<add> Assert.isInstanceOf(HttpEntity.class, returnValue);
<add> httpEntity = (HttpEntity<?>) returnValue;
<add> }
<add>
<add> if (httpEntity.getBody() instanceof ProblemDetail detail) {
<add> if (detail.getInstance() == null) {
<add> URI path = URI.create(inputMessage.getServletRequest().getRequestURI());
<add> detail.setInstance(path);
<add> }
<add> }
<ide>
<ide> HttpHeaders outputHeaders = outputMessage.getHeaders();
<ide> HttpHeaders entityHeaders = httpEntity.getHeaders();
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 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> import java.util.Set;
<ide>
<ide> import jakarta.servlet.FilterChain;
<add>import jakarta.servlet.http.HttpServletResponse;
<ide> import org.junit.jupiter.api.BeforeEach;
<ide> import org.junit.jupiter.api.Test;
<ide> import org.mockito.ArgumentCaptor;
<ide> import org.springframework.http.HttpOutputMessage;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<add>import org.springframework.http.ProblemDetail;
<ide> import org.springframework.http.RequestEntity;
<ide> import org.springframework.http.ResponseEntity;
<ide> import org.springframework.http.converter.HttpMessageConverter;
<ide> import static org.mockito.Mockito.times;
<ide> import static org.mockito.Mockito.verify;
<ide> import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM;
<add>import static org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON;
<add>import static org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE;
<ide> import static org.springframework.http.MediaType.TEXT_PLAIN;
<ide> import static org.springframework.web.servlet.HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;
<ide>
<ide> public class HttpEntityMethodProcessorMockTests {
<ide>
<ide> private HttpMessageConverter<Object> resourceRegionMessageConverter;
<ide>
<add> private HttpMessageConverter<Object> jsonMessageConverter;
<add>
<ide> private MethodParameter paramHttpEntity;
<ide>
<ide> private MethodParameter paramRequestEntity;
<ide> public class HttpEntityMethodProcessorMockTests {
<ide>
<ide> private MethodParameter returnTypeInt;
<ide>
<add> private MethodParameter returnTypeProblemDetail;
<add>
<ide> private ModelAndViewContainer mavContainer;
<ide>
<ide> private MockHttpServletRequest servletRequest;
<ide> public void setup() throws Exception {
<ide> given(resourceRegionMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL));
<ide> given(resourceRegionMessageConverter.getSupportedMediaTypes(any())).willReturn(Collections.singletonList(MediaType.ALL));
<ide>
<add> jsonMessageConverter = mock(HttpMessageConverter.class);
<add> given(jsonMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.APPLICATION_PROBLEM_JSON));
<add> given(jsonMessageConverter.getSupportedMediaTypes(any())).willReturn(Collections.singletonList(MediaType.APPLICATION_PROBLEM_JSON));
<add>
<ide> processor = new HttpEntityMethodProcessor(Arrays.asList(
<del> stringHttpMessageConverter, resourceMessageConverter, resourceRegionMessageConverter));
<add> stringHttpMessageConverter, resourceMessageConverter, resourceRegionMessageConverter, jsonMessageConverter));
<ide>
<ide> Method handle1 = getClass().getMethod("handle1", HttpEntity.class, ResponseEntity.class,
<ide> Integer.TYPE, RequestEntity.class);
<ide> public void setup() throws Exception {
<ide> returnTypeHttpEntitySubclass = new MethodParameter(getClass().getMethod("handle2x", HttpEntity.class), -1);
<ide> returnTypeInt = new MethodParameter(getClass().getMethod("handle3"), -1);
<ide> returnTypeResponseEntityResource = new MethodParameter(getClass().getMethod("handle5"), -1);
<add> returnTypeProblemDetail = new MethodParameter(getClass().getMethod("handle6"), -1);
<ide>
<ide> mavContainer = new ModelAndViewContainer();
<ide> servletRequest = new MockHttpServletRequest("GET", "/foo");
<ide> public void supportsReturnType() {
<ide> assertThat(processor.supportsReturnType(returnTypeResponseEntity)).as("ResponseEntity return type not supported").isTrue();
<ide> assertThat(processor.supportsReturnType(returnTypeHttpEntity)).as("HttpEntity return type not supported").isTrue();
<ide> assertThat(processor.supportsReturnType(returnTypeHttpEntitySubclass)).as("Custom HttpEntity subclass not supported").isTrue();
<add> assertThat(processor.supportsReturnType(returnTypeProblemDetail)).isTrue();
<ide> assertThat(processor.supportsReturnType(paramRequestEntity)).as("RequestEntity parameter supported").isFalse();
<ide> assertThat(processor.supportsReturnType(returnTypeInt)).as("non-ResponseBody return type supported").isFalse();
<ide> }
<ide> public void shouldHandleReturnValue() throws Exception {
<ide> verify(stringHttpMessageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
<ide> }
<ide>
<add> @Test
<add> public void shouldHandleProblemDetail() throws Exception {
<add> ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
<add> servletRequest.addHeader("Accept", APPLICATION_PROBLEM_JSON_VALUE);
<add> given(jsonMessageConverter.canWrite(ProblemDetail.class, APPLICATION_PROBLEM_JSON)).willReturn(true);
<add>
<add> processor.handleReturnValue(problemDetail, returnTypeProblemDetail, mavContainer, webRequest);
<add>
<add> assertThat(mavContainer.isRequestHandled()).isTrue();
<add> assertThat(webRequest.getNativeResponse(HttpServletResponse.class).getStatus()).isEqualTo(400);
<add> verify(jsonMessageConverter).write(eq(problemDetail), eq(APPLICATION_PROBLEM_JSON), isA(HttpOutputMessage.class));
<add>
<add> assertThat(problemDetail).isNotNull()
<add> .extracting(ProblemDetail::getInstance).isNotNull()
<add> .extracting(URI::toString)
<add> .as("Instance was not set to the request path")
<add> .isEqualTo(servletRequest.getRequestURI());
<add>
<add>
<add> // But if instance is set, it should be respected
<add> problemDetail.setInstance(URI.create("/something/else"));
<add> processor.handleReturnValue(problemDetail, returnTypeProblemDetail, mavContainer, webRequest);
<add>
<add> assertThat(problemDetail).isNotNull()
<add> .extracting(ProblemDetail::getInstance).isNotNull()
<add> .extracting(URI::toString)
<add> .as("Instance was not set to the request path")
<add> .isEqualTo("/something/else");
<add> }
<add>
<ide> @Test
<ide> public void shouldHandleReturnValueWithProducibleMediaType() throws Exception {
<ide> String body = "Foo";
<ide> public ResponseEntity<Resource> handle5() {
<ide> return null;
<ide> }
<ide>
<add> @SuppressWarnings("unused")
<add> public ProblemDetail handle6() {
<add> return null;
<add> }
<add>
<ide> @SuppressWarnings("unused")
<ide> public static class CustomHttpEntity extends HttpEntity<Object> {
<ide> } | 6 |
PHP | PHP | remove unused argument | 6ae503d9000e6594b322e435176501242acdc8aa | <ide><path>src/Validation/Validation.php
<ide> protected static function _check($check, $regex)
<ide> * Luhn algorithm
<ide> *
<ide> * @param string|array $check Value to check.
<del> * @param bool $deep If true performs deep check.
<ide> * @return bool Success
<ide> * @see http://en.wikipedia.org/wiki/Luhn_algorithm
<ide> */
<del> public static function luhn($check, $deep = false)
<add> public static function luhn($check)
<ide> {
<ide> if (!is_scalar($check) || (int)$check === 0) {
<ide> return false; | 1 |
Ruby | Ruby | avoid implicit rollback when testing migration | 4f7d32311e6500eac52fee1aedd4aca18d73fce5 | <ide><path>activerecord/test/cases/adapters/postgresql/uuid_test.rb
<ide> def test_schema_dumper_for_uuid_primary_key_default
<ide> end
<ide> end
<ide>
<add> uses_transaction \
<ide> def test_schema_dumper_for_uuid_primary_key_default_in_legacy_migration
<ide> @verbose_was = ActiveRecord::Migration.verbose
<ide> ActiveRecord::Migration.verbose = false
<ide> def test_schema_dumper_for_uuid_primary_key_with_default_override_via_nil
<ide> assert_match(/\bcreate_table "pg_uuids", id: :uuid, default: nil/, schema)
<ide> end
<ide>
<add> uses_transaction \
<ide> def test_schema_dumper_for_uuid_primary_key_with_default_nil_in_legacy_migration
<ide> @verbose_was = ActiveRecord::Migration.verbose
<ide> ActiveRecord::Migration.verbose = false | 1 |
Javascript | Javascript | resolve process.setegid error on ubuntu | 3dc540410596ff1173586ba1bd9c171196d6f348 | <ide><path>test/parallel/test-process-geteuid-getegid.js
<ide> if (process.getuid() !== 0) {
<ide>
<ide> // If we are running as super user...
<ide> const oldgid = process.getegid();
<del>process.setegid('nobody');
<add>try {
<add> process.setegid('nobody');
<add>} catch (err) {
<add> if (err.message !== 'setegid group id does not exist') {
<add> throw err;
<add> } else {
<add> process.setegid('nogroup');
<add> }
<add>}
<ide> const newgid = process.getegid();
<ide> assert.notStrictEqual(newgid, oldgid);
<ide> | 1 |
Javascript | Javascript | change es6 module syntax to module.exports | 4a814d1370329ac75a6fb0924c73c48b3d3754fb | <ide><path>Libraries/Components/View/ViewContext.js
<ide> export type ViewChildContext = {|
<ide> +isInAParentText: boolean,
<ide> |};
<ide>
<del>export const ViewContextTypes = {
<del> isInAParentText: PropTypes.bool,
<add>module.exports = {
<add> ViewContextTypes: {
<add> isInAParentText: PropTypes.bool,
<add> },
<ide> }; | 1 |
Text | Text | fix typos in docs/reference/builder.md | 9ccb1f159e964384df32c083058197340941fafa | <ide><path>docs/reference/builder.md
<ide> Practices](../userguide/eng-image/dockerfile_best-practices.md) for a tip-orient
<ide> The [`docker build`](commandline/build.md) command builds an image from
<ide> a `Dockerfile` and a *context*. The build's context is the files at a specified
<ide> location `PATH` or `URL`. The `PATH` is a directory on your local filesystem.
<del>The `URL` is a the location of a Git repository.
<add>The `URL` is a Git repository location.
<ide>
<ide> A context is processed recursively. So, a `PATH` includes any subdirectories and
<ide> the `URL` includes the repository and its submodules. A simple build command
<ide> default is `/bin/sh -c` on Linux or `cmd /S /C` on Windows)
<ide> - `RUN ["executable", "param1", "param2"]` (*exec* form)
<ide>
<ide> The `RUN` instruction will execute any commands in a new layer on top of the
<del>current image and commit the results. The resulting comitted image will be
<add>current image and commit the results. The resulting committed image will be
<ide> used for the next step in the `Dockerfile`.
<ide>
<ide> Layering `RUN` instructions and generating commits conforms to the core
<ide> command.
<ide>
<ide> In the *shell* form you can use a `\` (backslash) to continue a single
<ide> RUN instruction onto the next line. For example, consider these two lines:
<add>
<ide> ```
<del>RUN /bin/bash -c 'source $HOME/.bashrc ;\
<add>RUN /bin/bash -c 'source $HOME/.bashrc; \
<ide> echo $HOME'
<ide> ```
<ide> Together they are equivalent to this single line:
<add>
<ide> ```
<del>RUN /bin/bash -c 'source $HOME/.bashrc ; echo $HOME'
<add>RUN /bin/bash -c 'source $HOME/.bashrc; echo $HOME'
<ide> ```
<ide>
<ide> > **Note**:
<ide> If the user specifies arguments to `docker run` then they will override the
<ide> default specified in `CMD`.
<ide>
<ide> > **Note**:
<del>> don't confuse `RUN` with `CMD`. `RUN` actually runs a command and commits
<add>> Don't confuse `RUN` with `CMD`. `RUN` actually runs a command and commits
<ide> > the result; `CMD` does not execute anything at build time, but specifies
<ide> > the intended command for the image.
<ide>
<ide> and
<ide> ENV myDog Rex The Dog
<ide> ENV myCat fluffy
<ide>
<del>will yield the same net results in the final container, but the first form
<add>will yield the same net results in the final image, but the first form
<ide> is preferred because it produces a single cache layer.
<ide>
<ide> The environment variables set using `ENV` will persist when a container is run
<ide> ADD has two forms:
<ide> whitespace)
<ide>
<ide> The `ADD` instruction copies new files, directories or remote file URLs from `<src>`
<del>and adds them to the filesystem of the container at the path `<dest>`.
<add>and adds them to the filesystem of the image at the path `<dest>`.
<ide>
<ide> Multiple `<src>` resource may be specified but if they are files or
<ide> directories then they must be relative to the source directory that is
<ide> of whether or not the file has changed and the cache should be updated.
<ide> > can only contain a URL based `ADD` instruction. You can also pass a
<ide> > compressed archive through STDIN: (`docker build - < archive.tar.gz`),
<ide> > the `Dockerfile` at the root of the archive and the rest of the
<del>> archive will get used at the context of the build.
<add>> archive will be used as the context of the build.
<ide>
<ide> > **Note**:
<ide> > If your URL files are protected using authentication, you
<ide> guide](../userguide/eng-image/dockerfile_best-practices.md#build-cache) for more
<ide> - If `<src>` is a *local* tar archive in a recognized compression format
<ide> (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources
<ide> from *remote* URLs are **not** decompressed. When a directory is copied or
<del> unpacked, it has the same behavior as `tar -x`: the result is the union of:
<add> unpacked, it has the same behavior as `tar -x`, the result is the union of:
<ide>
<ide> 1. Whatever existed at the destination path and
<ide> 2. The contents of the source tree, with conflicts resolved in favor
<ide> a shell operates. For example, using `SHELL cmd /S /C /V:ON|OFF` on Windows, del
<ide> environment variable expansion semantics could be modified.
<ide>
<ide> The `SHELL` instruction can also be used on Linux should an alternate shell be
<del>required such `zsh`, `csh`, `tcsh` and others.
<add>required such as `zsh`, `csh`, `tcsh` and others.
<ide>
<ide> The `SHELL` feature was added in Docker 1.12.
<ide> | 1 |
Mixed | Javascript | fix spelling errors | 2b28c540ad7ebf4a9c3a6f108a9cb5b673d3712d | <ide><path>CONTRIBUTING.md
<ide> restarted.
<ide> git push origin my-fix-branch -f
<ide> ```
<ide>
<del> This is generally easier to follow, but seperate commits are useful if the Pull Request contains
<add> This is generally easier to follow, but separate commits are useful if the Pull Request contains
<ide> iterations that might be interesting to see side-by-side.
<ide>
<ide> That's it! Thank you for your contribution!
<ide><path>src/ng/compile.js
<ide> *
<ide> * When the original node and the replace template declare the same directive(s), they will be
<ide> * {@link guide/compiler#double-compilation-and-how-to-avoid-it compiled twice} because the compiler
<del> * does not deduplicate them. In many cases, this is not noticable, but e.g. {@link ngModel} will
<add> * does not deduplicate them. In many cases, this is not noticeable, but e.g. {@link ngModel} will
<ide> * attach `$formatters` and `$parsers` twice.
<ide> *
<ide> * See issue [#2573](https://github.com/angular/angular.js/issues/2573).
<ide><path>test/ng/directive/selectSpec.js
<ide> describe('select', function() {
<ide> });
<ide>
<ide>
<del> it('should only call selectCtrl.writeValue after a digest has occured', function() {
<add> it('should only call selectCtrl.writeValue after a digest has occurred', function() {
<ide> scope.mySelect = 'B';
<ide> scope.$apply();
<ide> | 3 |
PHP | PHP | fix issue with postgres | 7c42905d10f978ba08b8dc765f8f1d6b692d74d2 | <ide><path>tests/TestCase/ORM/QueryRegressionTest.php
<ide> public function testComplexOrderWithUnion()
<ide> {
<ide> $table = TableRegistry::get('Comments');
<ide> $query = $table->find();
<del> $inner = $table->find()->where(['id >' => 3]);
<del> $inner2 = $table->find()->where(['id <' => 3]);
<add> $inner = $table->find()
<add> ->select(['content' => 'comment'])
<add> ->where(['id >' => 3]);
<add> $inner2 = $table->find()
<add> ->select(['content' => 'comment'])
<add> ->where(['id <' => 3]);
<ide>
<del> $order = $query->func()->concat(['inside__comment' => 'literal', 'test']);
<add> $order = $query->func()->concat(['content' => 'literal', 'test']);
<ide>
<del> $query->select(['inside__comment' => 'Comments__comment'])
<add> $query->select(['inside.content'])
<ide> ->from(['inside' => $inner->unionAll($inner2)])
<ide> ->orderAsc($order);
<ide> | 1 |
Text | Text | add 1.13.0 changelog.md | 433bb525214db1359df18be280f555d915f7e386 | <ide><path>CHANGELOG.md
<ide> information on the list of deprecated flags and APIs please have a look at
<ide> https://docs.docker.com/engine/deprecated/ where target removal dates can also
<ide> be found.
<ide>
<add>## 1.13.0 (2016-12-08)
<add>
<add>### Builder
<add>+ Add capability to specify images used as a cache source on build. These images do not need to have local parent chain and can be pulled from other registries [#26839](https://github.com/docker/docker/pull/26839)
<add>+ (experimental) Add option to squash image layers to the FROM image after successful builds [#22641](https://github.com/docker/docker/pull/22641)
<add>* Fix dockerfile parser with empty line after escape [#24725](https://github.com/docker/docker/pull/24725)
<add>- Add step number on `docker build` [#24978](https://github.com/docker/docker/pull/24978)
<add>+ Add support for compressing build context during image build [#25837](https://github.com/docker/docker/pull/25837)
<add>+ add `--network` to `docker build` [#27702](https://github.com/docker/docker/pull/27702)
<add>- Fix inconsistent behavior between `--label` flag on `docker build` and `docker run` [#26027](https://github.com/docker/docker/issues/26027)
<add>- Fix image layer inconsistencies when using the overlay storage driver [#27209](https://github.com/docker/docker/pull/27209)
<add>* Unused build-args are now allowed. A warning is presented instead of an error and failed build [#27412](https://github.com/docker/docker/pull/27412)
<add>- Fix builder cache issue on Windows [#27805](https://github.com/docker/docker/pull/27805)
<add>
<add>### Contrib
<add>+ Add support for building docker debs for Ubuntu Xenial on PPC64 [#23438](https://github.com/docker/docker/pull/23438)
<add>+ Add support for building docker debs for Ubuntu Xenial on s390x [#26104](https://github.com/docker/docker/pull/26104)
<add>- Add RPM builder for VMWare Photon OS [#24116](https://github.com/docker/docker/pull/24116)
<add>+ Add shell completions to tgz [#27735](https://github.com/docker/docker/pull/27735)
<add>* Update the install script to allow using the mirror in China [#27005](https://github.com/docker/docker/pull/27005)
<add>+ Add DEB builder for Ubuntu 16.10 Yakkety Yak [#27993](https://github.com/docker/docker/pull/27993)
<add>+ Add RPM builder for Fedora 25 [#28222](https://github.com/docker/docker/pull/28222)
<add>
<add>### Distribution
<add>
<add>* Update notary dependency to 0.4.2 (full changelogs [here](https://github.com/docker/notary/releases/tag/v0.4.2)) [#27074](https://github.com/docker/docker/pull/27074)
<add> - Support for compilation on windows [docker/notary#970](https://github.com/docker/notary/pull/970)
<add> - Improved error messages for client authentication errors [docker/notary#972](https://github.com/docker/notary/pull/972)
<add> - Support for finding keys that are anywhere in the `~/.docker/trust/private` directory, not just under `~/.docker/trust/private/root_keys` or `~/.docker/trust/private/tuf_keys` [docker/notary#981](https://github.com/docker/notary/pull/981)
<add> - Previously, on any error updating, the client would fall back on the cache. Now we only do so if there is a network error or if the server is unavailable or missing the TUF data. Invalid TUF data will cause the update to fail - for example if there was an invalid root rotation. [docker/notary#982](https://github.com/docker/notary/pull/982)
<add> - Improve root validation and yubikey debug logging [docker/notary#858](https://github.com/docker/notary/pull/858) [docker/notary#891](https://github.com/docker/notary/pull/891)
<add> - Warn if certificates for root or delegations are near expiry [docker/notary#802](https://github.com/docker/notary/pull/802)
<add> - Warn if role metadata is near expiry [docker/notary#786](https://github.com/docker/notary/pull/786)
<add> - Fix passphrase retrieval attempt counting and terminal detection [docker/notary#906](https://github.com/docker/notary/pull/906)
<add>- Avoid unnecessary blob uploads when different users push same layers to authenticated registry [#26564](https://github.com/docker/docker/pull/26564)
<add>* Allow external storage for registry credentials [#26354](https://github.com/docker/docker/pull/26354)
<add>
<add>### Logging
<add>
<add>* Standardize the default logging tag value in all logging drivers [#22911](https://github.com/docker/docker/pull/22911)
<add>- Improve performance and memory use when logging of long log lines [#22982](https://github.com/docker/docker/pull/22982)
<add>+ Enable syslog driver for windows [#25736](https://github.com/docker/docker/pull/25736)
<add>+ Add Logentries Driver [#27471](https://github.com/docker/docker/pull/27471)
<add>+ Update of AWS log driver to support tags [#27707](https://github.com/docker/docker/pull/27707)
<add>+ Unix socket support for fluentd [#26088](https://github.com/docker/docker/pull/26088)
<add>* Enable fluentd logging driver on Windows [#28189](https://github.com/docker/docker/pull/28189)
<add>- Sanitize docker labels when used as journald field names [#23725](https://github.com/docker/docker/pull/23725)
<add>
<add>### Networking
<add>
<add>+ Add `--attachable` network support to enable `docker run` to work in swarm-mode overlay network [#25962](https://github.com/docker/docker/pull/25962)
<add>+ Add support for host port PublishMode in services using the `--port` option in `docker service create` [#27917](https://github.com/docker/docker/pull/27917)
<add>+ Add support for Windows server 2016 overlay network driver (requires upcoming ws2016 update) [#28182](https://github.com/docker/docker/pull/28182)
<add>* Change the default `FORWARD` policy to `DROP` [#28257](https://github.com/docker/docker/pull/28257)
<add>+ Add support for specifying static IP addresses for predefined network on windows [#22208](https://github.com/docker/docker/pull/22208)
<add>- Fix `--publish` flag on `docker run` not working with IPv6 addresses [#27860](https://github.com/docker/docker/pull/27860)
<add>- Fix inspect network show gateway with mask [#25564](https://github.com/docker/docker/pull/25564)
<add>- Fix an issue where multiple addresses in a bridge may cause `--fixed-cidr` to not have the correct addresses [#26659](https://github.com/docker/docker/pull/26659)
<add>+ Add creation timestamp to `docker network inspect` [#26130](https://github.com/docker/docker/pull/26130)
<add>- Show peer nodes in `docker network inspect` for swarm overlay networks [#28078](https://github.com/docker/docker/pull/28078)
<add>- Enable ping for service VIP address [#28019](https://github.com/docker/docker/pull/28019)
<add>
<add>### Plugins
<add>
<add>- Move plugins out of experimental [#28226](https://github.com/docker/docker/pull/28226)
<add>- Add `--force` on `docker plugin remove` [#25096](https://github.com/docker/docker/pull/25096)
<add>* Add support for dynamically reloading authorization plugins [#22770](https://github.com/docker/docker/pull/22770)
<add>+ Add description in `docker plugin ls` [#25556](https://github.com/docker/docker/pull/25556)
<add>+ Add `-f`/`--format` to `docker plugin inspect` [#25990](https://github.com/docker/docker/pull/25990)
<add>+ Add `docker plugin create` command [#28164](https://github.com/docker/docker/pull/28164)
<add>* Send request's TLS peer certificates to authorization plugins [#27383](https://github.com/docker/docker/pull/27383)
<add>* Support for global-scoped network and ipam plugins in swarm-mode [#27287](https://github.com/docker/docker/pull/27287)
<add>
<add>### Remote API (v1.25) & Client
<add>
<add>+ Support `docker stack deploy` from a Compose file [#27998](https://github.com/docker/docker/pull/27998)
<add>+ (experimental) Implement checkpoint and restore [#22049](https://github.com/docker/docker/pull/22049)
<add>+ Add `--format` flag to `docker info` [#23808](https://github.com/docker/docker/pull/23808)
<add>* Remove `--name` from `docker volume create` [#23830](https://github.com/docker/docker/pull/23830)
<add>+ Add `docker stack ls` [#23886](https://github.com/docker/docker/pull/23886)
<add>+ Add a new `is-task` ps filter [#24411](https://github.com/docker/docker/pull/24411)
<add>+ Add `--env-file` flag to `docker create service` [#24844](https://github.com/docker/docker/pull/24844)
<add>+ Add `--format` on `docker stats` [#24987](https://github.com/docker/docker/pull/24987)
<add>+ Make `docker node ps` default to `self` in swarm node [#25214](https://github.com/docker/docker/pull/25214)
<add>+ Add `--group` in `docker service create` [#25317](https://github.com/docker/docker/pull/25317)
<add>+ Add `--no-trunc` to service/node/stack ps output [#25337(https://github.com/docker/docker/pull/25337)
<add>+ Add Logs to `ContainerAttachOptions` so go clients can request to retrieve container logs as part of the attach process [#26718](https://github.com/docker/docker/pull/26718)
<add>+ Allow client to talk to an older server [#27745](https://github.com/docker/docker/pull/27745)
<add>* Inform user client-side that a container removal is in progress [#26074](https://github.com/docker/docker/pull/26074)
<add>+ Add `Isolation` to the /info endpoint [#26255](https://github.com/docker/docker/pull/26255)
<add>+ Add `userns` to the /info endpoint [#27840](https://github.com/docker/docker/pull/27840)
<add>- Do not allow more than one mode be requested at once in the services endpoint [#26643](https://github.com/docker/docker/pull/26643)
<add>+ Add `--mount` flag to `docker create` and `docker run` [#26825](https://github.com/docker/docker/pull/26825)[#28150](https://github.com/docker/docker/pull/28150)
<add>+ Add capability to /containers/create API to specify mounts in a more granular and safer way [#22373](https://github.com/docker/docker/pull/22373)
<add>+ Add `--format` flag to `network ls` and `volume ls` [#23475](https://github.com/docker/docker/pull/23475)
<add>* Allow the top-level `docker inspect` command to inspect any kind of resource [#23614](https://github.com/docker/docker/pull/23614)
<add>- Allow unsetting the `--entrypoint` in `docker run` or `docker create` [#23718](https://github.com/docker/docker/pull/23718)
<add>* Restructure CLI commands by adding `docker image` and `docker container` commands for more consistency [#26025](https://github.com/docker/docker/pull/26025)
<add>- Remove `COMMAND` column from `service ls` output [#28029](https://github.com/docker/docker/pull/28029)
<add>+ Add `--format` to `docker events` [#26268](https://github.com/docker/docker/pull/26268)
<add>* Allow specifying multiple nodes on `docker node ps` [#26299](https://github.com/docker/docker/pull/26299)
<add>* Restrict fractional digits to 2 decimals in `docker images` output [#26303](https://github.com/docker/docker/pull/26303)
<add>+ Add `--dns-option` to `docker run` [#28186](https://github.com/docker/docker/pull/28186)
<add>+ Add Image ID to container commit event [#28128](https://github.com/docker/docker/pull/28128)
<add>+ Add external binaries version to docker info [#27955](https://github.com/docker/docker/pull/27955)
<add>+ Add information for `Manager Addresses` in the output of `docker info` [#28042](https://github.com/docker/docker/pull/28042)
<add>+ Add a new reference filter for `docker images` [#27872](https://github.com/docker/docker/pull/27872)
<add>
<add>### Runtime
<add>
<add>+ Add `--experimental` daemon flag to enable experimental features, instead of shipping them in a separate build [#27223](https://github.com/docker/docker/pull/27223)
<add>+ Add a `--shutdown-timeout` daemon flag to specify the default timeout (in seconds) to stop containers gracefully before daemon exit [#23036](https://github.com/docker/docker/pull/23036)
<add>+ Add `--stop-timeout` to specify the timeout value (in seconds) for individual containers to stop [#22566](https://github.com/docker/docker/pull/22566)
<add>+ Add a new daemon flag `--userland-proxy-path` to allow configuring the userland proxy instead of using the hardcoded `docker-proxy` from `$PATH` [#26882](https://github.com/docker/docker/pull/26882)
<add>+ Add boolean flag `--init` on `dockerd` and on `docker run` to use [tini](https://github.com/krallin/tini) a zombie-reaping init process as PID 1 [#26061](https://github.com/docker/docker/pull/26061) [#28037](https://github.com/docker/docker/pull/28037)
<add>+ Add a new daemon flag `--init-path` to allow configuring the path to the `docker-init` binary [#26941](https://github.com/docker/docker/pull/26941)
<add>+ Add support for live reloading insecure registry in configuration [#22337](https://github.com/docker/docker/pull/22337)
<add>+ Add support for storage-opt size on Windows daemons [#23391](https://github.com/docker/docker/pull/23391)
<add>* Improve reliability of `docker run --rm` by moving it from the client to the daemon [#20848](https://github.com/docker/docker/pull/20848)
<add>+ Add support for `--cpu-rt-period` and `--cpu-rt-runtime` flags, allowing containers to run real-time threads when `CONFIG_RT_GROUP_SCHED` is enabled in the kernel [#23430](https://github.com/docker/docker/pull/23430)
<add>* Allow parallel stop, pause, unpause [#24761](https://github.com/docker/docker/pull/24761) / [#26778](https://github.com/docker/docker/pull/26778)
<add>* Implement XFS quota for overlay2 [#24771](https://github.com/docker/docker/pull/24771)
<add>- Fix partial/full filter issue in `service tasks --filter` [#24850](https://github.com/docker/docker/pull/24850)
<add>- Allow engine to run inside a user namespace [#25672](https://github.com/docker/docker/pull/25672)
<add>- Fix a race condition between device deferred removal and resume device, when using the devicemapper graphdriver [#23497](https://github.com/docker/docker/pull/23497)
<add>- Add `docker stats` support in Windows [#25737](https://github.com/docker/docker/pull/25737)
<add>- Allow using `--pid=host` and `--net=host` when `--userns=host` [#25771](https://github.com/docker/docker/pull/25771)
<add>+ (experimental) Add metrics output [#25820](https://github.com/docker/docker/pull/25820)
<add>- Fix issue in `docker stats` with `NetworkDisabled=true` [#25905](https://github.com/docker/docker/pull/25905)
<add>+ Add `docker top` support in Windows [#25891](https://github.com/docker/docker/pull/25891)
<add>+ Record pid of exec'd process [#27470](https://github.com/docker/docker/pull/27470)
<add>+ Add support for looking up user/groups via `getent` [#27599](https://github.com/docker/docker/pull/27599)
<add>+ Add new `docker system` command with `df` and `prune` subcommands for system resource management, as well as `docker {container,image,volume,network} prune` subcommands [#26108](https://github.com/docker/docker/pull/26108) [#27525](https://github.com/docker/docker/pull/27525) / [#27525](https://github.com/docker/docker/pull/27525)
<add>- Fix an issue where containers could not be stopped or killed by setting xfs max_retries to 0 upon ENOSPC with devicemapper [#26212](https://github.com/docker/docker/pull/26212)
<add>- Fix `docker cp` failing to copy to a container's volume dir on CentOS with devicemapper [#28047](https://github.com/docker/docker/pull/28047)
<add>* Promote overlay(2) graphdriver [#27932](https://github.com/docker/docker/pull/27932)
<add>+ Add `--seccomp-profile` daemon flag to specify a path to a seccomp profile that overrides the default [#26276](https://github.com/docker/docker/pull/26276)
<add>- Fix ulimits in `docker inspect` when `--default-ulimit` is set on daemon [#26405](https://github.com/docker/docker/pull/26405)
<add>- Add workaround for overlay issues during build in older kernels [#28138](https://github.com/docker/docker/pull/28138)
<add>+ Add `TERM` environment variable on `docker exec -t` [#26461](https://github.com/docker/docker/pull/26461)
<add>* Honor a container’s `--stop-signal` setting upon `docker kill` [#26464](https://github.com/docker/docker/pull/26464)
<add>
<add>### Swarm Mode
<add>
<add>+ Add secret management [#27794](https://github.com/docker/docker/pull/27794)
<add>* Display the endpoint mode in the output of `docker service inspect --pretty` [#26906](https://github.com/docker/docker/pull/26906)
<add>* Make `docker service ps` output more bearable by shortening service IDs in task names [#28088](https://github.com/docker/docker/pull/28088)
<add>* `docker node ps` now defaults to the current node [#25214](https://github.com/docker/docker/pull/25214)
<add>+ Add `-a`/`--all` flags to `docker service ps` and `docker node ps` to show all results [#25983](https://github.com/docker/docker/pull/25983)
<add>+ Add `--dns`, -`-dns-opt`, and `--dns-search` to service create. [#27567](https://github.com/docker/docker/pull/27567)
<add>+ Add `--force` to `docker service update` [#27596](https://github.com/docker/docker/pull/27596)
<add>+ Add `-q` to `docker service ps` [#27654](https://github.com/docker/docker/pull/27654)
<add>* Display number of global services in `docker service ls` [#27710](https://github.com/docker/docker/pull/27710)
<add>- Remove `--name` flag from `docker service update`. This flag is only functional on `docker service create`, so was removed from the `update` command [#26988](https://github.com/docker/docker/pull/26988)
<add>- Fix worker nodes failing to recover because of transient networking issues [#26646](https://github.com/docker/docker/issues/26646)
<add>* Add support for health aware load balancing and DNS records [#27279](https://github.com/docker/docker/pull/27279)
<add>* Add `--hostname` to `docker service create` [#27857](https://github.com/docker/docker/pull/27857)
<add>- Add `--tty` flag to `docker service create`/`update` [#28076](https://github.com/docker/docker/pull/28076)
<add>* Autodetect, store, and expose node IP address as seen by the manager [#27910](https://github.com/docker/docker/pull/27910)
<add>* Encryption at rest of manager keys and raft data [#27967](https://github.com/docker/docker/pull/27967)
<add>+ Add `--update-max-failure-ratio`, `--update-monitor` and `--rollback` flags to `docker service update` [#26421](https://github.com/docker/docker/pull/26421)
<add>- Fix an issue with address autodiscovery on `docker swarm init` running inside a container [#26457](https://github.com/docker/docker/pull/26457)
<add>+ (experimental) Add `docker service logs` command to view logs for a service [#28089](https://github.com/docker/docker/pull/28089)
<add>- Pin images by digest for `docker service create` and `update` [#28173](https://github.com/docker/docker/pull/28173)
<add>- Add short (`-f`) flag for `docker node rm --force` and `docker swarm leave --force` [#28196](https://github.com/docker/docker/pull/28196)
<add>+ Don't repull image if pinned by digest [#28265](https://github.com/docker/docker/pull/28265)
<add>+ swarm-mode support for indows [#27838](https://github.com/docker/docker/pull/27838)
<add>
<add>### Volume
<add>
<add>+ Add support for labels on volumes [#25628](https://github.com/docker/docker/pull/21567)
<add>+ Add support for filtering volumes by label [#25628](https://github.com/docker/docker/pull/25628)
<add>* Add a `--force` flag in `docker volume rm` to forcefully purge the data of the volume that has already been deleted [#23436](https://github.com/docker/docker/pull/23436)
<add>* Enhance `docker volume inspect` to show all options used when creating the volume [#26671](https://github.com/docker/docker/pull/26671)
<add>* Add support for local NFS volumes to resolve hostnames [#27329](https://github.com/docker/docker/pull/27329)
<add>
<add>### Security
<add>
<add>- Fix selinux labeling of volumes shared in a container [#23024](https://github.com/docker/docker/pull/23024)
<add>- Prohibit `/sys/firmware/**` from being accessed with apparmor [#26618](https://github.com/docker/docker/pull/26618)
<add>
<add>### DEPRECATION
<add>
<add>- Marked the `docker daemon` command as deprecated. The daemon is moved to a separate binary (`dockerd`), and should be used instead [#26834](https://github.com/docker/docker/pull/26834)
<add>- Deprecate unversioned API endpoints [#28208](https://github.com/docker/docker/pull/28208)
<add>- Remove Ubuntu 15.10 (Wily Werewolf) as supported platform. Ubuntu 15.10 is EOL, and no longer receives updates [#27042](https://github.com/docker/docker/pull/27042)
<add>- Remove Fedora 22 as supported platform. Fedora 22 is EOL, and no longer receives updates [#27432](https://github.com/docker/docker/pull/27432)
<add>- Deprecate the `repo:shortid` syntax on `docker pull` [#27207](https://github.com/docker/docker/pull/27207)
<add>- Deprecate backing filesystem without d_type for overlay/overlay2 storage drivers [#27433](https://github.com/docker/docker/pull/27433)
<add>- Deprecate MAINTAINER in Dockerfile [#25466](https://github.com/docker/docker/pull/25466)
<add>- Deprecated filter param for endpoint `/images/json` [#27872](https://github.com/docker/docker/pull/27872)
<add>
<ide> ## 1.12.3 (2016-10-26)
<ide>
<ide> **IMPORTANT**: Docker 1.12 ships with an updated systemd unit file for rpm
<ide> systemctl restart docker` to reload changes and (re)start the docker daemon.
<ide> - Fix issue preventing `service update --publish-add` to work as intended [#25428](https://github.com/docker/docker/pull/25428)
<ide> - Remove `service update --network-add` and `service update --network-rm` flags
<ide> because this feature is not yet implemented in 1.12, but was inadvertently added
<del> to the client in 1.12.0 [#25646](https://github.com/docker/docker/pull/25646)
<add> to the client in 1.12.0 [#25646](https://github.com/docker/docker/pull/25646)
<ide>
<ide> ### Contrib
<ide> | 1 |
Mixed | Go | add tls support for discovery backend | 124792a8714425283226c599ee69cbeac2e4d650 | <ide><path>daemon/config.go
<ide> type CommonConfig struct {
<ide> // mechanism.
<ide> ClusterStore string
<ide>
<add> // ClusterOpts is used to pass options to the discovery package for tuning libkv settings, such
<add> // as TLS configuration settings.
<add> ClusterOpts map[string]string
<add>
<ide> // ClusterAdvertise is the network endpoint that the Engine advertises for the purpose of node
<ide> // discovery. This should be a 'host:port' combination on which that daemon instance is
<ide> // reachable by other hosts.
<ide> func (config *Config) InstallCommonFlags(cmd *flag.FlagSet, usageFn func(string)
<ide> cmd.Var(opts.NewMapOpts(config.LogConfig.Config, nil), []string{"-log-opt"}, usageFn("Set log driver options"))
<ide> cmd.StringVar(&config.ClusterAdvertise, []string{"-cluster-advertise"}, "", usageFn("Address of the daemon instance to advertise"))
<ide> cmd.StringVar(&config.ClusterStore, []string{"-cluster-store"}, "", usageFn("Set the cluster store"))
<add> cmd.Var(opts.NewMapOpts(config.ClusterOpts, nil), []string{"-cluster-store-opt"}, usageFn("Set cluster store options"))
<ide> }
<ide><path>daemon/daemon.go
<ide> func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemo
<ide> // DiscoveryWatcher version.
<ide> if config.ClusterStore != "" && config.ClusterAdvertise != "" {
<ide> var err error
<del> if d.discoveryWatcher, err = initDiscovery(config.ClusterStore, config.ClusterAdvertise); err != nil {
<add> if d.discoveryWatcher, err = initDiscovery(config.ClusterStore, config.ClusterAdvertise, config.ClusterOpts); err != nil {
<ide> return nil, fmt.Errorf("discovery initialization failed (%v)", err)
<ide> }
<ide> }
<ide><path>daemon/discovery.go
<ide> const (
<ide>
<ide> // initDiscovery initialized the nodes discovery subsystem by connecting to the specified backend
<ide> // and start a registration loop to advertise the current node under the specified address.
<del>func initDiscovery(backend, address string) (discovery.Backend, error) {
<add>func initDiscovery(backend, address string, clusterOpts map[string]string) (discovery.Backend, error) {
<ide> var (
<ide> discoveryBackend discovery.Backend
<ide> err error
<ide> )
<del> if discoveryBackend, err = discovery.New(backend, defaultDiscoveryHeartbeat, defaultDiscoveryTTL); err != nil {
<add> if discoveryBackend, err = discovery.New(backend, defaultDiscoveryHeartbeat, defaultDiscoveryTTL, clusterOpts); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide><path>docker/daemon.go
<ide> func NewDaemonCli() *DaemonCli {
<ide> // TODO(tiborvass): remove InstallFlags?
<ide> daemonConfig := new(daemon.Config)
<ide> daemonConfig.LogConfig.Config = make(map[string]string)
<add> daemonConfig.ClusterOpts = make(map[string]string)
<ide> daemonConfig.InstallFlags(daemonFlags, presentInHelp)
<ide> daemonConfig.InstallFlags(flag.CommandLine, absentFromHelp)
<ide> registryOptions := new(registry.Options)
<ide><path>docs/reference/commandline/daemon.md
<ide> weight=1
<ide> --default-gateway-v6="" Container default gateway IPv6 address
<ide> --cluster-store="" URL of the distributed storage backend
<ide> --cluster-advertise="" Address of the daemon instance to advertise
<add> --cluster-store-opt=map[] Set cluster options
<ide> --dns=[] DNS server to use
<ide> --dns-opt=[] DNS options to use
<ide> --dns-search=[] DNS search domains to use
<ide> please check the [run](run.md) reference.
<ide> daemon instance should use when advertising itself to the cluster. The daemon
<ide> should be reachable by remote hosts on this 'host:port' combination.
<ide>
<add>The daemon uses [libkv](https://github.com/docker/libkv/) to advertise
<add>the node within the cluster. Some Key/Value backends support mutual
<add>TLS, and the client TLS settings used by the daemon can be configured
<add>using the `--cluster-store-opt` flag, specifying the paths to PEM encoded
<add>files. For example:
<add>
<add>```bash
<add> --cluster-advertise 192.168.1.2:2376 \
<add> --cluster-store etcd://192.168.1.2:2379 \
<add> --cluster-store-opt kv.cacertfile=/path/to/ca.pem \
<add> --cluster-store-opt kv.certfile=/path/to/cert.pem \
<add> --cluster-store-opt kv.keyfile=/path/to/key.pem
<add>```
<add>
<ide> ## Miscellaneous options
<ide>
<ide> IP masquerading uses address translation to allow containers without a public
<ide><path>pkg/discovery/backends.go
<ide> func parse(rawurl string) (string, string) {
<ide>
<ide> // New returns a new Discovery given a URL, heartbeat and ttl settings.
<ide> // Returns an error if the URL scheme is not supported.
<del>func New(rawurl string, heartbeat time.Duration, ttl time.Duration) (Backend, error) {
<add>func New(rawurl string, heartbeat time.Duration, ttl time.Duration, clusterOpts map[string]string) (Backend, error) {
<ide> scheme, uri := parse(rawurl)
<ide> if backend, exists := backends[scheme]; exists {
<ide> log.WithFields(log.Fields{"name": scheme, "uri": uri}).Debug("Initializing discovery service")
<del> err := backend.Initialize(uri, heartbeat, ttl)
<add> err := backend.Initialize(uri, heartbeat, ttl, clusterOpts)
<ide> return backend, err
<ide> }
<ide>
<ide><path>pkg/discovery/discovery.go
<ide> type Backend interface {
<ide> // Watcher must be provided by every backend.
<ide> Watcher
<ide>
<del> // Initialize the discovery with URIs, a heartbeat and a ttl.
<del> Initialize(string, time.Duration, time.Duration) error
<add> // Initialize the discovery with URIs, a heartbeat, a ttl and optional settings.
<add> Initialize(string, time.Duration, time.Duration, map[string]string) error
<ide>
<ide> // Register to the discovery.
<ide> Register(string) error
<ide><path>pkg/discovery/file/file.go
<ide> func Init() {
<ide> }
<ide>
<ide> // Initialize is exported
<del>func (s *Discovery) Initialize(path string, heartbeat time.Duration, ttl time.Duration) error {
<add>func (s *Discovery) Initialize(path string, heartbeat time.Duration, ttl time.Duration, _ map[string]string) error {
<ide> s.path = path
<ide> s.heartbeat = heartbeat
<ide> return nil
<ide><path>pkg/discovery/file/file_test.go
<ide> var _ = check.Suite(&DiscoverySuite{})
<ide>
<ide> func (s *DiscoverySuite) TestInitialize(c *check.C) {
<ide> d := &Discovery{}
<del> d.Initialize("/path/to/file", 1000, 0)
<add> d.Initialize("/path/to/file", 1000, 0, nil)
<ide> c.Assert(d.path, check.Equals, "/path/to/file")
<ide> }
<ide>
<ide> func (s *DiscoverySuite) TestNew(c *check.C) {
<del> d, err := discovery.New("file:///path/to/file", 0, 0)
<add> d, err := discovery.New("file:///path/to/file", 0, 0, nil)
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(d.(*Discovery).path, check.Equals, "/path/to/file")
<ide> }
<ide> func (s *DiscoverySuite) TestWatch(c *check.C) {
<ide>
<ide> // Set up file discovery.
<ide> d := &Discovery{}
<del> d.Initialize(tmp.Name(), 1000, 0)
<add> d.Initialize(tmp.Name(), 1000, 0, nil)
<ide> stopCh := make(chan struct{})
<ide> ch, errCh := d.Watch(stopCh)
<ide>
<ide><path>pkg/discovery/kv/kv.go
<ide> import (
<ide>
<ide> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/discovery"
<add> "github.com/docker/docker/pkg/tlsconfig"
<ide> "github.com/docker/libkv"
<ide> "github.com/docker/libkv/store"
<ide> "github.com/docker/libkv/store/consul"
<ide> func Init() {
<ide> }
<ide>
<ide> // Initialize is exported
<del>func (s *Discovery) Initialize(uris string, heartbeat time.Duration, ttl time.Duration) error {
<add>func (s *Discovery) Initialize(uris string, heartbeat time.Duration, ttl time.Duration, clusterOpts map[string]string) error {
<ide> var (
<ide> parts = strings.SplitN(uris, "/", 2)
<ide> addrs = strings.Split(parts[0], ",")
<ide> func (s *Discovery) Initialize(uris string, heartbeat time.Duration, ttl time.Du
<ide> s.ttl = ttl
<ide> s.path = path.Join(s.prefix, discoveryPath)
<ide>
<add> var config *store.Config
<add> if clusterOpts["kv.cacertfile"] != "" && clusterOpts["kv.certfile"] != "" && clusterOpts["kv.keyfile"] != "" {
<add> log.Info("Initializing discovery with TLS")
<add> tlsConfig, err := tlsconfig.Client(tlsconfig.Options{
<add> CAFile: clusterOpts["kv.cacertfile"],
<add> CertFile: clusterOpts["kv.certfile"],
<add> KeyFile: clusterOpts["kv.keyfile"],
<add> })
<add> if err != nil {
<add> return err
<add> }
<add> config = &store.Config{
<add> // Set ClientTLS to trigger https (bug in libkv/etcd)
<add> ClientTLS: &store.ClientTLSConfig{
<add> CACertFile: clusterOpts["kv.cacertfile"],
<add> CertFile: clusterOpts["kv.certfile"],
<add> KeyFile: clusterOpts["kv.keyfile"],
<add> },
<add> // The actual TLS config that will be used
<add> TLS: tlsConfig,
<add> }
<add> } else {
<add> log.Info("Initializing discovery without TLS")
<add> }
<add>
<ide> // Creates a new store, will ignore options given
<ide> // if not supported by the chosen store
<del> s.store, err = libkv.NewStore(s.backend, addrs, nil)
<add> s.store, err = libkv.NewStore(s.backend, addrs, config)
<ide> return err
<ide> }
<ide>
<ide><path>pkg/discovery/kv/kv_test.go
<ide> package kv
<ide>
<ide> import (
<ide> "errors"
<add> "io/ioutil"
<add> "os"
<ide> "path"
<ide> "testing"
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/discovery"
<add> "github.com/docker/libkv"
<ide> "github.com/docker/libkv/store"
<ide>
<ide> "github.com/go-check/check"
<ide> func (ds *DiscoverySuite) TestInitialize(c *check.C) {
<ide> Endpoints: []string{"127.0.0.1"},
<ide> }
<ide> d := &Discovery{backend: store.CONSUL}
<del> d.Initialize("127.0.0.1", 0, 0)
<add> d.Initialize("127.0.0.1", 0, 0, nil)
<ide> d.store = storeMock
<ide>
<ide> s := d.store.(*FakeStore)
<ide> func (ds *DiscoverySuite) TestInitialize(c *check.C) {
<ide> Endpoints: []string{"127.0.0.1:1234"},
<ide> }
<ide> d = &Discovery{backend: store.CONSUL}
<del> d.Initialize("127.0.0.1:1234/path", 0, 0)
<add> d.Initialize("127.0.0.1:1234/path", 0, 0, nil)
<ide> d.store = storeMock
<ide>
<ide> s = d.store.(*FakeStore)
<ide> func (ds *DiscoverySuite) TestInitialize(c *check.C) {
<ide> Endpoints: []string{"127.0.0.1:1234", "127.0.0.2:1234", "127.0.0.3:1234"},
<ide> }
<ide> d = &Discovery{backend: store.CONSUL}
<del> d.Initialize("127.0.0.1:1234,127.0.0.2:1234,127.0.0.3:1234/path", 0, 0)
<add> d.Initialize("127.0.0.1:1234,127.0.0.2:1234,127.0.0.3:1234/path", 0, 0, nil)
<ide> d.store = storeMock
<ide>
<ide> s = d.store.(*FakeStore)
<ide> func (ds *DiscoverySuite) TestInitialize(c *check.C) {
<ide> c.Assert(d.path, check.Equals, "path/"+discoveryPath)
<ide> }
<ide>
<add>// Extremely limited mock store so we can test initialization
<add>type Mock struct {
<add> // Endpoints passed to InitializeMock
<add> Endpoints []string
<add>
<add> // Options passed to InitializeMock
<add> Options *store.Config
<add>}
<add>
<add>func NewMock(endpoints []string, options *store.Config) (store.Store, error) {
<add> s := &Mock{}
<add> s.Endpoints = endpoints
<add> s.Options = options
<add> return s, nil
<add>}
<add>func (s *Mock) Put(key string, value []byte, opts *store.WriteOptions) error {
<add> return errors.New("Put not supported")
<add>}
<add>func (s *Mock) Get(key string) (*store.KVPair, error) {
<add> return nil, errors.New("Get not supported")
<add>}
<add>func (s *Mock) Delete(key string) error {
<add> return errors.New("Delete not supported")
<add>}
<add>
<add>// Exists mock
<add>func (s *Mock) Exists(key string) (bool, error) {
<add> return false, errors.New("Exists not supported")
<add>}
<add>
<add>// Watch mock
<add>func (s *Mock) Watch(key string, stopCh <-chan struct{}) (<-chan *store.KVPair, error) {
<add> return nil, errors.New("Watch not supported")
<add>}
<add>
<add>// WatchTree mock
<add>func (s *Mock) WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*store.KVPair, error) {
<add> return nil, errors.New("WatchTree not supported")
<add>}
<add>
<add>// NewLock mock
<add>func (s *Mock) NewLock(key string, options *store.LockOptions) (store.Locker, error) {
<add> return nil, errors.New("NewLock not supported")
<add>}
<add>
<add>// List mock
<add>func (s *Mock) List(prefix string) ([]*store.KVPair, error) {
<add> return nil, errors.New("List not supported")
<add>}
<add>
<add>// DeleteTree mock
<add>func (s *Mock) DeleteTree(prefix string) error {
<add> return errors.New("DeleteTree not supported")
<add>}
<add>
<add>// AtomicPut mock
<add>func (s *Mock) AtomicPut(key string, value []byte, previous *store.KVPair, opts *store.WriteOptions) (bool, *store.KVPair, error) {
<add> return false, nil, errors.New("AtomicPut not supported")
<add>}
<add>
<add>// AtomicDelete mock
<add>func (s *Mock) AtomicDelete(key string, previous *store.KVPair) (bool, error) {
<add> return false, errors.New("AtomicDelete not supported")
<add>}
<add>
<add>// Close mock
<add>func (s *Mock) Close() {
<add> return
<add>}
<add>
<add>func (ds *DiscoverySuite) TestInitializeWithCerts(c *check.C) {
<add> cert := `-----BEGIN CERTIFICATE-----
<add>MIIDCDCCAfKgAwIBAgIICifG7YeiQOEwCwYJKoZIhvcNAQELMBIxEDAOBgNVBAMT
<add>B1Rlc3QgQ0EwHhcNMTUxMDAxMjMwMDAwWhcNMjAwOTI5MjMwMDAwWjASMRAwDgYD
<add>VQQDEwdUZXN0IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1wRC
<add>O+flnLTK5ImjTurNRHwSejuqGbc4CAvpB0hS+z0QlSs4+zE9h80aC4hz+6caRpds
<add>+J908Q+RvAittMHbpc7VjbZP72G6fiXk7yPPl6C10HhRSoSi3nY+B7F2E8cuz14q
<add>V2e+ejhWhSrBb/keyXpcyjoW1BOAAJ2TIclRRkICSCZrpXUyXxAvzXfpFXo1RhSb
<add>UywN11pfiCQzDUN7sPww9UzFHuAHZHoyfTr27XnJYVUerVYrCPq8vqfn//01qz55
<add>Xs0hvzGdlTFXhuabFtQnKFH5SNwo/fcznhB7rePOwHojxOpXTBepUCIJLbtNnWFT
<add>V44t9gh5IqIWtoBReQIDAQABo2YwZDAOBgNVHQ8BAf8EBAMCAAYwEgYDVR0TAQH/
<add>BAgwBgEB/wIBAjAdBgNVHQ4EFgQUZKUI8IIjIww7X/6hvwggQK4bD24wHwYDVR0j
<add>BBgwFoAUZKUI8IIjIww7X/6hvwggQK4bD24wCwYJKoZIhvcNAQELA4IBAQDES2cz
<add>7sCQfDCxCIWH7X8kpi/JWExzUyQEJ0rBzN1m3/x8ySRxtXyGekimBqQwQdFqlwMI
<add>xzAQKkh3ue8tNSzRbwqMSyH14N1KrSxYS9e9szJHfUasoTpQGPmDmGIoRJuq1h6M
<add>ej5x1SCJ7GWCR6xEXKUIE9OftXm9TdFzWa7Ja3OHz/mXteii8VXDuZ5ACq6EE5bY
<add>8sP4gcICfJ5fTrpTlk9FIqEWWQrCGa5wk95PGEj+GJpNogjXQ97wVoo/Y3p1brEn
<add>t5zjN9PAq4H1fuCMdNNA+p1DHNwd+ELTxcMAnb2ajwHvV6lKPXutrTFc4umJToBX
<add>FpTxDmJHEV4bzUzh
<add>-----END CERTIFICATE-----
<add>`
<add> key := `-----BEGIN RSA PRIVATE KEY-----
<add>MIIEpQIBAAKCAQEA1wRCO+flnLTK5ImjTurNRHwSejuqGbc4CAvpB0hS+z0QlSs4
<add>+zE9h80aC4hz+6caRpds+J908Q+RvAittMHbpc7VjbZP72G6fiXk7yPPl6C10HhR
<add>SoSi3nY+B7F2E8cuz14qV2e+ejhWhSrBb/keyXpcyjoW1BOAAJ2TIclRRkICSCZr
<add>pXUyXxAvzXfpFXo1RhSbUywN11pfiCQzDUN7sPww9UzFHuAHZHoyfTr27XnJYVUe
<add>rVYrCPq8vqfn//01qz55Xs0hvzGdlTFXhuabFtQnKFH5SNwo/fcznhB7rePOwHoj
<add>xOpXTBepUCIJLbtNnWFTV44t9gh5IqIWtoBReQIDAQABAoIBAHSWipORGp/uKFXj
<add>i/mut776x8ofsAxhnLBARQr93ID+i49W8H7EJGkOfaDjTICYC1dbpGrri61qk8sx
<add>qX7p3v/5NzKwOIfEpirgwVIqSNYe/ncbxnhxkx6tXtUtFKmEx40JskvSpSYAhmmO
<add>1XSx0E/PWaEN/nLgX/f1eWJIlxlQkk3QeqL+FGbCXI48DEtlJ9+MzMu4pAwZTpj5
<add>5qtXo5JJ0jRGfJVPAOznRsYqv864AhMdMIWguzk6EGnbaCWwPcfcn+h9a5LMdony
<add>MDHfBS7bb5tkF3+AfnVY3IBMVx7YlsD9eAyajlgiKu4zLbwTRHjXgShy+4Oussz0
<add>ugNGnkECgYEA/hi+McrZC8C4gg6XqK8+9joD8tnyDZDz88BQB7CZqABUSwvjDqlP
<add>L8hcwo/lzvjBNYGkqaFPUICGWKjeCtd8pPS2DCVXxDQX4aHF1vUur0uYNncJiV3N
<add>XQz4Iemsa6wnKf6M67b5vMXICw7dw0HZCdIHD1hnhdtDz0uVpeevLZ8CgYEA2KCT
<add>Y43lorjrbCgMqtlefkr3GJA9dey+hTzCiWEOOqn9RqGoEGUday0sKhiLofOgmN2B
<add>LEukpKIey8s+Q/cb6lReajDVPDsMweX8i7hz3Wa4Ugp4Xa5BpHqu8qIAE2JUZ7bU
<add>t88aQAYE58pUF+/Lq1QzAQdrjjzQBx6SrBxieecCgYEAvukoPZEC8mmiN1VvbTX+
<add>QFHmlZha3QaDxChB+QUe7bMRojEUL/fVnzkTOLuVFqSfxevaI/km9n0ac5KtAchV
<add>xjp2bTnBb5EUQFqjopYktWA+xO07JRJtMfSEmjZPbbay1kKC7rdTfBm961EIHaRj
<add>xZUf6M+rOE8964oGrdgdLlECgYEA046GQmx6fh7/82FtdZDRQp9tj3SWQUtSiQZc
<add>qhO59Lq8mjUXz+MgBuJXxkiwXRpzlbaFB0Bca1fUoYw8o915SrDYf/Zu2OKGQ/qa
<add>V81sgiVmDuEgycR7YOlbX6OsVUHrUlpwhY3hgfMe6UtkMvhBvHF/WhroBEIJm1pV
<add>PXZ/CbMCgYEApNWVktFBjOaYfY6SNn4iSts1jgsQbbpglg3kT7PLKjCAhI6lNsbk
<add>dyT7ut01PL6RaW4SeQWtrJIVQaM6vF3pprMKqlc5XihOGAmVqH7rQx9rtQB5TicL
<add>BFrwkQE4HQtQBV60hYQUzzlSk44VFDz+jxIEtacRHaomDRh2FtOTz+I=
<add>-----END RSA PRIVATE KEY-----
<add>`
<add> certFile, err := ioutil.TempFile("", "cert")
<add> c.Assert(err, check.IsNil)
<add> defer os.Remove(certFile.Name())
<add> certFile.Write([]byte(cert))
<add> certFile.Close()
<add> keyFile, err := ioutil.TempFile("", "key")
<add> c.Assert(err, check.IsNil)
<add> defer os.Remove(keyFile.Name())
<add> keyFile.Write([]byte(key))
<add> keyFile.Close()
<add>
<add> libkv.AddStore("mock", NewMock)
<add> d := &Discovery{backend: "mock"}
<add> err = d.Initialize("127.0.0.3:1234", 0, 0, map[string]string{
<add> "kv.cacertfile": certFile.Name(),
<add> "kv.certfile": certFile.Name(),
<add> "kv.keyfile": keyFile.Name(),
<add> })
<add> c.Assert(err, check.IsNil)
<add> s := d.store.(*Mock)
<add> c.Assert(s.Options.TLS, check.NotNil)
<add> c.Assert(s.Options.TLS.RootCAs, check.NotNil)
<add> c.Assert(s.Options.TLS.Certificates, check.HasLen, 1)
<add>}
<add>
<ide> func (ds *DiscoverySuite) TestWatch(c *check.C) {
<ide> mockCh := make(chan []*store.KVPair)
<ide>
<ide> func (ds *DiscoverySuite) TestWatch(c *check.C) {
<ide> }
<ide>
<ide> d := &Discovery{backend: store.CONSUL}
<del> d.Initialize("127.0.0.1:1234/path", 0, 0)
<add> d.Initialize("127.0.0.1:1234/path", 0, 0, nil)
<ide> d.store = storeMock
<ide>
<ide> expected := discovery.Entries{
<ide><path>pkg/discovery/nodes/nodes.go
<ide> func Init() {
<ide> }
<ide>
<ide> // Initialize is exported
<del>func (s *Discovery) Initialize(uris string, _ time.Duration, _ time.Duration) error {
<add>func (s *Discovery) Initialize(uris string, _ time.Duration, _ time.Duration, _ map[string]string) error {
<ide> for _, input := range strings.Split(uris, ",") {
<ide> for _, ip := range discovery.Generate(input) {
<ide> entry, err := discovery.NewEntry(ip)
<ide><path>pkg/discovery/nodes/nodes_test.go
<ide> var _ = check.Suite(&DiscoverySuite{})
<ide>
<ide> func (s *DiscoverySuite) TestInitialize(c *check.C) {
<ide> d := &Discovery{}
<del> d.Initialize("1.1.1.1:1111,2.2.2.2:2222", 0, 0)
<add> d.Initialize("1.1.1.1:1111,2.2.2.2:2222", 0, 0, nil)
<ide> c.Assert(len(d.entries), check.Equals, 2)
<ide> c.Assert(d.entries[0].String(), check.Equals, "1.1.1.1:1111")
<ide> c.Assert(d.entries[1].String(), check.Equals, "2.2.2.2:2222")
<ide> }
<ide>
<ide> func (s *DiscoverySuite) TestInitializeWithPattern(c *check.C) {
<ide> d := &Discovery{}
<del> d.Initialize("1.1.1.[1:2]:1111,2.2.2.[2:4]:2222", 0, 0)
<add> d.Initialize("1.1.1.[1:2]:1111,2.2.2.[2:4]:2222", 0, 0, nil)
<ide> c.Assert(len(d.entries), check.Equals, 5)
<ide> c.Assert(d.entries[0].String(), check.Equals, "1.1.1.1:1111")
<ide> c.Assert(d.entries[1].String(), check.Equals, "1.1.1.2:1111")
<ide> func (s *DiscoverySuite) TestInitializeWithPattern(c *check.C) {
<ide>
<ide> func (s *DiscoverySuite) TestWatch(c *check.C) {
<ide> d := &Discovery{}
<del> d.Initialize("1.1.1.1:1111,2.2.2.2:2222", 0, 0)
<add> d.Initialize("1.1.1.1:1111,2.2.2.2:2222", 0, 0, nil)
<ide> expected := discovery.Entries{
<ide> &discovery.Entry{Host: "1.1.1.1", Port: "1111"},
<ide> &discovery.Entry{Host: "2.2.2.2", Port: "2222"}, | 13 |
Java | Java | restore removal of trailing semicolon content | 990a9c74b93b3124dae554e6246b9b75504a5d23 | <ide><path>spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java
<ide> private static String removeSemicolonContentInternal(String requestUri) {
<ide> }
<ide> StringBuilder sb = new StringBuilder(requestUri);
<ide> while (semicolonIndex != -1) {
<del> int slashIndex = requestUri.indexOf('/', semicolonIndex);
<del> if (slashIndex >= 0) {
<del> sb.delete(semicolonIndex, slashIndex);
<add> int slashIndex = requestUri.indexOf('/', semicolonIndex + 1);
<add> if (slashIndex == -1) {
<add> slashIndex = sb.length();
<ide> }
<add> sb.delete(semicolonIndex, slashIndex);
<ide> semicolonIndex = sb.indexOf(";", semicolonIndex);
<ide> }
<ide> return sb.toString(); | 1 |
Javascript | Javascript | fix quaternion.slerp for small angles | 4c6fcc8585ffa21ea7153942deafa4ea4c867161 | <ide><path>src/math/Quaternion.js
<ide> Object.assign( Quaternion.prototype, {
<ide>
<ide> }
<ide>
<del> var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
<add> var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
<ide>
<del> if ( Math.abs( sinHalfTheta ) < 0.001 ) {
<add> if ( sqrSinHalfTheta <= Number.EPSILON ) {
<ide>
<del> this._w = 0.5 * ( w + this._w );
<del> this._x = 0.5 * ( x + this._x );
<del> this._y = 0.5 * ( y + this._y );
<del> this._z = 0.5 * ( z + this._z );
<add> var s = 1 - t;
<add> this._w = s * w + t * this._w;
<add> this._x = s * x + t * this._x;
<add> this._y = s * y + t * this._y;
<add> this._z = s * z + t * this._z;
<ide>
<ide> return this;
<ide>
<ide> }
<ide>
<add> var sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
<ide> var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
<ide> var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
<ide> ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; | 1 |
Ruby | Ruby | add missing requires inside av | 3f2ac795b8f49ad07ec30790fe716cbdac78642c | <ide><path>actionview/lib/action_view/base.rb
<ide> require 'active_support/core_ext/class/attribute_accessors'
<ide> require 'active_support/ordered_options'
<ide> require 'action_view/log_subscriber'
<add>require 'action_view/helpers'
<add>require 'action_view/context'
<add>require 'action_view/template'
<add>require 'action_view/lookup_context'
<ide>
<ide> module ActionView #:nodoc:
<ide> # = Action View Base
<ide><path>actionview/lib/action_view/helpers/record_tag_helper.rb
<add>require 'action_view/record_identifier'
<add>
<ide> module ActionView
<ide> # = Action View Record Tag Helpers
<ide> module Helpers
<ide><path>actionview/lib/action_view/layouts.rb
<add>require "action_view/rendering"
<ide> require "active_support/core_ext/module/remove_method"
<ide>
<del>
<ide> module ActionView
<ide> # Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in
<ide> # repeated setups. The inclusion pattern has pages that look like this:
<ide><path>actionview/lib/action_view/rendering.rb
<add>require "action_view/view_paths"
<ide>
<ide> module ActionView
<ide> # This is a class to fix I18n global state. Whenever you provide I18n.locale during a request, | 4 |
Text | Text | fix minor errata on debugging section [ci-skip] | d578002b9194bbe940030382c031bb885dcce3b2 | <ide><path>guides/source/debugging_rails_applications.md
<ide> It's also possible to use these options together: `backtrace [num] /pattern/`.
<ide>
<ide> #### The outline command
<ide>
<del>This command is similar to `pry` and `irb`'s `ls` command. It will show you what's accessible from you current scope, including:
<add>This command is similar to `pry` and `irb`'s `ls` command. It will show you what's accessible from the current scope, including:
<ide>
<ide> - Local variables
<ide> - Instance variables
<ide> - Class variables
<ide> - Methods & their sources
<del>- ...etc.
<ide>
<ide> ```rb
<ide> ActiveSupport::Configurable#methods: config
<ide> class variables: raise_on_open_redirects
<ide>
<ide> ### Breakpoints
<ide>
<del>There are many ways to insert and trigger a breakpoint in the debugger. In additional to adding debugging statements (e.g. `debugger`) directly in your code, you can also insert breakpoints with commands:
<add>There are many ways to insert and trigger a breakpoint in the debugger. In addition to adding debugging statements (e.g. `debugger`) directly in your code, you can also insert breakpoints with commands:
<ide>
<ide> - `break` (or `b`)
<ide> - `break` - list all breakpoints
<ide> And to remove them, you can use:
<ide>
<ide> #### The break command
<ide>
<del>**Set a breakpoint with specified line number - e.g. `b 28`**
<add>**Set a breakpoint on a specified line number - e.g. `b 28`**
<ide>
<ide> ```rb
<ide> [20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
<ide> See [ruby/debug#408](https://github.com/ruby/debug/issues/408) for details.
<ide> Debugging with the `web-console` gem
<ide> ------------------------------------
<ide>
<del>Web Console is a bit like `debug`, but it runs in the browser. In any page you
<del>are developing, you can request a console in the context of a view or a
<del>controller. The console would be rendered next to your HTML content.
<add>Web Console is a bit like `debug`, but it runs in the browser. You can request a console in the context of a view or a controller on any page. The console would be rendered next to your HTML content.
<ide>
<ide> ### Console
<ide> | 1 |
Text | Text | fix grammatical errors in linux build file | 6832845b91f7a7ae4c58b58ffee0e430cf22f44d | <ide><path>docs/build-instructions/linux.md
<ide> Ubuntu LTS 12.04 64-bit is the recommended platform.
<ide>
<ide> * `sudo apt-get install build-essential git libgnome-keyring-dev fakeroot`
<ide> * Instructions for [Node.js](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager#ubuntu-mint-elementary-os).
<del> * Make sure the command `node` is available after Node.js installation (some sytems install it as `nodejs`).
<add> * Make sure the command `node` is available after Node.js installation (some systems install it as `nodejs`).
<ide> * Use `which node` to check if it is available.
<ide> * Use `sudo update-alternatives --install /usr/bin/node node /usr/bin/nodejs 10` to update it.
<ide>
<ide> If you have problems with permissions don't forget to prefix with `sudo`
<ide>
<ide> To use the newly installed Atom, quit and restart all running Atom instances.
<ide>
<del>5. *Optionally*, you may generate distributable packages of Atom at `$TMPDIR/atom-build`. Currenty, `.deb` and `.rpm` package types are supported. To create a `.deb` package run:
<add>5. *Optionally*, you may generate distributable packages of Atom at `$TMPDIR/atom-build`. Currently, `.deb` and `.rpm` package types are supported. To create a `.deb` package run:
<ide>
<ide> ```sh
<ide> script/grunt mkdeb
<ide> and restart Atom. If Atom now works fine, you can make this setting permanent:
<ide> echo 32768 | sudo tee -a /proc/sys/fs/inotify/max_user_watches
<ide> ```
<ide>
<del>See also https://github.com/atom/atom/issues/2082.
<add>See also [#2082](https://github.com/atom/atom/issues/2082).
<ide>
<ide> ### /usr/bin/env: node: No such file or directory
<ide> | 1 |
Ruby | Ruby | change outdated message | f0601e91bc6bbd9abbc5cf76acfd6685aabc5239 | <ide><path>Library/Homebrew/install.rb
<ide> def install_formula(
<ide> version_upgrade = "#{f.linked_version} -> #{f.pkg_version}"
<ide>
<ide> oh1 <<~EOS
<del> #{f.name} #{f.linked_version} is installed and outdated
<add> #{f.name} #{f.linked_version} is installed but outdated
<ide> Upgrading #{Formatter.identifier(f.name)} #{version_upgrade}
<ide> EOS
<ide> outdated_kegs = outdated_formulae.map(&:linked_keg).select(&:directory?).map { |k| Keg.new(k.resolved_path) } | 1 |
Text | Text | remove confusing note about child process stdio | 189eaa043535c27cde96a863a2f90785913b1071 | <ide><path>doc/api/child_process.md
<ide> stdout in excess of that limit without the output being captured, the child
<ide> process will block waiting for the pipe buffer to accept more data. This is
<ide> identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`
<ide> option if the output will not be consumed.
<del>It is possible to stream data through these pipes in a non-blocking way. Note,
<del>however, that some programs use line-buffered I/O internally. While that does
<del>not affect Node.js, it can mean that data sent to the child process may not be
<del>immediately consumed.
<ide>
<ide> The [`child_process.spawn()`][] method spawns the child process asynchronously,
<ide> without blocking the Node.js event loop. The [`child_process.spawnSync()`][] | 1 |
Java | Java | fix jsonview + httpentity reactive handling | c530745015d5c7031cfcb6f633f3f459ed97935d | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractMessageReaderArgumentResolver.java
<ide> * failure results in an {@link ServerWebInputException}.
<ide> *
<ide> * @author Rossen Stoyanchev
<add> * @author Sebastien Deleuze
<ide> * @since 5.0
<ide> */
<ide> public abstract class AbstractMessageReaderArgumentResolver extends HandlerMethodArgumentResolverSupport {
<ide> public List<HttpMessageReader<?>> getMessageReaders() {
<ide> }
<ide>
<ide>
<add> /**
<add> * Read the body from a method argument with {@link HttpMessageReader}.
<add> * @param bodyParameter the {@link MethodParameter} to read
<add> * @param isBodyRequired true if the body is required
<add> * @param bindingContext the binding context to use
<add> * @param exchange the current exchange
<add> * @return the body
<add> * @see #readBody(MethodParameter, MethodParameter, boolean, BindingContext, ServerWebExchange)
<add> */
<ide> protected Mono<Object> readBody(MethodParameter bodyParameter, boolean isBodyRequired,
<ide> BindingContext bindingContext, ServerWebExchange exchange) {
<add> return this.readBody(bodyParameter, null, isBodyRequired, bindingContext, exchange);
<add> }
<add>
<add> /**
<add> * Read the body from a method argument with {@link HttpMessageReader}.
<add> * @param bodyParameter the {@link MethodParameter} to read
<add> * @param actualParameter the actual {@link MethodParameter} to read; could be different
<add> * from {@code bodyParameter} when processing {@code HttpEntity} for example
<add> * @param isBodyRequired true if the body is required
<add> * @param bindingContext the binding context to use
<add> * @param exchange the current exchange
<add> * @return the body
<add> * @since 5.0.2
<add> */
<add> protected Mono<Object> readBody(MethodParameter bodyParameter, @Nullable MethodParameter actualParameter,
<add> boolean isBodyRequired, BindingContext bindingContext, ServerWebExchange exchange) {
<ide>
<ide> ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParameter);
<add> ResolvableType actualType = (actualParameter == null ?
<add> bodyType : ResolvableType.forMethodParameter(actualParameter));
<ide> Class<?> resolvedType = bodyType.resolve();
<ide> ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
<ide> ResolvableType elementType = (adapter != null ? bodyType.getGeneric() : bodyType);
<ide> protected Mono<Object> readBody(MethodParameter bodyParameter, boolean isBodyReq
<ide> if (reader.canRead(elementType, mediaType)) {
<ide> Map<String, Object> readHints = Collections.emptyMap();
<ide> if (adapter != null && adapter.isMultiValue()) {
<del> Flux<?> flux = reader.read(bodyType, elementType, request, response, readHints);
<add> Flux<?> flux = reader.read(actualType, elementType, request, response, readHints);
<ide> flux = flux.onErrorResume(ex -> Flux.error(handleReadError(bodyParameter, ex)));
<ide> if (isBodyRequired || !adapter.supportsEmpty()) {
<ide> flux = flux.switchIfEmpty(Flux.error(handleMissingBody(bodyParameter)));
<ide> protected Mono<Object> readBody(MethodParameter bodyParameter, boolean isBodyReq
<ide> }
<ide> else {
<ide> // Single-value (with or without reactive type wrapper)
<del> Mono<?> mono = reader.readMono(bodyType, elementType, request, response, readHints);
<add> Mono<?> mono = reader.readMono(actualType, elementType, request, response, readHints);
<ide> mono = mono.onErrorResume(ex -> Mono.error(handleReadError(bodyParameter, ex)));
<ide> if (isBodyRequired || (adapter != null && !adapter.supportsEmpty())) {
<ide> mono = mono.switchIfEmpty(Mono.error(handleMissingBody(bodyParameter)));
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractMessageWriterResultHandler.java
<ide> * to the response with {@link HttpMessageWriter}.
<ide> *
<ide> * @author Rossen Stoyanchev
<add> * @author Sebastien Deleuze
<ide> * @since 5.0
<ide> */
<ide> public abstract class AbstractMessageWriterResultHandler extends HandlerResultHandlerSupport {
<ide> public List<HttpMessageWriter<?>> getMessageWriters() {
<ide> }
<ide>
<ide>
<del> @SuppressWarnings("unchecked")
<add> /**
<add> * Write a given body to the response with {@link HttpMessageWriter}.
<add> * @param body the object to write
<add> * @param bodyParameter the {@link MethodParameter} of the body to write
<add> * @param exchange the current exchange
<add> * @return indicates completion or error
<add> * @see #writeBody(Object, MethodParameter, MethodParameter, ServerWebExchange)
<add> */
<ide> protected Mono<Void> writeBody(@Nullable Object body, MethodParameter bodyParameter, ServerWebExchange exchange) {
<add> return this.writeBody(body, bodyParameter, null, exchange);
<add> }
<add>
<add> /**
<add> * Write a given body to the response with {@link HttpMessageWriter}.
<add> * @param body the object to write
<add> * @param bodyParameter the {@link MethodParameter} of the body to write
<add> * @param actualParameter the actual return type of the method that returned the
<add> * value; could be different from {@code bodyParameter} when processing {@code HttpEntity}
<add> * for example
<add> * @param exchange the current exchange
<add> * @return indicates completion or error
<add> * @since 5.0.2
<add> */
<add> @SuppressWarnings("unchecked")
<add> protected Mono<Void> writeBody(@Nullable Object body, MethodParameter bodyParameter,
<add> @Nullable MethodParameter actualParameter, ServerWebExchange exchange) {
<add>
<ide> ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParameter);
<add> ResolvableType actualType = (actualParameter == null ?
<add> bodyType : ResolvableType.forMethodParameter(actualParameter));
<ide> Class<?> bodyClass = bodyType.resolve();
<ide> ReactiveAdapter adapter = getAdapterRegistry().getAdapter(bodyClass, body);
<ide>
<ide> protected Mono<Void> writeBody(@Nullable Object body, MethodParameter bodyParame
<ide> if (bestMediaType != null) {
<ide> for (HttpMessageWriter<?> writer : getMessageWriters()) {
<ide> if (writer.canWrite(elementType, bestMediaType)) {
<del> return writer.write((Publisher) publisher, bodyType, elementType,
<add> return writer.write((Publisher) publisher, actualType, elementType,
<ide> bestMediaType, request, response, Collections.emptyMap());
<ide> }
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/HttpEntityArgumentResolver.java
<ide> public Mono<Object> resolveArgument(
<ide> MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {
<ide>
<ide> Class<?> entityType = parameter.getParameterType();
<del> return readBody(parameter.nested(), false, bindingContext, exchange)
<add> return readBody(parameter.nested(), parameter, false, bindingContext, exchange)
<ide> .map(body -> createEntity(body, entityType, exchange.getRequest()))
<ide> .defaultIfEmpty(createEntity(null, entityType, exchange.getRequest()));
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandler.java
<ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result)
<ide> Mono<?> returnValueMono;
<ide> MethodParameter bodyParameter;
<ide> ReactiveAdapter adapter = getAdapter(result);
<add> MethodParameter actualParameter = result.getReturnTypeSource();
<ide>
<ide> if (adapter != null) {
<ide> Assert.isTrue(!adapter.isMultiValue(), "Only a single ResponseEntity supported");
<ide> returnValueMono = Mono.from(adapter.toPublisher(result.getReturnValue()));
<del> bodyParameter = result.getReturnTypeSource().nested().nested();
<add> bodyParameter = actualParameter.nested().nested();
<ide> }
<ide> else {
<ide> returnValueMono = Mono.justOrEmpty(result.getReturnValue());
<del> bodyParameter = result.getReturnTypeSource().nested();
<add> bodyParameter = actualParameter.nested();
<ide> }
<ide>
<ide> return returnValueMono.flatMap(returnValue -> {
<ide> else if (returnValue instanceof HttpHeaders) {
<ide> return exchange.getResponse().setComplete();
<ide> }
<ide>
<del> return writeBody(httpEntity.getBody(), bodyParameter, exchange);
<add> return writeBody(httpEntity.getBody(), bodyParameter, actualParameter, exchange);
<ide> });
<ide> }
<ide>
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/JacksonHintsIntegrationTests.java
<ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext;
<ide> import org.springframework.context.annotation.ComponentScan;
<ide> import org.springframework.context.annotation.Configuration;
<add>import org.springframework.http.HttpEntity;
<ide> import org.springframework.http.MediaType;
<add>import org.springframework.http.ResponseEntity;
<ide> import org.springframework.web.bind.annotation.GetMapping;
<ide> import org.springframework.web.bind.annotation.PostMapping;
<ide> import org.springframework.web.bind.annotation.RequestBody;
<ide> public void jsonViewWithMonoResponse() throws Exception {
<ide> assertEquals(expected, performGet("/response/mono", MediaType.APPLICATION_JSON_UTF8, String.class).getBody());
<ide> }
<ide>
<add> @Test // SPR-16098
<add> public void jsonViewWithMonoResponseEntity() throws Exception {
<add> String expected = "{\"withView1\":\"with\"}";
<add> assertEquals(expected, performGet("/response/entity", MediaType.APPLICATION_JSON_UTF8, String.class).getBody());
<add> }
<add>
<ide> @Test
<ide> public void jsonViewWithFluxResponse() throws Exception {
<ide> String expected = "[{\"withView1\":\"with\"},{\"withView1\":\"with\"}]";
<ide> public void jsonViewWithMonoRequest() throws Exception {
<ide> new JacksonViewBean("with", "with", "without"), MediaType.APPLICATION_JSON_UTF8, String.class).getBody());
<ide> }
<ide>
<add> @Test // SPR-16098
<add> public void jsonViewWithEntityMonoRequest() throws Exception {
<add> String expected = "{\"withView1\":\"with\",\"withView2\":null,\"withoutView\":null}";
<add> assertEquals(expected, performPost("/request/entity/mono", MediaType.APPLICATION_JSON,
<add> new JacksonViewBean("with", "with", "without"),
<add> MediaType.APPLICATION_JSON_UTF8, String.class).getBody());
<add> }
<add>
<add> @Test // SPR-16098
<add> public void jsonViewWithEntityFluxRequest() throws Exception {
<add> String expected = "[" +
<add> "{\"withView1\":\"with\",\"withView2\":null,\"withoutView\":null}," +
<add> "{\"withView1\":\"with\",\"withView2\":null,\"withoutView\":null}]";
<add> assertEquals(expected, performPost("/request/entity/flux", MediaType.APPLICATION_JSON,
<add> Arrays.asList(new JacksonViewBean("with", "with", "without"),
<add> new JacksonViewBean("with", "with", "without")),
<add> MediaType.APPLICATION_JSON_UTF8, String.class).getBody());
<add> }
<add>
<ide> @Test
<ide> public void jsonViewWithFluxRequest() throws Exception {
<ide> String expected = "[" +
<ide> public Mono<JacksonViewBean> monoResponse() {
<ide> return Mono.just(new JacksonViewBean("with", "with", "without"));
<ide> }
<ide>
<add> @GetMapping("/response/entity")
<add> @JsonView(MyJacksonView1.class)
<add> public Mono<ResponseEntity<JacksonViewBean>> monoResponseEntity() {
<add> return Mono.just(ResponseEntity.ok(new JacksonViewBean("with", "with", "without")));
<add> }
<add>
<ide> @GetMapping("/response/flux")
<ide> @JsonView(MyJacksonView1.class)
<ide> public Flux<JacksonViewBean> fluxResponse() {
<ide> public Mono<JacksonViewBean> monoRequest(@JsonView(MyJacksonView1.class) @Reques
<ide> return mono;
<ide> }
<ide>
<add> @PostMapping("/request/entity/mono")
<add> public Mono<JacksonViewBean> entityMonoRequest(@JsonView(MyJacksonView1.class) HttpEntity<Mono<JacksonViewBean>> entityMono) {
<add> return entityMono.getBody();
<add> }
<add>
<add> @PostMapping("/request/entity/flux")
<add> public Flux<JacksonViewBean> entityFluxRequest(@JsonView(MyJacksonView1.class) HttpEntity<Flux<JacksonViewBean>> entityFlux) {
<add> return entityFlux.getBody();
<add> }
<add>
<ide> @PostMapping("/request/flux")
<ide> public Flux<JacksonViewBean> fluxRequest(@JsonView(MyJacksonView1.class) @RequestBody Flux<JacksonViewBean> flux) {
<ide> return flux; | 5 |
Text | Text | fix markdown syntax error | 55f82e9a7d6a890670d81ab7b6dcd80c25639a7a | <ide><path>guides/source/plugins.md
<ide> class ActsAsYaffleTest < ActiveSupport::TestCase
<ide> end
<ide> ```
<ide>
<del>Run the test to make sure the last two tests fail with an error that contains "NoMethodError: undefined method `squawk'",
<add>Run the test to make sure the last two tests fail with an error that contains "NoMethodError: undefined method \`squawk'",
<ide> then update `acts_as_yaffle.rb` to look like this:
<ide>
<ide> ```ruby | 1 |
Javascript | Javascript | hide empty sensors in web ui | 6f1caa5c31be89a3bb8ac279bb89404835a10374 | <ide><path>glances/outputs/static/js/services/plugins/glances_sensors.js
<ide> glancesApp.service('GlancesPluginSensors', function(GlancesPlugin) {
<ide> this.sensors = [];
<ide>
<ide> this.setData = function(data, views) {
<del> _.remove(data[_pluginName], function(sensor) {
<del> return sensor.type == "battery" && _.isArray(sensor.value) && _.isEmpty(sensor.value);
<add> data = data[_pluginName];
<add>
<add> _.remove(data, function(sensor) {
<add> return (_.isArray(sensor.value) && _.isEmpty(sensor.value)) || sensor.value === 0;
<ide> });
<ide>
<del> this.sensors = data[_pluginName];
<add> this.sensors = data;
<ide> };
<ide>
<ide> this.getAlert = function(sensor) { | 1 |
Ruby | Ruby | remove lock from method model | fca1906bc22dae61262b1d76672baa64b1cf5315 | <ide><path>actionpack/lib/action_controller/metal/params_wrapper.rb
<ide> def initialize(name, format, include, exclude, klass, model) # :nodoc:
<ide> end
<ide>
<ide> def model
<del> super || synchronize { super || self.model = _default_wrap_model }
<add> super || self.model = _default_wrap_model
<ide> end
<ide>
<ide> def include | 1 |
Text | Text | update readme to reflect jdk 1.7 build prereq | f0f76e493dd58f4f51a05619402aa4ec5de8dc15 | <ide><path>README.md
<ide> simple step-by-step instructions.
<ide> The Spring Framework uses a [Gradle][]-based build system. In the instructions
<ide> below, [`./gradlew`][] is invoked from the root of the source tree and serves as
<ide> a cross-platform, self-contained bootstrap mechanism for the build. The only
<del>prerequisites are [Git][] and JDK 1.6+.
<add>prerequisites are [Git][] and JDK 1.7+.
<ide>
<ide> ### check out sources
<ide> `git clone git://github.com/SpringSource/spring-framework.git` | 1 |
Javascript | Javascript | remove capabilities from webglglprogram | 085ad279fa802ecf34b7b64a50b280ca920a8cf3 | <ide><path>src/renderers/webgl/WebGLProgram.js
<ide> function generateEnvMapBlendingDefine( parameters, material ) {
<ide>
<ide> }
<ide>
<del>function WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities ) {
<add>function WebGLProgram( renderer, extensions, code, material, shader, parameters ) {
<ide>
<ide> var gl = renderer.getContext();
<ide>
<ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters,
<ide>
<ide> var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
<ide>
<del> var customExtensions = capabilities.isWebGL2 ? '' : generateExtensions( material.extensions, parameters, extensions );
<add> var customExtensions = parameters.isWebGL2 ? '' : generateExtensions( material.extensions, parameters, extensions );
<ide>
<ide> var customDefines = generateDefines( defines );
<ide>
<ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters,
<ide> parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
<ide>
<ide> parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
<del> parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
<add> parameters.logarithmicDepthBuffer && ( parameters.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
<ide> 'uniform mat4 modelMatrix;',
<ide> 'uniform vec3 cameraPosition;',
<ide>
<ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters,
<ide> parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
<ide>
<ide> parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
<del> parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
<add> parameters.logarithmicDepthBuffer && ( parameters.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
<ide>
<del> ( ( material.extensions ? material.extensions.shaderTextureLOD : false ) || parameters.envMap ) && ( capabilities.isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) ) ? '#define TEXTURE_LOD_EXT' : '',
<add> ( ( material.extensions ? material.extensions.shaderTextureLOD : false ) || parameters.envMap ) && ( parameters.isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) ) ? '#define TEXTURE_LOD_EXT' : '',
<ide>
<ide> 'uniform vec3 cameraPosition;',
<ide>
<ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters,
<ide> vertexShader = unrollLoops( vertexShader );
<ide> fragmentShader = unrollLoops( fragmentShader );
<ide>
<del> if ( capabilities.isWebGL2 && ! material.isRawShaderMaterial ) {
<add> if ( parameters.isWebGL2 && ! material.isRawShaderMaterial ) {
<ide>
<ide> var isGLSL3ShaderMaterial = false;
<ide>
<ide><path>src/renderers/webgl/WebGLPrograms.js
<ide> function WebGLPrograms( renderer, extensions, capabilities ) {
<ide> shaderID: shaderID,
<ide>
<ide> precision: precision,
<add> isWebGL2: capabilities.isWebGL2,
<ide> supportsVertexTextures: capabilities.vertexTextures,
<ide> outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
<ide> map: !! material.map,
<ide> function WebGLPrograms( renderer, extensions, capabilities ) {
<ide>
<ide> if ( program === undefined ) {
<ide>
<del> program = new WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities );
<add> program = new WebGLProgram( renderer, extensions, code, material, shader, parameters );
<ide> programs.push( program );
<ide>
<ide> } | 2 |
Python | Python | fix a warning on python3 | 82ca6d418588ccd61d663ec8029937290b62d583 | <ide><path>examples/addition_rnn.py
<ide> class colors:
<ide> y = y[indices]
<ide>
<ide> # Explicitly set apart 10% for validation data that we never train over
<del>split_at = len(X) - len(X) / 10
<add>split_at = len(X) - len(X) // 10
<ide> (X_train, X_val) = (slice_X(X, 0, split_at), slice_X(X, split_at))
<ide> (y_train, y_val) = (y[:split_at], y[split_at:])
<ide> | 1 |
Ruby | Ruby | use stricter formula match | 72d13106361c1dda00ea520638080b80cdefad43 | <ide><path>Library/Contributions/cmd/brew-pull.rb
<ide> def tap arg
<ide> `git diff #{revision}.. --name-status`.each_line do |line|
<ide> status, filename = line.split
<ide> # Don't try and do anything to removed files.
<del> if (status == 'A' or status == 'M') and filename.include? '/Formula/' or tap url
<add> if (status == 'A' or status == 'M') and filename.match /Formula\/\w+\.rb$/ or tap url
<ide> formula = File.basename(filename, '.rb')
<ide> ohai "Installing #{formula}"
<ide> install = Formula.factory(formula).installed? ? 'upgrade' : 'install'
<ide><path>Library/Contributions/cmd/brew-test-bot.rb
<ide> def single_commit? start_revision, end_revision
<ide> status, filename = line.split
<ide> # Don't try and do anything to removed files.
<ide> if (status == 'A' or status == 'M')
<del> if filename.include? '/Formula/'
<add> if filename.match /Formula\/\w+\.rb$/
<ide> @formulae << File.basename(filename, '.rb')
<ide> end
<ide> end | 2 |
Python | Python | fix tests for boolean | 04102657b2348c02fe3b870d7fb6b9e941de16d8 | <ide><path>numpy/lib/tests/test_ufunclike.py
<ide> Test isposinf, isneginf, sign
<ide> >>> a = nx.array([nx.Inf, -nx.Inf, nx.NaN, 0.0, 3.0, -3.0])
<ide> >>> U.isposinf(a)
<del>array([True, False, False, False, False, False], dtype=bool)
<add>array([ True, False, False, False, False, False], dtype=bool)
<ide> >>> U.isneginf(a)
<del>array([False, True, False, False, False, False], dtype=bool)
<add>array([False, True, False, False, False, False], dtype=bool)
<ide> >>> olderr = nx.seterr(invalid='ignore')
<ide> >>> nx.sign(a)
<ide> array([ 1., -1., 0., 0., 1., -1.])
<ide> Same thing with an output array:
<ide> >>> y = nx.zeros(a.shape, bool)
<ide> >>> U.isposinf(a, y)
<del>array([True, False, False, False, False, False], dtype=bool)
<add>array([ True, False, False, False, False, False], dtype=bool)
<ide> >>> y
<del>array([True, False, False, False, False, False], dtype=bool)
<add>array([ True, False, False, False, False, False], dtype=bool)
<ide> >>> U.isneginf(a, y)
<del>array([False, True, False, False, False, False], dtype=bool)
<add>array([False, True, False, False, False, False], dtype=bool)
<ide> >>> y
<del>array([False, True, False, False, False, False], dtype=bool)
<add>array([False, True, False, False, False, False], dtype=bool)
<ide> >>> olderr = nx.seterr(invalid='ignore')
<ide> >>> nx.sign(a, y)
<del>array([True, True, False, False, True, True], dtype=bool)
<add>array([ True, True, False, False, True, True], dtype=bool)
<ide> >>> olderr = nx.seterr(**olderr)
<ide> >>> y
<del>array([True, True, False, False, True, True], dtype=bool)
<add>array([ True, True, False, False, True, True], dtype=bool)
<ide>
<ide> Now log2:
<ide> >>> a = nx.array([4.5, 2.3, 6.5]) | 1 |
Text | Text | commit textual suggestions from pr review | 3cd03898cff204aa2589735e39da7630b347c647 | <ide><path>README.md
<ide> Call for Contributions
<ide>
<ide> The NumPy project welcomes your expertise and enthusiasm!
<ide>
<del>Small improvements or fixes are always appreciated. (Issues labeled as "good
<del>first issue" may be a good starting point.) If you are considering larger
<add>Small improvements or fixes are always appreciated; issues labeled as "good
<add>first issue" may be a good starting point. If you are considering larger
<ide> contributions to the source code, please contact us through the [mailing
<ide> list](https://mail.python.org/mailman/listinfo/numpy-discussion) first.
<ide>
<ide> Writing code isn’t the only way to contribute to NumPy. You can also:
<ide> - review pull requests
<ide> - triage issues
<ide> - develop tutorials, presentations, and other educational materials
<del>- maintain and improve our website numpy.org
<add>- maintain and improve [our website](https://github.com/numpy/numpy.org)
<ide> - develop graphic design for our brand assets and promotional materials
<ide> - translate website content
<ide> - help with outreach and onboard new contributors | 1 |
Text | Text | fix typo in writing-your-own-keras-layers.md | 4b6f514cfc3d6c6ce535adff43b5028a98fa5abf | <ide><path>docs/templates/layers/writing-your-own-keras-layers.md
<ide> class MyLayer(Layer):
<ide> return (input_shape[0], self.output_dim)
<ide> ```
<ide>
<del>It is also possible to define Keras layers which have multiple input tensors and multiple ouput tensors. To do this, you should assume that the inputs and outputs of the methods `build(input_shape)`, `call(x)` and `compute_output_shape(input_shape)` are lists. Here is an example, similar to the one above:
<add>It is also possible to define Keras layers which have multiple input tensors and multiple output tensors. To do this, you should assume that the inputs and outputs of the methods `build(input_shape)`, `call(x)` and `compute_output_shape(input_shape)` are lists. Here is an example, similar to the one above:
<ide>
<ide> ```python
<ide> from keras import backend as K | 1 |
Javascript | Javascript | improve coverage on removelisteners functions | 7d2dc90aeb7a7e05588b1623dd03be72970fa222 | <ide><path>test/parallel/test-event-emitter-remove-all-listeners.js
<ide> function listener() {}
<ide> const ee = new events.EventEmitter();
<ide> assert.deepStrictEqual(ee, ee.removeAllListeners());
<ide> }
<add>
<add>{
<add> const ee = new events.EventEmitter();
<add> ee._events = undefined;
<add> assert.strictEqual(ee, ee.removeAllListeners());
<add>}
<ide><path>test/parallel/test-event-emitter-remove-listeners.js
<ide> assert.throws(() => {
<ide>
<ide> ee.removeListener('foo', null);
<ide> }, /^TypeError: "listener" argument must be a function$/);
<add>
<add>{
<add> const ee = new EventEmitter();
<add> const listener = () => {};
<add> ee._events = undefined;
<add> const e = ee.removeListener('foo', listener);
<add> assert.strictEqual(e, ee);
<add>} | 2 |
Javascript | Javascript | fix linting errors | ef6bfe8cb2d22e691a7f1d3dcd9dc0e1039b9b23 | <ide><path>lib/adapters/xhr.js
<ide> module.exports = function xhrAdapter(resolve, reject, config) {
<ide>
<ide> // For IE 8/9 CORS support
<ide> // Only supports POST and GET calls and doesn't returns the response headers.
<del> if (window.XDomainRequest && !("withCredentials" in request) && !isURLSameOrigin(config.url)) {
<add> if (window.XDomainRequest && !('withCredentials' in request) && !isURLSameOrigin(config.url)) {
<ide> request = new window.XDomainRequest();
<ide> }
<ide>
<ide> module.exports = function xhrAdapter(resolve, reject, config) {
<ide> return;
<ide> }
<ide> // Prepare the response
<del> var responseHeaders = "getAllResponseHeaders" in request ? parseHeaders(request.getAllResponseHeaders()) : null;
<add> var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
<ide> var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response;
<ide> var response = {
<ide> data: transformData(
<ide> module.exports = function xhrAdapter(resolve, reject, config) {
<ide> config: config
<ide> };
<ide> // Resolve or reject the Promise based on the status
<del> ((request.status >= 200 && request.status < 300) || (!("status" in request) && request.responseText) ?
<add> ((request.status >= 200 && request.status < 300) || (!('status' in request) && request.responseText) ?
<ide> resolve :
<ide> reject)(response);
<ide>
<ide> module.exports = function xhrAdapter(resolve, reject, config) {
<ide> }
<ide>
<ide> // Add headers to the request
<del> if ("setRequestHeader" in request) {
<add> if ('setRequestHeader' in request) {
<ide> utils.forEach(requestHeaders, function setRequestHeader(val, key) {
<ide> if (!requestData && key.toLowerCase() === 'content-type') {
<ide> // Remove Content-Type if data is undefined | 1 |
Python | Python | remove warning ignoring from nanfuncs | c1ddf841f6a48248b946a990ae750505b8b91686 | <ide><path>numpy/lib/nanfunctions.py
<ide> def _divide_by_count(a, b, out=None):
<ide> in place. If `a` is a numpy scalar, the division preserves its type.
<ide>
<ide> """
<del> with np.errstate(invalid='ignore'):
<add> with np.errstate(invalid='ignore', divide='ignore'):
<ide> if isinstance(a, np.ndarray):
<ide> if out is None:
<ide> return np.divide(a, b, out=a, casting='unsafe')
<ide> def nanmean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue):
<ide> if out is not None and not issubclass(out.dtype.type, np.inexact):
<ide> raise TypeError("If a is inexact, then out must be inexact")
<ide>
<del> # The warning context speeds things up.
<del> with warnings.catch_warnings():
<del> warnings.simplefilter('ignore')
<del> cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=keepdims)
<del> tot = np.sum(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
<del> avg = _divide_by_count(tot, cnt, out=out)
<add> cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=keepdims)
<add> tot = np.sum(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
<add> avg = _divide_by_count(tot, cnt, out=out)
<ide>
<ide> isbad = (cnt == 0)
<ide> if isbad.any():
<ide> def nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue):
<ide> if out is not None and not issubclass(out.dtype.type, np.inexact):
<ide> raise TypeError("If a is inexact, then out must be inexact")
<ide>
<del> with warnings.catch_warnings():
<del> warnings.simplefilter('ignore')
<del>
<del> # Compute mean
<del> if type(arr) is np.matrix:
<del> _keepdims = np._NoValue
<del> else:
<del> _keepdims = True
<del> # we need to special case matrix for reverse compatibility
<del> # in order for this to work, these sums need to be called with
<del> # keepdims=True, however matrix now raises an error in this case, but
<del> # the reason that it drops the keepdims kwarg is to force keepdims=True
<del> # so this used to work by serendipity.
<del> cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=_keepdims)
<del> avg = np.sum(arr, axis=axis, dtype=dtype, keepdims=_keepdims)
<del> avg = _divide_by_count(avg, cnt)
<del>
<del> # Compute squared deviation from mean.
<del> np.subtract(arr, avg, out=arr, casting='unsafe')
<del> arr = _copyto(arr, 0, mask)
<del> if issubclass(arr.dtype.type, np.complexfloating):
<del> sqr = np.multiply(arr, arr.conj(), out=arr).real
<del> else:
<del> sqr = np.multiply(arr, arr, out=arr)
<del>
<del> # Compute variance.
<del> var = np.sum(sqr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
<del> if var.ndim < cnt.ndim:
<del> # Subclasses of ndarray may ignore keepdims, so check here.
<del> cnt = cnt.squeeze(axis)
<del> dof = cnt - ddof
<del> var = _divide_by_count(var, dof)
<add> # Compute mean
<add> if type(arr) is np.matrix:
<add> _keepdims = np._NoValue
<add> else:
<add> _keepdims = True
<add> # we need to special case matrix for reverse compatibility
<add> # in order for this to work, these sums need to be called with
<add> # keepdims=True, however matrix now raises an error in this case, but
<add> # the reason that it drops the keepdims kwarg is to force keepdims=True
<add> # so this used to work by serendipity.
<add> cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=_keepdims)
<add> avg = np.sum(arr, axis=axis, dtype=dtype, keepdims=_keepdims)
<add> avg = _divide_by_count(avg, cnt)
<add>
<add> # Compute squared deviation from mean.
<add> np.subtract(arr, avg, out=arr, casting='unsafe')
<add> arr = _copyto(arr, 0, mask)
<add> if issubclass(arr.dtype.type, np.complexfloating):
<add> sqr = np.multiply(arr, arr.conj(), out=arr).real
<add> else:
<add> sqr = np.multiply(arr, arr, out=arr)
<add>
<add> # Compute variance.
<add> var = np.sum(sqr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
<add> if var.ndim < cnt.ndim:
<add> # Subclasses of ndarray may ignore keepdims, so check here.
<add> cnt = cnt.squeeze(axis)
<add> dof = cnt - ddof
<add> var = _divide_by_count(var, dof)
<ide>
<ide> isbad = (dof <= 0)
<ide> if np.any(isbad):
<ide><path>numpy/lib/tests/test_nanfunctions.py
<ide> import numpy as np
<ide> from numpy.testing import (
<ide> run_module_suite, TestCase, assert_, assert_equal, assert_almost_equal,
<del> assert_warns, assert_no_warnings, assert_raises, assert_array_equal
<add> assert_no_warnings, assert_raises, assert_array_equal, suppress_warnings
<ide> )
<ide>
<ide>
<ide> def test_dtype_from_dtype(self):
<ide> codes = 'efdgFDG'
<ide> for nf, rf in zip(self.nanfuncs, self.stdfuncs):
<ide> for c in codes:
<del> tgt = rf(mat, dtype=np.dtype(c), axis=1).dtype.type
<del> res = nf(mat, dtype=np.dtype(c), axis=1).dtype.type
<del> assert_(res is tgt)
<del> # scalar case
<del> tgt = rf(mat, dtype=np.dtype(c), axis=None).dtype.type
<del> res = nf(mat, dtype=np.dtype(c), axis=None).dtype.type
<del> assert_(res is tgt)
<add> with suppress_warnings() as sup:
<add> sup.filter(np.ComplexWarning)
<add> tgt = rf(mat, dtype=np.dtype(c), axis=1).dtype.type
<add> res = nf(mat, dtype=np.dtype(c), axis=1).dtype.type
<add> assert_(res is tgt)
<add> # scalar case
<add> tgt = rf(mat, dtype=np.dtype(c), axis=None).dtype.type
<add> res = nf(mat, dtype=np.dtype(c), axis=None).dtype.type
<add> assert_(res is tgt)
<ide>
<ide> def test_dtype_from_char(self):
<ide> mat = np.eye(3)
<ide> codes = 'efdgFDG'
<ide> for nf, rf in zip(self.nanfuncs, self.stdfuncs):
<ide> for c in codes:
<del> tgt = rf(mat, dtype=c, axis=1).dtype.type
<del> res = nf(mat, dtype=c, axis=1).dtype.type
<del> assert_(res is tgt)
<del> # scalar case
<del> tgt = rf(mat, dtype=c, axis=None).dtype.type
<del> res = nf(mat, dtype=c, axis=None).dtype.type
<del> assert_(res is tgt)
<add> with suppress_warnings() as sup:
<add> sup.filter(np.ComplexWarning)
<add> tgt = rf(mat, dtype=c, axis=1).dtype.type
<add> res = nf(mat, dtype=c, axis=1).dtype.type
<add> assert_(res is tgt)
<add> # scalar case
<add> tgt = rf(mat, dtype=c, axis=None).dtype.type
<add> res = nf(mat, dtype=c, axis=None).dtype.type
<add> assert_(res is tgt)
<ide>
<ide> def test_dtype_from_input(self):
<ide> codes = 'efdgFDG'
<ide> def test_ddof_too_big(self):
<ide> dsize = [len(d) for d in _rdat]
<ide> for nf, rf in zip(nanfuncs, stdfuncs):
<ide> for ddof in range(5):
<del> with warnings.catch_warnings(record=True) as w:
<del> warnings.simplefilter('always')
<add> with suppress_warnings() as sup:
<add> sup.record(RuntimeWarning)
<add> sup.filter(np.ComplexWarning)
<ide> tgt = [ddof >= d for d in dsize]
<ide> res = nf(_ndat, axis=1, ddof=ddof)
<ide> assert_equal(np.isnan(res), tgt)
<ide> if any(tgt):
<del> assert_(len(w) == 1)
<del> assert_(issubclass(w[0].category, RuntimeWarning))
<add> assert_(len(sup.log) == 1)
<ide> else:
<del> assert_(len(w) == 0)
<add> assert_(len(sup.log) == 0)
<ide>
<ide> def test_allnans(self):
<ide> mat = np.array([np.nan]*9).reshape(3, 3)
<ide> def test_result_values(self):
<ide> def test_allnans(self):
<ide> mat = np.array([np.nan]*9).reshape(3, 3)
<ide> for axis in [None, 0, 1]:
<del> with warnings.catch_warnings(record=True) as w:
<del> warnings.simplefilter('always')
<del> warnings.simplefilter('ignore', FutureWarning)
<add> with suppress_warnings() as sup:
<add> sup.record(RuntimeWarning)
<add>
<ide> assert_(np.isnan(np.nanmedian(mat, axis=axis)).all())
<ide> if axis is None:
<del> assert_(len(w) == 1)
<add> assert_(len(sup.log) == 1)
<ide> else:
<del> assert_(len(w) == 3)
<del> assert_(issubclass(w[0].category, RuntimeWarning))
<add> assert_(len(sup.log) == 3)
<ide> # Check scalar
<ide> assert_(np.isnan(np.nanmedian(np.nan)))
<ide> if axis is None:
<del> assert_(len(w) == 2)
<add> assert_(len(sup.log) == 2)
<ide> else:
<del> assert_(len(w) == 4)
<del> assert_(issubclass(w[0].category, RuntimeWarning))
<add> assert_(len(sup.log) == 4)
<ide>
<ide> def test_empty(self):
<ide> mat = np.zeros((0, 3))
<ide> def test_extended_axis_invalid(self):
<ide>
<ide> def test_float_special(self):
<ide> with warnings.catch_warnings(record=True):
<del> warnings.simplefilter('ignore', RuntimeWarning)
<add> warnings.simplefilter('always', RuntimeWarning)
<ide> a = np.array([[np.inf, np.nan], [np.nan, np.nan]])
<ide> assert_equal(np.nanmedian(a, axis=0), [np.inf, np.nan])
<ide> assert_equal(np.nanmedian(a, axis=1), [np.inf, np.nan])
<ide><path>numpy/lib/tests/test_twodim_base.py
<ide>
<ide> from numpy.testing import (
<ide> TestCase, run_module_suite, assert_equal, assert_array_equal,
<del> assert_array_max_ulp, assert_array_almost_equal, assert_raises
<add> assert_array_max_ulp, assert_array_almost_equal, assert_raises,
<ide> )
<ide>
<ide> from numpy import ( | 3 |
Javascript | Javascript | add vimeo to connect sources | 6eca181f6f3857865b80acae48a7dfd354ac2fe2 | <ide><path>server/server.js
<ide> app.use(helmet.csp({
<ide> 'http://cdn.inspectlet.com/inspectlet.js',
<ide> 'http://www.freecodecamp.org'
<ide> ].concat(trusted),
<del> 'connect-src': [].concat(trusted),
<add> 'connect-src': [
<add> 'vimeo.com'
<add> ].concat(trusted),
<ide> styleSrc: [
<ide> '*.googleapis.com',
<ide> '*.gstatic.com' | 1 |
Text | Text | remove styleguide content from `readme.md` | 5659eeaadd750e404152c731728ebf922c824226 | <ide><path>website/README.md
<ide> rendered version is available at https://spacy.io/styleguide._
<ide>
<ide> </Comment>
<ide>
<del>The [spacy.io](https://spacy.io) website is implemented using
<del>[Gatsby](https://www.gatsbyjs.org) with
<del>[Remark](https://github.com/remarkjs/remark) and [MDX](https://mdxjs.com/). This
<del>allows authoring content in **straightforward Markdown** without the usual
<del>limitations. Standard elements can be overwritten with powerful
<del>[React](http://reactjs.org/) components and wherever Markdown syntax isn't
<del>enough, JSX components can be used.
<del>
<del>> #### Contributing to the site
<del>>
<del>> The docs can always use another example or more detail, and they should always
<del>> be up to date and not misleading. We always appreciate a
<del>> [pull request](https://github.com/explosion/spaCy/pulls). To quickly find the
<del>> correct file to edit, simply click on the "Suggest edits" button at the bottom
<del>> of a page.
<del>>
<del>> For more details on editing the site locally, see the installation
<del>> instructions and markdown reference below.
<del>
<del>## Logo {#logo source="website/src/images/logo.svg"}
<del>
<del>import { Logos } from 'widgets/styleguide'
<del>
<del>If you would like to use the spaCy logo on your site, please get in touch and
<del>ask us first. However, if you want to show support and tell others that your
<del>project is using spaCy, you can grab one of our
<del>[spaCy badges](/usage/spacy-101#faq-project-with-spacy).
<del>
<del><Logos />
<del>
<del>## Colors {#colors}
<del>
<del>import { Colors, Patterns } from 'widgets/styleguide'
<del>
<del><Colors />
<del>
<del>### Patterns
<del>
<del><Patterns />
<del>
<del>## Typography {#typography}
<del>
<del>import { H1, H2, H3, H4, H5, Label, InlineList, Comment } from
<del>'components/typography'
<del>
<del>> #### Markdown
<del>>
<del>> ```markdown_
<del>> ## Headline 2
<del>> ## Headline 2 {#some_id}
<del>> ## Headline 2 {#some_id tag="method"}
<del>> ```
<del>>
<del>> #### JSX
<del>>
<del>> ```jsx
<del>> <H2>Headline 2</H2>
<del>> <H2 id="some_id">Headline 2</H2>
<del>> <H2 id="some_id" tag="method">Headline 2</H2>
<del>> ```
<del>
<del>Headlines are set in
<del>[HK Grotesk](http://cargocollective.com/hanken/HK-Grotesk-Open-Source-Font) by
<del>Hanken Design. All other body text and code uses the best-matching default
<del>system font to provide a "native" reading experience. All code uses the
<del>[JetBrains Mono](https://www.jetbrains.com/lp/mono/) typeface by JetBrains.
<del>
<del><Infobox title="Important note" variant="warning">
<del>
<del>Level 2 headings are automatically wrapped in `<section>` elements at compile
<del>time, using a custom
<del>[Markdown transformer](https://github.com/explosion/spaCy/tree/master/website/plugins/remark-wrap-section.js).
<del>This makes it easier to highlight the section that's currently in the viewpoint
<del>in the sidebar menu.
<del>
<del></Infobox>
<del>
<del><div>
<del><H1>Headline 1</H1>
<del><H2>Headline 2</H2>
<del><H3>Headline 3</H3>
<del><H4>Headline 4</H4>
<del><H5>Headline 5</H5>
<del><Label>Label</Label>
<del></div>
<del>
<del>---
<del>
<del>The following optional attributes can be set on the headline to modify it. For
<del>example, to add a tag for the documented type or mark features that have been
<del>introduced in a specific version or require statistical models to be loaded.
<del>Tags are also available as standalone `<Tag />` components.
<del>
<del>| Argument | Example | Result |
<del>| -------- | -------------------------- | ----------------------------------------- |
<del>| `tag` | `{tag="method"}` | <Tag>method</Tag> |
<del>| `new` | `{new="3"}` | <Tag variant="new">3</Tag> |
<del>| `model` | `{model="tagger, parser"}` | <Tag variant="model">tagger, parser</Tag> |
<del>| `hidden` | `{hidden="true"}` | |
<del>
<del>## Elements {#elements}
<del>
<del>### Links {#links}
<del>
<del>> #### Markdown
<del>>
<del>> ```markdown
<del>> [I am a link](https://spacy.io)
<del>> ```
<del>>
<del>> #### JSX
<del>>
<del>> ```jsx
<del>> <Link to="https://spacy.io">I am a link</Link>
<del>> ```
<del>
<del>Special link styles are used depending on the link URL.
<del>
<del>- [I am a regular external link](https://explosion.ai)
<del>- [I am a link to the documentation](/api/doc)
<del>- [I am a link to an architecture](/api/architectures#HashEmbedCNN)
<del>- [I am a link to a model](/models/en#en_core_web_sm)
<del>- [I am a link to GitHub](https://github.com/explosion/spaCy)
<del>
<del>### Abbreviations {#abbr}
<del>
<del>import { Abbr } from 'components/typography'
<del>
<del>> #### JSX
<del>>
<del>> ```jsx
<del>> <Abbr title="Explanation">Abbreviation</Abbr>
<del>> ```
<del>
<del>Some text with <Abbr title="Explanation here">an abbreviation</Abbr>. On small
<del>screens, I collapse and the explanation text is displayed next to the
<del>abbreviation.
<del>
<del>### Tags {#tags}
<del>
<del>import Tag from 'components/tag'
<del>
<del>> ```jsx
<del>> <Tag>method</Tag>
<del>> <Tag variant="new">4</Tag>
<del>> <Tag variant="model">tagger, parser</Tag>
<del>> ```
<del>
<del>Tags can be used together with headlines, or next to properties across the
<del>documentation, and combined with tooltips to provide additional information. An
<del>optional `variant` argument can be used for special tags. `variant="new"` makes
<del>the tag take a version number to mark new features. Using the component,
<del>visibility of this tag can later be toggled once the feature isn't considered
<del>new anymore. Setting `variant="model"` takes a description of model capabilities
<del>and can be used to mark features that require a respective model to be
<del>installed.
<del>
<del><InlineList>
<del>
<del><Tag>method</Tag> <Tag variant="new">4</Tag> <Tag variant="model">tagger,
<del>parser</Tag>
<del>
<del></InlineList>
<del>
<del>### Buttons {#buttons}
<del>
<del>import Button from 'components/button'
<del>
<del>> ```jsx
<del>> <Button to="#" variant="primary">Primary small</Button>
<del>> <Button to="#" variant="secondary">Secondary small</Button>
<del>> ```
<del>
<del>Link buttons come in two variants, `primary` and `secondary` and two sizes, with
<del>an optional `large` size modifier. Since they're mostly used as enhanced links,
<del>the buttons are implemented as styled links instead of native button elements.
<del>
<del><InlineList><Button to="#" variant="primary">Primary small</Button>
<del><Button to="#" variant="secondary">Secondary small</Button></InlineList>
<del>
<del><br />
<del>
<del><InlineList><Button to="#" variant="primary" large>Primary large</Button>
<del><Button to="#" variant="secondary" large>Secondary large</Button></InlineList>
<del>
<del>## Components
<del>
<del>### Table {#table}
<del>
<del>> #### Markdown
<del>>
<del>> ```markdown_
<del>> | Header 1 | Header 2 |
<del>> | -------- | -------- |
<del>> | Column 1 | Column 2 |
<del>> ```
<del>>
<del>> #### JSX
<del>>
<del>> ```markup
<del>> <Table>
<del>> <Tr><Th>Header 1</Th><Th>Header 2</Th></Tr></thead>
<del>> <Tr><Td>Column 1</Td><Td>Column 2</Td></Tr>
<del>> </Table>
<del>> ```
<del>
<del>Tables are used to present data and API documentation. Certain keywords can be
<del>used to mark a footer row with a distinct style, for example to visualize the
<del>return values of a documented function.
<del>
<del>| Header 1 | Header 2 | Header 3 | Header 4 |
<del>| ----------- | -------- | :------: | -------: |
<del>| Column 1 | Column 2 | Column 3 | Column 4 |
<del>| Column 1 | Column 2 | Column 3 | Column 4 |
<del>| Column 1 | Column 2 | Column 3 | Column 4 |
<del>| Column 1 | Column 2 | Column 3 | Column 4 |
<del>| **RETURNS** | Column 2 | Column 3 | Column 4 |
<del>
<del>Tables also support optional "divider" rows that are typically used to denote
<del>keyword-only arguments in API documentation. To turn a row into a dividing
<del>headline, it should only include content in its first cell, and its value should
<del>be italicized:
<del>
<del>> #### Markdown
<del>>
<del>> ```markdown_
<del>> | Header 1 | Header 2 | Header 3 |
<del>> | -------- | -------- | -------- |
<del>> | Column 1 | Column 2 | Column 3 |
<del>> | _Hello_ | | |
<del>> | Column 1 | Column 2 | Column 3 |
<del>> ```
<del>
<del>| Header 1 | Header 2 | Header 3 |
<del>| -------- | -------- | -------- |
<del>| Column 1 | Column 2 | Column 3 |
<del>| _Hello_ | | |
<del>| Column 1 | Column 2 | Column 3 |
<del>
<del>### Type Annotations {#type-annotations}
<del>
<del>> #### Markdown
<del>>
<del>> ```markdown_
<del>> ~~Model[List[Doc], Floats2d]~~
<del>> ```
<del>>
<del>> #### JSX
<del>>
<del>> ```markup
<del>> <TypeAnnotation>Model[List[Doc], Floats2d]</Typeannotation>
<del>> ```
<del>
<del>Type annotations are special inline code blocks are used to describe Python
<del>types in the [type hints](https://docs.python.org/3/library/typing.html) format.
<del>The special component will split the type, apply syntax highlighting and link
<del>all types that specify links in `meta/type-annotations.json`. Types can link to
<del>internal or external documentation pages. To make it easy to represent the type
<del>annotations in Markdown, the rendering "hijacks" the `~~` tags that would
<del>typically be converted to a `<del>` element – but in this case, text surrounded
<del>by `~~` becomes a type annotation.
<del>
<del>- ~~Dict[str, List[Union[Doc, Span]]]~~
<del>- ~~Model[List[Doc], List[numpy.ndarray]]~~
<del>
<del>Type annotations support a special visual style in tables and will render as a
<del>separate row, under the cell text. This allows the API docs to display complex
<del>types without taking up too much space in the cell. The type annotation should
<del>always be the **last element** in the row.
<del>
<del>> #### Markdown
<del>>
<del>> ```markdown_
<del>> | Header 1 | Header 2 |
<del>> | -------- | ----------------------- |
<del>> | Column 1 | Column 2 ~~List[Doc]~~ |
<del>> ```
<del>
<del>| Name | Description |
<del>| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<del>| `vocab` | The shared vocabulary. ~~Vocab~~ |
<del>| `model` | The Thinc [`Model`](https://thinc.ai/docs/api-model) wrapping the transformer. ~~Model[List[Doc], FullTransformerBatch]~~ |
<del>| `set_extra_annotations` | Function that takes a batch of `Doc` objects and transformer outputs and can set additional annotations on the `Doc`. ~~Callable[[List[Doc], FullTransformerBatch], None]~~ |
<del>
<del>### List {#list}
<del>
<del>> #### Markdown
<del>>
<del>> ```markdown_
<del>> 1. One
<del>> 2. Two
<del>> ```
<del>>
<del>> #### JSX
<del>>
<del>> ```markup
<del>> <Ol>
<del>> <Li>One</Li>
<del>> <Li>Two</Li>
<del>> </Ol>
<del>> ```
<del>
<del>Lists are available as bulleted and numbered. Markdown lists are transformed
<del>automatically.
<del>
<del>- I am a bulleted list
<del>- I have nice bullets
<del>- Lorem ipsum dolor
<del>- consectetur adipiscing elit
<del>
<del>1. I am an ordered list
<del>2. I have nice numbers
<del>3. Lorem ipsum dolor
<del>4. consectetur adipiscing elit
<del>
<del>### Aside {#aside}
<del>
<del>> #### Markdown
<del>>
<del>> ```markdown_
<del>> > #### Aside title
<del>> > This is aside text.
<del>> ```
<del>>
<del>> #### JSX
<del>>
<del>> ```jsx
<del>> <Aside title="Aside title">This is aside text.</Aside>
<del>> ```
<del>
<del>Asides can be used to display additional notes and content in the right-hand
<del>column. Asides can contain text, code and other elements if needed. Visually,
<del>asides are moved to the side on the X-axis, and displayed at the same level they
<del>were inserted. On small screens, they collapse and are rendered in their
<del>original position, in between the text.
<del>
<del>To make them easier to use in Markdown, paragraphs formatted as blockquotes will
<del>turn into asides by default. Level 4 headlines (with a leading `####`) will
<del>become aside titles.
<del>
<del>### Code Block {#code-block}
<del>
<del>> #### Markdown
<del>>
<del>> ````markdown_
<del>> ```python
<del>> ### This is a title
<del>> import spacy
<del>> ```
<del>> ````
<del>>
<del>> #### JSX
<del>>
<del>> ```jsx
<del>> <CodeBlock title="This is a title" lang="python">
<del>> import spacy
<del>> </CodeBlock>
<del>> ```
<del>
<del>Code blocks use the [Prism](http://prismjs.com/) syntax highlighter with a
<del>custom theme. The language can be set individually on each block, and defaults
<del>to raw text with no highlighting. An optional label can be added as the first
<del>line with the prefix `####` (Python-like) and `///` (JavaScript-like). the
<del>indented block as plain text and preserve whitespace.
<del>
<del>```python
<del>### Using spaCy
<del>import spacy
<del>nlp = spacy.load("en_core_web_sm")
<del>doc = nlp("This is a sentence.")
<del>for token in doc:
<del> print(token.text, token.pos_)
<del>```
<del>
<del>Code blocks and also specify an optional range of line numbers to highlight by
<del>adding `{highlight="..."}` to the headline. Acceptable ranges are spans like
<del>`5-7`, but also `5-7,10` or `5-7,10,13-14`.
<del>
<del>> #### Markdown
<del>>
<del>> ````markdown_
<del>> ```python
<del>> ### This is a title {highlight="1-2"}
<del>> import spacy
<del>> nlp = spacy.load("en_core_web_sm")
<del>> ```
<del>> ````
<del>
<del>```python
<del>### Using the matcher {highlight="5-7"}
<del>import spacy
<del>from spacy.matcher import Matcher
<del>
<del>nlp = spacy.load('en_core_web_sm')
<del>matcher = Matcher(nlp.vocab)
<del>pattern = [{"LOWER": "hello"}, {"IS_PUNCT": True}, {"LOWER": "world"}]
<del>matcher.add("HelloWorld", None, pattern)
<del>doc = nlp("Hello, world! Hello world!")
<del>matches = matcher(doc)
<del>```
<del>
<del>Adding `{executable="true"}` to the title turns the code into an executable
<del>block, powered by [Binder](https://mybinder.org) and
<del>[Juniper](https://github.com/ines/juniper). If JavaScript is disabled, the
<del>interactive widget defaults to a regular code block.
<del>
<del>> #### Markdown
<del>>
<del>> ````markdown_
<del>> ```python
<del>> ### {executable="true"}
<del>> import spacy
<del>> nlp = spacy.load("en_core_web_sm")
<del>> ```
<del>> ````
<del>
<del>```python
<del>### {executable="true"}
<del>import spacy
<del>nlp = spacy.load("en_core_web_sm")
<del>doc = nlp("This is a sentence.")
<del>for token in doc:
<del> print(token.text, token.pos_)
<del>```
<del>
<del>If a code block only contains a URL to a GitHub file, the raw file contents are
<del>embedded automatically and syntax highlighting is applied. The link to the
<del>original file is shown at the top of the widget.
<del>
<del>> #### Markdown
<del>>
<del>> ````markdown_
<del>> ```python
<del>> https://github.com/...
<del>> ```
<del>> ````
<del>>
<del>> #### JSX
<del>>
<del>> ```jsx
<del>> <GitHubCode url="https://github.com/..." lang="python" />
<del>> ```
<del>
<del>```python
<del>https://github.com/explosion/spaCy/tree/master/spacy/language.py
<del>```
<del>
<del>### Infobox {#infobox}
<del>
<del>import Infobox from 'components/infobox'
<del>
<del>> #### JSX
<del>>
<del>> ```jsx
<del>> <Infobox title="Information">Regular infobox</Infobox>
<del>> <Infobox title="Important note" variant="warning">This is a warning.</Infobox>
<del>> <Infobox title="Be careful!" variant="danger">This is dangerous.</Infobox>
<del>> ```
<del>
<del>Infoboxes can be used to add notes, updates, warnings or additional information
<del>to a page or section. Semantically, they're implemented and interpreted as an
<del>`aside` element. Infoboxes can take an optional `title` argument, as well as an
<del>optional `variant` (either `"warning"` or `"danger"`).
<del>
<del><Infobox title="This is an infobox">
<del>
<del>If needed, an infobox can contain regular text, `inline code`, lists and other
<del>blocks.
<del>
<del></Infobox>
<del>
<del><Infobox title="This is a warning" variant="warning">
<del>
<del>If needed, an infobox can contain regular text, `inline code`, lists and other
<del>blocks.
<del>
<del></Infobox>
<del>
<del><Infobox title="This is dangerous" variant="danger">
<del>
<del>If needed, an infobox can contain regular text, `inline code`, lists and other
<del>blocks.
<del>
<del></Infobox>
<del>
<del>### Accordion {#accordion}
<del>
<del>import Accordion from 'components/accordion'
<del>
<del>> #### JSX
<del>>
<del>> ```jsx
<del>> <Accordion title="This is an accordion">
<del>> Accordion content goes here.
<del>> </Accordion>
<del>> ```
<del>
<del>Accordions are collapsible sections that are mostly used for lengthy tables,
<del>like the tag and label annotation schemes for different languages. They all need
<del>to be presented – but chances are the user doesn't actually care about _all_ of
<del>them, especially not at the same time. So it's fairly reasonable to hide them
<del>begin a click. This particular implementation was inspired by the amazing
<del>[Inclusive Components blog](https://inclusive-components.design/collapsible-sections/).
<del>
<del><Accordion title="This is an accordion">
<del>
<del>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque enim ante,
<del>pretium a orci eget, varius dignissim augue. Nam eu dictum mauris, id tincidunt
<del>nisi. Integer commodo pellentesque tincidunt. Nam at turpis finibus tortor
<del>gravida sodales tincidunt sit amet est. Nullam euismod arcu in tortor auctor,
<del>sit amet dignissim justo congue.
<del>
<del></Accordion>
<del>
<ide> ## Setup and installation {#setup}
<ide>
<ide> Before running the setup, make sure your versions of
<ide> docker build -t spacy-io .
<ide> This will take some time, so if you want to use the prebuilt image you'll save a
<ide> bit of time.
<ide>
<del>## Markdown reference {#markdown}
<del>
<del>All page content and page meta lives in the `.md` files in the `/docs`
<del>directory. The frontmatter block at the top of each file defines the page title
<del>and other settings like the sidebar menu.
<del>
<del>````markdown
<del>---
<del>title: Page title
<del>---
<del>
<del>## Headline starting a section {#some_id}
<del>
<del>This is a regular paragraph with a [link](https://spacy.io) and **bold text**.
<del>
<del>> #### This is an aside title
<del>>
<del>> This is aside text.
<del>
<del>### Subheadline
<del>
<del>| Header 1 | Header 2 |
<del>| -------- | -------- |
<del>| Column 1 | Column 2 |
<del>
<del>```python
<del>### Code block title {highlight="2-3"}
<del>import spacy
<del>nlp = spacy.load("en_core_web_sm")
<del>doc = nlp("Hello world")
<del>```
<del>
<del><Infobox title="Important note" variant="warning">
<del>
<del>This is content in the infobox.
<del>
<del></Infobox>
<del>````
<del>
<del>In addition to the native markdown elements, you can use the components
<del>[`<Infobox />`][infobox], [`<Accordion />`][accordion], [`<Abbr />`][abbr] and
<del>[`<Tag />`][tag] via their JSX syntax.
<del>
<del>[infobox]: https://spacy.io/styleguide#infobox
<del>[accordion]: https://spacy.io/styleguide#accordion
<del>[abbr]: https://spacy.io/styleguide#abbr
<del>[tag]: https://spacy.io/styleguide#tag
<del>
<ide> ## Project structure {#structure}
<ide>
<ide> ```yaml
<ide> In addition to the native markdown elements, you can use the components
<ide> ├── gatsby-node.js # Node-specific hooks for Gatsby
<ide> └── package.json # package settings and dependencies
<ide> ```
<del>
<del>## Editorial {#editorial}
<del>
<del>- "spaCy" should always be spelled with a lowercase "s" and a capital "C",
<del> unless it specifically refers to the Python package or Python import `spacy`
<del> (in which case it should be formatted as code).
<del> - ✅ spaCy is a library for advanced NLP in Python.
<del> - ❌ Spacy is a library for advanced NLP in Python.
<del> - ✅ First, you need to install the `spacy` package from pip.
<del>- Mentions of code, like function names, classes, variable names etc. in inline
<del> text should be formatted as `code`.
<del> - ✅ "Calling the `nlp` object on a text returns a `Doc`."
<del>- Objects that have pages in the [API docs](/api) should be linked – for
<del> example, [`Doc`](/api/doc) or [`Language.to_disk`](/api/language#to_disk). The
<del> mentions should still be formatted as code within the link. Links pointing to
<del> the API docs will automatically receive a little icon. However, if a paragraph
<del> includes many references to the API, the links can easily get messy. In that
<del> case, we typically only link the first mention of an object and not any
<del> subsequent ones.
<del> - ✅ The [`Span`](/api/span) and [`Token`](/api/token) objects are views of a
<del> [`Doc`](/api/doc). [`Span.as_doc`](/api/span#as_doc) creates a `Doc` object
<del> from a `Span`.
<del> - ❌ The [`Span`](/api/span) and [`Token`](/api/token) objects are views of a
<del> [`Doc`](/api/doc). [`Span.as_doc`](/api/span#as_doc) creates a
<del> [`Doc`](/api/doc) object from a [`Span`](/api/span).
<del>
<del>* Other things we format as code are: references to trained pipeline packages
<del> like `en_core_web_sm` or file names like `code.py` or `meta.json`.
<del>
<del> - ✅ After training, the `config.cfg` is saved to disk.
<del>
<del>* [Type annotations](#type-annotations) are a special type of code formatting,
<del> expressed by wrapping the text in `~~` instead of backticks. The result looks
<del> like this: ~~List[Doc]~~. All references to known types will be linked
<del> automatically.
<del>
<del> - ✅ The model has the input type ~~List[Doc]~~ and it outputs a
<del> ~~List[Array2d]~~.
<del>
<del>* We try to keep links meaningful but short.
<del> - ✅ For details, see the usage guide on
<del> [training with custom code](/usage/training#custom-code).
<del> - ❌ For details, see
<del> [the usage guide on training with custom code](/usage/training#custom-code).
<del> - ❌ For details, see the usage guide on training with custom code
<del> [here](/usage/training#custom-code). | 1 |
Text | Text | add translation kr/threejs-game.md | 682f4bd31093fe1fd5b70cb40c8f83bd245d5371 | <ide><path>threejs/lessons/kr/threejs-game.md
<add>Title: Three.js로 게임 만들기
<add>Description: Three.js로 게임을 만들어봅니다
<add>Category: solutions
<add>TOC: 게임 만들기
<add>
<add>제가 꽤 많이 받았던 질문 중 하나가 Three.js로 게임을 만드는 방법에 관한 것이었습니다. 기초적인 것이긴 해도 부디 이 글에 여러분이 원했던 내용이 있다면 좋겠네요.
<add>
<add>글을 쓰는 현재를 기준으로, 아마 이 글이 이 시리즈에서 가장 긴 글이 될 것 같습니다. 예제로 쓴 코드가 지나치게 전문적으로 보일 수도 있지만 그건 예제를 만들며 문제가 생길 때마다 이전에 제가 실제로 만들었던 게임의 코드를 가져와서 그렇습니다. 또한 왜 이런 해결책을 썼는지 최대한 적으려고 했으니 길 수밖에 없죠. 물론 만들려는 게임의 규모가 작다면 이런 해결책이 전부 필요 없을 수 있습니다. 하지만 예제로 구현한 것도 굉장히 간단한 게임에 속합니다. 통상적으로 3D 캐릭터가 2D 캐릭터보다 더 복잡하니 처리해줘야 할 것이 많을 수밖에 없죠.
<add>
<add>팩맨(PacMan)을 2D로 구현한다면 팩맨이 코너를 돌 때 바로 90도 꺾기만 하면 됩니다. 프레임 사이에 따로 처리해줘야 할 것이 없죠. 하지만 3D의 세계에서는 바로 방향을 틀기보다 몇 프레임에 걸쳐 서서히 방향을 트는 게 일반적입니다. 아주 간단한 차이점이지만, 이것 때문에 작업이 훨씬 복잡해집니다.
<add>
<add>이 글에서 다룰 내용은 Three.js에 관한 것이라고 보기 어렵습니다. 왜냐하면 **Three.js는 게임 엔진이 아니기 때문**이죠. Three.js는 3D 라이브러리입니다. 3D 요소를 계열화하는 [씬 그래프](threejs-scenegraph.html)와 3D 요소를 렌더링하도록 도와주는 기능 등을 제공하죠. 하지만 게임과 관련한 기능은 지원하지 않습니다. 충돌(collision), 물리(physics), 입력 시스템, 패스 파인딩(path finding) 등등.. 이런 기능은 직접 만들어야 합니다.
<add>
<add>결국 이 글의 *미완성* 게임을 만드는 데 꽤 많은 코드를 썼습니다. 아까 말했듯 제가 코드를 너무 지나치게 짰을 수도 있고, 더 간단한 해결책이 있을 수도 있으나, 저는 글을 마무리한 지금도 충분히 많은 코드를 썼는지, 설명을 빠뜨린 것이 없는지 걱정됩니다.
<add>
<add>이 글에서 쓴 방법은 대부분 [유니티(Unity) 엔진](https://unity.com)의 영향을 크게 받았습니다. 하지만 유니티를 잘 모른다고 해서 이 글을 읽는 게 어렵진 않을 겁니다. 1000개의 기능이 있다면 그 중 10개 정도 밖에 쓰지 않았거든요.
<add>
<add>먼저 Three.js 부분부터 시작해봅시다. 게임에 쓸 모델들부터 찾아보죠.
<add>
<add>[opengameart.org](https://opengameart.org) 사이트에서 [quaternius](https://opengameart.org/users/quaternius) 작가의 [움직이는 기사 모델](https://opengameart.org/content/lowpoly-animated-knight)을 찾았습니다.
<add>
<add><div class="threejs_center"><img src="resources/images/knight.jpg" style="width: 375px;"></div>
<add>
<add>[같은 작가](https://opengameart.org/users/quaternius)가 만든 작품 중에 [움직이는 동물들](https://opengameart.org/content/lowpoly-animated-farm-animal-pack)도 있더군요.
<add>
<add><div class="threejs_center"><img src="resources/images/animals.jpg" style="width: 606px;"></div>
<add>
<add>이 모델들로 꽤 괜찮은 게임을 만들 수 있을 것 같습니다. 모델들을 불러와보죠.
<add>
<add>[glTF 파일 불러오기](threejs-load-gltf.html)에 대해서는 이전에 다뤘었습니다. 동일한 방법을 사용하지만 이번에는 모델이 여러 개이기도 하고, 모델을 전부 불러오기 전에 게임을 시작해선 안 됩니다.
<add>
<add>이런 경우를 대비해 Three.js는 `LoadingManager`를 제공합니다. `LoadingManager`의 인스턴스를 생성해 다른 로더(loader)에 넘겨주기면 되죠. `LoadingManager`의 [`onProgress`](LoadingManager.onProgress)와 [`onLoad`](LoadingManager.onLoad) 속성에 콜백 함수를 지정하면 되는데, [`onLoad`](LoadingManager.onLoad)는 모든 파일을 불러온 뒤 호출하고, [`onProgress`](LoadingManager.onProgress)는 각 파일을 불러왔을 때 호출합니다. [`onProgress`](LoadingManager.onProgress)를 이용하면 프로그래스 바를 보여줄 수 있죠.
<add>
<add>[glTF 파일 불러오기](threejs-load-gltf.html) 예제를 가져와 카메라 절두체(frustum)를 조정하는 코드를 지우고 아래 코드를 추가합니다.
<add>
<add>```js
<add>const manager = new THREE.LoadingManager();
<add>manager.onLoad = init;
<add>const models = {
<add> pig: { url: 'resources/models/animals/Pig.gltf' },
<add> cow: { url: 'resources/models/animals/Cow.gltf' },
<add> llama: { url: 'resources/models/animals/Llama.gltf' },
<add> pug: { url: 'resources/models/animals/Pug.gltf' },
<add> sheep: { url: 'resources/models/animals/Sheep.gltf' },
<add> zebra: { url: 'resources/models/animals/Zebra.gltf' },
<add> horse: { url: 'resources/models/animals/Horse.gltf' },
<add> knight: { url: 'resources/models/knight/KnightCharacter.gltf' },
<add>};
<add>{
<add> const gltfLoader = new GLTFLoader(manager);
<add> for (const model of Object.values(models)) {
<add> gltfLoader.load(model.url, (gltf) => {
<add> model.gltf = gltf;
<add> });
<add> }
<add>}
<add>
<add>function init() {
<add> // 나중에 작성할 예정
<add>}
<add>```
<add>
<add>위 코드는 `models` 객체에 있는 파일을 불러오고, `LoadingManager`가 파일을 전부 불러왔을 때 `init` 함수를 호출합니다. `models` 객체를 전역으로 선언한 건 나중에 `GLTFLoader`의 콜백을 이용해 각 모델의 정보를 사용할 때 불러온 각 모델에 접근할 수 있도록 하기 위함입니다.
<add>
<add>모든 모델과 모델의 애니메이션 데이터는 현재 약 6.6MB입니다. 꽤 용량이 크네요. 여러분의 서버가 압축을 지원(이 사이트의 웹 서버가 이 기능을 지원합니다)한다면 용량은 약 1.4MB까지 줄어들 겁니다. 6.6MB와 비교하면 확실히 적은 데이터지만 절대 작은 데이터는 아닙니다. 프로그래스 바를 만들어 사용자에게 얼마나 기다려야 하는지를 표시해준다면 좋겠네요.
<add>
<add>[`onProgress`](LoadingManager.onProgress)에 콜백 함수를 지정해줍시다. 이 콜백 함수는 호출할 때 3개의 매개변수를 받습니다. 각각 마지막에 불러온 파일의 `url`, 그리고 불러온 파일의 개수, 전체 파일의 개수입니다.
<add>
<add>프로그래스 바는 HTML로 간단히 구현하도록 하죠.
<add>
<add>```html
<add><body>
<add> <canvas id="c"></canvas>
<add>+ <div id="loading">
<add>+ <div>
<add>+ <div>...loading...</div>
<add>+ <div class="progress"><div id="progressbar"></div></div>
<add>+ </div>
<add>+ </div>
<add></body>
<add>```
<add>
<add>`#progressbar`를 참조한 뒤 `width`를 퍼센트(%) 단위로 표시해 현재 진행율을 보여줄 겁니다. 콜백에서 이 스타일만 처리해주면 되겠네요.
<add>
<add>```js
<add>const manager = new THREE.LoadingManager();
<add>manager.onLoad = init;
<add>
<add>+const progressbarElem = document.querySelector('#progressbar');
<add>+manager.onProgress = (url, itemsLoaded, itemsTotal) => {
<add>+ progressbarElem.style.width = `${ itemsLoaded / itemsTotal * 100 | 0 }%`;
<add>+};
<add>```
<add>
<add>이미 모든 모델을 불러왔을 때 `init` 함수를 호출하게 해놓았으니, 여기서 `#loading` 요소를 숨겨 프로그래스 바를 없앱니다.
<add>
<add>```js
<add>function init() {
<add>+ // 프로그래스 바를 숨깁니다.
<add>+ const loadingElem = document.querySelector('#loading');
<add>+ loadingElem.style.display = 'none';
<add>}
<add>```
<add>
<add>아래는 프로그래스 바를 꾸미기 위한 CSS입니다. `#loading`은 페이지 전체를 꽉 채우고 자식 요소를 가운데 정렬시킵니다. 그리고 `.progress`는 프로그래스 바가 들어갈 영역을 정의하죠. 프로그래스 바에 간단한 애니메이션도 넣어줬습니다.
<add>
<add>```css
<add>#loading {
<add> position: absolute;
<add> left: 0;
<add> top: 0;
<add> width: 100%;
<add> height: 100%;
<add> display: flex;
<add> align-items: center;
<add> justify-content: center;
<add> text-align: center;
<add> font-size: xx-large;
<add> font-family: sans-serif;
<add>}
<add>#loading>div>div {
<add> padding: 2px;
<add>}
<add>.progress {
<add> width: 50vw;
<add> border: 1px solid black;
<add>}
<add>#progressbar {
<add> width: 0;
<add> transition: width ease-out .5s;
<add> height: 1em;
<add> background-color: #888;
<add> background-image: linear-gradient(
<add> -45deg,
<add> rgba(255, 255, 255, .5) 25%,
<add> transparent 25%,
<add> transparent 50%,
<add> rgba(255, 255, 255, .5) 50%,
<add> rgba(255, 255, 255, .5) 75%,
<add> transparent 75%,
<add> transparent
<add> );
<add> background-size: 50px 50px;
<add> animation: progressanim 2s linear infinite;
<add>}
<add>
<add>@keyframes progressanim {
<add> 0% {
<add> background-position: 50px 50px;
<add> }
<add> 100% {
<add> background-position: 0 0;
<add> }
<add>}
<add>```
<add>
<add>이제 프로그래스 바가 생겼으니 모델을 처리할 차례입니다. 이 모델들에는 애니메이션이 있는데, 이 애니메이션을 제어할 수 없다면 애니메이션이 있는 의미가 없겠죠. Three.js는 기본적으로 애니메이션들을 배열 형태로 저장합니다. 하지만 배열이 아닌 이름 형태로 저장하는 게 나중에 쓰기에 편하니 각 모델에 `animation` 속성을 만들겠습니다. 물론 각 애니메이션의 이름은 고유한 값이어야 하겠죠.
<add>
<add>```js
<add>+function prepModelsAndAnimations() {
<add>+ Object.values(models).forEach(model => {
<add>+ const animsByName = {};
<add>+ model.gltf.animations.forEach((clip) => {
<add>+ animsByName[clip.name] = clip;
<add>+ });
<add>+ model.animations = animsByName;
<add>+ });
<add>+}
<add>
<add>function init() {
<add> // 프로그래스 바를 숨깁니다.
<add> const loadingElem = document.querySelector('#loading');
<add> loadingElem.style.display = 'none';
<add>
<add>+ prepModelsAndAnimations();
<add>}
<add>```
<add>
<add>이제 애니메이션이 들어간 모델을 화면에 띄워봅시다.
<add>
<add>[이전 glTF 파일 예제](threejs-load-gltf.html)와 달리 이번에는 각 모델을 하나 이상 배치할 계획입니다. 그러니 파일을 불러온 뒤 바로 장면에 넣는 대신 각 glTF의 씬 그래프(scene), 이 경우에는 움직이는 캐릭터를 복사해야 합니다. 다행히 Three.js에는 `SkeletonUtil.clone`이라는 함수가 있어 이를 쉽게 구현할 수 있죠. 먼저 해당 모듈을 불러오겠습니다.
<add>
<add>```js
<add>import * as THREE from './resources/three/r115/build/three.module.js';
<add>import { OrbitControls } from './resources/threejs/r115/examples/jsm/controls/OrbitControls.js';
<add>import { GLTFLoader } from './resources/threejs/r115/examples/jsm/loaders/GLTFLoader.js';
<add>+import { SkeletonUtils } from './resources/threejs/r115/examples/jsm/utils/SkeletonUtils.js';
<add>```
<add>
<add>그리고 아까 불러왔던 모델을 복사합니다.
<add>
<add>```js
<add>function init() {
<add> // 프로그래스 바를 숨깁니다.
<add> const loadingElem = document.querySelector('#loading');
<add> loadingElem.style.display = 'none';
<add>
<add> prepModelsAndAnimations();
<add>
<add>+ Object.values(models).forEach((model, ndx) => {
<add>+ const clonedScene = SkeletonUtils.clone(model.gltf.scene);
<add>+ const root = new THREE.Object3D();
<add>+ root.add(clonedScene);
<add>+ scene.add(root);
<add>+ root.position.x = (ndx - 3) * 3;
<add>+ });
<add>}
<add>```
<add>
<add>위 코드에서는 불러온 각 모델의 `gltf.scene`을 복사해 새로운 `Object3D`의 자식으로 추가했습니다. 부모를 따로 만든 건 모델의 애니메이션이 모델의 각 요소의 위치값에 영향을 미치기에 코드로 직접 위치값을 수정하기도 어렵고, 제대로 반영도 안 될 것이기 때문입니다.
<add>
<add>각 모델의 애니메이션을 재생하려면 `AnimationMixer`를 써야 합니다. `AnimationMixer`는 하나 이상의 `AnimationAction`으로 이루어지고, 각 `AnimationAction`에는 하나의 `AnimationClip`이 있습니다. `AnimationAction`에는 여러 액션(action)을 이어서 재생하거나, 다른 애니메이션으로 부드럽게 전환하기 등 다양한 설정이 있죠. 당장은 첫 번째 `AnimationClip`으로 액션을 만들어봅시다. 설정을 바꾸지 않는다면 해당 애니메이션 클립(clip)을 반복해 재생할 겁니다.
<add>
<add>```js
<add>+const mixers = [];
<add>
<add>function init() {
<add> // 프로그래스 바를 숨깁니다.
<add> const loadingElem = document.querySelector('#loading');
<add> loadingElem.style.display = 'none';
<add>
<add> prepModelsAndAnimations();
<add>
<add> Object.values(models).forEach((model, ndx) => {
<add> const clonedScene = SkeletonUtils.clone(model.gltf.scene);
<add> const root = new THREE.Object3D();
<add> root.add(clonedScene);
<add> scene.add(root);
<add> root.position.x = (ndx - 3) * 3;
<add>
<add>+ const mixer = new THREE.AnimationMixer(clonedScene);
<add>+ const firstClip = Object.values(model.animations)[0];
<add>+ const action = mixer.clipAction(firstClip);
<add>+ action.play();
<add>+ mixers.push(mixer);
<add> });
<add>}
<add>```
<add>
<add>애니메이션을 시작하기 위해 [`play`](AnimationAction.play) 메서드를 호출했습니다. 그리고 생성한 `AnimationMixer`들을 전부 `mixers` 배열에 넣었죠. 마지막으로 렌더링 루프에서 각 `AnimationMixer`의 `AnimationMixer.update` 메서드에 바로 직전 프레임과 현재 프레임의 시간값을 넘겨주어야 합니다.
<add>
<add>```js
<add>+let then = 0;
<add>function render(now) {
<add>+ now *= 0.001; // 초 단위로 변환
<add>+ const deltaTime = now - then;
<add>+ then = now;
<add>
<add> if (resizeRendererToDisplaySize(renderer)) {
<add> const canvas = renderer.domElement;
<add> camera.aspect = canvas.clientWidth / canvas.clientHeight;
<add> camera.updateProjectionMatrix();
<add> }
<add>
<add>+ for (const mixer of mixers) {
<add>+ mixer.update(deltaTime);
<add>+ }
<add>
<add> renderer.render(scene, camera);
<add>
<add> requestAnimationFrame(render);
<add>}
<add>```
<add>
<add>이제 각 모델과 모델의 첫 번째 애니메이션이 보일 겁니다.
<add>
<add>{{{example url="../threejs-game-load-models.html"}}}
<add>
<add>모든 애니메이션을 확인할 수 있도록 예제를 수정해봅시다. 애니메이션 클립을 전부 액션으로 만들어 재생할 수 있도록 만들겠습니다.
<add>
<add>```js
<add>-const mixers = [];
<add>+const mixerInfos = [];
<add>
<add>function init() {
<add> // 프로그래스 바를 숨깁니다.
<add> const loadingElem = document.querySelector('#loading');
<add> loadingElem.style.display = 'none';
<add>
<add> prepModelsAndAnimations();
<add>
<add> Object.values(models).forEach((model, ndx) => {
<add> const clonedScene = SkeletonUtils.clone(model.gltf.scene);
<add> const root = new THREE.Object3D();
<add> root.add(clonedScene);
<add> scene.add(root);
<add> root.position.x = (ndx - 3) * 3;
<add>
<add> const mixer = new THREE.AnimationMixer(clonedScene);
<add>- const firstClip = Object.values(model.animations)[0];
<add>- const action = mixer.clipAction(firstClip);
<add>- action.play();
<add>- mixers.push(mixer);
<add>+ const actions = Object.values(model.animations).map((clip) => {
<add>+ return mixer.clipAction(clip);
<add>+ });
<add>+ const mixerInfo = {
<add>+ mixer,
<add>+ actions,
<add>+ actionNdx: -1,
<add>+ };
<add>+ mixerInfos.push(mixerInfo);
<add>+ playNextAction(mixerInfo);
<add> });
<add>}
<add>
<add>+function playNextAction(mixerInfo) {
<add>+ const { actions, actionNdx } = mixerInfo;
<add>+ const nextActionNdx = (actionNdx + 1) % actions.length;
<add>+ mixerInfo.actionNdx = nextActionNdx;
<add>+ actions.forEach((action, ndx) => {
<add>+ const enabled = ndx === nextActionNdx;
<add>+ action.enabled = enabled;
<add>+ if (enabled) {
<add>+ action.play();
<add>+ }
<add>+ });
<add>+}
<add>```
<add>
<add>위 코드에서는 각 모델마다 액션 배열과 `AnimationMixer`를 객체로 만들어 저장했습니다. 액션 배열은 모델의 각 `AnimationClip`마다 `AnimationAction`을 하나씩 생성해 배열로 만든 것이죠. 그리고 하나의 액션을 제외한 나머지 액션의 `enabled` 속성을 끄는 `playNextAction`을 호출했습니다.
<add>
<add>데이터 형식이 바뀌었으니 렌더링 루프의 업데이트 쪽 코드도 수정해야 합니다.
<add>
<add>```js
<add>-for (const mixer of mixers) {
<add>+for (const { mixer } of mixerInfos) {
<add> mixer.update(deltaTime);
<add>}
<add>```
<add>
<add>숫자키 1-8번을 눌러 각 모델의 애니메이션을 선택할 수 있도록 리스너를 지정합니다.
<add>
<add>```js
<add>window.addEventListener('keydown', (e) => {
<add> const mixerInfo = mixerInfos[e.keyCode - 49];
<add> if (!mixerInfo) {
<add> return;
<add> }
<add> playNextAction(mixerInfo);
<add>});
<add>```
<add>
<add>이제 예제를 클릭한 뒤 숫자키 1-8번을 누르면 각 번호에 해당하는 모델의 애니메이션이 바뀔 겁니다.
<add>
<add>{{{example url="../threejs-game-check-animations.html"}}}
<add>
<add>Three.js 관련 내용은 여기까지입니다. 여태까지 다수의 파일을 불러오는 법, 텍스처가 씌워진 모델을 복사하는 법, 해당 모델의 애니메이션을 재생하는 법을 알아봤죠. 실제 게임에서는 `AnimationAction` 객체로 다양한 동작을 직접 처리해줘야 합니다.
<add>
<add>자, 이제 게임의 기본 틀을 만들어봅시다.
<add>
<add>최신 게임을 만들 때는 보통 [Entity Component System(ECS)](https://www.google.com/search?q=entity+component+system)을 많이 사용합니다. Entity Component System에서는 게임의 요소를 여러 개의 *컴포넌트(component)*로 이루어진 *엔티티(entity)*라 부르죠. 새로운 엔티티를 생성할 때는 모든 코드를 새로 쓰는 것이 아닌, 미리 만들어 놓은 컴포넌트들을 엮어 생성합니다.
<add>
<add>예제에서는 엔티티를 `GameObject`라 부르겠습니다. 이는 단순히 컴포넌트 배열과 `THREE.Object3D`를 합친 것입니다.
<add>
<add>```js
<add>function removeArrayElement(array, element) {
<add> const ndx = array.indexOf(element);
<add> if (ndx >= 0) {
<add> array.splice(ndx, 1);
<add> }
<add>}
<add>
<add>class GameObject {
<add> constructor(parent, name) {
<add> this.name = name;
<add> this.components = [];
<add> this.transform = new THREE.Object3D();
<add> parent.add(this.transform);
<add> }
<add> addComponent(ComponentType, ...args) {
<add> const component = new ComponentType(this, ...args);
<add> this.components.push(component);
<add> return component;
<add> }
<add> removeComponent(component) {
<add> removeArrayElement(this.components, component);
<add> }
<add> getComponent(ComponentType) {
<add> return this.components.find(c => c instanceof ComponentType);
<add> }
<add> update() {
<add> for (const component of this.components) {
<add> component.update();
<add> }
<add> }
<add>}
<add>```
<add>
<add>`GameObject.update` 메서드를 호출하면 각 컴포넌트의 `update` 메서드를 호출합니다.
<add>
<add>name 속성은 단순히 디버깅을 위한 것입니다. 콘솔에서 `GameObject`를 봤을 때 어떤 요소인지 쉽게 확인할 수 있겠죠.
<add>
<add>생소해 보일 수 있는 것들 몇 가지만 집고 넘어가겠습니다.
<add>
<add>`GameObject.addComponent`는 컴포넌트를 생성할 때 사용합니다. GameObject 안에서 컴포넌트를 생성하는 게 최선인지는 모르겠으나, 개인적으로 컴포넌트가 GameObject 밖에 존재하는 건 의미가 없어 보였습니다. 그래서 생성한 컴포넌트를 자동으로 GameObject의 배열에 추가하고, GameObject 자체도 컴포넌트의 constructor에 넘겨줄 수 있으면 편하겠다고 생각했죠. 쉽게 말해 지금은 다음처럼 컴포넌트를 추가하지만,
<add>
<add>```js
<add>const gameObject = new GameObject(scene, 'foo');
<add>gameObject.addComponent(TypeOfComponent);
<add>```
<add>
<add>위와 같은 방식을 선호하지 않는다면 다음처럼 추가할 수도 있습니다.
<add>
<add>```js
<add>const gameObject = new GameObject(scene, 'foo');
<add>const component = new TypeOfComponent(gameObject);
<add>gameObject.addComponent(component);
<add>```
<add>
<add>첫 번째 코드가 짧고 자동화됐다는 면에서 더 좋을까요, 아니면 기존 형식을 해쳐서 더 별로일까요? 저는 어떻다고 판단하기가 어렵네요.
<add>
<add>`GameObject.getComponent`는 컴포넌트의 타입을 이용해 컴포넌트를 찾습니다. 이는 하나의 GameObject가 같은 타입의 컴포넌트를 두 개 이상 사용할 수 없다는 이야기죠. 물론 두 개 이상 사용한다고 에러가 나거나 하진 않겠지만, 별도의 API를 추가하지 않는 한 저 메서드는 항상 같은 타입 중 첫 번째 컴포넌트만을 반환할 겁니다.
<add>
<add>컴포넌트가 다른 컴포넌트를 찾는 건 흔한 일입니다. 그리고 컴포넌트를 찾을 때는 잘못 참조하는 일이 없도록 타입을 체크해야 하죠. 그냥 각 컴포넌트에 고유한 이름 속성을 주고 그 이름으로 해당 컴포넌트를 찾을 수도 있습니다. 이렇게 하면 같은 타입의 컴포넌트를 여러 개 쓸 수 있으니 확장성 면에서 유리할 겁니다. 하지만 이 방법은 그다지 일관성이 없습니다. 이번에도 어떤 쪽이 더 좋다고 판단하기가 어렵네요.
<add>
<add>아래는 컴포넌트의 기초 클래스입니다.
<add>
<add>```js
<add>// 모든 컴포넌트의 기초
<add>class Component {
<add> constructor(gameObject) {
<add> this.gameObject = gameObject;
<add> }
<add> update() {
<add> }
<add>}
<add>```
<add>
<add>컴포넌트에 기초 클래스가 필요할까요? 자바스크립트는 타입이 느슨한 언어이기에 굳이 기초 클래스를 쓸 필요는 없습니다. 각 컴포넌트의 constructor에서 첫 번째 인자가 GameObject이기만 하면 되죠. 만약 GameObject를 나중에 참조할 필요가 없다면 굳이 저장하지 않아도 될 겁니다. 하지만 저는 왠지 이 형식이 더 좋아 보이네요. 기초 클래스를 두면 부모의 GameObject에 쉽게 접근할 수 있을 뿐만 아니라 다른 컴포넌트를 쉽게 찾을 수 있고, 어떤 차이점이 있는지도 쉽게 알 수 있을 테니까요.
<add>
<add>GameObject를 다루려면 GameObject를 관리하는 클래스를 만드는 게 좋을 듯합니다. 얼핏 GameObject를 배열 형식으로 갖고 있어도 괜찮지 않나 싶을 수 있으나, 실제로 게임을 플레이할 때는 요소가 추가되기도 하고, 없어지기도 합니다. 예를 들어 총 GameObject는 총을 발사할 때마다 총알 GameObject를 추가할 겁니다. 몬스터 GameObject가 누군가에 의해 죽는다면 해당 GameObject는 사라지겠죠. GameObject를 배열로 저장한다면 십중팔구 다음과 같은 식의 코드를 쓸 겁니다.
<add>
<add>```js
<add>for (const gameObject of globalArrayOfGameObjects) {
<add> gameObject.update();
<add>}
<add>```
<add>
<add>위 반복문은 `globalArrayOfGameObjects`에 GameObject가 추가되거나 제거됐을 경우, 특정 컴포넌트의 `update` 메서드에서 에러를 던지거나 예상 밖의 동작을 할 수 있습니다.
<add>
<add>이런 일을 방지하기 위해 안전 장치를 추가해보도록 하죠.
<add>
<add>```js
<add>class SafeArray {
<add> constructor() {
<add> this.array = [];
<add> this.addQueue = [];
<add> this.removeQueue = new Set();
<add> }
<add> get isEmpty() {
<add> return this.addQueue.length + this.array.length > 0;
<add> }
<add> add(element) {
<add> this.addQueue.push(element);
<add> }
<add> remove(element) {
<add> this.removeQueue.add(element);
<add> }
<add> forEach(fn) {
<add> this._addQueued();
<add> this._removeQueued();
<add> for (const element of this.array) {
<add> if (this.removeQueue.has(element)) {
<add> continue;
<add> }
<add> fn(element);
<add> }
<add> this._removeQueued();
<add> }
<add> _addQueued() {
<add> if (this.addQueue.length) {
<add> this.array.splice(this.array.length, 0, ...this.addQueue);
<add> this.addQueue = [];
<add> }
<add> }
<add> _removeQueued() {
<add> if (this.removeQueue.size) {
<add> this.array = this.array.filter(element => !this.removeQueue.has(element));
<add> this.removeQueue.clear();
<add> }
<add> }
<add>}
<add>```
<add>
<add>위 클래스는 `SafeArray`의 요소를 더하거나 제거할 수 있도록 해줍니다. 원본 배열의 반복되는 동안 원본 배열을 변경하지 않는다는 게 차이점이죠. 대신 반복 중간에 추가된 요소는 `addQueue`에, 제거된 요소는 `removeQueue`에 들어간 뒤, 반복문이 돌아가지 않을 때 원본 배열에 제거/추가됩니다.
<add>
<add>아래는 위 클래스를 이용한 GameObject의 관리 클래스입니다.
<add>
<add>```js
<add>class GameObjectManager {
<add> constructor() {
<add> this.gameObjects = new SafeArray();
<add> }
<add> createGameObject(parent, name) {
<add> const gameObject = new GameObject(parent, name);
<add> this.gameObjects.add(gameObject);
<add> return gameObject;
<add> }
<add> removeGameObject(gameObject) {
<add> this.gameObjects.remove(gameObject);
<add> }
<add> update() {
<add> this.gameObjects.forEach(gameObject => gameObject.update());
<add> }
<add>}
<add>```
<add>
<add>여태까지 만든 요소로 첫 컴포넌트를 만들어봅시다. 이 컴포넌트는 아까 만들었던 것과 같은 Three.js glTF 객체를 관리할 겁니다. 간단히 애니메이션의 이름을 받아 해당 애니메이션을 재생하는 `setAnimation` 메서드만 새로 만들도록 하겠습니다.
<add>
<add>```js
<add>class SkinInstance extends Component {
<add> constructor(gameObject, model) {
<add> super(gameObject);
<add> this.model = model;
<add> this.animRoot = SkeletonUtils.clone(this.model.gltf.scene);
<add> this.mixer = new THREE.AnimationMixer(this.animRoot);
<add> gameObject.transform.add(this.animRoot);
<add> this.actions = {};
<add> }
<add> setAnimation(animName) {
<add> const clip = this.model.animations[animName];
<add> // 모든 액션을 끕니다.
<add> for (const action of Object.values(this.actions)) {
<add> action.enabled = false;
<add> }
<add> // 해당 클립에 해당하는 액션을 생성 또는 가져옵니다.
<add> const action = this.mixer.clipAction(clip);
<add> action.enabled = true;
<add> action.reset();
<add> action.play();
<add> this.actions[animName] = action;
<add> }
<add> update() {
<add> this.mixer.update(globals.deltaTime);
<add> }
<add>}
<add>```
<add>
<add>이 클래스는 아까 했던 것처럼 불러온 씬 그래프를 복사하고, `AnimationMixer`를 만듭니다. 클래스의 `setAnimation` 메서드는 해당 클립에 대한 액션이 존재하지 않는다면 새로 생성하고, 다른 액션을 전부 끄는 역할을 합니다.
<add>
<add>이 코드는 `globals.deltaTime`을 사용합니다. 이 전역 객체도 만들어야겠죠.
<add>
<add>```js
<add>const globals = {
<add> time: 0,
<add> deltaTime: 0,
<add>};
<add>```
<add>
<add>그리고 렌더링 루프에서 전역 객체를 업데이트하도록 합니다.
<add>
<add>```js
<add>let then = 0;
<add>function render(now) {
<add> // 초 단위로 변환
<add> globals.time = now * 0.001;
<add> // 시간값이 너무 크지 않도록 제한합니다.
<add> globals.deltaTime = Math.min(globals.time - then, 1 / 20);
<add> then = globals.time;
<add>```
<add>
<add>위 코드에서는 시간값의 범위가 1/20초를 넘지 않도록 했습니다. 이는 사용자가 탭을 숨기거나 했을 경우 시간값이 너무 커지지 않게 하기 위한 것이죠. 만약 이렇게 제한을 두지 않는다면 사용자가 탭을 몇 초, 또는 몇 분 숨겼다가 다시 탭을 열었을 때 프레임 간 시간값이 너무 커질 테고, 아래와 같이 시간으로 속력을 계산하는 경우 캐릭터가 순간이동하는 것처럼 보일 수 있습니다.
<add>
<add>```js
<add>position += velocity * deltaTime;
<add>```
<add>
<add>`deltaTime`의 최댓값을 설정하면 이런 문제를 막을 수 있죠.
<add>
<add>이제 플레이어 컴포넌트를 만들어봅시다.
<add>
<add>```js
<add>class Player extends Component {
<add> constructor(gameObject) {
<add> super(gameObject);
<add> const model = models.knight;
<add> this.skinInstance = gameObject.addComponent(SkinInstance, model);
<add> this.skinInstance.setAnimation('Run');
<add> }
<add>}
<add>```
<add>
<add>플레이어 컴포넌트는 초기화 시에 `'Run'`을 인자로 `setAnimation`을 호출합니다. 개인적으로 미리 어떤 애니메이션이 있는지 보려고 이전 예제를 수정해 애니메이션의 이름을 출력하도록 했죠.
<add>
<add>```js
<add>function prepModelsAndAnimations() {
<add> Object.values(models).forEach(model => {
<add>+ console.log('------->:', model.url);
<add> const animsByName = {};
<add> model.gltf.animations.forEach((clip) => {
<add> animsByName[clip.name] = clip;
<add>+ console.log(' ', clip.name);
<add> });
<add> model.animations = animsByName;
<add> });
<add>}
<add>```
<add>
<add>아래는 실제로 [자바스크립트 개발자 콘솔](https://developers.google.com/web/tools/chrome-devtools/console/javascript)에 출력된 결과입니다.
<add>
<add>```
<add> ------->: resources/models/animals/Pig.gltf
<add> Idle
<add> Death
<add> WalkSlow
<add> Jump
<add> Walk
<add> ------->: resources/models/animals/Cow.gltf
<add> Walk
<add> Jump
<add> WalkSlow
<add> Death
<add> Idle
<add> ------->: resources/models/animals/Llama.gltf
<add> Jump
<add> Idle
<add> Walk
<add> Death
<add> WalkSlow
<add> ------->: resources/models/animals/Pug.gltf
<add> Jump
<add> Walk
<add> Idle
<add> WalkSlow
<add> Death
<add> ------->: resources/models/animals/Sheep.gltf
<add> WalkSlow
<add> Death
<add> Jump
<add> Walk
<add> Idle
<add> ------->: resources/models/animals/Zebra.gltf
<add> Jump
<add> Walk
<add> Death
<add> WalkSlow
<add> Idle
<add> ------->: resources/models/animals/Horse.gltf
<add> Jump
<add> WalkSlow
<add> Death
<add> Walk
<add> Idle
<add> ------->: resources/models/knight/KnightCharacter.gltf
<add> Run_swordRight
<add> Run
<add> Idle_swordLeft
<add> Roll_sword
<add> Idle
<add> Run_swordAttack
<add>```
<add>
<add>운 좋게도 동물들의 애니메이션 이름이 전부 똑같네요. 나중에 편할 듯합니다. 뭐, 그건 나중 얘기고, 지금은 플레이어의 애니메이션 중 `Run`만 신경씁시다.
<add>
<add>이제 만든 컴포넌트를 써 보겠습니다. 먼저 `init` 함수를 약간 수정합니다. `init` 함수는 `GameObject`를 만들고 거기에 `Player` 컴포넌트를 추가하는 역할을 할 겁니다.
<add>
<add>```js
<add>const globals = {
<add> time: 0,
<add> deltaTime: 0,
<add>};
<add>+const gameObjectManager = new GameObjectManager();
<add>
<add>function init() {
<add> // 프로그래스 바를 숨깁니다.
<add> const loadingElem = document.querySelector('#loading');
<add> loadingElem.style.display = 'none';
<add>
<add> prepModelsAndAnimations();
<add>
<add>+ {
<add>+ const gameObject = gameObjectManager.createGameObject(scene, 'player');
<add>+ gameObject.addComponent(Player);
<add>+ }
<add>}
<add>```
<add>
<add>렌더링 루프에서 `gameObjectManager.update`를 호출하도록 합니다.
<add>
<add>```js
<add>let then = 0;
<add>function render(now) {
<add> // 초 단위로 변환
<add> globals.time = now * 0.001;
<add> // 시간값이 너무 크지 않도록 제한합니다.
<add> globals.deltaTime = Math.min(globals.time - then, 1 / 20);
<add> then = globals.time;
<add>
<add> if (resizeRendererToDisplaySize(renderer)) {
<add> const canvas = renderer.domElement;
<add> camera.aspect = canvas.clientWidth / canvas.clientHeight;
<add> camera.updateProjectionMatrix();
<add> }
<add>
<add>- for (const { mixer } of mixerInfos) {
<add>- mixer.update(deltaTime);
<add>- }
<add>+ gameObjectManager.update();
<add>
<add> renderer.render(scene, camera);
<add>
<add> requestAnimationFrame(render);
<add>}
<add>```
<add>
<add>예제를 실행하면 플레이어 하나만 보일 겁니다.
<add>
<add>{{{example url="../threejs-game-just-player.html"}}}
<add>
<add>단순히 Entity Component System을 구현하는 데만 너무 많은 코드를 쓴 게 아닌가 싶지만, 이 정도가 대부분의 게임이 갖춰야할 기본입니다.
<add>
<add>이제 사용자 입력 시스템을 추가해봅시다. 단순히 키보드 이벤트에 직접 코드를 작성하기보다 클래스를 만들어 코드의 다른 부분에서도 `왼쪽`, `오른쪽`을 확인할 수 있도록 하겠습니다. 이러면 `왼쪽`, `오른쪽` 등 다양한 키를 다양한 방법으로 지정할 수 있겠죠. 먼저 키보드 이벤트부터 지정합시다.
<add>
<add>```js
<add>/**
<add> * 키 또는 버튼의 상태를 추적합니다.
<add> *
<add> * 왼쪽 방향키가 눌렸는지 확인하려면
<add> *
<add> * inputManager.keys.left.down
<add> *
<add> * 을 확인하고, 현재 프레임에서 왼쪽 키를 눌렀는지 확인하려면
<add> *
<add> * inputManager.keys.left.justPressed
<add> *
<add> * 를 확인하면 됩니다.
<add> *
<add> * 현재 등록된 키는 'left', 'right', 'a', 'b', 'up', 'down' 입니다.
<add> **/
<add>class InputManager {
<add> constructor() {
<add> this.keys = {};
<add> const keyMap = new Map();
<add>
<add> const setKey = (keyName, pressed) => {
<add> const keyState = this.keys[keyName];
<add> keyState.justPressed = pressed && !keyState.down;
<add> keyState.down = pressed;
<add> };
<add>
<add> const addKey = (keyCode, name) => {
<add> this.keys[name] = { down: false, justPressed: false };
<add> keyMap.set(keyCode, name);
<add> };
<add>
<add> const setKeyFromKeyCode = (keyCode, pressed) => {
<add> const keyName = keyMap.get(keyCode);
<add> if (!keyName) {
<add> return;
<add> }
<add> setKey(keyName, pressed);
<add> };
<add>
<add> addKey(37, 'left');
<add> addKey(39, 'right');
<add> addKey(38, 'up');
<add> addKey(40, 'down');
<add> addKey(90, 'a');
<add> addKey(88, 'b');
<add>
<add> window.addEventListener('keydown', (e) => {
<add> setKeyFromKeyCode(e.keyCode, true);
<add> });
<add> window.addEventListener('keyup', (e) => {
<add> setKeyFromKeyCode(e.keyCode, false);
<add> });
<add> }
<add> update() {
<add> for (const keyState of Object.values(this.keys)) {
<add> if (keyState.justPressed) {
<add> keyState.justPressed = false;
<add> }
<add> }
<add> }
<add>}
<add>```
<add>
<add>위 코드는 키가 눌렸는지, 뗐는지를 추적합니다. 특정 키를 눌렀는지 확인하려면 예를 들어 `inputManager.keys.left.down`을 체크하면 되고, 해당 객체에 `justPressed`를 체크하면 사용자가 해당 프레임에서 키를 눌렀는지 확인할 수 있습니다. 예를 들어 점프를 구현할 경우 유저가 키를 누르고 있는지를 추적할 이유는 없겠죠. 단순히 해당 프레임에서 키를 눌렀는지만 확인하면 될 겁니다.
<add>
<add>이제 `InputManager`의 인스턴스를 생성합니다.
<add>
<add>```js
<add>const globals = {
<add> time: 0,
<add> deltaTime: 0,
<add>};
<add>const gameObjectManager = new GameObjectManager();
<add>+const inputManager = new InputManager();
<add>```
<add>
<add>그리고 렌더링 루프에서 `update` 메서드를 호출하도록 합니다.
<add>
<add>```js
<add>function render(now) {
<add>
<add> ...
<add>
<add> gameObjectManager.update();
<add>+ inputManager.update();
<add>
<add> ...
<add>}
<add>```
<add>
<add>`gameObjectManager.update` 전에 이 메서드를 호출하면 `justPressed`가 항상 `false`일 테니 `gameObjectManager.update` 뒤에 메서드를 호출하도록 했습니다.
<add>
<add>이제 `Player` 컴포넌트에 사용자 입력을 추가해봅시다.
<add>
<add>```js
<add>+const kForward = new THREE.Vector3(0, 0, 1);
<add>const globals = {
<add> time: 0,
<add> deltaTime: 0,
<add>+ moveSpeed: 16,
<add>};
<add>
<add>class Player extends Component {
<add> constructor(gameObject) {
<add> super(gameObject);
<add> const model = models.knight;
<add> this.skinInstance = gameObject.addComponent(SkinInstance, model);
<add> this.skinInstance.setAnimation('Run');
<add>+ this.turnSpeed = globals.moveSpeed / 4;
<add> }
<add>+ update() {
<add>+ const { deltaTime, moveSpeed } = globals;
<add>+ const { transform } = this.gameObject;
<add>+ const delta = (inputManager.keys.left.down ? 1 : 0) +
<add>+ (inputManager.keys.right.down ? -1 : 0);
<add>+ transform.rotation.y += this.turnSpeed * delta * deltaTime;
<add>+ transform.translateOnAxis(kForward, moveSpeed * deltaTime);
<add>+ }
<add>}
<add>```
<add>
<add>위 코드에서는 플레이어를 앞으로 움직이기 위해 `Object3D.transformOnAxis`를 사용했습니다. `Object3D.transformOnAxis`는 지역 공간을 기준으로 하기에 해당 객체가 장면의 루트(root) 요소에 속할 때만 정상적으로 작동합니다. <a class="footnote" href="#parented" id="parented-backref">1</a>
<add>
<add>또한 전역 객체에 `moveSpeed`를 추가했고 이를 `turnSpeed`의 기준으로 삼았습니다. 이는 캐릭터가 목표를 향해 상대적으로 빠르게 돌도록 만든 것으로, 이 `turnSpeed`의 값이 너무 작다면 캐릭터는 목표 주위를 빙빙 돌기만 하고 절대 목표에 닿지는 못할 겁니다. 물론 위 값은 어떤 수학적 공식을 사용한 것이 아닙니다. 그냥 대충 때려 넣은 것이죠.
<add>
<add>이대로도 예제는 잘 작동할 테지만 플레이어가 화면을 벗어나면 캐릭터가 어디 있는지 찾기가 어려울 겁니다. 일단 화면에서 벗어난 뒤 일정 시간이 지나면 플레이어를 다시 중점으로 순간이동시키기로 합시다. Three.js의 `Frustum` 클래스를 이용하면 특정 점이 카메라의 절두체(frustum) 안에 있는지 알 수 있습니다.
<add>
<add>먼저 카메라로 절두체를 만들어야 합니다. 플레이어 컴포넌트에서 이걸 처리할 수도 있지만, 다른 요소도 이 방법을 써야 할 수 있으니 카메라의 절두체를 관리하는 새로운 컴포넌트를 만들겠습니다.
<add>
<add>```js
<add>class CameraInfo extends Component {
<add> constructor(gameObject) {
<add> super(gameObject);
<add> this.projScreenMatrix = new THREE.Matrix4();
<add> this.frustum = new THREE.Frustum();
<add> }
<add> update() {
<add> const { camera } = globals;
<add> this.projScreenMatrix.multiplyMatrices(
<add> camera.projectionMatrix,
<add> camera.matrixWorldInverse);
<add> this.frustum.setFromProjectionMatrix(this.projScreenMatrix);
<add> }
<add>}
<add>```
<add>
<add>다음으로 `init` 함수에서 방금 만든 컴포넌트로 새로운 GameObject를 추가합니다.
<add>
<add>```js
<add>function init() {
<add> // 프로그래스 바를 숨깁니다.
<add> const loadingElem = document.querySelector('#loading');
<add> loadingElem.style.display = 'none';
<add>
<add> prepModelsAndAnimations();
<add>
<add>+ {
<add>+ const gameObject = gameObjectManager.createGameObject(camera, 'camera');
<add>+ globals.cameraInfo = gameObject.addComponent(CameraInfo);
<add>+ }
<add>
<add> {
<add> const gameObject = gameObjectManager.createGameObject(scene, 'player');
<add> gameObject.addComponent(Player);
<add> }
<add>}
<add>```
<add>
<add>`Player` 컴포넌트에 방금 만든 GameObject를 사용하는 코드를 추가합니다.
<add>
<add>```js
<add>class Player extends Component {
<add> constructor(gameObject) {
<add> super(gameObject);
<add> const model = models.knight;
<add> this.skinInstance = gameObject.addComponent(SkinInstance, model);
<add> this.skinInstance.setAnimation('Run');
<add> this.turnSpeed = globals.moveSpeed / 4;
<add>+ this.offscreenTimer = 0;
<add>+ this.maxTimeOffScreen = 3;
<add> }
<add> update() {
<add>- const { deltaTime, moveSpeed } = globals;
<add>+ const { deltaTime, moveSpeed, cameraInfo } = globals;
<add> const { transform } = this.gameObject;
<add> const delta = (inputManager.keys.left.down ? 1 : 0) +
<add> (inputManager.keys.right.down ? -1 : 0);
<add> transform.rotation.y += this.turnSpeed * delta * deltaTime;
<add> transform.translateOnAxis(kForward, moveSpeed * deltaTime);
<add>
<add>+ const { frustum } = cameraInfo;
<add>+ if (frustum.containsPoint(transform.position)) {
<add>+ this.offscreenTimer = 0;
<add>+ } else {
<add>+ this.offscreenTimer += deltaTime;
<add>+ if (this.offscreenTimer >= this.maxTimeOffScreen) {
<add>+ transform.position.set(0, 0, 0);
<add>+ }
<add>+ }
<add> }
<add>}
<add>```
<add>
<add>예제를 실행하기 전에 모바일 환경을 위한 터치 인터페이스를 추가하겠습니다. 먼저 터치 이벤트를 받을 HTML 요소를 만듭니다.
<add>
<add>```html
<add><body>
<add> <canvas id="c"></canvas>
<add>+ <div id="ui">
<add>+ <div id="left"><img src="resources/images/left.svg"></div>
<add>+ <div style="flex: 0 0 40px;"></div>
<add>+ <div id="right"><img src="resources/images/right.svg"></div>
<add>+ </div>
<add> <div id="loading">
<add> <div>
<add> <div>...loading...</div>
<add> <div class="progress"><div id="progressbar"></div></div>
<add> </div>
<add> </div>
<add></body>
<add>```
<add>
<add>버튼의 스타일도 작성합니다.
<add>
<add>```css
<add>#ui {
<add> position: absolute;
<add> left: 0;
<add> top: 0;
<add> width: 100%;
<add> height: 100%;
<add> display: flex;
<add> justify-items: center;
<add> align-content: stretch;
<add>}
<add>#ui>div {
<add> display: flex;
<add> align-items: flex-end;
<add> flex: 1 1 auto;
<add>}
<add>.bright {
<add> filter: brightness(2);
<add>}
<add>#left {
<add> justify-content: flex-end;
<add>}
<add>#right {
<add> justify-content: flex-start;
<add>}
<add>#ui img {
<add> padding: 10px;
<add> width: 80px;
<add> height: 80px;
<add> display: block;
<add>}
<add>```
<add>
<add>제가 사용한 방법은 하나의 div 요소, `#ui`로 화면 전체를 채우고, 해당 요소의 자식으로 화면의 대략 반을 차지하는 `#left`와 `#right`를 각각 양쪽에, 가운데에는 40px짜리 구분선을 넣어 화면 전체가 이벤트를 감지하도록 한 것입니다. 이러면 사용자가 왼쪽 화살표를 누른 뒤 왼쪽에서 오른쪽으로 손가락을 움직였을 때 `InputManager`의 `keys.left`과 `keys.right`를 업데이트할 수 있겠죠. 굳이 작은 화살표를 누르느라 고생하지 않아도 되니 이 편이 훨씬 나을 겁니다.
<add>
<add>```js
<add>class InputManager {
<add> constructor() {
<add> this.keys = {};
<add> const keyMap = new Map();
<add>
<add> const setKey = (keyName, pressed) => {
<add> const keyState = this.keys[keyName];
<add> keyState.justPressed = pressed && !keyState.down;
<add> keyState.down = pressed;
<add> };
<add>
<add> const addKey = (keyCode, name) => {
<add> this.keys[name] = { down: false, justPressed: false };
<add> keyMap.set(keyCode, name);
<add> };
<add>
<add> const setKeyFromKeyCode = (keyCode, pressed) => {
<add> const keyName = keyMap.get(keyCode);
<add> if (!keyName) {
<add> return;
<add> }
<add> setKey(keyName, pressed);
<add> };
<add>
<add> addKey(37, 'left');
<add> addKey(39, 'right');
<add> addKey(38, 'up');
<add> addKey(40, 'down');
<add> addKey(90, 'a');
<add> addKey(88, 'b');
<add>
<add> window.addEventListener('keydown', (e) => {
<add> setKeyFromKeyCode(e.keyCode, true);
<add> });
<add> window.addEventListener('keyup', (e) => {
<add> setKeyFromKeyCode(e.keyCode, false);
<add> });
<add>
<add>+ const sides = [
<add>+ { elem: document.querySelector('#left'), key: 'left' },
<add>+ { elem: document.querySelector('#right'), key: 'right' },
<add>+ ];
<add>+
<add>+ const clearKeys = () => {
<add>+ for (const {key} of sides) {
<add>+ setKey(key, false);
<add>+ }
<add>+ };
<add>+
<add>+ const checkSides = (e) => {
<add>+ for (const {elem, key} of sides) {
<add>+ let pressed = false;
<add>+ const rect = elem.getBoundingClientRect();
<add>+ for (const touch of e.touches) {
<add>+ const x = touch.clientX;
<add>+ const y = touch.clientY;
<add>+ const inRect = x >= rect.left && x < rect.right &&
<add>+ y >= rect.top && y < rect.bottom;
<add>+ if (inRect) {
<add>+ pressed = true;
<add>+ }
<add>+ }
<add>+ setKey(key, pressed);
<add>+ }
<add>+ };
<add>+
<add>+ const uiElem = document.querySelector('#ui');
<add>+ uiElem.addEventListener('touchstart', (e) => {
<add>+ e.preventDefault();
<add>+ checkSides(e);
<add>+ }, { passive: false });
<add>+ uiElem.addEventListener('touchmove', (e) => {
<add>+ e.preventDefault(); // 화면 스크롤 방지
<add>+ checkSides(e);
<add>+ }, { passive: false });
<add>+ uiElem.addEventListener('touchend', () => {
<add>+ clearKeys();
<add>+ });
<add>+
<add>+ function handleMouseMove(e) {
<add>+ e.preventDefault();
<add>+ checkSides({
<add>+ touches: [e],
<add>+ });
<add>+ }
<add>+
<add>+ function handleMouseUp() {
<add>+ clearKeys();
<add>+ window.removeEventListener('mousemove', handleMouseMove, { passive: false });
<add>+ window.removeEventListener('mouseup', handleMouseUp);
<add>+ }
<add>+
<add>+ uiElem.addEventListener('mousedown', (e) => {
<add>+ handleMouseMove(e);
<add>+ window.addEventListener('mousemove', handleMouseMove);
<add>+ window.addEventListener('mouseup', handleMouseUp);
<add>+ }, { passive: false });
<add> }
<add> update() {
<add> for (const keyState of Object.values(this.keys)) {
<add> if (keyState.justPressed) {
<add> keyState.justPressed = false;
<add> }
<add> }
<add> }
<add>}
<add>```
<add>
<add>이제 화살표 키나 화면을 터치해 캐릭터를 움직일 수 있을 겁니다.
<add>
<add>{{{example url="../threejs-game-player-input.html"}}}
<add>
<add>물론 플레이어가 화면 밖으로 나갔을 때 카메라를 움직이거나, "화면 밖 = 죽음"이라는 설정을 넣을 수도 있습니다. 하지만 이것까지 다룬다면 안 그래도 긴 글이 더 길어질 테니 이 방법으로 만족하겠습니다.
<add>
<add>이제 동물을 추가해봅시다. `Player`와 비슷한 방법으로 `Animal` 컴포넌트를 만듭니다.
<add>
<add>```js
<add>class Animal extends Component {
<add> constructor(gameObject, model) {
<add> super(gameObject);
<add> const skinInstance = gameObject.addComponent(SkinInstance, model);
<add> skinInstance.mixer.timeScale = globals.moveSpeed / 4;
<add> skinInstance.setAnimation('Idle');
<add> }
<add>}
<add>```
<add>
<add>위 코드에서는 `AnimationMixer.timeScale`을 설정해 애니메이션 속도가 이동 속도에 비례하도록 만들었습니다. 이러면 이동 속도와 같이 애니메이션 속도가 빨라지고 느려지겠죠.
<add>
<add>다음으로 `init` 함수에서 각 동물을 배치합니다.
<add>
<add>```js
<add>function init() {
<add> // 프로그래스 바를 숨깁니다.
<add> const loadingElem = document.querySelector('#loading');
<add> loadingElem.style.display = 'none';
<add>
<add> prepModelsAndAnimations();
<add> {
<add> const gameObject = gameObjectManager.createGameObject(camera, 'camera');
<add> globals.cameraInfo = gameObject.addComponent(CameraInfo);
<add> }
<add>
<add> {
<add> const gameObject = gameObjectManager.createGameObject(scene, 'player');
<add> globals.player = gameObject.addComponent(Player);
<add> globals.congaLine = [gameObject];
<add> }
<add>
<add>+ const animalModelNames = [
<add>+ 'pig',
<add>+ 'cow',
<add>+ 'llama',
<add>+ 'pug',
<add>+ 'sheep',
<add>+ 'zebra',
<add>+ 'horse',
<add>+ ];
<add>+ animalModelNames.forEach((name, ndx) => {
<add>+ const gameObject = gameObjectManager.createGameObject(scene, name);
<add>+ gameObject.addComponent(Animal, models[name]);
<add>+ gameObject.transform.position.x = (ndx + 1) * 5;
<add>+ });
<add>}
<add>```
<add>
<add>동물들을 배치하고 끝내면 심심하니 뭔가를 추가해야겠네요.
<add>
<add>동물이 플레이어를 따라 기차놀이*를 하게 해봅시다. 플레이어가 동물에 가까이 갔을 때만 기차에 합류하도록 하겠습니다. 이를 구현하려면 아래와 같은 모션(상태, state)이 필요할 겁니다.
<add>
<add>※ 원문은 "conga line"입니다. 기차놀이와 유사한 꼬리잇기 놀이로, 우리에게 더 익숙한 "기차놀이"로 의역했습니다. 역주.
<add>
<add>* 가만히 서 있는 모션(Idle):
<add>
<add> 플레이어가 가까워지기 전까지의 모션입니다.
<add>
<add>* 기차의 끝에 갈 때까지 기다리는 모션(Wait for End of Line):
<add>
<add> 플레이어가 동물과 닿더라도 기차의 끝에 합류해야 하므로 그 전까지 기다리는 모션입니다.
<add>
<add>* 따라붙기(Go to Last):
<add>
<add> 자신이 따라갈 대상이 있던 위치로 이동함과 동시에 따라갈 대상이 어디 있는지 기록합니다.
<add>
<add>* 따라가기(Follow):
<add>
<add> 자신이 따라가는 대상의 현재 위치를 기록함과 동시에 대상이 있었던 위치로 이동합니다.
<add>
<add>이런 상태를 다룰 방법은 아주 다양합니다. 보통은 [유한 상태 기계(Finite State Machine)](https://www.google.com/search?q=finite+state+machine)와 이런 상태를 다룰 헬퍼 클래스를 사용하죠.
<add>
<add>```js
<add>class FiniteStateMachine {
<add> constructor(states, initialState) {
<add> this.states = states;
<add> this.transition(initialState);
<add> }
<add> get state() {
<add> return this.currentState;
<add> }
<add> transition(state) {
<add> const oldState = this.states[this.currentState];
<add> if (oldState && oldState.exit) {
<add> oldState.exit.call(this);
<add> }
<add> this.currentState = state;
<add> const newState = this.states[state];
<add> if (newState.enter) {
<add> newState.enter.call(this);
<add> }
<add> }
<add> update() {
<add> const state = this.states[this.currentState];
<add> if (state.update) {
<add> state.update.call(this);
<add> }
<add> }
<add>}
<add>```
<add>
<add>위 클래스는 앞서 말한 헬퍼 클래스를 간단히 구현한 것입니다. 클래스는 생성 시 상태들의 객체를 받고, 각 상태에는 `enter`, `update`, `exit`이라는 메서드가 있습니다. 상태를 바꾸려면 `FiniteStateMachine.transition`을 호출할 때 새로운 이름을 넘겨주면 되죠. 만약 현재 상태에 `exit` 메서드가 있다면 해당 메서드를 호출합니다. 그리고 새로운 상태에 `enter` 메서드가 있을 경우 `enter` 메서드를 호출합니다. 마지막으로 매 프레임마다 `FiniteStateMachine.update`를 호출하면 각 상태의 `update` 메서드를 호출합니다.
<add>
<add>이제 이 클래스를 활용해 동물들의 상태를 바꿔봅시다.
<add>
<add>```js
<add>// 매개변수 obj1과 obj2이 가깝다면 true를 반환합니다.
<add>function isClose(obj1, obj1Radius, obj2, obj2Radius) {
<add> const minDist = obj1Radius + obj2Radius;
<add> const dist = obj1.position.distanceTo(obj2.position);
<add> return dist < minDist;
<add>}
<add>
<add>// v 의 값이 -min과 +min 사이가 되도록 합니다.
<add>function minMagnitude(v, min) {
<add> return Math.abs(v) > min
<add> ? min * Math.sign(v)
<add> : v;
<add>}
<add>
<add>const aimTowardAndGetDistance = function() {
<add> const delta = new THREE.Vector3();
<add>
<add> return function aimTowardAndGetDistance(source, targetPos, maxTurn) {
<add> delta.subVectors(targetPos, source.position);
<add> // 바라볼 방향을 계산합니다.
<add> const targetRot = Math.atan2(delta.x, delta.z) + Math.PI * 1.5;
<add> // 더 가까운 방향으로 회전합니다.
<add> const deltaRot = (targetRot - source.rotation.y + Math.PI * 1.5) % (Math.PI * 2) - Math.PI;
<add> // maxTurn보다 빠른 속도로 돌지 않도록 합니다.
<add> const deltaRotation = minMagnitude(deltaRot, maxTurn);
<add> // rotation 값을 0에서 Math.PI * 2 사이로 유지합니다.
<add> source.rotation.y = THREE.MathUtils.euclideanModulo(
<add> source.rotation.y + deltaRotation, Math.PI * 2);
<add> // 목표까지의 거리를 반환합니다.
<add> return delta.length();
<add> };
<add>}();
<add>
<add>class Animal extends Component {
<add> constructor(gameObject, model) {
<add> super(gameObject);
<add>+ const hitRadius = model.size / 2;
<add> const skinInstance = gameObject.addComponent(SkinInstance, model);
<add> skinInstance.mixer.timeScale = globals.moveSpeed / 4;
<add>+ const transform = gameObject.transform;
<add>+ const playerTransform = globals.player.gameObject.transform;
<add>+ const maxTurnSpeed = Math.PI * (globals.moveSpeed / 4);
<add>+ const targetHistory = [];
<add>+ let targetNdx = 0;
<add>+
<add>+ function addHistory() {
<add>+ const targetGO = globals.congaLine[targetNdx];
<add>+ const newTargetPos = new THREE.Vector3();
<add>+ newTargetPos.copy(targetGO.transform.position);
<add>+ targetHistory.push(newTargetPos);
<add>+ }
<add>+
<add>+ this.fsm = new FiniteStateMachine({
<add>+ idle: {
<add>+ enter: () => {
<add>+ skinInstance.setAnimation('Idle');
<add>+ },
<add>+ update: () => {
<add>+ // 플레이어가 근처에 있는지 확인합니다.
<add>+ if (isClose(transform, hitRadius, playerTransform, globals.playerRadius)) {
<add>+ this.fsm.transition('waitForEnd');
<add>+ }
<add>+ },
<add>+ },
<add>+ waitForEnd: {
<add>+ enter: () => {
<add>+ skinInstance.setAnimation('Jump');
<add>+ },
<add>+ update: () => {
<add>+ // 기차의 가장 마지막에 있는 gameObject를 가져옵니다.
<add>+ const lastGO = globals.congaLine[globals.congaLine.length - 1];
<add>+ const deltaTurnSpeed = maxTurnSpeed * globals.deltaTime;
<add>+ const targetPos = lastGO.transform.position;
<add>+ aimTowardAndGetDistance(transform, targetPos, deltaTurnSpeed);
<add>+ // 기차의 마지막에 있는 요소가 근처에 있는지 확인합니다.
<add>+ if (isClose(transform, hitRadius, lastGO.transform, globals.playerRadius)) {
<add>+ this.fsm.transition('goToLast');
<add>+ }
<add>+ },
<add>+ },
<add>+ goToLast: {
<add>+ enter: () => {
<add>+ // 따라갈 대상을 기록합니다. remember who we're following
<add>+ targetNdx = globals.congaLine.length - 1;
<add>+ // 기차의 마지막에 스스로를 추가합니다.
<add>+ globals.congaLine.push(gameObject);
<add>+ skinInstance.setAnimation('Walk');
<add>+ },
<add>+ update: () => {
<add>+ addHistory();
<add>+ // 기록된 위치 중 가장 나중 위치로 이동합니다.
<add>+ const targetPos = targetHistory[0];
<add>+ const maxVelocity = globals.moveSpeed * globals.deltaTime;
<add>+ const deltaTurnSpeed = maxTurnSpeed * globals.deltaTime;
<add>+ const distance = aimTowardAndGetDistance(transform, targetPos, deltaTurnSpeed);
<add>+ const velocity = distance;
<add>+ transform.translateOnAxis(kForward, Math.min(velocity, maxVelocity));
<add>+ if (distance <= maxVelocity) {
<add>+ this.fsm.transition('follow');
<add>+ }
<add>+ },
<add>+ },
<add>+ follow: {
<add>+ update: () => {
<add>+ addHistory();
<add>+ // 가장 오래된 위치값을 지우고 자기 자신의 위치값을 추가합니다.
<add>+ const targetPos = targetHistory.shift();
<add>+ transform.position.copy(targetPos);
<add>+ const deltaTurnSpeed = maxTurnSpeed * globals.deltaTime;
<add>+ aimTowardAndGetDistance(transform, targetHistory[0], deltaTurnSpeed);
<add>+ },
<add>+ },
<add>+ }, 'idle');
<add>+ }
<add>+ update() {
<add>+ this.fsm.update();
<add>+ }
<add>}
<add>```
<add>
<add>한 번에 너무 많은 코드를 보여준 듯하지만 위 코드는 방금 언급한 역할을 합니다. 각 상태에 대한 코드를 보고 어떤 식으로 작동하는지 분석해보기 바랍니다.
<add>
<add>여기에 몇 가지 요소를 추가해야 합니다. 플레이어가 자기 자신을 전역 객체(globals)에 추가해 다른 동물이 자신의 위치를 추적하도록 해야 하고, 또 기차의 머리를 플레이어의 `GameObject`로 지정해야 합니다.
<add>
<add>```js
<add>function init() {
<add>
<add> ...
<add>
<add> {
<add> const gameObject = gameObjectManager.createGameObject(scene, 'player');
<add>+ globals.player = gameObject.addComponent(Player);
<add>+ globals.congaLine = [gameObject];
<add> }
<add>
<add>}
<add>```
<add>
<add>각 모델의 크기도 계산해야 합니다.
<add>
<add>```js
<add>function prepModelsAndAnimations() {
<add>+ const box = new THREE.Box3();
<add>+ const size = new THREE.Vector3();
<add> Object.values(models).forEach(model => {
<add>+ box.setFromObject(model.gltf.scene);
<add>+ box.getSize(size);
<add>+ model.size = size.length();
<add> const animsByName = {};
<add> model.gltf.animations.forEach((clip) => {
<add> animsByName[clip.name] = clip;
<add> // 이런 부분은 .blend 파일에서 수정하는 게 좋습니다.
<add> if (clip.name === 'Walk') {
<add> clip.duration /= 2;
<add> }
<add> });
<add> model.animations = animsByName;
<add> });
<add>}
<add>```
<add>
<add>그리고 플레이어가 자기 자신의 크기를 기록하도록 합니다.
<add>
<add>```js
<add>class Player extends Component {
<add> constructor(gameObject) {
<add> super(gameObject);
<add> const model = models.knight;
<add>+ globals.playerRadius = model.size / 2;
<add>```
<add>
<add>이제 와 생각해보니 플레이어가 아니라 기차의 머리를 바라보게 하는 편이 더 나았겠네요. 이건 나중에 돌아와 고치도록 하겠습니다.
<add>
<add>예제를 처음 만들었을 때는 동물들이 모두 같은 크기의 경계 원(radius)을 썼지만, 이렇게 하고 보니 말과 퍼그(강아지)의 크기가 같은 게 말이 안 된다는 생각이 들었습니다. 그래서 각 모델의 크기에 따라 경계 원을 따로 지정했죠. 그리고 상태를 보여주면 좋겠다는 생각이 들어 상태를 보여 줄 `StatusDisplayHelper` 컴포넌트를 추가했습니다.
<add>
<add>또한 `PolarGridHelper`를 써 각 캐릭터의 경계 원이 보이도록 했고, [HTML 요소를 3D로 정렬하기](threejs-align-html-elements-to-3d.html)에서 썼던 방법으로 각 캐릭터의 상태를 HTML로 보여주도록 했습니다.
<add>
<add>먼저 각 요소를 담을 HTML을 추가합니다.
<add>
<add>```html
<add><body>
<add> <canvas id="c"></canvas>
<add> <div id="ui">
<add> <div id="left"><img src="resources/images/left.svg"></div>
<add> <div style="flex: 0 0 40px;"></div>
<add> <div id="right"><img src="resources/images/right.svg"></div>
<add> </div>
<add> <div id="loading">
<add> <div>
<add> <div>...loading...</div>
<add> <div class="progress"><div id="progressbar"></div></div>
<add> </div>
<add> </div>
<add>+ <div id="labels"></div>
<add></body>
<add>```
<add>
<add>CSS도 작성합니다.
<add>
<add>```css
<add>#labels {
<add> position: absolute; /* 기준 요소 위로 올라가도록 합니다. */
<add> left: 0; /* 기준 요소 왼쪽 위로 정렬합니다. */
<add> top: 0;
<add> color: white;
<add> width: 100%;
<add> height: 100%;
<add> overflow: hidden;
<add> pointer-events: none;
<add>}
<add>#labels>div {
<add> position: absolute; /* 기준 요소를 기준으로 합니다. */
<add> left: 0; /* 기준 요소의 왼쪽 위로 정렬합니다. */
<add> top: 0;
<add> font-size: large;
<add> font-family: monospace;
<add> user-select: none; /* 텍스트를 선택할 수 없도록 합니다. */
<add> text-shadow: /* 글자에 검은 윤곽선을 넣습니다. */
<add> -1px -1px 0 #000,
<add> 0 -1px 0 #000,
<add> 1px -1px 0 #000,
<add> 1px 0 0 #000,
<add> 1px 1px 0 #000,
<add> 0 1px 0 #000,
<add> -1px 1px 0 #000,
<add> -1px 0 0 #000;
<add>}
<add>```
<add>
<add>아래는 `StateDisplayHelper` 컴포넌트입니다.
<add>
<add>```js
<add>const labelContainerElem = document.querySelector('#labels');
<add>
<add>class StateDisplayHelper extends Component {
<add> constructor(gameObject, size) {
<add> super(gameObject);
<add> this.elem = document.createElement('div');
<add> labelContainerElem.appendChild(this.elem);
<add> this.pos = new THREE.Vector3();
<add>
<add> this.helper = new THREE.PolarGridHelper(size / 2, 1, 1, 16);
<add> gameObject.transform.add(this.helper);
<add> }
<add> setState(s) {
<add> this.elem.textContent = s;
<add> }
<add> setColor(cssColor) {
<add> this.elem.style.color = cssColor;
<add> this.helper.material.color.set(cssColor);
<add> }
<add> update() {
<add> const { pos } = this;
<add> const { transform } = this.gameObject;
<add> const { canvas } = globals;
<add> pos.copy(transform.position);
<add>
<add> /**
<add> * 해당 위치값을 정규화하면 x와 y 값은 -1에서 +1 사이의 값이 됩니다.
<add> * x = -1 이면 왼쪽, y = -1 이면 오른쪽이죠.
<add> **/
<add> pos.project(globals.camera);
<add>
<add> // 정규화한 위치값을 CSS 위치값으로 변환합니다.
<add> const x = (pos.x * .5 + .5) * canvas.clientWidth;
<add> const y = (pos.y * -.5 + .5) * canvas.clientHeight;
<add>
<add> // HTML 요소를 해당 위치로 옮깁니다.
<add> this.elem.style.transform = `translate(-50%, -50%) translate(${ x }px, ${ y }px)`;
<add> }
<add>}
<add>```
<add>
<add>동물 컴포넌트를 생성할 때 위 컴포넌트를 추가하도록 합니다.
<add>
<add>```js
<add>class Animal extends Component {
<add> constructor(gameObject, model) {
<add> super(gameObject);
<add>+ this.helper = gameObject.addComponent(StateDisplayHelper, model.size);
<add>
<add> ...
<add>
<add> }
<add> update() {
<add> this.fsm.update();
<add>+ const dir = THREE.MathUtils.radToDeg(this.gameObject.transform.rotation.y);
<add>+ this.helper.setState(`${ this.fsm.state }:${ dir.toFixed(0) }`);
<add> }
<add>}
<add>```
<add>
<add>추가로 dat.GUI를 이용해 위 디버깅 요소들를 켜고 끌 수 있도록 합니다.
<add>
<add>```js
<add>import * as THREE from './resources/three/r115/build/three.module.js';
<add>import { OrbitControls } from './resources/threejs/r115/examples/jsm/controls/OrbitControls.js';
<add>import { GLTFLoader } from './resources/threejs/r115/examples/jsm/loaders/GLTFLoader.js';
<add>import { SkeletonUtils } from './resources/threejs/r115/examples/jsm/utils/SkeletonUtils.js';
<add>+import { GUI } from '../3rdparty/dat.gui.module.js';
<add>```
<add>
<add>```js
<add>+const gui = new GUI();
<add>+gui.add(globals, 'debug').onChange(showHideDebugInfo);
<add>+showHideDebugInfo();
<add>
<add>const labelContainerElem = document.querySelector('#labels');
<add>+function showHideDebugInfo() {
<add>+ labelContainerElem.style.display = globals.debug ? '' : 'none';
<add>+}
<add>+showHideDebugInfo();
<add>
<add>class StateDisplayHelper extends Component {
<add>
<add> ...
<add>
<add> update() {
<add>+ this.helper.visible = globals.debug;
<add>+ if (!globals.debug) {
<add>+ return;
<add>+ }
<add>
<add> ...
<add> }
<add>}
<add>```
<add>
<add>게임의 가장 기본적인 틀을 완성했네요.
<add>
<add>{{{example url="../threejs-game-conga-line.html"}}}
<add>
<add>원래 처음에는 [지렁이 게임](https://www.google.com/search?q=snake+game)을 만들려고 했습니다. 동물이 기차에 붙어 기차가 길어질수록 장애물을 피하기 어려워지는 게임이죠. 예제에 몇 가지 장애물 놓거나 화면 둘레에 벽을 세우기도 했습니다.
<add>
<add>하지만 예제에서 사용한 동물은 이에 적합하지 않습니다. 예제의 동물들은 대부분 위에서 봤을 때 길고 폭이 얇거든요. 아래는 얼룩말을 위에서 본 것입니다.
<add>
<add><div class="threejs_center"><img src="resources/images/zebra.png" style="width: 113px;"></div>
<add>
<add>예제는 원 모양의 경계로 요소끼리의 충돌을 감지하기에 아래와 같이 울타리에 닿는 경우도 충돌로 감지할 겁니다.
<add>
<add><div class="threejs_center"><img src="resources/images/zebra-collisions.svg" style="width: 400px;"></div>
<add>
<add>동물과 동물이 부딪히는 경우에도 마찬가지입니다. 특히 게임에서는 이래서 좋을 게 없죠.
<add>
<add>2D 사각형을 만들어 충돌을 감지하는 것도 생각했으나, 바로 너무 많은 코드를 써야 한다는 걸 깨달았습니다. 예제의 각 모델에 다른 크기의 사각형을 추가하는 데는 그다지 많은 코드가 들어가지 않습니다. 하지만 이렇게 몇 가지 모델에 사각형을 추가해보면 곧 충돌을 감지하는 코드를 손봐야 할 필요가 생길 겁니다. 먼저 각 모델이 서로 충돌하는지 확인해야 하니 각 모델의 경계 정육면체나 경계 구체, 또는 모델과 같은 방향으로 정렬된 경계 육면체를 검사해야 합니다. 각 모델의 경계가 충돌했다는 건 두 모델이 *어쩌면* 서로 충돌했을 수도 있다는 이야기이기에, 각 모델이 *실제로* 충돌했는지 검사하기 위해 해당 모델들을 다시 검사해야 합니다. 대체로 경계 구체를 검사하는 것만 해도 꽤 많은 작업이 필요합니다. 가능하다면 각 요소가 근접했는지의 여부만 검사하는 등 더 특수한 방법을 사용하는 게 더 경제적이죠.
<add>
<add>또한 충돌 여부를 검사하기만 하는 것으로 끝나는 것이 아니라 충돌 시스템도 구축해야 합니다. 그때 그때 각 모델에게 "너 다른 애랑 충돌했니?" 이렇게 물어보는 것보다 시스템이 직접 충돌 여부를 이벤트 등으로 알려주는 게 더 편할 테니까요. 충돌 시스템은 충돌과 관련한 이벤트나 콜백을 사용합니다. 이 방법의 장점은 모든 충돌을 한 번만 검사하기에 각 모델이 "내가 다른 애랑 충돌했나?" 이렇게 검사를 따로 할 필요가 없다는 거죠. 연산량을 훨씬 줄일 수 있습니다.
<add>
<add>사각형을 확인하는 정도의 간단한 충돌 시스템을 만드는 코드는 100-300 줄 정도를 넘지 않을 겁니다. 하지만 예제와 비교하면 여전히 많은 코드이니 지금은 이대로 남겨 두겠습니다.
<add>
<add>시도해봄직한 다른 방법은 다른 캐릭터 중 위에서 바라봤을 때 가장 원형에 가까운 캐릭터를 찾는 겁니다*. 인간형 캐릭터의 경우는 대부분 잘 작동할 테고, 동물과 동물의 경우도 일부 경우는 잘 작동할 겁니다. 하지만 동물과 울타리의 경우는 감지하지 못하겠죠. 원래 화면 주위에 울타리나 덤불, 둥근 막대를 둘러보려고 했으나 이러려면 120에서 200개 정도의 요소를 더 만들어야 하고, 위에서 언급한 최적화 문제에 부딪쳤을 겁니다.
<add>
<add>※ 시야각 때문에 카메라의 중심에서 벗어날수록 머리 위가 아닌 옆이 보이는 걸 이용한 방법. 역주.
<add>
<add>이런 여러 문제 때문에 대부분의 게임들이 기존에 쓰던 방법을 사용합니다. 그리고 이 방법들 중에는 물리 라이브러리에서 쓰는 것들도 있죠. 물리 라이브러리는 요소가 서로 충돌하는지 확인하는 기능이 필수기에, 제가 위에서 사용했던 방법을 사용하기도 합니다.
<add>
<add>Three.js의 예제 중 [ammo.js](https://github.com/kripken/ammo.js/)를 사용한 것을 보면 이런 해결 방법을 찾는 데 도움이 될지도 모르겠네요.
<add>
<add>또 다른 방법은 장애물을 일정한 격자(grid)에 놓고 플레이어와 동물이 해당 격자만 참조하게 하는 겁니다. 성능 면에서 굉장히 좋은 방법인데, 이 또한 여러분이 직접 연습할 수 있는 😜 요소로 남겨 두면 좋겠다는 생각이 들더군요.
<add>
<add>덧붙여 대부분의 게임 시스템에는 [코루틴(coroutine)](https://www.google.com/search?q=coroutines)이라는 것이 있습니다. 코루틴은 특정 작업을 하는 동안 멈췄다가 나중에 다시 시작하는 루틴(routine)을 말하죠.
<add>
<add>플레이어 위에 음표를 띄워 노래로 동물들을 꼬시는 것처럼 해보겠습니다. 구현할 수 있는 방법은 아주 많지만, 예제에서는 코루틴을 사용해 이를 구현하겠습니다.
<add>
<add>먼저 코루틴을 관리하는 클래스를 만듭니다.
<add>
<add>```js
<add>function* waitSeconds(duration) {
<add> while (duration > 0) {
<add> duration -= globals.deltaTime;
<add> yield;
<add> }
<add>}
<add>
<add>class CoroutineRunner {
<add> constructor() {
<add> this.generatorStacks = [];
<add> this.addQueue = [];
<add> this.removeQueue = new Set();
<add> }
<add> isBusy() {
<add> return this.addQueue.length + this.generatorStacks.length > 0;
<add> }
<add> add(generator, delay = 0) {
<add> const genStack = [generator];
<add> if (delay) {
<add> genStack.push(waitSeconds(delay));
<add> }
<add> this.addQueue.push(genStack);
<add> }
<add> remove(generator) {
<add> this.removeQueue.add(generator);
<add> }
<add> update() {
<add> this._addQueued();
<add> this._removeQueued();
<add> for (const genStack of this.generatorStacks) {
<add> const main = genStack[0];
<add> // 다른 코루틴이 해당 요소를 제거했을 경우
<add> if (this.removeQueue.has(main)) {
<add> continue;
<add> }
<add> while (genStack.length) {
<add> const topGen = genStack[genStack.length - 1];
<add> const { value, done } = topGen.next();
<add> if (done) {
<add> if (genStack.length === 1) {
<add> this.removeQueue.add(topGen);
<add> break;
<add> }
<add> genStack.pop();
<add> } else if (value) {
<add> genStack.push(value);
<add> } else {
<add> break;
<add> }
<add> }
<add> }
<add> this._removeQueued();
<add> }
<add> _addQueued() {
<add> if (this.addQueue.length) {
<add> this.generatorStacks.splice(this.generatorStacks.length, 0, ...this.addQueue);
<add> this.addQueue = [];
<add> }
<add> }
<add> _removeQueued() {
<add> if (this.removeQueue.size) {
<add> this.generatorStacks = this.generatorStacks.filter(genStack => !this.removeQueue.has(genStack[0]));
<add> this.removeQueue.clear();
<add> }
<add> }
<add>}
<add>```
<add>
<add>위 클래스는 다른 코루틴이 실행되는 동안 요소를 안전하게 제거/추가하도록 `SafeArray`와 비슷한 구조로 만들었습니다. 또한 이 클래스는 중첩된 코루틴도 처리합니다.
<add>
<add>코루틴을 만들려면 자바스크립트의 [제너레이터 함수](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/function*)를 만들어야 합니다. 제너레이터 함수는 `function*`이라는 키워드로 생성하죠(별표를 붙여야 합니다!).
<add>
<add>제너레이터 함수는 `yield` 키워드로 실행 순서를 **양보(yield)**할 수 있습니다.
<add>
<add>```js
<add>function* countOTo9() {
<add> for (let i = 0; i < 10; ++i) {
<add> console.log(i);
<add> yield;
<add> }
<add>}
<add>```
<add>
<add>이 함수를 아까 만든 `CoroutineRunner`에 추가하면 한 프레임, 또는 `runner.update`를 호출할 때마다 0부터 9까지의 숫자를 차례대로 출력할 겁니다.
<add>
<add>```js
<add>const runner = new CoroutineRunner();
<add>runner.add(count0To9);
<add>while(runner.isBusy()) {
<add> runner.update();
<add>}
<add>```
<add>
<add>코루틴은 동작이 끝났을 때 자동으로 제거됩니다. 코루틴이 끝나기 전에 제거하려면 제너레이터를 미리 참조한 뒤 `remove` 메서드를 호출해야 합니다.
<add>
<add>```js
<add>const gen = count0To9();
<add>runner.add(gen);
<add>
<add>// 얼마 후
<add>
<add>runner.remove(gen);
<add>```
<add>
<add>이제 플레이어가 0.5에서 1초 사이마다 한 번씩 음표를 뱉도록 해봅시다.
<add>
<add>```js
<add>class Player extends Component {
<add> constructor(gameObject) {
<add>
<add> ...
<add>
<add>+ this.runner = new CoroutineRunner();
<add>+
<add>+ function* emitNotes() {
<add>+ for (;;) {
<add>+ yield waitSeconds(rand(0.5, 1));
<add>+ const noteGO = gameObjectManager.createGameObject(scene, 'note');
<add>+ noteGO.transform.position.copy(gameObject.transform.position);
<add>+ noteGO.transform.position.y += 5;
<add>+ noteGO.addComponent(Note);
<add>+ }
<add>+ }
<add>+
<add>+ this.runner.add(emitNotes());
<add> }
<add> update() {
<add>+ this.runner.update();
<add>
<add> ...
<add>
<add> }
<add>}
<add>
<add>function rand(min, max) {
<add> if (max === undefined) {
<add> max = min;
<add> min = 0;
<add> }
<add> return Math.random() * (max - min) + min;
<add>}
<add>```
<add>
<add>위 코드에서는 `CoroutineRunner`를 만들고 `emitNotes` 코루틴을 추가했습니다. 이 함수는 0.5초에서 1초 사이마다 계속해서 `Note` 컴포넌트를 생성합니다.
<add>
<add>`Note` 컴포넌트를 만들려면 먼저 텍스처가 필요합니다. 음표 이미지를 불러올 수도 있지만, [캔버스로 텍스처 만들기](threejs-canvas-textures.html)에서 다뤘던 것처럼 캔버스를 이용해 직접 음표를 만들겠습니다.
<add>
<add>```js
<add>function makeTextTexture(str) {
<add> const ctx = document.createElement('canvas').getContext('2d');
<add> ctx.canvas.width = 64;
<add> ctx.canvas.height = 64;
<add> ctx.font = '60px sans-serif';
<add> ctx.textAlign = 'center';
<add> ctx.textBaseline = 'middle';
<add> ctx.fillStyle = '#FFF';
<add> ctx.fillText(str, ctx.canvas.width / 2, ctx.canvas.height / 2);
<add> return new THREE.CanvasTexture(ctx.canvas);
<add>}
<add>const noteTexture = makeTextTexture('♪');
<add>```
<add>
<add>위에서 만든 텍스처는 하얀색으로, 나중에 텍스처를 사용할 때 색을 따로 지정해 원하는 색의 음표를 그릴 수 있습니다.
<add>
<add>이제 음표 텍스처를 만들었으니 `Note` 컴포넌트를 만들 차례입니다. 음표 컴포넌트는 [빌보드에 관한 글](threejs-billboards.html)에서 다뤘던 `SpriteMaterial`과 `Sprite`를 사용합니다.
<add>
<add>```js
<add>class Note extends Component {
<add> constructor(gameObject) {
<add> super(gameObject);
<add> const { transform } = gameObject;
<add> const noteMaterial = new THREE.SpriteMaterial({
<add> color: new THREE.Color().setHSL(rand(1), 1, 0.5),
<add> map: noteTexture,
<add> side: THREE.DoubleSide,
<add> transparent: true,
<add> });
<add> const note = new THREE.Sprite(noteMaterial);
<add> note.scale.setScalar(3);
<add> transform.add(note);
<add> this.runner = new CoroutineRunner();
<add> const direction = new THREE.Vector3(rand(-0.2, 0.2), 1, rand(-0.2, 0.2));
<add>
<add> function* moveAndRemove() {
<add> for (let i = 0; i < 60; ++i) {
<add> transform.translateOnAxis(direction, globals.deltaTime * 10);
<add> noteMaterial.opacity = 1 - (i / 60);
<add> yield;
<add> }
<add> transform.parent.remove(transform);
<add> gameObjectManager.removeGameObject(gameObject);
<add> }
<add>
<add> this.runner.add(moveAndRemove());
<add> }
<add> update() {
<add> this.runner.update();
<add> }
<add>}
<add>```
<add>
<add>이 컴포넌트는 `Sprite`를 만들고 무작위로 속도를 정해 60프레임 동안 그 속도로 이동하게 합니다. 동시에 재질의 [`opacity`](Material.opacity) 속성을 바꿔 페이드-아웃 효과도 주죠. 반복문이 끝나면 이 컴포넌트는 위치값과 음표를 해당 GameObject에서 제거합니다.
<add>
<add>정말 마지막으로, 동물의 수를 좀 늘려보겠습니다.
<add>
<add>```js
<add>function init() {
<add>
<add> ...
<add>
<add> const animalModelNames = [
<add> 'pig',
<add> 'cow',
<add> 'llama',
<add> 'pug',
<add> 'sheep',
<add> 'zebra',
<add> 'horse',
<add> ];
<add>+ const base = new THREE.Object3D();
<add>+ const offset = new THREE.Object3D();
<add>+ base.add(offset);
<add>+
<add>+ // 소용돌이 형태로 동물들을 배치합니다.
<add>+ const numAnimals = 28;
<add>+ const arc = 10;
<add>+ const b = 10 / (2 * Math.PI);
<add>+ let r = 10;
<add>+ let phi = r / b;
<add>+ for (let i = 0; i < numAnimals; ++i) {
<add>+ const name = animalModelNames[rand(animalModelNames.length) | 0];
<add> const gameObject = gameObjectManager.createGameObject(scene, name);
<add> gameObject.addComponent(Animal, models[name]);
<add>+ base.rotation.y = phi;
<add>+ offset.position.x = r;
<add>+ offset.updateWorldMatrix(true, false);
<add>+ offset.getWorldPosition(gameObject.transform.position);
<add>+ phi += arc / r;
<add>+ r = b * phi;
<add> }
<add>```
<add>
<add>{{{example url="../threejs-game-conga-line-w-notes.html"}}}
<add>
<add>누군가 `setTimeout`을 쓰면 안 되냐고 물을지도 모르겠습니다. `setTimeout`을 쓰지 않은 건 `setTimeout`은 게임의 프레임 주기와 무관하기 때문입니다. 예를 들어 예제에서는 프레임 간 시간값을 최대 1/20초로 제한했죠. 방금 구축한 코루틴 시스템도 이 제한을 따를 테지만, `setTimeout`을 쓰면 그렇지 않을 겁니다.
<add>
<add>물론 좀 더 간단한 타이머를 만들 수도 있습니다.
<add>
<add>```js
<add>class Player ... {
<add> update() {
<add> this.noteTimer -= globals.deltaTime;
<add> if (this.noteTimer <= 0) {
<add> // 타이머를 초기화합니다.
<add> this.noteTimer = rand(0.5, 1);
<add> // GameObject로 음표 컴포넌트를 만듭니다.
<add> }
<add> }
<add>```
<add>
<add>특정 경우에야 이 방법이 더 좋을 수도 있지만, 더 많은 요소를 추가하면 그만큼 더 많은 변수와 코루틴을 추가해야 할테고, 그럴수록 `setTimeout`을 *설정하고 까먹을* 확률이 높아질 겁니다.
<add>
<add>동물들의 상태를 설정할 때도 아래와 같이 코루틴을 사용할 수 있습니다.
<add>
<add>```js
<add>// 실제로 사용하지 않는 함수
<add>function* animalCoroutine() {
<add> setAnimation('Idle');
<add> while(playerIsTooFar()) {
<add> yield;
<add> }
<add> const target = endOfLine;
<add> setAnimation('Jump');
<add> while(targetIsTooFar()) {
<add> aimAt(target);
<add> yield;
<add> }
<add> setAnimation('Walk')
<add> while(notAtOldestPositionOfTarget()) {
<add> addHistory();
<add> aimAt(target);
<add> yield;
<add> }
<add> for(;;) {
<add> addHistory();
<add> const pos = history.unshift();
<add> transform.position.copy(pos);
<add> aimAt(history[0]);
<add> yield;
<add> }
<add>}
<add>```
<add>
<add>이 방법을 써도 딱히 문제는 없었겠지만, 상태가 일정하지 않아 다시 `FiniteStateMachine`을 찾게 될 겁니다.
<add>
<add>또 저는 코루틴을 해당 컴포넌트와 독립적으로 실행하는 게 좋은지 잘 모르겠습니다. 물론 그냥 전역에 `CoroutineRunner`를 만들어 모든 코루틴을 여기에 집어 넣을 수는 있죠. 하지만 이러면 코루틴을 없애기가 힘들어질 겁니다. 지금 예제는 GameObject를 제거하면 해당 컴포넌트도 제거되고, 그러면 생성한 `CoroutineRunner`의 메서드를 호출할 일도 없으니 코루틴도 전부 가비지 컬렉션에 들어갈 겁니다. 전역에 `CoroutineRunner`를 두면 컴포넌트에서 직접 이 전역 객체의 코루틴을 제거하거나 자동으로 코루틴을 제거할 다른 방법이 필요할 겁니다.
<add>
<add>실제 게임 엔진이라면 더 고려해야 할 문제가 많습니다. 지금은 GameObject나 컴포넌트에 따로 순서를 지정할 수 없죠. 그냥 추가한 순서가 해당 요소의 순서가 됩니다. 대부분의 게임 엔진은 우선 순위를 정해 순서를 바꿀 수 있습니다.
<add>
<add>다른 문제는 `Note` 컴포넌트가 장면 위 GameObject의 transform 속성을 변경한다는 겁니다. 애초에 `GameObject`가 transform 속성을 변경했으니 좀 더 제대로 구현하려면 `GameObject`가 계속 transform 속성을 관리하는 게 맞겠죠. `GameObject`에 `dispose` 같은 메서드를 두고 `GameObjectManager.removeGameObject`에서 이 메서드를 호출했다면 어떨까요?
<add>
<add>또 `gameObjectManager.update`나 `inputManager.update`를 직접 호출하는 대신 `SystemManager`를 만들어 `update`메서드를 가진 요소를 전부 추가해 이 클래스가 메서드를 호출하도록 하는 게 더 나을 수도 있습니다. 이렇게 하면 `CollisionManager` 등 새로운 시스템을 만들었을 때 `render` 함수를 수정하는 게 아니라 `SystemManager`에 이 시스템을 추가하기만 하면 될 겁니다.
<add>
<add>저는 이런 문제들을 전부 다루기보다 여러분의 몫으로 남겨 두고자 합니다. 부디 이 글이 여러분만의 게임 엔진을 만드는 데 도움이 되었다면 좋겠네요.
<add>
<add>어쩌면 제가 게임 잼(game jam)*을 열 수도 있겠네요. 위 예제의 *jsfiddle*이나 *codepen*을 클릭해보면 코드를 바로 편집해 볼 수 있는 사이트가 열릴 겁니다. 특정 기능을 추가하거나 해서 예제를 퍼그가 기사(knight)을 끌고 다니는 게임을 만들거나, 기사의 구르기 애니메이션을 볼링공으로써 동물 볼링 게임을 만들 수도 있겠죠. 또는 동물 이어 달리기 게임이라든가요. 괜찮은 게임을 만들었다면 아래에 댓글로 링크를 남겨주시면 감사하겠습니다.
<add>
<add>※ 게임 잼: 보통 24시간에서 72시간 정도의 짧은 기간 내에 팀, 또는 개인이 게임을 만드는 대회. 역주.
<add>
<add><div class="footnotes">
<add>[<a id="parented">1</a>]: 물론 부모의 어떤 요소도 translation, rotation, scale 속성을 바꾸지 않았다면 정상적으로 작동합니다.<a href="#parented-backref">[돌아가기]</a>
<add></div>
<ide>\ No newline at end of file | 1 |
Go | Go | exclude default routes from checkrouteoverlaps | a886fbfa4a01f7d73c9c2d836da89ecf23a40a33 | <ide><path>network.go
<ide> func networkSize(mask net.IPMask) int32 {
<ide>
<ide> func checkRouteOverlaps(networks []netlink.Route, dockerNetwork *net.IPNet) error {
<ide> for _, network := range networks {
<del> if networkOverlaps(dockerNetwork, network.IPNet) {
<add> if !network.Default && networkOverlaps(dockerNetwork, network.IPNet) {
<ide> return fmt.Errorf("Network %s is already routed: '%s'", dockerNetwork, network)
<ide> }
<ide> } | 1 |
Text | Text | add comment to example about 2xx status codes | a720c0edcc40a86bee9a696cd791df3420c398ad | <ide><path>doc/api/http.md
<ide> http.get('http://nodejs.org/dist/index.json', (res) => {
<ide> const contentType = res.headers['content-type'];
<ide>
<ide> let error;
<add> // Any 2xx status code signals a successful response but
<add> // here we're only checking for 200.
<ide> if (statusCode !== 200) {
<ide> error = new Error('Request Failed.\n' +
<ide> `Status Code: ${statusCode}`); | 1 |
Java | Java | fix bytecode generation for spel opplus | 94ee763bc8bd945a79dcc3aa9330734cde6bc730 | <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpPlus.java
<ide> private void walk(MethodVisitor mv, CodeFlow cf, SpelNodeImpl operand) {
<ide> else {
<ide> cf.enterCompilationScope();
<ide> operand.generateCode(mv,cf);
<add> if (cf.lastDescriptor() != "Ljava/lang/String") {
<add> mv.visitTypeInsn(CHECKCAST, "java/lang/String");
<add> }
<ide> cf.exitCompilationScope();
<ide> mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
<ide> }
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
<ide> public void opPlusString() throws Exception {
<ide> expression = parse("'hello' + 3 + ' spring'");
<ide> assertEquals("hello3 spring",expression.getValue(new Greeter()));
<ide> assertCantCompile(expression);
<add>
<add> expression = parse("object + 'a'");
<add> assertEquals("objecta",expression.getValue(new Greeter()));
<add> assertCanCompile(expression);
<add> assertEquals("objecta",expression.getValue(new Greeter()));
<add>
<add> expression = parse("'a'+object");
<add> assertEquals("aobject",expression.getValue(new Greeter()));
<add> assertCanCompile(expression);
<add> assertEquals("aobject",expression.getValue(new Greeter()));
<add>
<add> expression = parse("'a'+object+'a'");
<add> assertEquals("aobjecta",expression.getValue(new Greeter()));
<add> assertCanCompile(expression);
<add> assertEquals("aobjecta",expression.getValue(new Greeter()));
<add>
<add> expression = parse("object+'a'+object");
<add> assertEquals("objectaobject",expression.getValue(new Greeter()));
<add> assertCanCompile(expression);
<add> assertEquals("objectaobject",expression.getValue(new Greeter()));
<add>
<add> expression = parse("object+object");
<add> assertEquals("objectobject",expression.getValue(new Greeter()));
<add> assertCanCompile(expression);
<add> assertEquals("objectobject",expression.getValue(new Greeter()));
<ide> }
<ide>
<ide> public static class Greeter {
<ide> public String getWorld() {
<ide> return "world";
<ide> }
<add>
<add> public Object getObject() {
<add> return "object";
<add> }
<ide> }
<ide>
<ide> @Test | 2 |
Text | Text | add hostnfly as users of airflow | c0c71cac630ab9b8d82a2283338de9375d28ad4f | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [HelloFresh](https://www.hellofresh.com) [[@tammymendt](https://github.com/tammymendt) & [@davidsbatista](https://github.com/davidsbatista) & [@iuriinedostup](https://github.com/iuriinedostup)]
<ide> 1. [Holimetrix](http://holimetrix.com/) [[@thibault-ketterer](https://github.com/thibault-ketterer)]
<ide> 1. [Hootsuite](https://github.com/hootsuite)
<add>1. [Hostnfly](https://www.hostnfly.com/) [[@CyrilLeMat](https://github.com/CyrilLeMat) & [@pierrechopin](https://github.com/pierrechopin) & [@alexisrosuel](https://github.com/alexisrosuel)]
<ide> 1. [HotelQuickly](https://github.com/HotelQuickly) [[@zinuzoid](https://github.com/zinuzoid)]
<ide> 1. [IFTTT](https://www.ifttt.com/) [[@apurvajoshi](https://github.com/apurvajoshi)]
<ide> 1. [iHeartRadio](http://www.iheart.com/)[[@yiwang](https://github.com/yiwang)] | 1 |
Ruby | Ruby | fix rdoc markup [ci skip] | 16a27b68ea7ed22c71ca898d8dd369e9dbd4b019 | <ide><path>railties/lib/rails/paths.rb
<ide> module Paths
<ide> #
<ide> # Notice that when you add a path using +add+, the path object created already
<ide> # contains the path with the same path value given to +add+. In some situations,
<del> # you may not want this behavior, so you can give +:with+ as option.
<add> # you may not want this behavior, so you can give <tt>:with</tt> as option.
<ide> #
<ide> # root.add "config/routes", with: "config/routes.rb"
<ide> # root["config/routes"].inspect # => ["config/routes.rb"] | 1 |
Go | Go | prevent a panic with docker run -v / | 536da93380f1cacb82c344ad09c2daaae29f8ac3 | <ide><path>commands.go
<ide> func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Co
<ide> flVolumes.Set(dstDir)
<ide> binds = append(binds, bind)
<ide> flVolumes.Delete(bind)
<add> } else if bind == "/" {
<add> return nil, nil, cmd, fmt.Errorf("Invalid volume: path can't be '/'")
<ide> }
<ide> }
<ide>
<ide><path>commands_unit_test.go
<ide> func TestParseRunVolumes(t *testing.T) {
<ide> t.Fatalf("Error parsing volume flags, without volume, no volume should be present. Received %v", config.Volumes)
<ide> }
<ide>
<del> mustParse(t, "-v /")
<add> if _, _, err := parse(t, "-v /"); err == nil {
<add> t.Fatalf("Expected error, but got none")
<add> }
<ide>
<ide> if _, _, err := parse(t, "-v /:/"); err == nil {
<ide> t.Fatalf("Error parsing volume flags, `-v /:/` should fail but didn't")
<ide><path>container.go
<ide> func (container *Container) createVolumes() error {
<ide> volPath = path.Join(container.RootfsPath(), volPath)
<ide> rootVolPath, err := utils.FollowSymlinkInScope(volPath, container.RootfsPath())
<ide> if err != nil {
<del> panic(err)
<add> return err
<ide> }
<ide>
<ide> if _, err := os.Stat(rootVolPath); err != nil { | 3 |
Text | Text | add content, standardize style | 84cbd7ca33592b1a85c34fd72471085730dc74d6 | <ide><path>guide/english/accessibility/accessibility-basics/index.md
<ide> title: Accessibility Basics
<ide>
<ide> Accessibility's role in development is essentially understanding the user's perspective and needs, and knowing that the web, and applications are a solution for people with disabilities.
<ide>
<del>In this day and age, more and more new technologies are invented to make the life of developers, as well as users, easier. To what degree this is a good thing is a debate for another time, for now it's enough to say the toolbox of a developer, especially a web developer, is as ever-changing as the so called "dark arts" are according to our friend Snape.
<add>In this day and age, more and more new technologies are invented to make the lives of developers, as well as users, easier. To what degree this is a good thing is a debate for another time; for now, it's enough to say the toolbox of a developer, especially a web developer, is as ever-changing as the so-called "dark arts" are according to our friend Snape.
<ide>
<ide> One tool in that toolbox should be accessibility. It is a tool that should ideally be used in one of the very first steps of writing any form of web content. However, this tool is often not all that well presented in the toolbox of most developers. This could be due to a simple case of not knowing it even exists to extreme cases like not caring about it.
<ide>
<ide> In my life as a user, and later a developer, who benefits from accessibility in any form of content, I have seen both ends of that spectrum. If you are reading this article, I am guessing you are in one of the following categories:
<ide>
<ide> * You are a novice web developer and would like to know more about accessibility.
<del>* You are a seasoned web developer and have lost your way (more on that later).
<del>* You feel that there is a legal obligation from work, and need to learn more about it.
<add>* You are a seasoned web developer and have lost your way. (More on that later.)
<add>* You feel that there is a legal obligation from your employer, and you need to learn more about it.
<ide>
<ide> If you fall outside these rather broad categories, please let me know. I always like to hear from the people who read what I write about. Implementing accessibility impacts the entire team, from the colors chosen by the designer, the copy written by the copywriter, and to you, the developer.
<ide>
<ide> ## So, what is accessibility anyway?
<ide>
<del>Accessibility in itself is a bit of a misleading term sometimes, especially if English is your second language. It is sometimes referred to as inclusive design.
<add>Accessibility in itself is a bit of a misleading term sometimes, especially if English is your second language. It is sometimes referred to as "inclusive design."
<ide>
<ide> If your site is on the Internet, reachable by anyone with a web browser, in one sense that website is accessible to everyone with a web browser.
<ide>
<del>But, is all content on your website actually readable, usable and understandable for everyone? Are there no thresholds that bar certain people from 'accessing' all the information you are exposing?
<add>But, is all content on your website actually readable, usable and understandable for everyone? Are there no thresholds that bar certain people from "accessing" all the information you are exposing?
<ide>
<ide> You could ask yourself questions like the following:
<ide>
<ide> You could ask yourself questions like the following:
<ide> * Does your application still work (progressive enhancement) assuming that JavaScript does not load in time?
<ide> * If your website is very resource-heavy, will someone on an older device with a slow or spotty connection be able to access your content?
<ide>
<del>This is where accessibility comes into play. Accessibility basically entails making your content as friendly, as easy to 'access' as possible for the largest amount of people. This includes people who are older, deaf, low-vision, blind, dyslexic, colorblind, have epilepsy, have mental fatigue, have physical limitations, cannot afford new devices or high-speed connections, etc.
<add>This is where accessibility comes into play. Accessibility basically entails making your content as friendly, as easy to "access" as possible for the largest amount of people. This includes people who are older, deaf, low-vision, blind, dyslexic, colorblind, have epilepsy, have mental fatigue, have physical limitations, cannot afford new devices or high-speed connections, etc.
<ide>
<ide> ## Why implement accessibility?
<ide>
<ide> However, doing this research is key in actually defending such a statement. Did
<ide>
<ide> If you did, good for you. If not, I guess this drives my point home all the more.
<ide>
<del>The picture gets even more complicated when we look at legislation that actually forces you to make certain websites and web apps accessible. A prime example is the US-based <a href='http://jimthatcher.com/webcourse1.htm' target='_blank' rel='nofollow'>section 508</a>. Right now, this law mainly refers to government organizations, public sector websites etc. However, laws change.
<add>The picture gets even more complicated when we look at legislation that actually forces you to make certain websites and web apps accessible. A prime example is the US-based <a href='http://jimthatcher.com/webcourse1.htm' target='_blank' rel='nofollow'>Section 508</a>. Right now, this law mainly refers to government organizations, public sector websites, etc. However, laws change.
<ide>
<ide> Last year, airline websites were included in this list which meant that even here in Europe, airline website devs scrambled to make their content accessible. Not doing so can get your company a fine of literally tens of thousands of dollars for each day the problem isn't fixed.
<ide>
<ide> There are variations on this legislation all over the world, some more severe and all-encompassing than others. Not knowing about that fact doesn't make the lawsuit go away, sadly.
<ide>
<ide> ## Ok, so accessibility is a big deal. Now how do we implement it?
<ide>
<del>That question, sadly, is harder to answer than it may seem. The Harry Potter quote at the top is there for a reason, and it's not my being an avid Fantasy reader.
<add>That question, sadly, is harder to answer than it may seem. The Harry Potter quote at the top is there for a reason, and it's not my being an avid fantasy reader.
<ide>
<ide> As I stated above, accessibility is important for a large group of different people, each with their own needs. Making your website work for literally everyone is a large, on-going task.
<ide>
<ide> The HTML specification is a document that describes how the language should be u
<ide> ```
<ide> Guess what? All three of these elements break several criteria of WCAG and therefore are not accessible at all.
<ide>
<del>The first element breaks the so-called 'name, role, value'-criterium, which states that all elements on a web page should expose their name, their role (like button) and their value (like the contents of an edit field) to assistive technologies. This div actually doesn't provide any of the three, rendering it invisible to screen-readers.
<add>The first element breaks the so-called "name, role, value"-criterium, which states that all elements on a web page should expose their name, their role (like button) and their value (like the contents of an edit field) to assistive technologies. This div actually doesn't provide any of the three, rendering it invisible to screen-readers.
<ide>
<ide> The second element looks like a heading visually after styling it with CSS, but semantically is a span. Therefore, assistive technologies won't know it's a heading. A screen-reader will read this as regular text, instead of a heading. Screen-readers often have a hotkey to quickly jump to the nearest heading, this heading will not be included in that scope.
<ide>
<ide> I guess the best way to illustrate this is by giving an example:
<ide> <input type='text' id='username'>
<ide> ```
<ide>
<del>This will make for example a screen-reader say "username, text edit field", instead of just reporting' text edit field' and requiring the user to go look for a label. This also really helps people who use speech recognition software.
<add>This will make for example a screen-reader say "username, text edit field," instead of just reporting "text edit field" and requiring the user to go look for a label. This also really helps people who use speech recognition software.
<ide>
<ide> ### That's a tall order
<ide>
<ide><path>guide/english/bootstrap/carousel/index.md
<ide> title: Carousel
<ide> ## Carousel
<ide>
<ide> Carousel is a slideshow component for cycling through elements like images or slides of text.
<del>It provides a dynamic way of representing large amount of data (text or images) by sliding or cycling through, in a smooth fashion
<add>It provides a dynamic way of representing large amount of data (text or images) by sliding or cycling through, in a smooth fashion.
<ide>
<ide> Sample Code of Image Slider is below :
<ide>
<ide> Understanding the attributes and classes used in above example:
<ide>
<ide> a) `data-ride` :- `data-ride ="carousel"` allows on page load animation to begin.
<ide>
<del>b) `data-target` :- It points to the id of the Carousel
<add>b) `data-target` :- It points to the `id` of the carousel.
<ide>
<del>c) `data-slide-to` :- It specifies which slide to move on to when clicking on the indicators(specific dots).
<add>c) `data-slide-to` :- It specifies which slide to move on to when clicking on the indicators (specific dots).
<ide>
<ide> ### 2) Classes
<ide>
<del>a) `carousel` :- `class="carousel"` specifies that the div contains carousel.
<add>a) `carousel` :- `class="carousel"` specifies that the `div` contains carousel.
<ide>
<ide> b) `slide` :- This class adds CSS transitions.
<ide>
<ide> The `data-ride="carousel"` attribute is used to mark a carousel as animating sta
<ide> `data-slide` accepts the keywords `prev` or `next`, which alters the slide position relative to its current position.
<ide> #### 2) Via JavaScript
<ide> Call carousel manually with:
<del>
<del>`$('.carousel').carousel()`
<del>
<add>```javascript
<add>$('.carousel').carousel()
<add>```
<ide> ### Options
<ide> Options can be passed via data attributes or JavaScript. For data attributes, append the option name to `data-`, as in `data-interval=""`.
<ide>
<ide><path>guide/english/computer-hardware/hard-drives/index.md
<ide> Hard drives are permanent storage devices for computers. There are several types
<ide>
<ide> Traditional hard disks use magnetic needles and rotating magnetized platters to store data. Due to these moving parts, hard drives are easily damaged by drops and/or shocks. The motor that rotates the platters also consumes a lot of power, and yet no other storage method is as affordable for large volumes of storage.
<ide>
<del>Hard drives come in various storage capacities, with some even storing 10TB (10 trillion bytes). Typical computers come with 256GB (256 million bytes) to 1TB of storage space. Laptops usually use Solid State Drives (SSDs) because they are faster, lighter, and contain no moving parts, making them less likely to fail due to impact. For the same amount of storage, SSDs are generally more expensive than hard drives. Recently, some SSDs have been released that interface with the motherboard through the PCIe (PCI Express) bus slot using a system called NVMe. These SSDs have proven to be even faster at read/write times than traditional SATA SSDs.
<add>Hard drives come in various storage capacities, with some even storing 10TB (10 trillion bytes). Typical computers come with 256GB (256 million bytes) to 1TB of storage space. Laptops usually use Solid State Drives (SSDs) because they are faster, lighter, and contain no moving parts, making them less likely to fail due to impact. For the same amount of storage, SSDs are generally more expensive than hard drives. Recently, some SSDs have been released that interface with the motherboard through the PCI Express (PCIe) bus slot using a system called Non-Volatile Memory Express (NVMe). These SSDs have proven to be even faster at read/write times than traditional Serial Advanced Technology Attachment (SATA) SSDs.
<ide>
<ide> Magnetic heads are responsible for reading and writing data, which is physically stored on a set of magnetically coated discs stacked above one another, referred to as a platter. The heads are located at the end of an armature. The interior discs of the platter have two heads on a single arm. This allows data to be accessed from both the discs, beneath and above the arm. The top and bottom discs of the platter only have one head at the end of an arm. On the opposite end of the arm is an actuator. It provides movement of the arm to travel from the center of the platter, the spindle, to the outermost regions of the platter. The amount of time it takes to place the head in the correct concentric location is referred to as the seek time. Once the head is in the correct concentric spatial location more time is spent waiting for the disc to rotate such that the sector with the requested data is beneath the head. This amount of time is referred to as latency.
<ide>
<del>The heads are positioned only a few nanometers away from the rotating discs. The heads are said to "fly" above the platter and as such the distance between head and platter is referred to as the 'flying height'. The heads are designed to never touch the locations of the platters that store data and are magnetically coated. Should the head 'touch down' on a platter, both the head and sectors of the platters may be destroyed resulting in data loss (hence the phrase "a hard drive crash" or "head crash").
<add>The heads are positioned only a few nanometers away from the rotating discs. The heads are said to "fly" above the platter and as such the distance between head and platter is referred to as the "flying height." The heads are designed to never touch the locations of the platters that store data and are magnetically coated. Should the head "touch down" on a platter, both the head and sectors of the platters may be destroyed, resulting in data loss (hence the phrases "a hard drive crash" or "head crash").
<ide>
<del>Hard drives retrieve and store data from applications at the request of the CPU. This is referred to as input/output operations--IO for short. When a running program requires a certain piece of data, the CPU dispatches an instruction for the data to be fetched from the hard drive. Reading this piece of data is an input operation (from the CPU's perspective). The program may then perform a computation which changes the data and the results need to be stored back out to the hard drive. The CPU requests the data be written back out to the drive. This would be an example of an output operation (again, from the CPU's perspective).
<add>Hard drives retrieve and store data from applications at the request of the central processing unit (CPU). This is referred to as input/output operations (IO). When a running program requires a certain piece of data, the CPU dispatches an instruction for the data to be fetched from the hard drive. Reading this piece of data is an input operation (from the CPU's perspective). The program may then perform a computation which changes the data and the results need to be stored back out to the hard drive. The CPU requests the data be written back out to the drive. This would be an example of an output operation (again, from the CPU's perspective).
<ide>
<del>Hard drive performance is measured primarily by two key metrics 1) response time, which is how long it takes a read or write operation to complete and 2) IOPS which is an acronym for 'Input / Output Operations per Second'. As the name would suggest, IOPS is a measurement of the maximum IO operations in one second. The primary factor in achieving maximum IOPS at the lowest response time is the hard drive's rotational speed measured in revolutions per minute (RPM). Common rotational speeds are 5,400 RPM, 7,200 RPM, 10,000 RPM and 15,000 RPM (commonly notated as 5.4K, 7.2K, 10K and 15K). Hard drives with higher rotational rates (RPM's) will have more platter real estate pass beneath the heads for IO operations (reads and writes). Hard drives with lower RPM rotational rates will have much higher mechanical latencies, as less real estate passes beneath the heads.
<add>Hard drive performance is measured primarily by two key metrics: 1) response time, which is how long it takes a read or write operation to complete, and 2) IOPS which is an acronym for "Input/Output Operations per Second". As the name would suggest, IOPS is a measurement of the maximum IO operations in one second. The primary factor in achieving maximum IOPS at the lowest response time is the hard drive's rotational speed measured in revolutions per minute (RPM). Common rotational speeds are 5,400 RPM, 7,200 RPM, 10,000 RPM and 15,000 RPM (commonly notated as 5.4K, 7.2K, 10K, and 15K, respectively). Hard drives with higher rotational rates (RPMs) will have more platter real estate pass beneath the heads for IO operations (reads and writes). Hard drives with lower RPM rotational rates will have much higher mechanical latencies, as less real estate passes beneath the heads.
<ide>
<del>One simple tool for measuring hard drive performance metrics is called IOMeter (see link below). The program is very lightweight and easy to install. Once it is up and running, several different variations of workloads can be run to simulate data reads & writes to the disk. This data is analyzed and outputs metrics for read/write times, IOPS, as well as other useful metrics. Tests can be saved for consistent checks and the data can easily be parsed in a table or graph form.
<add>One simple tool for measuring hard drive performance metrics is called IOMeter (see link below). The program is very lightweight and easy to install. Once it is up and running, several different variations of workloads can be run to simulate data reads & writes to the disk. This data is analyzed and outputs metrics for read/write times, IOPS, as well as other useful metrics. Tests can be saved for consistent checks, and the data can easily be parsed in a table or graph form.
<ide>
<ide> Hard drives tend to be categorized by use case (capacity or performance). Home PC's and general-use office workstations tend to use slower rotating hard drives (5.4K and 7.2K) which is fine for storing pictures and office files. However, large databases that support online banking transactions for instance, use the faster 10K and 15K RPM hard drives as they'll be components in an enterprise server or storage array. There's a tradeoff between a hard drive's performance and capacity, however. For instance, the largest capacity 15K hard drive available today is only 600 GB, whereas the largest capacity hard drive for the both 5.4K and 7.2K RPM is 10 TB. The 600 GB 15K drive is capable of 250 IOPS @ 3 ms response time (averages). Whereas the 10 TB 7.2K TB drive does not measure IOPS at a given response time, as it's not optimized nor intended for IOPS centric performance use cases. There are also other tradeoffs in price per GB, energy consumed and size (2.5" vs 3.5" inches).
<ide>
<del>Computers store data and files on hard drives for later use. Because hard drives have moving parts, it takes much longer to read a file from a hard drive than from RAM or cache memory on the CPU. You can think of a hard drive as a filing cabinet: a place to store things that we aren't using right now, but need later. You don't have enough room on your desk for all your papers, so you store things you aren't using right now in the filing cabinet. A computer does just this. It keeps files it is using right now in RAM, and files it might need later stay on the hard drive. Though RAM has access and response times that are two orders of magnitude faster when compared to hard drives, their typical capacity is 1-2 orders of magnitude less that a typical hard drive. You can fit reams of paper in the filing cabinet, but only a few on your desk.
<add>Computers store data and files on hard drives for later use. Because hard drives have moving parts, it takes much longer to read a file from a hard drive than from random access memory (RAM) or cache memory on the CPU. You can think of a hard drive as a filing cabinet: a place to store things that we aren't using right now, but need later. You don't have enough room on your desk for all your papers, so you store things you aren't using right now in the filing cabinet. A computer does just this. It keeps files it is using right now in RAM, and files it might need later stay on the hard drive. Though RAM has access and response times that are two orders of magnitude faster when compared to hard drives, their typical capacity is 1-2 orders of magnitude less that a typical hard drive. You can fit reams of paper in the filing cabinet, but only a few on your desk.
<ide>
<ide>
<del>Data stored in RAM is said to be fleeting whereas data written out to a hard drive is persistent. Meaning if the power suddenly goes out, any data that was in RAM is lost and will not be there after power is restored and the computer is booted back up. However data that was written to the hard drive will be there when power is restored. For this reason, modern operating systems and applications will periodically write session and application related data that's currently in RAM out to the hard drive. This way if the power goes out, only 10 minutes of data entered in a newly created spreadsheet that was being worked on for 3 hours preceding the power outage and not yet saved to the hard drive will be lost. These files are usually denoted with a tilde, ~ , and can be found in a temporary or temp directory or possibly located in a 'blind directory' whose contents are referred to as hidden files.
<add>Data stored in RAM is said to be fleeting whereas data written out to a hard drive is persistent. Meaning if the power suddenly goes out, any data that was in RAM is lost and will not be there after power is restored and the computer is booted back up. However data that was written to the hard drive will be there when power is restored. For this reason, modern operating systems and applications will periodically write session and application related data that's currently in RAM out to the hard drive. This way if the power goes out, only 10 minutes of data entered in a newly created spreadsheet that was being worked on for 3 hours preceding the power outage and not yet saved to the hard drive will be lost. These files are usually denoted with a tilde (`~`) and can be found in a temporary or temp directory or possibly located in a "blind directory" whose contents are referred to as hidden files.
<ide>
<ide>
<ide> ## Solid State Drives (SSD)
<ide> Solid State Drives uses integrated circuits to store data. Therefore, an SSD has no moving parts like the HDD. This makes them less prone to physical shocks, run silently, and have faster read/write times thanks to not needing to locate the data physically.
<ide>
<ide> SSDs are commonly used as boot drives or storage for the most used applications and files on a system. This is because even though prices have dropped in recent years, SSDs are still more expensive than a traditional hard drive when considering cost per unit of storage. Also they have a lifetime, in the sense that their performance keeps decreasing as we write more and more data to them and eventually they need to be replaced. Thus, HDDs are still used for bulk data such as entertainment media (pictures, videos, music) and in data centers or server farms. Though here it is common for the Hard Drives to be accelerated with an SSD.
<ide>
<del>While most Hard Drives use either a SATA or SAS connector, Solid State Drives often use other connections that can handle higher bandwidth and lower latencies, with the most notable being PCI Express (PCI-e) where form factors such as M.2 or U.2 dominate. Though other form factors are available, such as Intel's 'Yard stick' form factor or PCI-e cards that look quite similar to a low end graphics card.
<add>While most Hard Drives use either a SATA or SAS connector, Solid State Drives often use other connections that can handle higher bandwidth and lower latencies, with the most notable being PCI Express (PCI-e) where form factors such as M.2 or U.2 dominate. Though other form factors are available, such as Intel's "Yard stick" form factor or PCI-e cards that look quite similar to a low end graphics card.
<ide>
<ide> The one caviat to these is that they usually have a lower amount of full writes that the drives can do before starting to go bad.
<ide>
<ide> ## Solid State Hard Drives (SSHD) a.k.a Hybrid Drives
<del>
<del>Solid State Hard Drives fill a specific gap in between Solid State Drives and traditional hard drives. It combines the relative affordable cost of cheap magnetic storage in traditional drives and pairs it with a smaller capacity Solid State Drive with the intent of using the SSD portion to cache frequently used data to increase performance over a plain traditional hard drive at a marginal cost. Hence the combination of the two technologies creates a "hybrid device" that is cost effectively but still is able to benefit from the high performance of SSD drives primarily for low intensity workloads that mostly utilize read requests from the drive.
<del>
<add>Solid State Hard Drives fill a specific gap in between Solid State Drives and traditional hard drives. They combine the relative affordable cost of cheap magnetic storage in traditional drives and pairs it with a smaller capacity Solid State Drive with the intent of using the SSD portion to cache frequently used data to increase performance over a plain traditional hard drive at a marginal cost. Hence the combination of the two technologies creates a "hybrid device" that is cost effectively but still is able to benefit from the high performance of SSD drives primarily for low intensity workloads that mostly utilize read requests from the drive.
<ide>
<ide> #### More Information:
<ide> | 3 |
Text | Text | update initial sample with colours | dfcf874735cb2cd7ed3e395ce66a6a89172c6d1c | <ide><path>docs/00-Getting-Started.md
<ide> var myChart = new Chart(ctx, {
<ide> labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
<ide> datasets: [{
<ide> label: '# of Votes',
<del> data: [12, 19, 3, 5, 2, 3]
<add> data: [12, 19, 3, 5, 2, 3],
<add> backgroundColor: [
<add> 'rgba(255, 99, 132, 0.2)',
<add> 'rgba(54, 162, 235, 0.2)',
<add> 'rgba(255, 206, 86, 0.2)',
<add> 'rgba(75, 192, 192, 0.2)',
<add> 'rgba(153, 102, 255, 0.2)',
<add> 'rgba(255, 159, 64, 0.2)'
<add> ],
<add> borderColor: [
<add> 'rgba(255,99,132,1)',
<add> 'rgba(54, 162, 235, 1)',
<add> 'rgba(255, 206, 86, 1)',
<add> 'rgba(75, 192, 192, 1)',
<add> 'rgba(153, 102, 255, 1)',
<add> 'rgba(255, 159, 64, 1)'
<add> ],
<add> borderWidth: 1
<ide> }]
<ide> },
<ide> options: { | 1 |
Javascript | Javascript | add disabled binding to all controls | 4532f0a3afeab665f244acef9139f99de477b93d | <ide><path>packages/sproutcore-handlebars/lib/controls/button.js
<ide> SC.Button = SC.View.extend({
<ide> classNameBindings: ['isActive'],
<ide>
<ide> tagName: 'button',
<del> attributeBindings: ['type'],
<add> attributeBindings: ['type', 'disabled'],
<ide> type: 'button',
<del>
<add> disabled: false,
<add>
<ide> targetObject: function() {
<ide> var target = get(this, 'target');
<ide>
<ide><path>packages/sproutcore-handlebars/lib/controls/checkbox.js
<ide> var set = SC.set, get = SC.get;
<ide> SC.Checkbox = SC.View.extend({
<ide> title: null,
<ide> value: false,
<add> disabled: false,
<ide>
<ide> classNames: ['sc-checkbox'],
<ide>
<del> defaultTemplate: SC.Handlebars.compile('<label><input type="checkbox" {{bindAttr checked="value"}}>{{title}}</label>'),
<add> defaultTemplate: SC.Handlebars.compile('<label><input type="checkbox" {{bindAttr checked="value" disabled="disabled"}}>{{title}}</label>'),
<ide>
<ide> change: function() {
<ide> SC.run.once(this, this._updateElementValue);
<ide><path>packages/sproutcore-handlebars/lib/controls/text_area.js
<ide> SC.TextArea = SC.View.extend({
<ide>
<ide> tagName: "textarea",
<ide> value: "",
<del> attributeBindings: ['placeholder'],
<add> attributeBindings: ['placeholder', 'disabled'],
<ide> placeholder: null,
<add> disabled: false,
<ide>
<ide> insertNewline: SC.K,
<ide> cancel: SC.K,
<ide><path>packages/sproutcore-handlebars/lib/controls/text_field.js
<ide> SC.TextField = SC.View.extend(
<ide> cancel: SC.K,
<ide>
<ide> tagName: "input",
<del> attributeBindings: ['type', 'placeholder', 'value'],
<add> attributeBindings: ['type', 'placeholder', 'value', 'disabled'],
<ide> type: "text",
<ide> value: "",
<ide> placeholder: null,
<add> disabled: false,
<ide>
<ide> focusOut: function(event) {
<ide> this._elementValueDidChange();
<ide><path>packages/sproutcore-handlebars/lib/views/metamorph_view.js
<ide> SC.Metamorph = SC.Mixin.create({
<ide> domManagerClass: SC.Object.extend({
<ide> remove: function(view) {
<ide> var morph = getPath(this, 'view.morph');
<add> if (morph.isRemoved()) { return; }
<ide> getPath(this, 'view.morph').remove();
<ide> },
<ide>
<ide><path>packages/sproutcore-handlebars/tests/controls/button_test.js
<ide> function synthesizeEvent(type, view) {
<ide> view.$().trigger(type);
<ide> }
<ide>
<add>function append() {
<add> SC.run(function() {
<add> button.appendTo('#qunit-fixture');
<add> });
<add>}
<add>
<add>test("should become disabled if the disabled attribute is true", function() {
<add> button.set('disabled', true);
<add> append();
<add>
<add> ok(button.$().is(":disabled"));
<add>});
<add>
<add>test("should become disabled if the disabled attribute is true", function() {
<add> append();
<add> ok(button.$().is(":not(:disabled)"));
<add>
<add> SC.run(function() { button.set('disabled', true); });
<add> ok(button.$().is(":disabled"));
<add>
<add> SC.run(function() { button.set('disabled', false); });
<add> ok(button.$().is(":not(:disabled)"));
<add>});
<add>
<ide> test("should trigger an action when clicked", function() {
<ide> var wasClicked = false;
<ide>
<ide><path>packages/sproutcore-handlebars/tests/controls/checkbox_test.js
<ide> function setAndFlush(view, key, value) {
<ide> });
<ide> }
<ide>
<add>function append() {
<add> SC.run(function() {
<add> checkboxView.appendTo('#qunit-fixture');
<add> });
<add>}
<add>
<add>test("should become disabled if the disabled attribute is true", function() {
<add> checkboxView = SC.Checkbox.create({});
<add>
<add> checkboxView.set('disabled', true);
<add> append();
<add>
<add> ok(checkboxView.$("input").is(":disabled"));
<add>});
<add>
<add>test("should become disabled if the disabled attribute is true", function() {
<add> checkboxView = SC.Checkbox.create({});
<add>
<add> append();
<add> ok(checkboxView.$("input").is(":not(:disabled)"));
<add>
<add> SC.run(function() { checkboxView.set('disabled', true); });
<add> ok(checkboxView.$("input").is(":disabled"));
<add>
<add> SC.run(function() { checkboxView.set('disabled', false); });
<add> ok(checkboxView.$("input").is(":not(:disabled)"));
<add>});
<add>
<ide> test("value property mirrors input value", function() {
<ide> checkboxView = SC.Checkbox.create({});
<ide> SC.run(function() { checkboxView.append(); });
<ide><path>packages/sproutcore-handlebars/tests/controls/text_area_test.js
<ide> module("SC.TextArea", {
<ide> }
<ide> });
<ide>
<add>function append() {
<add> SC.run(function() {
<add> textArea.appendTo('#qunit-fixture');
<add> });
<add>}
<add>
<add>test("should become disabled if the disabled attribute is true", function() {
<add> textArea.set('disabled', true);
<add> append();
<add>
<add> ok(textArea.$().is(":disabled"));
<add>});
<add>
<add>test("should become disabled if the disabled attribute is true", function() {
<add> append();
<add> ok(textArea.$().is(":not(:disabled)"));
<add>
<add> SC.run(function() { textArea.set('disabled', true); });
<add> ok(textArea.$().is(":disabled"));
<add>
<add> SC.run(function() { textArea.set('disabled', false); });
<add> ok(textArea.$().is(":not(:disabled)"));
<add>});
<add>
<ide> test("input value is updated when setting value property of view", function() {
<ide> SC.run(function() {
<ide> set(textArea, 'value', 'foo');
<ide><path>packages/sproutcore-handlebars/tests/controls/text_field_test.js
<ide> module("SC.TextField", {
<ide> }
<ide> });
<ide>
<add>function append() {
<add> SC.run(function() {
<add> textField.appendTo('#qunit-fixture');
<add> });
<add>}
<add>
<add>test("should become disabled if the disabled attribute is true", function() {
<add> textField.set('disabled', true);
<add> append();
<add>
<add> ok(textField.$().is(":disabled"));
<add>});
<add>
<add>test("should become disabled if the disabled attribute is true", function() {
<add> append();
<add> ok(textField.$().is(":not(:disabled)"));
<add>
<add> SC.run(function() { textField.set('disabled', true); });
<add> ok(textField.$().is(":disabled"));
<add>
<add> SC.run(function() { textField.set('disabled', false); });
<add> ok(textField.$().is(":not(:disabled)"));
<add>});
<add>
<ide> test("input value is updated when setting value property of view", function() {
<ide> SC.run(function() {
<ide> set(textField, 'value', 'foo'); | 9 |
Text | Text | use code markup/markdown in headers | ff6e7a0b3e53ac191ee4f2c765fcd473c5dc570c | <ide><path>doc/api/util.md
<ide> module developers as well. It can be accessed using:
<ide> const util = require('util');
<ide> ```
<ide>
<del>## util.callbackify(original)
<add>## `util.callbackify(original)`
<ide> <!-- YAML
<ide> added: v8.2.0
<ide> -->
<ide> callbackFunction((err, ret) => {
<ide> });
<ide> ```
<ide>
<del>## util.debuglog(section)
<add>## `util.debuglog(section)`
<ide> <!-- YAML
<ide> added: v0.11.3
<ide> -->
<ide> FOO-BAR 3257: hi there, it's foo-bar [2333]
<ide> Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`
<ide> environment variable: `NODE_DEBUG=fs,net,tls`.
<ide>
<del>## util.deprecate(fn, msg\[, code\])
<add>## `util.deprecate(fn, msg[, code])`
<ide> <!-- YAML
<ide> added: v0.8.0
<ide> changes:
<ide> The `--throw-deprecation` command line flag and `process.throwDeprecation`
<ide> property take precedence over `--trace-deprecation` and
<ide> `process.traceDeprecation`.
<ide>
<del>## util.format(format\[, ...args\])
<add>## `util.format(format[, ...args])`
<ide> <!-- YAML
<ide> added: v0.5.3
<ide> changes:
<ide> util.format('%% %s');
<ide> Some input values can have a significant performance overhead that can block the
<ide> event loop. Use this function with care and never in a hot code path.
<ide>
<del>## util.formatWithOptions(inspectOptions, format\[, ...args\])
<add>## `util.formatWithOptions(inspectOptions, format[, ...args])`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
<ide> // when printed to a terminal.
<ide> ```
<ide>
<del>## util.getSystemErrorName(err)
<add>## `util.getSystemErrorName(err)`
<ide> <!-- YAML
<ide> added: v9.7.0
<ide> -->
<ide> fs.access('file/that/does/not/exist', (err) => {
<ide> });
<ide> ```
<ide>
<del>## util.inherits(constructor, superConstructor)
<add>## `util.inherits(constructor, superConstructor)`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> changes:
<ide> stream.on('data', (data) => {
<ide> stream.write('With ES6');
<ide> ```
<ide>
<del>## util.inspect(object\[, options\])
<del>## util.inspect(object\[, showHidden\[, depth\[, colors\]\]\])
<add>## `util.inspect(object[, options])`
<add>## `util.inspect(object[, showHidden[, depth[, colors]]])`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> changes:
<ide> util.inspect(obj);
<ide> // Returns: "{ bar: 'baz' }"
<ide> ```
<ide>
<del>### util.inspect.custom
<add>### `util.inspect.custom`
<ide> <!-- YAML
<ide> added: v6.6.0
<ide> changes:
<ide> console.log(password);
<ide>
<ide> See [Custom inspection functions on Objects][] for more details.
<ide>
<del>### util.inspect.defaultOptions
<add>### `util.inspect.defaultOptions`
<ide> <!-- YAML
<ide> added: v6.4.0
<ide> -->
<ide> util.inspect.defaultOptions.maxArrayLength = null;
<ide> console.log(arr); // logs the full array
<ide> ```
<ide>
<del>## util.isDeepStrictEqual(val1, val2)
<add>## `util.isDeepStrictEqual(val1, val2)`
<ide> <!-- YAML
<ide> added: v9.0.0
<ide> -->
<ide> Otherwise, returns `false`.
<ide> See [`assert.deepStrictEqual()`][] for more information about deep strict
<ide> equality.
<ide>
<del>## util.promisify(original)
<add>## `util.promisify(original)`
<ide> <!-- YAML
<ide> added: v8.0.0
<ide> -->
<ide> doSomething[util.promisify.custom] = (foo) => {
<ide> If `promisify.custom` is defined but is not a function, `promisify()` will
<ide> throw an error.
<ide>
<del>### util.promisify.custom
<add>### `util.promisify.custom`
<ide> <!-- YAML
<ide> added: v8.0.0
<ide> -->
<ide>
<ide> * {symbol} that can be used to declare custom promisified variants of functions,
<ide> see [Custom promisified functions][].
<ide>
<del>## Class: util.TextDecoder
<add>## Class: `util.TextDecoder`
<ide> <!-- YAML
<ide> added: v8.3.0
<ide> -->
<ide> Different Node.js build configurations support different sets of encodings.
<ide> The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][]
<ide> is not supported.
<ide>
<del>### new TextDecoder(\[encoding\[, options\]\])
<add>### `new TextDecoder([encoding[, options]])`
<ide> <!-- YAML
<ide> added: v8.3.0
<ide> changes:
<ide> supported encodings or an alias.
<ide>
<ide> The `TextDecoder` class is also available on the global object.
<ide>
<del>### textDecoder.decode(\[input\[, options\]\])
<add>### `textDecoder.decode([input[, options]])`
<ide>
<ide> * `input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView` or
<ide> `TypedArray` instance containing the encoded data.
<ide> internally and emitted after the next call to `textDecoder.decode()`.
<ide> If `textDecoder.fatal` is `true`, decoding errors that occur will result in a
<ide> `TypeError` being thrown.
<ide>
<del>### textDecoder.encoding
<add>### `textDecoder.encoding`
<ide>
<ide> * {string}
<ide>
<ide> The encoding supported by the `TextDecoder` instance.
<ide>
<del>### textDecoder.fatal
<add>### `textDecoder.fatal`
<ide>
<ide> * {boolean}
<ide>
<ide> The value will be `true` if decoding errors result in a `TypeError` being
<ide> thrown.
<ide>
<del>### textDecoder.ignoreBOM
<add>### `textDecoder.ignoreBOM`
<ide>
<ide> * {boolean}
<ide>
<ide> The value will be `true` if the decoding result will include the byte order
<ide> mark.
<ide>
<del>## Class: util.TextEncoder
<add>## Class: `util.TextEncoder`
<ide> <!-- YAML
<ide> added: v8.3.0
<ide> changes:
<ide> const uint8array = encoder.encode('this is some data');
<ide>
<ide> The `TextEncoder` class is also available on the global object.
<ide>
<del>### textEncoder.encode(\[input\])
<add>### `textEncoder.encode([input])`
<ide>
<ide> * `input` {string} The text to encode. **Default:** an empty string.
<ide> * Returns: {Uint8Array}
<ide>
<ide> UTF-8 encodes the `input` string and returns a `Uint8Array` containing the
<ide> encoded bytes.
<ide>
<del>### textEncoder.encodeInto(src, dest)
<add>### `textEncoder.encodeInto(src, dest)`
<ide>
<ide> * `src` {string} The text to encode.
<ide> * `dest` {Uint8Array} The array to hold the encode result.
<ide> const dest = new Uint8Array(10);
<ide> const { read, written } = encoder.encodeInto(src, dest);
<ide> ```
<ide>
<del>### textEncoder.encoding
<add>### `textEncoder.encoding`
<ide>
<ide> * {string}
<ide>
<ide> The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`.
<ide>
<del>## util.types
<add>## `util.types`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> The result generally does not make any guarantees about what kinds of
<ide> properties or behavior a value exposes in JavaScript. They are primarily
<ide> useful for addon developers who prefer to do type checking in JavaScript.
<ide>
<del>### util.types.isAnyArrayBuffer(value)
<add>### `util.types.isAnyArrayBuffer(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true
<ide> util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true
<ide> ```
<ide>
<del>### util.types.isArgumentsObject(value)
<add>### `util.types.isArgumentsObject(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> function foo() {
<ide> }
<ide> ```
<ide>
<del>### util.types.isArrayBuffer(value)
<add>### `util.types.isArrayBuffer(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isArrayBuffer(new ArrayBuffer()); // Returns true
<ide> util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false
<ide> ```
<ide>
<del>### util.types.isAsyncFunction(value)
<add>### `util.types.isAsyncFunction(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isAsyncFunction(function foo() {}); // Returns false
<ide> util.types.isAsyncFunction(async function foo() {}); // Returns true
<ide> ```
<ide>
<del>### util.types.isBigInt64Array(value)
<add>### `util.types.isBigInt64Array(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isBigInt64Array(new BigInt64Array()); // Returns true
<ide> util.types.isBigInt64Array(new BigUint64Array()); // Returns false
<ide> ```
<ide>
<del>### util.types.isBigUint64Array(value)
<add>### `util.types.isBigUint64Array(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isBigUint64Array(new BigInt64Array()); // Returns false
<ide> util.types.isBigUint64Array(new BigUint64Array()); // Returns true
<ide> ```
<ide>
<del>### util.types.isBooleanObject(value)
<add>### `util.types.isBooleanObject(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isBooleanObject(Boolean(false)); // Returns false
<ide> util.types.isBooleanObject(Boolean(true)); // Returns false
<ide> ```
<ide>
<del>### util.types.isBoxedPrimitive(value)
<add>### `util.types.isBoxedPrimitive(value)`
<ide> <!-- YAML
<ide> added: v10.11.0
<ide> -->
<ide> util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true
<ide> util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
<ide> ```
<ide>
<del>### util.types.isDataView(value)
<add>### `util.types.isDataView(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isDataView(new Float64Array()); // Returns false
<ide>
<ide> See also [`ArrayBuffer.isView()`][].
<ide>
<del>### util.types.isDate(value)
<add>### `util.types.isDate(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> Returns `true` if the value is a built-in [`Date`][] instance.
<ide> util.types.isDate(new Date()); // Returns true
<ide> ```
<ide>
<del>### util.types.isExternal(value)
<add>### `util.types.isExternal(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> added: v10.0.0
<ide>
<ide> Returns `true` if the value is a native `External` value.
<ide>
<del>### util.types.isFloat32Array(value)
<add>### `util.types.isFloat32Array(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isFloat32Array(new Float32Array()); // Returns true
<ide> util.types.isFloat32Array(new Float64Array()); // Returns false
<ide> ```
<ide>
<del>### util.types.isFloat64Array(value)
<add>### `util.types.isFloat64Array(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isFloat64Array(new Uint8Array()); // Returns false
<ide> util.types.isFloat64Array(new Float64Array()); // Returns true
<ide> ```
<ide>
<del>### util.types.isGeneratorFunction(value)
<add>### `util.types.isGeneratorFunction(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isGeneratorFunction(function foo() {}); // Returns false
<ide> util.types.isGeneratorFunction(function* foo() {}); // Returns true
<ide> ```
<ide>
<del>### util.types.isGeneratorObject(value)
<add>### `util.types.isGeneratorObject(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> const generator = foo();
<ide> util.types.isGeneratorObject(generator); // Returns true
<ide> ```
<ide>
<del>### util.types.isInt8Array(value)
<add>### `util.types.isInt8Array(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isInt8Array(new Int8Array()); // Returns true
<ide> util.types.isInt8Array(new Float64Array()); // Returns false
<ide> ```
<ide>
<del>### util.types.isInt16Array(value)
<add>### `util.types.isInt16Array(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isInt16Array(new Int16Array()); // Returns true
<ide> util.types.isInt16Array(new Float64Array()); // Returns false
<ide> ```
<ide>
<del>### util.types.isInt32Array(value)
<add>### `util.types.isInt32Array(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isInt32Array(new Int32Array()); // Returns true
<ide> util.types.isInt32Array(new Float64Array()); // Returns false
<ide> ```
<ide>
<del>### util.types.isMap(value)
<add>### `util.types.isMap(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> Returns `true` if the value is a built-in [`Map`][] instance.
<ide> util.types.isMap(new Map()); // Returns true
<ide> ```
<ide>
<del>### util.types.isMapIterator(value)
<add>### `util.types.isMapIterator(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isMapIterator(map.entries()); // Returns true
<ide> util.types.isMapIterator(map[Symbol.iterator]()); // Returns true
<ide> ```
<ide>
<del>### util.types.isModuleNamespaceObject(value)
<add>### `util.types.isModuleNamespaceObject(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> import * as ns from './a.js';
<ide> util.types.isModuleNamespaceObject(ns); // Returns true
<ide> ```
<ide>
<del>### util.types.isNativeError(value)
<add>### `util.types.isNativeError(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isNativeError(new TypeError()); // Returns true
<ide> util.types.isNativeError(new RangeError()); // Returns true
<ide> ```
<ide>
<del>### util.types.isNumberObject(value)
<add>### `util.types.isNumberObject(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isNumberObject(0); // Returns false
<ide> util.types.isNumberObject(new Number(0)); // Returns true
<ide> ```
<ide>
<del>### util.types.isPromise(value)
<add>### `util.types.isPromise(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> Returns `true` if the value is a built-in [`Promise`][].
<ide> util.types.isPromise(Promise.resolve(42)); // Returns true
<ide> ```
<ide>
<del>### util.types.isProxy(value)
<add>### `util.types.isProxy(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isProxy(target); // Returns false
<ide> util.types.isProxy(proxy); // Returns true
<ide> ```
<ide>
<del>### util.types.isRegExp(value)
<add>### `util.types.isRegExp(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isRegExp(/abc/); // Returns true
<ide> util.types.isRegExp(new RegExp('abc')); // Returns true
<ide> ```
<ide>
<del>### util.types.isSet(value)
<add>### `util.types.isSet(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> Returns `true` if the value is a built-in [`Set`][] instance.
<ide> util.types.isSet(new Set()); // Returns true
<ide> ```
<ide>
<del>### util.types.isSetIterator(value)
<add>### `util.types.isSetIterator(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isSetIterator(set.entries()); // Returns true
<ide> util.types.isSetIterator(set[Symbol.iterator]()); // Returns true
<ide> ```
<ide>
<del>### util.types.isSharedArrayBuffer(value)
<add>### `util.types.isSharedArrayBuffer(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false
<ide> util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true
<ide> ```
<ide>
<del>### util.types.isStringObject(value)
<add>### `util.types.isStringObject(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isStringObject('foo'); // Returns false
<ide> util.types.isStringObject(new String('foo')); // Returns true
<ide> ```
<ide>
<del>### util.types.isSymbolObject(value)
<add>### `util.types.isSymbolObject(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isSymbolObject(symbol); // Returns false
<ide> util.types.isSymbolObject(Object(symbol)); // Returns true
<ide> ```
<ide>
<del>### util.types.isTypedArray(value)
<add>### `util.types.isTypedArray(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isTypedArray(new Float64Array()); // Returns true
<ide>
<ide> See also [`ArrayBuffer.isView()`][].
<ide>
<del>### util.types.isUint8Array(value)
<add>### `util.types.isUint8Array(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isUint8Array(new Uint8Array()); // Returns true
<ide> util.types.isUint8Array(new Float64Array()); // Returns false
<ide> ```
<ide>
<del>### util.types.isUint8ClampedArray(value)
<add>### `util.types.isUint8ClampedArray(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true
<ide> util.types.isUint8ClampedArray(new Float64Array()); // Returns false
<ide> ```
<ide>
<del>### util.types.isUint16Array(value)
<add>### `util.types.isUint16Array(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isUint16Array(new Uint16Array()); // Returns true
<ide> util.types.isUint16Array(new Float64Array()); // Returns false
<ide> ```
<ide>
<del>### util.types.isUint32Array(value)
<add>### `util.types.isUint32Array(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isUint32Array(new Uint32Array()); // Returns true
<ide> util.types.isUint32Array(new Float64Array()); // Returns false
<ide> ```
<ide>
<del>### util.types.isWeakMap(value)
<add>### `util.types.isWeakMap(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> Returns `true` if the value is a built-in [`WeakMap`][] instance.
<ide> util.types.isWeakMap(new WeakMap()); // Returns true
<ide> ```
<ide>
<del>### util.types.isWeakSet(value)
<add>### `util.types.isWeakSet(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> Returns `true` if the value is a built-in [`WeakSet`][] instance.
<ide> util.types.isWeakSet(new WeakSet()); // Returns true
<ide> ```
<ide>
<del>### util.types.isWebAssemblyCompiledModule(value)
<add>### `util.types.isWebAssemblyCompiledModule(value)`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> util.types.isWebAssemblyCompiledModule(module); // Returns true
<ide> The following APIs are deprecated and should no longer be used. Existing
<ide> applications and modules should be updated to find alternative approaches.
<ide>
<del>### util.\_extend(target, source)
<add>### `util._extend(target, source)`
<ide> <!-- YAML
<ide> added: v0.7.5
<ide> deprecated: v6.0.0
<ide> Node.js modules. The community found and used it anyway.
<ide> It is deprecated and should not be used in new code. JavaScript comes with very
<ide> similar built-in functionality through [`Object.assign()`][].
<ide>
<del>### util.isArray(object)
<add>### `util.isArray(object)`
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> deprecated: v4.0.0
<ide> util.isArray({});
<ide> // Returns: false
<ide> ```
<ide>
<del>### util.isBoolean(object)
<add>### `util.isBoolean(object)`
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> util.isBoolean(false);
<ide> // Returns: true
<ide> ```
<ide>
<del>### util.isBuffer(object)
<add>### `util.isBuffer(object)`
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> util.isBuffer(Buffer.from('hello world'));
<ide> // Returns: true
<ide> ```
<ide>
<del>### util.isDate(object)
<add>### `util.isDate(object)`
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> deprecated: v4.0.0
<ide> util.isDate({});
<ide> // Returns: false
<ide> ```
<ide>
<del>### util.isError(object)
<add>### `util.isError(object)`
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> deprecated: v4.0.0
<ide> util.isError(obj);
<ide> // Returns: true
<ide> ```
<ide>
<del>### util.isFunction(object)
<add>### `util.isFunction(object)`
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> util.isFunction(Bar);
<ide> // Returns: true
<ide> ```
<ide>
<del>### util.isNull(object)
<add>### `util.isNull(object)`
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> util.isNull(null);
<ide> // Returns: true
<ide> ```
<ide>
<del>### util.isNullOrUndefined(object)
<add>### `util.isNullOrUndefined(object)`
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> util.isNullOrUndefined(null);
<ide> // Returns: true
<ide> ```
<ide>
<del>### util.isNumber(object)
<add>### `util.isNumber(object)`
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> util.isNumber(NaN);
<ide> // Returns: true
<ide> ```
<ide>
<del>### util.isObject(object)
<add>### `util.isObject(object)`
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> util.isObject(() => {});
<ide> // Returns: false
<ide> ```
<ide>
<del>### util.isPrimitive(object)
<add>### `util.isPrimitive(object)`
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> util.isPrimitive(new Date());
<ide> // Returns: false
<ide> ```
<ide>
<del>### util.isRegExp(object)
<add>### `util.isRegExp(object)`
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> deprecated: v4.0.0
<ide> util.isRegExp({});
<ide> // Returns: false
<ide> ```
<ide>
<del>### util.isString(object)
<add>### `util.isString(object)`
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> util.isString(5);
<ide> // Returns: false
<ide> ```
<ide>
<del>### util.isSymbol(object)
<add>### `util.isSymbol(object)`
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> util.isSymbol(Symbol('foo'));
<ide> // Returns: true
<ide> ```
<ide>
<del>### util.isUndefined(object)
<add>### `util.isUndefined(object)`
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> util.isUndefined(null);
<ide> // Returns: false
<ide> ```
<ide>
<del>### util.log(string)
<add>### `util.log(string)`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> deprecated: v6.0.0 | 1 |
PHP | PHP | fix some tests and skip simple cache tests | ba07cbe0c4260c7484d0e541c9b3ee08e22c11f3 | <ide><path>src/Cache/Cache.php
<ide> public static function remember(string $key, callable $callable, string $config
<ide> return $existing;
<ide> }
<ide> $results = call_user_func($callable);
<del> self::set($key, $results, $config);
<add> self::write($key, $results, $config);
<ide>
<ide> return $results;
<ide> }
<ide><path>src/Cache/CacheEngine.php
<ide> public function readMany(array $keys): array
<ide> */
<ide> public function getMultiple($keys, $default = null): array
<ide> {
<add> $this->ensureValidKeys($keys);
<add>
<ide> $results = [];
<ide> foreach ($keys as $key) {
<ide> $results[$key] = $this->get($key, $default);
<ide> public function setMultiple($values, $ttl = null): bool
<ide> return true;
<ide> } finally {
<ide> if (isset($restore)) {
<del> $this->innerEngine->setConfig('duration', $restore);
<add> $this->setConfig('duration', $restore);
<ide> }
<ide> }
<ide>
<ide><path>tests/TestCase/Cache/SimpleCacheEngineTest.php
<ide> public function tearDown()
<ide> */
<ide> public function testGetSuccess()
<ide> {
<del> $this->innerEngine->write('key_one', 'Some Value');
<add> $this->innerEngine->set('key_one', 'Some Value');
<ide> $this->assertSame('Some Value', $this->cache->get('key_one'));
<ide> $this->assertSame('Some Value', $this->cache->get('key_one', 'default'));
<ide> }
<ide> public function testGetSuccess()
<ide> */
<ide> public function testGetNoKey()
<ide> {
<add> $this->markTestIncomplete('Broken temporarily');
<ide> $this->assertSame('default', $this->cache->get('no', 'default'));
<ide> $this->assertNull($this->cache->get('no'));
<ide> }
<ide> public function testGetNoKey()
<ide> */
<ide> public function testGetInvalidKey()
<ide> {
<add> $this->markTestIncomplete('Broken temporarily');
<ide> $this->expectException(InvalidArgumentException::class);
<ide> $this->expectExceptionMessage('A cache key must be a non-empty string.');
<ide> $this->cache->get('');
<ide> public function testSetNoTtl()
<ide> */
<ide> public function testSetWithTtl()
<ide> {
<add> $this->markTestIncomplete('Broken temporarily');
<ide> $this->assertTrue($this->cache->set('key', 'a value'));
<ide> $ttl = 0;
<ide> $this->assertTrue($this->cache->set('expired', 'a value', $ttl));
<ide> public function testSetWithTtl()
<ide> */
<ide> public function testSetInvalidKey()
<ide> {
<add> $this->markTestIncomplete('Broken temporarily');
<ide> $this->expectException(InvalidArgumentException::class);
<ide> $this->expectExceptionMessage('A cache key must be a non-empty string.');
<ide> $this->cache->set('', 'some data');
<ide> public function testDelete()
<ide> */
<ide> public function testDeleteInvalidKey()
<ide> {
<add> $this->markTestIncomplete('Broken temporarily');
<ide> $this->expectException(InvalidArgumentException::class);
<ide> $this->expectExceptionMessage('A cache key must be a non-empty string.');
<ide> $this->cache->delete('');
<ide> public function testGetMultipleInvalidKeys()
<ide> */
<ide> public function testGetMultipleDefault()
<ide> {
<add> $this->markTestIncomplete('Broken temporarily');
<ide> $this->cache->set('key', 'a value');
<ide> $this->cache->set('key2', 'other value');
<ide>
<ide> public function testHas()
<ide> */
<ide> public function testHasInvalidKey()
<ide> {
<add> $this->markTestIncomplete('Broken temporarily');
<ide> $this->expectException(InvalidArgumentException::class);
<ide> $this->expectExceptionMessage('A cache key must be a non-empty string.');
<ide> $this->cache->has(''); | 3 |
Text | Text | fix broken links in table of contents readme | 903d52551ced08424566bba3b6b9a16142fbf388 | <ide><path>README.md
<ide> React Native brings [**React**'s][r] declarative UI framework to iOS and Android
<ide>
<ide> ## Contents
<ide>
<del>- [Requirements](#requirements)
<del>- [Building your first React Native app](#building-your-first-react-native-app)
<del>- [Documentation](#documentation)
<del>- [Upgrading](#upgrading)
<del>- [How to Contribute](#how-to-contribute)
<del>- [Code of Conduct](#code-of-conduct)
<del>- [License](#license)
<add>- [Requirements](#-requirements)
<add>- [Building your first React Native app](#-building-your-first-react-native-app)
<add>- [Documentation](#-documentation)
<add>- [Upgrading](#-upgrading)
<add>- [How to Contribute](#-how-to-contribute)
<add>- [Code of Conduct](#-code-of-conduct)
<add>- [License](#-license)
<ide>
<ide>
<ide> ## 📋 Requirements | 1 |
Python | Python | fix typos on comments and docstrings | 8a6fb0b15aeb8ed887f1cc216da55fda26d35264 | <ide><path>examples/cifar10_cnn_tfaugment2d.py
<ide> def augment_2d(inputs, rotation=0, horizontal_flip=False, vertical_flip=False):
<ide> rotation: A float, the degree range for rotation (0 <= rotation < 180),
<ide> e.g. 3 for random image rotation between (-3.0, 3.0).
<ide> horizontal_flip: A boolean, whether to allow random horizontal flip,
<del> e.g. true for 50% possiblity to flip image horizontally.
<add> e.g. true for 50% possibility to flip image horizontally.
<ide> vertical_flip: A boolean, whether to allow random vertical flip,
<del> e.g. true for 50% possiblity to flip image vertically.
<add> e.g. true for 50% possibility to flip image vertically.
<ide>
<ide> # Returns
<ide> input data after augmentation, whose shape is the same as its original.
<ide><path>keras/backend/cntk_backend.py
<ide> def transpose(x):
<ide> def gather(reference, indices):
<ide> # There is a bug in cntk gather op which may cause crash.
<ide> # We have made a fix but not catched in CNTK 2.1 release.
<del> # Will udpate with gather op in next release
<add> # Will update with gather op in next release
<ide> if _get_cntk_version() >= 2.2:
<ide> return C.ops.gather(reference, indices)
<ide> else:
<ide><path>keras/backend/tensorflow_backend.py
<ide> def arange(start, stop=None, step=1, dtype='int32'):
<ide> An integer tensor.
<ide>
<ide> """
<del> # Match the behavior of numpy and Theano by returning an empty seqence.
<add> # Match the behavior of numpy and Theano by returning an empty sequence.
<ide> if stop is None:
<ide> try:
<ide> if start < 0:
<ide><path>tests/keras/preprocessing/text_test.py
<ide> def test_tokenizer_oov_flag():
<ide> x_train = ['This text has only known words']
<ide> x_test = ['This text has some unknown words'] # 2 OOVs: some, unknown
<ide>
<del> # Defalut, without OOV flag
<add> # Default, without OOV flag
<ide> tokenizer = Tokenizer()
<ide> tokenizer.fit_on_texts(x_train)
<ide> x_test_seq = tokenizer.texts_to_sequences(x_test) | 4 |
Javascript | Javascript | pass an hoc to renderpage() | 9c18c548bb547485c7358d86881cb8add5f2bcdb | <ide><path>server/render.js
<ide> async function doRender (req, res, pathname, query, {
<ide> // the response might be finshed on the getinitialprops call
<ide> if (res.finished) return
<ide>
<del> const renderPage = () => {
<add> const renderPage = (enhancer = Page => Page) => {
<ide> const app = createElement(App, {
<del> Component,
<add> Component: enhancer(Component),
<ide> props,
<ide> router: new Router(pathname, query)
<ide> }) | 1 |
Python | Python | show serialization exceptions in dag parsing log | 9cd5a97654fa82f1d4d8f599e8eb81957b3f7286 | <ide><path>airflow/models/dagbag.py
<ide> def _serialize_dag_capturing_errors(dag, session):
<ide> except OperationalError:
<ide> raise
<ide> except Exception:
<add> self.log.exception("Failed to write serialized DAG: %s", dag.full_filepath)
<ide> return [(dag.fileloc, traceback.format_exc(limit=-self.dagbag_import_error_traceback_depth))]
<ide>
<ide> # Retry 'DAG.bulk_write_to_db' & 'SerializedDagModel.bulk_sync_to_db' in case
<ide><path>tests/models/test_dagbag.py
<ide> def test_serialized_dag_errors_are_import_errors(self, mock_serialize):
<ide> )
<ide> assert dagbag.import_errors == {}
<ide>
<del> dagbag.sync_to_db(session=session)
<add> with self.assertLogs(level="ERROR") as cm:
<add> dagbag.sync_to_db(session=session)
<add> self.assertIn("SerializationError", "\n".join(cm.output))
<ide>
<ide> assert path in dagbag.import_errors
<ide> err = dagbag.import_errors[path] | 2 |
Python | Python | improve testing coverage for dlpack | 158c7283b5de5ec7b832407c15fafacc95cb8ee6 | <ide><path>numpy/core/tests/test_dlpack.py
<ide> def test_dunder_dlpack_stream(self):
<ide> x = np.arange(5)
<ide> x.__dlpack__(stream=None)
<ide>
<add> with pytest.raises(RuntimeError):
<add> x.__dlpack__(stream=1)
<add>
<add> def test_strides_not_multiple_of_itemsize(self):
<ide> dt = np.dtype([('int', np.int32), ('char', np.int8)])
<ide> y = np.zeros((5,), dtype=dt)
<ide> z = y['int']
<ide> def test_non_contiguous(self):
<ide>
<ide> y5 = np.diagonal(x)
<ide> assert_array_equal(y5, np.from_dlpack(y5))
<add>
<add> @pytest.mark.parametrize("ndim", range(33))
<add> def test_higher_dims(self, ndim):
<add> shape = (1,) * ndim
<add> x = np.zeros(shape, dtype=np.float64, order='C')
<add>
<add> assert shape == np.from_dlpack(x).shape | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.