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 | add example to menu | f3689f2321c42eeddb67ab1ee85fa2ab5050ad8a | <ide><path>examples/files.js
<ide> var files = {
<ide> "webgl_interactive_raycasting_points",
<ide> "webgl_interactive_voxelpainter",
<ide> "webgl_kinect",
<add> "webgl_layers",
<ide> "webgl_lensflares",
<ide> "webgl_lights_hemisphere",
<ide> "webgl_lights_physical", | 1 |
Text | Text | add panva to collaborators | db79783bad754fb659328e53ecd7ab50c8055bf1 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Ali Ijaz Sheikh** <ofrobots@google.com> (he/him)
<ide> * [oyyd](https://github.com/oyyd) -
<ide> **Ouyang Yadong** <oyydoibh@gmail.com> (he/him)
<add>* [panva](https://github.com/panva) -
<add>**Filip Skokan** <panva.ip@gmail.com>
<ide> * [PoojaDurgad](https://github.com/PoojaDurgad) -
<ide> **Pooja D P** <Pooja.D.P@ibm.com> (she/her)
<ide> * [psmarshall](https://github.com/psmarshall) - | 1 |
Python | Python | make trace_task_ret and fast_trace_task public | 3af6d9d5e3f52556a63e8091ee777890672256f4 | <ide><path>celery/app/trace.py
<ide> def _signal_internal_error(task, uuid, args, kwargs, request, exc):
<ide> del tb
<ide>
<ide>
<del>def _trace_task_ret(name, uuid, request, body, content_type,
<del> content_encoding, loads=loads_message, app=None,
<del> **extra_request):
<add>def trace_task_ret(name, uuid, request, body, content_type,
<add> content_encoding, loads=loads_message, app=None,
<add> **extra_request):
<ide> app = app or current_app._get_current_object()
<ide> embed = None
<ide> if content_type:
<ide> def _trace_task_ret(name, uuid, request, body, content_type,
<ide> return (1, R, T) if I else (0, Rstr, T)
<ide>
<ide>
<del>trace_task_ret = _trace_task_ret # noqa: E305
<del>
<del>
<del>def _fast_trace_task(task, uuid, request, body, content_type,
<del> content_encoding, loads=loads_message, _loc=None,
<del> hostname=None, **_):
<add>def fast_trace_task(task, uuid, request, body, content_type,
<add> content_encoding, loads=loads_message, _loc=None,
<add> hostname=None, **_):
<ide> _loc = _localized if not _loc else _loc
<ide> embed = None
<ide> tasks, accept, hostname = _loc
<ide> def _fast_trace_task(task, uuid, request, body, content_type,
<ide> )
<ide> return (1, R, T) if I else (0, Rstr, T)
<ide>
<del>fast_trace_task = _fast_trace_task # noqa: E305
<del>
<ide>
<ide> def report_internal_error(task, exc):
<ide> _type, _value, _tb = sys.exc_info()
<ide><path>t/unit/tasks/test_trace.py
<ide>
<ide> from celery import group, signals, states, uuid
<ide> from celery.app.task import Context
<del>from celery.app.trace import (TraceInfo, _fast_trace_task, _trace_task_ret,
<add>from celery.app.trace import (TraceInfo, fast_trace_task, trace_task_ret,
<ide> build_tracer, get_log_policy, get_task_name,
<ide> log_policy_expected, log_policy_ignore,
<ide> log_policy_internal, log_policy_reject,
<ide> def test_trace_exception(self, mock_traceback_clear):
<ide> mock_traceback_clear.assert_called()
<ide>
<ide> def test_trace_task_ret__no_content_type(self):
<del> _trace_task_ret(
<add> trace_task_ret(
<ide> self.add.name, 'id1', {}, ((2, 2), {}, {}), None, None, app=self.app,
<ide> )
<ide>
<ide> def test_fast_trace_task__no_content_type(self):
<ide> self.app.tasks[self.add.name].__trace__ = build_tracer(
<ide> self.add.name, self.add, app=self.app,
<ide> )
<del> _fast_trace_task(
<add> fast_trace_task(
<ide> self.add.name,
<ide> 'id1',
<ide> {},
<ide><path>t/unit/worker/test_request.py
<ide> from kombu.utils.uuid import uuid
<ide>
<ide> from celery import states
<del>from celery.app.trace import (TraceInfo, _trace_task_ret, build_tracer,
<add>from celery.app.trace import (TraceInfo, trace_task_ret, build_tracer,
<ide> mro_lookup, reset_worker_optimizations,
<del> setup_worker_optimizations, trace_task)
<add> setup_worker_optimizations, trace_task,
<add> fast_trace_task)
<ide> from celery.backends.base import BaseDictBackend
<ide> from celery.exceptions import (Ignore, InvalidTaskError, Reject, Retry,
<ide> TaskRevokedError, Terminated, WorkerLostError)
<ide> def test_on_soft_timeout(self, patching):
<ide> assert self.mytask.backend.get_status(job.id) == states.PENDING
<ide>
<ide> def test_fast_trace_task(self):
<del> from celery.app import trace
<ide> assert self.app.use_fast_trace_task is False
<ide> setup_worker_optimizations(self.app)
<ide> assert self.app.use_fast_trace_task is True
<ide> def test_fast_trace_task(self):
<ide> self.mytask.name, self.mytask, self.app.loader, 'test',
<ide> app=self.app,
<ide> )
<del> failed, res, runtime = trace.fast_trace_task(
<add> failed, res, runtime = fast_trace_task(
<ide> self.mytask.name, tid, message.headers, message.body,
<ide> message.content_type, message.content_encoding)
<ide> assert not failed
<ide> def test_fast_trace_task(self):
<ide> reset_worker_optimizations(self.app)
<ide> assert self.app.use_fast_trace_task is False
<ide> delattr(self.mytask, '__trace__')
<del> failed, res, runtime = trace.trace_task_ret(
<add> failed, res, runtime = trace_task_ret(
<ide> self.mytask.name, tid, message.headers, message.body,
<ide> message.content_type, message.content_encoding, app=self.app,
<ide> )
<ide> def test_trace_task_ret(self):
<ide> )
<ide> tid = uuid()
<ide> message = self.TaskMessage(self.mytask.name, tid, args=[4])
<del> _, R, _ = _trace_task_ret(
<add> _, R, _ = trace_task_ret(
<ide> self.mytask.name, tid, message.headers,
<ide> message.body, message.content_type,
<ide> message.content_encoding, app=self.app,
<ide> def test_trace_task_ret__no_trace(self):
<ide> pass
<ide> tid = uuid()
<ide> message = self.TaskMessage(self.mytask.name, tid, args=[4])
<del> _, R, _ = _trace_task_ret(
<add> _, R, _ = trace_task_ret(
<ide> self.mytask.name, tid, message.headers,
<ide> message.body, message.content_type,
<ide> message.content_encoding, app=self.app,
<ide> def test_execute_fail(self):
<ide> assert isinstance(meta['result'], KeyError)
<ide>
<ide> def test_execute_using_pool(self):
<del> from celery.app.trace import trace_task_ret
<ide> tid = uuid()
<ide> job = self.xRequest(id=tid, args=[4])
<ide> p = Mock()
<ide> def test_execute_using_pool(self):
<ide> assert args[3] == job.message.body
<ide>
<ide> def test_execute_using_pool_fast_trace_task(self):
<del> from celery.app.trace import fast_trace_task
<ide> self.app.use_fast_trace_task = True
<ide> tid = uuid()
<ide> job = self.xRequest(id=tid, args=[4])
<ide> def test_execute_using_pool__expired(self):
<ide> job.execute_using_pool(self.pool)
<ide>
<ide> def test_execute_using_pool(self):
<del> from celery.app.trace import trace_task_ret as trace
<ide> weakref_ref = Mock(name='weakref.ref')
<ide> job = self.zRequest(id=uuid(), revoked_tasks=set(), ref=weakref_ref)
<ide> job.execute_using_pool(self.pool)
<ide> self.pool.apply_async.assert_called_with(
<del> trace,
<add> trace_task_ret,
<ide> args=(job.type, job.id, job.request_dict, job.body,
<ide> job.content_type, job.content_encoding),
<ide> accept_callback=job.on_accepted,
<ide> def test_execute_using_pool(self):
<ide> assert job._apply_result is weakref_ref()
<ide>
<ide> def test_execute_using_pool_with_use_fast_trace_task(self):
<del> from celery.app.trace import fast_trace_task as trace
<ide> self.app.use_fast_trace_task = True
<ide> weakref_ref = Mock(name='weakref.ref')
<ide> job = self.zRequest(id=uuid(), revoked_tasks=set(), ref=weakref_ref)
<ide> job.execute_using_pool(self.pool)
<ide> self.pool.apply_async.assert_called_with(
<del> trace,
<add> fast_trace_task,
<ide> args=(job.type, job.id, job.request_dict, job.body,
<ide> job.content_type, job.content_encoding),
<ide> accept_callback=job.on_accepted,
<ide> def test_execute_using_pool_with_use_fast_trace_task(self):
<ide> assert job._apply_result is weakref_ref()
<ide>
<ide> def test_execute_using_pool_with_none_timelimit_header(self):
<del> from celery.app.trace import trace_task_ret as trace
<ide> weakref_ref = Mock(name='weakref.ref')
<ide> job = self.zRequest(id=uuid(),
<ide> revoked_tasks=set(),
<ide> ref=weakref_ref,
<ide> headers={'timelimit': None})
<ide> job.execute_using_pool(self.pool)
<ide> self.pool.apply_async.assert_called_with(
<del> trace,
<add> trace_task_ret,
<ide> args=(job.type, job.id, job.request_dict, job.body,
<ide> job.content_type, job.content_encoding),
<ide> accept_callback=job.on_accepted, | 3 |
Go | Go | add pkg/chrootarchive and use it on the daemon | 0357b26c1b5ecc3a4d0d1b2e7cf63ea8e5f70eba | <ide><path>builder/internals.go
<ide> import (
<ide> "github.com/docker/docker/daemon"
<ide> imagepkg "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/archive"
<add> "github.com/docker/docker/pkg/chrootarchive"
<ide> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/promise"
<ide> func (b *Builder) readContext(context io.Reader) error {
<ide> if b.context, err = tarsum.NewTarSum(decompressedStream, true, tarsum.Version0); err != nil {
<ide> return err
<ide> }
<del> if err := archive.Untar(b.context, tmpdirPath, nil); err != nil {
<add>
<add> os.MkdirAll(tmpdirPath, 0700)
<add> if err := chrootarchive.Untar(b.context, tmpdirPath, nil); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (b *Builder) addContext(container *daemon.Container, orig, dest string, dec
<ide> }
<ide>
<ide> // try to successfully untar the orig
<del> if err := archive.UntarPath(origPath, tarDest); err == nil {
<add> if err := chrootarchive.UntarPath(origPath, tarDest); err == nil {
<ide> return nil
<ide> } else if err != io.EOF {
<ide> log.Debugf("Couldn't untar %s to %s: %s", origPath, tarDest, err)
<ide> func (b *Builder) addContext(container *daemon.Container, orig, dest string, dec
<ide> if err := os.MkdirAll(path.Dir(destPath), 0755); err != nil {
<ide> return err
<ide> }
<del> if err := archive.CopyWithTar(origPath, destPath); err != nil {
<add> if err := chrootarchive.CopyWithTar(origPath, destPath); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (b *Builder) addContext(container *daemon.Container, orig, dest string, dec
<ide> }
<ide>
<ide> func copyAsDirectory(source, destination string, destinationExists bool) error {
<del> if err := archive.CopyWithTar(source, destination); err != nil {
<add> if err := chrootarchive.CopyWithTar(source, destination); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>daemon/graphdriver/aufs/aufs.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/pkg/archive"
<add> "github.com/docker/docker/pkg/chrootarchive"
<ide> "github.com/docker/docker/pkg/log"
<ide> mountpk "github.com/docker/docker/pkg/mount"
<ide> "github.com/docker/docker/utils"
<ide> func (a *Driver) Diff(id, parent string) (archive.Archive, error) {
<ide> }
<ide>
<ide> func (a *Driver) applyDiff(id string, diff archive.ArchiveReader) error {
<del> return archive.Untar(diff, path.Join(a.rootPath(), "diff", id), nil)
<add> return chrootarchive.Untar(diff, path.Join(a.rootPath(), "diff", id), nil)
<ide> }
<ide>
<ide> // DiffSize calculates the changes between the specified id
<ide><path>daemon/graphdriver/fsdiff.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<add> "github.com/docker/docker/pkg/chrootarchive"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/utils"
<ide> func (gdw *naiveDiffDriver) ApplyDiff(id, parent string, diff archive.ArchiveRea
<ide>
<ide> start := time.Now().UTC()
<ide> log.Debugf("Start untar layer")
<del> if err = archive.ApplyLayer(layerFs, diff); err != nil {
<add> if err = chrootarchive.ApplyLayer(layerFs, diff); err != nil {
<ide> return
<ide> }
<ide> log.Debugf("Untar time: %vs", time.Now().UTC().Sub(start).Seconds())
<ide><path>daemon/graphdriver/vfs/driver.go
<ide> import (
<ide> "path"
<ide>
<ide> "github.com/docker/docker/daemon/graphdriver"
<del> "github.com/docker/docker/pkg/archive"
<add> "github.com/docker/docker/pkg/chrootarchive"
<ide> "github.com/docker/libcontainer/label"
<ide> )
<ide>
<ide> func (d *Driver) Create(id, parent string) error {
<ide> if err != nil {
<ide> return fmt.Errorf("%s: %s", parent, err)
<ide> }
<del> if err := archive.CopyWithTar(parentDir, dir); err != nil {
<add> if err := chrootarchive.CopyWithTar(parentDir, dir); err != nil {
<ide> return err
<ide> }
<ide> return nil
<ide><path>daemon/volumes.go
<ide> import (
<ide> "syscall"
<ide>
<ide> "github.com/docker/docker/daemon/execdriver"
<del> "github.com/docker/docker/pkg/archive"
<add> "github.com/docker/docker/pkg/chrootarchive"
<ide> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/pkg/symlink"
<ide> "github.com/docker/docker/volumes"
<ide> func copyExistingContents(source, destination string) error {
<ide>
<ide> if len(srcList) == 0 {
<ide> // If the source volume is empty copy files from the root into the volume
<del> if err := archive.CopyWithTar(source, destination); err != nil {
<add> if err := chrootarchive.CopyWithTar(source, destination); err != nil {
<ide> return err
<ide> }
<ide> }
<ide><path>pkg/chrootarchive/archive.go
<add>package chrootarchive
<add>
<add>import (
<add> "flag"
<add> "fmt"
<add> "io"
<add> "os"
<add> "runtime"
<add> "syscall"
<add>
<add> "github.com/docker/docker/pkg/archive"
<add> "github.com/docker/docker/pkg/reexec"
<add>)
<add>
<add>func untar() {
<add> runtime.LockOSThread()
<add> flag.Parse()
<add>
<add> if err := syscall.Chroot(flag.Arg(0)); err != nil {
<add> fatal(err)
<add> }
<add> if err := syscall.Chdir("/"); err != nil {
<add> fatal(err)
<add> }
<add> if err := archive.Untar(os.Stdin, "/", nil); err != nil {
<add> fatal(err)
<add> }
<add> os.Exit(0)
<add>}
<add>
<add>var (
<add> chrootArchiver = &archive.Archiver{Untar}
<add>)
<add>
<add>func Untar(archive io.Reader, dest string, options *archive.TarOptions) error {
<add> if _, err := os.Stat(dest); os.IsNotExist(err) {
<add> if err := os.MkdirAll(dest, 0777); err != nil {
<add> return err
<add> }
<add> }
<add> cmd := reexec.Command("docker-untar", dest)
<add> cmd.Stdin = archive
<add> out, err := cmd.CombinedOutput()
<add> if err != nil {
<add> return fmt.Errorf("Untar %s %s", err, out)
<add> }
<add> return nil
<add>}
<add>
<add>func TarUntar(src, dst string) error {
<add> return chrootArchiver.TarUntar(src, dst)
<add>}
<add>
<add>// CopyWithTar creates a tar archive of filesystem path `src`, and
<add>// unpacks it at filesystem path `dst`.
<add>// The archive is streamed directly with fixed buffering and no
<add>// intermediary disk IO.
<add>func CopyWithTar(src, dst string) error {
<add> return chrootArchiver.CopyWithTar(src, dst)
<add>}
<add>
<add>// CopyFileWithTar emulates the behavior of the 'cp' command-line
<add>// for a single file. It copies a regular file from path `src` to
<add>// path `dst`, and preserves all its metadata.
<add>//
<add>// If `dst` ends with a trailing slash '/', the final destination path
<add>// will be `dst/base(src)`.
<add>func CopyFileWithTar(src, dst string) (err error) {
<add> return chrootArchiver.CopyFileWithTar(src, dst)
<add>}
<add>
<add>// UntarPath is a convenience function which looks for an archive
<add>// at filesystem path `src`, and unpacks it at `dst`.
<add>func UntarPath(src, dst string) error {
<add> return chrootArchiver.UntarPath(src, dst)
<add>}
<ide><path>pkg/chrootarchive/diff.go
<add>package chrootarchive
<add>
<add>import (
<add> "flag"
<add> "fmt"
<add> "os"
<add> "runtime"
<add> "syscall"
<add>
<add> "github.com/docker/docker/pkg/archive"
<add> "github.com/docker/docker/pkg/reexec"
<add>)
<add>
<add>func applyLayer() {
<add> runtime.LockOSThread()
<add> flag.Parse()
<add>
<add> if err := syscall.Chroot(flag.Arg(0)); err != nil {
<add> fatal(err)
<add> }
<add> if err := syscall.Chdir("/"); err != nil {
<add> fatal(err)
<add> }
<add> if err := archive.ApplyLayer("/", os.Stdin); err != nil {
<add> fatal(err)
<add> }
<add> os.Exit(0)
<add>}
<add>
<add>func ApplyLayer(dest string, layer archive.ArchiveReader) error {
<add> cmd := reexec.Command("docker-applyLayer", dest)
<add> cmd.Stdin = layer
<add> out, err := cmd.CombinedOutput()
<add> if err != nil {
<add> return fmt.Errorf("ApplyLayer %s %s", err, out)
<add> }
<add> return nil
<add>}
<ide><path>pkg/chrootarchive/init.go
<add>package chrootarchive
<add>
<add>import (
<add> "fmt"
<add> "os"
<add>
<add> "github.com/docker/docker/pkg/reexec"
<add>)
<add>
<add>func init() {
<add> reexec.Register("docker-untar", untar)
<add> reexec.Register("docker-applyLayer", applyLayer)
<add>}
<add>
<add>func fatal(err error) {
<add> fmt.Fprint(os.Stderr, err)
<add> os.Exit(1)
<add>}
<ide><path>pkg/reexec/command_linux.go
<add>// +build linux
<add>
<add>package reexec
<add>
<add>import (
<add> "os/exec"
<add> "syscall"
<add>)
<add>
<add>func Command(args ...string) *exec.Cmd {
<add> return &exec.Cmd{
<add> Path: Self(),
<add> Args: args,
<add> SysProcAttr: &syscall.SysProcAttr{
<add> Pdeathsig: syscall.SIGTERM,
<add> },
<add> }
<add>}
<ide><path>pkg/reexec/command_unsupported.go
<add>// +build !linux
<add>
<add>package reexec
<add>
<add>import (
<add> "os/exec"
<add>)
<add>
<add>func Command(args ...string) *exec.Cmd {
<add> return nil
<add>}
<ide><path>pkg/reexec/reexec.go
<ide> func Init() bool {
<ide>
<ide> return true
<ide> }
<del>
<ide> return false
<ide> }
<ide>
<ide> // Self returns the path to the current processes binary
<ide> func Self() string {
<ide> name := os.Args[0]
<del>
<ide> if filepath.Base(name) == name {
<ide> if lp, err := exec.LookPath(name); err == nil {
<ide> name = lp
<ide> }
<ide> }
<del>
<ide> return name
<ide> } | 11 |
PHP | PHP | fix method override | 3d533f03e6b10dd5809333341548b9890a79a3a5 | <ide><path>laravel/core.php
<ide>
<ide> use Symfony\Component\HttpFoundation\LaravelRequest as RequestFoundation;
<ide>
<add>RequestFoundation::enableHttpMethodParameterOverride();
<add>
<ide> Request::$foundation = RequestFoundation::createFromGlobals();
<ide>
<add>
<add>
<ide> /*
<ide> |--------------------------------------------------------------------------
<ide> | Determine The Application Environment | 1 |
Go | Go | increase healthcheck timeout | 8c9362857f352548b94bc39c675d558b4da0d3b3 | <ide><path>integration-cli/docker_cli_service_health_test.go
<ide> func (s *DockerSwarmSuite) TestServiceHealthRun(c *check.C) {
<ide> result := cli.BuildCmd(c, imageName, cli.Daemon(d),
<ide> build.WithDockerfile(`FROM busybox
<ide> RUN touch /status
<del> HEALTHCHECK --interval=1s --timeout=1s --retries=1\
<add> HEALTHCHECK --interval=1s --timeout=5s --retries=1\
<ide> CMD cat /status`),
<ide> )
<ide> result.Assert(c, icmd.Success) | 1 |
Ruby | Ruby | remove obsolete tests | e5eaa6696c7580682365063501d62ae27108f566 | <ide><path>Library/Homebrew/test/test_formula.rb
<ide> def test_mirror_support
<ide> f.downloader.instance_variable_get(:@url)
<ide> end
<ide>
<del> def test_formula_specs
<del> f = SpecTestBall.new
<add> def test_formula_spec_integration
<add> f = Class.new(Formula) do
<add> homepage 'http://example.com'
<add> url 'file:///foo.com/testball-0.1.tbz'
<add> mirror 'file:///foo.org/testball-0.1.tbz'
<add> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5'
<add>
<add> head 'https://github.com/mxcl/homebrew.git', :tag => 'foo'
<add>
<add> devel do
<add> url 'file:///foo.com/testball-0.2.tbz'
<add> mirror 'file:///foo.org/testball-0.2.tbz'
<add> sha256 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef'
<add> end
<add>
<add> bottle do
<add> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :snow_leopard_32
<add> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :snow_leopard
<add> sha1 'baadf00dbaadf00dbaadf00dbaadf00dbaadf00d' => :lion
<add> sha1 '8badf00d8badf00d8badf00d8badf00d8badf00d' => :mountain_lion
<add> end
<add>
<add> def initialize(name="spec_test_ball", path=nil)
<add> super
<add> end
<add> end.new
<ide>
<ide> assert_equal 'http://example.com', f.homepage
<del> assert_equal 'file:///foo.com/testball-0.1.tbz', f.url
<del> assert_equal 1, f.mirrors.length
<ide> assert_version_equal '0.1', f.version
<ide> assert_equal f.stable, f.active_spec
<ide> assert_equal CurlDownloadStrategy, f.download_strategy
<ide> def test_formula_specs
<ide> assert_instance_of Bottle, f.bottle
<ide> assert_instance_of SoftwareSpec, f.devel
<ide> assert_instance_of HeadSoftwareSpec, f.head
<del>
<del> assert_equal 'file:///foo.com/testball-0.1.tbz', f.stable.url
<del> assert_equal "https://downloads.sf.net/project/machomebrew/Bottles/spec_test_ball-0.1.#{MacOS.cat}.bottle.tar.gz",
<del> f.bottle.url
<del> assert_equal 'file:///foo.com/testball-0.2.tbz', f.devel.url
<del> assert_equal 'https://github.com/mxcl/homebrew.git', f.head.url
<del>
<del> assert_empty f.stable.specs
<del> assert_empty f.bottle.specs
<del> assert_empty f.devel.specs
<del> assert_equal({ :tag => 'foo' }, f.head.specs)
<del>
<del> assert_equal CurlDownloadStrategy, f.stable.download_strategy
<del> assert_equal CurlBottleDownloadStrategy, f.bottle.download_strategy
<del> assert_equal CurlDownloadStrategy, f.devel.download_strategy
<del> assert_equal GitDownloadStrategy, f.head.download_strategy
<del>
<del> assert_instance_of Checksum, f.stable.checksum
<del> assert_instance_of Checksum, f.bottle.checksum
<del> assert_instance_of Checksum, f.devel.checksum
<del> assert !f.stable.checksum.empty?
<del> assert !f.bottle.checksum.empty?
<del> assert !f.devel.checksum.empty?
<del> assert_nil f.head.checksum
<del> assert_equal :sha1, f.stable.checksum.hash_type
<del> assert_equal :sha1, f.bottle.checksum.hash_type
<del> assert_equal :sha256, f.devel.checksum.hash_type
<del> assert_equal case MacOS.cat
<del> when :snow_leopard_32 then 'deadbeef'*5
<del> when :snow_leopard then 'faceb00c'*5
<del> when :lion then 'baadf00d'*5
<del> when :mountain_lion then '8badf00d'*5
<del> end, f.bottle.checksum.hexdigest
<del> assert_match(/[0-9a-fA-F]{40}/, f.stable.checksum.hexdigest)
<del> assert_match(/[0-9a-fA-F]{64}/, f.devel.checksum.hexdigest)
<del>
<del> assert_equal 1, f.stable.mirrors.length
<del> assert f.bottle.mirrors.empty?
<del> assert_equal 1, f.devel.mirrors.length
<del> assert f.head.mirrors.empty?
<del>
<del> assert f.stable.version.detected_from_url?
<del> assert f.bottle.version.detected_from_url?
<del> assert f.devel.version.detected_from_url?
<del> assert_version_equal '0.1', f.stable.version
<del> assert_version_equal '0.1', f.bottle.version
<del> assert_version_equal '0.2', f.devel.version
<del> assert_version_equal 'HEAD', f.head.version
<del> assert_equal 0, f.bottle.revision
<del> end
<del>
<del> def test_devel_active_spec
<del> ARGV << '--devel'
<del> f = SpecTestBall.new
<del> assert_equal f.devel, f.active_spec
<del> assert_version_equal '0.2', f.version
<del> assert_equal 'file:///foo.com/testball-0.2.tbz', f.url
<del> assert_equal CurlDownloadStrategy, f.download_strategy
<del> assert_instance_of CurlDownloadStrategy, f.downloader
<del> ensure
<del> ARGV.delete '--devel'
<del> end
<del>
<del> def test_head_active_spec
<del> ARGV << '--HEAD'
<del> f = SpecTestBall.new
<del> assert_equal f.head, f.active_spec
<del> assert_version_equal 'HEAD', f.version
<del> assert_equal 'https://github.com/mxcl/homebrew.git', f.url
<del> assert_equal GitDownloadStrategy, f.download_strategy
<del> assert_instance_of GitDownloadStrategy, f.downloader
<del> ensure
<del> ARGV.delete '--HEAD'
<del> end
<del>
<del> def test_explicit_version_spec
<del> f = ExplicitVersionSpecTestBall.new
<del> assert_version_equal '0.3', f.version
<del> assert_version_equal '0.3', f.stable.version
<del> assert_version_equal '0.4', f.devel.version
<del> assert !f.stable.version.detected_from_url?
<del> assert !f.devel.version.detected_from_url?
<del> end
<del>
<del> def test_head_only_specs
<del> f = HeadOnlySpecTestBall.new
<del>
<del> assert_nil f.stable
<del> assert_nil f.bottle
<del> assert_nil f.devel
<del>
<del> assert_equal f.head, f.active_spec
<del> assert_version_equal 'HEAD', f.version
<del> assert_nil f.head.checksum
<del> assert_equal 'https://github.com/mxcl/homebrew.git', f.url
<del> assert_equal GitDownloadStrategy, f.download_strategy
<del> assert_instance_of GitDownloadStrategy, f.downloader
<del> assert_instance_of HeadSoftwareSpec, f.head
<del> end
<del>
<del> def test_incomplete_stable_specs
<del> f = IncompleteStableSpecTestBall.new
<del>
<del> assert_nil f.stable
<del> assert_nil f.bottle
<del> assert_nil f.devel
<del>
<del> assert_equal f.head, f.active_spec
<del> assert_version_equal 'HEAD', f.version
<del> assert_nil f.head.checksum
<del> assert_equal 'https://github.com/mxcl/homebrew.git', f.url
<del> assert_equal GitDownloadStrategy, f.download_strategy
<del> assert_instance_of GitDownloadStrategy, f.downloader
<del> assert_instance_of HeadSoftwareSpec, f.head
<del> end
<del>
<del> def test_head_only_with_version_specs
<del> f = IncompleteStableSpecTestBall.new
<del>
<del> assert_nil f.stable
<del> assert_nil f.bottle
<del> assert_nil f.devel
<del>
<del> assert_equal f.head, f.active_spec
<del> assert_version_equal 'HEAD', f.version
<del> assert_nil f.head.checksum
<del> assert_equal 'https://github.com/mxcl/homebrew.git', f.url
<del> assert_equal GitDownloadStrategy, f.download_strategy
<del> assert_instance_of GitDownloadStrategy, f.downloader
<del> assert_instance_of HeadSoftwareSpec, f.head
<del> end
<del>
<del> def test_explicit_strategy_specs
<del> f = ExplicitStrategySpecTestBall.new
<del>
<del> assert_instance_of SoftwareSpec, f.stable
<del> assert_instance_of SoftwareSpec, f.devel
<del> assert_instance_of HeadSoftwareSpec, f.head
<del>
<del> assert_equal f.stable, f.active_spec
<del>
<del> assert_nil f.stable.checksum
<del> assert_nil f.devel.checksum
<del> assert_nil f.head.checksum
<del>
<del> assert_equal MercurialDownloadStrategy, f.stable.download_strategy
<del> assert_equal BazaarDownloadStrategy, f.devel.download_strategy
<del> assert_equal SubversionDownloadStrategy, f.head.download_strategy
<del>
<del> assert_equal({ :tag => '0.2' }, f.stable.specs)
<del> assert_equal({ :tag => '0.3' }, f.devel.specs)
<del> assert f.head.specs.empty?
<del> end
<del>
<del> def test_revised_bottle_specs
<del> f = RevisedBottleSpecTestBall.new
<del>
<del> assert_equal 1, f.bottle.revision
<del> assert_equal case MacOS.cat
<del> when :snow_leopard_32 then 'deadbeef'*5
<del> when :snow_leopard then 'faceb00k'*5
<del> when :lion then 'baadf00d'*5
<del> when :mountain_lion then '8badf00d'*5
<del> end, f.bottle.checksum.hexdigest
<del> end
<del>
<del> def test_custom_version_scheme
<del> scheme = Class.new(Version)
<del> f = Class.new(TestBall) { version '1.0' => scheme }.new
<del>
<del> assert_version_equal '1.0', f.version
<del> assert_instance_of scheme, f.version
<ide> end
<ide>
<ide> def test_formula_funcs
<ide><path>Library/Homebrew/test/test_formula_spec_selection.rb
<ide> def assert_spec_selected(spec)
<ide> assert_equal @_f.send(spec), @_f.active_spec
<ide> end
<ide>
<add> def assert_spec_unset(spec)
<add> assert_nil @_f.send(spec)
<add> end
<add>
<ide> def test_selects_head_when_requested
<ide> ARGV.stubs(:build_head?).returns(true)
<ide>
<ide> def test_selects_head_when_exclusive
<ide>
<ide> assert_spec_selected :head
<ide> end
<add>
<add> def test_incomplete_spec_not_selected
<add> formula do
<add> sha1 'deadbeef'*5
<add> version '1.0'
<add> head 'foo'
<add> end
<add>
<add> assert_spec_selected :head
<add> end
<add>
<add> def test_incomplete_stable_not_set
<add> formula do
<add> sha1 'foo'
<add> devel { url 'foo-1.1a' }
<add> head 'foo'
<add> end
<add>
<add> assert_spec_unset :stable
<add> assert_spec_selected :devel
<add> end
<add>
<add> def test_incomplete_devel_not_set
<add> formula do
<add> url 'foo-1.0'
<add> devel { version '1.1a' }
<add> head 'foo'
<add> end
<add>
<add> assert_spec_unset :devel
<add> assert_spec_selected :stable
<add> end
<add>
<add> def test_incomplete_bottle_not_set
<add> formula do
<add> url 'foo-1.0'
<add> bottle do
<add> sha1 'deadbeef'*5 => :some_nonexistent_thing
<add> end
<add> end
<add>
<add> assert_spec_unset :bottle
<add> assert_spec_selected :stable
<add> end
<ide> end
<ide><path>Library/Homebrew/test/test_software_spec.rb
<ide> def test_url_with_specs
<ide> assert_equal({ :branch => 'master' }, @spec.specs)
<ide> end
<ide>
<del> def test_url_with_custom_download_strategy
<add> def test_url_with_custom_download_strategy_class
<ide> strategy = Class.new(AbstractDownloadStrategy)
<ide> @spec.url('foo', :using => strategy)
<ide> assert_equal 'foo', @spec.url
<ide> def test_url_with_specs_and_download_strategy
<ide> assert_equal strategy, @spec.download_strategy
<ide> end
<ide>
<add> def test_url_with_custom_download_strategy_symbol
<add> @spec.url('foo', :using => :git)
<add> assert_equal 'foo', @spec.url
<add> assert_equal GitDownloadStrategy, @spec.download_strategy
<add> end
<add>
<ide> def test_version
<ide> @spec.version('1.0')
<ide> assert_version_equal '1.0', @spec.version
<add> assert !@spec.version.detected_from_url?
<ide> end
<ide>
<ide> def test_version_from_url
<ide> @spec.url('http://foo.com/bar-1.0.tar.gz')
<ide> assert_version_equal '1.0', @spec.version
<add> assert @spec.version.detected_from_url?
<ide> end
<ide>
<ide> def test_version_with_scheme
<ide> def test_verify_download_integrity
<ide> end
<ide>
<ide> class BottleTests < Test::Unit::TestCase
<del> include VersionAssertions
<del>
<ide> def setup
<ide> @spec = Bottle.new
<ide> end
<ide><path>Library/Homebrew/test/testball.rb
<ide> def install
<ide> system "./configure"
<ide> end
<ide> end
<del>
<del>class SpecTestBall < Formula
<del> homepage 'http://example.com'
<del> url 'file:///foo.com/testball-0.1.tbz'
<del> mirror 'file:///foo.org/testball-0.1.tbz'
<del> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5'
<del>
<del> head 'https://github.com/mxcl/homebrew.git', :tag => 'foo'
<del>
<del> devel do
<del> url 'file:///foo.com/testball-0.2.tbz'
<del> mirror 'file:///foo.org/testball-0.2.tbz'
<del> sha256 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef'
<del> end
<del>
<del> bottle do
<del> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :snow_leopard_32
<del> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :snow_leopard
<del> sha1 'baadf00dbaadf00dbaadf00dbaadf00dbaadf00d' => :lion
<del> sha1 '8badf00d8badf00d8badf00d8badf00d8badf00d' => :mountain_lion
<del> end
<del>
<del> def initialize(name="spec_test_ball", path=nil)
<del> super
<del> end
<del>end
<del>
<del>class ExplicitVersionSpecTestBall < Formula
<del> homepage 'http://example.com'
<del> url 'file:///foo.com/testball-stable.tbz'
<del> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5'
<del> version '0.3'
<del>
<del> devel do
<del> url 'file:///foo.com/testball-devel.tbz'
<del> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef'
<del> version '0.4'
<del> end
<del>
<del> bottle do
<del> version '1'
<del> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :snow_leopard
<del> sha1 'baadf00dbaadf00dbaadf00dbaadf00dbaadf00d' => :lion
<del> sha1 '8badf00d8badf00d8badf00d8badf00d8badf00d' => :mountain_lion
<del> end
<del>
<del> def initialize(name="explicit_version_spec_test_ball", path=nil)
<del> super
<del> end
<del>end
<del>
<del>class HeadOnlySpecTestBall < Formula
<del> homepage 'http://example.com'
<del> head 'https://github.com/mxcl/homebrew.git'
<del>
<del> def initialize(name="head_only_spec_test_ball", path=nil)
<del> super
<del> end
<del>end
<del>
<del>class IncompleteStableSpecTestBall < Formula
<del> homepage 'http://example.com'
<del> head 'https://github.com/mxcl/homebrew.git'
<del> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5'
<del>
<del> def initialize(name="incomplete_spec_test_ball", path=nil)
<del> super
<del> end
<del>end
<del>
<del>class HeadOnlyWithVersionSpecTestBall < Formula
<del> homepage 'http://example.com'
<del> head 'https://github.com/mxcl/homebrew.git'
<del> version '0.3'
<del>
<del> def initialize(name="head_only_with_version_spec_test_ball", path=nil)
<del> super
<del> end
<del>end
<del>
<del>class ExplicitStrategySpecTestBall < Formula
<del> homepage 'http://example.com'
<del> url 'file:///foo.com/testball-stable', :using => :hg, :tag => '0.2'
<del> head 'file:///foo.com/testball-head', :using => :svn
<del>
<del> devel do
<del> url 'file:///foo.com/testball-devel', :using => :bzr, :tag => '0.3'
<del> end
<del>
<del> def initialize(name="explicit_strategy_spec_test_ball", path=nil)
<del> super
<del> end
<del>end
<del>
<del>class SnowLeopardBottleSpecTestBall < Formula
<del> homepage 'http://example.com'
<del> url 'file:///foo.com/testball-0.1.tbz'
<del> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5'
<del>
<del> bottle do
<del> cellar :any
<del> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :snow_leopard
<del> end
<del>
<del> def initialize(name="snow_leopard_bottle_spec_test_ball", path=nil)
<del> super
<del> end
<del>end
<del>
<del>class LionBottleSpecTestBall < Formula
<del> homepage 'http://example.com'
<del> url 'file:///foo.com/testball-0.1.tbz'
<del> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5'
<del>
<del> bottle do
<del> cellar :any
<del> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :lion
<del> end
<del>
<del> def initialize(name="lion_bottle_spec_test_ball", path=nil)
<del> super
<del> end
<del>end
<del>
<del>class AllCatsBottleSpecTestBall < Formula
<del> homepage 'http://example.com'
<del> url 'file:///foo.com/testball-0.1.tbz'
<del> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5'
<del>
<del> bottle do
<del> prefix '/private/tmp/testbrew/prefix'
<del> cellar '/private/tmp/testbrew/cellar'
<del> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :snow_leopard_32
<del> sha1 'faceb00cfaceb00cfaceb00cfaceb00cfaceb00c' => :snow_leopard
<del> sha1 'baadf00dbaadf00dbaadf00dbaadf00dbaadf00d' => :lion
<del> sha1 '8badf00d8badf00d8badf00d8badf00d8badf00d' => :mountain_lion
<del> end
<del>
<del> def initialize(name="all_cats_bottle_spec_test_ball", path=nil)
<del> super
<del> end
<del>end
<del>
<del>class RevisedBottleSpecTestBall < Formula
<del> homepage 'http://example.com'
<del> url 'file:///foo.com/testball-0.1.tbz'
<del> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5'
<del>
<del> bottle do
<del> revision 1
<del> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :snow_leopard_32
<del> sha1 'faceb00cfaceb00cfaceb00cfaceb00cfaceb00c' => :snow_leopard
<del> sha1 'baadf00dbaadf00dbaadf00dbaadf00dbaadf00d' => :lion
<del> sha1 '8badf00d8badf00d8badf00d8badf00d8badf00d' => :mountain_lion
<del> end
<del>
<del> def initialize(name="revised_bottle_spec_test_ball", path=nil)
<del> super
<del> end
<del>end | 4 |
PHP | PHP | use valid error codes | e7132e7079e9e4c55e8eed0a45c217720f41f2d9 | <ide><path>src/Console/CommandRunner.php
<ide> public function run(array $argv, ConsoleIo $io = null)
<ide> if ($result === null || $result === true) {
<ide> return Command::CODE_SUCCESS;
<ide> }
<del> if (is_int($result) && $result > 0 && $result < 256) {
<add> if (is_int($result) && $result >= 0 && $result <= 255) {
<ide> return $result;
<ide> }
<ide> | 1 |
Javascript | Javascript | compute flat normals when detail is zero | 5c521f8da5e7972f7cc22729ffaa80efae2b70a3 | <ide><path>src/geometries/PolyhedronGeometry.js
<ide> function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
<ide>
<ide> if ( detail === 0 ) {
<ide>
<del> BufferGeometry.prototype.computeVertexNormals.call( this ); // flat normals
<add> this.computeVertexNormals(); // flat normals
<ide>
<ide> } else {
<ide> | 1 |
Text | Text | add a link to the slack community | 9adc337d44dfcb9607c9cb863dc7fed92198ff07 | <ide><path>README.md
<ide> function (state, action) {
<ide>
<ide> [Read more](https://github.com/sebmarkbage/ecmascript-rest-spread) about the spread properties ES7 proposal.
<ide>
<add>## Discussion
<add>
<add>Join the **#redux** channel of the [Reactiflux](http://reactiflux.com/) Slack community
<add>
<ide> ## Inspiration and Thanks
<ide>
<ide> * [Webpack](https://github.com/webpack/docs/wiki/hot-module-replacement-with-webpack) for Hot Module Replacement | 1 |
Text | Text | add video tutorials links | 5d1a778583cd43b8f7c355f30295fe452043d944 | <ide><path>guide/english/cloud-development/azure/index.md
<ide> Link of all current Azure services - https://azure.microsoft.com/en-us/services/
<ide> * <a href='https://azure.microsoft.com/en-us/' target='_blank' rel='nofollow'>Microsoft Azure</a>
<ide> * <a href='https://docs.microsoft.com/en-us/learn/' target='_blank' rel='nofollow'>Microsoft Learn</a>
<ide>
<add>### Video Tutorials
<add>- [Microsoft Azure Tutorials for Beginners](https://www.youtube.com/watch?v=0bPJPiX89K0)
<add>- [Cloud Computing for Beginners](https://www.youtube.com/watch?v=kQnNd-DyrpA) | 1 |
Ruby | Ruby | apply suggestions from code review | 9256a01afeb94611f3fa7024f96f6558cd235f4f | <ide><path>Library/Homebrew/cask/artifact/moved.rb
<ide> def move(adopt: false, force: false, verbose: false, command: nil, **options)
<ide> ohai "Adopting existing #{self.class.english_name} at '#{target}'"
<ide> same = command.run(
<ide> "/usr/bin/diff",
<del> args: ["-rq", source, target],
<add> args: ["--recursive", "--brief", source, target],
<ide> verbose: verbose,
<ide> print_stdout: verbose,
<ide> ).success?
<ide> def move(adopt: false, force: false, verbose: false, command: nil, **options)
<ide> "the one being installed."
<ide> end
<ide>
<del> # Simulate moving the source to the target location
<add> # Remove the source as we don't need to move it to the target location
<ide> source.rmtree
<ide>
<ide> return post_move(command) | 1 |
Javascript | Javascript | fix constructor fix | 60d83cc52de32a3bbeb838b0febc94bc4f9a4063 | <ide><path>examples/js/loaders/PDBLoader.js
<ide> THREE.PDBLoader = function ( manager ) {
<ide>
<ide> THREE.PDBLoader.prototype = {
<ide>
<del> constructor: THREE.OBJLoader,
<add> constructor: THREE.PDBLoader,
<ide>
<ide> load: function ( url, onLoad ) {
<ide> | 1 |
Ruby | Ruby | optimize the hstore parser | 9ef7f406e6b2ed6cdc237c281bc5b3ad36c67e2a | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb
<ide> def type
<ide>
<ide> def deserialize(value)
<ide> if value.is_a?(::String)
<del> ::Hash[value.scan(HstorePair).map { |k, v|
<del> v = v.upcase == "NULL" ? nil : v.gsub(/\A"(.*)"\Z/m, '\1').gsub(/\\(.)/, '\1')
<del> k = k.gsub(/\A"(.*)"\Z/m, '\1').gsub(/\\(.)/, '\1')
<del> [k, v]
<del> }]
<add> hash = {}
<add> value.scan(HstorePair) do |key, value|
<add> key.gsub!('\"', '"')
<add> key.gsub!('\\\\', '\\')
<add>
<add> value&.gsub!('\"', '"')
<add> value&.gsub!('\\\\', '\\')
<add>
<add> hash[key] = value
<add> end
<add> hash
<ide> else
<ide> value
<ide> end
<ide> def changed_in_place?(raw_old_value, new_value)
<ide>
<ide> private
<ide> HstorePair = begin
<del> quoted_string = /"[^"\\]*(?:\\.[^"\\]*)*"/
<del> unquoted_string = /(?:\\.|[^\s,])[^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*/
<del> /(#{quoted_string}|#{unquoted_string})\s*=>\s*(#{quoted_string}|#{unquoted_string})/
<add> quoted_string = /"([^"\\]*(?:\\.[^"\\]*)*)"/
<add> /#{quoted_string}\s*=>\s*(?:(?=NULL)|#{quoted_string})/
<ide> end
<ide>
<ide> def escape_hstore(value)
<ide><path>activerecord/test/cases/adapters/postgresql/hstore_test.rb
<ide> def test_cast_value_on_write
<ide> def test_type_cast_hstore
<ide> assert_equal({ "1" => "2" }, @type.deserialize("\"1\"=>\"2\""))
<ide> assert_equal({}, @type.deserialize(""))
<del> assert_equal({ "key" => nil }, @type.deserialize("key => NULL"))
<del> assert_equal({ "c" => "}", '"a"' => 'b "a b' }, @type.deserialize(%q(c=>"}", "\"a\""=>"b \"a b")))
<add> assert_cycle("key" => nil)
<add> assert_cycle("c" => "}", '"a"' => 'b "a b')
<ide> end
<ide>
<ide> def test_with_store_accessors
<ide> def test_hstore_dirty_from_database_equal
<ide> assert_not_predicate hstore, :changed?
<ide> end
<ide>
<del> def test_gen1
<del> assert_equal('" "=>""', @type.serialize(" " => ""))
<add> def test_spaces
<add> assert_cycle(" " => " ")
<ide> end
<ide>
<del> def test_gen2
<del> assert_equal('","=>""', @type.serialize("," => ""))
<add> def test_commas
<add> assert_cycle("," => "")
<ide> end
<ide>
<del> def test_gen3
<del> assert_equal('"="=>""', @type.serialize("=" => ""))
<add> def test_signs
<add> assert_cycle("=" => ">")
<ide> end
<ide>
<del> def test_gen4
<del> assert_equal('">"=>""', @type.serialize(">" => ""))
<add> def test_various_null
<add> assert_cycle({ "a" => nil, "b" => nil, "c" => "NuLl", "null" => "c" })
<ide> end
<ide>
<del> def test_parse1
<del> assert_equal({ "a" => nil, "b" => nil, "c" => "NuLl", "null" => "c" }, @type.deserialize('a=>null,b=>NuLl,c=>"NuLl",null=>c'))
<del> end
<del>
<del> def test_parse2
<del> assert_equal({ " " => " " }, @type.deserialize("\\ =>\\ "))
<del> end
<del>
<del> def test_parse3
<del> assert_equal({ "=" => ">" }, @type.deserialize("==>>"))
<del> end
<del>
<del> def test_parse4
<del> assert_equal({ "=a" => "q=w" }, @type.deserialize('\=a=>q=w'))
<add> def test_equal_signs
<add> assert_cycle("=a" => "q=w")
<ide> end
<ide>
<ide> def test_parse5
<del> assert_equal({ "=a" => "q=w" }, @type.deserialize('"=a"=>q\=w'))
<add> assert_cycle("=a" => "q=w")
<ide> end
<ide>
<ide> def test_parse6
<del> assert_equal({ "\"a" => "q>w" }, @type.deserialize('"\"a"=>q>w'))
<add> assert_cycle("\"a" => "q>w")
<ide> end
<ide>
<ide> def test_parse7
<del> assert_equal({ "\"a" => "q\"w" }, @type.deserialize('\"a=>q"w'))
<add> assert_cycle("\"a" => "q\"w")
<ide> end
<ide>
<ide> def test_rewrite | 2 |
Ruby | Ruby | convert fetch test to spec | e637eb414e880559695a71b3fc1efbc7104ee64e | <add><path>Library/Homebrew/cask/spec/cask/cli/fetch_spec.rb
<del><path>Library/Homebrew/cask/test/cask/cli/fetch_test.rb
<del>require "test_helper"
<add>require "spec_helper"
<ide>
<ide> describe Hbc::CLI::Fetch do
<ide> let(:local_transmission) {
<ide> shutup do
<ide> Hbc::CLI::Fetch.run("local-transmission", "local-caffeine")
<ide> end
<del> Hbc::CurlDownloadStrategy.new(local_transmission).cached_location.must_be :exist?
<del> Hbc::CurlDownloadStrategy.new(local_caffeine).cached_location.must_be :exist?
<add> expect(Hbc::CurlDownloadStrategy.new(local_transmission).cached_location).to exist
<add> expect(Hbc::CurlDownloadStrategy.new(local_caffeine).cached_location).to exist
<ide> end
<ide>
<ide> it "prevents double fetch (without nuking existing installation)" do
<ide> end
<ide> new_ctime = File.stat(download_stategy.cached_location).ctime
<ide>
<del> old_ctime.to_i.must_equal new_ctime.to_i
<add> expect(old_ctime.to_i).to eq(new_ctime.to_i)
<ide> end
<ide>
<ide> it "allows double fetch with --force" do
<ide> download_stategy = Hbc::CurlDownloadStrategy.new(local_transmission)
<ide> new_ctime = File.stat(download_stategy.cached_location).ctime
<ide>
<del> # new_ctime.to_i.must_be :>, old_ctime.to_i
<del> new_ctime.to_i.must_be :>, old_ctime.to_i
<add> expect(new_ctime.to_i).to be > old_ctime.to_i
<ide> end
<ide>
<ide> it "properly handles Casks that are not present" do
<del> lambda {
<add> expect {
<ide> shutup do
<ide> Hbc::CLI::Fetch.run("notacask")
<ide> end
<del> }.must_raise Hbc::CaskUnavailableError
<add> }.to raise_error(Hbc::CaskUnavailableError)
<ide> end
<ide>
<ide> describe "when no Cask is specified" do
<ide> it "raises an exception" do
<del> lambda {
<add> expect {
<ide> Hbc::CLI::Fetch.run
<del> }.must_raise Hbc::CaskUnspecifiedError
<add> }.to raise_error(Hbc::CaskUnspecifiedError)
<ide> end
<ide> end
<ide>
<ide> describe "when no Cask is specified, but an invalid option" do
<ide> it "raises an exception" do
<del> lambda {
<add> expect {
<ide> Hbc::CLI::Fetch.run("--notavalidoption")
<del> }.must_raise Hbc::CaskUnspecifiedError
<add> }.to raise_error(Hbc::CaskUnspecifiedError)
<ide> end
<ide> end
<ide> end | 1 |
Python | Python | resolve dir for better output [ci skip] | 43c92ec8c99dfbc873ab62f63e33e93d167649d6 | <ide><path>spacy/cli/init_pipeline.py
<ide> def init_vectors_cli(
<ide> msg.good(
<ide> "Saved nlp object with vectors to output directory. You can now use the "
<ide> "path to it in your config as the 'vectors' setting in [initialize.vocab].",
<del> output_dir,
<add> output_dir.resolve(),
<ide> )
<ide>
<ide> | 1 |
Text | Text | add 1.7.8 release notes | e629fe4a789954084c886a2e770f70c79e8b8bd0 | <ide><path>CHANGELOG.md
<add><a name="1.7.8"></a>
<add># 1.7.8 enthusiastic-oblation (2019-03-11)
<add>
<add>
<add>## Bug Fixes
<add>- **required:** correctly validate required on non-input element surrounded by ngIf
<add> ([a4c7bd](https://github.com/angular/angular.js/commit/a4c7bdccd76c39c30e33f6215da9a00cc8acde2c),
<add> [#16830](https://github.com/angular/angular.js/issues/16830),
<add> [#16836](https://github.com/angular/angular.js/issues/16836))
<add>
<add>
<ide> <a name="1.7.7"></a>
<ide> # 1.7.7 kingly-exiting (2019-02-04)
<ide> | 1 |
Javascript | Javascript | fix typo in `eslint-plugin-next` code comments | 3405fb9453a2cee05086f76dcaf4b912749ce539 | <ide><path>packages/eslint-plugin-next/lib/utils/url.js
<ide> function parseUrlForPages(urlprefix, directory) {
<ide> }
<ide>
<ide> /**
<del> * Takes a url and does the following things.
<del> * - replace `index.html` with `/`
<del> * - Makes sure all URLs are have a trainiling `/`
<add> * Takes a URL and does the following things.
<add> * - Replaces `index.html` with `/`
<add> * - Makes sure all URLs are have a trailing `/`
<ide> * - Removes query string
<ide> * @param {string} url
<ide> */
<ide> function normalizeURL(url) {
<ide> url = url.split('?')[0]
<ide> url = url.split('#')[0]
<ide> url = url = url.replace(/(\/index\.html)$/, '/')
<del> // empty URLs should not be trailed with `/`, e.g. `#heading`
<add> // Empty URLs should not be trailed with `/`, e.g. `#heading`
<ide> if (url === '') {
<ide> return url
<ide> } | 1 |
Mixed | Ruby | use type column first in multi-column indexes | 9cdd0a1fdf8308985231242d378e3a1c29c4ab00 | <ide><path>activerecord/CHANGELOG.md
<add>* Use type column first in multi-column indexes created with `add-reference`
<add>
<add> *Derek Prior*
<add>
<ide> * `AR::UnknownAttributeError` now includes the class name of a record.
<ide>
<ide> User.new(name: "Yuki Nishijima", project_attributes: {name: "kaminari"})
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
<ide> def references(*args)
<ide> args.each do |col|
<ide> column("#{col}_id", type, options)
<ide> column("#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
<del> index(polymorphic ? %w(id type).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
<add> index(polymorphic ? %w(type id).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
<ide> end
<ide> end
<ide> alias :belongs_to :references
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def add_reference(table_name, ref_name, options = {})
<ide> type = options.delete(:type) || :integer
<ide> add_column(table_name, "#{ref_name}_id", type, options)
<ide> add_column(table_name, "#{ref_name}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
<del> add_index(table_name, polymorphic ? %w[id type].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
<add> add_index(table_name, polymorphic ? %w[type id].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
<ide> end
<ide> alias :add_belongs_to :add_reference
<ide>
<ide><path>activerecord/test/cases/migration/references_index_test.rb
<ide> def test_creates_polymorphic_index
<ide> t.references :foo, :polymorphic => true, :index => true
<ide> end
<ide>
<del> assert connection.index_exists?(table_name, [:foo_id, :foo_type], :name => :index_testings_on_foo_id_and_foo_type)
<add> assert connection.index_exists?(table_name, [:foo_type, :foo_id], name: :index_testings_on_foo_type_and_foo_id)
<ide> end
<ide> end
<ide>
<ide> def test_creates_polymorphic_index_for_existing_table
<ide> t.references :foo, :polymorphic => true, :index => true
<ide> end
<ide>
<del> assert connection.index_exists?(table_name, [:foo_id, :foo_type], :name => :index_testings_on_foo_id_and_foo_type)
<add> assert connection.index_exists?(table_name, [:foo_type, :foo_id], name: :index_testings_on_foo_type_and_foo_id)
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/migration/references_statements_test.rb
<ide> def test_does_not_create_reference_id_index
<ide>
<ide> def test_creates_polymorphic_index
<ide> add_reference table_name, :taggable, polymorphic: true, index: true
<del> assert index_exists?(table_name, [:taggable_id, :taggable_type])
<add> assert index_exists?(table_name, [:taggable_type, :taggable_id])
<ide> end
<ide>
<ide> def test_creates_reference_type_column_with_default | 5 |
Ruby | Ruby | add test for `config.active_storage.routes_prefix` | 70b5a7594e91d7e3f3ee60642102b7a2323c2e0c | <ide><path>railties/test/application/configuration_test.rb
<ide> class ::DummySerializer < ActiveJob::Serializers::ObjectSerializer; end
<ide> assert_equal [ "password", "credit_card_number" ].to_set, ActiveRecord::Base.filter_attributes
<ide> end
<ide>
<add> test "ActiveStorage.routes_prefix can be configured via config.active_storage.routes_prefix" do
<add> app_file "config/environments/development.rb", <<-RUBY
<add> Rails.application.configure do
<add> config.active_storage.routes_prefix = '/files'
<add> end
<add> RUBY
<add>
<add> output = rails("routes", "-g", "active_storage")
<add> assert_equal <<~MESSAGE, output
<add> Prefix Verb URI Pattern Controller#Action
<add> rails_service_blob GET /files/blobs/:signed_id/*filename(.:format) active_storage/blobs#show
<add> rails_blob_representation GET /files/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
<add> rails_disk_service GET /files/disk/:encoded_key/*filename(.:format) active_storage/disk#show
<add> update_rails_disk_service PUT /files/disk/:encoded_token(.:format) active_storage/disk#update
<add> rails_direct_uploads POST /files/direct_uploads(.:format) active_storage/direct_uploads#create
<add> MESSAGE
<add> end
<add>
<ide> private
<ide> def force_lazy_load_hooks
<ide> yield # Tasty clarifying sugar, homie! We only need to reference a constant to load it. | 1 |
Text | Text | restore missing emojis and fix broken links | 73277d8ba87e57dec187fafa05d12cfb482b9ffb | <ide><path>guide/english/c/file-handling/index.md
<ide> title: File Handling
<ide> ## File Handling
<ide>
<ide> ### Introduction
<del>If you've written the C `helloworld` program before, you've already done file INPUT/OUTPUT(Genrally reffered as IO) in C! Congratulations! :tada:
<add>If you've written the C `helloworld` program before, you've already done file INPUT/OUTPUT(Genrally reffered as IO) in C! Congratulations!
<ide>
<ide> ```c
<ide> /* A simple hello world in C. */
<ide> C provides a number of build-in function to perform basic file operation
<ide> ### Opening a file
<ide>
<ide> The **fopen()** creates a file or opens an existing file
<del>
<add>
<ide> ```c
<ide> fp = fopen(const char filename,const char mode);
<ide> ```
<del>
<del> In C there are many mode for opening a file
<del>
<add>
<add> In C there are many mode for opening a file
<add>
<ide> **r** **-** **open a file in reading mode**
<ide> ..//Provide access only to read a file but not to write it.
<del>
<add>
<ide> **w** **-** **opens or create a text file in writing mode**
<ide> ..//Provides access only to write on file not to read it.
<del>
<add>
<ide> **a** **-** **opens a file in append mode**
<ide> ..//Provides acces to append more words in file.
<del>
<add>
<ide> **r+** **-** **opens a file in both reading and writing mode**
<del>
<add>
<ide> **a+** **-** **opens a file in both reading and writing mode**
<del>
<add>
<ide> **w+** **-** **opens a file in both reading and writing mode**
<del>
<add>
<ide> **b** **-** **opens a file in binary mode**
<del>
<add>
<ide> Here's an example of reading and writing data to a file
<del>
<add>
<ide> ```c
<ide> #include<stdio.h>
<ide> #include<conio.h>
<ide> main()
<ide> }
<ide> fclose(fp);
<ide> fp = fopen("hello.txt", "r");
<del>
<add>
<ide> while( (ch = getc(fp)! = EOF)
<ide> printf("%c",ch);
<del>
<add>
<ide> fclose(fp);
<ide> }
<ide> ```
<ide> Hello, Logan!
<ide> Hello, Carol!
<ide> ```
<ide>
<del>Super awesome, right! :smile:
<add>Super awesome, right!
<ide>
<ide> ### More Information:
<ide> - <a href='https://en.wikibooks.org/wiki/C_Programming/File_IO' target='_blank' rel='nofollow'>Wikibooks page on file IO</a>
<ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops/index.md
<ide> title: Nesting For Loops
<ide> ---
<ide> ## Nesting For Loops
<ide>
<del><strong>Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:</strong>
<add><strong>Remember to use Read-Search-Ask if you get stuck. Try to pair program and write your own code/</strong>
<ide>
<del>:checkered_flag: <strong>Problem Explanation:</strong>
<add><strong>Problem Explanation:</strong>
<ide>
<del>If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays.
<add>If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays.
<ide>
<ide> Here is an example:
<ide>
<ide> This outputs each sub-element in <code>arr</code> one at a time. Note that for t
<ide> <li><a href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop">Iterate Through An Array With A For Loop</a></li>
<ide> <li><a href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays">Accessing Nested Arrays</a></li>
<ide> </ul>
<del>
<del>:speech_balloon: Hint: 1
<add>
<add>### Hint: 1
<ide>
<ide> Make sure to check with <code>length</code> and not the overall array.
<ide>
<ide> <em>try to solve the problem now</em>
<ide>
<del>:speech_balloon: Hint 2<br>
<add>### Hint 2
<ide>
<ide> Use both <code>i</code> and <code>j</code> when multiplying the product.
<ide>
<ide> <em>try to solve the problem now</em>
<ide>
<del>:speech_balloon: Hint 3<br>
<add>### Hint 3
<ide>
<ide> Remember to use <code>arr[i]</code> when you multiply the sub-arrays with the <code>product</code> variable.
<ide>
<ide> Remember to use <code>arr[i]</code> when you multiply the sub-arrays with the <c
<ide> <br>
<ide> <strong>Solution Ahead!</strong>
<ide>
<del>:beginner: <strong>Basic Code Solution:</strong>
<add><strong>Basic Code Solution:</strong>
<ide> ```
<ide> function multiplyAll(arr) {
<ide> var product = 1;
<ide> function multiplyAll(arr) {
<ide> multiplyAll([[1,2],[3,4],[5,6,7]]);
<ide>
<ide> ```
<del>:rocket: <strong><a href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops/">Run Code</a></strong>
<add><strong><a href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops/">Run Code</a></strong>
<ide>
<ide> <strong>Code Explanation:</strong>
<ide>
<ide> multiplyAll([[1,2],[3,4],[5,6,7]]);
<ide> <li>The two sub-arrays to multiply are <code>arr[i]</code> and <code>j</code>.</li>
<ide> </ul>
<ide>
<del>:clipboard: <strong>NOTES FOR CONTRIBUTIONS:</strong>
<del><ul>
<del><li>:warning: <strong>DO NOT</strong> add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.</li>
<del> <li>Add an explanation of your solution.</li>
<del><li>Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light:</li>
<del> </ul>
<ide>\ No newline at end of file
<add>## <strong>NOTES FOR CONTRIBUTIONS:</strong>
<add>
<add>* <strong>DO NOT</strong> add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
<add>* Add an explanation of your solution.
<add>* Categorize the solution in one of the following categories — Basic, Intermediate and Advanced.
<ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing/index.md
<ide> Make `i` start at 0. Also the loop **should not** be executed for i == 5. In oth
<ide> ```javascript
<ide> for (let i = 0; i < len; i++) {
<ide> ```
<del>**Happy Coding!** :computer:
<add>**Happy Coding!**
<ide> ### Resources
<ide> - [For statements challenge at FreeCodeCamp](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops)
<ide> - [For statements at MDN web docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement)
<ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions/index.md
<ide> title: Set Default Parameters for Your Functions
<ide> ## Set Default Parameters for Your Functions
<ide>
<ide>
<del>:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:
<add>Remember to use Read-Search-Ask if you get stuck. Try to pair program and write your own code.
<ide>
<ide>
<del>### :checkered_flag: Problem Explanation:
<add>### Problem Explanation:
<ide> ```javascript
<ide> const increment = (function() {
<ide> "use strict";
<ide> console.log(increment(5)); // returns NaN
<ide>
<ide> We'll be modifying the increment function so that the **number** parameter is incremented by 1 by default, by setting **value** to 1 if a value for **value** is not passed to the increment function.
<ide>
<del>### :speech_balloon: Hint: 1
<add>### Hint: 1
<ide>
<ide> Let's identify where the parameter **value** is in JS function
<ide>
<ide> try to solve the problem now
<ide>
<del>### :speech_balloon: Hint: 2
<add>### Hint: 2
<ide>
<ide> Set **value** equal to something so that it is that value by default
<ide>
<ide> try to solve the problem now
<ide>
<ide> ### Spoiler Alert!
<del>
<ide>
<ide> Solution ahead!
<ide>
<del>## :beginner: Basic Code Solution:
<add>## Basic Code Solution:
<ide> ```javascript
<ide> const increment = (function() {
<ide> "use strict";
<ide> const increment = (function() {
<ide> console.log(increment(5, 2)); // returns 7
<ide> console.log(increment(5)); // returns NaN
<ide> ```
<del>:rocket: [Run Code](https://repl.it/@RyanPisuena/PleasingFumblingThings)
<add>[Run Code](https://repl.it/@RyanPisuena/PleasingFumblingThings)
<ide>
<del>## Code Explanation
<add>### Code Explanation
<ide>
<del>* This section is pretty straightforward. Pass this section by setting the **value** parameter equal to 1. When the function comes across test cases where **value** has not been passed anything, then **value** will be assigned one by default.
<add>* This section is pretty straightforward. Pass this section by setting the **value** parameter equal to 1. When the function comes across test cases where **value** has not been passed anything, then **value** will be assigned one by default.
<ide>
<del>Relevant Links:
<add>Relevant Links:
<ide>
<ide> [JavaScript default parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)
<ide>
<del># :clipboard: NOTES FOR CONTRIBUTIONS:
<add>## NOTES FOR CONTRIBUTIONS:
<ide>
<del>* :warning: DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
<add>* DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
<ide> * Add an explanation of your solution.
<del>* Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light:
<add>* Categorize the solution in one of the following categories — Basic, Intermediate and Advanced.
<ide><path>guide/english/html/html-entities/index.md
<ide> title: HTML Entities
<ide> HTML entities are characters that are used to replace reserved characters in HTML or for characters that do not appear on your keyboard. Some characters are reserved in HTML. If you use the less than(<) or greater than(>) signs in your text, the browser might mix them up with tags.
<ide>
<ide> ### What are they used for?
<del>
<add>
<ide> As mentioned about HTML entities are used in order to replace reserved characters that are reserved by HTML.
<ide>
<ide> ### How do you use them?
<ide> Or
<ide> <!-- example for a less-than sign (<) -->
<ide> <
<ide> ```
<del>
<add>
<ide> ## Reference Guide
<ide>
<del>This is by no means an exhaustive list but the links below will be able to give you more entities if the ones below do not work for your needs. Happy Coding :bowtie:
<add>This is by no means an exhaustive list but the links below will be able to give you more entities if the ones below do not work for your needs. Happy Coding.
<ide>
<ide>
<ide> | Character | Entity Name | Entity Number | Description |
<ide> This is by no means an exhaustive list but the links below will be able to give
<ide> | # | `#` | `#` | Number sign |
<ide> | $ | `$`| `$` | Dollar sign |
<ide> | ¢ | `¢` | `¢` | Cent sign |
<del>| € | `€` | `€` | Euro sign |
<add>| € | `€` | `€` | Euro sign |
<ide> | £ | `£` | `£` | GBP sign |
<ide> | ¥ | `¥` | `¥` | Yen sign |
<ide> | % | `%`| `%` | Percent sign |
<ide><path>guide/english/python/setting-up-python-web-framework-django-and-flask/index.md
<ide> Before we install Django we will get you to install an extremely useful tool to
<ide>
<ide> So, let's create a virtual environment (also called a virtualenv). Virtualenv will isolate your Python/Django setup on a per-project basis. This means that any changes you make to one website won't affect any others you're also developing. Neat, right?
<ide>
<del>For more information on virtual environments see the relevent section <a href='https://guide.freecodecamp.org/python/virtual-environments/' target='_blank' rel='nofollow'>here<a>.
<add>For more information on virtual environments see the relevent section <a href='https://guide.freecodecamp.org/python/virtual-environments/' target='_blank' rel='nofollow'>here</a>.
<ide>
<ide> ## Wrapping Up
<ide>
<ide> $ django-admin startproject myproject
<ide> $ cd myproject
<ide> $ python manage.py runserver
<ide> ```
<del>Go to `http://localhost:8000`! :rocket:
<add>Go to `http://localhost:8000`!
<ide>
<ide> We have successfully installed the web-framework of our need. However, it's not yet complete. Most web applications are content and data driven - so we need a data storage. Or, a Database, if you will.
<ide>
<ide> In next article, we would be discussing how to install PostgreSQL and use it with our Python web application.
<ide>
<ide> A point to ponder - we have been using `pip` heavily, but we have barely said anything about it. Well, for now, it's just a package manager like `npm`. It has some differences with `npm`; but, you don't need to worry about that now. If you are interested, do check out the <a href='http://pip-python3.readthedocs.org/en/latest/index.html' target='_blank' rel='nofollow'>official `pip` documentation</a>.
<ide>
<del>_If you have suggestions or questions, come join us on <a href='https://gitter.im/FreeCodeCamp/FreeCodeCamp' target='_blank' rel='nofollow'>gitter</a>_.
<add><em>If you have suggestions or questions, come join us on <a href='https://gitter.im/FreeCodeCamp/home' target='_blank' rel='nofollow'>gitter</a></em>. | 6 |
Javascript | Javascript | remove reactcomponenttreehook from internals | 607148673b3156d051d1fed17cd49e83698dce54 | <ide><path>packages/react/src/ReactSharedInternals.js
<ide> const ReactSharedInternals = {
<ide> };
<ide>
<ide> if (__DEV__) {
<del> Object.assign(ReactSharedInternals, {
<del> // These should not be included in production.
<del> ReactDebugCurrentFrame,
<del> // Shim for React DOM 16.0.0 which still destructured (but not used) this.
<del> // TODO: remove in React 17.0.
<del> ReactComponentTreeHook: {},
<del> });
<add> ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
<ide> }
<ide>
<ide> export default ReactSharedInternals;
<ide><path>packages/react/src/forks/ReactSharedInternals.umd.js
<ide> const ReactSharedInternals = {
<ide> ReactCurrentBatchConfig,
<ide> // Used by renderers to avoid bundling object-assign twice in UMD bundles:
<ide> assign,
<add>
<add> // Re-export the schedule API(s) for UMD bundles.
<add> // This avoids introducing a dependency on a new UMD global in a minor update,
<add> // Since that would be a breaking change (e.g. for all existing CodeSandboxes).
<add> // This re-export is only required for UMD bundles;
<add> // CJS bundles use the shared NPM package.
<add> Scheduler,
<add> SchedulerTracing,
<ide> };
<ide>
<ide> if (__DEV__) {
<del> Object.assign(ReactSharedInternals, {
<del> // These should not be included in production.
<del> ReactDebugCurrentFrame,
<del> // Shim for React DOM 16.0.0 which still destructured (but not used) this.
<del> // TODO: remove in React 17.0.
<del> ReactComponentTreeHook: {},
<del> });
<add> ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
<ide> }
<ide>
<del>// Re-export the schedule API(s) for UMD bundles.
<del>// This avoids introducing a dependency on a new UMD global in a minor update,
<del>// Since that would be a breaking change (e.g. for all existing CodeSandboxes).
<del>// This re-export is only required for UMD bundles;
<del>// CJS bundles use the shared NPM package.
<del>Object.assign(ReactSharedInternals, {
<del> Scheduler,
<del> SchedulerTracing,
<del>});
<del>
<ide> export default ReactSharedInternals; | 2 |
Java | Java | remove warnings in some rn android classes | a679f592cd1803e8f3b847c858bb7117a1e1b1f2 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java
<ide> import com.facebook.react.uimanager.util.ReactFindViewUtil;
<ide> import java.util.ArrayList;
<ide> import java.util.HashMap;
<add>import java.util.List;
<ide> import java.util.Map;
<ide> import javax.annotation.Nonnull;
<ide> import javax.annotation.Nullable;
<ide> new MatrixMathHelper.MatrixDecompositionContext();
<ide> private static double[] sTransformDecompositionArray = new double[16];
<ide>
<del> public static final HashMap<String, Integer> sStateDescription = new HashMap<String, Integer>();
<add> public static final Map<String, Integer> sStateDescription = new HashMap<>();
<ide>
<ide> static {
<ide> sStateDescription.put("busy", R.string.state_busy_description);
<ide> public void setZIndex(@Nonnull T view, float zIndex) {
<ide> int integerZIndex = Math.round(zIndex);
<ide> ViewGroupManager.setViewZIndex(view, integerZIndex);
<ide> ViewParent parent = view.getParent();
<del> if (parent != null && parent instanceof ReactZIndexedViewGroup) {
<add> if (parent instanceof ReactZIndexedViewGroup) {
<ide> ((ReactZIndexedViewGroup) parent).updateDrawingOrder();
<ide> }
<ide> }
<ide> public void setViewStates(@Nonnull T view, @Nullable ReadableArray accessibility
<ide> if (sStateDescription.containsKey(state)) {
<ide> shouldUpdateContentDescription = true;
<ide> }
<del> if (state.equals("selected")) {
<add> if ("selected".equals(state)) {
<ide> view.setSelected(true);
<del> } else if (state.equals("disabled")) {
<add> } else if ("disabled".equals(state)) {
<ide> view.setEnabled(false);
<ide> }
<ide> }
<ide> private void updateViewContentDescription(@Nonnull T view) {
<ide> (ReadableArray) view.getTag(R.id.accessibility_states);
<ide> final ReadableMap accessibilityState = (ReadableMap) view.getTag(R.id.accessibility_state);
<ide> final String accessibilityHint = (String) view.getTag(R.id.accessibility_hint);
<del> final ArrayList<String> contentDescription = new ArrayList<String>();
<add> final List<String> contentDescription = new ArrayList<>();
<ide> if (accessibilityLabel != null) {
<ide> contentDescription.add(accessibilityLabel);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java
<ide> import com.facebook.systrace.Systrace;
<ide> import com.facebook.systrace.SystraceMessage;
<ide> import java.util.Arrays;
<del>import java.util.HashMap;
<del>import java.util.Map;
<ide> import javax.annotation.Nullable;
<ide> import javax.annotation.concurrent.NotThreadSafe;
<ide>
<ide> public class NativeViewHierarchyManager {
<ide> private final JSResponderHandler mJSResponderHandler = new JSResponderHandler();
<ide> private final RootViewManager mRootViewManager;
<ide> private final LayoutAnimationController mLayoutAnimator = new LayoutAnimationController();
<del> private final Map<Integer, SparseIntArray> mTagsToPendingIndicesToDelete = new HashMap<>();
<add> private final SparseArray<SparseIntArray> mTagsToPendingIndicesToDelete = new SparseArray<>();
<ide> private final int[] mDroppedViewArray = new int[100];
<ide>
<ide> private boolean mLayoutAnimationEnabled;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManager.java
<ide> public void receiveCommand(@Nonnull T root, int commandId, @Nullable ReadableArr
<ide> /**
<ide> * Subclasses may use this method to receive events/commands directly from JS through the {@link
<ide> * UIManager}. Good example of such a command would be {@code scrollTo} request with coordinates
<del> * for a {@link ScrollView} instance.
<add> * for a {@link ReactScrollView} instance.
<ide> *
<ide> * @param root View instance that should receive the command
<ide> * @param commandId code of the command
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.java
<ide> import android.graphics.Rect;
<ide> import android.os.Build;
<ide> import android.view.View;
<add>import androidx.annotation.NonNull;
<add>import androidx.annotation.Nullable;
<ide> import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
<ide> import com.facebook.react.bridge.ReactContext;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.yoga.YogaConstants;
<ide> import java.util.Locale;
<ide> import java.util.Map;
<del>import javax.annotation.Nullable;
<ide>
<ide> /** View manager for AndroidViews (plain React Views). */
<ide> @ReactModule(name = ReactViewManager.REACT_CLASS)
<ide> public class ReactViewManager extends ViewGroupManager<ReactViewGroup> {
<ide> };
<ide> private static final int CMD_HOTSPOT_UPDATE = 1;
<ide> private static final int CMD_SET_PRESSED = 2;
<add> private static final String HOTSPOT_UPDATE_KEY = "hotspotUpdate";
<ide>
<ide> @ReactProp(name = "accessible")
<ide> public void setAccessible(ReactViewGroup view, boolean accessible) {
<ide> public void setBackfaceVisibility(ReactViewGroup view, String backfaceVisibility
<ide> }
<ide>
<ide> @Override
<del> public void setOpacity(ReactViewGroup view, float opacity) {
<add> public void setOpacity(@NonNull ReactViewGroup view, float opacity) {
<ide> view.setOpacityIfPossible(opacity);
<ide> }
<ide>
<ide> @Override
<del> public void setTransform(ReactViewGroup view, ReadableArray matrix) {
<add> public void setTransform(@NonNull ReactViewGroup view, @Nullable ReadableArray matrix) {
<ide> super.setTransform(view, matrix);
<ide> view.setBackfaceVisibilityDependantOpacity();
<ide> }
<ide> public ReactViewGroup createViewInstance(ThemedReactContext context) {
<ide>
<ide> @Override
<ide> public Map<String, Integer> getCommandsMap() {
<del> return MapBuilder.of("hotspotUpdate", CMD_HOTSPOT_UPDATE, "setPressed", CMD_SET_PRESSED);
<add> return MapBuilder.of(HOTSPOT_UPDATE_KEY, CMD_HOTSPOT_UPDATE, "setPressed", CMD_SET_PRESSED);
<ide> }
<ide>
<ide> @Override
<ide> public void receiveCommand(ReactViewGroup root, int commandId, @Nullable Readabl
<ide> @Override
<ide> public void receiveCommand(ReactViewGroup root, String commandId, @Nullable ReadableArray args) {
<ide> switch (commandId) {
<del> case "hotspotUpdate":
<add> case HOTSPOT_UPDATE_KEY:
<ide> {
<ide> handleHotspotUpdate(root, args);
<ide> break; | 4 |
Java | Java | remove path variables from pathwithinmapping | ec03e8830ed0edb3cffbda1395c491127c0353b6 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractUrlHandlerMapping.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import org.springframework.beans.BeansException;
<ide> import org.springframework.context.ApplicationContext;
<del>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.http.server.RequestPath;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.AntPathMatcher;
<ide> protected Object lookupHandler(
<ide> handler = obtainApplicationContext().getBean(handlerName);
<ide> }
<ide> validateHandler(handler, request);
<del> PathContainer pathWithinMapping = pattern.extractPathWithinPattern(path.pathWithinApplication());
<del> return buildPathExposingHandler(handler, pattern.getPatternString(), pathWithinMapping.value(), null);
<add> String pathWithinMapping = pattern.extractPathWithinPattern(path.pathWithinApplication()).value();
<add> pathWithinMapping = UrlPathHelper.defaultInstance.removeSemicolonContent(pathWithinMapping);
<add> return buildPathExposingHandler(handler, pattern.getPatternString(), pathWithinMapping, null);
<ide> }
<ide>
<ide> /**
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMappingTests.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> void checkMappings(String beanName) throws Exception {
<ide> assertThat(request.getAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("/welcome.html");
<ide> assertThat(request.getAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE)).isEqualTo(bean);
<ide>
<del> request = PathPatternsTestUtils.initRequest("GET", "/welcome.x", usePathPatterns);
<add> request = PathPatternsTestUtils.initRequest("GET", "/welcome.x;jsessionid=123", usePathPatterns);
<ide> chain = getHandler(hm, request);
<ide> assertThat(chain.getHandler()).isSameAs(otherBean);
<ide> assertThat(request.getAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("welcome.x"); | 2 |
Text | Text | adjust args of bundler.require in guides [ci skip] | 50a286db529aa1d3fd050101950678854be87b61 | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> file (in `config/application.rb`):
<ide> ```ruby
<ide> # Require the gems listed in Gemfile, including any gems
<ide> # you've limited to :test, :development, or :production.
<del>Bundler.require(:default, Rails.env)
<add>Bundler.require(*Rails.groups)
<ide> ```
<ide>
<ide> ### vendor/plugins | 1 |
Ruby | Ruby | add tests for runner#test_files method | 3cc783b6bf20da27079038e7c52ce214f1042df3 | <ide><path>railties/lib/rails/test_unit/runner.rb
<ide> def show_backtrace?
<ide> @options[:backtrace]
<ide> end
<ide>
<del> private
<del> def run_tests
<del> test_files.to_a.each do |file|
<del> require File.expand_path file
<del> end
<del> end
<del>
<ide> def test_files
<ide> return [@options[:filename]] if @options[:filename]
<ide> if @options[:patterns]
<ide> def test_files
<ide> Rake::FileList[pattern]
<ide> end
<ide>
<add> private
<add> def run_tests
<add> test_files.to_a.each do |file|
<add> require File.expand_path file
<add> end
<add> end
<add>
<ide> def test_methods
<ide> methods_map = []
<ide> suites = Minitest::Runnable.runnables.shuffle
<ide><path>railties/test/test_unit/runner_test.rb
<ide> class TestUnitTestRunnerTest < ActiveSupport::TestCase
<ide> assert_equal ["#{__dir__}/**/*_test.rb", "#{application_dir}/**/*_test.rb"], options[:patterns]
<ide> assert_nil options[:filename]
<ide> assert_nil options[:line]
<add>
<add> runner = Rails::TestRunner.new(options)
<add> assert runner.test_files.size > 0
<ide> end
<ide>
<ide> test "run multiple files and run one file by line" do
<ide> class TestUnitTestRunnerTest < ActiveSupport::TestCase
<ide> assert_equal ["#{__dir__}/**/*_test.rb"], options[:patterns]
<ide> assert_equal __FILE__, options[:filename]
<ide> assert_equal line, options[:line]
<add>
<add> runner = Rails::TestRunner.new(options)
<add> assert_equal [__FILE__], runner.test_files, 'Only returns the file that running by line'
<add> end
<add>
<add> test "running multiple files passing line number" do
<add> line = __LINE__
<add> options = @options.parse(["foobar.rb:8", "#{__FILE__}:#{line}"])
<add>
<add> assert_equal __FILE__, options[:filename], 'Returns the last file'
<add> assert_equal line, options[:line]
<ide> end
<ide> end | 2 |
Javascript | Javascript | remove uglify options in preparation of webpack 4 | 18676e08703a8d6c39049fe15996f3ede23323ae | <ide><path>server/build/webpack.js
<ide> export default async function getBaseWebpackConfig (dir, {dev = false, isServer
<ide> ...nodePathList // Support for NODE_PATH environment variable
<ide> ],
<ide> alias: {
<del> next: nextDir,
<del> // React already does something similar to this.
<del> // But if the user has react-devtools, it'll throw an error showing that
<del> // we haven't done dead code elimination (via uglifyjs).
<del> // We purposly do not uglify React code to save the build time.
<del> // (But it didn't increase the overall build size)
<del> // Here we are doing an exact match with '$'
<del> // So, you can still require nested modules like `react-dom/server`
<del> react$: dev ? 'react/cjs/react.development.js' : 'react/cjs/react.production.min.js',
<del> 'react-dom$': dev ? 'react-dom/cjs/react-dom.development.js' : 'react-dom/cjs/react-dom.production.min.js'
<add> next: nextDir
<ide> }
<ide> },
<ide> resolveLoader: {
<ide> export default async function getBaseWebpackConfig (dir, {dev = false, isServer
<ide> useHashIndex: false
<ide> }),
<ide> !isServer && !dev && new UglifyJSPlugin({
<del> exclude: /react\.js/,
<ide> parallel: true,
<ide> sourceMap: false,
<ide> uglifyOptions: {
<del> compress: {
<del> arrows: false,
<del> booleans: false,
<del> collapse_vars: false,
<del> comparisons: false,
<del> computed_props: false,
<del> hoist_funs: false,
<del> hoist_props: false,
<del> hoist_vars: false,
<del> if_return: false,
<del> inline: false,
<del> join_vars: false,
<del> keep_infinity: true,
<del> loops: false,
<del> negate_iife: false,
<del> properties: false,
<del> reduce_funcs: false,
<del> reduce_vars: false,
<del> sequences: false,
<del> side_effects: false,
<del> switches: false,
<del> top_retain: false,
<del> toplevel: false,
<del> typeofs: false,
<del> unused: false,
<del> conditionals: true,
<del> dead_code: true,
<del> evaluate: true
<del> },
<ide> mangle: {
<ide> safari10: true
<ide> } | 1 |
PHP | PHP | fix small typo | e4c0dee6ee62beab596644d801443f786935d8dc | <ide><path>lib/Cake/Model/Model.php
<ide> public function __construct($id = false, $table = null, $ds = null) {
<ide>
<ide> /**
<ide> * Returns a list of all events that will fire in the model during it's lifecycle.
<del> * You can override this function to add you own listener callbacks
<add> * You can override this function to add your own listener callbacks
<ide> *
<ide> * @return array
<ide> */ | 1 |
PHP | PHP | add support for custom labels | 7c2e902316968b56279fdbc423d69a15641c6c12 | <ide><path>Cake/View/Input/Radio.php
<ide> public function render($data) {
<ide> $radio['disabled'] = true;
<ide> }
<ide>
<del> $labelAttrs = ['for' => $radio['id'], 'escape' => $escape];
<del> $label = $this->_templates->format('label', [
<del> 'text' => $escape ? h($radio['text']) : $radio['text'],
<del> 'attrs' => $this->_templates->formatAttributes($labelAttrs),
<del> ]);
<add> $label = $this->_renderLabel($radio, $data['label'], $escape);
<ide>
<ide> $input = $this->_templates->format('radio', [
<ide> 'name' => $radio['name'],
<ide> protected function _isDisabled($radio, $disabled) {
<ide> return (!is_array($disabled) || in_array((string)$radio['value'], $disabled, !$isNumeric));
<ide> }
<ide>
<add> protected function _renderLabel($radio, $label, $escape) {
<add> if (!$label) {
<add> return false;
<add> }
<add> $labelAttrs = is_array($label) ? $label : [];
<add> $labelAttrs += ['for' => $radio['id'], 'escape' => $escape];
<add>
<add> return $this->_templates->format('label', [
<add> 'text' => $escape ? h($radio['text']) : $radio['text'],
<add> 'attrs' => $this->_templates->formatAttributes($labelAttrs),
<add> ]);
<add> }
<add>
<ide> }
<ide><path>Test/TestCase/View/Input/RadioTest.php
<ide> public function testRenderDisabled() {
<ide> * @return void
<ide> */
<ide> public function testRenderLabelOptions() {
<del> $this->markTestIncomplete();
<add> $radio = new Radio($this->templates);
<add> $data = [
<add> 'name' => 'Versions[ver]',
<add> 'options' => [
<add> 1 => 'one',
<add> '1x' => 'one x',
<add> '2' => 'two',
<add> ],
<add> 'label' => false,
<add> ];
<add> $result = $radio->render($data);
<add> $expected = [
<add> ['input' => [
<add> 'id' => 'Versions_ver_1',
<add> 'name' => 'Versions[ver]',
<add> 'type' => 'radio',
<add> 'value' => '1',
<add> ]],
<add> ['input' => [
<add> 'id' => 'Versions_ver_1x',
<add> 'name' => 'Versions[ver]',
<add> 'type' => 'radio',
<add> 'value' => '1x',
<add> ]],
<add> ];
<add> $this->assertTags($result, $expected);
<add>
<add> $data = [
<add> 'name' => 'Versions[ver]',
<add> 'options' => [
<add> 1 => 'one',
<add> '1x' => 'one x',
<add> '2' => 'two',
<add> ],
<add> 'label' => [
<add> 'class' => 'my-class',
<add> ]
<add> ];
<add> $result = $radio->render($data);
<add> $expected = [
<add> ['input' => [
<add> 'id' => 'Versions_ver_1',
<add> 'name' => 'Versions[ver]',
<add> 'type' => 'radio',
<add> 'value' => '1',
<add> ]],
<add> ['label' => ['class' => 'my-class', 'for' => 'Versions_ver_1']],
<add> 'one',
<add> '/label',
<add> ['input' => [
<add> 'id' => 'Versions_ver_1x',
<add> 'name' => 'Versions[ver]',
<add> 'type' => 'radio',
<add> 'value' => '1x',
<add> ]],
<add> ['label' => ['class' => 'my-class', 'for' => 'Versions_ver_1x']],
<add> 'one x',
<add> '/label',
<add> ];
<add> $this->assertTags($result, $expected);
<ide> }
<ide>
<ide> /** | 2 |
PHP | PHP | fix "slow redirect" | 09ec31fa509dedbca7627d32e45ef0a966f07ea2 | <ide><path>src/Illuminate/Routing/Router.php
<ide> use Illuminate\Container\Container;
<ide> use Symfony\Component\HttpKernel\HttpKernelInterface;
<ide> use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
<add>use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
<ide> use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
<ide>
<ide> class Router implements HttpKernelInterface, RouteFiltererInterface {
<ide> public function callRouteFilter($filter, $parameters, $route, $request, $respons
<ide> */
<ide> protected function prepareResponse($response)
<ide> {
<del> if ( ! $response instanceof Response)
<add> if ( ! $response instanceof SymfonyResponse)
<ide> {
<ide> $response = new Response($response);
<ide> } | 1 |
Java | Java | fix cache decoration | 119dfd9cf9215b2800d2d178913917103761fefd | <ide><path>spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheCacheManager.java
<ide> *
<ide> * @author Costin Leau
<ide> * @author Juergen Hoeller
<add> * @author Stephane Nicoll
<ide> * @since 3.1
<ide> */
<ide> public class EhCacheCacheManager extends AbstractTransactionSupportingCacheManager {
<ide> protected Collection<Cache> loadCaches() {
<ide> }
<ide>
<ide> @Override
<del> public Cache getCache(String name) {
<del> Cache cache = super.getCache(name);
<del> if (cache == null) {
<del> // Check the EhCache cache again (in case the cache was added at runtime)
<del> Ehcache ehcache = getCacheManager().getEhcache(name);
<del> if (ehcache != null) {
<del> addCache(new EhCacheCache(ehcache));
<del> cache = super.getCache(name); // potentially decorated
<del> }
<add> protected Cache getMissingCache(String name) {
<add> // check the EhCache cache again
<add> // (in case the cache was added at runtime)
<add> Ehcache ehcache = getCacheManager().getEhcache(name);
<add> if (ehcache != null) {
<add> return new EhCacheCache(ehcache);
<ide> }
<del> return cache;
<add> return null;
<ide> }
<ide>
<ide> }
<ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/JCacheCacheManager.java
<ide> * <p>Note: This class has been updated for JCache 1.0, as of Spring 4.0.
<ide> *
<ide> * @author Juergen Hoeller
<add> * @author Stephane Nicoll
<ide> * @since 3.2
<ide> */
<ide> public class JCacheCacheManager extends AbstractTransactionSupportingCacheManager {
<ide> protected Collection<Cache> loadCaches() {
<ide> }
<ide>
<ide> @Override
<del> public Cache getCache(String name) {
<del> Cache cache = super.getCache(name);
<del> if (cache == null) {
<del> // Check the JCache cache again (in case the cache was added at runtime)
<del> javax.cache.Cache<Object, Object> jcache = getCacheManager().getCache(name);
<del> if (jcache != null) {
<del> addCache(new JCacheCache(jcache, isAllowNullValues()));
<del> cache = super.getCache(name); // potentially decorated
<del> }
<add> protected Cache getMissingCache(String name) {
<add> // Check the JCache cache again (in case the cache was added at runtime)
<add> javax.cache.Cache<Object, Object> jcache = getCacheManager().getCache(name);
<add> if (jcache != null) {
<add> return new JCacheCache(jcache, isAllowNullValues());
<ide> }
<del> return cache;
<add> return null;
<ide> }
<ide>
<ide> }
<ide><path>spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheCacheManagerTests.java
<add>/*
<add> * Copyright 2002-2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.cache.ehcache;
<add>
<add>import net.sf.ehcache.CacheManager;
<add>import net.sf.ehcache.config.CacheConfiguration;
<add>import net.sf.ehcache.config.Configuration;
<add>import org.junit.After;
<add>import org.junit.Before;
<add>import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManagerTests;
<add>
<add>/**
<add> * @author Stephane Nicoll
<add> */
<add>public class EhCacheCacheManagerTests extends AbstractTransactionSupportingCacheManagerTests<EhCacheCacheManager> {
<add>
<add> private CacheManager nativeCacheManager;
<add> private EhCacheCacheManager cacheManager;
<add> private EhCacheCacheManager transactionalCacheManager;
<add>
<add> @Before
<add> public void setup() {
<add> nativeCacheManager = new CacheManager(new Configuration().name("EhCacheCacheManagerTests")
<add> .defaultCache(new CacheConfiguration("default", 100)));
<add> addNativeCache(CACHE_NAME);
<add>
<add> cacheManager = new EhCacheCacheManager(nativeCacheManager);
<add> cacheManager.setTransactionAware(false);
<add> cacheManager.afterPropertiesSet();
<add>
<add> transactionalCacheManager = new EhCacheCacheManager(nativeCacheManager);
<add> transactionalCacheManager.setTransactionAware(true);
<add> transactionalCacheManager.afterPropertiesSet();
<add> }
<add>
<add> @After
<add> public void tearDown() {
<add> nativeCacheManager.shutdown();
<add> }
<add>
<add>
<add> @Override
<add> protected EhCacheCacheManager getCacheManager(boolean transactionAware) {
<add> if (transactionAware) {
<add> return transactionalCacheManager;
<add> } else {
<add> return cacheManager;
<add> }
<add> }
<add>
<add> @Override
<add> protected Class<? extends org.springframework.cache.Cache> getCacheType() {
<add> return EhCacheCache.class;
<add> }
<add>
<add> @Override
<add> protected void addNativeCache(String cacheName) {
<add> nativeCacheManager.addCache(cacheName);
<add> }
<add>
<add> @Override
<add> protected void removeNativeCache(String cacheName) {
<add> nativeCacheManager.removeCache(cacheName);
<add> }
<add>}
<ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/JCacheCacheManagerTests.java
<add>/*
<add> * Copyright 2002-2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.cache.jcache;
<add>
<add>import static org.mockito.BDDMockito.*;
<add>import static org.mockito.Mockito.mock;
<add>
<add>import javax.cache.Cache;
<add>import javax.cache.CacheManager;
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>import org.junit.Before;
<add>import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManagerTests;
<add>
<add>/**
<add> * @author Stephane Nicoll
<add> */
<add>public class JCacheCacheManagerTests extends AbstractTransactionSupportingCacheManagerTests<JCacheCacheManager> {
<add>
<add> private CacheManagerMock cacheManagerMock;
<add> private JCacheCacheManager cacheManager;
<add> private JCacheCacheManager transactionalCacheManager;
<add>
<add> @Before
<add> public void setupOnce() {
<add> cacheManagerMock = new CacheManagerMock();
<add> cacheManagerMock.addCache(CACHE_NAME);
<add>
<add> cacheManager = new JCacheCacheManager(cacheManagerMock.getCacheManager());
<add> cacheManager.setTransactionAware(false);
<add> cacheManager.afterPropertiesSet();
<add>
<add> transactionalCacheManager = new JCacheCacheManager(cacheManagerMock.getCacheManager());
<add> transactionalCacheManager.setTransactionAware(true);
<add> transactionalCacheManager.afterPropertiesSet();
<add> }
<add>
<add>
<add> @Override
<add> protected JCacheCacheManager getCacheManager(boolean transactionAware) {
<add> if (transactionAware) {
<add> return transactionalCacheManager;
<add> } else {
<add> return cacheManager;
<add> }
<add> }
<add>
<add> @Override
<add> protected Class<? extends org.springframework.cache.Cache> getCacheType() {
<add> return JCacheCache.class;
<add> }
<add>
<add> @Override
<add> protected void addNativeCache(String cacheName) {
<add> cacheManagerMock.addCache(cacheName);
<add> }
<add>
<add> @Override
<add> protected void removeNativeCache(String cacheName) {
<add> cacheManagerMock.removeCache(cacheName);
<add> }
<add>
<add> private static class CacheManagerMock {
<add>
<add> private final List<String> cacheNames;
<add> private final CacheManager cacheManager;
<add>
<add> private CacheManagerMock() {
<add> this.cacheNames = new ArrayList<String>();
<add> this.cacheManager = mock(CacheManager.class);
<add> given(cacheManager.getCacheNames()).willReturn(cacheNames);
<add> }
<add>
<add> private CacheManager getCacheManager() {
<add> return cacheManager;
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> public void addCache(String name) {
<add> cacheNames.add(name);
<add> Cache cache = mock(Cache.class);
<add> given(cache.getName()).willReturn(name);
<add> given(cacheManager.getCache(name)).willReturn(cache);
<add> }
<add>
<add> public void removeCache(String name) {
<add> cacheNames.remove(name);
<add> given(cacheManager.getCache(name)).willReturn(null);
<add> }
<add> }
<add>}
<ide><path>spring-context-support/src/test/java/org/springframework/cache/transaction/AbstractTransactionSupportingCacheManagerTests.java
<add>/*
<add> * Copyright 2002-2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.cache.transaction;
<add>
<add>import static org.hamcrest.Matchers.*;
<add>import static org.junit.Assert.*;
<add>
<add>import org.junit.Rule;
<add>import org.junit.Test;
<add>import org.junit.rules.TestName;
<add>import org.springframework.cache.Cache;
<add>import org.springframework.cache.CacheManager;
<add>
<add>/**
<add> * Shared tests for {@link CacheManager} that inherit from
<add> * {@link AbstractTransactionSupportingCacheManager}.
<add> *
<add> * @author Stephane Nicoll
<add> */
<add>public abstract class AbstractTransactionSupportingCacheManagerTests<T extends CacheManager> {
<add>
<add> public static final String CACHE_NAME = "testCacheManager";
<add>
<add> @Rule
<add> public final TestName name = new TestName();
<add>
<add>
<add> /**
<add> * Returns the {@link CacheManager} to use.
<add> *
<add> * @param transactionAware if the requested cache manager should be aware
<add> * of the transaction
<add> * @return the cache manager to use
<add> * @see org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager#setTransactionAware(boolean)
<add> */
<add> protected abstract T getCacheManager(boolean transactionAware);
<add>
<add> /**
<add> * Returns the expected concrete type of the cache.
<add> */
<add> protected abstract Class<? extends Cache> getCacheType();
<add>
<add> /**
<add> * Adds a cache with the specified name to the native manager.
<add> */
<add> protected abstract void addNativeCache(String cacheName);
<add>
<add> /**
<add> * Removes the cache with the specified name from the native manager.
<add> */
<add> protected abstract void removeNativeCache(String cacheName);
<add>
<add> @Test
<add> public void getOnExistingCache() {
<add> assertThat(getCacheManager(false).getCache(CACHE_NAME), is(instanceOf(getCacheType())));
<add> }
<add>
<add> @Test
<add> public void getOnNewCache() {
<add> T cacheManager = getCacheManager(false);
<add> String cacheName = name.getMethodName();
<add> addNativeCache(cacheName);
<add> assertFalse(cacheManager.getCacheNames().contains(cacheName));
<add> try {
<add> assertThat(cacheManager.getCache(cacheName),
<add> is(instanceOf(getCacheType())));
<add> assertTrue(cacheManager.getCacheNames().contains(cacheName));
<add> } finally {
<add> removeNativeCache(cacheName);
<add> }
<add> }
<add>
<add> @Test
<add> public void getOnUnknownCache() {
<add> T cacheManager = getCacheManager(false);
<add> String cacheName = name.getMethodName();
<add> assertFalse(cacheManager.getCacheNames().contains(cacheName));
<add> assertThat(cacheManager.getCache(cacheName), nullValue());
<add> }
<add>
<add> @Test
<add> public void getTransactionalOnExistingCache() {
<add> assertThat(getCacheManager(true).getCache(CACHE_NAME),
<add> is(instanceOf(TransactionAwareCacheDecorator.class)));
<add> }
<add>
<add> @Test
<add> public void getTransactionalOnNewCache() {
<add> String cacheName = name.getMethodName();
<add> T cacheManager = getCacheManager(true);
<add> assertFalse(cacheManager.getCacheNames().contains(cacheName));
<add> addNativeCache(cacheName);
<add> try {
<add> assertThat(cacheManager.getCache(cacheName),
<add> is(instanceOf(TransactionAwareCacheDecorator.class)));
<add> assertTrue(cacheManager.getCacheNames().contains(cacheName));
<add> } finally {
<add> removeNativeCache(cacheName);
<add> }
<add> }
<add>}
<ide><path>spring-context/src/main/java/org/springframework/cache/support/AbstractCacheManager.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> *
<ide> * @author Costin Leau
<ide> * @author Juergen Hoeller
<add> * @author Stephane Nicoll
<ide> * @since 3.1
<ide> */
<ide> public abstract class AbstractCacheManager implements CacheManager, InitializingBean {
<ide> protected Cache decorateCache(Cache cache) {
<ide> return cache;
<ide> }
<ide>
<add> /**
<add> * Return a missing cache with the specified {@code name} or {@code null} if
<add> * such cache does not exist or could not be created on the fly.
<add> * <p>Some caches may be created at runtime in the native provided. If a lookup
<add> * by name does not yield any result, a subclass gets a chance to register
<add> * such a cache at runtime. The returned cache will be automatically added to
<add> * this instance.
<add> * @param name the name of the cache to retrieve
<add> * @return the missing cache or {@code null} if no such cache exists or could be
<add> * created
<add> * @see #getCache(String)
<add> */
<add> protected Cache getMissingCache(String name) {
<add> return null;
<add> }
<ide>
<ide> @Override
<ide> public Cache getCache(String name) {
<del> return this.cacheMap.get(name);
<add> Cache cache = lookupCache(name);
<add> if (cache != null) {
<add> return cache;
<add> }
<add> else {
<add> Cache missingCache = getMissingCache(name);
<add> if (missingCache != null) {
<add> addCache(missingCache);
<add> return lookupCache(name); // May be decorated
<add> }
<add> return null;
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public Collection<String> getCacheNames() {
<ide> return Collections.unmodifiableSet(this.cacheNames);
<ide> }
<ide>
<add> private Cache lookupCache(String name) {
<add> return this.cacheMap.get(name);
<add> }
<ide>
<ide> /**
<ide> * Load the caches for this cache manager. Occurs at startup. | 6 |
Python | Python | add a run_classifier.py in albert folder | 5f296bbef998e75721818d6b336264ae10f4a77d | <ide><path>official/nlp/albert/run_classifier.py
<add># Copyright 2019 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""ALBERT classification finetuning runner in tf2.x."""
<add>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import json
<add>
<add>from absl import app
<add>from absl import flags
<add>import tensorflow as tf
<add>
<add>from official.nlp.albert import configs as albert_configs
<add>from official.nlp.bert import run_classifier as run_classifier_bert
<add>from official.utils.misc import distribution_utils
<add>
<add>FLAGS = flags.FLAGS
<add>
<add>
<add>def main(_):
<add> # Users should always run this script under TF 2.x
<add> assert tf.version.VERSION.startswith('2.')
<add>
<add> with tf.io.gfile.GFile(FLAGS.input_meta_data_path, 'rb') as reader:
<add> input_meta_data = json.loads(reader.read().decode('utf-8'))
<add>
<add> if not FLAGS.model_dir:
<add> FLAGS.model_dir = '/tmp/bert20/'
<add>
<add> strategy = distribution_utils.get_distribution_strategy(
<add> distribution_strategy=FLAGS.distribution_strategy,
<add> num_gpus=FLAGS.num_gpus,
<add> tpu_address=FLAGS.tpu)
<add> max_seq_length = input_meta_data['max_seq_length']
<add> train_input_fn = run_classifier_bert.get_dataset_fn(
<add> FLAGS.train_data_path,
<add> max_seq_length,
<add> FLAGS.train_batch_size,
<add> is_training=True)
<add> eval_input_fn = run_classifier_bert.get_dataset_fn(
<add> FLAGS.eval_data_path,
<add> max_seq_length,
<add> FLAGS.eval_batch_size,
<add> is_training=False)
<add>
<add> albert_config = albert_configs.AlbertConfig.from_json_file(
<add> FLAGS.bert_config_file)
<add> run_classifier_bert.run_bert(strategy, input_meta_data, albert_config,
<add> train_input_fn, eval_input_fn)
<add>
<add>
<add>if __name__ == '__main__':
<add> flags.mark_flag_as_required('bert_config_file')
<add> flags.mark_flag_as_required('input_meta_data_path')
<add> flags.mark_flag_as_required('model_dir')
<add> app.run(main)
<ide><path>official/nlp/bert/run_classifier.py
<ide>
<ide> from official.modeling import model_training_utils
<ide> from official.nlp import optimization
<del>from official.nlp.albert import configs as albert_configs
<ide> from official.nlp.bert import bert_models
<ide> from official.nlp.bert import common_flags
<ide> from official.nlp.bert import configs as bert_configs
<ide> def export_classifier(model_export_path, input_meta_data,
<ide>
<ide> def run_bert(strategy,
<ide> input_meta_data,
<add> model_config,
<ide> train_input_fn=None,
<ide> eval_input_fn=None):
<ide> """Run BERT training."""
<del> if FLAGS.model_type == 'bert':
<del> bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file)
<del> else:
<del> assert FLAGS.model_type == 'albert'
<del> bert_config = albert_configs.AlbertConfig.from_json_file(
<del> FLAGS.bert_config_file)
<ide> if FLAGS.mode == 'export_only':
<ide> # As Keras ModelCheckpoint callback used with Keras compile/fit() API
<ide> # internally uses model.save_weights() to save checkpoints, we must
<ide> # use model.load_weights() when Keras compile/fit() is used.
<ide> export_classifier(FLAGS.model_export_path, input_meta_data,
<ide> FLAGS.use_keras_compile_fit,
<del> bert_config, FLAGS.model_dir)
<add> model_config, FLAGS.model_dir)
<ide> return
<ide>
<ide> if FLAGS.mode != 'train_and_eval':
<ide> def run_bert(strategy,
<ide>
<ide> trained_model = run_bert_classifier(
<ide> strategy,
<del> bert_config,
<add> model_config,
<ide> input_meta_data,
<ide> FLAGS.model_dir,
<ide> epochs,
<ide> def main(_):
<ide> FLAGS.eval_batch_size,
<ide> is_training=False)
<ide>
<del> run_bert(strategy, input_meta_data, train_input_fn, eval_input_fn)
<add> bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file)
<add> run_bert(strategy, input_meta_data, bert_config, train_input_fn,
<add> eval_input_fn)
<ide>
<ide>
<ide> if __name__ == '__main__': | 2 |
Javascript | Javascript | avoid boolean type check | 20841c7c6604378d94d11d9373aa1cfd9f399798 | <ide><path>src/lib/create/from-anything.js
<ide> function configFromInput(config) {
<ide> export function createLocalOrUTC (input, format, locale, strict, isUTC) {
<ide> var c = {};
<ide>
<del> if (typeof(locale) === 'boolean') {
<add> if (locale === true || locale === false) {
<ide> strict = locale;
<ide> locale = undefined;
<ide> } | 1 |
Javascript | Javascript | remove view.proptypes rn deprecation workaround | c043c1e7d9ee4aa224454530d91152cbb9764125 | <ide><path>src/isomorphic/classic/element/ReactElementValidator.js
<ide> function validatePropTypes(element) {
<ide> return;
<ide> }
<ide> var name = componentClass.displayName || componentClass.name;
<del>
<del> // ReactNative `View.propTypes` have been deprecated in favor of `ViewPropTypes`.
<del> // In their place a temporary getter has been added with a deprecated warning message.
<del> // Avoid triggering that warning during validation using the temporary workaround,
<del> // __propTypesSecretDontUseThesePlease.
<del> // TODO (bvaughn) Revert this particular change any time after April 1 ReactNative tag.
<del> var propTypes = typeof componentClass.__propTypesSecretDontUseThesePlease ===
<del> 'object'
<del> ? componentClass.__propTypesSecretDontUseThesePlease
<del> : componentClass.propTypes;
<add> var propTypes = componentClass.propTypes;
<ide>
<ide> if (propTypes) {
<ide> currentlyValidatingElement = element; | 1 |
Javascript | Javascript | ignore replayed events | fe406bf717444def6e7a6cb10b8e9120d9679450 | <ide><path>src/plugins/plugin.legend.js
<ide> export default {
<ide>
<ide>
<ide> afterEvent(chart, args) {
<del> chart.legend.handleEvent(args.event);
<add> if (!args.replay) {
<add> chart.legend.handleEvent(args.event);
<add> }
<ide> },
<ide>
<ide> defaults: { | 1 |
PHP | PHP | fix comment style | ef8ee59f93da71798412271a7c0cb8f45a1a3c9d | <ide><path>tests/Routing/RoutingUrlGeneratorTest.php
<ide> public function testForceRootUrl()
<ide> $url->forceRootUrl('https://www.bar.com');
<ide> $this->assertEquals('http://www.bar.com/foo/bar', $url->to('foo/bar'));
<ide>
<del> /**
<del> * Ensure trailing / is trimmed from root URL as UrlGenerator already handles this
<del> */
<add> // Ensure trailing slash is trimmed from root URL as UrlGenerator already handles this
<ide> $url->forceRootUrl('http://www.foo.com/');
<ide> $this->assertEquals('http://www.foo.com/bar', $url->to('/bar'));
<ide> | 1 |
Ruby | Ruby | modernize flash tests | 93cba1207a22b0dc0e2a87769fb5b9fbc907bce7 | <ide><path>actionpack/test/controller/flash_test.rb
<ide> def rescue_action(e)
<ide> end
<ide>
<ide> def setup
<del> initialize_request_and_response
<add> @request = ActionController::TestRequest.new
<add> @response = ActionController::TestResponse.new
<add> @controller = TestController.new
<ide> end
<ide>
<ide> def test_flash
<del> @request.action = "set_flash"
<del> response = process_request
<add> get :set_flash
<ide>
<del> @request.action = "use_flash"
<del> first_response = process_request
<del> assert_equal "hello", first_response.template.assigns["flash_copy"]["that"]
<del> assert_equal "hello", first_response.template.assigns["flashy"]
<add> get :use_flash
<add> assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
<add> assert_equal "hello", @response.template.assigns["flashy"]
<ide>
<del> second_response = process_request
<del> assert_nil second_response.template.assigns["flash_copy"]["that"], "On second flash"
<add> get :use_flash
<add> assert_nil @response.template.assigns["flash_copy"]["that"], "On second flash"
<ide> end
<ide>
<ide> def test_keep_flash
<del> @request.action = "set_flash"
<del> response = process_request
<add> get :set_flash
<ide>
<del> @request.action = "use_flash_and_keep_it"
<del> first_response = process_request
<del> assert_equal "hello", first_response.template.assigns["flash_copy"]["that"]
<del> assert_equal "hello", first_response.template.assigns["flashy"]
<add> get :use_flash_and_keep_it
<add> assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
<add> assert_equal "hello", @response.template.assigns["flashy"]
<ide>
<del> @request.action = "use_flash"
<del> second_response = process_request
<del> assert_equal "hello", second_response.template.assigns["flash_copy"]["that"], "On second flash"
<add> get :use_flash
<add> assert_equal "hello", @response.template.assigns["flash_copy"]["that"], "On second flash"
<ide>
<del> third_response = process_request
<del> assert_nil third_response.template.assigns["flash_copy"]["that"], "On third flash"
<add> get :use_flash
<add> assert_nil @response.template.assigns["flash_copy"]["that"], "On third flash"
<ide> end
<ide>
<ide> def test_flash_now
<del> @request.action = "set_flash_now"
<del> response = process_request
<del> assert_equal "hello", response.template.assigns["flash_copy"]["that"]
<del> assert_equal "bar" , response.template.assigns["flash_copy"]["foo"]
<del> assert_equal "hello", response.template.assigns["flashy"]
<add> get :set_flash_now
<add> assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
<add> assert_equal "bar" , @response.template.assigns["flash_copy"]["foo"]
<add> assert_equal "hello", @response.template.assigns["flashy"]
<ide>
<del> @request.action = "attempt_to_use_flash_now"
<del> first_response = process_request
<del> assert_nil first_response.template.assigns["flash_copy"]["that"]
<del> assert_nil first_response.template.assigns["flash_copy"]["foo"]
<del> assert_nil first_response.template.assigns["flashy"]
<add> get :attempt_to_use_flash_now
<add> assert_nil @response.template.assigns["flash_copy"]["that"]
<add> assert_nil @response.template.assigns["flash_copy"]["foo"]
<add> assert_nil @response.template.assigns["flashy"]
<ide> end
<del>
<del> private
<del> def initialize_request_and_response
<del> @request = ActionController::TestRequest.new
<del> @response = ActionController::TestResponse.new
<del> end
<del>
<del> def process_request
<del> TestController.process(@request, @response)
<del> end
<del>end
<add>end
<ide>\ No newline at end of file | 1 |
PHP | PHP | use compact instead of defining arrays | 4f9dbfa54c534920fe1a3214d4cd7d3d72adfdf5 | <ide><path>src/View/Helper/BreadcrumbsHelper.php
<ide> public function add($title, $url = null, array $options = [])
<ide> */
<ide> public function prepend($title, $url = null, array $options = [])
<ide> {
<del> array_unshift($this->crumbs, ['title' => $title, 'url' => $url, 'options' => $options]);
<add> array_unshift($this->crumbs, compact('title', 'url', 'options'));
<ide>
<ide> return $this;
<ide> }
<ide> public function prepend($title, $url = null, array $options = [])
<ide> */
<ide> public function insertAt($index, $title, $url = null, array $options = [])
<ide> {
<del> array_splice($this->crumbs, $index, 0, [['title' => $title, 'url' => $url, 'options' => $options]]);
<add> array_splice($this->crumbs, $index, 0, [compact('title', 'url', 'options')]);
<ide>
<ide> return $this;
<ide> } | 1 |
Ruby | Ruby | add benchmark helper that works in erb | 904e544cc8f5846de7c31827bb5556c6a238c0de | <ide><path>actionpack/lib/action_view/helpers.rb
<del>require 'active_support/benchmarkable'
<del>
<ide> module ActionView #:nodoc:
<ide> module Helpers #:nodoc:
<ide> extend ActiveSupport::Autoload
<ide>
<ide> autoload :ActiveModelHelper
<ide> autoload :AssetTagHelper
<ide> autoload :AtomFeedHelper
<add> autoload :BenchmarkHelper
<ide> autoload :CacheHelper
<ide> autoload :CaptureHelper
<ide> autoload :ControllerHelper
<ide> module Helpers #:nodoc:
<ide> extend SanitizeHelper::ClassMethods
<ide> end
<ide>
<del> include ActiveSupport::Benchmarkable
<ide> include ActiveModelHelper
<ide> include AssetTagHelper
<ide> include AtomFeedHelper
<add> include BenchmarkHelper
<ide> include CacheHelper
<ide> include CaptureHelper
<ide> include ControllerHelper
<ide><path>actionpack/lib/action_view/helpers/benchmark_helper.rb
<add>require 'active_support/benchmarkable'
<add>
<add>module ActionView
<add> module Helpers
<add> module BenchmarkHelper
<add> include ActiveSupport::Benchmarkable
<add>
<add> def benchmark(*)
<add> capture { super }
<add> end
<add> end
<add> end
<add>end
<ide><path>actionpack/test/template/benchmark_helper_test.rb
<add>require 'abstract_unit'
<add>require 'stringio'
<add>
<add>class BenchmarkHelperTest < ActionView::TestCase
<add> include RenderERBUtils
<add> tests ActionView::Helpers::BenchmarkHelper
<add>
<add> def test_output_in_erb
<add> output = render_erb("Hello <%= benchmark do %>world<% end %>")
<add> expected = 'Hello world'
<add> assert_equal expected, output
<add> end
<add>
<add> def test_returns_value_from_block
<add> assert_equal 'test', benchmark { 'test' }
<add> end
<add>
<add> def test_default_message
<add> log = StringIO.new
<add> self.stubs(:logger).returns(Logger.new(log))
<add> benchmark {}
<add> assert_match(log.rewind && log.read, /Benchmarking \(\d+.\d+ms\)/)
<add> end
<add>end | 3 |
Text | Text | improve reacttestutils.simulate documentation | 97e219e78592bba72c7fbc4ba0716cbc3fa1cd3e | <ide><path>docs/docs/10.4-test-utils.md
<ide> Simulate.{eventName}(DOMElement element, object eventData)
<ide>
<ide> Simulate an event dispatch on a DOM node with optional `eventData` event data. **This is possibly the single most useful utility in `ReactTestUtils`.**
<ide>
<del>Example usage:
<add>**Clicking an element**
<add>```javascript
<add>var node = React.findDOMNode(this.refs.button);
<add>React.addons.TestUtils.Simulate.click(node);
<add>```
<ide>
<add>**Changing the value of an input field and then pressing ENTER**
<ide> ```javascript
<ide> var node = React.findDOMNode(this.refs.input);
<del>React.addons.TestUtils.Simulate.click(node);
<del>React.addons.TestUtils.Simulate.change(node, {target: {value: 'Hello, world'}});
<del>React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter"});
<add>node.value = 'giraffe'
<add>React.addons.TestUtils.Simulate.change(node);
<add>React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13});
<ide> ```
<ide>
<add>*note that you will have to provide any event property that you're using in your component (e.g. keyCode, which, etc...) as React is not creating any of these for you*
<add>
<ide> `Simulate` has a method for every event that React understands.
<ide>
<ide> ### renderIntoDocument | 1 |
Mixed | Ruby | add option for per-form csrf tokens | 3e98819e20bc113343d4d4c0df614865ad5a9d3a | <ide><path>actionpack/CHANGELOG.md
<add>* Add option for per-form CSRF tokens.
<add>
<add> *Ben Toews*
<add>
<ide> * Add tests and documentation for `ActionController::Renderers::use_renderers`.
<ide>
<ide> *Benjamin Fleischer*
<ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb
<ide> module RequestForgeryProtection
<ide> config_accessor :forgery_protection_origin_check
<ide> self.forgery_protection_origin_check = false
<ide>
<add> # Controls whether form-action/method specific CSRF tokens are used.
<add> config_accessor :per_form_csrf_tokens
<add> self.per_form_csrf_tokens = false
<add>
<ide> helper_method :form_authenticity_token
<ide> helper_method :protect_against_forgery?
<ide> end
<ide> def request_authenticity_tokens
<ide> end
<ide>
<ide> # Sets the token value for the current session.
<del> def form_authenticity_token
<del> masked_authenticity_token(session)
<add> def form_authenticity_token(form_options: {})
<add> masked_authenticity_token(session, form_options: form_options)
<ide> end
<ide>
<ide> # Creates a masked version of the authenticity token that varies
<ide> # on each request. The masking is used to mitigate SSL attacks
<ide> # like BREACH.
<del> def masked_authenticity_token(session)
<add> def masked_authenticity_token(session, form_options: {})
<add> action, method = form_options.values_at(:action, :method)
<add>
<add> raw_token = if per_form_csrf_tokens && action && method
<add> action_path = normalize_action_path(action)
<add> per_form_csrf_token(session, action_path, method)
<add> else
<add> real_csrf_token(session)
<add> end
<add>
<ide> one_time_pad = SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH)
<del> encrypted_csrf_token = xor_byte_strings(one_time_pad, real_csrf_token(session))
<add> encrypted_csrf_token = xor_byte_strings(one_time_pad, raw_token)
<ide> masked_token = one_time_pad + encrypted_csrf_token
<ide> Base64.strict_encode64(masked_token)
<ide> end
<ide> def valid_authenticity_token?(session, encoded_masked_token)
<ide> compare_with_real_token masked_token, session
<ide>
<ide> elsif masked_token.length == AUTHENTICITY_TOKEN_LENGTH * 2
<del> # Split the token into the one-time pad and the encrypted
<del> # value and decrypt it
<del> one_time_pad = masked_token[0...AUTHENTICITY_TOKEN_LENGTH]
<del> encrypted_csrf_token = masked_token[AUTHENTICITY_TOKEN_LENGTH..-1]
<del> csrf_token = xor_byte_strings(one_time_pad, encrypted_csrf_token)
<del>
<del> compare_with_real_token csrf_token, session
<add> csrf_token = unmask_token(masked_token)
<ide>
<add> compare_with_real_token(csrf_token, session) ||
<add> valid_per_form_csrf_token?(csrf_token, session)
<ide> else
<ide> false # Token is malformed
<ide> end
<ide> end
<ide>
<add> def unmask_token(masked_token)
<add> # Split the token into the one-time pad and the encrypted
<add> # value and decrypt it
<add> one_time_pad = masked_token[0...AUTHENTICITY_TOKEN_LENGTH]
<add> encrypted_csrf_token = masked_token[AUTHENTICITY_TOKEN_LENGTH..-1]
<add> xor_byte_strings(one_time_pad, encrypted_csrf_token)
<add> end
<add>
<ide> def compare_with_real_token(token, session)
<ide> ActiveSupport::SecurityUtils.secure_compare(token, real_csrf_token(session))
<ide> end
<ide>
<add> def valid_per_form_csrf_token?(token, session)
<add> if per_form_csrf_tokens
<add> correct_token = per_form_csrf_token(
<add> session,
<add> normalize_action_path(request.fullpath),
<add> request.request_method
<add> )
<add>
<add> ActiveSupport::SecurityUtils.secure_compare(token, correct_token)
<add> else
<add> false
<add> end
<add> end
<add>
<ide> def real_csrf_token(session)
<ide> session[:_csrf_token] ||= SecureRandom.base64(AUTHENTICITY_TOKEN_LENGTH)
<ide> Base64.strict_decode64(session[:_csrf_token])
<ide> end
<ide>
<add> def per_form_csrf_token(session, action_path, method)
<add> OpenSSL::HMAC.digest(
<add> OpenSSL::Digest::SHA256.new,
<add> real_csrf_token(session),
<add> [action_path, method.downcase].join("#")
<add> )
<add> end
<add>
<ide> def xor_byte_strings(s1, s2)
<ide> s1.bytes.zip(s2.bytes).map { |(c1,c2)| c1 ^ c2 }.pack('c*')
<ide> end
<ide> def valid_request_origin?
<ide> true
<ide> end
<ide> end
<add>
<add> def normalize_action_path(action_path)
<add> action_path.split('?').first.to_s.chomp('/')
<add> end
<ide> end
<ide> end
<ide><path>actionpack/test/controller/request_forgery_protection_test.rb
<ide> def form_authenticity_param
<ide> end
<ide> end
<ide>
<add>class PerFormTokensController < ActionController::Base
<add> protect_from_forgery :with => :exception
<add> self.per_form_csrf_tokens = true
<add>
<add> def index
<add> render inline: "<%= form_tag (params[:form_path] || '/per_form_tokens/post_one'), method: (params[:form_method] || :post) %>"
<add> end
<add>
<add> def post_one
<add> render plain: ''
<add> end
<add>
<add> def post_two
<add> render plain: ''
<add> end
<add>end
<add>
<ide> # common test methods
<ide> module RequestForgeryProtectionTests
<ide> def setup
<ide> def test_should_warn_if_form_authenticity_param_does_not_match_form_authenticity
<ide> end
<ide> end
<ide> end
<add>
<add>class PerFormTokensControllerTest < ActionController::TestCase
<add> def test_per_form_token_is_same_size_as_global_token
<add> get :index
<add> expected = ActionController::RequestForgeryProtection::AUTHENTICITY_TOKEN_LENGTH
<add> actual = @controller.send(:per_form_csrf_token, session, '/path', 'post').size
<add> assert_equal expected, actual
<add> end
<add>
<add> def test_accepts_token_for_correct_path_and_method
<add> get :index
<add>
<add> form_token = nil
<add> assert_select 'input[name=custom_authenticity_token]' do |elts|
<add> form_token = elts.first['value']
<add> assert_not_nil form_token
<add> end
<add>
<add> actual = @controller.send(:unmask_token, Base64.strict_decode64(form_token))
<add> expected = @controller.send(:per_form_csrf_token, session, '/per_form_tokens/post_one', 'post')
<add> assert_equal expected, actual
<add>
<add> # This is required because PATH_INFO isn't reset between requests.
<add> @request.env['PATH_INFO'] = '/per_form_tokens/post_one'
<add> assert_nothing_raised do
<add> post :post_one, params: {custom_authenticity_token: form_token}
<add> end
<add> assert_response :success
<add> end
<add>
<add> def test_rejects_token_for_incorrect_path
<add> get :index
<add>
<add> form_token = nil
<add> assert_select 'input[name=custom_authenticity_token]' do |elts|
<add> form_token = elts.first['value']
<add> assert_not_nil form_token
<add> end
<add>
<add> actual = @controller.send(:unmask_token, Base64.strict_decode64(form_token))
<add> expected = @controller.send(:per_form_csrf_token, session, '/per_form_tokens/post_one', 'post')
<add> assert_equal expected, actual
<add>
<add> # This is required because PATH_INFO isn't reset between requests.
<add> @request.env['PATH_INFO'] = '/per_form_tokens/post_two'
<add> assert_raises(ActionController::InvalidAuthenticityToken) do
<add> post :post_two, params: {custom_authenticity_token: form_token}
<add> end
<add> end
<add>
<add> def test_rejects_token_for_incorrect_method
<add> get :index
<add>
<add> form_token = nil
<add> assert_select 'input[name=custom_authenticity_token]' do |elts|
<add> form_token = elts.first['value']
<add> assert_not_nil form_token
<add> end
<add>
<add> actual = @controller.send(:unmask_token, Base64.strict_decode64(form_token))
<add> expected = @controller.send(:per_form_csrf_token, session, '/per_form_tokens/post_one', 'post')
<add> assert_equal expected, actual
<add>
<add> # This is required because PATH_INFO isn't reset between requests.
<add> @request.env['PATH_INFO'] = '/per_form_tokens/post_one'
<add> assert_raises(ActionController::InvalidAuthenticityToken) do
<add> patch :post_one, params: {custom_authenticity_token: form_token}
<add> end
<add> end
<add>
<add> def test_accepts_global_csrf_token
<add> get :index
<add>
<add> token = @controller.send(:form_authenticity_token)
<add>
<add> # This is required because PATH_INFO isn't reset between requests.
<add> @request.env['PATH_INFO'] = '/per_form_tokens/post_one'
<add> assert_nothing_raised do
<add> post :post_one, params: {custom_authenticity_token: token}
<add> end
<add> assert_response :success
<add> end
<add>
<add> def test_ignores_params
<add> get :index, params: {form_path: '/per_form_tokens/post_one?foo=bar'}
<add>
<add> form_token = nil
<add> assert_select 'input[name=custom_authenticity_token]' do |elts|
<add> form_token = elts.first['value']
<add> assert_not_nil form_token
<add> end
<add>
<add> actual = @controller.send(:unmask_token, Base64.strict_decode64(form_token))
<add> expected = @controller.send(:per_form_csrf_token, session, '/per_form_tokens/post_one', 'post')
<add> assert_equal expected, actual
<add>
<add> # This is required because PATH_INFO isn't reset between requests.
<add> @request.env['PATH_INFO'] = '/per_form_tokens/post_one?foo=baz'
<add> assert_nothing_raised do
<add> post :post_one, params: {custom_authenticity_token: form_token, baz: 'foo'}
<add> end
<add> assert_response :success
<add> end
<add>
<add> def test_ignores_trailing_slash_during_generation
<add> get :index, params: {form_path: '/per_form_tokens/post_one/'}
<add>
<add> form_token = nil
<add> assert_select 'input[name=custom_authenticity_token]' do |elts|
<add> form_token = elts.first['value']
<add> assert_not_nil form_token
<add> end
<add>
<add> # This is required because PATH_INFO isn't reset between requests.
<add> @request.env['PATH_INFO'] = '/per_form_tokens/post_one'
<add> assert_nothing_raised do
<add> post :post_one, params: {custom_authenticity_token: form_token}
<add> end
<add> assert_response :success
<add> end
<add>
<add> def test_ignores_trailing_slash_during_validation
<add> get :index
<add>
<add> form_token = nil
<add> assert_select 'input[name=custom_authenticity_token]' do |elts|
<add> form_token = elts.first['value']
<add> assert_not_nil form_token
<add> end
<add>
<add> # This is required because PATH_INFO isn't reset between requests.
<add> @request.env['PATH_INFO'] = '/per_form_tokens/post_one/'
<add> assert_nothing_raised do
<add> post :post_one, params: {custom_authenticity_token: form_token}
<add> end
<add> assert_response :success
<add> end
<add>
<add> def test_method_is_case_insensitive
<add> get :index, params: {form_method: "POST"}
<add>
<add> form_token = nil
<add> assert_select 'input[name=custom_authenticity_token]' do |elts|
<add> form_token = elts.first['value']
<add> assert_not_nil form_token
<add> end
<add>
<add> # This is required because PATH_INFO isn't reset between requests.
<add> @request.env['PATH_INFO'] = '/per_form_tokens/post_one/'
<add> assert_nothing_raised do
<add> post :post_one, params: {custom_authenticity_token: form_token}
<add> end
<add> assert_response :success
<add> end
<add>end
<ide><path>actionview/lib/action_view/helpers/form_tag_helper.rb
<ide> def extra_tags_for_form(html_options)
<ide> ''
<ide> when /^post$/i, "", nil
<ide> html_options["method"] = "post"
<del> token_tag(authenticity_token)
<add> token_tag(authenticity_token, form_options: {
<add> action: html_options["action"],
<add> method: "post"
<add> })
<ide> else
<ide> html_options["method"] = "post"
<del> method_tag(method) + token_tag(authenticity_token)
<add> method_tag(method) + token_tag(authenticity_token, form_options: {
<add> action: html_options["action"],
<add> method: method
<add> })
<ide> end
<ide>
<ide> if html_options.delete("enforce_utf8") { true }
<ide><path>actionview/lib/action_view/helpers/url_helper.rb
<ide> def button_to(name = nil, options = nil, html_options = nil, &block)
<ide> form_options[:action] = url
<ide> form_options[:'data-remote'] = true if remote
<ide>
<del> request_token_tag = form_method == 'post' ? token_tag : ''
<add> request_token_tag = if form_method == 'post'
<add> token_tag(nil, form_options: form_options)
<add> else
<add> ''
<add> end
<ide>
<ide> html_options = convert_options_to_data_attributes(options, html_options)
<ide> html_options['type'] = 'submit'
<ide> def add_method_to_attributes!(html_options, method)
<ide> html_options["data-method"] = method
<ide> end
<ide>
<del> def token_tag(token=nil)
<add> def token_tag(token=nil, form_options: {})
<ide> if token != false && protect_against_forgery?
<del> token ||= form_authenticity_token
<add> token ||= form_authenticity_token(form_options: form_options)
<ide> tag(:input, type: "hidden", name: request_forgery_protection_token.to_s, value: token)
<ide> else
<ide> ''
<ide><path>actionview/test/template/url_helper_test.rb
<ide> def protect_against_forgery?
<ide> self.request_forgery
<ide> end
<ide>
<del> def form_authenticity_token
<add> def form_authenticity_token(*args)
<ide> "secret"
<ide> end
<ide>
<ide><path>guides/source/configuring.md
<ide> The schema dumper adds one additional configuration option:
<ide>
<ide> * `config.action_controller.forgery_protection_origin_check` configures whether the HTTP `Origin` header should be checked against the site's origin as an additional CSRF defense.
<ide>
<add>* `config.action_controller.per_form_csrf_tokens` configures whether CSRF tokens are only valid for the method/action they were generated for.
<add>
<ide> * `config.action_controller.relative_url_root` can be used to tell Rails that you are [deploying to a subdirectory](configuring.html#deploy-to-a-subdirectory-relative-url-root). The default is `ENV['RAILS_RELATIVE_URL_ROOT']`.
<ide>
<ide> * `config.action_controller.permit_all_parameters` sets all the parameters for mass assignment to be permitted by default. The default value is `false`.
<ide><path>railties/lib/rails/generators/rails/app/templates/config/initializers/per_form_csrf_tokens.rb
<add># Be sure to restart your server when you modify this file.
<add>
<add># Enable per-form CSRF tokens.
<add>Rails.application.config.action_controller.per_form_csrf_tokens = true
<ide><path>railties/test/application/configuration_test.rb
<ide> def update
<ide>
<ide> private
<ide>
<del> def form_authenticity_token; token; end # stub the authenticy token
<add> def form_authenticity_token(*args); token; end # stub the authenticy token
<ide> end
<ide> RUBY
<ide> | 9 |
Ruby | Ruby | use prepared statements for primary key queries | a9e8554b46a29573094eec139b16778e29e5c37a | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def pk_and_sequence_for(table) #:nodoc:
<ide>
<ide> # Returns just a table's primary key
<ide> def primary_key(table)
<del> pk_and_sequence = pk_and_sequence_for(table)
<del> pk_and_sequence && pk_and_sequence.first
<add> row = exec_query(<<-end_sql, 'SCHEMA', [[nil, table]]).rows.first
<add> SELECT DISTINCT(attr.attname)
<add> FROM pg_attribute attr,
<add> pg_depend dep,
<add> pg_namespace name,
<add> pg_constraint cons
<add> WHERE attr.attrelid = dep.refobjid
<add> AND attr.attnum = dep.refobjsubid
<add> AND attr.attrelid = cons.conrelid
<add> AND attr.attnum = cons.conkey[1]
<add> AND cons.contype = 'p'
<add> AND dep.refobjid = $1::regclass
<add> end_sql
<add>
<add> row && row.first
<ide> end
<ide>
<ide> # Renames a table. | 1 |
Javascript | Javascript | trigger fallback bar after user clicks in pdf | 6e9d158a98b695e0cf1411490585b25fbb099c0b | <ide><path>web/app.js
<ide> const PDFViewerApplication = {
<ide> externalServices: DefaultExternalServices,
<ide> _boundEvents: {},
<ide> contentDispositionFilename: null,
<add> _hasInteracted: false,
<add> _delayedFallbackFeatureIds: [],
<ide>
<ide> // Called once when the document is loaded.
<ide> async initialize(appConfig) {
<ide> const PDFViewerApplication = {
<ide> typeof PDFJSDev === "undefined" ||
<ide> PDFJSDev.test("MOZCENTRAL || GENERIC")
<ide> ) {
<add> // For PDFs that contain script and form errors, we should only trigger
<add> // the fallback once the user has interacted with the page.
<add> if (this._delayedFallbackFeatureIds.length >= 1 && this._hasInteracted) {
<add> featureId = this._delayedFallbackFeatureIds[0];
<add> // Reset to prevent all click events from showing fallback bar.
<add> this._delayedFallbackFeatureIds = [];
<add> }
<add>
<ide> // Only trigger the fallback once so we don't spam the user with messages
<ide> // for one PDF.
<ide> if (this.fellback) {
<ide> return;
<ide> }
<add>
<ide> this.fellback = true;
<ide> this.externalServices.fallback(
<ide> {
<ide> const PDFViewerApplication = {
<ide> return false;
<ide> }
<ide> console.warn("Warning: JavaScript is not supported");
<del> this.fallback(UNSUPPORTED_FEATURES.javaScript);
<add> this._delayedFallbackFeatureIds.push(UNSUPPORTED_FEATURES.javaScript);
<ide> return true;
<ide> });
<ide>
<ide> const PDFViewerApplication = {
<ide>
<ide> if (info.IsAcroFormPresent) {
<ide> console.warn("Warning: AcroForm/XFA is not supported");
<del> this.fallback(UNSUPPORTED_FEATURES.forms);
<add> this._delayedFallbackFeatureIds.push(UNSUPPORTED_FEATURES.forms);
<ide> }
<ide>
<ide> if (
<ide> const PDFViewerApplication = {
<ide> window.addEventListener("wheel", webViewerWheel, { passive: false });
<ide> window.addEventListener("click", webViewerClick);
<ide> window.addEventListener("keydown", webViewerKeyDown);
<add> window.addEventListener("keyup", webViewerKeyUp);
<ide> window.addEventListener("resize", _boundEvents.windowResize);
<ide> window.addEventListener("hashchange", _boundEvents.windowHashChange);
<ide> window.addEventListener("beforeprint", _boundEvents.windowBeforePrint);
<ide> const PDFViewerApplication = {
<ide> window.removeEventListener("wheel", webViewerWheel, { passive: false });
<ide> window.removeEventListener("click", webViewerClick);
<ide> window.removeEventListener("keydown", webViewerKeyDown);
<add> window.removeEventListener("keyup", webViewerKeyUp);
<ide> window.removeEventListener("resize", _boundEvents.windowResize);
<ide> window.removeEventListener("hashchange", _boundEvents.windowHashChange);
<ide> window.removeEventListener("beforeprint", _boundEvents.windowBeforePrint);
<ide> function webViewerWheel(evt) {
<ide> }
<ide>
<ide> function webViewerClick(evt) {
<add> PDFViewerApplication._hasInteracted = true;
<add>
<add> // Avoid triggering the fallback bar when the user clicks on the
<add> // toolbar or sidebar.
<add> if (
<add> PDFViewerApplication._delayedFallbackFeatureIds.length >= 1 &&
<add> PDFViewerApplication.pdfViewer.containsElement(evt.target)
<add> ) {
<add> PDFViewerApplication.fallback();
<add> }
<add>
<ide> if (!PDFViewerApplication.secondaryToolbar.isOpen) {
<ide> return;
<ide> }
<ide> function webViewerClick(evt) {
<ide> }
<ide> }
<ide>
<add>function webViewerKeyUp(evt) {
<add> if (evt.keyCode === 9) {
<add> // The user is tabbing into the pdf. Display the error message
<add> // if it has not already been displayed.
<add> PDFViewerApplication._hasInteracted = true;
<add>
<add> if (PDFViewerApplication._delayedFallbackFeatureIds.length >= 1) {
<add> PDFViewerApplication.fallback();
<add> }
<add> }
<add>}
<add>
<ide> function webViewerKeyDown(evt) {
<ide> if (PDFViewerApplication.overlayManager.active) {
<ide> return; | 1 |
Javascript | Javascript | use ember.assert instead of throw | b6c1c2fffa2e535da8e1eb7babaa6119ff58b731 | <ide><path>packages/ember-metal/lib/mixin.js
<ide> function mergeMixins(mixins, m, descs, values, base) {
<ide> for(idx=0;idx<len;idx++) {
<ide>
<ide> mixin = mixins[idx];
<del> if (!mixin) throw new Error('Null value found in Ember.mixin()');
<add> Ember.assert('Null value found in Ember.mixin()', !!mixin);
<ide>
<ide> if (mixin instanceof Mixin) {
<ide> guid = Ember.guidFor(mixin);
<ide> function applyMixin(obj, mixins, partial) {
<ide>
<ide> if (desc === REQUIRED) {
<ide> if (!(key in obj)) {
<del> if (!partial) throw new Error('Required property not defined: '+key);
<add> Ember.assert('Required property not defined: '+key, !!partial);
<ide>
<ide> // for partial applies add to hash of required keys
<ide> req = writableReq(obj);
<ide> function applyMixin(obj, mixins, partial) {
<ide> if (META_SKIP[key]) continue;
<ide> keys.push(key);
<ide> }
<del> throw new Error('Required properties not defined: '+keys.join(','));
<add> // TODO: Remove surrounding if clause from production build
<add> Ember.assert('Required properties not defined: '+keys.join(','));
<ide> }
<ide> return obj;
<ide> } | 1 |
Java | Java | fix mountitem logging | a0403c0626c4048082a2e89c6e16abf5e3c4b5be | <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/IntBufferBatchMountItem.java
<ide> public String toString() {
<ide> } else if (type == INSTRUCTION_UPDATE_LAYOUT) {
<ide> s.append(
<ide> String.format(
<del> "UPDATE LAYOUT [%d]: x:%d y:%d w:%d h:%d layoutDirection:%d\n",
<add> "UPDATE LAYOUT [%d]: x:%d y:%d w:%d h:%d layoutDirection:%d displayType:%d\n",
<add> mIntBuffer[i++],
<ide> mIntBuffer[i++],
<ide> mIntBuffer[i++],
<ide> mIntBuffer[i++], | 1 |
Python | Python | document the verbose parameter in earlystopping | 2c8864dd5363d464a2b9c6ad0a37c5eed13b7534 | <ide><path>keras/callbacks.py
<ide> class EarlyStopping(Callback):
<ide> improvement.
<ide> patience: Number of epochs with no improvement
<ide> after which training will be stopped.
<del> verbose: verbosity mode.
<add> verbose: int. 0: quiet, 1: message when the training is stopped
<add> and if weights got restored.
<ide> mode: One of `{"auto", "min", "max"}`. In `min` mode,
<ide> training will stop when the quantity
<ide> monitored has stopped decreasing; in `"max"` | 1 |
Ruby | Ruby | update generators to use new defaults | 8fabcb2eca03150b1c0c3dbc88dd13123f76894f | <ide><path>railties/lib/generators/rails/mailer/templates/mailer.rb
<ide> class <%= class_name %> < ActionMailer::Base
<del> self.defaults = { :from => "from@example.com" }
<add> self.defaults :from => "from@example.com"
<ide> <% for action in actions -%>
<ide>
<ide> # Subject can be set in your I18n file at config/locales/en.yml
<ide><path>railties/test/generators/mailer_generator_test.rb
<ide> def test_mailer_skeleton_is_created
<ide> run_generator
<ide> assert_file "app/mailers/notifier.rb" do |mailer|
<ide> assert_match /class Notifier < ActionMailer::Base/, mailer
<del> assert_match /self\.defaults\ =\ \{\ :from\ =>\ "from@example\.com"\ \}/, mailer
<add> assert_match /self\.defaults :from => "from@example.com"/, mailer
<ide> end
<ide> end
<ide> | 2 |
Javascript | Javascript | improve value validation utils | c405e9b23c6c6dc78f5d2b0747a75ceb61eaf4d9 | <ide><path>lib/internal/validators.js
<ide> 'use strict';
<ide>
<ide> const {
<add> ArrayIsArray,
<ide> NumberIsInteger,
<ide> NumberMAX_SAFE_INTEGER,
<ide> NumberMIN_SAFE_INTEGER,
<ide> function validateNumber(value, name) {
<ide> throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
<ide> }
<ide>
<add>function validateBoolean(value, name) {
<add> if (typeof value !== 'boolean')
<add> throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value);
<add>}
<add>
<add>const validateObject = hideStackFrames(
<add> (value, name, { nullable = false } = {}) => {
<add> if ((!nullable && value === null) ||
<add> ArrayIsArray(value) ||
<add> typeof value !== 'object') {
<add> throw new ERR_INVALID_ARG_TYPE(name, 'Object', value);
<add> }
<add> });
<add>
<add>const validateArray = hideStackFrames((value, name, { minLength = 0 } = {}) => {
<add> if (!ArrayIsArray(value)) {
<add> throw new ERR_INVALID_ARG_TYPE(name, 'Array', value);
<add> }
<add> if (value.length < minLength) {
<add> const reason = `must be longer than ${minLength}`;
<add> throw new ERR_INVALID_ARG_VALUE(name, value, reason);
<add> }
<add>});
<add>
<ide> function validateSignalName(signal, name = 'signal') {
<ide> if (typeof signal !== 'string')
<ide> throw new ERR_INVALID_ARG_TYPE(name, 'string', signal);
<ide> module.exports = {
<ide> isInt32,
<ide> isUint32,
<ide> parseFileMode,
<add> validateArray,
<add> validateBoolean,
<ide> validateBuffer,
<ide> validateEncoding,
<add> validateObject,
<ide> validateInteger,
<ide> validateInt32,
<ide> validateUint32,
<ide><path>test/parallel/test-validators.js
<ide> // Flags: --expose-internals
<ide> 'use strict';
<add>
<ide> require('../common');
<ide> const assert = require('assert');
<ide> const {
<del> validateInteger
<add> validateArray,
<add> validateBoolean,
<add> validateInteger,
<add> validateObject,
<ide> } = require('internal/validators');
<ide> const { MAX_SAFE_INTEGER, MIN_SAFE_INTEGER } = Number;
<ide> const outOfRangeError = {
<ide> code: 'ERR_OUT_OF_RANGE',
<del> name: 'RangeError'
<add> name: 'RangeError',
<add>};
<add>const invalidArgTypeError = {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError',
<ide> };
<add>const invalidArgValueError = {
<add> code: 'ERR_INVALID_ARG_VALUE',
<add> name: 'TypeError',
<add>};
<add>
<add>{
<add> // validateInteger tests.
<add>
<add> // validateInteger() defaults to validating safe integers.
<add> validateInteger(MAX_SAFE_INTEGER, 'foo');
<add> validateInteger(MIN_SAFE_INTEGER, 'foo');
<add> assert.throws(() => {
<add> validateInteger(MAX_SAFE_INTEGER + 1, 'foo');
<add> }, outOfRangeError);
<add> assert.throws(() => {
<add> validateInteger(MIN_SAFE_INTEGER - 1, 'foo');
<add> }, outOfRangeError);
<add>
<add> // validateInteger() works with unsafe integers.
<add> validateInteger(MAX_SAFE_INTEGER + 1, 'foo', 0, MAX_SAFE_INTEGER + 1);
<add> validateInteger(MIN_SAFE_INTEGER - 1, 'foo', MIN_SAFE_INTEGER - 1);
<add>}
<add>
<add>{
<add> // validateArray tests.
<add> validateArray([], 'foo');
<add> validateArray([1, 2, 3], 'foo');
<add>
<add> [undefined, null, true, false, 0, 0.0, 42, '', 'string', {}]
<add> .forEach((val) => {
<add> assert.throws(() => {
<add> validateArray(val, 'foo');
<add> }, invalidArgTypeError);
<add> });
<add>
<add> validateArray([1], 'foo', { minLength: 1 });
<add> assert.throws(() => {
<add> validateArray([], 'foo', { minLength: 1 });
<add> }, invalidArgValueError);
<add>}
<add>
<add>{
<add> // validateBoolean tests.
<add> validateBoolean(true, 'foo');
<add> validateBoolean(false, 'foo');
<add>
<add> [undefined, null, 0, 0.0, 42, '', 'string', {}, []].forEach((val) => {
<add> assert.throws(() => {
<add> validateBoolean(val, 'foo');
<add> }, invalidArgTypeError);
<add> });
<add>}
<add>
<add>{
<add> // validateObject tests.
<add> validateObject({}, 'foo');
<add> validateObject({ a: 42, b: 'foo' }, 'foo');
<add>
<add> [undefined, null, true, false, 0, 0.0, 42, '', 'string', []]
<add> .forEach((val) => {
<add> assert.throws(() => {
<add> validateObject(val, 'foo');
<add> }, invalidArgTypeError);
<add> });
<ide>
<del>// validateInteger() defaults to validating safe integers.
<del>validateInteger(MAX_SAFE_INTEGER, 'foo');
<del>validateInteger(MIN_SAFE_INTEGER, 'foo');
<del>assert.throws(() => {
<del> validateInteger(MAX_SAFE_INTEGER + 1, 'foo');
<del>}, outOfRangeError);
<del>assert.throws(() => {
<del> validateInteger(MIN_SAFE_INTEGER - 1, 'foo');
<del>}, outOfRangeError);
<del>
<del>// validateInteger() works with unsafe integers.
<del>validateInteger(MAX_SAFE_INTEGER + 1, 'foo', 0, MAX_SAFE_INTEGER + 1);
<del>validateInteger(MIN_SAFE_INTEGER - 1, 'foo', MIN_SAFE_INTEGER - 1);
<add> validateObject(null, 'foo', { nullable: true });
<add>} | 2 |
Text | Text | add gists provided by mary | 35cbcc2fc1334b14a6aa9a1adf432c0ee80fd108 | <ide><path>docs/reference/run.md
<ide> parent = "mn_reference"
<ide> </style>
<ide> # Docker run reference
<ide>
<del>**Docker runs processes in isolated containers**. When an operator
<del>executes `docker run`, she starts a process with its own file system,
<del>its own networking, and its own isolated process tree. The
<del>[*Image*](/reference/glossary/#image) which starts the process may define
<del>defaults related to the binary to run, the networking to expose, and
<del>more, but `docker run` gives additional control to the operator who starts
<del>the container from the image. That's the main reason
<del>[*run*](/reference/commandline/run) has more options than any
<del>other `docker` command.
<add>Docker runs processes in isolated containers. A container is a process
<add>which runs on a host. The host may be local or remote. When an operator
<add>executes `docker run`, the container process that runs is isolated in
<add>that it has its own file system, its own networking, and its own
<add>isolated process tree separate from the host.
<add>
<add>This page details how to use the `docker run` command to define the
<add>container's resources at runtime.
<ide>
<ide> ## General form
<ide>
<ide> The basic `docker run` command takes this form:
<ide>
<ide> $ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]
<ide>
<del>To learn how to interpret the types of `[OPTIONS]`,
<del>see [*Option types*](/reference/commandline/cli/#option-types).
<del>
<del>The `run` options control the image's runtime behavior in a container. These
<del>settings affect:
<add>The `docker run` command must specify an [*IMAGE*](/reference/glossary/#image)
<add>to derive the container from. An image developer can define image
<add>defaults related to:
<ide>
<ide> * detached or foreground running
<ide> * container identification
<ide> * network settings
<ide> * runtime constraints on CPU and memory
<ide> * privileges and LXC configuration
<del>
<del>An image developer may set defaults for these same settings when she creates the
<del>image using the `docker build` command. Operators can use the `run` options to override most of the
<del>defaults set by the developer. And, operators can override nearly all the defaults set by the Docker runtime itself.
<ide>
<del>Finally, depending on your Docker system configuration, you may be required to
<del>preface each `docker` command with `sudo`. To avoid having to use `sudo` with
<del>the `docker` command, your system administrator can create a Unix group called
<del>`docker` and add users to it. For more information about this configuration,
<del>refer to the Docker installation documentation for your operating system.
<add>With the `docker run [OPTIONS]` an operator can add to or override the
<add>image defaults set by a developer. And, additionally, operators can
<add>override nearly all the defaults set by the Docker runtime itself. The
<add>operator's ability to override image and Docker runtime defaults is why
<add>[*run*](/reference/commandline/cli/run/) has more options than any
<add>other `docker` command.
<add>
<add>To learn how to interpret the types of `[OPTIONS]`, see [*Option
<add>types*](/reference/commandline/cli/#option-types).
<add>
<add>> **Note**: Depending on your Docker system configuration, you may be
<add>> required to preface the `docker run` command with `sudo`. To avoid
<add>> having to use `sudo` with the `docker` command, your system
<add>> administrator can create a Unix group called `docker` and add users to
<add>> it. For more information about this configuration, refer to the Docker
<add>> installation documentation for your operating system.
<add>
<ide>
<ide> ## Operator exclusive options
<ide>
<ide> or two examples of how to pass more parameters to that ENTRYPOINT:
<ide>
<ide> ### EXPOSE (incoming ports)
<ide>
<del>The Dockerfile doesn't give much control over networking, only providing
<del>the `EXPOSE` instruction to specify incoming ports that provide services.
<ide> The following `run` command options work with container networking:
<ide>
<del> --expose=[]: Expose a port or a range of ports from the container,
<del> in addition to ports exposed by the `EXPOSE` Dockerfile instruction
<add> --expose=[]: Expose a port or a range of ports inside the container.
<add> These are additional to those exposed by the `EXPOSE` instruction
<ide> -P=false : Publish all exposed ports to the host interfaces
<ide> -p=[] : Publish a container᾿s port or a range of ports to the host
<ide> format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort
<del> Both hostPort and containerPort can be specified as a range of ports.
<del> When specifying ranges for both, the number of container ports in the range must match the number of host ports in the range. (e.g., `-p 1234-1236:1234-1236/tcp`)
<del> When specifying a range for hostPort only, the containerPort must not be a range. In this case the container port is published somewhere within the specified hostPort range. (e.g., `-p 1234-1236:1234/tcp`)
<add> Both hostPort and containerPort can be specified as a
<add> range of ports. When specifying ranges for both, the
<add> number of container ports in the range must match the
<add> number of host ports in the range, for example:
<add> -p 1234-1236:1234-1236/tcp
<add>
<add> When specifying a range for hostPort only, the
<add> containerPort must not be a range. In this case the
<add> container port is published somewhere within the
<add> specified hostPort range. (e.g., `-p 1234-1236:1234/tcp`)
<add>
<ide> (use 'docker port' to see the actual mapping)
<add>
<ide> --link="" : Add link to another container (<name or id>:alias or <name or id>)
<ide>
<del>As mentioned previously, `EXPOSE` (and `--expose`) makes ports available
<del>**in** a container for incoming connections. The port number on the
<del>inside of the container (where the service listens) does not need to be
<del>the same number as the port exposed on the outside of the container
<del>(where clients connect), so inside the container you might have an HTTP
<del>service listening on port 80 (and so you `EXPOSE 80` in the Dockerfile),
<del>but outside the container the port might be 42800.
<del>
<del>To help a new client container reach the server container's internal
<del>port operator `--expose`'d by the operator or `EXPOSE`'d by the
<del>developer, the operator has three choices: start the server container
<del>with `-P` or `-p,` or start the client container with `--link`.
<del>
<del>If the operator uses `-P` or `-p` then Docker will make the exposed port
<del>accessible on the host and the ports will be available to any client that can
<del>reach the host. When using `-P`, Docker will bind the exposed port to a random
<del>port on the host within an *ephemeral port range* defined by
<del>`/proc/sys/net/ipv4/ip_local_port_range`. To find the mapping between the host
<del>ports and the exposed ports, use `docker port`.
<del>
<del>If the operator uses `--link` when starting the new client container,
<add>With the exception of the `EXPOSE` directive, an image developer hasn't
<add>got much control over networking. The `EXPOSE` instruction defines the
<add>initial incoming ports that provide services. These ports are available
<add>to processes inside the container. An operator can use the `--expose`
<add>option to add to the exposed ports.
<add>
<add>To expose a container's internal port, an operator can start the
<add>container with the `-P` or `-p` flag. The exposed port is accessible on
<add>the host and the ports are available to any client that can reach the
<add>host.
<add>
<add>The `-P` option publishes all the ports to the host interfaces. Docker
<add>binds each exposed port to a random port on the host. The range of
<add>ports are within an *ephemeral port range* defined by
<add>`/proc/sys/net/ipv4/ip_local_port_range`. Use the `-p` flag to
<add>explicitly map a single port or range of ports.
<add>
<add>The port number inside the container (where the service listens) does
<add>not need to match the port number exposed on the outside of the
<add>container (where clients connect). For example, inside the container an
<add>HTTP service is listening on port 80 (and so the image developer
<add>specifies `EXPOSE 80` in the Dockerfile). At runtime, the port might be
<add>bound to 42800 on the host. To find the mapping between the host ports
<add>and the exposed ports, use `docker port`.
<add>
<add>If the operator uses `--link` when starting a new client container,
<ide> then the client container can access the exposed port via a private
<del>networking interface. Docker will set some environment variables in the
<del>client container to help indicate which interface and port to use.
<add>networking interface. Docker will set some environment variables in the
<add>client container to help indicate which interface and port to use. For
<add>more information on linking, see [the guide on linking container
<add>together](/userguide/dockerlinks/)
<ide>
<ide> ### ENV (environment variables)
<ide> | 1 |
PHP | PHP | use fullpath for validator facade | 63256100705a4020796fa5faa9cf780506d440e7 | <ide><path>app/Http/Controllers/Auth/RegisterController.php
<ide> namespace App\Http\Controllers\Auth;
<ide>
<ide> use App\User;
<del>use Validator;
<ide> use App\Http\Controllers\Controller;
<add>use Illuminate\Support\Facades\Validator;
<ide> use Illuminate\Foundation\Auth\RegistersUsers;
<ide>
<ide> class RegisterController extends Controller | 1 |
PHP | PHP | fix issue with duplicate class inclusions | ccefe02de9d4cc462cdfc8a74158862d347afbac | <ide><path>lib/Cake/Core/App.php
<ide> public static function load($className) {
<ide> }
<ide> }
<ide>
<del> //To help apps migrate to 2.0 old style file names are allowed
<add> // To help apps migrate to 2.0 old style file names are allowed
<add> // if the trailing segment is one of the types that changed, alternates will be tried.
<ide> foreach ($paths as $path) {
<ide> $underscored = Inflector::underscore($className);
<ide> $tries = array($path . $underscored . '.php');
<ide> $parts = explode('_', $underscored);
<del> if (count($parts) > 1) {
<add> $numParts = count($parts);
<add> if ($numParts > 1 && in_array($parts[$numParts - 1], array('behavior', 'helper', 'component'))) {
<ide> array_pop($parts);
<ide> $tries[] = $path . implode('_', $parts) . '.php';
<ide> } | 1 |
Javascript | Javascript | fix broken link | c87cc34c015753904e96c35143c37f4d2fc63054 | <ide><path>packages/ember-application/lib/system/application.js
<ide> var get = Ember.get, set = Ember.set,
<ide>
<ide> To learn more about the advantages of event delegation and the Ember view
<ide> layer, and a list of the event listeners that are setup by default, visit the
<del> [Ember View Layer guide](http://emberjs.com/guides/view_layer#toc_event-delegation).
<add> [Ember View Layer guide](http://emberjs.com/guides/understanding-ember/the-view-layer/#toc_event-delegation).
<ide>
<ide> ### Initializers
<ide> | 1 |
Text | Text | add baseserializer heading | c0150e619ca02a69d87c335a70c47644e9b2e509 | <ide><path>docs/topics/3.0-announcement.md
<ide> See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-fr
<ide>
<ide> **TODO**: Drop`.object`, use `.validated_data` or get the instance with `.save()`.
<ide>
<add>#### The `BaseSerializer` class.
<add>
<add>**TODO**
<add>
<ide> #### Always use `fields`, not `exclude`.
<ide>
<ide> The `exclude` option is no longer available. You should use the more explicit `fields` option instead. | 1 |
Ruby | Ruby | add test case | 4fbb1e9f5bf1f22ad3aa913764b8ecb0c6e06c7d | <ide><path>actionpack/test/controller/renderer_test.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "abstract_unit"
<add>require "test_component"
<ide>
<ide> class RendererTest < ActiveSupport::TestCase
<ide> test "action controller base has a renderer" do
<ide> class RendererTest < ActiveSupport::TestCase
<ide> assert_equal "The secret is foo\n", content
<ide> end
<ide>
<add> def test_render_component
<add> renderer = ApplicationController.renderer
<add>
<add> assert_equal(
<add> %(<span title="my title">(Inline render)</span>),
<add> renderer.render(TestComponent.new(title: "my title")).strip
<add> )
<add> end
<add>
<ide> test "rendering with custom env" do
<ide> renderer = ApplicationController.renderer.new method: "post"
<ide> content = renderer.render inline: "<%= request.post? %>"
<ide><path>actionpack/test/lib/test_component.rb
<add># frozen_string_literal: true
<add>
<add>class TestComponent < ActionView::Base
<add> include ActiveModel::Validations
<add>
<add> validates :title, presence: true
<add> delegate :render, to: :view_context
<add>
<add> def initialize(title:)
<add> @title = title
<add> end
<add>
<add> # Entrypoint for rendering. Called by ActionView::RenderingHelper#render.
<add> #
<add> # Returns ActionView::OutputBuffer.
<add> def render_in(view_context)
<add> self.class.compile
<add> @view_context = view_context
<add> validate!
<add> rendered_template
<add> end
<add>
<add> def self.template
<add> <<~'erb'
<add> <span title="<%= title %>">(<%= render(plain: "Inline render") %>)</span>
<add> erb
<add> end
<add>
<add> def self.compile
<add> @compiled ||= nil
<add> return if @compiled
<add>
<add> class_eval(
<add> "def rendered_template; @output_buffer = ActionView::OutputBuffer.new; " +
<add> ActionView::Template::Handlers::ERB.erb_implementation.new(template, trim: true).src +
<add> "; end"
<add> )
<add>
<add> @compiled = true
<add> end
<add>
<add>private
<add> attr_reader :title, :view_context
<add>end | 2 |
Javascript | Javascript | set ng-app for editing with plunker | 99e85fc9b5b71a1bf3e54126b9c080b3c355c336 | <ide><path>docs/src/templates/js/docs.js
<ide> docsApp.serviceFactory.openPlunkr = function(templateMerge, formPostData, angula
<ide> return function(content) {
<ide> var allFiles = [].concat(content.js, content.css, content.html);
<ide> var indexHtmlContent = '<!doctype html>\n' +
<del> '<html ng-app>\n' +
<add> '<html ng-app="{{module}}">\n' +
<ide> ' <head>\n' +
<ide> ' <script src="{{angularJSUrl}}"></script>\n' +
<ide> '{{scriptDeps}}\n' +
<ide> docsApp.serviceFactory.openPlunkr = function(templateMerge, formPostData, angula
<ide> }
<ide> });
<ide> indexProp = {
<add> module: content.module,
<ide> angularJSUrl: angularUrls['angular.js'],
<ide> scriptDeps: scriptDeps,
<ide> indexContents: content.html[0].content | 1 |
Ruby | Ruby | fix unstated usage of action dispatch | a0e8eca30bc1f3cf7519bea37456cbfc98b56047 | <ide><path>railties/lib/rails/configuration.rb
<ide> module Rails
<ide> module Configuration
<ide> module Shared
<ide> def middleware
<del> @@default_middleware_stack ||= ActionDispatch::MiddlewareStack.new.tap do |middleware|
<del> middleware.use('::ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
<del> middleware.use('::Rack::Lock', :if => lambda { !Rails.application.config.allow_concurrency })
<del> middleware.use('::Rack::Runtime')
<del> middleware.use('::Rails::Rack::Logger')
<del> middleware.use('::ActionDispatch::ShowExceptions', lambda { Rails.application.config.consider_all_requests_local })
<del> middleware.use('::Rack::Sendfile', lambda { Rails.application.config.action_dispatch.x_sendfile_header })
<del> middleware.use('::ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes })
<del> middleware.use('::ActionDispatch::Cookies')
<del> middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options })
<del> middleware.use('::ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store })
<del> middleware.use(lambda { Rails.application.metal_loader.build_middleware(Rails.application.config.metals) }, :if => lambda { Rails.application.metal_loader.metals.any? })
<del> middleware.use('ActionDispatch::ParamsParser')
<del> middleware.use('::Rack::MethodOverride')
<del> middleware.use('::ActionDispatch::Head')
<del> end
<add> @@default_middleware_stack ||= default_middleware
<ide> end
<ide>
<ide> # Holds generators configuration:
<ide> def config_keys
<ide> def options
<ide> @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
<ide> end
<add>
<add> def default_middleware
<add> require 'action_dispatch'
<add> ActionDispatch::MiddlewareStack.new.tap do |middleware|
<add> middleware.use('::ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
<add> middleware.use('::Rack::Lock', :if => lambda { !Rails.application.config.allow_concurrency })
<add> middleware.use('::Rack::Runtime')
<add> middleware.use('::Rails::Rack::Logger')
<add> middleware.use('::ActionDispatch::ShowExceptions', lambda { Rails.application.config.consider_all_requests_local })
<add> middleware.use('::Rack::Sendfile', lambda { Rails.application.config.action_dispatch.x_sendfile_header })
<add> middleware.use('::ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes })
<add> middleware.use('::ActionDispatch::Cookies')
<add> middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options })
<add> middleware.use('::ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store })
<add> middleware.use(lambda { Rails.application.metal_loader.build_middleware(Rails.application.config.metals) }, :if => lambda { Rails.application.metal_loader.metals.any? })
<add> middleware.use('ActionDispatch::ParamsParser')
<add> middleware.use('::Rack::MethodOverride')
<add> middleware.use('::ActionDispatch::Head')
<add> end
<add> end
<ide> end
<ide>
<ide> class Generators #:nodoc: | 1 |
PHP | PHP | log errors before rendering | 5b21974325d2a974baf778e9ce3aa9da561b17bf | <ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php
<ide> public function handleException(Throwable $exception, ServerRequestInterface $re
<ide> $renderer = $errorHandler->getRenderer($exception, $request);
<ide>
<ide> try {
<del> $response = $renderer->render();
<ide> $errorHandler->logException($exception, $request);
<add> $response = $renderer->render();
<ide> } catch (Throwable $internalException) {
<ide> $errorHandler->logException($internalException, $request);
<ide> $response = $this->handleInternalError(); | 1 |
Ruby | Ruby | add tests for json merging | d768b6649a8682431a49397ae79c192bcdc1e219 | <ide><path>Library/Homebrew/dev-cmd/bottle.rb
<ide> def bottle_formula(f, args:)
<ide> end
<ide> end
<ide>
<del> def merge(args:)
<del> bottles_hash = args.named.reduce({}) do |hash, json_file|
<del> hash.deep_merge(JSON.parse(IO.read(json_file))) do |key, first, second|
<add> def parse_json_files(filenames)
<add> filenames.map do |filename|
<add> JSON.parse(IO.read(filename))
<add> end
<add> end
<add>
<add> def merge_json_files(json_files)
<add> json_files.reduce({}) do |hash, json_file|
<add> hash.deep_merge(json_file) do |key, first, second|
<ide> if key == "cellar"
<ide> # Prioritize HOMEBREW_CELLAR over :any over :any_skip_relocation
<ide> cellars = [first, second]
<ide> def merge(args:)
<ide> second
<ide> end
<ide> end
<add> end
<add>
<add> def merge(args:)
<add> bottles_hash = merge_json_files(parse_json_files(args.named))
<ide>
<ide> any_cellars = ["any", "any_skip_relocation"]
<ide> bottles_hash.each do |formula_name, bottle_hash|
<ide><path>Library/Homebrew/test/dev-cmd/bottle_spec.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "cmd/shared_examples/args_parse"
<add>require "dev-cmd/bottle"
<ide>
<ide> describe "Homebrew.bottle_args" do
<ide> it_behaves_like "parseable arguments"
<ide> end
<ide> end
<ide> end
<add>
<add>describe Homebrew do
<add> subject(:homebrew) { described_class }
<add>
<add> def stub_hash(parameters)
<add> <<~EOS
<add> {
<add> "#{parameters[:name]}":{
<add> "formula":{
<add> "pkg_version":"#{parameters[:version]}",
<add> "path":"#{parameters[:path]}"
<add> },
<add> "bottle":{
<add> "root_url":"https://homebrew.bintray.com/bottles",
<add> "prefix":"/usr/local",
<add> "cellar":"#{parameters[:cellar]}",
<add> "rebuild":0,
<add> "tags":{
<add> "#{parameters[:os]}":{
<add> "filename":"#{parameters[:filename]}",
<add> "local_filename":"#{parameters[:local_filename]}",
<add> "sha256":"#{parameters[:sha256]}"
<add> }
<add> }
<add> },
<add> "bintray":{
<add> "package":"#{parameters[:name]}",
<add> "repository":"bottles"
<add> }
<add> }
<add> }
<add> EOS
<add> end
<add>
<add> let(:hello_hash_big_sur) {
<add> JSON.parse(
<add> stub_hash(
<add> {
<add> "name": "hello",
<add> "version": "1.0",
<add> "path": "/home/hello.rb",
<add> "cellar": "any_skip_relocation",
<add> "os": "big_sur",
<add> "filename": "hello-1.0.big_sur.bottle.tar.gz",
<add> "local_filename": "hello--1.0.big_sur.bottle.tar.gz",
<add> "sha256": "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
<add> },
<add> ),
<add> )
<add> }
<add> let(:hello_hash_catalina) {
<add> JSON.parse(
<add> stub_hash(
<add> {
<add> "name": "hello",
<add> "version": "1.0",
<add> "path": "/home/hello.rb",
<add> "cellar": "any_skip_relocation",
<add> "os": "catalina",
<add> "filename": "hello-1.0.catalina.bottle.tar.gz",
<add> "local_filename": "hello--1.0.catalina.bottle.tar.gz",
<add> "sha256": "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac",
<add> },
<add> ),
<add> )
<add> }
<add> let(:unzip_hash_big_sur) {
<add> JSON.parse(
<add> stub_hash(
<add> {
<add> "name": "unzip",
<add> "version": "2.0",
<add> "path": "/home/unzip.rb",
<add> "cellar": "any_skip_relocation",
<add> "os": "big_sur",
<add> "filename": "unzip-2.0.big_sur.bottle.tar.gz",
<add> "local_filename": "unzip--2.0.big_sur.bottle.tar.gz",
<add> "sha256": "16cf230afdfcb6306c208d169549cf8773c831c8653d2c852315a048960d7e72",
<add> },
<add> ),
<add> )
<add> }
<add> let(:unzip_hash_catalina) {
<add> JSON.parse(
<add> stub_hash(
<add> {
<add> "name": "unzip",
<add> "version": "2.0",
<add> "path": "/home/unzip.rb",
<add> "cellar": "any",
<add> "os": "catalina",
<add> "filename": "unzip-2.0.catalina.bottle.tar.gz",
<add> "local_filename": "unzip--2.0.catalina.bottle.tar.gz",
<add> "sha256": "d9cc50eec8ac243148a121049c236cba06af4a0b1156ab397d0a2850aa79c137",
<add> },
<add> ),
<add> )
<add> }
<add>
<add> specify "::parse_json_files" do
<add> Tempfile.open("hello--1.0.big_sur.bottle.json") do |f|
<add> f.write(
<add> stub_hash(
<add> {
<add> "name": "hello",
<add> "version": "1.0",
<add> "path": "/home/hello.rb",
<add> "cellar": "any_skip_relocation",
<add> "os": "big_sur",
<add> "filename": "hello-1.0.big_sur.bottle.tar.gz",
<add> "local_filename": "hello--1.0.big_sur.bottle.tar.gz",
<add> "sha256": "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
<add> },
<add> ),
<add> )
<add> f.close
<add> expect(
<add> homebrew.parse_json_files([f.path]).first["hello"]["bottle"]["tags"]["big_sur"]["filename"],
<add> ).to eq("hello-1.0.big_sur.bottle.tar.gz")
<add> end
<add> end
<add>
<add> specify "::merge_json_files" do
<add> bottles_hash = homebrew.merge_json_files(
<add> [hello_hash_big_sur, hello_hash_catalina, unzip_hash_big_sur, unzip_hash_catalina],
<add> )
<add>
<add> hello_hash = bottles_hash["hello"]
<add> expect(hello_hash["bottle"]["cellar"]).to eq("any_skip_relocation")
<add> expect(hello_hash["bottle"]["tags"]["big_sur"]["filename"]).to eq("hello-1.0.big_sur.bottle.tar.gz")
<add> expect(hello_hash["bottle"]["tags"]["big_sur"]["local_filename"]).to eq("hello--1.0.big_sur.bottle.tar.gz")
<add> expect(hello_hash["bottle"]["tags"]["big_sur"]["sha256"]).to eq(
<add> "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
<add> )
<add> expect(hello_hash["bottle"]["tags"]["catalina"]["filename"]).to eq("hello-1.0.catalina.bottle.tar.gz")
<add> expect(hello_hash["bottle"]["tags"]["catalina"]["local_filename"]).to eq("hello--1.0.catalina.bottle.tar.gz")
<add> expect(hello_hash["bottle"]["tags"]["catalina"]["sha256"]).to eq(
<add> "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac",
<add> )
<add> unzip_hash = bottles_hash["unzip"]
<add> expect(unzip_hash["bottle"]["cellar"]).to eq("any")
<add> expect(unzip_hash["bottle"]["tags"]["big_sur"]["filename"]).to eq("unzip-2.0.big_sur.bottle.tar.gz")
<add> expect(unzip_hash["bottle"]["tags"]["big_sur"]["local_filename"]).to eq("unzip--2.0.big_sur.bottle.tar.gz")
<add> expect(unzip_hash["bottle"]["tags"]["big_sur"]["sha256"]).to eq(
<add> "16cf230afdfcb6306c208d169549cf8773c831c8653d2c852315a048960d7e72",
<add> )
<add> expect(unzip_hash["bottle"]["tags"]["catalina"]["filename"]).to eq("unzip-2.0.catalina.bottle.tar.gz")
<add> expect(unzip_hash["bottle"]["tags"]["catalina"]["local_filename"]).to eq("unzip--2.0.catalina.bottle.tar.gz")
<add> expect(unzip_hash["bottle"]["tags"]["catalina"]["sha256"]).to eq(
<add> "d9cc50eec8ac243148a121049c236cba06af4a0b1156ab397d0a2850aa79c137",
<add> )
<add> end
<add>end | 2 |
Ruby | Ruby | read extra args for 'rails new' from ~/.railsrc | 7039def6e116b12ccab8142cec7f7feabc264220 | <ide><path>railties/lib/rails/commands/application.rb
<ide> ARGV[0] = "--help"
<ide> else
<ide> ARGV.shift
<add> railsrc = File.join(File.expand_path("~"), ".railsrc")
<add> if File.exist?(railsrc)
<add> extra_args_string = File.open(railsrc).read
<add> extra_args = extra_args_string.split(/\n+/).map {|l| l.split}.flatten
<add> ARGV << extra_args
<add> ARGV.flatten!
<add> end
<ide> end
<ide>
<ide> require 'rubygems' if ARGV.include?("--dev") | 1 |
Mixed | Text | improve documentation on custom serializers | 71721dc1c9b769d3c06317122dc88cad4a346580 | <ide><path>activejob/README.md
<ide> MyJob.set(wait: 1.week).perform_later(record) # Enqueue a job to be performed 1
<ide>
<ide> That's it!
<ide>
<del>## Supported types for arguments
<ide>
<del>ActiveJob supports the following types of arguments by default:
<del>
<del> - Standard types (`NilClass`, `String`, `Integer`, `Fixnum`, `Bignum`, `Float`, `BigDecimal`, `TrueClass`, `FalseClass`)
<del> - `Hash`. Keys should be of `String` or `Symbol` type
<del> - `ActiveSupport::HashWithIndifferentAccess`
<del> - `Array`
<del>
<del>
<del>### GlobalID support
<add>## GlobalID support
<ide>
<ide> Active Job supports [GlobalID serialization](https://github.com/rails/globalid/) for parameters. This makes it possible
<ide> to pass live Active Record objects to your job instead of class/id pairs, which
<ide> end
<ide> This works with any class that mixes in GlobalID::Identification, which
<ide> by default has been mixed into Active Record classes.
<ide>
<del>### Serializers
<del>
<del>You can extend list of supported types for arguments. You just need to define your own serializer.
<del>
<del>```ruby
<del>class MySpecialSerializer
<del> class << self
<del> # Check if this object should be serialized using this serializer
<del> def serialize?(argument)
<del> object.is_a? MySpecialValueObject
<del> end
<del>
<del> # Convert an object to a simpler representative using supported object types.
<del> # The recommended representative is a Hash with a specific key. Keys can be of basic types only
<del> def serialize(object)
<del> {
<del> key => ActiveJob::Serializers.serialize(object.value)
<del> 'another_attribute' => ActiveJob::Serializers.serialize(object.another_attribute)
<del> }
<del> end
<del>
<del> # Check if this serialized value be deserialized using this serializer
<del> def deserialize?(argument)
<del> object.is_a?(Hash) && object.keys == [key, 'another_attribute']
<del> end
<del>
<del> # Convert serialized value into a proper object
<del> def deserialize(object)
<del> value = ActiveJob::Serializers.deserialize(object[key])
<del> another_attribute = ActiveJob::Serializers.deserialize(object['another_attribute'])
<del> MySpecialValueObject.new value, another_attribute
<del> end
<del>
<del> # Define this method if you are using a hash as a representative.
<del> # This key will be added to a list of restricted keys for hashes. Use basic types only
<del> def key
<del> "_aj_custom_dummy_value_object"
<del> end
<del> end
<del>end
<del>```
<del>
<del>And now you just need to add this serializer to a list:
<del>
<del>```ruby
<del>ActiveJob::Base.add_serializers(MySpecialSerializer)
<del>```
<ide>
<ide> ## Supported queueing systems
<ide>
<ide><path>activejob/lib/active_job/serializers/base_serializer.rb
<ide>
<ide> module ActiveJob
<ide> module Serializers
<add> # Implement the basic interface for Active Job arguments serializers.
<ide> class BaseSerializer
<ide> include Singleton
<ide>
<ide> class << self
<ide> delegate :serialize?, :deserialize?, :serialize, :deserialize, to: :instance
<ide> end
<ide>
<add> # Determines if an argument should be serialized by a serializer.
<ide> def serialize?(argument)
<ide> argument.is_a?(klass)
<ide> end
<ide>
<add> # Determines if an argument should be deserialized by a serializer.
<ide> def deserialize?(_argument)
<ide> raise NotImplementedError
<ide> end
<ide>
<add> # Serializes an argument to a JSON primitive type.
<ide> def serialize(_argument)
<ide> raise NotImplementedError
<ide> end
<ide>
<add> # Deserilizes an argument form a JSON primiteve type.
<ide> def deserialize(_argument)
<ide> raise NotImplementedError
<ide> end
<ide>
<ide> protected
<ide>
<add> # The class of the object that will be serialized.
<ide> def klass
<ide> raise NotImplementedError
<ide> end
<ide><path>activejob/lib/active_job/serializers/object_serializer.rb
<ide>
<ide> module ActiveJob
<ide> module Serializers
<add> # Base class for serializing and deserializing custom times.
<add> #
<add> # Example
<add> #
<add> # class MoneySerializer < ActiveJob::Serializers::ObjectSerializer
<add> # def serialize(money)
<add> # super("cents" => money.cents, "currency" => money.currency)
<add> # end
<add> #
<add> # def deserialize(hash)
<add> # Money.new(hash["cents"], hash["currency"])
<add> # end
<add> #
<add> # private
<add> #
<add> # def klass
<add> # Money
<add> # end
<add> # end
<ide> class ObjectSerializer < BaseSerializer
<ide> def serialize(hash)
<ide> { OBJECT_SERIALIZER_KEY => self.class.name }.merge!(hash)
<ide><path>guides/source/active_job_basics.md
<ide> Supported types for arguments
<ide> ActiveJob supports the following types of arguments by default:
<ide>
<ide> - Basic types (`NilClass`, `String`, `Integer`, `Fixnum`, `Bignum`, `Float`, `BigDecimal`, `TrueClass`, `FalseClass`)
<add> - `Symbol
<add> - `ActiveSupport::Duration`
<add> - `Date`
<add> - `Time`
<add> - `DateTime`
<add> - `ActiveSupport::TimeWithZone`
<ide> - `Hash`. Keys should be of `String` or `Symbol` type
<ide> - `ActiveSupport::HashWithIndifferentAccess`
<ide> - `Array`
<ide> by default has been mixed into Active Record classes.
<ide> You can extend list of supported types for arguments. You just need to define your own serializer.
<ide>
<ide> ```ruby
<del>class MySpecialSerializer
<del> class << self
<del> # Check if this object should be serialized using this serializer
<add>class MoneySerializer < ActiveJob::Serializers::ObjectSerializer
<add> # Check if this object should be serialized using this serializer.
<ide> def serialize?(argument)
<del> argument.is_a? MySpecialValueObject
<add> argument.is_a? Money
<ide> end
<ide>
<ide> # Convert an object to a simpler representative using supported object types.
<del> # The recommended representative is a Hash with a specific key. Keys can be of basic types only
<add> # The recommended representative is a Hash with a specific key. Keys can be of basic types only.
<add> # You should call `super` to add the custom serializer type to the hash
<ide> def serialize(object)
<del> {
<del> key => ActiveJob::Serializers.serialize(object.value)
<del> 'another_attribute' => ActiveJob::Serializers.serialize(object.another_attribute)
<del> }
<add> super(
<add> "cents" => object.cents,
<add> "currency" => object.currency
<add> )
<ide> end
<ide>
<del> # Check if this serialized value be deserialized using this serializer
<add> # Check if this serialized value be deserialized using this serializer.
<add> # ActiveJob::Serializers::ObjectSerializer#deserialize? already take care of this.
<ide> def deserialize?(argument)
<del> argument.is_a?(Hash) && argument.keys == [key, 'another_attribute']
<add> super
<ide> end
<ide>
<ide> # Convert serialized value into a proper object
<del> def deserialize(object)
<del> value = ActiveJob::Serializers.deserialize(object[key])
<del> another_attribute = ActiveJob::Serializers.deserialize(object['another_attribute'])
<del> MySpecialValueObject.new value, another_attribute
<del> end
<del>
<del> # Define this method if you are using a hash as a representative.
<del> # This key will be added to a list of restricted keys for hashes. Use basic types only
<del> def key
<del> "_aj_custom_dummy_value_object"
<add> def deserialize(hash)
<add> Money.new hash["cents"], hash["currency"]
<ide> end
<ide> end
<ide> end
<ide> end
<ide> And now you just need to add this serializer to a list:
<ide>
<ide> ```ruby
<del>ActiveJob::Base.add_serializers(MySpecialSerializer)
<add>Rails.application.config.active_job.custom_serializers << MySpecialSerializer
<ide> ```
<ide>
<ide> | 4 |
Text | Text | add file analysis to the active storage guide | ff1f8b02d6ad789a9de22a1c48712fb44b87d6bd | <ide><path>guides/source/active_storage_overview.md
<ide> message.video.open do |file|
<ide> end
<ide> ```
<ide>
<add>Analyzing Files
<add>---------------
<add>
<add>Active Storage [analyzes](https://api.rubyonrails.org/classes/ActiveStorage/Blob/Analyzable.html#method-i-analyze) files once they've been uploaded by queuing a job in Active Job. Analyzed files will store additional information in the metadata hash, including `analyzed: true`. You can check whether a blob has been analyzed by calling `analyzed?` on it.
<add>
<add>Image analysis provides `width` and `height` attributes. Video analysis provides these, as well as `duration`, `angle`, and `display_aspect_ratio`.
<add>
<add>Analysis requires the `mini_magick` gem. Video analysis also requires the [FFmpeg](https://www.ffmpeg.org/) library, which you must include separately.
<add>
<ide> Transforming Images
<ide> -------------------
<ide>
<del>To create a variation of the image, call `variant` on the `Blob`. You can pass
<del>any transformation to the method supported by the processor. The default
<del>processor is [MiniMagick](https://github.com/minimagick/minimagick), but you
<del>can also use [Vips](https://www.rubydoc.info/gems/ruby-vips/Vips/Image).
<del>
<ide> To enable variants, add the `image_processing` gem to your `Gemfile`:
<ide>
<ide> ```ruby
<del>gem 'image_processing', '~> 1.2'
<add>gem 'image_processing'
<ide> ```
<ide>
<add>To create a variation of an image, call `variant` on the `Blob`. You can pass any transformation to the method supported by the processor. The default processor for Active Storage is MiniMagick, but you can also use [Vips](https://www.rubydoc.info/gems/ruby-vips/Vips/Image).
<add>
<ide> When the browser hits the variant URL, Active Storage will lazily transform the
<ide> original blob into the specified format and redirect to its new service
<ide> location. | 1 |
Python | Python | update description of orderingfilter | 617745eca027dc17c37718a67f82700caef5be3a | <ide><path>rest_framework/filters.py
<ide> class OrderingFilter(BaseFilterBackend):
<ide> def get_ordering(self, request):
<ide> """
<ide> Ordering is set by a comma delimited ?ordering=... query parameter.
<add>
<add> The `ordering` query parameter can be overridden by setting
<add> the `ordering_param` value on the OrderingFilter or by
<add> specifying an `ORDERING_PARAM` value in the API settings.
<ide> """
<ide> params = request.QUERY_PARAMS.get(self.ordering_param)
<ide> if params: | 1 |
Javascript | Javascript | fix failing async tests in node 10 | b753f76a74644dd19e7a29f8aa4e8c759190f9ef | <ide><path>packages/react-dom/src/__tests__/ReactServerRenderingHydration-test.js
<ide> describe('ReactDOMServerHydration', () => {
<ide> });
<ide>
<ide> it('should be able to use lazy components after hydrating', async () => {
<del> async function fakeImport(result) {
<del> return {default: result};
<del> }
<del>
<ide> const Lazy = React.lazy(
<ide> () =>
<ide> new Promise(resolve => {
<ide> setTimeout(
<ide> () =>
<del> resolve(
<del> fakeImport(function World() {
<add> resolve({
<add> default: function World() {
<ide> return 'world';
<del> }),
<del> ),
<add> },
<add> }),
<ide> 1000,
<ide> );
<ide> }),
<ide> describe('ReactDOMServerHydration', () => {
<ide> expect(element.textContent).toBe('Hello loading');
<ide>
<ide> jest.runAllTimers();
<del> await Lazy;
<add> await Promise.resolve();
<ide> expect(element.textContent).toBe('Hello world');
<ide> });
<ide> });
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalPerf-test.internal.js
<ide> describe('ReactDebugFiberPerf', () => {
<ide> return <span />;
<ide> }
<ide>
<del> async function fakeImport(result) {
<add> function fakeImport(result) {
<ide> return {default: result};
<ide> }
<ide>
<ide> describe('ReactDebugFiberPerf', () => {
<ide> return <div />;
<ide> }),
<ide> );
<del> await LazyFoo;
<add>
<add> await Promise.resolve();
<ide>
<ide> ReactNoop.render(
<ide> <Parent>
<ide><path>packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js
<ide> describe('ReactLazy', () => {
<ide> return fakeImport(Foo);
<ide> });
<ide>
<del> const LazyForwardRef = lazy(async () => {
<add> const LazyForwardRef = lazy(() => {
<ide> class Bar extends React.Component {
<ide> render() {
<ide> return <Text text="Bar" />; | 3 |
Javascript | Javascript | remove donation prevention | d7c4fd7fea433087a9104515079fda961c6d65c3 | <ide><path>client/src/client-only-routes/ShowCertification.js
<ide> import {
<ide> showCert,
<ide> userFetchStateSelector,
<ide> usernameSelector,
<del> isDonatingSelector,
<del> isDonationRequestedSelector,
<del> preventDonationRequests
<add> isDonatingSelector
<ide> } from '../redux';
<ide> import validCertNames from '../../utils/validCertNames';
<ide> import { createFlashMessage } from '../components/Flash/redux';
<ide> const propTypes = {
<ide> errored: PropTypes.bool
<ide> }),
<ide> isDonating: PropTypes.bool,
<del> isDonationRequested: PropTypes.bool,
<ide> issueDate: PropTypes.string,
<del> preventDonationRequests: PropTypes.func,
<ide> showCert: PropTypes.func.isRequired,
<ide> signedInUserName: PropTypes.string,
<ide> userFetchState: PropTypes.shape({
<ide> const mapStateToProps = (state, { certName }) => {
<ide> usernameSelector,
<ide> userFetchStateSelector,
<ide> isDonatingSelector,
<del> isDonationRequestedSelector,
<del> (
<del> cert,
<del> fetchState,
<del> signedInUserName,
<del> userFetchState,
<del> isDonating,
<del> isDonationRequested
<del> ) => ({
<add> (cert, fetchState, signedInUserName, userFetchState, isDonating) => ({
<ide> cert,
<ide> fetchState,
<ide> validCertName,
<ide> signedInUserName,
<ide> userFetchState,
<del> isDonating,
<del> isDonationRequested
<add> isDonating
<ide> })
<ide> );
<ide> };
<ide>
<ide> const mapDispatchToProps = dispatch =>
<del> bindActionCreators(
<del> { createFlashMessage, showCert, preventDonationRequests },
<del> dispatch
<del> );
<add> bindActionCreators({ createFlashMessage, showCert }, dispatch);
<ide>
<ide> class ShowCertification extends Component {
<ide> componentDidMount() {
<ide> class ShowCertification extends Component {
<ide> validCertName,
<ide> createFlashMessage,
<ide> certName,
<del> preventDonationRequests,
<ide> signedInUserName,
<ide> isDonating,
<del> isDonationRequested,
<ide> userFetchState
<ide> } = this.props;
<ide>
<ide> class ShowCertification extends Component {
<ide>
<ide> let conditionalDonationMessage = '';
<ide>
<del> if (
<del> userComplete &&
<del> signedInUserName === username &&
<del> !isDonating &&
<del> !isDonationRequested
<del> ) {
<add> if (userComplete && signedInUserName === username && !isDonating) {
<ide> conditionalDonationMessage = (
<ide> <Grid>
<ide> <Row className='certification-donation text-center'>
<ide> class ShowCertification extends Component {
<ide> around the world. Make a tax-deductible supporting donation to our
<ide> nonprofit today.
<ide> </p>
<del> <Link
<del> className={'btn'}
<del> onClick={preventDonationRequests}
<del> to={'/donate'}
<del> >
<add> <Link className={'btn'} to={'/donate'}>
<ide> Check out our donation dashboard
<ide> </Link>
<ide> </Row>
<ide><path>client/src/redux/donation-saga.js
<ide> import { put, select, takeEvery, delay } from 'redux-saga/effects';
<ide>
<ide> import {
<ide> openDonationModal,
<del> shouldRequestDonationSelector,
<del> preventDonationRequests
<add> preventDonationRequests,
<add> shouldRequestDonationSelector
<ide> } from './';
<ide>
<ide> function* showDonateModalSaga() {
<ide><path>client/src/redux/index.js
<ide> const initialState = {
<ide> canRequestDonation: false,
<ide> completionCount: 0,
<ide> currentChallengeId: store.get(CURRENT_CHALLENGE_KEY),
<del> donationRequested: false,
<ide> showCert: {},
<ide> showCertFetchState: {
<ide> ...defaultFetchState
<ide> export const completedChallengesSelector = state =>
<ide> userSelector(state).completedChallenges || [];
<ide> export const completionCountSelector = state => state[ns].completionCount;
<ide> export const currentChallengeIdSelector = state => state[ns].currentChallengeId;
<del>export const isDonationRequestedSelector = state => state[ns].donationRequested;
<ide> export const isDonatingSelector = state => userSelector(state).isDonating;
<ide>
<ide> export const isOnlineSelector = state => state[ns].isOnline;
<ide> export const signInLoadingSelector = state =>
<ide> export const showCertSelector = state => state[ns].showCert;
<ide> export const showCertFetchStateSelector = state => state[ns].showCertFetchState;
<ide>
<del>export const shouldRequestDonationSelector = state => {
<del> const isDonationRequested = isDonationRequestedSelector(state);
<del> const isDonating = isDonatingSelector(state);
<del> if (
<del> isDonationRequested === false &&
<del> isDonating === false &&
<del> state[ns].canRequestDonation
<del> ) {
<del> return true;
<del> }
<del> return false;
<del>};
<add>export const shouldRequestDonationSelector = state =>
<add> !isDonatingSelector(state) && state[ns].canRequestDonation;
<add>
<ide> export const userByNameSelector = username => state => {
<ide> const { user } = state[ns];
<ide> return username in user ? user[username] : {};
<ide> export const reducer = handleActions(
<ide> }),
<ide> [types.preventDonationRequests]: state => ({
<ide> ...state,
<del> donationRequested: true
<add> canRequestDonation: false
<ide> }),
<ide> [types.resetUserData]: state => ({
<ide> ...state, | 3 |
Python | Python | update parent package and version | 8fb574900a6680f8342487e32979829efa33a11a | <ide><path>spacy/about.py
<ide> # fmt: off
<del>__title__ = "spacy"
<del>__version__ = "3.0.0.dev14"
<add>__title__ = "spacy_nightly"
<add>__version__ = "3.0.0a0"
<ide> __release__ = True
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Python | Python | remove global variable with api auth backend | 7b23d4d01f35b693848fb3b2c482db66d91b658b | <ide><path>airflow/api/__init__.py
<ide> log = logging.getLogger(__name__)
<ide>
<ide>
<del>class ApiAuth: # pylint: disable=too-few-public-methods
<del> """Class to keep module of Authentication API """
<del> def __init__(self):
<del> self.api_auth = None
<del>
<del>
<del>API_AUTH = ApiAuth()
<del>
<del>
<ide> def load_auth():
<ide> """Loads authentication backend"""
<ide> auth_backend = 'airflow.api.auth.backend.default'
<ide> def load_auth():
<ide> pass
<ide>
<ide> try:
<del> API_AUTH.api_auth = import_module(auth_backend)
<add> return import_module(auth_backend)
<ide> except ImportError as err:
<ide> log.critical(
<ide> "Cannot import %s for API authentication due to: %s",
<ide><path>airflow/api/auth/backend/default.py
<ide> # under the License.
<ide> """Default authentication backend - everything is allowed"""
<ide> from functools import wraps
<del>from typing import Callable, Optional, TypeVar, cast
<add>from typing import Callable, TypeVar, cast
<ide>
<ide> from airflow.typing_compat import Protocol
<ide>
<ide> def handle_response(self, _):
<ide> ...
<ide>
<ide>
<del>CLIENT_AUTH = None # type: Optional[ClientAuthProtocol]
<del>
<del>
<ide> def init_app(_):
<ide> """Initializes authentication backend"""
<ide>
<ide><path>airflow/api/client/__init__.py
<ide> def get_current_api_client() -> Client:
<ide> api_module = import_module(conf.get('cli', 'api_client')) # type: Any
<ide> api_client = api_module.Client(
<ide> api_base_url=conf.get('cli', 'endpoint_url'),
<del> auth=api.API_AUTH.api_auth.CLIENT_AUTH
<add> auth=api.load_auth()
<ide> )
<ide> return api_client
<ide><path>airflow/settings.py
<ide> from sqlalchemy.orm.session import Session as SASession
<ide> from sqlalchemy.pool import NullPool
<ide>
<del># noinspection PyUnresolvedReferences
<del>from airflow import api
<ide> # pylint: disable=unused-import
<ide> from airflow.configuration import AIRFLOW_HOME, WEBSERVER_CONFIG, conf # NOQA F401
<ide> from airflow.logging_config import configure_logging
<ide> def initialize():
<ide> # The webservers import this file from models.py with the default settings.
<ide> configure_orm()
<ide> configure_action_logging()
<del> api.load_auth()
<ide>
<ide> # Ensure we close DB connections at scheduler and gunicon worker terminations
<ide> atexit.register(dispose_orm)
<ide><path>airflow/www/api/experimental/endpoints.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide> import logging
<add>from functools import wraps
<add>from typing import Callable, TypeVar, cast
<ide>
<del>from flask import Blueprint, g, jsonify, request, url_for
<add>from flask import Blueprint, current_app, g, jsonify, request, url_for
<ide>
<del>import airflow.api
<ide> from airflow import models
<ide> from airflow.api.common.experimental import delete_dag as delete, pool as pool_api, trigger_dag as trigger
<ide> from airflow.api.common.experimental.get_code import get_code
<ide>
<ide> log = logging.getLogger(__name__)
<ide>
<del>requires_authentication = airflow.api.API_AUTH.api_auth.requires_authentication
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<add>
<add>
<add>def requires_authentication(function: T):
<add> """Decorator for functions that require authentication"""
<add> @wraps(function)
<add> def decorated(*args, **kwargs):
<add> return current_app.api_auth.requires_authentication(function)(*args, **kwargs)
<add>
<add> return cast(T, decorated)
<add>
<ide>
<ide> api_experimental = Blueprint('api_experimental', __name__)
<ide>
<ide><path>airflow/www/extensions/init_security.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<add>import logging
<add>from importlib import import_module
<ide>
<ide> from airflow.configuration import conf
<add>from airflow.exceptions import AirflowConfigException, AirflowException
<add>
<add>log = logging.getLogger(__name__)
<ide>
<ide>
<ide> def init_xframe_protection(app):
<ide> def apply_caching(response):
<ide>
<ide>
<ide> def init_api_experimental_auth(app):
<del> """Initialize authorization in Experimental API"""
<del> from airflow import api
<del>
<del> api.load_auth()
<del> api.API_AUTH.api_auth.init_app(app)
<add> """Loads authentication backend"""
<add> auth_backend = 'airflow.api.auth.backend.default'
<add> try:
<add> auth_backend = conf.get("api", "auth_backend")
<add> except AirflowConfigException:
<add> pass
<add>
<add> try:
<add> app.api_auth = import_module(auth_backend)
<add> app.api_auth.init_app(app)
<add> except ImportError as err:
<add> log.critical(
<add> "Cannot import %s for API authentication due to: %s",
<add> auth_backend, err
<add> )
<add> raise AirflowException(err)
<ide><path>airflow/www/extensions/init_views.py
<ide> def init_api_experimental(app):
<ide> """Initialize Experimental API"""
<ide> from airflow.www.api.experimental import endpoints
<ide>
<del> # required for testing purposes otherwise the module retains
<del> # a link to the default_auth
<del> if app.config['TESTING']:
<del> import importlib
<del>
<del> importlib.reload(endpoints)
<del>
<ide> app.register_blueprint(endpoints.api_experimental, url_prefix='/api/experimental')
<ide> app.extensions['csrf'].exempt(endpoints.api_experimental) | 7 |
Go | Go | remove https prefix from registry | 57d751c3770194ff867ebace36eb1be7d72d2fe9 | <ide><path>registry/registry.go
<ide> func (r *Registry) GetRemoteTags(registries []string, repository string, token [
<ide> repository = "library/" + repository
<ide> }
<ide> for _, host := range registries {
<del> endpoint := fmt.Sprintf("https://%s/v1/repositories/%s/tags", host, repository)
<add> endpoint := fmt.Sprintf("%s/v1/repositories/%s/tags", host, repository)
<ide> req, err := r.opaqueRequest("GET", endpoint, nil)
<ide> if err != nil {
<ide> return nil, err
<ide> func (r *Registry) GetRepositoryData(remote string) (*RepositoryData, error) {
<ide>
<ide> // Push a local image to the registry
<ide> func (r *Registry) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, registry string, token []string) error {
<del> registry = "https://" + registry + "/v1"
<add> registry = registry + "/v1"
<ide> // FIXME: try json with UTF8
<ide> req, err := http.NewRequest("PUT", registry+"/images/"+imgData.ID+"/json", strings.NewReader(string(jsonRaw)))
<ide> if err != nil {
<ide> func (r *Registry) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, regis
<ide> }
<ide>
<ide> func (r *Registry) PushImageLayerRegistry(imgId string, layer io.Reader, registry string, token []string) error {
<del> registry = "https://" + registry + "/v1"
<add> registry = registry + "/v1"
<ide> req, err := http.NewRequest("PUT", registry+"/images/"+imgId+"/layer", layer)
<ide> if err != nil {
<ide> return err
<ide> func (r *Registry) opaqueRequest(method, urlStr string, body io.Reader) (*http.R
<ide> func (r *Registry) PushRegistryTag(remote, revision, tag, registry string, token []string) error {
<ide> // "jsonify" the string
<ide> revision = "\"" + revision + "\""
<del> registry = "https://" + registry + "/v1"
<add> registry = registry + "/v1"
<ide>
<ide> req, err := r.opaqueRequest("PUT", registry+"/repositories/"+remote+"/tags/"+tag, strings.NewReader(revision))
<ide> if err != nil {
<ide><path>server.go
<ide> func (srv *Server) pullRepository(r *registry.Registry, out io.Writer, local, re
<ide> out.Write(sf.FormatStatus("Pulling image %s (%s) from %s", img.ID, img.Tag, remote))
<ide> success := false
<ide> for _, ep := range repoData.Endpoints {
<del> if err := srv.pullImage(r, out, img.ID, "https://"+ep+"/v1", repoData.Tokens, sf); err != nil {
<add> if err := srv.pullImage(r, out, img.ID, ep+"/v1", repoData.Tokens, sf); err != nil {
<ide> out.Write(sf.FormatStatus("Error while retrieving image for tag: %s (%s); checking next endpoint", askedTag, err))
<ide> continue
<ide> }
<ide> func (srv *Server) ImagePush(name, endpoint string, out io.Writer, sf *utils.Str
<ide> if err2 != nil {
<ide> return err2
<ide> }
<add>
<ide> if err != nil {
<ide> out.Write(sf.FormatStatus("The push refers to a repository [%s] (len: %d)", name, len(srv.runtime.repositories.Repositories[name])))
<ide> // If it fails, try to get the repository | 2 |
PHP | PHP | fix misordered assertequals arguments | 093a6f8628d15914ebc0c3af8d0fc1dabe9373f6 | <ide><path>tests/Auth/AuthAccessGateTest.php
<ide> public function testResponseReturnsResponseWhenAbilityDenied()
<ide> $this->assertSame('Not allowed to view as it is not published.', $response->message());
<ide> $this->assertFalse($response->allowed());
<ide> $this->assertTrue($response->denied());
<del> $this->assertEquals($response->code(), 'unpublished');
<add> $this->assertEquals('unpublished', $response->code());
<ide> }
<ide>
<ide> public function testAuthorizeReturnsAnAllowedResponseForATruthyReturn()
<ide><path>tests/Auth/AuthorizeMiddlewareTest.php
<ide> public function testSimpleAbilityAuthorized()
<ide>
<ide> $response = $this->router->dispatch(Request::create('dashboard', 'GET'));
<ide>
<del> $this->assertEquals($response->content(), 'success');
<add> $this->assertEquals('success', $response->content());
<ide> }
<ide>
<ide> public function testSimpleAbilityWithStringParameter()
<ide> public function testSimpleAbilityWithStringParameter()
<ide>
<ide> $response = $this->router->dispatch(Request::create('dashboard', 'GET'));
<ide>
<del> $this->assertEquals($response->content(), 'success');
<add> $this->assertEquals('success', $response->content());
<ide> }
<ide>
<ide> public function testSimpleAbilityWithNullParameter()
<ide> public function testSimpleAbilityWithOptionalParameter()
<ide> ]);
<ide>
<ide> $response = $this->router->dispatch(Request::create('posts/1/comments', 'GET'));
<del> $this->assertEquals($response->content(), 'success');
<add> $this->assertEquals('success', $response->content());
<ide>
<ide> $response = $this->router->dispatch(Request::create('comments', 'GET'));
<del> $this->assertEquals($response->content(), 'success');
<add> $this->assertEquals('success', $response->content());
<ide> }
<ide>
<ide> public function testSimpleAbilityWithStringParameterFromRouteParameter()
<ide> public function testSimpleAbilityWithStringParameterFromRouteParameter()
<ide>
<ide> $response = $this->router->dispatch(Request::create('dashboard/true', 'GET'));
<ide>
<del> $this->assertEquals($response->content(), 'success');
<add> $this->assertEquals('success', $response->content());
<ide> }
<ide>
<ide> public function testModelTypeUnauthorized()
<ide> public function testModelTypeUnauthorized()
<ide> $this->expectExceptionMessage('This action is unauthorized.');
<ide>
<ide> $this->gate()->define('create', function ($user, $model) {
<del> $this->assertEquals($model, 'App\User');
<add> $this->assertEquals('App\User', $model);
<ide>
<ide> return false;
<ide> });
<ide> public function testModelTypeUnauthorized()
<ide> public function testModelTypeAuthorized()
<ide> {
<ide> $this->gate()->define('create', function ($user, $model) {
<del> $this->assertEquals($model, 'App\User');
<add> $this->assertEquals('App\User', $model);
<ide>
<ide> return true;
<ide> });
<ide> public function testModelTypeAuthorized()
<ide>
<ide> $response = $this->router->dispatch(Request::create('users/create', 'GET'));
<ide>
<del> $this->assertEquals($response->content(), 'success');
<add> $this->assertEquals('success', $response->content());
<ide> }
<ide>
<ide> public function testModelUnauthorized()
<ide> public function testModelAuthorized()
<ide>
<ide> $response = $this->router->dispatch(Request::create('posts/1/edit', 'GET'));
<ide>
<del> $this->assertEquals($response->content(), 'success');
<add> $this->assertEquals('success', $response->content());
<ide> }
<ide>
<ide> public function testModelInstanceAsParameter()
<ide><path>tests/Cache/CacheRepositoryTest.php
<ide> public function testRegisterMacroWithNonStaticCall()
<ide> $repo::macro(__CLASS__, function () {
<ide> return 'Taylor';
<ide> });
<del> $this->assertEquals($repo->{__CLASS__}(), 'Taylor');
<add> $this->assertEquals('Taylor', $repo->{__CLASS__}());
<ide> }
<ide>
<ide> public function testForgettingCacheKey()
<ide><path>tests/Container/ContainerTest.php
<ide> public function testGetAlias()
<ide> {
<ide> $container = new Container;
<ide> $container->alias('ConcreteStub', 'foo');
<del> $this->assertEquals($container->getAlias('foo'), 'ConcreteStub');
<add> $this->assertEquals('ConcreteStub', $container->getAlias('foo'));
<ide> }
<ide>
<ide> public function testItThrowsExceptionWhenAbstractIsSameAsAlias()
<ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> public function testUpdateOrCreate()
<ide> );
<ide>
<ide> $this->assertSame('Mohamed Said', $user3->name);
<del> $this->assertEquals(EloquentTestUser::count(), 2);
<add> $this->assertEquals(2, EloquentTestUser::count());
<ide> }
<ide>
<ide> public function testUpdateOrCreateOnDifferentConnection()
<ide> public function testUpdateOrCreateOnDifferentConnection()
<ide> ['name' => 'Mohamed Said']
<ide> );
<ide>
<del> $this->assertEquals(EloquentTestUser::count(), 1);
<del> $this->assertEquals(EloquentTestUser::on('second_connection')->count(), 2);
<add> $this->assertEquals(1, EloquentTestUser::count());
<add> $this->assertEquals(2, EloquentTestUser::on('second_connection')->count());
<ide> }
<ide>
<ide> public function testCheckAndCreateMethodsOnMultiConnections()
<ide> public function testEagerLoadedMorphToRelationsOnAnotherDatabaseConnection()
<ide> $defaultConnectionPost = EloquentTestPhoto::with('imageable')->first()->imageable;
<ide> $secondConnectionPost = EloquentTestPhoto::on('second_connection')->with('imageable')->first()->imageable;
<ide>
<del> $this->assertEquals($defaultConnectionPost->name, 'Default Connection Post');
<del> $this->assertEquals($secondConnectionPost->name, 'Second Connection Post');
<add> $this->assertEquals('Default Connection Post', $defaultConnectionPost->name);
<add> $this->assertEquals('Second Connection Post', $secondConnectionPost->name);
<ide> }
<ide>
<ide> public function testBelongsToManyCustomPivot()
<ide><path>tests/Database/DatabaseSchemaBuilderTest.php
<ide> public function testGetColumnTypeAddsPrefix()
<ide> $column->shouldReceive('getType')->once()->andReturn($type);
<ide> $type->shouldReceive('getName')->once()->andReturn('integer');
<ide>
<del> $this->assertEquals($builder->getColumnType('users', 'id'), 'integer');
<add> $this->assertEquals('integer', $builder->getColumnType('users', 'id'));
<ide> }
<ide> }
<ide><path>tests/Events/EventsSubscriberTest.php
<ide> public function testEventSubscribeCanReturnMappings()
<ide> $d->subscribe(DeclarativeSubscriber::class);
<ide>
<ide> $d->dispatch('myEvent1');
<del> $this->assertEquals(DeclarativeSubscriber::$string, 'L1_L2_');
<add> $this->assertEquals('L1_L2_', DeclarativeSubscriber::$string);
<ide>
<ide> $d->dispatch('myEvent2');
<del> $this->assertEquals(DeclarativeSubscriber::$string, 'L1_L2_L3');
<add> $this->assertEquals('L1_L2_L3', DeclarativeSubscriber::$string);
<ide> }
<ide> }
<ide>
<ide><path>tests/Foundation/FoundationApplicationTest.php
<ide> public function testDeferredServiceDontRunWhenInstanceSet()
<ide> $app->setDeferredServices(['foo' => ApplicationDeferredServiceProviderStub::class]);
<ide> $app->instance('foo', 'bar');
<ide> $instance = $app->make('foo');
<del> $this->assertEquals($instance, 'bar');
<add> $this->assertEquals('bar', $instance);
<ide> }
<ide>
<ide> public function testDeferredServicesAreLazilyInitialized()
<ide> public function testDeferredServiceIsLoadedWhenAccessingImplementationThroughInt
<ide> SampleImplementation::class => SampleImplementationDeferredServiceProvider::class,
<ide> ]);
<ide> $instance = $app->make(SampleInterface::class);
<del> $this->assertEquals($instance->getPrimitive(), 'foo');
<add> $this->assertEquals('foo', $instance->getPrimitive());
<ide> }
<ide>
<ide> public function testEnvironment()
<ide><path>tests/Http/HttpRequestTest.php
<ide> public function testMagicMethods()
<ide> $request = Request::create('/', 'GET', ['foo' => 'bar', 'empty' => '']);
<ide>
<ide> // Parameter 'foo' is 'bar', then it ISSET and is NOT EMPTY.
<del> $this->assertEquals($request->foo, 'bar');
<del> $this->assertEquals(isset($request->foo), true);
<del> $this->assertEquals(empty($request->foo), false);
<add> $this->assertEquals('bar', $request->foo);
<add> $this->assertEquals(true, isset($request->foo));
<add> $this->assertEquals(false, empty($request->foo));
<ide>
<ide> // Parameter 'empty' is '', then it ISSET and is EMPTY.
<del> $this->assertEquals($request->empty, '');
<add> $this->assertEquals('', $request->empty);
<ide> $this->assertTrue(isset($request->empty));
<ide> $this->assertEmpty($request->empty);
<ide>
<ide> // Parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY.
<del> $this->assertEquals($request->undefined, null);
<del> $this->assertEquals(isset($request->undefined), false);
<del> $this->assertEquals(empty($request->undefined), true);
<add> $this->assertEquals(null, $request->undefined);
<add> $this->assertEquals(false, isset($request->undefined));
<add> $this->assertEquals(true, empty($request->undefined));
<ide>
<ide> // Simulates Route parameters.
<ide> $request = Request::create('/example/bar', 'GET', ['xyz' => 'overwritten']);
<ide> public function testMagicMethods()
<ide> // Router parameter 'foo' is 'bar', then it ISSET and is NOT EMPTY.
<ide> $this->assertSame('bar', $request->foo);
<ide> $this->assertSame('bar', $request['foo']);
<del> $this->assertEquals(isset($request->foo), true);
<del> $this->assertEquals(empty($request->foo), false);
<add> $this->assertEquals(true, isset($request->foo));
<add> $this->assertEquals(false, empty($request->foo));
<ide>
<ide> // Router parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY.
<del> $this->assertEquals($request->undefined, null);
<del> $this->assertEquals(isset($request->undefined), false);
<del> $this->assertEquals(empty($request->undefined), true);
<add> $this->assertEquals(null, $request->undefined);
<add> $this->assertEquals(false, isset($request->undefined));
<add> $this->assertEquals(true, empty($request->undefined));
<ide>
<ide> // Special case: router parameter 'xyz' is 'overwritten' by QueryString, then it ISSET and is NOT EMPTY.
<ide> // Basically, QueryStrings have priority over router parameters.
<del> $this->assertEquals($request->xyz, 'overwritten');
<del> $this->assertEquals(isset($request->foo), true);
<del> $this->assertEquals(empty($request->foo), false);
<add> $this->assertEquals('overwritten', $request->xyz);
<add> $this->assertEquals(true, isset($request->foo));
<add> $this->assertEquals(false, empty($request->foo));
<ide>
<ide> // Simulates empty QueryString and Routes.
<ide> $request = Request::create('/', 'GET');
<ide> public function testMagicMethods()
<ide> });
<ide>
<ide> // Parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY.
<del> $this->assertEquals($request->undefined, null);
<del> $this->assertEquals(isset($request->undefined), false);
<del> $this->assertEquals(empty($request->undefined), true);
<add> $this->assertEquals(null, $request->undefined);
<add> $this->assertEquals(false, isset($request->undefined));
<add> $this->assertEquals(true, empty($request->undefined));
<ide>
<ide> // Special case: simulates empty QueryString and Routes, without the Route Resolver.
<ide> // It'll happen when you try to get a parameter outside a route.
<ide> $request = Request::create('/', 'GET');
<ide>
<ide> // Parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY.
<del> $this->assertEquals($request->undefined, null);
<del> $this->assertEquals(isset($request->undefined), false);
<del> $this->assertEquals(empty($request->undefined), true);
<add> $this->assertEquals(null, $request->undefined);
<add> $this->assertEquals(false, isset($request->undefined));
<add> $this->assertEquals(true, empty($request->undefined));
<ide> }
<ide>
<ide> public function testHttpRequestFlashCallsSessionFlashInputWithInputData()
<ide><path>tests/Integration/Foundation/FoundationHelpersTest.php
<ide> class FoundationHelpersTest extends TestCase
<ide> {
<ide> public function testRescue()
<ide> {
<del> $this->assertEquals(rescue(function () {
<del> throw new Exception;
<del> }, 'rescued!'), 'rescued!');
<del>
<del> $this->assertEquals(rescue(function () {
<del> throw new Exception;
<del> }, function () {
<del> return 'rescued!';
<del> }), 'rescued!');
<del>
<del> $this->assertEquals(rescue(function () {
<del> return 'no need to rescue';
<del> }, 'rescued!'), 'no need to rescue');
<add> $this->assertEquals(
<add> 'rescued!',
<add> rescue(function () {
<add> throw new Exception;
<add> }, 'rescued!')
<add> );
<add>
<add> $this->assertEquals(
<add> 'rescued!',
<add> rescue(function () {
<add> throw new Exception;
<add> }, function () {
<add> return 'rescued!';
<add> })
<add> );
<add>
<add> $this->assertEquals(
<add> 'no need to rescue',
<add> rescue(function () {
<add> return 'no need to rescue';
<add> }, 'rescued!')
<add> );
<ide>
<ide> $testClass = new class {
<ide> public function test(int $a)
<ide> public function test(int $a)
<ide> }
<ide> };
<ide>
<del> $this->assertEquals(rescue(function () use ($testClass) {
<del> $testClass->test([]);
<del> }, 'rescued!'), 'rescued!');
<add> $this->assertEquals(
<add> 'rescued!',
<add> rescue(function () use ($testClass) {
<add> $testClass->test([]);
<add> }, 'rescued!')
<add> );
<ide> }
<ide>
<ide> public function testMixReportsExceptionWhenAssetIsMissingFromManifest()
<ide><path>tests/Queue/QueueSqsQueueTest.php
<ide> public function testSizeProperlyReadsSqsQueueSize()
<ide> $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl);
<ide> $this->sqs->shouldReceive('getQueueAttributes')->once()->with(['QueueUrl' => $this->queueUrl, 'AttributeNames' => ['ApproximateNumberOfMessages']])->andReturn($this->mockedQueueAttributesResponseModel);
<ide> $size = $queue->size($this->queueName);
<del> $this->assertEquals($size, 1);
<add> $this->assertEquals(1, $size);
<ide> }
<ide>
<ide> public function testGetQueueProperlyResolvesUrlWithPrefix()
<ide><path>tests/Session/SessionStoreTest.php
<ide> public function testName()
<ide> $session = $this->getSession();
<ide> $this->assertEquals($session->getName(), $this->getSessionName());
<ide> $session->setName('foo');
<del> $this->assertEquals($session->getName(), 'foo');
<add> $this->assertEquals('foo', $session->getName());
<ide> }
<ide>
<ide> public function testKeyExists()
<ide><path>tests/Support/SupportArrTest.php
<ide> public function testDot()
<ide> $this->assertEquals(['foo.bar' => []], $array);
<ide>
<ide> $array = Arr::dot(['name' => 'taylor', 'languages' => ['php' => true]]);
<del> $this->assertEquals($array, ['name' => 'taylor', 'languages.php' => true]);
<add> $this->assertEquals(['name' => 'taylor', 'languages.php' => true], $array);
<ide> }
<ide>
<ide> public function testExcept()
<ide><path>tests/Support/SupportFluentTest.php
<ide> public function testArrayAccessToAttributes()
<ide> $fluent = new Fluent(['attributes' => '1']);
<ide>
<ide> $this->assertTrue(isset($fluent['attributes']));
<del> $this->assertEquals($fluent['attributes'], 1);
<add> $this->assertEquals(1, $fluent['attributes']);
<ide>
<ide> $fluent->attributes();
<ide>
<ide><path>tests/Validation/ValidationFactoryTest.php
<ide> public function testValidateCallsValidateOnTheValidator()
<ide> ['foo' => 'required']
<ide> );
<ide>
<del> $this->assertEquals($validated, ['foo' => 'bar']);
<add> $this->assertEquals(['foo' => 'bar'], $validated);
<ide> }
<ide>
<ide> public function testCustomResolverIsCalled()
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testInvalidMethod()
<ide> '*.name' => 'required',
<ide> ]);
<ide>
<del> $this->assertEquals($v->invalid(), [
<del> 1 => ['name' => null],
<del> 2 => ['name' => ''],
<del> ]);
<add> $this->assertEquals(
<add> [
<add> 1 => ['name' => null],
<add> 2 => ['name' => ''],
<add> ],
<add> $v->invalid()
<add> );
<ide>
<ide> $v = new Validator($trans,
<ide> [
<ide> public function testInvalidMethod()
<ide> 'name' => 'required',
<ide> ]);
<ide>
<del> $this->assertEquals($v->invalid(), [
<del> 'name' => '',
<del> ]);
<add> $this->assertEquals(
<add> [
<add> 'name' => '',
<add> ],
<add> $v->invalid()
<add> );
<ide> }
<ide>
<ide> public function testValidMethod()
<ide> public function testValidMethod()
<ide> '*.name' => 'required',
<ide> ]);
<ide>
<del> $this->assertEquals($v->valid(), [
<del> 0 => ['name' => 'John'],
<del> 3 => ['name' => 'Doe'],
<del> ]);
<add> $this->assertEquals(
<add> [
<add> 0 => ['name' => 'John'],
<add> 3 => ['name' => 'Doe'],
<add> ],
<add> $v->valid()
<add> );
<ide>
<ide> $v = new Validator($trans,
<ide> [
<ide> public function testValidMethod()
<ide> 'age' => 'required|int',
<ide> ]);
<ide>
<del> $this->assertEquals($v->valid(), [
<del> 'name' => 'Carlos',
<del> 'gender' => 'male',
<del> ]);
<add> $this->assertEquals(
<add> [
<add> 'name' => 'Carlos',
<add> 'gender' => 'male',
<add> ],
<add> $v->valid()
<add> );
<ide> }
<ide>
<ide> public function testNestedInvalidMethod()
<ide> public function testNestedInvalidMethod()
<ide> 'regex:/[A-F]{3}[0-9]{3}/',
<ide> ],
<ide> ]);
<del> $this->assertEquals($v->invalid(), [
<del> 'testinvalid' => '',
<del> 'records' => [
<del> 3 => 'ADCD23',
<add> $this->assertEquals(
<add> [
<add> 'testinvalid' => '',
<add> 'records' => [
<add> 3 => 'ADCD23',
<add> ],
<ide> ],
<del> ]);
<add> $v->invalid()
<add> );
<ide> }
<ide>
<ide> public function testMultipleFileUploads() | 16 |
Go | Go | update native driver to set rootfs | 532c29ef7deea38bed68506b785f067796a1836b | <ide><path>daemon/execdriver/native/create.go
<ide> func (d *driver) createContainer(c *execdriver.Command) (*libcontainer.Config, e
<ide> container.Cgroups.Name = c.ID
<ide> container.Cgroups.AllowedDevices = c.AllowedDevices
<ide> container.MountConfig.DeviceNodes = c.AutoCreatedDevices
<add> container.RootFs = c.Rootfs
<ide>
<ide> // check to see if we are running in ramdisk to disable pivot root
<ide> container.MountConfig.NoPivotRoot = os.Getenv("DOCKER_RAMDISK") != ""
<ide><path>daemon/execdriver/native/driver.go
<ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba
<ide> return -1, err
<ide> }
<ide>
<del> return namespaces.Exec(container, c.ProcessConfig.Stdin, c.ProcessConfig.Stdout, c.ProcessConfig.Stderr, c.ProcessConfig.Console, c.Rootfs, dataPath, args, func(container *libcontainer.Config, console, rootfs, dataPath, init string, child *os.File, args []string) *exec.Cmd {
<add> return namespaces.Exec(container, c.ProcessConfig.Stdin, c.ProcessConfig.Stdout, c.ProcessConfig.Stderr, c.ProcessConfig.Console, dataPath, args, func(container *libcontainer.Config, console, dataPath, init string, child *os.File, args []string) *exec.Cmd {
<ide> c.ProcessConfig.Path = d.initPath
<ide> c.ProcessConfig.Args = append([]string{
<ide> DriverName,
<ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba
<ide> c.ProcessConfig.ExtraFiles = []*os.File{child}
<ide>
<ide> c.ProcessConfig.Env = container.Env
<del> c.ProcessConfig.Dir = c.Rootfs
<add> c.ProcessConfig.Dir = container.RootFs
<ide>
<ide> return &c.ProcessConfig.Cmd
<ide> }, func() { | 2 |
Javascript | Javascript | fix xhtml regression. close gh-1375 | 2d4c0d5f375bcf59a5a0cd19c4562bd57f03fb1d | <ide><path>src/manipulation/support.js
<ide> define([
<ide> div = fragment.appendChild( document.createElement( "div" ) );
<ide>
<ide> // #11217 - WebKit loses check when the name is after the checked attribute
<del> div.innerHTML = "<input type='radio' checked name='t'/>";
<add> div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
<ide>
<ide> // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
<ide> // old WebKit doesn't clone checked state correctly in fragments | 1 |
Ruby | Ruby | convert accessibility test to spec | af8b91746c8ee67cc5c050fdd4182089171dd0ab | <ide><path>Library/Homebrew/cask/spec/cask/accessibility_spec.rb
<add>require "spec_helper"
<add>
<add># TODO: this test should be named after the corresponding class, once
<add># that class is abstracted from installer.rb.
<add>describe "Accessibility Access" do
<add> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-accessibility-access.rb") }
<add> let(:fake_system_command) { class_double(Hbc::SystemCommand) }
<add> let(:installer) { Hbc::Installer.new(cask, command: fake_system_command) }
<add>
<add> before(:each) do
<add> allow(MacOS).to receive(:version).and_return(MacOS::Version.new(macos_version))
<add> allow(installer).to receive(:bundle_identifier).and_return("com.example.BasicCask")
<add> end
<add>
<add> context "on MacOS 10.8 and below" do
<add> let(:macos_version) { "10.8" }
<add>
<add> it "can enable accessibility access in macOS releases prior to Mavericks" do
<add> expect(fake_system_command).to receive(:run!).with(
<add> "/usr/bin/touch",
<add> args: [Hbc.pre_mavericks_accessibility_dotfile],
<add> sudo: true
<add> )
<add>
<add> shutup do
<add> installer.enable_accessibility_access
<add> end
<add> end
<add>
<add> it "warns about disabling accessibility access on old macOS releases" do
<add> expect {
<add> installer.disable_accessibility_access
<add> }.to output(/Warning: Accessibility access cannot be disabled automatically on this version of macOS\./).to_stderr
<add> end
<add> end
<add>
<add> context "on MacOS 10.9" do
<add> let(:macos_version) { "10.9" }
<add>
<add> it "can enable accessibility access" do
<add> expect(fake_system_command).to receive(:run!).with(
<add> "/usr/bin/sqlite3",
<add> args: [Hbc.tcc_db, "INSERT OR REPLACE INTO access VALUES('kTCCServiceAccessibility','com.example.BasicCask',0,1,1,NULL);"],
<add> sudo: true
<add> )
<add>
<add> shutup do
<add> installer.enable_accessibility_access
<add> end
<add> end
<add>
<add> it "can disable accessibility access" do
<add> expect(fake_system_command).to receive(:run!).with(
<add> "/usr/bin/sqlite3",
<add> args: [Hbc.tcc_db, "DELETE FROM access WHERE client='com.example.BasicCask';"],
<add> sudo: true
<add> )
<add>
<add> shutup do
<add> installer.disable_accessibility_access
<add> end
<add> end
<add> end
<add>
<add> context "on MacOS 10.12 and above" do
<add> let(:macos_version) { "10.12" }
<add>
<add> it "warns about enabling accessibility access on new macOS releases" do
<add> expect {
<add> expect {
<add> installer.enable_accessibility_access
<add> }.to output.to_stdout
<add> }.to output(/Warning: Accessibility access cannot be enabled automatically on this version of macOS\./).to_stderr
<add> end
<add>
<add> it "warns about disabling accessibility access on new macOS releases" do
<add> expect {
<add> installer.disable_accessibility_access
<add> }.to output(/Warning: Accessibility access cannot be disabled automatically on this version of macOS\./).to_stderr
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/cask/test/cask/accessibility_test.rb
<del>require "test_helper"
<del>
<del># TODO: this test should be named after the corresponding class, once
<del># that class is abstracted from installer.rb.
<del>describe "Accessibility Access" do
<del> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-accessibility-access.rb") }
<del> let(:with_fake_command) { { command: Hbc::FakeSystemCommand } }
<del> let(:installer) { Hbc::Installer.new(cask, with_fake_command) }
<del>
<del> describe "install" do
<del> it "can enable accessibility access" do
<del> MacOS.stub :version, MacOS::Version.new("10.9") do
<del> installer.stub :bundle_identifier, "com.example.BasicCask" do
<del> Hbc::FakeSystemCommand.expects_command(
<del> ["/usr/bin/sudo", "-E", "--", "/usr/bin/sqlite3", Hbc.tcc_db, "INSERT OR REPLACE INTO access VALUES('kTCCServiceAccessibility','com.example.BasicCask',0,1,1,NULL);"]
<del> )
<del> shutup do
<del> installer.enable_accessibility_access
<del> end
<del> end
<del> end
<del> end
<del>
<del> it "can enable accessibility access in macOS releases prior to Mavericks" do
<del> MacOS.stub :version, MacOS::Version.new("10.8") do
<del> Hbc::FakeSystemCommand.expects_command(
<del> ["/usr/bin/sudo", "-E", "--", "/usr/bin/touch", Hbc.pre_mavericks_accessibility_dotfile]
<del> )
<del> shutup do
<del> installer.enable_accessibility_access
<del> end
<del> end
<del> end
<del>
<del> it "warns about enabling accessibility access on new macOS releases" do
<del> MacOS.stub :version, MacOS::Version.new("10.12") do
<del> installer.stub :bundle_identifier, "com.example.BasicCask" do
<del> capture_io { installer.enable_accessibility_access }[1]
<del> .must_match("Warning: Accessibility access cannot be enabled automatically on this version of macOS.")
<del> end
<del> end
<del> end
<del> end
<del>
<del> describe "uninstall" do
<del> it "can disable accessibility access" do
<del> MacOS.stub :version, MacOS::Version.new("10.9") do
<del> installer.stub :bundle_identifier, "com.example.BasicCask" do
<del> Hbc::FakeSystemCommand.expects_command(
<del> ["/usr/bin/sudo", "-E", "--", "/usr/bin/sqlite3", Hbc.tcc_db, "DELETE FROM access WHERE client='com.example.BasicCask';"]
<del> )
<del> shutup do
<del> installer.disable_accessibility_access
<del> end
<del> end
<del> end
<del> end
<del>
<del> it "warns about disabling accessibility access on old macOS releases" do
<del> MacOS.stub :version, MacOS::Version.new("10.8") do
<del> installer.stub :bundle_identifier, "com.example.BasicCask" do
<del> capture_io { installer.disable_accessibility_access }[1]
<del> .must_match("Warning: Accessibility access cannot be disabled automatically on this version of macOS.")
<del> end
<del> end
<del> end
<del>
<del> it "warns about disabling accessibility access on new macOS releases" do
<del> MacOS.stub :version, MacOS::Version.new("10.12") do
<del> installer.stub :bundle_identifier, "com.example.BasicCask" do
<del> capture_io { installer.disable_accessibility_access }[1]
<del> .must_match("Warning: Accessibility access cannot be disabled automatically on this version of macOS.")
<del> end
<del> end
<del> end
<del> end
<del>end | 2 |
PHP | PHP | add cursor mode to db and paginator (no conflict) | f358e0dcb4e8ac37bf19f4a707f45413068d7693 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> protected function ungroupedPaginate($paginator, $perPage, $columns)
<ide> return $paginator->make($this->get($columns)->all(), $total, $perPage);
<ide> }
<ide>
<add> /**
<add> * Get a paginator in cursor mode for the "select" statement.
<add> *
<add> * @param int $perPage
<add> * @param array $columns
<add> * @return \Illuminate\Pagination\Paginator
<add> */
<add> public function cursor($perPage = null, $columns = array('*'))
<add> {
<add> $paginator = $this->query->getConnection()->getPaginator();
<add>
<add> $page = $paginator->getCurrentPage();
<add> $perPage = $perPage ?: $this->model->getPerPage();
<add>
<add> // Use skip method to set correct offset and take perPage + 1 items.
<add> $this->query->skip(($page - 1) * $perPage)->take($perPage + 1);
<add>
<add> return $paginator->make($this->get($columns)->all(), $perPage);
<add> }
<add>
<ide> /**
<ide> * Update a record in the database.
<ide> *
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function getPaginationCount()
<ide> return $total;
<ide> }
<ide>
<add> /**
<add> * Get a paginator in cursor mode for the "select" statement.
<add> *
<add> * @param int $perPage
<add> * @param array $columns
<add> * @return \Illuminate\Pagination\Paginator
<add> */
<add> public function cursor($perPage = null, $columns = array('*'))
<add> {
<add> $paginator = $this->connection->getPaginator();
<add>
<add> $page = $paginator->getCurrentPage();
<add> $perPage = $perPage ?: $this->model->getPerPage();
<add>
<add> // Use skip method to set correct offset and take perPage + 1 items.
<add> $this->skip(($page - 1) * $perPage)->take($perPage + 1);
<add>
<add> return $paginator->make($this->get($columns), $perPage);
<add> }
<add>
<ide> /**
<ide> * Determine if any rows exist for the current query.
<ide> *
<ide><path>src/Illuminate/Pagination/Factory.php
<ide> protected function setupPaginationEnvironment()
<ide> *
<ide> * @param array $items
<ide> * @param int $total
<del> * @param int $perPage
<add> * @param mixed $perPage
<ide> * @return \Illuminate\Pagination\Paginator
<ide> */
<del> public function make(array $items, $total, $perPage)
<add> public function make(array $items, $total, $perPage = null)
<ide> {
<ide> $paginator = new Paginator($this, $items, $total, $perPage);
<ide>
<ide><path>src/Illuminate/Pagination/Paginator.php
<ide> class Paginator implements ArrayableInterface, ArrayAccess, Countable, IteratorA
<ide> */
<ide> protected $total;
<ide>
<add> /**
<add> * Item, array or object indicating if next page is available.
<add> *
<add> * @var mixed
<add> */
<add> protected $cursor;
<add>
<ide> /**
<ide> * The amount of items to show per page.
<ide> *
<ide> public function setupPaginationContext()
<ide> */
<ide> protected function calculateCurrentAndLastPages()
<ide> {
<del> $this->lastPage = (int) ceil($this->total / $this->perPage);
<add> if (is_null($this->total))
<add> {
<add> $page = $this->factory->getCurrentPage();
<add> $this->currentPage = $this->isValidPageNumber($page) ? (int) $page : 1;
<add>
<add> $this->lastPage = is_null($this->cursor) ? $this->currentPage : $this->currentPage + 1;
<add> }
<add> else
<add> {
<add> $this->lastPage = (int) ceil($this->total / $this->perPage);
<ide>
<del> $this->currentPage = $this->calculateCurrentPage($this->lastPage);
<add> $this->currentPage = $this->calculateCurrentPage($this->lastPage);
<add> }
<ide> }
<ide>
<ide> /**
<ide> public function getTotal()
<ide> return $this->total;
<ide> }
<ide>
<add> /**
<add> * Get cursor for this paginator.
<add> *
<add> * @return mixed
<add> */
<add> public function getCursor()
<add> {
<add> return $this->cursor;
<add> }
<add>
<ide> /**
<ide> * Set the base URL in use by the paginator.
<ide> *
<ide><path>tests/Database/DatabaseEloquentBuilderTest.php
<ide> public function testPaginateMethodWithGroupedQuery()
<ide> }
<ide>
<ide>
<add> public function testCursorMethod()
<add> {
<add> $query = $this->getMock('Illuminate\Database\Query\Builder', array('from', 'getConnection', 'skip', 'take'), array(
<add> m::mock('Illuminate\Database\ConnectionInterface'),
<add> m::mock('Illuminate\Database\Query\Grammars\Grammar'),
<add> m::mock('Illuminate\Database\Query\Processors\Processor'),
<add> ));
<add> $query->expects($this->once())->method('from')->will($this->returnValue('foo_table'));
<add> $builder = $this->getMock('Illuminate\Database\Eloquent\Builder', array('get'), array($query));
<add> $builder->setModel($this->getMockModel());
<add> $builder->getModel()->shouldReceive('getPerPage')->once()->andReturn(15);
<add> $conn = m::mock('stdClass');
<add> $paginator = m::mock('stdClass');
<add> $paginator->shouldReceive('getCurrentPage')->once()->andReturn(1);
<add> $conn->shouldReceive('getPaginator')->once()->andReturn($paginator);
<add> $query->expects($this->once())->method('getConnection')->will($this->returnValue($conn));
<add> $query->expects($this->once())->method('skip')->with(0)->will($this->returnValue($query));
<add> $query->expects($this->once())->method('take')->with(16)->will($this->returnValue($query));
<add> $builder->expects($this->once())->method('get')->with($this->equalTo(array('*')))->will($this->returnValue(new Collection(array('results'))));
<add> $paginator->shouldReceive('make')->once()->with(array('results'), 15)->andReturn(array('results'));
<add>
<add> $this->assertEquals(array('results'), $builder->cursor());
<add> }
<add>
<add>
<ide> public function testGetModelsProperlyHydratesModels()
<ide> {
<ide> $builder = m::mock('Illuminate\Database\Eloquent\Builder[get]', array($this->getMockQueryBuilder()));
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testGetPaginationCountGetsResultCount()
<ide> }
<ide>
<ide>
<add> public function testCursorCorrectlyCreatesPaginatorInstance()
<add> {
<add> $connection = m::mock('Illuminate\Database\ConnectionInterface');
<add> $grammar = m::mock('Illuminate\Database\Query\Grammars\Grammar');
<add> $processor = m::mock('Illuminate\Database\Query\Processors\Processor');
<add> $builder = $this->getMock('Illuminate\Database\Query\Builder', array('skip', 'take', 'get'), array($connection, $grammar, $processor));
<add> $paginator = m::mock('Illuminate\Pagination\Environment');
<add> $paginator->shouldReceive('getCurrentPage')->once()->andReturn(1);
<add> $connection->shouldReceive('getPaginator')->once()->andReturn($paginator);
<add> $builder->expects($this->once())->method('skip')->with($this->equalTo(0))->will($this->returnValue($builder));
<add> $builder->expects($this->once())->method('take')->with($this->equalTo(16))->will($this->returnValue($builder));
<add> $builder->expects($this->once())->method('get')->with($this->equalTo(array('*')))->will($this->returnValue(array('foo')));
<add> $paginator->shouldReceive('make')->once()->with(array('foo'), 15)->andReturn(array('results'));
<add>
<add> $this->assertEquals(array('results'), $builder->cursor(15, array('*')));
<add> }
<add>
<add>
<ide> public function testPluckMethodReturnsSingleColumn()
<ide> {
<ide> $builder = $this->getBuilder(); | 6 |
Javascript | Javascript | append js_require_ to require profile names | 87253ca722a47534b8fd33d38ae1dbe96e2c5dbe | <ide><path>packager/react-packager/src/Resolver/polyfills/require.js
<ide> // require cycles inside the factory from causing an infinite require loop.
<ide> mod.isInitialized = true;
<ide>
<del> __DEV__ && BridgeProfiling().profile(id);
<add> __DEV__ && BridgeProfiling().profile('JS_require_' + id);
<ide>
<ide> // keep args in sync with with defineModuleCode in
<ide> // packager/react-packager/src/Resolver/index.js | 1 |
Javascript | Javascript | fix model<->option interaction when using track by | 6a03ca274314352052c3082163367a146bb11c2d | <ide><path>src/ng/directive/ngOptions.js
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> selectValueMap: selectValueMap,
<ide> getOptionFromViewValue: function(value) {
<ide> return selectValueMap[getTrackByValue(value, getLocals(value))];
<add> },
<add> getViewValueFromOption: function(option) {
<add> // If the viewValue could be an object that may be mutated by the application,
<add> // we need to make a copy and not return the reference to the value on the option.
<add> return trackBy ? angular.copy(option.viewValue) : option.viewValue;
<ide> }
<ide> };
<ide> }
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> if (selectedOption && !selectedOption.disabled) {
<ide> removeEmptyOption();
<ide> removeUnknownOption();
<del> return selectedOption.viewValue;
<add> return options.getViewValueFromOption(selectedOption);
<ide> }
<ide> return null;
<ide> };
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide>
<ide> forEach(selectedValues, function(value) {
<ide> var option = options.selectValueMap[value];
<del> if (!option.disabled) selections.push(option.viewValue);
<add> if (!option.disabled) selections.push(options.getViewValueFromOption(option));
<ide> });
<ide>
<ide> return selections;
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> // We will re-render the option elements if the option values or labels change
<ide> scope.$watchCollection(ngOptions.getWatchables, updateOptions);
<ide>
<add> // We also need to watch to see if the internals of the model changes, since
<add> // ngModel only watches for object identity change
<add> scope.$watch(attr.ngModel, function() { ngModelCtrl.$render(); }, true);
<add>
<ide> // ------------------------------------------------------------------ //
<ide>
<ide>
<ide><path>test/ng/directive/ngOptionsSpec.js
<ide> describe('ngOptions', function() {
<ide> expect(options.eq(2)).toEqualTrackedOption(20, 'twenty');
<ide> });
<ide>
<del>
<add>
<add> it('should update the selected option even if only the tracked property on the selected object changes (single)', function() {
<add> createSelect({
<add> 'ng-model': 'selected',
<add> 'ng-options': 'item.label for item in arr track by item.id'
<add> });
<add>
<add> scope.$apply(function() {
<add> scope.selected = {id: 10, label: 'ten'};
<add> });
<add>
<add> expect(element.val()).toEqual('10');
<add>
<add> // Update the properties on the selected object, rather than replacing the whole object
<add> scope.$apply(function() {
<add> scope.selected.id = 20;
<add> scope.selected.label = 'new twenty';
<add> });
<add>
<add> // The value of the select should change since the id property changed
<add> expect(element.val()).toEqual('20');
<add>
<add> // But the label of the selected option does not change
<add> var option = element.find('option').eq(1);
<add> expect(option.prop('selected')).toEqual(true);
<add> expect(option.text()).toEqual('twenty'); // not 'new twenty'
<add> });
<add>
<add>
<add> it('should update the selected options even if only the tracked properties on the objects in the ' +
<add> 'selected collection change (multi)', function() {
<add> createSelect({
<add> 'ng-model': 'selected',
<add> 'multiple': true,
<add> 'ng-options': 'item.label for item in arr track by item.id'
<add> });
<add>
<add> scope.$apply(function() {
<add> scope.selected = [{id: 10, label: 'ten'}];
<add> });
<add>
<add> expect(element.val()).toEqual(['10']);
<add>
<add> // Update the properties on the object in the selected array, rather than replacing the whole object
<add> scope.$apply(function() {
<add> scope.selected[0].id = 20;
<add> scope.selected[0].label = 'new twenty';
<add> });
<add>
<add> // The value of the select should change since the id property changed
<add> expect(element.val()).toEqual(['20']);
<add>
<add> // But the label of the selected option does not change
<add> var option = element.find('option').eq(1);
<add> expect(option.prop('selected')).toEqual(true);
<add> expect(option.text()).toEqual('twenty'); // not 'new twenty'
<add> });
<add>
<add>
<add> it('should prevent changes to the selected object from modifying the options objects (single)', function() {
<add>
<add> createSelect({
<add> 'ng-model': 'selected',
<add> 'ng-options': 'item.label for item in arr track by item.id'
<add> });
<add>
<add> element.val('10');
<add> browserTrigger(element, 'change');
<add>
<add> expect(scope.selected).toEqual(scope.arr[0]);
<add>
<add> scope.$apply(function() {
<add> scope.selected.id = 20;
<add> });
<add>
<add> expect(scope.selected).not.toEqual(scope.arr[0]);
<add> expect(element.val()).toEqual('20');
<add> expect(scope.arr).toEqual([{id: 10, label: 'ten'}, {id:20, label: 'twenty'}]);
<add> });
<add>
<add>
<ide> it('should preserve value even when reference has changed (single&array)', function() {
<ide> createSelect({
<ide> 'ng-model': 'selected',
<ide> describe('ngOptions', function() {
<ide> expect(element.val()).toBe('10');
<ide>
<ide> setSelectValue(element, 1);
<del> expect(scope.selected).toBe(scope.obj['2']);
<add> expect(scope.selected).toEqual(scope.obj['2']);
<ide> });
<ide>
<ide>
<ide> describe('ngOptions', function() {
<ide>
<ide> element.val('10');
<ide> browserTrigger(element, 'change');
<del> expect(scope.selected).toBe(scope.arr[0].subItem);
<add> expect(scope.selected).toEqual(scope.arr[0].subItem);
<ide>
<ide> // Now reload the array
<ide> scope.$apply(function() {
<ide> describe('ngOptions', function() {
<ide> scope.values.pop();
<ide> });
<ide>
<del> expect(element.val()).toEqualUnknownValue();
<add> expect(element.val()).toEqual('');
<ide> expect(scope.selected).toEqual(null);
<ide>
<ide> // Check after model change
<ide> describe('ngOptions', function() {
<ide> scope.values.pop();
<ide> });
<ide>
<del> expect(element.val()).toEqualUnknownValue();
<add> expect(element.val()).toEqual('');
<ide> expect(scope.selected).toEqual(null);
<ide> });
<ide> | 2 |
Ruby | Ruby | add support for extracting lha archives | 8fe0b5681056fe2540aba05721bfc6cde363e8d8 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def lzippath
<ide> "#{HOMEBREW_PREFIX}/opt/lzip/bin/lzip"
<ide> end
<ide>
<add> def lhapath
<add> "#{HOMEBREW_PREFIX}/opt/lha/bin/lha"
<add> end
<add>
<ide> def cvspath
<ide> @cvspath ||= %W[
<ide> /usr/bin/cvs
<ide> def stage
<ide> when :lzip
<ide> with_system_path { pipe_to_tar(lzippath) }
<ide> chdir
<add> when :lha
<add> safe_system lhapath, "x", cached_location
<ide> when :xar
<ide> safe_system "/usr/bin/xar", "-xf", cached_location
<ide> when :rar
<ide><path>Library/Homebrew/extend/pathname.rb
<ide> def compression_type
<ide> return :gzip_only
<ide> when ".bz2"
<ide> return :bzip2_only
<add> when ".lha", ".lzh"
<add> return :lha
<ide> end
<ide>
<ide> # Get enough of the file to detect common file types | 2 |
Javascript | Javascript | fix race conditions in test-http-upgrade-client2 | 40f675b64b99f0c0392599bd692c5a580500bfd2 | <ide><path>test/simple/test-http-upgrade-client2.js
<ide> server.on('upgrade', function(req, socket, head) {
<ide> socket.end();
<ide> });
<ide> });
<del>server.listen(8000);
<ide>
<del>var client = http.createClient(8000);
<ide>
<del>function upgradeRequest(fn) {
<del> var request = client.request('GET', '/', {
<del> 'Connection': 'Upgrade',
<del> 'Upgrade': 'Test'
<del> });
<del>
<del> var wasUpgrade = false;
<del>
<del> function onUpgrade(res, socket, head) {
<del> wasUpgrade = true;
<add>server.listen(common.PORT, function () {
<add>
<add> var client = http.createClient(common.PORT);
<add>
<add> function upgradeRequest(fn) {
<add> var request = client.request('GET', '/', {
<add> 'Connection': 'Upgrade',
<add> 'Upgrade': 'Test'
<add> });
<ide>
<del> client.removeListener('upgrade', onUpgrade);
<del> socket.end();
<del> }
<del> client.on('upgrade', onUpgrade);
<del>
<del> function onEnd() {
<del> client.removeListener('end', onEnd);
<del> if (!wasUpgrade) {
<del> throw new Error('hasn\'t received upgrade event');
<del> } else {
<del> fn && process.nextTick(fn);
<add> var wasUpgrade = false;
<add>
<add> function onUpgrade(res, socket, head) {
<add> wasUpgrade = true;
<add>
<add> client.removeListener('upgrade', onUpgrade);
<add> socket.end();
<ide> }
<del> }
<del> client.on('end', onEnd);
<del>
<del> request.write('head');
<add> client.on('upgrade', onUpgrade);
<add>
<add> function onEnd() {
<add> client.removeListener('end', onEnd);
<add> if (!wasUpgrade) {
<add> throw new Error('hasn\'t received upgrade event');
<add> } else {
<add> fn && process.nextTick(fn);
<add> }
<add> }
<add> client.on('end', onEnd);
<add>
<add> request.write('head');
<ide>
<del>}
<add> }
<ide>
<del>successCount = 0;
<del>upgradeRequest(function() {
<del> successCount++;
<add> successCount = 0;
<ide> upgradeRequest(function() {
<ide> successCount++;
<del> // Test pass
<del> console.log('Pass!');
<del> client.end();
<del> client.destroy();
<del> server.close();
<add> upgradeRequest(function() {
<add> successCount++;
<add> // Test pass
<add> console.log('Pass!');
<add> client.end();
<add> client.destroy();
<add> server.close();
<add> });
<ide> });
<add>
<ide> });
<ide>
<ide> process.on('exit', function () { | 1 |
Ruby | Ruby | reduce potential modifications to frozen string | a998c364f4394b30ca45f7e100c51652d26389d6 | <ide><path>Library/Homebrew/requirement.rb
<ide> def mktemp(&block)
<ide>
<ide> def infer_name
<ide> klass = self.class.name || self.class.to_s
<del> klass.sub!(/(Dependency|Requirement)$/, "")
<del> klass.sub!(/^(\w+::)*/, "")
<add> klass = klass.sub(/(Dependency|Requirement)$/, "")
<add> klass = klass.sub(/^(\w+::)*/, "")
<ide> return klass.downcase if klass.present?
<ide>
<ide> return @cask if @cask.present? | 1 |
Javascript | Javascript | change var to let/const | b1a13b12f22148467e5c6f71b660505387c3f456 | <ide><path>lib/_stream_writable.js
<ide> function WritableState(options, stream, isDuplex) {
<ide> }
<ide>
<ide> WritableState.prototype.getBuffer = function getBuffer() {
<del> var current = this.bufferedRequest;
<add> let current = this.bufferedRequest;
<ide> const out = [];
<ide> while (current) {
<ide> out.push(current);
<ide> WritableState.prototype.getBuffer = function getBuffer() {
<ide>
<ide> // Test _writableState for inheritance to account for Duplex streams,
<ide> // whose prototype chain only points to Readable.
<del>var realHasInstance;
<add>let realHasInstance;
<ide> if (typeof Symbol === 'function' && SymbolHasInstance) {
<ide> realHasInstance = FunctionPrototype[SymbolHasInstance];
<ide> ObjectDefineProperty(Writable, SymbolHasInstance, {
<ide> function writeOrBuffer(stream, state, chunk, encoding, cb) {
<ide> state.needDrain = true;
<ide>
<ide> if (state.writing || state.corked || state.errored) {
<del> var last = state.lastBufferedRequest;
<add> const last = state.lastBufferedRequest;
<ide> state.lastBufferedRequest = {
<ide> chunk,
<ide> encoding,
<ide> function onwrite(stream, er) {
<ide> }
<ide> } else {
<ide> // Check if we're actually ready to finish, but don't emit yet
<del> var finished = needFinish(state) || stream.destroyed;
<add> const finished = needFinish(state) || stream.destroyed;
<ide>
<ide> if (!finished &&
<ide> !state.corked &&
<ide> function errorBuffer(state, err) {
<ide> // If there's something in the buffer waiting, then process it
<ide> function clearBuffer(stream, state) {
<ide> state.bufferProcessing = true;
<del> var entry = state.bufferedRequest;
<add> let entry = state.bufferedRequest;
<ide>
<ide> if (stream._writev && entry && entry.next) {
<ide> // Fast case, write everything using _writev()
<del> var l = state.bufferedRequestCount;
<del> var buffer = new Array(l);
<del> var holder = state.corkedRequestsFree;
<add> const l = state.bufferedRequestCount;
<add> const buffer = new Array(l);
<add> const holder = state.corkedRequestsFree;
<ide> holder.entry = entry;
<ide>
<del> var count = 0;
<del> var allBuffers = true;
<add> let count = 0;
<add> let allBuffers = true;
<ide> while (entry) {
<ide> buffer[count] = entry;
<ide> if (entry.encoding !== 'buffer')
<ide> function clearBuffer(stream, state) {
<ide> state.corkedRequestsFree = holder.next;
<ide> holder.next = null;
<ide> } else {
<del> var corkReq = { next: null, entry: null, finish: undefined };
<add> const corkReq = { next: null, entry: null, finish: undefined };
<ide> corkReq.finish = onCorkedFinish.bind(undefined, corkReq, state);
<ide> state.corkedRequestsFree = corkReq;
<ide> }
<ide> state.bufferedRequestCount = 0;
<ide> } else {
<ide> // Slow case, write chunks one-by-one
<ide> while (entry) {
<del> var chunk = entry.chunk;
<del> var encoding = entry.encoding;
<del> var cb = entry.callback;
<del> var len = state.objectMode ? 1 : chunk.length;
<add> const chunk = entry.chunk;
<add> const encoding = entry.encoding;
<add> const cb = entry.callback;
<add> const len = state.objectMode ? 1 : chunk.length;
<ide>
<ide> doWrite(stream, state, false, len, chunk, encoding, cb);
<ide> entry = entry.next;
<ide> function endWritable(stream, state, cb) {
<ide> }
<ide>
<ide> function onCorkedFinish(corkReq, state, err) {
<del> var entry = corkReq.entry;
<add> let entry = corkReq.entry;
<ide> corkReq.entry = null;
<ide> while (entry) {
<del> var cb = entry.callback;
<add> const cb = entry.callback;
<ide> state.pendingcb--;
<ide> cb(err);
<ide> entry = entry.next; | 1 |
Text | Text | use single quotes, remove extra whitespace | 0ceb5115ace29ffffac4e37f8f59c75fef23deb0 | <ide><path>docs/docs/optimizing-performance.md
<ide> If you're using Create React App, both `Object.assign` and the object spread syn
<ide> Immutability makes tracking changes cheap. A change will always result in a new object so we only need to check if the reference to the object has changed. For example, in this regular JavaScript code:
<ide>
<ide> ```javascript
<del>const x = { foo: "bar" };
<add>const x = { foo: 'bar' };
<ide> const y = x;
<del>y.foo = "baz";
<add>y.foo = 'baz';
<ide> x === y; // true
<ide> ```
<ide>
<ide> Although `y` was edited, since it's a reference to the same object as `x`, this comparison returns `true`. You can write similar code with immutable.js:
<ide>
<ide> ```javascript
<ide> const SomeRecord = Immutable.Record({ foo: null });
<del>const x = new SomeRecord({ foo: 'bar' });
<add>const x = new SomeRecord({ foo: 'bar' });
<ide> const y = x.set('foo', 'baz');
<ide> x === y; // false
<ide> ``` | 1 |
Java | Java | fix typo in javadoc for testcontextbootstrapper | 0cd21aa55f79d6b36890172f0cf28b880c0f1f34 | <ide><path>spring-test/src/main/java/org/springframework/test/context/TestContextBootstrapper.java
<ide> public interface TestContextBootstrapper {
<ide> * <li>If a {@code ContextLoader} class has been explicitly declared via
<ide> * {@link ContextConfiguration#loader}, use it.</li>
<ide> * <li>Otherwise, concrete implementations are free to determine which
<del> * {@code ContextLoader} class to use as as default.</li>
<add> * {@code ContextLoader} class to use as a default.</li>
<ide> * </ol>
<ide> * @return the merged context configuration, never {@code null}
<ide> * @see #buildTestContext() | 1 |
Text | Text | add targos as a collaborator | 6f306e0ed286612c279aee94713316608ff203e5 | <ide><path>README.md
<ide> information about the governance of the io.js project, see
<ide> * **Rich Trott** <rtrott@gmail.com> ([@Trott](https://github.com/Trott))
<ide> * **Сковорода Никита Андреевич** <chalkerx@gmail.com> ([@ChALkeR](https://github.com/ChALkeR))
<ide> * **Sakthipriyan Vairamani** <thechargingvolcano@gmail.com> ([@thefourtheye](https://github.com/thefourtheye))
<add>* **Michaël Zasso** <mic.besace@gmail.com> ([@targos](https://github.com/targos))
<ide>
<ide> Collaborators & TSC members follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the io.js project. | 1 |
Mixed | Ruby | add migration versioning via migration subclasses | 6940dc860c4b25bff2eded370f2af4316de15a30 | <ide><path>activerecord/CHANGELOG.md
<add>* Version the API presented to migration classes, so we can change parameter
<add> defaults without breaking existing migrations, or forcing them to be
<add> rewritten through a deprecation cycle.
<add>
<add> *Matthew Draper*, *Ravil Bayramgalin*
<add>
<ide> * Use bind params for `limit` and `offset`. This will generate significantly
<ide> fewer prepared statements for common tasks like pagination. To support this
<ide> change, passing a string containing a comma to `limit` has been deprecated,
<ide><path>activerecord/lib/active_record/migration.rb
<ide> def initialize(message = DEFAULT_MESSAGE)
<ide> # are in a Migration with <tt>self.disable_ddl_transaction!</tt>.
<ide> class Migration
<ide> autoload :CommandRecorder, 'active_record/migration/command_recorder'
<add> autoload :Compatibility, 'active_record/migration/compatibility'
<add>
<add> # This must be defined before the inherited hook, below
<add> class Current < Migration # :nodoc:
<add> end
<add>
<add> def self.inherited(subclass) # :nodoc:
<add> super
<add> if subclass.superclass == Migration
<add> subclass.include Compatibility::Legacy
<add> end
<add> end
<add>
<add> def self.[](version)
<add> version = version.to_s
<add> name = "V#{version.tr('.', '_')}"
<add> unless Compatibility.const_defined?(name)
<add> versions = Compatibility.constants.grep(/\AV[0-9_]+\z/).map { |s| s.to_s.delete('V').tr('_', '.').inspect }
<add> raise "Unknown migration version #{version.inspect}; expected one of #{versions.sort.join(', ')}"
<add> end
<add> Compatibility.const_get(name)
<add> end
<add>
<add> def self.current_version
<add> Rails.version.to_f
<add> end
<ide>
<ide> MigrationFilenameRegexp = /\A([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/ # :nodoc:
<ide>
<ide><path>activerecord/lib/active_record/migration/compatibility.rb
<add>module ActiveRecord
<add> class Migration
<add> module Compatibility # :nodoc: all
<add> V5_0 = Current
<add>
<add> module FourTwoShared
<add> end
<add>
<add> class V4_2 < V5_0
<add> # 4.2 is defined as a module because it needs to be shared with
<add> # Legacy. When the time comes, V5_0 should be defined straight
<add> # in its class.
<add> include FourTwoShared
<add> end
<add>
<add> module Legacy
<add> include FourTwoShared
<add>
<add> def run(*)
<add> ActiveSupport::Deprecation.warn \
<add> "Directly inheriting from ActiveRecord::Migration is deprecated. " \
<add> "Please specify the Rails release the migration was written for:\n" \
<add> "\n" \
<add> " class #{self.class.name} < ActiveRecord::Migration[4.2]"
<add> super
<add> end
<add> end
<add> end
<add> end
<add>end
<ide><path>activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb
<del>class <%= migration_class_name %> < ActiveRecord::Migration
<add>class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
<ide> def change
<ide> create_table :<%= table_name %><%= primary_key_type %> do |t|
<ide> <% attributes.each do |attribute| -%>
<ide><path>activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
<del>class <%= migration_class_name %> < ActiveRecord::Migration
<add>class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
<ide> <%- if migration_action == 'add' -%>
<ide> def change
<ide> <% attributes.each do |attribute| -%> | 5 |
PHP | PHP | use strict assertion | 41383c82858ee70be13689de56daa32547e3ebad | <ide><path>tests/TestCase/Cache/Engine/RedisEngineTest.php
<ide> public function testIncrementAfterWrite()
<ide> $this->assertTrue($result);
<ide>
<ide> $result = Cache::read('test_increment', 'redis');
<del> $this->assertEquals(1, $result);
<add> $this->assertSame(1, $result);
<ide>
<ide> $result = Cache::increment('test_increment', 2, 'redis');
<del> $this->assertEquals(3, $result);
<add> $this->assertSame(3, $result);
<ide>
<ide> $result = Cache::read('test_increment', 'redis');
<del> $this->assertEquals(3, $result);
<add> $this->assertSame(3, $result);
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | remove xrange that slipped into test_numeric.py | f2bec652c1a3137db0e0904312fcb9fe773350ec | <ide><path>numpy/core/tests/test_numeric.py
<ide> def load_data(self, n, eindex):
<ide> """Utility method for the issue 2592 tests.
<ide>
<ide> Raise an exception at the desired index in the iterator."""
<del> for e in xrange(n):
<add> for e in range(n):
<ide> if e == eindex:
<ide> raise NIterError('error at index %s' % eindex)
<ide> yield e | 1 |
PHP | PHP | use correct brackets | 600e8a9b00cb0bbda141c8b2c6e1b1c9e6ebf2ee | <ide><path>src/Network/Request.php
<ide> class Request implements \ArrayAccess {
<ide> */
<ide> public static function createFromGlobals() {
<ide> list($base, $webroot) = static::_base();
<del> $sessionConfig = (array)Configure::read('Session') + array('defaults' => 'php');
<add> $sessionConfig = (array)Configure::read('Session') + ['defaults' => 'php'];
<ide> $config = array(
<ide> 'query' => $_GET,
<ide> 'post' => $_POST, | 1 |
Python | Python | use self.assertequal instead of assert | 7c79f4fc65ecd2a19969b61fa495084364f30790 | <ide><path>libcloud/test/test_utils.py
<ide> class TestPublicKeyUtils(unittest.TestCase):
<ide>
<ide> def test_pubkey_openssh_fingerprint(self):
<ide> fp = get_pubkey_openssh_fingerprint(self.PUBKEY)
<del> assert fp == '35:22:13:5b:82:e2:5d:e1:90:8c:73:74:9f:ef:3b:d8'
<add> self.assertEqual(fp, '35:22:13:5b:82:e2:5d:e1:90:8c:73:74:9f:ef:3b:d8')
<ide>
<ide> def test_pubkey_ssh2_fingerprint(self):
<ide> fp = get_pubkey_ssh2_fingerprint(self.PUBKEY)
<del> assert fp == '11:ad:5d:4c:5b:99:c9:80:7e:81:03:76:5a:25:9d:8c'
<add> self.assertEqual(fp, '11:ad:5d:4c:5b:99:c9:80:7e:81:03:76:5a:25:9d:8c')
<ide>
<ide>
<ide> def test_decorator(): | 1 |
Python | Python | revise imports from collections.abc module | 1bc1fd6bc2ec9c68997736cec1ce5dd4a625ea2f | <ide><path>doc/summarize.py
<ide>
<ide> """
<ide> import os, glob, re, sys, inspect, optparse
<del>try:
<del> # Accessing collections abstract classes from collections
<del> # has been deprecated since Python 3.3
<del> import collections.abc as collections_abc
<del>except ImportError:
<del> import collections as collections_abc
<add>import collections.abc
<add>
<ide> sys.path.append(os.path.join(os.path.dirname(__file__), 'sphinxext'))
<ide> from sphinxext.phantom_import import import_phantom_module
<ide>
<ide> def get_undocumented(documented, module, module_name=None, skip=[]):
<ide>
<ide> if full_name in skip: continue
<ide> if full_name.startswith('numpy.') and full_name[6:] in skip: continue
<del> if not (inspect.ismodule(obj) or isinstance(obj, collections_abc.Callable) or inspect.isclass(obj)):
<add> if not (inspect.ismodule(obj) or
<add> isinstance(obj, collections.abc.Callable) or
<add> inspect.isclass(obj)):
<ide> continue
<ide>
<ide> if full_name not in documented:
<ide><path>numpy/core/_ufunc_config.py
<ide>
<ide> This provides helpers which wrap `umath.geterrobj` and `umath.seterrobj`
<ide> """
<del>try:
<del> # Accessing collections abstract classes from collections
<del> # has been deprecated since Python 3.3
<del> import collections.abc as collections_abc
<del>except ImportError:
<del> import collections as collections_abc
<add>import collections.abc
<ide> import contextlib
<ide>
<ide> from .overrides import set_module
<ide> def seterrcall(func):
<ide> OrderedDict([('divide', 'log'), ('invalid', 'log'), ('over', 'log'), ('under', 'log')])
<ide>
<ide> """
<del> if func is not None and not isinstance(func, collections_abc.Callable):
<del> if not hasattr(func, 'write') or not isinstance(func.write, collections_abc.Callable):
<add> if func is not None and not isinstance(func, collections.abc.Callable):
<add> if (not hasattr(func, 'write') or
<add> not isinstance(func.write, collections.abc.Callable)):
<ide> raise ValueError("Only callable can be used as callback")
<ide> pyvals = umath.geterrobj()
<ide> old = geterrcall()
<ide><path>numpy/core/tests/test_multiarray.py
<del>try:
<del> # Accessing collections abstract classes from collections
<del> # has been deprecated since Python 3.3
<del> import collections.abc as collections_abc
<del>except ImportError:
<del> import collections as collections_abc
<add>import collections.abc
<ide> import tempfile
<ide> import sys
<ide> import shutil
<ide> def test_arrays_not_hashable(self):
<ide>
<ide> def test_collections_hashable(self):
<ide> x = np.array([])
<del> assert_(not isinstance(x, collections_abc.Hashable))
<add> assert_(not isinstance(x, collections.abc.Hashable))
<ide>
<ide>
<ide> class TestArrayPriority:
<ide><path>numpy/core/tests/test_records.py
<del>import sys
<del>try:
<del> # Accessing collections abstract classes from collections
<del> # has been deprecated since Python 3.3
<del> import collections.abc as collections_abc
<del>except ImportError:
<del> import collections as collections_abc
<add>import collections.abc
<ide> import textwrap
<ide> from os import path
<ide> import pytest
<ide> def test_recarray_conflict_fields(self):
<ide> assert_array_equal(ra['shape'], [['A', 'B', 'C']])
<ide> ra.field = 5
<ide> assert_array_equal(ra['field'], [[5, 5, 5]])
<del> assert_(isinstance(ra.field, collections_abc.Callable))
<add> assert_(isinstance(ra.field, collections.abc.Callable))
<ide>
<ide> def test_fromrecords_with_explicit_dtype(self):
<ide> a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')],
<ide><path>numpy/lib/function_base.py
<del>try:
<del> # Accessing collections abstract classes from collections
<del> # has been deprecated since Python 3.3
<del> import collections.abc as collections_abc
<del>except ImportError:
<del> import collections as collections_abc
<add>import collections.abc
<ide> import functools
<ide> import re
<ide> import sys
<ide> def piecewise(x, condlist, funclist, *args, **kw):
<ide> y = zeros(x.shape, x.dtype)
<ide> for k in range(n):
<ide> item = funclist[k]
<del> if not isinstance(item, collections_abc.Callable):
<add> if not isinstance(item, collections.abc.Callable):
<ide> y[condlist[k]] = item
<ide> else:
<ide> vals = x[condlist[k]]
<ide><path>numpy/matrixlib/tests/test_defmatrix.py
<del>try:
<del> # Accessing collections abstract classes from collections
<del> # has been deprecated since Python 3.3
<del> import collections.abc as collections_abc
<del>except ImportError:
<del> import collections as collections_abc
<add>import collections.abc
<ide>
<ide> import numpy as np
<ide> from numpy import matrix, asmatrix, bmat
<ide> def test_instance_methods(self):
<ide> if attrib.startswith('_') or attrib in excluded_methods:
<ide> continue
<ide> f = getattr(a, attrib)
<del> if isinstance(f, collections_abc.Callable):
<add> if isinstance(f, collections.abc.Callable):
<ide> # reset contents of a
<ide> a.astype('f8')
<ide> a.fill(1.0)
<ide><path>numpy/testing/_private/decorators.py
<ide> ``nose.tools`` for more information.
<ide>
<ide> """
<del>try:
<del> # Accessing collections abstract classes from collections
<del> # has been deprecated since Python 3.3
<del> import collections.abc as collections_abc
<del>except ImportError:
<del> import collections as collections_abc
<add>import collections.abc
<ide>
<ide> from .utils import SkipTest, assert_warns, HAS_REFCOUNT
<ide>
<ide> def skip_decorator(f):
<ide> import nose
<ide>
<ide> # Allow for both boolean or callable skip conditions.
<del> if isinstance(skip_condition, collections_abc.Callable):
<add> if isinstance(skip_condition, collections.abc.Callable):
<ide> skip_val = lambda: skip_condition()
<ide> else:
<ide> skip_val = lambda: skip_condition
<ide> def knownfailureif(fail_condition, msg=None):
<ide> msg = 'Test skipped due to known failure'
<ide>
<ide> # Allow for both boolean or callable known failure conditions.
<del> if isinstance(fail_condition, collections_abc.Callable):
<add> if isinstance(fail_condition, collections.abc.Callable):
<ide> fail_val = lambda: fail_condition()
<ide> else:
<ide> fail_val = lambda: fail_condition
<ide> def _deprecated_imp(*args, **kwargs):
<ide> with assert_warns(DeprecationWarning):
<ide> f(*args, **kwargs)
<ide>
<del> if isinstance(conditional, collections_abc.Callable):
<add> if isinstance(conditional, collections.abc.Callable):
<ide> cond = conditional()
<ide> else:
<ide> cond = conditional | 7 |
Ruby | Ruby | ask the request if we should show exceptions | 6716ad555a687b1e825fa71ba076e641f4dc097a | <ide><path>actionpack/lib/action_dispatch/http/request.rb
<ide> def request_method=(request_method) #:nodoc:
<ide> end
<ide> end
<ide>
<add> def show_exceptions? # :nodoc:
<add> # We're treating `nil` as "unset", and we want the default setting to be
<add> # `true`. This logic should be extracted to `env_config` and calculated
<add> # once.
<add> !(env['action_dispatch.show_exceptions'.freeze] == false)
<add> end
<add>
<ide> # Returns a symbol form of the #request_method
<ide> def request_method_symbol
<ide> HTTP_METHOD_LOOKUP[request_method]
<ide><path>actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
<ide> def initialize(app, routes_app = nil)
<ide> end
<ide>
<ide> def call(env)
<add> request = ActionDispatch::Request.new env
<ide> _, headers, body = response = @app.call(env)
<ide>
<ide> if headers['X-Cascade'] == 'pass'
<ide> def call(env)
<ide>
<ide> response
<ide> rescue Exception => exception
<del> raise exception if env['action_dispatch.show_exceptions'] == false
<add> raise exception unless request.show_exceptions?
<ide> render_exception(env, exception)
<ide> end
<ide>
<ide><path>actionpack/lib/action_dispatch/middleware/show_exceptions.rb
<ide> def initialize(app, exceptions_app)
<ide> end
<ide>
<ide> def call(env)
<add> request = ActionDispatch::Request.new env
<ide> @app.call(env)
<ide> rescue Exception => exception
<del> if env['action_dispatch.show_exceptions'] == false
<del> raise exception
<del> else
<add> if request.show_exceptions?
<ide> render_exception(env, exception)
<add> else
<add> raise exception
<ide> end
<ide> end
<ide> | 3 |
PHP | PHP | simplify conditional | 07ab16fdfe4db427b4518ceda5693dbd3911b663 | <ide><path>src/Illuminate/Foundation/Console/ModelMakeCommand.php
<ide> class ModelMakeCommand extends GeneratorCommand
<ide> */
<ide> public function fire()
<ide> {
<del> if (parent::fire() !== false) {
<del> if ($this->option('migration')) {
<del> $table = Str::plural(Str::snake(class_basename($this->argument('name'))));
<add> if (parent::fire() === false) {
<add> return;
<add> }
<add>
<add> if ($this->option('migration')) {
<add> $table = Str::plural(Str::snake(class_basename($this->argument('name'))));
<ide>
<del> $this->call('make:migration', [
<del> 'name' => "create_{$table}_table",
<del> '--create' => $table,
<del> ]);
<del> }
<add> $this->call('make:migration', [
<add> 'name' => "create_{$table}_table",
<add> '--create' => $table,
<add> ]);
<add> }
<ide>
<del> if ($this->option('controller')) {
<del> $controller = Str::studly(class_basename($this->argument('name')));
<add> if ($this->option('controller')) {
<add> $controller = Str::studly(class_basename($this->argument('name')));
<ide>
<del> $this->call('make:controller', [
<del> 'name' => "{$controller}Controller",
<del> '--resource' => $this->option('resource'),
<del> ]);
<del> }
<add> $this->call('make:controller', [
<add> 'name' => "{$controller}Controller",
<add> '--resource' => $this->option('resource'),
<add> ]);
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | use fetch --retry | 281494c2556febe95fe64357577cd713846fcbf4 | <ide><path>Library/Contributions/cmd/brew-test-bot.rb
<ide> def formula formula
<ide> test "brew install apple-gcc42"
<ide> end
<ide>
<del> test "brew fetch #{dependencies}" unless dependencies.empty?
<add> test "brew fetch --retry #{dependencies}" unless dependencies.empty?
<ide> formula_fetch_options = " "
<ide> formula_fetch_options << " --build-bottle" unless ARGV.include? '--no-bottle'
<ide> formula_fetch_options << " --force" if ARGV.include? '--cleanup'
<del> test "brew fetch#{formula_fetch_options} #{formula}"
<add> test "brew fetch --retry#{formula_fetch_options} #{formula}"
<ide> test "brew uninstall --force #{formula}" if formula_object.installed?
<ide> install_args = '--verbose'
<ide> install_args << ' --build-bottle' unless ARGV.include? '--no-bottle'
<ide> def formula formula
<ide> test "brew uninstall --force #{formula}"
<ide> end
<ide> if formula_object.devel and not ARGV.include? '--HEAD'
<del> test "brew fetch --devel#{formula_fetch_options} #{formula}"
<add> test "brew fetch --retry --devel#{formula_fetch_options} #{formula}"
<ide> test "brew install --devel --verbose #{formula}"
<ide> devel_install_passed = steps.last.passed?
<ide> test "brew audit --devel #{formula}" | 1 |
Javascript | Javascript | add debug button to example | 891b364c1b61faaa43880bcaa86e002dbe48cf49 | <ide><path>src/ng/log.js
<ide> <button ng-click="$log.warn(message)">warn</button>
<ide> <button ng-click="$log.info(message)">info</button>
<ide> <button ng-click="$log.error(message)">error</button>
<add> <button ng-click="$log.debug(message)">debug</button>
<ide> </div>
<ide> </file>
<ide> </example> | 1 |
Ruby | Ruby | reuse existing validate_index_length! method | 8f7ab136437038c6ed078cb7585d300f92710e17 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def index_name_exists?(table_name, index_name, default)
<ide> # [<tt>:type</tt>]
<ide> # The reference column type. Defaults to +:integer+.
<ide> # [<tt>:index</tt>]
<del> # Add an appropriate index. Defaults to false.
<add> # Add an appropriate index. Defaults to false.
<ide> # See #add_index for usage of this option.
<ide> # [<tt>:foreign_key</tt>]
<ide> # Add an appropriate foreign key constraint. Defaults to false.
<ide> def add_index_options(table_name, column_name, comment: nil, **options) # :nodoc
<ide> index_type ||= options[:unique] ? "UNIQUE" : ""
<ide> index_name = options[:name].to_s if options.key?(:name)
<ide> index_name ||= index_name(table_name, index_name_options(column_names))
<del> max_index_length = options.fetch(:internal, false) ? index_name_length : allowed_index_name_length
<ide>
<ide> if options.key?(:algorithm)
<ide> algorithm = index_algorithms.fetch(options[:algorithm]) {
<ide> def add_index_options(table_name, column_name, comment: nil, **options) # :nodoc
<ide> index_options = options[:where] ? " WHERE #{options[:where]}" : ""
<ide> end
<ide>
<del> if index_name.length > max_index_length
<del> raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{max_index_length} characters"
<del> end
<add> validate_index_length!(table_name, index_name, options.fetch(:internal, false))
<add>
<ide> if data_source_exists?(table_name) && index_name_exists?(table_name, index_name, false)
<ide> raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
<ide> end
<ide> def foreign_key_name(table_name, options) # :nodoc:
<ide> end
<ide> end
<ide>
<del> def validate_index_length!(table_name, new_name) # :nodoc:
<del> if new_name.length > allowed_index_name_length
<add> def validate_index_length!(table_name, new_name, internal = false) # :nodoc:
<add> max_index_length = internal ? index_name_length : allowed_index_name_length
<add>
<add> if new_name.length > max_index_length
<ide> raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters"
<ide> end
<ide> end | 1 |
Go | Go | improve error if auto-selecting ip-range failed | 03b2393a80ccb2b8e148ee7e4261f4084f98199a | <ide><path>libnetwork/netutils/utils_linux.go
<ide> func ElectInterfaceAddresses(name string) ([]*net.IPNet, []*net.IPNet, error) {
<ide> }
<ide>
<ide> if link == nil || len(v4Nets) == 0 {
<del> // Choose from predefined local scope networks
<add> // Choose from predefined local scope networks
<ide> v4Net, err := FindAvailableNetwork(ipamutils.PredefinedLocalScopeDefaultNetworks)
<ide> if err != nil {
<del> return nil, nil, err
<add> return nil, nil, fmt.Errorf("%s, PredefinedLocalScopeDefaultNetworks List: %+v",
<add> err.Error(),
<add> ipamutils.PredefinedLocalScopeDefaultNetworks)
<ide> }
<ide> v4Nets = append(v4Nets, v4Net)
<ide> } | 1 |
Javascript | Javascript | improve inline comments | 27d4a4f0cad3abdff4a1df9c7314b4adb7eeb2c9 | <ide><path>src/ng/directive/ngRepeat.js
<ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
<ide> //watch props
<ide> $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
<ide> var index, length,
<del> previousNode = $element[0], // current position of the node
<add> previousNode = $element[0], // node that cloned nodes should be inserted after
<add> // initialized to the comment node anchor
<ide> nextNode,
<ide> // Same as lastBlockMap but it has the current state. It will become the
<ide> // lastBlockMap on the next iteration.
<ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
<ide> if (block.scope) {
<ide> // if we have already seen this object, then we need to reuse the
<ide> // associated scope/element
<add>
<ide> nextNode = previousNode;
<add>
<add> // skip nodes that are already pending removal via leave animation
<ide> do {
<ide> nextNode = nextNode.nextSibling;
<ide> } while (nextNode && nextNode[NG_REMOVED]); | 1 |
Javascript | Javascript | simplify schlick signature | 528ada08ea8abfbe4f81ab1ecb08f63396d8c113 | <ide><path>src/renderers/shaders/ShaderChunk/bsdfs.glsl.js
<ide> export default /* glsl */`
<ide> // via 'environmentBRDF' from "Physically Based Shading on Mobile"
<ide> // https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile
<ide> vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {
<add>
<ide> const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
<ide>
<ide> const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
<ide> vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {
<ide>
<ide> float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
<ide>
<del> return vec2( -1.04, 1.04 ) * a004 + r.zw;
<add> return vec2( - 1.04, 1.04 ) * a004 + r.zw;
<ide>
<ide> }
<ide>
<ide> float punctualLightIntensityToIrradianceFactor( const in float lightDistance, co
<ide>
<ide> if( cutoffDistance > 0.0 && decayExponent > 0.0 ) {
<ide>
<del> return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );
<add> return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );
<ide>
<ide> }
<ide>
<ide> vec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {
<ide>
<ide> } // validated
<ide>
<del>vec3 F_Schlick( const in vec3 f0, const in vec3 f90, const in float dotVH ) {
<add>vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
<ide>
<ide> // Original approximation by Christophe Schlick '94
<ide> // float fresnel = pow( 1.0 - dotVH, 5.0 );
<ide>
<ide> // Optimized variant (presented by Epic at SIGGRAPH '13)
<ide> // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
<del> float fresnel = exp2( ( -5.55473 * dotVH - 6.98316 ) * dotVH );
<add> float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
<ide>
<del> return ( f90 - f0 ) * fresnel + f0;
<add> return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
<ide>
<ide> } // validated
<ide>
<ide> float D_GGX( const in float alpha, const in float dotNH ) {
<ide>
<ide> }
<ide>
<del>// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility
<del>vec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in vec3 f90, const in float roughness ) {
<add>// GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
<add>vec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {
<ide>
<ide> float alpha = pow2( roughness ); // UE4's roughness
<ide>
<ide> vec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in Ge
<ide> float dotNH = saturate( dot( geometry.normal, halfDir ) );
<ide> float dotVH = saturate( dot( geometry.viewDir, halfDir ) );
<ide>
<del> vec3 F = F_Schlick( specularColor, vec3( 1.0 ), dotVH );
<add> vec3 F = F_Schlick( specularColor, 1.0, dotVH );
<ide>
<ide> float G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );
<ide>
<ide><path>src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl.js
<ide> material.specularRoughness = min( material.specularRoughness, 1.0 );
<ide>
<ide> #ifdef SPECULAR
<ide>
<del> vec3 specularIntensityFactor = vec3( specularIntensity );
<add> float specularIntensityFactor = specularIntensity;
<ide> vec3 specularTintFactor = specularTint;
<ide>
<ide> #ifdef USE_SPECULARINTENSITYMAP
<ide> material.specularRoughness = min( material.specularRoughness, 1.0 );
<ide>
<ide> #endif
<ide>
<del> material.specularColorF90 = mix( specularIntensityFactor, vec3( 1.0 ), metalnessFactor );
<add> material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
<ide>
<ide> #else
<ide>
<del> vec3 specularIntensityFactor = vec3( 1.0 );
<add> float specularIntensityFactor = 1.0;
<ide> vec3 specularTintFactor = vec3( 1.0 );
<del> material.specularColorF90 = vec3( 1.0 );
<add> material.specularF90 = 1.0;
<ide>
<ide> #endif
<ide>
<ide> material.specularRoughness = min( material.specularRoughness, 1.0 );
<ide> #else
<ide>
<ide> material.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );
<del> material.specularColorF90 = vec3( 1.0 );
<add> material.specularF90 = 1.0;
<ide>
<ide> #endif
<ide>
<ide><path>src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl.js
<ide> struct PhysicalMaterial {
<ide> vec3 diffuseColor;
<ide> float specularRoughness;
<ide> vec3 specularColor;
<del> vec3 specularColorF90;
<add> float specularF90;
<ide>
<ide> #ifdef CLEARCOAT
<ide> float clearcoat;
<ide> void RE_Direct_Physical( const in IncidentLight directLight, const in GeometricC
<ide>
<ide> float clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );
<ide>
<del> reflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), vec3( 1.0 ), material.clearcoatRoughness );
<add> reflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), 1.0, material.clearcoatRoughness );
<ide>
<ide> #else
<ide>
<ide> void RE_Direct_Physical( const in IncidentLight directLight, const in GeometricC
<ide> #endif
<ide>
<ide> #ifdef USE_SHEEN
<add>
<ide> reflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(
<ide> material.specularRoughness,
<ide> directLight.direction,
<ide> geometry,
<ide> material.sheenColor
<ide> );
<add>
<ide> #else
<del> reflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularColorF90, material.specularRoughness);
<add>
<add> reflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.specularRoughness );
<add>
<ide> #endif
<ide>
<ide> reflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor ); | 3 |
Java | Java | move requestpath to parent server package | 6855a85c41a51aeb151c8c1103e30a6a6745197b | <ide><path>spring-test/src/main/java/org/springframework/mock/web/reactive/function/server/MockServerRequest.java
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpRange;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.server.reactive.PathContainer;
<del>import org.springframework.http.server.reactive.RequestPath;
<add>import org.springframework.http.server.PathContainer;
<add>import org.springframework.http.server.RequestPath;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<add><path>spring-web/src/main/java/org/springframework/http/server/DefaultPathContainer.java
<del><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultPathContainer.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.reactive;
<add>package org.springframework.http.server;
<ide>
<ide> import java.nio.charset.Charset;
<ide> import java.nio.charset.StandardCharsets;
<add><path>spring-web/src/main/java/org/springframework/http/server/DefaultRequestPath.java
<del><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultRequestPath.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.reactive;
<add>package org.springframework.http.server;
<ide>
<ide> import java.net.URI;
<ide> import java.util.List;
<ide> class DefaultRequestPath implements RequestPath {
<ide> this.pathWithinApplication = extractPathWithinApplication(this.fullPath, this.contextPath);
<ide> }
<ide>
<del> DefaultRequestPath(RequestPath requestPath, @Nullable String contextPath) {
<add> private DefaultRequestPath(RequestPath requestPath, String contextPath) {
<ide> this.fullPath = requestPath;
<ide> this.contextPath = initContextPath(this.fullPath, contextPath);
<ide> this.pathWithinApplication = extractPathWithinApplication(this.fullPath, this.contextPath);
<ide> public PathContainer pathWithinApplication() {
<ide> return this.pathWithinApplication;
<ide> }
<ide>
<add> @Override
<add> public RequestPath modifyContextPath(String contextPath) {
<add> return new DefaultRequestPath(this, contextPath);
<add> }
<add>
<ide>
<ide> @Override
<ide> public boolean equals(@Nullable Object other) {
<add><path>spring-web/src/main/java/org/springframework/http/server/PathContainer.java
<del><path>spring-web/src/main/java/org/springframework/http/server/reactive/PathContainer.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.server.reactive;
<add>package org.springframework.http.server;
<ide>
<ide> import java.util.List;
<ide>
<ide> * of {@link Separator Separator} and {@link PathSegment PathSegment} elements.
<ide> *
<ide> * <p>An instance of this class can be created via {@link #parsePath(String)} or
<del> * {@link #parseUrlPath(String)}. For an HTTP request the path can be
<del> * accessed via {@link ServerHttpRequest#getPath()}.
<add> * {@link #parseUrlPath(String)}.
<ide> *
<ide> * <p>For a URL path each {@link UrlPathSegment UrlPathSegment} exposes its
<ide> * structure decoded safely without the risk of encoded reserved characters
<add><path>spring-web/src/main/java/org/springframework/http/server/RequestPath.java
<del><path>spring-web/src/main/java/org/springframework/http/server/reactive/RequestPath.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>package org.springframework.http.server.reactive;
<add>package org.springframework.http.server;
<ide>
<ide> import java.net.URI;
<ide>
<ide> public interface RequestPath extends PathContainer {
<ide> * The context path is always at the beginning of the path and starts but
<ide> * does not end with "/". It is shared for URLs of the same application.
<ide> * <p>The context path may come from the underlying runtime API such as
<del> * when deploying as a WAR to a Servlet container or it may also be assigned
<del> * through the use of {@link ContextPathCompositeHandler} or both.
<add> * when deploying as a WAR to a Servlet container or it may be assigned in
<add> * a WebFlux application through the use of
<add> * {@link org.springframework.http.server.reactive.ContextPathCompositeHandler
<add> * ContextPathCompositeHandler}.
<ide> */
<ide> PathContainer contextPath();
<ide>
<ide> public interface RequestPath extends PathContainer {
<ide> */
<ide> PathContainer pathWithinApplication();
<ide>
<add> /**
<add> * Return a new {@code RequestPath} instance with a modified context path.
<add> * The new context path must match the beginning of this request path.
<add> * @param contextPath the new context path
<add> * @return a new {@code RequestPath} instance
<add> */
<add> RequestPath modifyContextPath(String contextPath);
<add>
<ide>
<ide> /**
<ide> * Create a new {@code RequestPath} with the given parameters.
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpRequest.java
<ide>
<ide> import org.springframework.http.HttpCookie;
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.server.RequestPath;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultServerHttpRequestBuilder.java
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<add>import org.springframework.http.server.RequestPath;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> private RequestPath getRequestPathToUse(@Nullable URI uriToUse) {
<ide> return null;
<ide> }
<ide> else if (uriToUse == null) {
<del> return new DefaultRequestPath(this.delegate.getPath(), this.contextPath);
<add> return this.delegate.getPath().modifyContextPath(this.contextPath);
<ide> }
<ide> else {
<ide> return RequestPath.parse(uriToUse, this.contextPath);
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServerHttpRequest.java
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpRequest;
<ide> import org.springframework.http.ReactiveHttpInputMessage;
<add>import org.springframework.http.server.RequestPath;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.MultiValueMap;
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServerHttpRequestDecorator.java
<ide> import org.springframework.http.HttpCookie;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<add>import org.springframework.http.server.RequestPath;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MultiValueMap;
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/cors/reactive/UrlBasedCorsConfigurationSource.java
<ide> import java.util.LinkedHashMap;
<ide> import java.util.Map;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.web.cors.CorsConfiguration;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/CaptureTheRestPathElement.java
<ide>
<ide> import java.util.List;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer.Element;
<del>import org.springframework.http.server.reactive.PathContainer.UrlPathSegment;
<add>import org.springframework.http.server.PathContainer.Element;
<add>import org.springframework.http.server.PathContainer.UrlPathSegment;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.util.pattern.PathPattern.MatchingContext;
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/CaptureVariablePathElement.java
<ide> import java.util.regex.Matcher;
<ide> import java.util.regex.Pattern;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer.UrlPathSegment;
<add>import org.springframework.http.server.PathContainer.UrlPathSegment;
<ide> import org.springframework.lang.Nullable;
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/LiteralPathElement.java
<ide>
<ide> package org.springframework.web.util.pattern;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer;
<del>import org.springframework.http.server.reactive.PathContainer.Element;
<del>import org.springframework.http.server.reactive.PathContainer.PathSegment;
<add>import org.springframework.http.server.PathContainer;
<add>import org.springframework.http.server.PathContainer.Element;
<add>import org.springframework.http.server.PathContainer.PathSegment;
<ide> import org.springframework.web.util.pattern.PathPattern.MatchingContext;
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/ParsingPathMatcher.java
<ide> import java.util.concurrent.ConcurrentMap;
<ide> import java.util.stream.Collectors;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.PathMatcher;
<ide> import org.springframework.web.util.pattern.PathPattern.PathMatchResult;
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/PathPattern.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer;
<del>import org.springframework.http.server.reactive.PathContainer.Element;
<del>import org.springframework.http.server.reactive.PathContainer.Separator;
<add>import org.springframework.http.server.PathContainer;
<add>import org.springframework.http.server.PathContainer.Element;
<add>import org.springframework.http.server.PathContainer.Separator;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.MultiValueMap;
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/RegexPathElement.java
<ide> import java.util.regex.Matcher;
<ide> import java.util.regex.Pattern;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer.UrlPathSegment;
<add>import org.springframework.http.server.PathContainer.UrlPathSegment;
<ide> import org.springframework.web.util.pattern.PathPattern.MatchingContext;
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/SingleCharWildcardedPathElement.java
<ide>
<ide> package org.springframework.web.util.pattern;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer.Element;
<del>import org.springframework.http.server.reactive.PathContainer.PathSegment;
<add>import org.springframework.http.server.PathContainer.Element;
<add>import org.springframework.http.server.PathContainer.PathSegment;
<ide> import org.springframework.web.util.pattern.PathPattern.MatchingContext;
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/WildcardPathElement.java
<ide>
<ide> package org.springframework.web.util.pattern;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer;
<del>import org.springframework.http.server.reactive.PathContainer.Element;
<add>import org.springframework.http.server.PathContainer;
<add>import org.springframework.http.server.PathContainer.Element;
<ide> import org.springframework.web.util.pattern.PathPattern.MatchingContext;
<ide>
<ide> /**
<add><path>spring-web/src/test/java/org/springframework/http/server/DefaultPathContainerTests.java
<del><path>spring-web/src/test/java/org/springframework/http/server/reactive/DefaultPathContainerTests.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>package org.springframework.http.server.reactive;
<add>package org.springframework.http.server;
<ide>
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide>
<ide> import org.junit.Test;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer.UrlPathSegment;
<add>import org.springframework.http.server.PathContainer.UrlPathSegment;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide>
<add><path>spring-web/src/test/java/org/springframework/http/server/DefaultRequestPathTests.java
<del><path>spring-web/src/test/java/org/springframework/http/server/reactive/DefaultRequestPathTests.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>package org.springframework.http.server.reactive;
<add>package org.springframework.http.server;
<ide>
<ide> import java.net.URI;
<ide>
<ide><path>spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternMatcherTests.java
<ide> import org.junit.Test;
<ide> import org.junit.rules.ExpectedException;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer;
<del>import org.springframework.http.server.reactive.PathContainer.Element;
<add>import org.springframework.http.server.PathContainer;
<add>import org.springframework.http.server.PathContainer.Element;
<ide> import org.springframework.util.AntPathMatcher;
<ide> import org.springframework.web.util.pattern.PathPattern.PathMatchResult;
<ide> import org.springframework.web.util.pattern.PathPattern.PathRemainingMatchInfo;
<ide><path>spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternParserTests.java
<ide>
<ide> import org.junit.Test;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.web.util.pattern.PathPattern.PathMatchResult;
<ide> import org.springframework.web.util.pattern.PatternParseException.PatternMessage;
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/config/PathMatchConfigurer.java
<ide> public class PathMatchConfigurer {
<ide> @Nullable
<ide> private Boolean trailingSlashMatch;
<ide>
<add>
<ide> @Nullable
<ide> private Boolean caseSensitiveMatch;
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/DefaultServerRequest.java
<ide> import org.springframework.http.HttpRange;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.codec.HttpMessageReader;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.util.Assert;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/PathResourceLookupFunction.java
<ide> import org.springframework.core.io.ClassPathResource;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.core.io.UrlResource;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.util.ResourceUtils;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.util.pattern.PathPattern;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicates.java
<ide> import org.springframework.http.HttpCookie;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ServerRequest.java
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.codec.HttpMessageReader;
<ide> import org.springframework.http.codec.json.Jackson2CodecSupport;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.CollectionUtils;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/support/ServerRequestWrapper.java
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpRange;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MultiValueMap;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/handler/AbstractUrlHandlerMapping.java
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.beans.BeansException;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.StringUtils;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceUrlProvider.java
<ide> import org.springframework.context.ApplicationListener;
<ide> import org.springframework.context.event.ContextRefreshedEvent;
<ide> import org.springframework.core.annotation.AnnotationAwareOrderComparator;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceWebHandler.java
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.MediaTypeFactory;
<ide> import org.springframework.http.codec.ResourceHttpMessageWriter;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.CollectionUtils;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/PatternsRequestCondition.java
<ide> import java.util.TreeSet;
<ide> import java.util.stream.Collectors;
<ide>
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.util.pattern.PathPattern;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMapping.java
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.InvalidMediaTypeException;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.method.HandlerMethod;
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/config/ResourceHandlerRegistryTests.java
<ide> import org.springframework.context.support.GenericApplicationContext;
<ide> import org.springframework.core.io.buffer.support.DataBufferTestUtils;
<ide> import org.springframework.http.CacheControl;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
<ide> import org.springframework.web.reactive.HandlerMapping;
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/server/MockServerRequest.java
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpRange;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.server.reactive.PathContainer;
<del>import org.springframework.http.server.reactive.RequestPath;
<add>import org.springframework.http.server.PathContainer;
<add>import org.springframework.http.server.RequestPath;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/handler/SimpleUrlHandlerMappingTests.java
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.context.support.ClassPathXmlApplicationContext;
<ide> import org.springframework.http.HttpMethod;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
<ide> import org.springframework.web.reactive.HandlerMapping;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.PathContainer;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerWebExchange; | 37 |
PHP | PHP | add subquery support for "from" and "table" | 6c1e014943a508afb2c10869c3175f7783a004e1 | <ide><path>src/Illuminate/Database/Capsule/Manager.php
<ide> public static function connection($connection = null)
<ide> /**
<ide> * Get a fluent query builder instance.
<ide> *
<del> * @param string $table
<add> * @param \Closure|\Illuminate\Database\Query\Builder|string $table
<add> * @param string|null $as
<ide> * @param string|null $connection
<ide> * @return \Illuminate\Database\Query\Builder
<ide> */
<del> public static function table($table, $connection = null)
<add> public static function table($table, $as = null, $connection = null)
<ide> {
<del> return static::$instance->connection($connection)->table($table);
<add> return static::$instance->connection($connection)->table($table, $as);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Connection.php
<ide> public function getSchemaBuilder()
<ide> /**
<ide> * Begin a fluent query against a database table.
<ide> *
<del> * @param string $table
<add> * @param \Closure|\Illuminate\Database\Query\Builder|string $table
<add> * @param string|null $as
<ide> * @return \Illuminate\Database\Query\Builder
<ide> */
<del> public function table($table)
<add> public function table($table, $as = null)
<ide> {
<del> return $this->query()->from($table);
<add> return $this->query()->from($table, $as);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/ConnectionInterface.php
<ide> interface ConnectionInterface
<ide> /**
<ide> * Begin a fluent query against a database table.
<ide> *
<del> * @param string $table
<add> * @param \Closure|\Illuminate\Database\Query\Builder|string $table
<add> * @param string|null $as
<ide> * @return \Illuminate\Database\Query\Builder
<ide> */
<del> public function table($table);
<add> public function table($table, $as = null);
<ide>
<ide> /**
<ide> * Get a new raw query expression.
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function distinct()
<ide> /**
<ide> * Set the table which the query is targeting.
<ide> *
<del> * @param string $table
<add> * @param \Closure|\Illuminate\Database\Query\Builder|string $table
<add> * @param string|null $as
<ide> * @return $this
<ide> */
<del> public function from($table)
<add> public function from($table, $as = null)
<ide> {
<del> $this->from = $table;
<add> if ($table instanceof self ||
<add> $table instanceof EloquentBuilder ||
<add> $table instanceof Closure) {
<add> return $this->fromSub($table, $as);
<add> }
<add>
<add> $this->from = $as ? "{$table} as {$as}" : $table;
<ide>
<ide> return $this;
<ide> }
<ide><path>tests/Integration/Database/QueryBuilderTest.php
<ide> protected function setUp(): void
<ide> ]);
<ide> }
<ide>
<add> public function testFromWithAlias()
<add> {
<add> $this->assertSame('select * from "posts" as "alias"', DB::table('posts', 'alias')->toSql());
<add> }
<add>
<add> public function testFromWithSubQuery()
<add> {
<add> $this->assertSame(
<add> 'Fake Post',
<add> DB::table(function ($query) {
<add> $query->selectRaw("'Fake Post' as title");
<add> }, 'posts')->first()->title
<add> );
<add> }
<add>
<ide> public function testWhereDate()
<ide> {
<ide> $this->assertSame(1, DB::table('posts')->whereDate('created_at', '2018-01-02')->count()); | 5 |
Ruby | Ruby | add nclt sdk apache include directory to superenv | af06c75d72fe9c3c9f928b1480a5444746d93bd7 | <ide><path>Library/Homebrew/superenv.rb
<ide> def determine_cmake_include_path
<ide> paths = []
<ide> paths << "#{MacSystem.x11_prefix}/include/freetype2" if x11?
<ide> paths << "#{sdk}/usr/include/libxml2" unless deps.include? 'libxml2'
<del> # TODO prolly shouldn't always do this?
<del> paths << "#{sdk}/System/Library/Frameworks/Python.framework/Versions/Current/include/python2.7" if MacSystem.xcode43_without_clt?
<add> if MacSystem.xcode43_without_clt?
<add> paths << "#{sdk}/usr/include/apache2"
<add> # TODO prolly shouldn't always do this?
<add> paths << "#{sdk}/System/Library/Frameworks/Python.framework/Versions/Current/include/python2.7"
<add> end
<ide> paths << "#{sdk}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Headers/"
<ide> paths.to_path_s
<ide> end | 1 |
Text | Text | add readme with instructions on using benchpress | bfd311174d8a841c6896120af873c7db116afd6d | <ide><path>benchmarks/README.md
<add>Instructions for using benchpress (how to create benchmarks, how to run, how to configure) can be
<add>found at: https://github.com/angular/benchpress/blob/master/README.md.
<add>
<add>In this project, there is a configured grunt task for building the benchmarks, and placing them in
<add>"/build/benchmarks/".
<add>The existing `grunt webserver` task can be used to serve the built benchmarks at `localhost:8000/build/benchmarks/<benchmark-name>` | 1 |
Ruby | Ruby | eliminate mutation of dependency objects | 1981e78eb2fe7231c999edf86c862597320ec5fe | <ide><path>Library/Homebrew/dependency.rb
<ide> class Dependency
<ide> include Dependable
<ide>
<del> attr_reader :name, :tags
<del> attr_accessor :env_proc, :option_name
<add> attr_reader :name, :tags, :env_proc, :option_name
<ide>
<del> def initialize(name, tags=[])
<del> @name = @option_name = name
<add> DEFAULT_ENV_PROC = proc {}
<add>
<add> def initialize(name, tags=[], env_proc=DEFAULT_ENV_PROC, option_name=name)
<add> @name = name
<ide> @tags = tags
<add> @env_proc = env_proc
<add> @option_name = option_name
<ide> end
<ide>
<ide> def to_s
<ide> def missing_options(inherited_options=[])
<ide> missing
<ide> end
<ide>
<del> def universal!
<del> tags << 'universal' if to_formula.build.has_option? 'universal'
<del> end
<del>
<ide> def modify_build_environment
<ide> env_proc.call unless env_proc.nil?
<ide> end
<ide> def merge_repeats(deps)
<ide>
<ide> deps.uniq.map do |dep|
<ide> tags = grouped.fetch(dep.name).map(&:tags).flatten.uniq
<del> merged_dep = dep.class.new(dep.name, tags)
<del> merged_dep.env_proc = dep.env_proc
<del> merged_dep
<add> dep.class.new(dep.name, tags, dep.env_proc)
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/requirement.rb
<ide> def inspect
<ide> def to_dependency
<ide> f = self.class.default_formula
<ide> raise "No default formula defined for #{inspect}" if f.nil?
<del> dep = Dependency.new(f, tags)
<del> dep.option_name = name
<del> dep.env_proc = method(:modify_build_environment)
<del> dep
<add> Dependency.new(f, tags, method(:modify_build_environment), name)
<ide> end
<ide>
<ide> private
<ide><path>Library/Homebrew/test/test_dependency_expansion.rb
<ide> def test_merges_repeated_deps_with_differing_options
<ide> end
<ide>
<ide> def test_merger_preserves_env_proc
<del> env_proc = @foo.env_proc = stub
<add> env_proc = stub
<add> dep = Dependency.new("foo", [], env_proc)
<add> dep.stubs(:to_formula).returns(stub(:deps => []))
<add> @deps.replace [dep]
<ide> assert_equal env_proc, Dependency.expand(@f).first.env_proc
<ide> end
<ide> | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.