content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
add "default" key for form schema fields
efef4985571e708e26700b72ba1f02448af81220
<ide><path>src/Form/Schema.php <ide> class Schema <ide> 'type' => null, <ide> 'length' => null, <ide> 'precision' => null, <add> 'default' => null, <ide> ]; <ide> <ide> /** <ide><path>tests/TestCase/Form/SchemaTest.php <ide> public function testAddingFields() <ide> <ide> $this->assertEquals(['name'], $schema->fields()); <ide> $res = $schema->field('name'); <del> $expected = ['type' => 'string', 'length' => null, 'precision' => null]; <add> $expected = ['type' => 'string', 'length' => null, 'precision' => null, 'default' => null]; <ide> $this->assertEquals($expected, $res); <ide> <ide> $res = $schema->addField('email', 'string'); <ide> $this->assertSame($schema, $res, 'Should be chainable'); <ide> <ide> $this->assertEquals(['name', 'email'], $schema->fields()); <ide> $res = $schema->field('email'); <del> $expected = ['type' => 'string', 'length' => null, 'precision' => null]; <add> $expected = ['type' => 'string', 'length' => null, 'precision' => null, 'default' => null]; <ide> $this->assertEquals($expected, $res); <ide> } <ide> <ide> public function testAddingFieldsWhitelist() <ide> $schema = new Schema(); <ide> <ide> $schema->addField('name', ['derp' => 'derp', 'type' => 'string']); <del> $expected = ['type' => 'string', 'length' => null, 'precision' => null]; <add> $expected = ['type' => 'string', 'length' => null, 'precision' => null, 'default' => null]; <ide> $this->assertEquals($expected, $schema->field('name')); <ide> } <ide> <ide> public function testDebugInfo() <ide> $result = $schema->__debugInfo(); <ide> $expected = [ <ide> '_fields' => [ <del> 'name' => ['type' => 'string', 'length' => null, 'precision' => null], <del> 'numbery' => ['type' => 'decimal', 'length' => null, 'precision' => null], <add> 'name' => ['type' => 'string', 'length' => null, 'precision' => null, 'default' => null], <add> 'numbery' => ['type' => 'decimal', 'length' => null, 'precision' => null, 'default' => null], <ide> ], <ide> ]; <ide> $this->assertEquals($expected, $result);
2
Python
Python
use 2to3 on py3k
c3b78b89523fd118c832c9bedb0edc948e083bd1
<ide><path>celery/app/amqp.py <ide> <ide> """ <ide> from datetime import datetime, timedelta <del>from UserDict import UserDict <del> <ide> <ide> from celery import routes <ide> from celery import signals <ide> from celery.utils import gen_unique_id, textindent <add>from celery.utils.compat import UserDict <ide> <ide> from kombu import compat as messaging <ide> from kombu import BrokerConnection <ide><path>celery/beat.py <ide> import traceback <ide> import multiprocessing <ide> from datetime import datetime <del>from UserDict import UserDict <ide> <ide> from celery import platforms <ide> from celery import registry <ide> from celery.app import app_or_default <ide> from celery.log import SilenceRepeated <ide> from celery.schedules import maybe_schedule <ide> from celery.utils import instantiate <add>from celery.utils.compat import UserDict <ide> from celery.utils.timeutils import humanize_seconds <ide> <ide> <ide><path>celery/datastructures.py <ide> import traceback <ide> <ide> from itertools import chain <del>from UserList import UserList <ide> from Queue import Queue, Empty as QueueEmpty <ide> <del>from celery.utils.compat import OrderedDict <add>from celery.utils.compat import OrderedDict, UserList <ide> <ide> <ide> class AttributeDictMixin(object): <ide><path>celery/registry.py <ide> """celery.registry""" <ide> import inspect <ide> <del>from UserDict import UserDict <del> <ide> from celery.exceptions import NotRegistered <add>from celery.utils.compat import UserDict <ide> <ide> <ide> class TaskRegistry(UserDict): <ide><path>celery/task/sets.py <ide> import warnings <ide> <del>from UserList import UserList <del> <ide> from celery import registry <ide> from celery.app import app_or_default <ide> from celery.datastructures import AttributeDict <ide> from celery.utils import gen_unique_id <add>from celery.utils.compat import UserList <ide> <ide> TASKSET_DEPRECATION_TEXT = """\ <ide> Using this invocation of TaskSet is deprecated and will be removed <ide><path>celery/tests/test_pickle.py <ide> def test_pickle_regular_exception(self): <ide> exc = None <ide> try: <ide> raise RegularException("RegularException raised") <del> except RegularException, exc: <del> pass <add> except RegularException, exc_: <add> exc = exc_ <ide> <ide> pickled = pickle.dumps({"exception": exc}) <ide> unpickled = pickle.loads(pickled) <ide> def test_pickle_arg_override_exception(self): <ide> try: <ide> raise ArgOverrideException("ArgOverrideException raised", <ide> status_code=100) <del> except ArgOverrideException, exc: <del> pass <add> except ArgOverrideException, exc_: <add> exc = exc_ <ide> <ide> pickled = pickle.dumps({"exception": exc}) <ide> unpickled = pickle.loads(pickled) <ide><path>celery/tests/test_task_http.py <ide> <ide> import logging <ide> from celery.tests.utils import unittest <del>from urllib import addinfourl <add>try: <add> from urllib import addinfourl <add>except ImportError: # py3k <add> from urllib.request import addinfourl <ide> try: <ide> from contextlib import contextmanager <ide> except ImportError: <ide><path>celery/tests/test_task_sets.py <ide> from celery.tests.utils import unittest <ide> <del>import simplejson <add>import anyjson <ide> <ide> from celery.app import app_or_default <ide> from celery.task import Task <ide> def test_is_JSON_serializable(self): <ide> s.args = list(s.args) # tuples are not preserved <ide> # but this doesn't matter. <ide> self.assertEqual(s, <del> subtask(simplejson.loads(simplejson.dumps(s)))) <add> subtask(anyjson.deserialize( <add> anyjson.serialize(s)))) <ide> <ide> <ide> class test_TaskSet(unittest.TestCase): <ide><path>celery/tests/test_worker_job.py <ide> # -*- coding: utf-8 -*- <ide> import logging <del>import simplejson <add>import anyjson <ide> import sys <ide> from celery.tests.utils import unittest <ide> from celery.tests.utils import StringIO <ide> def test_task_wrapper_mail_attrs(self): <ide> def test_from_message(self): <ide> body = {"task": mytask.name, "id": gen_unique_id(), <ide> "args": [2], "kwargs": {u"æØåveéðƒeæ": "bar"}} <del> m = Message(None, body=simplejson.dumps(body), backend="foo", <add> m = Message(None, body=anyjson.serialize(body), backend="foo", <ide> content_type="application/json", <ide> content_encoding="utf-8") <ide> tw = TaskRequest.from_message(m, m.decode()) <ide> def test_from_message(self): <ide> def test_from_message_nonexistant_task(self): <ide> body = {"task": "cu.mytask.doesnotexist", "id": gen_unique_id(), <ide> "args": [2], "kwargs": {u"æØåveéðƒeæ": "bar"}} <del> m = Message(None, body=simplejson.dumps(body), backend="foo", <add> m = Message(None, body=anyjson.serialize(body), backend="foo", <ide> content_type="application/json", <ide> content_encoding="utf-8") <ide> self.assertRaises(NotRegistered, TaskRequest.from_message, <ide><path>celery/utils/__init__.py <ide> def __cmp__(self, rhs): <ide> return -cmp(rhs, self()) <ide> return cmp(self(), rhs) <ide> <add> def __eq__(self, rhs): <add> return self() == rhs <add> <ide> def __deepcopy__(self, memo): <ide> memo[id(self)] = self <ide> return self <ide><path>celery/utils/compat.py <ide> from __future__ import generators <ide> <add>############## py3k ######################################################### <add>try: <add> from UserList import UserList <add>except ImportError: <add> from collections import UserList <add> <add>try: <add> from UserDict import UserDict <add>except ImportError: <add> from collections import UserDict <add> <ide> ############## urlparse.parse_qsl ########################################### <ide> <ide> try: <ide> def any(iterable): <ide> <ide> class _Link(object): <ide> """Doubly linked list.""" <del> __slots__ = 'prev', 'next', 'key', '__weakref__' <add> # next can't be lowercase because 2to3 thinks it's a generator <add> # and renames it to __next__. <add> __slots__ = 'PREV', 'NEXT', 'key', '__weakref__' <ide> <ide> <del>class OrderedDict(dict, MutableMapping): <add>class CompatOrderedDict(dict, MutableMapping): <ide> """Dictionary that remembers insertion order""" <ide> # An inherited dict maps keys to values. <ide> # The inherited dict provides __getitem__, __len__, __contains__, and get. <ide> def __init__(self, *args, **kwds): <ide> raise TypeError("expected at most 1 arguments, got %d" % ( <ide> len(args))) <ide> try: <del> self.__root <add> self._root <ide> except AttributeError: <ide> # sentinel node for the doubly linked list <del> self.__root = root = _Link() <del> root.prev = root.next = root <add> self._root = root = _Link() <add> root.PREV = root.NEXT = root <ide> self.__map = {} <ide> self.update(*args, **kwds) <ide> <ide> def clear(self): <ide> "od.clear() -> None. Remove all items from od." <del> root = self.__root <del> root.prev = root.next = root <add> root = self._root <add> root.PREV = root.NEXT = root <ide> self.__map.clear() <ide> dict.clear(self) <ide> <ide> def __setitem__(self, key, value): <ide> # key/value pair. <ide> if key not in self: <ide> self.__map[key] = link = _Link() <del> root = self.__root <del> last = root.prev <del> link.prev, link.next, link.key = last, root, key <del> last.next = root.prev = weakref.proxy(link) <add> root = self._root <add> last = root.PREV <add> link.PREV, link.NEXT, link.key = last, root, key <add> last.NEXT = root.PREV = weakref.proxy(link) <ide> dict.__setitem__(self, key, value) <ide> <ide> def __delitem__(self, key): <ide> def __delitem__(self, key): <ide> # predecessor and successor nodes. <ide> dict.__delitem__(self, key) <ide> link = self.__map.pop(key) <del> link.prev.next = link.next <del> link.next.prev = link.prev <add> link.PREV.NEXT = link.NEXT <add> link.NEXT.PREV = link.PREV <ide> <ide> def __iter__(self): <ide> """od.__iter__() <==> iter(od)""" <ide> # Traverse the linked list in order. <del> root = self.__root <del> curr = root.next <add> root = self._root <add> curr = root.NEXT <ide> while curr is not root: <ide> yield curr.key <del> curr = curr.next <add> curr = curr.NEXT <ide> <ide> def __reversed__(self): <ide> """od.__reversed__() <==> reversed(od)""" <ide> # Traverse the linked list in reverse order. <del> root = self.__root <del> curr = root.prev <add> root = self._root <add> curr = root.PREV <ide> while curr is not root: <ide> yield curr.key <del> curr = curr.prev <add> curr = curr.PREV <ide> <ide> def __reduce__(self): <ide> """Return state information for pickling""" <ide> items = [[k, self[k]] for k in self] <del> tmp = self.__map, self.__root <del> del(self.__map, self.__root) <add> tmp = self.__map, self._root <add> del(self.__map, self._root) <ide> inst_dict = vars(self).copy() <del> self.__map, self.__root = tmp <add> self.__map, self._root = tmp <ide> if inst_dict: <ide> return (self.__class__, (items,), inst_dict) <ide> return self.__class__, (items,) <ide> def __eq__(self, other): <ide> def __ne__(self, other): <ide> return not (self == other) <ide> <add>try: <add> from collections import OrderedDict <add>except ImportError: <add> OrderedDict = CompatOrderedDict <add> <ide> ############## collections.defaultdict ###################################### <ide> <ide> try: <ide><path>celery/worker/control/registry.py <del>from UserDict import UserDict <add>from celery.utils.compat import UserDict <ide> <ide> <ide> class Panel(UserDict): <ide><path>setup.py <ide> import codecs <ide> import platform <ide> <add>extra = {} <add>tests_require = {"nose", "nose-cover3"} <add>if sys.version_info >= (3, 0): <add> extra.update(use_2to3=True) <add>elif sys.version_info <= (2, 6): <add> tests_require.append("unittest2") <add>elif sys.version_info <= (2, 5): <add> tests_require.append("simplejson") <add> <add>if sys.version_info < (2, 4): <add> raise Exception("Celery requires Python 2.4 or higher.") <add> <ide> try: <ide> from setuptools import setup, find_packages, Command <ide> from setuptools.command.test import test <ide> def run(self, *args, **kwargs): <ide> "bin/celeryev"], <ide> zip_safe=False, <ide> install_requires=install_requires, <del> tests_require=['nose', 'nose-cover3', 'unittest2', 'simplejson'], <add> tests_require=tests_require, <ide> cmdclass={"install": upgrade_and_install, <ide> "upgrade": upgrade, <ide> "test": mytest, <ide> def run(self, *args, **kwargs): <ide> 'console_scripts': console_scripts, <ide> }, <ide> long_description=long_description, <add> **extra <ide> )
13
Python
Python
set genericforeignkey fields on object before save
0a0e4f22e72badd1d8700a2b253cb27450a5319f
<ide><path>rest_framework/serializers.py <ide> import inspect <ide> import types <ide> from decimal import Decimal <add>from django.contrib.contenttypes.generic import GenericForeignKey <ide> from django.core.paginator import Page <ide> from django.db import models <ide> from django.forms import widgets <ide> def restore_object(self, attrs, instance=None): <ide> <ide> # Forward m2m relations <ide> for field in meta.many_to_many + meta.virtual_fields: <add> if isinstance(field, GenericForeignKey): <add> continue <ide> if field.name in attrs: <ide> m2m_data[field.name] = attrs.pop(field.name) <ide>
1
Go
Go
remove uses of pkg/urlutil.istransporturl()
c2ca3e1118d88bdcddc5206afc26b1125e0b5575
<ide><path>daemon/logger/syslog/syslog.go <ide> import ( <ide> "time" <ide> <ide> syslog "github.com/RackSec/srslog" <del> <ide> "github.com/docker/docker/daemon/logger" <ide> "github.com/docker/docker/daemon/logger/loggerutils" <del> "github.com/docker/docker/pkg/urlutil" <ide> "github.com/docker/go-connections/tlsconfig" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <ide> const ( <ide> name = "syslog" <ide> secureProto = "tcp+tls" <add> defaultPort = "514" <ide> ) <ide> <ide> var facilities = map[string]syslog.Priority{ <ide> func parseAddress(address string) (string, string, error) { <ide> if address == "" { <ide> return "", "", nil <ide> } <del> if !urlutil.IsTransportURL(address) { <del> return "", "", fmt.Errorf("syslog-address should be in form proto://address, got %v", address) <del> } <del> url, err := url.Parse(address) <add> addr, err := url.Parse(address) <ide> if err != nil { <ide> return "", "", err <ide> } <ide> <ide> // unix and unixgram socket validation <del> if url.Scheme == "unix" || url.Scheme == "unixgram" { <del> if _, err := os.Stat(url.Path); err != nil { <add> if addr.Scheme == "unix" || addr.Scheme == "unixgram" { <add> if _, err := os.Stat(addr.Path); err != nil { <ide> return "", "", err <ide> } <del> return url.Scheme, url.Path, nil <add> return addr.Scheme, addr.Path, nil <add> } <add> if addr.Scheme != "udp" && addr.Scheme != "tcp" && addr.Scheme != secureProto { <add> return "", "", fmt.Errorf("unsupported scheme: '%s'", addr.Scheme) <ide> } <ide> <ide> // here we process tcp|udp <del> host := url.Host <add> host := addr.Host <ide> if _, _, err := net.SplitHostPort(host); err != nil { <ide> if !strings.Contains(err.Error(), "missing port in address") { <ide> return "", "", err <ide> } <del> host = host + ":514" <add> host = net.JoinHostPort(host, defaultPort) <ide> } <ide> <del> return url.Scheme, host, nil <add> return addr.Scheme, host, nil <ide> } <ide> <ide> // ValidateLogOpt looks for syslog specific log options <ide><path>daemon/logger/syslog/syslog_test.go <ide> package syslog // import "github.com/docker/docker/daemon/logger/syslog" <ide> <ide> import ( <add> "log" <ide> "net" <add> "os" <add> "path/filepath" <ide> "reflect" <add> "runtime" <add> "strings" <ide> "testing" <ide> <ide> syslog "github.com/RackSec/srslog" <ide> func TestValidateLogOptEmpty(t *testing.T) { <ide> } <ide> <ide> func TestValidateSyslogAddress(t *testing.T) { <del> err := ValidateLogOpt(map[string]string{ <del> "syslog-address": "this is not an uri", <del> }) <del> if err == nil { <del> t.Fatal("Expected error with invalid uri") <del> } <del> <del> // File exists <del> err = ValidateLogOpt(map[string]string{ <del> "syslog-address": "unix:///", <del> }) <add> const sockPlaceholder = "/TEMPDIR/socket.sock" <add> s, err := os.Create(filepath.Join(t.TempDir(), "socket.sock")) <ide> if err != nil { <del> t.Fatal(err) <del> } <del> <del> // File does not exist <del> err = ValidateLogOpt(map[string]string{ <del> "syslog-address": "unix:///does_not_exist", <del> }) <del> if err == nil { <del> t.Fatal("Expected error when address is non existing file") <del> } <del> <del> // accepts udp and tcp URIs <del> err = ValidateLogOpt(map[string]string{ <del> "syslog-address": "udp://1.2.3.4", <del> }) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> err = ValidateLogOpt(map[string]string{ <del> "syslog-address": "tcp://1.2.3.4", <del> }) <del> if err != nil { <del> t.Fatal(err) <add> log.Fatal(err) <add> } <add> socketPath := s.Name() <add> _ = s.Close() <add> <add> tests := []struct { <add> address string <add> expectedErr string <add> skipOn string <add> }{ <add> { <add> address: "this is not an uri", <add> expectedErr: "unsupported scheme: ''", <add> }, <add> { <add> address: "corrupted:42", <add> expectedErr: "unsupported scheme: 'corrupted'", <add> }, <add> { <add> address: "unix://" + sockPlaceholder, <add> skipOn: "windows", // doesn't work with unix:// sockets <add> }, <add> { <add> address: "unix:///does_not_exist", <add> expectedErr: "no such file or directory", <add> skipOn: "windows", // error message differs <add> }, <add> { <add> address: "tcp://1.2.3.4", <add> }, <add> { <add> address: "udp://1.2.3.4", <add> }, <add> { <add> address: "http://1.2.3.4", <add> expectedErr: "unsupported scheme: 'http'", <add> }, <add> } <add> for _, tc := range tests { <add> tc := tc <add> if tc.skipOn == runtime.GOOS { <add> continue <add> } <add> t.Run(tc.address, func(t *testing.T) { <add> address := strings.Replace(tc.address, sockPlaceholder, socketPath, 1) <add> err := ValidateLogOpt(map[string]string{"syslog-address": address}) <add> if tc.expectedErr != "" { <add> if err == nil { <add> t.Fatal("expected an error, got nil") <add> } <add> if !strings.Contains(err.Error(), tc.expectedErr) { <add> t.Fatalf("expected error to contain '%s', got: '%s'", tc.expectedErr, err) <add> } <add> } else if err != nil { <add> t.Fatalf("unexpected error: '%s'", err) <add> } <add> }) <ide> } <ide> } <ide> <ide> func TestParseAddressDefaultPort(t *testing.T) { <ide> } <ide> <ide> _, port, _ := net.SplitHostPort(address) <del> if port != "514" { <del> t.Fatalf("Expected to default to port 514. It used port %s", port) <add> if port != defaultPort { <add> t.Fatalf("Expected to default to port %s. It used port %s", defaultPort, port) <ide> } <ide> } <ide> <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *testing.T) { <ide> assert.NilError(c, err, out) <ide> } <ide> <del>// FIXME(vdemeester) should be a unit test <del>func (s *DockerDaemonSuite) TestDaemonCorruptedLogDriverAddress(c *testing.T) { <del> d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) <del> assert.Assert(c, d.StartWithError("--log-driver=syslog", "--log-opt", "syslog-address=corrupted:42") != nil) <del> expected := "syslog-address should be in form proto://address" <del> icmd.RunCommand("grep", expected, d.LogFileName()).Assert(c, icmd.Success) <del>} <del> <ide> // FIXME(vdemeester) should be a unit test <ide> func (s *DockerDaemonSuite) TestDaemonCorruptedFluentdAddress(c *testing.T) { <ide> d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
3
Ruby
Ruby
remove unused argument
b03faffcc10ab7d174c8164d28739e71f9c9ce97
<ide><path>Library/Homebrew/utils.rb <ide> def initialize(error) <ide> end <ide> end <ide> <del> def open url, headers={}, &block <add> def open(url, &block) <ide> # This is a no-op if the user is opting out of using the GitHub API. <ide> return if ENV['HOMEBREW_NO_GITHUB_API'] <ide> <ide> require "net/https" <ide> <del> default_headers = { <add> headers = { <ide> "User-Agent" => HOMEBREW_USER_AGENT, <ide> "Accept" => "application/vnd.github.v3+json", <ide> } <ide> <del> default_headers['Authorization'] = "token #{HOMEBREW_GITHUB_API_TOKEN}" if HOMEBREW_GITHUB_API_TOKEN <add> headers["Authorization"] = "token #{HOMEBREW_GITHUB_API_TOKEN}" if HOMEBREW_GITHUB_API_TOKEN <ide> <ide> begin <del> Kernel.open(url, default_headers.merge(headers)) do |f| <del> yield Utils::JSON.load(f.read) <del> end <add> Kernel.open(url, headers) { |f| yield Utils::JSON.load(f.read) } <ide> rescue OpenURI::HTTPError => e <ide> handle_api_error(e) <ide> rescue EOFError, SocketError, OpenSSL::SSL::SSLError => e
1
Java
Java
fix debughooktest as per direction from @abersnaze
68983965c9f742f88bd626ad30dc71f7684c648c
<ide><path>rxjava-contrib/rxjava-debug/src/test/java/rx/debug/DebugHookTest.java <ide> public void onError(Throwable e) { <ide> public void onNext(Integer t) { <ide> } <ide> }); <del> verify(events, times(6)).call(subscribe()); <add> verify(events, atLeast(3)).call(subscribe()); <ide> verify(events, times(4)).call(onNext(1)); <ide> // one less because it originates from the inner observable sent to merge <ide> verify(events, times(3)).call(onNext(2));
1
Go
Go
add tarsum calculation during v2 pull operation
213e3d116642431adbe634d39740eddc5a81e063
<ide><path>graph/pull.go <ide> import ( <ide> log "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/image" <add> "github.com/docker/docker/pkg/tarsum" <ide> "github.com/docker/docker/registry" <ide> "github.com/docker/docker/utils" <ide> "github.com/docker/libtrust" <ide> func (s *TagStore) CmdPull(job *engine.Job) engine.Status { <ide> } <ide> defer s.poolRemove("pull", repoInfo.LocalName+":"+tag) <ide> <add> <add> log.Debugf("pulling image from host %q with remote name %q", repoInfo.Index.Name, repoInfo.RemoteName) <ide> endpoint, err := repoInfo.GetEndpoint() <ide> if err != nil { <ide> return job.Error(err) <ide> func (s *TagStore) CmdPull(job *engine.Job) engine.Status { <ide> logName += ":" + tag <ide> } <ide> <add> // Calling the v2 code path might change the session <add> // endpoint value, so save the original one! <add> originalSession := *r <add> <ide> if len(repoInfo.Index.Mirrors) == 0 && (repoInfo.Index.Official || endpoint.Version == registry.APIVersion2) { <ide> j := job.Eng.Job("trust_update_base") <ide> if err = j.Run(); err != nil { <ide> func (s *TagStore) CmdPull(job *engine.Job) engine.Status { <ide> return job.Errorf("error getting authorization: %s", err) <ide> } <ide> <add> log.Debugf("pulling v2 repository with local name %q", repoInfo.LocalName) <ide> if err := s.pullV2Repository(job.Eng, r, job.Stdout, repoInfo, tag, sf, job.GetenvBool("parallel"), auth); err == nil { <ide> if err = job.Eng.Job("log", "pull", logName, "").Run(); err != nil { <ide> log.Errorf("Error logging event 'pull' for %s: %s", logName, err) <ide> func (s *TagStore) CmdPull(job *engine.Job) engine.Status { <ide> } else if err != registry.ErrDoesNotExist { <ide> log.Errorf("Error from V2 registry: %s", err) <ide> } <add> <add> log.Debug("image does not exist on v2 registry, falling back to v1") <ide> } <ide> <add> r = &originalSession <add> <add> log.Debugf("pulling v1 repository with local name %q", repoInfo.LocalName) <ide> if err = s.pullRepository(r, job.Stdout, repoInfo, tag, sf, job.GetenvBool("parallel")); err != nil { <ide> return job.Error(err) <ide> } <ide> func (s *TagStore) pullRepository(r *registry.Session, out io.Writer, repoInfo * <ide> log.Debugf("Retrieving the tag list") <ide> tagsList, err := r.GetRemoteTags(repoData.Endpoints, repoInfo.RemoteName, repoData.Tokens) <ide> if err != nil { <del> log.Errorf("%v", err) <add> log.Errorf("unable to get remote tags: %s", err) <ide> return err <ide> } <ide> <ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri <ide> return err <ide> } <ide> defer r.Close() <del> io.Copy(tmpFile, utils.ProgressReader(r, int(l), out, sf, false, utils.TruncateID(img.ID), "Downloading")) <add> <add> // Wrap the reader with the appropriate TarSum reader. <add> tarSumReader, err := tarsum.NewTarSumForLabel(r, true, sumType) <add> if err != nil { <add> return fmt.Errorf("unable to wrap image blob reader with TarSum: %s", err) <add> } <add> <add> io.Copy(tmpFile, utils.ProgressReader(ioutil.NopCloser(tarSumReader), int(l), out, sf, false, utils.TruncateID(img.ID), "Downloading")) <add> <add> out.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Verifying Checksum", nil)) <add> <add> if finalChecksum := tarSumReader.Sum(nil); !strings.EqualFold(finalChecksum, sumStr) { <add> return fmt.Errorf("image verification failed: checksum mismatch - expected %q but got %q", sumStr, finalChecksum) <add> } <ide> <ide> out.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Download complete", nil)) <ide> <ide><path>image/image.go <ide> func StoreImage(img *Image, layerData archive.ArchiveReader, root string) error <ide> <ide> // If layerData is not nil, unpack it into the new layer <ide> if layerData != nil { <del> layerDataDecompressed, err := archive.DecompressStream(layerData) <del> if err != nil { <del> return err <del> } <add> // If the image doesn't have a checksum, we should add it. The layer <add> // checksums are verified when they are pulled from a remote, but when <add> // a container is committed it should be added here. <add> if img.Checksum == "" { <add> layerDataDecompressed, err := archive.DecompressStream(layerData) <add> if err != nil { <add> return err <add> } <add> defer layerDataDecompressed.Close() <ide> <del> defer layerDataDecompressed.Close() <add> if layerTarSum, err = tarsum.NewTarSum(layerDataDecompressed, true, tarsum.VersionDev); err != nil { <add> return err <add> } <ide> <del> if layerTarSum, err = tarsum.NewTarSum(layerDataDecompressed, true, tarsum.VersionDev); err != nil { <del> return err <del> } <add> if size, err = driver.ApplyDiff(img.ID, img.Parent, layerTarSum); err != nil { <add> return err <add> } <ide> <del> if size, err = driver.ApplyDiff(img.ID, img.Parent, layerTarSum); err != nil { <add> img.Checksum = layerTarSum.Sum(nil) <add> } else if size, err = driver.ApplyDiff(img.ID, img.Parent, layerData); err != nil { <ide> return err <ide> } <ide> <del> checksum := layerTarSum.Sum(nil) <del> <del> if img.Checksum != "" && img.Checksum != checksum { <del> log.Warnf("image layer checksum mismatch: computed %q, expected %q", checksum, img.Checksum) <del> } <del> <del> img.Checksum = checksum <ide> } <ide> <ide> img.Size = size <ide><path>pkg/tarsum/tarsum.go <ide> package tarsum <ide> import ( <ide> "bytes" <ide> "compress/gzip" <add> "crypto" <ide> "crypto/sha256" <ide> "encoding/hex" <add> "errors" <add> "fmt" <ide> "hash" <ide> "io" <ide> "strings" <ide> func NewTarSumHash(r io.Reader, dc bool, v Version, tHash THash) (TarSum, error) <ide> return ts, err <ide> } <ide> <add>// Create a new TarSum using the provided TarSum version+hash label. <add>func NewTarSumForLabel(r io.Reader, disableCompression bool, label string) (TarSum, error) { <add> parts := strings.SplitN(label, "+", 2) <add> if len(parts) != 2 { <add> return nil, errors.New("tarsum label string should be of the form: {tarsum_version}+{hash_name}") <add> } <add> <add> versionName, hashName := parts[0], parts[1] <add> <add> version, ok := tarSumVersionsByName[versionName] <add> if !ok { <add> return nil, fmt.Errorf("unknown TarSum version name: %q", versionName) <add> } <add> <add> hashConfig, ok := standardHashConfigs[hashName] <add> if !ok { <add> return nil, fmt.Errorf("unknown TarSum hash name: %q", hashName) <add> } <add> <add> tHash := NewTHash(hashConfig.name, hashConfig.hash.New) <add> <add> return NewTarSumHash(r, disableCompression, version, tHash) <add>} <add> <ide> // TarSum is the generic interface for calculating fixed time <ide> // checksums of a tar archive <ide> type TarSum interface { <ide> func NewTHash(name string, h func() hash.Hash) THash { <ide> return simpleTHash{n: name, h: h} <ide> } <ide> <add>type tHashConfig struct { <add> name string <add> hash crypto.Hash <add>} <add> <add>var ( <add> standardHashConfigs = map[string]tHashConfig{ <add> "sha256": {name: "sha256", hash: crypto.SHA256}, <add> "sha512": {name: "sha512", hash: crypto.SHA512}, <add> } <add>) <add> <ide> // TarSum default is "sha256" <ide> var DefaultTHash = NewTHash("sha256", sha256.New) <ide> <ide><path>pkg/tarsum/versioning.go <ide> func GetVersions() []Version { <ide> return v <ide> } <ide> <del>var tarSumVersions = map[Version]string{ <del> Version0: "tarsum", <del> Version1: "tarsum.v1", <del> VersionDev: "tarsum.dev", <del>} <add>var ( <add> tarSumVersions = map[Version]string{ <add> Version0: "tarsum", <add> Version1: "tarsum.v1", <add> VersionDev: "tarsum.dev", <add> } <add> tarSumVersionsByName = map[string]Version{ <add> "tarsum": Version0, <add> "tarsum.v1": Version1, <add> "tarsum.dev": VersionDev, <add> } <add>) <ide> <ide> func (tsv Version) String() string { <ide> return tarSumVersions[tsv] <ide><path>registry/endpoint.go <ide> func NewEndpoint(index *IndexInfo) (*Endpoint, error) { <ide> if err != nil { <ide> return nil, err <ide> } <add> if err := validateEndpoint(endpoint); err != nil { <add> return nil, err <add> } <add> <add> return endpoint, nil <add>} <ide> <add>func validateEndpoint(endpoint *Endpoint) error { <ide> log.Debugf("pinging registry endpoint %s", endpoint) <ide> <ide> // Try HTTPS ping to registry <ide> endpoint.URL.Scheme = "https" <ide> if _, err := endpoint.Ping(); err != nil { <del> if index.Secure { <add> if endpoint.IsSecure { <ide> // If registry is secure and HTTPS failed, show user the error and tell them about `--insecure-registry` <ide> // in case that's what they need. DO NOT accept unknown CA certificates, and DO NOT fallback to HTTP. <del> return nil, fmt.Errorf("invalid registry endpoint %s: %v. If this private registry supports only HTTP or HTTPS with an unknown CA certificate, please add `--insecure-registry %s` to the daemon's arguments. In the case of HTTPS, if you have access to the registry's CA certificate, no need for the flag; simply place the CA certificate at /etc/docker/certs.d/%s/ca.crt", endpoint, err, endpoint.URL.Host, endpoint.URL.Host) <add> return fmt.Errorf("invalid registry endpoint %s: %v. If this private registry supports only HTTP or HTTPS with an unknown CA certificate, please add `--insecure-registry %s` to the daemon's arguments. In the case of HTTPS, if you have access to the registry's CA certificate, no need for the flag; simply place the CA certificate at /etc/docker/certs.d/%s/ca.crt", endpoint, err, endpoint.URL.Host, endpoint.URL.Host) <ide> } <ide> <ide> // If registry is insecure and HTTPS failed, fallback to HTTP. <ide> func NewEndpoint(index *IndexInfo) (*Endpoint, error) { <ide> <ide> var err2 error <ide> if _, err2 = endpoint.Ping(); err2 == nil { <del> return endpoint, nil <add> return nil <ide> } <ide> <del> return nil, fmt.Errorf("invalid registry endpoint %q. HTTPS attempt: %v. HTTP attempt: %v", endpoint, err, err2) <add> return fmt.Errorf("invalid registry endpoint %q. HTTPS attempt: %v. HTTP attempt: %v", endpoint, err, err2) <ide> } <ide> <del> return endpoint, nil <add> return nil <ide> } <ide> <ide> func newEndpoint(address string, secure bool) (*Endpoint, error) { <ide><path>registry/session_v2.go <ide> func (r *Session) GetV2Authorization(imageName string, readOnly bool) (auth *Req <ide> } <ide> <ide> var registry *Endpoint <del> if r.indexEndpoint.URL.Host == IndexServerURL.Host { <del> registry, err = NewEndpoint(REGISTRYSERVER, nil) <add> if r.indexEndpoint.String() == IndexServerAddress() { <add> registry, err = newEndpoint(REGISTRYSERVER, true) <add> if err != nil { <add> return <add> } <add> err = validateEndpoint(registry) <ide> if err != nil { <ide> return <ide> }
6
Javascript
Javascript
fix branding violation addmanagedpathsplugin
edc7c8fcd59aa0f60019f6d9d52a7d80e2f2001e
<ide><path>lib/cache/AddManagedPathsPlugin.js <ide> class AddManagedPathsPlugin { <ide> } <ide> <ide> /** <del> * @param {Compiler} compiler Webpack compiler <add> * @param {Compiler} compiler webpack compiler <ide> * @returns {void} <ide> */ <ide> apply(compiler) {
1
Javascript
Javascript
convert var to es6 const
c49dcb319b22ec5084384fe279e91a88108b10e9
<ide><path>benchmark/arrays/var-int.js <ide> 'use strict'; <del>var common = require('../common.js'); <add>const common = require('../common.js'); <ide> <del>var types = [ <del> 'Array', <del> 'Buffer', <del> 'Int8Array', <del> 'Uint8Array', <del> 'Int16Array', <del> 'Uint16Array', <del> 'Int32Array', <del> 'Uint32Array', <del> 'Float32Array', <del> 'Float64Array' <del>]; <del> <del>var bench = common.createBenchmark(main, { <del> type: types, <add>const bench = common.createBenchmark(main, { <add> type: [ <add> 'Array', <add> 'Buffer', <add> 'Int8Array', <add> 'Uint8Array', <add> 'Int16Array', <add> 'Uint16Array', <add> 'Int32Array', <add> 'Uint32Array', <add> 'Float32Array', <add> 'Float64Array' <add> ], <ide> n: [25] <ide> }); <ide> <ide> function main(conf) { <del> var type = conf.type; <del> var clazz = global[type]; <del> var n = +conf.n; <add> const type = conf.type; <add> const clazz = global[type]; <add> const n = +conf.n; <ide> <ide> bench.start(); <ide> var arr = new clazz(n * 1e6); <ide><path>benchmark/arrays/zero-float.js <ide> 'use strict'; <del>var common = require('../common.js'); <add>const common = require('../common.js'); <ide> <del>var types = [ <del> 'Array', <del> 'Buffer', <del> 'Int8Array', <del> 'Uint8Array', <del> 'Int16Array', <del> 'Uint16Array', <del> 'Int32Array', <del> 'Uint32Array', <del> 'Float32Array', <del> 'Float64Array' <del>]; <del> <del>var bench = common.createBenchmark(main, { <del> type: types, <add>const bench = common.createBenchmark(main, { <add> type: [ <add> 'Array', <add> 'Buffer', <add> 'Int8Array', <add> 'Uint8Array', <add> 'Int16Array', <add> 'Uint16Array', <add> 'Int32Array', <add> 'Uint32Array', <add> 'Float32Array', <add> 'Float64Array' <add> ], <ide> n: [25] <ide> }); <ide> <ide> function main(conf) { <del> var type = conf.type; <del> var clazz = global[type]; <del> var n = +conf.n; <add> const type = conf.type; <add> const clazz = global[type]; <add> const n = +conf.n; <ide> <ide> bench.start(); <ide> var arr = new clazz(n * 1e6); <ide><path>benchmark/arrays/zero-int.js <ide> 'use strict'; <del>var common = require('../common.js'); <add>const common = require('../common.js'); <ide> <del>var types = [ <del> 'Array', <del> 'Buffer', <del> 'Int8Array', <del> 'Uint8Array', <del> 'Int16Array', <del> 'Uint16Array', <del> 'Int32Array', <del> 'Uint32Array', <del> 'Float32Array', <del> 'Float64Array' <del>]; <del> <del>var bench = common.createBenchmark(main, { <del> type: types, <add>const bench = common.createBenchmark(main, { <add> type: [ <add> 'Array', <add> 'Buffer', <add> 'Int8Array', <add> 'Uint8Array', <add> 'Int16Array', <add> 'Uint16Array', <add> 'Int32Array', <add> 'Uint32Array', <add> 'Float32Array', <add> 'Float64Array' <add> ], <ide> n: [25] <ide> }); <ide> <ide> function main(conf) { <del> var type = conf.type; <del> var clazz = global[type]; <del> var n = +conf.n; <add> const type = conf.type; <add> const clazz = global[type]; <add> const n = +conf.n; <ide> <ide> bench.start(); <ide> var arr = new clazz(n * 1e6);
3
Javascript
Javascript
pass polyfillmodulenames into packager
e53046b9ec1e04e9c808cd17e36136ec11b1f6fb
<ide><path>local-cli/server/runServer.js <ide> function getPackagerServer(args, config) { <ide> getTransformOptions: config.getTransformOptions, <ide> hasteImpl: config.hasteImpl, <ide> platforms: defaultPlatforms.concat(args.platforms), <add> polyfillModuleNames: config.getPolyfillModuleNames(), <ide> postProcessModules: config.postProcessModules, <ide> postMinifyProcess: config.postMinifyProcess, <ide> projectRoots: args.projectRoots, <ide><path>local-cli/util/Config.js <ide> export type ConfigT = { <ide> */ <ide> getBlacklistRE(): RegExp, <ide> <add> /** <add> * Specify any additional polyfill modules that should be processed <add> * before regular module loading. <add> */ <add> getPolyfillModuleNames: () => Array<string>, <add> <ide> /** <ide> * Specify any additional platforms to be used by the packager. <ide> * For example, if you want to add a "custom" platform, and use modules <ide> const defaultConfig: ConfigT = { <ide> getAssetExts: () => [], <ide> getBlacklistRE: () => blacklist(), <ide> getPlatforms: () => [], <add> getPolyfillModuleNames: () => [], <ide> getProjectRoots: () => [process.cwd()], <ide> getProvidesModuleNodeModules: () => providesModuleNodeModules.slice(), <ide> getSourceExts: () => [],
2
Python
Python
implement get_image function for softlayer
32d54fd4f98ed441f224ffc9b03588e88d587558
<ide><path>libcloud/compute/drivers/softlayer.py <ide> crypto = False <ide> <ide> from libcloud.common.softlayer import SoftLayerConnection, SoftLayerException <add>from libcloud.common.types import LibcloudError <ide> from libcloud.compute.types import Provider, NodeState <ide> from libcloud.compute.base import NodeDriver, Node, NodeLocation, NodeSize, \ <ide> NodeImage, KeyPair <ide> def list_images(self, location=None): <ide> ).object <ide> return [self._to_image(i) for i in result['operatingSystems']] <ide> <add> def get_image(self, image_id): <add> """ <add> Gets an image based on an image_id. <add> <add> :param image_id: Image identifier <add> :type image_id: ``str`` <add> <add> :return: A NodeImage object <add> :rtype: :class:`NodeImage` <add> <add> """ <add> images = self.list_images() <add> images = [image for image in images if image.id == image_id] <add> if len(images) < 1: <add> raise LibcloudError('could not find the image with id %s' % image_id) <add> image = images[0] <add> return image <add> <ide> def _to_size(self, id, size): <ide> return NodeSize( <ide> id=id,
1
Python
Python
handle an empty document
742ccaa2cf186e64a03a7b1fd9076374f67aace1
<ide><path>keras/preprocessing/sequence.py <ide> def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncati <ide> <ide> x = (np.ones((nb_samples, maxlen)) * value).astype(dtype) <ide> for idx, s in enumerate(sequences): <add> if len(s) == 0: <add> continue # empty list was found <ide> if truncating == 'pre': <ide> trunc = s[-maxlen:] <ide> elif truncating == 'post':
1
Javascript
Javascript
add support for custom attributes
06f002b161f61079933d482668440d8649fd84fc
<ide><path>src/ngSanitize/filter/linky.js <ide> * <ide> * @param {string} text Input text. <ide> * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in. <add> * @param {object|function(url)} [attributes] Add custom attributes to the link element. <add> * <add> * Can be one of: <add> * <add> * - `object`: A map of attributes <add> * - `function`: Takes the url as a parameter and returns a map of attributes <add> * <add> * If the map of attributes contains a value for `target`, it overrides the value of <add> * the target parameter. <add> * <ide> * @returns {string} Html-linkified text. <ide> * <ide> * @usage <ide> 'mailto:us@somewhere.org,\n'+ <ide> 'another@somewhere.org,\n'+ <ide> 'and one more: ftp://127.0.0.1/.'; <del> $scope.snippetWithTarget = 'http://angularjs.org/'; <add> $scope.snippetWithSingleURL = 'http://angularjs.org/'; <ide> }]); <ide> </script> <ide> <div ng-controller="ExampleController"> <ide> <tr id="linky-target"> <ide> <td>linky target</td> <ide> <td> <del> <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre> <add> <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre> <add> </td> <add> <td> <add> <div ng-bind-html="snippetWithSingleURL | linky:'_blank'"></div> <add> </td> <add> </tr> <add> <tr id="linky-custom-attributes"> <add> <td>linky custom attributes</td> <add> <td> <add> <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"&gt;<br>&lt;/div&gt;</pre> <ide> </td> <ide> <td> <del> <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div> <add> <div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"></div> <ide> </td> <ide> </tr> <ide> <tr id="escaped-html"> <ide> <ide> it('should work with the target property', function() { <ide> expect(element(by.id('linky-target')). <del> element(by.binding("snippetWithTarget | linky:'_blank'")).getText()). <add> element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()). <ide> toBe('http://angularjs.org/'); <ide> expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); <ide> }); <add> <add> it('should optionally add custom attributes', function() { <add> expect(element(by.id('linky-custom-attributes')). <add> element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()). <add> toBe('http://angularjs.org/'); <add> expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow'); <add> }); <ide> </file> <ide> </example> <ide> */ <ide> angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { <ide> /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i, <ide> MAILTO_REGEXP = /^mailto:/i; <ide> <del> return function(text, target) { <add> return function(text, target, attributes) { <ide> if (!text) return text; <ide> var match; <ide> var raw = text; <ide> angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { <ide> } <ide> <ide> function addLink(url, text) { <add> var key; <ide> html.push('<a '); <del> if (angular.isDefined(target)) { <add> if (angular.isFunction(attributes)) { <add> attributes = attributes(url); <add> } <add> if (angular.isObject(attributes)) { <add> for (key in attributes) { <add> html.push(key + '="' + attributes[key] + '" '); <add> } <add> } else { <add> attributes = {}; <add> } <add> if (angular.isDefined(target) && !('target' in attributes)) { <ide> html.push('target="', <ide> target, <ide> '" '); <ide><path>test/ngSanitize/filter/linkySpec.js <ide> describe('linky', function() { <ide> toBeOneOf('<a target="someNamedIFrame" href="http://example.com">http://example.com</a>', <ide> '<a href="http://example.com" target="someNamedIFrame">http://example.com</a>'); <ide> }); <add> <add> describe('custom attributes', function() { <add> <add> it('should optionally add custom attributes', function() { <add> expect(linky("http://example.com", "_self", {rel: "nofollow"})). <add> toBeOneOf('<a rel="nofollow" target="_self" href="http://example.com">http://example.com</a>', <add> '<a href="http://example.com" target="_self" rel="nofollow">http://example.com</a>'); <add> }); <add> <add> <add> it('should override target parameter with custom attributes', function() { <add> expect(linky("http://example.com", "_self", {target: "_blank"})). <add> toBeOneOf('<a target="_blank" href="http://example.com">http://example.com</a>', <add> '<a href="http://example.com" target="_blank">http://example.com</a>'); <add> }); <add> <add> <add> it('should optionally add custom attributes from function', function() { <add> expect(linky("http://example.com", "_self", function(url) {return {"class": "blue"};})). <add> toBeOneOf('<a class="blue" target="_self" href="http://example.com">http://example.com</a>', <add> '<a href="http://example.com" target="_self" class="blue">http://example.com</a>', <add> '<a class="blue" href="http://example.com" target="_self">http://example.com</a>'); <add> }); <add> <add> <add> it('should pass url as parameter to custom attribute function', function() { <add> var linkParameters = jasmine.createSpy('linkParameters').andReturn({"class": "blue"}); <add> linky("http://example.com", "_self", linkParameters); <add> expect(linkParameters).toHaveBeenCalledWith('http://example.com'); <add> }); <add> <add> <add> it('should strip unsafe attributes', function() { <add> expect(linky("http://example.com", "_self", {"class": "blue", "onclick": "alert('Hi')"})). <add> toBeOneOf('<a class="blue" target="_self" href="http://example.com">http://example.com</a>', <add> '<a href="http://example.com" target="_self" class="blue">http://example.com</a>', <add> '<a class="blue" href="http://example.com" target="_self">http://example.com</a>'); <add> }); <add> }); <ide> });
2
Javascript
Javascript
improve error handling in parsekeyencoding
3afa5d7ba8d7b25ff3acda303c20e41230342e18
<ide><path>lib/internal/crypto/keys.js <ide> function isStringOrBuffer(val) { <ide> } <ide> <ide> function parseKeyEncoding(enc, keyType, isPublic, objName) { <add> if (enc === null || typeof enc !== 'object') <add> throw new ERR_INVALID_ARG_TYPE('options', 'object', enc); <add> <ide> const isInput = keyType === undefined; <ide> <ide> const { <ide><path>test/parallel/test-crypto-key-objects.js <ide> const privatePem = fixtures.readSync('test_rsa_privkey.pem', 'ascii'); <ide> assert.strictEqual(derivedPublicKey.asymmetricKeyType, 'rsa'); <ide> assert.strictEqual(derivedPublicKey.symmetricKeySize, undefined); <ide> <add> // Test exporting with an invalid options object, this should throw. <add> for (const opt of [undefined, null, 'foo', 0, NaN]) { <add> common.expectsError(() => publicKey.export(opt), { <add> type: TypeError, <add> code: 'ERR_INVALID_ARG_TYPE', <add> message: 'The "options" argument must be of type object. Received type ' + <add> typeof opt <add> }); <add> } <add> <ide> const publicDER = publicKey.export({ <ide> format: 'der', <ide> type: 'pkcs1'
2
Text
Text
add contributor agreement
833c66c9b2af1a7d255911921a6e24d4e2ef675d
<ide><path>.github/contributors/bdewilde.md <add># spaCy contributor agreement <add> <add>This spaCy Contributor Agreement (**"SCA"**) is based on the <add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf). <add>The SCA applies to any contribution that you make to any product or project <add>managed by us (the **"project"**), and sets out the intellectual property rights <add>you grant to us in the contributed materials. The term **"us"** shall mean <add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term <add>**"you"** shall mean the person or entity identified below. <add> <add>If you agree to be bound by these terms, fill in the information requested <add>below and include the filled-in version with your first pull request, under the <add>folder [`.github/contributors/`](/.github/contributors/). The name of the file <add>should be your GitHub username, with the extension `.md`. For example, the user <add>example_user would create the file `.github/contributors/example_user.md`. <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>## Contributor Agreement <add> <add>1. The term "contribution" or "contributed materials" means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, <add>documentation, or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and <add>registrations, in your contribution: <add> <add> * you hereby assign to us joint ownership, and to the extent that such <add> assignment is or becomes invalid, ineffective or unenforceable, you hereby <add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, <add> royalty-free, unrestricted license to exercise all rights under those <add> copyrights. This includes, at our option, the right to sublicense these same <add> rights to third parties through multiple levels of sublicensees or other <add> licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your <add> contribution as if each of us were the sole owners, and if one of us makes <add> a derivative work of your contribution, the one who makes the derivative <add> work (or has it made will be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution <add> against us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and <add> exercise all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the <add> consent of, pay or render an accounting to the other for any use or <add> distribution of your contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, <add>non-exclusive, worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer <add> your contribution in whole or in part, alone or in combination with or <add> included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through <add> multiple levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective <add>on the date you first submitted a contribution to us, even if your submission <add>took place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of <add> authorship and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any <add> third party's copyrights, trademarks, patents, or other intellectual <add> property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and <add> other applicable export and import laws. You agree to notify us if you <add> become aware of any circumstance which would make any of the foregoing <add> representations inaccurate in any respect. We may publicly disclose your <add> participation in the project, including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable <add>U.S. Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add> * [x] I am signing on behalf of myself as an individual and no other person <add> or entity, including my employer, has or will have rights with respect to my <add> contributions. <add> <add> * [ ] I am signing on behalf of my employer or a legal entity and I have the <add> actual authority to contractually bind that entity. <add> <add>## Contributor Details <add> <add>| Field | Entry | <add>|------------------------------- | ---------------------------- | <add>| Name | Burton DeWilde | <add>| Company name (if applicable) | - | <add>| Title or role (if applicable) | data scientist | <add>| Date | 20 November 2017 | <add>| GitHub username | bdewilde | <add>| Website (optional) | https://bdewilde.github.io/ |
1
Javascript
Javascript
kill the build if the cdn version was not found
29f19f91fb5a542100e3eae4fbe06d64c70f920c
<ide><path>Gruntfile.js <ide> module.exports = function(grunt) { <ide> NG_VERSION.cdn = versionInfo.cdnVersion; <ide> var dist = 'angular-'+ NG_VERSION.full; <ide> <add> if (versionInfo.cdnVersion == null) { <add> throw new Error('Unable to read CDN version, are you offline or has the CDN not been properly pushed?'); <add> } <add> <ide> //config <ide> grunt.initConfig({ <ide> NG_VERSION: NG_VERSION,
1
Java
Java
restore timeout on the test
60656e53c955e70bacd773f540c151b4aa36c188
<ide><path>src/test/java/rx/internal/operators/OperatorRetryTest.java <ide> public Observable<String> call(GroupedObservable<String, String> t1) { <ide> inOrder.verify(observer, times(1)).onCompleted(); <ide> inOrder.verifyNoMoreInteractions(); <ide> } <del> @Test/*(timeout = 3000)*/ <add> @Test(timeout = 3000) <ide> public void testIssue1900SourceNotSupportingBackpressure() { <ide> @SuppressWarnings("unchecked") <ide> Observer<String> observer = mock(Observer.class);
1
Text
Text
add information about html form submit
009baf06fa9f1ffb948d5a384d01bae1a12d3150
<ide><path>guide/english/html/html-forms/index.md <ide> A form will take input from the site visitor and then will post it to a back-end <ide> The HTML `<form>` tag is used to create an HTML form and it has the following syntax − <ide> <ide> ``` html <del> <form action = "Script URL" method = "POST"> <del> form elements like input, textarea etc. <del> </form> <del><form action = "Script URL" method = "GET"> <del> form elements like input, textarea etc. <del> </form> <add><form action="Script URL" method="POST"> <add> form elements like input, textarea etc. <add></form> <add> <add><form action="Script URL" method="GET"> <add> form elements like input, textarea etc. <add></form> <ide> ``` <ide> <ide> If the form method is not defined then it will default to "GET". <add>If you want to submit sensitive or large amounts of data you should prefer HTTP "POST" over "GET", since form data is visible in the URL when using "GET". <ide> <del>The form tag can also have an attribute named "target" which specifies where the link will open. It can open in the browser tab, a frame, or in the current window. <add>The form tag can also have an attribute named "target" which specifies where the link will open. It can open in the browser tab, a frame, or in the current window. If the target is not defined, the target URL will open in the current tab by default. <ide> <ide> The action attribute defines the action to be performed when the form is submitted. <ide> Normally, the form data is sent to a web page at the Script URL when the user clicks on the submit button. If the action attribute is omitted, the action is set to the current page.
1
Javascript
Javascript
remove trailing whitespace from about.js
c3cb9e39beeecb7191c6fc8724091436b010a119
<ide><path>server/boot/about.js <ide> function getCertCount(userCount, cert) { <ide> } <ide> <ide> function getAllThreeCertsCount(userCount) { <del> return userCount({ <del> isFrontEndCert: true, <del> isDataVisCert: true, <del> isBackEndCert: true <add> return userCount({ <add> isFrontEndCert: true, <add> isDataVisCert: true, <add> isBackEndCert: true <ide> }) <ide> ::timeCache(2, 'hours'); <ide> } <ide> export default function about(app) { <ide> allThreeCount <ide> }) <ide> ) <del> .doOnNext(({ <del> frontEndCount, <del> dataVisCount, <del> backEndCount, <del> allThreeCount <del> }) => { <add> .doOnNext(({ <add> frontEndCount, <add> dataVisCount, <add> backEndCount, <add> allThreeCount <add> }) => { <ide> res.render('resources/about', { <ide> frontEndCount: numberWithCommas(frontEndCount), <ide> dataVisCount: numberWithCommas(dataVisCount),
1
Python
Python
handle msvc v10 in _msvcrver_to_fullver
24523565b5dbb23d6de0591ef2a4c1d014722c5d
<ide><path>numpy/distutils/mingw32ccompiler.py <ide> def _build_import_library_x86(): <ide> if sys.platform == 'win32': <ide> try: <ide> import msvcrt <del> if hasattr(msvcrt, "CRT_ASSEMBLY_VERSION"): <del> _MSVCRVER_TO_FULLVER['90'] = msvcrt.CRT_ASSEMBLY_VERSION <del> else: <del> _MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8" <ide> # I took one version in my SxS directory: no idea if it is the good <ide> # one, and we can't retrieve it from python <ide> _MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42" <add> _MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8" <add> # Value from msvcrt.CRT_ASSEMBLY_VERSION under Python 3.3.0 on Windows XP: <add> _MSVCRVER_TO_FULLVER['100'] = "10.0.30319.460" <add> if hasattr(msvcrt, "CRT_ASSEMBLY_VERSION"): <add> major, minor, rest = msvcrt.CRT_ASSEMBLY_VERSION.split(".",2) <add> _MSVCRVER_TO_FULLVER[major + minor] = msvcrt.CRT_ASSEMBLY_VERSION <add> del major, minor, rest <ide> except ImportError: <ide> # If we are here, means python was not built with MSVC. Not sure what to do <ide> # in that case: manifest building will fail, but it should not be used in
1
Javascript
Javascript
tell jquery not to execute when getting script
7592131e0869d82b258c0d4f7657f1e700d05fbd
<ide><path>client/commonFramework/init.js <ide> window.common = (function(global) { <ide> <ide> common.getScriptContent$ = function getScriptContent$(script) { <ide> return Observable.create(function(observer) { <del> const jqXHR = $.get(script) <add> const jqXHR = $.get(script, null, null, 'text') <ide> .success(data => { <ide> observer.onNext(data); <ide> observer.onCompleted();
1
Javascript
Javascript
add resolve dependencies to compilation
a2601eb5c8a68a4674c43b1796ac5d3a87828d74
<ide><path>lib/container/OverridablesPlugin.js <ide> <ide> const ModuleNotFoundError = require("../ModuleNotFoundError"); <ide> const RuntimeGlobals = require("../RuntimeGlobals"); <add>const { <add> toConstantDependency, <add> evaluateToString <add>} = require("../javascript/JavascriptParserHelpers"); <add>const LazySet = require("../util/LazySet"); <ide> const OverridableModule = require("./OverridableModule"); <ide> const OverridableOriginalDependency = require("./OverridableOriginalDependency"); <ide> const OverridableOriginalModuleFactory = require("./OverridableOriginalModuleFactory"); <ide> const OverridablesRuntimeModule = require("./OverridablesRuntimeModule"); <ide> const parseOptions = require("./parseOptions"); <del>const { <del> toConstantDependency, <del> evaluateToString <del>} = require("../javascript/JavascriptParserHelpers"); <ide> <add>/** @typedef {import("enhanced-resolve").ResolveContext} ResolveContext */ <ide> /** @typedef {import("../Compiler")} Compiler */ <ide> <ide> class OverridablesPlugin { <ide> class OverridablesPlugin { <ide> ); <ide> <ide> const resolvedOverridables = new Map(); <add> const resolveContext = { <add> /** @type {LazySet<string>} */ <add> fileDependencies: new LazySet(), <add> /** @type {LazySet<string>} */ <add> contextDependencies: new LazySet(), <add> /** @type {LazySet<string>} */ <add> missingDependencies: new LazySet() <add> }; <ide> const promise = Promise.all( <ide> this.overridables.map(([key, request]) => { <ide> const resolver = compilation.resolverFactory.get("normal"); <ide> class OverridablesPlugin { <ide> {}, <ide> compiler.context, <ide> request, <del> {}, <add> resolveContext, <ide> (err, result) => { <ide> if (err) { <ide> compilation.errors.push( <ide> class OverridablesPlugin { <ide> ); <ide> }); <ide> }) <del> ); <add> ).then(() => { <add> compilation.contextDependencies.addAll( <add> resolveContext.contextDependencies <add> ); <add> compilation.fileDependencies.addAll(resolveContext.fileDependencies); <add> compilation.missingDependencies.addAll( <add> resolveContext.missingDependencies <add> ); <add> }); <ide> normalModuleFactory.hooks.afterResolve.tapAsync( <ide> "OverridablesPlugin", <ide> (resolveData, callback) => {
1
Javascript
Javascript
replace link to old label
1c12812d1a218f505ccfcd4d958f88ab895ed83e
<ide><path>website/src/templates/universe.js <ide> const UniverseContent = ({ content = [], categories, theme, pageContext, mdxComp <ide> The Universe database is open-source and collected in a simple JSON file. <ide> For more details on the formats and available fields, see the documentation. <ide> Looking for inspiration your own spaCy plugin or extension? Check out the <del> <Link to={github() + '/labels/project%20idea'} hideIcon ws> <del> <InlineCode>project idea</InlineCode> <add> <Link to={"https://github.com/explosion/spaCy/discussions/categories/new-features-project-ideas/"} hideIcon ws> <add> project idea <ide> </Link> <del> label on the issue tracker. <add> section in Discussions. <ide> </p> <ide> <ide> <InlineList>
1
Text
Text
es6 getters + setters tests
49f6875db51057160861a2489648d459698db6c9
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.md <ide> Getters and setters are important because they hide internal implementation deta <ide> ## Instructions <ide> <section id='instructions'> <ide> Use the <code>class</code> keyword to create a Thermostat class. The constructor accepts a Fahrenheit temperature. <del>Now create a <code>getter</code> and a <code>setter</code> in the class, to obtain the temperature in Celsius. <add>In the class, create a <code>getter</code> to obtain the temperature in Celsius and a <code>setter</code> to set the temperature in Celsius. <ide> Remember that <code>C = 5/9 * (F - 32)</code> and <code>F = C * 9.0 / 5 + 32</code>, where <code>F</code> is the value of temperature in Fahrenheit, and <code>C</code> is the value of the same temperature in Celsius. <ide> <strong>Note:</strong> When you implement this, you will track the temperature inside the class in one scale, either Fahrenheit or Celsius. <ide> This is the power of a getter and a setter. You are creating an API for another user, who can get the correct result regardless of which one you track. <ide> tests: <ide> - text: <code>class</code> keyword should be used. <ide> testString: assert(code.match(/class/g)); <ide> - text: <code>Thermostat</code> should be able to be instantiated. <del> testString: assert((() => {const t = new Thermostat(32);return typeof t === 'object' && t.temperature === 0;})()); <add> testString: assert((() => {const t = new Thermostat(122);return typeof t === 'object'})()); <add> - text: When instantiated with a Fahrenheit value, <code>Thermostat</code> should set the correct temperature. <add> testString: assert((() => {const t = new Thermostat(122);return t.temperature === 50})()); <ide> - text: A <code>getter</code> should be defined. <ide> testString: assert((() => {const desc = Object.getOwnPropertyDescriptor(Thermostat.prototype, 'temperature');return !!desc && typeof desc.get === 'function';})()); <ide> - text: A <code>setter</code> should be defined. <ide> testString: assert((() => {const desc = Object.getOwnPropertyDescriptor(Thermostat.prototype, 'temperature');return !!desc && typeof desc.set === 'function';})()); <del> - text: Calling the <code>setter</code> should set the temperature. <del> testString: assert((() => {const t = new Thermostat(32); t.temperature = 26;return t.temperature !== 0;})()); <add> - text: Calling the <code>setter</code> with a Celsius value should set the temperature. <add> testString: assert((() => {const t = new Thermostat(32); t.temperature = 26; const u = new Thermostat(32); u.temperature = 50; return t.temperature === 26 && u.temperature === 50;})()); <ide> <ide> ``` <ide>
1
Go
Go
remove obsolete comment
8706c5124a09ba4ad49ca2eb009bdcaec98b7637
<ide><path>container/monitor.go <ide> func (m *containerMonitor) Close() error { <ide> // Cleanup networking and mounts <ide> m.supervisor.Cleanup(m.container) <ide> <del> // FIXME: here is race condition between two RUN instructions in Dockerfile <del> // because they share same runconfig and change image. Must be fixed <del> // in builder/builder.go <ide> if err := m.container.ToDisk(); err != nil { <ide> logrus.Errorf("Error dumping container %s state to disk: %s", m.container.ID, err) <ide>
1
Ruby
Ruby
move array test files under array
00979fdb2c00de4e124a7c939b9024f57b4a835e
<ide><path>activesupport/test/core_ext/array/access_test.rb <add>require 'abstract_unit' <add>require 'active_support/core_ext/array' <add> <add>class AccessTest < ActiveSupport::TestCase <add> def test_from <add> assert_equal %w( a b c d ), %w( a b c d ).from(0) <add> assert_equal %w( c d ), %w( a b c d ).from(2) <add> assert_equal %w(), %w( a b c d ).from(10) <add> assert_equal %w( d e ), %w( a b c d e ).from(-2) <add> assert_equal %w(), %w( a b c d e ).from(-10) <add> end <add> <add> def test_to <add> assert_equal %w( a ), %w( a b c d ).to(0) <add> assert_equal %w( a b c ), %w( a b c d ).to(2) <add> assert_equal %w( a b c d ), %w( a b c d ).to(10) <add> assert_equal %w( a b c ), %w( a b c d ).to(-2) <add> assert_equal %w(), %w( a b c ).to(-10) <add> end <add> <add> def test_specific_accessor <add> array = (1..42).to_a <add> <add> assert_equal array[1], array.second <add> assert_equal array[2], array.third <add> assert_equal array[3], array.fourth <add> assert_equal array[4], array.fifth <add> assert_equal array[41], array.forty_two <add> end <add>end <ide><path>activesupport/test/core_ext/array/conversions_test.rb <add>require 'abstract_unit' <add>require 'active_support/core_ext/array' <add>require 'active_support/core_ext/big_decimal' <add>require 'active_support/core_ext/hash' <add>require 'active_support/core_ext/string' <add> <add>class ToSentenceTest < ActiveSupport::TestCase <add> def test_plain_array_to_sentence <add> assert_equal "", [].to_sentence <add> assert_equal "one", ['one'].to_sentence <add> assert_equal "one and two", ['one', 'two'].to_sentence <add> assert_equal "one, two, and three", ['one', 'two', 'three'].to_sentence <add> end <add> <add> def test_to_sentence_with_words_connector <add> assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(words_connector: ' ') <add> assert_equal "one & two, and three", ['one', 'two', 'three'].to_sentence(words_connector: ' & ') <add> assert_equal "onetwo, and three", ['one', 'two', 'three'].to_sentence(words_connector: nil) <add> end <add> <add> def test_to_sentence_with_last_word_connector <add> assert_equal "one, two, and also three", ['one', 'two', 'three'].to_sentence(last_word_connector: ', and also ') <add> assert_equal "one, twothree", ['one', 'two', 'three'].to_sentence(last_word_connector: nil) <add> assert_equal "one, two three", ['one', 'two', 'three'].to_sentence(last_word_connector: ' ') <add> assert_equal "one, two and three", ['one', 'two', 'three'].to_sentence(last_word_connector: ' and ') <add> end <add> <add> def test_two_elements <add> assert_equal "one and two", ['one', 'two'].to_sentence <add> assert_equal "one two", ['one', 'two'].to_sentence(two_words_connector: ' ') <add> end <add> <add> def test_one_element <add> assert_equal "one", ['one'].to_sentence <add> end <add> <add> def test_one_element_not_same_object <add> elements = ["one"] <add> assert_not_equal elements[0].object_id, elements.to_sentence.object_id <add> end <add> <add> def test_one_non_string_element <add> assert_equal '1', [1].to_sentence <add> end <add> <add> def test_does_not_modify_given_hash <add> options = { words_connector: ' ' } <add> assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(options) <add> assert_equal({ words_connector: ' ' }, options) <add> end <add> <add> def test_with_blank_elements <add> assert_equal ", one, , two, and three", [nil, 'one', '', 'two', 'three'].to_sentence <add> end <add>end <add> <add>class ToSTest < ActiveSupport::TestCase <add> class TestDB <add> @@counter = 0 <add> def id <add> @@counter += 1 <add> end <add> end <add> <add> def test_to_s_db <add> collection = [TestDB.new, TestDB.new, TestDB.new] <add> <add> assert_equal "null", [].to_s(:db) <add> assert_equal "1,2,3", collection.to_s(:db) <add> end <add>end <add> <add>class ToXmlTest < ActiveSupport::TestCase <add> def test_to_xml_with_hash_elements <add> xml = [ <add> { name: "David", age: 26, age_in_millis: 820497600000 }, <add> { name: "Jason", age: 31, age_in_millis: BigDecimal.new('1.0') } <add> ].to_xml(skip_instruct: true, indent: 0) <add> <add> assert_equal '<objects type="array"><object>', xml.first(30) <add> assert xml.include?(%(<age type="integer">26</age>)), xml <add> assert xml.include?(%(<age-in-millis type="integer">820497600000</age-in-millis>)), xml <add> assert xml.include?(%(<name>David</name>)), xml <add> assert xml.include?(%(<age type="integer">31</age>)), xml <add> assert xml.include?(%(<age-in-millis type="decimal">1.0</age-in-millis>)), xml <add> assert xml.include?(%(<name>Jason</name>)), xml <add> end <add> <add> def test_to_xml_with_non_hash_elements <add> xml = [1, 2, 3].to_xml(skip_instruct: true, indent: 0) <add> <add> assert_equal '<fixnums type="array"><fixnum', xml.first(29) <add> assert xml.include?(%(<fixnum type="integer">2</fixnum>)), xml <add> end <add> <add> def test_to_xml_with_non_hash_different_type_elements <add> xml = [1, 2.0, '3'].to_xml(skip_instruct: true, indent: 0) <add> <add> assert_equal '<objects type="array"><object', xml.first(29) <add> assert xml.include?(%(<object type="integer">1</object>)), xml <add> assert xml.include?(%(<object type="float">2.0</object>)), xml <add> assert xml.include?(%(object>3</object>)), xml <add> end <add> <add> def test_to_xml_with_dedicated_name <add> xml = [ <add> { name: "David", age: 26, age_in_millis: 820497600000 }, { name: "Jason", age: 31 } <add> ].to_xml(skip_instruct: true, indent: 0, root: "people") <add> <add> assert_equal '<people type="array"><person>', xml.first(29) <add> end <add> <add> def test_to_xml_with_options <add> xml = [ <add> { name: "David", street_address: "Paulina" }, { name: "Jason", street_address: "Evergreen" } <add> ].to_xml(skip_instruct: true, skip_types: true, indent: 0) <add> <add> assert_equal "<objects><object>", xml.first(17) <add> assert xml.include?(%(<street-address>Paulina</street-address>)) <add> assert xml.include?(%(<name>David</name>)) <add> assert xml.include?(%(<street-address>Evergreen</street-address>)) <add> assert xml.include?(%(<name>Jason</name>)) <add> end <add> <add> def test_to_xml_with_indent_set <add> xml = [ <add> { name: "David", street_address: "Paulina" }, { name: "Jason", street_address: "Evergreen" } <add> ].to_xml(skip_instruct: true, skip_types: true, indent: 4) <add> <add> assert_equal "<objects>\n <object>", xml.first(22) <add> assert xml.include?(%(\n <street-address>Paulina</street-address>)) <add> assert xml.include?(%(\n <name>David</name>)) <add> assert xml.include?(%(\n <street-address>Evergreen</street-address>)) <add> assert xml.include?(%(\n <name>Jason</name>)) <add> end <add> <add> def test_to_xml_with_dasherize_false <add> xml = [ <add> { name: "David", street_address: "Paulina" }, { name: "Jason", street_address: "Evergreen" } <add> ].to_xml(skip_instruct: true, skip_types: true, indent: 0, dasherize: false) <add> <add> assert_equal "<objects><object>", xml.first(17) <add> assert xml.include?(%(<street_address>Paulina</street_address>)) <add> assert xml.include?(%(<street_address>Evergreen</street_address>)) <add> end <add> <add> def test_to_xml_with_dasherize_true <add> xml = [ <add> { name: "David", street_address: "Paulina" }, { name: "Jason", street_address: "Evergreen" } <add> ].to_xml(skip_instruct: true, skip_types: true, indent: 0, dasherize: true) <add> <add> assert_equal "<objects><object>", xml.first(17) <add> assert xml.include?(%(<street-address>Paulina</street-address>)) <add> assert xml.include?(%(<street-address>Evergreen</street-address>)) <add> end <add> <add> def test_to_xml_with_instruct <add> xml = [ <add> { name: "David", age: 26, age_in_millis: 820497600000 }, <add> { name: "Jason", age: 31, age_in_millis: BigDecimal.new('1.0') } <add> ].to_xml(skip_instruct: false, indent: 0) <add> <add> assert_match(/^<\?xml [^>]*/, xml) <add> assert_equal 0, xml.rindex(/<\?xml /) <add> end <add> <add> def test_to_xml_with_block <add> xml = [ <add> { name: "David", age: 26, age_in_millis: 820497600000 }, <add> { name: "Jason", age: 31, age_in_millis: BigDecimal.new('1.0') } <add> ].to_xml(skip_instruct: true, indent: 0) do |builder| <add> builder.count 2 <add> end <add> <add> assert xml.include?(%(<count>2</count>)), xml <add> end <add> <add> def test_to_xml_with_empty <add> xml = [].to_xml <add> assert_match(/type="array"\/>/, xml) <add> end <add> <add> def test_to_xml_dups_options <add> options = { skip_instruct: true } <add> [].to_xml(options) <add> # :builder, etc, shouldn't be added to options <add> assert_equal({ skip_instruct: true }, options) <add> end <add>end <add> <add>class ToParamTest < ActiveSupport::TestCase <add> class ToParam < String <add> def to_param <add> "#{self}1" <add> end <add> end <add> <add> def test_string_array <add> assert_equal '', %w().to_param <add> assert_equal 'hello/world', %w(hello world).to_param <add> assert_equal 'hello/10', %w(hello 10).to_param <add> end <add> <add> def test_number_array <add> assert_equal '10/20', [10, 20].to_param <add> end <add> <add> def test_to_param_array <add> assert_equal 'custom1/param1', [ToParam.new('custom'), ToParam.new('param')].to_param <add> end <add>end <ide><path>activesupport/test/core_ext/array/extract_options_test.rb <add>require 'abstract_unit' <add>require 'active_support/core_ext/array' <add>require 'active_support/core_ext/hash' <add> <add>class ExtractOptionsTest < ActiveSupport::TestCase <add> class HashSubclass < Hash <add> end <add> <add> class ExtractableHashSubclass < Hash <add> def extractable_options? <add> true <add> end <add> end <add> <add> def test_extract_options <add> assert_equal({}, [].extract_options!) <add> assert_equal({}, [1].extract_options!) <add> assert_equal({ a: :b }, [{ a: :b }].extract_options!) <add> assert_equal({ a: :b }, [1, { a: :b }].extract_options!) <add> end <add> <add> def test_extract_options_doesnt_extract_hash_subclasses <add> hash = HashSubclass.new <add> hash[:foo] = 1 <add> array = [hash] <add> options = array.extract_options! <add> assert_equal({}, options) <add> assert_equal([hash], array) <add> end <add> <add> def test_extract_options_extracts_extractable_subclass <add> hash = ExtractableHashSubclass.new <add> hash[:foo] = 1 <add> array = [hash] <add> options = array.extract_options! <add> assert_equal({ foo: 1 }, options) <add> assert_equal([], array) <add> end <add> <add> def test_extract_options_extracts_hash_with_indifferent_access <add> array = [{ foo: 1 }.with_indifferent_access] <add> options = array.extract_options! <add> assert_equal(1, options[:foo]) <add> end <add>end <ide><path>activesupport/test/core_ext/array/grouping_test.rb <add>require 'abstract_unit' <add>require 'active_support/core_ext/array' <add> <add>class GroupingTest < ActiveSupport::TestCase <add> def setup <add> Fixnum.send :private, :/ # test we avoid Integer#/ (redefined by mathn) <add> end <add> <add> def teardown <add> Fixnum.send :public, :/ <add> end <add> <add> def test_in_groups_of_with_perfect_fit <add> groups = [] <add> ('a'..'i').to_a.in_groups_of(3) do |group| <add> groups << group <add> end <add> <add> assert_equal [%w(a b c), %w(d e f), %w(g h i)], groups <add> assert_equal [%w(a b c), %w(d e f), %w(g h i)], ('a'..'i').to_a.in_groups_of(3) <add> end <add> <add> def test_in_groups_of_with_padding <add> groups = [] <add> ('a'..'g').to_a.in_groups_of(3) do |group| <add> groups << group <add> end <add> <add> assert_equal [%w(a b c), %w(d e f), ['g', nil, nil]], groups <add> end <add> <add> def test_in_groups_of_pads_with_specified_values <add> groups = [] <add> <add> ('a'..'g').to_a.in_groups_of(3, 'foo') do |group| <add> groups << group <add> end <add> <add> assert_equal [%w(a b c), %w(d e f), %w(g foo foo)], groups <add> end <add> <add> def test_in_groups_of_without_padding <add> groups = [] <add> <add> ('a'..'g').to_a.in_groups_of(3, false) do |group| <add> groups << group <add> end <add> <add> assert_equal [%w(a b c), %w(d e f), %w(g)], groups <add> end <add> <add> def test_in_groups_returned_array_size <add> array = (1..7).to_a <add> <add> 1.upto(array.size + 1) do |number| <add> assert_equal number, array.in_groups(number).size <add> end <add> end <add> <add> def test_in_groups_with_empty_array <add> assert_equal [[], [], []], [].in_groups(3) <add> end <add> <add> def test_in_groups_with_block <add> array = (1..9).to_a <add> groups = [] <add> <add> array.in_groups(3) do |group| <add> groups << group <add> end <add> <add> assert_equal array.in_groups(3), groups <add> end <add> <add> def test_in_groups_with_perfect_fit <add> assert_equal [[1, 2, 3], [4, 5, 6], [7, 8, 9]], <add> (1..9).to_a.in_groups(3) <add> end <add> <add> def test_in_groups_with_padding <add> array = (1..7).to_a <add> <add> assert_equal [[1, 2, 3], [4, 5, nil], [6, 7, nil]], <add> array.in_groups(3) <add> assert_equal [[1, 2, 3], [4, 5, 'foo'], [6, 7, 'foo']], <add> array.in_groups(3, 'foo') <add> end <add> <add> def test_in_groups_without_padding <add> assert_equal [[1, 2, 3], [4, 5], [6, 7]], <add> (1..7).to_a.in_groups(3, false) <add> end <add>end <add> <add>class SplitTest < ActiveSupport::TestCase <add> def test_split_with_empty_array <add> assert_equal [[]], [].split(0) <add> end <add> <add> def test_split_with_argument <add> a = [1, 2, 3, 4, 5] <add> assert_equal [[1, 2], [4, 5]], a.split(3) <add> assert_equal [[1, 2, 3, 4, 5]], a.split(0) <add> assert_equal [1, 2, 3, 4, 5], a <add> end <add> <add> def test_split_with_block <add> a = (1..10).to_a <add> assert_equal [[1, 2], [4, 5], [7, 8], [10]], a.split { |i| i % 3 == 0 } <add> assert_equal [1, 2, 3, 4, 5, 6, 7, 8, 9 ,10], a <add> end <add> <add> def test_split_with_edge_values <add> a = [1, 2, 3, 4, 5] <add> assert_equal [[], [2, 3, 4, 5]], a.split(1) <add> assert_equal [[1, 2, 3, 4], []], a.split(5) <add> assert_equal [[], [2, 3, 4], []], a.split { |i| i == 1 || i == 5 } <add> assert_equal [1, 2, 3, 4, 5], a <add> end <add>end <ide><path>activesupport/test/core_ext/array/prepend_append_test.rb <add>require 'abstract_unit' <add>require 'active_support/core_ext/array' <add> <add>class PrependAppendTest < ActiveSupport::TestCase <add> def test_append <add> assert_equal [1, 2], [1].append(2) <add> end <add> <add> def test_prepend <add> assert_equal [2, 1], [1].prepend(2) <add> end <add>end <ide><path>activesupport/test/core_ext/array/wrap_test.rb <add>require 'abstract_unit' <add>require 'active_support/core_ext/array' <add> <add>class WrapTest < ActiveSupport::TestCase <add> class FakeCollection <add> def to_ary <add> ["foo", "bar"] <add> end <add> end <add> <add> class Proxy <add> def initialize(target) @target = target end <add> def method_missing(*a) @target.send(*a) end <add> end <add> <add> class DoubtfulToAry <add> def to_ary <add> :not_an_array <add> end <add> end <add> <add> class NilToAry <add> def to_ary <add> nil <add> end <add> end <add> <add> def test_array <add> ary = %w(foo bar) <add> assert_same ary, Array.wrap(ary) <add> end <add> <add> def test_nil <add> assert_equal [], Array.wrap(nil) <add> end <add> <add> def test_object <add> o = Object.new <add> assert_equal [o], Array.wrap(o) <add> end <add> <add> def test_string <add> assert_equal ["foo"], Array.wrap("foo") <add> end <add> <add> def test_string_with_newline <add> assert_equal ["foo\nbar"], Array.wrap("foo\nbar") <add> end <add> <add> def test_object_with_to_ary <add> assert_equal ["foo", "bar"], Array.wrap(FakeCollection.new) <add> end <add> <add> def test_proxy_object <add> p = Proxy.new(Object.new) <add> assert_equal [p], Array.wrap(p) <add> end <add> <add> def test_proxy_to_object_with_to_ary <add> p = Proxy.new(FakeCollection.new) <add> assert_equal [p], Array.wrap(p) <add> end <add> <add> def test_struct <add> o = Struct.new(:foo).new(123) <add> assert_equal [o], Array.wrap(o) <add> end <add> <add> def test_wrap_returns_wrapped_if_to_ary_returns_nil <add> o = NilToAry.new <add> assert_equal [o], Array.wrap(o) <add> end <add> <add> def test_wrap_does_not_complain_if_to_ary_does_not_return_an_array <add> assert_equal DoubtfulToAry.new.to_ary, Array.wrap(DoubtfulToAry.new) <add> end <add>end <ide><path>activesupport/test/core_ext/array_ext_test.rb <del>require 'abstract_unit' <del>require 'active_support/core_ext/array' <del>require 'active_support/core_ext/big_decimal' <del>require 'active_support/core_ext/hash' <del>require 'active_support/core_ext/object/conversions' <del>require 'active_support/core_ext/string' <del> <del>class ArrayExtAccessTests < ActiveSupport::TestCase <del> def test_from <del> assert_equal %w( a b c d ), %w( a b c d ).from(0) <del> assert_equal %w( c d ), %w( a b c d ).from(2) <del> assert_equal %w(), %w( a b c d ).from(10) <del> assert_equal %w( d e ), %w( a b c d e ).from(-2) <del> assert_equal %w(), %w( a b c d e ).from(-10) <del> end <del> <del> def test_to <del> assert_equal %w( a ), %w( a b c d ).to(0) <del> assert_equal %w( a b c ), %w( a b c d ).to(2) <del> assert_equal %w( a b c d ), %w( a b c d ).to(10) <del> assert_equal %w( a b c ), %w( a b c d ).to(-2) <del> assert_equal %w(), %w( a b c ).to(-10) <del> end <del> <del> def test_second_through_tenth <del> array = (1..42).to_a <del> <del> assert_equal array[1], array.second <del> assert_equal array[2], array.third <del> assert_equal array[3], array.fourth <del> assert_equal array[4], array.fifth <del> assert_equal array[41], array.forty_two <del> end <del>end <del> <del>class ArrayExtToParamTests < ActiveSupport::TestCase <del> class ToParam < String <del> def to_param <del> "#{self}1" <del> end <del> end <del> <del> def test_string_array <del> assert_equal '', %w().to_param <del> assert_equal 'hello/world', %w(hello world).to_param <del> assert_equal 'hello/10', %w(hello 10).to_param <del> end <del> <del> def test_number_array <del> assert_equal '10/20', [10, 20].to_param <del> end <del> <del> def test_to_param_array <del> assert_equal 'custom1/param1', [ToParam.new('custom'), ToParam.new('param')].to_param <del> end <del>end <del> <del>class ArrayExtToSentenceTests < ActiveSupport::TestCase <del> def test_plain_array_to_sentence <del> assert_equal "", [].to_sentence <del> assert_equal "one", ['one'].to_sentence <del> assert_equal "one and two", ['one', 'two'].to_sentence <del> assert_equal "one, two, and three", ['one', 'two', 'three'].to_sentence <del> end <del> <del> def test_to_sentence_with_words_connector <del> assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(:words_connector => ' ') <del> assert_equal "one & two, and three", ['one', 'two', 'three'].to_sentence(:words_connector => ' & ') <del> assert_equal "onetwo, and three", ['one', 'two', 'three'].to_sentence(:words_connector => nil) <del> end <del> <del> def test_to_sentence_with_last_word_connector <del> assert_equal "one, two, and also three", ['one', 'two', 'three'].to_sentence(:last_word_connector => ', and also ') <del> assert_equal "one, twothree", ['one', 'two', 'three'].to_sentence(:last_word_connector => nil) <del> assert_equal "one, two three", ['one', 'two', 'three'].to_sentence(:last_word_connector => ' ') <del> assert_equal "one, two and three", ['one', 'two', 'three'].to_sentence(:last_word_connector => ' and ') <del> end <del> <del> def test_two_elements <del> assert_equal "one and two", ['one', 'two'].to_sentence <del> assert_equal "one two", ['one', 'two'].to_sentence(:two_words_connector => ' ') <del> end <del> <del> def test_one_element <del> assert_equal "one", ['one'].to_sentence <del> end <del> <del> def test_one_element_not_same_object <del> elements = ["one"] <del> assert_not_equal elements[0].object_id, elements.to_sentence.object_id <del> end <del> <del> def test_one_non_string_element <del> assert_equal '1', [1].to_sentence <del> end <del> <del> def test_does_not_modify_given_hash <del> options = { words_connector: ' ' } <del> assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(options) <del> assert_equal({ words_connector: ' ' }, options) <del> end <del> <del> def test_with_blank_elements <del> assert_equal ", one, , two, and three", [nil, 'one', '', 'two', 'three'].to_sentence <del> end <del>end <del> <del>class ArrayExtToSTests < ActiveSupport::TestCase <del> def test_to_s_db <del> collection = [ <del> Class.new { def id() 1 end }.new, <del> Class.new { def id() 2 end }.new, <del> Class.new { def id() 3 end }.new <del> ] <del> <del> assert_equal "null", [].to_s(:db) <del> assert_equal "1,2,3", collection.to_s(:db) <del> end <del>end <del> <del>class ArrayExtGroupingTests < ActiveSupport::TestCase <del> def setup <del> Fixnum.send :private, :/ # test we avoid Integer#/ (redefined by mathn) <del> end <del> <del> def teardown <del> Fixnum.send :public, :/ <del> end <del> <del> def test_in_groups_of_with_perfect_fit <del> groups = [] <del> ('a'..'i').to_a.in_groups_of(3) do |group| <del> groups << group <del> end <del> <del> assert_equal [%w(a b c), %w(d e f), %w(g h i)], groups <del> assert_equal [%w(a b c), %w(d e f), %w(g h i)], ('a'..'i').to_a.in_groups_of(3) <del> end <del> <del> def test_in_groups_of_with_padding <del> groups = [] <del> ('a'..'g').to_a.in_groups_of(3) do |group| <del> groups << group <del> end <del> <del> assert_equal [%w(a b c), %w(d e f), ['g', nil, nil]], groups <del> end <del> <del> def test_in_groups_of_pads_with_specified_values <del> groups = [] <del> <del> ('a'..'g').to_a.in_groups_of(3, 'foo') do |group| <del> groups << group <del> end <del> <del> assert_equal [%w(a b c), %w(d e f), ['g', 'foo', 'foo']], groups <del> end <del> <del> def test_in_groups_of_without_padding <del> groups = [] <del> <del> ('a'..'g').to_a.in_groups_of(3, false) do |group| <del> groups << group <del> end <del> <del> assert_equal [%w(a b c), %w(d e f), ['g']], groups <del> end <del> <del> def test_in_groups_returned_array_size <del> array = (1..7).to_a <del> <del> 1.upto(array.size + 1) do |number| <del> assert_equal number, array.in_groups(number).size <del> end <del> end <del> <del> def test_in_groups_with_empty_array <del> assert_equal [[], [], []], [].in_groups(3) <del> end <del> <del> def test_in_groups_with_block <del> array = (1..9).to_a <del> groups = [] <del> <del> array.in_groups(3) do |group| <del> groups << group <del> end <del> <del> assert_equal array.in_groups(3), groups <del> end <del> <del> def test_in_groups_with_perfect_fit <del> assert_equal [[1, 2, 3], [4, 5, 6], [7, 8, 9]], <del> (1..9).to_a.in_groups(3) <del> end <del> <del> def test_in_groups_with_padding <del> array = (1..7).to_a <del> <del> assert_equal [[1, 2, 3], [4, 5, nil], [6, 7, nil]], <del> array.in_groups(3) <del> assert_equal [[1, 2, 3], [4, 5, 'foo'], [6, 7, 'foo']], <del> array.in_groups(3, 'foo') <del> end <del> <del> def test_in_groups_without_padding <del> assert_equal [[1, 2, 3], [4, 5], [6, 7]], <del> (1..7).to_a.in_groups(3, false) <del> end <del>end <del> <del>class ArraySplitTests < ActiveSupport::TestCase <del> def test_split_with_empty_array <del> assert_equal [[]], [].split(0) <del> end <del> <del> def test_split_with_argument <del> a = [1, 2, 3, 4, 5] <del> assert_equal [[1, 2], [4, 5]], a.split(3) <del> assert_equal [[1, 2, 3, 4, 5]], a.split(0) <del> assert_equal [1, 2, 3, 4, 5], a <del> end <del> <del> def test_split_with_block <del> a = (1..10).to_a <del> assert_equal [[1, 2], [4, 5], [7, 8], [10]], a.split { |i| i % 3 == 0 } <del> assert_equal [1, 2, 3, 4, 5, 6, 7, 8, 9 ,10], a <del> end <del> <del> def test_split_with_edge_values <del> a = [1, 2, 3, 4, 5] <del> assert_equal [[], [2, 3, 4, 5]], a.split(1) <del> assert_equal [[1, 2, 3, 4], []], a.split(5) <del> assert_equal [[], [2, 3, 4], []], a.split { |i| i == 1 || i == 5 } <del> assert_equal [1, 2, 3, 4, 5], a <del> end <del>end <del> <del>class ArrayToXmlTests < ActiveSupport::TestCase <del> def test_to_xml_with_hash_elements <del> xml = [ <del> { :name => "David", :age => 26, :age_in_millis => 820497600000 }, <del> { :name => "Jason", :age => 31, :age_in_millis => BigDecimal.new('1.0') } <del> ].to_xml(:skip_instruct => true, :indent => 0) <del> <del> assert_equal '<objects type="array"><object>', xml.first(30) <del> assert xml.include?(%(<age type="integer">26</age>)), xml <del> assert xml.include?(%(<age-in-millis type="integer">820497600000</age-in-millis>)), xml <del> assert xml.include?(%(<name>David</name>)), xml <del> assert xml.include?(%(<age type="integer">31</age>)), xml <del> assert xml.include?(%(<age-in-millis type="decimal">1.0</age-in-millis>)), xml <del> assert xml.include?(%(<name>Jason</name>)), xml <del> end <del> <del> def test_to_xml_with_non_hash_elements <del> xml = [1, 2, 3].to_xml(:skip_instruct => true, :indent => 0) <del> <del> assert_equal '<fixnums type="array"><fixnum', xml.first(29) <del> assert xml.include?(%(<fixnum type="integer">2</fixnum>)), xml <del> end <del> <del> def test_to_xml_with_non_hash_different_type_elements <del> xml = [1, 2.0, '3'].to_xml(:skip_instruct => true, :indent => 0) <del> <del> assert_equal '<objects type="array"><object', xml.first(29) <del> assert xml.include?(%(<object type="integer">1</object>)), xml <del> assert xml.include?(%(<object type="float">2.0</object>)), xml <del> assert xml.include?(%(object>3</object>)), xml <del> end <del> <del> def test_to_xml_with_dedicated_name <del> xml = [ <del> { :name => "David", :age => 26, :age_in_millis => 820497600000 }, { :name => "Jason", :age => 31 } <del> ].to_xml(:skip_instruct => true, :indent => 0, :root => "people") <del> <del> assert_equal '<people type="array"><person>', xml.first(29) <del> end <del> <del> def test_to_xml_with_options <del> xml = [ <del> { :name => "David", :street_address => "Paulina" }, { :name => "Jason", :street_address => "Evergreen" } <del> ].to_xml(:skip_instruct => true, :skip_types => true, :indent => 0) <del> <del> assert_equal "<objects><object>", xml.first(17) <del> assert xml.include?(%(<street-address>Paulina</street-address>)) <del> assert xml.include?(%(<name>David</name>)) <del> assert xml.include?(%(<street-address>Evergreen</street-address>)) <del> assert xml.include?(%(<name>Jason</name>)) <del> end <del> <del> def test_to_xml_with_indent_set <del> xml = [ <del> { :name => "David", :street_address => "Paulina" }, { :name => "Jason", :street_address => "Evergreen" } <del> ].to_xml(:skip_instruct => true, :skip_types => true, :indent => 4) <del> <del> assert_equal "<objects>\n <object>", xml.first(22) <del> assert xml.include?(%(\n <street-address>Paulina</street-address>)) <del> assert xml.include?(%(\n <name>David</name>)) <del> assert xml.include?(%(\n <street-address>Evergreen</street-address>)) <del> assert xml.include?(%(\n <name>Jason</name>)) <del> end <del> <del> def test_to_xml_with_dasherize_false <del> xml = [ <del> { :name => "David", :street_address => "Paulina" }, { :name => "Jason", :street_address => "Evergreen" } <del> ].to_xml(:skip_instruct => true, :skip_types => true, :indent => 0, :dasherize => false) <del> <del> assert_equal "<objects><object>", xml.first(17) <del> assert xml.include?(%(<street_address>Paulina</street_address>)) <del> assert xml.include?(%(<street_address>Evergreen</street_address>)) <del> end <del> <del> def test_to_xml_with_dasherize_true <del> xml = [ <del> { :name => "David", :street_address => "Paulina" }, { :name => "Jason", :street_address => "Evergreen" } <del> ].to_xml(:skip_instruct => true, :skip_types => true, :indent => 0, :dasherize => true) <del> <del> assert_equal "<objects><object>", xml.first(17) <del> assert xml.include?(%(<street-address>Paulina</street-address>)) <del> assert xml.include?(%(<street-address>Evergreen</street-address>)) <del> end <del> <del> def test_to_xml_with_instruct <del> xml = [ <del> { :name => "David", :age => 26, :age_in_millis => 820497600000 }, <del> { :name => "Jason", :age => 31, :age_in_millis => BigDecimal.new('1.0') } <del> ].to_xml(:skip_instruct => false, :indent => 0) <del> <del> assert_match(/^<\?xml [^>]*/, xml) <del> assert_equal 0, xml.rindex(/<\?xml /) <del> end <del> <del> def test_to_xml_with_block <del> xml = [ <del> { :name => "David", :age => 26, :age_in_millis => 820497600000 }, <del> { :name => "Jason", :age => 31, :age_in_millis => BigDecimal.new('1.0') } <del> ].to_xml(:skip_instruct => true, :indent => 0) do |builder| <del> builder.count 2 <del> end <del> <del> assert xml.include?(%(<count>2</count>)), xml <del> end <del> <del> def test_to_xml_with_empty <del> xml = [].to_xml <del> assert_match(/type="array"\/>/, xml) <del> end <del> <del> def test_to_xml_dups_options <del> options = {:skip_instruct => true} <del> [].to_xml(options) <del> # :builder, etc, shouldn't be added to options <del> assert_equal({:skip_instruct => true}, options) <del> end <del>end <del> <del>class ArrayExtractOptionsTests < ActiveSupport::TestCase <del> class HashSubclass < Hash <del> end <del> <del> class ExtractableHashSubclass < Hash <del> def extractable_options? <del> true <del> end <del> end <del> <del> def test_extract_options <del> assert_equal({}, [].extract_options!) <del> assert_equal({}, [1].extract_options!) <del> assert_equal({:a=>:b}, [{:a=>:b}].extract_options!) <del> assert_equal({:a=>:b}, [1, {:a=>:b}].extract_options!) <del> end <del> <del> def test_extract_options_doesnt_extract_hash_subclasses <del> hash = HashSubclass.new <del> hash[:foo] = 1 <del> array = [hash] <del> options = array.extract_options! <del> assert_equal({}, options) <del> assert_equal [hash], array <del> end <del> <del> def test_extract_options_extracts_extractable_subclass <del> hash = ExtractableHashSubclass.new <del> hash[:foo] = 1 <del> array = [hash] <del> options = array.extract_options! <del> assert_equal({:foo => 1}, options) <del> assert_equal [], array <del> end <del> <del> def test_extract_options_extracts_hwia <del> hash = [{:foo => 1}.with_indifferent_access] <del> options = hash.extract_options! <del> assert_equal 1, options[:foo] <del> end <del>end <del> <del>class ArrayWrapperTests < ActiveSupport::TestCase <del> class FakeCollection <del> def to_ary <del> ["foo", "bar"] <del> end <del> end <del> <del> class Proxy <del> def initialize(target) @target = target end <del> def method_missing(*a) @target.send(*a) end <del> end <del> <del> class DoubtfulToAry <del> def to_ary <del> :not_an_array <del> end <del> end <del> <del> class NilToAry <del> def to_ary <del> nil <del> end <del> end <del> <del> def test_array <del> ary = %w(foo bar) <del> assert_same ary, Array.wrap(ary) <del> end <del> <del> def test_nil <del> assert_equal [], Array.wrap(nil) <del> end <del> <del> def test_object <del> o = Object.new <del> assert_equal [o], Array.wrap(o) <del> end <del> <del> def test_string <del> assert_equal ["foo"], Array.wrap("foo") <del> end <del> <del> def test_string_with_newline <del> assert_equal ["foo\nbar"], Array.wrap("foo\nbar") <del> end <del> <del> def test_object_with_to_ary <del> assert_equal ["foo", "bar"], Array.wrap(FakeCollection.new) <del> end <del> <del> def test_proxy_object <del> p = Proxy.new(Object.new) <del> assert_equal [p], Array.wrap(p) <del> end <del> <del> def test_proxy_to_object_with_to_ary <del> p = Proxy.new(FakeCollection.new) <del> assert_equal [p], Array.wrap(p) <del> end <del> <del> def test_struct <del> o = Struct.new(:foo).new(123) <del> assert_equal [o], Array.wrap(o) <del> end <del> <del> def test_wrap_returns_wrapped_if_to_ary_returns_nil <del> o = NilToAry.new <del> assert_equal [o], Array.wrap(o) <del> end <del> <del> def test_wrap_does_not_complain_if_to_ary_does_not_return_an_array <del> assert_equal DoubtfulToAry.new.to_ary, Array.wrap(DoubtfulToAry.new) <del> end <del>end <del> <del>class ArrayPrependAppendTest < ActiveSupport::TestCase <del> def test_append <del> assert_equal [1, 2], [1].append(2) <del> end <del> <del> def test_prepend <del> assert_equal [2, 1], [1].prepend(2) <del> end <del>end
7
Ruby
Ruby
extract helper from stray file checks
6a020239d14d5a5d8a8853f8d619b0d4b6b1b57a
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_for_macgpg2 <ide> end unless File.exist? '/usr/local/MacGPG2/share/gnupg/VERSION' <ide> end <ide> <del>def check_for_stray_dylibs <del> unbrewed_dylibs = Dir['/usr/local/lib/*.dylib'].select { |f| File.file? f and not File.symlink? f } <add>def __check_stray_files(pattern, white_list, message) <add> files = Dir[pattern].select { |f| File.file? f and not File.symlink? f } <add> bad = files.reject {|d| white_list.key? File.basename(d) } <add> inject_file_list(bad, message) unless bad.empty? <add>end <ide> <add>def check_for_stray_dylibs <ide> # Dylibs which are generally OK should be added to this list, <ide> # with a short description of the software they come with. <ide> white_list = { <ide> "libfuse.2.dylib" => "MacFuse", <ide> "libfuse_ino64.2.dylib" => "MacFuse" <ide> } <ide> <del> bad_dylibs = unbrewed_dylibs.reject {|d| white_list.key? File.basename(d) } <del> return if bad_dylibs.empty? <del> <del> s = <<-EOS.undent <add> __check_stray_files '/usr/local/lib/*.dylib', white_list, <<-EOS.undent <ide> Unbrewed dylibs were found in /usr/local/lib. <ide> If you didn't put them there on purpose they could cause problems when <ide> building Homebrew formulae, and may need to be deleted. <ide> <ide> Unexpected dylibs: <ide> EOS <del> inject_file_list(bad_dylibs, s) <ide> end <ide> <ide> def check_for_stray_static_libs <del> unbrewed_alibs = Dir['/usr/local/lib/*.a'].select { |f| File.file? f and not File.symlink? f } <del> <ide> # Static libs which are generally OK should be added to this list, <ide> # with a short description of the software they come with. <ide> white_list = { <ide> "libsecurity_agent_client.a" => "OS X 10.8.2 Supplemental Update", <ide> "libsecurity_agent_server.a" => "OS X 10.8.2 Supplemental Update" <ide> } <ide> <del> bad_alibs = unbrewed_alibs.reject {|d| white_list.key? File.basename(d) } <del> return if bad_alibs.empty? <del> <del> s = <<-EOS.undent <add> __check_stray_files '/usr/local/lib/*.a', white_list, <<-EOS.undent <ide> Unbrewed static libraries were found in /usr/local/lib. <ide> If you didn't put them there on purpose they could cause problems when <ide> building Homebrew formulae, and may need to be deleted. <ide> <ide> Unexpected static libraries: <ide> EOS <del> inject_file_list(bad_alibs, s) <ide> end <ide> <ide> def check_for_stray_pcs <del> unbrewed_pcs = Dir['/usr/local/lib/pkgconfig/*.pc'].select { |f| File.file? f and not File.symlink? f } <del> <ide> # Package-config files which are generally OK should be added to this list, <ide> # with a short description of the software they come with. <del> white_list = { } <add> white_list = {} <ide> <del> bad_pcs = unbrewed_pcs.reject {|d| white_list.key? File.basename(d) } <del> return if bad_pcs.empty? <del> <del> s = <<-EOS.undent <add> __check_stray_files '/usr/local/lib/pkgconfig/*.pc', white_list, <<-EOS.undent <ide> Unbrewed .pc files were found in /usr/local/lib/pkgconfig. <ide> If you didn't put them there on purpose they could cause problems when <ide> building Homebrew formulae, and may need to be deleted. <ide> <ide> Unexpected .pc files: <ide> EOS <del> inject_file_list(bad_pcs, s) <ide> end <ide> <ide> def check_for_stray_las <del> unbrewed_las = Dir['/usr/local/lib/*.la'].select { |f| File.file? f and not File.symlink? f } <del> <ide> white_list = { <ide> "libfuse.la" => "MacFuse", <ide> "libfuse_ino64.la" => "MacFuse", <ide> } <ide> <del> bad_las = unbrewed_las.reject {|d| white_list.key? File.basename(d) } <del> return if bad_las.empty? <del> <del> s = <<-EOS.undent <add> __check_stray_files '/usr/local/lib/*.la', white_list, <<-EOS.undent <ide> Unbrewed .la files were found in /usr/local/lib. <ide> If you didn't put them there on purpose they could cause problems when <ide> building Homebrew formulae, and may need to be deleted. <ide> <ide> Unexpected .la files: <ide> EOS <del> inject_file_list(bad_las, s) <ide> end <ide> <ide> def check_for_other_package_managers
1
Javascript
Javascript
ignore mocks in packager
84a681cea9217a1a2621064dd1cee9f9179fb2dd
<ide><path>Libraries/BatchedBridge/__mocks__/MessageQueueTestModule.js <ide> * LICENSE file in the root directory of this source tree. An additional grant <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> * <del> * @providesModule MessageQueueTestModule <ide> */ <ide> 'use strict'; <ide>
1
Javascript
Javascript
pass proxylogger to params
2297881f91724390adb18c648f57a669bcc529d5
<ide><path>client/src/templates/Challenges/redux/execute-challenge-saga.js <ide> const testWorker = new WorkerExecutor('test-evaluator'); <ide> const testTimeout = 5000; <ide> <ide> function* ExecuteChallengeSaga() { <add> const consoleProxy = yield channel(); <ide> try { <ide> const { js, bonfire, backend } = challengeTypes; <ide> const { challengeType } = yield select(challengeMetaSelector); <ide> <ide> yield put(initLogs()); <ide> yield put(initConsole('// running tests')); <add> yield fork(logToConsole, consoleProxy); <ide> <ide> let testResults; <ide> switch (challengeType) { <ide> case js: <ide> case bonfire: <del> testResults = yield ExecuteJSChallengeSaga(); <add> testResults = yield ExecuteJSChallengeSaga(consoleProxy); <ide> break; <ide> case backend: <del> testResults = yield ExecuteBackendChallengeSaga(); <add> testResults = yield ExecuteBackendChallengeSaga(consoleProxy); <ide> break; <ide> default: <del> testResults = yield ExecuteDOMChallengeSaga(); <add> testResults = yield ExecuteDOMChallengeSaga(consoleProxy); <ide> } <ide> <ide> yield put(updateTests(testResults)); <ide> yield put(updateConsole('// tests completed')); <ide> yield put(logsToConsole('// console output')); <ide> } catch (e) { <ide> yield put(updateConsole(e)); <add> } finally { <add> consoleProxy.close(); <ide> } <ide> } <ide> <ide> function* logToConsole(channel) { <ide> }); <ide> } <ide> <del>function* ExecuteJSChallengeSaga() { <add>function* ExecuteJSChallengeSaga(proxyLogger) { <ide> const files = yield select(challengeFilesSelector); <ide> const { code, solution } = yield call(buildJSFromFiles, files); <ide> <del> const consoleProxy = yield channel(); <del> yield fork(logToConsole, consoleProxy); <del> const log = args => consoleProxy.put(args); <add> const log = args => proxyLogger.put(args); <ide> testWorker.on('LOG', log); <ide> <del> const testResults = yield call(executeTests, (testString, testTimeout) => <del> testWorker <del> .execute({ script: solution + '\n' + testString, code }, testTimeout) <del> .then(result => { <del> testWorker.killWorker(); <del> return result; <del> }) <del> ); <del> <del> testWorker.remove('LOG', log); <del> consoleProxy.close(); <del> return testResults; <add> try { <add> return yield call(executeTests, (testString, testTimeout) => <add> testWorker <add> .execute({ script: solution + '\n' + testString, code }, testTimeout) <add> .then(result => { <add> testWorker.killWorker(); <add> return result; <add> }) <add> ); <add> } finally { <add> testWorker.remove('LOG', log); <add> } <ide> } <ide> <ide> function createTestFrame(state, ctx, proxyLogger) { <ide> function createTestFrame(state, ctx, proxyLogger) { <ide> }); <ide> } <ide> <del>function* ExecuteDOMChallengeSaga() { <add>function* ExecuteDOMChallengeSaga(proxyLogger) { <ide> const state = yield select(); <ide> const ctx = yield call(buildHtmlFromFiles, state); <del> const consoleProxy = yield channel(); <del> yield fork(logToConsole, consoleProxy); <ide> <del> yield call(createTestFrame, state, ctx, consoleProxy); <add> yield call(createTestFrame, state, ctx, proxyLogger); <ide> // wait for a code execution on a "ready" event in jQuery challenges <ide> yield delay(100); <ide> <del> const testResults = yield call(executeTests, (testString, testTimeout) => <add> return yield call(executeTests, (testString, testTimeout) => <ide> Promise.race([ <ide> runTestInTestFrame(document, testString), <ide> new Promise((_, reject) => <ide> setTimeout(() => reject('timeout'), testTimeout) <ide> ) <ide> ]) <ide> ); <del> <del> consoleProxy.close(); <del> return testResults; <ide> } <ide> <ide> // TODO: use a web worker <del>function* ExecuteBackendChallengeSaga() { <add>function* ExecuteBackendChallengeSaga(proxyLogger) { <ide> const state = yield select(); <ide> const ctx = yield call(buildBackendChallenge, state); <del> const consoleProxy = yield channel(); <ide> <del> yield call(createTestFrame, state, ctx, consoleProxy); <add> yield call(createTestFrame, state, ctx, proxyLogger); <ide> <del> const testResults = yield call(executeTests, (testString, testTimeout) => <add> return yield call(executeTests, (testString, testTimeout) => <ide> Promise.race([ <ide> runTestInTestFrame(document, testString), <ide> new Promise((_, reject) => <ide> setTimeout(() => reject('timeout'), testTimeout) <ide> ) <ide> ]) <ide> ); <del> <del> consoleProxy.close(); <del> return testResults; <ide> } <ide> <ide> function* executeTests(testRunner) {
1
Python
Python
fix wrong masked median for some special cases
2144aa713b607a5f0592525d9b36adca332e9d51
<ide><path>numpy/lib/tests/test_nanfunctions.py <ide> def test_float_special(self): <ide> a = np.array([[inf, inf], [inf, inf]]) <ide> assert_equal(np.nanmedian(a, axis=1), inf) <ide> <add> a = np.array([[inf, 7, -inf, -9], <add> [-10, np.nan, np.nan, 5], <add> [4, np.nan, np.nan, inf]], <add> dtype=np.float32) <add> if inf > 0: <add> assert_equal(np.nanmedian(a, axis=0), [4., 7., -inf, 5.]) <add> assert_equal(np.nanmedian(a), 4.5) <add> else: <add> assert_equal(np.nanmedian(a, axis=0), [-10., 7., -inf, -9.]) <add> assert_equal(np.nanmedian(a), -2.5) <add> assert_equal(np.nanmedian(a, axis=-1), [-1., -2.5, inf]) <add> <ide> for i in range(0, 10): <ide> for j in range(1, 10): <ide> a = np.array([([np.nan] * i) + ([inf] * j)] * 2) <ide><path>numpy/ma/extras.py <ide> def _median(a, axis=None, out=None, overwrite_input=False): <ide> ind[axis] = np.minimum(h, asorted.shape[axis] - 1) <ide> high = asorted[tuple(ind)] <ide> <add> def replace_masked(s): <add> # Replace masked entries with minimum_full_value unless it all values <add> # are masked. This is required as the sort order of values equal or <add> # larger than the fill value is undefined and a valid value placed <add> # elsewhere, e.g. [4, --, inf]. <add> if np.ma.is_masked(s): <add> rep = (~np.all(asorted.mask, axis=axis)) & s.mask <add> s.data[rep] = np.ma.minimum_fill_value(asorted) <add> s.mask[rep] = False <add> <add> replace_masked(low) <add> replace_masked(high) <add> <ide> # duplicate high if odd number of elements so mean does nothing <ide> odd = counts % 2 == 1 <ide> np.copyto(low, high, where=odd) <ide> def _median(a, axis=None, out=None, overwrite_input=False): <ide> else: <ide> s = np.ma.mean([low, high], axis=0, out=out) <ide> <del> # if result is masked either the input contained enough minimum_fill_value <del> # so that it would be the median or all values masked <del> if np.ma.is_masked(s): <del> rep = (~np.all(asorted.mask, axis=axis)) & s.mask <del> s.data[rep] = np.ma.minimum_fill_value(asorted) <del> s.mask[rep] = False <ide> return s <ide> <ide> <ide><path>numpy/ma/tests/test_extras.py <ide> def test_inf(self): <ide> r = np.ma.median(np.ma.masked_array([[np.inf, np.inf], <ide> [np.inf, np.inf]]), axis=None) <ide> assert_equal(r, np.inf) <add> # all masked <add> r = np.ma.median(np.ma.masked_array([[np.inf, np.inf], <add> [np.inf, np.inf]], mask=True), <add> axis=-1) <add> assert_equal(r.mask, True) <add> r = np.ma.median(np.ma.masked_array([[np.inf, np.inf], <add> [np.inf, np.inf]], mask=True), <add> axis=None) <add> assert_equal(r.mask, True) <ide> <ide> def test_non_masked(self): <ide> x = np.arange(9) <ide> def test_special(self): <ide> assert_equal(np.ma.median(a, axis=0), inf) <ide> assert_equal(np.ma.median(a, axis=1), inf) <ide> <add> a = np.array([[inf, 7, -inf, -9], <add> [-10, np.nan, np.nan, 5], <add> [4, np.nan, np.nan, inf]], <add> dtype=np.float32) <add> a = np.ma.masked_array(a, mask=np.isnan(a)) <add> if inf > 0: <add> assert_equal(np.ma.median(a, axis=0), [4., 7., -inf, 5.]) <add> assert_equal(np.ma.median(a), 4.5) <add> else: <add> assert_equal(np.ma.median(a, axis=0), [-10., 7., -inf, -9.]) <add> assert_equal(np.ma.median(a), -2.5) <add> assert_equal(np.ma.median(a, axis=1), [-1., -2.5, inf]) <add> <ide> for i in range(0, 10): <ide> for j in range(1, 10): <ide> a = np.array([([np.nan] * i) + ([inf] * j)] * 2)
3
Python
Python
remove injecting of `keras_preprocessing`
064f2d3f446a384abd1ebdd9ded8ac47dad9b4fc
<ide><path>keras/preprocessing/__init__.py <ide> # limitations under the License. <ide> # ============================================================================== <ide> """Provides keras data preprocessing utils to pre-process tf.data.Datasets before they are fed to the model.""" <del># pylint: disable=g-import-not-at-top <del># TODO(mihaimaruseac): remove the import of keras_preprocessing and injecting <del># once we update to latest version of keras_preprocessing <del>import keras_preprocessing <del> <ide> from keras import backend <ide> from keras.preprocessing import image <ide> from keras.preprocessing import sequence <ide> from keras.preprocessing import text <ide> from keras.preprocessing import timeseries <ide> from keras.utils import all_utils as utils <del> <del># This exists for compatibility with prior version of keras_preprocessing. <del>keras_preprocessing.set_keras_submodules(backend=backend, utils=utils)
1
Java
Java
add support for custom androidviews
1fabd8604836f54764852bafdac41dd55a84b0ed
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNode.java <ide> public ThemedReactContext getThemedContext() { <ide> return Assertions.assertNotNull(mThemedContext); <ide> } <ide> <del> protected void setThemedContext(ThemedReactContext themedContext) { <add> public void setThemedContext(ThemedReactContext themedContext) { <ide> mThemedContext = themedContext; <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java <ide> protected final ReactShadowNode resolveShadowNode(int reactTag) { <ide> return mShadowNodeRegistry.getNode(reactTag); <ide> } <ide> <add> protected final ViewManager resolveViewManager(String className) { <add> return mViewManagers.get(className); <add> } <add> <ide> /** <ide> * Registers a root node with a given tag, size and ThemedReactContext <ide> * and adds it to a node registry. <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputShadowNode.java <ide> public ReactTextInputShadowNode() { <ide> } <ide> <ide> @Override <del> protected void setThemedContext(ThemedReactContext themedContext) { <add> public void setThemedContext(ThemedReactContext themedContext) { <ide> super.setThemedContext(themedContext); <ide> <ide> // TODO #7120264: cache this stuff better
3
Ruby
Ruby
add docs to collectionassociation#many?
3c91c8127050c7abbe091c19052f9813a62b1af7
<ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> def any? <ide> end <ide> end <ide> <del> # Returns true if the collection has more than 1 record. Equivalent to collection.size > 1. <add> # Returns true if the collection has more than 1 record. <add> # Equivalent to +collection.size > 1+. <add> # <add> # class Person < ActiveRecord::Base <add> # has_many :pets <add> # end <add> # <add> # person.pets.count #=> 1 <add> # person.pets.many? #=> false <add> # <add> # person.pets << Pet.new(name: 'Snoopy') <add> # person.pets.count #=> 2 <add> # person.pets.many? #=> true <add> # <add> # Also, you can pass a block to define a criteria. The <add> # behaviour is the same, it returns true if the collection <add> # based on the criteria has more than 1 record. <add> # <add> # person.pets <add> # # => [ <add> # # #<Pet name: "GorbyPuff", group: "cats">, <add> # # #<Pet name: "Wy", group: "cats">, <add> # # #<Pet name: "Snoop", group: "dogs"> <add> # # ] <add> # <add> # person.pets.many? do |pet| <add> # pet.group == 'dogs' <add> # end <add> # # => false <add> # <add> # person.pets.many? do |pet| <add> # pet.group == 'cats' <add> # end <add> # # => true <ide> def many? <ide> if block_given? <ide> load_target.many? { |*block_args| yield(*block_args) }
1
Ruby
Ruby
improve handling of --version/-v option
233a38ac9542db8eff93ffbcb305694da875bb69
<ide><path>Library/brew.rb <ide> $:.unshift(HOMEBREW_LIBRARY_PATH.to_s) <ide> require "global" <ide> <del>if ARGV.first == "--version" <del> puts Homebrew.homebrew_version_string <add>if ARGV == %w[--version] || ARGV == %w[-v] <add> puts "Homebrew #{Homebrew.homebrew_version_string}" <ide> exit 0 <ide> elsif ARGV.first == "-v" <del> puts "Homebrew #{Homebrew.homebrew_version_string}" <ide> # Shift the -v to the end of the parameter list <ide> ARGV << ARGV.shift <del> # If no other arguments, just quit here. <del> exit 0 if ARGV.length == 1 <ide> end <ide> <ide> if OS.mac?
1
Go
Go
remove useless wait in run
a5b765a769736171d05692aff3abdf3f02dfe5be
<ide><path>commands.go <ide> func CmdRun(args ...string) error { <ide> if err != nil { <ide> return err <ide> } <del> var status int <add> <ide> if config.AttachStdin || config.AttachStdout || config.AttachStderr { <ide> if err := hijack("POST", "/containers/"+out.Id+"/attach?"+v.Encode(), config.Tty); err != nil { <ide> return err <ide> } <del> body, _, err := call("POST", "/containers/"+out.Id+"/wait", nil) <del> if err != nil { <del> fmt.Printf("%s", err) <del> } else { <del> var out ApiWait <del> err = json.Unmarshal(body, &out) <del> if err != nil { <del> return err <del> } <del> status = out.StatusCode <del> } <ide> } <ide> <ide> if !config.AttachStdout && !config.AttachStderr { <ide> fmt.Println(out.Id) <ide> } <del> <del> if status != 0 { <del> os.Exit(status) <del> } <ide> return nil <ide> } <ide> <ide> func hijack(method, path string, setRawTerminal bool) error { <ide> <ide> sendStdin := Go(func() error { <ide> _, err := io.Copy(rwc, os.Stdin) <del> rwc.Close() <add> if err := rwc.(*net.TCPConn).CloseWrite(); err != nil { <add> fmt.Fprintf(os.Stderr, "Couldn't send EOF: " + err.Error()) <add> } <ide> return err <ide> }) <ide>
1
Go
Go
modify test to include /dev/shm sharing
457aeaa2e1bdbb75c5b3bcedacde460920965c2f
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunModeIpcHost(c *check.C) { <ide> func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) { <ide> testRequires(c, SameHostDaemon) <ide> <del> out, _ := dockerCmd(c, "run", "-d", "busybox", "top") <add> out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && top") <ide> <ide> id := strings.TrimSpace(out) <ide> state, err := inspectField(id, "State.Running") <ide> func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) { <ide> if parentContainerIpc != out { <ide> c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out) <ide> } <add> <add> catOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "cat", "/dev/shm/test") <add> if catOutput != "test" { <add> c.Fatalf("Output of /dev/shm/test expected test but found: %s", catOutput) <add> } <ide> } <ide> <ide> func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
1
Text
Text
add readme file for token dropping bert
cdccf02cda475c5e6a505e0ac3730e5e933b44bc
<ide><path>official/projects/token_dropping/README.md <add># Token Dropping for Efficient BERT Pretraining <add> <add>The token dropping method aims to accelerate the pretraining of transformer <add>models such as BERT without degrading its performance on downstream tasks. In <add>particular, we drop unimportant tokens starting from an intermediate layer in <add>the model, to make the model focus on important tokens more efficiently with its <add>limited computational resources. The dropped tokens are later picked up by the <add>last layer of the model, so that the model still produces full-length sequences. <add>We leverage the already built-in masked language modeling (MLM) loss and its <add>dynamics to identify unimportant tokens with practically no computational <add>overhead. In our experiments, this simple approach reduces the pretraining cost <add>of BERT by 25% while achieving slightly better overall fine-tuning performance <add>on standard downstream tasks. <add> <add>A BERT model pretrained using this token dropping method is not different to <add>a BERT model pretrained in the conventional way: a BERT checkpoint pretrained <add>with token dropping can be viewed and used as a normal BERT checkpoint, for <add>finetuning etc. Thus, this README file only illustrates how to run token <add>dropping for pretraining. <add> <add>### Requirements <add> <add>The starter code requires Tensorflow. If you haven't installed it yet, follow <add>the instructions on [tensorflow.org][1]. <add>This code has been tested with Tensorflow 2.5.0. Going forward, <add>we will continue to target the latest released version of Tensorflow. <add> <add>Please verify that you have Python 3.6+ and Tensorflow 2.5.0 or higher <add>installed by running the following commands: <add> <add>```sh <add>python --version <add>python -c 'import tensorflow as tf; print(tf.__version__)' <add>``` <add> <add>Refer to the [instructions here][2] <add>for using the model in this repo. Make sure to add the models folder to your <add>Python path. <add> <add>[1]: https://www.tensorflow.org/install/ <add>[2]: <add>https://github.com/tensorflow/models/tree/master/official#running-the-models <add> <add>Then, you need to generate pretraining data. See <add>[this instruction] <add>(https://github.com/tensorflow/models/blob/27fb855b027ead16d2616dcb59c67409a2176b7f/official/legacy/bert/README.md#pre-training) <add>on how to do that. <add> <add>## Train using the config file. <add> <add>After you generated your pretraining data, run the following command to start <add>pretraining: <add> <add>```bash <add>PARAMS="task.train_data.input_data=/path/to/train/data" <add>PARAMS="${PARAMS},task.validation_data.input_path=/path/to/validation/data" <add>PARAMS="${PARAMS},runtime.distribution_strategy=tpu" <add> <add>python3 train.py \ <add> --experiment=token_drop_bert/pretraining \ <add> --config_file=wiki_books_pretrain_sequence_pack.yaml \ <add> --config_file=bert_en_uncased_base_token_drop.yaml \ <add> --params_override=${PARAMS} \ <add> --tpu=local \ <add> --model_dir=/folder/to/hold/logs/and/models/ \ <add> --mode=train_and_eval <add>``` <add> <add>## Implementation <add> <add>We implement the encoder and layers using `tf.keras` APIs in NLP <add>modeling library: <add> <add> * [masked_lm.py](https://github.com/tensorflow/models/blob/master/official/projects/token_dropping/masked_lm.py) <add> contains the BERT pretraining task. <add> <add> * [experiment_configs.py](https://github.com/tensorflow/models/blob/master/official/projects/token_dropping/experiment_configs.py) <add> registers the token dropping experiment. <add> <add> * [encoder.py](https://github.com/tensorflow/models/blob/master/official/projects/token_dropping/encoder.py) <add> contains the BERT encoder that supports token dropping. <add> <add> * [encoder_config.py](https://github.com/tensorflow/models/blob/master/official/projects/token_dropping/encoder_config.py) <add> contains the config and method for instantiating the token dropping BERT <add> encoder. <add> <add> * [train.py](https://github.com/tensorflow/models/blob/master/official/projects/token_dropping/train.py) <add> is the program entry.
1
PHP
PHP
apply fixes from styleci
4d66ce89c8865ecec0e079f41bb9ea98ce7f7255
<ide><path>src/Illuminate/Queue/WorkerOptions.php <ide> class WorkerOptions <ide> * @param bool $stopWhenEmpty <ide> * @return void <ide> */ <del> public function __construct($name= 'default', $backoff = 0, $memory = 128, $timeout = 60, $sleep = 3, $maxTries = 1, $force = false, $stopWhenEmpty = false) <add> public function __construct($name = 'default', $backoff = 0, $memory = 128, $timeout = 60, $sleep = 3, $maxTries = 1, $force = false, $stopWhenEmpty = false) <ide> { <ide> $this->name = $name; <ide> $this->backoff = $backoff;
1
Ruby
Ruby
add docs for eager_laod and preload
91c8d91536b1f41f0c4518e67b4bf31b1ef4f109
<ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def includes!(*args) <ide> self <ide> end <ide> <add> # Forces eager loading by performing a LEFT OUTER JOIN on +args+: <add> # <add> # User.eager_load(:posts) <add> # => SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ... <add> # FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = <add> # "users"."id" <ide> def eager_load(*args) <ide> args.blank? ? self : spawn.eager_load!(*args) <ide> end <ide> def eager_load!(*args) <ide> self <ide> end <ide> <add> # Allows preloading of +args+, in the same way that +includes+ does: <add> # <add> # User.preload(:posts) <add> # => SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3) <ide> def preload(*args) <ide> args.blank? ? self : spawn.preload!(*args) <ide> end
1
Python
Python
use correct separator
7ecfe7d20f8708a1dada5761cdc02905b0e370e5
<ide><path>scripts/ci/wheel_factory.py <ide> req_file = open(args.file, 'r') <ide> <ide> for req in requirements.parse(req_file): <del> print "Checking " + args.wheeldir + os.path.pathsep + req.name + "*.whl" <del> if not glob.glob(args.wheeldir + os.path.pathsep + req.name + "*.whl"): <add> print "Checking " + args.wheeldir + os.path.sep + req.name + "*.whl" <add> if not glob.glob(args.wheeldir + os.path.sep + req.name + "*.whl"): <ide> os.system("pip wheel --wheel-dir=" + args.wheeldir + " " + req.name + "".join(req.specs) + "".join(req.extras))
1
Javascript
Javascript
convert the find controller to es6 syntax
9a95d91b923a0622ec9ab3a6bcd58021e6922f42
<ide><path>web/pdf_find_bar.js <ide> * limitations under the License. <ide> */ <ide> <del>import { FindStates } from './pdf_find_controller'; <add>import { FindState } from './pdf_find_controller'; <ide> import { NullL10n } from './ui_utils'; <ide> <ide> /** <ide> class PDFFindBar { <ide> var status = ''; <ide> <ide> switch (state) { <del> case FindStates.FIND_FOUND: <add> case FindState.FOUND: <ide> break; <ide> <del> case FindStates.FIND_PENDING: <add> case FindState.PENDING: <ide> status = 'pending'; <ide> break; <ide> <del> case FindStates.FIND_NOTFOUND: <add> case FindState.NOT_FOUND: <ide> findMsg = this.l10n.get('find_not_found', null, 'Phrase not found'); <ide> notFound = true; <ide> break; <ide> <del> case FindStates.FIND_WRAPPED: <add> case FindState.WRAPPED: <ide> if (previous) { <ide> findMsg = this.l10n.get('find_reached_top', null, <ide> 'Reached top of document, continued from bottom'); <ide><path>web/pdf_find_controller.js <ide> import { createPromiseCapability } from 'pdfjs-lib'; <ide> import { scrollIntoView } from './ui_utils'; <ide> <del>var FindStates = { <del> FIND_FOUND: 0, <del> FIND_NOTFOUND: 1, <del> FIND_WRAPPED: 2, <del> FIND_PENDING: 3, <add>const FindState = { <add> FOUND: 0, <add> NOT_FOUND: 1, <add> WRAPPED: 2, <add> PENDING: 3, <ide> }; <ide> <del>var FIND_SCROLL_OFFSET_TOP = -50; <del>var FIND_SCROLL_OFFSET_LEFT = -400; <add>const FIND_SCROLL_OFFSET_TOP = -50; <add>const FIND_SCROLL_OFFSET_LEFT = -400; <add>const FIND_TIMEOUT = 250; // ms <ide> <del>var CHARACTERS_TO_NORMALIZE = { <add>const CHARACTERS_TO_NORMALIZE = { <ide> '\u2018': '\'', // Left single quotation mark <ide> '\u2019': '\'', // Right single quotation mark <ide> '\u201A': '\'', // Single low-9 quotation mark <ide> var CHARACTERS_TO_NORMALIZE = { <ide> }; <ide> <ide> /** <del> * Provides "search" or "find" functionality for the PDF. <del> * This object actually performs the search for a given string. <add> * Provides search functionality to find a given string in a PDF document. <ide> */ <del>var PDFFindController = (function PDFFindControllerClosure() { <del> function PDFFindController(options) { <del> this.pdfViewer = options.pdfViewer || null; <add>class PDFFindController { <add> constructor({ pdfViewer, }) { <add> this.pdfViewer = pdfViewer; <ide> <ide> this.onUpdateResultsCount = null; <ide> this.onUpdateState = null; <ide> <ide> this.reset(); <ide> <ide> // Compile the regular expression for text normalization once. <del> var replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(''); <add> let replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(''); <ide> this.normalizationRegex = new RegExp('[' + replace + ']', 'g'); <ide> } <ide> <del> PDFFindController.prototype = { <del> reset: function PDFFindController_reset() { <del> this.startedTextExtraction = false; <del> this.extractTextPromises = []; <del> this.pendingFindMatches = Object.create(null); <del> this.active = false; // If active, find results will be highlighted. <del> this.pageContents = []; // Stores the text for each page. <del> this.pageMatches = []; <del> this.pageMatchesLength = null; <del> this.matchCount = 0; <del> this.selected = { // Currently selected match. <del> pageIdx: -1, <del> matchIdx: -1, <del> }; <del> this.offset = { // Where the find algorithm currently is in the document. <del> pageIdx: null, <del> matchIdx: null, <del> }; <del> this.pagesToSearch = null; <del> this.resumePageIdx = null; <del> this.state = null; <del> this.dirtyMatch = false; <del> this.findTimeout = null; <add> reset() { <add> this.startedTextExtraction = false; <add> this.extractTextPromises = []; <add> this.pendingFindMatches = Object.create(null); <add> this.active = false; // If active, find results will be highlighted. <add> this.pageContents = []; // Stores the text for each page. <add> this.pageMatches = []; <add> this.pageMatchesLength = null; <add> this.matchCount = 0; <add> this.selected = { // Currently selected match. <add> pageIdx: -1, <add> matchIdx: -1, <add> }; <add> this.offset = { // Where the find algorithm currently is in the document. <add> pageIdx: null, <add> matchIdx: null, <add> }; <add> this.pagesToSearch = null; <add> this.resumePageIdx = null; <add> this.state = null; <add> this.dirtyMatch = false; <add> this.findTimeout = null; <add> <add> this._firstPagePromise = new Promise((resolve) => { <add> this.resolveFirstPage = resolve; <add> }); <add> } <ide> <del> this._firstPagePromise = new Promise((resolve) => { <del> this.resolveFirstPage = resolve; <del> }); <del> }, <add> normalize(text) { <add> return text.replace(this.normalizationRegex, function (ch) { <add> return CHARACTERS_TO_NORMALIZE[ch]; <add> }); <add> } <ide> <del> normalize: function PDFFindController_normalize(text) { <del> return text.replace(this.normalizationRegex, function (ch) { <del> return CHARACTERS_TO_NORMALIZE[ch]; <del> }); <del> }, <del> <del> // Helper for multiple search - fills matchesWithLength array <del> // and takes into account cases when one search term <del> // include another search term (for example, "tamed tame" or "this is"). <del> // Looking for intersecting terms in the 'matches' and <del> // leave elements with a longer match-length. <del> <del> _prepareMatches: function PDFFindController_prepareMatches( <del> matchesWithLength, matches, matchesLength) { <del> <del> function isSubTerm(matchesWithLength, currentIndex) { <del> var currentElem, prevElem, nextElem; <del> currentElem = matchesWithLength[currentIndex]; <del> nextElem = matchesWithLength[currentIndex + 1]; <del> // checking for cases like "TAMEd TAME" <del> if (currentIndex < matchesWithLength.length - 1 && <del> currentElem.match === nextElem.match) { <del> currentElem.skipped = true; <del> return true; <del> } <del> // checking for cases like "thIS IS" <del> for (var i = currentIndex - 1; i >= 0; i--) { <del> prevElem = matchesWithLength[i]; <del> if (prevElem.skipped) { <del> continue; <del> } <del> if (prevElem.match + prevElem.matchLength < currentElem.match) { <del> break; <del> } <del> if (prevElem.match + prevElem.matchLength >= <del> currentElem.match + currentElem.matchLength) { <del> currentElem.skipped = true; <del> return true; <del> } <del> } <del> return false; <add> /** <add> * Helper for multi-term search that fills the `matchesWithLength` array <add> * and handles cases where one search term includes another search term (for <add> * example, "tamed tame" or "this is"). It looks for intersecting terms in <add> * the `matches` and keeps elements with a longer match length. <add> */ <add> _prepareMatches(matchesWithLength, matches, matchesLength) { <add> function isSubTerm(matchesWithLength, currentIndex) { <add> let currentElem = matchesWithLength[currentIndex]; <add> let nextElem = matchesWithLength[currentIndex + 1]; <add> <add> // Check for cases like "TAMEd TAME". <add> if (currentIndex < matchesWithLength.length - 1 && <add> currentElem.match === nextElem.match) { <add> currentElem.skipped = true; <add> return true; <ide> } <ide> <del> var i, len; <del> // Sorting array of objects { match: <match>, matchLength: <matchLength> } <del> // in increasing index first and then the lengths. <del> matchesWithLength.sort(function(a, b) { <del> return a.match === b.match ? <del> a.matchLength - b.matchLength : a.match - b.match; <del> }); <del> for (i = 0, len = matchesWithLength.length; i < len; i++) { <del> if (isSubTerm(matchesWithLength, i)) { <add> // Check for cases like "thIS IS". <add> for (let i = currentIndex - 1; i >= 0; i--) { <add> let prevElem = matchesWithLength[i]; <add> if (prevElem.skipped) { <ide> continue; <ide> } <del> matches.push(matchesWithLength[i].match); <del> matchesLength.push(matchesWithLength[i].matchLength); <del> } <del> }, <del> <del> calcFindPhraseMatch: function PDFFindController_calcFindPhraseMatch( <del> query, pageIndex, pageContent) { <del> var matches = []; <del> var queryLen = query.length; <del> var matchIdx = -queryLen; <del> while (true) { <del> matchIdx = pageContent.indexOf(query, matchIdx + queryLen); <del> if (matchIdx === -1) { <add> if (prevElem.match + prevElem.matchLength < currentElem.match) { <ide> break; <ide> } <del> matches.push(matchIdx); <del> } <del> this.pageMatches[pageIndex] = matches; <del> }, <del> <del> calcFindWordMatch: function PDFFindController_calcFindWordMatch( <del> query, pageIndex, pageContent) { <del> var matchesWithLength = []; <del> // Divide the query into pieces and search for text on each piece. <del> var queryArray = query.match(/\S+/g); <del> var subquery, subqueryLen, matchIdx; <del> for (var i = 0, len = queryArray.length; i < len; i++) { <del> subquery = queryArray[i]; <del> subqueryLen = subquery.length; <del> matchIdx = -subqueryLen; <del> while (true) { <del> matchIdx = pageContent.indexOf(subquery, matchIdx + subqueryLen); <del> if (matchIdx === -1) { <del> break; <del> } <del> // Other searches do not, so we store the length. <del> matchesWithLength.push({ <del> match: matchIdx, <del> matchLength: subqueryLen, <del> skipped: false, <del> }); <add> if (prevElem.match + prevElem.matchLength >= <add> currentElem.match + currentElem.matchLength) { <add> currentElem.skipped = true; <add> return true; <ide> } <ide> } <del> // Prepare arrays for store the matches. <del> if (!this.pageMatchesLength) { <del> this.pageMatchesLength = []; <del> } <del> this.pageMatchesLength[pageIndex] = []; <del> this.pageMatches[pageIndex] = []; <del> // Sort matchesWithLength, clean up intersecting terms <del> // and put the result into the two arrays. <del> this._prepareMatches(matchesWithLength, this.pageMatches[pageIndex], <del> this.pageMatchesLength[pageIndex]); <del> }, <del> <del> calcFindMatch: function PDFFindController_calcFindMatch(pageIndex) { <del> var pageContent = this.normalize(this.pageContents[pageIndex]); <del> var query = this.normalize(this.state.query); <del> var caseSensitive = this.state.caseSensitive; <del> var phraseSearch = this.state.phraseSearch; <del> var queryLen = query.length; <del> <del> if (queryLen === 0) { <del> // Do nothing: the matches should be wiped out already. <del> return; <add> return false; <add> } <add> <add> // Sort the array of `{ match: <match>, matchLength: <matchLength> }` <add> // objects on increasing index first and on the length otherwise. <add> matchesWithLength.sort(function(a, b) { <add> return a.match === b.match ? a.matchLength - b.matchLength : <add> a.match - b.match; <add> }); <add> for (let i = 0, len = matchesWithLength.length; i < len; i++) { <add> if (isSubTerm(matchesWithLength, i)) { <add> continue; <ide> } <add> matches.push(matchesWithLength[i].match); <add> matchesLength.push(matchesWithLength[i].matchLength); <add> } <add> } <ide> <del> if (!caseSensitive) { <del> pageContent = pageContent.toLowerCase(); <del> query = query.toLowerCase(); <add> calcFindPhraseMatch(query, pageIndex, pageContent) { <add> let matches = []; <add> let queryLen = query.length; <add> let matchIdx = -queryLen; <add> while (true) { <add> matchIdx = pageContent.indexOf(query, matchIdx + queryLen); <add> if (matchIdx === -1) { <add> break; <ide> } <add> matches.push(matchIdx); <add> } <add> this.pageMatches[pageIndex] = matches; <add> } <ide> <del> if (phraseSearch) { <del> this.calcFindPhraseMatch(query, pageIndex, pageContent); <del> } else { <del> this.calcFindWordMatch(query, pageIndex, pageContent); <add> calcFindWordMatch(query, pageIndex, pageContent) { <add> let matchesWithLength = []; <add> // Divide the query into pieces and search for text in each piece. <add> let queryArray = query.match(/\S+/g); <add> for (let i = 0, len = queryArray.length; i < len; i++) { <add> let subquery = queryArray[i]; <add> let subqueryLen = subquery.length; <add> let matchIdx = -subqueryLen; <add> while (true) { <add> matchIdx = pageContent.indexOf(subquery, matchIdx + subqueryLen); <add> if (matchIdx === -1) { <add> break; <add> } <add> // Other searches do not, so we store the length. <add> matchesWithLength.push({ <add> match: matchIdx, <add> matchLength: subqueryLen, <add> skipped: false, <add> }); <ide> } <add> } <add> <add> // Prepare arrays for storing the matches. <add> if (!this.pageMatchesLength) { <add> this.pageMatchesLength = []; <add> } <add> this.pageMatchesLength[pageIndex] = []; <add> this.pageMatches[pageIndex] = []; <add> <add> // Sort `matchesWithLength`, remove intersecting terms and put the result <add> // into the two arrays. <add> this._prepareMatches(matchesWithLength, this.pageMatches[pageIndex], <add> this.pageMatchesLength[pageIndex]); <add> } <ide> <del> this.updatePage(pageIndex); <del> if (this.resumePageIdx === pageIndex) { <del> this.resumePageIdx = null; <del> this.nextPageMatch(); <del> } <add> calcFindMatch(pageIndex) { <add> let pageContent = this.normalize(this.pageContents[pageIndex]); <add> let query = this.normalize(this.state.query); <add> let caseSensitive = this.state.caseSensitive; <add> let phraseSearch = this.state.phraseSearch; <add> let queryLen = query.length; <add> <add> if (queryLen === 0) { <add> // Do nothing: the matches should be wiped out already. <add> return; <add> } <add> <add> if (!caseSensitive) { <add> pageContent = pageContent.toLowerCase(); <add> query = query.toLowerCase(); <add> } <add> <add> if (phraseSearch) { <add> this.calcFindPhraseMatch(query, pageIndex, pageContent); <add> } else { <add> this.calcFindWordMatch(query, pageIndex, pageContent); <add> } <add> <add> this.updatePage(pageIndex); <add> if (this.resumePageIdx === pageIndex) { <add> this.resumePageIdx = null; <add> this.nextPageMatch(); <add> } <ide> <del> // Update the matches count <del> if (this.pageMatches[pageIndex].length > 0) { <del> this.matchCount += this.pageMatches[pageIndex].length; <del> this.updateUIResultsCount(); <del> } <del> }, <add> // Update the match count. <add> if (this.pageMatches[pageIndex].length > 0) { <add> this.matchCount += this.pageMatches[pageIndex].length; <add> this.updateUIResultsCount(); <add> } <add> } <ide> <del> extractText() { <del> if (this.startedTextExtraction) { <del> return; <del> } <del> this.startedTextExtraction = true; <del> this.pageContents.length = 0; <del> <del> let promise = Promise.resolve(); <del> for (let i = 0, ii = this.pdfViewer.pagesCount; i < ii; i++) { <del> let extractTextCapability = createPromiseCapability(); <del> this.extractTextPromises[i] = extractTextCapability.promise; <del> <del> promise = promise.then(() => { <del> return this.pdfViewer.getPageTextContent(i).then((textContent) => { <del> let textItems = textContent.items; <del> let strBuf = []; <del> <del> for (let j = 0, jj = textItems.length; j < jj; j++) { <del> strBuf.push(textItems[j].str); <del> } <del> // Store the pageContent as a string. <del> this.pageContents[i] = strBuf.join(''); <del> extractTextCapability.resolve(i); <del> }); <add> extractText() { <add> if (this.startedTextExtraction) { <add> return; <add> } <add> this.startedTextExtraction = true; <add> this.pageContents.length = 0; <add> <add> let promise = Promise.resolve(); <add> for (let i = 0, ii = this.pdfViewer.pagesCount; i < ii; i++) { <add> let extractTextCapability = createPromiseCapability(); <add> this.extractTextPromises[i] = extractTextCapability.promise; <add> <add> promise = promise.then(() => { <add> return this.pdfViewer.getPageTextContent(i).then((textContent) => { <add> let textItems = textContent.items; <add> let strBuf = []; <add> <add> for (let j = 0, jj = textItems.length; j < jj; j++) { <add> strBuf.push(textItems[j].str); <add> } <add> // Store the pageContent as a string. <add> this.pageContents[i] = strBuf.join(''); <add> extractTextCapability.resolve(i); <ide> }); <del> } <del> }, <del> <del> executeCommand: function PDFFindController_executeCommand(cmd, state) { <del> if (this.state === null || cmd !== 'findagain') { <del> this.dirtyMatch = true; <del> } <del> this.state = state; <del> this.updateUIState(FindStates.FIND_PENDING); <del> <del> this._firstPagePromise.then(() => { <del> this.extractText(); <del> <del> clearTimeout(this.findTimeout); <del> if (cmd === 'find') { <del> // Only trigger the find action after 250ms of silence. <del> this.findTimeout = setTimeout(this.nextMatch.bind(this), 250); <del> } else { <del> this.nextMatch(); <del> } <ide> }); <del> }, <del> <del> updatePage: function PDFFindController_updatePage(index) { <del> if (this.selected.pageIdx === index) { <del> // If the page is selected, scroll the page into view, which triggers <del> // rendering the page, which adds the textLayer. Once the textLayer is <del> // build, it will scroll onto the selected match. <del> this.pdfViewer.currentPageNumber = index + 1; <del> } <add> } <add> } <ide> <del> var page = this.pdfViewer.getPageView(index); <del> if (page.textLayer) { <del> page.textLayer.updateMatches(); <del> } <del> }, <del> <del> nextMatch: function PDFFindController_nextMatch() { <del> var previous = this.state.findPrevious; <del> var currentPageIndex = this.pdfViewer.currentPageNumber - 1; <del> var numPages = this.pdfViewer.pagesCount; <del> <del> this.active = true; <del> <del> if (this.dirtyMatch) { <del> // Need to recalculate the matches, reset everything. <del> this.dirtyMatch = false; <del> this.selected.pageIdx = this.selected.matchIdx = -1; <del> this.offset.pageIdx = currentPageIndex; <del> this.offset.matchIdx = null; <del> this.hadMatch = false; <del> this.resumePageIdx = null; <del> this.pageMatches = []; <del> this.matchCount = 0; <del> this.pageMatchesLength = null; <del> <del> for (let i = 0; i < numPages; i++) { <del> // Wipe out any previous highlighted matches. <del> this.updatePage(i); <del> <del> // As soon as the text is extracted start finding the matches. <del> if (!(i in this.pendingFindMatches)) { <del> this.pendingFindMatches[i] = true; <del> this.extractTextPromises[i].then((pageIdx) => { <del> delete this.pendingFindMatches[pageIdx]; <del> this.calcFindMatch(pageIdx); <del> }); <del> } <del> } <add> executeCommand(cmd, state) { <add> if (this.state === null || cmd !== 'findagain') { <add> this.dirtyMatch = true; <add> } <add> this.state = state; <add> this.updateUIState(FindState.PENDING); <add> <add> this._firstPagePromise.then(() => { <add> this.extractText(); <add> <add> clearTimeout(this.findTimeout); <add> if (cmd === 'find') { <add> // Trigger the find action with a small delay to avoid starting the <add> // search when the user is still typing (saving resources). <add> this.findTimeout = setTimeout(this.nextMatch.bind(this), FIND_TIMEOUT); <add> } else { <add> this.nextMatch(); <ide> } <add> }); <add> } <ide> <del> // If there's no query there's no point in searching. <del> if (this.state.query === '') { <del> this.updateUIState(FindStates.FIND_FOUND); <del> return; <del> } <add> updatePage(index) { <add> if (this.selected.pageIdx === index) { <add> // If the page is selected, scroll the page into view, which triggers <add> // rendering the page, which adds the textLayer. Once the textLayer is <add> // build, it will scroll onto the selected match. <add> this.pdfViewer.currentPageNumber = index + 1; <add> } <add> <add> let page = this.pdfViewer.getPageView(index); <add> if (page.textLayer) { <add> page.textLayer.updateMatches(); <add> } <add> } <ide> <del> // If we're waiting on a page, we return since we can't do anything else. <del> if (this.resumePageIdx) { <del> return; <del> } <add> nextMatch() { <add> let previous = this.state.findPrevious; <add> let currentPageIndex = this.pdfViewer.currentPageNumber - 1; <add> let numPages = this.pdfViewer.pagesCount; <ide> <del> var offset = this.offset; <del> // Keep track of how many pages we should maximally iterate through. <del> this.pagesToSearch = numPages; <del> // If there's already a matchIdx that means we are iterating through a <del> // page's matches. <del> if (offset.matchIdx !== null) { <del> var numPageMatches = this.pageMatches[offset.pageIdx].length; <del> if ((!previous && offset.matchIdx + 1 < numPageMatches) || <del> (previous && offset.matchIdx > 0)) { <del> // The simple case; we just have advance the matchIdx to select <del> // the next match on the page. <del> this.hadMatch = true; <del> offset.matchIdx = (previous ? offset.matchIdx - 1 : <del> offset.matchIdx + 1); <del> this.updateMatch(true); <del> return; <del> } <del> // We went beyond the current page's matches, so we advance to <del> // the next page. <del> this.advanceOffsetPage(previous); <del> } <del> // Start searching through the page. <del> this.nextPageMatch(); <del> }, <add> this.active = true; <add> <add> if (this.dirtyMatch) { <add> // Need to recalculate the matches, reset everything. <add> this.dirtyMatch = false; <add> this.selected.pageIdx = this.selected.matchIdx = -1; <add> this.offset.pageIdx = currentPageIndex; <add> this.offset.matchIdx = null; <add> this.hadMatch = false; <add> this.resumePageIdx = null; <add> this.pageMatches = []; <add> this.matchCount = 0; <add> this.pageMatchesLength = null; <ide> <del> matchesReady: function PDFFindController_matchesReady(matches) { <del> var offset = this.offset; <del> var numMatches = matches.length; <del> var previous = this.state.findPrevious; <add> for (let i = 0; i < numPages; i++) { <add> // Wipe out any previously highlighted matches. <add> this.updatePage(i); <ide> <del> if (numMatches) { <del> // There were matches for the page, so initialize the matchIdx. <add> // Start finding the matches as soon as the text is extracted. <add> if (!(i in this.pendingFindMatches)) { <add> this.pendingFindMatches[i] = true; <add> this.extractTextPromises[i].then((pageIdx) => { <add> delete this.pendingFindMatches[pageIdx]; <add> this.calcFindMatch(pageIdx); <add> }); <add> } <add> } <add> } <add> <add> // If there's no query there's no point in searching. <add> if (this.state.query === '') { <add> this.updateUIState(FindState.FOUND); <add> return; <add> } <add> <add> // If we're waiting on a page, we return since we can't do anything else. <add> if (this.resumePageIdx) { <add> return; <add> } <add> <add> let offset = this.offset; <add> // Keep track of how many pages we should maximally iterate through. <add> this.pagesToSearch = numPages; <add> // If there's already a `matchIdx` that means we are iterating through a <add> // page's matches. <add> if (offset.matchIdx !== null) { <add> let numPageMatches = this.pageMatches[offset.pageIdx].length; <add> if ((!previous && offset.matchIdx + 1 < numPageMatches) || <add> (previous && offset.matchIdx > 0)) { <add> // The simple case; we just have advance the matchIdx to select <add> // the next match on the page. <ide> this.hadMatch = true; <del> offset.matchIdx = (previous ? numMatches - 1 : 0); <add> offset.matchIdx = (previous ? offset.matchIdx - 1 : <add> offset.matchIdx + 1); <ide> this.updateMatch(true); <del> return true; <add> return; <ide> } <del> // No matches, so attempt to search the next page. <add> // We went beyond the current page's matches, so we advance to <add> // the next page. <ide> this.advanceOffsetPage(previous); <del> if (offset.wrapped) { <del> offset.matchIdx = null; <del> if (this.pagesToSearch < 0) { <del> // No point in wrapping again, there were no matches. <del> this.updateMatch(false); <del> // while matches were not found, searching for a page <del> // with matches should nevertheless halt. <del> return true; <del> } <del> } <del> // Matches were not found (and searching is not done). <del> return false; <del> }, <del> <del> /** <del> * The method is called back from the text layer when match presentation <del> * is updated. <del> * @param {number} pageIndex - page index. <del> * @param {number} index - match index. <del> * @param {Array} elements - text layer div elements array. <del> * @param {number} beginIdx - start index of the div array for the match. <del> */ <del> updateMatchPosition: function PDFFindController_updateMatchPosition( <del> pageIndex, index, elements, beginIdx) { <del> if (this.selected.matchIdx === index && <del> this.selected.pageIdx === pageIndex) { <del> var spot = { <del> top: FIND_SCROLL_OFFSET_TOP, <del> left: FIND_SCROLL_OFFSET_LEFT, <del> }; <del> scrollIntoView(elements[beginIdx], spot, <del> /* skipOverflowHiddenElements = */ true); <add> } <add> // Start searching through the page. <add> this.nextPageMatch(); <add> } <add> <add> matchesReady(matches) { <add> let offset = this.offset; <add> let numMatches = matches.length; <add> let previous = this.state.findPrevious; <add> <add> if (numMatches) { <add> // There were matches for the page, so initialize `matchIdx`. <add> this.hadMatch = true; <add> offset.matchIdx = (previous ? numMatches - 1 : 0); <add> this.updateMatch(true); <add> return true; <add> } <add> // No matches, so attempt to search the next page. <add> this.advanceOffsetPage(previous); <add> if (offset.wrapped) { <add> offset.matchIdx = null; <add> if (this.pagesToSearch < 0) { <add> // No point in wrapping again, there were no matches. <add> this.updateMatch(false); <add> // While matches were not found, searching for a page <add> // with matches should nevertheless halt. <add> return true; <ide> } <del> }, <add> } <add> // Matches were not found (and searching is not done). <add> return false; <add> } <add> <add> /** <add> * Called from the text layer when match presentation is updated. <add> * <add> * @param {number} pageIndex - The index of the page. <add> * @param {number} matchIndex - The index of the match. <add> * @param {Array} elements - Text layer `div` elements. <add> * @param {number} beginIdx - Start index of the `div` array for the match. <add> */ <add> updateMatchPosition(pageIndex, matchIndex, elements, beginIdx) { <add> if (this.selected.matchIdx === matchIndex && <add> this.selected.pageIdx === pageIndex) { <add> let spot = { <add> top: FIND_SCROLL_OFFSET_TOP, <add> left: FIND_SCROLL_OFFSET_LEFT, <add> }; <add> scrollIntoView(elements[beginIdx], spot, <add> /* skipOverflowHiddenElements = */ true); <add> } <add> } <ide> <del> nextPageMatch: function PDFFindController_nextPageMatch() { <del> if (this.resumePageIdx !== null) { <del> console.error('There can only be one pending page.'); <add> nextPageMatch() { <add> if (this.resumePageIdx !== null) { <add> console.error('There can only be one pending page.'); <add> } <add> <add> let matches = null; <add> do { <add> let pageIdx = this.offset.pageIdx; <add> matches = this.pageMatches[pageIdx]; <add> if (!matches) { <add> // The matches don't exist yet for processing by `matchesReady`, <add> // so set a resume point for when they do exist. <add> this.resumePageIdx = pageIdx; <add> break; <ide> } <del> do { <del> var pageIdx = this.offset.pageIdx; <del> var matches = this.pageMatches[pageIdx]; <del> if (!matches) { <del> // The matches don't exist yet for processing by "matchesReady", <del> // so set a resume point for when they do exist. <del> this.resumePageIdx = pageIdx; <del> break; <del> } <del> } while (!this.matchesReady(matches)); <del> }, <add> } while (!this.matchesReady(matches)); <add> } <ide> <del> advanceOffsetPage: function PDFFindController_advanceOffsetPage(previous) { <del> var offset = this.offset; <del> var numPages = this.extractTextPromises.length; <del> offset.pageIdx = (previous ? offset.pageIdx - 1 : offset.pageIdx + 1); <del> offset.matchIdx = null; <add> advanceOffsetPage(previous) { <add> let offset = this.offset; <add> let numPages = this.extractTextPromises.length; <add> offset.pageIdx = (previous ? offset.pageIdx - 1 : offset.pageIdx + 1); <add> offset.matchIdx = null; <ide> <del> this.pagesToSearch--; <add> this.pagesToSearch--; <ide> <del> if (offset.pageIdx >= numPages || offset.pageIdx < 0) { <del> offset.pageIdx = (previous ? numPages - 1 : 0); <del> offset.wrapped = true; <del> } <del> }, <del> <del> updateMatch: function PDFFindController_updateMatch(found) { <del> var state = FindStates.FIND_NOTFOUND; <del> var wrapped = this.offset.wrapped; <del> this.offset.wrapped = false; <del> <del> if (found) { <del> var previousPage = this.selected.pageIdx; <del> this.selected.pageIdx = this.offset.pageIdx; <del> this.selected.matchIdx = this.offset.matchIdx; <del> state = (wrapped ? FindStates.FIND_WRAPPED : FindStates.FIND_FOUND); <del> // Update the currently selected page to wipe out any selected matches. <del> if (previousPage !== -1 && previousPage !== this.selected.pageIdx) { <del> this.updatePage(previousPage); <del> } <del> } <add> if (offset.pageIdx >= numPages || offset.pageIdx < 0) { <add> offset.pageIdx = (previous ? numPages - 1 : 0); <add> offset.wrapped = true; <add> } <add> } <ide> <del> this.updateUIState(state, this.state.findPrevious); <del> if (this.selected.pageIdx !== -1) { <del> this.updatePage(this.selected.pageIdx); <del> } <del> }, <add> updateMatch(found = false) { <add> let state = FindState.NOT_FOUND; <add> let wrapped = this.offset.wrapped; <add> this.offset.wrapped = false; <ide> <del> updateUIResultsCount: <del> function PDFFindController_updateUIResultsCount() { <del> if (this.onUpdateResultsCount) { <del> this.onUpdateResultsCount(this.matchCount); <del> } <del> }, <add> if (found) { <add> let previousPage = this.selected.pageIdx; <add> this.selected.pageIdx = this.offset.pageIdx; <add> this.selected.matchIdx = this.offset.matchIdx; <add> state = (wrapped ? FindState.WRAPPED : FindState.FOUND); <ide> <del> updateUIState: function PDFFindController_updateUIState(state, previous) { <del> if (this.onUpdateState) { <del> this.onUpdateState(state, previous, this.matchCount); <add> // Update the currently selected page to wipe out any selected matches. <add> if (previousPage !== -1 && previousPage !== this.selected.pageIdx) { <add> this.updatePage(previousPage); <ide> } <del> }, <del> }; <del> return PDFFindController; <del>})(); <add> } <add> <add> this.updateUIState(state, this.state.findPrevious); <add> if (this.selected.pageIdx !== -1) { <add> this.updatePage(this.selected.pageIdx); <add> } <add> } <add> <add> updateUIResultsCount() { <add> if (this.onUpdateResultsCount) { <add> this.onUpdateResultsCount(this.matchCount); <add> } <add> } <add> <add> updateUIState(state, previous) { <add> if (this.onUpdateState) { <add> this.onUpdateState(state, previous, this.matchCount); <add> } <add> } <add>} <ide> <ide> export { <del> FindStates, <add> FindState, <ide> PDFFindController, <ide> };
2
Python
Python
reduce logger verbosity
d47cfee815f6a7ac42638d631dd76ac65601fecd
<ide><path>airflow/jobs.py <ide> def _execute(self): <ide> <ide> # Mark the task as not ready to run <ide> elif ti.state in (State.NONE, State.UPSTREAM_FAILED): <del> self.logger.debug('Added {} to not_ready'.format(ti)) <ide> not_ready.add(key) <ide> <ide> self.heartbeat() <ide><path>airflow/models.py <ide> def process_file(self, filepath, only_if_updated=True, safe_mode=True): <ide> filepath not in self.file_last_changed or <ide> dttm != self.file_last_changed[filepath]): <ide> try: <del> self.logger.info("Importing " + filepath) <add> self.logger.debug("Importing " + filepath) <ide> if mod_name in sys.modules: <ide> del sys.modules[mod_name] <ide> with timeout( <ide> def bag_dag(self, dag, parent_dag, root_dag): <ide> subdag.fileloc = root_dag.full_filepath <ide> subdag.is_subdag = True <ide> self.bag_dag(subdag, parent_dag=dag, root_dag=root_dag) <del> self.logger.info('Loaded DAG {dag}'.format(**locals())) <add> self.logger.debug('Loaded DAG {dag}'.format(**locals())) <ide> <ide> def collect_dags( <ide> self,
2
Python
Python
fix strtobool conversion tests on python 2
e9ede4086f547e812b0ee5f8e5ae2fc1175cb9de
<ide><path>t/unit/utils/test_serialization.py <ide> def test_default_table(self, s, b): <ide> <ide> def test_unknown_value(self): <ide> with pytest.raises(TypeError, <del> match="Cannot coerce 'foo' to type bool"): <add> # todo replace below when dropping python 2.7 <add> # match="Cannot coerce 'foo' to type bool"): <add> match=r"Cannot coerce u?'foo' to type bool"): <ide> strtobool('foo') <ide> <ide> def test_no_op(self):
1
Python
Python
fix tf error for separableconv1d when strides > 1
fb1887d132a8ce8548ff53d868a6ba531cd63b34
<ide><path>keras/backend/tensorflow_backend.py <ide> def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1, <ide> padding = _preprocess_padding(padding) <ide> if tf_data_format == 'NHWC': <ide> spatial_start_dim = 1 <del> strides = (1, 1) + strides + (1,) <add> strides = (1,) + strides * 2 + (1,) <ide> else: <ide> spatial_start_dim = 2 <del> strides = (1, 1, 1) + strides <add> strides = (1, 1) + strides * 2 <ide> x = tf.expand_dims(x, spatial_start_dim) <ide> depthwise_kernel = tf.expand_dims(depthwise_kernel, 0) <ide> pointwise_kernel = tf.expand_dims(pointwise_kernel, 0) <ide><path>tests/keras/layers/convolutional_test.py <ide> def test_separable_conv_1d(): <ide> num_step = 9 <ide> <ide> for padding in _convolution_paddings: <del> for multiplier in [1, 2]: <del> for dilation_rate in [1, 2]: <del> if padding == 'same': <del> continue <del> if dilation_rate != 1: <del> continue <add> for strides in [1, 2]: <add> for multiplier in [1, 2]: <add> for dilation_rate in [1, 2]: <add> if padding == 'same' and strides != 1: <add> continue <add> if dilation_rate != 1 and strides != 1: <add> continue <ide> <del> layer_test(convolutional.SeparableConv1D, <del> kwargs={'filters': filters, <del> 'kernel_size': 3, <del> 'padding': padding, <del> 'strides': 1, <del> 'depth_multiplier': multiplier, <del> 'dilation_rate': dilation_rate}, <del> input_shape=(num_samples, num_step, stack_size)) <add> layer_test(convolutional.SeparableConv1D, <add> kwargs={'filters': filters, <add> 'kernel_size': 3, <add> 'padding': padding, <add> 'strides': strides, <add> 'depth_multiplier': multiplier, <add> 'dilation_rate': dilation_rate}, <add> input_shape=(num_samples, num_step, stack_size)) <ide> <ide> layer_test(convolutional.SeparableConv1D, <ide> kwargs={'filters': filters,
2
Ruby
Ruby
remove unused `hstorepair` constant
e68cd6fe964a0ccb3072f37491c8942fa72834c0
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb <ide> def changed_in_place?(raw_old_value, new_value) <ide> end <ide> <ide> private <del> HstorePair = begin <del> quoted_string = /"([^"\\]*(?:\\.[^"\\]*)*)"/ <del> /#{quoted_string}\s*=>\s*(?:(?=NULL)|#{quoted_string})/ <del> end <del> <ide> def escape_hstore(value) <ide> if value.nil? <ide> "NULL"
1
Text
Text
fix wrong function arguments in the buffer.md
6050bbe60a9c9f0b95bda8fe5718209b4eb0028a
<ide><path>doc/api/buffer.md <ide> console.log(buf.lastIndexOf('buffer', 4)); <ide> const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); <ide> <ide> // Prints: 6 <del>console.log(utf16Buffer.lastIndexOf('\u03a3', null, 'ucs2')); <add>console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'ucs2')); <ide> <ide> // Prints: 4 <ide> console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'ucs2')); <ide> const buf = Buffer.from([0, 5]); <ide> console.log(buf.readInt16BE()); <ide> <ide> // Prints: 1280 <del>console.log(buf.readInt16LE(1)); <add>console.log(buf.readInt16LE()); <ide> <ide> // Throws an exception: RangeError: Index out of range <ide> console.log(buf.readInt16LE(1));
1
Java
Java
remove response content-type before error handling
e47f7ef7b51b8197d4c9b41c3a5b33e7cb62ef45
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/RequestMappingHandlerAdapter.java <ide> import org.springframework.context.ApplicationContextAware; <ide> import org.springframework.context.ConfigurableApplicationContext; <ide> import org.springframework.core.ReactiveAdapterRegistry; <add>import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.codec.HttpMessageReader; <ide> import org.springframework.http.codec.ServerCodecConfigurer; <ide> import org.springframework.lang.Nullable; <ide> private Mono<HandlerResult> handleException(Throwable exception, HandlerMethod h <ide> <ide> // Success and error responses may use different content types <ide> exchange.getAttributes().remove(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE); <add> if (!exchange.getResponse().isCommitted()) { <add> exchange.getResponse().getHeaders().remove(HttpHeaders.CONTENT_TYPE); <add> } <ide> <ide> InvocableHandlerMethod invocable = this.methodResolver.getExceptionHandlerMethod(exception, handlerMethod); <ide> if (invocable != null) { <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java <ide> public void exceptionAfterSeveralItems() { <ide> public void exceptionFromMethodWithProducesCondition() throws Exception { <ide> try { <ide> HttpHeaders headers = new HttpHeaders(); <del> headers.add("Accept", "text/csv, application/problem+json"); <add> headers.add("Accept", "text/plain, application/problem+json"); <ide> performGet("/SPR-16318", headers, String.class).getBody(); <ide> fail(); <ide> } <ide> public Flux<String> errors() { <ide> }); <ide> } <ide> <del> @GetMapping(path = "/SPR-16318", produces = "text/csv") <del> public String handleCsv() throws Exception { <del> throw new Spr16318Exception(); <add> @GetMapping(path = "/SPR-16318", produces = "text/plain") <add> public Mono<String> handleTextPlain() throws Exception { <add> return Mono.error(new Spr16318Exception()); <ide> } <ide> <ide> @ExceptionHandler
2
Ruby
Ruby
fix some typos found in activemodel
233737706cfe1a9b0d50140ca5c814a070b4b1be
<ide><path>activemodel/test/cases/callbacks_test.rb <ide> class Violin2 < Violin <ide> test "after_create callbacks with both callbacks declared in one line" do <ide> assert_equal ["callback1", "callback2"], Violin1.new.create.history <ide> end <del> test "after_create callbacks with both callbacks declared in differnt lines" do <add> test "after_create callbacks with both callbacks declared in different lines" do <ide> assert_equal ["callback1", "callback2"], Violin2.new.create.history <ide> end <ide> <ide><path>activemodel/test/cases/validations/with_validation_test.rb <ide> def check_validity! <ide> end <ide> end <ide> <del> test "vaidation with class that adds errors" do <add> test "validation with class that adds errors" do <ide> Topic.validates_with(ValidatorThatAddsErrors) <ide> topic = Topic.new <ide> assert topic.invalid?, "A class that adds errors causes the record to be invalid" <ide><path>activemodel/test/cases/validations_test.rb <ide> def teardown <ide> def test_single_field_validation <ide> r = Reply.new <ide> r.title = "There's no content!" <del> assert r.invalid?, "A reply without content shouldn't be saveable" <add> assert r.invalid?, "A reply without content shouldn't be savable" <ide> assert r.after_validation_performed, "after_validation callback should be called" <ide> <ide> r.content = "Messa content!" <del> assert r.valid?, "A reply with content should be saveable" <add> assert r.valid?, "A reply with content should be savable" <ide> assert r.after_validation_performed, "after_validation callback should be called" <ide> end <ide>
3
Python
Python
fix compute_accuracy() in mnist_siamese_graph.py
bd5d6162f1a6815588e8e9f48bc92201aa7e0ce4
<ide><path>examples/mnist_siamese_graph.py <ide> def create_base_network(input_dim): <ide> def compute_accuracy(predictions, labels): <ide> '''Compute classification accuracy with a fixed threshold on distances. <ide> ''' <del> return labels[predictions.ravel() < 0.5].mean() <add> preds = predictions.ravel() < 0.5 <add> return ((preds & labels).sum() + <add> (np.logical_not(preds) & np.logical_not(labels)).sum()) / float(labels.size) <ide> <ide> <ide> # the data, shuffled and split between train and test sets
1
Mixed
Ruby
fix bug with presence validation of associations
25262bc280e8c9c0e875315958f82230b67cbf35
<ide><path>activerecord/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* Fix bug with presence validation of associations. Would incorrectly add duplicated errors <add> when the association was blank. Bug introduced in 1fab518c6a75dac5773654646eb724a59741bc13. <add> <add> *Scott Willson* <add> <ide> * Fix bug where sum(expression) returns string '0' for no matching records <ide> Fixes #7439 <ide> <ide><path>activerecord/lib/active_record/validations/presence.rb <ide> def validate(record) <ide> super <ide> attributes.each do |attribute| <ide> next unless record.class.reflect_on_association(attribute) <del> value = record.send(attribute) <del> if Array(value).all? { |r| r.marked_for_destruction? } <add> associated_records = Array(record.send(attribute)) <add> <add> # Superclass validates presence. Ensure present records aren't about to be destroyed. <add> if associated_records.present? && associated_records.all? { |r| r.marked_for_destruction? } <ide> record.errors.add(attribute, :blank, options) <ide> end <ide> end <ide><path>activerecord/test/cases/validations/presence_validation_test.rb <ide> def test_validates_presence_of_non_association <ide> assert b.valid? <ide> end <ide> <add> def test_validates_presence_of_has_one <add> Boy.validates_presence_of(:face) <add> b = Boy.new <add> assert b.invalid?, "should not be valid if has_one association missing" <add> assert_equal 1, b.errors[:face].size, "validates_presence_of should only add one error" <add> end <add> <ide> def test_validates_presence_of_has_one_marked_for_destruction <ide> Boy.validates_presence_of(:face) <ide> b = Boy.new
3
Java
Java
fix resourcehttprequesthandler empty location log
bc5246938d07820305167e581e7a8ece23ed265e
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.http.MediaType; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <add>import org.springframework.util.CollectionUtils; <ide> import org.springframework.util.FileCopyUtils; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.HttpRequestHandler; <ide> public void setLocations(List<Resource> locations) { <ide> <ide> @Override <ide> public void afterPropertiesSet() throws Exception { <del> if (logger.isWarnEnabled()) { <add> if (logger.isWarnEnabled() && CollectionUtils.isEmpty(this.locations)) { <ide> logger.warn("Locations list is empty. No resources will be served"); <ide> } <ide> }
1
Python
Python
implement list_volumes for digitalocean
71eb9565e1092dcf4468ee88692745868c3f2d44
<ide><path>libcloud/compute/drivers/digitalocean.py <ide> from libcloud.compute.types import Provider, NodeState <ide> from libcloud.compute.base import NodeImage, NodeSize, NodeLocation, KeyPair <ide> from libcloud.compute.base import Node, NodeDriver <add>from libcloud.compute.base import StorageVolume <ide> <ide> __all__ = [ <ide> 'DigitalOceanNodeDriver', <ide> def list_sizes(self): <ide> data = self._paginated_request('/v2/sizes', 'sizes') <ide> return list(map(self._to_size, data)) <ide> <add> def list_volumes(self): <add> data = self._paginated_request('/v2/volumes', 'volumes') <add> return list(map(self._to_volume, data)) <add> <ide> def create_node(self, name, size, image, location, ex_create_attr=None, <ide> ex_ssh_key_ids=None, ex_user_data=None): <ide> """ <ide> def _to_image(self, data): <ide> return NodeImage(id=data['id'], name=data['name'], driver=self, <ide> extra=extra) <ide> <add> def _to_volume(self, data): <add> extra = {'created_at': data['created_at'], <add> 'droplet_ids': data['droplet_ids'], <add> 'region': data['region'], <add> 'region_slug': data['region']['slug']} <add> <add> return StorageVolume(id=data['id'], name=data['name'], <add> size=data['size_gigabytes'], driver=self, <add> extra=extra) <add> <ide> def _to_location(self, data): <ide> return NodeLocation(id=data['slug'], name=data['name'], country=None, <ide> driver=self)
1
PHP
PHP
change "login" text to "log in"
cbddb27c7e63eb1942efcdd95c8bd5bdf5be940f
<ide><path>resources/views/welcome.blade.php <ide> @auth <ide> <a href="{{ url('/home') }}" class="text-sm text-gray-700 underline">Home</a> <ide> @else <del> <a href="{{ route('login') }}" class="text-sm text-gray-700 underline">Login</a> <add> <a href="{{ route('login') }}" class="text-sm text-gray-700 underline">Log in</a> <ide> <ide> @if (Route::has('register')) <ide> <a href="{{ route('register') }}" class="ml-4 text-sm text-gray-700 underline">Register</a>
1
Text
Text
remove redundant line in docs
cd7a59c404e78da7b7378b9048e4238719a8a57e
<ide><path>docs/templates/activations.md <ide> You can also pass an element-wise TensorFlow/Theano/CNTK function as an activati <ide> from keras import backend as K <ide> <ide> model.add(Dense(64, activation=K.tanh)) <del>model.add(Activation(K.tanh)) <ide> ``` <ide> <ide> ## Available activations
1
PHP
PHP
fix mailable->priority()
3ef58e60e27baf5bac0a43cb95560f33a156bae9
<ide><path>src/Illuminate/Mail/Mailable.php <ide> public function locale($locale) <ide> public function priority($level = 3) <ide> { <ide> $this->callbacks[] = function ($message) use ($level) { <del> $message->setPriority($level); <add> $message->priority($level); <ide> }; <ide> <ide> return $this; <ide><path>tests/Mail/MailMailableTest.php <ide> <ide> namespace Illuminate\Tests\Mail; <ide> <add>use Illuminate\Contracts\View\Factory; <ide> use Illuminate\Mail\Mailable; <add>use Illuminate\Mail\Mailer; <add>use Illuminate\Mail\Transport\ArrayTransport; <add>use Mockery as m; <ide> use PHPUnit\Framework\TestCase; <ide> <ide> class MailMailableTest extends TestCase <ide> { <add> protected function tearDown(): void <add> { <add> m::close(); <add> } <add> <ide> public function testMailableSetsRecipientsCorrectly() <ide> { <ide> $mailable = new WelcomeMailableStub; <ide> public function testMailerMayBeSet() <ide> <ide> $this->assertSame('array', $mailable->mailer); <ide> } <add> <add> public function testMailablePriorityGetsSent() <add> { <add> $view = m::mock(Factory::class); <add> <add> $mailer = new Mailer('array', $view, new ArrayTransport); <add> <add> $mailable = new WelcomeMailableStub; <add> $mailable->to('hello@laravel.com'); <add> $mailable->from('taylor@laravel.com'); <add> $mailable->html('test content'); <add> <add> $mailable->priority(1); <add> <add> $sentMessage = $mailer->send($mailable); <add> <add> $this->assertSame('hello@laravel.com', $sentMessage->getEnvelope()->getRecipients()[0]->getAddress()); <add> $this->assertStringContainsString('X-Priority: 1 (Highest)', $sentMessage->toString()); <add> } <ide> } <ide> <ide> class WelcomeMailableStub extends Mailable
2
Python
Python
add ent_id constant
62655fd36fd13a4bcad3cfd09b853126fa2b5a27
<ide><path>spacy/language_data/util.py <ide> <ide> <ide> PRON_LEMMA = "-PRON-" <add>ENT_ID = "ent_id" <ide> <ide> <ide> def update_exc(exc, additions):
1
PHP
PHP
fix issue with scripts_for_layout compatibility
9cdf8042bf3a55cc5269eb77db4248254f035356
<ide><path>lib/Cake/View/View.php <ide> public function renderLayout($content, $layout = null) { <ide> $this->getEventManager()->dispatch(new CakeEvent('View.beforeLayout', $this, array($layoutFileName))); <ide> <ide> $scripts = implode("\n\t", $this->_scripts); <del> $scripts .= $this->get('meta') . $this->get('css') . $this->get('script'); <add> $scripts .= $this->Blocks->get('meta') . $this->Blocks->get('css') . $this->Blocks->get('script'); <ide> <ide> $this->viewVars = array_merge($this->viewVars, array( <ide> 'content_for_layout' => $content,
1
Text
Text
fix some typos
f1a19fa8c08a9b68d3a7014f9800cadf40fc150f
<ide><path>contrib/vagrant-docker/README.md <ide> script <ide> end script <ide> ``` <ide> <del>Once that's done, you need to set up a SSH tunnel between your host machine and the vagrant machine that's running Docker. This can be done by running the following command in a host terminal: <add>Once that's done, you need to set up an SSH tunnel between your host machine and the vagrant machine that's running Docker. This can be done by running the following command in a host terminal: <ide> <ide> ``` <ide> ssh -L 2375:localhost:2375 -p 2222 vagrant@localhost <ide><path>docs/extend/plugins_volume.md <ide> Docker needs reminding of the path to the volume on the host. <ide> <ide> Respond with the path on the host filesystem where the volume has been made <ide> available, and/or a string error if an error occurred. `Mountpoint` is optional, <del>however the plugin may be queried again later if one is not provided. <add>however, the plugin may be queried again later if one is not provided. <ide> <ide> ### /VolumeDriver.Unmount <ide> <ide> Respond with a string error if an error occurred. `Mountpoint` is optional. <ide> ``` <ide> <ide> Get the list of capabilities the driver supports. <del>The driver is not required to implement this endpoint, however in such cases <add>The driver is not required to implement this endpoint, however, in such cases <ide> the default values will be taken. <ide> <ide> **Response**: <ide><path>docs/reference/commandline/dockerd.md <ide> drivers: `aufs`, `devicemapper`, `btrfs`, `zfs`, `overlay` and `overlay2`. <ide> <ide> The `aufs` driver is the oldest, but is based on a Linux kernel patch-set that <ide> is unlikely to be merged into the main kernel. These are also known to cause <del>some serious kernel crashes. However, `aufs` allows containers to share <add>some serious kernel crashes. However `aufs` allows containers to share <ide> executable and shared library memory, so is a useful choice when running <ide> thousands of containers with the same program or libraries. <ide> <ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`. <ide> <ide> Overrides the Linux kernel version check allowing overlay2. Support for <ide> specifying multiple lower directories needed by overlay2 was added to the <del> Linux kernel in 4.0.0. However some older kernel versions may be patched <add> Linux kernel in 4.0.0. However, some older kernel versions may be patched <ide> to add multiple lower directory support for OverlayFS. This option should <ide> only be used after verifying this support exists in the kernel. Applying <ide> this option on a kernel without this support will cause failures on mount. <ide><path>experimental/vlan-networks.md <ide> $ ip route <ide> <ide> Example: Multi-Subnet Ipvlan L2 Mode starting two containers on the same subnet and pinging one another. In order for the `192.168.114.0/24` to reach `192.168.116.0/24` it requires an external router in L2 mode. L3 mode can route between subnets that share a common `-o parent=`. <ide> <del>Secondary addresses on network routers are common as an address space becomes exhausted to add another secondary to a L3 vlan interface or commonly referred to as a "switched virtual interface" (SVI). <add>Secondary addresses on network routers are common as an address space becomes exhausted to add another secondary to an L3 vlan interface or commonly referred to as a "switched virtual interface" (SVI). <ide> <ide> ``` <ide> docker network create -d ipvlan \ <ide><path>pkg/locker/README.md <ide> Locker <ide> locker provides a mechanism for creating finer-grained locking to help <ide> free up more global locks to handle other tasks. <ide> <del>The implementation looks close to a sync.Mutex, however the user must provide a <add>The implementation looks close to a sync.Mutex, however, the user must provide a <ide> reference to use to refer to the underlying lock when locking and unlocking, <ide> and unlock may generate an error. <ide>
5
Ruby
Ruby
fix super calls
e8143e5de7726a4ba4c1fd5e82d4b3ab5f5dff9a
<ide><path>Library/Homebrew/cask/exceptions.rb <ide> class CaskError < RuntimeError; end <ide> <ide> class MultipleCaskErrors < CaskError <ide> def initialize(errors) <del> super <add> super() <ide> <ide> @errors = errors <ide> end <ide> class CaskQuarantineError < CaskError <ide> attr_reader :path, :reason <ide> <ide> def initialize(path, reason) <del> super <add> super() <ide> <ide> @path = path <ide> @reason = reason
1
Javascript
Javascript
add support for serializing circular values
9cecf3c4a427725b42e066c6ca6bd93399b8dcd9
<ide><path>lib/serialization/ObjectMiddleware.js <ide> class ObjectMiddleware extends SerializerMiddleware { <ide> throw e; <ide> } <ide> }, <add> setCircularReference(ref) { <add> addReferenceable(ref); <add> }, <ide> snapshot() { <ide> return { <ide> length: result.length, <ide> class ObjectMiddleware extends SerializerMiddleware { <ide> } <ide> <ide> if (cycleStack.has(item)) { <del> throw new Error(`Circular references can't be serialized`); <add> throw new Error( <add> `This is a circular references. To serialize circular references use 'setCircularReference' somewhere in the circle during serialize and deserialize.` <add> ); <ide> } <ide> <ide> const { request, name, serializer } = ObjectMiddleware.getSerializerFor( <ide> class ObjectMiddleware extends SerializerMiddleware { <ide> read() { <ide> return decodeValue(); <ide> }, <add> setCircularReference(ref) { <add> addReferenceable(ref); <add> }, <ide> ...context <ide> }; <ide> this.extendContext(ctx); <ide> class ObjectMiddleware extends SerializerMiddleware { <ide> throw new Error( <ide> `Unexpected end of object at position ${currentDataPos - 1}` <ide> ); <del> } else if (typeof nextItem === "number" && nextItem < 0) { <del> // relative reference <del> return referenceable[currentPos + nextItem]; <ide> } else { <ide> const request = nextItem; <ide> let serializer; <ide> <ide> if (typeof request === "number") { <add> if (request < 0) { <add> // relative reference <add> return referenceable[currentPos + request]; <add> } <ide> serializer = objectTypeLookup[currentPosTypeLookup - request]; <ide> } else { <ide> if (typeof request !== "string") {
1
Ruby
Ruby
upgrade virtualenv to 16.3.0
80d8d441a288f1a77633d981380e6657f0ff8231
<ide><path>Library/Homebrew/language/python_virtualenv_constants.rb <ide> PYTHON_VIRTUALENV_URL = <del> "https://github.com/pypa/virtualenv/archive/16.2.0.tar.gz".freeze <add> "https://files.pythonhosted.org/packages/8b/f4" \ <add> "/360aa656ddb0f4168aeaa1057d8784b95d1ce12f34332c1cf52420b6db4e" \ <add> "/virtualenv-16.3.0.tar.gz".freeze <ide> PYTHON_VIRTUALENV_SHA256 = <del> "448def1220df9960e6d18fb5424107ffb1249eb566a5a311257860ab6b52b3fd".freeze <add> "729f0bcab430e4ef137646805b5b1d8efbb43fe53d4a0f33328624a84a5121f7".freeze
1
PHP
PHP
apply fixes from styleci
1d0fbe64e75ebedd3410f279fc120ab9281e17d0
<ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php <ide> use Illuminate\Queue\Console\ListFailedCommand as ListFailedQueueCommand; <ide> use Illuminate\Queue\Console\FlushFailedCommand as FlushFailedQueueCommand; <ide> use Illuminate\Queue\Console\ForgetFailedCommand as ForgetFailedQueueCommand; <del>use Illuminate\Database\Console\Migrations\ResetCommand as MigrateResetCommand; <ide> use Illuminate\Database\Console\Migrations\FreshCommand as MigrateFreshCommand; <add>use Illuminate\Database\Console\Migrations\ResetCommand as MigrateResetCommand; <ide> use Illuminate\Database\Console\Migrations\StatusCommand as MigrateStatusCommand; <ide> use Illuminate\Database\Console\Migrations\InstallCommand as MigrateInstallCommand; <ide> use Illuminate\Database\Console\Migrations\RefreshCommand as MigrateRefreshCommand;
1
Ruby
Ruby
add shfmt exit status to `brew style`
966189d07db604c953855e97c97377006e4ce8dd
<ide><path>Library/Homebrew/style.rb <ide> def check_style_impl(files, output_type, <ide> run_shellcheck(shell_files, output_type) <ide> end <ide> <del> run_shfmt(shell_files, fix: fix) if ruby_files.none? || shell_files.any? <add> shfmt_result = if ruby_files.any? && shell_files.none? <add> true <add> else <add> run_shfmt(shell_files, fix: fix) <add> end <ide> <ide> if output_type == :json <ide> Offenses.new(rubocop_result + shellcheck_result) <ide> else <del> rubocop_result && shellcheck_result <add> rubocop_result && shellcheck_result && shfmt_result <ide> end <ide> end <ide>
1
Python
Python
fix assert_array_equal_spec for complex types
74bca4fa9262d365eda8f59932c0d5bc86582f4b
<ide><path>numpy/core/tests/test_umath_complex.py <ide> def assert_equal_spec(x, y): <ide> xi = np.imag(x) <ide> yi = np.imag(y) <ide> <del> if not _are_equal(xr, xi) and _are_equal(yr, yi): <add> if not (_are_equal(xr, yr) and _are_equal(xi, yi)): <ide> raise AssertionError("Items are not equal:\n" \ <ide> "ACTUAL: %s\n" \ <ide> "DESIRED: %s\n" % (str(x), str(y)))
1
PHP
PHP
take a different approach for invalid option error
846eff66414c4e2b1527c3aaf18c268269d8045c
<ide><path>src/Console/CommandCollection.php <ide> public function autoDiscover(): array <ide> } <ide> <ide> /** <del> * Find suggested command names based on $needle <add> * Get the list of available command names. <ide> * <del> * Used to generate suggested commands when a <del> * command cannot be found in the collection. <del> * <del> * @param string $needle The missing command to find suggestions for. <del> * @return string[] <add> * @return string[] Command names <ide> */ <del> public function suggest(string $needle): array <add> public function keys(): array <ide> { <del> $found = []; <del> foreach (array_keys($this->commands) as $candidate) { <del> if (levenshtein($candidate, $needle) < 3) { <del> $found[] = $candidate; <del> } elseif (strpos($candidate, $needle) === 0) { <del> $found[] = $candidate; <del> } <del> } <del> <del> return $found; <add> return array_keys($this->commands); <ide> } <ide> } <ide><path>src/Console/CommandRunner.php <ide> <ide> use Cake\Command\HelpCommand; <ide> use Cake\Command\VersionCommand; <del>use Cake\Console\Exception\NoOptionException; <add>use Cake\Console\Exception\InvalidOptionException; <ide> use Cake\Console\Exception\StopException; <ide> use Cake\Core\ConsoleApplicationInterface; <ide> use Cake\Core\HttpApplicationInterface; <ide> public function run(array $argv, ?ConsoleIo $io = null): int <ide> try { <ide> [$name, $argv] = $this->longestCommandName($commands, $argv); <ide> $name = $this->resolveName($commands, $io, $name); <del> } catch (NoOptionException $e) { <add> } catch (InvalidOptionException $e) { <ide> $io->error($e->getFullMessage()); <ide> <ide> return Command::CODE_ERROR; <ide> protected function resolveName(CommandCollection $commands, ConsoleIo $io, ?stri <ide> $name = Inflector::underscore($name); <ide> } <ide> if (!$commands->has($name)) { <del> $suggestions = $commands->suggest($name); <del> throw new NoOptionException( <add> throw new InvalidOptionException( <ide> "Unknown command `{$this->root} {$name}`. " . <ide> "Run `{$this->root} --help` to get the list of commands.", <del> $suggestions <add> $name, <add> $commands->keys() <ide> ); <ide> } <ide> <ide><path>src/Console/ConsoleOptionParser.php <ide> namespace Cake\Console; <ide> <ide> use Cake\Console\Exception\ConsoleException; <add>use Cake\Console\Exception\InvalidOptionException; <ide> use Cake\Utility\Inflector; <ide> use LogicException; <ide> <ide> public function help(?string $subcommand = null, string $format = 'text', int $w <ide> return $subparser->help(null, $format, $width); <ide> } <ide> <del> return $this->getCommandError($subcommand); <add> $rootCommand = $this->getCommand(); <add> $message = sprintf( <add> 'Unable to find the `%s %s` subcommand. See `bin/%s %s --help`.', <add> $rootCommand, <add> $command, <add> $this->rootName, <add> $rootCommand <add> ); <add> throw new InvalidOptionException( <add> $message, <add> $command, <add> array_keys((array)$this->subcommands()), <add> ); <ide> } <ide> <ide> /** <ide> public function setRootName(string $name) <ide> return $this; <ide> } <ide> <del> /** <del> * Get the message output in the console stating that the command can not be found and tries to guess what the user <del> * wanted to say. Output a list of available subcommands as well. <del> * <del> * @param string $command Unknown command name trying to be dispatched. <del> * @return string The message to be displayed in the console. <del> */ <del> protected function getCommandError(string $command): string <del> { <del> $rootCommand = $this->getCommand(); <del> $subcommands = array_keys((array)$this->subcommands()); <del> $bestGuess = $this->findClosestItem($command, $subcommands); <del> <del> $out = [ <del> sprintf( <del> 'Unable to find the `%s %s` subcommand. See `bin/%s %s --help`.', <del> $rootCommand, <del> $command, <del> $this->rootName, <del> $rootCommand <del> ), <del> '', <del> ]; <del> <del> if ($bestGuess !== null) { <del> $out[] = sprintf('Did you mean : `%s %s` ?', $rootCommand, $bestGuess); <del> $out[] = ''; <del> } <del> $out[] = sprintf('Available subcommands for the `%s` command are : ', $rootCommand); <del> $out[] = ''; <del> foreach ($subcommands as $subcommand) { <del> $out[] = ' - ' . $subcommand; <del> } <del> <del> return implode("\n", $out); <del> } <del> <del> /** <del> * Get the message output in the console stating that the option can not be found and tries to guess what the user <del> * wanted to say. Output a list of available options as well. <del> * <del> * @param string $option Unknown option name trying to be used. <del> * @return string The message to be displayed in the console. <del> */ <del> protected function getOptionError(string $option): string <del> { <del> $availableOptions = array_keys($this->_options); <del> $bestGuess = $this->findClosestItem($option, $availableOptions); <del> $out = [ <del> sprintf('Unknown option `%s`.', $option), <del> '', <del> ]; <del> <del> if ($bestGuess !== null) { <del> $out[] = sprintf('Did you mean `%s` ?', $bestGuess); <del> $out[] = ''; <del> } <del> <del> $out[] = 'Available options are :'; <del> $out[] = ''; <del> foreach ($availableOptions as $availableOption) { <del> $out[] = ' - ' . $availableOption; <del> } <del> <del> return implode("\n", $out); <del> } <del> <del> /** <del> * Get the message output in the console stating that the short option can not be found. Output a list of available <del> * short options and what option they refer to as well. <del> * <del> * @param string $option Unknown short option name trying to be used. <del> * @return string The message to be displayed in the console. <del> */ <del> protected function getShortOptionError(string $option): string <del> { <del> $out = [sprintf('Unknown short option `%s`', $option)]; <del> $out[] = ''; <del> $out[] = 'Available short options are :'; <del> $out[] = ''; <del> <del> foreach ($this->_shortOptions as $short => $long) { <del> $out[] = sprintf(' - `%s` (short for `--%s`)', $short, $long); <del> } <del> <del> return implode("\n", $out); <del> } <del> <del> /** <del> * Tries to guess the item name the user originally wanted using the some regex pattern and the levenshtein <del> * algorithm. <del> * <del> * @param string $needle Unknown item (either a subcommand name or an option for instance) trying to be used. <del> * @param string[] $haystack List of items available for the type $needle belongs to. <del> * @return string|null The closest name to the item submitted by the user. <del> */ <del> protected function findClosestItem(string $needle, array $haystack): ?string <del> { <del> $bestGuess = null; <del> foreach ($haystack as $item) { <del> if (preg_match('/^' . $needle . '/', $item)) { <del> return $item; <del> } <del> } <del> <del> foreach ($haystack as $item) { <del> if (preg_match('/' . $needle . '/', $item)) { <del> return $item; <del> } <del> <del> $score = levenshtein($needle, $item); <del> <del> if (!isset($bestScore) || $score < $bestScore) { <del> $bestScore = $score; <del> $bestGuess = $item; <del> } <del> } <del> <del> return $bestGuess; <del> } <del> <ide> /** <ide> * Parse the value for a long option out of $this->_tokens. Will handle <ide> * options with an `=` in them. <ide> protected function _parseShortOption(string $option, array $params): array <ide> } <ide> } <ide> if (!isset($this->_shortOptions[$key])) { <del> throw new ConsoleException($this->getShortOptionError($key)); <add> $options = []; <add> foreach ($this->_shortOptions as $short => $long) { <add> $options[] = "{$short} (short for `--{$long}`)"; <add> } <add> throw new InvalidOptionException( <add> "Unknown short option `{$key}`.", <add> $key, <add> $options <add> ); <ide> } <ide> $name = $this->_shortOptions[$key]; <ide> <ide> protected function _parseShortOption(string $option, array $params): array <ide> protected function _parseOption(string $name, array $params): array <ide> { <ide> if (!isset($this->_options[$name])) { <del> throw new ConsoleException($this->getOptionError($name)); <add> throw new InvalidOptionException( <add> "Unknown option `{$name}`.", <add> $name, <add> array_keys($this->_options) <add> ); <ide> } <ide> $option = $this->_options[$name]; <ide> $isBoolean = $option->isBoolean(); <ide><path>src/Console/Exception/InvalidOptionException.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://book.cakephp.org/3.0/en/development/errors.html#error-exception-configuration <add> * @since 4.0.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Console\Exception; <add> <add>use Throwable; <add> <add>/** <add> * Exception raised with suggestions <add> */ <add>class InvalidOptionException extends ConsoleException <add>{ <add> /** <add> * The requested thing that was not found. <add> * <add> * @var string <add> */ <add> protected $requested = ''; <add> <add> /** <add> * The valid suggestions. <add> * <add> * @var string[] <add> */ <add> protected $suggestions = []; <add> <add> /** <add> * Constructor. <add> * <add> * @param string $message The string message. <add> * @param string $requested The requested value. <add> * @param array $suggestions The list of potential values that were valid. <add> * @param int|null $code The exception code if relevant. <add> * @param \Throwable|null $previous the previous exception. <add> */ <add> public function __construct( <add> string $message, <add> string $requested = '', <add> array $suggestions = [], <add> ?int $code = null, <add> ?Throwable $previous = null <add> ) { <add> $this->suggestions = $suggestions; <add> $this->requested = $requested; <add> parent::__construct($message, $code, $previous); <add> } <add> <add> /** <add> * Get the message with suggestions <add> * <add> * @return string <add> */ <add> public function getFullMessage(): string <add> { <add> $out = $this->getMessage(); <add> $bestGuess = $this->findClosestItem($this->requested, $this->suggestions); <add> if ($bestGuess) { <add> $out .= " Did you mean: `{$bestGuess}`?"; <add> } <add> if ($this->suggestions) { <add> $suggestions = array_map(function ($item) { <add> return '- ' . $item; <add> }, $this->suggestions); <add> <add> $out .= "\n\nOther valid choices:\n\n" . implode("\n", $suggestions); <add> } <add> <add> return $out; <add> } <add> <add> /** <add> * Find the best match for requested in suggestions <add> * <add> * @param string $needle Unknown option name trying to be used. <add> * @param string[] $haystack Suggestions to look through. <add> * @return string The best match <add> */ <add> protected function findClosestItem($needle, $haystack): ?string <add> { <add> $bestGuess = null; <add> foreach ($haystack as $item) { <add> if (preg_match('/^' . $needle . '/', $item)) { <add> return $item; <add> } <add> } <add> <add> $bestScore = 4; <add> foreach ($haystack as $item) { <add> $score = levenshtein($needle, $item); <add> <add> if (!isset($bestScore) || $score < $bestScore) { <add> $bestScore = $score; <add> $bestGuess = $item; <add> } <add> } <add> <add> return $bestGuess; <add> } <add>} <ide><path>src/Console/Exception/NoOptionException.php <del><?php <del>declare(strict_types=1); <del> <del>/** <del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * @link https://book.cakephp.org/3.0/en/development/errors.html#error-exception-configuration <del> * @since 4.0.0 <del> * @license https://opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Console\Exception; <del> <del>use Throwable; <del> <del>/** <del> * Exception raised with suggestions <del> */ <del>class NoOptionException extends ConsoleException <del>{ <del> /** <del> * The suggestions for the error. <del> * <del> * @var string[] <del> */ <del> protected $suggestions = []; <del> <del> /** <del> * Constructor. <del> * <del> * @param string $message The string message. <del> * @param array $suggestions The code of the error, is also the HTTP status code for the error. <del> * @param int|null $code Either the string of the error message, or an array of attributes <del> * @param \Throwable|null $previous the previous exception. <del> */ <del> public function __construct( <del> string $message = '', <del> array $suggestions = [], <del> ?int $code = null, <del> ?Throwable $previous = null <del> ) { <del> $this->suggestions = $suggestions; <del> parent::__construct($message, $code, $previous); <del> } <del> <del> /** <del> * Get the message with suggestions <del> * <del> * @return string <del> */ <del> public function getFullMessage(): string <del> { <del> $out = $this->getMessage(); <del> if ($this->suggestions) { <del> $suggestions = array_map(function ($item) { <del> return '`' . $item . '`'; <del> }, $this->suggestions); <del> $out .= ' Did you mean: ' . implode(', ', $suggestions) . '?'; <del> } <del> <del> return $out; <del> } <del> <del> /** <del> * Get suggestions from exception. <del> * <del> * @return string[] <del> */ <del> public function getSuggetions() <del> { <del> return $this->suggestions; <del> } <del>} <ide><path>tests/TestCase/Console/CommandCollectionTest.php <ide> public function testDiscoverPlugin() <ide> } <ide> <ide> /** <del> * Test suggest <add> * Test keys <ide> * <ide> * @return void <ide> */ <del> public function testSuggest() <add> public function testKeys() <ide> { <ide> $collection = new CommandCollection(); <ide> $collection->add('demo', DemoCommand::class); <ide> $collection->add('demo sample', DemoCommand::class); <ide> $collection->add('dang', DemoCommand::class); <del> $collection->add('woot', DemoCommand::class); <del> $collection->add('wonder', DemoCommand::class); <ide> <del> $this->assertEmpty($collection->suggest('nope')); <del> $this->assertEquals(['demo', 'demo sample'], $collection->suggest('dem')); <del> $this->assertEquals(['dang'], $collection->suggest('dan')); <del> $this->assertEquals(['woot', 'wonder'], $collection->suggest('wo')); <del> $this->assertEquals(['wonder'], $collection->suggest('wander'), 'typos should be found'); <add> $result = $collection->keys(); <add> $this->assertSame(['demo', 'demo sample', 'dang'], $result); <ide> } <ide> } <ide><path>tests/TestCase/Console/CommandRunnerTest.php <ide> public function testRunInvalidCommandSuggestion() <ide> <ide> $messages = implode("\n", $output->messages()); <ide> $this->assertStringContainsString( <del> 'Did you mean: `cache clear`, `cache clear_all`, `cache list`?', <add> "Did you mean: `cache clear`?\n" . <add> "\n" . <add> "Other valid choices:\n" . <add> "\n" . <add> "- version", <ide> $messages <ide> ); <ide> } <ide><path>tests/TestCase/Console/ConsoleOptionParserTest.php <ide> use Cake\Console\ConsoleInputOption; <ide> use Cake\Console\ConsoleInputSubcommand; <ide> use Cake\Console\ConsoleOptionParser; <add>use Cake\Console\Exception\InvalidOptionException; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <ide> public function testOptionWithBooleanParam() <ide> */ <ide> public function testOptionThatDoesNotExist() <ide> { <del> $this->expectException(\Cake\Console\Exception\ConsoleException::class); <del> $this->expectExceptionMessageRegExp( <del> '/Unknown option `fail`.\n\nDid you mean `help` \?\n\nAvailable options are :\n\n - help\n - no-commit/' <del> ); <del> <ide> $parser = new ConsoleOptionParser('test', false); <ide> $parser->addOption('no-commit', ['boolean' => true]); <ide> <del> $parser->parse(['--fail', 'other']); <add> try { <add> $parser->parse(['--he', 'other']); <add> } catch (InvalidOptionException $e) { <add> $this->assertStringContainsString( <add> "Unknown option `he`. Did you mean: `help`?\n" . <add> "\n" . <add> "Other valid choices:\n" . <add> "\n" . <add> "- help\n" . <add> "- no-commit", <add> $e->getFullMessage() <add> ); <add> } <ide> } <ide> <ide> /** <ide> public function testOptionThatDoesNotExist() <ide> */ <ide> public function testShortOptionThatDoesNotExist() <ide> { <del> $this->expectException(\Cake\Console\Exception\ConsoleException::class); <del> $this->expectExceptionMessageRegExp( <del> '/Unknown short option `f`\n\nAvailable short options are :\n\n - `c` \(short for `--clear`\)\n - `h` \(short for `--help`\)\n - `n` \(short for `--no-commit`\)/' <del> ); <del> <ide> $parser = new ConsoleOptionParser('test', false); <ide> $parser->addOption('no-commit', ['boolean' => true, 'short' => 'n']); <ide> $parser->addOption('construct', ['boolean' => true]); <ide> $parser->addOption('clear', ['boolean' => true, 'short' => 'c']); <ide> <del> $parser->parse(['-f']); <add> try { <add> $parser->parse(['-f']); <add> } catch (InvalidOptionException $e) { <add> $this->assertStringContainsString( <add> "Unknown short option `f`.\n" . <add> "\n" . <add> "Other valid choices:\n" . <add> "\n" . <add> "- c (short for `--clear`)\n" . <add> "- h (short for `--help`)\n" . <add> "- n (short for `--no-commit`)", <add> $e->getFullMessage() <add> ); <add> } <ide> } <ide> <ide> /**
8
Javascript
Javascript
replace string concatenation with template
01eddd97f733148b70d753129c612ef09db3493b
<ide><path>test/parallel/test-icu-data-dir.js <ide> 'use strict'; <ide> const common = require('../common'); <add>const os = require('os'); <ide> if (!(common.hasIntl && common.hasSmallICU)) <ide> common.skip('missing Intl'); <ide> <ide> const { spawnSync } = require('child_process'); <ide> <ide> const expected = <ide> 'could not initialize ICU (check NODE_ICU_DATA or ' + <del> '--icu-data-dir parameters)' + (common.isWindows ? '\r\n' : '\n'); <add> `--icu-data-dir parameters)${os.EOL}`; <ide> <ide> { <ide> const child = spawnSync(process.execPath, ['--icu-data-dir=/', '-e', '0']);
1
PHP
PHP
remove invalid @deprecated annoation
5688676398bbe8c30c6aa5b02725688a813523cb
<ide><path>src/Database/QueryCompiler.php <ide> class QueryCompiler <ide> * The list of query clauses to traverse for generating an UPDATE statement <ide> * <ide> * @var array<string> <del> * @deprecated Not used. <ide> */ <ide> protected $_updateParts = ['with', 'update', 'set', 'where', 'epilog']; <ide>
1
Text
Text
fix typo in fs.md
d6397afbac475316d50b1b147c89879f5f4dbd72
<ide><path>doc/api/fs.md <ide> added: v10.0.0 <ide> * Returns: {Promise} <ide> <ide> Reads the contents of a directory then resolves the `Promise` with an array <del>of the names of the files in the directory excludiing `'.'` and `'..'`. <add>of the names of the files in the directory excluding `'.'` and `'..'`. <ide> <ide> The optional `options` argument can be a string specifying an encoding, or an <ide> object with an `encoding` property specifying the character encoding to use for
1
PHP
PHP
add wherecolumn clause
853300b13201f98b8149acb3992554af25e2232c
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function where($column, $operator = null, $value = null, $boolean = 'and' <ide> * <ide> * @param array $column <ide> * @param string $boolean <add> * @param string $method <ide> * @return $this <ide> */ <del> protected function addArrayOfWheres($column, $boolean) <add> protected function addArrayOfWheres($column, $boolean, $method = 'where') <ide> { <del> return $this->whereNested(function ($query) use ($column) { <add> return $this->whereNested(function ($query) use ($column, $method) { <ide> foreach ($column as $key => $value) { <ide> if (is_numeric($key) && is_array($value)) { <del> call_user_func_array([$query, 'where'], $value); <add> call_user_func_array([$query, $method], $value); <ide> } else { <del> $query->where($key, '=', $value); <add> $query->$method($key, '=', $value); <ide> } <ide> } <ide> }, $boolean); <ide> public function orWhere($column, $operator = null, $value = null) <ide> return $this->where($column, $operator, $value, 'or'); <ide> } <ide> <add> /** <add> * Add a "where" clause comparing two columns to the query. <add> * <add> * @param string|array $first <add> * @param string|null $operator <add> * @param string|null $second <add> * @param string|null $boolean <add> * @return \Illuminate\Database\Query\Builder|static <add> */ <add> public function whereColumn($first, $operator = null, $second = null, $boolean = 'and') <add> { <add> // If the column is an array, we will assume it is an array of key-value pairs <add> // and can add them each as a where clause. We will maintain the boolean we <add> // received when the method was called and pass it into the nested where. <add> if (is_array($first)) { <add> return $this->addArrayOfWheres($first, $boolean, 'whereColumn'); <add> } <add> <add> // If the given operator is not found in the list of valid operators we will <add> // assume that the developer is just short-cutting the '=' operators and <add> // we will set the operators to '=' and set the values appropriately. <add> if (! in_array(strtolower($operator), $this->operators, true) && <add> ! in_array(strtolower($operator), $this->grammar->getOperators(), true)) { <add> list($second, $operator) = [$operator, '=']; <add> } <add> <add> $type = 'Column'; <add> <add> $this->wheres[] = compact('type', 'first', 'operator', 'second', 'boolean'); <add> <add> return $this; <add> } <add> <add> /** <add> * Add an "or where" clause comparing two columns to the query. <add> * <add> * @param string|array $first <add> * @param string|null $operator <add> * @param string|null $second <add> * @return \Illuminate\Database\Query\Builder|static <add> */ <add> public function orWhereColumn($first, $operator = null, $second = null) <add> { <add> return $this->whereColumn($first, $operator, $second, 'or'); <add> } <add> <ide> /** <ide> * Determine if the given operator and value combination is legal. <ide> * <ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php <ide> protected function whereBasic(Builder $query, $where) <ide> return $this->wrap($where['column']).' '.$where['operator'].' '.$value; <ide> } <ide> <add> /** <add> * Compile a where clause comparing two columns.. <add> * <add> * @param \Illuminate\Database\Query\Builder $query <add> * @param array $where <add> * @return string <add> */ <add> protected function whereColumn(Builder $query, $where) <add> { <add> $second = $this->wrap($where['second']); <add> <add> return $this->wrap($where['first']).' '.$where['operator'].' '.$second; <add> } <add> <ide> /** <ide> * Compile a "between" where clause. <ide> * <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testEmptyWhereNotIns() <ide> $this->assertEquals([0 => 1], $builder->getBindings()); <ide> } <ide> <add> public function testBasicWhereColumn() <add> { <add> $builder = $this->getBuilder(); <add> $builder->select('*')->from('users')->whereColumn('first_name', 'last_name')->orWhereColumn('first_name', 'middle_name'); <add> $this->assertEquals('select * from "users" where "first_name" = "last_name" or "first_name" = "middle_name"', $builder->toSql()); <add> $this->assertEquals([], $builder->getBindings()); <add> <add> $builder = $this->getBuilder(); <add> $builder->select('*')->from('users')->whereColumn('updated_at', '>', 'created_at'); <add> $this->assertEquals('select * from "users" where "updated_at" > "created_at"', $builder->toSql()); <add> $this->assertEquals([], $builder->getBindings()); <add> } <add> <add> public function testArrayWhereColumn() <add> { <add> $conditions = [ <add> ['first_name', 'last_name'], <add> ['updated_at', '>', 'created_at'] <add> ]; <add> <add> $builder = $this->getBuilder(); <add> $builder->select('*')->from('users')->whereColumn($conditions); <add> $this->assertEquals('select * from "users" where ("first_name" = "last_name" and "updated_at" > "created_at")', $builder->toSql()); <add> $this->assertEquals([], $builder->getBindings()); <add> } <add> <ide> public function testUnions() <ide> { <ide> $builder = $this->getBuilder();
3
Javascript
Javascript
add forgotten clippath wrapper in getmarkupwrap
3b10a7b0386bf6787e6da58fea696f7a9d6f802c
<ide><path>src/vendor/core/getMarkupWrap.js <ide> var markupWrap = { <ide> 'th': trWrap, <ide> <ide> 'circle': svgWrap, <add> 'clipPath': svgWrap, <ide> 'defs': svgWrap, <ide> 'ellipse': svgWrap, <ide> 'g': svgWrap,
1
Text
Text
remove lemma from exception examples [ci skip]
25b2b3ff4527f1fba5a2df0756cbe4f843b469a7
<ide><path>website/docs/api/tokenizer.md <ide> and examples. <ide> > #### Example <ide> > <ide> > ```python <del>> from spacy.attrs import ORTH, LEMMA <del>> case = [{ORTH: "do"}, {ORTH: "n't", LEMMA: "not"}] <add>> from spacy.attrs import ORTH, NORM <add>> case = [{ORTH: "do"}, {ORTH: "n't", NORM: "not"}] <ide> > tokenizer.add_special_case("don't", case) <ide> > ``` <ide> <ide><path>website/docs/api/top-level.md <ide> an error if key doesn't match `ORTH` values. <ide> > <ide> > ```python <ide> > BASE = {"a.": [{ORTH: "a."}], ":)": [{ORTH: ":)"}]} <del>> NEW = {"a.": [{ORTH: "a.", LEMMA: "all"}]} <add>> NEW = {"a.": [{ORTH: "a.", NORM: "all"}]} <ide> > exceptions = util.update_exc(BASE, NEW) <del>> # {"a.": [{ORTH: "a.", LEMMA: "all"}], ":)": [{ORTH: ":)"}]} <add>> # {"a.": [{ORTH: "a.", NORM: "all"}], ":)": [{ORTH: ":)"}]} <ide> > ``` <ide> <ide> | Name | Type | Description | <ide><path>website/docs/usage/linguistic-features.md <ide> import Tokenization101 from 'usage/101/\_tokenization.md' <ide> data in <ide> [`spacy/lang`](https://github.com/explosion/spaCy/tree/master/spacy/lang). The <ide> tokenizer exceptions define special cases like "don't" in English, which needs <del>to be split into two tokens: `{ORTH: "do"}` and `{ORTH: "n't", LEMMA: "not"}`. <add>to be split into two tokens: `{ORTH: "do"}` and `{ORTH: "n't", NORM: "not"}`. <ide> The prefixes, suffixes and infixes mostly define punctuation rules – for <ide> example, when to split off periods (at the end of a sentence), and when to leave <ide> tokens containing periods intact (abbreviations like "U.S.").
3
Text
Text
allow code on new lines for camper-cafe
54a15c65894d815c28ef941e1200653f4a13a84d
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-basic-css-by-building-a-cafe-menu/step-002.md <ide> assert(code.match(/<\/title>/i)); <ide> Your `<title>` element should be nested in your `<head>` element. <ide> <ide> ```js <del>assert(code.match(/<head>\s*<title>.*<\/title>\s*<\/head>/i)); <add>assert(code.match(/<head>\s*<title>.*<\/title>\s*<\/head>/si)); <ide> ``` <ide> <ide> Your `<title>` element should have the text `Camper Cafe Menu`. You may need to check your spelling. <ide> <ide> ```js <del>assert(code.match(/<title>camper\scafe\smenu<\/title>/i)); <add>assert.match(document.querySelector('title')?.innerText, /camper cafe menu/i); <ide> ``` <ide> <ide> # --seed--
1
Java
Java
remove reflection from contentdispositiontests
d927d31e135bcbc8b4a69ac3b3b3aab354d1670b
<ide><path>spring-web/src/main/java/org/springframework/http/ContentDisposition.java <ide> public String toString() { <ide> } <ide> else { <ide> sb.append("; filename*="); <del> sb.append(encodeHeaderFieldParam(this.filename, this.charset)); <add> sb.append(encodeFilename(this.filename, this.charset)); <ide> } <ide> } <ide> if (this.size != null) { <ide> public static ContentDisposition parse(String contentDisposition) { <ide> String attribute = part.substring(0, eqIndex); <ide> String value = (part.startsWith("\"", eqIndex + 1) && part.endsWith("\"") ? <ide> part.substring(eqIndex + 2, part.length() - 1) : <del> part.substring(eqIndex + 1, part.length())); <add> part.substring(eqIndex + 1)); <ide> if (attribute.equals("name") ) { <ide> name = value; <ide> } <ide> else if (attribute.equals("filename*") ) { <del> filename = decodeHeaderFieldParam(value); <del> charset = Charset.forName(value.substring(0, value.indexOf('\''))); <del> Assert.isTrue(UTF_8.equals(charset) || ISO_8859_1.equals(charset), <del> "Charset should be UTF-8 or ISO-8859-1"); <add> int idx1 = value.indexOf('\''); <add> int idx2 = value.indexOf('\'', idx1 + 1); <add> if (idx1 != -1 && idx2 != -1) { <add> charset = Charset.forName(value.substring(0, idx1)); <add> Assert.isTrue(UTF_8.equals(charset) || ISO_8859_1.equals(charset), <add> "Charset should be UTF-8 or ISO-8859-1"); <add> filename = decodeFilename(value.substring(idx2 + 1), charset); <add> } <add> else { <add> // US ASCII <add> filename = decodeFilename(value, StandardCharsets.US_ASCII); <add> } <ide> } <ide> else if (attribute.equals("filename") && (filename == null)) { <ide> filename = value; <ide> else if (!escaped && ch == '"') { <ide> /** <ide> * Decode the given header field param as described in RFC 5987. <ide> * <p>Only the US-ASCII, UTF-8 and ISO-8859-1 charsets are supported. <del> * @param input the header field param <add> * @param filename the filename <add> * @param charset the charset for the filename <ide> * @return the encoded header field param <ide> * @see <a href="https://tools.ietf.org/html/rfc5987">RFC 5987</a> <ide> */ <del> private static String decodeHeaderFieldParam(String input) { <del> Assert.notNull(input, "Input String should not be null"); <del> int firstQuoteIndex = input.indexOf('\''); <del> int secondQuoteIndex = input.indexOf('\'', firstQuoteIndex + 1); <del> // US_ASCII <del> if (firstQuoteIndex == -1 || secondQuoteIndex == -1) { <del> return input; <del> } <del> Charset charset = Charset.forName(input.substring(0, firstQuoteIndex)); <del> Assert.isTrue(UTF_8.equals(charset) || ISO_8859_1.equals(charset), <del> "Charset should be UTF-8 or ISO-8859-1"); <del> byte[] value = input.substring(secondQuoteIndex + 1, input.length()).getBytes(charset); <add> private static String decodeFilename(String filename, Charset charset) { <add> Assert.notNull(filename, "'input' String` should not be null"); <add> Assert.notNull(charset, "'charset' should not be null"); <add> byte[] value = filename.getBytes(charset); <ide> ByteArrayOutputStream bos = new ByteArrayOutputStream(); <ide> int index = 0; <ide> while (index < value.length) { <ide> private static boolean isRFC5987AttrChar(byte c) { <ide> * @return the encoded header field param <ide> * @see <a href="https://tools.ietf.org/html/rfc5987">RFC 5987</a> <ide> */ <del> private static String encodeHeaderFieldParam(String input, Charset charset) { <add> private static String encodeFilename(String input, Charset charset) { <ide> Assert.notNull(input, "Input String should not be null"); <ide> Assert.notNull(charset, "Charset should not be null"); <ide> if (StandardCharsets.US_ASCII.equals(charset)) { <ide><path>spring-web/src/test/java/org/springframework/http/ContentDispositionTests.java <ide> <ide> package org.springframework.http; <ide> <del>import java.lang.reflect.Method; <del>import java.nio.charset.Charset; <ide> import java.nio.charset.StandardCharsets; <ide> import java.time.ZonedDateTime; <ide> import java.time.format.DateTimeFormatter; <ide> <ide> import org.junit.jupiter.api.Test; <ide> <del>import org.springframework.util.ReflectionUtils; <del> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <ide> <ide> public void parseEncodedFilename() { <ide> .build()); <ide> } <ide> <add> @Test <add> public void parseEncodedFilenameWithoutCharset() { <add> assertThat(parse("form-data; name=\"name\"; filename*=test.txt")) <add> .isEqualTo(ContentDisposition.builder("form-data") <add> .name("name") <add> .filename("test.txt") <add> .build()); <add> } <add> <add> @Test <add> public void parseEncodedFilenameWithInvalidCharset() { <add> assertThatIllegalArgumentException() <add> .isThrownBy(() -> parse("form-data; name=\"name\"; filename*=UTF-16''test.txt")); <add> } <add> <add> @Test <add> public void parseEncodedFilenameWithInvalidName() { <add> assertThatIllegalArgumentException() <add> .isThrownBy(() -> parse("form-data; name=\"name\"; filename*=UTF-8''%A")); <add> <add> assertThatIllegalArgumentException() <add> .isThrownBy(() -> parse("form-data; name=\"name\"; filename*=UTF-8''%A.txt")); <add> } <add> <ide> @Test // gh-23077 <ide> public void parseWithEscapedQuote() { <ide> assertThat(parse("form-data; name=\"file\"; filename=\"\\\"The Twilight Zone\\\".txt\"; size=123")) <ide> private static ContentDisposition parse(String input) { <ide> <ide> <ide> @Test <del> public void headerValue() { <add> public void format() { <ide> assertThat( <ide> ContentDisposition.builder("form-data") <ide> .name("foo") <ide> public void headerValue() { <ide> } <ide> <ide> @Test <del> public void headerValueWithEncodedFilename() { <add> public void formatWithEncodedFilename() { <ide> assertThat( <ide> ContentDisposition.builder("form-data") <ide> .name("name") <ide> public void headerValueWithEncodedFilename() { <ide> .isEqualTo("form-data; name=\"name\"; filename*=UTF-8''%E4%B8%AD%E6%96%87.txt"); <ide> } <ide> <del> @Test // SPR-14547 <del> public void encodeHeaderFieldParam() { <del> Method encode = ReflectionUtils.findMethod(ContentDisposition.class, <del> "encodeHeaderFieldParam", String.class, Charset.class); <del> ReflectionUtils.makeAccessible(encode); <del> <del> String result = (String)ReflectionUtils.invokeMethod(encode, null, "test.txt", <del> StandardCharsets.US_ASCII); <del> assertThat(result).isEqualTo("test.txt"); <del> <del> result = (String)ReflectionUtils.invokeMethod(encode, null, "中文.txt", StandardCharsets.UTF_8); <del> assertThat(result).isEqualTo("UTF-8''%E4%B8%AD%E6%96%87.txt"); <del> } <del> <ide> @Test <del> public void encodeHeaderFieldParamInvalidCharset() { <del> Method encode = ReflectionUtils.findMethod(ContentDisposition.class, <del> "encodeHeaderFieldParam", String.class, Charset.class); <del> ReflectionUtils.makeAccessible(encode); <del> assertThatIllegalArgumentException().isThrownBy(() -> <del> ReflectionUtils.invokeMethod(encode, null, "test", StandardCharsets.UTF_16)); <del> } <del> <del> @Test // SPR-14408 <del> public void decodeHeaderFieldParam() { <del> Method decode = ReflectionUtils.findMethod(ContentDisposition.class, <del> "decodeHeaderFieldParam", String.class); <del> ReflectionUtils.makeAccessible(decode); <del> <del> String result = (String)ReflectionUtils.invokeMethod(decode, null, "test.txt"); <del> assertThat(result).isEqualTo("test.txt"); <del> <del> result = (String)ReflectionUtils.invokeMethod(decode, null, "UTF-8''%E4%B8%AD%E6%96%87.txt"); <del> assertThat(result).isEqualTo("中文.txt"); <del> } <del> <del> @Test <del> public void decodeHeaderFieldParamInvalidCharset() { <del> Method decode = ReflectionUtils.findMethod(ContentDisposition.class, <del> "decodeHeaderFieldParam", String.class); <del> ReflectionUtils.makeAccessible(decode); <del> assertThatIllegalArgumentException().isThrownBy(() -> <del> ReflectionUtils.invokeMethod(decode, null, "UTF-16''test")); <del> } <del> <del> @Test <del> public void decodeHeaderFieldParamShortInvalidEncodedFilename() { <del> Method decode = ReflectionUtils.findMethod(ContentDisposition.class, <del> "decodeHeaderFieldParam", String.class); <del> ReflectionUtils.makeAccessible(decode); <del> assertThatIllegalArgumentException().isThrownBy(() -> <del> ReflectionUtils.invokeMethod(decode, null, "UTF-8''%A")); <add> public void formatWithEncodedFilenameUsingUsAscii() { <add> assertThat( <add> ContentDisposition.builder("form-data") <add> .name("name") <add> .filename("test.txt", StandardCharsets.US_ASCII) <add> .build() <add> .toString()) <add> .isEqualTo("form-data; name=\"name\"; filename=\"test.txt\""); <ide> } <ide> <ide> @Test <del> public void decodeHeaderFieldParamLongerInvalidEncodedFilename() { <del> Method decode = ReflectionUtils.findMethod(ContentDisposition.class, <del> "decodeHeaderFieldParam", String.class); <del> ReflectionUtils.makeAccessible(decode); <add> public void formatWithEncodedFilenameUsingInvalidCharset() { <ide> assertThatIllegalArgumentException().isThrownBy(() -> <del> ReflectionUtils.invokeMethod(decode, null, "UTF-8''%A.txt")); <add> ContentDisposition.builder("form-data") <add> .name("name") <add> .filename("test.txt", StandardCharsets.UTF_16) <add> .build() <add> .toString()); <ide> } <ide> <ide> }
2
PHP
PHP
add notifyvia method
4e7d69f90e5bdf4e1336566a53b33ca48d85e1bb
<ide><path>src/Illuminate/Notifications/RoutesNotifications.php <ide> public function notify($instance) <ide> } <ide> } <ide> <add> /** <add> * Send the given notification via the given channels. <add> * <add> * @param array|string $channels <add> * @param mixed $instance <add> * @return void <add> */ <add> public function notifyVia($channels, $instance) <add> { <add> $manager = app(ChannelManager::class); <add> <add> $notifications = Channels\Notification::notificationsFromInstance( <add> $this, $instance, (array) $channels <add> ); <add> <add> foreach ($notifications as $notification) { <add> $notification->via((array) $channels); <add> } <add> <add> if ($instance instanceof ShouldQueue) { <add> return $this->queueNotifications($instance, $notifications); <add> } <add> <add> foreach ($notifications as $notification) { <add> $manager->send($notification); <add> } <add> } <add> <ide> /** <ide> * Queue the given notification instances. <ide> *
1
PHP
PHP
trigger a deprecation warning
9438e57de8bfcf60d1e802c979ec7c40295efa33
<ide><path>src/ORM/Table.php <ide> public function hasBehavior($name) <ide> */ <ide> public function association($name) <ide> { <add> deprecationWarning('Use Table::getAssociation() instead.'); <add> <ide> return $this->getAssociation($name); <ide> } <ide>
1
PHP
PHP
fix cs errors
d809b1480e352be58cb045238b3ef40ebce3cf18
<ide><path>lib/Cake/Model/Behavior/TreeBehavior.php <ide> protected function _recoverByParentId(Model $Model, $counter = 1, $parentId = nu <ide> $hasChildren = (bool)$children; <ide> <ide> if (!is_null($parentId)) { <del> if($hasChildren) { <add> if ($hasChildren) { <ide> $Model->updateAll( <ide> array($this->settings[$Model->alias]['left'] => $counter), <ide> array($Model->escapeField() => $parentId) <ide><path>lib/Cake/Test/Case/Controller/Component/Auth/BasicAuthenticateTest.php <ide> public function testAuthenticateChallenge() { <ide> <ide> try { <ide> $this->auth->unauthenticated($request, $this->response); <del> } catch (UnauthorizedException $e) {} <add> } catch (UnauthorizedException $e) { <add> } <ide> <ide> $this->assertNotEmpty($e); <ide> <ide><path>lib/Cake/Test/Case/Controller/Component/Auth/DigestAuthenticateTest.php <ide> public function testAuthenticateChallenge() { <ide> <ide> try { <ide> $this->auth->unauthenticated($request, $this->response); <del> } catch (UnauthorizedException $e) {} <add> } catch (UnauthorizedException $e) { <add> } <ide> <ide> $this->assertNotEmpty($e); <ide> <ide><path>lib/Cake/Test/Case/View/Helper/TextHelperTest.php <ide> public function testAutoParagraph() { <ide> <p>This is a test text</p> <ide> <ide> TEXT; <del> $result = $this->Text->autoParagraph($text); <del> $text = 'This is a <br/> <BR> test text'; <del> $expected = <<<TEXT <add> $result = $this->Text->autoParagraph($text); <add> $text = 'This is a <br/> <BR> test text'; <add> $expected = <<<TEXT <ide> <p>This is a </p> <ide> <p> test text</p> <ide> <ide> TEXT; <del> $result = $this->Text->autoParagraph($text); <del> $this->assertEquals($expected, $result); <del> $result = $this->Text->autoParagraph($text); <del> $text = 'This is a <BR id="test"/><br class="test"> test text'; <del> $expected = <<<TEXT <add> $result = $this->Text->autoParagraph($text); <add> $this->assertEquals($expected, $result); <add> $result = $this->Text->autoParagraph($text); <add> $text = 'This is a <BR id="test"/><br class="test"> test text'; <add> $expected = <<<TEXT <ide> <p>This is a </p> <ide> <p> test text</p> <ide> <ide> TEXT; <del> $result = $this->Text->autoParagraph($text); <del> $this->assertEquals($expected, $result); <add> $result = $this->Text->autoParagraph($text); <add> $this->assertEquals($expected, $result); <ide> $text = <<<TEXT <ide> This is a test text. <ide> This is a line return. <ide><path>lib/Cake/Utility/Validation.php <ide> public static function phone($check, $regex = null, $country = 'all') { <ide> switch ($country) { <ide> case 'us': <ide> case 'ca': <del> // deprecated three-letter-code <del> case 'can': <add> case 'can': // deprecated three-letter-code <ide> case 'all': <ide> // includes all NANPA members. <ide> // see http://en.wikipedia.org/wiki/North_American_Numbering_Plan#List_of_NANPA_countries_and_territories <ide><path>lib/Cake/View/Helper/TextHelper.php <ide> public function autoParagraph($text) { <ide> } <ide> return $text; <ide> } <del> <add> <ide> /** <ide> * @see String::stripLinks() <ide> *
6
Ruby
Ruby
fix whitespace errors
b7a9890d7765a0a6edc1161f58304386266bdf2e
<ide><path>activerecord/test/cases/connection_pool_test.rb <ide> def test_checkout_behaviour <ide> assert_not_nil connection <ide> end <ide> end <del> <add> <ide> threads.each {|t| t.join} <del> <add> <ide> Thread.new do <ide> threads.each do |t| <ide> thread_ids = pool.instance_variable_get(:@reserved_connections).keys
1
Python
Python
manage catch error on old psutil version
17d6318ed5ee94d43819c69d61d4ef1d0ffa1522
<ide><path>glances/processes.py <ide> <ide> import psutil <ide> <add># Workaround for old PsUtil version <add>if hasattr(psutil, 'WindowsError'): <add> PsUtilWindowsError = psutil.WindowsError <add>else: <add> PsUtilWindowsError = None <add> <ide> <ide> def is_kernel_thread(proc): <ide> """Return True if proc is a kernel thread, False instead.""" <ide> def __get_mandatory_stats(self, proc, procstat): <ide> # Patch for issue #391 <ide> try: <ide> self.cmdline_cache[procstat['pid']] = proc.cmdline() <del> except (AttributeError, UnicodeDecodeError, psutil.AccessDenied, psutil.NoSuchProcess, psutil.WindowsError): <add> except (AttributeError, UnicodeDecodeError, psutil.AccessDenied, psutil.NoSuchProcess, PsUtilWindowsError): <ide> self.cmdline_cache[procstat['pid']] = "" <ide> procstat['cmdline'] = self.cmdline_cache[procstat['pid']] <ide>
1
Javascript
Javascript
update modal.js to fix
6a83ac3af62308e4c286ca169f4834b6d2c3fadd
<ide><path>Libraries/Modal/Modal.js <ide> class Modal extends React.Component { <ide> */ <ide> visible: PropTypes.bool, <ide> /** <del> * The `onRequestClose` prop allows passing a function that will be called once the modal has been dismissed. <del> * <del> * _On the Android platform, this is a required function._ <add> * The `onRequestClose` callback is called when the user taps the hardware back button. <add> * @platform android <ide> */ <ide> onRequestClose: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func, <ide> /**
1
PHP
PHP
add env variable
7eb03cdb06259269db02404080d946f52a433825
<ide><path>src/Illuminate/Foundation/Console/ServeCommand.php <ide> protected function startProcess() <ide> return [$key => $value]; <ide> } <ide> <del> return $key === 'APP_ENV' <add> return in_array($key, ['APP_ENV', 'LARAVEL_SAIL']) <ide> ? [$key => $value] <ide> : [$key => false]; <ide> })->all());
1
PHP
PHP
remove unused code.
73c64077b223181d7c47ff6358e3df71af183ec8
<ide><path>src/Illuminate/Notifications/ChannelManager.php <ide> public function deliverVia($channels) <ide> { <ide> $this->defaultChannels = (array) $channels; <ide> } <del> <del> /** <del> * Build a new channel notification from the given object. <del> * <del> * @param mixed $notifiable <del> * @param mixed $notification <del> * @param array|null $channels <del> * @return array <del> */ <del> public function notificationsFromInstance($notifiable, $notification, $channels = null) <del> { <del> return Channels\Notification::notificationsFromInstance($notifiable, $notification, $channels); <del> } <ide> }
1
Ruby
Ruby
include bad value in invalid-option error message
094f6f47ddcb3cabc30ed935a4be4cf855c94e73
<ide><path>Library/Homebrew/software_spec.rb <ide> def option(name, description = "") <ide> puts "Symbols are reserved for future use, please pass a string instead" <ide> name = name.to_s <ide> end <add> unless String === name <add> raise ArgumentError, "option name must be string or symbol; got a #{name.class}: #{name}" <add> end <ide> raise ArgumentError, "option name is required" if name.empty? <del> raise ArgumentError, "option name must be longer than one character" unless name.length > 1 <del> raise ArgumentError, "option name must not start with dashes" if name.start_with?("-") <add> raise ArgumentError, "option name must be longer than one character: #{name}" unless name.length > 1 <add> raise ArgumentError, "option name must not start with dashes: #{name}" if name.start_with?("-") <ide> Option.new(name, description) <ide> end <ide> options << opt
1
Text
Text
update theme docs
3ae5213ebf6ea2de459287117bf327e3d7875080
<ide><path>docs/creating-a-theme.md <ide> a few things before starting: <ide> ## Creating a Minimal Syntax Theme <ide> <ide> 1. Open the Command Palette (`cmd-p`) <del>1. Search for `Package Generator: Generate Theme` and select it. <del>1. Choose a name for the folder which will contain your theme. <add>1. Search for `Package Generator: Generate Syntax Theme` and select it. <add>1. Choose a name for your theme. A folder will be created with this name. <add>1. Press enter to create your theme. After creation, your theme will be <add> installed and enabled. <ide> 1. An Atom window will open with your newly created theme. <ide> 1. Open `package.json` and update the relevant parts. <ide> 1. Open `stylesheets/colors.less` to change the various colors variables which <ide> have been already been defined. <ide> 1. Open `stylesheets/base.less` and modify the various syntax CSS selectors <ide> that have been already been defined. <del> 1. When you're ready update the `README.md` and include an example screenshot <add> 1. When you're ready, update the `README.md` and include an example screenshot <ide> of your new theme in action. <del>1. Reload Atom (`cmd-r`) and your theme should now be applied. <add>1. Reload atom (`cmd-r`) to see changes you made reflected in your Atom window. <ide> 1. Look in the theme settings, your new theme should be show in the enabled themes section <ide> ![themesettings-img] <ide> 1. Open a terminal to your new theme directory; it should be in `~/.atom/packages/<my-name>`. <ide> 1. To publish, initialize a git repository, push to GitHub, and run <ide> `apm publish`. <ide> <add>Want to make edits and have them immediately show up without reloading? Open a <add>development window (__View > Developer > Open in Dev Mode__ menu) to the <add>directory of your choice &mdash; even the new theme itself. Then just edit away! <add>Changes will be instantly reflected in the editor without having to reload. <add> <ide> ## Interface Themes <ide> <ide> There are only two differences between interface and syntax themes - what <ide> To create a UI theme, do the following: <ide> 1. [atom-dark-ui] <ide> 1. [atom-light-ui] <ide> 1. Open a terminal in the forked theme's directory <del>1. Open your new theme in a Dev Mode Atom window (either run `atom -d .` in the terminal or use `cmd-shift-o` from atom) <add>1. Open your new theme in a Dev Mode Atom window (run `atom -d .` in the terminal or use the __View > Developer > Open in Dev Mode__ menu) <ide> 1. Change the name of the theme in the theme's `package.json` file <ide> 1. Run `apm link` to tell Atom about your new theme <ide> 1. Reload Atom (`cmd-r`) <ide> Reloading via `cmd-r` after you make changes to your theme less than ideal. Atom <ide> supports [live updating][livereload] of styles on Dev Mode Atom windows. <ide> <ide> 1. Open your theme directory in a dev window by either using the <del>__File > Open in Dev Mode__ menu or the `cmd-shift-o` shortcut <add>__View > Developer > Open in Dev Mode__ menu or the `cmd-shift-o` shortcut <ide> 1. Make a change to your theme file and save &mdash; your change should be <ide> immediately applied! <ide>
1
Go
Go
update core calls to network drivers
c712e74b45005e0f38297d254fb606aa18606d11
<ide><path>config.go <ide> import ( <ide> "net" <ide> ) <ide> <add>const ( <add> DefaultNetworkMtu = 1500 <add> DisableNetworkBridge = "none" <add>) <add> <ide> // FIXME: separate runtime configuration from http api configuration <ide> type DaemonConfig struct { <ide> Pidfile string <ide> type DaemonConfig struct { <ide> Dns []string <ide> EnableIptables bool <ide> EnableIpForward bool <del> BridgeIface string <del> BridgeIp string <ide> DefaultIp net.IP <add> BridgeIface string <add> BridgeIP string <ide> InterContainerCommunication bool <ide> GraphDriver string <ide> Mtu int <add> DisableNetwork bool <ide> } <ide> <ide> // ConfigFromJob creates and returns a new DaemonConfig object <ide> func DaemonConfigFromJob(job *engine.Job) *DaemonConfig { <ide> AutoRestart: job.GetenvBool("AutoRestart"), <ide> EnableIptables: job.GetenvBool("EnableIptables"), <ide> EnableIpForward: job.GetenvBool("EnableIpForward"), <del> BridgeIp: job.Getenv("BridgeIp"), <add> BridgeIP: job.Getenv("BridgeIp"), <ide> DefaultIp: net.ParseIP(job.Getenv("DefaultIp")), <ide> InterContainerCommunication: job.GetenvBool("InterContainerCommunication"), <ide> GraphDriver: job.Getenv("GraphDriver"), <ide> } <ide> if dns := job.GetenvList("Dns"); dns != nil { <ide> config.Dns = dns <ide> } <del> if br := job.Getenv("BridgeIface"); br != "" { <del> config.BridgeIface = br <del> } else { <del> config.BridgeIface = DefaultNetworkBridge <del> } <ide> if mtu := job.GetenvInt("Mtu"); mtu != 0 { <ide> config.Mtu = mtu <ide> } else { <ide> config.Mtu = DefaultNetworkMtu <ide> } <add> config.DisableNetwork = job.Getenv("BridgeIface") == DisableNetworkBridge <ide> <ide> return config <ide> } <ide><path>container.go <ide> import ( <ide> "github.com/dotcloud/docker/engine" <ide> "github.com/dotcloud/docker/execdriver" <ide> "github.com/dotcloud/docker/graphdriver" <del> "github.com/dotcloud/docker/networkdriver/ipallocator" <ide> "github.com/dotcloud/docker/pkg/mount" <ide> "github.com/dotcloud/docker/pkg/term" <ide> "github.com/dotcloud/docker/utils" <ide> "github.com/kr/pty" <ide> "io" <ide> "io/ioutil" <ide> "log" <del> "net" <ide> "os" <ide> "path" <ide> "path/filepath" <ide> type Container struct { <ide> State State <ide> Image string <ide> <del> network *NetworkInterface <ide> NetworkSettings *NetworkSettings <ide> <ide> ResolvConfPath string <ide> func populateCommand(c *Container) { <ide> en *execdriver.Network <ide> driverConfig []string <ide> ) <add> <ide> if !c.Config.NetworkDisabled { <ide> network := c.NetworkSettings <ide> en = &execdriver.Network{ <ide> func (container *Container) Start() (err error) { <ide> if container.State.IsRunning() { <ide> return fmt.Errorf("The container %s is already running.", container.ID) <ide> } <add> <ide> defer func() { <ide> if err != nil { <ide> container.cleanup() <ide> } <ide> }() <add> <ide> if err := container.Mount(); err != nil { <ide> return err <ide> } <del> if container.runtime.networkManager.disabled { <add> <add> if container.runtime.config.DisableNetwork { <ide> container.Config.NetworkDisabled = true <ide> container.buildHostnameAndHostsFiles("127.0.1.1") <ide> } else { <ide> func (container *Container) Start() (err error) { <ide> } <ide> <ide> if len(children) > 0 { <del> container.activeLinks = make(map[string]*Link, len(children)) <del> <del> // If we encounter an error make sure that we rollback any network <del> // config and ip table changes <del> rollback := func() { <del> for _, link := range container.activeLinks { <del> link.Disable() <del> } <del> container.activeLinks = nil <del> } <del> <del> for p, child := range children { <del> link, err := NewLink(container, child, p, runtime.networkManager.bridgeIface) <del> if err != nil { <del> rollback() <del> return err <del> } <del> <del> container.activeLinks[link.Alias()] = link <del> if err := link.Enable(); err != nil { <del> rollback() <del> return err <del> } <add> panic("todo crosbymichael") <add> /* <add> linking is specific to iptables and the bridge we need to move this to a job <add> <add> container.activeLinks = make(map[string]*Link, len(children)) <add> <add> // If we encounter an error make sure that we rollback any network <add> // config and ip table changes <add> rollback := func() { <add> for _, link := range container.activeLinks { <add> link.Disable() <add> } <add> container.activeLinks = nil <add> } <ide> <del> for _, envVar := range link.ToEnv() { <del> env = append(env, envVar) <del> } <del> } <add> for p, child := range children { <add> link, err := NewLink(container, child, p, runtime.networkManager.bridgeIface) <add> if err != nil { <add> rollback() <add> return err <add> } <add> <add> container.activeLinks[link.Alias()] = link <add> if err := link.Enable(); err != nil { <add> rollback() <add> return err <add> } <add> <add> for _, envVar := range link.ToEnv() { <add> env = append(env, envVar) <add> } <add> } <add> */ <ide> } <ide> <ide> for _, elem := range container.Config.Env { <ide> func (container *Container) allocateNetwork() error { <ide> } <ide> <ide> var ( <del> iface *NetworkInterface <del> err error <add> env *engine.Env <add> eng = container.runtime.srv.Eng <ide> ) <ide> if container.State.IsGhost() { <del> if manager := container.runtime.networkManager; manager.disabled { <del> iface = &NetworkInterface{disabled: true} <add> if container.runtime.config.DisableNetwork { <add> env = &engine.Env{} <ide> } else { <del> iface = &NetworkInterface{ <del> IPNet: net.IPNet{IP: net.ParseIP(container.NetworkSettings.IPAddress), Mask: manager.bridgeNetwork.Mask}, <del> Gateway: manager.bridgeNetwork.IP, <del> manager: manager, <del> } <del> if iface != nil && iface.IPNet.IP != nil { <del> if _, err := ipallocator.RequestIP(manager.bridgeNetwork, &iface.IPNet.IP); err != nil { <del> return err <add> // TODO: @crosbymichael <add> panic("not implemented") <add> /* <add> iface = &NetworkInterface{ <add> IPNet: net.IPNet{IP: net.ParseIP(container.NetworkSettings.IPAddress), Mask: manager.bridgeNetwork.Mask}, <add> Gateway: manager.bridgeNetwork.IP, <ide> } <del> } else { <del> iface, err = container.runtime.networkManager.Allocate() <del> if err != nil { <del> return err <add> <add> // request an existing ip <add> if iface != nil && iface.IPNet.IP != nil { <add> if _, err := ipallocator.RequestIP(manager.bridgeNetwork, &iface.IPNet.IP); err != nil { <add> return err <add> } <add> } else { <add> job = eng.Job("allocate_interface", container.ID) <add> if err := job.Run(); err != nil { <add> return err <add> } <ide> } <del> } <add> */ <ide> } <ide> } else { <del> iface, err = container.runtime.networkManager.Allocate() <add> job := eng.Job("allocate_interface", container.ID) <add> var err error <add> env, err = job.Stdout.AddEnv() <ide> if err != nil { <ide> return err <ide> } <add> if err := job.Run(); err != nil { <add> return err <add> } <ide> } <ide> <ide> if container.Config.PortSpecs != nil { <ide> func (container *Container) allocateNetwork() error { <ide> if container.hostConfig.PublishAllPorts && len(binding) == 0 { <ide> binding = append(binding, PortBinding{}) <ide> } <add> <ide> for i := 0; i < len(binding); i++ { <ide> b := binding[i] <del> nat, err := iface.AllocatePort(port, b) <del> if err != nil { <del> iface.Release() <add> <add> portJob := eng.Job("allocate_port", container.ID) <add> portJob.Setenv("HostIP", b.HostIp) <add> portJob.Setenv("HostPort", b.HostPort) <add> portJob.Setenv("Proto", port.Proto()) <add> portJob.Setenv("ContainerPort", port.Port()) <add> <add> if err := portJob.Run(); err != nil { <add> eng.Job("release_interface", container.ID).Run() <ide> return err <ide> } <del> utils.Debugf("Allocate port: %s:%s->%s", nat.Binding.HostIp, port, nat.Binding.HostPort) <del> binding[i] = nat.Binding <ide> } <ide> bindings[port] = binding <ide> } <ide> container.writeHostConfig() <ide> <ide> container.NetworkSettings.Ports = bindings <del> container.network = iface <ide> <del> container.NetworkSettings.Bridge = container.runtime.networkManager.bridgeIface <del> container.NetworkSettings.IPAddress = iface.IPNet.IP.String() <del> container.NetworkSettings.IPPrefixLen, _ = iface.IPNet.Mask.Size() <del> container.NetworkSettings.Gateway = iface.Gateway.String() <add> container.NetworkSettings.Bridge = env.Get("Bridge") <add> container.NetworkSettings.IPAddress = env.Get("IP") <add> container.NetworkSettings.IPPrefixLen = env.GetInt("IPPrefixLen") <add> container.NetworkSettings.Gateway = env.Get("Gateway") <add> fmt.Printf("\n-----> %#v\n", container.NetworkSettings) <ide> <ide> return nil <ide> } <ide> <ide> func (container *Container) releaseNetwork() { <del> if container.Config.NetworkDisabled || container.network == nil { <add> if container.Config.NetworkDisabled { <ide> return <ide> } <del> container.network.Release() <del> container.network = nil <add> eng := container.runtime.srv.Eng <add> <add> eng.Job("release_interface", container.ID).Run() <ide> container.NetworkSettings = &NetworkSettings{} <ide> } <ide> <ide><path>networkdriver/lxc/driver.go <ide> import ( <ide> <ide> const ( <ide> DefaultNetworkBridge = "docker0" <del> DisableNetworkBridge = "none" <del> DefaultNetworkMtu = 1500 <ide> siocBRADDBR = 0x89a0 <ide> ) <ide> <ide> func InitDriver(job *engine.Job) engine.Status { <ide> enableIPTables = job.GetenvBool("EnableIptables") <ide> icc = job.GetenvBool("InterContainerCommunication") <ide> ipForward = job.GetenvBool("EnableIpForward") <add> bridgeIP = job.Getenv("BridgeIP") <ide> ) <add> <ide> bridgeIface = job.Getenv("BridgeIface") <add> if bridgeIface == "" { <add> bridgeIface = DefaultNetworkBridge <add> } <ide> <ide> addr, err := networkdriver.GetIfaceAddr(bridgeIface) <ide> if err != nil { <ide> // If the iface is not found, try to create it <del> if err := createBridgeIface(bridgeIface); err != nil { <add> job.Logf("creating new bridge for %s", bridgeIface) <add> if err := createBridge(bridgeIP); err != nil { <ide> job.Error(err) <ide> return engine.StatusErr <ide> } <ide> <add> job.Logf("getting iface addr") <ide> addr, err = networkdriver.GetIfaceAddr(bridgeIface) <ide> if err != nil { <ide> job.Error(err) <ide> func InitDriver(job *engine.Job) engine.Status { <ide> } <ide> <ide> bridgeNetwork = network <add> <add> // https://github.com/dotcloud/docker/issues/2768 <add> job.Eng.Hack_SetGlobalVar("httpapi.bridgeIP", bridgeNetwork.IP) <add> <ide> for name, f := range map[string]engine.Handler{ <ide> "allocate_interface": Allocate, <ide> "release_interface": Release, <add> "allocate_port": AllocatePort, <ide> } { <ide> if err := job.Eng.Register(name, f); err != nil { <ide> job.Error(err) <ide> func Allocate(job *engine.Job) engine.Status { <ide> out.Set("IP", string(*ip)) <ide> out.Set("Mask", string(bridgeNetwork.Mask)) <ide> out.Set("Gateway", string(bridgeNetwork.IP)) <add> out.Set("Bridge", bridgeIface) <add> <add> size, _ := bridgeNetwork.Mask.Size() <add> out.SetInt("IPPrefixLen", size) <ide> <ide> currentInterfaces[id] = &networkInterface{ <ide> IP: *ip, <ide><path>runtime.go <ide> import ( <ide> "container/list" <ide> "fmt" <ide> "github.com/dotcloud/docker/archive" <add> "github.com/dotcloud/docker/engine" <ide> "github.com/dotcloud/docker/execdriver" <ide> "github.com/dotcloud/docker/execdriver/chroot" <ide> "github.com/dotcloud/docker/execdriver/lxc" <ide> import ( <ide> _ "github.com/dotcloud/docker/graphdriver/btrfs" <ide> _ "github.com/dotcloud/docker/graphdriver/devmapper" <ide> _ "github.com/dotcloud/docker/graphdriver/vfs" <add> _ "github.com/dotcloud/docker/networkdriver/lxc" <ide> "github.com/dotcloud/docker/networkdriver/portallocator" <ide> "github.com/dotcloud/docker/pkg/graphdb" <ide> "github.com/dotcloud/docker/pkg/sysinfo" <ide> type Runtime struct { <ide> repository string <ide> sysInitPath string <ide> containers *list.List <del> networkManager *NetworkManager <ide> graph *Graph <ide> repositories *TagStore <ide> idIndex *utils.TruncIndex <ide> func (runtime *Runtime) RegisterLink(parent, child *Container, alias string) err <ide> } <ide> <ide> // FIXME: harmonize with NewGraph() <del>func NewRuntime(config *DaemonConfig) (*Runtime, error) { <del> runtime, err := NewRuntimeFromDirectory(config) <add>func NewRuntime(config *DaemonConfig, eng *engine.Engine) (*Runtime, error) { <add> runtime, err := NewRuntimeFromDirectory(config, eng) <ide> if err != nil { <ide> return nil, err <ide> } <ide> return runtime, nil <ide> } <ide> <del>func NewRuntimeFromDirectory(config *DaemonConfig) (*Runtime, error) { <add>func NewRuntimeFromDirectory(config *DaemonConfig, eng *engine.Engine) (*Runtime, error) { <ide> <ide> // Set the default driver <ide> graphdriver.DefaultDriver = config.GraphDriver <ide> func NewRuntimeFromDirectory(config *DaemonConfig) (*Runtime, error) { <ide> if err != nil { <ide> return nil, fmt.Errorf("Couldn't create Tag store: %s", err) <ide> } <del> if config.BridgeIface == "" { <del> config.BridgeIface = DefaultNetworkBridge <del> } <del> netManager, err := newNetworkManager(config) <del> if err != nil { <del> return nil, err <add> <add> if !config.DisableNetwork { <add> job := eng.Job("init_networkdriver") <add> <add> job.SetenvBool("EnableIptables", config.EnableIptables) <add> job.SetenvBool("InterContainerCommunication", config.InterContainerCommunication) <add> job.SetenvBool("EnableIpForward", config.EnableIpForward) <add> job.Setenv("BridgeIface", config.BridgeIface) <add> job.Setenv("BridgeIP", config.BridgeIP) <add> <add> if err := job.Run(); err != nil { <add> return nil, err <add> } <ide> } <ide> <ide> graphdbPath := path.Join(config.Root, "linkgraph.db") <ide> func NewRuntimeFromDirectory(config *DaemonConfig) (*Runtime, error) { <ide> runtime := &Runtime{ <ide> repository: runtimeRepo, <ide> containers: list.New(), <del> networkManager: netManager, <ide> graph: g, <ide> repositories: repositories, <ide> idIndex: utils.NewTruncIndex(), <ide><path>server.go <ide> func jobInitApi(job *engine.Job) engine.Status { <ide> }() <ide> job.Eng.Hack_SetGlobalVar("httpapi.server", srv) <ide> job.Eng.Hack_SetGlobalVar("httpapi.runtime", srv.runtime) <del> // https://github.com/dotcloud/docker/issues/2768 <del> if srv.runtime.networkManager.bridgeNetwork != nil { <del> job.Eng.Hack_SetGlobalVar("httpapi.bridgeIP", srv.runtime.networkManager.bridgeNetwork.IP) <del> } <add> <ide> for name, handler := range map[string]engine.Handler{ <ide> "export": srv.ContainerExport, <ide> "create": srv.ContainerCreate, <ide> func (srv *Server) ContainerCopy(job *engine.Job) engine.Status { <ide> } <ide> <ide> func NewServer(eng *engine.Engine, config *DaemonConfig) (*Server, error) { <del> runtime, err := NewRuntime(config) <add> runtime, err := NewRuntime(config, eng) <ide> if err != nil { <ide> return nil, err <ide> }
5
Ruby
Ruby
improve mysql2 mismatched foreign keys reporting
df5023a541b1c329dcbfe9811e6e853957d3472e
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def build_statement_pool <ide> end <ide> <ide> def mismatched_foreign_key(message, sql:, binds:) <add> foreign_key_pat = <add> /Referencing column '(\w+)' and referenced/i =~ message ? $1 : '\w+' <add> <ide> match = %r/ <ide> (?:CREATE|ALTER)\s+TABLE\s*(?:`?\w+`?\.)?`?(?<table>\w+)`?.+? <del> FOREIGN\s+KEY\s*\(`?(?<foreign_key>\w+)`?\)\s* <add> FOREIGN\s+KEY\s*\(`?(?<foreign_key>#{foreign_key_pat})`?\)\s* <ide> REFERENCES\s*(`?(?<target_table>\w+)`?)\s*\(`?(?<primary_key>\w+)`?\) <ide> /xmi.match(sql) <ide> <ide><path>activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb <ide> def test_errors_for_bigint_fks_on_integer_pk_table_in_alter_table <ide> @conn.execute("ALTER TABLE engines DROP COLUMN old_car_id") rescue nil <ide> end <ide> <add> def test_errors_for_multiple_fks_on_mismatched_types_for_pk_table_in_alter_table <add> skip "MariaDB does not return mismatched foreign key in error message" if @conn.mariadb? <add> <add> begin <add> error = assert_raises(ActiveRecord::MismatchedForeignKey) do <add> # we should add matched foreign key first to properly test error parsing <add> @conn.add_reference :engines, :person, foreign_key: true <add> <add> # table old_cars has primary key of integer <add> @conn.add_reference :engines, :old_car, foreign_key: true <add> end <add> <add> assert_match( <add> %r/Column `old_car_id` on table `engines` does not match column `id` on `old_cars`, which has type `int(\(11\))?`\./, <add> error.message <add> ) <add> assert_match( <add> %r/To resolve this issue, change the type of the `old_car_id` column on `engines` to be :integer\. \(For example `t.integer :old_car_id`\)\./, <add> error.message <add> ) <add> assert_not_nil error.cause <add> ensure <add> @conn.remove_reference(:engines, :person) <add> @conn.remove_reference(:engines, :old_car) <add> end <add> end <add> <ide> def test_errors_for_bigint_fks_on_integer_pk_table_in_create_table <ide> # table old_cars has primary key of integer <ide>
2
Text
Text
fix wrong condition for an app rejection
45cb6753b536aa54383836201cdd74fe63937c12
<ide><path>docs/Acceptable-Casks.md <ide> Common reasons to reject a cask entirely: <ide> + The author has [specifically asked us not to include it](https://github.com/Homebrew/homebrew-cask/pull/5342). <ide> + App requires [SIP to be disabled](https://github.com/Homebrew/homebrew-cask/pull/41890) to be installed and/or used. <ide> + App installer is a `pkg` that requires [`allow_untrusted: true`](https://docs.brew.sh/Cask-Cookbook#pkg-allow_untrusted). <del>+ App works on Homebrew supported macOS versions and platforms with GateKeeper enabled. <add>+ App fails with GateKeeper enabled on Homebrew supported macOS versions and platforms (e.g., unsigned apps fail on Macs with Apple silicon/ARM). <ide> <ide> Common reasons to reject a cask from the main repo: <ide>
1
Javascript
Javascript
simplify agent initialization
f19a576f6c73d21064699c8cc81a26ac5139a88b
<ide><path>lib/_http_agent.js <ide> function Agent(options) { <ide> return; <ide> } <ide> <del> let freeSockets = this.freeSockets[name]; <del> const freeLen = freeSockets ? freeSockets.length : 0; <add> const freeSockets = this.freeSockets[name] || []; <add> const freeLen = freeSockets.length; <ide> let count = freeLen; <ide> if (this.sockets[name]) <ide> count += this.sockets[name].length; <ide> function Agent(options) { <ide> return; <ide> } <ide> <del> freeSockets = freeSockets || []; <ide> this.freeSockets[name] = freeSockets; <ide> socket[async_id_symbol] = -1; <ide> socket._httpMessage = null;
1
Go
Go
fix a failed test
1d9973c0d4c51362e8c5b38e585a025c90baf085
<ide><path>integration-cli/docker_cli_run_unix_test.go <ide> func (s *DockerSuite) TestRunOOMExitCode(c *check.C) { <ide> errChan := make(chan error) <ide> go func() { <ide> defer close(errChan) <del> out, exitCode, _ := dockerCmdWithError("run", "-m", "4MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done") <add> // memory limit lower than 8MB will raise an error of "device or resource busy" from docker-runc. <add> out, exitCode, _ := dockerCmdWithError("run", "-m", "8MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done") <ide> if expected := 137; exitCode != expected { <ide> errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out) <ide> }
1
PHP
PHP
add test for options with 0 value
b20f6e132d06968bc33a0f30dbb23d94a3ae51b4
<ide><path>lib/Cake/Test/Case/Console/ConsoleOptionParserTest.php <ide> public function testAddOptionLong() { <ide> $this->assertEquals(array('test' => 'value', 'help' => false), $result[0], 'Long parameter did not parse out'); <ide> } <ide> <add>/** <add> * test adding an option with a zero value <add> * <add> * @return void <add> */ <add> public function testAddOptionZero() { <add> $parser = new ConsoleOptionParser('test', false); <add> $parser->addOption('count', array()); <add> $result = $parser->parse(array('--count', '0')); <add> $this->assertEquals(array('count' => '0', 'help' => false), $result[0], 'Zero parameter did not parse out'); <add> } <add> <ide> /** <ide> * test addOption with an object. <ide> *
1
Javascript
Javascript
make variables and checks stricter
1d6b729cea909769ac0bcb3aa68f5fe567c4ffb7
<ide><path>lib/console.js <ide> function Console(stdout, stderr, ignoreErrors = true) { <ide> Object.defineProperty(this, '_stdout', prop); <ide> prop.value = stderr; <ide> Object.defineProperty(this, '_stderr', prop); <del> prop.value = ignoreErrors; <add> prop.value = Boolean(ignoreErrors); <ide> Object.defineProperty(this, '_ignoreErrors', prop); <ide> prop.value = new Map(); <ide> Object.defineProperty(this, '_times', prop); <ide> function createWriteErrorHandler(stream) { <ide> // This conditional evaluates to true if and only if there was an error <ide> // that was not already emitted (which happens when the _write callback <ide> // is invoked asynchronously). <del> if (err && !stream._writableState.errorEmitted) { <add> if (err !== null && !stream._writableState.errorEmitted) { <ide> // If there was an error, it will be emitted on `stream` as <ide> // an `error` event. Adding a `once` listener will keep that error <ide> // from becoming an uncaught exception, but since the handler is <ide> function write(ignoreErrors, stream, string, errorhandler, groupIndent) { <ide> } <ide> string += '\n'; <ide> <del> if (!ignoreErrors) return stream.write(string); <add> if (ignoreErrors === false) return stream.write(string); <ide> <ide> // There may be an error occurring synchronously (e.g. for files or TTYs <ide> // on POSIX systems) or asynchronously (e.g. pipes on POSIX systems), so
1
Go
Go
fix stale sandbox from store problem
670302e66b25061be8e7317d07c6507a167faecb
<ide><path>libnetwork/controller.go <ide> type NetworkController interface { <ide> // SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned. <ide> SandboxByID(id string) (Sandbox, error) <ide> <add> // SandboxDestroy destroys a sandbox given a container ID <add> SandboxDestroy(id string) error <add> <ide> // Stop network controller <ide> Stop() <ide> } <ide> func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (S <ide> return nil, types.BadRequestErrorf("invalid container ID") <ide> } <ide> <del> var existing Sandbox <del> look := SandboxContainerWalker(&existing, containerID) <del> c.WalkSandboxes(look) <del> if existing != nil { <del> return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, existing) <add> var sb *sandbox <add> c.Lock() <add> for _, s := range c.sandboxes { <add> if s.containerID == containerID { <add> // If not a stub, then we already have a complete sandbox. <add> if !s.isStub { <add> c.Unlock() <add> return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, s) <add> } <add> <add> // We already have a stub sandbox from the <add> // store. Make use of it so that we don't lose <add> // the endpoints from store but reset the <add> // isStub flag. <add> sb = s <add> sb.isStub = false <add> break <add> } <ide> } <add> c.Unlock() <ide> <ide> // Create sandbox and process options first. Key generation depends on an option <del> sb := &sandbox{ <del> id: stringid.GenerateRandomID(), <del> containerID: containerID, <del> endpoints: epHeap{}, <del> epPriority: map[string]int{}, <del> config: containerConfig{}, <del> controller: c, <add> if sb == nil { <add> sb = &sandbox{ <add> id: stringid.GenerateRandomID(), <add> containerID: containerID, <add> endpoints: epHeap{}, <add> epPriority: map[string]int{}, <add> config: containerConfig{}, <add> controller: c, <add> } <ide> } <ide> <ide> heap.Init(&sb.endpoints) <ide> func (c *controller) Sandboxes() []Sandbox { <ide> <ide> list := make([]Sandbox, 0, len(c.sandboxes)) <ide> for _, s := range c.sandboxes { <add> // Hide stub sandboxes from libnetwork users <add> if s.isStub { <add> continue <add> } <add> <ide> list = append(list, s) <ide> } <ide> <ide> func (c *controller) SandboxByID(id string) (Sandbox, error) { <ide> return s, nil <ide> } <ide> <add>// SandboxDestroy destroys a sandbox given a container ID <add>func (c *controller) SandboxDestroy(id string) error { <add> var sb *sandbox <add> c.Lock() <add> for _, s := range c.sandboxes { <add> if s.containerID == id { <add> sb = s <add> break <add> } <add> } <add> c.Unlock() <add> <add> // It is not an error if sandbox is not available <add> if sb == nil { <add> return nil <add> } <add> <add> return sb.Delete() <add>} <add> <ide> // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID <ide> func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker { <ide> return func(sb Sandbox) bool { <ide><path>libnetwork/sandbox.go <ide> type sandbox struct { <ide> joinLeaveDone chan struct{} <ide> dbIndex uint64 <ide> dbExists bool <add> isStub bool <ide> inDelete bool <ide> sync.Mutex <ide> } <ide><path>libnetwork/sandbox_store.go <ide> func (c *controller) sandboxCleanup() { <ide> endpoints: epHeap{}, <ide> epPriority: map[string]int{}, <ide> dbIndex: sbs.dbIndex, <add> isStub: true, <ide> dbExists: true, <ide> } <ide>
3
PHP
PHP
simplify some model code
b99066ddd92315872192946b5deb7162bdc64ab3
<ide><path>lib/Cake/Model/Model.php <ide> public function deconstruct($field, $data) { <ide> <ide> $type = $this->getColumnType($field); <ide> <del> if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) { <del> $useNewDate = (isset($data['year']) || isset($data['month']) || <del> isset($data['day']) || isset($data['hour']) || isset($data['minute'])); <add> if (!in_array($type, array('datetime', 'timestamp', 'date', 'time'))) { <add> return $data; <add> } <ide> <del> $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec'); <del> $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec'); <del> $date = array(); <add> $useNewDate = (isset($data['year']) || isset($data['month']) || <add> isset($data['day']) || isset($data['hour']) || isset($data['minute'])); <ide> <del> if (isset($data['meridian']) && empty($data['meridian'])) { <del> return null; <del> } <add> $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec'); <add> $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec'); <add> $date = array(); <ide> <del> if ( <del> isset($data['hour']) && <del> isset($data['meridian']) && <del> !empty($data['hour']) && <del> $data['hour'] != 12 && <del> 'pm' == $data['meridian'] <del> ) { <del> $data['hour'] = $data['hour'] + 12; <del> } <del> if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) { <del> $data['hour'] = '00'; <add> if (isset($data['meridian']) && empty($data['meridian'])) { <add> return null; <add> } <add> <add> if ( <add> isset($data['hour']) && <add> isset($data['meridian']) && <add> !empty($data['hour']) && <add> $data['hour'] != 12 && <add> 'pm' == $data['meridian'] <add> ) { <add> $data['hour'] = $data['hour'] + 12; <add> } <add> if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) { <add> $data['hour'] = '00'; <add> } <add> if ($type == 'time') { <add> foreach ($timeFields as $key => $val) { <add> if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') { <add> $data[$val] = '00'; <add> } elseif ($data[$val] !== '') { <add> $data[$val] = sprintf('%02d', $data[$val]); <add> } <add> if (!empty($data[$val])) { <add> $date[$key] = $data[$val]; <add> } else { <add> return null; <add> } <ide> } <del> if ($type == 'time') { <del> foreach ($timeFields as $key => $val) { <add> } <add> <add> if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') { <add> foreach ($dateFields as $key => $val) { <add> if ($val == 'hour' || $val == 'min' || $val == 'sec') { <ide> if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') { <ide> $data[$val] = '00'; <del> } elseif ($data[$val] !== '') { <del> $data[$val] = sprintf('%02d', $data[$val]); <del> } <del> if (!empty($data[$val])) { <del> $date[$key] = $data[$val]; <ide> } else { <del> return null; <add> $data[$val] = sprintf('%02d', $data[$val]); <ide> } <ide> } <del> } <del> <del> if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') { <del> foreach ($dateFields as $key => $val) { <del> if ($val == 'hour' || $val == 'min' || $val == 'sec') { <del> if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') { <del> $data[$val] = '00'; <del> } else { <del> $data[$val] = sprintf('%02d', $data[$val]); <del> } <del> } <del> if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) { <del> return null; <del> } <del> if (isset($data[$val]) && !empty($data[$val])) { <del> $date[$key] = $data[$val]; <del> } <add> if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) { <add> return null; <add> } <add> if (isset($data[$val]) && !empty($data[$val])) { <add> $date[$key] = $data[$val]; <ide> } <ide> } <add> } <ide> <del> if ($useNewDate && !empty($date)) { <del> $format = $this->getDataSource()->columns[$type]['format']; <del> foreach (array('m', 'd', 'H', 'i', 's') as $index) { <del> if (isset($date[$index])) { <del> $date[$index] = sprintf('%02d', $date[$index]); <del> } <add> if ($useNewDate && !empty($date)) { <add> $format = $this->getDataSource()->columns[$type]['format']; <add> foreach (array('m', 'd', 'H', 'i', 's') as $index) { <add> if (isset($date[$index])) { <add> $date[$index] = sprintf('%02d', $date[$index]); <ide> } <del> return str_replace(array_keys($date), array_values($date), $format); <ide> } <add> return str_replace(array_keys($date), array_values($date), $format); <ide> } <ide> return $data; <ide> } <ide> public function schema($field = false) { <ide> $this->_schema = array(); <ide> } <ide> } <del> if (is_string($field)) { <del> if (isset($this->_schema[$field])) { <del> return $this->_schema[$field]; <del> } else { <del> return null; <del> } <add> if (!is_string($field)) { <add> return $this->_schema; <add> } <add> if (isset($this->_schema[$field])) { <add> return $this->_schema[$field]; <ide> } <del> return $this->_schema; <add> return null; <ide> } <ide> <ide> /** <ide> public function hasField($name, $checkVirtual = false) { <ide> return false; <ide> } <ide> <del> if ($checkVirtual && !empty($this->virtualFields)) { <del> if ($this->isVirtualField($name)) { <del> return true; <del> } <add> if ($checkVirtual && !empty($this->virtualFields) && $this->isVirtualField($name)) { <add> return true; <ide> } <ide> <ide> if (empty($this->_schema)) { <ide> public function hasMethod($method) { <ide> if (method_exists($this, $method)) { <ide> return true; <ide> } <del> if ($this->Behaviors->hasMethod($method)) { <del> return true; <del> } <del> return false; <add> return $this->Behaviors->hasMethod($method); <ide> } <ide> <ide> /** <ide> public function getVirtualField($field = null) { <ide> } <ide> if ($this->isVirtualField($field)) { <ide> if (strpos($field, '.') !== false) { <del> list($model, $field) = explode('.', $field); <add> list(, $field) = pluginSplit($field); <ide> } <ide> return $this->virtualFields[$field]; <ide> } <ide> public function field($name, $conditions = null, $order = null) { <ide> if ($conditions === null && $this->id !== false) { <ide> $conditions = array($this->alias . '.' . $this->primaryKey => $this->id); <ide> } <add> $recursive = $this->recursive; <ide> if ($this->recursive >= 1) { <ide> $recursive = -1; <del> } else { <del> $recursive = $this->recursive; <ide> } <ide> $fields = $name; <del> if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) { <del> if (strpos($name, '.') === false) { <del> if (isset($data[$this->alias][$name])) { <del> return $data[$this->alias][$name]; <del> } <del> } else { <del> $name = explode('.', $name); <del> if (isset($data[$name[0]][$name[1]])) { <del> return $data[$name[0]][$name[1]]; <del> } <del> } <del> if (isset($data[0]) && count($data[0]) > 0) { <del> return array_shift($data[0]); <add> $data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive')); <add> if (!$data) { <add> return false; <add> } <add> if (strpos($name, '.') === false) { <add> if (isset($data[$this->alias][$name])) { <add> return $data[$this->alias][$name]; <ide> } <ide> } else { <del> return false; <add> $name = explode('.', $name); <add> if (isset($data[$name[0]][$name[1]])) { <add> return $data[$name[0]][$name[1]]; <add> } <add> } <add> if (isset($data[0]) && count($data[0]) > 0) { <add> return array_shift($data[0]); <ide> } <ide> } <ide> <ide> public function saveField($name, $value, $validate = false) { <ide> $id = $this->id; <ide> $this->create(false); <ide> <add> $options = array('validate' => $validate, 'fieldList' => array($name)); <ide> if (is_array($validate)) { <ide> $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate); <del> } else { <del> $options = array('validate' => $validate, 'fieldList' => array($name)); <ide> } <ide> return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options); <ide> } <ide> public function save($data = null, $validate = true, $fieldList = array()) { <ide> } <ide> <ide> if (!empty($options['fieldList'])) { <add> $this->whitelist = $options['fieldList']; <ide> if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) { <ide> $this->whitelist = $options['fieldList'][$this->alias]; <del> } else { <del> $this->whitelist = $options['fieldList']; <ide> } <ide> } elseif ($options['fieldList'] === null) { <ide> $this->whitelist = array(); <ide> public function save($data = null, $validate = true, $fieldList = array()) { <ide> } <ide> <ide> if (!$db->create($this, $fields, $values)) { <del> $success = $created = false; <add> $success = false; <ide> } else { <ide> $created = true; <ide> } <ide> public function saveMany($data = null, $options = array()) { <ide> if ($validates) { <ide> if ($transactionBegun) { <ide> return $db->commit() !== false; <del> } else { <del> return true; <ide> } <add> return true; <ide> } <ide> $db->rollback(); <ide> return false; <ide> public function saveAssociated($data = null, $options = array()) { <ide> if ($validates) { <ide> if ($transactionBegun) { <ide> return $db->commit() !== false; <del> } else { <del> return true; <ide> } <add> return true; <ide> } <ide> $db->rollback(); <ide> return false; <ide> public function delete($id = null, $cascade = true) { <ide> $event = new CakeEvent('Model.beforeDelete', $this, array($cascade)); <ide> list($event->break, $event->breakOn) = array(true, array(false, null)); <ide> $this->getEventManager()->dispatch($event); <del> if (!$event->isStopped()) { <del> if (!$this->exists()) { <del> return false; <del> } <del> $db = $this->getDataSource(); <add> if ($event->isStopped()) { <add> return false; <add> } <add> if (!$this->exists()) { <add> return false; <add> } <ide> <del> $this->_deleteDependent($id, $cascade); <del> $this->_deleteLinks($id); <del> $this->id = $id; <add> $this->_deleteDependent($id, $cascade); <add> $this->_deleteLinks($id); <add> $this->id = $id; <ide> <del> $updateCounterCache = false; <del> if (!empty($this->belongsTo)) { <del> foreach ($this->belongsTo as $assoc) { <del> if (!empty($assoc['counterCache'])) { <del> $updateCounterCache = true; <del> break; <del> } <del> } <del> if ($updateCounterCache) { <del> $keys = $this->find('first', array( <del> 'fields' => $this->_collectForeignKeys(), <del> 'conditions' => array($this->alias . '.' . $this->primaryKey => $id), <del> 'recursive' => -1, <del> 'callbacks' => false <del> )); <add> if (!empty($this->belongsTo)) { <add> foreach ($this->belongsTo as $assoc) { <add> if (empty($assoc['counterCache'])) { <add> continue; <ide> } <del> } <ide> <del> if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) { <del> if ($updateCounterCache) { <del> $this->updateCounterCache($keys[$this->alias]); <del> } <del> $this->getEventManager()->dispatch(new CakeEvent('Model.afterDelete', $this)); <del> $this->_clearCache(); <del> $this->id = false; <del> return true; <add> $keys = $this->find('first', array( <add> 'fields' => $this->_collectForeignKeys(), <add> 'conditions' => array($this->alias . '.' . $this->primaryKey => $id), <add> 'recursive' => -1, <add> 'callbacks' => false <add> )); <add> break; <ide> } <ide> } <del> return false; <add> <add> if (!$this->getDataSource()->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) { <add> return false; <add> } <add> <add> if (!empty($keys[$this->alias])) { <add> $this->updateCounterCache($keys[$this->alias]); <add> } <add> $this->getEventManager()->dispatch(new CakeEvent('Model.afterDelete', $this)); <add> $this->_clearCache(); <add> $this->id = false; <add> return true; <ide> } <ide> <ide> /** <ide> public function delete($id = null, $cascade = true) { <ide> * @return void <ide> */ <ide> protected function _deleteDependent($id, $cascade) { <add> if ($cascade !== true) { <add> return; <add> } <ide> if (!empty($this->__backAssociation)) { <ide> $savedAssociatons = $this->__backAssociation; <ide> $this->__backAssociation = array(); <ide> } <del> if ($cascade === true) { <del> foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) { <del> if ($data['dependent'] === true) { <ide> <del> $model = $this->{$assoc}; <add> foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) { <add> if ($data['dependent'] === true) { <add> $model = $this->{$assoc}; <ide> <del> if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $model->getAssociated('belongsTo'))) { <del> $model->recursive = 0; <del> $conditions = array($this->escapeField(null, $this->name) => $id); <del> } else { <del> $model->recursive = -1; <del> $conditions = array($model->escapeField($data['foreignKey']) => $id); <del> if ($data['conditions']) { <del> $conditions = array_merge((array)$data['conditions'], $conditions); <del> } <add> if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $model->getAssociated('belongsTo'))) { <add> $model->recursive = 0; <add> $conditions = array($this->escapeField(null, $this->name) => $id); <add> } else { <add> $model->recursive = -1; <add> $conditions = array($model->escapeField($data['foreignKey']) => $id); <add> if ($data['conditions']) { <add> $conditions = array_merge((array)$data['conditions'], $conditions); <ide> } <add> } <ide> <del> if (isset($data['exclusive']) && $data['exclusive']) { <del> $model->deleteAll($conditions); <del> } else { <del> $records = $model->find('all', array( <del> 'conditions' => $conditions, 'fields' => $model->primaryKey <del> )); <add> if (isset($data['exclusive']) && $data['exclusive']) { <add> $model->deleteAll($conditions); <add> } else { <add> $records = $model->find('all', array( <add> 'conditions' => $conditions, 'fields' => $model->primaryKey <add> )); <ide> <del> if (!empty($records)) { <del> foreach ($records as $record) { <del> $model->delete($record[$model->alias][$model->primaryKey]); <del> } <add> if (!empty($records)) { <add> foreach ($records as $record) { <add> $model->delete($record[$model->alias][$model->primaryKey]); <ide> } <ide> } <ide> } <ide> public function deleteAll($conditions, $cascade = true, $callbacks = false) { <ide> <ide> if (!$cascade && !$callbacks) { <ide> return $db->delete($this, $conditions); <del> } else { <del> $ids = $this->find('all', array_merge(array( <del> 'fields' => "{$this->alias}.{$this->primaryKey}", <del> 'recursive' => 0), compact('conditions')) <del> ); <del> if ($ids === false) { <del> return false; <del> } <add> } <add> $ids = $this->find('all', array_merge(array( <add> 'fields' => "{$this->alias}.{$this->primaryKey}", <add> 'recursive' => 0), compact('conditions')) <add> ); <add> if ($ids === false) { <add> return false; <add> } <ide> <del> $ids = Hash::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}"); <del> if (empty($ids)) { <del> return true; <add> $ids = Hash::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}"); <add> if (empty($ids)) { <add> return true; <add> } <add> <add> if ($callbacks) { <add> $_id = $this->id; <add> $result = true; <add> foreach ($ids as $id) { <add> $result = $result && $this->delete($id, $cascade); <ide> } <add> $this->id = $_id; <add> return $result; <add> } <ide> <del> if ($callbacks) { <del> $_id = $this->id; <del> $result = true; <del> foreach ($ids as $id) { <del> $result = ($result && $this->delete($id, $cascade)); <del> } <del> $this->id = $_id; <del> return $result; <del> } else { <del> foreach ($ids as $id) { <del> $this->_deleteLinks($id); <del> if ($cascade) { <del> $this->_deleteDependent($id, $cascade); <del> } <del> } <del> return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids)); <add> foreach ($ids as $id) { <add> $this->_deleteLinks($id); <add> if ($cascade) { <add> $this->_deleteDependent($id, $cascade); <ide> } <ide> } <add> return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids)); <ide> } <ide> <ide> /** <ide> public function exists($id = null) { <ide> } <ide> $conditions = array($this->alias . '.' . $this->primaryKey => $id); <ide> $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false); <del> return ($this->find('count', $query) > 0); <add> return $this->find('count', $query) > 0; <ide> } <ide> <ide> /** <ide> public function buildQuery($type = 'first', $query = array()) { <ide> (array)$query <ide> ); <ide> <del> if ($type !== 'all') { <del> if ($this->findMethods[$type] === true) { <del> $query = $this->{'_find' . ucfirst($type)}('before', $query); <del> } <add> if ($type !== 'all' && $this->findMethods[$type] === true) { <add> $query = $this->{'_find' . ucfirst($type)}('before', $query); <ide> } <ide> <ide> if (!is_numeric($query['page']) || intval($query['page']) < 1) { <ide> protected function _findCount($state, $query, $results = array()) { <ide> if (isset($results[0][$key]['count'])) { <ide> if ($query['group']) { <ide> return count($results); <del> } else { <del> return intval($results[0][$key]['count']); <ide> } <add> return intval($results[0][$key]['count']); <ide> } <ide> } <ide> return false; <ide> protected function _findList($state, $query, $results = array()) { <ide> if (empty($results)) { <ide> return array(); <ide> } <del> $lst = $query['list']; <del> return Hash::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']); <add> return Hash::combine($results, $query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']); <ide> } <ide> } <ide> <ide> public function isUnique($fields, $or = true) { <ide> unset($fields[$field]); <ide> <ide> $field = $value; <add> $value = null; <ide> if (isset($this->data[$this->alias][$field])) { <ide> $value = $this->data[$this->alias][$field]; <del> } else { <del> $value = null; <ide> } <ide> } <ide> <ide> public function getID($list = 0) { <ide> if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) { <ide> return false; <ide> } <del> <ide> if (!is_array($this->id)) { <ide> return $this->id; <ide> } <del> <ide> if (isset($this->id[$list]) && !empty($this->id[$list])) { <ide> return $this->id[$list]; <del> } elseif (isset($this->id[$list])) { <add> } <add> if (isset($this->id[$list])) { <ide> return false; <ide> } <ide> <ide> public function getAssociated($type = null) { <ide> } <ide> } <ide> return $associated; <del> } elseif (in_array($type, $this->_associations)) { <add> } <add> if (in_array($type, $this->_associations)) { <ide> if (empty($this->{$type})) { <ide> return array(); <ide> } <ide> return array_keys($this->{$type}); <del> } else { <del> $assoc = array_merge( <del> $this->hasOne, <del> $this->hasMany, <del> $this->belongsTo, <del> $this->hasAndBelongsToMany <del> ); <del> if (array_key_exists($type, $assoc)) { <del> foreach ($this->_associations as $a) { <del> if (isset($this->{$a}[$type])) { <del> $assoc[$type]['association'] = $a; <del> break; <del> } <add> } <add> <add> $assoc = array_merge( <add> $this->hasOne, <add> $this->hasMany, <add> $this->belongsTo, <add> $this->hasAndBelongsToMany <add> ); <add> if (array_key_exists($type, $assoc)) { <add> foreach ($this->_associations as $a) { <add> if (isset($this->{$a}[$type])) { <add> $assoc[$type]['association'] = $a; <add> break; <ide> } <del> return $assoc[$type]; <ide> } <del> return null; <add> return $assoc[$type]; <ide> } <add> return null; <ide> } <ide> <ide> /** <ide> public function joinModel($assoc, $keys = array()) { <ide> if (is_string($assoc)) { <ide> list(, $assoc) = pluginSplit($assoc); <ide> return array($assoc, array_keys($this->{$assoc}->schema())); <del> } elseif (is_array($assoc)) { <add> } <add> if (is_array($assoc)) { <ide> $with = key($assoc); <ide> return array($with, array_unique(array_merge($assoc[$with], $keys))); <ide> }
1
Ruby
Ruby
ensure writability, handle errors
a8527f4c16d7df419f6539fd583302635ec98a4a
<ide><path>Library/Homebrew/formula.rb <ide> def time <ide> end <ide> end <ide> <add> # Replaces a universal binary with its native slice. <add> # <add> # If called with no parameters, does this with all compatible <add> # universal binaries in a {Formula}'s {Keg}. <ide> sig { params(targets: T.nilable(T.any(Pathname, String))).void } <ide> def deuniversalize_machos(*targets) <ide> if targets.blank? <ide> def deuniversalize_machos(*targets) <ide> end <ide> end <ide> <del> targets.each do |t| <del> macho = MachO::FatFile.new(t) <add> targets.each { |t| extract_slice_from(Pathname.new(t), Hardware::CPU.arch) } <add> end <add> <add> # @private <add> sig { params(file: Pathname, arch: T.nilable(Symbol)).void } <add> def extract_slice_from(file, arch = Hardware::CPU.arch) <add> odebug "Extracting #{arch} slice from #{file}" <add> file.ensure_writable do <add> macho = MachO::FatFile.new(file) <ide> native_slice = macho.extract(Hardware::CPU.arch) <del> native_slice.write t <add> native_slice.write file <add> rescue MachO::MachOBinaryError <add> onoe "#{file} is not a universal binary" <add> raise <add> rescue NoMethodError <add> onoe "#{file} does not contain an #{arch} slice" <add> raise <ide> end <ide> end <ide>
1
PHP
PHP
fix bug in router parameter parsing
c47a30fca631de586f2862f4f5d10a88aca18f21
<ide><path>laravel/routing/router.php <ide> protected function match($destination, $keys, $callback) <ide> { <ide> foreach (explode(', ', $keys) as $key) <ide> { <del> if (preg_match('#^'.$this->wildcards($key).'$#', $destination)) <add> if (preg_match('#^'.$this->wildcards($key).'$#', $destination, $parameters)) <ide> { <del> return new Route($keys, $callback, $this->parameters($destination, $key)); <add> array_shift($parameters); <add> <add> return new Route($keys, $callback, $parameters); <ide> } <ide> } <ide> } <ide> protected function wildcards($key) <ide> return str_replace(array_keys($this->patterns), array_values($this->patterns), $key); <ide> } <ide> <del> /** <del> * Extract the parameters from a URI based on a route URI. <del> * <del> * Any route segment wrapped in parentheses is considered a parameter. <del> * <del> * @param string $uri <del> * @param string $route <del> * @return array <del> */ <del> protected function parameters($uri, $route) <del> { <del> list($uri, $route) = array(explode('/', $uri), explode('/', $route)); <del> <del> $count = count($route); <del> <del> $parameters = array(); <del> <del> // To find the parameters that should be passed to the route, we will <del> // iterate through the route segments, and if the segment is enclosed <del> // in parentheses, we will take the matching segment from the request <del> // URI and add it to the array of parameters. <del> for ($i = 0; $i < $count; $i++) <del> { <del> if (preg_match('/\(.+\)/', $route[$i]) and isset($uri[$i])) <del> { <del> $parameters[] = $uri[$i]; <del> } <del> } <del> <del> return $parameters; <del> } <del> <ide> } <ide>\ No newline at end of file
1
Text
Text
add xadillax to collaborators
56441ff774baa7f3f2ab25691a753d6f701a2b6c
<ide><path>README.md <ide> more information about the governance of the Node.js project, see <ide> **Daijiro Wachi** &lt;daijiro.wachi@gmail.com&gt; (he/him) <ide> * [whitlockjc](https://github.com/whitlockjc) - <ide> **Jeremy Whitlock** &lt;jwhitlock@apache.org&gt; <add>* [XadillaX](https://github.com/XadillaX) - <add>**Khaidi Chu** &lt;i@2333.moe&gt; (he/him) <ide> * [yorkie](https://github.com/yorkie) - <ide> **Yorkie Liu** &lt;yorkiefixer@gmail.com&gt; <ide> * [yosuke-furukawa](https://github.com/yosuke-furukawa) -
1
Python
Python
allow longs as well as ints to satisfy win64
da3677060f54b6ac39db93728b4e9948adeeae6c
<ide><path>numpy/lib/format.py <ide> def read_array_header_1_0(fp): <ide> <ide> # Sanity-check the values. <ide> if (not isinstance(d['shape'], tuple) or <del> not numpy.all([isinstance(x, int) for x in d['shape']])): <add> not numpy.all([isinstance(x, (int,long)) for x in d['shape']])): <ide> msg = "shape is not valid: %r" <ide> raise ValueError(msg % (d['shape'],)) <ide> if not isinstance(d['fortran_order'], bool):
1
Go
Go
add missing sandboxes routes
72eb02d807bd582fb40e13514c05a6a78544513b
<ide><path>libnetwork/cmd/dnet/dnet.go <ide> func (d *dnetConnection) dnetDaemon() error { <ide> post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler) <ide> post = r.PathPrefix("/services").Subrouter() <ide> post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler) <add> post = r.PathPrefix("/{.*}/sandboxes").Subrouter() <add> post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler) <add> post = r.PathPrefix("/sandboxes").Subrouter() <add> post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler) <ide> return http.ListenAndServe(d.addr, r) <ide> } <ide>
1
Javascript
Javascript
remove references to last arguments to a fn call
e61eae1b1f2351c51bcfe4142749a4e68a2806ff
<ide><path>src/ng/parse.js <ide> Parser.prototype = { <ide> ? fn.apply(context, args) <ide> : fn(args[0], args[1], args[2], args[3], args[4]); <ide> <add> if (args) { <add> // Free-up the memory (arguments of the last function call). <add> args.length = 0; <add> } <add> <ide> return ensureSafeObject(v, expressionText); <ide> }; <ide> },
1
Javascript
Javascript
implement stricter weekday parsing
a8a7abfaa80f13f132827527d2c119249c84aaf6
<ide><path>src/lib/units/day-of-week.js <ide> addRegexToken('dd', matchWord); <ide> addRegexToken('ddd', matchWord); <ide> addRegexToken('dddd', matchWord); <ide> <del>addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config) { <del> var weekday = config._locale.weekdaysParse(input); <add>addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { <add> var weekday = config._locale.weekdaysParse(input, token, config._strict); <ide> // if we didn't get a weekday name, mark the date as invalid <ide> if (weekday != null) { <ide> week.d = weekday; <ide> export function localeWeekdaysMin (m) { <ide> return this._weekdaysMin[m.day()]; <ide> } <ide> <del>export function localeWeekdaysParse (weekdayName) { <add>export function localeWeekdaysParse (weekdayName, format, strict) { <ide> var i, mom, regex; <ide> <del> this._weekdaysParse = this._weekdaysParse || []; <add> if (!this._weekdaysParse) { <add> this._weekdaysParse = []; <add> this._minWeekdaysParse = []; <add> this._shortWeekdaysParse = []; <add> this._fullWeekdaysParse = []; <add> } <ide> <ide> for (i = 0; i < 7; i++) { <ide> // make the regex if we don't have it already <add> <add> mom = createLocal([2000, 1]).day(i); <add> if (strict && !this._fullWeekdaysParse[i]) { <add> this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i'); <add> this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i'); <add> this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i'); <add> } <ide> if (!this._weekdaysParse[i]) { <del> mom = createLocal([2000, 1]).day(i); <ide> regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); <ide> this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); <ide> } <ide> // test the regex <del> if (this._weekdaysParse[i].test(weekdayName)) { <add> if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { <add> return i; <add> } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { <add> return i; <add> } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { <add> return i; <add> } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { <ide> return i; <ide> } <ide> } <ide><path>src/test/locale/en.js <ide> test('lenient ordinal parsing', function (assert) { <ide> } <ide> }); <ide> <add>test('weekdays strict parsing', function (assert) { <add> var m = moment('2015-01-01T12', moment.ISO_8601, true), <add> enLocale = moment.localeData('en'); <add> <add> for (var i = 0; i < 7; ++i) { <add> assert.equal(moment(enLocale.weekdays(m.day(i), ''), 'dddd', true).isValid(), true, 'parse weekday ' + i); <add> assert.equal(moment(enLocale.weekdaysShort(m.day(i), ''), 'ddd', true).isValid(), true, 'parse short weekday ' + i); <add> assert.equal(moment(enLocale.weekdaysMin(m.day(i), ''), 'dd', true).isValid(), true, 'parse min weekday ' + i); <add> <add> // negative tests <add> assert.equal(moment(enLocale.weekdaysMin(m.day(i), ''), 'ddd', true).isValid(), false, 'parse short weekday ' + i); <add> assert.equal(moment(enLocale.weekdaysShort(m.day(i), ''), 'dd', true).isValid(), false, 'parse min weekday ' + i); <add> } <add>}); <add> <ide> test('lenient ordinal parsing of number', function (assert) { <ide> var i, testMoment; <ide> for (i = 1; i <= 31; ++i) {
2
Python
Python
deprecate request.json property
61097c47a35ad8883c77fc49b93c1314f7819464
<ide><path>flask/wrappers.py <ide> def json(self): <ide> <ide> The :meth:`get_json` method should be used instead. <ide> """ <del> # XXX: deprecate property <add> from warnings import warn <add> warn(DeprecationWarning('json is deprecated. ' <add> 'Use get_json() instead.'), stacklevel=2) <ide> return self.get_json() <ide> <ide> @property
1