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
Javascript
Javascript
prevent aborted event when already completed
f7a6971281d863e2b56682ff0f45eee7a7c4d3bb
<ide><path>test/parallel/test-http-client-spurious-aborted.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const http = require('http'); <add>const assert = require('assert'); <add>const fs = require('fs'); <add>const Countdown = require('../common/countdown'); <add> <add>function cleanup(fname) { <add> try { <add> if (fs.statSync(fname)) fs.unlinkSync(fname); <add> } catch (err) {} <add>} <add> <add>const N = 2; <add>const fname = '/dev/null'; <add>let abortRequest = true; <add> <add>const server = http.Server(common.mustCall((req, res) => { <add> const headers = { 'Content-Type': 'text/plain' }; <add> headers['Content-Length'] = 50; <add> const socket = res.socket; <add> res.writeHead(200, headers); <add> setTimeout(() => res.write('aaaaaaaaaa'), 100); <add> setTimeout(() => res.write('bbbbbbbbbb'), 200); <add> setTimeout(() => res.write('cccccccccc'), 300); <add> setTimeout(() => res.write('dddddddddd'), 400); <add> if (abortRequest) { <add> setTimeout(() => socket.destroy(), 600); <add> } else { <add> setTimeout(() => res.end('eeeeeeeeee'), 1000); <add> } <add>}, N)); <add> <add>server.listen(0, common.mustCall(() => { <add> cleanup(fname); <add> download(); <add>})); <add> <add>const finishCountdown = new Countdown(N, common.mustCall(() => { <add> server.close(); <add>})); <add>const reqCountdown = new Countdown(N, common.mustCall()); <add> <add>function download() { <add> const opts = { <add> port: server.address().port, <add> path: '/', <add> }; <add> const req = http.get(opts); <add> req.on('error', common.mustNotCall()); <add> req.on('response', (res) => { <add> assert.strictEqual(res.statusCode, 200); <add> assert.strictEqual(res.headers.connection, 'close'); <add> let aborted = false; <add> const fstream = fs.createWriteStream(fname); <add> res.pipe(fstream); <add> const _handle = res.socket._handle; <add> _handle._close = res.socket._handle.close; <add> _handle.close = function(callback) { <add> _handle._close(); <add> // set readable to true event though request is complete <add> if (res.complete) res.readable = true; <add> callback(); <add> }; <add> res.on('end', common.mustCall(() => { <add> reqCountdown.dec(); <add> })); <add> res.on('aborted', () => { <add> aborted = true; <add> }); <add> res.on('error', common.mustNotCall()); <add> fstream.on('finish', () => { <add> assert.strictEqual(aborted, abortRequest); <add> cleanup(fname); <add> finishCountdown.dec(); <add> if (finishCountdown.remaining === 0) return; <add> abortRequest = false; // next one should be a good response <add> download(); <add> }); <add> }); <add> req.end(); <add>}
1
Mixed
Javascript
remove problematic auto-linking of curl man pages
26e660f9627f776678106d0afa7da428c44c45cf
<ide><path>doc/api/repl.md <ide> For an example of running a "full-featured" (`terminal`) REPL over <ide> a `net.Server` and `net.Socket` instance, see: <ide> <https://gist.github.com/TooTallNate/2209310>. <ide> <del>For an example of running a REPL instance over [curl(1)][], see: <add>For an example of running a REPL instance over [`curl(1)`][], see: <ide> <https://gist.github.com/TooTallNate/2053342>. <ide> <ide> [ZSH]: https://en.wikipedia.org/wiki/Z_shell <ide> For an example of running a REPL instance over [curl(1)][], see: <ide> [`util.inspect()`]: util.html#util_util_inspect_object_options <ide> [`reverse-i-search`]: #repl_reverse_i_search <ide> [TTY keybindings]: readline.html#readline_tty_keybindings <del>[curl(1)]: https://curl.haxx.se/docs/manpage.html <add>[`curl(1)`]: https://curl.haxx.se/docs/manpage.html <ide> [stream]: stream.html <ide><path>tools/doc/html.js <ide> function preprocessText({ nodeVersion }) { <ide> <ide> // Syscalls which appear in the docs, but which only exist in BSD / macOS. <ide> const BSD_ONLY_SYSCALLS = new Set(['lchmod']); <del>const HAXX_ONLY_SYSCALLS = new Set(['curl']); <ide> const MAN_PAGE = /(^|\s)([a-z.]+)\((\d)([a-z]?)\)/gm; <ide> <ide> // Handle references to man pages, eg "open(2)" or "lchmod(2)". <ide> function linkManPages(text) { <ide> return `${beginning}<a href="https://www.freebsd.org/cgi/man.cgi` + <ide> `?query=${name}&sektion=${number}">${displayAs}</a>`; <ide> } <del> if (HAXX_ONLY_SYSCALLS.has(name)) { <del> return `${beginning}<a href="https://${name}.haxx.se/docs/manpage.html">${displayAs}</a>`; <del> } <ide> <ide> return `${beginning}<a href="http://man7.org/linux/man-pages/man${number}` + <ide> `/${name}.${number}${optionalCharacter}.html">${displayAs}</a>`;
2
Go
Go
use containerd/cgroups to detect cgroups v2
6458f750e18ad808331e3e6a81c56cc9abe87b91
<ide><path>cmd/dockerd/config_unix.go <ide> package main <ide> import ( <ide> "os/exec" <ide> <add> "github.com/containerd/cgroups" <ide> "github.com/docker/docker/daemon/config" <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/rootless" <ide> units "github.com/docker/go-units" <del> "github.com/opencontainers/runc/libcontainer/cgroups" <ide> "github.com/pkg/errors" <ide> "github.com/spf13/pflag" <ide> ) <ide> func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <ide> // Note that defaultUserlandProxyPath and honorXDG are configured according to the value of rootless.RunningWithRootlessKit, not the value of --rootless. <ide> flags.BoolVar(&conf.Rootless, "rootless", rootless.RunningWithRootlessKit(), "Enable rootless mode; typically used with RootlessKit") <ide> defaultCgroupNamespaceMode := "host" <del> if cgroups.IsCgroup2UnifiedMode() { <add> if cgroups.Mode() == cgroups.Unified { <ide> defaultCgroupNamespaceMode = "private" <ide> } <ide> flags.StringVar(&conf.CgroupNamespaceMode, "default-cgroupns-mode", defaultCgroupNamespaceMode, `Default mode for containers cgroup namespace ("host" | "private")`) <ide><path>daemon/daemon_unix.go <ide> import ( <ide> "strings" <ide> "time" <ide> <add> "github.com/containerd/cgroups" <ide> statsV1 "github.com/containerd/cgroups/stats/v1" <ide> statsV2 "github.com/containerd/cgroups/v2/stats" <ide> "github.com/containerd/containerd/sys" <ide> import ( <ide> "github.com/docker/libnetwork/options" <ide> lntypes "github.com/docker/libnetwork/types" <ide> "github.com/moby/sys/mount" <del> "github.com/opencontainers/runc/libcontainer/cgroups" <ide> specs "github.com/opencontainers/runtime-spec/specs-go" <ide> "github.com/opencontainers/selinux/go-selinux/label" <ide> "github.com/pkg/errors" <ide> func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConf <ide> if hostConfig.CgroupnsMode.IsEmpty() { <ide> // for cgroup v2: unshare cgroupns even for privileged containers <ide> // https://github.com/containers/libpod/pull/4374#issuecomment-549776387 <del> if hostConfig.Privileged && !cgroups.IsCgroup2UnifiedMode() { <add> if hostConfig.Privileged && cgroups.Mode() != cgroups.Unified { <ide> hostConfig.CgroupnsMode = containertypes.CgroupnsMode("host") <ide> } else { <ide> m := "host" <del> if cgroups.IsCgroup2UnifiedMode() { <add> if cgroups.Mode() == cgroups.Unified { <ide> m = "private" <ide> } <ide> if daemon.configStore != nil { <ide> func UsingSystemd(config *config.Config) bool { <ide> return true <ide> } <ide> // On cgroup v2 hosts, default to systemd driver <del> if getCD(config) == "" && cgroups.IsCgroup2UnifiedMode() && IsRunningSystemd() { <add> if getCD(config) == "" && cgroups.Mode() == cgroups.Unified && IsRunningSystemd() { <ide> return true <ide> } <ide> return false <ide> func verifyDaemonSettings(conf *config.Config) error { <ide> } <ide> } <ide> <del> if conf.Rootless && UsingSystemd(conf) && !cgroups.IsCgroup2UnifiedMode() { <add> if conf.Rootless && UsingSystemd(conf) && cgroups.Mode() != cgroups.Unified { <ide> return fmt.Errorf("exec-opt native.cgroupdriver=systemd requires cgroup v2 for rootless mode") <ide> } <ide> <ide><path>daemon/oci_linux.go <ide> import ( <ide> "strconv" <ide> "strings" <ide> <add> cdcgroups "github.com/containerd/cgroups" <ide> "github.com/containerd/containerd/containers" <ide> coci "github.com/containerd/containerd/oci" <ide> "github.com/containerd/containerd/sys" <ide> func WithRootless(daemon *Daemon) coci.SpecOpts { <ide> return func(_ context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error { <ide> var v2Controllers []string <ide> if daemon.getCgroupDriver() == cgroupSystemdDriver { <del> if !cgroups.IsCgroup2UnifiedMode() { <add> if cdcgroups.Mode() != cdcgroups.Unified { <ide> return errors.New("rootless systemd driver doesn't support cgroup v1") <ide> } <ide> rootlesskitParentEUID := os.Getenv("ROOTLESSKIT_PARENT_EUID") <ide> func WithCgroups(daemon *Daemon, c *container.Container) coci.SpecOpts { <ide> return nil <ide> } <ide> <del> if cgroups.IsCgroup2UnifiedMode() { <add> if cdcgroups.Mode() == cdcgroups.Unified { <ide> return errors.New("daemon-scoped cpu-rt-period and cpu-rt-runtime are not implemented for cgroup v2") <ide> } <ide> <ide><path>daemon/start_unix.go <ide> package daemon // import "github.com/docker/docker/daemon" <ide> <ide> import ( <add> "github.com/containerd/cgroups" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/errdefs" <del> "github.com/opencontainers/runc/libcontainer/cgroups" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> func (daemon *Daemon) getLibcontainerdCreateOptions(container *container.Contain <ide> rt.Shim = defaultV2ShimConfig(daemon.configStore, p) <ide> } <ide> if rt.Shim.Binary == linuxShimV1 { <del> if cgroups.IsCgroup2UnifiedMode() { <add> if cgroups.Mode() == cgroups.Unified { <ide> return "", nil, errdefs.InvalidParameter(errors.Errorf("runtime %q is not supported while cgroups v2 (unified hierarchy) is being used", container.HostConfig.Runtime)) <ide> } <ide> logrus.Warnf("Configured runtime %q is deprecated and will be removed in the next release", container.HostConfig.Runtime) <ide><path>pkg/sysinfo/sysinfo_linux.go <ide> import ( <ide> "strings" <ide> "sync" <ide> <add> cdcgroups "github.com/containerd/cgroups" <ide> "github.com/opencontainers/runc/libcontainer/cgroups" <ide> "github.com/sirupsen/logrus" <ide> "golang.org/x/sys/unix" <ide> func New(quiet bool, options ...Opt) *SysInfo { <ide> for _, o := range options { <ide> o(&opts) <ide> } <del> if cgroups.IsCgroup2UnifiedMode() { <add> if cdcgroups.Mode() == cdcgroups.Unified { <ide> return newV2(quiet, &opts) <ide> } <ide>
5
Python
Python
remove logging lines used for testing
55695f815521f1018a85b6db9dcedd439226fa44
<ide><path>airflow/jobs.py <ide> def manage_slas(self, dag, session=None): <ide> <ide> if slas: <ide> sla_dates = [sla.execution_date for sla in slas] <del> logging.info(len(sla_dates)) <ide> blocking_tis = ( <ide> session <ide> .query(TI) <ide> def manage_slas(self, dag, session=None): <ide> .filter(TI.dag_id == dag.dag_id) <ide> .all() <ide> ) <del> logging.info(len(blocking_tis)) <ide> for ti in blocking_tis: <ide> ti.task = dag.get_task(ti.task_id) <ide> blocking_tis = ([ti for ti in blocking_tis
1
Text
Text
change weird selector name
aeec7ff28444599d2079bcd1cce477305a986d93
<ide><path>docs/recipes/ComputingDerivedData.md <ide> In the example above, `visibilityFilterSelector` and `todosSelector` are input-s <ide> <ide> ### Composing Selectors <ide> <del>A memoized selector can itself be an input-selector to another memoized selector. Here is `visibleTodosSelector` being used as an input-selector to a selector that further filters the todos: <add>A memoized selector can itself be an input-selector to another memoized selector. Here is `visibleTodosSelector` being used as an input-selector to a selector that further filters the todos by keyword: <ide> <ide> ```js <del>const filterBySelector = (state) => state.filterBy; <add>const keywordSelector = (state) => state.keyword; <ide> <del>const mentionsReduxSelector = createSelector( <del> [visibleTodosSelector, filterBySelector], <del> (visibleTodos, filterBy) => visibleTodos.filter( <del> todo => todo.indexOf(filterBy) > -1 <add>const keywordFilterSelector = createSelector( <add> [visibleTodosSelector, keywordSelector], <add> (visibleTodos, keyword) => visibleTodos.filter( <add> todo => todo.indexOf(keyword) > -1 <ide> ) <ide> ); <ide> ```
1
PHP
PHP
set the class name if not already set
3571fdc6e16f8acbda1d80e63006075a8e42b9ec
<ide><path>src/ORM/Association.php <ide> public function __construct($alias, array $options = []) <ide> } <ide> } <ide> <add> if(!$this->_className) { <add> $this->_className = $alias; <add> } <add> <ide> list(,$name) = pluginSplit($alias); <ide> $this->_name = $name; <add> <ide> $this->_options($options); <ide> <ide> if (!empty($options['strategy'])) {
1
Python
Python
add tests for numpy.ctypeslib.as_array
1ec8f6d93ea150d79cfea6515ffe02f6d78753b2
<ide><path>numpy/tests/test_ctypeslib.py <ide> import pytest <ide> <ide> import numpy as np <del>from numpy.ctypeslib import ndpointer, load_library <add>from numpy.ctypeslib import ndpointer, load_library, as_array <ide> from numpy.distutils.misc_util import get_shared_lib_extension <del>from numpy.testing import assert_, assert_raises <add>from numpy.testing import assert_, assert_array_equal, assert_raises <ide> <ide> try: <ide> cdll = None <ide> def test_cache(self): <ide> a1 = ndpointer(dtype=np.float64) <ide> a2 = ndpointer(dtype=np.float64) <ide> assert_(a1 == a2) <add> <add>class TestAsArray(object): <add> @pytest.mark.skipif(not _HAS_CTYPE, <add> reason="ctypes not available on this python installation") <add> def test_array(self): <add> from ctypes import c_int <add> at = c_int * 2 <add> a = as_array(at(1, 2)) <add> assert_(a.shape == (2,)) <add> assert_array_equal(a, np.array([1, 2])) <add> a = as_array((at * 3)(at(1, 2), at(3, 4), at(5, 6))) <add> assert_(a.shape == (3, 2)) <add> assert_array_equal(a, np.array([[1, 2], [3, 4], [5, 6]])) <add> <add> @pytest.mark.skipif(not _HAS_CTYPE, <add> reason="ctypes not available on this python installation") <add> def test_pointer(self): <add> from ctypes import c_int, cast, POINTER <add> p = cast((c_int * 10)(*range(10)), POINTER(c_int)) <add> a = as_array(p, (10,)) <add> assert_(a.shape == (10,)) <add> assert_array_equal(a, np.array(range(10)))
1
Javascript
Javascript
add coverage for asyncresource constructor
52f358b5316a40b481a8298239ae1727e1d2bdaa
<ide><path>test/parallel/test-async-wrap-asyncresource-constructor.js <add>'use strict'; <add>require('../common'); <add> <add>// This tests that AsyncResource throws an error if bad parameters are passed <add> <add>const assert = require('assert'); <add>const AsyncResource = require('async_hooks').AsyncResource; <add> <add>assert.throws(() => { <add> return new AsyncResource(); <add>}, /^TypeError: type must be a string with length > 0$/); <add> <add>assert.throws(() => { <add> new AsyncResource(''); <add>}, /^TypeError: type must be a string with length > 0$/); <add> <add>assert.throws(() => { <add> new AsyncResource('type', -4); <add>}, /^RangeError: triggerId must be an unsigned integer$/); <add> <add>assert.throws(() => { <add> new AsyncResource('type', Math.PI); <add>}, /^RangeError: triggerId must be an unsigned integer$/);
1
Text
Text
train t5 in tensoflow 2 community notebook
a42f62d34f7b2acdb7298e586adbe9f0f28864ea
<ide><path>notebooks/README.md <ide> Pull Request so it can be included under the Community notebooks. <ide> <ide> ## Hugging Face's notebooks 🤗 <ide> <add> <ide> | Notebook | Description | | <ide> |:----------|:-------------|------:| <ide> | [Getting Started Tokenizers](https://github.com/huggingface/transformers/blob/master/notebooks/01-training-tokenizers.ipynb) | How to train and use your very own tokenizer |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/transformers/blob/master/notebooks/01-training-tokenizers.ipynb) | <ide> Pull Request so it can be included under the Community notebooks. <ide> <ide> | Notebook | Description | Author | | <ide> |:----------|:-------------|:-------------|------:| <add>| [Train T5 in Tensoflow 2 ](https://github.com/snapthat/TF-T5-text-to-text) | How to train T5 for any task using Tensorflow 2. This notebook demonstrates a Question & Answer task implemented in Tensorflow 2 using SQUAD | [Muhammad Harris](https://github.com/HarrisDePerceptron) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/snapthat/TF-T5-text-to-text/blob/master/snapthatT5/notebooks/TF-T5-Datasets%20Training.ipynb) | <ide> | [Train T5 on TPU](https://github.com/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb) | How to train T5 on SQUAD with Transformers and Nlp | [Suraj Patil](https://github.com/patil-suraj) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb#scrollTo=QLGiFCDqvuil) | <ide> | [Fine-tune T5 for Classification and Multiple Choice](https://github.com/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | How to fine-tune T5 for classification and multiple choice tasks using a text-to-text format with PyTorch Lightning | [Suraj Patil](https://github.com/patil-suraj) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | <ide> | [Fine-tune DialoGPT on New Datasets and Languages](https://github.com/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | How to fine-tune the DialoGPT model on a new dataset for open-dialog conversational chatbots | [Nathan Cooper](https://github.com/ncoop57) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) |
1
PHP
PHP
fix coding standards in cache/
04c843b17bffd5c0e6a55881491503578f0a8cd5
<ide><path>lib/Cake/Cache/Cache.php <ide> public static function settings($name = 'default') { <ide> } <ide> return array(); <ide> } <add> <ide> } <ide> <ide><path>lib/Cake/Cache/CacheEngine.php <ide> public function init($settings = array()) { <ide> * Permanently remove all expired and deleted data <ide> * @return void <ide> */ <del> public function gc() { } <add> public function gc() { <add> } <ide> <ide> /** <ide> * Write value for a key into cache <ide> public function key($key) { <ide> $key = Inflector::underscore(str_replace(array(DS, '/', '.'), '_', strval($key))); <ide> return $key; <ide> } <add> <ide> } <ide><path>lib/Cake/Cache/Engine/ApcEngine.php <ide> public function write($key, $value, $duration) { <ide> } else { <ide> $expires = time() + $duration; <ide> } <del> apc_store($key.'_expires', $expires, $duration); <add> apc_store($key . '_expires', $expires, $duration); <ide> return apc_store($key, $value, $duration); <ide> } <ide> <ide> public function write($key, $value, $duration) { <ide> */ <ide> public function read($key) { <ide> $time = time(); <del> $cachetime = intval(apc_fetch($key.'_expires')); <add> $cachetime = intval(apc_fetch($key . '_expires')); <ide> if ($cachetime !== 0 && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) { <ide> return false; <ide> } <ide><path>lib/Cake/Cache/Engine/FileEngine.php <ide> protected function _setKey($key, $createKey = false) { <ide> } <ide> unset($path); <ide> <del> if (!$exists && !chmod($this->_File->getPathname(), (int) $this->settings['mask'])) { <add> if (!$exists && !chmod($this->_File->getPathname(), (int)$this->settings['mask'])) { <ide> trigger_error(__d( <ide> 'cake_dev', 'Could not apply permission mask "%s" on cache file "%s"', <ide> array($this->_File->getPathname(), $this->settings['mask'])), E_USER_WARNING); <ide> protected function _active() { <ide> } <ide> return true; <ide> } <add> <ide> } <ide><path>lib/Cake/Cache/Engine/MemcacheEngine.php <ide> public function connect($host, $port = 11211) { <ide> } <ide> return true; <ide> } <add> <ide> } <ide><path>lib/Cake/Cache/Engine/XcacheEngine.php <ide> protected function _auth($reverse = false) { <ide> } <ide> } <ide> } <add> <ide> }
6
Text
Text
remove outdated note about read_only+default
bcf196d0ac14a1b6a8d28eda2e8c26711f717d99
<ide><path>docs/api-guide/validators.md <ide> If you want the date field to be visible, but not editable by the user, then set <ide> <ide> published = serializers.DateTimeField(read_only=True, default=timezone.now) <ide> <del>The field will not be writable to the user, but the default value will still be passed through to the `validated_data`. <del> <ide> #### Using with a hidden date field. <ide> <ide> If you want the date field to be entirely hidden from the user, then use `HiddenField`. This field type does not accept user input, but instead always returns its default value to the `validated_data` in the serializer.
1
Javascript
Javascript
fix externalmodule bug
94e47d572120274b16714aecaff4ada925388f33
<ide><path>lib/ExternalModule.js <ide> const Template = require("./Template"); <ide> const StaticExportsDependency = require("./dependencies/StaticExportsDependency"); <ide> const makeSerializable = require("./util/makeSerializable"); <ide> const propertyAccess = require("./util/propertyAccess"); <add>const extractUrlAndGlobal = require("./util/extractUrlAndGlobal"); <ide> <ide> /** @typedef {import("webpack-sources").Source} Source */ <ide> /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ <ide> const getSourceForImportExternal = (moduleAndSpecifiers, runtimeTemplate) => { <ide> */ <ide> const getSourceForScriptExternal = (urlAndGlobal, runtimeTemplate) => { <ide> if (typeof urlAndGlobal === "string") { <del> urlAndGlobal = urlAndGlobal.split("@").reverse(); <add> urlAndGlobal = extractUrlAndGlobal(urlAndGlobal); <ide> } <ide> const url = urlAndGlobal[0]; <ide> const globalName = urlAndGlobal[1]; <ide><path>lib/util/extractUrlAndGlobal.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add> Author Sam Chen @chenxsan <add>*/ <add> <add>"use strict"; <add> <add>/** <add> * @param {string} urlAndGlobal the script request <add> * @returns {string[]} script url and its global variable <add> */ <add>module.exports = function extractUrlAndGlobal(urlAndGlobal) { <add> const index = urlAndGlobal.indexOf("@"); <add> return [urlAndGlobal.substring(index + 1), urlAndGlobal.substring(0, index)]; <add>}; <ide><path>test/extractUrlAndGlobal.unittest.js <add>"use strict"; <add> <add>const extractUrlAndGlobal = require("../lib/util/extractUrlAndGlobal"); <add> <add>describe("extractUrlAndGlobal", () => { <add> it("should return jQuery", () => { <add> const result = extractUrlAndGlobal( <add> "jQuery@https://code.jquery.com/jquery-3.5.1.min.js" <add> ); <add> expect(result).toEqual([ <add> "https://code.jquery.com/jquery-3.5.1.min.js", <add> "jQuery" <add> ]); <add> }); <add> it("should return _", () => { <add> const result = extractUrlAndGlobal( <add> "_@https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js" <add> ); <add> expect(result).toEqual([ <add> "https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js", <add> "_" <add> ]); <add> }); <add>});
3
Mixed
Javascript
expose allowfileaccess property in webview
0c576ef84a1c7f79b228f205cc687ab1b945bda1
<ide><path>Libraries/Components/WebView/WebView.android.js <ide> class WebView extends React.Component { <ide> */ <ide> scalesPageToFit: PropTypes.bool, <ide> <add> /** <add> * Sets whether the webview allow access to file system. <add> * @platform android <add> */ <add> allowFileAccess: PropTypes.bool, <add> <ide> /** <ide> * Sets the user-agent for this WebView. The user-agent can also be set in native using <ide> * WebViewConfig. This prop will overwrite that config. <ide> class WebView extends React.Component { <ide> style={webViewStyles} <ide> source={resolveAssetSource(source)} <ide> scalesPageToFit={this.props.scalesPageToFit} <add> allowFileAccess={this.props.allowFileAccess} <ide> injectedJavaScript={this.props.injectedJavaScript} <ide> userAgent={this.props.userAgent} <ide> javaScriptEnabled={this.props.javaScriptEnabled} <ide><path>RNTester/js/WebViewExample.js <ide> exports.examples = [ <ide> backgroundColor: BGWASH, <ide> height: 100, <ide> }} <add> allowFileAccess={true} <ide> originWhitelist={FILE_SYSTEM_ORIGIN_WHITE_LIST} <ide> source={require('./helloworld.html')} <ide> scalesPageToFit={true} <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/webview/ReactWebViewManager.java <ide> package com.facebook.react.views.webview; <ide> <ide> import android.annotation.TargetApi; <del>import android.content.Context; <del>import com.facebook.react.uimanager.UIManagerModule; <del>import java.util.LinkedList; <del>import java.util.List; <del>import java.util.regex.Pattern; <del>import javax.annotation.Nullable; <del> <del>import java.io.UnsupportedEncodingException; <del>import java.net.URLEncoder; <del>import java.util.ArrayList; <del>import java.util.HashMap; <del>import java.util.Locale; <del>import java.util.Map; <del> <ide> import android.content.ActivityNotFoundException; <add>import android.content.Context; <ide> import android.content.Intent; <ide> import android.graphics.Bitmap; <ide> import android.graphics.Picture; <ide> import com.facebook.react.module.annotations.ReactModule; <ide> import com.facebook.react.uimanager.SimpleViewManager; <ide> import com.facebook.react.uimanager.ThemedReactContext; <add>import com.facebook.react.uimanager.UIManagerModule; <ide> import com.facebook.react.uimanager.annotations.ReactProp; <ide> import com.facebook.react.uimanager.events.ContentSizeChangeEvent; <ide> import com.facebook.react.uimanager.events.Event; <ide> import com.facebook.react.views.webview.events.TopLoadingStartEvent; <ide> import com.facebook.react.views.webview.events.TopMessageEvent; <ide> import java.io.UnsupportedEncodingException; <add>import java.net.URLEncoder; <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <add>import java.util.LinkedList; <add>import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Map; <add>import java.util.regex.Pattern; <ide> import javax.annotation.Nullable; <ide> import org.json.JSONException; <ide> import org.json.JSONObject; <ide> public void onPageStarted(WebView webView, String url, Bitmap favicon) { <ide> mLastLoadFailed = false; <ide> <ide> dispatchEvent( <del> webView, <del> new TopLoadingStartEvent( <del> webView.getId(), <del> createWebViewEvent(webView, url))); <add> webView, <add> new TopLoadingStartEvent( <add> webView.getId(), <add> createWebViewEvent(webView, url))); <ide> } <ide> <ide> @Override <ide> public boolean shouldOverrideUrlLoading(WebView view, String url) { <ide> // url blacklisting <ide> if (mUrlPrefixesForDefaultIntent != null && mUrlPrefixesForDefaultIntent.size() > 0) { <ide> ArrayList<Object> urlPrefixesForDefaultIntent = <del> mUrlPrefixesForDefaultIntent.toArrayList(); <add> mUrlPrefixesForDefaultIntent.toArrayList(); <ide> for (Object urlPrefix : urlPrefixesForDefaultIntent) { <ide> if (url.startsWith((String) urlPrefix)) { <ide> launchIntent(view.getContext(), url); <ide> private boolean shouldHandleURL(List<Pattern> originWhitelist, String url) { <ide> <ide> @Override <ide> public void onReceivedError( <del> WebView webView, <del> int errorCode, <del> String description, <del> String failingUrl) { <add> WebView webView, <add> int errorCode, <add> String description, <add> String failingUrl) { <ide> super.onReceivedError(webView, errorCode, description, failingUrl); <ide> mLastLoadFailed = true; <ide> <ide> public void onReceivedError( <ide> eventData.putString("description", description); <ide> <ide> dispatchEvent( <del> webView, <del> new TopLoadingErrorEvent(webView.getId(), eventData)); <add> webView, <add> new TopLoadingErrorEvent(webView.getId(), eventData)); <ide> } <ide> <ide> protected void emitFinishEvent(WebView webView, String url) { <ide> dispatchEvent( <del> webView, <del> new TopLoadingFinishEvent( <del> webView.getId(), <del> createWebViewEvent(webView, url))); <add> webView, <add> new TopLoadingFinishEvent( <add> webView.getId(), <add> createWebViewEvent(webView, url))); <ide> } <ide> <ide> protected WritableMap createWebViewEvent(WebView webView, String url) { <ide> protected void evaluateJavascriptWithFallback(String script) { <ide> <ide> public void callInjectedJavaScript() { <ide> if (getSettings().getJavaScriptEnabled() && <del> injectedJS != null && <del> !TextUtils.isEmpty(injectedJS)) { <add> injectedJS != null && <add> !TextUtils.isEmpty(injectedJS)) { <ide> evaluateJavascriptWithFallback("(function() {\n" + injectedJS + ";\n})();"); <ide> } <ide> } <ide> public void onReceiveValue(String value) { <ide> evaluateJavascriptWithFallback("(" + <ide> "window.originalPostMessage = window.postMessage," + <ide> "window.postMessage = function(data) {" + <del> BRIDGE_NAME + ".postMessage(String(data));" + <add> BRIDGE_NAME + ".postMessage(String(data));" + <ide> "}" + <del> ")"); <add> ")"); <ide> } <ide> } <ide> <ide> public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermiss <ide> <ide> // Fixes broken full-screen modals/galleries due to body height being 0. <ide> webView.setLayoutParams( <del> new LayoutParams(LayoutParams.MATCH_PARENT, <del> LayoutParams.MATCH_PARENT)); <add> new LayoutParams(LayoutParams.MATCH_PARENT, <add> LayoutParams.MATCH_PARENT)); <ide> <ide> setGeolocationEnabled(webView, false); <ide> if (ReactBuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { <ide> public void setSource(WebView view, @Nullable ReadableMap source) { <ide> String html = source.getString("html"); <ide> if (source.hasKey("baseUrl")) { <ide> view.loadDataWithBaseURL( <del> source.getString("baseUrl"), html, HTML_MIME_TYPE, HTML_ENCODING, null); <add> source.getString("baseUrl"), html, HTML_MIME_TYPE, HTML_ENCODING, null); <ide> } else { <ide> view.loadData(html, HTML_MIME_TYPE, HTML_ENCODING); <ide> } <ide> public void setMixedContentMode(WebView view, @Nullable String mixedContentMode) <ide> <ide> @ReactProp(name = "urlPrefixesForDefaultIntent") <ide> public void setUrlPrefixesForDefaultIntent( <del> WebView view, <del> @Nullable ReadableArray urlPrefixesForDefaultIntent) { <add> WebView view, <add> @Nullable ReadableArray urlPrefixesForDefaultIntent) { <ide> ReactWebViewClient client = ((ReactWebView) view).getReactWebViewClient(); <ide> if (client != null && urlPrefixesForDefaultIntent != null) { <ide> client.setUrlPrefixesForDefaultIntent(urlPrefixesForDefaultIntent); <ide> } <ide> } <ide> <add> @ReactProp(name = "allowFileAccess") <add> public void setAllowFileAccess( <add> WebView view, <add> @Nullable Boolean allowFileAccess) { <add> view.getSettings().setAllowFileAccess(allowFileAccess != null && allowFileAccess); <add> } <add> <ide> @ReactProp(name = "geolocationEnabled") <ide> public void setGeolocationEnabled( <ide> WebView view, <ide> protected void addEventEmitters(ThemedReactContext reactContext, WebView view) { <ide> @Override <ide> public @Nullable Map<String, Integer> getCommandsMap() { <ide> return MapBuilder.of( <del> "goBack", COMMAND_GO_BACK, <del> "goForward", COMMAND_GO_FORWARD, <del> "reload", COMMAND_RELOAD, <del> "stopLoading", COMMAND_STOP_LOADING, <del> "postMessage", COMMAND_POST_MESSAGE, <del> "injectJavaScript", COMMAND_INJECT_JAVASCRIPT <del> ); <add> "goBack", COMMAND_GO_BACK, <add> "goForward", COMMAND_GO_FORWARD, <add> "reload", COMMAND_RELOAD, <add> "stopLoading", COMMAND_STOP_LOADING, <add> "postMessage", COMMAND_POST_MESSAGE, <add> "injectJavaScript", COMMAND_INJECT_JAVASCRIPT <add> ); <ide> } <ide> <ide> @Override <ide> public void receiveCommand(WebView root, int commandId, @Nullable ReadableArray <ide> "var event;" + <ide> "var data = " + eventInitDict.toString() + ";" + <ide> "try {" + <del> "event = new MessageEvent('message', data);" + <add> "event = new MessageEvent('message', data);" + <ide> "} catch (e) {" + <del> "event = document.createEvent('MessageEvent');" + <del> "event.initMessageEvent('message', true, true, data.data, data.origin, data.lastEventId, data.source);" + <add> "event = document.createEvent('MessageEvent');" + <add> "event.initMessageEvent('message', true, true, data.data, data.origin, data.lastEventId, data.source);" + <ide> "}" + <ide> "document.dispatchEvent(event);" + <del> "})();"); <add> "})();"); <ide> } catch (JSONException e) { <ide> throw new RuntimeException(e); <ide> }
3
Text
Text
add changelog for v3.27.4
ea322a34a9e7b4654c009f27ce81582a96825daf
<ide><path>CHANGELOG.md <ide> <ide> - [#19472](https://github.com/emberjs/ember.js/pull/19472) [BUGFIX] Prevent transformation of block params called `attrs` <ide> <add>## v3.27.4 (June 9, 2021) <add> <add>- [#19594](https://github.com/emberjs/ember.js/pull/19594) [BUGFIX] Revert lazy hash changes <add>- [#19596](https://github.com/emberjs/ember.js/pull/19596) [DOC] Fix "Dormant" addon warning typo <add> <ide> ## v3.27.3 (June 3, 2021) <ide> <ide> - [#19565](https://github.com/emberjs/ember.js/pull/19565) [BUGFIX] Ensures that `computed` can depend on dynamic `(hash` keys <ide> - [#19571](https://github.com/emberjs/ember.js/pull/19571) [BUGFIX] Extend `Route.prototype.transitionTo` deprecation until 5.0.0 <del>- [#19586](https://github.com/emberjs/ember.js/pull/19586) [BUGFIX] Fix Embroider compatibility <add>- [#19586](https://github.com/emberjs/ember.js/pull/19586) [BUGFIX] Fix Embroider compatibility <ide> <ide> ### v3.27.2 (May 27, 2021) <ide>
1
Ruby
Ruby
remove unnecessary code
6cccc2d0fefe2474fb34e44c849ce0c0375c3a88
<ide><path>Library/Homebrew/test/test_integration_cmds.rb <ide> class Testball < Formula <ide> <ide> def test_desc <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> desc "Some test" <ide> url "https://example.com/testball-0.1.tar.gz" <ide> end <ide> EOS <del> formula_file.write content <ide> <ide> assert_equal "testball: Some test", cmd("desc", "testball") <ide> ensure <ide> class Testball < Formula <ide> def test_edit <ide> (HOMEBREW_REPOSITORY/".git").mkpath <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> url "https://example.com/testball-0.1.tar.gz" <ide> # something here <ide> end <ide> EOS <del> formula_file.write content <ide> <ide> assert_match "# something here", <ide> cmd("edit", "testball", {"HOMEBREW_EDITOR" => "/bin/cat"}) <ide> def test_sh <ide> <ide> def test_info <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> url "https://example.com/testball-0.1.tar.gz" <ide> end <ide> EOS <del> formula_file.write content <ide> <ide> assert_match "testball: stable 0.1", <ide> cmd("info", "testball") <ide> def test_tap_readme <ide> <ide> def test_unpack <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> url "file://#{File.expand_path("..", __FILE__)}/tarballs/testball-0.1.tbz" <ide> end <ide> EOS <del> formula_file.write content <ide> <ide> mktmpdir do |path| <ide> cmd "unpack", "testball", "--destdir=#{path}" <ide> class Testball < Formula <ide> <ide> def test_options <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> url "file://#{File.expand_path("..", __FILE__)}/tarballs/testball-0.1.tbz" <ide> option "with-foo", "foobar" <ide> depends_on "bar" => :recommended <ide> end <ide> EOS <del> formula_file.write content <ide> <ide> assert_equal "--with-foo\n\tfoobar\n--without-bar\n\tBuild without bar support", <ide> cmd_output("options", "testball").chomp <ide> class Testball < Formula <ide> <ide> def test_outdated <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> url "file://#{File.expand_path("..", __FILE__)}/tarballs/testball-0.1.tbz" <ide> end <ide> EOS <del> formula_file.write content <del> <ide> (HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath <ide> <ide> assert_equal "testball", cmd("outdated") <ide> class Testball < Formula <ide> <ide> def test_upgrade <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> url "file://#{File.expand_path("..", __FILE__)}/tarballs/testball-0.1.tbz" <ide> sha256 "#{TESTBALL_SHA256}" <ide> def install <ide> end <ide> end <ide> EOS <del> formula_file.write content <ide> <ide> (HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath <ide> <ide> def test_linkapps <ide> apps_dir.mkpath <ide> <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> url "https://example.com/testball-0.1.tar.gz" <ide> end <ide> EOS <del> formula_file.write content <ide> <ide> source_dir = HOMEBREW_CELLAR/"testball/0.1/TestBall.app" <ide> source_dir.mkpath <ide> def test_unlinkapps <ide> apps_dir.mkpath <ide> <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> url "https://example.com/testball-0.1.tar.gz" <ide> end <ide> EOS <del> formula_file.write content <ide> <ide> source_app = (HOMEBREW_CELLAR/"testball/0.1/TestBall.app") <ide> source_app.mkpath <ide> class Testball < Formula <ide> <ide> def test_pin_unpin <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> url "file://#{File.expand_path("..", __FILE__)}/tarballs/testball-0.1.tbz" <ide> sha256 "#{TESTBALL_SHA256}" <ide> def install <ide> end <ide> end <ide> EOS <del> formula_file.write content <del> <ide> (HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath <ide> <ide> cmd("pin", "testball") <ide> def install <ide> <ide> def test_reinstall <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> url "file://#{File.expand_path("..", __FILE__)}/tarballs/testball-0.1.tbz" <ide> sha256 "#{TESTBALL_SHA256}" <ide> def install <ide> end <ide> end <ide> EOS <del> formula_file.write content <ide> <ide> cmd("install", "testball", "--with-foo") <ide> foo_dir = HOMEBREW_CELLAR/"testball/0.1/foo" <ide> def test_create <ide> <ide> def test_fetch <ide> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <del> content = <<-EOS.undent <add> formula_file.write <<-EOS.undent <ide> class Testball < Formula <ide> url "file://#{File.expand_path("..", __FILE__)}/tarballs/testball-0.1.tbz" <ide> sha256 "#{TESTBALL_SHA256}" <ide> end <ide> EOS <del> formula_file.write content <ide> <ide> cmd("fetch", "testball") <ide> assert (HOMEBREW_CACHE/"testball-0.1.tbz").exist?,
1
Javascript
Javascript
add node.assert for internal debugging
7e7deed5106489f0ff2f8314c33311c0c75e7a45
<ide><path>src/util.js <ide> node.inherits = function (ctor, superCtor) { <ide> ctor.prototype.constructor = ctor; <ide> }; <ide> <add>node.assert = function (x) { <add> if (!(x)) throw (msg || "assertion error"); <add>}; <add> <ide> // This is useful for dealing with raw encodings. <ide> node.encodeUtf8 = function (array) { <ide> var string = "";
1
Javascript
Javascript
ignore error/warning when module does not exists
0a3b0c63d47b5e1ffe76f9e836f7cb96028ad68e
<ide><path>lib/IgnoreErrorModuleFactory.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add> Author Ivan Kopeykin @vankop <add>*/ <add> <add>"use strict"; <add> <add>const ModuleFactory = require("./ModuleFactory"); <add> <add>/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ <add>/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ <add>/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ <add> <add>/** <add> * Ignores error when module is unresolved <add> */ <add>class IgnoreErrorModuleFactory extends ModuleFactory { <add> /** <add> * @param {NormalModuleFactory} normalModuleFactory normalModuleFactory instance <add> */ <add> constructor(normalModuleFactory) { <add> super(); <add> <add> this.normalModuleFactory = normalModuleFactory; <add> } <add> <add> /** <add> * @param {ModuleFactoryCreateData} data data object <add> * @param {function(Error=, ModuleFactoryResult=): void} callback callback <add> * @returns {void} <add> */ <add> create(data, callback) { <add> this.normalModuleFactory.create(data, (err, result) => { <add> return callback(null, result); <add> }); <add> } <add>} <add> <add>module.exports = IgnoreErrorModuleFactory; <ide><path>lib/WebpackIsIncludedPlugin.js <ide> <ide> "use strict"; <ide> <add>const IgnoreErrorModuleFactory = require("./IgnoreErrorModuleFactory"); <ide> const WebpackIsIncludedDependency = require("./dependencies/WebpackIsIncludedDependency"); <ide> const { <ide> toConstantDependency <ide> class WebpackIsIncludedPlugin { <ide> (compilation, { normalModuleFactory }) => { <ide> compilation.dependencyFactories.set( <ide> WebpackIsIncludedDependency, <del> normalModuleFactory <add> new IgnoreErrorModuleFactory(normalModuleFactory) <ide> ); <ide> compilation.dependencyTemplates.set( <ide> WebpackIsIncludedDependency, <ide><path>test/cases/parsing/webpack-is-included/index.js <ide> import "./module1"; <ide> import { <ide> isWebpackIncludedFunction, <ide> used, <del> unused <add> unused, <add> notPresented <ide> } from "./module2"; <ide> <ide> it("__webpack_is_included__ should be a function", () => { <ide> it("__webpack_is_included__ should be true for bundled modules, otherwise false" <ide> expect(used).toBe(true); <ide> expect(unused).toBe(false); <ide> }); <add> <add>it("__webpack_is_included__ should return false for missing module", () => { <add> expect(notPresented).toBe(false); <add>}); <ide><path>test/cases/parsing/webpack-is-included/module2.js <ide> export const isWebpackIncludedFunction = typeof __webpack_is_included__ === "function"; <ide> export const unused = __webpack_is_included__("./moduleUnused"); <ide> export const used = __webpack_is_included__("./module" + "Used"); <add>export const notPresented = __webpack_is_included__("./anyOtherModule");
4
Go
Go
correct all the formate to formatter
b8155bd5bead29bf116aeea9159563e1a6409c41
<ide><path>cli/command/formatter/disk_usage.go <ide> const ( <ide> uniqueSizeHeader = "UNIQUE SiZE" <ide> ) <ide> <del>// DiskUsageContext contains disk usage specific information required by the formater, encapsulate a Context struct. <add>// DiskUsageContext contains disk usage specific information required by the formatter, encapsulate a Context struct. <ide> type DiskUsageContext struct { <ide> Context <ide> Verbose bool <ide><path>cli/command/formatter/image.go <ide> const ( <ide> digestHeader = "DIGEST" <ide> ) <ide> <del>// ImageContext contains image specific information required by the formater, encapsulate a Context struct. <add>// ImageContext contains image specific information required by the formatter, encapsulate a Context struct. <ide> type ImageContext struct { <ide> Context <ide> Digest bool
2
Javascript
Javascript
update old jquery versions for tests
e0c16f6db5c13a72215e98a0a6f426bab5ee959b
<ide><path>bin/run-tests.js <ide> function generateBuiltTests() { <ide> <ide> function generateOldJQueryTests() { <ide> testFunctions.push(function() { <del> return run('jquery=1.8.3&nolint=true'); <add> return run('jquery=1.10.2&nolint=true'); <ide> }); <ide> testFunctions.push(function() { <del> return run('jquery=1.10.2&nolint=true'); <add> return run('jquery=1.12.4&nolint=true'); <ide> }); <ide> testFunctions.push(function() { <ide> return run('jquery=2.2.4&nolint=true');
1
Go
Go
add regression tests for client debug flag
9f315dd328a33b51133a41067a508a8b59166a39
<ide><path>api/client/info.go <ide> import ( <ide> Cli "github.com/docker/docker/cli" <ide> "github.com/docker/docker/pkg/ioutils" <ide> flag "github.com/docker/docker/pkg/mflag" <add> "github.com/docker/docker/utils" <ide> "github.com/docker/go-units" <ide> ) <ide> <ide> func (cli *DockerCli) CmdInfo(args ...string) error { <ide> ioutils.FprintfIfNotEmpty(cli.out, "Name: %s\n", info.Name) <ide> ioutils.FprintfIfNotEmpty(cli.out, "ID: %s\n", info.ID) <ide> <add> fmt.Fprintf(cli.out, "Debug mode (client): %v\n", utils.IsDebugEnabled()) <add> fmt.Fprintf(cli.out, "Debug mode (server): %v\n", info.Debug) <add> <ide> if info.Debug { <del> fmt.Fprintf(cli.out, "Debug mode (server): %v\n", info.Debug) <ide> fmt.Fprintf(cli.out, " File Descriptors: %d\n", info.NFd) <ide> fmt.Fprintf(cli.out, " Goroutines: %d\n", info.NGoroutines) <ide> fmt.Fprintf(cli.out, " System Time: %s\n", info.SystemTime) <ide><path>docker/client_test.go <add>package main <add> <add>import ( <add> "os" <add> "testing" <add> <add> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/utils" <add>) <add> <add>func TestClientDebugEnabled(t *testing.T) { <add> defer utils.DisableDebug() <add> <add> clientFlags.Common.FlagSet.Parse([]string{"-D"}) <add> clientFlags.PostParse() <add> <add> if os.Getenv("DEBUG") != "1" { <add> t.Fatal("expected debug enabled, got false") <add> } <add> if logrus.GetLevel() != logrus.DebugLevel { <add> t.Fatalf("expected logrus debug level, got %v", logrus.GetLevel()) <add> } <add>} <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *check.C) { <ide> newD.Stop() <ide> c.Assert(b.String(), check.Not(checker.Contains), infoLog) <ide> } <add> <add>func (s *DockerDaemonSuite) TestDaemonDebugLog(c *check.C) { <add> testRequires(c, DaemonIsLinux) <add> newD := NewDaemon(c) <add> <add> debugLog := "\x1b[37mDEBU\x1b" <add> <add> p, tty, err := pty.Open() <add> c.Assert(err, checker.IsNil) <add> defer func() { <add> tty.Close() <add> p.Close() <add> }() <add> <add> b := bytes.NewBuffer(nil) <add> go io.Copy(b, p) <add> <add> newD.StartWithLogFile(tty, "--debug") <add> newD.Stop() <add> c.Assert(b.String(), checker.Contains, debugLog) <add>} <ide><path>integration-cli/docker_cli_info_test.go <ide> func (s *DockerSuite) TestInfoDisplaysStoppedContainers(c *check.C) { <ide> c.Assert(out, checker.Contains, fmt.Sprintf(" Paused: %d\n", 0)) <ide> c.Assert(out, checker.Contains, fmt.Sprintf(" Stopped: %d\n", 1)) <ide> } <add> <add>func (s *DockerSuite) TestInfoDebug(c *check.C) { <add> testRequires(c, SameHostDaemon, DaemonIsLinux) <add> <add> d := NewDaemon(c) <add> err := d.Start("--debug") <add> c.Assert(err, checker.IsNil) <add> defer d.Stop() <add> <add> out, err := d.Cmd("--debug", "info") <add> c.Assert(err, checker.IsNil) <add> c.Assert(out, checker.Contains, "Debug mode (client): true\n") <add> c.Assert(out, checker.Contains, "Debug mode (server): true\n") <add> c.Assert(out, checker.Contains, "File Descriptors") <add> c.Assert(out, checker.Contains, "Goroutines") <add> c.Assert(out, checker.Contains, "System Time") <add> c.Assert(out, checker.Contains, "EventsListeners") <add> c.Assert(out, checker.Contains, "Docker Root Dir") <add>} <ide><path>utils/debug_test.go <add>package utils <add> <add>import ( <add> "os" <add> "testing" <add> <add> "github.com/Sirupsen/logrus" <add>) <add> <add>func TestEnableDebug(t *testing.T) { <add> defer func() { <add> os.Setenv("DEBUG", "") <add> logrus.SetLevel(logrus.InfoLevel) <add> }() <add> EnableDebug() <add> if os.Getenv("DEBUG") != "1" { <add> t.Fatalf("expected DEBUG=1, got %s\n", os.Getenv("DEBUG")) <add> } <add> if logrus.GetLevel() != logrus.DebugLevel { <add> t.Fatalf("expected log level %v, got %v\n", logrus.DebugLevel, logrus.GetLevel()) <add> } <add>} <add> <add>func TestDisableDebug(t *testing.T) { <add> DisableDebug() <add> if os.Getenv("DEBUG") != "" { <add> t.Fatalf("expected DEBUG=\"\", got %s\n", os.Getenv("DEBUG")) <add> } <add> if logrus.GetLevel() != logrus.InfoLevel { <add> t.Fatalf("expected log level %v, got %v\n", logrus.InfoLevel, logrus.GetLevel()) <add> } <add>} <add> <add>func TestDebugEnabled(t *testing.T) { <add> EnableDebug() <add> if !IsDebugEnabled() { <add> t.Fatal("expected debug enabled, got false") <add> } <add> DisableDebug() <add> if IsDebugEnabled() { <add> t.Fatal("expected debug disabled, got true") <add> } <add>}
5
Python
Python
add new tests for array coercion
f253a7e39204142e3cf82d6beeef1ce22f5500cd
<ide><path>numpy/core/tests/test_array_coercion.py <add>""" <add>Tests for array coercion, mainly through testing `np.array` results directly. <add>Note that other such tests exist e.g. in `test_api.py` and many corner-cases <add>are tested (sometimes indirectly) elsewhere. <add>""" <add> <add>import pytest <add>from pytest import param <add> <add>from itertools import product <add> <add>import numpy as np <add>from numpy.core._rational_tests import rational <add> <add>from numpy.testing import ( <add> assert_array_equal, assert_warns, IS_PYPY) <add> <add> <add>def arraylikes(): <add> """ <add> Generator for functions converting an array into various array-likes. <add> If full is True (default) includes array-likes not capable of handling <add> all dtypes <add> """ <add> # base array: <add> def ndarray(a): <add> return a <add> <add> yield param(ndarray, id="ndarray") <add> <add> # subclass: <add> class MyArr(np.ndarray): <add> pass <add> <add> def subclass(a): <add> return a.view(MyArr) <add> <add> yield subclass <add> <add> # Array-interface <add> class ArrayDunder: <add> def __init__(self, a): <add> self.a = a <add> <add> def __array__(self, dtype=None): <add> return self.a <add> <add> yield param(ArrayDunder, id="__array__") <add> <add> # memory-view <add> yield param(memoryview, id="memoryview") <add> <add> # Array-interface <add> class ArrayInterface: <add> def __init__(self, a): <add> self.a = a # need to hold on to keep interface valid <add> self.__array_interface__ = a.__array_interface__ <add> <add> yield param(ArrayInterface, id="__array_interface__") <add> <add> # Array-Struct <add> class ArrayStruct: <add> def __init__(self, a): <add> self.a = a # need to hold on to keep struct valid <add> self.__array_struct__ = a.__array_struct__ <add> <add> yield param(ArrayStruct, id="__array_struct__") <add> <add> <add>def scalar_instances(times=True, extended_precision=True, user_dtype=True): <add> # Hard-coded list of scalar instances. <add> # Floats: <add> yield param(np.sqrt(np.float16(5)), id="float16") <add> yield param(np.sqrt(np.float32(5)), id="float32") <add> yield param(np.sqrt(np.float64(5)), id="float64") <add> if extended_precision: <add> yield param(np.sqrt(np.longdouble(5)), id="longdouble") <add> <add> # Complex: <add> yield param(np.sqrt(np.complex64(2+3j)), id="complex64") <add> yield param(np.sqrt(np.complex128(2+3j)), id="complex128") <add> if extended_precision: <add> yield param(np.sqrt(np.longcomplex(2+3j)), id="clongdouble") <add> <add> # Bool: <add> # XFAIL: Bool should be added, but has some bad properties when it <add> # comes to strings, see also gh-9875 <add> # yield param(np.bool_(0), id="bool") <add> <add> # Integers: <add> yield param(np.int8(2), id="int8") <add> yield param(np.int16(2), id="int16") <add> yield param(np.int32(2), id="int32") <add> yield param(np.int64(2), id="int64") <add> <add> yield param(np.uint8(2), id="uint8") <add> yield param(np.uint16(2), id="uint16") <add> yield param(np.uint32(2), id="uint32") <add> yield param(np.uint64(2), id="uint64") <add> <add> # Rational: <add> if user_dtype: <add> yield param(rational(1, 2), id="rational") <add> <add> # Cannot create a structured void scalar directly: <add> structured = np.array([(1, 3)], "i,i")[0] <add> assert isinstance(structured, np.void) <add> assert structured.dtype == np.dtype("i,i") <add> yield param(structured, id="structured") <add> <add> if times: <add> # Datetimes and timedelta <add> yield param(np.timedelta64(2), id="timedelta64[generic]") <add> yield param(np.timedelta64(23, "s"), id="timedelta64[s]") <add> yield param(np.timedelta64("NaT", "s"), id="timedelta64[s](NaT)") <add> <add> yield param(np.datetime64("NaT"), id="datetime64[generic](NaT)") <add> yield param(np.datetime64("2020-06-07 12:43", "ms"), id="datetime64[ms]") <add> <add> # Strings and unstructured void: <add> yield param(np.bytes_(b"1234"), id="bytes") <add> yield param(np.unicode_("2345"), id="unicode") <add> yield param(np.void(b"4321"), id="unstructured_void") <add> <add> <add>def is_parametric_dtype(dtype): <add> """Returns True if the the dtype is a parametric legacy dtype (itemsize <add> is 0, or a datetime without units) <add> """ <add> if dtype.itemsize == 0: <add> return True <add> if issubclass(dtype.type, (np.datetime64, np.timedelta64)): <add> if dtype.name.endswith("64"): <add> # Generic time units <add> return True <add> return False <add> <add> <add>class TestStringDiscovery: <add> @pytest.mark.parametrize("obj", <add> [object(), 1.2, 10**43, None, "string"], <add> ids=["object", "1.2", "10**43", "None", "string"]) <add> def test_basic_stringlength(self, obj): <add> if not isinstance(obj, (str, int)): <add> pytest.xfail( <add> "The Single object (first assert) uses a different branch " <add> "and thus gives a different result (either wrong or longer" <add> "string than normally discovered).") <add> <add> length = len(str(obj)) <add> expected = np.dtype(f"S{length}") <add> <add> assert np.array(obj, dtype="S").dtype == expected <add> assert np.array([obj], dtype="S").dtype == expected <add> <add> # A nested array is also discovered correctly <add> arr = np.array(obj, dtype="O") <add> assert np.array(arr, dtype="S").dtype == expected <add> <add> @pytest.mark.xfail(reason="Only single array unpacking is supported") <add> @pytest.mark.parametrize("obj", <add> [object(), 1.2, 10**43, None, "string"], <add> ids=["object", "1.2", "10**43", "None", "string"]) <add> def test_nested_arrays_stringlength(self, obj): <add> length = len(str(obj)) <add> expected = np.dtype(f"S{length}") <add> arr = np.array(obj, dtype="O") <add> assert np.array([arr, arr], dtype="S").dtype == expected <add> <add> @pytest.mark.xfail(reason="Only single array unpacking is supported") <add> @pytest.mark.parametrize("arraylike", arraylikes()) <add> def test_unpack_first_level(self, arraylike): <add> # We unpack exactly one level of array likes <add> obj = np.array([None]) <add> obj[0] = np.array(1.2) <add> # the length of the included item, not of the float dtype <add> length = len(str(obj[0])) <add> expected = np.dtype(f"S{length}") <add> <add> obj = arraylike(obj) <add> # casting to string usually calls str(obj) <add> arr = np.array([obj], dtype="S") <add> assert arr.shape == (1, 1) <add> assert arr.dtype == expected <add> <add> <add>class TestScalarDiscovery: <add> def test_void_special_case(self): <add> # Void dtypes with structures discover tuples as elements <add> arr = np.array((1, 2, 3), dtype="i,i,i") <add> assert arr.shape == () <add> arr = np.array([(1, 2, 3)], dtype="i,i,i") <add> assert arr.shape == (1,) <add> <add> def test_char_special_case(self): <add> arr = np.array("string", dtype="c") <add> assert arr.shape == (6,) <add> assert arr.dtype.char == "c" <add> arr = np.array(["string"], dtype="c") <add> assert arr.shape == (1, 6) <add> assert arr.dtype.char == "c" <add> <add> def test_char_special_case_deep(self): <add> # Check that the character special case errors correctly if the <add> # array is too deep: <add> nested = ["string"] # 2 dimensions (due to string being sequence) <add> for i in range(np.MAXDIMS - 2): <add> nested = [nested] <add> <add> arr = np.array(nested, dtype='c') <add> assert arr.shape == (1,) * (np.MAXDIMS - 1) + (6,) <add> with pytest.raises(ValueError): <add> np.array([nested], dtype="c") <add> <add> def test_unknown_object(self): <add> arr = np.array(object()) <add> assert arr.shape == () <add> assert arr.dtype == np.dtype("O") <add> <add> @pytest.mark.parametrize("scalar", scalar_instances()) <add> def test_scalar(self, scalar): <add> arr = np.array(scalar) <add> assert arr.shape == () <add> assert arr.dtype == scalar.dtype <add> <add> if type(scalar) is np.bytes_: <add> pytest.xfail("Nested bytes use len(str(scalar)) currently.") <add> <add> arr = np.array([[scalar, scalar]]) <add> assert arr.shape == (1, 2) <add> assert arr.dtype == scalar.dtype <add> <add> # Additionally to string this test also runs into a corner case <add> # with datetime promotion (the difference is the promotion order). <add> @pytest.mark.xfail(reason="Coercion to string is not symmetric") <add> def test_scalar_promotion(self): <add> for sc1, sc2 in product(scalar_instances(), scalar_instances()): <add> sc1, sc2 = sc1.values[0], sc2.values[0] <add> # test all combinations: <add> arr = np.array([sc1, sc2]) <add> assert arr.shape == (2,) <add> try: <add> dt1, dt2 = sc1.dtype, sc2.dtype <add> expected_dtype = np.promote_types(dt1, dt2) <add> assert arr.dtype == expected_dtype <add> except TypeError as e: <add> # Will currently always go to object dtype <add> assert arr.dtype == np.dtype("O") <add> <add> @pytest.mark.parametrize("scalar", scalar_instances()) <add> def test_scalar_coercion(self, scalar): <add> # This tests various scalar coercion paths, mainly for the numerical <add> # types. It includes some paths not directly related to `np.array` <add> if isinstance(scalar, np.inexact): <add> # Ensure we have a full-precision number if available <add> scalar = type(scalar)((scalar * 2)**0.5) <add> <add> if is_parametric_dtype(scalar.dtype) or type(scalar) is rational: <add> # datetime with unit will be named "datetime64[unit]" <add> # Rational generally fails due to a missing cast. In the future <add> # object casts should automatically be defined based on `setitem`. <add> pytest.xfail("0-D object array to a unit-less datetime cast fails") <add> <add> # Use casting from object: <add> arr = np.array(scalar, dtype=object).astype(scalar.dtype) <add> <add> # Test various ways to create an array containing this scalar: <add> arr1 = np.array(scalar).reshape(1) <add> arr2 = np.array([scalar]) <add> arr3 = np.empty(1, dtype=scalar.dtype) <add> arr3[0] = scalar <add> arr4 = np.empty(1, dtype=scalar.dtype) <add> arr4[:] = [scalar] <add> # All of these methods should yield the same results <add> assert_array_equal(arr, arr1) <add> assert_array_equal(arr, arr2) <add> assert_array_equal(arr, arr3) <add> assert_array_equal(arr, arr4) <add> <add> @pytest.mark.xfail(IS_PYPY, reason="`int(np.complex128(3))` fails on PyPy") <add> @pytest.mark.filterwarnings("ignore::numpy.ComplexWarning") <add> # After change, can enable times here, and below and it will work, <add> # Right now times are too complex, so map out some details below. <add> @pytest.mark.parametrize("cast_to", scalar_instances(times=False)) <add> def test_scalar_coercion_same_as_cast_and_assignment(self, cast_to): <add> """ <add> Test that in most cases: <add> * `np.array(scalar, dtype=dtype)` <add> * `np.empty((), dtype=dtype)[()] = scalar` <add> * `np.array(scalar).astype(dtype)` <add> should behave the same. The only exceptions are paramteric dtypes <add> (mainly datetime/timedelta without unit) and void without fields. <add> """ <add> dtype = cast_to.dtype # use to parametrize only the target dtype <add> <add> # XFAIL: Some extended precision tests fail, because assigning to <add> # complex256 will use float(float128). Rational fails currently. <add> for scalar in scalar_instances( <add> times=False, extended_precision=False, user_dtype=False): <add> scalar = scalar.values[0] <add> <add> if dtype.type == np.void: <add> if scalar.dtype.fields is not None and dtype.fields is None: <add> # Here, coercion to "V6" works, but the cast fails. <add> # Since the types are identical, SETITEM takes care of <add> # this, but has different rules than the cast. <add> with pytest.raises(TypeError): <add> np.array(scalar).astype(dtype) <add> # XFAIL: np.array(scalar, dtype=dtype) <add> np.array([scalar], dtype=dtype) <add> continue <add> <add> # The main test, we first try to use casting and if it succeeds <add> # continue below testing that things are the same, otherwise <add> # test that the alternative paths at least also fail. <add> try: <add> cast = np.array(scalar).astype(dtype) <add> except (TypeError, ValueError, RuntimeError): <add> # coercion should also raise (error type may change) <add> with pytest.raises(Exception): <add> np.array(scalar, dtype=dtype) <add> # assignment should also raise <add> res = np.zeros((), dtype=dtype) <add> with pytest.raises(Exception): <add> res[()] = scalar <add> <add> return <add> <add> # Non error path: <add> arr = np.array(scalar, dtype=dtype) <add> assert_array_equal(arr, cast) <add> # assignment behaves the same <add> ass = np.zeros((), dtype=dtype) <add> ass[()] = scalar <add> assert_array_equal(ass, cast) <add> <add> <add>class TestTimeScalars: <add> @pytest.mark.parametrize("dtype", [np.int64, np.float32]) <add> @pytest.mark.parametrize("scalar", <add> [param(np.timedelta64("NaT", "s"), id="timedelta64[s](NaT)"), <add> param(np.timedelta64(123, "s"), id="timedelta64[s]"), <add> param(np.datetime64("NaT", "generic"), id="datetime64[generic](NaT)"), <add> param(np.datetime64(1, "D"), id="datetime64[D]")],) <add> @pytest.mark.xfail( <add> reason="This uses int(scalar) or float(scalar) to assign, which " <add> "fails. However, casting currently does not fail.") <add> def test_coercion_basic(self, dtype, scalar): <add> arr = np.array(scalar, dtype=dtype) <add> cast = np.array(scalar).astype(dtype) <add> ass = np.ones((), dtype=dtype) <add> ass[()] = scalar # raises, as would np.array([scalar], dtype=dtype) <add> <add> assert_array_equal(arr, cast) <add> assert_array_equal(cast, cast) <add> <add> @pytest.mark.parametrize("dtype", [np.int64, np.float32]) <add> @pytest.mark.parametrize("scalar", <add> [param(np.timedelta64(123, "ns"), id="timedelta64[ns]"), <add> param(np.timedelta64(12, "generic"), id="timedelta64[generic]")]) <add> def test_coercion_timedelta_convert_to_number(self, dtype, scalar): <add> # Only "ns" and "generic" timedeltas can be converted to numbers <add> # so these are slightly special. <add> arr = np.array(scalar, dtype=dtype) <add> cast = np.array(scalar).astype(dtype) <add> ass = np.ones((), dtype=dtype) <add> ass[()] = scalar # raises, as would np.array([scalar], dtype=dtype) <add> <add> assert_array_equal(arr, cast) <add> assert_array_equal(cast, cast) <add> <add> @pytest.mark.parametrize(["val", "unit"], <add> [param(123, "s", id="[s]"), param(123, "D", id="[D]")]) <add> @pytest.mark.parametrize("scalar_type", [np.datetime64, np.timedelta64]) <add> @pytest.mark.xfail(reason="Error not raised for assignment") <add> def test_coercion_assignment_times(self, scalar_type, val, unit): <add> scalar = scalar_type(val, unit) <add> <add> # The error type is not ideal, fails because string is too short: <add> with pytest.raises(RuntimeError): <add> np.array(scalar, dtype="S6") <add> with pytest.raises(RuntimeError): <add> cast = np.array(scalar).astype("S6") <add> ass = np.ones((), dtype="S6") <add> with pytest.raises(RuntimeError): <add> ass[()] = scalar <add> <add> <add>class TestNested: <add> @pytest.mark.xfail(reason="No deprecation warning given.") <add> def test_nested_simple(self): <add> initial = [1.2] <add> nested = initial <add> for i in range(np.MAXDIMS - 1): <add> nested = [nested] <add> <add> arr = np.array(nested, dtype="float64") <add> assert arr.shape == (1,) * np.MAXDIMS <add> with pytest.raises(ValueError): <add> np.array([nested], dtype="float64") <add> <add> # We discover object automatically at this time: <add> with assert_warns(np.VisibleDeprecationWarning): <add> arr = np.array([nested]) <add> assert arr.dtype == np.dtype("O") <add> assert arr.shape == (1,) * np.MAXDIMS <add> assert arr.item() is initial <add> <add> def test_pathological_self_containing(self): <add> # Test that this also works for two nested sequences <add> l = [] <add> l.append(l) <add> arr = np.array([l, l, l], dtype=object) <add> assert arr.shape == (3,) + (1,) * (np.MAXDIMS - 1) <add> <add> # Also check a ragged case: <add> arr = np.array([l, [None], l], dtype=object) <add> assert arr.shape == (3, 1) <add> <add> @pytest.mark.xfail( <add> reason="For arrays and memoryview, this used to not complain " <add> "and assign to a too small array instead. For other " <add> "array-likes the error is different because fewer (only " <add> "MAXDIM-1) dimensions are found, failing the last test.") <add> @pytest.mark.parametrize("arraylike", arraylikes()) <add> def test_nested_arraylikes(self, arraylike): <add> # We try storing an array like into an array, but the array-like <add> # will have too many dimensions. This means the shape discovery <add> # decides that the array-like must be treated as an object (a special <add> # case of ragged discovery). The result will be an array with one <add> # dimension less than the maximum dimensions, and the array being <add> # assigned to it (which does work for object or if `float(arraylike)` <add> # works). <add> initial = arraylike(np.ones((1, 1))) <add> #if not isinstance(initial, (np.ndarray, memoryview)): <add> # pytest.xfail( <add> # "When coercing to object, these cases currently discover " <add> # "fewer dimensions than ndarray failing the second part.") <add> <add> nested = initial <add> for i in range(np.MAXDIMS - 1): <add> nested = [nested] <add> <add> with pytest.raises(ValueError): <add> # It will refuse to assign the array into <add> np.array(nested, dtype="float64") <add> <add> # If this is object, we end up assigning a (1, 1) array into (1,) <add> # (due to running out of dimensions), this is currently supported but <add> # a special case which is not ideal. <add> arr = np.array(nested, dtype=object) <add> assert arr.shape == (1,) * np.MAXDIMS <add> assert arr.item() == np.array(initial).item() <add> <add> @pytest.mark.parametrize("arraylike", arraylikes()) <add> def test_uneven_depth_ragged(self, arraylike): <add> arr = np.arange(4).reshape((2, 2)) <add> arr = arraylike(arr) <add> <add> # Array is ragged in the second dimension already: <add> out = np.array([arr, [arr]], dtype=object) <add> assert out.shape == (2,) <add> assert out[0] is arr <add> assert type(out[1]) is list <add> <add> if not isinstance(arr, (np.ndarray, memoryview)): <add> pytest.xfail( <add> "does not raise ValueError below, because it discovers " <add> "the dimension as (2,) and not (2, 2, 2)") <add> <add> # Array is ragged in the third dimension: <add> with pytest.raises(ValueError): <add> # This is a broadcast error during assignment, because <add> # the array shape would be (2, 2, 2) but `arr[0, 0] = arr` fails. <add> np.array([arr, [arr, arr]], dtype=object) <add> <add> def test_empty_sequence(self): <add> arr = np.array([[], [1], [[1]]], dtype=object) <add> assert arr.shape == (3,) <add> <add> # The empty sequence stops further dimension discovery, so the <add> # result shape will be (0,) which leads to an error during: <add> with pytest.raises(ValueError): <add> np.array([[], np.empty((0, 1))], dtype=object) <add> <add> <add>class TestBadSequences: <add> # These are tests for bad objects passed into `np.array`, in general <add> # these have undefined behaviour. In the old code they partially worked <add> # when now they will fail. We could (and maybe should) create a copy <add> # of all sequences to be safe against bad-actors. <add> <add> def test_growing_list(self): <add> # List to coerce, `mylist` will append to it during coercion <add> obj = [] <add> class mylist(list): <add> def __len__(self): <add> obj.append([1, 2]) <add> return super().__len__() <add> <add> obj.append(mylist([1, 2])) <add> <add> with pytest.raises(ValueError): # changes to RuntimeError <add> np.array(obj) <add> <add> # Note: We do not test a shrinking list. These do very evil things <add> # and the only way to fix them would be to copy all sequences. <add> # (which may be a real option in the future). <add> <add> def test_mutated_list(self): <add> # List to coerce, `mylist` will mutate the first element <add> obj = [] <add> class mylist(list): <add> def __len__(self): <add> obj[0] = [2, 3] # replace with a different list. <add> return super().__len__() <add> <add> obj.append([2, 3]) <add> obj.append(mylist([1, 2])) <add> #with pytest.raises(RuntimeError): # Will error in the future <add> np.array(obj) <add> <add> def test_replace_0d_array(self): <add> # List to coerce, `mylist` will mutate the first element <add> obj = [] <add> class baditem: <add> def __len__(self): <add> obj[0][0] = 2 # replace with a different list. <add> raise ValueError("not actually a sequence!") <add> <add> def __getitem__(self): <add> pass <add> <add> # Runs into a corner case in the new code, the `array(2)` is cached <add> # so replacing it invalidates the cache. <add> obj.append([np.array(2), baditem()]) <add> # with pytest.raises(RuntimeError): # Will error in the future <add> np.array(obj) <add> <add> <add>class TestArrayLikes: <add> @pytest.mark.parametrize("arraylike", arraylikes()) <add> def test_0d_object_special_case(self, arraylike): <add> arr = np.array(0.) <add> obj = arraylike(arr) <add> # A single array-like is always converted: <add> res = np.array(obj, dtype=object) <add> assert_array_equal(arr, res) <add> <add> # But a single 0-D nested array-like never: <add> res = np.array([obj], dtype=object) <add> assert res[0] is obj <add> <add> def test_0d_generic_special_case(self): <add> class ArraySubclass(np.ndarray): <add> def __float__(self): <add> raise TypeError("e.g. quantities raise on this") <add> <add> arr = np.array(0.) <add> obj = arr.view(ArraySubclass) <add> res = np.array(obj) <add> # The subclass is simply cast: <add> assert_array_equal(arr, res) <add> <add> # If the 0-D array-like is included, __float__ is currently <add> # guaranteed to be used. We may want to change that, quantities <add> # and masked arrays half make use of this. <add> with pytest.raises(TypeError): <add> np.array([obj]) <add> <add> # The same holds for memoryview: <add> obj = memoryview(arr) <add> res = np.array(obj) <add> assert_array_equal(arr, res) <add> with pytest.raises(ValueError): <add> # The error type does not matter much here. <add> np.array([obj]) <ide><path>numpy/core/tests/test_indexing.py <ide> def __array_finalize__(self, old): <ide> a[...] = s <ide> assert_((a == 1).all()) <ide> <add> def test_array_like_values(self): <add> # Similar to the above test, but use a memoryview instead <add> a = np.zeros((5, 5)) <add> s = np.arange(25, dtype=np.float64).reshape(5, 5) <add> <add> a[[0, 1, 2, 3, 4], :] = memoryview(s) <add> assert_array_equal(a, s) <add> <add> a[:, [0, 1, 2, 3, 4]] = memoryview(s) <add> assert_array_equal(a, s) <add> <add> a[...] = memoryview(s) <add> assert_array_equal(a, s) <add> <ide> def test_subclass_writeable(self): <ide> d = np.rec.array([('NGC1001', 11), ('NGC1002', 1.), ('NGC1003', 1.)], <ide> dtype=[('target', 'S20'), ('V_mag', '>f4')]) <ide><path>numpy/testing/_private/utils.py <ide> def func_assert_same_pos(x, y, func=isnan, hasval='nan'): <ide> at the same locations. <ide> <ide> """ <add> __tracebackhide__ = True # Hide traceback for py.test <add> <ide> x_id = func(x) <ide> y_id = func(y) <ide> # We include work-arounds here to handle three types of slightly
3
Text
Text
add 2.7.1 to the changelog.md
1568459714bbe54d03b6711ea7d3501e08758300
<ide><path>CHANGELOG.md <ide> - [#13855](https://github.com/emberjs/ember.js/pull/13855) [FEATURE ember-runtime-enumerable-includes] Enable by default. <ide> - [#13855](https://github.com/emberjs/ember.js/pull/13855) [FEATURE ember-testing-check-waiters] Enable by default. <ide> <add>### 2.7.1 (August 15, 2016) <add> <add>- [#13920](https://github.com/emberjs/ember.js/pull/13920) [BUGFIX] Add more info to the `Ember.Binding` deprecation. <add>- [#14058](https://github.com/emberjs/ember.js/pull/14058) [BUGFIX] Fix issues related to `Ember.Router.map` changes in 2.7.0. <add>- [#14068](https://github.com/emberjs/ember.js/pull/14068) [BUGFIX] Prevent errors when clicking a `{{link-to}}` during an existing transition. <add> <ide> ### 2.7.0 (July 25, 2016) <ide> <ide> - [#13764](https://github.com/emberjs/ember.js/pull/13764) [BUGFIX] Keep rest positional parameters when nesting contextual components if needed.
1
Ruby
Ruby
memoize calculated ip without additional variable
43aa2d308c27f387f2ea3051170769bb60b99015
<ide><path>actionpack/lib/action_dispatch/middleware/remote_ip.rb <ide> class GetIp <ide> }x <ide> <ide> def initialize(env, middleware) <del> @env = env <del> @middleware = middleware <del> @calculated_ip = false <add> @env = env <add> @middleware = middleware <add> @ip = nil <ide> end <ide> <ide> # Determines originating IP address. REMOTE_ADDR is the standard <ide> def calculate_ip <ide> end <ide> <ide> def to_s <del> return @ip if @calculated_ip <del> @calculated_ip = true <del> @ip = calculate_ip <add> @ip ||= calculate_ip <ide> end <ide> <ide> private
1
Text
Text
improve grammar a bit
507e522e26b4073455b2337bcf1670e52bba5429
<ide><path>guides/source/working_with_javascript.md <ide> $(document).ready -> <ide> <ide> We call this 'unobtrusive' JavaScript because we're no longer mixing our <ide> JavaScript into our HTML. We've properly separated our concerns, making future <del>change easy. We can easily add behavior to any link by adding the data <add>changes easier. We can easily add behavior to any link by adding the data <ide> attribute. We can run all of our JavaScript through a minimizer and <ide> concatenator. We can serve our entire JavaScript bundle on every page, which <ide> means that it'll get downloaded on the first page load and then be cached on
1
Javascript
Javascript
fix assertion order
3f7755b24c234eeeb592f484c504b4b85a8f9fb8
<ide><path>test/parallel/test-https-client-get-url.js <ide> const options = { <ide> }; <ide> <ide> const server = https.createServer(options, common.mustCall((req, res) => { <del> assert.strictEqual('GET', req.method); <del> assert.strictEqual('/foo?bar', req.url); <add> assert.strictEqual(req.method, 'GET'); <add> assert.strictEqual(req.url, '/foo?bar'); <ide> res.writeHead(200, { 'Content-Type': 'text/plain' }); <ide> res.write('hello\n'); <ide> res.end();
1
Text
Text
update readme.md file in /templates/variables
25d9fbeccf3af7f7d29fc871fc5ff1219a7f3b96
<ide><path>airflow/www/templates/airflow/variables/README.md <ide> ## Variable Editor <ide> ---- <ide> This folder contains forms used to edit values in the "Variable" key-value <del>store. This data can be edited under the "Browse" admin tab, but sometimes <add>store. This data can be edited under the "Admin" admin tab, but sometimes <ide> it is preferable to use a form that can perform checking and provide a nicer <ide> interface. <ide>
1
Javascript
Javascript
remove uneeded code
9bcf4f46fd67872d25a7c31ce056ed90dc281b21
<ide><path>editor/js/Viewport.js <ide> var Viewport = function ( editor ) { <ide> }; <ide> <ide> var sceneCameraDisplay = new UI.Row(); <del> sceneCameraDisplay.setId( 'cameraSelect' ); <del> sceneCameraDisplay.dom.setAttribute( 'layout', config.getKey( 'project/renderer/sceneCameras' ) || 'topLeft' ); <del> sceneCameraDisplay.setDisplay( 'none' ); <add> sceneCameraDisplay.setId( 'cameraSelect' ).setDisplay( 'none' ); <ide> document.body.appendChild( sceneCameraDisplay.dom ); <ide> <ide> var cameraSelect = new UI.Select().onChange( render );
1
Javascript
Javascript
remove unnecessary use of array.from
61b228d8a056a14bf79dacdafd305e736d3ac92b
<ide><path>spec/project-spec.js <ide> /* <ide> * decaffeinate suggestions: <del> * DS101: Remove unnecessary use of Array.from <ide> * DS102: Remove unnecessary code created because of implicit returns <ide> * DS103: Rewrite code to no longer use __guard__ <ide> * DS201: Simplify complex destructure assignments <ide> describe('Project', function () { <ide> ) <ide> <ide> describe('before and after saving a buffer', function () { <del> let [buffer] = Array.from([]) <add> let buffer <ide> beforeEach(() => <ide> waitsForPromise(() => <ide> atom.project.bufferForPath(path.join(__dirname, 'fixtures', 'sample.js')).then(function (o) { <ide> describe('Project', function () { <ide> }) <ide> <ide> describe('when a custom repository-provider service is provided', function () { <del> let [fakeRepositoryProvider, fakeRepository] = Array.from([]) <add> let fakeRepositoryProvider, fakeRepository <ide> <ide> beforeEach(function () { <ide> fakeRepository = {destroy () { return null }} <ide> describe('Project', function () { <ide> }) <ide> <ide> describe('.open(path)', function () { <del> let [absolutePath, newBufferHandler] = Array.from([]) <add> let absolutePath, newBufferHandler <ide> <ide> beforeEach(function () { <ide> absolutePath = require.resolve('./fixtures/dir/a') <ide> describe('Project', function () { <ide> Promise.all([ <ide> atom.project.bufferForPath('c'), <ide> atom.project.bufferForPath('c') <del> ]).then(function (...args) { <del> const [buffer1, buffer2] = Array.from(args[0]) <add> ]).then(function ([buffer1, buffer2]) { <ide> return expect(buffer1).toBe(buffer2) <ide> }) <ide> ) <ide> describe('Project', function () { <ide> <ide> atom.project.setPaths([directory1, directory2, directory3]) <ide> <del> const [repo1, repo2, repo3] = Array.from(atom.project.getRepositories()) <add> const [repo1, repo2, repo3] = atom.project.getRepositories() <ide> expect(repo1).toBeNull() <ide> expect(repo2.getShortHead()).toBe('master') <ide> expect(repo2.getPath()).toBe(fs.realpathSync(path.join(directory2, '.git'))) <ide> describe('Project', function () { <ide> const onDidChangePathsSpy = jasmine.createSpy('onDidChangePaths spy') <ide> atom.project.onDidChangePaths(onDidChangePathsSpy) <ide> <del> const [oldPath] = Array.from(atom.project.getPaths()) <add> const [oldPath] = atom.project.getPaths() <ide> <ide> const newPath = temp.mkdirSync('dir') <ide> atom.project.addPath(newPath) <ide> describe('Project', function () { <ide> it("doesn't add redundant paths", function () { <ide> const onDidChangePathsSpy = jasmine.createSpy('onDidChangePaths spy') <ide> atom.project.onDidChangePaths(onDidChangePathsSpy) <del> const [oldPath] = Array.from(atom.project.getPaths()) <add> const [oldPath] = atom.project.getPaths() <ide> <ide> // Doesn't re-add an existing root directory <ide> atom.project.addPath(oldPath) <ide> describe('Project', function () { <ide> <ide> beforeEach(() => <ide> sub = atom.project.onDidChangeFiles(function (incoming) { <del> events.push(...Array.from(incoming || [])) <add> events.push(...incoming || []) <ide> return checkCallback() <ide> }) <ide> ) <ide> describe('Project', function () { <ide> <ide> const expire = function () { <ide> checkCallback = function () {} <del> console.error('Paths not seen:', Array.from(remaining)) <add> console.error('Paths not seen:', remaining) <ide> return reject(new Error('Expired before all expected events were delivered.')) <ide> } <ide>
1
Go
Go
use spf13/cobra for docker logs
4f4b59cc435fbfef236017f3aa36145c1187426b
<ide><path>api/client/commands.go <ide> func (cli *DockerCli) Command(name string) func(...string) error { <ide> "load": cli.CmdLoad, <ide> "login": cli.CmdLogin, <ide> "logout": cli.CmdLogout, <del> "logs": cli.CmdLogs, <ide> "network": cli.CmdNetwork, <ide> "network create": cli.CmdNetworkCreate, <ide> "network connect": cli.CmdNetworkConnect, <ide><path>api/client/container/logs.go <add>package container <add> <add>import ( <add> "fmt" <add> "io" <add> <add> "golang.org/x/net/context" <add> <add> "github.com/docker/docker/api/client" <add> "github.com/docker/docker/cli" <add> "github.com/docker/docker/pkg/stdcopy" <add> "github.com/docker/engine-api/types" <add> "github.com/spf13/cobra" <add>) <add> <add>var validDrivers = map[string]bool{ <add> "json-file": true, <add> "journald": true, <add>} <add> <add>type logsOptions struct { <add> follow bool <add> since string <add> timestamps bool <add> details bool <add> tail string <add> <add> container string <add>} <add> <add>// NewLogsCommand creats a new cobra.Command for `docker logs` <add>func NewLogsCommand(dockerCli *client.DockerCli) *cobra.Command { <add> var opts logsOptions <add> <add> cmd := &cobra.Command{ <add> Use: "logs [OPTIONS] CONTAINER", <add> Short: "Fetch the logs of a container", <add> Args: cli.ExactArgs(1), <add> RunE: func(cmd *cobra.Command, args []string) error { <add> opts.container = args[0] <add> return runLogs(dockerCli, &opts) <add> }, <add> } <add> cmd.SetFlagErrorFunc(flagErrorFunc) <add> <add> flags := cmd.Flags() <add> flags.BoolVarP(&opts.follow, "follow", "f", false, "Follow log output") <add> flags.StringVar(&opts.since, "since", "", "Show logs since timestamp") <add> flags.BoolVarP(&opts.timestamps, "timestamps", "t", false, "Show timestamps") <add> flags.BoolVar(&opts.details, "details", false, "Show extra details provided to logs") <add> flags.StringVar(&opts.tail, "tail", "all", "Number of lines to show from the end of the logs") <add> return cmd <add>} <add> <add>func runLogs(dockerCli *client.DockerCli, opts *logsOptions) error { <add> ctx := context.Background() <add> <add> c, err := dockerCli.Client().ContainerInspect(ctx, opts.container) <add> if err != nil { <add> return err <add> } <add> <add> if !validDrivers[c.HostConfig.LogConfig.Type] { <add> return fmt.Errorf("\"logs\" command is supported only for \"json-file\" and \"journald\" logging drivers (got: %s)", c.HostConfig.LogConfig.Type) <add> } <add> <add> options := types.ContainerLogsOptions{ <add> ShowStdout: true, <add> ShowStderr: true, <add> Since: opts.since, <add> Timestamps: opts.timestamps, <add> Follow: opts.follow, <add> Tail: opts.tail, <add> Details: opts.details, <add> } <add> responseBody, err := dockerCli.Client().ContainerLogs(ctx, opts.container, options) <add> if err != nil { <add> return err <add> } <add> defer responseBody.Close() <add> <add> if c.Config.Tty { <add> _, err = io.Copy(dockerCli.Out(), responseBody) <add> } else { <add> _, err = stdcopy.StdCopy(dockerCli.Out(), dockerCli.Err(), responseBody) <add> } <add> return err <add>} <ide><path>api/client/logs.go <del>package client <del> <del>import ( <del> "fmt" <del> "io" <del> <del> "golang.org/x/net/context" <del> <del> Cli "github.com/docker/docker/cli" <del> flag "github.com/docker/docker/pkg/mflag" <del> "github.com/docker/docker/pkg/stdcopy" <del> "github.com/docker/engine-api/types" <del>) <del> <del>var validDrivers = map[string]bool{ <del> "json-file": true, <del> "journald": true, <del>} <del> <del>// CmdLogs fetches the logs of a given container. <del>// <del>// docker logs [OPTIONS] CONTAINER <del>func (cli *DockerCli) CmdLogs(args ...string) error { <del> cmd := Cli.Subcmd("logs", []string{"CONTAINER"}, Cli.DockerCommands["logs"].Description, true) <del> follow := cmd.Bool([]string{"f", "-follow"}, false, "Follow log output") <del> since := cmd.String([]string{"-since"}, "", "Show logs since timestamp") <del> times := cmd.Bool([]string{"t", "-timestamps"}, false, "Show timestamps") <del> details := cmd.Bool([]string{"-details"}, false, "Show extra details provided to logs") <del> tail := cmd.String([]string{"-tail"}, "all", "Number of lines to show from the end of the logs") <del> cmd.Require(flag.Exact, 1) <del> <del> cmd.ParseFlags(args, true) <del> <del> name := cmd.Arg(0) <del> <del> ctx := context.Background() <del> <del> c, err := cli.client.ContainerInspect(ctx, name) <del> if err != nil { <del> return err <del> } <del> <del> if !validDrivers[c.HostConfig.LogConfig.Type] { <del> return fmt.Errorf("\"logs\" command is supported only for \"json-file\" and \"journald\" logging drivers (got: %s)", c.HostConfig.LogConfig.Type) <del> } <del> <del> options := types.ContainerLogsOptions{ <del> ShowStdout: true, <del> ShowStderr: true, <del> Since: *since, <del> Timestamps: *times, <del> Follow: *follow, <del> Tail: *tail, <del> Details: *details, <del> } <del> responseBody, err := cli.client.ContainerLogs(ctx, name, options) <del> if err != nil { <del> return err <del> } <del> defer responseBody.Close() <del> <del> if c.Config.Tty { <del> _, err = io.Copy(cli.out, responseBody) <del> } else { <del> _, err = stdcopy.StdCopy(cli.out, cli.err, responseBody) <del> } <del> return err <del>} <ide><path>cli/cobraadaptor/adaptor.go <ide> func NewCobraAdaptor(clientFlags *cliflags.ClientFlags) CobraAdaptor { <ide> rootCmd.AddCommand( <ide> container.NewCreateCommand(dockerCli), <ide> container.NewExportCommand(dockerCli), <add> container.NewLogsCommand(dockerCli), <ide> container.NewRunCommand(dockerCli), <ide> container.NewStopCommand(dockerCli), <ide> image.NewRemoveCommand(dockerCli), <ide><path>cli/usage.go <ide> var DockerCommandUsage = []Command{ <ide> {"load", "Load an image from a tar archive or STDIN"}, <ide> {"login", "Log in to a Docker registry"}, <ide> {"logout", "Log out from a Docker registry"}, <del> {"logs", "Fetch the logs of a container"}, <ide> {"network", "Manage Docker networks"}, <ide> {"pause", "Pause all processes within a container"}, <ide> {"port", "List port mappings or a specific mapping for the CONTAINER"},
5
Python
Python
replace deprecated functions
7fb8b0f24d841096dd9e1225c71c2ab658a09b17
<ide><path>im2txt/im2txt/ops/image_processing.py <ide> def process_image(encoded_image, <ide> # only logged in thread 0. <ide> def image_summary(name, image): <ide> if not thread_id: <del> tf.image_summary(name, tf.expand_dims(image, 0)) <add> tf.summary.image(name, tf.expand_dims(image, 0)) <ide> <ide> # Decode image into a float32 Tensor of shape [?, ?, 3] with values in [0, 1). <ide> with tf.name_scope("decode", values=[encoded_image]): <ide><path>im2txt/im2txt/ops/inputs.py <ide> def prefetch_input_data(reader, <ide> enqueue_ops.append(values_queue.enqueue([value])) <ide> tf.train.queue_runner.add_queue_runner(tf.train.queue_runner.QueueRunner( <ide> values_queue, enqueue_ops)) <del> tf.scalar_summary( <add> tf.summary.scalar( <ide> "queue/%s/fraction_of_%d_full" % (values_queue.name, capacity), <ide> tf.cast(values_queue.size(), tf.float32) * (1. / capacity)) <ide> <ide> def batch_with_dynamic_pad(images_and_captions, <ide> <ide> if add_summaries: <ide> lengths = tf.add(tf.reduce_sum(mask, 1), 1) <del> tf.scalar_summary("caption_length/batch_min", tf.reduce_min(lengths)) <del> tf.scalar_summary("caption_length/batch_max", tf.reduce_max(lengths)) <del> tf.scalar_summary("caption_length/batch_mean", tf.reduce_mean(lengths)) <add> tf.summary.scalar("caption_length/batch_min", tf.reduce_min(lengths)) <add> tf.summary.scalar("caption_length/batch_max", tf.reduce_max(lengths)) <add> tf.summary.scalar("caption_length/batch_mean", tf.reduce_mean(lengths)) <ide> <ide> return images, input_seqs, target_seqs, mask <ide><path>im2txt/im2txt/show_and_tell_model.py <ide> def build_model(self): <ide> batch_loss = tf.div(tf.reduce_sum(tf.mul(losses, weights)), <ide> tf.reduce_sum(weights), <ide> name="batch_loss") <del> tf.contrib.losses.add_loss(batch_loss) <del> total_loss = tf.contrib.losses.get_total_loss() <add> tf.losses.add_loss(batch_loss) <add> total_loss = tf.losses.get_total_loss() <ide> <ide> # Add summaries. <del> tf.scalar_summary("batch_loss", batch_loss) <del> tf.scalar_summary("total_loss", total_loss) <add> tf.summary.scalar("losses/batch_loss", batch_loss) <add> tf.summary.scalar("losses/total_loss", total_loss) <ide> for var in tf.trainable_variables(): <del> tf.histogram_summary(var.op.name, var) <add> tf.summary.histogram("parameters/" + var.op.name, var) <ide> <ide> self.total_loss = total_loss <ide> self.target_cross_entropy_losses = losses # Used in evaluation. <ide><path>im2txt/im2txt/show_and_tell_model_test.py <ide> def setUp(self): <ide> def _countModelParameters(self): <ide> """Counts the number of parameters in the model at top level scope.""" <ide> counter = {} <del> for v in tf.all_variables(): <add> for v in tf.global_variables(): <ide> name = v.op.name.split("/")[0] <ide> num_params = v.get_shape().num_elements() <ide> assert num_params <ide> def _checkOutputs(self, expected_shapes, feed_dict=None): <ide> fetches = expected_shapes.keys() <ide> <ide> with self.test_session() as sess: <del> sess.run(tf.initialize_all_variables()) <add> sess.run(tf.global_variables_initializer()) <ide> outputs = sess.run(fetches, feed_dict) <ide> <ide> for index, output in enumerate(outputs):
4
PHP
PHP
remove function import
78041a1529e2b11146939d4a0e9b607b98a9a5b6
<ide><path>src/Illuminate/Routing/ControllerDispatcher.php <ide> <ide> use Illuminate\Container\Container; <ide> use Illuminate\Routing\Contracts\ControllerDispatcher as ControllerDispatcherContract; <del>use function method_exists; <ide> <ide> class ControllerDispatcher implements ControllerDispatcherContract <ide> {
1
Javascript
Javascript
use test/common/tmpdir consistently
0376b5b7baf627b112915183edf9e1ea2d3856b7
<ide><path>benchmark/fs/read-stream-throughput.js <ide> <ide> const path = require('path'); <ide> const common = require('../common.js'); <del>const filename = path.resolve(process.env.NODE_TMPDIR || __dirname, <del> `.removeme-benchmark-garbage-${process.pid}`); <ide> const fs = require('fs'); <ide> const assert = require('assert'); <ide> <add>const tmpdir = require('../../test/common/tmpdir'); <add>tmpdir.refresh(); <add>const filename = path.resolve(tmpdir.path, <add> `.removeme-benchmark-garbage-${process.pid}`); <add> <ide> let encodingType, encoding, size, filesize; <ide> <ide> const bench = common.createBenchmark(main, { <ide><path>benchmark/fs/readfile.js <ide> <ide> const path = require('path'); <ide> const common = require('../common.js'); <del>const filename = path.resolve(process.env.NODE_TMPDIR || __dirname, <del> `.removeme-benchmark-garbage-${process.pid}`); <ide> const fs = require('fs'); <ide> const assert = require('assert'); <ide> <add>const tmpdir = require('../../test/common/tmpdir'); <add>tmpdir.refresh(); <add>const filename = path.resolve(tmpdir.path, <add> `.removeme-benchmark-garbage-${process.pid}`); <add> <ide> const bench = common.createBenchmark(main, { <ide> dur: [5], <ide> len: [1024, 16 * 1024 * 1024], <ide><path>benchmark/fs/write-stream-throughput.js <ide> <ide> const path = require('path'); <ide> const common = require('../common.js'); <del>const filename = path.resolve(process.env.NODE_TMPDIR || __dirname, <del> `.removeme-benchmark-garbage-${process.pid}`); <ide> const fs = require('fs'); <ide> <add>const tmpdir = require('../../test/common/tmpdir'); <add>tmpdir.refresh(); <add>const filename = path.resolve(tmpdir.path, <add> `.removeme-benchmark-garbage-${process.pid}`); <add> <ide> const bench = common.createBenchmark(main, { <ide> dur: [5], <ide> encodingType: ['buf', 'asc', 'utf'], <ide><path>test/benchmark/test-benchmark-fs.js <ide> runBenchmark('fs', [ <ide> 'filesize=1024', <ide> 'dir=.github', <ide> 'withFileTypes=false' <del>], { NODE_TMPDIR: tmpdir.path, NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <add>], { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });
4
PHP
PHP
fix $expectedlistener in docblock
089ce46a43219c05f6087e7aed61474693b83be7
<ide><path>src/Illuminate/Support/Facades/Event.php <ide> * @method static void assertDispatchedTimes(string $event, int $times = 1) <ide> * @method static void assertNotDispatched(string|\Closure $event, callable|int $callback = null) <ide> * @method static void assertNothingDispatched() <del> * @method static void assertListening(string $expectedEvent, string expectedListener) <add> * @method static void assertListening(string $expectedEvent, string $expectedListener) <ide> * @method static void flush(string $event) <ide> * @method static void forget(string $event) <ide> * @method static void forgetPushed()
1
Text
Text
fix url to defaults.js
484443f2512268e4682081eeb0b05daa983554f2
<ide><path>README.md <ide> instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; <ide> <ide> ### Config order of precedence <ide> <del>Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. <add>Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults/index.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. <ide> <ide> ```js <ide> // Create an instance using the config defaults provided by the library
1
Text
Text
add patch in http verb constraints [ci skip]
3a0cc5c059b49452057359cab6017f98d93dd916
<ide><path>guides/source/routing.md <ide> This will define a `user_path` method that will be available in controllers, hel <ide> <ide> ### HTTP Verb Constraints <ide> <del>In general, you should use the `get`, `post`, `put` and `delete` methods to constrain a route to a particular verb. You can use the `match` method with the `:via` option to match multiple verbs at once: <add>In general, you should use the `get`, `post`, `put`, `patch` and `delete` methods to constrain a route to a particular verb. You can use the `match` method with the `:via` option to match multiple verbs at once: <ide> <ide> ```ruby <ide> match 'photos', to: 'photos#show', via: [:get, :post]
1
Ruby
Ruby
kill unused variable warnings
5696d948ed0eb9cf755e843564f80801ea864ee2
<ide><path>activerecord/lib/active_record/schema_dumper.rb <ide> def table(table, stream) <ide> <ide> # first dump primary key column <ide> if @connection.respond_to?(:pk_and_sequence_for) <del> pk, pk_seq = @connection.pk_and_sequence_for(table) <add> pk, _ = @connection.pk_and_sequence_for(table) <ide> elsif @connection.respond_to?(:primary_key) <ide> pk = @connection.primary_key(table) <ide> end
1
Python
Python
add examples for join and index
7f43baa7b24ec36b65426428209901c7599c41ef
<ide><path>numpy/core/defchararray.py <ide> def index(a, sub, start=0, end=None): <ide> -------- <ide> find, str.find <ide> <add> Examples <add> -------- <add> >>> a = np.array(["Computer Science"]) <add> >>> np.char.index(a, "Science", start=0, end=None) <add> array([9]) <add> <ide> """ <ide> return _vec_string( <ide> a, int_, 'index', [sub, start] + _clean_args(end)) <ide> def join(sep, seq): <ide> See Also <ide> -------- <ide> str.join <add> <add> Examples <add> -------- <add> >>> np.char.join('-', 'osd') <add> array('o-s-d', dtype='<U5') <add> <add> >>> np.char.join(['-', '.'], ['ghc', 'osd']) <add> array(['g-h-c', 'o.s.d'], dtype='<U5') <add> <ide> """ <ide> return _to_string_or_unicode_array( <ide> _vec_string(sep, object_, 'join', (seq,)))
1
Text
Text
fix typo in readme
98a4d38eb4a478280b2fbc7aa01c795b814b0138
<ide><path>README.md <ide> The environment variables are: <ide> <ide> For VirtualBox, you can simply ignore setting any of the environment <ide> variables and omit the ``provider`` flag. VirtualBox is still supported with <del>VirtualBox <= 1.1: <add>Vagrant <= 1.1: <ide> <ide> ```bash <ide> $ vagrant up --provider=aws
1
Javascript
Javascript
handle invalid prepareasymmetrickey jwk inputs
d94833cf91c0960136cef71076b6a7867e61d903
<ide><path>lib/internal/crypto/keygen.js <ide> const { <ide> SecretKeyObject, <ide> parsePublicKeyEncoding, <ide> parsePrivateKeyEncoding, <del> isJwk <ide> } = require('internal/crypto/keys'); <ide> <ide> const { <ide> const { isArrayBufferView } = require('internal/util/types'); <ide> <ide> const { getOptionValue } = require('internal/options'); <ide> <add>function isJwk(obj) { <add> return obj != null && obj.kty !== undefined; <add>} <add> <ide> function wrapKey(key, ctor) { <ide> if (typeof key === 'string' || <ide> isArrayBufferView(key) || <ide><path>lib/internal/crypto/keys.js <ide> function prepareAsymmetricKey(key, ctx) { <ide> return { format: kKeyFormatPEM, data: getArrayBufferOrView(key, 'key') }; <ide> } else if (typeof key === 'object') { <ide> const { key: data, encoding, format } = key; <add> <ide> // The 'key' property can be a KeyObject as well to allow specifying <ide> // additional options such as padding along with the key. <ide> if (isKeyObject(data)) <ide> return { data: getKeyObjectHandle(data, ctx) }; <ide> else if (isCryptoKey(data)) <ide> return { data: getKeyObjectHandle(data[kKeyObject], ctx) }; <del> else if (isJwk(data) && format === 'jwk') <add> else if (format === 'jwk') { <add> validateObject(data, 'key.key'); <ide> return { data: getKeyObjectHandleFromJwk(data, ctx), format: 'jwk' }; <add> } <add> <ide> // Either PEM or DER using PKCS#1 or SPKI. <ide> if (!isStringOrBuffer(data)) { <ide> throw new ERR_INVALID_ARG_TYPE( <ide> function isCryptoKey(obj) { <ide> return obj != null && obj[kKeyObject] !== undefined; <ide> } <ide> <del>function isJwk(obj) { <del> return obj != null && obj.kty !== undefined; <del>} <del> <ide> module.exports = { <ide> // Public API. <ide> createSecretKey, <ide> module.exports = { <ide> PrivateKeyObject, <ide> isKeyObject, <ide> isCryptoKey, <del> isJwk, <ide> }; <ide><path>test/parallel/test-crypto-key-objects.js <ide> const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem', <ide> assert(!first.equals(third)); <ide> assert(!third.equals(first)); <ide> } <add> <add>{ <add> // This should not cause a crash: https://github.com/nodejs/node/issues/44471 <add> for (const key of ['', 'foo', null, undefined, true, Boolean]) { <add> assert.throws(() => { <add> createPublicKey({ key, format: 'jwk' }); <add> }, { code: 'ERR_INVALID_ARG_TYPE', message: /The "key\.key" property must be of type object/ }); <add> assert.throws(() => { <add> createPrivateKey({ key, format: 'jwk' }); <add> }, { code: 'ERR_INVALID_ARG_TYPE', message: /The "key\.key" property must be of type object/ }); <add> } <add>} <ide><path>test/parallel/test-crypto-sign-verify.js <ide> assert.throws( <ide> message: /digest too big for rsa key/ <ide> }); <ide> } <add> <add>{ <add> // This should not cause a crash: https://github.com/nodejs/node/issues/44471 <add> for (const key of ['', 'foo', null, undefined, true, Boolean]) { <add> assert.throws(() => { <add> crypto.verify('sha256', 'foo', { key, format: 'jwk' }, Buffer.alloc(0)); <add> }, { code: 'ERR_INVALID_ARG_TYPE', message: /The "key\.key" property must be of type object/ }); <add> assert.throws(() => { <add> crypto.createVerify('sha256').verify({ key, format: 'jwk' }, Buffer.alloc(0)); <add> }, { code: 'ERR_INVALID_ARG_TYPE', message: /The "key\.key" property must be of type object/ }); <add> assert.throws(() => { <add> crypto.sign('sha256', 'foo', { key, format: 'jwk' }); <add> }, { code: 'ERR_INVALID_ARG_TYPE', message: /The "key\.key" property must be of type object/ }); <add> assert.throws(() => { <add> crypto.createSign('sha256').sign({ key, format: 'jwk' }); <add> }, { code: 'ERR_INVALID_ARG_TYPE', message: /The "key\.key" property must be of type object/ }); <add> } <add>}
4
Text
Text
fix broken url in docs
11dc2aad0e05b80bdf9134a84bb6dd908b1f11ea
<ide><path>docs/docs/charts/scatter.md <ide> var scatterChart = new Chart(ctx, { <ide> <ide> ## Dataset Properties <ide> <del>The scatter chart supports all of the same properties as the [line chart](./charts/line#dataset-properties). <add>The scatter chart supports all of the same properties as the [line chart](./charts/line.mdx#dataset-properties). <ide> <ide> ## Data Structure <ide>
1
Text
Text
fix description of `decimalfield`'s `max_digits`
aed8387e05a7a665439044d90b7fac5d1fd61225
<ide><path>docs/api-guide/fields.md <ide> Corresponds to `django.db.models.fields.DecimalField`. <ide> <ide> **Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)` <ide> <del>- `max_digits` The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. <add>- `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`. <ide> - `decimal_places` The number of decimal places to store with the number. <ide> - `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`. <ide> - `max_value` Validate that the number provided is no greater than this value.
1
PHP
PHP
add shortcut to model option
4572938cce79d8a8a0f222c8bdca2768332e9f19
<ide><path>src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php <ide> protected function getPath($name) <ide> protected function getOptions() <ide> { <ide> return [ <del> ['model', null, InputOption::VALUE_OPTIONAL, 'The name of the model'], <add> ['model', 'm', InputOption::VALUE_OPTIONAL, 'The name of the model'], <ide> ]; <ide> } <ide> }
1
Text
Text
add backwards incompatibility [ci skip]
f873548f6c26a91715beaf91d04831e29e60df2f
<ide><path>website/docs/usage/v2-2.md <ide> check if all of your models are up to date, you can run the <ide> <ide> </Infobox> <ide> <del><!-- TODO: copy from release notes once they're ready --> <add>- The Dutch models have been trained on a new NER corpus (custom labelled UD <add> instead of WikiNER), so their predictions may be very different compared to <add> the previous version. The results should be significantly better and more <add> generalizable, though. <add>- The `spacy download` command does **not** set the `--no-deps` pip argument <add> anymore by default, meaning that model package dependencies (if available) <add> will now be also downloaded and installed. If spaCy (which is also a model <add> dependency) is not installed in the current environment, e.g. if a user has <add> built from source, `--no-deps` is added back automatically to prevent spaCy <add> from being downloaded and installed again from pip. <add>- The built-in `biluo_tags_from_offsets` converter is now stricter and will <add> raise an error if entities are overlapping (instead of silently skipping <add> them). If your data contains invalid entity annotations, make sure to clean it <add> and resolve conflicts. You can now also use the new `debug-data` command to <add> find problems in your data. <add>- The default punctuation in the `sentencizer` has been extended and now <add> includes more characters common in various languages. This also means that the <add> results it produces may change, depending on your text. If you want the <add> previous behaviour with limited characters, set `punct_chars=[".", "!", "?"]` <add> on initialization. <add>- Lemmatization tables (rules, exceptions, index and lookups) are now part of <add> the `Vocab` and serialized with it. This means that serialized objects (`nlp`, <add> pipeline components, vocab) will now include additional data, and models <add> written to disk will include additional files. <add>- The `Serbian` language class (introduced in v2.1.8) incorrectly used the <add> language code `rs` instead of `sr`. This has now been fixed, so `Serbian` is <add> now available via `spacy.lang.sr`. <add>- The `"sources"` in the `meta.json` have changed from a list of strings to a <add> list of dicts. This is mostly internals, but if your code used <add> `nlp.meta["sources"]`, you might have to update it.
1
Go
Go
move imageid validation to stringid pkg
9f3046f9a03f1a710bdb7fcddd37ff50e71e31c3
<ide><path>image/v1/imagev1.go <ide> package v1 <ide> <ide> import ( <ide> "encoding/json" <del> "fmt" <ide> "reflect" <del> "regexp" <ide> "strings" <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/distribution/digest" <ide> "github.com/docker/docker/api/types/versions" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/layer" <add> "github.com/docker/docker/pkg/stringid" <ide> ) <ide> <del>var validHex = regexp.MustCompile(`^([a-f0-9]{64})$`) <del> <ide> // noFallbackMinVersion is the minimum version for which v1compatibility <ide> // information will not be marshaled through the Image struct to remove <ide> // blank fields. <ide> func rawJSON(value interface{}) *json.RawMessage { <ide> <ide> // ValidateID checks whether an ID string is a valid image ID. <ide> func ValidateID(id string) error { <del> if ok := validHex.MatchString(id); !ok { <del> return fmt.Errorf("image ID %q is invalid", id) <del> } <del> return nil <add> return stringid.ValidateID(id) <ide> } <ide><path>pkg/stringid/stringid.go <ide> package stringid <ide> import ( <ide> "crypto/rand" <ide> "encoding/hex" <add> "fmt" <ide> "io" <ide> "regexp" <ide> "strconv" <ide> import ( <ide> <ide> const shortLen = 12 <ide> <del>var validShortID = regexp.MustCompile("^[a-z0-9]{12}$") <add>var ( <add> validShortID = regexp.MustCompile("^[a-f0-9]{12}$") <add> validHex = regexp.MustCompile(`^[a-f0-9]{64}$`) <add>) <ide> <ide> // IsShortID determines if an arbitrary string *looks like* a short ID. <ide> func IsShortID(id string) bool { <ide> func GenerateRandomID() string { <ide> func GenerateNonCryptoID() string { <ide> return generateID(false) <ide> } <add> <add>// ValidateID checks whether an ID string is a valid image ID. <add>func ValidateID(id string) error { <add> if ok := validHex.MatchString(id); !ok { <add> return fmt.Errorf("image ID %q is invalid", id) <add> } <add> return nil <add>} <ide><path>reference/reference.go <ide> import ( <ide> <ide> "github.com/docker/distribution/digest" <ide> distreference "github.com/docker/distribution/reference" <del> "github.com/docker/docker/image/v1" <add> "github.com/docker/docker/pkg/stringid" <ide> ) <ide> <ide> const ( <ide> func IsNameOnly(ref Named) bool { <ide> // ParseIDOrReference parses string for an image ID or a reference. ID can be <ide> // without a default prefix. <ide> func ParseIDOrReference(idOrRef string) (digest.Digest, Named, error) { <del> if err := v1.ValidateID(idOrRef); err == nil { <add> if err := stringid.ValidateID(idOrRef); err == nil { <ide> idOrRef = "sha256:" + idOrRef <ide> } <ide> if dgst, err := digest.ParseDigest(idOrRef); err == nil { <ide> func normalize(name string) (string, error) { <ide> } <ide> <ide> func validateName(name string) error { <del> if err := v1.ValidateID(name); err == nil { <add> if err := stringid.ValidateID(name); err == nil { <ide> return fmt.Errorf("Invalid repository name (%s), cannot specify 64-byte hexadecimal strings", name) <ide> } <ide> return nil
3
PHP
PHP
use peer_name instead of deprecated cn_match
d07a41307b6ba453dfec253096d3916c9cef09b4
<ide><path>src/Network/Http/Adapter/Stream.php <ide> protected function _buildSslContext(Request $request, $options) <ide> if (!empty($options['ssl_verify_host'])) { <ide> $url = $request->url(); <ide> $host = parse_url($url, PHP_URL_HOST); <del> $this->_sslContextOptions['CN_match'] = $host; <add> $this->_sslContextOptions['peer_name'] = $host; <ide> } <ide> foreach ($sslOptions as $key) { <ide> if (isset($options[$key])) { <ide><path>tests/TestCase/Network/Http/Adapter/StreamTest.php <ide> public function testSendContextSsl() <ide> $this->stream->send($request, $options); <ide> $result = $this->stream->contextOptions(); <ide> $expected = [ <del> 'CN_match' => 'localhost.com', <add> 'peer_name' => 'localhost.com', <ide> 'verify_peer' => true, <ide> 'verify_depth' => 9000, <ide> 'allow_self_signed' => false,
2
Ruby
Ruby
use file.lutime instead of system call
8ab5ea52495a3f2a53e376e43e8e3551227e58ef
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def bottle_formula(f, args:) <ide> <ide> keg.find do |file| <ide> if file.symlink? <del> # Ruby does not support `File.lutime` yet. <del> # Shellout using `touch` to change modified time of symlink itself. <del> system "/usr/bin/touch", "-h", <del> "-t", tab.source_modified_time.strftime("%Y%m%d%H%M.%S"), file <add> File.lutime(tab.source_modified_time, tab.source_modified_time, file) <ide> else <ide> file.utime(tab.source_modified_time, tab.source_modified_time) <ide> end
1
Javascript
Javascript
move debug statement
2154a3ce0f2eca1d26e1ad8e7bbeae1039822a5a
<ide><path>lib/net.js <ide> function internalConnect( <ide> var err; <ide> <ide> if (localAddress || localPort) { <del> debug('binding to localAddress: %s and localPort: %d (addressType: %d)', <del> localAddress, localPort, addressType); <del> <ide> if (addressType === 4) { <ide> localAddress = localAddress || '0.0.0.0'; <ide> err = self._handle.bind(localAddress, localPort); <ide> function internalConnect( <ide> self.destroy(new TypeError('Invalid addressType: ' + addressType)); <ide> return; <ide> } <add> debug('binding to localAddress: %s and localPort: %d (addressType: %d)', <add> localAddress, localPort, addressType); <ide> <ide> if (err) { <ide> const ex = exceptionWithHostPort(err, 'bind', localAddress, localPort);
1
Text
Text
fix typo in readme (#787)
789edb87b77db836717e357d632e05e6d06927ed
<ide><path>README.md <ide> Here's a list of supported events: <ide> <ide> > Here `url` is the URL shown in the browser. If you call `Router.push(url, as)` (or similar), then the value of `url` will be `as`. <ide> <del>Here's how to property listen to the router event `routeChangeStart`: <add>Here's how to properly listen to the router event `routeChangeStart`: <ide> <ide> ```js <ide> Router.onRouteChangeStart = (url) => {
1
Text
Text
add description on depth in model comparison table
c442abf264be7b6c935a63c39e0be72688992ac3
<ide><path>docs/templates/applications.md <ide> model = InceptionV3(input_tensor=input_tensor, weights='imagenet', include_top=T <ide> <ide> The top-1 and top-5 accuracy refers to the model's performance on the ImageNet validation dataset. <ide> <add>Depth refers to the topological depth of the network. This includes activation layers, batch normalization layers etc. <add> <ide> ----- <ide> <ide>
1
Javascript
Javascript
add test case
80bf77d26f282f53b7067a9d1084581db5f37b78
<ide><path>test/watchCases/cache/unsafe-cache/0/index.js <ide> import value from "./changing-module"; <add>import "./proxy-module"; <ide> <ide> it("should compile and cleanup correctly", () => { <ide> expect(value).toBe(WATCH_STEP); <ide><path>test/watchCases/cache/unsafe-cache/0/proxy-module.js <ide> import "./unchanged-module.js"; <ide> import "./unchanged-module.json"; <ide> new URL("./unchanged-module.svg", import.meta.url); <add>import "external"; <ide><path>test/watchCases/cache/unsafe-cache/1/changing-module.js <ide> import "./unchanged-module.js"; <ide> import "./unchanged-module.json"; <ide> new URL("./unchanged-module.svg", import.meta.url); <add>import "external"; <ide> <ide> export default "1"; <ide><path>test/watchCases/cache/unsafe-cache/2/changing-module.js <ide> import "./unchanged-module.js"; <ide> import "./unchanged-module.json"; <ide> new URL("./unchanged-module.svg", import.meta.url); <add>import "external"; <ide> <ide> export default "2"; <ide><path>test/watchCases/cache/unsafe-cache/webpack.config.js <ide> module.exports = { <ide> }, <ide> module: { <ide> unsafeCache: true <add> }, <add> externals: { <add> external: "var 123" <ide> } <ide> };
5
Javascript
Javascript
handle junk at the end of postscript functions
e5732f489d27f40b125714f88d2a8279dbcddd32
<ide><path>src/function.js <ide> var PostScriptLexer = (function PostScriptLexerClosure() { <ide> // operator <ide> var str = ch.toLowerCase(); <ide> while (true) { <del> ch = stream.lookChar().toLowerCase(); <add> ch = stream.lookChar(); <add> if (ch === null) <add> break; <add> ch.toLowerCase(); <ide> if (ch >= 'a' && ch <= 'z') <ide> str += ch; <ide> else <ide><path>test/unit/function_spec.js <ide> describe('function', function() { <ide> expect(function() { parse('{'); }).toThrow( <ide> new Error('Unexpected symbol: found undefined expected 1.')); <ide> }); <add> it('handles junk after the end', function() { <add> var number = 3.3; <add> var program = parse('{ ' + number + ' }#'); <add> var expectedProgram = [number]; <add> expect(program).toMatchArray(expectedProgram); <add> }); <ide> }); <ide> <ide> describe('PostScriptEvaluator', function() {
2
PHP
PHP
fix cs errors
9bd82d7ac13642f03cde23c43e73c5a5271694b9
<ide><path>src/Auth/AbstractPasswordHasher.php <ide> */ <ide> abstract class AbstractPasswordHasher <ide> { <del> <ide> use InstanceConfigTrait; <ide> <ide> /** <ide><path>src/Auth/BaseAuthenticate.php <ide> */ <ide> namespace Cake\Auth; <ide> <del>use Cake\Auth\AbstractPasswordHasher; <ide> use Cake\Controller\ComponentRegistry; <ide> use Cake\Core\InstanceConfigTrait; <ide> use Cake\Event\EventListenerInterface; <ide> */ <ide> abstract class BaseAuthenticate implements EventListenerInterface <ide> { <del> <ide> use InstanceConfigTrait; <ide> use LocatorAwareTrait; <ide> <ide> abstract class BaseAuthenticate implements EventListenerInterface <ide> protected $_defaultConfig = [ <ide> 'fields' => [ <ide> 'username' => 'username', <del> 'password' => 'password' <add> 'password' => 'password', <ide> ], <ide> 'userModel' => 'Users', <ide> 'finder' => 'all', <del> 'passwordHasher' => 'Default' <add> 'passwordHasher' => 'Default', <ide> ]; <ide> <ide> /** <ide> protected function _query(string $username): Query <ide> $table = $this->getTableLocator()->get($config['userModel']); <ide> <ide> $options = [ <del> 'conditions' => [$table->aliasField($config['fields']['username']) => $username] <add> 'conditions' => [$table->aliasField($config['fields']['username']) => $username], <ide> ]; <ide> <ide> $finder = $config['finder']; <ide><path>src/Auth/BaseAuthorize.php <ide> */ <ide> abstract class BaseAuthorize <ide> { <del> <ide> use InstanceConfigTrait; <ide> <ide> /** <ide><path>src/Auth/BasicAuthenticate.php <ide> */ <ide> class BasicAuthenticate extends BaseAuthenticate <ide> { <del> <ide> /** <ide> * Authenticate a user using HTTP auth. Will use the configured User model and attempt a <ide> * login using HTTP auth. <ide> public function loginHeaders(ServerRequest $request): array <ide> $realm = $this->getConfig('realm') ?: $request->getEnv('SERVER_NAME'); <ide> <ide> return [ <del> 'WWW-Authenticate' => sprintf('Basic realm="%s"', $realm) <add> 'WWW-Authenticate' => sprintf('Basic realm="%s"', $realm), <ide> ]; <ide> } <ide> } <ide><path>src/Auth/ControllerAuthorize.php <ide> */ <ide> class ControllerAuthorize extends BaseAuthorize <ide> { <del> <ide> /** <ide> * Controller for the request. <ide> * <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> * @return \Cake\Controller\Controller <ide> * @throws \Cake\Core\Exception\Exception If controller does not have method `isAuthorized()`. <ide> */ <del> public function controller(Controller $controller = null): Controller <add> public function controller(?Controller $controller = null): Controller <ide> { <ide> if ($controller) { <ide> if (!method_exists($controller, 'isAuthorized')) { <ide><path>src/Auth/DefaultPasswordHasher.php <ide> */ <ide> class DefaultPasswordHasher extends AbstractPasswordHasher <ide> { <del> <ide> /** <ide> * Default config for this object. <ide> * <ide> class DefaultPasswordHasher extends AbstractPasswordHasher <ide> */ <ide> protected $_defaultConfig = [ <ide> 'hashType' => PASSWORD_DEFAULT, <del> 'hashOptions' => [] <add> 'hashOptions' => [], <ide> ]; <ide> <ide> /** <ide><path>src/Auth/DigestAuthenticate.php <ide> */ <ide> class DigestAuthenticate extends BasicAuthenticate <ide> { <del> <ide> /** <ide> * Constructor <ide> * <ide> public function loginHeaders(ServerRequest $request): array <ide> 'realm' => $realm, <ide> 'qop' => $this->_config['qop'], <ide> 'nonce' => $this->generateNonce(), <del> 'opaque' => $this->_config['opaque'] ?: md5($realm) <add> 'opaque' => $this->_config['opaque'] ?: md5($realm), <ide> ]; <ide> <ide> $digest = $this->_getDigest($request); <ide> public function loginHeaders(ServerRequest $request): array <ide> } <ide> <ide> return [ <del> 'WWW-Authenticate' => 'Digest ' . implode(',', $opts) <add> 'WWW-Authenticate' => 'Digest ' . implode(',', $opts), <ide> ]; <ide> } <ide> <ide><path>src/Auth/FallbackPasswordHasher.php <ide> */ <ide> class FallbackPasswordHasher extends AbstractPasswordHasher <ide> { <del> <ide> /** <ide> * Default config for this object. <ide> * <ide> * @var array <ide> */ <ide> protected $_defaultConfig = [ <del> 'hashers' => [] <add> 'hashers' => [], <ide> ]; <ide> <ide> /** <ide><path>src/Auth/FormAuthenticate.php <ide> */ <ide> class FormAuthenticate extends BaseAuthenticate <ide> { <del> <ide> /** <ide> * Checks the fields to ensure they are supplied. <ide> * <ide><path>src/Auth/PasswordHasherFactory.php <ide> */ <ide> namespace Cake\Auth; <ide> <del>use Cake\Auth\AbstractPasswordHasher; <ide> use Cake\Core\App; <ide> use RuntimeException; <ide> <ide> */ <ide> class PasswordHasherFactory <ide> { <del> <ide> /** <ide> * Returns password hasher object out of a hasher name or a configuration array <ide> * <ide><path>src/Auth/Storage/MemoryStorage.php <ide> */ <ide> namespace Cake\Auth\Storage; <ide> <del>use Cake\Auth\Storage\StorageInterface; <del> <ide> /** <ide> * Memory based non-persistent storage for authenticated user record. <ide> */ <ide> class MemoryStorage implements StorageInterface <ide> { <del> <ide> /** <ide> * User record. <ide> * <ide><path>src/Auth/Storage/SessionStorage.php <ide> */ <ide> class SessionStorage implements StorageInterface <ide> { <del> <ide> use InstanceConfigTrait; <ide> <ide> /** <ide> class SessionStorage implements StorageInterface <ide> */ <ide> protected $_defaultConfig = [ <ide> 'key' => 'Auth.User', <del> 'redirect' => 'Auth.redirect' <add> 'redirect' => 'Auth.redirect', <ide> ]; <ide> <ide> /** <ide><path>src/Auth/WeakPasswordHasher.php <ide> */ <ide> class WeakPasswordHasher extends AbstractPasswordHasher <ide> { <del> <ide> /** <ide> * Default config for this object. <ide> * <ide> * @var array <ide> */ <ide> protected $_defaultConfig = [ <del> 'hashType' => null <add> 'hashType' => null, <ide> ]; <ide> <ide> /** <ide><path>src/Cache/Cache.php <ide> */ <ide> class Cache <ide> { <del> <ide> use StaticConfigTrait; <ide> <ide> /** <ide><path>src/Cache/CacheEngine.php <ide> */ <ide> abstract class CacheEngine <ide> { <del> <ide> use InstanceConfigTrait; <ide> <ide> /** <ide><path>src/Cache/CacheRegistry.php <ide> */ <ide> class CacheRegistry extends ObjectRegistry <ide> { <del> <ide> /** <ide> * Resolve a cache engine classname. <ide> * <ide><path>src/Cache/Engine/ApcuEngine.php <ide> */ <ide> class ApcuEngine extends CacheEngine <ide> { <del> <ide> /** <ide> * Contains the compiled group names <ide> * (prefixed with the global configuration prefix) <ide><path>src/Cache/Engine/FileEngine.php <ide> */ <ide> class FileEngine extends CacheEngine <ide> { <del> <ide> /** <ide> * Instance of SplFileObject class <ide> * <ide> class FileEngine extends CacheEngine <ide> 'path' => null, <ide> 'prefix' => 'cake_', <ide> 'probability' => 100, <del> 'serialize' => true <add> 'serialize' => true, <ide> ]; <ide> <ide> /** <ide><path>src/Cache/Engine/MemcachedEngine.php <ide> */ <ide> class MemcachedEngine extends CacheEngine <ide> { <del> <ide> /** <ide> * memcached wrapper. <ide> * <ide> public function init(array $config = []) <ide> $this->_serializers = [ <ide> 'igbinary' => Memcached::SERIALIZER_IGBINARY, <ide> 'json' => Memcached::SERIALIZER_JSON, <del> 'php' => Memcached::SERIALIZER_PHP <add> 'php' => Memcached::SERIALIZER_PHP, <ide> ]; <ide> if (defined('Memcached::HAVE_MSGPACK') && Memcached::HAVE_MSGPACK) { <ide> $this->_serializers['msgpack'] = Memcached::SERIALIZER_MSGPACK; <ide><path>src/Cache/Engine/NullEngine.php <ide> */ <ide> class NullEngine extends CacheEngine <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Cache/Engine/RedisEngine.php <ide> */ <ide> class RedisEngine extends CacheEngine <ide> { <del> <ide> /** <ide> * Redis wrapper. <ide> * <ide><path>src/Cache/Engine/WincacheEngine.php <ide> */ <ide> class WincacheEngine extends CacheEngine <ide> { <del> <ide> /** <ide> * Contains the compiled group names <ide> * (prefixed with the global configuration prefix) <ide><path>src/Collection/Collection.php <ide> */ <ide> class Collection extends IteratorIterator implements CollectionInterface, Serializable <ide> { <del> <ide> use CollectionTrait; <ide> <ide> /** <ide><path>src/Collection/CollectionInterface.php <ide> */ <ide> interface CollectionInterface extends Iterator, JsonSerializable <ide> { <del> <ide> /** <ide> * Executes the passed callable for each of the elements in this collection <ide> * and passes both the value and key for them on each step. <ide> public function each(callable $c): CollectionInterface; <ide> * If left null, a callback that filters out falsey values will be used. <ide> * @return \Cake\Collection\CollectionInterface <ide> */ <del> public function filter(callable $c = null): CollectionInterface; <add> public function filter(?callable $c = null): CollectionInterface; <ide> <ide> /** <ide> * Looks through each value in the collection, and returns another collection with <ide> public function stopWhen($condition): CollectionInterface; <ide> * the items in the collection and should return an array or Traversable object <ide> * @return \Cake\Collection\CollectionInterface <ide> */ <del> public function unfold(callable $transformer = null): CollectionInterface; <add> public function unfold(?callable $transformer = null): CollectionInterface; <ide> <ide> /** <ide> * Passes this collection through a callable as its first argument. <ide> public function countKeys(): int; <ide> * of the final results. <ide> * @return \Cake\Collection\CollectionInterface <ide> */ <del> public function cartesianProduct(callable $operation = null, callable $filter = null): CollectionInterface; <add> public function cartesianProduct(?callable $operation = null, ?callable $filter = null): CollectionInterface; <ide> } <ide><path>src/Collection/CollectionTrait.php <ide> <ide> use AppendIterator; <ide> use ArrayIterator; <del>use Cake\Collection\CollectionInterface; <ide> use Cake\Collection\Iterator\BufferedIterator; <ide> use Cake\Collection\Iterator\ExtractIterator; <ide> use Cake\Collection\Iterator\FilterIterator; <ide> */ <ide> trait CollectionTrait <ide> { <del> <ide> use ExtractTrait; <ide> <ide> /** <ide> public function each(callable $c): CollectionInterface <ide> * <ide> * @return \Cake\Collection\CollectionInterface <ide> */ <del> public function filter(callable $c = null): CollectionInterface <add> public function filter(?callable $c = null): CollectionInterface <ide> { <ide> if ($c === null) { <ide> $c = function ($v) { <ide> public function min($callback, int $type = \SORT_NUMERIC) <ide> public function avg($matcher = null) <ide> { <ide> $result = $this; <del> if ($matcher != null) { <add> if ($matcher !== null) { <ide> $result = $result->extract($matcher); <ide> } <ide> $result = $result <ide> public function avg($matcher = null) <ide> public function median($matcher = null) <ide> { <ide> $elements = $this; <del> if ($matcher != null) { <add> if ($matcher !== null) { <ide> $elements = $elements->extract($matcher); <ide> } <ide> $values = $elements->toList(); <ide> public function combine($keyPath, $valuePath, $groupPath = null): CollectionInte <ide> $options = [ <ide> 'keyPath' => $this->_propertyExtractor($keyPath), <ide> 'valuePath' => $this->_propertyExtractor($valuePath), <del> 'groupPath' => $groupPath ? $this->_propertyExtractor($groupPath) : null <add> 'groupPath' => $groupPath ? $this->_propertyExtractor($groupPath) : null, <ide> ]; <ide> <ide> $mapper = function ($value, $key, $mapReduce) use ($options) { <ide> public function listNested($dir = 'desc', $nestingKey = 'children'): CollectionI <ide> $modes = [ <ide> 'desc' => TreeIterator::SELF_FIRST, <ide> 'asc' => TreeIterator::CHILD_FIRST, <del> 'leaves' => TreeIterator::LEAVES_ONLY <add> 'leaves' => TreeIterator::LEAVES_ONLY, <ide> ]; <ide> <ide> return new TreeIterator( <ide> new NestIterator($this, $nestingKey), <del> isset($modes[$dir]) ? $modes[$dir] : $dir <add> $modes[$dir] ?? $dir <ide> ); <ide> } <ide> <ide> public function stopWhen($condition): CollectionInterface <ide> /** <ide> * {@inheritDoc} <ide> */ <del> public function unfold(callable $transformer = null): CollectionInterface <add> public function unfold(?callable $transformer = null): CollectionInterface <ide> { <ide> if ($transformer === null) { <ide> $transformer = function ($item) { <ide> public function unwrap(): Traversable <ide> * <ide> * @return \Cake\Collection\CollectionInterface <ide> */ <del> public function cartesianProduct(callable $operation = null, callable $filter = null): CollectionInterface <add> public function cartesianProduct(?callable $operation = null, ?callable $filter = null): CollectionInterface <ide> { <ide> if ($this->isEmpty()) { <ide> return new Collection([]); <ide> public function transpose(): CollectionInterface <ide> $length = count(current($arrayValue)); <ide> $result = []; <ide> foreach ($arrayValue as $column => $row) { <del> if (count($row) != $length) { <add> if (count($row) !== $length) { <ide> throw new LogicException('Child arrays do not have even length'); <ide> } <ide> } <ide><path>src/Collection/ExtractTrait.php <ide> */ <ide> trait ExtractTrait <ide> { <del> <ide> /** <ide> * Returns a callable that can be used to extract a property or column from <ide> * an array or object based on a dot separated path. <ide> protected function _createMatcherFilter(array $conditions): callable <ide> foreach ($conditions as $property => $value) { <ide> $extractor = $this->_propertyExtractor($property); <ide> $matchers[] = function ($v) use ($extractor, $value) { <del> return $extractor($v) == $value; <add> return $extractor($v) === $value; <ide> }; <ide> } <ide> <ide><path>src/Collection/Iterator/BufferedIterator.php <ide> */ <ide> class BufferedIterator extends Collection implements Countable, Serializable <ide> { <del> <ide> /** <ide> * The in-memory cache containing results from previous iterators <ide> * <ide> public function valid() <ide> $this->_key = parent::key(); <ide> $this->_buffer->push([ <ide> 'key' => $this->_key, <del> 'value' => $this->_current <add> 'value' => $this->_current, <ide> ]); <ide> } <ide> <ide><path>src/Collection/Iterator/ExtractIterator.php <ide> */ <ide> class ExtractIterator extends Collection <ide> { <del> <ide> /** <ide> * A callable responsible for extracting a single value for each <ide> * item in the collection. <ide><path>src/Collection/Iterator/FilterIterator.php <ide> */ <ide> class FilterIterator extends Collection <ide> { <del> <ide> /** <ide> * The callback used to filter the elements in this collection <ide> * <ide><path>src/Collection/Iterator/InsertIterator.php <ide> */ <ide> class InsertIterator extends Collection <ide> { <del> <ide> /** <ide> * The collection from which to extract the values to be inserted <ide> * <ide><path>src/Collection/Iterator/MapReduce.php <ide> */ <ide> class MapReduce implements IteratorAggregate <ide> { <del> <ide> /** <ide> * Holds the shuffled results that were emitted from the map <ide> * phase <ide> class MapReduce implements IteratorAggregate <ide> * of the bucket that was created during the mapping phase and third one is an <ide> * instance of this class. <ide> */ <del> public function __construct(Traversable $data, callable $mapper, callable $reducer = null) <add> public function __construct(Traversable $data, callable $mapper, ?callable $reducer = null) <ide> { <ide> $this->_data = $data; <ide> $this->_mapper = $mapper; <ide><path>src/Collection/Iterator/NestIterator.php <ide> */ <ide> class NestIterator extends Collection implements RecursiveIterator <ide> { <del> <ide> /** <ide> * The name of the property that contains the nested items for each element <ide> * <ide><path>src/Collection/Iterator/NoChildrenIterator.php <ide> */ <ide> class NoChildrenIterator extends Collection implements RecursiveIterator <ide> { <del> <ide> /** <ide> * Returns false as there are no children iterators in this collection <ide> * <ide><path>src/Collection/Iterator/ReplaceIterator.php <ide> */ <ide> class ReplaceIterator extends Collection <ide> { <del> <ide> /** <ide> * The callback function to be used to transform values <ide> * <ide><path>src/Collection/Iterator/SortIterator.php <ide> */ <ide> class SortIterator extends Collection <ide> { <del> <ide> /** <ide> * Wraps this iterator around the passed items so when iterated they are returned <ide> * in order. <ide><path>src/Collection/Iterator/StoppableIterator.php <ide> */ <ide> class StoppableIterator extends Collection <ide> { <del> <ide> /** <ide> * The condition to evaluate for each item of the collection <ide> * <ide><path>src/Collection/Iterator/TreeIterator.php <ide> */ <ide> class TreeIterator extends RecursiveIteratorIterator implements CollectionInterface <ide> { <del> <ide> use CollectionTrait; <ide> <ide> /** <ide><path>src/Collection/Iterator/TreePrinter.php <ide> */ <ide> class TreePrinter extends RecursiveIteratorIterator <ide> { <del> <ide> use CollectionTrait; <ide> <ide> /** <ide><path>src/Collection/Iterator/UnfoldIterator.php <ide> */ <ide> class UnfoldIterator extends IteratorIterator implements RecursiveIterator <ide> { <del> <ide> /** <ide> * A function that is passed each element in this iterator and <ide> * must return an array or Traversable object. <ide><path>src/Collection/Iterator/ZipIterator.php <ide> */ <ide> class ZipIterator extends MultipleIterator implements CollectionInterface, Serializable <ide> { <del> <ide> use CollectionTrait; <ide> <ide> /** <ide><path>src/Command/HelpCommand.php <ide> protected function asText($io, $commands) <ide> } <ide> <ide> foreach ($commands as $name => $class) { <del> if (count($invert[$class]) == 1) { <add> if (count($invert[$class]) === 1) { <ide> $io->out('- ' . $name); <ide> } <ide> <ide> protected function buildOptionParser(ConsoleOptionParser $parser) <ide> 'Get the list of available shells for this application.' <ide> )->addOption('xml', [ <ide> 'help' => 'Get the listing as XML.', <del> 'boolean' => true <add> 'boolean' => true, <ide> ]); <ide> <ide> return $parser; <ide><path>src/Console/Command.php <ide> class Command <ide> * <ide> * @var int <ide> */ <del> const CODE_ERROR = 1; <add> public const CODE_ERROR = 1; <ide> <ide> /** <ide> * Default success code <ide> * <ide> * @var int <ide> */ <del> const CODE_SUCCESS = 0; <add> public const CODE_SUCCESS = 0; <ide> <ide> /** <ide> * The name of this command. <ide><path>src/Console/CommandFactory.php <ide> */ <ide> class CommandFactory implements CommandFactoryInterface <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Console/CommandRunner.php <ide> <ide> use Cake\Command\HelpCommand; <ide> use Cake\Command\VersionCommand; <del>use Cake\Console\CommandCollection; <del>use Cake\Console\CommandCollectionAwareInterface; <del>use Cake\Console\ConsoleIo; <ide> use Cake\Console\Exception\StopException; <del>use Cake\Console\Shell; <ide> use Cake\Core\ConsoleApplicationInterface; <ide> use Cake\Core\HttpApplicationInterface; <ide> use Cake\Core\PluginApplicationInterface; <ide> class CommandRunner implements EventDispatcherInterface <ide> * @param string $root The root command name to be removed from argv. <ide> * @param \Cake\Console\CommandFactoryInterface|null $factory Command factory instance. <ide> */ <del> public function __construct(ConsoleApplicationInterface $app, $root = 'cake', CommandFactoryInterface $factory = null) <add> public function __construct(ConsoleApplicationInterface $app, $root = 'cake', ?CommandFactoryInterface $factory = null) <ide> { <ide> $this->app = $app; <ide> $this->root = $root; <ide> public function setAliases(array $aliases) <ide> * @return int The exit code of the command. <ide> * @throws \RuntimeException <ide> */ <del> public function run(array $argv, ConsoleIo $io = null) <add> public function run(array $argv, ?ConsoleIo $io = null) <ide> { <ide> $this->bootstrap(); <ide> <ide><path>src/Console/CommandScanner.php <ide> protected function scanDir($path, $namespace, $prefix, array $hide) <ide> 'file' => $path . $file, <ide> 'fullName' => $prefix . $name, <ide> 'name' => $name, <del> 'class' => $class <add> 'class' => $class, <ide> ]; <ide> } <ide> <ide><path>src/Console/ConsoleErrorHandler.php <ide> */ <ide> class ConsoleErrorHandler extends BaseErrorHandler <ide> { <del> <ide> /** <ide> * Standard error stream. <ide> * <ide><path>src/Console/ConsoleInput.php <ide> */ <ide> class ConsoleInput <ide> { <del> <ide> /** <ide> * Input value. <ide> * <ide> public function dataAvailable($timeout = 0) <ide> $readFds = [$this->_input]; <ide> $readyFds = stream_select($readFds, $writeFds, $errorFds, $timeout); <ide> <del> return ($readyFds > 0); <add> return $readyFds > 0; <ide> } <ide> } <ide><path>src/Console/ConsoleInputArgument.php <ide> */ <ide> class ConsoleInputArgument <ide> { <del> <ide> /** <ide> * Name of the argument. <ide> * <ide><path>src/Console/ConsoleInputOption.php <ide> */ <ide> class ConsoleInputOption <ide> { <del> <ide> /** <ide> * Name of the option <ide> * <ide><path>src/Console/ConsoleInputSubcommand.php <ide> */ <ide> class ConsoleInputSubcommand <ide> { <del> <ide> /** <ide> * Name of the subcommand <ide> * <ide><path>src/Console/ConsoleIo.php <ide> */ <ide> class ConsoleIo <ide> { <del> <ide> /** <ide> * The output stream <ide> * <ide> class ConsoleIo <ide> * <ide> * @var int <ide> */ <del> const VERBOSE = 2; <add> public const VERBOSE = 2; <ide> <ide> /** <ide> * Output constant for making normal shells. <ide> * <ide> * @var int <ide> */ <del> const NORMAL = 1; <add> public const NORMAL = 1; <ide> <ide> /** <ide> * Output constants for making quiet shells. <ide> * <ide> * @var int <ide> */ <del> const QUIET = 0; <add> public const QUIET = 0; <ide> <ide> /** <ide> * The current output level. <ide> class ConsoleIo <ide> * @param \Cake\Console\ConsoleInput|null $in A ConsoleInput object for stdin. <ide> * @param \Cake\Console\HelperRegistry|null $helpers A HelperRegistry instance <ide> */ <del> public function __construct(ConsoleOutput $out = null, ConsoleOutput $err = null, ConsoleInput $in = null, HelperRegistry $helpers = null) <add> public function __construct(?ConsoleOutput $out = null, ?ConsoleOutput $err = null, ?ConsoleInput $in = null, ?HelperRegistry $helpers = null) <ide> { <ide> $this->_out = $out ?: new ConsoleOutput('php://stdout'); <ide> $this->_err = $err ?: new ConsoleOutput('php://stderr'); <ide> public function setLoggers($enable) <ide> if ($enable !== static::QUIET) { <ide> $stdout = new ConsoleLog([ <ide> 'types' => $outLevels, <del> 'stream' => $this->_out <add> 'stream' => $this->_out, <ide> ]); <ide> Log::setConfig('stdout', ['engine' => $stdout]); <ide> } <ide><path>src/Console/ConsoleOptionParser.php <ide> */ <ide> class ConsoleOptionParser <ide> { <del> <ide> /** <ide> * Description text - displays before options when help is generated <ide> * <ide> public function __construct($command = null, $defaultOptions = true) <ide> $this->addOption('help', [ <ide> 'short' => 'h', <ide> 'help' => 'Display this help.', <del> 'boolean' => true <add> 'boolean' => true, <ide> ]); <ide> <ide> if ($defaultOptions) { <ide> $this->addOption('verbose', [ <ide> 'short' => 'v', <ide> 'help' => 'Enable verbose output.', <del> 'boolean' => true <add> 'boolean' => true, <ide> ])->addOption('quiet', [ <ide> 'short' => 'q', <ide> 'help' => 'Enable quiet output.', <del> 'boolean' => true <add> 'boolean' => true, <ide> ]); <ide> } <ide> } <ide> public function toArray() <ide> 'options' => $this->_options, <ide> 'subcommands' => $this->_subcommands, <ide> 'description' => $this->_description, <del> 'epilog' => $this->_epilog <add> 'epilog' => $this->_epilog, <ide> ]; <ide> <ide> return $result; <ide> public function addOption($name, array $options = []) <ide> 'help' => '', <ide> 'default' => null, <ide> 'boolean' => false, <del> 'choices' => [] <add> 'choices' => [], <ide> ]; <ide> $options += $defaults; <ide> $option = new ConsoleInputOption($options); <ide> public function addArgument($name, array $params = []) <ide> 'help' => '', <ide> 'index' => count($this->_args), <ide> 'required' => false, <del> 'choices' => [] <add> 'choices' => [], <ide> ]; <ide> $options = $params + $defaults; <ide> $index = $options['index']; <ide> public function addSubcommand($name, array $options = []) <ide> $defaults = [ <ide> 'name' => $name, <ide> 'help' => '', <del> 'parser' => null <add> 'parser' => null, <ide> ]; <ide> $options += $defaults; <ide> <ide> protected function getCommandError($command) <ide> $this->rootName, <ide> $rootCommand <ide> ), <del> '' <add> '', <ide> ]; <ide> <ide> if ($bestGuess !== null) { <ide> protected function getOptionError($option) <ide> $bestGuess = $this->findClosestItem($option, $availableOptions); <ide> $out = [ <ide> sprintf('Unknown option `%s`.', $option), <del> '' <add> '', <ide> ]; <ide> <ide> if ($bestGuess !== null) { <ide> protected function _parseArg($argument, $args) <ide> */ <ide> protected function _nextToken() <ide> { <del> return isset($this->_tokens[0]) ? $this->_tokens[0] : ''; <add> return $this->_tokens[0] ?? ''; <ide> } <ide> } <ide><path>src/Console/ConsoleOutput.php <ide> */ <ide> class ConsoleOutput <ide> { <del> <ide> /** <ide> * Raw output constant - no modification of output text. <ide> * <ide> * @var int <ide> */ <del> const RAW = 0; <add> public const RAW = 0; <ide> <ide> /** <ide> * Plain output - tags will be stripped. <ide> * <ide> * @var int <ide> */ <del> const PLAIN = 1; <add> public const PLAIN = 1; <ide> <ide> /** <ide> * Color output - Convert known tags in to ANSI color escape codes. <ide> * <ide> * @var int <ide> */ <del> const COLOR = 2; <add> public const COLOR = 2; <ide> <ide> /** <ide> * Constant for a newline. <ide> * <ide> * @var string <ide> */ <del> const LF = PHP_EOL; <add> public const LF = PHP_EOL; <ide> <ide> /** <ide> * File handle for output. <ide> class ConsoleOutput <ide> 'blue' => 34, <ide> 'magenta' => 35, <ide> 'cyan' => 36, <del> 'white' => 37 <add> 'white' => 37, <ide> ]; <ide> <ide> /** <ide> class ConsoleOutput <ide> 'blue' => 44, <ide> 'magenta' => 45, <ide> 'cyan' => 46, <del> 'white' => 47 <add> 'white' => 47, <ide> ]; <ide> <ide> /** <ide> class ConsoleOutput <ide> 'success' => ['text' => 'green'], <ide> 'comment' => ['text' => 'blue'], <ide> 'question' => ['text' => 'magenta'], <del> 'notice' => ['text' => 'cyan'] <add> 'notice' => ['text' => 'cyan'], <ide> ]; <ide> <ide> /** <ide> public function write($message, $newlines = 1) <ide> */ <ide> public function styleText($text) <ide> { <del> if ($this->_outputAs == static::RAW) { <add> if ($this->_outputAs === static::RAW) { <ide> return $text; <ide> } <del> if ($this->_outputAs == static::PLAIN) { <add> if ($this->_outputAs === static::PLAIN) { <ide> $tags = implode('|', array_keys(static::$_styles)); <ide> <ide> return preg_replace('#</?(?:' . $tags . ')>#', '', $text); <ide> public function styles($style = null, $definition = null) <ide> return static::$_styles; <ide> } <ide> if (is_string($style) && $definition === null) { <del> return isset(static::$_styles[$style]) ? static::$_styles[$style] : null; <add> return static::$_styles[$style] ?? null; <ide> } <ide> if ($definition === false) { <ide> unset(static::$_styles[$style]); <ide><path>src/Console/Exception/MissingHelperException.php <ide> */ <ide> class MissingHelperException extends Exception <ide> { <del> <ide> protected $_messageTemplate = 'Helper class %s could not be found.'; <ide> } <ide><path>src/Console/Exception/MissingShellException.php <ide> */ <ide> class MissingShellException extends Exception <ide> { <del> <ide> protected $_messageTemplate = 'Shell class for "%s" could not be found. If you are trying to use a plugin shell, that was loaded via $this->addPlugin(), you may need to update bin/cake.php to match https://github.com/cakephp/app/tree/master/bin/cake.php'; <ide> } <ide><path>src/Console/Exception/MissingShellMethodException.php <ide> */ <ide> class MissingShellMethodException extends Exception <ide> { <del> <ide> protected $_messageTemplate = "Unknown command %1\$s %2\$s.\nFor usage try `cake %1\$s --help`"; <ide> } <ide><path>src/Console/Exception/MissingTaskException.php <ide> */ <ide> class MissingTaskException extends Exception <ide> { <del> <ide> protected $_messageTemplate = 'Task class %s could not be found.'; <ide> } <ide><path>src/Console/HelpFormatter.php <ide> */ <ide> class HelpFormatter <ide> { <del> <ide> /** <ide> * The maximum number of arguments shown when generating usage. <ide> * <ide> public function text($width = 72) <ide> $out[] = Text::wrapBlock($command->help($max), [ <ide> 'width' => $width, <ide> 'indent' => str_repeat(' ', $max), <del> 'indentAt' => 1 <add> 'indentAt' => 1, <ide> ]); <ide> } <ide> $out[] = ''; <ide> public function text($width = 72) <ide> $out[] = Text::wrapBlock($option->help($max), [ <ide> 'width' => $width, <ide> 'indent' => str_repeat(' ', $max), <del> 'indentAt' => 1 <add> 'indentAt' => 1, <ide> ]); <ide> } <ide> $out[] = ''; <ide> public function text($width = 72) <ide> $out[] = Text::wrapBlock($argument->help($max), [ <ide> 'width' => $width, <ide> 'indent' => str_repeat(' ', $max), <del> 'indentAt' => 1 <add> 'indentAt' => 1, <ide> ]); <ide> } <ide> $out[] = ''; <ide><path>src/Console/HelperRegistry.php <ide> */ <ide> class HelperRegistry extends ObjectRegistry <ide> { <del> <ide> /** <ide> * Shell to use to set params to tasks. <ide> * <ide> protected function _throwMissingClassError($class, $plugin) <ide> { <ide> throw new MissingHelperException([ <ide> 'class' => $class, <del> 'plugin' => $plugin <add> 'plugin' => $plugin, <ide> ]); <ide> } <ide> <ide><path>src/Console/Shell.php <ide> */ <ide> class Shell <ide> { <del> <ide> use LocatorAwareTrait; <ide> use LogTrait; <ide> use MergeVariablesTrait; <ide> class Shell <ide> * <ide> * @var int <ide> */ <del> const CODE_ERROR = 1; <add> public const CODE_ERROR = 1; <ide> <ide> /** <ide> * Default success code <ide> * <ide> * @var int <ide> */ <del> const CODE_SUCCESS = 0; <add> public const CODE_SUCCESS = 0; <ide> <ide> /** <ide> * Output constant making verbose shells. <ide> * <ide> * @var int <ide> */ <del> const VERBOSE = ConsoleIo::VERBOSE; <add> public const VERBOSE = ConsoleIo::VERBOSE; <ide> <ide> /** <ide> * Output constant for making normal shells. <ide> * <ide> * @var int <ide> */ <del> const NORMAL = ConsoleIo::NORMAL; <add> public const NORMAL = ConsoleIo::NORMAL; <ide> <ide> /** <ide> * Output constants for making quiet shells. <ide> * <ide> * @var int <ide> */ <del> const QUIET = ConsoleIo::QUIET; <add> public const QUIET = ConsoleIo::QUIET; <ide> <ide> /** <ide> * An instance of ConsoleOptionParser that has been configured for this class. <ide> class Shell <ide> * @param \Cake\ORM\Locator\LocatorInterface|null $locator Table locator instance. <ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#Shell <ide> */ <del> public function __construct(ConsoleIo $io = null, LocatorInterface $locator = null) <add> public function __construct(?ConsoleIo $io = null, ?LocatorInterface $locator = null) <ide> { <ide> if (!$this->name) { <ide> list(, $class) = namespaceSplit(get_class($this)); <ide><path>src/Console/ShellDispatcher.php <ide> */ <ide> class ShellDispatcher <ide> { <del> <ide> /** <ide> * Contains arguments parsed from the command line. <ide> * <ide> public static function alias($short, $original = null) <ide> static::$_aliases[$short] = $original; <ide> } <ide> <del> return isset(static::$_aliases[$short]) ? static::$_aliases[$short] : false; <add> return static::$_aliases[$short] ?? false; <ide> } <ide> <ide> /** <ide><path>src/Console/TaskRegistry.php <ide> */ <ide> class TaskRegistry extends ObjectRegistry <ide> { <del> <ide> /** <ide> * Shell to use to set params to tasks. <ide> * <ide> protected function _throwMissingClassError($class, $plugin) <ide> { <ide> throw new MissingTaskException([ <ide> 'class' => $class, <del> 'plugin' => $plugin <add> 'plugin' => $plugin, <ide> ]); <ide> } <ide> <ide><path>src/Controller/Component.php <ide> */ <ide> class Component implements EventListenerInterface <ide> { <del> <ide> use InstanceConfigTrait; <ide> use LogTrait; <ide> <ide><path>src/Controller/Component/AuthComponent.php <ide> */ <ide> class AuthComponent extends Component <ide> { <del> <ide> use EventDispatcherTrait; <ide> <ide> /** <ide> * The query string key used for remembering the referrered page when getting <ide> * redirected to login. <ide> */ <del> const QUERY_STRING_REDIRECT = 'redirect'; <add> public const QUERY_STRING_REDIRECT = 'redirect'; <ide> <ide> /** <ide> * Constant for 'all' <ide> * <ide> * @var string <ide> */ <del> const ALL = 'all'; <add> public const ALL = 'all'; <ide> <ide> /** <ide> * Default config <ide> class AuthComponent extends Component <ide> 'authError' => null, <ide> 'unauthorizedRedirect' => true, <ide> 'storage' => 'Session', <del> 'checkAuthIn' => 'Controller.startup' <add> 'checkAuthIn' => 'Controller.startup', <ide> ]; <ide> <ide> /** <ide> protected function _setDefaults() <ide> 'flash' => [ <ide> 'element' => 'error', <ide> 'key' => 'flash', <del> 'params' => ['class' => 'error'] <add> 'params' => ['class' => 'error'], <ide> ], <ide> 'loginAction' => [ <ide> 'controller' => 'Users', <ide> 'action' => 'login', <del> 'plugin' => null <add> 'plugin' => null, <ide> ], <ide> 'logoutRedirect' => $this->_config['loginAction'], <del> 'authError' => __d('cake', 'You are not authorized to access that location.') <add> 'authError' => __d('cake', 'You are not authorized to access that location.'), <ide> ]; <ide> <ide> $config = $this->getConfig(); <ide> protected function _setDefaults() <ide> * If empty, the current request will be used. <ide> * @return bool True if $user is authorized, otherwise false <ide> */ <del> public function isAuthorized($user = null, ServerRequest $request = null) <add> public function isAuthorized($user = null, ?ServerRequest $request = null) <ide> { <ide> if (empty($user) && !$this->user()) { <ide> return false; <ide> public function getAuthorize($alias) <ide> $this->constructAuthorize(); <ide> } <ide> <del> return isset($this->_authorizeObjects[$alias]) ? $this->_authorizeObjects[$alias] : null; <add> return $this->_authorizeObjects[$alias] ?? null; <ide> } <ide> <ide> /** <ide> public function constructAuthenticate() <ide> * object as storage or if null returns configured storage object. <ide> * @return \Cake\Auth\Storage\StorageInterface|\Cake\Core\InstanceConfigTrait|null <ide> */ <del> public function storage(StorageInterface $storage = null) <add> public function storage(?StorageInterface $storage = null) <ide> { <ide> if ($storage !== null) { <ide> $this->_storage = $storage; <ide> public function getAuthenticate($alias) <ide> $this->constructAuthenticate(); <ide> } <ide> <del> return isset($this->_authenticateObjects[$alias]) ? $this->_authenticateObjects[$alias] : null; <add> return $this->_authenticateObjects[$alias] ?? null; <ide> } <ide> <ide> /** <ide><path>src/Controller/Component/FlashComponent.php <ide> */ <ide> class FlashComponent extends Component <ide> { <del> <ide> /** <ide> * The Session object instance <ide> * <ide> class FlashComponent extends Component <ide> 'element' => 'default', <ide> 'params' => [], <ide> 'clear' => false, <del> 'duplicate' => true <add> 'duplicate' => true, <ide> ]; <ide> <ide> /** <ide> public function set($message, array $options = []) <ide> 'message' => $message, <ide> 'key' => $options['key'], <ide> 'element' => $options['element'], <del> 'params' => $options['params'] <add> 'params' => $options['params'], <ide> ]; <ide> <ide> $this->_session->write('Flash.' . $options['key'], $messages); <ide><path>src/Controller/Component/PaginatorComponent.php <ide> */ <ide> class PaginatorComponent extends Component <ide> { <del> <ide> /** <ide> * Default pagination settings. <ide> * <ide> class PaginatorComponent extends Component <ide> 'page' => 1, <ide> 'limit' => 20, <ide> 'maxLimit' => 100, <del> 'whitelist' => ['limit', 'sort', 'page', 'direction'] <add> 'whitelist' => ['limit', 'sort', 'page', 'direction'], <ide> ]; <ide> <ide> /** <ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> 'viewClassMap' => [ <ide> 'json' => 'Json', <ide> 'xml' => 'Xml', <del> 'ajax' => 'Ajax' <add> 'ajax' => 'Ajax', <ide> ], <ide> 'inputTypeMap' => [ <ide> 'json' => ['json_decode', true], <ide> 'xml' => [[$this, 'convertXml']], <del> ] <add> ], <ide> ]; <ide> parent::__construct($registry, $config); <ide> } <ide> public function requestedWith($type = null) <ide> return $response->mapType($contentType); <ide> } <ide> if (is_string($type)) { <del> return ($type === $response->mapType($contentType)); <add> return $type === $response->mapType($contentType); <ide> } <ide> } <ide> <ide><path>src/Controller/Component/SecurityComponent.php <ide> */ <ide> class SecurityComponent extends Component <ide> { <del> <ide> /** <ide> * Default message used for exceptions thrown <ide> */ <del> const DEFAULT_EXCEPTION_MESSAGE = 'The request has been black-holed'; <add> public const DEFAULT_EXCEPTION_MESSAGE = 'The request has been black-holed'; <ide> <ide> /** <ide> * Default config <ide> class SecurityComponent extends Component <ide> 'allowedActions' => [], <ide> 'unlockedFields' => [], <ide> 'unlockedActions' => [], <del> 'validatePost' => true <add> 'validatePost' => true, <ide> ]; <ide> <ide> /** <ide> public function requireSecure($actions = null) <ide> * @link https://book.cakephp.org/3.0/en/controllers/components/security.html#handling-blackhole-callbacks <ide> * @throws \Cake\Http\Exception\BadRequestException <ide> */ <del> public function blackHole(Controller $controller, $error = '', SecurityException $exception = null) <add> public function blackHole(Controller $controller, $error = '', ?SecurityException $exception = null) <ide> { <ide> if (!$this->_config['blackHoleCallback']) { <ide> $this->_throwException($exception); <ide> protected function _hashParts(Controller $controller) <ide> Router::url($request->getRequestTarget()), <ide> serialize($fieldList), <ide> $unlocked, <del> $session->id() <add> $session->id(), <ide> ]; <ide> } <ide> <ide> public function generateToken(ServerRequest $request) <ide> $request->getSession()->write('_Token', $token); <ide> <ide> return $request->withParam('_Token', [ <del> 'unlockedFields' => $token['unlockedFields'] <add> 'unlockedFields' => $token['unlockedFields'], <ide> ]); <ide> } <ide> <ide><path>src/Controller/ComponentRegistry.php <ide> */ <ide> class ComponentRegistry extends ObjectRegistry implements EventDispatcherInterface <ide> { <del> <ide> use EventDispatcherTrait; <ide> <ide> /** <ide> class ComponentRegistry extends ObjectRegistry implements EventDispatcherInterfa <ide> * <ide> * @param \Cake\Controller\Controller|null $controller Controller instance. <ide> */ <del> public function __construct(Controller $controller = null) <add> public function __construct(?Controller $controller = null) <ide> { <ide> if ($controller) { <ide> $this->setController($controller); <ide> protected function _throwMissingClassError($class, $plugin) <ide> { <ide> throw new MissingComponentException([ <ide> 'class' => $class . 'Component', <del> 'plugin' => $plugin <add> 'plugin' => $plugin, <ide> ]); <ide> } <ide> <ide> protected function _throwMissingClassError($class, $plugin) <ide> protected function _create($class, $alias, $config) <ide> { <ide> $instance = new $class($this, $config); <del> $enable = isset($config['enabled']) ? $config['enabled'] : true; <add> $enable = $config['enabled'] ?? true; <ide> if ($enable) { <ide> $this->getEventManager()->on($instance); <ide> } <ide><path>src/Controller/Controller.php <ide> */ <ide> class Controller implements EventListenerInterface, EventDispatcherInterface <ide> { <del> <ide> use EventDispatcherTrait; <ide> use LocatorAwareTrait; <ide> use LogTrait; <ide> class Controller implements EventListenerInterface, EventDispatcherInterface <ide> * @param \Cake\Event\EventManager|null $eventManager The event manager. Defaults to a new instance. <ide> * @param \Cake\Controller\ComponentRegistry|null $components The component registry. Defaults to a new instance. <ide> */ <del> public function __construct(ServerRequest $request = null, Response $response = null, $name = null, $eventManager = null, $components = null) <add> public function __construct(?ServerRequest $request = null, ?Response $response = null, $name = null, $eventManager = null, $components = null) <ide> { <ide> if ($name !== null) { <ide> $this->name = $name; <ide><path>src/Controller/ErrorController.php <ide> */ <ide> class ErrorController extends Controller <ide> { <del> <ide> /** <ide> * Initialization hook method. <ide> * <ide><path>src/Controller/Exception/MissingActionException.php <ide> */ <ide> class MissingActionException extends Exception <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Controller/Exception/MissingComponentException.php <ide> */ <ide> class MissingComponentException extends Exception <ide> { <del> <ide> protected $_messageTemplate = 'Component class %s could not be found.'; <ide> } <ide><path>src/Core/App.php <ide> */ <ide> class App <ide> { <del> <ide> /** <ide> * Return the class name namespaced. This method checks if the class is defined on the <ide> * application/plugin, otherwise try to load from the CakePHP core <ide> public static function shortName($class, $type, $suffix = '') <ide> <ide> $nonPluginNamespaces = [ <ide> 'Cake', <del> str_replace('\\', '/', Configure::read('App.namespace')) <add> str_replace('\\', '/', Configure::read('App.namespace')), <ide> ]; <ide> if (in_array($pluginName, $nonPluginNamespaces)) { <ide> return $name; <ide><path>src/Core/BasePlugin.php <ide> */ <ide> class BasePlugin implements PluginInterface <ide> { <del> <ide> /** <ide> * Do bootstrapping or not <ide> * <ide><path>src/Core/ClassLoader.php <ide> */ <ide> class ClassLoader <ide> { <del> <ide> /** <ide> * An associative array where the key is a namespace prefix and the value <ide> * is an array of base directories for classes in that namespace. <ide><path>src/Core/Configure.php <ide> */ <ide> class Configure <ide> { <del> <ide> /** <ide> * Array of values currently stored in Configure. <ide> * <ide> * @var array <ide> */ <ide> protected static $_values = [ <del> 'debug' => false <add> 'debug' => false, <ide> ]; <ide> <ide> /** <ide><path>src/Core/Configure/ConfigEngineInterface.php <ide> */ <ide> interface ConfigEngineInterface <ide> { <del> <ide> /** <ide> * Read a configuration file/storage key <ide> * <ide><path>src/Core/Configure/Engine/IniConfig.php <ide> */ <ide> class IniConfig implements ConfigEngineInterface <ide> { <del> <ide> use FileConfigTrait; <ide> <ide> /** <ide><path>src/Core/Configure/Engine/JsonConfig.php <ide> */ <ide> class JsonConfig implements ConfigEngineInterface <ide> { <del> <ide> use FileConfigTrait; <ide> <ide> /** <ide><path>src/Core/Configure/Engine/PhpConfig.php <ide> */ <ide> class PhpConfig implements ConfigEngineInterface <ide> { <del> <ide> use FileConfigTrait; <ide> <ide> /** <ide><path>src/Core/Configure/FileConfigTrait.php <ide> */ <ide> trait FileConfigTrait <ide> { <del> <ide> /** <ide> * The path this engine finds files on. <ide> * <ide><path>src/Core/ConventionsTrait.php <ide> */ <ide> trait ConventionsTrait <ide> { <del> <ide> /** <ide> * Creates a fixture name <ide> * <ide><path>src/Core/Exception/Exception.php <ide> */ <ide> class Exception extends RuntimeException <ide> { <del> <ide> /** <ide> * Array of attributes that are passed in from the constructor, and <ide> * made available in the view when a development error is displayed. <ide><path>src/Core/Exception/MissingPluginException.php <ide> */ <ide> class MissingPluginException extends Exception <ide> { <del> <ide> protected $_messageTemplate = 'Plugin %s could not be found.'; <ide> } <ide><path>src/Core/InstanceConfigTrait.php <ide> */ <ide> trait InstanceConfigTrait <ide> { <del> <ide> /** <ide> * Runtime config <ide> * <ide> protected function _configRead($key) <ide> } <ide> <ide> if (strpos($key, '.') === false) { <del> return isset($this->_config[$key]) ? $this->_config[$key] : null; <add> return $this->_config[$key] ?? null; <ide> } <ide> <ide> $return = $this->_config; <ide><path>src/Core/ObjectRegistry.php <ide> */ <ide> abstract class ObjectRegistry implements Countable, IteratorAggregate <ide> { <del> <ide> /** <ide> * Map of loaded objects. <ide> * <ide><path>src/Core/Plugin.php <ide> */ <ide> class Plugin <ide> { <del> <ide> /** <ide> * Holds a list of all loaded plugins and their configuration <ide> * <ide> public static function load($plugin, array $config = []) <ide> 'routes' => false, <ide> 'console' => true, <ide> 'classBase' => 'src', <del> 'name' => $plugin <add> 'name' => $plugin, <ide> ]; <ide> <ide> if (!isset($config['path'])) { <ide> public static function loadAll(array $options = []) <ide> <ide> $collection = static::getCollection(); <ide> foreach ($plugins as $p) { <del> $opts = isset($options[$p]) ? $options[$p] : null; <add> $opts = $options[$p] ?? null; <ide> if ($opts === null && isset($options[0])) { <ide> $opts = $options[0]; <ide> } <ide><path>src/Core/PluginInterface.php <ide> interface PluginInterface <ide> /** <ide> * List of valid hooks. <ide> */ <del> const VALID_HOOKS = ['routes', 'bootstrap', 'console', 'middleware']; <add> public const VALID_HOOKS = ['routes', 'bootstrap', 'console', 'middleware']; <ide> <ide> /** <ide> * Get the name of this plugin. <ide><path>src/Core/Retry/CommandRetry.php <ide> */ <ide> class CommandRetry <ide> { <del> <ide> /** <ide> * The strategy to follow should the executed action fail. <ide> * <ide><path>src/Core/StaticConfigTrait.php <ide> */ <ide> trait StaticConfigTrait <ide> { <del> <ide> /** <ide> * Configuration sets. <ide> * <ide> public static function setConfig($key, $config = null) <ide> */ <ide> public static function getConfig($key) <ide> { <del> return isset(static::$_config[$key]) ? static::$_config[$key] : null; <add> return static::$_config[$key] ?? null; <ide> } <ide> <ide> /** <ide><path>src/Core/functions.php <ide> function env($key, $default = null) <ide> { <ide> if ($key === 'HTTPS') { <ide> if (isset($_SERVER['HTTPS'])) { <del> return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'); <add> return !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'; <ide> } <ide> <del> return (strpos((string)env('SCRIPT_URI'), 'https://') === 0); <add> return strpos((string)env('SCRIPT_URI'), 'https://') === 0; <ide> } <ide> <ide> if ($key === 'SCRIPT_NAME') { <ide> function env($key, $default = null) <ide> case 'PHP_SELF': <ide> return str_replace(env('DOCUMENT_ROOT'), '', env('SCRIPT_FILENAME')); <ide> case 'CGI_MODE': <del> return (PHP_SAPI === 'cgi'); <add> return PHP_SAPI === 'cgi'; <ide> } <ide> <ide> return $default; <ide><path>src/Database/Connection.php <ide> */ <ide> class Connection implements ConnectionInterface <ide> { <del> <ide> use TypeConverterTrait; <ide> <ide> /** <ide> public function __debugInfo() <ide> 'username' => '*****', <ide> 'host' => '*****', <ide> 'database' => '*****', <del> 'port' => '*****' <add> 'port' => '*****', <ide> ]; <ide> $replace = array_intersect_key($secrets, $this->_config); <ide> $config = $replace + $this->_config; <ide> public function __debugInfo() <ide> 'transactionStarted' => $this->_transactionStarted, <ide> 'useSavePoints' => $this->_useSavePoints, <ide> 'logQueries' => $this->_logQueries, <del> 'logger' => $this->_logger <add> 'logger' => $this->_logger, <ide> ]; <ide> } <ide> } <ide><path>src/Database/Dialect/MysqlDialectTrait.php <ide> */ <ide> trait MysqlDialectTrait <ide> { <del> <ide> use SqlDialectTrait; <ide> <ide> /** <ide><path>src/Database/Dialect/PostgresDialectTrait.php <ide> */ <ide> trait PostgresDialectTrait <ide> { <del> <ide> use SqlDialectTrait; <ide> <ide> /** <ide> protected function _expressionTranslators() <ide> $namespace = 'Cake\Database\Expression'; <ide> <ide> return [ <del> $namespace . '\FunctionExpression' => '_transformFunctionExpression' <add> $namespace . '\FunctionExpression' => '_transformFunctionExpression', <ide> ]; <ide> } <ide> <ide><path>src/Database/Dialect/SqliteDialectTrait.php <ide> */ <ide> trait SqliteDialectTrait <ide> { <del> <ide> use SqlDialectTrait; <ide> use TupleComparisonTranslatorTrait; <ide> <ide> trait SqliteDialectTrait <ide> 'minute' => 'M', <ide> 'second' => 'S', <ide> 'week' => 'W', <del> 'year' => 'Y' <add> 'year' => 'Y', <ide> ]; <ide> <ide> /** <ide> protected function _expressionTranslators() <ide> <ide> return [ <ide> $namespace . '\FunctionExpression' => '_transformFunctionExpression', <del> $namespace . '\TupleComparison' => '_transformTupleComparison' <add> $namespace . '\TupleComparison' => '_transformTupleComparison', <ide> ]; <ide> } <ide> <ide><path>src/Database/Dialect/SqlserverDialectTrait.php <ide> */ <ide> namespace Cake\Database\Dialect; <ide> <del>use Cake\Database\ExpressionInterface; <ide> use Cake\Database\Expression\FunctionExpression; <ide> use Cake\Database\Expression\OrderByExpression; <ide> use Cake\Database\Expression\UnaryExpression; <add>use Cake\Database\ExpressionInterface; <ide> use Cake\Database\Query; <ide> use Cake\Database\Schema\SqlserverSchema; <ide> use Cake\Database\SqlDialectTrait; <ide> */ <ide> trait SqlserverDialectTrait <ide> { <del> <ide> use SqlDialectTrait; <ide> use TupleComparisonTranslatorTrait; <ide> <ide> protected function _pagingSubquery($original, $limit, $offset) <ide> <ide> $query = clone $original; <ide> $query->select([ <del> '_cake_page_rownum_' => new UnaryExpression('ROW_NUMBER() OVER', $order) <add> '_cake_page_rownum_' => new UnaryExpression('ROW_NUMBER() OVER', $order), <ide> ])->limit(null) <ide> ->offset(null) <ide> ->order([], true); <ide> protected function _transformDistinct($original) <ide> ->setConjunction(' '); <ide> <ide> return [ <del> '_cake_distinct_pivot_' => $over <add> '_cake_distinct_pivot_' => $over, <ide> ]; <ide> }) <ide> ->limit(null) <ide> protected function _expressionTranslators() <ide> <ide> return [ <ide> $namespace . '\FunctionExpression' => '_transformFunctionExpression', <del> $namespace . '\TupleComparison' => '_transformTupleComparison' <add> $namespace . '\TupleComparison' => '_transformTupleComparison', <ide> ]; <ide> } <ide> <ide><path>src/Database/Dialect/TupleComparisonTranslatorTrait.php <ide> */ <ide> trait TupleComparisonTranslatorTrait <ide> { <del> <ide> /** <ide> * Receives a TupleExpression and changes it so that it conforms to this <ide> * SQL dialect. <ide><path>src/Database/Driver.php <ide> */ <ide> namespace Cake\Database; <ide> <del>use Cake\Database\Query; <ide> use Cake\Database\Statement\PDOStatement; <ide> use InvalidArgumentException; <ide> use PDO; <ide> public function __destruct() <ide> public function __debugInfo() <ide> { <ide> return [ <del> 'connected' => $this->_connection !== null <add> 'connected' => $this->_connection !== null, <ide> ]; <ide> } <ide> } <ide><path>src/Database/Driver/Mysql.php <ide> */ <ide> class Mysql extends Driver <ide> { <del> <ide> use MysqlDialectTrait; <ide> <ide> /** <ide><path>src/Database/Driver/Postgres.php <ide> */ <ide> class Postgres extends Driver <ide> { <del> <ide> use PostgresDialectTrait; <ide> <ide> /** <ide> public function connect() <ide> $config['flags'] += [ <ide> PDO::ATTR_PERSISTENT => $config['persistent'], <ide> PDO::ATTR_EMULATE_PREPARES => false, <del> PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION <add> PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, <ide> ]; <ide> if (empty($config['unix_socket'])) { <ide> $dsn = "pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']}"; <ide><path>src/Database/Driver/Sqlite.php <ide> */ <ide> class Sqlite extends Driver <ide> { <del> <ide> use SqliteDialectTrait; <ide> <ide> /** <ide> public function connect() <ide> $config['flags'] += [ <ide> PDO::ATTR_PERSISTENT => $config['persistent'], <ide> PDO::ATTR_EMULATE_PREPARES => false, <del> PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION <add> PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, <ide> ]; <ide> <ide> $databaseExists = file_exists($config['database']); <ide> <ide> $dsn = "sqlite:{$config['database']}"; <ide> $this->_connect($dsn, $config); <ide> <del> if (!$databaseExists && $config['database'] != ':memory:') { <add> if (!$databaseExists && $config['database'] !== ':memory:') { <ide> //@codingStandardsIgnoreStart <ide> @chmod($config['database'], $config['mask']); <ide> //@codingStandardsIgnoreEnd <ide><path>src/Database/Driver/Sqlserver.php <ide> */ <ide> class Sqlserver extends Driver <ide> { <del> <ide> use SqlserverDialectTrait; <ide> <ide> /** <ide> public function connect() <ide> <ide> $config['flags'] += [ <ide> PDO::ATTR_EMULATE_PREPARES => false, <del> PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION <add> PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, <ide> ]; <ide> <ide> if (!empty($config['encoding'])) { <ide><path>src/Database/DriverInterface.php <ide> */ <ide> namespace Cake\Database; <ide> <del>use Cake\Database\Query; <del> <ide> /** <ide> * Interface for database driver. <ide> */ <ide><path>src/Database/Exception.php <ide> */ <ide> class Exception extends CakeException <ide> { <del> <ide> } <ide><path>src/Database/Exception/MissingConnectionException.php <ide> */ <ide> class MissingConnectionException extends Exception <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Database/Exception/MissingDriverException.php <ide> */ <ide> class MissingDriverException extends Exception <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Database/Exception/MissingExtensionException.php <ide> */ <ide> class MissingExtensionException extends Exception <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Database/Exception/NestedTransactionRollbackException.php <ide> */ <ide> class NestedTransactionRollbackException extends Exception <ide> { <del> <ide> /** <ide> * Constructor <ide> * <ide><path>src/Database/Expression/BetweenExpression.php <ide> */ <ide> class BetweenExpression implements ExpressionInterface, FieldInterface <ide> { <del> <ide> use ExpressionTypeCasterTrait; <ide> use FieldTrait; <ide> <ide> public function sql(ValueBinder $generator) <ide> { <ide> $parts = [ <ide> 'from' => $this->_from, <del> 'to' => $this->_to <add> 'to' => $this->_to, <ide> ]; <ide> <ide> $field = $this->_field; <ide><path>src/Database/Expression/CaseExpression.php <ide> */ <ide> class CaseExpression implements ExpressionInterface <ide> { <del> <ide> use ExpressionTypeCasterTrait; <ide> <ide> /** <ide> public function __construct($conditions = [], $values = [], $types = []) <ide> if (is_array($conditions) && is_array($values) && count($values) > count($conditions)) { <ide> end($values); <ide> $key = key($values); <del> $this->elseValue($values[$key], isset($types[$key]) ? $types[$key] : null); <add> $this->elseValue($values[$key], $types[$key] ?? null); <ide> } <ide> } <ide> <ide> protected function _addExpressions($conditions, $values, $types) <ide> } <ide> <ide> $this->_conditions[] = $c; <del> $value = isset($rawValues[$k]) ? $rawValues[$k] : 1; <add> $value = $rawValues[$k] ?? 1; <ide> <ide> if ($value === 'literal') { <ide> $value = $keyValues[$k]; <ide> protected function _addExpressions($conditions, $values, $types) <ide> continue; <ide> } <ide> <del> $type = isset($types[$k]) ? $types[$k] : null; <add> $type = $types[$k] ?? null; <ide> <ide> if ($type !== null && !$value instanceof ExpressionInterface) { <ide> $value = $this->_castToExpression($value, $type); <ide><path>src/Database/Expression/Comparison.php <ide> */ <ide> class Comparison implements ExpressionInterface, FieldInterface <ide> { <del> <ide> use ExpressionTypeCasterTrait; <ide> use FieldTrait; <ide> <ide><path>src/Database/Expression/FieldInterface.php <ide> */ <ide> interface FieldInterface <ide> { <del> <ide> /** <ide> * Sets the field name <ide> * <ide><path>src/Database/Expression/FieldTrait.php <ide> */ <ide> trait FieldTrait <ide> { <del> <ide> /** <ide> * The field name or expression to be used in the left hand side of the operator <ide> * <ide><path>src/Database/Expression/FunctionExpression.php <ide> namespace Cake\Database\Expression; <ide> <ide> use Cake\Database\ExpressionInterface; <add>use Cake\Database\Type\ExpressionTypeCasterTrait; <ide> use Cake\Database\TypedResultInterface; <ide> use Cake\Database\TypedResultTrait; <del>use Cake\Database\Type\ExpressionTypeCasterTrait; <ide> use Cake\Database\ValueBinder; <ide> <ide> /** <ide> */ <ide> class FunctionExpression extends QueryExpression implements TypedResultInterface <ide> { <del> <ide> use ExpressionTypeCasterTrait; <ide> use TypedResultTrait; <ide> <ide><path>src/Database/Expression/IdentifierExpression.php <ide> */ <ide> class IdentifierExpression implements ExpressionInterface <ide> { <del> <ide> /** <ide> * Holds the identifier string <ide> * <ide><path>src/Database/Expression/OrderByExpression.php <ide> */ <ide> class OrderByExpression extends QueryExpression <ide> { <del> <ide> /** <ide> * Constructor <ide> * <ide><path>src/Database/Expression/QueryExpression.php <ide> */ <ide> class QueryExpression implements ExpressionInterface, Countable <ide> { <del> <ide> use TypeMapTrait; <ide> <ide> /** <ide><path>src/Database/Expression/TupleComparison.php <ide> */ <ide> class TupleComparison extends Comparison <ide> { <del> <ide> /** <ide> * Constructor <ide> * <ide> protected function _stringifyValues($generator) <ide> continue; <ide> } <ide> <del> $valType = $multiType && isset($type[$i]) ? $type[$i] : $type; <add> $valType = $multiType && $type[$i] ?? $type; <ide> $values[] = $this->_bindValue($generator, $value, $valType); <ide> } <ide> <ide><path>src/Database/Expression/UnaryExpression.php <ide> */ <ide> class UnaryExpression implements ExpressionInterface <ide> { <del> <ide> /** <ide> * Indicates that the operation is in pre-order <ide> * <ide> */ <del> const PREFIX = 0; <add> public const PREFIX = 0; <ide> <ide> /** <ide> * Indicates that the operation is in post-order <ide> * <ide> */ <del> const POSTFIX = 1; <add> public const POSTFIX = 1; <ide> <ide> /** <ide> * The operator this unary expression represents <ide><path>src/Database/Expression/ValuesExpression.php <ide> use Cake\Database\Exception; <ide> use Cake\Database\ExpressionInterface; <ide> use Cake\Database\Query; <del>use Cake\Database\TypeMapTrait; <ide> use Cake\Database\Type\ExpressionTypeCasterTrait; <add>use Cake\Database\TypeMapTrait; <ide> use Cake\Database\ValueBinder; <ide> <ide> /** <ide> */ <ide> class ValuesExpression implements ExpressionInterface <ide> { <del> <ide> use ExpressionTypeCasterTrait; <ide> use TypeMapTrait; <ide> <ide><path>src/Database/ExpressionInterface.php <ide> */ <ide> interface ExpressionInterface <ide> { <del> <ide> /** <ide> * Converts the Node into a SQL string fragment. <ide> * <ide><path>src/Database/FieldTypeConverter.php <ide> */ <ide> class FieldTypeConverter <ide> { <del> <ide> /** <ide> * An array containing the name of the fields and the Type objects <ide> * each should use when converting them. <ide><path>src/Database/FunctionsBuilder.php <ide> */ <ide> class FunctionsBuilder <ide> { <del> <ide> /** <ide> * Returns a new instance of a FunctionExpression. This is used for generating <ide> * arbitrary function calls in the final SQL string. <ide><path>src/Database/IdentifierQuoter.php <ide> */ <ide> class IdentifierQuoter <ide> { <del> <ide> /** <ide> * The driver instance used to do the identifier quoting <ide> * <ide><path>src/Database/Log/LoggedQuery.php <ide> */ <ide> class LoggedQuery <ide> { <del> <ide> /** <ide> * Query string that was executed <ide> * <ide><path>src/Database/Log/LoggingStatement.php <ide> */ <ide> class LoggingStatement extends StatementDecorator <ide> { <del> <ide> /** <ide> * Logger instance responsible for actually doing the logging task <ide> * <ide><path>src/Database/Log/QueryLogger.php <ide> */ <ide> class QueryLogger <ide> { <del> <ide> /** <ide> * Writes a LoggedQuery into a log <ide> * <ide><path>src/Database/Query.php <ide> */ <ide> class Query implements ExpressionInterface, IteratorAggregate <ide> { <del> <ide> use TypeMapTrait; <ide> <ide> /** <ide> class Query implements ExpressionInterface, IteratorAggregate <ide> 'limit' => null, <ide> 'offset' => null, <ide> 'union' => [], <del> 'epilog' => null <add> 'epilog' => null, <ide> ]; <ide> <ide> /** <ide> public function rowCountAndClose() <ide> * associated values for expressions <ide> * @return string <ide> */ <del> public function sql(ValueBinder $generator = null) <add> public function sql(?ValueBinder $generator = null) <ide> { <ide> if (!$generator) { <ide> $generator = $this->getValueBinder(); <ide> protected function _makeJoin($table, $conditions, $type) <ide> $alias => [ <ide> 'table' => $table, <ide> 'conditions' => $conditions, <del> 'type' => $type <del> ] <add> 'type' => $type, <add> ], <ide> ]; <ide> } <ide> <ide> public function union($query, $overwrite = false) <ide> } <ide> $this->_parts['union'][] = [ <ide> 'all' => false, <del> 'query' => $query <add> 'query' => $query, <ide> ]; <ide> $this->_dirty(); <ide> <ide> public function unionAll($query, $overwrite = false) <ide> } <ide> $this->_parts['union'][] = [ <ide> 'all' => true, <del> 'query' => $query <add> 'query' => $query, <ide> ]; <ide> $this->_dirty(); <ide> <ide> public function __debugInfo() <ide> 'params' => $params, <ide> 'defaultTypes' => $this->getDefaultTypes(), <ide> 'decorators' => count($this->_resultDecorators), <del> 'executed' => $this->_iterator ? true : false <add> 'executed' => $this->_iterator ? true : false, <ide> ]; <ide> } <ide> } <ide><path>src/Database/QueryCompiler.php <ide> */ <ide> class QueryCompiler <ide> { <del> <ide> /** <ide> * List of sprintf templates that will be used for compiling the SQL for <ide> * this query. There are some clauses that can be built as just as the <ide> class QueryCompiler <ide> 'order' => ' %s', <ide> 'limit' => ' LIMIT %s', <ide> 'offset' => ' OFFSET %s', <del> 'epilog' => ' %s' <add> 'epilog' => ' %s', <ide> ]; <ide> <ide> /** <ide> class QueryCompiler <ide> */ <ide> protected $_selectParts = [ <ide> 'select', 'from', 'join', 'where', 'group', 'having', 'order', 'limit', <del> 'offset', 'union', 'epilog' <add> 'offset', 'union', 'epilog', <ide> ]; <ide> <ide> /** <ide><path>src/Database/Schema/BaseSchema.php <ide> */ <ide> abstract class BaseSchema <ide> { <del> <ide> /** <ide> * The driver instance being used. <ide> * <ide><path>src/Database/Schema/CachedCollection.php <ide> */ <ide> class CachedCollection extends Collection <ide> { <del> <ide> /** <ide> * The name of the cache config key to use for caching table metadata, <ide> * of false if disabled. <ide><path>src/Database/Schema/Collection.php <ide> */ <ide> class Collection <ide> { <del> <ide> /** <ide> * Connection object <ide> * <ide><path>src/Database/Schema/MysqlSchema.php <ide> namespace Cake\Database\Schema; <ide> <ide> use Cake\Database\Exception; <del>use Cake\Database\Schema\TableSchema; <ide> <ide> /** <ide> * Schema generation/reflection features for MySQL <ide> protected function _convertColumn($column) <ide> } <ide> if (strpos($col, 'text') !== false) { <ide> $lengthName = substr($col, 0, -4); <del> $length = isset(TableSchema::$columnLengths[$lengthName]) ? TableSchema::$columnLengths[$lengthName] : null; <add> $length = TableSchema::$columnLengths[$lengthName] ?? null; <ide> <ide> return ['type' => TableSchema::TYPE_TEXT, 'length' => $length]; <ide> } <ide> protected function _convertColumn($column) <ide> } <ide> if (strpos($col, 'blob') !== false || $col === 'binary') { <ide> $lengthName = substr($col, 0, -4); <del> $length = isset(TableSchema::$columnLengths[$lengthName]) ? TableSchema::$columnLengths[$lengthName] : null; <add> $length = TableSchema::$columnLengths[$lengthName] ?? null; <ide> <ide> return ['type' => TableSchema::TYPE_BINARY, 'length' => $length]; <ide> } <ide> protected function _convertColumn($column) <ide> 'type' => TableSchema::TYPE_FLOAT, <ide> 'length' => $length, <ide> 'precision' => $precision, <del> 'unsigned' => $unsigned <add> 'unsigned' => $unsigned, <ide> ]; <ide> } <ide> if (strpos($col, 'decimal') !== false) { <ide> return [ <ide> 'type' => TableSchema::TYPE_DECIMAL, <ide> 'length' => $length, <ide> 'precision' => $precision, <del> 'unsigned' => $unsigned <add> 'unsigned' => $unsigned, <ide> ]; <ide> } <ide> <ide> public function convertIndexDescription(TableSchema $schema, $row) <ide> <ide> if ($row['Index_type'] === 'FULLTEXT') { <ide> $type = TableSchema::INDEX_FULLTEXT; <del> } elseif ($row['Non_unique'] == 0 && $type !== 'primary') { <add> } elseif ($row['Non_unique'] === 0 && $type !== 'primary') { <ide> $type = TableSchema::CONSTRAINT_UNIQUE; <ide> } elseif ($type !== 'primary') { <ide> $type = TableSchema::INDEX_INDEX; <ide> public function convertIndexDescription(TableSchema $schema, $row) <ide> $schema->addIndex($name, [ <ide> 'type' => $type, <ide> 'columns' => $columns, <del> 'length' => $length <add> 'length' => $length, <ide> ]); <ide> } else { <ide> $schema->addConstraint($name, [ <ide> 'type' => $type, <ide> 'columns' => $columns, <del> 'length' => $length <add> 'length' => $length, <ide> ]); <ide> } <ide> } <ide> public function columnSql(TableSchema $schema, $name) <ide> TableSchema::TYPE_DATETIME => ' DATETIME', <ide> TableSchema::TYPE_TIMESTAMP => ' TIMESTAMP', <ide> TableSchema::TYPE_UUID => ' CHAR(36)', <del> TableSchema::TYPE_JSON => $nativeJson ? ' JSON' : ' LONGTEXT' <add> TableSchema::TYPE_JSON => $nativeJson ? ' JSON' : ' LONGTEXT', <ide> ]; <ide> $specialMap = [ <ide> 'string' => true, <ide> public function columnSql(TableSchema $schema, $name) <ide> TableSchema::TYPE_INTEGER, <ide> TableSchema::TYPE_SMALLINTEGER, <ide> TableSchema::TYPE_TINYINTEGER, <del> TableSchema::TYPE_STRING <add> TableSchema::TYPE_STRING, <ide> ]; <ide> if (in_array($data['type'], $hasLength, true) && isset($data['length'])) { <ide> $out .= '(' . (int)$data['length'] . ')'; <ide> public function columnSql(TableSchema $schema, $name) <ide> TableSchema::TYPE_INTEGER, <ide> TableSchema::TYPE_BIGINTEGER, <ide> TableSchema::TYPE_FLOAT, <del> TableSchema::TYPE_DECIMAL <add> TableSchema::TYPE_DECIMAL, <ide> ]; <ide> if (in_array($data['type'], $hasUnsigned, true) && <ide> isset($data['unsigned']) && $data['unsigned'] === true <ide> public function columnSql(TableSchema $schema, $name) <ide> $out .= ' NOT NULL'; <ide> } <ide> $addAutoIncrement = ( <del> [$name] == (array)$schema->primaryKey() && <add> (array)$schema->primaryKey() === [$name] && <ide> !$schema->hasAutoincrement() && <ide> !isset($data['autoIncrement']) <ide> ); <ide><path>src/Database/Schema/PostgresSchema.php <ide> namespace Cake\Database\Schema; <ide> <ide> use Cake\Database\Exception; <del>use Cake\Database\Schema\TableSchema; <ide> <ide> /** <ide> * Schema management/reflection features for Postgres. <ide> */ <ide> class PostgresSchema extends BaseSchema <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide> public function convertColumnDescription(TableSchema $schema, $row) <ide> 'default' => $this->_defaultValue($row['default']), <ide> 'null' => $row['null'] === 'YES', <ide> 'collate' => $row['collation_name'], <del> 'comment' => $row['comment'] <add> 'comment' => $row['comment'], <ide> ]; <ide> $field['length'] = $row['char_length'] ?: $field['length']; <ide> <ide> public function convertIndexDescription(TableSchema $schema, $row) <ide> if (!$index) { <ide> $index = [ <ide> 'type' => $type, <del> 'columns' => [] <add> 'columns' => [], <ide> ]; <ide> } <ide> $index['columns'][] = $row['attname']; <ide> protected function _convertConstraint($schema, $name, $type, $row) <ide> if (!$constraint) { <ide> $constraint = [ <ide> 'type' => $type, <del> 'columns' => [] <add> 'columns' => [], <ide> ]; <ide> } <ide> $constraint['columns'][] = $row['attname']; <ide> public function columnSql(TableSchema $schema, $name) <ide> TableSchema::TYPE_DATETIME => ' TIMESTAMP', <ide> TableSchema::TYPE_TIMESTAMP => ' TIMESTAMP', <ide> TableSchema::TYPE_UUID => ' UUID', <del> TableSchema::TYPE_JSON => ' JSONB' <add> TableSchema::TYPE_JSON => ' JSONB', <ide> ]; <ide> <ide> if (isset($typeMap[$data['type']])) { <ide> public function columnSql(TableSchema $schema, $name) <ide> <ide> if ($data['type'] === TableSchema::TYPE_INTEGER || $data['type'] === TableSchema::TYPE_BIGINTEGER) { <ide> $type = $data['type'] === TableSchema::TYPE_INTEGER ? ' INTEGER' : ' BIGINT'; <del> if ([$name] === $schema->primaryKey() || $data['autoIncrement'] === true) { <add> if ($schema->primaryKey() === [$name] || $data['autoIncrement'] === true) { <ide> $type = $data['type'] === TableSchema::TYPE_INTEGER ? ' SERIAL' : ' BIGSERIAL'; <ide> unset($data['null'], $data['default']); <ide> } <ide> public function columnSql(TableSchema $schema, $name) <ide> $type = ' CHAR'; <ide> } <ide> $out .= $type; <del> if (isset($data['length']) && $data['length'] != 36) { <add> if (isset($data['length']) && $data['length'] !== 36) { <ide> $out .= '(' . (int)$data['length'] . ')'; <ide> } <ide> } <ide> public function truncateTableSql(TableSchema $schema) <ide> $name = $this->_driver->quoteIdentifier($schema->name()); <ide> <ide> return [ <del> sprintf('TRUNCATE %s RESTART IDENTITY CASCADE', $name) <add> sprintf('TRUNCATE %s RESTART IDENTITY CASCADE', $name), <ide> ]; <ide> } <ide> <ide><path>src/Database/Schema/SqlGeneratorInterface.php <ide> */ <ide> interface SqlGeneratorInterface <ide> { <del> <ide> /** <ide> * Generate the SQL to create the Table. <ide> * <ide><path>src/Database/Schema/SqliteSchema.php <ide> namespace Cake\Database\Schema; <ide> <ide> use Cake\Database\Exception; <del>use Cake\Database\Schema\TableSchema; <ide> <ide> /** <ide> * Schema management/reflection features for Sqlite <ide> */ <ide> class SqliteSchema extends BaseSchema <ide> { <del> <ide> /** <ide> * Array containing the foreign keys constraints names <ide> * Necessary for composite foreign keys to be handled <ide> protected function _convertColumn($column) <ide> if ($col === 'bigint') { <ide> return ['type' => TableSchema::TYPE_BIGINTEGER, 'length' => $length, 'unsigned' => $unsigned]; <ide> } <del> if ($col == 'smallint') { <add> if ($col === 'smallint') { <ide> return ['type' => TableSchema::TYPE_SMALLINTEGER, 'length' => $length, 'unsigned' => $unsigned]; <ide> } <del> if ($col == 'tinyint') { <add> if ($col === 'tinyint') { <ide> return ['type' => TableSchema::TYPE_TINYINTEGER, 'length' => $length, 'unsigned' => $unsigned]; <ide> } <ide> if (strpos($col, 'int') !== false) { <ide> public function listTablesSql($config) <ide> return [ <ide> 'SELECT name FROM sqlite_master WHERE type="table" ' . <ide> 'AND name != "sqlite_sequence" ORDER BY name', <del> [] <add> [], <ide> ]; <ide> } <ide> <ide> public function convertColumnDescription(TableSchema $schema, $row) <ide> if ($row['pk']) { <ide> $constraint = (array)$schema->getConstraint('primary') + [ <ide> 'type' => TableSchema::CONSTRAINT_PRIMARY, <del> 'columns' => [] <add> 'columns' => [], <ide> ]; <ide> $constraint['columns'] = array_merge($constraint['columns'], [$row['name']]); <ide> $schema->addConstraint('primary', $constraint); <ide> public function convertIndexDescription(TableSchema $schema, $row) <ide> if ($row['unique']) { <ide> $schema->addConstraint($row['name'], [ <ide> 'type' => TableSchema::CONSTRAINT_UNIQUE, <del> 'columns' => $columns <add> 'columns' => $columns, <ide> ]); <ide> } else { <ide> $schema->addIndex($row['name'], [ <ide> 'type' => TableSchema::INDEX_INDEX, <del> 'columns' => $columns <add> 'columns' => $columns, <ide> ]); <ide> } <ide> } <ide> public function convertForeignKeyDescription(TableSchema $schema, $row) <ide> { <ide> $name = $row['from'] . '_fk'; <ide> <del> $update = isset($row['on_update']) ? $row['on_update'] : ''; <del> $delete = isset($row['on_delete']) ? $row['on_delete'] : ''; <add> $update = $row['on_update'] ?? ''; <add> $delete = $row['on_delete'] ?? ''; <ide> $data = [ <ide> 'type' => TableSchema::CONSTRAINT_FOREIGN, <ide> 'columns' => [$row['from']], <ide> public function columnSql(TableSchema $schema, $name) <ide> TableSchema::TYPE_TIME => ' TIME', <ide> TableSchema::TYPE_DATETIME => ' DATETIME', <ide> TableSchema::TYPE_TIMESTAMP => ' TIMESTAMP', <del> TableSchema::TYPE_JSON => ' TEXT' <add> TableSchema::TYPE_JSON => ' TEXT', <ide> ]; <ide> <ide> $out = $this->_driver->quoteIdentifier($name); <ide> public function columnSql(TableSchema $schema, $name) <ide> TableSchema::TYPE_INTEGER, <ide> TableSchema::TYPE_BIGINTEGER, <ide> TableSchema::TYPE_FLOAT, <del> TableSchema::TYPE_DECIMAL <add> TableSchema::TYPE_DECIMAL, <ide> ]; <ide> <ide> if (in_array($data['type'], $hasUnsigned, true) && <ide> isset($data['unsigned']) && $data['unsigned'] === true <ide> ) { <del> if ($data['type'] !== TableSchema::TYPE_INTEGER || [$name] !== (array)$schema->primaryKey()) { <add> if ($data['type'] !== TableSchema::TYPE_INTEGER || (array)$schema->primaryKey() !== [$name]) { <ide> $out .= ' UNSIGNED'; <ide> } <ide> } <ide> public function columnSql(TableSchema $schema, $name) <ide> TableSchema::TYPE_INTEGER, <ide> ]; <ide> if (in_array($data['type'], $integerTypes, true) && <del> isset($data['length']) && [$name] !== (array)$schema->primaryKey() <add> isset($data['length']) && (array)$schema->primaryKey() !== [$name] <ide> ) { <ide> $out .= '(' . (int)$data['length'] . ')'; <ide> } <ide> public function columnSql(TableSchema $schema, $name) <ide> $out .= ' NOT NULL'; <ide> } <ide> <del> if ($data['type'] === TableSchema::TYPE_INTEGER && [$name] === (array)$schema->primaryKey()) { <add> if ($data['type'] === TableSchema::TYPE_INTEGER && (array)$schema->primaryKey() === [$name]) { <ide> $out .= ' PRIMARY KEY AUTOINCREMENT'; <ide> } <ide> <ide><path>src/Database/Schema/SqlserverSchema.php <ide> */ <ide> class SqlserverSchema extends BaseSchema <ide> { <del> <del> const DEFAULT_SCHEMA_NAME = 'dbo'; <add> public const DEFAULT_SCHEMA_NAME = 'dbo'; <ide> <ide> /** <ide> * {@inheritDoc} <ide> public function convertIndexDescription(TableSchema $schema, $row) <ide> if ($type === TableSchema::CONSTRAINT_PRIMARY || $type === TableSchema::CONSTRAINT_UNIQUE) { <ide> $schema->addConstraint($name, [ <ide> 'type' => $type, <del> 'columns' => $columns <add> 'columns' => $columns, <ide> ]); <ide> <ide> return; <ide> } <ide> $schema->addIndex($name, [ <ide> 'type' => $type, <del> 'columns' => $columns <add> 'columns' => $columns, <ide> ]); <ide> } <ide> <ide> public function columnSql(TableSchema $schema, $name) <ide> } <ide> <ide> if ($data['type'] === TableSchema::TYPE_INTEGER || $data['type'] === TableSchema::TYPE_BIGINTEGER) { <del> if ([$name] === $schema->primaryKey() || $data['autoIncrement'] === true) { <add> if ($schema->primaryKey() === [$name] || $data['autoIncrement'] === true) { <ide> unset($data['null'], $data['default']); <ide> $out .= ' IDENTITY(1, 1)'; <ide> } <ide> public function truncateTableSql(TableSchema $schema) <ide> { <ide> $name = $this->_driver->quoteIdentifier($schema->name()); <ide> $queries = [ <del> sprintf('DELETE FROM %s', $name) <add> sprintf('DELETE FROM %s', $name), <ide> ]; <ide> <ide> // Restart identity sequences <ide><path>src/Database/Schema/TableSchema.php <ide> */ <ide> class TableSchema implements TableSchemaInterface, SqlGeneratorInterface <ide> { <del> <ide> /** <ide> * The name of the table <ide> * <ide> class TableSchema implements TableSchemaInterface, SqlGeneratorInterface <ide> * <ide> * @var int <ide> */ <del> const LENGTH_TINY = 255; <add> public const LENGTH_TINY = 255; <ide> <ide> /** <ide> * Column length when using a `medium` column type <ide> * <ide> * @var int <ide> */ <del> const LENGTH_MEDIUM = 16777215; <add> public const LENGTH_MEDIUM = 16777215; <ide> <ide> /** <ide> * Column length when using a `long` column type <ide> * <ide> * @var int <ide> */ <del> const LENGTH_LONG = 4294967295; <add> public const LENGTH_LONG = 4294967295; <ide> <ide> /** <ide> * Valid column length that can be used with text type columns <ide> class TableSchema implements TableSchemaInterface, SqlGeneratorInterface <ide> public static $columnLengths = [ <ide> 'tiny' => self::LENGTH_TINY, <ide> 'medium' => self::LENGTH_MEDIUM, <del> 'long' => self::LENGTH_LONG <add> 'long' => self::LENGTH_LONG, <ide> ]; <ide> <ide> /** <ide> class TableSchema implements TableSchemaInterface, SqlGeneratorInterface <ide> * <ide> * @var string <ide> */ <del> const CONSTRAINT_PRIMARY = 'primary'; <add> public const CONSTRAINT_PRIMARY = 'primary'; <ide> <ide> /** <ide> * Unique constraint type <ide> * <ide> * @var string <ide> */ <del> const CONSTRAINT_UNIQUE = 'unique'; <add> public const CONSTRAINT_UNIQUE = 'unique'; <ide> <ide> /** <ide> * Foreign constraint type <ide> * <ide> * @var string <ide> */ <del> const CONSTRAINT_FOREIGN = 'foreign'; <add> public const CONSTRAINT_FOREIGN = 'foreign'; <ide> <ide> /** <ide> * Index - index type <ide> * <ide> * @var string <ide> */ <del> const INDEX_INDEX = 'index'; <add> public const INDEX_INDEX = 'index'; <ide> <ide> /** <ide> * Fulltext index type <ide> * <ide> * @var string <ide> */ <del> const INDEX_FULLTEXT = 'fulltext'; <add> public const INDEX_FULLTEXT = 'fulltext'; <ide> <ide> /** <ide> * Foreign key cascade action <ide> * <ide> * @var string <ide> */ <del> const ACTION_CASCADE = 'cascade'; <add> public const ACTION_CASCADE = 'cascade'; <ide> <ide> /** <ide> * Foreign key set null action <ide> * <ide> * @var string <ide> */ <del> const ACTION_SET_NULL = 'setNull'; <add> public const ACTION_SET_NULL = 'setNull'; <ide> <ide> /** <ide> * Foreign key no action <ide> * <ide> * @var string <ide> */ <del> const ACTION_NO_ACTION = 'noAction'; <add> public const ACTION_NO_ACTION = 'noAction'; <ide> <ide> /** <ide> * Foreign key restrict action <ide> * <ide> * @var string <ide> */ <del> const ACTION_RESTRICT = 'restrict'; <add> public const ACTION_RESTRICT = 'restrict'; <ide> <ide> /** <ide> * Foreign key restrict default <ide> * <ide> * @var string <ide> */ <del> const ACTION_SET_DEFAULT = 'setDefault'; <add> public const ACTION_SET_DEFAULT = 'setDefault'; <ide> <ide> /** <ide> * Constructor. <ide> public function isNullable($name) <ide> return true; <ide> } <ide> <del> return ($this->_columns[$name]['null'] === true); <add> return $this->_columns[$name]['null'] === true; <ide> } <ide> <ide> /** <ide><path>src/Database/Schema/TableSchemaAwareInterface.php <ide> */ <ide> interface TableSchemaAwareInterface <ide> { <del> <ide> /** <ide> * Get and set the schema for this fixture. <ide> * <ide><path>src/Database/Schema/TableSchemaInterface.php <ide> */ <ide> interface TableSchemaInterface extends SchemaInterface <ide> { <del> <ide> /** <ide> * Binary column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_BINARY = 'binary'; <add> public const TYPE_BINARY = 'binary'; <ide> <ide> /** <ide> * Binary UUID column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_BINARY_UUID = 'binaryuuid'; <add> public const TYPE_BINARY_UUID = 'binaryuuid'; <ide> <ide> /** <ide> * Date column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_DATE = 'date'; <add> public const TYPE_DATE = 'date'; <ide> <ide> /** <ide> * Datetime column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_DATETIME = 'datetime'; <add> public const TYPE_DATETIME = 'datetime'; <ide> <ide> /** <ide> * Time column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_TIME = 'time'; <add> public const TYPE_TIME = 'time'; <ide> <ide> /** <ide> * Timestamp column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_TIMESTAMP = 'timestamp'; <add> public const TYPE_TIMESTAMP = 'timestamp'; <ide> <ide> /** <ide> * JSON column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_JSON = 'json'; <add> public const TYPE_JSON = 'json'; <ide> <ide> /** <ide> * String column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_STRING = 'string'; <add> public const TYPE_STRING = 'string'; <ide> <ide> /** <ide> * Text column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_TEXT = 'text'; <add> public const TYPE_TEXT = 'text'; <ide> <ide> /** <ide> * Tiny Integer column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_TINYINTEGER = 'tinyinteger'; <add> public const TYPE_TINYINTEGER = 'tinyinteger'; <ide> <ide> /** <ide> * Small Integer column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_SMALLINTEGER = 'smallinteger'; <add> public const TYPE_SMALLINTEGER = 'smallinteger'; <ide> <ide> /** <ide> * Integer column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_INTEGER = 'integer'; <add> public const TYPE_INTEGER = 'integer'; <ide> <ide> /** <ide> * Big Integer column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_BIGINTEGER = 'biginteger'; <add> public const TYPE_BIGINTEGER = 'biginteger'; <ide> <ide> /** <ide> * Float column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_FLOAT = 'float'; <add> public const TYPE_FLOAT = 'float'; <ide> <ide> /** <ide> * Decimal column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_DECIMAL = 'decimal'; <add> public const TYPE_DECIMAL = 'decimal'; <ide> <ide> /** <ide> * Boolean column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_BOOLEAN = 'boolean'; <add> public const TYPE_BOOLEAN = 'boolean'; <ide> <ide> /** <ide> * UUID column type <ide> * <ide> * @var string <ide> */ <del> const TYPE_UUID = 'uuid'; <add> public const TYPE_UUID = 'uuid'; <ide> <ide> /** <ide> * Check whether or not a table has an autoIncrement column defined. <ide><path>src/Database/SchemaCache.php <ide> namespace Cake\Database; <ide> <ide> use Cake\Cache\Cache; <del>use Cake\Database\Connection; <ide> <ide> /** <ide> * Schema Cache. <ide> */ <ide> class SchemaCache <ide> { <del> <ide> /** <ide> * Schema <ide> * <ide><path>src/Database/SqlDialectTrait.php <ide> */ <ide> trait SqlDialectTrait <ide> { <del> <ide> /** <ide> * Quotes a database identifier (a column name, table name, etc..) to <ide> * be used safely in queries without the risk of using reserved words <ide><path>src/Database/SqliteCompiler.php <ide> */ <ide> class SqliteCompiler extends QueryCompiler <ide> { <del> <ide> /** <ide> * SQLite does not support ORDER BY in UNION queries. <ide> * <ide><path>src/Database/SqlserverCompiler.php <ide> */ <ide> class SqlserverCompiler extends QueryCompiler <ide> { <del> <ide> /** <ide> * SQLserver does not support ORDER BY in UNION queries. <ide> * <ide> class SqlserverCompiler extends QueryCompiler <ide> 'having' => ' HAVING %s ', <ide> 'order' => ' %s', <ide> 'offset' => ' OFFSET %s ROWS', <del> 'epilog' => ' %s' <add> 'epilog' => ' %s', <ide> ]; <ide> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide> protected $_selectParts = [ <ide> 'select', 'from', 'join', 'where', 'group', 'having', 'order', 'offset', <del> 'limit', 'union', 'epilog' <add> 'limit', 'union', 'epilog', <ide> ]; <ide> <ide> /** <ide><path>src/Database/Statement/BufferResultsTrait.php <ide> */ <ide> trait BufferResultsTrait <ide> { <del> <ide> /** <ide> * Whether or not to buffer results in php <ide> * <ide><path>src/Database/Statement/CallbackStatement.php <ide> */ <ide> class CallbackStatement extends StatementDecorator <ide> { <del> <ide> /** <ide> * A callback function to be applied to results. <ide> * <ide><path>src/Database/Statement/MysqlStatement.php <ide> */ <ide> class MysqlStatement extends PDOStatement <ide> { <del> <ide> use BufferResultsTrait; <ide> <ide> /** <ide><path>src/Database/Statement/PDOStatement.php <ide> */ <ide> class PDOStatement extends StatementDecorator <ide> { <del> <ide> /** <ide> * Constructor <ide> * <ide> * @param \PDOStatement|null $statement Original statement to be decorated. <ide> * @param \Cake\Database\Driver|null $driver Driver instance. <ide> */ <del> public function __construct(Statement $statement = null, $driver = null) <add> public function __construct(?Statement $statement = null, $driver = null) <ide> { <ide> parent::__construct($statement, $driver); <ide> } <ide><path>src/Database/Statement/SqliteStatement.php <ide> */ <ide> class SqliteStatement extends StatementDecorator <ide> { <del> <ide> use BufferResultsTrait; <ide> <ide> /** <ide><path>src/Database/Statement/SqlserverStatement.php <ide> */ <ide> class SqlserverStatement extends PDOStatement <ide> { <del> <ide> /** <ide> * The SQL Server PDO driver requires that binary parameters be bound with the SQLSRV_ENCODING_BINARY attribute. <ide> * This overrides the PDOStatement::bindValue method in order to bind binary columns using the required attribute. <ide> public function bindValue($column, $value, $type = 'string') <ide> if (!ctype_digit($type)) { <ide> list($value, $type) = $this->cast($value, $type); <ide> } <del> if ($type == PDO::PARAM_LOB) { <add> if ($type === PDO::PARAM_LOB) { <ide> $this->_statement->bindParam($column, $value, $type, 0, PDO::SQLSRV_ENCODING_BINARY); <ide> } else { <ide> $this->_statement->bindValue($column, $value, $type); <ide><path>src/Database/StatementInterface.php <ide> interface StatementInterface <ide> * <ide> * @var string <ide> */ <del> const FETCH_TYPE_NUM = 'num'; <add> public const FETCH_TYPE_NUM = 'num'; <ide> <ide> /** <ide> * Used to designate that an associated array be returned in a result when calling fetch methods <ide> * <ide> * @var string <ide> */ <del> const FETCH_TYPE_ASSOC = 'assoc'; <add> public const FETCH_TYPE_ASSOC = 'assoc'; <ide> <ide> /** <ide> * Used to designate that a stdClass object be returned in a result when calling fetch methods <ide> * <ide> * @var string <ide> */ <del> const FETCH_TYPE_OBJ = 'obj'; <add> public const FETCH_TYPE_OBJ = 'obj'; <ide> <ide> /** <ide> * Assign a value to a positional or named variable in prepared query. If using <ide><path>src/Database/Type/BaseType.php <ide> */ <ide> abstract class BaseType implements TypeInterface <ide> { <del> <ide> /** <ide> * Identifier name for this type <ide> * <ide><path>src/Database/Type/BatchCastingInterface.php <ide> */ <ide> interface BatchCastingInterface <ide> { <del> <ide> /** <ide> * Returns an array of the values converted to the PHP representation of <ide> * this type. <ide><path>src/Database/Type/BinaryType.php <ide> */ <ide> class BinaryType extends BaseType <ide> { <del> <ide> /** <ide> * Convert binary data into the database format. <ide> * <ide><path>src/Database/Type/BinaryUuidType.php <ide> */ <ide> class BinaryUuidType extends BaseType <ide> { <del> <ide> /** <ide> * Convert binary uuid data into the database format. <ide> * <ide><path>src/Database/Type/BoolType.php <ide> namespace Cake\Database\Type; <ide> <ide> use Cake\Database\Driver; <del>use Cake\Database\Type\BatchCastingInterface; <ide> use InvalidArgumentException; <ide> use PDO; <ide> <ide> */ <ide> class BoolType extends BaseType implements BatchCastingInterface <ide> { <del> <ide> /** <ide> * Convert bool data into the database format. <ide> * <ide><path>src/Database/Type/DateTimeType.php <ide> public function marshal($value) <ide> $value['minute'], <ide> $value['second'] <ide> ); <del> $tz = isset($value['timezone']) ? $value['timezone'] : null; <add> $tz = $value['timezone'] ?? null; <ide> <ide> return new $class($format, $tz); <ide> } <ide><path>src/Database/Type/DecimalType.php <ide> namespace Cake\Database\Type; <ide> <ide> use Cake\Database\Driver; <del>use Cake\Database\Type\BatchCastingInterface; <ide> use InvalidArgumentException; <ide> use PDO; <ide> use RuntimeException; <ide> */ <ide> class DecimalType extends BaseType implements BatchCastingInterface <ide> { <del> <ide> /** <ide> * The class to use for representing number objects <ide> * <ide><path>src/Database/Type/ExpressionTypeCasterTrait.php <ide> */ <ide> trait ExpressionTypeCasterTrait <ide> { <del> <ide> /** <ide> * Conditionally converts the passed value to an ExpressionInterface object <ide> * if the type class implements the ExpressionTypeInterface. Otherwise, <ide><path>src/Database/Type/ExpressionTypeInterface.php <ide> */ <ide> interface ExpressionTypeInterface <ide> { <del> <ide> /** <ide> * Returns an ExpressionInterface object for the given value that can <ide> * be used in queries. <ide><path>src/Database/Type/FloatType.php <ide> namespace Cake\Database\Type; <ide> <ide> use Cake\Database\Driver; <del>use Cake\Database\Type\BatchCastingInterface; <ide> use PDO; <ide> use RuntimeException; <ide> <ide> */ <ide> class FloatType extends BaseType implements BatchCastingInterface <ide> { <del> <ide> /** <ide> * The class to use for representing number objects <ide> * <ide><path>src/Database/Type/IntegerType.php <ide> namespace Cake\Database\Type; <ide> <ide> use Cake\Database\Driver; <del>use Cake\Database\Type\BatchCastingInterface; <ide> use InvalidArgumentException; <ide> use PDO; <ide> <ide> */ <ide> class IntegerType extends BaseType implements BatchCastingInterface <ide> { <del> <ide> /** <ide> * Convert integer data into the database format. <ide> * <ide><path>src/Database/Type/JsonType.php <ide> namespace Cake\Database\Type; <ide> <ide> use Cake\Database\Driver; <del>use Cake\Database\Type\BatchCastingInterface; <ide> use InvalidArgumentException; <ide> use PDO; <ide> <ide> */ <ide> class JsonType extends BaseType implements BatchCastingInterface <ide> { <del> <ide> /** <ide> * Convert a value data into a JSON string <ide> * <ide><path>src/Database/Type/OptionalConvertInterface.php <ide> */ <ide> interface OptionalConvertInterface <ide> { <del> <ide> /** <ide> * Returns whether the cast to PHP is required to be invoked, since <ide> * it is not a identity function. <ide><path>src/Database/Type/StringType.php <ide> */ <ide> class StringType extends BaseType implements OptionalConvertInterface <ide> { <del> <ide> /** <ide> * Convert string data into the database format. <ide> * <ide> public function marshal($value) <ide> /** <ide> * {@inheritDoc} <ide> * <del> * @return boolean False as database results are returned already as strings <add> * @return bool False as database results are returned already as strings <ide> */ <ide> public function requiresToPhpCast() <ide> { <ide><path>src/Database/Type/TimeType.php <ide> */ <ide> class TimeType extends DateTimeType <ide> { <del> <ide> /** <ide> * Time format for DateTime object <ide> * <ide><path>src/Database/Type/UuidType.php <ide> */ <ide> class UuidType extends StringType <ide> { <del> <ide> /** <ide> * Casts given value from a PHP type to one acceptable by database <ide> * <ide><path>src/Database/TypeConverterTrait.php <ide> */ <ide> trait TypeConverterTrait <ide> { <del> <ide> /** <ide> * Converts a give value to a suitable database value based on type <ide> * and return relevant internal statement type <ide><path>src/Database/TypeFactory.php <ide> */ <ide> class TypeFactory <ide> { <del> <ide> /** <ide> * List of supported database types. A human readable <ide> * identifier is used as key and a complete namespaced class name as value <ide> public static function buildAll() <ide> { <ide> $result = []; <ide> foreach (static::$_types as $name => $type) { <del> $result[$name] = isset(static::$_builtTypes[$name]) <del> ? static::$_builtTypes[$name] <del> : static::build($name); <add> $result[$name] = static::$_builtTypes[$name] ?? static::build($name); <ide> } <ide> <ide> return $result; <ide> public static function setMap(array $map) <ide> * @param string|null $type Type name to get mapped class for or null to get map array. <ide> * @return array|string|null Configured class name for given $type or map array. <ide> */ <del> public static function getMap(string $type = null) <add> public static function getMap(?string $type = null) <ide> { <ide> if ($type === null) { <ide> return static::$_types; <ide> } <ide> <del> return isset(static::$_types[$type]) ? static::$_types[$type] : null; <add> return static::$_types[$type] ?? null; <ide> } <ide> <ide> /** <ide><path>src/Database/TypeInterface.php <ide> */ <ide> interface TypeInterface <ide> { <del> <ide> /** <ide> * Casts given value from a PHP type to one acceptable by a database. <ide> * <ide><path>src/Database/TypeMap.php <ide> */ <ide> class TypeMap <ide> { <del> <ide> /** <ide> * Associative array with the default fields and the related types this query might contain. <ide> * <ide><path>src/Database/TypeMapTrait.php <ide> */ <ide> trait TypeMapTrait <ide> { <del> <ide> /** <ide> * @var \Cake\Database\TypeMap <ide> */ <ide><path>src/Database/TypedResultTrait.php <ide> */ <ide> trait TypedResultTrait <ide> { <del> <ide> /** <ide> * The type name this expression will return when executed <ide> * <ide><path>src/Database/ValueBinder.php <ide> */ <ide> class ValueBinder <ide> { <del> <ide> /** <ide> * Array containing a list of bound values to the conditions on this <ide> * object. Each array entry is another array structure containing the actual <ide> class ValueBinder <ide> public function bind($param, $value, $type = 'string') <ide> { <ide> $this->_bindings[$param] = compact('value', 'type') + [ <del> 'placeholder' => is_int($param) ? $param : substr($param, 1) <add> 'placeholder' => is_int($param) ? $param : substr($param, 1), <ide> ]; <ide> } <ide> <ide><path>src/Datasource/ConnectionManager.php <ide> */ <ide> class ConnectionManager <ide> { <del> <ide> use StaticConfigTrait { <ide> setConfig as protected _setConfig; <ide> parseDsn as protected _parseDsn; <ide><path>src/Datasource/ConnectionRegistry.php <ide> */ <ide> class ConnectionRegistry extends ObjectRegistry <ide> { <del> <ide> /** <ide> * Resolve a datasource classname. <ide> * <ide><path>src/Datasource/EntityInterface.php <ide> */ <ide> interface EntityInterface extends ArrayAccess, JsonSerializable <ide> { <del> <ide> /** <ide> * Sets hidden properties. <ide> * <ide><path>src/Datasource/EntityTrait.php <ide> */ <ide> trait EntityTrait <ide> { <del> <ide> /** <ide> * Holds all properties and their values for this entity <ide> * <ide> public function getErrors() <ide> */ <ide> public function getError($field) <ide> { <del> $errors = isset($this->_errors[$field]) ? $this->_errors[$field] : []; <add> $errors = $this->_errors[$field] ?? []; <ide> if ($errors) { <ide> return $errors; <ide> } <ide> protected function _nestedErrors($field) <ide> if ($entity instanceof EntityInterface) { <ide> $val = $entity->get($part); <ide> } elseif (is_array($entity)) { <del> $val = isset($entity[$part]) ? $entity[$part] : false; <add> $val = $entity[$part] ?? false; <ide> } <ide> <ide> if (is_array($val) || <ide> public function getInvalid() <ide> */ <ide> public function getInvalidField($field) <ide> { <del> $value = isset($this->_invalid[$field]) ? $this->_invalid[$field] : null; <add> $value = $this->_invalid[$field] ?? null; <ide> <ide> return $value; <ide> } <ide> public function setAccess($property, $set) <ide> */ <ide> public function isAccessible($property) <ide> { <del> $value = isset($this->_accessible[$property]) ? <del> $this->_accessible[$property] : <add> $value = $this->_accessible[$property] ?? <ide> null; <ide> <ide> return ($value === null && !empty($this->_accessible['*'])) || $value; <ide> public function __debugInfo() <ide> '[virtual]' => $this->_virtual, <ide> '[errors]' => $this->_errors, <ide> '[invalid]' => $this->_invalid, <del> '[repository]' => $this->_registryAlias <add> '[repository]' => $this->_registryAlias, <ide> ]; <ide> } <ide> } <ide><path>src/Datasource/Exception/InvalidPrimaryKeyException.php <ide> */ <ide> class InvalidPrimaryKeyException extends Exception <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Datasource/Exception/MissingDatasourceConfigException.php <ide> */ <ide> class MissingDatasourceConfigException extends Exception <ide> { <del> <ide> protected $_messageTemplate = 'The datasource configuration "%s" was not found.'; <ide> } <ide><path>src/Datasource/Exception/MissingDatasourceException.php <ide> */ <ide> class MissingDatasourceException extends Exception <ide> { <del> <ide> protected $_messageTemplate = 'Datasource class %s could not be found. %s'; <ide> } <ide><path>src/Datasource/Exception/MissingModelException.php <ide> */ <ide> class MissingModelException extends Exception <ide> { <del> <ide> protected $_messageTemplate = 'Model class "%s" of type "%s" could not be found.'; <ide> } <ide><path>src/Datasource/Exception/RecordNotFoundException.php <ide> */ <ide> class RecordNotFoundException extends Exception <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Datasource/InvalidPropertyInterface.php <ide> */ <ide> interface InvalidPropertyInterface <ide> { <del> <ide> /** <ide> * Get a list of invalid fields and their data for errors upon validation/patching <ide> * <ide><path>src/Datasource/ModelAwareTrait.php <ide> */ <ide> trait ModelAwareTrait <ide> { <del> <ide> /** <ide> * This object's primary model class name. Should be a plural form. <ide> * CakePHP will not inflect the name. <ide><path>src/Datasource/Paginator.php <ide> class Paginator implements PaginatorInterface <ide> 'page' => 1, <ide> 'limit' => 20, <ide> 'maxLimit' => 100, <del> 'whitelist' => ['limit', 'sort', 'page', 'direction'] <add> 'whitelist' => ['limit', 'sort', 'page', 'direction'], <ide> ]; <ide> <ide> /** <ide> public function paginate($object, array $params = [], array $settings = []) <ide> 'pageCount' => $pageCount, <ide> 'sort' => $options['sort'], <ide> 'direction' => current($order), <del> 'limit' => $defaults['limit'] != $limit ? $limit : null, <add> 'limit' => $defaults['limit'] !== $limit ? $limit : null, <ide> 'sortDefault' => $sortDefault, <ide> 'directionDefault' => $directionDefault, <ide> 'scope' => $options['scope'], <ide> public function paginate($object, array $params = [], array $settings = []) <ide> if ($requestedPage > $page) { <ide> throw new PageOutOfBoundsException([ <ide> 'requestedPage' => $requestedPage, <del> 'pagingParams' => $this->_pagingParams <add> 'pagingParams' => $this->_pagingParams, <ide> ]); <ide> } <ide> <ide> public function getDefaults($alias, $settings) <ide> } <ide> <ide> $defaults = $this->getConfig(); <del> $maxLimit = isset($settings['maxLimit']) ? $settings['maxLimit'] : $defaults['maxLimit']; <del> $limit = isset($settings['limit']) ? $settings['limit'] : $defaults['limit']; <add> $maxLimit = $settings['maxLimit'] ?? $defaults['maxLimit']; <add> $limit = $settings['limit'] ?? $defaults['limit']; <ide> <ide> if ($limit > $maxLimit) { <ide> $limit = $maxLimit; <ide><path>src/Datasource/QueryCacher.php <ide> */ <ide> class QueryCacher <ide> { <del> <ide> /** <ide> * The key or function to generate a key. <ide> * <ide><path>src/Datasource/QueryInterface.php <ide> */ <ide> interface QueryInterface <ide> { <del> <del> const JOIN_TYPE_INNER = 'INNER'; <del> const JOIN_TYPE_LEFT = 'LEFT'; <del> const JOIN_TYPE_RIGHT = 'RIGHT'; <add> public const JOIN_TYPE_INNER = 'INNER'; <add> public const JOIN_TYPE_LEFT = 'LEFT'; <add> public const JOIN_TYPE_RIGHT = 'RIGHT'; <ide> <ide> /** <ide> * Returns a key => value array representing a single aliased field <ide><path>src/Datasource/QueryTrait.php <ide> */ <ide> trait QueryTrait <ide> { <del> <ide> /** <ide> * Instance of a table object this query is bound to <ide> * <ide> public function toArray() <ide> * @return $this <ide> * @see \Cake\Collection\Iterator\MapReduce for details on how to use emit data to the map reducer. <ide> */ <del> public function mapReduce(callable $mapper = null, callable $reducer = null, $overwrite = false) <add> public function mapReduce(?callable $mapper = null, ?callable $reducer = null, $overwrite = false) <ide> { <ide> if ($overwrite) { <ide> $this->_mapReduce = []; <ide> public function getMapReducers() <ide> * @param bool|int $mode Whether or not to overwrite, append or prepend the formatter. <ide> * @return $this <ide> */ <del> public function formatResults(callable $formatter = null, $mode = 0) <add> public function formatResults(?callable $formatter = null, $mode = 0) <ide> { <ide> if ($mode === self::OVERWRITE) { <ide> $this->_formatters = []; <ide><path>src/Datasource/ResultSetDecorator.php <ide> */ <ide> class ResultSetDecorator extends Collection implements ResultSetInterface <ide> { <del> <ide> /** <ide> * Make this object countable. <ide> * <ide><path>src/Datasource/RulesAwareTrait.php <ide> */ <ide> trait RulesAwareTrait <ide> { <del> <ide> /** <ide> * The domain rules to be applied to entities saved by this table <ide> * <ide><path>src/Datasource/RulesChecker.php <ide> class RulesChecker <ide> * <ide> * @var string <ide> */ <del> const CREATE = 'create'; <add> public const CREATE = 'create'; <ide> <ide> /** <ide> * Indicates that the checking rules to apply are those used for updating entities <ide> * <ide> * @var string <ide> */ <del> const UPDATE = 'update'; <add> public const UPDATE = 'update'; <ide> <ide> /** <ide> * Indicates that the checking rules to apply are those used for deleting entities <ide> * <ide> * @var string <ide> */ <del> const DELETE = 'delete'; <add> public const DELETE = 'delete'; <ide> <ide> /** <ide> * The list of rules to be checked on both create and update operations <ide><path>src/Datasource/SchemaInterface.php <ide> */ <ide> interface SchemaInterface <ide> { <del> <ide> /** <ide> * Get the name of the table. <ide> * <ide><path>src/Error/BaseErrorHandler.php <ide> */ <ide> abstract class BaseErrorHandler <ide> { <del> <ide> /** <ide> * Options to use for the Error handling. <ide> * <ide> public function handleError($code, $description, $file = null, $line = null, $co <ide> $data += [ <ide> 'context' => $context, <ide> 'start' => 3, <del> 'path' => Debugger::trimPath($file) <add> 'path' => Debugger::trimPath($file), <ide> ]; <ide> } <ide> $this->_displayError($data, $debug); <ide> protected function _logError($level, $data) <ide> if (!empty($this->_options['trace'])) { <ide> $trace = Debugger::trace([ <ide> 'start' => 1, <del> 'format' => 'log' <add> 'format' => 'log', <ide> ]); <ide> <ide> $request = Router::getRequest(); <ide><path>src/Error/Debugger.php <ide> class Debugger <ide> * @var array <ide> */ <ide> protected $_defaultConfig = [ <del> 'outputMask' => [] <add> 'outputMask' => [], <ide> ]; <ide> <ide> /** <ide> class Debugger <ide> protected $_templates = [ <ide> 'log' => [ <ide> 'trace' => '{:reference} - {:path}, line {:line}', <del> 'error' => '{:error} ({:code}): {:description} in [{:file}, line {:line}]' <add> 'error' => '{:error} ({:code}): {:description} in [{:file}, line {:line}]', <ide> ], <ide> 'js' => [ <ide> 'error' => '', <ide> class Debugger <ide> 'txt' => [ <ide> 'error' => "{:error}: {:code} :: {:description} on line {:line} of {:path}\n{:info}", <ide> 'code' => '', <del> 'info' => '' <add> 'info' => '', <ide> ], <ide> 'base' => [ <ide> 'traceLine' => '{:reference} - {:path}, line {:line}', <ide> 'trace' => "Trace:\n{:trace}\n", <ide> 'context' => "Context:\n{:context}\n", <del> ] <add> ], <ide> ]; <ide> <ide> /** <ide> public static function formatTrace($backtrace, $options = []) <ide> 'args' => false, <ide> 'start' => 0, <ide> 'scope' => null, <del> 'exclude' => ['call_user_func_array', 'trigger_error'] <add> 'exclude' => ['call_user_func_array', 'trigger_error'], <ide> ]; <ide> $options = Hash::merge($defaults, $options); <ide> <ide> public static function formatTrace($backtrace, $options = []) <ide> 'line' => '??', <ide> 'file' => '[internal]', <ide> 'class' => null, <del> 'function' => '[main]' <add> 'function' => '[main]', <ide> ]; <ide> <ide> for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) { <ide> public static function excerpt($file, $line, $context = 2) <ide> continue; <ide> } <ide> $string = str_replace(["\r\n", "\n"], '', static::_highlight($data[$i])); <del> if ($i == $line) { <add> if ($i === $line) { <ide> $lines[] = '<span class="code-highlight">' . $string . '</span>'; <ide> } else { <ide> $lines[] = $string; <ide><path>src/Error/ExceptionRenderer.php <ide> */ <ide> class ExceptionRenderer implements ExceptionRendererInterface <ide> { <del> <ide> /** <ide> * The exception being handled. <ide> * <ide> class ExceptionRenderer implements ExceptionRendererInterface <ide> * @param \Exception $exception Exception. <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request - if this is set it will be used instead of creating a new one <ide> */ <del> public function __construct(Exception $exception, ServerRequestInterface $request = null) <add> public function __construct(Exception $exception, ?ServerRequestInterface $request = null) <ide> { <ide> $this->error = $exception; <ide> $this->request = $request; <ide> public function render() <ide> 'url' => h($url), <ide> 'error' => $unwrapped, <ide> 'code' => $code, <del> '_serialize' => ['message', 'url', 'code'] <add> '_serialize' => ['message', 'url', 'code'], <ide> ]; <ide> if ($isDebug) { <ide> $viewVars['trace'] = Debugger::formatTrace($unwrapped->getTrace(), [ <ide> 'format' => 'array', <del> 'args' => false <add> 'args' => false, <ide> ]); <ide> $viewVars['file'] = $exception->getFile() ?: 'null'; <ide> $viewVars['line'] = $exception->getLine() ?: 'null'; <ide><path>src/Error/FatalErrorException.php <ide> */ <ide> class FatalErrorException extends Exception <ide> { <del> <ide> /** <ide> * Constructor <ide> * <ide><path>src/Error/PHP7ErrorException.php <ide> */ <ide> class PHP7ErrorException extends Exception <ide> { <del> <ide> /** <ide> * The wrapped error object <ide> * <ide><path>src/Event/Decorator/AbstractDecorator.php <ide> */ <ide> abstract class AbstractDecorator <ide> { <del> <ide> /** <ide> * Callable <ide> * <ide><path>src/Event/Decorator/ConditionDecorator.php <ide> */ <ide> class ConditionDecorator extends AbstractDecorator <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Event/Decorator/SubjectFilterDecorator.php <ide> */ <ide> class SubjectFilterDecorator extends AbstractDecorator <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Event/Event.php <ide> */ <ide> class Event implements EventInterface <ide> { <del> <ide> /** <ide> * Name of the event <ide> * <ide> public function setResult($value = null) <ide> public function getData($key = null) <ide> { <ide> if ($key !== null) { <del> return isset($this->_data[$key]) ? $this->_data[$key] : null; <add> return $this->_data[$key] ?? null; <ide> } <ide> <ide> return (array)$this->_data; <ide><path>src/Event/EventDispatcherTrait.php <ide> */ <ide> trait EventDispatcherTrait <ide> { <del> <ide> /** <ide> * Instance of the Cake\Event\EventManager this object is using <ide> * to dispatch inner events. <ide><path>src/Event/EventList.php <ide> */ <ide> class EventList implements ArrayAccess, Countable <ide> { <del> <ide> /** <ide> * Events list <ide> * <ide><path>src/Event/EventListenerInterface.php <ide> */ <ide> interface EventListenerInterface <ide> { <del> <ide> /** <ide> * Returns a list of events this object is implementing. When the class is registered <ide> * in an event manager, each individual method will be associated with the respective event. <ide><path>src/Event/EventManager.php <ide> */ <ide> class EventManager implements EventManagerInterface <ide> { <del> <ide> /** <ide> * The default priority queue value for new, attached listeners <ide> * <ide> public function on($eventKey = null, $options = [], $callable = null) <ide> $argCount = func_num_args(); <ide> if ($argCount === 2) { <ide> $this->_listeners[$eventKey][static::$defaultPriority][] = [ <del> 'callable' => $options <add> 'callable' => $options, <ide> ]; <ide> <ide> return $this; <ide> } <ide> if ($argCount === 3) { <del> $priority = isset($options['priority']) ? $options['priority'] : static::$defaultPriority; <add> $priority = $options['priority'] ?? static::$defaultPriority; <ide> $this->_listeners[$eventKey][$priority][] = [ <del> 'callable' => $callable <add> 'callable' => $callable, <ide> ]; <ide> <ide> return $this; <ide> protected function _detachSubscriber(EventListenerInterface $subscriber, $eventK <ide> if (is_array($function)) { <ide> if (is_numeric(key($function))) { <ide> foreach ($function as $handler) { <del> $handler = isset($handler['callable']) ? $handler['callable'] : $handler; <add> $handler = $handler['callable'] ?? $handler; <ide> $this->off($key, [$subscriber, $handler]); <ide> } <ide> continue; <ide><path>src/Event/EventManagerInterface.php <ide> */ <ide> interface EventManagerInterface <ide> { <del> <ide> /** <ide> * Adds a new listener to an event. <ide> * <ide><path>src/Filesystem/File.php <ide> */ <ide> class File <ide> { <del> <ide> /** <ide> * Folder object of the file <ide> * <ide> protected static function _basename($path, $ext = null) <ide> { <ide> // check for multibyte string and use basename() if not found <ide> if (mb_strlen($path) === strlen($path)) { <del> return ($ext === null)? basename($path) : basename($path, $ext); <add> return ($ext === null) ? basename($path) : basename($path, $ext); <ide> } <ide> <ide> $splInfo = new SplFileInfo($path); <ide> protected static function _basename($path, $ext = null) <ide> $new = preg_replace("/({$ext})$/u", "", $name); <ide> <ide> // basename of '/etc/.d' is '.d' not '' <del> return ($new === '')? $name : $new; <add> return ($new === '') ? $name : $new; <ide> } <ide> <ide> /** <ide> public function exists() <ide> { <ide> $this->clearStatCache(); <ide> <del> return (file_exists($this->path) && is_file($this->path)); <add> return file_exists($this->path) && is_file($this->path); <ide> } <ide> <ide> /** <ide><path>src/Filesystem/Folder.php <ide> */ <ide> class Folder <ide> { <del> <ide> /** <ide> * Default scheme for Folder::copy <ide> * Recursively merges subfolders with the same name <ide> * <ide> * @var string <ide> */ <del> const MERGE = 'merge'; <add> public const MERGE = 'merge'; <ide> <ide> /** <ide> * Overwrite scheme for Folder::copy <ide> * subfolders with the same name will be replaced <ide> * <ide> * @var string <ide> */ <del> const OVERWRITE = 'overwrite'; <add> public const OVERWRITE = 'overwrite'; <ide> <ide> /** <ide> * Skip scheme for Folder::copy <ide> * if a subfolder with the same name exists it will be skipped <ide> * <ide> * @var string <ide> */ <del> const SKIP = 'skip'; <add> public const SKIP = 'skip'; <ide> <ide> /** <ide> * Sort mode by name <ide> * <ide> * @var string <ide> */ <del> const SORT_NAME = 'name'; <add> public const SORT_NAME = 'name'; <ide> <ide> /** <ide> * Sort mode by time <ide> * <ide> * @var string <ide> */ <del> const SORT_TIME = 'time'; <add> public const SORT_TIME = 'time'; <ide> <ide> /** <ide> * Path to Folder. <ide> class Folder <ide> */ <ide> protected $_fsorts = [ <ide> self::SORT_NAME => 'getPathname', <del> self::SORT_TIME => 'getCTime' <add> self::SORT_TIME => 'getCTime', <ide> ]; <ide> <ide> /** <ide> protected function _findRecursive($pattern, $sort = false) <ide> */ <ide> public static function isWindowsPath($path) <ide> { <del> return (preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) === '\\\\'); <add> return preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) === '\\\\'; <ide> } <ide> <ide> /** <ide> public static function isRegisteredStreamWrapper($path) <ide> public static function normalizeFullPath($path) <ide> { <ide> $to = Folder::correctSlashFor($path); <del> $from = ($to == '/' ? '\\' : '/'); <add> $from = ($to === '/' ? '\\' : '/'); <ide> <ide> return str_replace($from, $to, $path); <ide> } <ide> public function copy($to, array $options = []) <ide> 'mode' => $this->mode, <ide> 'skip' => [], <ide> 'scheme' => Folder::MERGE, <del> 'recursive' => true <add> 'recursive' => true, <ide> ]; <ide> <ide> $fromDir = $options['from']; <ide> public function copy($to, array $options = []) <ide> //@codingStandardsIgnoreEnd <ide> while (($item = readdir($handle)) !== false) { <ide> $to = Folder::addPathElement($toDir, $item); <del> if (($options['scheme'] != Folder::SKIP || !is_dir($to)) && !in_array($item, $exceptions)) { <add> if (($options['scheme'] !== Folder::SKIP || !is_dir($to)) && !in_array($item, $exceptions)) { <ide> $from = Folder::addPathElement($fromDir, $item); <del> if (is_file($from) && (!is_file($to) || $options['scheme'] != Folder::SKIP)) { <add> if (is_file($from) && (!is_file($to) || $options['scheme'] !== Folder::SKIP)) { <ide> if (copy($from, $to)) { <ide> chmod($to, intval($mode, 8)); <ide> touch($to, filemtime($from)); <ide><path>src/Form/Form.php <ide> use Cake\Event\EventDispatcherTrait; <ide> use Cake\Event\EventListenerInterface; <ide> use Cake\Event\EventManager; <del>use Cake\Form\Schema; <ide> use Cake\Utility\Hash; <ide> use Cake\Validation\ValidatorAwareInterface; <ide> use Cake\Validation\ValidatorAwareTrait; <ide> class Form implements EventListenerInterface, EventDispatcherInterface, Validato <ide> * <ide> * @var string <ide> */ <del> const VALIDATOR_PROVIDER_NAME = 'form'; <add> public const VALIDATOR_PROVIDER_NAME = 'form'; <ide> <ide> /** <ide> * The name of the event dispatched when a validator has been built. <ide> * <ide> * @var string <ide> */ <del> const BUILD_VALIDATOR_EVENT = 'Form.buildValidator'; <add> public const BUILD_VALIDATOR_EVENT = 'Form.buildValidator'; <ide> <ide> /** <ide> * The schema used by this form. <ide> class Form implements EventListenerInterface, EventDispatcherInterface, Validato <ide> * @param \Cake\Event\EventManager|null $eventManager The event manager. <ide> * Defaults to a new instance. <ide> */ <del> public function __construct(EventManager $eventManager = null) <add> public function __construct(?EventManager $eventManager = null) <ide> { <ide> if ($eventManager !== null) { <ide> $this->setEventManager($eventManager); <ide> public function implementedEvents() <ide> * @param \Cake\Form\Schema|null $schema The schema to set, or null. <ide> * @return \Cake\Form\Schema the schema instance. <ide> */ <del> public function schema(Schema $schema = null) <add> public function schema(?Schema $schema = null) <ide> { <ide> if ($schema === null && empty($this->_schema)) { <ide> $schema = $this->_buildSchema(new $this->_schemaClass); <ide> public function __debugInfo() <ide> $special = [ <ide> '_schema' => $this->schema()->__debugInfo(), <ide> '_errors' => $this->errors(), <del> '_validator' => $this->getValidator()->__debugInfo() <add> '_validator' => $this->getValidator()->__debugInfo(), <ide> ]; <ide> <ide> return $special + get_object_vars($this); <ide><path>src/Form/Schema.php <ide> */ <ide> class Schema <ide> { <del> <ide> /** <ide> * The fields in this schema. <ide> * <ide> public function fieldType($name) <ide> public function __debugInfo() <ide> { <ide> return [ <del> '_fields' => $this->_fields <add> '_fields' => $this->_fields, <ide> ]; <ide> } <ide> } <ide><path>src/Http/BaseApplication.php <ide> abstract class BaseApplication implements <ide> HttpApplicationInterface, <ide> PluginApplicationInterface <ide> { <del> <ide> use EventDispatcherTrait; <ide> <ide> /** <ide> abstract class BaseApplication implements <ide> * @param string $configDir The directory the bootstrap configuration is held in. <ide> * @param \Cake\Event\EventManagerInterface $eventManager Application event manager instance. <ide> */ <del> public function __construct($configDir, EventManagerInterface $eventManager = null) <add> public function __construct($configDir, ?EventManagerInterface $eventManager = null) <ide> { <ide> $this->configDir = $configDir; <ide> $this->plugins = Plugin::getCollection(); <ide><path>src/Http/Client.php <ide> */ <ide> class Client <ide> { <del> <ide> use InstanceConfigTrait; <ide> <ide> /** <ide> public function send(Request $request, $options = []) <ide> 'host' => $url->getHost(), <ide> 'port' => $url->getPort(), <ide> 'scheme' => $url->getScheme(), <del> 'protocolRelative' => true <add> 'protocolRelative' => true, <ide> ]); <ide> <ide> $request = $request->withUri(new Uri($locationUrl)); <ide> public function buildUrl($url, $query = [], $options = []) <ide> 'host' => null, <ide> 'port' => null, <ide> 'scheme' => 'http', <del> 'protocolRelative' => false <add> 'protocolRelative' => false, <ide> ]; <ide> $options += $defaults; <ide> <ide> public function buildUrl($url, $query = [], $options = []) <ide> <ide> $defaultPorts = [ <ide> 'http' => 80, <del> 'https' => 443 <add> 'https' => 443, <ide> ]; <ide> $out = $options['scheme'] . '://' . $options['host']; <del> if ($options['port'] && $options['port'] != $defaultPorts[$options['scheme']]) { <add> if ($options['port'] && $options['port'] !== $defaultPorts[$options['scheme']]) { <ide> $out .= ':' . $options['port']; <ide> } <ide> $out .= '/' . ltrim($url, '/'); <ide> protected function _createRequest($method, $url, $data, $options) <ide> } <ide> <ide> $request = new Request($url, $method, $headers, $data); <del> $cookies = isset($options['cookies']) ? $options['cookies'] : []; <add> $cookies = $options['cookies'] ?? []; <ide> /** @var \Cake\Http\Client\Request $request */ <ide> $request = $this->_cookies->addToRequest($request, $cookies); <ide> if (isset($options['auth'])) { <ide> protected function _typeHeaders($type) <ide> if (strpos($type, '/') !== false) { <ide> return [ <ide> 'Accept' => $type, <del> 'Content-Type' => $type <add> 'Content-Type' => $type, <ide> ]; <ide> } <ide> $typeMap = [ <ide><path>src/Http/Client/Adapter/Stream.php <ide> */ <ide> class Stream <ide> { <del> <ide> /** <ide> * Context resource used by the stream API. <ide> * <ide> public function createResponses($headers, $content) <ide> foreach ($indexes as $i => $start) { <ide> $end = isset($indexes[$i + 1]) ? $indexes[$i + 1] - $start : null; <ide> $headerSlice = array_slice($headers, $start, $end); <del> $body = $i == $last ? $content : ''; <add> $body = $i === $last ? $content : ''; <ide> $responses[] = $this->_buildResponse($headerSlice, $body); <ide> } <ide> <ide><path>src/Http/Client/Auth/Basic.php <ide> */ <ide> class Basic <ide> { <del> <ide> /** <ide> * Add Authorization header to the request. <ide> * <ide><path>src/Http/Client/Auth/Digest.php <ide> */ <ide> class Digest <ide> { <del> <ide> /** <ide> * Instance of Cake\Http\Client <ide> * <ide><path>src/Http/Client/Auth/Oauth.php <ide> */ <ide> class Oauth <ide> { <del> <ide> /** <ide> * Add headers for Oauth authorization. <ide> * <ide> protected function _plaintext($request, $credentials) <ide> */ <ide> protected function _hmacSha1($request, $credentials) <ide> { <del> $nonce = isset($credentials['nonce']) ? $credentials['nonce'] : uniqid(); <del> $timestamp = isset($credentials['timestamp']) ? $credentials['timestamp'] : time(); <add> $nonce = $credentials['nonce'] ?? uniqid(); <add> $timestamp = $credentials['timestamp'] ?? time(); <ide> $values = [ <ide> 'oauth_version' => '1.0', <ide> 'oauth_nonce' => $nonce, <ide> protected function _rsaSha1($request, $credentials) <ide> throw new RuntimeException('RSA-SHA1 signature method requires the OpenSSL extension.'); <ide> } <ide> <del> $nonce = isset($credentials['nonce']) ? $credentials['nonce'] : bin2hex(Security::randomBytes(16)); <del> $timestamp = isset($credentials['timestamp']) ? $credentials['timestamp'] : time(); <add> $nonce = $credentials['nonce'] ?? bin2hex(Security::randomBytes(16)); <add> $timestamp = $credentials['timestamp'] ?? time(); <ide> $values = [ <ide> 'oauth_version' => '1.0', <ide> 'oauth_nonce' => $nonce, <ide><path>src/Http/Client/FormData.php <ide> */ <ide> class FormData implements Countable <ide> { <del> <ide> /** <ide> * Boundary marker. <ide> * <ide><path>src/Http/Client/FormDataPart.php <ide> */ <ide> class FormDataPart <ide> { <del> <ide> /** <ide> * Name of the value. <ide> * <ide><path>src/Http/Client/Message.php <ide> */ <ide> class Message <ide> { <del> <ide> /** <ide> * HTTP 200 code <ide> * <ide> * @var int <ide> */ <del> const STATUS_OK = 200; <add> public const STATUS_OK = 200; <ide> <ide> /** <ide> * HTTP 201 code <ide> * <ide> * @var int <ide> */ <del> const STATUS_CREATED = 201; <add> public const STATUS_CREATED = 201; <ide> <ide> /** <ide> * HTTP 202 code <ide> * <ide> * @var int <ide> */ <del> const STATUS_ACCEPTED = 202; <add> public const STATUS_ACCEPTED = 202; <ide> <ide> /** <ide> * HTTP 203 code <ide> * <ide> * @var int <ide> */ <del> const STATUS_NON_AUTHORITATIVE_INFORMATION = 203; <add> public const STATUS_NON_AUTHORITATIVE_INFORMATION = 203; <ide> <ide> /** <ide> * HTTP 204 code <ide> * <ide> * @var int <ide> */ <del> const STATUS_NO_CONTENT = 204; <add> public const STATUS_NO_CONTENT = 204; <ide> <ide> /** <ide> * HTTP 301 code <ide> * <ide> * @var int <ide> */ <del> const STATUS_MOVED_PERMANENTLY = 301; <add> public const STATUS_MOVED_PERMANENTLY = 301; <ide> <ide> /** <ide> * HTTP 302 code <ide> * <ide> * @var int <ide> */ <del> const STATUS_FOUND = 302; <add> public const STATUS_FOUND = 302; <ide> <ide> /** <ide> * HTTP 303 code <ide> * <ide> * @var int <ide> */ <del> const STATUS_SEE_OTHER = 303; <add> public const STATUS_SEE_OTHER = 303; <ide> <ide> /** <ide> * HTTP 307 code <ide> * <ide> * @var int <ide> */ <del> const STATUS_TEMPORARY_REDIRECT = 307; <add> public const STATUS_TEMPORARY_REDIRECT = 307; <ide> <ide> /** <ide> * HTTP GET method <ide> * <ide> * @var string <ide> */ <del> const METHOD_GET = 'GET'; <add> public const METHOD_GET = 'GET'; <ide> <ide> /** <ide> * HTTP POST method <ide> * <ide> * @var string <ide> */ <del> const METHOD_POST = 'POST'; <add> public const METHOD_POST = 'POST'; <ide> <ide> /** <ide> * HTTP PUT method <ide> * <ide> * @var string <ide> */ <del> const METHOD_PUT = 'PUT'; <add> public const METHOD_PUT = 'PUT'; <ide> <ide> /** <ide> * HTTP DELETE method <ide> * <ide> * @var string <ide> */ <del> const METHOD_DELETE = 'DELETE'; <add> public const METHOD_DELETE = 'DELETE'; <ide> <ide> /** <ide> * HTTP PATCH method <ide> * <ide> * @var string <ide> */ <del> const METHOD_PATCH = 'PATCH'; <add> public const METHOD_PATCH = 'PATCH'; <ide> <ide> /** <ide> * HTTP OPTIONS method <ide> * <ide> * @var string <ide> */ <del> const METHOD_OPTIONS = 'OPTIONS'; <add> public const METHOD_OPTIONS = 'OPTIONS'; <ide> <ide> /** <ide> * HTTP TRACE method <ide> * <ide> * @var string <ide> */ <del> const METHOD_TRACE = 'TRACE'; <add> public const METHOD_TRACE = 'TRACE'; <ide> <ide> /** <ide> * HTTP HEAD method <ide> * <ide> * @var string <ide> */ <del> const METHOD_HEAD = 'HEAD'; <add> public const METHOD_HEAD = 'HEAD'; <ide> <ide> /** <ide> * The array of cookies in the response. <ide><path>src/Http/Client/Request.php <ide> */ <ide> namespace Cake\Http\Client; <ide> <del>use Cake\Core\Exception\Exception; <ide> use Psr\Http\Message\RequestInterface; <ide> use Zend\Diactoros\RequestTrait; <ide> use Zend\Diactoros\Stream; <ide> public function __construct($url = '', $method = self::METHOD_GET, array $header <ide> $this->uri = $this->createUri($url); <ide> $headers += [ <ide> 'Connection' => 'close', <del> 'User-Agent' => 'CakePHP' <add> 'User-Agent' => 'CakePHP', <ide> ]; <ide> $this->addHeaders($headers); <ide> $this->body($data); <ide><path>src/Http/Client/Response.php <ide> public function isRedirect() <ide> static::STATUS_TEMPORARY_REDIRECT, <ide> ]; <ide> <del> return ( <del> in_array($this->code, $codes) && <del> $this->getHeaderLine('Location') <del> ); <add> return in_array($this->code, $codes) && <add> $this->getHeaderLine('Location'); <ide> } <ide> <ide> /** <ide> protected function convertCookieToArray(CookieInterface $cookie) <ide> 'domain' => $cookie->getDomain(), <ide> 'secure' => $cookie->isSecure(), <ide> 'httponly' => $cookie->isHttpOnly(), <del> 'expires' => $cookie->getFormattedExpires() <add> 'expires' => $cookie->getFormattedExpires(), <ide> ]; <ide> } <ide> <ide><path>src/Http/ControllerFactory.php <ide> protected function missingController($request) <ide> 'class' => $request->getParam('controller'), <ide> 'plugin' => $request->getParam('plugin'), <ide> 'prefix' => $request->getParam('prefix'), <del> '_ext' => $request->getParam('_ext') <add> '_ext' => $request->getParam('_ext'), <ide> ]); <ide> } <ide> } <ide><path>src/Http/Cookie/Cookie.php <ide> */ <ide> class Cookie implements CookieInterface <ide> { <del> <ide> /** <ide> * Cookie name <ide> * <ide><path>src/Http/Cookie/CookieCollection.php <ide> */ <ide> class CookieCollection implements IteratorAggregate, Countable <ide> { <del> <ide> /** <ide> * Cookie objects <ide> * <ide> protected static function parseSetCookieHeader($values) <ide> 'secure' => false, <ide> 'httponly' => false, <ide> 'expires' => null, <del> 'max-age' => null <add> 'max-age' => null, <ide> ]; <ide> foreach ($parts as $i => $part) { <ide> if (strpos($part, '=') !== false) { <ide><path>src/Http/Cookie/CookieInterface.php <ide> */ <ide> interface CookieInterface <ide> { <del> <ide> /** <ide> * Expires attribute format. <ide> * <ide> * @var string <ide> */ <del> const EXPIRES_FORMAT = 'D, d-M-Y H:i:s T'; <add> public const EXPIRES_FORMAT = 'D, d-M-Y H:i:s T'; <ide> <ide> /** <ide> * Sets the cookie name <ide><path>src/Http/CorsBuilder.php <ide> */ <ide> class CorsBuilder <ide> { <del> <ide> /** <ide> * The response object this builder is attached to. <ide> * <ide><path>src/Http/Exception/BadRequestException.php <ide> */ <ide> class BadRequestException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Exception/ConflictException.php <ide> */ <ide> class ConflictException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Exception/ForbiddenException.php <ide> */ <ide> class ForbiddenException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Exception/GoneException.php <ide> */ <ide> class GoneException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Exception/InternalErrorException.php <ide> */ <ide> class InternalErrorException extends HttpException <ide> { <del> <ide> /** <ide> * Constructor <ide> * <ide><path>src/Http/Exception/InvalidCsrfTokenException.php <ide> */ <ide> class InvalidCsrfTokenException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Exception/MethodNotAllowedException.php <ide> */ <ide> class MethodNotAllowedException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Exception/NotAcceptableException.php <ide> */ <ide> class NotAcceptableException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Exception/NotFoundException.php <ide> */ <ide> class NotFoundException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Exception/NotImplementedException.php <ide> */ <ide> class NotImplementedException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Exception/ServiceUnavailableException.php <ide> */ <ide> class ServiceUnavailableException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Exception/UnauthorizedException.php <ide> */ <ide> class UnauthorizedException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Exception/UnavailableForLegalReasonsException.php <ide> */ <ide> class UnavailableForLegalReasonsException extends HttpException <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Http/Middleware/SecurityHeadersMiddleware.php <ide> */ <ide> class SecurityHeadersMiddleware <ide> { <del> <ide> /** <ide> * Security related headers to set <ide> * <ide> public function setReferrerPolicy($policy = 'same-origin') <ide> 'no-referrer', 'no-referrer-when-downgrade', 'origin', <ide> 'origin-when-cross-origin', <ide> 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin', <del> 'unsafe-url' <add> 'unsafe-url', <ide> ]; <ide> <ide> $this->checkValues($policy, $available); <ide><path>src/Http/Response.php <ide> <ide> use Cake\Core\Configure; <ide> use Cake\Filesystem\File; <del>use Cake\Filesystem\Folder; <ide> use Cake\Http\Cookie\Cookie; <ide> use Cake\Http\Cookie\CookieCollection; <ide> use Cake\Http\Cookie\CookieInterface; <del>use Cake\Http\CorsBuilder; <ide> use Cake\Http\Exception\NotFoundException; <del>use Cake\Log\Log; <ide> use DateTime; <ide> use DateTimeZone; <ide> use InvalidArgumentException; <ide> */ <ide> class Response implements ResponseInterface <ide> { <del> <ide> use MessageTrait; <ide> <ide> /** <ide> class Response implements ResponseInterface <ide> 'mkv' => 'video/x-matroska', <ide> 'pkpass' => 'application/vnd.apple.pkpass', <ide> 'ajax' => 'text/html', <del> 'bmp' => 'image/bmp' <add> 'bmp' => 'image/bmp', <ide> ]; <ide> <ide> /** <ide> protected function _setContentType() <ide> return; <ide> } <ide> $whitelist = [ <del> 'application/javascript', 'application/json', 'application/xml', 'application/rss+xml' <add> 'application/javascript', 'application/json', 'application/xml', 'application/rss+xml', <ide> ]; <ide> <ide> $charset = false; <ide> public function notModified() <ide> 'Content-Length', <ide> 'Content-MD5', <ide> 'Content-Type', <del> 'Last-Modified' <add> 'Last-Modified', <ide> ]; <ide> foreach ($remove as $header) { <ide> $this->_clearHeader($header); <ide> public function withNotModified() <ide> 'Content-Length', <ide> 'Content-MD5', <ide> 'Content-Type', <del> 'Last-Modified' <add> 'Last-Modified', <ide> ]; <ide> foreach ($remove as $header) { <ide> $new = $new->withoutHeader($header); <ide> public function withCookie($name, $data = '') <ide> 'path' => '/', <ide> 'domain' => '', <ide> 'secure' => false, <del> 'httpOnly' => false <add> 'httpOnly' => false, <ide> ]; <ide> $expires = $data['expire'] ? new DateTime('@' . $data['expire']) : null; <ide> $cookie = new Cookie( <ide> public function withExpiredCookie($name, $options = []) <ide> 'path' => '/', <ide> 'domain' => '', <ide> 'secure' => false, <del> 'httpOnly' => false <add> 'httpOnly' => false, <ide> ]; <ide> <ide> $cookie = new Cookie( <ide> protected function convertCookieToArray(CookieInterface $cookie) <ide> 'domain' => $cookie->getDomain(), <ide> 'secure' => $cookie->isSecure(), <ide> 'httpOnly' => $cookie->isHttpOnly(), <del> 'expire' => $cookie->getExpiresTimestamp() <add> 'expire' => $cookie->getExpiresTimestamp(), <ide> ]; <ide> } <ide> <ide> public function withFile($path, array $options = []) <ide> $file = $this->validateFile($path); <ide> $options += [ <ide> 'name' => null, <del> 'download' => null <add> 'download' => null, <ide> ]; <ide> <ide> $extension = strtolower($file->ext()); <ide> protected function _fileRange($file, $httpRange) <ide> preg_match('/^bytes\s*=\s*(\d+)?\s*-\s*(\d+)?$/', $httpRange, $matches); <ide> if ($matches) { <ide> $start = $matches[1]; <del> $end = isset($matches[2]) ? $matches[2] : ''; <add> $end = $matches[2] ?? ''; <ide> } <ide> <ide> if ($start === '') { <ide><path>src/Http/ResponseEmitter.php <ide> protected function emitCookies(array $cookies) <ide> 'path' => '', <ide> 'domain' => '', <ide> 'secure' => false, <del> 'httponly' => false <add> 'httponly' => false, <ide> ]; <ide> <ide> foreach ($parts as $part) { <ide> protected function emitCookies(array $cookies) <ide> */ <ide> protected function flush($maxBufferLevel = null) <ide> { <del> if (null === $maxBufferLevel) { <add> if ($maxBufferLevel === null) { <ide> $maxBufferLevel = ob_get_level(); <ide> } <ide> <ide><path>src/Http/Server.php <ide> public function __construct(HttpApplicationInterface $app) <ide> * @return \Psr\Http\Message\ResponseInterface <ide> * @throws \RuntimeException When the application does not make a response. <ide> */ <del> public function run(ServerRequestInterface $request = null, ResponseInterface $response = null) <add> public function run(?ServerRequestInterface $request = null, ?ResponseInterface $response = null) <ide> { <ide> $this->bootstrap(); <ide> <ide> protected function bootstrap() <ide> * When null, a SAPI Stream Emitter will be used. <ide> * @return void <ide> */ <del> public function emit(ResponseInterface $response, EmitterInterface $emitter = null) <add> public function emit(ResponseInterface $response, ?EmitterInterface $emitter = null) <ide> { <ide> if (!$emitter) { <ide> $emitter = new ResponseEmitter(); <ide><path>src/Http/ServerRequest.php <ide> use Cake\Core\Configure; <ide> use Cake\Http\Cookie\CookieCollection; <ide> use Cake\Http\Exception\MethodNotAllowedException; <del>use Cake\Http\Session; <ide> use Cake\Utility\Hash; <ide> use InvalidArgumentException; <ide> use Psr\Http\Message\ServerRequestInterface; <ide> */ <ide> class ServerRequest implements ServerRequestInterface <ide> { <del> <ide> /** <ide> * Array of parameters parsed from the URL. <ide> * <ide> class ServerRequest implements ServerRequestInterface <ide> 'controller' => null, <ide> 'action' => null, <ide> '_ext' => null, <del> 'pass' => [] <add> 'pass' => [], <ide> ]; <ide> <ide> /** <ide> protected function _setConfig($config) <ide> <ide> if (empty($config['session'])) { <ide> $config['session'] = new Session([ <del> 'cookiePath' => $config['base'] <add> 'cookiePath' => $config['base'], <ide> ]); <ide> } <ide> <ide> protected function _headerDetector($detect) <ide> return call_user_func($value, $header); <ide> } <ide> <del> return ($header === $value); <add> return $header === $value; <ide> } <ide> } <ide> <ide> protected function _paramDetector($detect) <ide> if (isset($detect['value'])) { <ide> $value = $detect['value']; <ide> <del> return isset($this->params[$key]) ? $this->params[$key] == $value : false; <add> return isset($this->params[$key]) ? $this->params[$key] === $value : false; <ide> } <ide> if (isset($detect['options'])) { <ide> return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false; <ide> protected function _environmentDetector($detect) <ide> { <ide> if (isset($detect['env'])) { <ide> if (isset($detect['value'])) { <del> return $this->getEnv($detect['env']) == $detect['value']; <add> return $this->getEnv($detect['env']) === $detect['value']; <ide> } <ide> if (isset($detect['pattern'])) { <ide> return (bool)preg_match($detect['pattern'], $this->getEnv($detect['env'])); <ide> public function getAttributes() <ide> 'params' => $this->params, <ide> 'webroot' => $this->webroot, <ide> 'base' => $this->base, <del> 'here' => $this->here <add> 'here' => $this->here, <ide> ]; <ide> <ide> return $this->attributes + $emulated; <ide><path>src/Http/ServerRequestFactory.php <ide> abstract class ServerRequestFactory extends BaseFactory <ide> * @throws \InvalidArgumentException for invalid file values <ide> */ <ide> public static function fromGlobals( <del> array $server = null, <del> array $query = null, <del> array $body = null, <del> array $cookies = null, <del> array $files = null <add> ?array $server = null, <add> ?array $query = null, <add> ?array $body = null, <add> ?array $cookies = null, <add> ?array $files = null <ide> ) { <ide> $server = static::normalizeServer($server ?: $_SERVER); <ide> $uri = static::createUri($server); <ide> $sessionConfig = (array)Configure::read('Session') + [ <ide> 'defaults' => 'php', <del> 'cookiePath' => $uri->webroot <add> 'cookiePath' => $uri->webroot, <ide> ]; <ide> $session = Session::create($sessionConfig); <ide> $request = new ServerRequest([ <ide> protected static function getBase($uri, $server) <ide> $config = (array)Configure::read('App') + [ <ide> 'base' => null, <ide> 'webroot' => null, <del> 'baseUrl' => null <add> 'baseUrl' => null, <ide> ]; <ide> $base = $config['base']; <ide> $baseUrl = $config['baseUrl']; <ide><path>src/Http/Session.php <ide> */ <ide> class Session <ide> { <del> <ide> /** <ide> * The Session handler instance used as an engine for persisting the session data. <ide> * <ide> public static function create($sessionConfig = []) <ide> } <ide> } <ide> <del> if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS') && ini_get('session.cookie_secure') != 1) { <add> if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS') && ini_get('session.cookie_secure') !== 1) { <ide> $sessionConfig['ini']['session.cookie_secure'] = 1; <ide> } <ide> <ide> public static function create($sessionConfig = []) <ide> unset($sessionConfig['ini']['session.save_handler']); <ide> } <ide> <del> if (!isset($sessionConfig['ini']['session.cookie_httponly']) && ini_get('session.cookie_httponly') != 1) { <add> if (!isset($sessionConfig['ini']['session.cookie_httponly']) && ini_get('session.cookie_httponly') !== 1) { <ide> $sessionConfig['ini']['session.cookie_httponly'] = 1; <ide> } <ide> <ide> protected static function _defaultConfig($name) <ide> 'php' => [ <ide> 'ini' => [ <ide> 'session.use_trans_sid' => 0, <del> ] <add> ], <ide> ], <ide> 'cake' => [ <ide> 'ini' => [ <ide> 'session.use_trans_sid' => 0, <ide> 'session.serialize_handler' => 'php', <ide> 'session.use_cookies' => 1, <ide> 'session.save_path' => TMP . 'sessions', <del> 'session.save_handler' => 'files' <del> ] <add> 'session.save_handler' => 'files', <add> ], <ide> ], <ide> 'cache' => [ <ide> 'ini' => [ <ide> protected static function _defaultConfig($name) <ide> ], <ide> 'handler' => [ <ide> 'engine' => 'CacheSession', <del> 'config' => 'default' <del> ] <add> 'config' => 'default', <add> ], <ide> ], <ide> 'database' => [ <ide> 'ini' => [ <ide> protected static function _defaultConfig($name) <ide> 'session.serialize_handler' => 'php', <ide> ], <ide> 'handler' => [ <del> 'engine' => 'DatabaseSession' <del> ] <del> ] <add> 'engine' => 'DatabaseSession', <add> ], <add> ], <ide> ]; <ide> <ide> if (isset($defaults[$name])) { <ide> public function read($name = null) <ide> } <ide> <ide> if ($name === null) { <del> return isset($_SESSION) ? $_SESSION : []; <add> return $_SESSION ?? []; <ide> } <ide> <ide> return Hash::get($_SESSION, $name); <ide> public function write($name, $value = null) <ide> $write = [$name => $value]; <ide> } <ide> <del> $data = isset($_SESSION) ? $_SESSION : []; <add> $data = $_SESSION ?? []; <ide> foreach ($write as $key => $val) { <ide> $data = Hash::insert($data, $key, $val); <ide> } <ide><path>src/Http/Session/CacheSession.php <ide> */ <ide> class CacheSession implements SessionHandlerInterface <ide> { <del> <ide> /** <ide> * Options for this session engine <ide> * <ide><path>src/I18n/ChainMessagesLoader.php <ide> */ <ide> class ChainMessagesLoader <ide> { <del> <ide> /** <ide> * The list of callables to execute one after another for loading messages <ide> * <ide><path>src/I18n/DateFormatTrait.php <ide> */ <ide> trait DateFormatTrait <ide> { <del> <ide> /** <ide> * The default locale to be used for displaying formatted date strings. <ide> * <ide> public function __debugInfo() <ide> return [ <ide> 'time' => $this->toIso8601String(), <ide> 'timezone' => $this->getTimezone()->getName(), <del> 'fixedNowTime' => static::hasTestNow() ? static::getTestNow()->toIso8601String() : false <add> 'fixedNowTime' => static::hasTestNow() ? static::getTestNow()->toIso8601String() : false, <ide> ]; <ide> } <ide> } <ide><path>src/I18n/Formatter/IcuFormatter.php <ide> */ <ide> class IcuFormatter implements FormatterInterface <ide> { <del> <ide> /** <ide> * Returns a string with all passed variables interpolated into the original <ide> * message. Variables are interpolated using the MessageFormatter class. <ide><path>src/I18n/Formatter/SprintfFormatter.php <ide> */ <ide> class SprintfFormatter implements FormatterInterface <ide> { <del> <ide> /** <ide> * Returns a string with all passed variables interpolated into the original <ide> * message. Variables are interpolated using the sprintf format. <ide><path>src/I18n/FrozenTime.php <ide> class FrozenTime extends Chronos implements JsonSerializable <ide> * <ide> * @var string <ide> */ <del> const UNIX_TIMESTAMP_FORMAT = 'unixTimestampFormat'; <add> public const UNIX_TIMESTAMP_FORMAT = 'unixTimestampFormat'; <ide> <ide> /** <ide> * {@inheritDoc} <ide><path>src/I18n/I18n.php <ide> */ <ide> class I18n <ide> { <del> <ide> /** <ide> * Default locale <ide> * <ide> * @var string <ide> */ <del> const DEFAULT_LOCALE = 'en_US'; <add> public const DEFAULT_LOCALE = 'en_US'; <ide> <ide> /** <ide> * The translators collection <ide><path>src/I18n/MessagesFileLoader.php <ide> */ <ide> class MessagesFileLoader <ide> { <del> <ide> /** <ide> * The package (domain) name. <ide> * <ide> public function translationsFolders() <ide> <ide> $folders = [ <ide> implode('_', [$locale['language'], $locale['region']]), <del> $locale['language'] <add> $locale['language'], <ide> ]; <ide> <ide> $searchPaths = []; <ide><path>src/I18n/Number.php <ide> */ <ide> class Number <ide> { <del> <ide> /** <ide> * Default locale <ide> * <ide> * @var string <ide> */ <del> const DEFAULT_LOCALE = 'en_US'; <add> public const DEFAULT_LOCALE = 'en_US'; <ide> <ide> /** <ide> * Format type to format as currency <ide> * <ide> * @var string <ide> */ <del> const FORMAT_CURRENCY = 'currency'; <add> public const FORMAT_CURRENCY = 'currency'; <ide> <ide> /** <ide> * A list of number formatters indexed by locale and type <ide> public static function currency($value, $currency = null, array $options = []) <ide> $abs = abs($value); <ide> if (!empty($options['fractionSymbol']) && $abs > 0 && $abs < 1) { <ide> $value *= 100; <del> $pos = isset($options['fractionPosition']) ? $options['fractionPosition'] : 'after'; <add> $pos = $options['fractionPosition'] ?? 'after'; <ide> <ide> return static::format($value, ['precision' => 0, $pos => $options['fractionSymbol']]); <ide> } <ide> <del> $before = isset($options['before']) ? $options['before'] : null; <del> $after = isset($options['after']) ? $options['after'] : null; <add> $before = $options['before'] ?? null; <add> $after = $options['after'] ?? null; <ide> <ide> return $before . $formatter->formatCurrency($value, $currency) . $after; <ide> } <ide> public static function defaultCurrency($currency = null) <ide> */ <ide> public static function formatter($options = []) <ide> { <del> $locale = isset($options['locale']) ? $options['locale'] : ini_get('intl.default_locale'); <add> $locale = $options['locale'] ?? ini_get('intl.default_locale'); <ide> <ide> if (!$locale) { <ide> $locale = static::DEFAULT_LOCALE; <ide> public static function formatter($options = []) <ide> 'places' => null, <ide> 'precision' => null, <ide> 'pattern' => null, <del> 'useIntlCode' => null <add> 'useIntlCode' => null, <ide> ]); <ide> if (empty($options)) { <ide> return $formatter; <ide><path>src/I18n/Parser/MoFileParser.php <ide> */ <ide> class MoFileParser <ide> { <del> <ide> /** <ide> * Magic used for validating the format of a MO file as well as <ide> * detecting if the machine used to create that file was little endian. <ide> * <ide> * @var float <ide> */ <del> const MO_LITTLE_ENDIAN_MAGIC = 0x950412de; <add> public const MO_LITTLE_ENDIAN_MAGIC = 0x950412de; <ide> <ide> /** <ide> * Magic used for validating the format of a MO file as well as <ide> * detecting if the machine used to create that file was big endian. <ide> * <ide> * @var float <ide> */ <del> const MO_BIG_ENDIAN_MAGIC = 0xde120495; <add> public const MO_BIG_ENDIAN_MAGIC = 0xde120495; <ide> <ide> /** <ide> * The size of the header of a MO file in bytes. <ide> * <ide> * @var int <ide> */ <del> const MO_HEADER_SIZE = 28; <add> public const MO_HEADER_SIZE = 28; <ide> <ide> /** <ide> * Parses machine object (MO) format, independent of the machine's endian it <ide> public function parse($resource) <ide> $magic = unpack('V1', fread($stream, 4)); <ide> $magic = hexdec(substr(dechex(current($magic)), -8)); <ide> <del> if ($magic == self::MO_LITTLE_ENDIAN_MAGIC) { <add> if ($magic === self::MO_LITTLE_ENDIAN_MAGIC) { <ide> $isBigEndian = false; <del> } elseif ($magic == self::MO_BIG_ENDIAN_MAGIC) { <add> } elseif ($magic === self::MO_BIG_ENDIAN_MAGIC) { <ide> $isBigEndian = true; <ide> } else { <ide> throw new RuntimeException('Invalid format for MO translations file'); <ide><path>src/I18n/Parser/PoFileParser.php <ide> public function parse($resource) <ide> <ide> $defaults = [ <ide> 'ids' => [], <del> 'translated' => null <add> 'translated' => null, <ide> ]; <ide> <ide> $messages = []; <ide> protected function _addMessage(array &$messages, array $item) <ide> } <ide> <ide> $singular = stripcslashes($item['ids']['singular']); <del> $context = isset($item['context']) ? $item['context'] : null; <add> $context = $item['context'] ?? null; <ide> $translation = $item['translated']; <ide> <ide> if (is_array($translation)) { <ide><path>src/I18n/PluralRules.php <ide> */ <ide> class PluralRules <ide> { <del> <ide> /** <ide> * A map of locale => plurals group used to determine <ide> * which plural rules apply to the language <ide> public static function calculate($locale, $n) <ide> case 0: <ide> return 0; <ide> case 1: <del> return $n == 1 ? 0 : 1; <add> return $n === 1 ? 0 : 1; <ide> case 2: <ide> return $n > 1 ? 1 : 0; <ide> case 3: <del> return $n % 10 == 1 && $n % 100 != 11 ? 0 : <add> return $n % 10 === 1 && $n % 100 !== 11 ? 0 : <ide> (($n % 10 >= 2 && $n % 10 <= 4) && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2); <ide> case 4: <del> return $n == 1 ? 0 : <add> return $n === 1 ? 0 : <ide> ($n >= 2 && $n <= 4 ? 1 : 2); <ide> case 5: <del> return $n == 1 ? 0 : <del> ($n == 2 ? 1 : ($n < 7 ? 2 : ($n < 11 ? 3 : 4))); <add> return $n === 1 ? 0 : <add> ($n === 2 ? 1 : ($n < 7 ? 2 : ($n < 11 ? 3 : 4))); <ide> case 6: <del> return $n % 10 == 1 && $n % 100 != 11 ? 0 : <add> return $n % 10 === 1 && $n % 100 !== 11 ? 0 : <ide> ($n % 10 >= 2 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2); <ide> case 7: <del> return $n % 100 == 1 ? 1 : <del> ($n % 100 == 2 ? 2 : ($n % 100 == 3 || $n % 100 == 4 ? 3 : 0)); <add> return $n % 100 === 1 ? 1 : <add> ($n % 100 === 2 ? 2 : ($n % 100 === 3 || $n % 100 === 4 ? 3 : 0)); <ide> case 8: <del> return $n % 10 == 1 ? 0 : ($n % 10 == 2 ? 1 : 2); <add> return $n % 10 === 1 ? 0 : ($n % 10 === 2 ? 1 : 2); <ide> case 9: <del> return $n == 1 ? 0 : <del> ($n == 0 || ($n % 100 > 0 && $n % 100 <= 10) ? 1 : <add> return $n === 1 ? 0 : <add> ($n === 0 || ($n % 100 > 0 && $n % 100 <= 10) ? 1 : <ide> ($n % 100 > 10 && $n % 100 < 20 ? 2 : 3)); <ide> case 10: <del> return $n % 10 == 1 && $n % 100 != 11 ? 0 : ($n != 0 ? 1 : 2); <add> return $n % 10 === 1 && $n % 100 !== 11 ? 0 : ($n !== 0 ? 1 : 2); <ide> case 11: <del> return $n == 1 ? 0 : <add> return $n === 1 ? 0 : <ide> ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2); <ide> case 12: <del> return $n == 1 ? 0 : <del> ($n == 0 || $n % 100 > 0 && $n % 100 < 20 ? 1 : 2); <add> return $n === 1 ? 0 : <add> ($n === 0 || $n % 100 > 0 && $n % 100 < 20 ? 1 : 2); <ide> case 13: <del> return $n == 0 ? 0 : <del> ($n == 1 ? 1 : <del> ($n == 2 ? 2 : <add> return $n === 0 ? 0 : <add> ($n === 1 ? 1 : <add> ($n === 2 ? 2 : <ide> ($n % 100 >= 3 && $n % 100 <= 10 ? 3 : <ide> ($n % 100 >= 11 ? 4 : 5)))); <ide> case 14: <del> return $n == 1 ? 0 : <del> ($n == 2 ? 1 : <del> ($n != 8 && $n != 11 ? 2 : 3)); <add> return $n === 1 ? 0 : <add> ($n === 2 ? 1 : <add> ($n !== 8 && $n !== 11 ? 2 : 3)); <ide> case 15: <del> return ($n % 10 != 1 || $n % 100 == 11) ? 1 : 0; <add> return ($n % 10 !== 1 || $n % 100 === 11) ? 1 : 0; <ide> } <ide> } <ide> } <ide><path>src/I18n/RelativeTimeFormatter.php <ide> class RelativeTimeFormatter <ide> * @return string The difference between the two days in a human readable format <ide> * @see \Cake\Chronos\ChronosInterface::diffForHumans <ide> */ <del> public function diffForHumans(ChronosInterface $date, ChronosInterface $other = null, $absolute = false) <add> public function diffForHumans(ChronosInterface $date, ?ChronosInterface $other = null, $absolute = false) <ide> { <ide> $isNow = $other === null; <ide> if ($isNow) { <ide> public function timeAgoInWords(DateTimeInterface $time, array $options = []) <ide> 'day' => __d('cake', 'about a day ago'), <ide> 'week' => __d('cake', 'about a week ago'), <ide> 'month' => __d('cake', 'about a month ago'), <del> 'year' => __d('cake', 'about a year ago') <add> 'year' => __d('cake', 'about a year ago'), <ide> ]; <ide> <ide> return $relativeDate ? sprintf($options['relativeString'], $relativeDate) : $aboutAgo[$fWord]; <ide> public function timeAgoInWords(DateTimeInterface $time, array $options = []) <ide> 'day' => __d('cake', 'in about a day'), <ide> 'week' => __d('cake', 'in about a week'), <ide> 'month' => __d('cake', 'in about a month'), <del> 'year' => __d('cake', 'in about a year') <add> 'year' => __d('cake', 'in about a year'), <ide> ]; <ide> <ide> return $aboutIn[$fWord]; <ide> protected function _diffData($futureTime, $pastTime, $backwards, $options) <ide> $days = ($daysInFutureMonth - $past['d']) + $future['d']; <ide> } <ide> <del> if ($future['m'] != $past['m']) { <add> if ($future['m'] !== $past['m']) { <ide> $months--; <ide> } <ide> } <ide> public function dateAgoInWords(DateTimeInterface $date, array $options = []) <ide> 'day' => __d('cake', 'about a day ago'), <ide> 'week' => __d('cake', 'about a week ago'), <ide> 'month' => __d('cake', 'about a month ago'), <del> 'year' => __d('cake', 'about a year ago') <add> 'year' => __d('cake', 'about a year ago'), <ide> ]; <ide> <ide> return $relativeDate ? sprintf($options['relativeString'], $relativeDate) : $aboutAgo[$fWord]; <ide> public function dateAgoInWords(DateTimeInterface $date, array $options = []) <ide> 'day' => __d('cake', 'in about a day'), <ide> 'week' => __d('cake', 'in about a week'), <ide> 'month' => __d('cake', 'in about a month'), <del> 'year' => __d('cake', 'in about a year') <add> 'year' => __d('cake', 'in about a year'), <ide> ]; <ide> <ide> return $aboutIn[$fWord]; <ide><path>src/I18n/Time.php <ide> class Time extends MutableDateTime implements JsonSerializable <ide> * <ide> * @var string <ide> */ <del> const UNIX_TIMESTAMP_FORMAT = 'unixTimestampFormat'; <add> public const UNIX_TIMESTAMP_FORMAT = 'unixTimestampFormat'; <ide> <ide> /** <ide> * {@inheritDoc} <ide> public function nice($timezone = null, $locale = null) <ide> */ <ide> public function isThisWeek() <ide> { <del> return static::now($this->getTimezone())->format('W o') == $this->format('W o'); <add> return static::now($this->getTimezone())->format('W o') === $this->format('W o'); <ide> } <ide> <ide> /** <ide> public function isThisWeek() <ide> */ <ide> public function isThisMonth() <ide> { <del> return static::now($this->getTimezone())->format('m Y') == $this->format('m Y'); <add> return static::now($this->getTimezone())->format('m Y') === $this->format('m Y'); <ide> } <ide> <ide> /** <ide> public function isThisMonth() <ide> */ <ide> public function isThisYear() <ide> { <del> return static::now($this->getTimezone())->format('Y') == $this->format('Y'); <add> return static::now($this->getTimezone())->format('Y') === $this->format('Y'); <ide> } <ide> <ide> /** <ide><path>src/I18n/Translator.php <ide> */ <ide> class Translator extends BaseTranslator <ide> { <del> <del> const PLURAL_PREFIX = 'p:'; <add> public const PLURAL_PREFIX = 'p:'; <ide> <ide> /** <ide> * Translates the message formatting any placeholders <ide> public function translate($key, array $tokensValues = []) <ide> <ide> // Resolve plural form. <ide> if (is_array($message)) { <del> $count = isset($tokensValues['_count']) ? $tokensValues['_count'] : 0; <add> $count = $tokensValues['_count'] ?? 0; <ide> $form = PluralRules::calculate($this->locale, $count); <del> $message = isset($message[$form]) ? $message[$form] : (string)end($message); <add> $message = $message[$form] ?? (string)end($message); <ide> } <ide> <ide> if (strlen($message) === 0) { <ide> public function translate($key, array $tokensValues = []) <ide> */ <ide> protected function resolveContext($key, $message, array $vars) <ide> { <del> $context = isset($vars['_context']) ? $vars['_context'] : null; <add> $context = $vars['_context'] ?? null; <ide> <ide> // No or missing context, fallback to the key/first message <ide> if ($context === null) { <ide><path>src/I18n/TranslatorFactory.php <ide> public function newInstance( <ide> $locale, <ide> Package $package, <ide> FormatterInterface $formatter, <del> TranslatorInterface $fallback = null <add> ?TranslatorInterface $fallback = null <ide> ) { <ide> $class = $this->class; <ide> if ($fallback !== null && get_class($fallback) !== $class) { <ide><path>src/I18n/TranslatorRegistry.php <ide> */ <ide> class TranslatorRegistry extends TranslatorLocator <ide> { <del> <ide> /** <ide> * A list of loader functions indexed by domain name. Loaders are <ide> * callables that are invoked as a default for building translation <ide> public function __construct( <ide> $this->registerLoader($this->_fallbackLoader, function ($name, $locale) { <ide> $chain = new ChainMessagesLoader([ <ide> new MessagesFileLoader($name, $locale, 'mo'), <del> new MessagesFileLoader($name, $locale, 'po') <add> new MessagesFileLoader($name, $locale, 'po'), <ide> ]); <ide> <ide> // \Aura\Intl\Package by default uses formatter configured with key "basic". <ide><path>src/Log/Engine/BaseLog.php <ide> */ <ide> abstract class BaseLog extends AbstractLogger <ide> { <del> <ide> use InstanceConfigTrait; <ide> <ide> /** <ide> abstract class BaseLog extends AbstractLogger <ide> */ <ide> protected $_defaultConfig = [ <ide> 'levels' => [], <del> 'scopes' => [] <add> 'scopes' => [], <ide> ]; <ide> <ide> /** <ide><path>src/Log/Engine/ConsoleLog.php <ide> */ <ide> class ConsoleLog extends BaseLog <ide> { <del> <ide> /** <ide> * Default config for this class <ide> * <ide> class ConsoleLog extends BaseLog <ide> 'stream' => 'php://stderr', <ide> 'levels' => null, <ide> 'scopes' => [], <del> 'outputAs' => 'see constructor' <add> 'outputAs' => 'see constructor', <ide> ]; <ide> <ide> /** <ide><path>src/Log/Engine/FileLog.php <ide> */ <ide> class FileLog extends BaseLog <ide> { <del> <ide> /** <ide> * Default config for this class <ide> * <ide><path>src/Log/Engine/SyslogLog.php <ide> */ <ide> class SyslogLog extends BaseLog <ide> { <del> <ide> /** <ide> * Default config for this class <ide> * <ide> class SyslogLog extends BaseLog <ide> 'format' => '%s: %s', <ide> 'flag' => LOG_ODELAY, <ide> 'prefix' => '', <del> 'facility' => LOG_USER <add> 'facility' => LOG_USER, <ide> ]; <ide> <ide> /** <ide> class SyslogLog extends BaseLog <ide> 'warning' => LOG_WARNING, <ide> 'notice' => LOG_NOTICE, <ide> 'info' => LOG_INFO, <del> 'debug' => LOG_DEBUG <add> 'debug' => LOG_DEBUG, <ide> ]; <ide> <ide> /** <ide><path>src/Log/Log.php <ide> */ <ide> class Log <ide> { <del> <ide> use StaticConfigTrait { <ide> setConfig as protected _setConfig; <ide> } <ide> class Log <ide> 'warning', <ide> 'notice', <ide> 'info', <del> 'debug' <add> 'debug', <ide> ]; <ide> <ide> /** <ide><path>src/Log/LogEngineRegistry.php <ide> */ <ide> class LogEngineRegistry extends ObjectRegistry <ide> { <del> <ide> /** <ide> * Resolve a logger classname. <ide> * <ide><path>src/Log/LogTrait.php <ide> */ <ide> trait LogTrait <ide> { <del> <ide> /** <ide> * Convenience method to write a message to Log. See Log::write() <ide> * for more information on writing to logs. <ide><path>src/Mailer/AbstractTransport.php <ide> */ <ide> abstract class AbstractTransport <ide> { <del> <ide> use InstanceConfigTrait; <ide> <ide> /** <ide><path>src/Mailer/Email.php <ide> */ <ide> class Email implements JsonSerializable, Serializable <ide> { <del> <ide> use StaticConfigTrait; <ide> use ViewVarsTrait; <ide> <ide> class Email implements JsonSerializable, Serializable <ide> * <ide> * @var int <ide> */ <del> const LINE_LENGTH_SHOULD = 78; <add> public const LINE_LENGTH_SHOULD = 78; <ide> <ide> /** <ide> * Line length - no must more - RFC 2822 - 2.1.1 <ide> * <ide> * @var int <ide> */ <del> const LINE_LENGTH_MUST = 998; <add> public const LINE_LENGTH_MUST = 998; <ide> <ide> /** <ide> * Type of message - HTML <ide> * <ide> * @var string <ide> */ <del> const MESSAGE_HTML = 'html'; <add> public const MESSAGE_HTML = 'html'; <ide> <ide> /** <ide> * Type of message - TEXT <ide> * <ide> * @var string <ide> */ <del> const MESSAGE_TEXT = 'text'; <add> public const MESSAGE_TEXT = 'text'; <ide> <ide> /** <ide> * Holds the regex pattern for email validation <ide> * <ide> * @var string <ide> */ <del> const EMAIL_PATTERN = '/^((?:[\p{L}0-9.!#$%&\'*+\/=?^_`{|}~-]+)*@[\p{L}0-9-._]+)$/ui'; <add> public const EMAIL_PATTERN = '/^((?:[\p{L}0-9.!#$%&\'*+\/=?^_`{|}~-]+)*@[\p{L}0-9-._]+)$/ui'; <ide> <ide> /** <ide> * Recipient of the email <ide> class Email implements JsonSerializable, Serializable <ide> '8bit', <ide> 'base64', <ide> 'binary', <del> 'quoted-printable' <add> 'quoted-printable', <ide> ]; <ide> <ide> /** <ide> class Email implements JsonSerializable, Serializable <ide> * @var array <ide> */ <ide> protected $_contentTypeCharset = [ <del> 'ISO-2022-JP-MS' => 'ISO-2022-JP' <add> 'ISO-2022-JP-MS' => 'ISO-2022-JP', <ide> ]; <ide> <ide> /** <ide> protected function _validateEmail($email, $context) <ide> } <ide> <ide> $context = ltrim($context, '_'); <del> if ($email == '') { <add> if ($email === '') { <ide> throw new InvalidArgumentException(sprintf('The email set for "%s" is empty.', $context)); <ide> } <ide> throw new InvalidArgumentException(sprintf('Invalid email set for "%s". You passed "%s".', $context, $email)); <ide> public function addHeaders(array $headers) <ide> */ <ide> public function getHeaders(array $include = []) <ide> { <del> if ($include == array_values($include)) { <add> if ($include === array_values($include)) { <ide> $include = array_fill_keys($include, true); <ide> } <ide> $defaults = array_fill_keys( <ide> public function getHeaders(array $include = []) <ide> 'from' => 'From', <ide> 'replyTo' => 'Reply-To', <ide> 'readReceipt' => 'Disposition-Notification-To', <del> 'returnPath' => 'Return-Path' <add> 'returnPath' => 'Return-Path', <ide> ]; <ide> foreach ($relation as $var => $header) { <ide> if ($include[$var]) { <ide> public static function setConfigTransport($key, $config = null) <ide> */ <ide> public static function getConfigTransport($key) <ide> { <del> return isset(static::$_transportConfig[$key]) ? static::$_transportConfig[$key] : null; <add> return static::$_transportConfig[$key] ?? null; <ide> } <ide> <ide> /** <ide> protected function _logDelivery($contents) <ide> } <ide> $config = [ <ide> 'level' => 'debug', <del> 'scope' => 'email' <add> 'scope' => 'email', <ide> ]; <ide> if ($this->_profile['log'] !== true) { <ide> if (!is_array($this->_profile['log'])) { <ide> protected function _applyConfig($config) <ide> $simpleMethods = [ <ide> 'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath', <ide> 'cc', 'bcc', 'messageId', 'domain', 'subject', 'attachments', <del> 'transport', 'emailFormat', 'emailPattern', 'charset', 'headerCharset' <add> 'transport', 'emailFormat', 'emailPattern', 'charset', 'headerCharset', <ide> ]; <ide> foreach ($simpleMethods as $method) { <ide> if (isset($config[$method])) { <ide> protected function _applyConfig($config) <ide> } <ide> <ide> $viewBuilderMethods = [ <del> 'template', 'layout', 'theme' <add> 'template', 'layout', 'theme', <ide> ]; <ide> foreach ($viewBuilderMethods as $method) { <ide> if (array_key_exists($method, $config)) { <ide> protected function _wrap($message, $wrapLength = Email::LINE_LENGTH_MUST) <ide> $message = str_replace(["\r\n", "\r"], "\n", $message); <ide> $lines = explode("\n", $message); <ide> $formatted = []; <del> $cut = ($wrapLength == Email::LINE_LENGTH_MUST); <add> $cut = ($wrapLength === Email::LINE_LENGTH_MUST); <ide> <ide> foreach ($lines as $line) { <ide> if (empty($line) && $line !== '0') { <ide> protected function _attachFiles($boundary = null) <ide> if (!empty($fileInfo['contentId'])) { <ide> continue; <ide> } <del> $data = isset($fileInfo['data']) ? $fileInfo['data'] : $this->_readFile($fileInfo['file']); <add> $data = $fileInfo['data'] ?? $this->_readFile($fileInfo['file']); <ide> $hasDisposition = ( <ide> !isset($fileInfo['contentDisposition']) || <ide> $fileInfo['contentDisposition'] <ide> protected function _attachInlineFiles($boundary = null) <ide> if (empty($fileInfo['contentId'])) { <ide> continue; <ide> } <del> $data = isset($fileInfo['data']) ? $fileInfo['data'] : $this->_readFile($fileInfo['file']); <add> $data = $fileInfo['data'] ?? $this->_readFile($fileInfo['file']); <ide> <ide> $msg[] = '--' . $boundary; <ide> $part = new FormDataPart('', $data, 'inline'); <ide> public function jsonSerialize() <ide> $properties = [ <ide> '_to', '_from', '_sender', '_replyTo', '_cc', '_bcc', '_subject', <ide> '_returnPath', '_readReceipt', '_emailFormat', '_emailPattern', '_domain', <del> '_attachments', '_messageId', '_headers', '_appCharset', 'viewVars', 'charset', 'headerCharset' <add> '_attachments', '_messageId', '_headers', '_appCharset', 'viewVars', 'charset', 'headerCharset', <ide> ]; <ide> <ide> $array = ['viewConfig' => $this->viewBuilder()->jsonSerialize()]; <ide><path>src/Mailer/Exception/MissingActionException.php <ide> */ <ide> class MissingActionException extends Exception <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Mailer/Exception/MissingMailerException.php <ide> */ <ide> class MissingMailerException extends Exception <ide> { <del> <ide> protected $_messageTemplate = 'Mailer class "%s" could not be found.'; <ide> } <ide><path>src/Mailer/Mailer.php <ide> */ <ide> abstract class Mailer implements EventListenerInterface <ide> { <del> <ide> use ModelAwareTrait; <ide> <ide> /** <ide> abstract class Mailer implements EventListenerInterface <ide> * <ide> * @param \Cake\Mailer\Email|null $email Email instance. <ide> */ <del> public function __construct(Email $email = null) <add> public function __construct(?Email $email = null) <ide> { <ide> if ($email === null) { <ide> $email = new Email(); <ide><path>src/Mailer/MailerAwareTrait.php <ide> */ <ide> trait MailerAwareTrait <ide> { <del> <ide> /** <ide> * Returns a mailer instance. <ide> * <ide> trait MailerAwareTrait <ide> * @return \Cake\Mailer\Mailer <ide> * @throws \Cake\Mailer\Exception\MissingMailerException if undefined mailer class. <ide> */ <del> protected function getMailer($name, Email $email = null) <add> protected function getMailer($name, ?Email $email = null) <ide> { <ide> if ($email === null) { <ide> $email = new Email(); <ide><path>src/Mailer/Transport/DebugTransport.php <ide> */ <ide> class DebugTransport extends AbstractTransport <ide> { <del> <ide> /** <ide> * Send mail <ide> * <ide><path>src/Mailer/Transport/MailTransport.php <ide> */ <ide> class MailTransport extends AbstractTransport <ide> { <del> <ide> /** <ide> * Send mail <ide> * <ide> public function send(Email $email) <ide> <ide> $message = implode($eol, $email->message()); <ide> <del> $params = isset($this->_config['additionalParameters']) ? $this->_config['additionalParameters'] : null; <add> $params = $this->_config['additionalParameters'] ?? null; <ide> $this->_mail($to, $subject, $message, $headers, $params); <ide> <ide> $headers .= $eol . 'To: ' . $to; <ide><path>src/Mailer/Transport/SmtpTransport.php <ide> */ <ide> class SmtpTransport extends AbstractTransport <ide> { <del> <ide> /** <ide> * Default config for this class <ide> * <ide> class SmtpTransport extends AbstractTransport <ide> 'password' => null, <ide> 'client' => null, <ide> 'tls' => false, <del> 'keepAlive' => false <add> 'keepAlive' => false, <ide> ]; <ide> <ide> /** <ide> protected function _bufferResponseLines(array $responseLines) <ide> if (preg_match('/^(\d{3})(?:[ -]+(.*))?$/', $responseLine, $match)) { <ide> $response[] = [ <ide> 'code' => $match[1], <del> 'message' => isset($match[2]) ? $match[2] : null <add> 'message' => $match[2] ?? null, <ide> ]; <ide> } <ide> } <ide><path>src/Network/Exception/SocketException.php <ide> */ <ide> class SocketException extends Exception <ide> { <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide><path>src/Network/Socket.php <ide> */ <ide> class Socket <ide> { <del> <ide> use InstanceConfigTrait; <ide> <ide> /** <ide> class Socket <ide> 'host' => 'localhost', <ide> 'protocol' => 'tcp', <ide> 'port' => 80, <del> 'timeout' => 30 <add> 'timeout' => 30, <ide> ]; <ide> <ide> /** <ide> public function enableCrypto($type, $clientOrServer = 'client', $enable = true) <ide> // <ide> // See https://github.com/php/php-src/commit/10bc5fd4c4c8e1dd57bd911b086e9872a56300a0 <ide> if (version_compare(PHP_VERSION, '5.6.7', '>=')) { <del> if ($method == STREAM_CRYPTO_METHOD_TLS_CLIENT) { <add> if ($method === STREAM_CRYPTO_METHOD_TLS_CLIENT) { <ide> // @codingStandardsIgnoreStart <ide> $method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; <ide> // @codingStandardsIgnoreEnd <ide> } <del> if ($method == STREAM_CRYPTO_METHOD_TLS_SERVER) { <add> if ($method === STREAM_CRYPTO_METHOD_TLS_SERVER) { <ide> // @codingStandardsIgnoreStart <ide> $method |= STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | STREAM_CRYPTO_METHOD_TLSv1_2_SERVER; <ide> // @codingStandardsIgnoreEnd <ide><path>src/ORM/Association.php <ide> */ <ide> abstract class Association <ide> { <del> <ide> use ConventionsTrait; <ide> use LocatorAwareTrait; <ide> <ide> abstract class Association <ide> * <ide> * @var string <ide> */ <del> const STRATEGY_JOIN = 'join'; <add> public const STRATEGY_JOIN = 'join'; <ide> <ide> /** <ide> * Strategy name to use a subquery for fetching associated records <ide> * <ide> * @var string <ide> */ <del> const STRATEGY_SUBQUERY = 'subquery'; <add> public const STRATEGY_SUBQUERY = 'subquery'; <ide> <ide> /** <ide> * Strategy name to use a select for fetching associated records <ide> * <ide> * @var string <ide> */ <del> const STRATEGY_SELECT = 'select'; <add> public const STRATEGY_SELECT = 'select'; <ide> <ide> /** <ide> * Association type for one to one associations. <ide> * <ide> * @var string <ide> */ <del> const ONE_TO_ONE = 'oneToOne'; <add> public const ONE_TO_ONE = 'oneToOne'; <ide> <ide> /** <ide> * Association type for one to many associations. <ide> * <ide> * @var string <ide> */ <del> const ONE_TO_MANY = 'oneToMany'; <add> public const ONE_TO_MANY = 'oneToMany'; <ide> <ide> /** <ide> * Association type for many to many associations. <ide> * <ide> * @var string <ide> */ <del> const MANY_TO_MANY = 'manyToMany'; <add> public const MANY_TO_MANY = 'manyToMany'; <ide> <ide> /** <ide> * Association type for many to one associations. <ide> * <ide> * @var string <ide> */ <del> const MANY_TO_ONE = 'manyToOne'; <add> public const MANY_TO_ONE = 'manyToOne'; <ide> <ide> /** <ide> * Name given to the association, it usually represents the alias <ide> abstract class Association <ide> protected $_validStrategies = [ <ide> self::STRATEGY_JOIN, <ide> self::STRATEGY_SELECT, <del> self::STRATEGY_SUBQUERY <add> self::STRATEGY_SUBQUERY, <ide> ]; <ide> <ide> /** <ide> public function __construct($alias, array $options = []) <ide> 'tableLocator', <ide> 'propertyName', <ide> 'sourceTable', <del> 'targetTable' <add> 'targetTable', <ide> ]; <ide> foreach ($defaults as $property) { <ide> if (isset($options[$property])) { <ide> public function getDependent() <ide> */ <ide> public function canBeJoined(array $options = []) <ide> { <del> $strategy = isset($options['strategy']) ? $options['strategy'] : $this->getStrategy(); <add> $strategy = $options['strategy'] ?? $this->getStrategy(); <ide> <del> return $strategy == $this::STRATEGY_JOIN; <add> return $strategy === $this::STRATEGY_JOIN; <ide> } <ide> <ide> /** <ide> public function attachTo(Query $query, array $options = []) <ide> 'fields' => [], <ide> 'type' => $joinType, <ide> 'table' => $table, <del> 'finder' => $this->getFinder() <add> 'finder' => $this->getFinder(), <ide> ]; <ide> <ide> if (!empty($options['foreignKey'])) { <ide> public function deleteAll($conditions) <ide> */ <ide> public function requiresKeys(array $options = []) <ide> { <del> $strategy = isset($options['strategy']) ? $options['strategy'] : $this->getStrategy(); <add> $strategy = $options['strategy'] ?? $this->getStrategy(); <ide> <ide> return $strategy === static::STRATEGY_SELECT; <ide> } <ide><path>src/ORM/Association/BelongsTo.php <ide> */ <ide> class BelongsTo extends Association <ide> { <del> <ide> /** <ide> * Valid strategies for this type of association <ide> * <ide> * @var array <ide> */ <ide> protected $_validStrategies = [ <ide> self::STRATEGY_JOIN, <del> self::STRATEGY_SELECT <add> self::STRATEGY_SELECT, <ide> ]; <ide> <ide> /** <ide> public function eagerLoader(array $options) <ide> 'bindingKey' => $this->getBindingKey(), <ide> 'strategy' => $this->getStrategy(), <ide> 'associationType' => $this->type(), <del> 'finder' => [$this, 'find'] <add> 'finder' => [$this, 'find'], <ide> ]); <ide> <ide> return $loader->buildEagerLoader($options); <ide><path>src/ORM/Association/BelongsToMany.php <ide> namespace Cake\ORM\Association; <ide> <ide> use Cake\Core\App; <del>use Cake\Database\ExpressionInterface; <ide> use Cake\Database\Expression\IdentifierExpression; <add>use Cake\Database\ExpressionInterface; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Datasource\QueryInterface; <ide> use Cake\ORM\Association; <ide> */ <ide> class BelongsToMany extends Association <ide> { <del> <ide> /** <ide> * Saving strategy that will only append to the links set <ide> * <ide> * @var string <ide> */ <del> const SAVE_APPEND = 'append'; <add> public const SAVE_APPEND = 'append'; <ide> <ide> /** <ide> * Saving strategy that will replace the links with the provided set <ide> * <ide> * @var string <ide> */ <del> const SAVE_REPLACE = 'replace'; <add> public const SAVE_REPLACE = 'replace'; <ide> <ide> /** <ide> * The type of join to be used when adding the association to a query <ide> class BelongsToMany extends Association <ide> */ <ide> protected $_validStrategies = [ <ide> self::STRATEGY_SELECT, <del> self::STRATEGY_SUBQUERY <add> self::STRATEGY_SUBQUERY, <ide> ]; <ide> <ide> /** <ide> protected function _generateJunctionAssociations($junction, $source, $target) <ide> if (!$junction->hasAssociation($tAlias)) { <ide> $junction->belongsTo($tAlias, [ <ide> 'foreignKey' => $this->getTargetForeignKey(), <del> 'targetTable' => $target <add> 'targetTable' => $target, <ide> ]); <ide> } <ide> if (!$junction->hasAssociation($sAlias)) { <ide> $junction->belongsTo($sAlias, [ <ide> 'foreignKey' => $this->getForeignKey(), <del> 'targetTable' => $source <add> 'targetTable' => $source, <ide> ]); <ide> } <ide> } <ide> protected function _appendNotMatching($query, $options) <ide> <ide> $assoc = $junction->getAssociation($this->getTarget()->getAlias()); <ide> $conditions = $assoc->_joinCondition([ <del> 'foreignKey' => $this->getTargetForeignKey() <add> 'foreignKey' => $this->getTargetForeignKey(), <ide> ]); <ide> $subquery = $this->_appendJunctionJoin($subquery, $conditions); <ide> <ide> public function eagerLoader(array $options) <ide> 'junctionConditions' => $this->junctionConditions(), <ide> 'finder' => function () { <ide> return $this->_appendJunctionJoin($this->find(), []); <del> } <add> }, <ide> ]); <ide> <ide> return $loader->buildEagerLoader($options); <ide> public function unlink(EntityInterface $sourceEntity, array $targetEntities, $op <ide> { <ide> if (is_bool($options)) { <ide> $options = [ <del> 'cleanProperty' => $options <add> 'cleanProperty' => $options, <ide> ]; <ide> } else { <ide> $options += ['cleanProperty' => true]; <ide> public function find($type = null, array $options = []) <ide> <ide> $belongsTo = $this->junction()->getAssociation($this->getTarget()->getAlias()); <ide> $conditions = $belongsTo->_joinCondition([ <del> 'foreignKey' => $this->getTargetForeignKey() <add> 'foreignKey' => $this->getTargetForeignKey(), <ide> ]); <ide> $conditions += $this->junctionConditions(); <ide> <ide> protected function _appendJunctionJoin($query, $conditions) <ide> $name => [ <ide> 'table' => $this->junction()->getTable(), <ide> 'conditions' => $conditions, <del> 'type' => QueryInterface::JOIN_TYPE_INNER <del> ] <add> 'type' => QueryInterface::JOIN_TYPE_INNER, <add> ], <ide> ]; <ide> <ide> $assoc = $this->getTarget()->getAssociation($name); <ide> protected function _junctionTableName($name = null) <ide> if (empty($this->_junctionTableName)) { <ide> $tablesNames = array_map('Cake\Utility\Inflector::underscore', [ <ide> $this->getSource()->getTable(), <del> $this->getTarget()->getTable() <add> $this->getTarget()->getTable(), <ide> ]); <ide> sort($tablesNames); <ide> $this->_junctionTableName = implode('_', $tablesNames); <ide><path>src/ORM/Association/DependentDeleteHelper.php <ide> */ <ide> class DependentDeleteHelper <ide> { <del> <ide> /** <ide> * Cascade a delete to remove dependent records. <ide> * <ide><path>src/ORM/Association/HasMany.php <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Datasource\QueryInterface; <ide> use Cake\ORM\Association; <del>use Cake\ORM\Association\DependentDeleteHelper; <ide> use Cake\ORM\Association\Loader\SelectLoader; <ide> use Cake\ORM\Table; <ide> use InvalidArgumentException; <ide> */ <ide> class HasMany extends Association <ide> { <del> <ide> /** <ide> * Order in which target records should be returned <ide> * <ide> class HasMany extends Association <ide> */ <ide> protected $_validStrategies = [ <ide> self::STRATEGY_SELECT, <del> self::STRATEGY_SUBQUERY <add> self::STRATEGY_SUBQUERY, <ide> ]; <ide> <ide> /** <ide> * Saving strategy that will only append to the links set <ide> * <ide> * @var string <ide> */ <del> const SAVE_APPEND = 'append'; <add> public const SAVE_APPEND = 'append'; <ide> <ide> /** <ide> * Saving strategy that will replace the links with the provided set <ide> * <ide> * @var string <ide> */ <del> const SAVE_REPLACE = 'replace'; <add> public const SAVE_REPLACE = 'replace'; <ide> <ide> /** <ide> * Saving strategy to be used by this association <ide> public function unlink(EntityInterface $sourceEntity, array $targetEntities, $op <ide> { <ide> if (is_bool($options)) { <ide> $options = [ <del> 'cleanProperty' => $options <add> 'cleanProperty' => $options, <ide> ]; <ide> } else { <ide> $options += ['cleanProperty' => true]; <ide> public function unlink(EntityInterface $sourceEntity, array $targetEntities, $op <ide> ->map(function ($entity) use ($targetPrimaryKey) { <ide> return $entity->extract($targetPrimaryKey); <ide> }) <del> ->toList() <add> ->toList(), <ide> ]; <ide> <ide> $this->_unlink($foreignKey, $target, $conditions, $options); <ide> function ($v) { <ide> if (count($exclusions) > 0) { <ide> $conditions = [ <ide> 'NOT' => [ <del> 'OR' => $exclusions <add> 'OR' => $exclusions, <ide> ], <del> $foreignKeyReference <add> $foreignKeyReference, <ide> ]; <ide> } <ide> <ide> public function eagerLoader(array $options) <ide> 'strategy' => $this->getStrategy(), <ide> 'associationType' => $this->type(), <ide> 'sort' => $this->getSort(), <del> 'finder' => [$this, 'find'] <add> 'finder' => [$this, 'find'], <ide> ]); <ide> <ide> return $loader->buildEagerLoader($options); <ide><path>src/ORM/Association/HasOne.php <ide> <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\ORM\Association; <del>use Cake\ORM\Association\DependentDeleteHelper; <ide> use Cake\ORM\Association\Loader\SelectLoader; <ide> use Cake\ORM\Table; <ide> use Cake\Utility\Inflector; <ide> class HasOne extends Association <ide> */ <ide> protected $_validStrategies = [ <ide> self::STRATEGY_JOIN, <del> self::STRATEGY_SELECT <add> self::STRATEGY_SELECT, <ide> ]; <ide> <ide> /** <ide> public function eagerLoader(array $options) <ide> 'bindingKey' => $this->getBindingKey(), <ide> 'strategy' => $this->getStrategy(), <ide> 'associationType' => $this->type(), <del> 'finder' => [$this, 'find'] <add> 'finder' => [$this, 'find'], <ide> ]); <ide> <ide> return $loader->buildEagerLoader($options); <ide><path>src/ORM/Association/Loader/SelectLoader.php <ide> */ <ide> class SelectLoader <ide> { <del> <ide> /** <ide> * The alias of the association loading the results <ide> * <ide> public function __construct(array $options) <ide> $this->bindingKey = $options['bindingKey']; <ide> $this->finder = $options['finder']; <ide> $this->associationType = $options['associationType']; <del> $this->sort = isset($options['sort']) ? $options['sort'] : null; <add> $this->sort = $options['sort'] ?? null; <ide> } <ide> <ide> /** <ide> protected function _defaultOptions() <ide> 'conditions' => [], <ide> 'strategy' => $this->strategy, <ide> 'nestKey' => $this->alias, <del> 'sort' => $this->sort <add> 'sort' => $this->sort, <ide> ]; <ide> } <ide> <ide> protected function _addFilteringCondition($query, $key, $filter) <ide> $conditions = $this->_createTupleCondition($query, $key, $filter, 'IN'); <ide> } <ide> <del> $conditions = isset($conditions) ? $conditions : [$key . ' IN' => $filter]; <add> $conditions = $conditions ?? [$key . ' IN' => $filter]; <ide> <ide> return $query->andWhere($conditions); <ide> } <ide><path>src/ORM/Association/Loader/SelectWithPivotLoader.php <ide> */ <ide> class SelectWithPivotLoader extends SelectLoader <ide> { <del> <ide> /** <ide> * The name of the junction association <ide> * <ide><path>src/ORM/AssociationCollection.php <ide> */ <ide> class AssociationCollection implements IteratorAggregate <ide> { <del> <ide> use AssociationsNormalizerTrait; <ide> use LocatorAwareTrait; <ide> <ide> class AssociationCollection implements IteratorAggregate <ide> * <ide> * @param \Cake\ORM\Locator\LocatorInterface|null $tableLocator Table locator instance. <ide> */ <del> public function __construct(LocatorInterface $tableLocator = null) <add> public function __construct(?LocatorInterface $tableLocator = null) <ide> { <ide> if ($tableLocator !== null) { <ide> $this->_tableLocator = $tableLocator; <ide> public function add($alias, Association $association) <ide> public function load($className, $associated, array $options = []) <ide> { <ide> $options += [ <del> 'tableLocator' => $this->getTableLocator() <add> 'tableLocator' => $this->getTableLocator(), <ide> ]; <ide> <ide> $association = new $className($associated, $options); <ide><path>src/ORM/AssociationsNormalizerTrait.php <ide> */ <ide> trait AssociationsNormalizerTrait <ide> { <del> <ide> /** <ide> * Returns an array out of the original passed associations list where dot notation <ide> * is transformed into nested arrays so that they can be parsed by other routines <ide> protected function _normalizeAssociations($associations) <ide> $pointer['associated'][$table] = $options + $pointer['associated'][$table]; <ide> } <ide> <del> return isset($result['associated']) ? $result['associated'] : $result; <add> return $result['associated'] ?? $result; <ide> } <ide> } <ide><path>src/ORM/Behavior.php <ide> */ <ide> class Behavior implements EventListenerInterface <ide> { <del> <ide> use InstanceConfigTrait; <ide> <ide> /** <ide> public function implementedEvents() <ide> 'Model.afterRules' => 'afterRules', <ide> ]; <ide> $config = $this->getConfig(); <del> $priority = isset($config['priority']) ? $config['priority'] : null; <add> $priority = $config['priority'] ?? null; <ide> $events = []; <ide> <ide> foreach ($eventMap as $event => $method) { <ide> public function implementedEvents() <ide> } else { <ide> $events[$event] = [ <ide> 'callable' => $method, <del> 'priority' => $priority <add> 'priority' => $priority, <ide> ]; <ide> } <ide> } <ide> protected function _reflectionCache() <ide> <ide> $return = [ <ide> 'finders' => [], <del> 'methods' => [] <add> 'methods' => [], <ide> ]; <ide> <ide> $reflection = new ReflectionClass($class); <ide><path>src/ORM/Behavior/CounterCacheBehavior.php <ide> */ <ide> class CounterCacheBehavior extends Behavior <ide> { <del> <ide> /** <ide> * Store the fields which should be ignored <ide> * <ide><path>src/ORM/Behavior/TimestampBehavior.php <ide> */ <ide> namespace Cake\ORM\Behavior; <ide> <del>use Cake\Database\TypeFactory; <ide> use Cake\Database\Type\DateTimeType; <add>use Cake\Database\TypeFactory; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Event\EventInterface; <ide> use Cake\I18n\Time; <ide> */ <ide> class TimestampBehavior extends Behavior <ide> { <del> <ide> /** <ide> * Default config <ide> * <ide> class TimestampBehavior extends Behavior <ide> 'implementedFinders' => [], <ide> 'implementedMethods' => [ <ide> 'timestamp' => 'timestamp', <del> 'touch' => 'touch' <add> 'touch' => 'touch', <ide> ], <ide> 'events' => [ <ide> 'Model.beforeSave' => [ <ide> 'created' => 'new', <del> 'modified' => 'always' <del> ] <add> 'modified' => 'always', <add> ], <ide> ], <del> 'refreshTimestamp' => true <add> 'refreshTimestamp' => true, <ide> ]; <ide> <ide> /** <ide> public function implementedEvents() <ide> * @param bool $refreshTimestamp If true timestamp is refreshed. <ide> * @return \DateTime <ide> */ <del> public function timestamp(DateTime $ts = null, $refreshTimestamp = false) <add> public function timestamp(?DateTime $ts = null, $refreshTimestamp = false) <ide> { <ide> if ($ts) { <ide> if ($this->_config['refreshTimestamp']) { <ide><path>src/ORM/Behavior/Translate/TranslateTrait.php <ide> */ <ide> trait TranslateTrait <ide> { <del> <ide> /** <ide> * Returns the entity containing the translated fields for this object and for <ide> * the specified language. If the translation for the passed language is not <ide><path>src/ORM/Behavior/TranslateBehavior.php <ide> */ <ide> class TranslateBehavior extends Behavior implements PropertyMarshalInterface <ide> { <del> <ide> use LocatorAwareTrait; <ide> <ide> /** <ide> class TranslateBehavior extends Behavior implements PropertyMarshalInterface <ide> 'implementedMethods' => [ <ide> 'setLocale' => 'setLocale', <ide> 'getLocale' => 'getLocale', <del> 'translationField' => 'translationField' <add> 'translationField' => 'translationField', <ide> ], <ide> 'fields' => [], <ide> 'translationTable' => 'I18n', <ide> class TranslateBehavior extends Behavior implements PropertyMarshalInterface <ide> 'onlyTranslated' => false, <ide> 'strategy' => 'subquery', <ide> 'tableLocator' => null, <del> 'validator' => false <add> 'validator' => false, <ide> ]; <ide> <ide> /** <ide> public function __construct(Table $table, array $config = []) <ide> { <ide> $config += [ <ide> 'defaultLocale' => I18n::getDefaultLocale(), <del> 'referenceName' => $this->_referenceName($table) <add> 'referenceName' => $this->_referenceName($table), <ide> ]; <ide> <ide> if (isset($config['tableLocator'])) { <ide> public function setupFieldAssociations($fields, $table, $model, $strategy) <ide> $fieldTable = $tableLocator->get($name, [ <ide> 'className' => $table, <ide> 'alias' => $name, <del> 'table' => $this->_translationTable->getTable() <add> 'table' => $this->_translationTable->getTable(), <ide> ]); <ide> } else { <ide> $fieldTable = $tableLocator->get($name); <ide> public function setupFieldAssociations($fields, $table, $model, $strategy) <ide> 'foreignKey' => 'foreign_key', <ide> 'joinType' => $filter ? QueryInterface::JOIN_TYPE_INNER : QueryInterface::JOIN_TYPE_LEFT, <ide> 'conditions' => $conditions, <del> 'propertyName' => $field . '_translation' <add> 'propertyName' => $field . '_translation', <ide> ]); <ide> } <ide> <ide> public function setupFieldAssociations($fields, $table, $model, $strategy) <ide> 'strategy' => $strategy, <ide> 'conditions' => $conditions, <ide> 'propertyName' => '_i18n', <del> 'dependent' => true <add> 'dependent' => true, <ide> ]); <ide> } <ide> <ide> public function beforeSave(EventInterface $event, EntityInterface $entity, Array <ide> 'field IN' => $fields, <ide> 'locale' => $locale, <ide> 'foreign_key' => $key, <del> 'model' => $model <add> 'model' => $model, <ide> ]) <ide> ->enableBufferedResults(false) <ide> ->all() <ide> public function beforeSave(EventInterface $event, EntityInterface $entity, Array <ide> foreach ($new as $field => $content) { <ide> $new[$field] = new Entity(compact('locale', 'field', 'content', 'model'), [ <ide> 'useSetters' => false, <del> 'markNew' => true <add> 'markNew' => true, <ide> ]); <ide> } <ide> <ide> public function buildMarshalMap($marshaller, $map, $options) <ide> } <ide> <ide> return $translations; <del> } <add> }, <ide> ]; <ide> } <ide> <ide> public function translationField($field) <ide> */ <ide> public function findTranslations(Query $query, array $options) <ide> { <del> $locales = isset($options['locales']) ? $options['locales'] : []; <add> $locales = $options['locales'] ?? []; <ide> $targetAlias = $this->_translationTable->getAlias(); <ide> <ide> return $query <ide> protected function _rowMapper($results, $locale) <ide> <ide> foreach ($this->_config['fields'] as $field) { <ide> $name = $field . '_translation'; <del> $translation = isset($row[$name]) ? $row[$name] : null; <add> $translation = $row[$name] ?? null; <ide> <ide> if ($translation === null || $translation === false) { <ide> unset($row[$name]); <ide> continue; <ide> } <ide> <del> $content = isset($translation['content']) ? $translation['content'] : null; <add> $content = $translation['content'] ?? null; <ide> if ($content !== null) { <ide> $row[$field] = $content; <ide> } <ide> public function groupTranslations($results) <ide> $translation = new $entityClass($keys + ['locale' => $locale], [ <ide> 'markNew' => false, <ide> 'useSetters' => false, <del> 'markClean' => true <add> 'markClean' => true, <ide> ]); <ide> $result[$locale] = $translation; <ide> } <ide> protected function _bundleTranslatedFields($entity) <ide> } <ide> $find[] = ['locale' => $lang, 'field' => $field, 'foreign_key' => $key]; <ide> $contents[] = new Entity(['content' => $translation->get($field)], [ <del> 'useSetters' => false <add> 'useSetters' => false, <ide> ]); <ide> } <ide> } <ide><path>src/ORM/Behavior/TreeBehavior.php <ide> */ <ide> class TreeBehavior extends Behavior <ide> { <del> <ide> /** <ide> * Cached copy of the first column in a table's primary key. <ide> * <ide> public function beforeSave(EventInterface $event, EntityInterface $entity) <ide> $dirty = $entity->isDirty($config['parent']); <ide> $level = $config['level']; <ide> <del> if ($parent && $entity->get($primaryKey) == $parent) { <add> if ($parent && $entity->get($primaryKey) === $parent) { <ide> throw new RuntimeException("Cannot set a node's parent as itself"); <ide> } <ide> <ide> protected function _removeFromTree($node) <ide> <ide> $node->set($config['parent'], null); <ide> <del> if ($right - $left == 1) { <add> if ($right - $left === 1) { <ide> return $this->_table->save($node); <ide> } <ide> <ide><path>src/ORM/BehaviorRegistry.php <ide> */ <ide> class BehaviorRegistry extends ObjectRegistry implements EventDispatcherInterface <ide> { <del> <ide> use EventDispatcherTrait; <ide> <ide> /** <ide> protected function _throwMissingClassError($class, $plugin) <ide> { <ide> throw new MissingBehaviorException([ <ide> 'class' => $class . 'Behavior', <del> 'plugin' => $plugin <add> 'plugin' => $plugin, <ide> ]); <ide> } <ide> <ide> protected function _throwMissingClassError($class, $plugin) <ide> protected function _create($class, $alias, $config) <ide> { <ide> $instance = new $class($this->_table, $config); <del> $enable = isset($config['enabled']) ? $config['enabled'] : true; <add> $enable = $config['enabled'] ?? true; <ide> if ($enable) { <ide> $this->getEventManager()->on($instance); <ide> }
300
Python
Python
add explanation of a sparse mesh grid
8f0f33b31da1777d2ebdc803690b8af8602e0e91
<ide><path>numpy/lib/function_base.py <ide> def meshgrid(*xi, copy=True, sparse=False, indexing='xy'): <ide> <ide> .. versionadded:: 1.7.0 <ide> sparse : bool, optional <del> If True a sparse grid is returned in order to conserve memory. <add> If True the shape of the returned coordinate array for dimension *i* <add> is reduced from ``(N1, ..., Ni, ... Nn)`` to <add> ``(1, ..., 1, Ni, 1, ..., 1)``. These sparse coordinate grids are <add> intended to be use with :ref:`basics.broadcasting`. When all <add> coordinates are used in an expression, broadcasting still leads to a <add> fully-dimensonal result array. <add> <ide> Default is False. <ide> <ide> .. versionadded:: 1.7.0 <ide> def meshgrid(*xi, copy=True, sparse=False, indexing='xy'): <ide> array([[0.], <ide> [1.]]) <ide> <del> `meshgrid` is very useful to evaluate functions on a grid. <add> `meshgrid` is very useful to evaluate functions on a grid. If the <add> function depends on all coordinates, you can use the parameter <add> ``sparse=True`` to save memory and computation time. <add> <add> >>> x = np.linspace(-5, 5, 101) <add> >>> y = np.linspace(-5, 5, 101) <add> >>> # full coorindate arrays <add> >>> xx, yy = np.meshgrid(x, y) <add> >>> zz = np.sqrt(xx**2 + yy**2) <add> >>> xx.shape, yy.shape, zz.shape <add> ((101, 101), (101, 101), (101, 101)) <add> >>> # sparse coordinate arrays <add> >>> xs, ys = np.meshgrid(x, y, sparse=True) <add> >>> zs = np.sqrt(xs**2 + ys**2) <add> >>> xs.shape, ys.shape, zs.shape <add> ((1, 101), (101, 1), (101, 101)) <add> >>> np.array_equal(zz, zs) <add> True <ide> <ide> >>> import matplotlib.pyplot as plt <del> >>> x = np.arange(-5, 5, 0.1) <del> >>> y = np.arange(-5, 5, 0.1) <del> >>> xx, yy = np.meshgrid(x, y, sparse=True) <del> >>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2) <del> >>> h = plt.contourf(x, y, z) <add> >>> h = plt.contourf(x, y, zs) <ide> >>> plt.axis('scaled') <add> >>> plt.colorbar() <ide> >>> plt.show() <del> <ide> """ <ide> ndim = len(xi) <ide>
1
Go
Go
add exec event create/start log
e3d813f37f48ed52330e3dc26aa363e58401fbf5
<ide><path>daemon/exec.go <ide> func (d *Daemon) ContainerExecCreate(job *engine.Job) engine.Status { <ide> Running: false, <ide> } <ide> <add> container.LogEvent("exec_create: " + execConfig.ProcessConfig.Entrypoint + " " + strings.Join(execConfig.ProcessConfig.Arguments, " ")) <add> <ide> d.registerExecCommand(execConfig) <ide> <ide> job.Printf("%s\n", execConfig.ID) <ide> func (d *Daemon) ContainerExecStart(job *engine.Job) engine.Status { <ide> log.Debugf("starting exec command %s in container %s", execConfig.ID, execConfig.Container.ID) <ide> container := execConfig.Container <ide> <add> container.LogEvent("exec_start: " + execConfig.ProcessConfig.Entrypoint + " " + strings.Join(execConfig.ProcessConfig.Arguments, " ")) <add> <ide> if execConfig.OpenStdin { <ide> r, w := io.Pipe() <ide> go func() {
1
Javascript
Javascript
add tests for new language features
3d2409c476e52d0ca8729f161eedf98ece37063e
<ide><path>test/parallel/test-assert.js <ide> common.expectsError( <ide> } <ide> ); <ide> common.expectsError( <del> () => assert(typeof 123 === 'string'), <add> () => assert(typeof 123n === 'string'), <ide> { <ide> code: 'ERR_ASSERTION', <ide> type: assert.AssertionError, <ide> generatedMessage: true, <ide> message: 'The expression evaluated to a falsy value:\n\n ' + <del> "assert(typeof 123 === 'string')\n" <add> "assert(typeof 123n === 'string')\n" <ide> } <ide> ); <ide> <ide><path>test/parallel/test-repl.js <ide> const errorTests = [ <ide> send: '1 }', <ide> expect: '{ a: 1 }' <ide> }, <add> // Multiline class with private member. <add> { <add> send: 'class Foo { #private = true ', <add> expect: '... ' <add> }, <add> // Class field with bigint. <add> { <add> send: 'num = 123456789n', <add> expect: '... ' <add> }, <add> // Static class features. <add> { <add> send: 'static foo = "bar" }', <add> expect: 'undefined' <add> }, <ide> // Multiline anonymous function with comment <ide> { <ide> send: '(function() {', <ide> const errorTests = [ <ide> expect: '... ' <ide> }, <ide> { <del> send: 'return 1;', <add> send: 'return 1n;', <ide> expect: '... ' <ide> }, <ide> { <ide> send: '})()', <del> expect: '1' <add> expect: '1n' <ide> }, <ide> // Multiline function call <ide> {
2
Python
Python
update documentation in keypoint boxcoder
8c767cfebd99bb8e9e6d84635a3f0bf182f7faa5
<ide><path>research/object_detection/box_coders/keypoint_box_coder.py <ide> th = log(h / ha) <ide> tw = log(w / wa) <ide> tky0 = (ky0 - ya) / ha <del> tkx0 = (kx0 - xa) / ha <add> tkx0 = (kx0 - xa) / wa <ide> tky1 = (ky1 - ya) / ha <del> tkx1 = (kx1 - xa) / ha <add> tkx1 = (kx1 - xa) / wa <ide> ... <ide> where x, y, w, h denote the box's center coordinates, width and height <ide> respectively. Similarly, xa, ya, wa, ha denote the anchor's center
1
Javascript
Javascript
simplify faces creation with for loop
7360ed9c5ec5cb45fd13701587ef87e92512c333
<ide><path>examples/js/exporters/OBJExporter.js <ide> THREE.OBJExporter.prototype = { <ide> var indexVertex = 0; <ide> var indexVertexUvs = 0; <ide> var indexNormals = 0; <add> <add> var faceVertexKeys = ["a", "b", "c"]; <ide> <ide> var parseMesh = function ( mesh ) { <ide> <ide> THREE.OBJExporter.prototype = { <ide> } <ide> <ide> } <del> <add> <ide> // faces <del> <del> <add> <ide> for ( var i = 0, j = 1, l = faces.length; i < l; i ++, j += 3 ) { <ide> <ide> var face = faces[ i ]; <ide> <ide> output += 'f '; <del> output += ( indexVertex + face.a + 1 ) + '/' + ( hasVertexUvs ? ( indexVertexUvs + j + 0 + 1 ) : '' ) + '/' + ( indexNormals + j + 0 + 1 ) + ' '; <del> output += ( indexVertex + face.b + 1 ) + '/' + ( hasVertexUvs ? ( indexVertexUvs + j + 1 + 1 ) : '' ) + '/' + ( indexNormals + j + 1 + 1 ) + ' '; <del> output += ( indexVertex + face.c + 1 ) + '/' + ( hasVertexUvs ? ( indexVertexUvs + j + 2 + 1 ) : '' ) + '/' + ( indexNormals + j + 2 + 1 ) + '\n'; <add> <add> for ( var m = 0; m < 3; m ++ ) { <add> output += ( indexVertex + face[ faceVertexKeys[ m ] ] + 1 ) + '/' + ( hasVertexUvs ? ( indexVertexUvs + j + m + 1 ) : '' ) + '/' + ( indexNormals + j + m + 1 ); <add> output += m === 2 ? "\n" : " "; <add> } <ide> <ide> } <ide>
1
Ruby
Ruby
improve rspec annotations
196d7badfae5692bfe7dd79e4559f5b41eea5761
<ide><path>Library/Homebrew/test/spec_helper.rb <ide> config.include(Test::Helper::OutputAsTTY) <ide> <ide> config.before(:each, :needs_compat) do <del> skip "Requires compatibility layer." if ENV["HOMEBREW_NO_COMPAT"] <add> skip "Requires the compatibility layer." if ENV["HOMEBREW_NO_COMPAT"] <ide> end <ide> <ide> config.before(:each, :needs_linux) do <del> skip "Not on Linux." unless OS.linux? <add> skip "Not running on Linux." unless OS.linux? <ide> end <ide> <ide> config.before(:each, :needs_macos) do <del> skip "Not on macOS." unless OS.mac? <add> skip "Not running on macOS." unless OS.mac? <ide> end <ide> <ide> config.before(:each, :needs_java) do <ide> else <ide> which("java") <ide> end <del> skip "Java not installed." unless java_installed <add> skip "Java is not installed." unless java_installed <ide> end <ide> <ide> config.before(:each, :needs_python) do <del> skip "Python not installed." unless which("python") <add> skip "Python is not installed." unless which("python") <ide> end <ide> <ide> config.before(:each, :needs_network) do <ide> skip "Requires network connection." unless ENV["HOMEBREW_TEST_ONLINE"] <ide> end <ide> <ide> config.before(:each, :needs_svn) do <del> skip "subversion not installed." unless quiet_system "#{HOMEBREW_SHIMS_PATH}/scm/svn", "--version" <add> skip "Subversion is not installed." unless quiet_system "#{HOMEBREW_SHIMS_PATH}/scm/svn", "--version" <ide> <ide> svn_paths = PATH.new(ENV["PATH"]) <ide> if OS.mac? <ide> <ide> svn = which("svn", svn_paths) <ide> svnadmin = which("svnadmin", svn_paths) <del> skip "subversion not installed." if !svn || !svnadmin <add> skip "Subversion is not installed." if !svn || !svnadmin <ide> <ide> ENV["PATH"] = PATH.new(ENV["PATH"]) <ide> .append(svn.dirname) <ide> .append(svnadmin.dirname) <ide> end <ide> <ide> config.before(:each, :needs_unzip) do <del> skip "unzip not installed." unless which("unzip") <add> skip "UnZip is not installed." unless which("unzip") <ide> end <ide> <ide> config.around do |example| <ide><path>Library/Homebrew/test/support/github_formatter.rb <ide> module Github <ide> class Formatter < RSpec::Core::Formatters::BaseFormatter <ide> RSpec::Core::Formatters.register self, :example_failed, :example_pending <ide> <add> def self.escape(string) <add> # See https://github.community/t/set-output-truncates-multiline-strings/16852/3. <add> string.gsub("%", "%25") <add> .gsub("\n", "%0A") <add> .gsub("\r", "%0D") <add> end <add> <ide> def self.relative_path(path) <ide> if (workspace = ENV["GITHUB_WORKSPACE"]) <ide> workspace = "#{File.realpath(workspace)}#{File::SEPARATOR}" <ide> def self.relative_path(path) <ide> def example_failed(failure) <ide> file, line = failure.example.location.split(":") <ide> file = self.class.relative_path(file) <del> output.puts "\n::error file=#{file},line=#{line}::#{failure.message_lines.join("%0A")}" <add> <add> description = failure.example.full_description <add> message = failure.message_lines.join("\n") <add> annotation = "#{description}:\n\n#{message}" <add> <add> output.puts "\n::error file=#{file},line=#{line}::#{self.class.escape(annotation)}" <ide> end <ide> <ide> def example_pending(pending) <ide> file, line = pending.example.location.split(":") <ide> file = self.class.relative_path(file) <del> output.puts "\n::warning file=#{file},line=#{line}::#{pending.example.full_description}" <add> <add> description = pending.example.full_description <add> message = if pending.example.skip <add> "Skipped: #{pending.example.execution_result.pending_message}" <add> else <add> "Pending: #{pending.example.execution_result.pending_message}" <add> end <add> annotation = "#{description}:\n\n#{message}" <add> <add> output.puts "\n::warning file=#{file},line=#{line}::#{self.class.escape(annotation)}" <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/utils/github/actions.rb <ide> module GitHub <ide> # @api private <ide> module Actions <ide> def self.escape(string) <del> string.gsub(/\r/, "%0D") <del> .gsub(/\n/, "%0A") <del> .gsub(/]/, "%5D") <del> .gsub(/;/, "%3B") <add> # See https://github.community/t/set-output-truncates-multiline-strings/16852/3. <add> string.gsub("%", "%25") <add> .gsub("\n", "%0A") <add> .gsub("\r", "%0D") <ide> end <ide> <ide> # Helper class for formatting annotations on GitHub Actions.
3
Javascript
Javascript
unify donation config
f30f8072b0ed170082713c9d6dc91a259e4a803c
<ide><path>api-server/server/boot/donate.js <ide> import debug from 'debug'; <ide> import crypto from 'crypto'; <ide> import { isEmail, isNumeric } from 'validator'; <ide> <add>import { <add> durationKeysConfig, <add> donationOneTimeConfig, <add> donationSubscriptionConfig <add>} from '../../../config/donation-settings'; <ide> import keys from '../../../config/secrets'; <ide> <ide> const log = debug('fcc:boot:donate'); <ide> export default function donateBoot(app, done) { <ide> const api = app.loopback.Router(); <ide> const donateRouter = app.loopback.Router(); <ide> <del> const durationKeys = ['year', 'month', 'onetime']; <del> const donationOneTimeConfig = [100000, 25000, 3500]; <del> const donationSubscriptionConfig = { <del> duration: { <del> year: 'Yearly', <del> month: 'Monthly' <del> }, <del> plans: { <del> year: [100000, 25000, 3500], <del> month: [5000, 3500, 500] <del> } <del> }; <del> <ide> const subscriptionPlans = Object.keys( <ide> donationSubscriptionConfig.plans <ide> ).reduce( <ide> export default function donateBoot(app, done) { <ide> function validStripeForm(amount, duration, email) { <ide> return isEmail('' + email) && <ide> isNumeric('' + amount) && <del> durationKeys.includes(duration) && <add> durationKeysConfig.includes(duration) && <ide> duration === 'onetime' <ide> ? donationOneTimeConfig.includes(amount) <ide> : donationSubscriptionConfig.plans[duration]; <ide><path>client/src/components/Donation/components/DonateForm.js <ide> import { <ide> Radio <ide> } from '@freecodecamp/react-bootstrap'; <ide> import { StripeProvider, Elements } from 'react-stripe-elements'; <add> <add>import { <add> amountsConfig, <add> durationsConfig, <add> defaultStateConfig <add>} from '../../../../../config/donation-settings'; <ide> import { apiLocation } from '../../../../config/env.json'; <ide> import Spacer from '../../helpers/Spacer'; <ide> import DonateFormChildViewForHOC from './DonateFormChildViewForHOC'; <ide> class DonateForm extends Component { <ide> constructor(...args) { <ide> super(...args); <ide> <add> this.durations = durationsConfig; <add> this.amounts = amountsConfig; <add> <ide> this.state = { <ide> processing: false, <ide> isDonating: this.props.isDonating, <del> donationAmount: 5000, <del> donationDuration: 'month', <del> paymentType: 'Card' <del> }; <del> <del> this.durations = { <del> year: 'yearly', <del> month: 'monthly', <del> onetime: 'one-time' <del> }; <del> this.amounts = { <del> year: [100000, 25000, 3500], <del> month: [5000, 3500, 500], <del> onetime: [100000, 25000, 3500] <add> ...defaultStateConfig <ide> }; <ide> <ide> this.getActiveDonationAmount = this.getActiveDonationAmount.bind(this); <ide><path>config/donation-settings.js <add>// Configuration for client side <add>const durationsConfig = { <add> year: 'yearly', <add> month: 'monthly', <add> onetime: 'one-time' <add>}; <add>const amountsConfig = { <add> year: [100000, 25000, 3500], <add> month: [5000, 3500, 500], <add> onetime: [100000, 25000, 3500] <add>}; <add>const defaultStateConfig = { <add> donationAmount: 5000, <add> donationDuration: 'month', <add> paymentType: 'Card' <add>}; <add> <add>// Configuration for server side <add>const durationKeysConfig = ['year', 'month', 'onetime']; <add>const donationOneTimeConfig = [100000, 25000, 3500]; <add>const donationSubscriptionConfig = { <add> duration: { <add> year: 'Yearly', <add> month: 'Monthly' <add> }, <add> plans: { <add> year: [100000, 25000, 3500], <add> month: [5000, 3500, 500] <add> } <add>}; <add> <add>module.exports = { <add> durationsConfig, <add> amountsConfig, <add> defaultStateConfig, <add> durationKeysConfig, <add> donationOneTimeConfig, <add> donationSubscriptionConfig <add>};
3
PHP
PHP
replace loose comparison with casting to boolean
a7c751922d4a728f66bdb18d0a660ced55c88a1b
<ide><path>lib/Cake/Controller/Component/AuthComponent.php <ide> public function shutdown(Controller $controller) { <ide> * @return boolean true if the user is logged in, false otherwise <ide> */ <ide> public function loggedIn() { <del> return $this->user() != array(); <add> return (boolean)$this->user(); <ide> } <ide> <ide> /**
1
Java
Java
fix typo in javadoc of abstractencoder
675e0b94c13e4a188a8b8a793f98593c5c897765
<ide><path>spring-core/src/main/java/org/springframework/core/codec/AbstractEncoder.java <ide> import org.springframework.util.MimeType; <ide> <ide> /** <del> * Abstract base class for {@link Decoder} implementations. <add> * Abstract base class for {@link Encoder} implementations. <ide> * <ide> * @author Sebastien Deleuze <ide> * @author Arjen Poutsma
1
Ruby
Ruby
improve/fix credential handling
6135da800e4f93ded3a5a331d0efa691f4822afb
<ide><path>Library/Homebrew/cmd/gist-logs.rb <ide> def gistify_logs(f) <ide> if ARGV.include?("--new-issue") || ARGV.switch?("n") <ide> auth = :AUTH_TOKEN <ide> <del> unless GitHub.api_credentials <add> if GitHub.api_credentials_type == :none <ide> puts "You can create a personal access token: https://github.com/settings/tokens" <ide> puts "and then set HOMEBREW_GITHUB_API_TOKEN as authentication method." <ide> puts <ide> <del> auth = :AUTH_BASIC <add> auth = :AUTH_USER_LOGIN <ide> end <ide> <ide> url = new_issue(f.tap, "#{f.name} failed to build on #{MacOS.full_version}", url, auth) <ide> def make_request(path, data, auth) <ide> headers = GitHub.api_headers <ide> headers["Content-Type"] = "application/json" <ide> <add> basic_auth_credentials = nil <add> if auth != :AUTH_USER_LOGIN <add> token, username = GitHub.api_credentials <add> case GitHub.api_credentials_type <add> when :keychain <add> basic_auth_credentials = [username, token] <add> when :environment <add> headers["Authorization"] = "token #{token}" <add> end <add> end <add> <ide> request = Net::HTTP::Post.new(path, headers) <add> request.basic_auth(*basic_auth_credentials) if basic_auth_credentials <ide> <del> login(request) if auth == :AUTH_BASIC <add> login(request) if auth == :AUTH_USER_LOGIN <ide> <ide> request.body = Utils::JSON.dump(data) <ide> request <ide> def post(path, data, auth = nil) <ide> when Net::HTTPCreated <ide> Utils::JSON.load get_body(response) <ide> else <add> GitHub.api_credentials_error_message(response) <ide> raise "HTTP #{response.code} #{response.message} (expected 201)" <ide> end <ide> end <ide><path>Library/Homebrew/utils.rb <ide> module GitHub <ide> class RateLimitExceededError < Error <ide> def initialize(reset, error) <ide> super <<-EOS.undent <del> GitHub #{error} <add> GitHub API Error: #{error} <ide> Try again in #{pretty_ratelimit_reset(reset)}, or create a personal access token: <ide> #{Tty.em}https://github.com/settings/tokens/new?scopes=&description=Homebrew#{Tty.reset} <ide> and then set the token as: export HOMEBREW_GITHUB_API_TOKEN="your_new_token" <ide> def initialize(error) <ide> EOS <ide> else <ide> message << <<-EOS.undent <del> The GitHub credentials in the OS X keychain are invalid. <add> The GitHub credentials in the OS X keychain may be invalid. <ide> Clear them with: <ide> printf "protocol=https\\nhost=github.com\\n" | git credential-osxkeychain erase <add> Or create a personal access token: <add> #{Tty.em}https://github.com/settings/tokens/new?scopes=&description=Homebrew#{Tty.reset} <add> and then set the token as: export HOMEBREW_GITHUB_API_TOKEN="your_new_token" <ide> EOS <ide> end <ide> super message <ide> def api_credentials <ide> end <ide> end <ide> <del> def api_headers <del> @api_headers ||= begin <del> headers = { <del> "User-Agent" => HOMEBREW_USER_AGENT, <del> "Accept" => "application/vnd.github.v3+json" <del> } <del> token, username = api_credentials <del> if token && !token.empty? <del> if username && !username.empty? <del> headers[:http_basic_authentication] = [username, token] <del> else <del> headers["Authorization"] = "token #{token}" <add> def api_credentials_type <add> token, username = api_credentials <add> if token && !token.empty? <add> if username && !username.empty? <add> :keychain <add> else <add> :environment <add> end <add> else <add> :none <add> end <add> end <add> <add> def api_credentials_error_message(response_headers) <add> @api_credentials_error_message_printed ||= begin <add> unauthorized = (response_headers["status"] == "401 Unauthorized") <add> scopes = response_headers["x-accepted-oauth-scopes"].to_s.split(", ") <add> if !unauthorized && scopes.empty? <add> credentials_scopes = response_headers["x-oauth-scopes"].to_s.split(", ") <add> <add> case GitHub.api_credentials_type <add> when :keychain <add> onoe <<-EOS.undent <add> Your OS X keychain GitHub credentials do not have sufficient scope! <add> Scopes they have: #{credentials_scopes} <add> Create a personal access token: https://github.com/settings/tokens <add> and then set HOMEBREW_GITHUB_API_TOKEN as the authentication method instead. <add> EOS <add> when :environment <add> onoe <<-EOS.undent <add> Your HOMEBREW_GITHUB_API_TOKEN does not have sufficient scope! <add> Scopes it has: #{credentials_scopes} <add> Create a new personal access token: https://github.com/settings/tokens <add> and then set the new HOMEBREW_GITHUB_API_TOKEN as the authentication method instead. <add> EOS <ide> end <ide> end <del> headers <add> true <ide> end <ide> end <ide> <add> def api_headers <add> { <add> "User-Agent" => HOMEBREW_USER_AGENT, <add> "Accept" => "application/vnd.github.v3+json" <add> } <add> end <add> <ide> def open(url, &_block) <ide> # This is a no-op if the user is opting out of using the GitHub API. <ide> return if ENV["HOMEBREW_NO_GITHUB_API"] <ide> <ide> require "net/https" <ide> <add> headers = api_headers <add> token, username = api_credentials <add> case api_credentials_type <add> when :keychain <add> headers[:http_basic_authentication] = [username, token] <add> when :environment <add> headers["Authorization"] = "token #{token}" <add> end <add> <ide> begin <del> Kernel.open(url, api_headers) { |f| yield Utils::JSON.load(f.read) } <add> Kernel.open(url, headers) { |f| yield Utils::JSON.load(f.read) } <ide> rescue OpenURI::HTTPError => e <ide> handle_api_error(e) <ide> rescue EOFError, SocketError, OpenSSL::SSL::SSLError => e <ide> def handle_api_error(e) <ide> raise RateLimitExceededError.new(reset, error) <ide> end <ide> <add> GitHub.api_credentials_error_message(e.io.meta) <add> <ide> case e.io.status.first <ide> when "401", "403" <ide> raise AuthenticationFailedError.new(e.message)
2
Java
Java
add missing package-info
572d0173703e15a80e76eac2ad0bea9c56f35326
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/generator/package-info.java <add>/** <add> * Support for generating code that represents the state of a bean factory. <add> */ <add>@NonNullApi <add>@NonNullFields <add>package org.springframework.beans.factory.generator; <add> <add>import org.springframework.lang.NonNullApi; <add>import org.springframework.lang.NonNullFields;
1
Python
Python
remove unnecessary namedtuple/dataclass
499c39acba4bedd1b73e3c0687020387013ee4ba
<ide><path>spacy/lang/ko/__init__.py <ide> # encoding: utf8 <ide> from __future__ import unicode_literals, print_function <ide> <del>import sys <del> <ide> from .stop_words import STOP_WORDS <ide> from .tag_map import TAG_MAP <ide> from ...attrs import LANG <ide> from ...language import Language <ide> from ...tokens import Doc <ide> from ...compat import copy_reg <ide> from ...util import DummyTokenizer <del>from ...compat import is_python3, is_python_pre_3_5 <del> <del>is_python_post_3_7 = is_python3 and sys.version_info[1] >= 7 <del> <del># fmt: off <del>if is_python_pre_3_5: <del> from collections import namedtuple <del> Morpheme = namedtuple("Morpheme", "surface lemma tag") <del>elif is_python_post_3_7: <del> from dataclasses import dataclass <del> <del> @dataclass(frozen=True) <del> class Morpheme: <del> surface: str <del> lemma: str <del> tag: str <del>else: <del> from typing import NamedTuple <del> <del> class Morpheme(NamedTuple): <del> <del> surface = str("") <del> lemma = str("") <del> tag = str("") <ide> <ide> <ide> def try_mecab_import(): <ide> try: <ide> from natto import MeCab <add> <ide> return MeCab <ide> except ImportError: <ide> raise ImportError( <ide> "Korean support requires [mecab-ko](https://bitbucket.org/eunjeon/mecab-ko/src/master/README.md), " <ide> "[mecab-ko-dic](https://bitbucket.org/eunjeon/mecab-ko-dic), " <ide> "and [natto-py](https://github.com/buruzaemon/natto-py)" <ide> ) <add> <add> <ide> # fmt: on <ide> <ide> <ide> def __call__(self, text): <ide> surfaces = [dt.surface for dt in dtokens] <ide> doc = Doc(self.vocab, words=surfaces, spaces=list(check_spaces(text, surfaces))) <ide> for token, dtoken in zip(doc, dtokens): <del> first_tag, sep, eomi_tags = dtoken.tag.partition("+") <add> first_tag, sep, eomi_tags = dtoken["tag"].partition("+") <ide> token.tag_ = first_tag # stem(어간) or pre-final(선어말 어미) <del> token.lemma_ = dtoken.lemma <del> doc.user_data["full_tags"] = [dt.tag for dt in dtokens] <add> token.lemma_ = dtoken["lemma"] <add> doc.user_data["full_tags"] = [dt["tag"] for dt in dtokens] <ide> return doc <ide> <ide> def detailed_tokens(self, text): <ide> def detailed_tokens(self, text): <ide> lemma, _, remainder = expr.partition("/") <ide> if lemma == "*": <ide> lemma = surface <del> yield Morpheme(surface, lemma, tag) <add> yield {"surface": surface, "lemma": lemma, "tag": tag} <ide> <ide> <ide> class KoreanDefaults(Language.Defaults):
1
Ruby
Ruby
use infinity const
a01756c33ed9e2fcb3724dbf607ba64c963b112f
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/cast.rb <ide> def string_to_time(string) <ide> return string unless String === string <ide> <ide> case string <del> when 'infinity'; 1.0 / 0.0 <del> when '-infinity'; -1.0 / 0.0 <add> when 'infinity'; Float::INFINITY <add> when '-infinity'; -Float::INFINITY <ide> when / BC$/ <ide> super("-" + string.sub(/ BC$/, "")) <ide> else
1
PHP
PHP
fix bug in ioc singleton checking
638032f4c0fa887aabcf494bf2504b54be470a34
<ide><path>laravel/ioc.php <ide> public static function resolve($name, $parameters = array()) <ide> // If the resolver is registering as a singleton resolver, we will cache <ide> // the instance of the object in the container so we can resolve it next <ide> // time without having to instantiate a brand new instance. <del> if (isset(static::$registry[$name]['singleton'])) <add> if (static::$registry[$name]['singleton']) <ide> { <ide> return static::$singletons[$name] = $object; <ide> }
1
Text
Text
remove duplicate whitespaces in doc/api
83a7247f12feb4f4d8ee558ad2c1528d26b503e0
<ide><path>doc/api/child_process.md <ide> pipes between the parent and child. The value is one of the following: <ide> `'ignore'` will cause Node.js to open `/dev/null` and attach it to the <ide> child's fd. <ide> 4. `'inherit'` - Pass through the corresponding stdio stream to/from the <del> parent process. In the first three positions, this is equivalent to <del> `process.stdin`, `process.stdout`, and `process.stderr`, respectively. In <add> parent process. In the first three positions, this is equivalent to <add> `process.stdin`, `process.stdout`, and `process.stderr`, respectively. In <ide> any other position, equivalent to `'ignore'`. <ide> 5. {Stream} object - Share a readable or writable stream that refers to a tty, <ide> file, socket, or a pipe with the child process. The stream's underlying <ide><path>doc/api/cli.md <ide> see those as two separate modules and would attempt to load the module multiple <ide> times, causing an exception to be thrown). <ide> <ide> The `--preserve-symlinks` flag does not apply to the main module, which allows <del>`node --preserve-symlinks node_module/.bin/<foo>` to work. To apply the same <add>`node --preserve-symlinks node_module/.bin/<foo>` to work. To apply the same <ide> behavior for the main module, also use `--preserve-symlinks-main`. <ide> <ide> ### `--preserve-symlinks-main` <ide><path>doc/api/cluster.md <ide> Node.js process and a cluster worker differs: <ide> the worker to use the supplied handle, rather than talk to the master <ide> process. <ide> 3. `server.listen(0)` Normally, this will cause servers to listen on a <del> random port. However, in a cluster, each worker will receive the <add> random port. However, in a cluster, each worker will receive the <ide> same "random" port each time they do `listen(0)`. In essence, the <ide> port is random the first time, but predictable thereafter. To listen <ide> on a unique port, generate a port number based on the cluster worker ID. <ide><path>doc/api/fs.md <ide> closing naturally. <ide> <ide> ```js <ide> const fs = require('fs'); <del>// Create a stream from some character device. <add>// Create a stream from some character device. <ide> const stream = fs.createReadStream('/dev/input/event0'); <ide> setTimeout(() => { <ide> stream.close(); // This may not close the stream. <ide> The following constants are meant for use with `fs.open()`. <ide> <td><code>O_NOATIME</code></td> <ide> <td>Flag indicating reading accesses to the file system will no longer <ide> result in an update to the <code>atime</code> information associated with <del> the file. This flag is available on Linux operating systems only.</td> <add> the file. This flag is available on Linux operating systems only.</td> <ide> </tr> <ide> <tr> <ide> <td><code>O_NOFOLLOW</code></td> <ide><path>doc/api/http2.md <ide> added: v10.12.0 <ide> <ide> * `origins` {string[]} <ide> <del>The `'origin'` event is emitted whenever an `ORIGIN` frame is received by <add>The `'origin'` event is emitted whenever an `ORIGIN` frame is received by <ide> the client. The event is emitted with an array of `origin` strings. The <ide> `http2session.originSet` will be updated to include the received <ide> origins. <ide> added: v10.0.0 <ide> <ide> Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method <ide> will cause the `Http2Stream` to be immediately closed and must only be <del>called after the `'wantTrailers'` event has been emitted. When sending a <add>called after the `'wantTrailers'` event has been emitted. When sending a <ide> request or sending a response, the `options.waitForTrailers` option must be set <ide> in order to keep the `Http2Stream` open after the final `DATA` frame so that <ide> trailers can be sent. <ide> added: v8.4.0 <ide> --> <ide> * `callback` {Function} <ide> <del>Stops the server from accepting new connections. See [`net.Server.close()`][]. <add>Stops the server from accepting new connections. See [`net.Server.close()`][]. <ide> <ide> Note that this is not analogous to restricting new requests since HTTP/2 <ide> connections are persistent. To achieve a similar graceful shutdown behavior, <ide> added: v8.4.0 <ide> --> <ide> * `callback` {Function} <ide> <del>Stops the server from accepting new connections. See [`tls.Server.close()`][]. <add>Stops the server from accepting new connections. See [`tls.Server.close()`][]. <ide> <ide> Note that this is not analogous to restricting new requests since HTTP/2 <ide> connections are persistent. To achieve a similar graceful shutdown behavior, <ide> const server = http2.createServer({ settings }); <ide> <ide> Once the client receives the `SETTINGS` frame from the server indicating that <ide> the extended CONNECT may be used, it may send `CONNECT` requests that use the <del>`':protocol'` HTTP/2 pseudo-header: <add>`':protocol'` HTTP/2 pseudo-header: <ide> <ide> ```js <ide> const http2 = require('http2'); <ide><path>doc/api/os.md <ide> The following error constants are exported by `os.constants.errno`: <ide> </tr> <ide> <tr> <ide> <td><code>EOPNOTSUPP</code></td> <del> <td>Indicates that an operation is not supported on the socket. Note that <add> <td>Indicates that an operation is not supported on the socket. Note that <ide> while <code>ENOTSUP</code> and <code>EOPNOTSUPP</code> have the same value <ide> on Linux, according to POSIX.1 these error values should be distinct.)</td> <ide> </tr> <ide><path>doc/api/tls.md <ide> the key type. <ide> For RSA keys, the following properties may be defined: <ide> * `bits` {number} The RSA bit size. Example: `1024`. <ide> * `exponent` {string} The RSA exponent, as a string in hexadecimal number <del> notation. Example: `'0x010001'`. <add> notation. Example: `'0x010001'`. <ide> * `modulus` {string} The RSA modulus, as a hexadecimal string. Example: <ide> `'B56CE45CB7...'`. <ide> * `pubkey` {Buffer} The public key. <ide> changes: <ide> `secureProtocol` option, use one or the other. **Default:** `'TLSv1.2'`. <ide> * `minVersion` {string} Optionally set the minimum TLS version to allow. One <ide> of `TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the <del> `secureProtocol` option, use one or the other. It is not recommended to use <add> `secureProtocol` option, use one or the other. It is not recommended to use <ide> less than TLSv1.2, but it may be required for interoperability. <ide> **Default:** `'TLSv1.2'`, unless changed using CLI options. Using <ide> `--tls-v1.0` changes the default to `'TLSv1'`. Using `--tls-v1.1` changes
7
Text
Text
use svg version of travis build status badge
9397a653a4cfd6725616ea8e1b23093d3b0d59b5
<ide><path>README.md <ide> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE <ide> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <ide> <ide> <del>[build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master <add>[build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.svg?branch=master <ide> [travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master <ide> [pypi-version]: https://pypip.in/version/djangorestframework/badge.svg <ide> [pypi]: https://pypi.python.org/pypi/djangorestframework
1
Text
Text
remove python 3.5 reference from readme
2689624c5cc944805a42d26bb957091b3283dcfb
<ide><path>README.md <ide> They are based on the official release schedule of Python and Kubernetes, nicely <ide> make them work in our CI pipeline (which might not be immediate due to dependencies catching up with <ide> new versions of Python mostly) we release new images/support in Airflow based on the working CI setup. <ide> <del>### Additional notes on Python version requirements <del> <del>* Previous versions [require](https://github.com/apache/airflow/issues/8162) at least Python 3.5.3 <del> when using Python 3. <del> <ide> ## Approach to dependencies of Airflow <ide> <ide> Airflow has a lot of dependencies - direct and transitive, also Airflow is both - library and application,
1
PHP
PHP
add test for mailers not being reset on error
0ab2d073ee2c73233f156337fd3c2e33488d587d
<ide><path>tests/TestCase/Mailer/MailerTest.php <ide> namespace Cake\Test\TestCase\Mailer; <ide> <ide> use Cake\TestSuite\TestCase; <add>use RuntimeException; <ide> use TestApp\Mailer\TestMailer; <ide> <ide> class MailerTest extends TestCase <ide> public function testSendWithUnsetTemplateDefaultsToActionName() <ide> $this->assertEquals($mailer->template, 'test'); <ide> } <ide> <add> /** <add> * Test that mailers call reset() when send fails <add> */ <add> public function testSendFailsEmailIsReset() <add> { <add> $email = $this->getMockForEmail(['send', 'reset']); <add> $email->expects($this->once()) <add> ->method('send') <add> ->will($this->throwException(new RuntimeException('kaboom'))); <add> <add> $mailer = $this->getMockBuilder('TestApp\Mailer\TestMailer') <add> ->setMethods(['welcome', 'reset']) <add> ->setConstructorArgs([$email]) <add> ->getMock(); <add> <add> // Mailer should be reset even if sending fails. <add> $mailer->expects($this->once()) <add> ->method('reset'); <add> <add> try { <add> $mailer->send('welcome', ['foo', 'bar']); <add> $this->fail('Exception should bubble up.'); <add> } catch (RuntimeException $e) { <add> $this->assertTrue(true, 'Exception was raised'); <add> } <add> } <add> <ide> /** <ide> * test that initial email instance config is restored after email is sent. <ide> *
1
Java
Java
change hasexception to hasthrowable
0531b8bff5c14d9504beefb4ad47f473e3a22932
<ide><path>rxjava-core/src/main/java/rx/Notification.java <ide> public boolean hasValue() { <ide> * <ide> * @return a value indicating whether this notification has an exception. <ide> */ <del> public boolean hasException() { <add> public boolean hasThrowable() { <ide> return isOnError() && throwable != null; <ide> } <ide> <ide> public String toString() { <ide> StringBuilder str = new StringBuilder("[").append(super.toString()).append(" ").append(getKind()); <ide> if (hasValue()) <ide> str.append(" ").append(getValue()); <del> if (hasException()) <add> if (hasThrowable()) <ide> str.append(" ").append(getThrowable().getMessage()); <ide> str.append("]"); <ide> return str.toString(); <ide> public int hashCode() { <ide> int hash = getKind().hashCode(); <ide> if (hasValue()) <ide> hash = hash * 31 + getValue().hashCode(); <del> if (hasException()) <add> if (hasThrowable()) <ide> hash = hash * 31 + getThrowable().hashCode(); <ide> return hash; <ide> } <ide> public boolean equals(Object obj) { <ide> return false; <ide> if (hasValue() && !getValue().equals(notification.getValue())) <ide> return false; <del> if (hasException() && !getThrowable().equals(notification.getThrowable())) <add> if (hasThrowable() && !getThrowable().equals(notification.getThrowable())) <ide> return false; <ide> return true; <ide> }
1
Python
Python
set version to v2.1.0a7
7d4a52a4d06ade37e27c63c7596acba4d863a32d
<ide><path>spacy/about.py <ide> # fmt: off <ide> <ide> __title__ = "spacy-nightly" <del>__version__ = "2.1.0a7.dev12" <add>__version__ = "2.1.0a7" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion AI" <ide> __email__ = "contact@explosion.ai" <ide> __license__ = "MIT" <del>__release__ = False <add>__release__ = True <ide> <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Text
Text
escape html on "<link> with <a> child" page
848bb3af73c399f83924fb2b31b4327c05ef7d45
<ide><path>errors/invalid-new-link-with-extra-anchor.md <del># Invalid <Link> with <a> child <add># Invalid &lt;Link&gt; with &lt;a&gt; child <ide> <ide> #### Why This Error Occurred <ide>
1
Go
Go
modify some files
128d07d3493aeee8ec6a044039f032aeb2adf699
<ide><path>daemon/cluster/cluster.go <ide> func (c *Cluster) Init(req types.InitRequest) (string, error) { <ide> // will be used as local address, if it belongs to this system. <ide> // If the advertise address is not local, then we try to find <ide> // a system address to use as local address. If this fails, <del> // we give up and ask user to pass the listen address. <add> // we give up and ask the user to pass the listen address. <ide> if net.ParseIP(localAddr).IsUnspecified() { <ide> advertiseIP := net.ParseIP(advertiseHost) <ide> <ide><path>daemon/events/events.go <ide> func (e *Events) Evict(l chan interface{}) { <ide> e.pub.Evict(l) <ide> } <ide> <del>// Log broadcasts event to listeners. Each listener has 100 millisecond for <del>// receiving event or it will be skipped. <add>// Log broadcasts event to listeners. Each listener has 100 milliseconds to <add>// receive the event or it will be skipped. <ide> func (e *Events) Log(action, eventType string, actor eventtypes.Actor) { <ide> eventsCounter.Inc() <ide> now := time.Now().UTC() <ide><path>distribution/metadata/v2_metadata_service.go <ide> type V2Metadata struct { <ide> HMAC string <ide> } <ide> <del>// CheckV2MetadataHMAC return true if the given "meta" is tagged with a hmac hashed by the given "key". <add>// CheckV2MetadataHMAC returns true if the given "meta" is tagged with a hmac hashed by the given "key". <ide> func CheckV2MetadataHMAC(meta *V2Metadata, key []byte) bool { <ide> if len(meta.HMAC) == 0 || len(key) == 0 { <ide> return len(meta.HMAC) == 0 && len(key) == 0 <ide><path>distribution/xfer/download.go <ide> type LayerDownloadManager struct { <ide> tm TransferManager <ide> } <ide> <del>// SetConcurrency set the max concurrent downloads for each pull <add>// SetConcurrency sets the max concurrent downloads for each pull <ide> func (ldm *LayerDownloadManager) SetConcurrency(concurrency int) { <ide> ldm.tm.SetConcurrency(concurrency) <ide> } <ide> type DownloadDescriptorWithRegistered interface { <ide> // the layer store, and the key is not used by an in-progress download, the <ide> // Download method is called to get the layer tar data. Layers are then <ide> // registered in the appropriate order. The caller must call the returned <del>// release function once it is is done with the returned RootFS object. <add>// release function once it is done with the returned RootFS object. <ide> func (ldm *LayerDownloadManager) Download(ctx context.Context, initialRootFS image.RootFS, layers []DownloadDescriptor, progressOutput progress.Output) (image.RootFS, func(), error) { <ide> var ( <ide> topLayer layer.Layer <ide><path>distribution/xfer/transfer.go <ide> func NewTransferManager(concurrencyLimit int) TransferManager { <ide> } <ide> } <ide> <del>// SetConcurrency set the concurrencyLimit <add>// SetConcurrency sets the concurrencyLimit <ide> func (tm *transferManager) SetConcurrency(concurrency int) { <ide> tm.mu.Lock() <ide> tm.concurrencyLimit = concurrency <ide><path>distribution/xfer/upload.go <ide> type LayerUploadManager struct { <ide> tm TransferManager <ide> } <ide> <del>// SetConcurrency set the max concurrent uploads for each push <add>// SetConcurrency sets the max concurrent uploads for each push <ide> func (lum *LayerUploadManager) SetConcurrency(concurrency int) { <ide> lum.tm.SetConcurrency(concurrency) <ide> }
6
Javascript
Javascript
improve progress reporting
1ac28f7fc28325974a77b358cd68830025573df2
<ide><path>lib/ProgressPlugin.js <ide> class ProgressPlugin { <ide> const showActiveModules = this.showActiveModules; <ide> let lastActiveModule = ""; <ide> let currentLoader = ""; <del> let lastModulesCount = this.modulesCount; <del> let lastDependenciesCount = this.dependenciesCount; <add> let lastModulesCount = 0; <add> let lastDependenciesCount = 0; <ide> let lastEntriesCount = 0; <ide> let modulesCount = 0; <ide> let dependenciesCount = 0; <ide> class ProgressPlugin { <ide> /** @type {string[]} */ <ide> const items = []; <ide> const percentByModules = <del> doneModules / Math.max(lastModulesCount, modulesCount); <add> doneModules / <add> Math.max(lastModulesCount || this.modulesCount, modulesCount); <ide> const percentByEntries = <del> doneEntries / Math.max(lastEntriesCount, entriesCount); <add> doneEntries / <add> Math.max(lastEntriesCount || this.dependenciesCount, entriesCount); <ide> const percentByDependencies = <ide> doneDependencies / Math.max(lastDependenciesCount, dependenciesCount); <ide> let percentageFactor; <ide> class ProgressPlugin { <ide> .getCache("ProgressPlugin") <ide> .getItemCache("counts", null); <ide> <del> compiler.hooks.beforeCompile.tapAsync( <del> "ProgressPlugin", <del> (params, callback) => { <del> handler(0.06, "setup", "waiting for cache"); <del> cache.get((err, data) => { <del> if (err) { <del> return callback(err); <del> } <add> let cacheGetPromise; <ide> <del> if (data) { <del> lastModulesCount = lastModulesCount || data.modulesCount; <del> lastDependenciesCount = <del> lastDependenciesCount || data.dependenciesCount; <add> compiler.hooks.beforeCompile.tap("ProgressPlugin", () => { <add> if (!cacheGetPromise) { <add> cacheGetPromise = cache.getPromise().then( <add> data => { <add> if (data) { <add> lastModulesCount = lastModulesCount || data.modulesCount; <add> lastDependenciesCount = <add> lastDependenciesCount || data.dependenciesCount; <add> } <add> }, <add> err => { <add> // Ignore error <ide> } <del> <del> callback(); <del> }); <add> ); <ide> } <del> ); <add> }); <ide> <del> compiler.hooks.afterCompile.tapAsync( <del> "ProgressPlugin", <del> (compilation, callback) => { <del> cache.store({ modulesCount, dependenciesCount }, callback); <del> } <del> ); <add> compiler.hooks.afterCompile.tapPromise("ProgressPlugin", compilation => { <add> return cacheGetPromise.then(() => <add> cache.storePromise({ modulesCount, dependenciesCount }) <add> ); <add> }); <ide> <ide> compiler.hooks.compilation.tap("ProgressPlugin", compilation => { <ide> if (compilation.compiler.isChild()) return; <ide><path>lib/WebpackOptionsApply.js <ide> class WebpackOptionsApply extends OptionsApply { <ide> const PackFileCacheStrategy = require("./cache/PackFileCacheStrategy"); <ide> new IdleFileCachePlugin( <ide> new PackFileCacheStrategy({ <add> compiler, <ide> fs: compiler.intermediateFileSystem, <ide> context: options.context, <ide> cacheLocation: cacheOptions.cacheLocation, <ide><path>lib/cache/IdleFileCachePlugin.js <ide> "use strict"; <ide> <ide> const Cache = require("../Cache"); <add>const ProgressPlugin = require("../ProgressPlugin"); <ide> <ide> /** @typedef {import("../Compiler")} Compiler */ <ide> <ide> class IdleFileCachePlugin { <ide> idleTimer = undefined; <ide> } <ide> isIdle = false; <del> const promises = Array.from(pendingIdleTasks.values()).map(fn => fn()); <add> const reportProgress = ProgressPlugin.getReporter(compiler); <add> const jobs = Array.from(pendingIdleTasks.values()); <add> if (reportProgress) reportProgress(0, "process pending cache items"); <add> const promises = jobs.map(fn => fn()); <ide> pendingIdleTasks.clear(); <ide> promises.push(currentIdlePromise); <del> let promise = Promise.all(promises); <add> const promise = Promise.all(promises); <ide> currentIdlePromise = promise.then(() => strategy.afterAllStored()); <add> if (reportProgress) { <add> currentIdlePromise = currentIdlePromise.then(() => { <add> reportProgress(1, `stored`); <add> }); <add> } <ide> return currentIdlePromise; <ide> } <ide> ); <ide><path>lib/cache/PackFileCacheStrategy.js <ide> "use strict"; <ide> <ide> const FileSystemInfo = require("../FileSystemInfo"); <add>const ProgressPlugin = require("../ProgressPlugin"); <ide> const LazySet = require("../util/LazySet"); <ide> const makeSerializable = require("../util/makeSerializable"); <ide> const memorize = require("../util/memorize"); <ide> const { createFileSerializer } = require("../util/serialization"); <ide> <ide> /** @typedef {import("../Cache").Etag} Etag */ <add>/** @typedef {import("../Compiler")} Compiler */ <ide> /** @typedef {import("../logging/Logger").Logger} Logger */ <ide> /** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ <ide> <ide> class PackContent { <ide> class PackFileCacheStrategy { <ide> /** <ide> * @param {Object} options options <add> * @param {Compiler} options.compiler the compiler <ide> * @param {IntermediateFileSystem} options.fs the filesystem <ide> * @param {string} options.context the context directory <ide> * @param {string} options.cacheLocation the location of the cache data <ide> class PackFileCacheStrategy { <ide> * @param {Iterable<string>} options.immutablePaths immutable paths <ide> */ <ide> constructor({ <add> compiler, <ide> fs, <ide> context, <ide> cacheLocation, <ide> class PackFileCacheStrategy { <ide> immutablePaths, <ide> logger: logger.getChildLogger("webpack.FileSystemInfo") <ide> }); <add> this.compiler = compiler; <ide> this.context = context; <ide> this.cacheLocation = cacheLocation; <ide> this.version = version; <ide> class PackFileCacheStrategy { <ide> } <ide> <ide> afterAllStored() { <add> const reportProgress = ProgressPlugin.getReporter(this.compiler); <ide> return this.packPromise <ide> .then(pack => { <ide> if (!pack.invalid) return; <ide> class PackFileCacheStrategy { <ide> } <ide> this.newBuildDependencies.clear(); <ide> if (newBuildDependencies.size > 0 || !this.buildSnapshot) { <add> if (reportProgress) reportProgress(0.5, "resolve build dependencies"); <ide> this.logger.debug( <ide> `Capturing build dependencies... (${Array.from( <ide> newBuildDependencies <ide> class PackFileCacheStrategy { <ide> } else { <ide> this.resolveResults = resolveResults; <ide> } <add> if (reportProgress) <add> reportProgress( <add> 0.6, <add> "snapshot build dependencies (timestamps)" <add> ); <ide> this.fileSystemInfo.createSnapshot( <ide> undefined, <ide> resolveDependencies.files, <ide> class PackFileCacheStrategy { <ide> } else { <ide> this.resolveBuildDependenciesSnapshot = snapshot; <ide> } <add> if (reportProgress) <add> reportProgress( <add> 0.7, <add> "snapshot build dependencies (hashes)" <add> ); <ide> this.fileSystemInfo.createSnapshot( <ide> undefined, <ide> files, <ide> class PackFileCacheStrategy { <ide> promise = Promise.resolve(); <ide> } <ide> return promise.then(() => { <add> if (reportProgress) reportProgress(0.8, "serialize pack"); <ide> this.logger.time(`store pack`); <ide> const content = new PackContainer( <ide> pack,
4
Python
Python
fix error in arm common libs
e4b35391af5d4472a2f43ce44d9920bad64ba464
<ide><path>libcloud/common/azure_arm.py <ide> def request(self, action, params=None, data=None, headers=None, <ide> # Log in again if the token has expired or is going to expire soon <ide> # (next 5 minutes). <ide> if (time.time() + 300) >= int(self.expires_on): <del> self.get_token_from_credentials(self) <add> self.get_token_from_credentials() <ide> <ide> return super(AzureResourceManagementConnection, self) \ <ide> .request(action, params=params,
1
Ruby
Ruby
add version.slice to compat suite
396ca3fc590ff1e8e5c6fb784458d7a5a5162b00
<ide><path>Library/Homebrew/compat/compatibility.rb <ide> def mountain_lion? <ide> end <ide> alias_method :mountain_lion_or_newer?, :mountain_lion? <ide> end <add> <add> <add>class Version <add> def slice *args <add> opoo "Calling slice on versions is deprecated, use: to_s.slice" <add> to_s.slice *args <add> end <add>end
1
Ruby
Ruby
use genderless pronouns in api docs
49ff20d9b164693ed7fee880b69cc14b141678b3
<ide><path>actionpack/lib/action_controller/base.rb <ide> module ActionController <ide> # or you can remove the entire session with +reset_session+. <ide> # <ide> # Sessions are stored by default in a browser cookie that's cryptographically signed, but unencrypted. <del> # This prevents the user from tampering with the session but also allows him to see its contents. <add> # This prevents the user from tampering with the session but also allows them to see its contents. <ide> # <ide> # Do not put secret information in cookie-based sessions! <ide> # <ide><path>activerecord/lib/active_record/validations/uniqueness.rb <ide> module ClassMethods <ide> # exception. You can either choose to let this error propagate (which <ide> # will result in the default Rails exception page being shown), or you <ide> # can catch it and restart the transaction (e.g. by telling the user <del> # that the title already exists, and asking him to re-enter the title). <add> # that the title already exists, and asking them to re-enter the title). <ide> # This technique is also known as <ide> # {optimistic concurrency control}[http://en.wikipedia.org/wiki/Optimistic_concurrency_control]. <ide> #
2
PHP
PHP
use assertnull in test case
f748b302f1e13f35b14dd759c9cc73d18f1bebe5
<ide><path>tests/TestCase/Http/ServerRequestTest.php <ide> public function testGetEnv() <ide> $request = new ServerRequest(); <ide> <ide> //Test default null <del> $this->assertSame($request->getEnv('Foo'), null); <add> $this->assertNull($request->getEnv('Foo'), null); <ide> <ide> //Test default set <ide> $this->assertSame($request->getEnv('Foo', 'Bar'), 'Bar');
1
Go
Go
update tests with new cookies for registry
b76d6120ac66a853d177f7e53318ab1ee75dca92
<ide><path>api.go <ide> func getBoolParam(value string) (bool, error) { <ide> <ide> func getAuth(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> // FIXME: Handle multiple login at once <add> // FIXME: return specific error code if config file missing? <ide> authConfig, err := auth.LoadConfig(srv.runtime.root) <ide> if err != nil { <del> return err <add> if err != auth.ErrConfigFileMissing { <add> return err <add> } <add> authConfig = &auth.AuthConfig{} <ide> } <ide> b, err := json.Marshal(&auth.AuthConfig{Username: authConfig.Username, Email: authConfig.Email}) <ide> if err != nil { <ide> func postAuth(srv *Server, version float64, w http.ResponseWriter, r *http.Reque <ide> <ide> authConfig, err := auth.LoadConfig(srv.runtime.root) <ide> if err != nil { <del> return err <add> if err != auth.ErrConfigFileMissing { <add> return err <add> } <add> authConfig = &auth.AuthConfig{} <ide> } <ide> if config.Username == authConfig.Username { <ide> config.Password = authConfig.Password <ide><path>api_test.go <ide> func TestGetAuth(t *testing.T) { <ide> defer nuke(runtime) <ide> <ide> srv := &Server{ <del> runtime: runtime, <del> registry: registry.NewRegistry(runtime.root), <add> runtime: runtime, <ide> } <ide> <ide> r := httptest.NewRecorder() <ide> func TestGetAuth(t *testing.T) { <ide> t.Fatalf("%d OK or 0 expected, received %d\n", http.StatusOK, r.Code) <ide> } <ide> <del> newAuthConfig := srv.registry.GetAuthConfig(false) <add> newAuthConfig := registry.NewRegistry(runtime.root).GetAuthConfig(false) <ide> if newAuthConfig.Username != authConfig.Username || <ide> newAuthConfig.Email != authConfig.Email { <ide> t.Fatalf("The auth configuration hasn't been set correctly") <ide> func TestGetImagesSearch(t *testing.T) { <ide> defer nuke(runtime) <ide> <ide> srv := &Server{ <del> runtime: runtime, <del> registry: registry.NewRegistry(runtime.root), <add> runtime: runtime, <ide> } <ide> <ide> r := httptest.NewRecorder() <ide> func TestPostAuth(t *testing.T) { <ide> defer nuke(runtime) <ide> <ide> srv := &Server{ <del> runtime: runtime, <del> registry: registry.NewRegistry(runtime.root), <add> runtime: runtime, <ide> } <ide> <del> authConfigOrig := &auth.AuthConfig{ <add> config := &auth.AuthConfig{ <ide> Username: "utest", <ide> Email: "utest@yopmail.com", <ide> } <del> srv.registry.ResetClient(authConfigOrig) <add> <add> authStr := auth.EncodeAuth(config) <add> auth.SaveConfig(runtime.root, authStr, config.Email) <ide> <ide> r := httptest.NewRecorder() <ide> if err := getAuth(srv, API_VERSION, r, nil, nil); err != nil { <ide> func TestPostAuth(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> if authConfig.Username != authConfigOrig.Username || authConfig.Email != authConfigOrig.Email { <add> if authConfig.Username != config.Username || authConfig.Email != config.Email { <ide> t.Errorf("The retrieve auth mismatch with the one set.") <ide> } <ide> } <ide><path>auth/auth.go <ide> package auth <ide> import ( <ide> "encoding/base64" <ide> "encoding/json" <add> "errors" <ide> "fmt" <ide> "io/ioutil" <ide> "net/http" <ide> const CONFIGFILE = ".dockercfg" <ide> // the registry server we want to login against <ide> const INDEX_SERVER = "https://index.docker.io/v1" <ide> <add>//const INDEX_SERVER = "http://indexstaging-docker.dotcloud.com/" <add> <add>var ( <add> ErrConfigFileMissing error = errors.New("The Auth config file is missing") <add>) <add> <ide> type AuthConfig struct { <ide> Username string `json:"username"` <ide> Password string `json:"password"` <ide> func DecodeAuth(authStr string) (*AuthConfig, error) { <ide> func LoadConfig(rootPath string) (*AuthConfig, error) { <ide> confFile := path.Join(rootPath, CONFIGFILE) <ide> if _, err := os.Stat(confFile); err != nil { <del> return &AuthConfig{}, fmt.Errorf("The Auth config file is missing") <add> return nil, ErrConfigFileMissing <ide> } <ide> b, err := ioutil.ReadFile(confFile) <ide> if err != nil { <ide> func LoadConfig(rootPath string) (*AuthConfig, error) { <ide> } <ide> <ide> // save the auth config <del>func saveConfig(rootPath, authStr string, email string) error { <add>func SaveConfig(rootPath, authStr string, email string) error { <ide> confFile := path.Join(rootPath, CONFIGFILE) <ide> if len(email) == 0 { <ide> os.Remove(confFile) <ide> func Login(authConfig *AuthConfig) (string, error) { <ide> status = "Login Succeeded\n" <ide> storeConfig = true <ide> } else if resp.StatusCode == 401 { <del> saveConfig(authConfig.rootPath, "", "") <add> if err := SaveConfig(authConfig.rootPath, "", ""); err != nil { <add> return "", err <add> } <ide> return "", fmt.Errorf("Wrong login/password, please try again") <ide> } else { <ide> return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body, <ide> func Login(authConfig *AuthConfig) (string, error) { <ide> } <ide> if storeConfig { <ide> authStr := EncodeAuth(authConfig) <del> saveConfig(authConfig.rootPath, authStr, authConfig.Email) <add> if err := SaveConfig(authConfig.rootPath, authStr, authConfig.Email); err != nil { <add> return "", err <add> } <ide> } <ide> return status, nil <ide> } <ide><path>runtime_test.go <ide> package docker <ide> <ide> import ( <ide> "fmt" <del> "github.com/dotcloud/docker/registry" <ide> "github.com/dotcloud/docker/utils" <ide> "io" <ide> "io/ioutil" <ide> func init() { <ide> <ide> // Create the "Server" <ide> srv := &Server{ <del> runtime: runtime, <del> registry: registry.NewRegistry(runtime.root), <add> runtime: runtime, <ide> } <ide> // Retrieve the Image <ide> if err := srv.ImagePull(unitTestImageName, "", "", os.Stdout, false); err != nil {
4
Mixed
Ruby
remove deprecated `name` argument from `#tables`
d5be101dd02214468a27b6839ffe338cfe8ef5f3
<ide><path>activerecord/CHANGELOG.md <add>* Remove deprecated `name` argument from `#tables`. <add> <add> *Rafael Mendonça França* <add> <ide> * Remove deprecated support to passing a column to `#quote`. <ide> <ide> *Rafael Mendonça França* <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def data_source_exists?(name) <ide> end <ide> <ide> # Returns an array of table names defined in the database. <del> def tables(name = nil) <add> def tables <ide> raise NotImplementedError, "#tables is not implemented" <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def collation <ide> show_variable "collation_database" <ide> end <ide> <del> def tables(name = nil) # :nodoc: <add> def tables # :nodoc: <ide> ActiveSupport::Deprecation.warn(<<-MSG.squish) <ide> #tables currently returns both tables and views. <ide> This behavior is deprecated and will be changed with Rails 5.1 to only return tables. <ide> Use #data_sources instead. <ide> MSG <ide> <del> if name <del> ActiveSupport::Deprecation.warn(<<-MSG.squish) <del> Passing arguments to #tables is deprecated without replacement. <del> MSG <del> end <del> <ide> data_sources <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb <ide> def drop_database(name) #:nodoc: <ide> end <ide> <ide> # Returns the list of all tables in the schema search path. <del> def tables(name = nil) <del> if name <del> ActiveSupport::Deprecation.warn(<<-MSG.squish) <del> Passing arguments to #tables is deprecated without replacement. <del> MSG <del> end <del> <add> def tables <ide> select_values("SELECT tablename FROM pg_tables WHERE schemaname = ANY(current_schemas(false))", "SCHEMA") <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def exec_rollback_db_transaction #:nodoc: <ide> <ide> # SCHEMA STATEMENTS ======================================== <ide> <del> def tables(name = nil) # :nodoc: <add> def tables # :nodoc: <ide> ActiveSupport::Deprecation.warn(<<-MSG.squish) <ide> #tables currently returns both tables and views. <ide> This behavior is deprecated and will be changed with Rails 5.1 to only return tables. <ide> Use #data_sources instead. <ide> MSG <ide> <del> if name <del> ActiveSupport::Deprecation.warn(<<-MSG.squish) <del> Passing arguments to #tables is deprecated without replacement. <del> MSG <del> end <del> <ide> data_sources <ide> end <ide> <ide><path>activerecord/test/cases/adapter_test.rb <ide> def test_tables_returning_both_tables_and_views_is_deprecated <ide> assert_deprecated { @connection.tables } <ide> end <ide> end <del> <del> def test_passing_arguments_to_tables_is_deprecated <del> assert_deprecated { @connection.tables(:books) } <del> end <ide> end <ide> <ide> class AdapterTestWithoutTransaction < ActiveRecord::TestCase <ide><path>activerecord/test/cases/adapters/postgresql/connection_test.rb <ide> def test_reset_with_transaction <ide> end <ide> <ide> def test_tables_logs_name <del> ActiveSupport::Deprecation.silence { @connection.tables("hello") } <add> @connection.tables <ide> assert_equal "SCHEMA", @subscriber.logged[0][1] <ide> end <ide> <ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb <ide> def test_tables_logs_name <ide> WHERE type IN ('table','view') AND name <> 'sqlite_sequence' <ide> SQL <ide> assert_logged [[sql.squish, "SCHEMA", []]] do <del> ActiveSupport::Deprecation.silence do <del> @conn.tables("hello") <del> end <add> @conn.tables <ide> end <ide> end <ide>
8
Javascript
Javascript
fix lint error, remove unnecessary comment
8af527919a9c24c913b5e1916f914d9ca0d4982e
<ide><path>src/jpx.js <ide> var JpxImage = (function JpxImageClosure() { <ide> ]; <ide> <ide> function BitModel(width, height, subband, zeroBitPlanes) { <del> // TODO do we need to know offsets of the coefficients (not only width <del> // and height) ? <ide> this.width = width; <ide> this.height = height; <ide> <ide> var JpxImage = (function JpxImageClosure() { <ide> if (!scalarExpounded) { <ide> // formula E-5 <ide> mu = spqcds[0].mu; <del> epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0); <add> epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0); <ide> } else { <ide> mu = spqcds[b].mu; <ide> epsilon = spqcds[b].epsilon;
1
PHP
PHP
apply fixes from styleci
be7f51ac647af34d75fb857ee683dc3374292373
<ide><path>src/Illuminate/Support/Collection.php <ide> use CachingIterator; <ide> use JsonSerializable; <ide> use IteratorAggregate; <del>use InvalidArgumentException; <ide> use Illuminate\Support\Debug\Dumper; <ide> use Illuminate\Support\Traits\Macroable; <ide> use Illuminate\Contracts\Support\Jsonable;
1
PHP
PHP
skip failing tests
ac63a20811ebb35453dc2716cef0b33d60b36018
<ide><path>tests/TestCase/Console/Command/Task/TestTaskTest.php <ide> public function tearDown() { <ide> * @return void <ide> */ <ide> public function testFilePathGenerationModelRepeated() { <add> $this->markTestIncomplete('Not working for some reason'); <ide> $this->Task->expects($this->never())->method('err'); <ide> $this->Task->expects($this->never())->method('_stop'); <ide>
1
Python
Python
remove old doc
0512444ee5dea5fa409ebd9396e9b7edac00afe2
<ide><path>src/transformers/models/mobilebert/modeling_mobilebert.py <ide> def forward( <ide> Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., <ide> config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored <ide> (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]`` <del> kwargs (:obj:`Dict[str, any]`, optional, defaults to `{}`): <del> Used to hide legacy arguments that have been deprecated. <ide> """ <ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict <ide>
1
Text
Text
add note about domain locales
6fbe5b439dc9725af8cd4889b9bb662a53c07e82
<ide><path>docs/advanced-features/i18n-routing.md <ide> By using domain routing you can configure locales to be served from different do <ide> // next.config.js <ide> module.exports = { <ide> i18n: { <del> locales: ['en-US', 'fr', 'nl-NL'], <add> locales: ['en-US', 'fr', 'nl-NL', 'nl-BE'], <ide> defaultLocale: 'en-US', <ide> <ide> domains: [ <ide> module.exports = { <ide> { <ide> domain: 'example.nl', <ide> defaultLocale: 'nl-NL', <add> // specify other locales that should be redirected <add> // to this domain <add> locales: ['nl-BE'], <ide> }, <ide> ], <ide> }, <ide> For example if you have `pages/blog.js` the following urls will be available: <ide> - `example.com/blog` <ide> - `example.fr/blog` <ide> - `example.nl/blog` <add>- `example.nl/nl-BE/blog` <ide> <ide> ## Automatic Locale Detection <ide>
1
Go
Go
use constant for task runtime value
2b7d34977e72054d197a481a10addd773aa23ca4
<ide><path>integration/service/plugin_test.go <ide> func TestServicePlugin(t *testing.T) { <ide> <ide> func makePlugin(repo, name string, constraints []string) func(*swarmtypes.Service) { <ide> return func(s *swarmtypes.Service) { <del> s.Spec.TaskTemplate.Runtime = "plugin" <add> s.Spec.TaskTemplate.Runtime = swarmtypes.RuntimePlugin <ide> s.Spec.TaskTemplate.PluginSpec = &runtime.PluginSpec{ <ide> Name: name, <ide> Remote: repo,
1
Text
Text
update the manual for docker wait
303ff807f2690c1f572439bb5bc53a9ba89bf48f
<ide><path>man/docker-wait.1.md <ide> % Docker Community <ide> % JUNE 2014 <ide> # NAME <del>docker-wait - Block until a container stops, then print its exit code. <add>docker-wait - Block until one or more containers stop, then print their exit codes <ide> <ide> # SYNOPSIS <ide> **docker wait** <ide> CONTAINER [CONTAINER...] <ide> <ide> # DESCRIPTION <ide> <del>Block until a container stops, then print its exit code. <add>Block until one or more containers stop, then print their exit codes. <ide> <ide> # OPTIONS <ide> **--help**
1
Text
Text
add note about passing webpack to config
553fbf75e0647f5088120788513b46ecf4af1360
<ide><path>packages/next/README.md <ide> In order to extend our usage of `webpack`, you can define a function that extend <ide> // next.config.js is not transformed by Babel. So you can only use javascript features supported by your version of Node.js. <ide> <ide> module.exports = { <del> webpack: (config, { buildId, dev, isServer, defaultLoaders }) => { <add> webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => { <add> // Note: we provide webpack above so you should not `require` it <ide> // Perform customizations to webpack config <ide> // Important: return the modified config <ide> return config
1
Javascript
Javascript
increase bufsize in child process write test
b71d67795a1366b2c9e77e4156e661df456d3660
<ide><path>test/parallel/test-child-process-stdio-big-write-end.js <ide> 'use strict'; <ide> require('../common'); <ide> const assert = require('assert'); <del>const BUFSIZE = 1024; <add>let bufsize = 0; <ide> <ide> switch (process.argv[2]) { <ide> case undefined: <ide> function parent() { <ide> // Write until the buffer fills up. <ide> let buf; <ide> do { <del> buf = Buffer.alloc(BUFSIZE, '.'); <del> sent += BUFSIZE; <add> bufsize += 1024; <add> buf = Buffer.alloc(bufsize, '.'); <add> sent += bufsize; <ide> } while (child.stdin.write(buf)); <ide> <ide> // then write a bunch more times. <ide> for (let i = 0; i < 100; i++) { <del> const buf = Buffer.alloc(BUFSIZE, '.'); <del> sent += BUFSIZE; <add> const buf = Buffer.alloc(bufsize, '.'); <add> sent += bufsize; <ide> child.stdin.write(buf); <ide> } <ide>
1
Mixed
Javascript
add public api for ipc channel
2dcb7f3826a360f7cac79a58833dc4c037f67e27
<ide><path>doc/api/child_process.md <ide> added: v0.5.9 <ide> The `'message'` event is triggered when a child process uses [`process.send()`][] <ide> to send messages. <ide> <add>### child.channel <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* {Object} A pipe representing the IPC channel to the child process. <add> <add>The `child.channel` property is a reference to the child's IPC channel. If no <add>IPC channel currently exists, this property is `undefined`. <add> <ide> ### child.connected <ide> <!-- YAML <ide> added: v0.7.2 <ide> console.log('中文测试'); <ide> [`'error'`]: #child_process_event_error <ide> [`'exit'`]: #child_process_event_exit <ide> [`'message'`]: #child_process_event_message <add>[`child.channel`]: #child_process_child_channel <ide> [`child.connected`]: #child_process_child_connected <ide> [`child.disconnect()`]: #child_process_child_disconnect <ide> [`child.kill()`]: #child_process_child_kill_signal <ide><path>doc/api/process.md <ide> $ bash -c 'exec -a customArgv0 ./node' <ide> 'customArgv0' <ide> ``` <ide> <add>## process.channel <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>If the Node.js process was spawned with an IPC channel (see the <add>[Child Process][] documentation), the `process.channel` <add>property is a reference to the IPC channel. If no IPC channel exists, this <add>property is `undefined`. <add> <ide> ## process.chdir(directory) <ide> <!-- YAML <ide> added: v0.1.17 <ide><path>lib/internal/child_process.js <ide> const handleConversion = { <ide> // the slave should keep track of the socket <ide> message.key = socket.server._connectionKey; <ide> <del> var firstTime = !this._channel.sockets.send[message.key]; <add> var firstTime = !this.channel.sockets.send[message.key]; <ide> var socketList = getSocketList('send', this, message.key); <ide> <ide> // the server should no longer expose a .connection property <ide> ChildProcess.prototype.unref = function() { <ide> <ide> <ide> function setupChannel(target, channel) { <del> target._channel = channel; <add> target.channel = channel; <add> <add> // _channel can be deprecated in version 8 <add> Object.defineProperty(target, '_channel', { <add> get() { return target.channel; }, <add> set(val) { target.channel = val; }, <add> enumerable: true <add> }); <add> <ide> target._handleQueue = null; <ide> target._pendingHandle = null; <ide> <ide> function setupChannel(target, channel) { <ide> target.disconnect(); <ide> channel.onread = nop; <ide> channel.close(); <del> target._channel = null; <add> target.channel = null; <ide> maybeClose(target); <ide> } <ide> }; <ide> function setupChannel(target, channel) { <ide> }); <ide> <ide> // Process a pending disconnect (if any). <del> if (!target.connected && target._channel && !target._handleQueue) <add> if (!target.connected && target.channel && !target._handleQueue) <ide> target._disconnect(); <ide> <ide> return; <ide> function setupChannel(target, channel) { <ide> }; <ide> <ide> target._send = function(message, handle, options, callback) { <del> assert(this.connected || this._channel); <add> assert(this.connected || this.channel); <ide> <ide> if (message === undefined) <ide> throw new TypeError('"message" argument cannot be undefined'); <ide> function setupChannel(target, channel) { <ide> // connected will be set to false immediately when a disconnect() is <ide> // requested, even though the channel might still be alive internally to <ide> // process queued messages. The three states are distinguished as follows: <del> // - disconnect() never requested: _channel is not null and connected <add> // - disconnect() never requested: channel is not null and connected <ide> // is true <del> // - disconnect() requested, messages in the queue: _channel is not null <add> // - disconnect() requested, messages in the queue: channel is not null <ide> // and connected is false <del> // - disconnect() requested, channel actually disconnected: _channel is <add> // - disconnect() requested, channel actually disconnected: channel is <ide> // null and connected is false <ide> target.connected = true; <ide> <ide> function setupChannel(target, channel) { <ide> }; <ide> <ide> target._disconnect = function() { <del> assert(this._channel); <add> assert(this.channel); <ide> <ide> // This marks the fact that the channel is actually disconnected. <del> this._channel = null; <add> this.channel = null; <ide> <ide> if (this._pendingHandle) { <ide> this._pendingHandle.close(); <ide> function setupChannel(target, channel) { <ide> <ide> const INTERNAL_PREFIX = 'NODE_'; <ide> function handleMessage(target, message, handle) { <del> if (!target._channel) <add> if (!target.channel) <ide> return; <ide> <ide> var eventName = 'message'; <ide> function _validateStdio(stdio, sync) { <ide> <ide> <ide> function getSocketList(type, slave, key) { <del> var sockets = slave._channel.sockets[type]; <add> var sockets = slave.channel.sockets[type]; <ide> var socketList = sockets[key]; <ide> if (!socketList) { <ide> var Construct = type === 'send' ? SocketListSend : SocketListReceive; <ide><path>lib/internal/process/stdio.js <ide> function setupStdio() { <ide> // sitting on fd=0, in such case the pipe for this fd is already <ide> // present and creating a new one will lead to the assertion failure <ide> // in libuv. <del> if (process._channel && process._channel.fd === fd) { <add> if (process.channel && process.channel.fd === fd) { <ide> stdin = new net.Socket({ <del> handle: process._channel, <add> handle: process.channel, <ide> readable: true, <ide> writable: false <ide> }); <ide><path>test/parallel/test-child-process-fork-regr-gh-2847.js <ide> var server = net.createServer(function(s) { <ide> } <ide> <ide> worker.process.once('close', common.mustCall(function() { <del> // Otherwise the crash on `_channel.fd` access may happen <del> assert.strictEqual(worker.process._channel, null); <add> // Otherwise the crash on `channel.fd` access may happen <add> assert.strictEqual(worker.process.channel, null); <ide> server.close(); <ide> })); <ide> <ide><path>test/parallel/test-child-process-fork.js <ide> var fork = require('child_process').fork; <ide> var args = ['foo', 'bar']; <ide> <ide> var n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); <add> <add>assert.strictEqual(n.channel, n._channel); <ide> assert.deepStrictEqual(args, ['foo', 'bar']); <ide> <ide> n.on('message', function(m) { <ide><path>test/parallel/test-child-process-recv-handle.js <ide> function master() { <ide> } <ide> <ide> function worker() { <del> process._channel.readStop(); // Make messages batch up. <add> process.channel.readStop(); // Make messages batch up. <ide> process.stdout.ref(); <ide> process.stdout.write('ok\r\n'); <ide> process.stdin.once('data', common.mustCall((data) => { <ide> assert.strictEqual(data.toString(), 'ok\r\n'); <del> process._channel.readStart(); <add> process.channel.readStart(); <ide> })); <ide> let n = 0; <ide> process.on('message', common.mustCall((msg, handle) => { <ide><path>test/parallel/test-child-process-silent.js <ide> if (process.argv[2] === 'pipe') { <ide> const child = childProcess.fork(process.argv[1], ['pipe'], {silent: true}); <ide> <ide> // Allow child process to self terminate <del> child._channel.close(); <del> child._channel = null; <add> child.channel.close(); <add> child.channel = null; <ide> <ide> child.on('exit', function() { <ide> process.exit(0);
8
Javascript
Javascript
use ember.set when cloning keywords - fixes
526e0c51f581699e179201a0e7a890cc8a9a7230
<ide><path>packages/ember-views/lib/views/view.js <ide> Ember.View = Ember.Object.extend(Ember.Evented, <ide> controller = get(this, 'controller'); <ide> <ide> var keywords = templateData ? Ember.copy(templateData.keywords) : {}; <del> keywords.view = get(this, 'concreteView'); <add> set(keywords, 'view', get(this, 'concreteView')); <ide> <ide> // If the view has a controller specified, make it available to the <ide> // template. If not, pass along the parent template's controller, <ide> // if it exists. <ide> if (controller) { <del> keywords.controller = controller; <add> set(keywords, 'controller', controller); <ide> } <ide> <ide> return keywords;
1
Text
Text
add example usage for replaceme tag
e7f1c0043cf5340778ddf75f7dc80ade65e2d974
<ide><path>tools/doc/README.md <ide> Each type of heading has a description block. <ide> <ide> A description of the function. <ide> <add> ### module.someNewFunction(x) <add> <!-- YAML <add> added: REPLACEME <add> --> <add> <add> * `x` {String} the description of the string <add> <add> This feature is not in a release yet. <add> <ide> ### Event: 'blerg' <ide> <!-- YAML <ide> added: v0.10.0
1
Text
Text
update pr guidelines
0a35529d5360eda2d8d10c7e633c4bc6c4b2bb27
<ide><path>docs/PullRequestGuidelines.md <ide> ## Tips on reviewing pull requests <ide> <del>Does the PR miss info required in the [Pull request template](https://github.com/facebook/react-native/blob/master/PULL_REQUEST_TEMPLATE.md)? Ask for it and link to the template. Add labels 'Needs revision' and 'Needs response from author'. Examples: [#6395](https://github.com/facebook/react-native/pull/6395). <del>Example: <add>Does the PR miss info required in the [Pull request template](https://github.com/facebook/react-native/blob/master/PULL_REQUEST_TEMPLATE.md)? Example: [#6395](https://github.com/facebook/react-native/pull/6395). Add labels 'Needs revision' and 'Needs response from author'. Add a response like: <ide> <ide> > Hey @author, thanks for sending the pull request. <ide> > Can you please add all the info specified in the [template](https://github.com/facebook/react-native/blob/master/PULL_REQUEST_TEMPLATE.md)? This is necessary for people to be able to understand and review your pull request. <ide> <del>Does the code style match the [Style guide](https://github.com/facebook/react-native/blob/master/CONTRIBUTING.md#style-guide), especially consistency with the rest of the codebase? If not, link to the style guide and add the label 'Needs revision'. <add>Does the code style match the [Style guide](https://github.com/facebook/react-native/blob/master/CONTRIBUTING.md#style-guide), especially consistency (formatting, naming) with the rest of the codebase? If not, link to the style guide and add the label 'Needs revision'. <ide> <del>Does the pull request add a completely new feature we don't want to add to the core and maintain? Ask the author to release it a separate npm module. <add>Does the pull request add a completely new feature we don't want to add to the core and maintain? Ask the author to release it a separate npm module and close the PR. Example: [#2648](https://github.com/facebook/react-native/pull/2648). <ide> <del>Does the pull request do several unrelated things at the same time? Ask the author to split it. <add>Does the pull request do several unrelated things at the same time? Ask the author to split it. <ide>\ No newline at end of file
1
Javascript
Javascript
add docs for prefer-util-format-errors rule
85e34b0c73794d3a241aa9e0c6139292f445c30a
<ide><path>tools/eslint-rules/prefer-util-format-errors.js <ide> module.exports = { <ide> if (!isArrowFunctionWithTemplateLiteral(msg)) <ide> return; <ide> <add> // Checks to see if order of arguments to function is the same as the <add> // order of them being concatenated in the template string. The idea is <add> // that if both match, then you can use `util.format`-style args. <add> // Would pass rule: (a, b) => `${b}${a}`. <add> // Would fail rule: (a, b) => `${a}${b}`, and needs to be rewritten. <ide> const { expressions } = msg.body; <ide> const hasSequentialParams = msg.params.every((param, index) => { <ide> const expr = expressions[index];
1
Javascript
Javascript
remove unused config
d68f946fe4ebaba02d68f5b118d53ec397ac705e
<ide><path>benchmark/process/next-tick-depth-args.js <ide> const bench = common.createBenchmark(main, { <ide> n: [12e6] <ide> }); <ide> <del>process.maxTickDepth = Infinity; <del> <ide> function main({ n }) { <ide> let counter = n; <ide> function cb4(arg1, arg2, arg3, arg4) { <ide><path>benchmark/process/next-tick-depth.js <ide> const bench = common.createBenchmark(main, { <ide> n: [12e6] <ide> }); <ide> <del>process.maxTickDepth = Infinity; <del> <ide> function main({ n }) { <ide> let counter = n; <ide> bench.start(); <ide><path>test/parallel/test-next-tick-intentional-starvation.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> <del>// this is the inverse of test-next-tick-starvation. <del>// it verifies that process.nextTick will *always* come before other <del>// events, up to the limit of the process.maxTickDepth value. <del> <del>// WARNING: unsafe! <del>process.maxTickDepth = Infinity; <add>// this is the inverse of test-next-tick-starvation. it verifies <add>// that process.nextTick will *always* come before other events <ide> <ide> let ran = false; <ide> let starved = false; <ide><path>test/parallel/test-stream2-read-sync-stack.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> const Readable = require('stream').Readable; <add> <add>// This tests synchronous read callbacks and verifies that even if they nest <add>// heavily the process handles it without an error <add> <ide> const r = new Readable(); <ide> const N = 256 * 1024; <ide> <del>// Go ahead and allow the pathological case for this test. <del>// Yes, it's an infinite loop, that's the point. <del>process.maxTickDepth = N + 2; <del> <ide> let reads = 0; <ide> r._read = function(n) { <ide> const chunk = reads++ === N ? null : Buffer.allocUnsafe(1); <ide><path>test/sequential/test-next-tick-error-spin.js <ide> if (process.argv[2] !== 'child') { <ide> <ide> const domain = require('domain'); <ide> const d = domain.create(); <del> process.maxTickDepth = 10; <ide> <ide> // in the error handler, we trigger several MakeCallback events <ide> d.on('error', function() {
5
Ruby
Ruby
convert attributes to hash in authenticate_by
c5bbc8101495aeaa3f7ca055d4fb8199d591f5db
<ide><path>activerecord/lib/active_record/secure_password.rb <ide> # frozen_string_literal: true <ide> <del>require "active_support/core_ext/hash/except" <del> <ide> module ActiveRecord <ide> module SecurePassword <ide> extend ActiveSupport::Concern <ide> module ClassMethods <ide> # User.authenticate_by(email: "jdoe@example.com") # => ArgumentError <ide> # User.authenticate_by(password: "abc123") # => ArgumentError <ide> def authenticate_by(attributes) <del> passwords = attributes.select { |name, value| !has_attribute?(name) && has_attribute?("#{name}_digest") } <add> passwords, identifiers = attributes.to_h.partition do |name, value| <add> !has_attribute?(name) && has_attribute?("#{name}_digest") <add> end.map(&:to_h) <ide> <ide> raise ArgumentError, "One or more password arguments are required" if passwords.empty? <del> raise ArgumentError, "One or more finder arguments are required" if passwords.size == attributes.size <add> raise ArgumentError, "One or more finder arguments are required" if identifiers.empty? <ide> <del> if record = find_by(attributes.except(*passwords.keys)) <add> if record = find_by(identifiers) <ide> record if passwords.count { |name, value| record.public_send(:"authenticate_#{name}", value) } == passwords.size <ide> else <del> self.new(passwords) <add> new(passwords) <ide> nil <ide> end <ide> end <ide><path>activerecord/test/cases/secure_password_test.rb <ide> class SecurePasswordTest < ActiveRecord::TestCase <ide> User.authenticate_by(password: @user.password) <ide> end <ide> end <add> <add> test "authenticate_by accepts any object that implements to_h" do <add> params = Enumerator.new { raise "must access via to_h" } <add> <add> assert_called_with(params, :to_h, [[]], returns: { token: @user.token, password: @user.password }) do <add> assert_equal @user, User.authenticate_by(params) <add> end <add> <add> assert_called_with(params, :to_h, [[]], returns: { token: "wrong", password: @user.password }) do <add> assert_nil User.authenticate_by(params) <add> end <add> end <ide> end
2
Ruby
Ruby
remove usage of thread.new
7fbfb02625cb979ec3a82ff3bf04f8efcf6e1ace
<ide><path>Library/Homebrew/cleanup.rb <ide> CLEANUP_MAX_AGE_DAYS = 120 <ide> <ide> module CleanupRefinement <del> refine Enumerator do <del> def parallel <del> queue = Queue.new <del> <del> each do |element| <del> queue.enq(element) <del> end <del> <del> workers = (0...Hardware::CPU.cores).map do <del> Thread.new do <del> Kernel.loop do <del> begin <del> yield queue.deq(true) <del> rescue ThreadError <del> break # if queue is empty <del> end <del> end <del> end <del> end <del> <del> workers.each(&:join) <del> end <del> end <del> <ide> refine Pathname do <ide> def incomplete? <ide> extname.end_with?(".incomplete") <ide> def rm_ds_store(dirs = nil) <ide> HOMEBREW_PREFIX/"Caskroom", <ide> ] <ide> end <del> dirs.select(&:directory?).each.parallel do |dir| <add> dirs.select(&:directory?).each do |dir| <ide> system_command "find", <ide> args: [dir, "-name", ".DS_Store", "-delete"], <ide> print_stderr: false <ide><path>Library/Homebrew/readall.rb <ide> module Readall <ide> class << self <ide> def valid_ruby_syntax?(ruby_files) <del> ruby_files_queue = Queue.new <del> ruby_files.each { |f| ruby_files_queue << f } <ide> failed = false <del> workers = (0...Hardware::CPU.cores).map do <del> Thread.new do <del> Kernel.loop do <del> begin <del> # As a side effect, print syntax errors/warnings to `$stderr`. <del> failed = true if syntax_errors_or_warnings?(ruby_files_queue.deq(true)) <del> rescue ThreadError <del> break <del> end <del> end <del> end <add> ruby_files.each do |ruby_file| <add> # As a side effect, print syntax errors/warnings to `$stderr`. <add> failed = true if syntax_errors_or_warnings?(ruby_file) <ide> end <del> workers.each(&:join) <ide> !failed <ide> end <ide>
2
Javascript
Javascript
add missing line
208d643b11b38906c4cc22c6841bc5c291a82a46
<ide><path>src/renderers/webvr/WebVRManager.js <ide> function WebVRManager( renderer ) { <ide> standingMatrix.makeTranslation(0, scope.userHeight, 0); <ide> } <ide> <add> standingMatrixInverse.getInverse( standingMatrix ); <ide> poseObject.position.applyMatrix4( standingMatrix ); <ide> poseObject.updateMatrixWorld(); <ide>
1
Ruby
Ruby
restore correct scaffold generation
e17ddc255d5d3d2d1032e0f42c627023769ad5ee
<ide><path>railties/lib/rails/generators/active_model.rb <ide> def initialize(name) <ide> <ide> # GET index <ide> def self.all(klass) <del> "#{klass}.scoped.to_a" <add> "#{klass}.all" <ide> end <ide> <ide> # GET show
1