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 | apply suggestions from code review | 4652906c9a88661c498b7c032ce6f672e985a9e4 | <ide><path>src/Http/Client/Auth/Oauth.php
<ide> protected function _normalizedParams(Request $request, array $oauthValues): stri
<ide> $post = [];
<ide> $contentType = $request->getHeaderLine('Content-Type');
<ide> if ($contentType === '' || $contentType === 'application/x-www-form-urlencoded') {
<del> $body = (string)$request->getBody();
<del> parse_str($body, $post);
<add> parse_str((string)$request->getBody(), $post);
<ide> }
<ide> $args = array_merge($queryArgs, $oauthValues, $post);
<ide> $pairs = $this->_normalizeData($args); | 1 |
Text | Text | add docs for `run|create --init|--init-path` | d049ef2b0db4aebfba4f85f5d8294e9884a4b7e2 | <ide><path>docs/reference/commandline/create.md
<ide> Options:
<ide> --health-timeout duration Maximum time to allow one check to run (ns|us|ms|s|m|h) (default 0s)
<ide> --help Print usage
<ide> -h, --hostname string Container host name
<add> --init Run an init inside the container that forwards signals and reaps processes
<add> --init-path string Path to the docker-init binary
<ide> -i, --interactive Keep STDIN open even if not attached
<ide> --io-maxbandwidth string Maximum IO bandwidth limit for the system drive (Windows only)
<ide> --io-maxiops uint Maximum IOps limit for the system drive (Windows only)
<ide><path>docs/reference/commandline/run.md
<ide> Options:
<ide> --health-timeout duration Maximum time to allow one check to run (ns|us|ms|s|m|h) (default 0s)
<ide> --help Print usage
<ide> -h, --hostname string Container host name
<add> --init Run an init inside the container that forwards signals and reaps processes
<add> --init-path string Path to the docker-init binary
<ide> -i, --interactive Keep STDIN open even if not attached
<ide> --io-maxbandwidth string Maximum IO bandwidth limit for the system drive (Windows only)
<ide> (Windows only). The format is `<number><unit>`.
<ide><path>man/docker-run.1.md
<ide> docker-run - Run a command in a new container
<ide> [**--group-add**[=*[]*]]
<ide> [**-h**|**--hostname**[=*HOSTNAME*]]
<ide> [**--help**]
<add>[**--init**]
<add>[**--init-path**[=*[]*]]
<ide> [**-i**|**--interactive**]
<ide> [**--ip**[=*IPv4-ADDRESS*]]
<ide> [**--ip6**[=*IPv6-ADDRESS*]]
<ide> redirection on the host system.
<ide> Sets the container host name that is available inside the container.
<ide>
<ide> **--help**
<del> Print usage statement
<add> Print usage statement
<add>
<add>**--init**
<add> Run an init inside the container that forwards signals and reaps processes
<add>
<add>**--init-path**=""
<add> Path to the docker-init binary
<ide>
<ide> **-i**, **--interactive**=*true*|*false*
<ide> Keep STDIN open even if not attached. The default is *false*. | 3 |
Python | Python | fix 1.3 compat issue. closes #780 | 3f91379e4eaf07418a99fda1932af91511c55e7b | <ide><path>rest_framework/compat.py
<ide> def parse_datetime(value):
<ide> try:
<ide> from django.utils.html import smart_urlquote
<ide> except ImportError:
<add> import re
<add> from django.utils.encoding import smart_str
<ide> try:
<ide> from urllib.parse import quote, urlsplit, urlunsplit
<ide> except ImportError: # Python 2
<ide> from urllib import quote
<ide> from urlparse import urlsplit, urlunsplit
<ide>
<add> unquoted_percents_re = re.compile(r'%(?![0-9A-Fa-f]{2})')
<add>
<ide> def smart_urlquote(url):
<ide> "Quotes a URL if it isn't already quoted."
<ide> # Handle IDN before quoting.
<ide> scheme, netloc, path, query, fragment = urlsplit(url)
<ide> try:
<del> netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
<del> except UnicodeError: # invalid domain part
<add> netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
<add> except UnicodeError: # invalid domain part
<ide> pass
<ide> else:
<ide> url = urlunsplit((scheme, netloc, path, query, fragment))
<ide> def smart_urlquote(url):
<ide> # contains a % not followed by two hexadecimal digits. See #9655.
<ide> if '%' not in url or unquoted_percents_re.search(url):
<ide> # See http://bugs.python.org/issue2637
<del> url = quote(force_bytes(url), safe=b'!*\'();:@&=+$,/?#[]~')
<add> url = quote(smart_str(url), safe=b'!*\'();:@&=+$,/?#[]~')
<ide>
<ide> return force_text(url)
<ide> | 1 |
Text | Text | fix typos in the user guide main page | 2d2b3535cae11d02573d12297d34e9a98a3e984a | <ide><path>docs/sources/userguide/index.md
<ide> using Docker and integrating it into your environment.
<ide>
<ide> We’ll teach you how to use Docker to:
<ide>
<del>* Dockerizing your applications.
<add>* Dockerize your applications.
<ide> * Run your own containers.
<ide> * Build Docker images.
<ide> * Share your Docker images with others.
<ide> the Docker life cycle:
<ide>
<ide> Docker Hub is the central hub for Docker. It hosts public Docker images
<ide> and provides services to help you build and manage your Docker
<del>environment. To learn more;
<add>environment. To learn more:
<ide>
<ide> Go to [Using Docker Hub](/userguide/dockerhub).
<ide>
<ide> Go to [Using Docker Hub](/userguide/dockerhub).
<ide> *How do I run applications inside containers?*
<ide>
<ide> Docker offers a *container-based* virtualization platform to power your
<del>applications. To learn how to Dockerize applications and run them.
<add>applications. To learn how to Dockerize applications and run them:
<ide>
<ide> Go to [Dockerizing Applications](/userguide/dockerizing).
<ide>
<ide> Go to [Working With Containers](/userguide/usingdocker).
<ide> Once you've learnt how to use Docker it's time to take the next step and
<ide> learn how to build your own application images with Docker.
<ide>
<del>Go to [Working with Docker Images](/userguide/dockerimages)
<add>Go to [Working with Docker Images](/userguide/dockerimages).
<ide>
<ide> ## Linking Containers Together
<ide> | 1 |
PHP | PHP | fix phpcs and psalm errors | 49ca31fce4ffa4d21ebb18aeaeaefbdb8d827467 | <ide><path>src/Http/ActionDispatcher.php
<ide> */
<ide> namespace Cake\Http;
<ide>
<del>use Cake\Http\ControllerInterface;
<ide> use Cake\Routing\Router;
<ide> use Psr\Http\Message\ResponseInterface;
<ide>
<ide><path>src/Http/ControllerFactory.php
<ide> namespace Cake\Http;
<ide>
<ide> use Cake\Core\App;
<del>use Cake\Http\ControllerInterface;
<ide> use Cake\Http\Exception\MissingControllerException;
<ide> use Cake\Utility\Inflector;
<ide> use ReflectionClass;
<ide> public function getControllerClass(ServerRequest $request): ?string
<ide> * Throws an exception when a controller is missing.
<ide> *
<ide> * @param \Cake\Http\ServerRequest $request The request.
<del> * @throws \Cake\Routing\Exception\MissingControllerException
<add> * @throws \Cake\Http\Exception\MissingControllerException
<ide> * @return void
<ide> */
<ide> protected function missingController(ServerRequest $request): void
<ide><path>src/Http/ControllerInterface.php
<ide> public function isAutoRenderEnabled(): bool;
<ide> * @return \Cake\Http\Response
<ide> */
<ide> public function getResponse(): Response;
<add>
<add> /**
<add> * Renders a response generally using a View.
<add> *
<add> * @param string|null $template Template to use for rendering
<add> * @param string|null $layout Layout to use
<add> * @return \Cake\Http\Response A response object containing the rendered view.
<add> */
<add> public function render(?string $template = null, ?string $layout = null): Response;
<ide> }
<ide><path>src/Http/Middleware/CsrfProtectionMiddleware.php
<ide> namespace Cake\Http\Middleware;
<ide>
<ide> use ArrayAccess;
<del>use DateTimeImmutable;
<ide> use Cake\Http\Cookie\Cookie;
<ide> use Cake\Http\Exception\InvalidCsrfTokenException;
<ide> use Cake\Http\Response;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Security;
<add>use DateTimeImmutable;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide> use Psr\Http\Server\MiddlewareInterface;
<ide><path>src/Http/ResponseEmitter.php
<ide> */
<ide> namespace Cake\Http;
<ide>
<del>use Cake\Core\Configure;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> use Zend\Diactoros\RelativeStream;
<ide> use Zend\HttpHandlerRunner\Emitter\EmitterInterface;
<ide><path>src/Routing/Exception/MissingControllerException.php
<ide> <?php
<add>declare(strict_types=1);
<add>
<ide> class_exists('Cake\Http\Exception\MissingControllerException');
<del>deprecationWarning('Use Cake\Http\Exception\MissingControllerException instead of Cake\Routing\Exception\MissingControllerException.');
<add>deprecationWarning(
<add> 'Use Cake\Http\Exception\MissingControllerException instead of Cake\Routing\Exception\MissingControllerException.'
<add>);
<ide><path>tests/TestCase/Error/ErrorHandlerTest.php
<ide> use Cake\Datasource\Exception\RecordNotFoundException;
<ide> use Cake\Error\ErrorHandler;
<ide> use Cake\Http\Exception\ForbiddenException;
<del>use Cake\Http\Exception\NotFoundException;
<ide> use Cake\Http\Exception\MissingControllerException;
<add>use Cake\Http\Exception\NotFoundException;
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\Log\Log;
<ide> use Cake\Routing\Router;
<ide><path>tests/TestCase/Http/ControllerFactoryTest.php
<ide> namespace Cake\Test\TestCase\Http;
<ide>
<ide> use Cake\Http\ControllerFactory;
<del>use Cake\Http\ServerRequest;
<ide> use Cake\Http\Exception\MissingControllerException;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide><path>tests/TestCase/Http/Middleware/CsrfProtectionMiddlewareTest.php
<ide> use Cake\Http\Middleware\CsrfProtectionMiddleware;
<ide> use Cake\Http\Response;
<ide> use Cake\Http\ServerRequest;
<del>use Cake\I18n\Time;
<ide> use Cake\TestSuite\TestCase;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide> use TestApp\Http\TestRequestHandler; | 9 |
Text | Text | fix common typo involving one-time listeners | de06dc92d150c1f999462a18c7594a5eea81225f | <ide><path>doc/api/events.md
<ide> added: v0.3.0
<ide> * `eventName` {any} The name of the event.
<ide> * `listener` {Function} The callback function
<ide>
<del>Adds a **one time** `listener` function for the event named `eventName`. The
<add>Adds a **one-time** `listener` function for the event named `eventName`. The
<ide> next time `eventName` is triggered, this listener is removed and then invoked.
<ide>
<ide> ```js
<ide> added: v6.0.0
<ide> * `eventName` {any} The name of the event.
<ide> * `listener` {Function} The callback function
<ide>
<del>Adds a **one time** `listener` function for the event named `eventName` to the
<add>Adds a **one-time** `listener` function for the event named `eventName` to the
<ide> *beginning* of the listeners array. The next time `eventName` is triggered, this
<ide> listener is removed, and then invoked.
<ide>
<ide><path>doc/api/http.md
<ide> This function allows one to transparently issue requests.
<ide> string, it is automatically parsed with [`url.parse()`][]. If it is a [`URL`][]
<ide> object, it will be automatically converted to an ordinary `options` object.
<ide>
<del>The optional `callback` parameter will be added as a one time listener for
<add>The optional `callback` parameter will be added as a one-time listener for
<ide> the [`'response'`][] event.
<ide>
<ide> `http.request()` returns an instance of the [`http.ClientRequest`][]
<ide><path>doc/api/net.md
<ide> socket.on('timeout', () => {
<ide>
<ide> If `timeout` is 0, then the existing idle timeout is disabled.
<ide>
<del>The optional `callback` parameter will be added as a one time listener for the
<add>The optional `callback` parameter will be added as a one-time listener for the
<ide> [`'timeout'`][] event.
<ide>
<ide> ### socket.unref() | 3 |
Python | Python | add test for empty string as control characters | 8a31abccb1928d3ca1e669e105020f3a21dfb1a8 | <ide><path>numpy/lib/npyio.py
<ide> def _read(fname, *, delimiter=',', comment='#', quote='"',
<ide> comments = None
<ide> else:
<ide> # assume comments are a sequence of strings
<add> if "" in comment:
<add> raise ValueError(
<add> "comments cannot be an empty string. Use comments=None to "
<add> "disable comments."
<add> )
<ide> comments = tuple(comment)
<ide> comment = None
<ide> if len(comments) == 0:
<ide><path>numpy/lib/tests/test_loadtxt.py
<ide> def test_datetime_parametric_unit_discovery(
<ide> a = np.loadtxt(fname, dtype=unitless_dtype)
<ide> assert a.dtype == expected.dtype
<ide> assert_equal(a, expected)
<add>
<add>
<add>def test_control_character_empty():
<add> with pytest.raises(TypeError, match="Text reading control character must"):
<add> np.loadtxt(StringIO("1 2 3"), delimiter="")
<add> with pytest.raises(TypeError, match="Text reading control character must"):
<add> np.loadtxt(StringIO("1 2 3"), quotechar="")
<add> with pytest.raises(ValueError, match="comments cannot be an empty string"):
<add> np.loadtxt(StringIO("1 2 3"), comments="")
<add> with pytest.raises(ValueError, match="comments cannot be an empty string"):
<add> np.loadtxt(StringIO("1 2 3"), comments=["#", ""]) | 2 |
Javascript | Javascript | remove memory cache from filecacheplugin | 77c2e61a31b184bc27cde644feee82520729a2a4 | <ide><path>lib/Cache.js
<ide>
<ide> const { AsyncParallelHook, AsyncSeriesBailHook, SyncHook } = require("tapable");
<ide>
<add>/** @typedef {(result: any, callback: (err?: Error) => void) => void} GotHandler */
<add>
<ide> class Cache {
<ide> constructor() {
<ide> this.hooks = {
<ide> /** @type {AsyncSeriesBailHook<string, string>} */
<ide> get: new AsyncSeriesBailHook(["identifier", "etag"]),
<ide> /** @type {AsyncParallelHook<string, string, any>} */
<add> got: new AsyncParallelHook(["identifier", "etag", "data"]),
<add> /** @type {AsyncParallelHook<string, string, any>} */
<ide> store: new AsyncParallelHook(["identifier", "etag", "data"]),
<ide> /** @type {SyncHook} */
<ide> beginIdle: new SyncHook([]),
<ide> class Cache {
<ide> }
<ide>
<ide> get(identifier, etag, callback) {
<del> this.hooks.get.callAsync(identifier, etag, callback);
<add> this.hooks.get.callAsync(identifier, etag, (err, result) => {
<add> if (err) {
<add> callback(err);
<add> return;
<add> }
<add> this.hooks.got.callAsync(identifier, etag, result, err => {
<add> if (err) {
<add> callback(err);
<add> return;
<add> }
<add> callback(null, result);
<add> });
<add> });
<ide> }
<ide>
<ide> store(identifier, etag, data, callback) {
<ide><path>lib/WebpackOptionsApply.js
<ide> class WebpackOptionsApply extends OptionsApply {
<ide> break;
<ide> }
<ide> case "filesystem": {
<add> const MemoryCachePlugin = require("./cache/MemoryCachePlugin");
<add> new MemoryCachePlugin().apply(compiler);
<ide> const FileCachePlugin = require("./cache/FileCachePlugin");
<ide> new FileCachePlugin(options.cache).apply(compiler);
<ide> break;
<ide><path>lib/cache/FileCachePlugin.js
<ide> class FileCachePlugin {
<ide> */
<ide> constructor(options) {
<ide> this.options = options;
<del> this.memoryCache = new Map();
<del> }
<del>
<del> purgeMemoryCache() {
<del> this.memoryCache.clear();
<add> this.missingEntries = new Set();
<ide> }
<ide>
<ide> /**
<ide> class FileCachePlugin {
<ide> : 0;
<ide> const store = this.options.store || "pack";
<ide>
<add> const resolvedPromise = Promise.resolve();
<add>
<ide> let pendingPromiseFactories = new Map();
<ide> const toHash = str => {
<ide> const hash = createHash(hashAlgorithm);
<ide> class FileCachePlugin {
<ide> return new Pack(version);
<ide> });
<ide> }
<del> compiler.cache.hooks.store.tapPromise(
<del> "FileCachePlugin",
<del> (identifier, etag, data) => {
<del> const entry = {
<del> identifier,
<del> data: etag ? () => data : data,
<del> etag,
<del> version
<del> };
<del> this.memoryCache.set(identifier, entry);
<del> const promiseFactory =
<del> store === "pack"
<del> ? () =>
<del> packPromise.then(pack => {
<add> const storeEntry = (identifier, etag, data) => {
<add> this.missingEntries.delete(identifier);
<add> const entry = {
<add> identifier,
<add> data: etag ? () => data : data,
<add> etag,
<add> version
<add> };
<add> const promiseFactory =
<add> store === "pack"
<add> ? () =>
<add> packPromise.then(pack => {
<add> if (log >= 2) {
<add> console.warn(`Cached ${identifier} to pack.`);
<add> }
<add> pack.set(identifier, entry);
<add> })
<add> : () => {
<add> const relativeFilename = toHash(identifier) + ".data";
<add> const filename = path.join(cacheDirectory, relativeFilename);
<add> return serializer
<add> .serializeToFile(entry, filename)
<add> .then(() => {
<ide> if (log >= 2) {
<del> console.warn(`Cached ${identifier} to pack.`);
<add> console.warn(`Cached ${identifier} to ${filename}.`);
<ide> }
<del> pack.set(identifier, entry);
<ide> })
<del> : () => {
<del> const relativeFilename = toHash(identifier) + ".data";
<del> const filename = path.join(cacheDirectory, relativeFilename);
<del> return serializer
<del> .serializeToFile(entry, filename)
<del> .then(() => {
<del> if (log >= 2) {
<del> console.warn(`Cached ${identifier} to ${filename}.`);
<del> }
<del> })
<del> .catch(err => {
<del> if (log >= 1) {
<del> console.warn(
<del> `Caching failed for ${identifier}: ${
<del> log >= 3 ? err.stack : err
<del> }`
<del> );
<del> }
<del> });
<del> };
<del> if (store === "instant") {
<del> return promiseFactory();
<del> } else if (store === "idle" || store === "pack") {
<del> pendingPromiseFactories.set(identifier, promiseFactory);
<del> return Promise.resolve();
<del> } else if (store === "background") {
<del> const promise = promiseFactory();
<del> pendingPromiseFactories.set(identifier, () => promise);
<del> return Promise.resolve();
<add> .catch(err => {
<add> if (log >= 1) {
<add> console.warn(
<add> `Caching failed for ${identifier}: ${
<add> log >= 3 ? err.stack : err
<add> }`
<add> );
<add> }
<add> });
<add> };
<add> if (store === "instant") {
<add> return promiseFactory();
<add> } else if (store === "idle" || store === "pack") {
<add> pendingPromiseFactories.set(identifier, promiseFactory);
<add> return resolvedPromise;
<add> } else if (store === "background") {
<add> const promise = promiseFactory();
<add> pendingPromiseFactories.set(identifier, () => promise);
<add> return resolvedPromise;
<add> }
<add> };
<add> compiler.cache.hooks.store.tapPromise("FileCachePlugin", storeEntry);
<add> compiler.cache.hooks.got.tapPromise(
<add> "FileCachePlugin",
<add> (identifier, etag, result) => {
<add> if (result !== undefined && this.missingEntries.has(identifier)) {
<add> return storeEntry(identifier, etag, result);
<add> } else {
<add> return resolvedPromise;
<ide> }
<ide> }
<ide> );
<add>
<ide> compiler.cache.hooks.get.tapPromise(
<ide> "FileCachePlugin",
<ide> (identifier, etag) => {
<del> const directMemory = this.memoryCache.get(identifier);
<del> if (directMemory !== undefined) {
<del> return Promise.resolve(
<del> directMemory.etag !== etag
<del> ? undefined
<del> : typeof directMemory.data === "function"
<del> ? directMemory.data()
<del> : directMemory.data
<del> );
<del> }
<ide> let logMessage;
<ide> let cacheEntryPromise;
<ide> if (store === "pack") {
<ide> class FileCachePlugin {
<ide> }
<ide> return cacheEntryPromise.then(
<ide> cacheEntry => {
<del> if (cacheEntry === undefined) return;
<del> this.memoryCache.set(identifier, cacheEntry);
<add> if (cacheEntry === undefined) {
<add> this.missingEntries.add(identifier);
<add> return;
<add> }
<ide> if (cacheEntry.identifier !== identifier) {
<ide> if (log >= 3) {
<ide> console.warn(
<ide> `Restored ${identifier} from ${logMessage}, but identifier doesn't match.`
<ide> );
<ide> }
<add> this.missingEntries.add(identifier);
<ide> return;
<ide> }
<ide> if (cacheEntry.etag !== etag) {
<ide> class FileCachePlugin {
<ide> `Restored ${identifier} from ${logMessage}, but etag doesn't match.`
<ide> );
<ide> }
<add> this.missingEntries.add(identifier);
<ide> return;
<ide> }
<ide> if (cacheEntry.version !== version) {
<ide> class FileCachePlugin {
<ide> `Restored ${identifier} from ${logMessage}, but version doesn't match.`
<ide> );
<ide> }
<add> this.missingEntries.add(identifier);
<ide> return;
<ide> }
<ide> if (log >= 3) {
<ide> class FileCachePlugin {
<ide> return cacheEntry.data;
<ide> },
<ide> err => {
<add> this.missingEntries.add(identifier);
<ide> if (log >= 1 && err && err.code !== "ENOENT") {
<ide> console.warn(
<ide> `Restoring failed for ${identifier} from ${logMessage}: ${
<ide> class FileCachePlugin {
<ide> };
<ide> compiler.cache.hooks.beginIdle.tap("FileCachePlugin", () => {
<ide> isIdle = true;
<del> Promise.resolve().then(processIdleTasks);
<add> resolvedPromise.then(processIdleTasks);
<ide> });
<ide> compiler.cache.hooks.endIdle.tap("FileCachePlugin", () => {
<ide> isIdle = false;
<ide><path>lib/cache/MemoryCachePlugin.js
<ide> class MemoryCachePlugin {
<ide> cache.set(identifier, { etag, data });
<ide> }
<ide> );
<add> compiler.cache.hooks.got.tap(
<add> "MemoryCachePlugin",
<add> (identifier, etag, result) => {
<add> if (result !== undefined) {
<add> cache.set(identifier, { etag, data: result });
<add> }
<add> }
<add> );
<ide> compiler.cache.hooks.get.tap("MemoryCachePlugin", (identifier, etag) => {
<ide> const cacheEntry = cache.get(identifier);
<ide> if (cacheEntry !== undefined && cacheEntry.etag === etag) { | 4 |
Javascript | Javascript | update buffergeometry tets | 61a49191a8e3872fc6f5911301e5ae05f39e759f | <ide><path>test/unit/src/core/BufferGeometry.tests.js
<ide> export default QUnit.module( 'Core', () => {
<ide>
<ide> var index = new BufferAttribute( new Uint16Array( [ 0, 1, 2, 3 ] ), 1 );
<ide> var attribute1 = new BufferAttribute( new Uint16Array( [ 1, 3, 5, 7 ] ), 1 );
<add> attribute1.name = "attribute1";
<ide> var a = new BufferGeometry();
<ide> a.name = "JSONQUnit.test";
<ide> // a.parameters = { "placeholder": 0 };
<ide> export default QUnit.module( 'Core', () => {
<ide> a.addGroup( 0, 1, 2 );
<ide> a.boundingSphere = new Sphere( new Vector3( x, y, z ), 0.5 );
<ide> var j = a.toJSON();
<del>
<ide> var gold = {
<ide> "metadata": {
<ide> "version": 4.5,
<ide> export default QUnit.module( 'Core', () => {
<ide> "itemSize": 1,
<ide> "type": "Uint16Array",
<ide> "array": [ 1, 3, 5, 7 ],
<del> "normalized": false
<add> "normalized": false,
<add> "name": "attribute1"
<ide> }
<ide> },
<ide> "index": {
<ide> export default QUnit.module( 'Core', () => {
<ide>
<ide> assert.deepEqual( j, gold, "Generated JSON is as expected" );
<ide>
<add> // add morphAttributes
<add> a.morphAttributes.attribute1 = [];
<add> a.morphAttributes.attribute1.push( attribute1.clone() );
<add> j = a.toJSON();
<add> gold.data.morphAttributes = {
<add> "attribute1": [ {
<add> "itemSize": 1,
<add> "type": "Uint16Array",
<add> "array": [ 1, 3, 5, 7 ],
<add> "normalized": false,
<add> "name": "attribute1"
<add> } ]
<add> };
<add>
<add> assert.deepEqual( j, gold, "Generated JSON with morphAttributes is as expected" );
<add>
<ide> } );
<ide>
<ide> QUnit.test( "clone", ( assert ) => { | 1 |
Javascript | Javascript | fix typos in ngoptions | 45ee8844f9678bad46e0f81eda18db888a42e264 | <ide><path>src/ng/directive/select.js
<ide> * Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>`
<ide> * elements for a `<select>` element using an array or an object obtained by evaluating the
<ide> * `ngOptions` expression.
<del> *˝˝
<del> * When an item in the select menu is select, the value of array element or object property
<add> *
<add> * When an item in the `<select>` menu is selected, the value of array element or object property
<ide> * represented by the selected option will be bound to the model identified by the `ngModel`
<ide> * directive of the parent select element.
<ide> * | 1 |
Python | Python | add remaining tests for metadata | d0eb2e6cae499a16b54df3fadac0050ce25c32a0 | <ide><path>tests/test_metadata.py
<ide> from __future__ import unicode_literals
<ide>
<add>import pytest
<ide> from django.core.validators import MaxValueValidator, MinValueValidator
<ide> from django.db import models
<ide> from django.test import TestCase
<ide>
<ide>
<ide> class TestMetadata:
<add>
<add> def test_determine_metadata_abstract_method_raises_proper_error(self):
<add> with pytest.raises(NotImplementedError):
<add> metadata.BaseMetadata().determine_metadata(None, None)
<add>
<ide> def test_metadata(self):
<ide> """
<ide> OPTIONS requests to views should return a valid 200 response.
<ide> def get_serializer(self):
<ide> view = ExampleView.as_view(versioning_class=scheme)
<ide> view(request=request)
<ide>
<add> def test_list_serializer_metadata_returns_info_about_fields_of_child_serializer(self):
<add> class ExampleSerializer(serializers.Serializer):
<add> integer_field = serializers.IntegerField(max_value=10)
<add> char_field = serializers.CharField(required=False)
<add>
<add> class ExampleListSerializer(serializers.ListSerializer):
<add> pass
<add>
<add> options = metadata.SimpleMetadata()
<add> child_serializer = ExampleSerializer()
<add> list_serializer = ExampleListSerializer(child=child_serializer)
<add> assert options.get_serializer_info(list_serializer) == options.get_serializer_info(child_serializer)
<add>
<ide>
<ide> class TestSimpleMetadataFieldInfo(TestCase):
<ide> def test_null_boolean_field_info_type(self): | 1 |
Javascript | Javascript | set httpparser trigger to socket | 8479606a24ca12212b75e0febf92925b71ef8d50 | <ide><path>lib/_http_server.js
<ide> const {
<ide> } = require('_http_common');
<ide> const { OutgoingMessage } = require('_http_outgoing');
<ide> const { outHeadersKey, ondrain } = require('internal/http');
<add>const {
<add> defaultTriggerAsyncIdScope,
<add> getOrSetAsyncId
<add>} = require('internal/async_hooks');
<ide> const errors = require('internal/errors');
<ide> const Buffer = require('buffer').Buffer;
<ide>
<ide> Server.prototype.setTimeout = function setTimeout(msecs, callback) {
<ide>
<ide>
<ide> function connectionListener(socket) {
<add> defaultTriggerAsyncIdScope(
<add> getOrSetAsyncId(socket), connectionListenerInternal, this, socket
<add> );
<add>}
<add>
<add>function connectionListenerInternal(server, socket) {
<ide> debug('SERVER new http connection');
<ide>
<ide> httpSocketSetup(socket);
<ide>
<ide> // Ensure that the server property of the socket is correctly set.
<ide> // See https://github.com/nodejs/node/issues/13435
<ide> if (socket.server === null)
<del> socket.server = this;
<add> socket.server = server;
<ide>
<ide> // If the user has added a listener to the server,
<ide> // request, or response, then it's their responsibility.
<ide> // otherwise, destroy on timeout by default
<del> if (this.timeout && typeof socket.setTimeout === 'function')
<del> socket.setTimeout(this.timeout);
<add> if (server.timeout && typeof socket.setTimeout === 'function')
<add> socket.setTimeout(server.timeout);
<ide> socket.on('timeout', socketOnTimeout);
<ide>
<ide> var parser = parsers.alloc();
<ide> function connectionListener(socket) {
<ide> parser.incoming = null;
<ide>
<ide> // Propagate headers limit from server instance to parser
<del> if (typeof this.maxHeadersCount === 'number') {
<del> parser.maxHeaderPairs = this.maxHeadersCount << 1;
<add> if (typeof server.maxHeadersCount === 'number') {
<add> parser.maxHeaderPairs = server.maxHeadersCount << 1;
<ide> } else {
<ide> // Set default value because parser may be reused from FreeList
<ide> parser.maxHeaderPairs = 2000;
<ide> function connectionListener(socket) {
<ide> outgoingData: 0,
<ide> keepAliveTimeoutSet: false
<ide> };
<del> state.onData = socketOnData.bind(undefined, this, socket, parser, state);
<del> state.onEnd = socketOnEnd.bind(undefined, this, socket, parser, state);
<add> state.onData = socketOnData.bind(undefined, server, socket, parser, state);
<add> state.onEnd = socketOnEnd.bind(undefined, server, socket, parser, state);
<ide> state.onClose = socketOnClose.bind(undefined, socket, state);
<ide> state.onDrain = socketOnDrain.bind(undefined, socket, state);
<ide> socket.on('data', state.onData);
<ide> socket.on('error', socketOnError);
<ide> socket.on('end', state.onEnd);
<ide> socket.on('close', state.onClose);
<ide> socket.on('drain', state.onDrain);
<del> parser.onIncoming = parserOnIncoming.bind(undefined, this, socket, state);
<add> parser.onIncoming = parserOnIncoming.bind(undefined, server, socket, state);
<ide>
<ide> // We are consuming socket, so it won't get any actual data
<ide> socket.on('resume', onSocketResume);
<ide> function connectionListener(socket) {
<ide> }
<ide> }
<ide> parser[kOnExecute] =
<del> onParserExecute.bind(undefined, this, socket, parser, state);
<add> onParserExecute.bind(undefined, server, socket, parser, state);
<ide>
<ide> socket._paused = false;
<ide> }
<ide><path>lib/internal/async_hooks.js
<ide> const async_wrap = process.binding('async_wrap');
<ide> * It has a fixed size, so if that is exceeded, calls to the native
<ide> * side are used instead in pushAsyncIds() and popAsyncIds().
<ide> */
<del>const { async_hook_fields, async_id_fields } = async_wrap;
<add>const { async_id_symbol, async_hook_fields, async_id_fields } = async_wrap;
<ide> // Store the pair executionAsyncId and triggerAsyncId in a std::stack on
<ide> // Environment::AsyncHooks::ids_stack_ tracks the resource responsible for the
<ide> // current execution stack. This is unwound as each resource exits. In the case
<ide> function newUid() {
<ide> return ++async_id_fields[kAsyncIdCounter];
<ide> }
<ide>
<add>function getOrSetAsyncId(object) {
<add> if (object.hasOwnProperty(async_id_symbol)) {
<add> return object[async_id_symbol];
<add> }
<add>
<add> return object[async_id_symbol] = newUid();
<add>}
<add>
<add>
<ide> // Return the triggerAsyncId meant for the constructor calling it. It's up to
<ide> // the user to safeguard this call and make sure it's zero'd out when the
<ide> // constructor is complete.
<ide> module.exports = {
<ide> disableHooks,
<ide> // Internal Embedder API
<ide> newUid,
<add> getOrSetAsyncId,
<ide> getDefaultTriggerAsyncId,
<ide> defaultTriggerAsyncIdScope,
<ide> emitInit: emitInitScript,
<ide><path>test/async-hooks/test-graph.http.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const initHooks = require('./init-hooks');
<add>const verifyGraph = require('./verify-graph');
<add>const http = require('http');
<add>
<add>const hooks = initHooks();
<add>hooks.enable();
<add>
<add>const server = http.createServer(common.mustCall(function(req, res) {
<add> res.end();
<add> this.close(common.mustCall());
<add>}));
<add>server.listen(0, common.mustCall(function() {
<add> http.get(`http://127.0.0.1:${server.address().port}`, common.mustCall());
<add>}));
<add>
<add>process.on('exit', function() {
<add> hooks.disable();
<add>
<add> verifyGraph(
<add> hooks,
<add> [ { type: 'TCPSERVERWRAP',
<add> id: 'tcpserver:1',
<add> triggerAsyncId: null },
<add> { type: 'TCPWRAP', id: 'tcp:1', triggerAsyncId: 'tcpserver:1' },
<add> { type: 'TCPCONNECTWRAP',
<add> id: 'tcpconnect:1',
<add> triggerAsyncId: 'tcp:1' },
<add> { type: 'HTTPPARSER',
<add> id: 'httpparser:1',
<add> triggerAsyncId: 'tcpserver:1' },
<add> { type: 'HTTPPARSER',
<add> id: 'httpparser:2',
<add> triggerAsyncId: 'tcpserver:1' },
<add> { type: 'TCPWRAP', id: 'tcp:2', triggerAsyncId: 'tcpserver:1' },
<add> { type: 'Timeout', id: 'timeout:1', triggerAsyncId: 'tcp:2' },
<add> { type: 'TIMERWRAP', id: 'timer:1', triggerAsyncId: 'tcp:2' },
<add> { type: 'HTTPPARSER',
<add> id: 'httpparser:3',
<add> triggerAsyncId: 'tcp:2' },
<add> { type: 'HTTPPARSER',
<add> id: 'httpparser:4',
<add> triggerAsyncId: 'tcp:2' },
<add> { type: 'Timeout',
<add> id: 'timeout:2',
<add> triggerAsyncId: 'httpparser:4' },
<add> { type: 'TIMERWRAP',
<add> id: 'timer:2',
<add> triggerAsyncId: 'httpparser:4' },
<add> { type: 'SHUTDOWNWRAP',
<add> id: 'shutdown:1',
<add> triggerAsyncId: 'tcp:2' } ]
<add> );
<add>}); | 3 |
Ruby | Ruby | fix broken sentence [ci skip] | 6807114bb5aa4abf61a5033955d43b7488a71606 | <ide><path>activerecord/lib/active_record/associations/association.rb
<ide> def set_inverse_instance(record)
<ide> end
<ide> end
<ide>
<del> # This class of the target. belongs_to polymorphic overrides this to look at the
<add> # Returns the class of the target. belongs_to polymorphic overrides this to look at the
<ide> # polymorphic_type field on the owner.
<ide> def klass
<ide> reflection.klass | 1 |
Javascript | Javascript | increase coverage of vm | c7205ba94197ab98e90e4b867c8a149d434a15c3 | <ide><path>test/parallel/test-vm-sigint-existing-handler.js
<ide> const vm = require('vm');
<ide>
<ide> const spawn = require('child_process').spawn;
<ide>
<add>const methods = [
<add> 'runInThisContext',
<add> 'runInContext'
<add>];
<add>
<ide> if (common.isWindows) {
<ide> // No way to send CTRL_C_EVENT to processes from JS right now.
<ide> common.skip('platform not supported');
<ide> return;
<ide> }
<ide>
<ide> if (process.argv[2] === 'child') {
<del> const parent = +process.env.REPL_TEST_PPID;
<del> assert.ok(parent);
<add> const method = process.argv[3];
<add> assert.ok(method);
<ide>
<ide> let firstHandlerCalled = 0;
<ide> process.on('SIGINT', common.mustCall(() => {
<ide> if (process.argv[2] === 'child') {
<ide> // Handler attached _before_ execution.
<ide> }));
<ide>
<del> assert.throws(() => {
<del> vm.runInThisContext(`process.kill(${parent}, 'SIGUSR2'); while(true) {}`, {
<del> breakOnSigint: true
<del> });
<del> }, /Script execution interrupted/);
<add> const script = `process.send('${method}'); while(true) {}`;
<add> const args = method === 'runInContext' ?
<add> [vm.createContext({ process })] :
<add> [];
<add> const options = { breakOnSigint: true };
<ide>
<add> assert.throws(() => { vm[method](script, ...args, options); },
<add> /^Error: Script execution interrupted\.$/);
<ide> assert.strictEqual(firstHandlerCalled, 0);
<ide> assert.strictEqual(onceHandlerCalled, 0);
<ide>
<ide> if (process.argv[2] === 'child') {
<ide> if (afterHandlerCalled++ === 0) {
<ide> // The first time it just bounces back to check that the `once()`
<ide> // handler is not called the second time.
<del> process.kill(parent, 'SIGUSR2');
<add> assert.strictEqual(firstHandlerCalled, 1);
<add> assert.strictEqual(onceHandlerCalled, 1);
<add> process.send(method);
<ide> return;
<ide> }
<ide>
<ide> if (process.argv[2] === 'child') {
<ide> timeout.unref();
<ide> }, 2));
<ide>
<del> process.kill(parent, 'SIGUSR2');
<add> process.send(method);
<ide>
<ide> return;
<ide> }
<ide>
<del>process.env.REPL_TEST_PPID = process.pid;
<del>
<del>// Set the `SIGUSR2` handler before spawning the child process to make sure
<del>// the signal is always handled.
<del>process.on('SIGUSR2', common.mustCall(() => {
<del> // First kill() breaks the while(true) loop, second one invokes the real
<del> // signal handlers.
<del> process.kill(child.pid, 'SIGINT');
<del>}, 3));
<add>for (const method of methods) {
<add> const child = spawn(process.execPath, [__filename, 'child', method], {
<add> stdio: [null, 'inherit', 'inherit', 'ipc']
<add> });
<ide>
<del>const child = spawn(process.execPath, [__filename, 'child'], {
<del> stdio: [null, 'inherit', 'inherit']
<del>});
<add> child.on('message', common.mustCall(() => {
<add> // First kill() breaks the while(true) loop, second one invokes the real
<add> // signal handlers.
<add> process.kill(child.pid, 'SIGINT');
<add> }, 3));
<ide>
<del>child.on('close', function(code, signal) {
<del> assert.strictEqual(signal, null);
<del> assert.strictEqual(code, 0);
<del>});
<add> child.on('close', common.mustCall((code, signal) => {
<add> assert.strictEqual(signal, null);
<add> assert.strictEqual(code, 0);
<add> }));
<add>}
<ide><path>test/parallel/test-vm-sigint.js
<ide> const vm = require('vm');
<ide>
<ide> const spawn = require('child_process').spawn;
<ide>
<add>const methods = [
<add> 'runInThisContext',
<add> 'runInContext'
<add>];
<add>
<ide> if (common.isWindows) {
<ide> // No way to send CTRL_C_EVENT to processes from JS right now.
<ide> common.skip('platform not supported');
<ide> return;
<ide> }
<ide>
<ide> if (process.argv[2] === 'child') {
<del> const parent = +process.env.REPL_TEST_PPID;
<del> assert.ok(parent);
<add> const method = process.argv[3];
<add> assert.ok(method);
<add>
<add> const script = `process.send('${method}'); while(true) {}`;
<add> const args = method === 'runInContext' ?
<add> [vm.createContext({ process })] :
<add> [];
<add> const options = { breakOnSigint: true };
<ide>
<del> assert.throws(() => {
<del> vm.runInThisContext(`process.kill(${parent}, "SIGUSR2"); while(true) {}`, {
<del> breakOnSigint: true
<del> });
<del> }, /Script execution interrupted/);
<add> assert.throws(() => { vm[method](script, ...args, options); },
<add> /^Error: Script execution interrupted\.$/);
<ide>
<ide> return;
<ide> }
<ide>
<del>process.env.REPL_TEST_PPID = process.pid;
<add>for (const method of methods) {
<add> const child = spawn(process.execPath, [__filename, 'child', method], {
<add> stdio: [null, 'pipe', 'inherit', 'ipc']
<add> });
<ide>
<del>// Set the `SIGUSR2` handler before spawning the child process to make sure
<del>// the signal is always handled.
<del>process.on('SIGUSR2', common.mustCall(() => {
<del> process.kill(child.pid, 'SIGINT');
<del>}));
<add> child.on('message', common.mustCall(() => {
<add> process.kill(child.pid, 'SIGINT');
<add> }));
<ide>
<del>const child = spawn(process.execPath, [__filename, 'child'], {
<del> stdio: [null, 'pipe', 'inherit']
<del>});
<del>
<del>child.on('close', common.mustCall((code, signal) => {
<del> assert.strictEqual(signal, null);
<del> assert.strictEqual(code, 0);
<del>}));
<add> child.on('close', common.mustCall((code, signal) => {
<add> assert.strictEqual(signal, null);
<add> assert.strictEqual(code, 0);
<add> }));
<add>} | 2 |
Ruby | Ruby | add failing test case for | 17a886b2759cb70ecebd174adeeac14e29bb8a11 | <ide><path>railties/test/application/rendering_test.rb
<add>require 'isolation/abstract_unit'
<add>require 'rack/test'
<add>
<add>module ApplicationTests
<add> class RoutingTest < ActiveSupport::TestCase
<add> include ActiveSupport::Testing::Isolation
<add> include Rack::Test::Methods
<add>
<add> def setup
<add> build_app
<add> boot_rails
<add> end
<add>
<add> def teardown
<add> teardown_app
<add> end
<add>
<add> test "Unknown format falls back to HTML template" do
<add> app_file 'config/routes.rb', <<-RUBY
<add> AppTemplate::Application.routes.draw do
<add> get 'pages/:id', to: 'pages#show'
<add> end
<add> RUBY
<add>
<add> app_file 'app/controllers/pages_controller.rb', <<-RUBY
<add> class PagesController < ApplicationController
<add> layout false
<add>
<add> def show
<add> end
<add> end
<add> RUBY
<add>
<add> app_file 'app/views/pages/show.html.erb', <<-RUBY
<add> <%= params[:id] %>
<add> RUBY
<add>
<add> get '/pages/foo'
<add> assert_equal 200, last_response.status
<add>
<add> get '/pages/foo.bar'
<add> assert_equal 200, last_response.status
<add> end
<add> end
<add>end | 1 |
Ruby | Ruby | allow option to omit `--retry` in curl_args | e687774e8adf892b0a955c8bc1d3dfef18788579 | <ide><path>Library/Homebrew/utils/curl.rb
<ide> def curl_executable
<ide> @curl
<ide> end
<ide>
<del> def curl_args(*extra_args, show_output: false, user_agent: :default)
<add> def curl_args(*extra_args, **options)
<ide> args = []
<ide>
<ide> # do not load .curlrc unless requested (must be the first argument)
<ide> def curl_args(*extra_args, show_output: false, user_agent: :default)
<ide>
<ide> args << "--show-error"
<ide>
<del> args << "--user-agent" << case user_agent
<add> args << "--user-agent" << case options[:user_agent]
<ide> when :browser, :fake
<ide> HOMEBREW_USER_AGENT_FAKE_SAFARI
<del> when :default
<add> when :default, nil
<ide> HOMEBREW_USER_AGENT_CURL
<del> else
<del> user_agent
<add> when String
<add> options[:user_agent]
<ide> end
<ide>
<ide> args << "--header" << "Accept-Language: en"
<ide>
<del> unless show_output
<add> unless options[:show_output] == true
<ide> args << "--fail"
<ide> args << "--progress-bar" unless Context.current.verbose?
<ide> args << "--verbose" if Homebrew::EnvConfig.curl_verbose?
<ide> args << "--silent" unless $stdout.tty?
<ide> end
<ide>
<del> args << "--retry" << Homebrew::EnvConfig.curl_retries
<add> args << "--retry" << Homebrew::EnvConfig.curl_retries unless options[:retry] == false
<ide>
<ide> args + extra_args
<ide> end | 1 |
Java | Java | add optional bound to onbackpressurebuffer | af275628baa8e62e2e00271ee08fff01de77845a | <ide><path>src/main/java/rx/Observable.java
<ide> public final Observable<T> onBackpressureBuffer() {
<ide> return lift(new OperatorOnBackpressureBuffer<T>());
<ide> }
<ide>
<add> /**
<add> * Instructs an Observable that is emitting items faster than its observer can consume them to buffer
<add> * up to a given amount of items until they can be emitted. The resulting Observable will {@code onError} emitting a
<add> * {@link java.nio.BufferOverflowException} as soon as the buffer's capacity is exceeded, dropping all
<add> * undelivered items, and unsubscribing from the source.
<add> * <p>
<add> * <img width="640" height="300" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/bp.obp.buffer.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code onBackpressureBuffer} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @return the source Observable modified to buffer items up to the given capacity.
<add> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a>
<add> */
<add> public final Observable<T> onBackpressureBuffer(long capacity) {
<add> return lift(new OperatorOnBackpressureBuffer<T>(capacity));
<add> }
<add>
<add> /**
<add> * Instructs an Observable that is emitting items faster than its observer can consume them to buffer
<add> * up to a given amount of items until they can be emitted. The resulting Observable will {@code onError} emitting a
<add> * {@link java.nio.BufferOverflowException} as soon as the buffer's capacity is exceeded, dropping all
<add> * undelivered items, unsubscribing from the source, and notifying the producer with {@code onOverflow}.
<add> * <p>
<add> * <img width="640" height="300" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/bp.obp.buffer.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code onBackpressureBuffer} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @return the source Observable modified to buffer items up to the given capacity.
<add> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a>
<add> */
<add> public final Observable<T> onBackpressureBuffer(long capacity, Func0<Void> onOverflow) {
<add> return lift(new OperatorOnBackpressureBuffer<T>(capacity, onOverflow));
<add> }
<add>
<ide> /**
<ide> * Instructs an Observable that is emitting items faster than its observer can consume them to discard,
<ide> * rather than emit, those items that its observer is not prepared to observe.
<ide><path>src/main/java/rx/internal/operators/OperatorOnBackpressureBuffer.java
<ide> */
<ide> package rx.internal.operators;
<ide>
<add>import java.nio.BufferOverflowException;
<ide> import java.util.Queue;
<ide> import java.util.concurrent.ConcurrentLinkedQueue;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<ide> import java.util.concurrent.atomic.AtomicLong;
<ide>
<ide> import rx.Observable.Operator;
<ide> import rx.Producer;
<ide> import rx.Subscriber;
<add>import rx.functions.Func0;
<ide>
<ide> public class OperatorOnBackpressureBuffer<T> implements Operator<T, T> {
<ide>
<ide> private final NotificationLite<T> on = NotificationLite.instance();
<ide>
<add> private final Long capacity;
<add> private final Func0 onOverflow;
<add>
<add> public OperatorOnBackpressureBuffer() {
<add> this.capacity = null;
<add> this.onOverflow = null;
<add> }
<add>
<add> public OperatorOnBackpressureBuffer(long capacity) {
<add> this(capacity, null);
<add> }
<add>
<add> public OperatorOnBackpressureBuffer(long capacity, Func0<Void> onOverflow) {
<add> if (capacity <= 0) {
<add> throw new IllegalArgumentException("Buffer capacity must be > 0");
<add> }
<add> this.capacity = capacity;
<add> this.onOverflow = onOverflow;
<add> }
<add>
<ide> @Override
<ide> public Subscriber<? super T> call(final Subscriber<? super T> child) {
<ide> // TODO get a different queue implementation
<del> // TODO start with size hint
<ide> final ConcurrentLinkedQueue<Object> queue = new ConcurrentLinkedQueue<Object>();
<add> final AtomicLong capacity = (this.capacity == null) ? null : new AtomicLong(this.capacity);
<ide> final AtomicLong wip = new AtomicLong();
<ide> final AtomicLong requested = new AtomicLong();
<ide>
<ide> public Subscriber<? super T> call(final Subscriber<? super T> child) {
<ide> @Override
<ide> public void request(long n) {
<ide> if (requested.getAndAdd(n) == 0) {
<del> pollQueue(wip, requested, queue, child);
<add> pollQueue(wip, requested, capacity, queue, child);
<ide> }
<ide> }
<ide>
<ide> });
<ide> // don't pass through subscriber as we are async and doing queue draining
<ide> // a parent being unsubscribed should not affect the children
<ide> Subscriber<T> parent = new Subscriber<T>() {
<add>
<add> private AtomicBoolean saturated = new AtomicBoolean(false);
<add>
<ide> @Override
<ide> public void onStart() {
<ide> request(Long.MAX_VALUE);
<ide> public void onStart() {
<ide> @Override
<ide> public void onCompleted() {
<ide> queue.offer(on.completed());
<del> pollQueue(wip, requested, queue, child);
<add> pollQueue(wip, requested, capacity, queue, child);
<ide> }
<ide>
<ide> @Override
<ide> public void onError(Throwable e) {
<ide> queue.offer(on.error(e));
<del> pollQueue(wip, requested, queue, child);
<add> pollQueue(wip, requested, capacity, queue, child);
<ide> }
<ide>
<ide> @Override
<ide> public void onNext(T t) {
<add> if (!ensureCapacity()) {
<add> return;
<add> }
<ide> queue.offer(on.next(t));
<del> pollQueue(wip, requested, queue, child);
<add> pollQueue(wip, requested, capacity, queue, child);
<ide> }
<ide>
<add> private boolean ensureCapacity() {
<add> if (capacity == null) {
<add> return true;
<add> }
<add>
<add> long currCapacity;
<add> do {
<add> currCapacity = capacity.get();
<add> if (currCapacity <= 0) {
<add> if (saturated.compareAndSet(false, true)) {
<add> // ensure single completion contract
<add> child.onError(new BufferOverflowException());
<add> unsubscribe();
<add> if (onOverflow != null) {
<add> onOverflow.call();
<add> }
<add> }
<add> return false;
<add> }
<add> // ensure no other thread stole our slot, or retry
<add> } while (!capacity.compareAndSet(currCapacity, currCapacity - 1));
<add> return true;
<add> }
<ide> };
<ide>
<ide> // if child unsubscribes it should unsubscribe the parent, but not the other way around
<ide> public void onNext(T t) {
<ide> return parent;
<ide> }
<ide>
<del> private void pollQueue(AtomicLong wip, AtomicLong requested, Queue<Object> queue, Subscriber<? super T> child) {
<add> private void pollQueue(AtomicLong wip, AtomicLong requested, AtomicLong capacity, Queue<Object> queue, Subscriber<? super T> child) {
<ide> // TODO can we do this without putting everything in the queue first so we can fast-path the case when we don't need to queue?
<ide> if (requested.get() > 0) {
<ide> // only one draining at a time
<ide> private void pollQueue(AtomicLong wip, AtomicLong requested, Queue<Object> queue
<ide> requested.incrementAndGet();
<ide> return;
<ide> }
<add> if (capacity != null) { // it's bounded
<add> capacity.incrementAndGet();
<add> }
<ide> on.accept(child, o);
<ide> } else {
<ide> // we hit the end ... so increment back to 0 again
<ide><path>src/test/java/rx/internal/operators/OperatorOnBackpressureBufferTest.java
<ide> */
<ide> package rx.internal.operators;
<ide>
<del>import static org.junit.Assert.assertEquals;
<del>
<add>import java.nio.BufferOverflowException;
<ide> import java.util.concurrent.CountDownLatch;
<ide>
<ide> import org.junit.Test;
<ide> import rx.Observable.OnSubscribe;
<ide> import rx.Observer;
<ide> import rx.Subscriber;
<add>import rx.Subscription;
<add>import rx.functions.Func0;
<add>import rx.observables.ConnectableObservable;
<ide> import rx.observers.TestSubscriber;
<ide> import rx.schedulers.Schedulers;
<ide>
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertTrue;
<add>
<ide> public class OperatorOnBackpressureBufferTest {
<ide>
<ide> @Test
<ide> public void onNext(Long t) {
<ide> assertEquals(499, ts.getOnNextEvents().get(499).intValue());
<ide> }
<ide>
<add> @Test(expected = IllegalArgumentException.class)
<add> public void testFixBackpressureBufferNegativeCapacity() throws InterruptedException {
<add> Observable.empty().onBackpressureBuffer(-1);
<add> }
<add>
<add> @Test(expected = IllegalArgumentException.class)
<add> public void testFixBackpressureBufferZeroCapacity() throws InterruptedException {
<add> Observable.empty().onBackpressureBuffer(-1);
<add> }
<add>
<add> @Test(timeout = 500)
<add> public void testFixBackpressureBoundedBuffer() throws InterruptedException {
<add> final CountDownLatch l1 = new CountDownLatch(250);
<add> final CountDownLatch l2 = new CountDownLatch(500);
<add> final CountDownLatch l3 = new CountDownLatch(1);
<add> TestSubscriber<Long> ts = new TestSubscriber<Long>(new Observer<Long>() {
<add>
<add> @Override
<add> public void onCompleted() {
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> }
<add>
<add> @Override
<add> public void onNext(Long t) {
<add> l1.countDown();
<add> l2.countDown();
<add> }
<add>
<add> });
<add>
<add> ts.requestMore(500);
<add>
<add> final ConnectableObservable<Long> flood =
<add> infinite.subscribeOn(Schedulers.computation())
<add> .publish();
<add> final ConnectableObservable<Long> batch =
<add> infinite.subscribeOn(Schedulers.computation())
<add> .onBackpressureBuffer(100, new Func0<Void>() {
<add> @Override
<add> public Void call() {
<add> l3.countDown();
<add> return null;
<add> }
<add> }).publish();
<add> Subscription s = batch.subscribe(ts);
<add> batch.connect(); // first controlled batch
<add>
<add> l1.await();
<add> flood.connect(); // open flood
<add> l2.await(); // ts can only swallow 250 more
<add> l3.await(); // hold until it chokes
<add>
<add> assertEquals(500, ts.getOnNextEvents().size());
<add> assertEquals(0, ts.getOnNextEvents().get(0).intValue());
<add> assertTrue(ts.getOnErrorEvents().get(0) instanceof BufferOverflowException);
<add> assertTrue(s.isUnsubscribed());
<add>
<add> }
<add>
<ide> static final Observable<Long> infinite = Observable.create(new OnSubscribe<Long>() {
<ide>
<ide> @Override
<ide> public void call(Subscriber<? super Long> s) {
<ide> }
<ide>
<ide> });
<add>
<ide> } | 3 |
Java | Java | add queryparamifpresent to uricomponentsbuilder | 7af726480f8da22f533b37d6ad01781aafeefa35 | <ide><path>spring-web/src/main/java/org/springframework/web/util/DefaultUriBuilderFactory.java
<ide> import java.util.Collections;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<add>import java.util.Optional;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.MultiValueMap;
<ide> public DefaultUriBuilder queryParam(String name, Object... values) {
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public DefaultUriBuilder queryParamIfPresent(String name, Optional<?> optionalValue) {
<add> this.uriComponentsBuilder.queryParamIfPresent(name, optionalValue);
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public DefaultUriBuilder queryParam(String name, @Nullable Collection<?> values) {
<ide> this.uriComponentsBuilder.queryParam(name, values);
<ide><path>spring-web/src/main/java/org/springframework/web/util/UriBuilder.java
<ide> import java.net.URI;
<ide> import java.util.Collection;
<ide> import java.util.Map;
<add>import java.util.Optional;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.MultiValueMap;
<ide> public interface UriBuilder {
<ide> */
<ide> UriBuilder queryParam(String name, Object... values);
<ide>
<add> /**
<add> * Delegates to {@link #queryParam(String, Object...)} or {@link #queryParam(String, Object...)} if and only if optionalValue has a value.
<add> * No action will be taken, and the query parameter name will not be added, if optionalValue is empty.
<add> * @param name the query parameter name
<add> * @param optionalValue an Optional, either empty or holding the query parameter value.
<add> * @return
<add> */
<add> UriBuilder queryParamIfPresent(String name, Optional<?> optionalValue);
<add>
<ide> /**
<ide> * Variant of {@link #queryParam(String, Object...)} with a Collection.
<ide> * <p><strong>Note: </strong> please, review the Javadoc of
<ide><path>spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.Optional;
<ide> import java.util.regex.Matcher;
<ide> import java.util.regex.Pattern;
<ide>
<ide> public UriComponentsBuilder queryParam(String name, Object... values) {
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public UriComponentsBuilder queryParamIfPresent(String name, Optional<?> optionalValue) {
<add> if (optionalValue.isPresent()) {
<add> Object value = optionalValue.get();
<add> if (value instanceof Collection) {
<add> queryParam(name, (Collection) value);
<add> }
<add> else {
<add> queryParam(name, value);
<add> }
<add> }
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public UriComponentsBuilder queryParam(String name, @Nullable Collection<?> values) {
<ide> return queryParam(name, (CollectionUtils.isEmpty(values) ? EMPTY_VALUES : values.toArray()));
<ide><path>spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java
<ide>
<ide> import java.net.URI;
<ide> import java.net.URISyntaxException;
<add>import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.Collection;
<ide> import java.util.Collections;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<add>import java.util.Optional;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> void fromUriStringQueryParamEncodedAndContainingPlus() {
<ide> assertThat(uri.toString()).isEqualTo(httpUrl);
<ide> }
<ide>
<add>
<add> @Test
<add> void queryParamIfPresent() {
<add> UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
<add> UriComponents result = builder.queryParamIfPresent("baz", Optional.of("qux")).queryParamIfPresent("foo", Optional.empty()).build();
<add>
<add> assertThat(result.getQuery()).isEqualTo("baz=qux");
<add> MultiValueMap<String, String> expectedQueryParams = new LinkedMultiValueMap<>(1);
<add> expectedQueryParams.add("baz", "qux");
<add> assertThat(result.getQueryParams()).isEqualTo(expectedQueryParams);
<add> }
<add>
<add> @Test
<add> void queryParamIfPresentCollection() {
<add> Collection<String> c = new ArrayList<>();
<add> c.add("foo");
<add> c.add("bar");
<add> UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
<add> UriComponents result = builder.queryParamIfPresent("baz", Optional.of(c)).build();
<add>
<add> assertThat(result.getQuery()).isEqualTo("baz=foo&baz=bar");
<add> MultiValueMap<String, String> expectedQueryParams = new LinkedMultiValueMap<>(1);
<add> expectedQueryParams.add("baz", "foo");
<add> expectedQueryParams.add("baz", "bar");
<add> assertThat(result.getQueryParams()).isEqualTo(expectedQueryParams);
<add> }
<add>
<ide> @Test // SPR-10539
<ide> void fromUriStringIPv6Host() {
<ide> UriComponents result = UriComponentsBuilder | 4 |
PHP | PHP | add matched route instance as request attribute | 1283dd9c6e3efe978f4f9c52482c913088d10343 | <ide><path>src/Command/RoutesCheckCommand.php
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide> }
<ide> }
<ide>
<del> unset($route['_matchedRoute']);
<add> unset($route['_route'], $route['_matchedRoute']);
<ide> ksort($route);
<ide>
<ide> $output = [
<ide><path>src/Routing/Middleware/RoutingMiddleware.php
<ide> public function process(ServerRequestInterface $request, RequestHandlerInterface
<ide> $params = Router::parseRequest($request) + $params;
<ide> if (isset($params['_middleware'])) {
<ide> $middleware = $params['_middleware'];
<del> unset($params['_middleware']);
<ide> }
<add> $route = $params['_route'];
<add> unset($params['_middleware'], $params['_route']);
<add>
<add> $request = $request->withAttribute('route', $route);
<ide> /** @var \Cake\Http\ServerRequest $request */
<ide> $request = $request->withAttribute('params', $params);
<ide> Router::setRequest($request);
<ide><path>src/Routing/Route/Route.php
<ide> public function parse(string $url, string $method): ?array
<ide> }
<ide> }
<ide> }
<add>
<add> $route['_route'] = $this;
<ide> $route['_matchedRoute'] = $this->template;
<ide> if (count($this->middleware) > 0) {
<ide> $route['_middleware'] = $this->middleware;
<ide><path>src/Routing/Router.php
<ide> public static function connect($route, $defaults = [], $options = []): void
<ide> }
<ide>
<ide> /**
<del> * Get the routing parameters for the request is possible.
<add> * Get the routing parameters for the request if possible.
<ide> *
<ide> * @param \Cake\Http\ServerRequest $request The request to parse request data from.
<ide> * @return array Parsed elements from URL.
<ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php
<ide> use Cake\Http\ServerRequestFactory;
<ide> use Cake\Routing\Exception\MissingRouteException;
<ide> use Cake\Routing\Middleware\RoutingMiddleware;
<add>use Cake\Routing\Route\Route;
<ide> use Cake\Routing\RouteBuilder;
<ide> use Cake\Routing\RouteCollection;
<ide> use Cake\Routing\Router;
<ide> public function testRouterSetParams(): void
<ide> $middleware->process($request, $handler);
<ide> }
<ide>
<add> /**
<add> * Test that Router sets matched routes instance.
<add> */
<add> public function testRouterSetRoute(): void
<add> {
<add> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
<add> $handler = new TestRequestHandler(function ($req) {
<add> $this->assertInstanceOf(Route::class, $req->getAttribute('route'));
<add> $this->assertSame('/articles', $req->getAttribute('route')->staticPath());
<add>
<add> return new Response();
<add> });
<add> $middleware = new RoutingMiddleware($this->app());
<add> $middleware->process($request, $handler);
<add> }
<add>
<ide> /**
<ide> * Test routing middleware does wipe off existing params keys.
<ide> */
<ide><path>tests/TestCase/Routing/Route/RouteTest.php
<ide> public function testComplexRouteCompilingAndParsing(): void
<ide> $this->assertMatchesRegularExpression($result, '/posts/08/01/2007/title-of-post');
<ide> $result = $route->parse('/posts/08/01/2007/title-of-post', 'GET');
<ide>
<del> $this->assertCount(7, $result);
<del> $this->assertEquals($result['controller'], 'Posts');
<del> $this->assertEquals($result['action'], 'view');
<del> $this->assertEquals($result['year'], '2007');
<del> $this->assertEquals($result['month'], '08');
<del> $this->assertEquals($result['day'], '01');
<del> $this->assertEquals($result['pass'][0], 'title-of-post');
<del> $this->assertEquals($result['_matchedRoute'], '/posts/{month}/{day}/{year}/*');
<add> $this->assertCount(8, $result);
<add> $this->assertSame('Posts', $result['controller']);
<add> $this->assertSame('view', $result['action']);
<add> $this->assertSame('2007', $result['year']);
<add> $this->assertSame('08', $result['month']);
<add> $this->assertSame('01', $result['day']);
<add> $this->assertSame('title-of-post', $result['pass'][0]);
<add> $this->assertSame($route, $result['_route']);
<add> $this->assertSame('/posts/{month}/{day}/{year}/*', $result['_matchedRoute']);
<ide>
<ide> $route = new Route(
<ide> '/{extra}/page/{slug}/*',
<ide> public function testParseRequestHostConditions(): void
<ide> 'controller' => 'Articles',
<ide> 'action' => 'index',
<ide> 'pass' => [],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/fallback',
<ide> ];
<ide> $this->assertEquals($expected, $result, 'Should match, domain is correct');
<ide> public function testParseWithPassDefaults(): void
<ide> 'controller' => 'Posts',
<ide> 'action' => 'display',
<ide> 'pass' => ['home'],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/{controller}',
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide> public function testParseWithMiddleware(): void
<ide> 'controller' => 'Posts',
<ide> 'action' => 'display',
<ide> 'pass' => ['home'],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/{controller}',
<ide> '_middleware' => ['auth', 'cookie'],
<ide> ];
<ide> public function testParseWithHttpHeaderConditions(): void
<ide> 'action' => 'index',
<ide> 'pass' => [],
<ide> '_method' => 'POST',
<add> '_route' => $route,
<ide> '_matchedRoute' => '/sample',
<ide> ];
<ide> $this->assertEquals($expected, $route->parse('/sample', 'post'));
<ide> public function testParseWithMultipleHttpMethodConditions(): void
<ide> 'action' => 'index',
<ide> 'pass' => [],
<ide> '_method' => ['PUT', 'POST'],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/sample',
<ide> ];
<ide> $this->assertEquals($expected, $route->parse('/sample', 'POST'));
<ide> public function testPatternOnAction(): void
<ide> 'controller' => 'BlogPosts',
<ide> 'action' => 'other',
<ide> 'pass' => [],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/blog/{action}/*',
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide> public function testParsePassedArgument(): void
<ide> 'controller' => 'Posts',
<ide> 'action' => 'edit',
<ide> 'pass' => ['1', '2', '0'],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/{controller}/{action}/*',
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide> public function testPassArgRestructure(): void
<ide> 'action' => 'view',
<ide> 'slug' => 'my-title',
<ide> 'pass' => ['my-title'],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/{controller}/{action}/{slug}',
<ide> ];
<ide> $this->assertEquals($expected, $result, 'Slug should have moved');
<ide> public function testParseTrailing(): void
<ide> 'controller' => 'Posts',
<ide> 'action' => 'index',
<ide> 'pass' => ['1/2/3/foo:bar'],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/{controller}/{action}/**',
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide> public function testParseTrailing(): void
<ide> 'controller' => 'Posts',
<ide> 'action' => 'index',
<ide> 'pass' => ['http://example.com'],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/{controller}/{action}/**',
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide> public function testParseTrailingUTF8(): void
<ide> 'controller' => 'Categories',
<ide> 'action' => 'index',
<ide> 'pass' => ['موبایل'],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/category/**',
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide> public function testUTF8PatternOnSection(): void
<ide> 'controller' => 'Posts',
<ide> 'action' => 'index',
<ide> 'pass' => [],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/{section}',
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide> public function testUTF8PatternOnSection(): void
<ide> 'controller' => 'Posts',
<ide> 'action' => 'index',
<ide> 'pass' => [],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/{section}',
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide> public function testUrlWithEncodedSlash(): void
<ide> 'controller' => 'Products',
<ide> 'action' => 'test',
<ide> 'pass' => ['xx%2Fyy'],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/products/tests/*',
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide> public function testUrlWithEncodedSlash(): void
<ide> 'action' => 'view',
<ide> 'slug' => 'xx%2Fyy',
<ide> 'pass' => [],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/products/view/{slug}',
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide> public function testSetState(): void
<ide> 'controller' => 'Pages',
<ide> 'action' => 'display',
<ide> 'pass' => ['home'],
<add> '_route' => $route,
<ide> '_matchedRoute' => '/',
<ide> ];
<ide> $this->assertEquals($expected, $route->parse('/', 'GET'));
<ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> public function testConnectTrimTrailingSlash(): void
<ide> 'pass' => [],
<ide> '_matchedRoute' => '/articles',
<ide> ];
<del> $this->assertEquals($expected, $this->collection->parse('/articles'));
<del> $this->assertEquals($expected, $this->collection->parse('/articles/'));
<add> $result = $this->collection->parse('/articles');
<add> unset($result['_route']);
<add> $this->assertEquals($expected, $result);
<add>
<add> $result = $this->collection->parse('/articles/');
<add> unset($result['_route']);
<add> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide> /**
<ide> public function testConnectShortString(): void
<ide> 'plugin' => null,
<ide> '_matchedRoute' => '/my-articles/view',
<ide> ];
<del> $this->assertEquals($expected, $this->collection->parse('/my-articles/view'));
<add> $result = $this->collection->parse('/my-articles/view');
<add> unset($result['_route']);
<add> $this->assertEquals($expected, $result);
<ide>
<ide> $url = $expected['_matchedRoute'];
<ide> unset($expected['_matchedRoute']);
<ide> public function testConnectShortStringPrefix(): void
<ide> 'action' => 'index',
<ide> '_matchedRoute' => '/admin/bookmarks',
<ide> ];
<del> $this->assertEquals($expected, $this->collection->parse('/admin/bookmarks'));
<add> $result = $this->collection->parse('/admin/bookmarks');
<add> unset($result['_route']);
<add> $this->assertEquals($expected, $result);
<ide>
<ide> $url = $expected['_matchedRoute'];
<ide> unset($expected['_matchedRoute']);
<ide> public function testConnectShortStringPlugin(): void
<ide> 'action' => 'view',
<ide> '_matchedRoute' => '/blog/articles/view',
<ide> ];
<del> $this->assertEquals($expected, $this->collection->parse('/blog/articles/view'));
<add> $result = $this->collection->parse('/blog/articles/view');
<add> unset($result['_route']);
<add> $this->assertEquals($expected, $result);
<ide>
<ide> $url = $expected['_matchedRoute'];
<ide> unset($expected['_matchedRoute']);
<ide> public function testConnectShortStringPluginPrefix(): void
<ide> 'action' => 'view',
<ide> '_matchedRoute' => '/admin/blog/articles/view',
<ide> ];
<del> $this->assertEquals($expected, $this->collection->parse('/admin/blog/articles/view'));
<add> $result = $this->collection->parse('/admin/blog/articles/view');
<add> unset($result['_route']);
<add> $this->assertEquals($expected, $result);
<ide>
<ide> $url = $expected['_matchedRoute'];
<ide> unset($expected['_matchedRoute']);
<ide><path>tests/TestCase/Routing/RouteCollectionTest.php
<ide> public function testParse(): void
<ide> $routes->connect('/media/search/*', ['controller' => 'Media', 'action' => 'search']);
<ide>
<ide> $result = $this->collection->parse('/b/');
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Articles',
<ide> 'action' => 'index',
<ide> public function testParse(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $this->collection->parse('/b/the-thing?one=two');
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Articles',
<ide> 'action' => 'view',
<ide> public function testParse(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $this->collection->parse('/b/media/search');
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'key' => 'value',
<ide> 'pass' => [],
<ide> public function testParse(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $this->collection->parse('/b/media/search/thing');
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'key' => 'value',
<ide> 'pass' => ['thing'],
<ide> public function testParseWithNameParameter(): void
<ide> $routes->connect('/media/search/*', ['controller' => 'Media', 'action' => 'search'], ['_name' => 'media_search']);
<ide>
<ide> $result = $this->collection->parse('/b/');
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Articles',
<ide> 'action' => 'index',
<ide> public function testParseWithNameParameter(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $this->collection->parse('/b/the-thing?one=two');
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Articles',
<ide> 'action' => 'view',
<ide> public function testParseWithNameParameter(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $this->collection->parse('/b/media/search');
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'key' => 'value',
<ide> 'pass' => [],
<ide> public function testParseWithNameParameter(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $this->collection->parse('/b/media/search/thing');
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'key' => 'value',
<ide> 'pass' => ['thing'],
<ide> public function testParseEncodedBytesInFixedSegment(): void
<ide> $routes->connect('/ден/{day}-{month}', ['controller' => 'Events', 'action' => 'index']);
<ide> $url = '/%D0%B4%D0%B5%D0%BD/15-%D0%BE%D0%BA%D1%82%D0%BE%D0%BC%D0%B2%D1%80%D0%B8?test=foo';
<ide> $result = $this->collection->parse($url);
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'plugin' => null,
<ide> public function testParseEncodedBytesInFixedSegment(): void
<ide>
<ide> $request = new ServerRequest(['url' => $url]);
<ide> $result = $this->collection->parseRequest($request);
<add> unset($result['_route']);
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide> public function testParseFallback(): void
<ide> $routes->connect('/{controller}/{action}', [], ['routeClass' => 'InflectedRoute']);
<ide>
<ide> $result = $this->collection->parse('/articles/add');
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Articles',
<ide> 'action' => 'add',
<ide> public function testParseRequestCheckHostCondition(): void
<ide> ],
<ide> ]);
<ide> $result = $this->collection->parseRequest($request);
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Articles',
<ide> 'action' => 'index',
<ide> public function testParseRequestCheckHostCondition(): void
<ide> ],
<ide> ]);
<ide> $result = $this->collection->parseRequest($request);
<add> unset($result['_route']);
<ide> $this->assertEquals($expected, $result, 'Should match, domain is a matching subdomain');
<ide>
<ide> $request = new ServerRequest([
<ide> public function testParseRequest(): void
<ide>
<ide> $request = new ServerRequest(['url' => '/b/']);
<ide> $result = $this->collection->parseRequest($request);
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Articles',
<ide> 'action' => 'index',
<ide> public function testParseRequest(): void
<ide>
<ide> $request = new ServerRequest(['url' => '/b/media/search']);
<ide> $result = $this->collection->parseRequest($request);
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'key' => 'value',
<ide> 'pass' => [],
<ide> public function testParseRequest(): void
<ide>
<ide> $request = new ServerRequest(['url' => '/b/media/search/thing']);
<ide> $result = $this->collection->parseRequest($request);
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'key' => 'value',
<ide> 'pass' => ['thing'],
<ide> public function testParseRequest(): void
<ide>
<ide> $request = new ServerRequest(['url' => '/b/the-thing?one=two']);
<ide> $result = $this->collection->parseRequest($request);
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Articles',
<ide> 'action' => 'view',
<ide> public function testParseRequestUnicode(): void
<ide>
<ide> $request = new ServerRequest(['url' => '/b/alta/confirmaci%C3%B3n']);
<ide> $result = $this->collection->parseRequest($request);
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Media',
<ide> 'action' => 'confirm',
<ide> public function testParseRequestUnicode(): void
<ide>
<ide> $request = new ServerRequest(['url' => '/b/alta/confirmación']);
<ide> $result = $this->collection->parseRequest($request);
<add> unset($result['_route']);
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function testMultipleResourceRoute(): void
<ide> Router::connect('/{controller}', ['action' => 'index', '_method' => ['GET', 'POST']]);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/Posts', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'plugin' => null,
<ide> public function testMultipleResourceRoute(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/Posts', 'POST'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'plugin' => null,
<ide> public function testUrlCatchAllRoute(): void
<ide> '_matchedRoute' => '/*',
<ide> ];
<ide> $result = Router::parseRequest($this->makeRequest('/0', 'GET'));
<add> unset($result['_route']);
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('0', 'GET'));
<add> unset($result['_route']);
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide> public function testUrlParsing(): void
<ide> ['value', 'somevalue', 'othervalue']
<ide> );
<ide> $result = Router::parseRequest($this->makeRequest('/posts/2007/08/01/title-of-post-here', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'value' => '2007',
<ide> 'somevalue' => '08',
<ide> public function testUrlParsing(): void
<ide> ['year' => $Year, 'month' => $Month, 'day' => $Day]
<ide> );
<ide> $result = Router::parseRequest($this->makeRequest('/posts/2007/08/01/title-of-post-here', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'year' => '2007',
<ide> 'month' => '08',
<ide> public function testUrlParsing(): void
<ide> ['year' => $Year, 'month' => $Month, 'day' => $Day]
<ide> );
<ide> $result = Router::parseRequest($this->makeRequest('/posts/01/2007/08/title-of-post-here', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'day' => '01',
<ide> 'year' => '2007',
<ide> public function testUrlParsing(): void
<ide> ['year' => $Year, 'month' => $Month, 'day' => $Day]
<ide> );
<ide> $result = Router::parseRequest($this->makeRequest('/posts/08/01/2007/title-of-post-here', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'month' => '08',
<ide> 'day' => '01',
<ide> public function testUrlParsing(): void
<ide> ['controller' => 'Posts', 'action' => 'view']
<ide> );
<ide> $result = Router::parseRequest($this->makeRequest('/posts/2007/08/01/title-of-post-here', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'year' => '2007',
<ide> 'month' => '08',
<ide> public function testUrlParsing(): void
<ide> Router::reload();
<ide> $this->_connectDefaultRoutes();
<ide> $result = Router::parseRequest($this->makeRequest('/pages/display/home', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'plugin' => null,
<ide> 'pass' => ['home'],
<ide> public function testUrlParsing(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('pages/display/home/', 'GET'));
<add> unset($result['_route']);
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('pages/display/home', 'GET'));
<add> unset($result['_route']);
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> Router::reload();
<ide> Router::connect('/page/*', ['controller' => 'Test']);
<ide> $result = Router::parseRequest($this->makeRequest('/page/my-page', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => ['my-page'],
<ide> 'plugin' => null,
<ide> public function testUrlParsing(): void
<ide> ['language' => '[a-z]{3}']
<ide> );
<ide> $result = Router::parseRequest($this->makeRequest('/eng/contact', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'language' => 'eng',
<ide> public function testUrlParsing(): void
<ide> );
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/forestillinger/10/2007/min-forestilling', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => ['min-forestilling'],
<ide> 'plugin' => 'Shows',
<ide> public function testUrlParsing(): void
<ide> Router::connect('/{controller}/{action}/*');
<ide> Router::connect('/', ['plugin' => 'pages', 'controller' => 'Pages', 'action' => 'display']);
<ide> $result = Router::parseRequest($this->makeRequest('/', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'controller' => 'Pages',
<ide> public function testUrlParsing(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/Posts/edit/0', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [0],
<ide> 'controller' => 'Posts',
<ide> public function testUrlParsing(): void
<ide> ['pass' => ['id', 'url_title'], 'id' => '[\d]+']
<ide> );
<ide> $result = Router::parseRequest($this->makeRequest('/Posts/5:sample-post-title', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => ['5', 'sample-post-title'],
<ide> 'id' => '5',
<ide> public function testUrlParsing(): void
<ide> ['pass' => ['id', 'url_title'], 'id' => '[\d]+']
<ide> );
<ide> $result = Router::parseRequest($this->makeRequest('/Posts/5:sample-post-title/other/params/4', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => ['5', 'sample-post-title', 'other', 'params', '4'],
<ide> 'id' => 5,
<ide> public function testUrlParsing(): void
<ide> Router::reload();
<ide> Router::connect('/posts/view/*', ['controller' => 'Posts', 'action' => 'view']);
<ide> $result = Router::parseRequest($this->makeRequest('/posts/view/10?id=123&tab=abc', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [10],
<ide> 'plugin' => null,
<ide> public function testUrlParsing(): void
<ide> ['pass' => ['id', 'url_title'], 'id' => $UUID]
<ide> );
<ide> $result = Router::parseRequest($this->makeRequest('/posts/sample-post-title-(uuid:47fc97a9-019c-41d1-a058-1fa3cbdd56cb)', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => ['47fc97a9-019c-41d1-a058-1fa3cbdd56cb', 'sample-post-title'],
<ide> 'id' => '47fc97a9-019c-41d1-a058-1fa3cbdd56cb',
<ide> public function testUrlParsing(): void
<ide> Router::reload();
<ide> Router::connect('/posts/view/*', ['controller' => 'Posts', 'action' => 'view']);
<ide> $result = Router::parseRequest($this->makeRequest('/posts/view/foo:bar/routing:fun', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => ['foo:bar', 'routing:fun'],
<ide> 'plugin' => null,
<ide> public function testParseRequest(): void
<ide> Router::connect('/articles/{action}/*', ['controller' => 'Articles']);
<ide> $request = new ServerRequest(['url' => '/articles/view/1']);
<ide> $result = Router::parseRequest($request);
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => ['1'],
<ide> 'plugin' => null,
<ide> public function testUuidRoutes(): void
<ide> ['category_id' => '\w{8}-\w{4}-\w{4}-\w{4}-\w{12}']
<ide> );
<ide> $result = Router::parseRequest($this->makeRequest('/subjects/add/4795d601-19c8-49a6-930e-06a8b01d17b7', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'category_id' => '4795d601-19c8-49a6-930e-06a8b01d17b7',
<ide> public function testRouteSymmetry(): void
<ide> );
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/some_extra/page/this_is_the_slug', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'plugin' => null,
<ide> public function testRouteSymmetry(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/page/this_is_the_slug', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'plugin' => null,
<ide> public function testExtensionParsing(): void
<ide> $this->_connectDefaultRoutes();
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/posts.rss', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'plugin' => null,
<ide> 'controller' => 'Posts',
<ide> public function testExtensionParsing(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/posts/view/1.rss', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'plugin' => null,
<ide> 'controller' => 'Posts',
<ide> public function testExtensionParsing(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/posts/view/1.rss?query=test', 'GET'));
<add> unset($result['_route']);
<ide> $expected['?'] = ['query' => 'test'];
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> public function testExtensionParsing(): void
<ide> $this->_connectDefaultRoutes();
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/posts.xml', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'plugin' => null,
<ide> 'controller' => 'Posts',
<ide> public function testExtensionParsing(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/posts.atom?hello=goodbye', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'plugin' => null,
<ide> 'controller' => 'Posts.atom',
<ide> public function testExtensionParsing(): void
<ide> Router::reload();
<ide> Router::connect('/controller/action', ['controller' => 'Controller', 'action' => 'action', '_ext' => 'rss']);
<ide> $result = Router::parseRequest($this->makeRequest('/controller/action', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Controller',
<ide> 'action' => 'action',
<ide> public function testExtensionParsing(): void
<ide> Router::reload();
<ide> Router::connect('/controller/action', ['controller' => 'Controller', 'action' => 'action', '_ext' => 'rss']);
<ide> $result = Router::parseRequest($this->makeRequest('/controller/action', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Controller',
<ide> 'action' => 'action',
<ide> public function testExtensionParsing(): void
<ide> Router::extensions('rss', false);
<ide> Router::connect('/controller/action', ['controller' => 'Controller', 'action' => 'action', '_ext' => 'rss']);
<ide> $result = Router::parseRequest($this->makeRequest('/controller/action', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'Controller',
<ide> 'action' => 'action',
<ide> public function testPagesUrlParsing(): void
<ide> Router::connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => ['home'],
<ide> 'plugin' => null,
<ide> public function testPagesUrlParsing(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/pages/home/', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => ['home'],
<ide> 'plugin' => null,
<ide> public function testPagesUrlParsing(): void
<ide> Router::connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => ['home'],
<ide> 'plugin' => null,
<ide> public function testPagesUrlParsing(): void
<ide> Router::connect('/', ['controller' => 'Posts', 'action' => 'index']);
<ide> Router::connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
<ide> $result = Router::parseRequest($this->makeRequest('/pages/contact/', 'GET'));
<add> unset($result['_route']);
<ide>
<ide> $expected = [
<ide> 'pass' => ['contact'],
<ide> public function testParsingWithPatternOnAction(): void
<ide> );
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/blog/other', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'plugin' => null,
<ide> 'controller' => 'BlogPosts',
<ide> public function testParsingWithLiteralPrefixes(): void
<ide> Router::setRequest($request);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/admin/Posts/', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'prefix' => 'Admin',
<ide> public function testParsingWithLiteralPrefixes(): void
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/admin/Posts', 'GET'));
<add> unset($result['_route']);
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Router::url(['prefix' => 'Admin', 'controller' => 'Posts']);
<ide> public function testParsingWithLiteralPrefixes(): void
<ide> Router::setRequest($request);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/members/Posts/index', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'prefix' => 'Members',
<ide> public function testRegexRouteMatching(): void
<ide> Router::connect('/{locale}/{controller}/{action}/*', [], ['locale' => 'dan|eng']);
<ide>
<ide> $result = Router::parseRequest($this->makeRequest('/eng/Test/testAction', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'locale' => 'eng',
<ide> public function testUsingCustomRouteClass(): void
<ide> ['routeClass' => 'PluginShortRoute', 'slug' => '[a-z_-]+']
<ide> );
<ide> $result = Router::parseRequest($this->makeRequest('/the-best', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'plugin' => 'TestPlugin',
<ide> 'controller' => 'TestPlugin',
<ide> public function testPatternOnAction(): void
<ide> $this->assertSame('/blog/actions/', $result);
<ide>
<ide> $result = $route->parseRequest($this->makeRequest('/blog/other', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'controller' => 'BlogPosts',
<ide> 'action' => 'other',
<ide> public function testConnectShortStringSyntax(): void
<ide> {
<ide> Router::connect('/admin/articles/view', 'Admin/Articles::view');
<ide> $result = Router::parseRequest($this->makeRequest('/admin/articles/view', 'GET'));
<add> unset($result['_route']);
<ide> $expected = [
<ide> 'pass' => [],
<ide> 'prefix' => 'Admin', | 9 |
Java | Java | fix missing urivariables | f2fa74055ea3a81246c94d4d60b28f1b6d41f216 | <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClientOperations.java
<ide> public HeaderSpec uri(URI uri) {
<ide>
<ide> @Override
<ide> public HeaderSpec uri(String uriTemplate, Object... uriVariables) {
<del> return uri(getUriBuilderFactory().expand(uriTemplate));
<add> return uri(getUriBuilderFactory().expand(uriTemplate, uriVariables));
<ide> }
<ide>
<ide> @Override | 1 |
PHP | PHP | add the class property | d541a32dac96c606a24e6e7a378266a2f910e9fe | <ide><path>src/Controller/Component.php
<ide> class Component implements EventListenerInterface
<ide> */
<ide> public $request;
<ide>
<add> /**
<add> * Response object
<add> *
<add> * @var \Cake\Network\Response
<add> */
<add> public $response;
<add>
<ide> /**
<ide> * Component registry class used to lazy load components.
<ide> * | 1 |
Ruby | Ruby | handle nil keys | 0513d9de5c3c1cd860474df3dfba3847e70331ff | <ide><path>Library/Homebrew/linkage_checker.rb
<ide> def initialize(keg, formula = nil)
<ide> end
<ide>
<ide> def dylib_to_dep(dylib)
<del> if dylib =~ %r{#{Regexp.escape(HOMEBREW_PREFIX)}/(opt|Cellar)/([\w+-.@]+)/}
<del> Regexp.last_match(2)
<del> else
<del> "Not a Homebrew library"
<del> end
<add> dylib =~ %r{#{Regexp.escape(HOMEBREW_PREFIX)}/(opt|Cellar)/([\w+-.@]+)/}
<add> Regexp.last_match(2)
<ide> end
<ide>
<ide> def check_dylibs
<ide> def display_items(label, things)
<ide> return if things.empty?
<ide> puts "#{label}:"
<ide> if things.is_a? Hash
<del> things.sort.each do |list_label, list|
<add> things.sort_by { |k, _| k.to_s }.each do |list_label, list|
<ide> list.sort.each do |item|
<ide> puts " #{item} (#{list_label})"
<ide> end | 1 |
PHP | PHP | declare property set in constructor | e19aaaa45c97434b34eef404d6d50614b06d19fd | <ide><path>tests/test_app/TestApp/Model/Table/FeaturedTagsTable.php
<ide> */
<ide> class FeaturedTagsTable extends Table
<ide> {
<add> protected $Posts;
<add>
<ide> public function initialize(array $config): void
<ide> {
<ide> // Used to reproduce https://github.com/cakephp/cakephp/issues/16373 | 1 |
Javascript | Javascript | replace function with arrow function | bd9f7d5994d526e0ec0877ebd694a0873fa8b390 | <ide><path>test/parallel/test-timers.js
<ide> const inputs = [
<ide> const timeouts = [];
<ide> const intervals = [];
<ide>
<del>inputs.forEach(function(value, index) {
<del> setTimeout(function() {
<add>inputs.forEach((value, index) => {
<add> setTimeout(() => {
<ide> timeouts[index] = true;
<ide> }, value);
<ide>
<del> const handle = setInterval(function() {
<add> const handle = setInterval(() => {
<ide> clearInterval(handle); // disarm timer or we'll never finish
<ide> intervals[index] = true;
<ide> }, value);
<ide> inputs.forEach(function(value, index) {
<ide> // All values in inputs array coerce to 1 ms. Therefore, they should all run
<ide> // before a timer set here for 2 ms.
<ide>
<del>setTimeout(common.mustCall(function() {
<add>setTimeout(common.mustCall(() => {
<ide> // assert that all other timers have run
<del> inputs.forEach(function(value, index) {
<add> inputs.forEach((value, index) => {
<ide> assert(timeouts[index]);
<ide> assert(intervals[index]);
<ide> }); | 1 |
Javascript | Javascript | add routercontext in production mode | 7e5e414bcb4f128880501dd84d6a86708d7c8b5e | <ide><path>packages/next/client/index.js
<ide> async function doRender ({ App, Component, props, err }) {
<ide> renderReactElement((
<ide> <ErrorBoundary fn={(error) => renderError({ App, err: error }).catch(err => console.error('Error rendering page: ', err))}>
<ide> <Suspense fallback={<div>Loading...</div>}>
<del> <HeadManagerContext.Provider value={headManager.updateHead}>
<del> <App {...appProps} />
<del> </HeadManagerContext.Provider>
<add> <RouterContext.Provider value={makePublicRouterInstance(router)}>
<add> <DataManagerContext.Provider value={dataManager}>
<add> <HeadManagerContext.Provider value={headManager.updateHead}>
<add> <App {...appProps} />
<add> </HeadManagerContext.Provider>
<add> </DataManagerContext.Provider>
<add> </RouterContext.Provider>
<ide> </Suspense>
<ide> </ErrorBoundary>
<ide> ), appContainer) | 1 |
Javascript | Javascript | remove reactchildren methods from react object | 3cf14e8f9b14ac05bcd24634daa26ac6772bd31b | <ide><path>src/addons/transitions/ReactTransitionKeySet.js
<ide>
<ide> "use strict";
<ide>
<del>var React = require('React');
<add>var ReactChildren = require('ReactChildren');
<ide>
<ide> var MERGE_KEY_SETS_TAIL_SENTINEL = {};
<ide>
<ide> var ReactTransitionKeySet = {
<ide> /**
<ide> * Given `this.props.children`, return an object mapping key to child. Just
<del> * simple syntactic sugar around React.mapChildren().
<add> * simple syntactic sugar around ReactChildren.map().
<ide> *
<ide> * @param {*} children `this.props.children`
<ide> * @return {object} Mapping of key to child
<ide> */
<ide> getChildMapping: function(children) {
<del> return React.mapChildren(children, function(child) {
<add> return ReactChildren.map(children, function(child) {
<ide> return child;
<ide> });
<ide> },
<ide> var ReactTransitionKeySet = {
<ide> * @return {object} Mapping of key to the value "true"
<ide> */
<ide> getKeySet: function(children) {
<del> return React.mapChildren(children, function() {
<add> return ReactChildren.map(children, function() {
<ide> return true;
<ide> });
<ide> },
<ide><path>src/core/React.js
<ide>
<ide> "use strict";
<ide>
<del>var ReactChildren = require('ReactChildren');
<ide> var ReactCompositeComponent = require('ReactCompositeComponent');
<ide> var ReactComponent = require('ReactComponent');
<ide> var ReactDOM = require('ReactDOM');
<ide> var React = {
<ide> createClass: ReactCompositeComponent.createClass,
<ide> constructAndRenderComponent: ReactMount.constructAndRenderComponent,
<ide> constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID,
<del> forEachChildren: ReactChildren.forEach,
<del> mapChildren: ReactChildren.map,
<ide> renderComponent: ReactPerf.measure(
<ide> 'React',
<ide> 'renderComponent', | 2 |
Text | Text | fix migrate formula link | d2cc9179601103dcb23606eb39dffb7e1e80023c | <ide><path>docs/Migrate-A-Formula-To-Multiple-Versions.md
<ide> In separate pull-requests:
<ide>
<ide> In separate pull-requests:
<ide>
<del>1. [Migrate the formula](Migrating-A-Formula-To-A-Tap) from Homebrew/homebrew-versions to Homebrew/homebrew-core with the same, old name e.g. `boost160.rb`.
<add>1. [Migrate the formula](Migrating-A-Formula-To-A-Tap.md) from Homebrew/homebrew-versions to Homebrew/homebrew-core with the same, old name e.g. `boost160.rb`.
<ide> 2. [Rename the formula](Rename-A-Formula.md) from e.g. `boost160.rb` to e.g. `boost@1.60.rb`. This should not require any `revision`ing or significant formula modification beyond the formula name.
<ide> 3. Tap authors should have their `depends_on "boost160"` updated to `depends_on "boost@1.60"`.
<ide> 5. When `boost@1.60` has two major/minor versions newer than it (e.g. `boost@1.62`) then consider removing `boost@1.60.rb` and anything that depends on it. | 1 |
Javascript | Javascript | remove one of the checks for memory leak | 38c122a73a843a0d117d4f962cc94fda6f553086 | <ide><path>test/data/testrunner.js
<ide> var oldStart = window.start,
<ide> // Store the old counts so that we only assert on tests that have actually leaked,
<ide> // instead of asserting every time a test has leaked sometime in the past
<ide> oldCacheLength = 0,
<del> oldFragmentsLength = 0,
<ide> oldActive = 0,
<ide>
<ide> expectedDataKeys = {},
<ide> QUnit.config.urlConfig.push({
<ide> window.moduleTeardown = function() {
<ide> var i,
<ide> expectedKeys, actualKeys,
<del> fragmentsLength = 0,
<ide> cacheLength = 0;
<ide>
<ide> // Only look for jQuery data problems if this test actually
<ide> window.moduleTeardown = function() {
<ide> ++cacheLength;
<ide> }
<ide>
<del> jQuery.fragments = {};
<del>
<del> for ( i in jQuery.fragments ) {
<del> ++fragmentsLength;
<del> }
<del>
<ide> // Because QUnit doesn't have a mechanism for retrieving the number of expected assertions for a test,
<ide> // if we unconditionally assert any of these, the test will fail with too many assertions :|
<ide> if ( cacheLength !== oldCacheLength ) {
<ide> equal( cacheLength, oldCacheLength, "No unit tests leak memory in jQuery.cache" );
<ide> oldCacheLength = cacheLength;
<ide> }
<del> if ( fragmentsLength !== oldFragmentsLength ) {
<del> equal( fragmentsLength, oldFragmentsLength, "No unit tests leak memory in jQuery.fragments" );
<del> oldFragmentsLength = fragmentsLength;
<del> }
<ide> };
<ide>
<ide> QUnit.done(function() { | 1 |
Text | Text | fix mistake in docs | 661c8f9ad56a1f5f35e4a769ac44b668227b14e6 | <ide><path>docs/api-guide/authentication.md
<ide> Typically the approach you should take is:
<ide> * If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked.
<ide> * If authentication is attempted but fails, raise a `AuthenticationFailed` exception. An error response will be returned immediately, without checking any other authentication schemes.
<ide>
<del>You *may* also override the `.authentication_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
<add>You *may* also override the `.authenticate_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
<ide>
<del>If the `.authentication_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
<add>If the `.authenticate_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
<ide>
<ide> ## Example
<ide> | 1 |
Ruby | Ruby | remove unused require | d266c2e0da0e9835e9156278d24e596d671be2b2 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> require 'active_support/core_ext/hash/except'
<ide> require 'active_support/core_ext/object/blank'
<del>require 'active_support/core_ext/object/inclusion'
<ide> require 'active_support/inflector'
<ide> require 'action_dispatch/routing/redirection'
<ide> | 1 |
PHP | PHP | allow use some additional config for old sqlserver | d20dd0da43162f6a2af0b7f6513ed310d73a082f | <ide><path>src/Database/Driver/Sqlserver.php
<ide> class Sqlserver extends Driver
<ide> 'failoverPartner' => null,
<ide> 'loginTimeout' => null,
<ide> 'multiSubnetFailover' => null,
<add> 'encrypt' => null,
<add> 'trustServerCertificate' => null,
<ide> ];
<ide>
<ide> /**
<ide> public function connect(): bool
<ide> if ($config['multiSubnetFailover'] !== null) {
<ide> $dsn .= ";MultiSubnetFailover={$config['multiSubnetFailover']}";
<ide> }
<add> if ($config['encrypt'] !== null) {
<add> $dsn .= ";Encrypt={$config['encrypt']}";
<add> }
<add> if ($config['trustServerCertificate'] !== null) {
<add> $dsn .= ";TrustServerCertificate={$config['trustServerCertificate']}";
<add> }
<ide> $this->_connect($dsn, $config);
<ide>
<ide> $connection = $this->getConnection();
<ide><path>tests/TestCase/Database/Driver/SqlserverTest.php
<ide> public function testConnectionConfigCustom(): void
<ide> $expected['loginTimeout'] = null;
<ide> $expected['multiSubnetFailover'] = null;
<ide> $expected['port'] = null;
<add> $expected['encrypt'] = null;
<add> $expected['trustServerCertificate'] = null;
<ide>
<ide> $connection = $this->getMockBuilder('stdClass')
<ide> ->addMethods(['exec', 'quote']) | 2 |
Ruby | Ruby | allow certain argv usages | 065475369568f7a1174efb681faab01183b648e4 | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_text
<ide> problem "Use 'build.head?' instead of inspecting 'version'"
<ide> end
<ide>
<del> if text =~ /ARGV/
<add> if text =~ /ARGV(?!\.(debug|verbose)\?)/
<ide> problem "Use build instead of ARGV to check options."
<ide> end
<ide> | 1 |
Python | Python | make git_version() work on python 3 | d1a184c1a112ffbaa553915c043c2b6851e4fc91 | <ide><path>setup.py
<ide> def _minimal_ext_cmd(cmd):
<ide>
<ide> try:
<ide> out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
<del> GIT_REVISION = out.strip()
<add> GIT_REVISION = out.strip().decode('ascii')
<ide> except OSError:
<ide> GIT_REVISION = "Unknown"
<ide> | 1 |
Ruby | Ruby | extract common code in `uuid_test.rb` | 671e997e5a71fbe0ba44d589b34c48b6c6502323 | <ide><path>activerecord/test/cases/adapters/postgresql/uuid_test.rb
<ide> require 'active_record/base'
<ide> require 'active_record/connection_adapters/postgresql_adapter'
<ide>
<add>module PostgresqlUUIDHelper
<add> def connection
<add> @connection ||= ActiveRecord::Base.connection
<add> end
<add>
<add> def enable_uuid_ossp
<add> unless connection.extension_enabled?('uuid-ossp')
<add> connection.enable_extension 'uuid-ossp'
<add> connection.commit_db_transaction
<add> end
<add>
<add> connection.reconnect!
<add> end
<add>
<add> def drop_table(name)
<add> connection.execute "drop table if exists #{name}"
<add> end
<add>end
<add>
<ide> class PostgresqlUUIDTest < ActiveRecord::TestCase
<add> include PostgresqlUUIDHelper
<add>
<ide> class UUIDType < ActiveRecord::Base
<ide> self.table_name = "uuid_data_type"
<ide> end
<ide>
<del> def setup
<del> @connection = ActiveRecord::Base.connection
<del> @connection.transaction do
<del> @connection.create_table "uuid_data_type" do |t|
<del> t.uuid 'guid'
<del> end
<add> setup do
<add> connection.create_table "uuid_data_type" do |t|
<add> t.uuid 'guid'
<ide> end
<ide> end
<ide>
<del> def teardown
<del> @connection.execute 'drop table if exists uuid_data_type'
<add> teardown do
<add> drop_table "uuid_data_type"
<ide> end
<ide>
<ide> def test_data_type_of_uuid_types
<ide> def test_uuid_formats
<ide> end
<ide>
<ide> class PostgresqlUUIDGenerationTest < ActiveRecord::TestCase
<add> include PostgresqlUUIDHelper
<add>
<ide> class UUID < ActiveRecord::Base
<ide> self.table_name = 'pg_uuids'
<ide> end
<ide>
<del> def setup
<del> @connection = ActiveRecord::Base.connection
<add> setup do
<add> enable_uuid_ossp
<ide>
<del> unless @connection.extension_enabled?('uuid-ossp')
<del> @connection.enable_extension 'uuid-ossp'
<del> @connection.commit_db_transaction
<del> end
<del>
<del> @connection.reconnect!
<del>
<del> @connection.transaction do
<del> @connection.create_table('pg_uuids', id: :uuid, default: 'uuid_generate_v1()') do |t|
<del> t.string 'name'
<del> t.uuid 'other_uuid', default: 'uuid_generate_v4()'
<del> end
<add> connection.create_table('pg_uuids', id: :uuid, default: 'uuid_generate_v1()') do |t|
<add> t.string 'name'
<add> t.uuid 'other_uuid', default: 'uuid_generate_v4()'
<ide> end
<ide> end
<ide>
<del> def teardown
<del> @connection.execute 'drop table if exists pg_uuids'
<add> teardown do
<add> drop_table "pg_uuids"
<ide> end
<ide>
<ide> if ActiveRecord::Base.connection.supports_extensions?
<ide> def test_auto_create_uuid
<ide> end
<ide>
<ide> def test_pk_and_sequence_for_uuid_primary_key
<del> pk, seq = @connection.pk_and_sequence_for('pg_uuids')
<add> pk, seq = connection.pk_and_sequence_for('pg_uuids')
<ide> assert_equal 'id', pk
<ide> assert_equal nil, seq
<ide> end
<ide>
<ide> def test_schema_dumper_for_uuid_primary_key
<ide> schema = StringIO.new
<del> ActiveRecord::SchemaDumper.dump(@connection, schema)
<add> ActiveRecord::SchemaDumper.dump(connection, schema)
<ide> assert_match(/\bcreate_table "pg_uuids", id: :uuid, default: "uuid_generate_v1\(\)"/, schema.string)
<ide> assert_match(/t\.uuid "other_uuid", default: "uuid_generate_v4\(\)"/, schema.string)
<ide> end
<ide> end
<ide> end
<ide>
<ide> class PostgresqlUUIDTestNilDefault < ActiveRecord::TestCase
<del> class UUID < ActiveRecord::Base
<del> self.table_name = 'pg_uuids'
<del> end
<add> include PostgresqlUUIDHelper
<ide>
<del> def setup
<del> @connection = ActiveRecord::Base.connection
<del> @connection.reconnect!
<add> setup do
<add> enable_uuid_ossp
<ide>
<del> unless @connection.extension_enabled?('uuid-ossp')
<del> @connection.enable_extension 'uuid-ossp'
<del> @connection.commit_db_transaction
<del> end
<del>
<del> @connection.transaction do
<del> @connection.create_table('pg_uuids', id: false) do |t|
<del> t.primary_key :id, :uuid, default: nil
<del> t.string 'name'
<del> end
<add> connection.create_table('pg_uuids', id: false) do |t|
<add> t.primary_key :id, :uuid, default: nil
<add> t.string 'name'
<ide> end
<ide> end
<ide>
<del> def teardown
<del> @connection.execute 'drop table if exists pg_uuids'
<add> teardown do
<add> drop_table "pg_uuids"
<ide> end
<ide>
<ide> if ActiveRecord::Base.connection.supports_extensions?
<ide> def test_id_allows_default_override_via_nil
<del> col_desc = @connection.execute("SELECT pg_get_expr(d.adbin, d.adrelid) as default
<add> col_desc = connection.execute("SELECT pg_get_expr(d.adbin, d.adrelid) as default
<ide> FROM pg_attribute a
<ide> LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
<ide> WHERE a.attname='id' AND a.attrelid = 'pg_uuids'::regclass").first
<ide> def test_id_allows_default_override_via_nil
<ide> end
<ide>
<ide> class PostgresqlUUIDTestInverseOf < ActiveRecord::TestCase
<add> include PostgresqlUUIDHelper
<add>
<ide> class UuidPost < ActiveRecord::Base
<ide> self.table_name = 'pg_uuid_posts'
<ide> has_many :uuid_comments, inverse_of: :uuid_post
<ide> class UuidComment < ActiveRecord::Base
<ide> belongs_to :uuid_post
<ide> end
<ide>
<del> def setup
<del> @connection = ActiveRecord::Base.connection
<del> @connection.reconnect!
<del>
<del> unless @connection.extension_enabled?('uuid-ossp')
<del> @connection.enable_extension 'uuid-ossp'
<del> @connection.commit_db_transaction
<del> end
<add> setup do
<add> enable_uuid_ossp
<ide>
<del> @connection.transaction do
<del> @connection.create_table('pg_uuid_posts', id: :uuid) do |t|
<add> connection.transaction do
<add> connection.create_table('pg_uuid_posts', id: :uuid) do |t|
<ide> t.string 'title'
<ide> end
<del> @connection.create_table('pg_uuid_comments', id: :uuid) do |t|
<add> connection.create_table('pg_uuid_comments', id: :uuid) do |t|
<ide> t.uuid :uuid_post_id, default: 'uuid_generate_v4()'
<ide> t.string 'content'
<ide> end
<ide> end
<ide> end
<ide>
<del> def teardown
<del> @connection.transaction do
<del> @connection.execute 'drop table if exists pg_uuid_comments'
<del> @connection.execute 'drop table if exists pg_uuid_posts'
<add> teardown do
<add> connection.transaction do
<add> drop_table "pg_uuid_comments"
<add> drop_table "pg_uuid_posts"
<ide> end
<ide> end
<ide> | 1 |
Python | Python | pin torch to < 1.13 temporarily | 8214a9f66a64987e08e42e20801436f3da751b32 | <ide><path>setup.py
<ide> "timeout-decorator",
<ide> "timm",
<ide> "tokenizers>=0.11.1,!=0.11.3,<0.14",
<del> "torch>=1.7,!=1.12.0",
<add> "torch>=1.7,!=1.12.0,<1.13.0",
<ide> "torchaudio",
<ide> "pyctcdecode>=0.4.0",
<ide> "tqdm>=4.27",
<ide><path>src/transformers/dependency_versions_table.py
<ide> "timeout-decorator": "timeout-decorator",
<ide> "timm": "timm",
<ide> "tokenizers": "tokenizers>=0.11.1,!=0.11.3,<0.14",
<del> "torch": "torch>=1.7,!=1.12.0",
<add> "torch": "torch>=1.7,!=1.12.0,<1.13.0",
<ide> "torchaudio": "torchaudio",
<ide> "pyctcdecode": "pyctcdecode>=0.4.0",
<ide> "tqdm": "tqdm>=4.27", | 2 |
Python | Python | remove duplicated code in routers.simplerouter | 940cf2e2e004f913d3cc260fa2b490d33a163b51 | <ide><path>rest_framework/routers.py
<ide> def get_routes(self, viewset):
<ide> else:
<ide> list_routes.append((httpmethods, methodname))
<ide>
<add> def _get_dynamic_routes(route, dynamic_routes):
<add> ret = []
<add> for httpmethods, methodname in dynamic_routes:
<add> method_kwargs = getattr(viewset, methodname).kwargs
<add> initkwargs = route.initkwargs.copy()
<add> initkwargs.update(method_kwargs)
<add> url_path = initkwargs.pop("url_path", None) or methodname
<add> ret.append(Route(
<add> url=replace_methodname(route.url, url_path),
<add> mapping=dict((httpmethod, methodname) for httpmethod in httpmethods),
<add> name=replace_methodname(route.name, url_path),
<add> initkwargs=initkwargs,
<add> ))
<add>
<add> return ret
<add>
<ide> ret = []
<ide> for route in self.routes:
<ide> if isinstance(route, DynamicDetailRoute):
<ide> # Dynamic detail routes (@detail_route decorator)
<del> for httpmethods, methodname in detail_routes:
<del> method_kwargs = getattr(viewset, methodname).kwargs
<del> initkwargs = route.initkwargs.copy()
<del> initkwargs.update(method_kwargs)
<del> url_path = initkwargs.pop("url_path", None) or methodname
<del> ret.append(Route(
<del> url=replace_methodname(route.url, url_path),
<del> mapping=dict((httpmethod, methodname) for httpmethod in httpmethods),
<del> name=replace_methodname(route.name, url_path),
<del> initkwargs=initkwargs,
<del> ))
<add> ret += _get_dynamic_routes(route, detail_routes)
<ide> elif isinstance(route, DynamicListRoute):
<ide> # Dynamic list routes (@list_route decorator)
<del> for httpmethods, methodname in list_routes:
<del> method_kwargs = getattr(viewset, methodname).kwargs
<del> initkwargs = route.initkwargs.copy()
<del> initkwargs.update(method_kwargs)
<del> url_path = initkwargs.pop("url_path", None) or methodname
<del> ret.append(Route(
<del> url=replace_methodname(route.url, url_path),
<del> mapping=dict((httpmethod, methodname) for httpmethod in httpmethods),
<del> name=replace_methodname(route.name, url_path),
<del> initkwargs=initkwargs,
<del> ))
<add> ret += _get_dynamic_routes(route, list_routes)
<ide> else:
<ide> # Standard route
<ide> ret.append(route) | 1 |
Javascript | Javascript | remove browserified file | d0bdde4ce3660c00e2444ff5f96be190275b3a44 | <ide><path>axios.js
<del>!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.axios=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
<del>module.exports = _dereq_('./lib/axios');
<del>},{"./lib/axios":3}],2:[function(_dereq_,module,exports){
<del>var buildUrl = _dereq_('./../buildUrl');
<del>var cookies = _dereq_('./../cookies');
<del>var defaults = _dereq_('./../defaults');
<del>var parseHeaders = _dereq_('./../parseHeaders');
<del>var transformData = _dereq_('./../transformData');
<del>var urlIsSameOrigin = _dereq_('./../urlIsSameOrigin');
<del>var utils = _dereq_('./../utils');
<del>
<del>module.exports = function xhrAdapter(resolve, reject, config) {
<del> // Transform request data
<del> var data = transformData(
<del> config.data,
<del> config.headers,
<del> config.transformRequest
<del> );
<del>
<del> // Merge headers
<del> var headers = utils.merge(
<del> defaults.headers.common,
<del> defaults.headers[config.method] || {},
<del> config.headers || {}
<del> );
<del>
<del> // Create the request
<del> var request = new(XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP');
<del> request.open(config.method, buildUrl(config.url, config.params), true);
<del>
<del> // Listen for ready state
<del> request.onreadystatechange = function () {
<del> if (request && request.readyState === 4) {
<del> // Prepare the response
<del> var headers = parseHeaders(request.getAllResponseHeaders());
<del> var response = {
<del> data: transformData(
<del> request.responseText,
<del> headers,
<del> config.transformResponse
<del> ),
<del> status: request.status,
<del> headers: headers,
<del> config: config
<del> };
<del>
<del> // Resolve or reject the Promise based on the status
<del> (request.status >= 200 && request.status < 300
<del> ? resolve
<del> : reject)(
<del> response.data,
<del> response.status,
<del> response.headers,
<del> response.config
<del> );
<del>
<del> // Clean up request
<del> request = null;
<del> }
<del> };
<del>
<del> // Add xsrf header
<del> var xsrfValue = urlIsSameOrigin(config.url)
<del> ? cookies.read(config.xsrfCookieName || defaults.xsrfCookieName)
<del> : undefined;
<del> if (xsrfValue) {
<del> headers[config.xsrfHeaderName || defaults.xsrfHeaderName] = xsrfValue;
<del> }
<del>
<del> // Add headers to the request
<del> utils.forEach(headers, function (val, key) {
<del> // Remove Content-Type if data is undefined
<del> if (!data && key.toLowerCase() === 'content-type') {
<del> delete headers[key];
<del> }
<del> // Otherwise add header to the request
<del> else {
<del> request.setRequestHeader(key, val);
<del> }
<del> });
<del>
<del> // Add withCredentials to request if needed
<del> if (config.withCredentials) {
<del> request.withCredentials = true;
<del> }
<del>
<del> // Add responseType to request if needed
<del> if (config.responseType) {
<del> try {
<del> request.responseType = config.responseType;
<del> } catch (e) {
<del> if (request.responseType !== 'json') {
<del> throw e;
<del> }
<del> }
<del> }
<del>
<del> // Send the request
<del> request.send(data);
<del>};
<del>},{"./../buildUrl":4,"./../cookies":5,"./../defaults":6,"./../parseHeaders":7,"./../transformData":9,"./../urlIsSameOrigin":10,"./../utils":11}],3:[function(_dereq_,module,exports){
<del>(function (process){
<del>var Promise = _dereq_('es6-promise').Promise;
<del>var defaults = _dereq_('./defaults');
<del>var utils = _dereq_('./utils');
<del>var spread = _dereq_('./spread');
<del>
<del>var axios = module.exports = function axios(config) {
<del> config = utils.merge({
<del> method: 'get',
<del> transformRequest: defaults.transformRequest,
<del> transformResponse: defaults.transformResponse
<del> }, config);
<del>
<del> // Don't allow overriding defaults.withCredentials
<del> config.withCredentials = config.withCredentials || defaults.withCredentials;
<del>
<del> var promise = new Promise(function (resolve, reject) {
<del> try {
<del> // For browsers use XHR adapter
<del> if (typeof window !== 'undefined') {
<del> _dereq_('./adapters/xhr')(resolve, reject, config);
<del> }
<del> // For node use HTTP adapter
<del> else if (typeof process !== 'undefined') {
<del> _dereq_('./adapters/http')(resolve, reject, config);
<del> }
<del> } catch (e) {
<del> reject(e);
<del> }
<del> });
<del>
<del> // Provide alias for success
<del> promise.success = function success(fn) {
<del> promise.then(function(response) {
<del> fn(response);
<del> });
<del> return promise;
<del> };
<del>
<del> // Provide alias for error
<del> promise.error = function error(fn) {
<del> promise.then(null, function(response) {
<del> fn(response);
<del> });
<del> return promise;
<del> };
<del>
<del> return promise;
<del>};
<del>
<del>// Expose defaults
<del>axios.defaults = defaults;
<del>
<del>// Expose all/spread
<del>axios.all = Promise.all;
<del>axios.spread = spread;
<del>
<del>// Provide aliases for supported request methods
<del>createShortMethods('delete', 'get', 'head');
<del>createShortMethodsWithData('post', 'put', 'patch');
<del>
<del>function createShortMethods() {
<del> utils.forEach(arguments, function (method) {
<del> axios[method] = function (url, config) {
<del> return axios(utils.merge(config || {}, {
<del> method: method,
<del> url: url
<del> }));
<del> };
<del> });
<del>}
<del>
<del>function createShortMethodsWithData() {
<del> utils.forEach(arguments, function (method) {
<del> axios[method] = function (url, data, config) {
<del> return axios(utils.merge(config || {}, {
<del> method: method,
<del> url: url,
<del> data: data
<del> }));
<del> };
<del> });
<del>}
<del>}).call(this,_dereq_("/usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js"))
<del>},{"./adapters/http":2,"./adapters/xhr":2,"./defaults":6,"./spread":8,"./utils":11,"/usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":22,"es6-promise":12}],4:[function(_dereq_,module,exports){
<del>'use strict';
<del>
<del>var utils = _dereq_('./utils');
<del>
<del>function encode(val) {
<del> return encodeURIComponent(val).
<del> replace(/%40/gi, '@').
<del> replace(/%3A/gi, ':').
<del> replace(/%24/g, '$').
<del> replace(/%2C/gi, ',').
<del> replace(/%20/g, '+');
<del>}
<del>
<del>module.exports = function buildUrl(url, params) {
<del> if (!params) {
<del> return url;
<del> }
<del>
<del> var parts = [];
<del>
<del> utils.forEach(params, function (val, key) {
<del> if (val === null || typeof val === 'undefined') {
<del> return;
<del> }
<del> if (!utils.isArray(val)) {
<del> val = [val];
<del> }
<del>
<del> utils.forEach(val, function (v) {
<del> if (utils.isDate(v)) {
<del> v = v.toISOString();
<del> }
<del> else if (utils.isObject(v)) {
<del> v = JSON.stringify(v);
<del> }
<del> parts.push(encode(key) + '=' + encode(v));
<del> });
<del> });
<del>
<del> if (parts.length > 0) {
<del> url += (url.indexOf('?') === -1 ? '?' : '&') + parts.join('&');
<del> }
<del>
<del> return url;
<del>};
<del>},{"./utils":11}],5:[function(_dereq_,module,exports){
<del>'use strict';
<del>
<del>var utils = _dereq_('./utils');
<del>
<del>module.exports = {
<del> write: function write(name, value, expires, path, domain, secure) {
<del> var cookie = [];
<del> cookie.push(name + '=' + encodeURIComponent(value));
<del>
<del> if (utils.isNumber(expires)) {
<del> cookie.push('expires=' + new Date(expires).toGMTString());
<del> }
<del>
<del> if (utils.isString(path)) {
<del> cookie.push('path=' + path);
<del> }
<del>
<del> if (utils.isString(domain)) {
<del> cookie.push('domain=' + domain);
<del> }
<del>
<del> if (secure === true) {
<del> cookie.push('secure');
<del> }
<del>
<del> document.cookie = cookie.join('; ');
<del> },
<del>
<del> read: function read(name) {
<del> var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
<del> return (match ? decodeURIComponent(match[3]) : null);
<del> },
<del>
<del> remove: function remove(name) {
<del> this.write(name, '', Date.now() - 86400000);
<del> }
<del>};
<del>},{"./utils":11}],6:[function(_dereq_,module,exports){
<del>'use strict';
<del>
<del>var utils = _dereq_('./utils');
<del>
<del>var JSON_START = /^\s*(\[|\{[^\{])/;
<del>var JSON_END = /[\}\]]\s*$/;
<del>var PROTECTION_PREFIX = /^\)\]\}',?\n/;
<del>var CONTENT_TYPE_APPLICATION_JSON = {
<del> 'Content-Type': 'application/json;charset=utf-8'
<del>};
<del>
<del>module.exports = {
<del> transformRequest: [function (data) {
<del> return utils.isObject(data) &&
<del> !utils.isFile(data) &&
<del> !utils.isBlob(data) ?
<del> JSON.stringify(data) : null;
<del> }],
<del>
<del> transformResponse: [function (data) {
<del> if (typeof data === 'string') {
<del> data = data.replace(PROTECTION_PREFIX, '');
<del> if (JSON_START.test(data) && JSON_END.test(data)) {
<del> data = JSON.parse(data);
<del> }
<del> }
<del> return data;
<del> }],
<del>
<del> headers: {
<del> common: {
<del> 'Accept': 'application/json, text/plain, */*'
<del> },
<del> patch: utils.merge(CONTENT_TYPE_APPLICATION_JSON),
<del> post: utils.merge(CONTENT_TYPE_APPLICATION_JSON),
<del> put: utils.merge(CONTENT_TYPE_APPLICATION_JSON)
<del> },
<del>
<del> xsrfCookieName: 'XSRF-TOKEN',
<del> xsrfHeaderName: 'X-XSRF-TOKEN'
<del>};
<del>},{"./utils":11}],7:[function(_dereq_,module,exports){
<del>'use strict';
<del>
<del>var utils = _dereq_('./utils');
<del>
<del>/**
<del> * Parse headers into an object
<del> *
<del> * ```
<del> * Date: Wed, 27 Aug 2014 08:58:49 GMT
<del> * Content-Type: application/json
<del> * Connection: keep-alive
<del> * Transfer-Encoding: chunked
<del> * ```
<del> *
<del> * @param {String} headers Headers needing to be parsed
<del> * @returns {Object} Headers parsed into an object
<del> */
<del>module.exports = function parseHeaders(headers) {
<del> var parsed = {}, key, val, i;
<del>
<del> if (!headers) return parsed;
<del>
<del> utils.forEach(headers.split('\n'), function(line) {
<del> i = line.indexOf(':');
<del> key = utils.trim(line.substr(0, i)).toLowerCase();
<del> val = utils.trim(line.substr(i + 1));
<del>
<del> if (key) {
<del> parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
<del> }
<del> });
<del>
<del> return parsed;
<del>};
<del>},{"./utils":11}],8:[function(_dereq_,module,exports){
<del>/**
<del> * Syntactic sugar for invoking a function and expanding an array for arguments.
<del> *
<del> * Common use case would be to use `Function.prototype.apply`.
<del> *
<del> * ```js
<del> * function f(x, y, z) {}
<del> * var args = [1, 2, 3];
<del> * f.apply(null, args);
<del> * ```
<del> *
<del> * With `spread` this example can be re-written.
<del> *
<del> * ```js
<del> * spread(function(x, y, z) {})([1, 2, 3]);
<del> * ```
<del> *
<del> * @param {Function} callback
<del> * @returns {Function}
<del> */
<del>module.exports = function spread(callback) {
<del> return function (arr) {
<del> callback.apply(null, arr);
<del> };
<del>};
<del>},{}],9:[function(_dereq_,module,exports){
<del>'use strict';
<del>
<del>var utils = _dereq_('./utils');
<del>
<del>/**
<del> * Transform the data for a request or a response
<del> *
<del> * @param {Object|String} data The data to be transformed
<del> * @param {Array} headers The headers for the request or response
<del> * @param {Array|Function} fns A single function or Array of functions
<del> * @returns {*} The resulting transformed data
<del> */
<del>module.exports = function transformData(data, headers, fns) {
<del> utils.forEach(fns, function (fn) {
<del> data = fn(data, headers);
<del> });
<del>
<del> return data;
<del>};
<del>},{"./utils":11}],10:[function(_dereq_,module,exports){
<del>'use strict';
<del>
<del>var msie = /(msie|trident)/i.test(navigator.userAgent);
<del>var utils = _dereq_('./utils');
<del>var urlParsingNode = document.createElement('a');
<del>var originUrl = urlResolve(window.location.href);
<del>
<del>/**
<del> * Parse a URL to discover it's components
<del> *
<del> * @param {String} url The URL to be parsed
<del> * @returns {Object}
<del> */
<del>function urlResolve(url) {
<del> var href = url;
<del>
<del> if (msie) {
<del> // IE needs attribute set twice to normalize properties
<del> urlParsingNode.setAttribute('href', href);
<del> href = urlParsingNode.href;
<del> }
<del>
<del> urlParsingNode.setAttribute('href', href);
<del>
<del> // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
<del> return {
<del> href: urlParsingNode.href,
<del> protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
<del> host: urlParsingNode.host,
<del> search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
<del> hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
<del> hostname: urlParsingNode.hostname,
<del> port: urlParsingNode.port,
<del> pathname: (urlParsingNode.pathname.charAt(0) === '/')
<del> ? urlParsingNode.pathname
<del> : '/' + urlParsingNode.pathname
<del> };
<del>}
<del>
<del>/**
<del> * Determine if a URL shares the same origin as the current location
<del> *
<del> * @param {String} requestUrl The URL to test
<del> * @returns {boolean} True if URL shares the same origin, otherwise false
<del> */
<del>module.exports = function urlIsSameOrigin(requestUrl) {
<del> var parsed = (utils.isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
<del> return (parsed.protocol === originUrl.protocol &&
<del> parsed.host === originUrl.host);
<del>};
<del>},{"./utils":11}],11:[function(_dereq_,module,exports){
<del>// utils is a library of generic helper functions non-specific to axios
<del>
<del>var toString = Object.prototype.toString;
<del>
<del>/**
<del> * Determine if a value is an Array
<del> *
<del> * @param {Object} val The value to test
<del> * @returns {boolean} True if value is an Array, otherwise false
<del> */
<del>function isArray(val) {
<del> return toString.call(val) === '[object Array]';
<del>}
<del>
<del>/**
<del> * Determine if a value is a String
<del> *
<del> * @param {Object} val The value to test
<del> * @returns {boolean} True if value is a String, otherwise false
<del> */
<del>function isString(val) {
<del> return typeof val === 'string';
<del>}
<del>
<del>/**
<del> * Determine if a value is a Number
<del> *
<del> * @param {Object} val The value to test
<del> * @returns {boolean} True if value is a Number, otherwise false
<del> */
<del>function isNumber(val) {
<del> return typeof val === 'number';
<del>}
<del>
<del>/**
<del> * Determine if a value is an Object
<del> *
<del> * @param {Object} val The value to test
<del> * @returns {boolean} True if value is an Object, otherwise false
<del> */
<del>function isObject(val) {
<del> return val !== null && typeof val === 'object';
<del>}
<del>
<del>/**
<del> * Determine if a value is a Date
<del> *
<del> * @param {Object} val The value to test
<del> * @returns {boolean} True if value is a Date, otherwise false
<del> */
<del>function isDate(val) {
<del> return toString.call(val) === '[object Date]';
<del>}
<del>
<del>/**
<del> * Determine if a value is a File
<del> *
<del> * @param {Object} val The value to test
<del> * @returns {boolean} True if value is a File, otherwise false
<del> */
<del>function isFile(val) {
<del> return toString.call(val) === '[object File]';
<del>}
<del>
<del>/**
<del> * Determine if a value is a Blob
<del> *
<del> * @param {Object} val The value to test
<del> * @returns {boolean} True if value is a Blob, otherwise false
<del> */
<del>function isBlob(val) {
<del> return toString.call(val) === '[object Blob]';
<del>}
<del>
<del>/**
<del> * Trim excess whitespace off the beginning and end of a string
<del> *
<del> * @param {String} str The String to trim
<del> * @returns {String} The String freed of excess whitespace
<del> */
<del>function trim(str) {
<del> return str.replace(/^\s*/, '').replace(/\s*$/, '');
<del>}
<del>
<del>/**
<del> * Iterate over an Array or an Object invoking a function for each item.
<del> *
<del> * If `obj` is an Array or arguments callback will be called passing
<del> * the value, index, and complete array for each item.
<del> *
<del> * If 'obj' is an Object callback will be called passing
<del> * the value, key, and complete object for each property.
<del> *
<del> * @param {Object|Array} obj The object to iterate
<del> * @param {Function} fn The callback to invoke for each item
<del> */
<del>function forEach(obj, fn) {
<del> // Don't bother if no value provided
<del> if (obj === null || typeof obj === 'undefined') {
<del> return;
<del> }
<del>
<del> // Check if obj is array-like
<del> var isArray = obj.constructor === Array || typeof obj.callee === 'function';
<del>
<del> // Force an array if not already something iterable
<del> if (typeof obj !== 'object' && !isArray) {
<del> obj = [obj];
<del> }
<del>
<del> // Iterate over array values
<del> if (isArray) {
<del> for (var i=0, l=obj.length; i<l; i++) {
<del> fn.call(null, obj[i], i, obj);
<del> }
<del> }
<del> // Iterate over object keys
<del> else {
<del> for (var key in obj) {
<del> if (obj.hasOwnProperty(key)) {
<del> fn.call(null, obj[key], key, obj);
<del> }
<del> }
<del> }
<del>}
<del>
<del>/**
<del> * Accepts varargs expecting each argument to be an object, then
<del> * immutably merges the properties of each object and returns result.
<del> *
<del> * When multiple objects contain the same key the later object in
<del> * the arguments list will take precedence.
<del> *
<del> * Example:
<del> *
<del> * ```js
<del> * var result = merge({foo: 123}, {foo: 456});
<del> * console.log(result.foo); // outputs 456
<del> * ```
<del> *
<del> * @param {Object} obj1 Object to merge
<del> * @returns {Object} Result of all merge properties
<del> */
<del>function merge(obj1/*, obj2, obj3, ...*/) {
<del> var result = {};
<del> forEach(arguments, function (obj) {
<del> forEach(obj, function (val, key) {
<del> result[key] = val;
<del> });
<del> });
<del> return result;
<del>}
<del>
<del>module.exports = {
<del> isArray: isArray,
<del> isString: isString,
<del> isNumber: isNumber,
<del> isObject: isObject,
<del> isDate: isDate,
<del> isFile: isFile,
<del> isBlob: isBlob,
<del> forEach: forEach,
<del> merge: merge,
<del> trim: trim
<del>};
<del>},{}],12:[function(_dereq_,module,exports){
<del>"use strict";
<del>var Promise = _dereq_("./promise/promise").Promise;
<del>var polyfill = _dereq_("./promise/polyfill").polyfill;
<del>exports.Promise = Promise;
<del>exports.polyfill = polyfill;
<del>},{"./promise/polyfill":16,"./promise/promise":17}],13:[function(_dereq_,module,exports){
<del>"use strict";
<del>/* global toString */
<del>
<del>var isArray = _dereq_("./utils").isArray;
<del>var isFunction = _dereq_("./utils").isFunction;
<del>
<del>/**
<del> Returns a promise that is fulfilled when all the given promises have been
<del> fulfilled, or rejected if any of them become rejected. The return promise
<del> is fulfilled with an array that gives all the values in the order they were
<del> passed in the `promises` array argument.
<del>
<del> Example:
<del>
<del> ```javascript
<del> var promise1 = RSVP.resolve(1);
<del> var promise2 = RSVP.resolve(2);
<del> var promise3 = RSVP.resolve(3);
<del> var promises = [ promise1, promise2, promise3 ];
<del>
<del> RSVP.all(promises).then(function(array){
<del> // The array here would be [ 1, 2, 3 ];
<del> });
<del> ```
<del>
<del> If any of the `promises` given to `RSVP.all` are rejected, the first promise
<del> that is rejected will be given as an argument to the returned promises's
<del> rejection handler. For example:
<del>
<del> Example:
<del>
<del> ```javascript
<del> var promise1 = RSVP.resolve(1);
<del> var promise2 = RSVP.reject(new Error("2"));
<del> var promise3 = RSVP.reject(new Error("3"));
<del> var promises = [ promise1, promise2, promise3 ];
<del>
<del> RSVP.all(promises).then(function(array){
<del> // Code here never runs because there are rejected promises!
<del> }, function(error) {
<del> // error.message === "2"
<del> });
<del> ```
<del>
<del> @method all
<del> @for RSVP
<del> @param {Array} promises
<del> @param {String} label
<del> @return {Promise} promise that is fulfilled when all `promises` have been
<del> fulfilled, or rejected if any of them become rejected.
<del>*/
<del>function all(promises) {
<del> /*jshint validthis:true */
<del> var Promise = this;
<del>
<del> if (!isArray(promises)) {
<del> throw new TypeError('You must pass an array to all.');
<del> }
<del>
<del> return new Promise(function(resolve, reject) {
<del> var results = [], remaining = promises.length,
<del> promise;
<del>
<del> if (remaining === 0) {
<del> resolve([]);
<del> }
<del>
<del> function resolver(index) {
<del> return function(value) {
<del> resolveAll(index, value);
<del> };
<del> }
<del>
<del> function resolveAll(index, value) {
<del> results[index] = value;
<del> if (--remaining === 0) {
<del> resolve(results);
<del> }
<del> }
<del>
<del> for (var i = 0; i < promises.length; i++) {
<del> promise = promises[i];
<del>
<del> if (promise && isFunction(promise.then)) {
<del> promise.then(resolver(i), reject);
<del> } else {
<del> resolveAll(i, promise);
<del> }
<del> }
<del> });
<del>}
<del>
<del>exports.all = all;
<del>},{"./utils":21}],14:[function(_dereq_,module,exports){
<del>(function (process,global){
<del>"use strict";
<del>var browserGlobal = (typeof window !== 'undefined') ? window : {};
<del>var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
<del>var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this);
<del>
<del>// node
<del>function useNextTick() {
<del> return function() {
<del> process.nextTick(flush);
<del> };
<del>}
<del>
<del>function useMutationObserver() {
<del> var iterations = 0;
<del> var observer = new BrowserMutationObserver(flush);
<del> var node = document.createTextNode('');
<del> observer.observe(node, { characterData: true });
<del>
<del> return function() {
<del> node.data = (iterations = ++iterations % 2);
<del> };
<del>}
<del>
<del>function useSetTimeout() {
<del> return function() {
<del> local.setTimeout(flush, 1);
<del> };
<del>}
<del>
<del>var queue = [];
<del>function flush() {
<del> for (var i = 0; i < queue.length; i++) {
<del> var tuple = queue[i];
<del> var callback = tuple[0], arg = tuple[1];
<del> callback(arg);
<del> }
<del> queue = [];
<del>}
<del>
<del>var scheduleFlush;
<del>
<del>// Decide what async method to use to triggering processing of queued callbacks:
<del>if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
<del> scheduleFlush = useNextTick();
<del>} else if (BrowserMutationObserver) {
<del> scheduleFlush = useMutationObserver();
<del>} else {
<del> scheduleFlush = useSetTimeout();
<del>}
<del>
<del>function asap(callback, arg) {
<del> var length = queue.push([callback, arg]);
<del> if (length === 1) {
<del> // If length is 1, that means that we need to schedule an async flush.
<del> // If additional callbacks are queued before the queue is flushed, they
<del> // will be processed by this flush that we are scheduling.
<del> scheduleFlush();
<del> }
<del>}
<del>
<del>exports.asap = asap;
<del>}).call(this,_dereq_("/usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
<del>},{"/usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":22}],15:[function(_dereq_,module,exports){
<del>"use strict";
<del>var config = {
<del> instrument: false
<del>};
<del>
<del>function configure(name, value) {
<del> if (arguments.length === 2) {
<del> config[name] = value;
<del> } else {
<del> return config[name];
<del> }
<del>}
<del>
<del>exports.config = config;
<del>exports.configure = configure;
<del>},{}],16:[function(_dereq_,module,exports){
<del>(function (global){
<del>"use strict";
<del>/*global self*/
<del>var RSVPPromise = _dereq_("./promise").Promise;
<del>var isFunction = _dereq_("./utils").isFunction;
<del>
<del>function polyfill() {
<del> var local;
<del>
<del> if (typeof global !== 'undefined') {
<del> local = global;
<del> } else if (typeof window !== 'undefined' && window.document) {
<del> local = window;
<del> } else {
<del> local = self;
<del> }
<del>
<del> var es6PromiseSupport =
<del> "Promise" in local &&
<del> // Some of these methods are missing from
<del> // Firefox/Chrome experimental implementations
<del> "resolve" in local.Promise &&
<del> "reject" in local.Promise &&
<del> "all" in local.Promise &&
<del> "race" in local.Promise &&
<del> // Older version of the spec had a resolver object
<del> // as the arg rather than a function
<del> (function() {
<del> var resolve;
<del> new local.Promise(function(r) { resolve = r; });
<del> return isFunction(resolve);
<del> }());
<del>
<del> if (!es6PromiseSupport) {
<del> local.Promise = RSVPPromise;
<del> }
<del>}
<del>
<del>exports.polyfill = polyfill;
<del>}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
<del>},{"./promise":17,"./utils":21}],17:[function(_dereq_,module,exports){
<del>"use strict";
<del>var config = _dereq_("./config").config;
<del>var configure = _dereq_("./config").configure;
<del>var objectOrFunction = _dereq_("./utils").objectOrFunction;
<del>var isFunction = _dereq_("./utils").isFunction;
<del>var now = _dereq_("./utils").now;
<del>var all = _dereq_("./all").all;
<del>var race = _dereq_("./race").race;
<del>var staticResolve = _dereq_("./resolve").resolve;
<del>var staticReject = _dereq_("./reject").reject;
<del>var asap = _dereq_("./asap").asap;
<del>
<del>var counter = 0;
<del>
<del>config.async = asap; // default async is asap;
<del>
<del>function Promise(resolver) {
<del> if (!isFunction(resolver)) {
<del> throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
<del> }
<del>
<del> if (!(this instanceof Promise)) {
<del> throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
<del> }
<del>
<del> this._subscribers = [];
<del>
<del> invokeResolver(resolver, this);
<del>}
<del>
<del>function invokeResolver(resolver, promise) {
<del> function resolvePromise(value) {
<del> resolve(promise, value);
<del> }
<del>
<del> function rejectPromise(reason) {
<del> reject(promise, reason);
<del> }
<del>
<del> try {
<del> resolver(resolvePromise, rejectPromise);
<del> } catch(e) {
<del> rejectPromise(e);
<del> }
<del>}
<del>
<del>function invokeCallback(settled, promise, callback, detail) {
<del> var hasCallback = isFunction(callback),
<del> value, error, succeeded, failed;
<del>
<del> if (hasCallback) {
<del> try {
<del> value = callback(detail);
<del> succeeded = true;
<del> } catch(e) {
<del> failed = true;
<del> error = e;
<del> }
<del> } else {
<del> value = detail;
<del> succeeded = true;
<del> }
<del>
<del> if (handleThenable(promise, value)) {
<del> return;
<del> } else if (hasCallback && succeeded) {
<del> resolve(promise, value);
<del> } else if (failed) {
<del> reject(promise, error);
<del> } else if (settled === FULFILLED) {
<del> resolve(promise, value);
<del> } else if (settled === REJECTED) {
<del> reject(promise, value);
<del> }
<del>}
<del>
<del>var PENDING = void 0;
<del>var SEALED = 0;
<del>var FULFILLED = 1;
<del>var REJECTED = 2;
<del>
<del>function subscribe(parent, child, onFulfillment, onRejection) {
<del> var subscribers = parent._subscribers;
<del> var length = subscribers.length;
<del>
<del> subscribers[length] = child;
<del> subscribers[length + FULFILLED] = onFulfillment;
<del> subscribers[length + REJECTED] = onRejection;
<del>}
<del>
<del>function publish(promise, settled) {
<del> var child, callback, subscribers = promise._subscribers, detail = promise._detail;
<del>
<del> for (var i = 0; i < subscribers.length; i += 3) {
<del> child = subscribers[i];
<del> callback = subscribers[i + settled];
<del>
<del> invokeCallback(settled, child, callback, detail);
<del> }
<del>
<del> promise._subscribers = null;
<del>}
<del>
<del>Promise.prototype = {
<del> constructor: Promise,
<del>
<del> _state: undefined,
<del> _detail: undefined,
<del> _subscribers: undefined,
<del>
<del> then: function(onFulfillment, onRejection) {
<del> var promise = this;
<del>
<del> var thenPromise = new this.constructor(function() {});
<del>
<del> if (this._state) {
<del> var callbacks = arguments;
<del> config.async(function invokePromiseCallback() {
<del> invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
<del> });
<del> } else {
<del> subscribe(this, thenPromise, onFulfillment, onRejection);
<del> }
<del>
<del> return thenPromise;
<del> },
<del>
<del> 'catch': function(onRejection) {
<del> return this.then(null, onRejection);
<del> }
<del>};
<del>
<del>Promise.all = all;
<del>Promise.race = race;
<del>Promise.resolve = staticResolve;
<del>Promise.reject = staticReject;
<del>
<del>function handleThenable(promise, value) {
<del> var then = null,
<del> resolved;
<del>
<del> try {
<del> if (promise === value) {
<del> throw new TypeError("A promises callback cannot return that same promise.");
<del> }
<del>
<del> if (objectOrFunction(value)) {
<del> then = value.then;
<del>
<del> if (isFunction(then)) {
<del> then.call(value, function(val) {
<del> if (resolved) { return true; }
<del> resolved = true;
<del>
<del> if (value !== val) {
<del> resolve(promise, val);
<del> } else {
<del> fulfill(promise, val);
<del> }
<del> }, function(val) {
<del> if (resolved) { return true; }
<del> resolved = true;
<del>
<del> reject(promise, val);
<del> });
<del>
<del> return true;
<del> }
<del> }
<del> } catch (error) {
<del> if (resolved) { return true; }
<del> reject(promise, error);
<del> return true;
<del> }
<del>
<del> return false;
<del>}
<del>
<del>function resolve(promise, value) {
<del> if (promise === value) {
<del> fulfill(promise, value);
<del> } else if (!handleThenable(promise, value)) {
<del> fulfill(promise, value);
<del> }
<del>}
<del>
<del>function fulfill(promise, value) {
<del> if (promise._state !== PENDING) { return; }
<del> promise._state = SEALED;
<del> promise._detail = value;
<del>
<del> config.async(publishFulfillment, promise);
<del>}
<del>
<del>function reject(promise, reason) {
<del> if (promise._state !== PENDING) { return; }
<del> promise._state = SEALED;
<del> promise._detail = reason;
<del>
<del> config.async(publishRejection, promise);
<del>}
<del>
<del>function publishFulfillment(promise) {
<del> publish(promise, promise._state = FULFILLED);
<del>}
<del>
<del>function publishRejection(promise) {
<del> publish(promise, promise._state = REJECTED);
<del>}
<del>
<del>exports.Promise = Promise;
<del>},{"./all":13,"./asap":14,"./config":15,"./race":18,"./reject":19,"./resolve":20,"./utils":21}],18:[function(_dereq_,module,exports){
<del>"use strict";
<del>/* global toString */
<del>var isArray = _dereq_("./utils").isArray;
<del>
<del>/**
<del> `RSVP.race` allows you to watch a series of promises and act as soon as the
<del> first promise given to the `promises` argument fulfills or rejects.
<del>
<del> Example:
<del>
<del> ```javascript
<del> var promise1 = new RSVP.Promise(function(resolve, reject){
<del> setTimeout(function(){
<del> resolve("promise 1");
<del> }, 200);
<del> });
<del>
<del> var promise2 = new RSVP.Promise(function(resolve, reject){
<del> setTimeout(function(){
<del> resolve("promise 2");
<del> }, 100);
<del> });
<del>
<del> RSVP.race([promise1, promise2]).then(function(result){
<del> // result === "promise 2" because it was resolved before promise1
<del> // was resolved.
<del> });
<del> ```
<del>
<del> `RSVP.race` is deterministic in that only the state of the first completed
<del> promise matters. For example, even if other promises given to the `promises`
<del> array argument are resolved, but the first completed promise has become
<del> rejected before the other promises became fulfilled, the returned promise
<del> will become rejected:
<del>
<del> ```javascript
<del> var promise1 = new RSVP.Promise(function(resolve, reject){
<del> setTimeout(function(){
<del> resolve("promise 1");
<del> }, 200);
<del> });
<del>
<del> var promise2 = new RSVP.Promise(function(resolve, reject){
<del> setTimeout(function(){
<del> reject(new Error("promise 2"));
<del> }, 100);
<del> });
<del>
<del> RSVP.race([promise1, promise2]).then(function(result){
<del> // Code here never runs because there are rejected promises!
<del> }, function(reason){
<del> // reason.message === "promise2" because promise 2 became rejected before
<del> // promise 1 became fulfilled
<del> });
<del> ```
<del>
<del> @method race
<del> @for RSVP
<del> @param {Array} promises array of promises to observe
<del> @param {String} label optional string for describing the promise returned.
<del> Useful for tooling.
<del> @return {Promise} a promise that becomes fulfilled with the value the first
<del> completed promises is resolved with if the first completed promise was
<del> fulfilled, or rejected with the reason that the first completed promise
<del> was rejected with.
<del>*/
<del>function race(promises) {
<del> /*jshint validthis:true */
<del> var Promise = this;
<del>
<del> if (!isArray(promises)) {
<del> throw new TypeError('You must pass an array to race.');
<del> }
<del> return new Promise(function(resolve, reject) {
<del> var results = [], promise;
<del>
<del> for (var i = 0; i < promises.length; i++) {
<del> promise = promises[i];
<del>
<del> if (promise && typeof promise.then === 'function') {
<del> promise.then(resolve, reject);
<del> } else {
<del> resolve(promise);
<del> }
<del> }
<del> });
<del>}
<del>
<del>exports.race = race;
<del>},{"./utils":21}],19:[function(_dereq_,module,exports){
<del>"use strict";
<del>/**
<del> `RSVP.reject` returns a promise that will become rejected with the passed
<del> `reason`. `RSVP.reject` is essentially shorthand for the following:
<del>
<del> ```javascript
<del> var promise = new RSVP.Promise(function(resolve, reject){
<del> reject(new Error('WHOOPS'));
<del> });
<del>
<del> promise.then(function(value){
<del> // Code here doesn't run because the promise is rejected!
<del> }, function(reason){
<del> // reason.message === 'WHOOPS'
<del> });
<del> ```
<del>
<del> Instead of writing the above, your code now simply becomes the following:
<del>
<del> ```javascript
<del> var promise = RSVP.reject(new Error('WHOOPS'));
<del>
<del> promise.then(function(value){
<del> // Code here doesn't run because the promise is rejected!
<del> }, function(reason){
<del> // reason.message === 'WHOOPS'
<del> });
<del> ```
<del>
<del> @method reject
<del> @for RSVP
<del> @param {Any} reason value that the returned promise will be rejected with.
<del> @param {String} label optional string for identifying the returned promise.
<del> Useful for tooling.
<del> @return {Promise} a promise that will become rejected with the given
<del> `reason`.
<del>*/
<del>function reject(reason) {
<del> /*jshint validthis:true */
<del> var Promise = this;
<del>
<del> return new Promise(function (resolve, reject) {
<del> reject(reason);
<del> });
<del>}
<del>
<del>exports.reject = reject;
<del>},{}],20:[function(_dereq_,module,exports){
<del>"use strict";
<del>function resolve(value) {
<del> /*jshint validthis:true */
<del> if (value && typeof value === 'object' && value.constructor === this) {
<del> return value;
<del> }
<del>
<del> var Promise = this;
<del>
<del> return new Promise(function(resolve) {
<del> resolve(value);
<del> });
<del>}
<del>
<del>exports.resolve = resolve;
<del>},{}],21:[function(_dereq_,module,exports){
<del>"use strict";
<del>function objectOrFunction(x) {
<del> return isFunction(x) || (typeof x === "object" && x !== null);
<del>}
<del>
<del>function isFunction(x) {
<del> return typeof x === "function";
<del>}
<del>
<del>function isArray(x) {
<del> return Object.prototype.toString.call(x) === "[object Array]";
<del>}
<del>
<del>// Date.now is not available in browsers < IE9
<del>// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility
<del>var now = Date.now || function() { return new Date().getTime(); };
<del>
<del>
<del>exports.objectOrFunction = objectOrFunction;
<del>exports.isFunction = isFunction;
<del>exports.isArray = isArray;
<del>exports.now = now;
<del>},{}],22:[function(_dereq_,module,exports){
<del>// shim for using process in browser
<del>
<del>var process = module.exports = {};
<del>
<del>process.nextTick = (function () {
<del> var canSetImmediate = typeof window !== 'undefined'
<del> && window.setImmediate;
<del> var canPost = typeof window !== 'undefined'
<del> && window.postMessage && window.addEventListener
<del> ;
<del>
<del> if (canSetImmediate) {
<del> return function (f) { return window.setImmediate(f) };
<del> }
<del>
<del> if (canPost) {
<del> var queue = [];
<del> window.addEventListener('message', function (ev) {
<del> var source = ev.source;
<del> if ((source === window || source === null) && ev.data === 'process-tick') {
<del> ev.stopPropagation();
<del> if (queue.length > 0) {
<del> var fn = queue.shift();
<del> fn();
<del> }
<del> }
<del> }, true);
<del>
<del> return function nextTick(fn) {
<del> queue.push(fn);
<del> window.postMessage('process-tick', '*');
<del> };
<del> }
<del>
<del> return function nextTick(fn) {
<del> setTimeout(fn, 0);
<del> };
<del>})();
<del>
<del>process.title = 'browser';
<del>process.browser = true;
<del>process.env = {};
<del>process.argv = [];
<del>
<del>function noop() {}
<del>
<del>process.on = noop;
<del>process.once = noop;
<del>process.off = noop;
<del>process.emit = noop;
<del>
<del>process.binding = function (name) {
<del> throw new Error('process.binding is not supported');
<del>}
<del>
<del>// TODO(shtylman)
<del>process.cwd = function () { return '/' };
<del>process.chdir = function (dir) {
<del> throw new Error('process.chdir is not supported');
<del>};
<del>
<del>},{}]},{},[1])
<del>(1)
<del>});
<ide>\ No newline at end of file | 1 |
Javascript | Javascript | remove duplicate code in test | b85c5cd1884924d7fe4389121736eaa516ed8e40 | <ide><path>packages/react-dom/src/__tests__/ReactDOMRoot-test.js
<ide> describe('ReactDOMRoot', () => {
<ide> expire = function(ms) {
<ide> now += ms;
<ide> };
<del> global.performance = {
<del> now() {
<del> return now;
<del> },
<del> };
<ide>
<ide> jest.resetModules();
<ide> React = require('react'); | 1 |
Ruby | Ruby | improve doc consistency | 81f110657b2a59b76926b4b3d89f685420e32a0e | <ide><path>activesupport/lib/active_support/multibyte/chars.rb
<ide> def reverse
<ide> chars(Unicode.unpack_graphemes(@wrapped_string).reverse.flatten.pack('U*'))
<ide> end
<ide>
<del> # Limit the byte size of the string to a number of bytes without breaking characters. Usable
<add> # Limits the byte size of the string to a number of bytes without breaking characters. Usable
<ide> # when the storage for a string is limited for some reason.
<ide> #
<ide> # Example:
<ide> def limit(limit)
<ide> slice(0...translate_offset(limit))
<ide> end
<ide>
<del> # Convert characters in the string to uppercase.
<add> # Converts characters in the string to uppercase.
<ide> #
<ide> # Example:
<ide> # 'Laurent, où sont les tests ?'.mb_chars.upcase.to_s # => "LAURENT, OÙ SONT LES TESTS ?"
<ide> def upcase
<ide> chars Unicode.upcase(@wrapped_string)
<ide> end
<ide>
<del> # Convert characters in the string to lowercase.
<add> # Converts characters in the string to lowercase.
<ide> #
<ide> # Example:
<ide> # 'VĚDA A VÝZKUM'.mb_chars.downcase.to_s # => "věda a výzkum" | 1 |
Python | Python | extend `nested_xxx` functions to mappings/dicts. | 335f9bcd3457d2c4c9c6d9aeb2dae06ab20a7b56 | <ide><path>src/transformers/trainer_pt_utils.py
<ide> def numpy_pad_and_concatenate(array1, array2, padding_index=-100):
<ide> def nested_concat(tensors, new_tensors, padding_index=-100):
<ide> """
<ide> Concat the `new_tensors` to `tensors` on the first dim and pad them on the second if needed. Works for tensors or
<del> nested list/tuples of tensors.
<add> nested list/tuples/dict of tensors.
<ide> """
<ide> assert type(tensors) == type(
<ide> new_tensors
<ide> def nested_concat(tensors, new_tensors, padding_index=-100):
<ide> return type(tensors)(nested_concat(t, n, padding_index=padding_index) for t, n in zip(tensors, new_tensors))
<ide> elif isinstance(tensors, torch.Tensor):
<ide> return torch_pad_and_concatenate(tensors, new_tensors, padding_index=padding_index)
<add> elif isinstance(tensors, Mapping):
<add> return type(tensors)(
<add> {k: nested_concat(t, new_tensors[k], padding_index=padding_index) for k, t in tensors.items()}
<add> )
<ide> elif isinstance(tensors, np.ndarray):
<ide> return numpy_pad_and_concatenate(tensors, new_tensors, padding_index=padding_index)
<ide> else:
<ide> def find_batch_size(tensors):
<ide>
<ide>
<ide> def nested_numpify(tensors):
<del> "Numpify `tensors` (even if it's a nested list/tuple of tensors)."
<add> "Numpify `tensors` (even if it's a nested list/tuple/dict of tensors)."
<ide> if isinstance(tensors, (list, tuple)):
<ide> return type(tensors)(nested_numpify(t) for t in tensors)
<add> if isinstance(tensors, Mapping):
<add> return type(tensors)({k: nested_numpify(t) for k, t in tensors.items()})
<add>
<ide> t = tensors.cpu()
<ide> if t.dtype == torch.bfloat16:
<ide> # As of Numpy 1.21.4, NumPy does not support bfloat16 (see
<ide> def nested_numpify(tensors):
<ide>
<ide>
<ide> def nested_detach(tensors):
<del> "Detach `tensors` (even if it's a nested list/tuple of tensors)."
<add> "Detach `tensors` (even if it's a nested list/tuple/dict of tensors)."
<ide> if isinstance(tensors, (list, tuple)):
<ide> return type(tensors)(nested_detach(t) for t in tensors)
<add> elif isinstance(tensors, Mapping):
<add> return type(tensors)({k: nested_detach(t) for k, t in tensors.items()})
<ide> return tensors.detach()
<ide>
<ide>
<ide> def nested_xla_mesh_reduce(tensors, name):
<ide>
<ide> if isinstance(tensors, (list, tuple)):
<ide> return type(tensors)(nested_xla_mesh_reduce(t, f"{name}_{i}") for i, t in enumerate(tensors))
<add> if isinstance(tensors, Mapping):
<add> return type(tensors)(
<add> {k: nested_xla_mesh_reduce(t, f"{name}_{i}") for i, (k, t) in enumerate(tensors.items())}
<add> )
<add>
<ide> tensors = atleast_1d(tensors)
<ide> return xm.mesh_reduce(name, tensors, torch.cat)
<ide> else:
<ide> def expand_like(arrays, new_seq_length, padding_index=-100):
<ide>
<ide>
<ide> def nested_truncate(tensors, limit):
<del> "Truncate `tensors` at `limit` (even if it's a nested list/tuple of tensors)."
<add> "Truncate `tensors` at `limit` (even if it's a nested list/tuple/dict of tensors)."
<ide> if isinstance(tensors, (list, tuple)):
<ide> return type(tensors)(nested_truncate(t, limit) for t in tensors)
<add> if isinstance(tensors, Mapping):
<add> return type(tensors)({k: nested_truncate(t, limit) for k, t in tensors.items()})
<add>
<ide> return tensors[:limit]
<ide>
<ide> | 1 |
PHP | PHP | apply fixes from styleci | 26471a48ed27178151fe3ccf263d9e24661dee52 | <ide><path>src/Illuminate/Mail/PendingMail.php
<ide> protected function fill(MailableContract $mailable)
<ide> if ($this->locale) {
<ide> $mailable->locale($this->locale);
<ide> }
<del> });
<add> });
<ide> }
<ide> } | 1 |
PHP | PHP | depreciate the elixir function | 86dbb2500308c7cf529daf829436ce1bced88d4c | <ide><path>src/Illuminate/Foundation/helpers.php
<ide> function dispatch_now($job, $handler = null)
<ide> * @return string
<ide> *
<ide> * @throws \InvalidArgumentException
<add> *
<add> * @deprecated Use Laravel Mix instead.
<ide> */
<ide> function elixir($file, $buildDirectory = 'build')
<ide> { | 1 |
Ruby | Ruby | initialize instance variables | 6a3d4695f043031b73b1f5bc218fbeeae9fff771 | <ide><path>actionpack/lib/action_dispatch/http/parameters.rb
<ide> module ActionDispatch
<ide> module Http
<ide> module Parameters
<add> def initialize(env)
<add> super
<add> @symbolized_path_params = nil
<add> end
<add>
<ide> # Returns both GET and POST \parameters in a single hash.
<ide> def parameters
<ide> @env["action_dispatch.request.parameters"] ||= begin
<ide><path>actionpack/lib/action_dispatch/http/request.rb
<ide> def #{env.sub(/^HTTP_/n, '').downcase} # def accept_charset
<ide> METHOD
<ide> end
<ide>
<add> def initialize(env)
<add> super
<add> @method = nil
<add> @request_method = nil
<add> @remote_ip = nil
<add> @original_fullpath = nil
<add> @fullpath = nil
<add> @ip = nil
<add> @uuid = nil
<add> end
<add>
<ide> def key?(key)
<ide> @env.key?(key)
<ide> end
<ide><path>actionpack/lib/action_dispatch/http/url.rb
<ide> def host_or_subdomain_and_domain(options)
<ide> end
<ide> end
<ide>
<add> def initialize(env)
<add> super
<add> @protocol = nil
<add> @port = nil
<add> end
<add>
<ide> # Returns the complete URL used for this request.
<ide> def url
<ide> protocol + host_with_port + fullpath | 3 |
Python | Python | fix incorrect matcher test | 2bccad88152272af36c13973098695efd52a6bdd | <ide><path>spacy/tests/regression/test_issue1450.py
<ide> ('a b', 0, 2),
<ide> ('a c', 0, 1),
<ide> ('a b c', 0, 2),
<del> ('a b b c', 0, 2),
<del> ('a b b', 0, 2),
<add> ('a b b c', 0, 3),
<add> ('a b b', 0, 3),
<ide> ]
<ide> )
<ide> def test_issue1450_matcher_end_zero_plus(string, start, end):
<ide> def test_issue1450_matcher_end_zero_plus(string, start, end):
<ide> if start is None or end is None:
<ide> assert matches == []
<ide>
<add> print(matches)
<ide> assert matches[-1][1] == start
<ide> assert matches[-1][2] == end | 1 |
PHP | PHP | fix missing imports | 5abfd3de2124e974c7da2e0d819b035cdcfb84fe | <ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> use Cake\Core\Exception\Exception;
<ide> use Cake\Database\Schema\TableSchema;
<ide> use Cake\Database\Schema\TableSchemaAwareInterface;
<add>use Cake\Datasource\ConnectionInterface;
<ide> use Cake\Datasource\ConnectionManager;
<add>use Cake\Datasource\FixtureInterface;
<add>use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Inflector;
<ide> use PDOException;
<ide> use UnexpectedValueException;
<ide> protected function _loadFixtures(TestCase $test): void
<ide> * Runs the drop and create commands on the fixtures if necessary.
<ide> *
<ide> * @param \Cake\Datasource\FixtureInterface $fixture the fixture object to create
<del> * @param \Cake\Database\Connection $db The Connection object instance to use
<add> * @param \Cake\Database\ConnectionInterface $db The Connection object instance to use
<ide> * @param array $sources The existing tables in the datasource.
<ide> * @param bool $drop whether drop the fixture if it is already created or not
<ide> * @return void
<ide> */
<del> protected function _setupTable(FixtureInterface $fixture, Connection $db, array $sources, bool $drop = true): void
<add> protected function _setupTable(FixtureInterface $fixture, ConnectionInterface $db, array $sources, bool $drop = true): void
<ide> {
<ide> $configName = $db->configName();
<ide> $isFixtureSetup = $this->isFixtureSetup($configName, $fixture); | 1 |
Python | Python | fix typo when getting system32 location | df2acae5a4bcbc4c76ebbeefcfb07f59c9ee2914 | <ide><path>numpy/distutils/mingw32ccompiler.py
<ide> def find_python_dll():
<ide> lib_dirs = []
<ide> lib_dirs.append(os.path.join(sys.prefix, 'lib'))
<ide> try:
<del> lib_dirs.append(os.path.join(os.environ['SYSTEM_ROOT'], 'system32'))
<add> lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'system32'))
<ide> except KeyError:
<ide> pass
<ide> | 1 |
Python | Python | correct an issue while getting core number | fcf7f31a28bdee2058a9ce6bd9d7051a83a92b4a | <ide><path>glances/__init__.py
<ide> # Global name
<ide> # Version should start and end with a numerical char
<ide> # See https://packaging.python.org/specifications/core-metadata/#version
<del>__version__ = '3.1.8b4'
<add>__version__ = '3.1.8b5'
<ide> __author__ = 'Nicolas Hennion <nicolas@nicolargo.com>'
<ide> __license__ = 'LGPLv3'
<ide>
<ide><path>glances/plugins/glances_core.py
<ide> def __init__(self, args=None, config=None):
<ide> # The core number is displayed by the load plugin
<ide> self.display_curse = False
<ide>
<del> @GlancesPlugin._check_decorator
<add> # Do *NOT* uncomment the following line
<add> # @GlancesPlugin._check_decorator
<ide> @GlancesPlugin._log_result_decorator
<ide> def update(self):
<ide> """Update core stats.
<ide><path>glances/plugins/glances_load.py
<ide> def __init__(self, args=None, config=None):
<ide> try:
<ide> self.nb_log_core = CorePlugin(args=self.args).update()["log"]
<ide> except Exception as e:
<del> logger.debug('Error: Can not retrieve the CPU core number (set it to 1) ({})'.format(e))
<add> logger.warning('Error: Can not retrieve the CPU core number (set it to 1) ({})'.format(e))
<ide> self.nb_log_core = 1
<ide>
<ide> def _getloadavg(self): | 3 |
Text | Text | update document about alternative installation | 90ec6bd500b676b7d68c0981a9cd6589707b0a33 | <ide><path>docs/Homebrew-on-Linux.md
<ide> Extract or `git clone` Homebrew wherever you want. Use `/home/linuxbrew/.linuxbr
<ide> ```sh
<ide> git clone https://github.com/Homebrew/brew ~/.linuxbrew/Homebrew
<ide> mkdir ~/.linuxbrew/bin
<del>ln -s ../Homebrew/bin/brew ~/.linuxbrew/bin
<add>ln -s ~/.linuxbrew/Homebrew/bin/brew ~/.linuxbrew/bin
<ide> eval $(~/.linuxbrew/bin/brew shellenv)
<ide> ```
<ide> | 1 |
Go | Go | enhance container detection on some corner cases | 2f9e62611e16f189b103929e7718709ca9f38cc1 | <ide><path>pkg/parsers/operatingsystem/operatingsystem_linux.go
<ide> func IsContainerized() (bool, error) {
<ide> return false, err
<ide> }
<ide> for _, line := range bytes.Split(b, []byte{'\n'}) {
<del> if len(line) > 0 && !bytes.HasSuffix(line, []byte{'/'}) && !bytes.HasSuffix(line, []byte("init.scope")) {
<add> if len(line) > 0 && !bytes.HasSuffix(line, []byte(":/")) && !bytes.HasSuffix(line, []byte(":/init.scope")) {
<ide> return true, nil
<ide> }
<ide> }
<ide><path>pkg/parsers/operatingsystem/operatingsystem_linux_test.go
<ide> func TestIsContainerized(t *testing.T) {
<ide> 3:cpuacct:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d
<ide> 2:cpu:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d
<ide> 1:cpuset:/`)
<add> nonContainerizedProc1CgroupNotSystemd = []byte(`9:memory:/not/init.scope
<add> 1:name=not_systemd:/not.init.scope
<add>`)
<ide> )
<ide>
<ide> dir := os.TempDir()
<ide> func TestIsContainerized(t *testing.T) {
<ide> t.Fatal("Wrongly assuming containerized for systemd /init.scope cgroup layout")
<ide> }
<ide>
<add> if err := ioutil.WriteFile(proc1Cgroup, nonContainerizedProc1CgroupNotSystemd, 0600); err != nil {
<add> t.Fatalf("failed to write to %s: %v", proc1Cgroup, err)
<add> }
<add> inContainer, err = IsContainerized()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if !inContainer {
<add> t.Fatal("Wrongly assuming non-containerized")
<add> }
<add>
<ide> if err := ioutil.WriteFile(proc1Cgroup, containerizedProc1Cgroup, 0600); err != nil {
<ide> t.Fatalf("failed to write to %s: %v", proc1Cgroup, err)
<ide> } | 2 |
Python | Python | fix uint test error | a52cfad2f0806ad44fca37e58b115b552147a09d | <ide><path>t/unit/backends/test_elasticsearch.py
<ide> def test_index(self):
<ide> x._server.index.return_value = expected_result
<ide>
<ide> body = {"field1": "value1"}
<add> x._index(id=sentinel.task_id, body=body, kwarg1='test1')
<ide> x._server.index.assert_called_once_with(
<ide> id=sentinel.task_id,
<ide> doc_type=x.doc_type,
<ide> def test_config_params(self):
<ide>
<ide> assert self.backend.es_max_retries == 10
<ide> assert self.backend.es_timeout == 20.0
<del> assert self.backend.es_retry_on_timeout == True
<add> assert self.backend.es_retry_on_timeout is True | 1 |
Javascript | Javascript | allow suspending in the shell during hydration | f7f7ed089eb04a3504762425baf1d673701c736b | <ide><path>packages/react-dom/src/__tests__/ReactDOMFizzShellHydration-test.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @emails react-core
<add> */
<add>
<add>let JSDOM;
<add>let React;
<add>let ReactDOM;
<add>let Scheduler;
<add>let clientAct;
<add>let ReactDOMFizzServer;
<add>let Stream;
<add>let document;
<add>let writable;
<add>let container;
<add>let buffer = '';
<add>let hasErrored = false;
<add>let fatalError = undefined;
<add>let textCache;
<add>
<add>describe('ReactDOMFizzShellHydration', () => {
<add> beforeEach(() => {
<add> jest.resetModules();
<add> JSDOM = require('jsdom').JSDOM;
<add> React = require('react');
<add> ReactDOM = require('react-dom');
<add> Scheduler = require('scheduler');
<add> clientAct = require('jest-react').act;
<add> ReactDOMFizzServer = require('react-dom/server');
<add> Stream = require('stream');
<add>
<add> textCache = new Map();
<add>
<add> // Test Environment
<add> const jsdom = new JSDOM(
<add> '<!DOCTYPE html><html><head></head><body><div id="container">',
<add> {
<add> runScripts: 'dangerously',
<add> },
<add> );
<add> document = jsdom.window.document;
<add> container = document.getElementById('container');
<add>
<add> buffer = '';
<add> hasErrored = false;
<add>
<add> writable = new Stream.PassThrough();
<add> writable.setEncoding('utf8');
<add> writable.on('data', chunk => {
<add> buffer += chunk;
<add> });
<add> writable.on('error', error => {
<add> hasErrored = true;
<add> fatalError = error;
<add> });
<add> });
<add>
<add> async function serverAct(callback) {
<add> await callback();
<add> // Await one turn around the event loop.
<add> // This assumes that we'll flush everything we have so far.
<add> await new Promise(resolve => {
<add> setImmediate(resolve);
<add> });
<add> if (hasErrored) {
<add> throw fatalError;
<add> }
<add> // JSDOM doesn't support stream HTML parser so we need to give it a proper fragment.
<add> // We also want to execute any scripts that are embedded.
<add> // We assume that we have now received a proper fragment of HTML.
<add> const bufferedContent = buffer;
<add> buffer = '';
<add> const fakeBody = document.createElement('body');
<add> fakeBody.innerHTML = bufferedContent;
<add> while (fakeBody.firstChild) {
<add> const node = fakeBody.firstChild;
<add> if (node.nodeName === 'SCRIPT') {
<add> const script = document.createElement('script');
<add> script.textContent = node.textContent;
<add> fakeBody.removeChild(node);
<add> container.appendChild(script);
<add> } else {
<add> container.appendChild(node);
<add> }
<add> }
<add> }
<add>
<add> function resolveText(text) {
<add> const record = textCache.get(text);
<add> if (record === undefined) {
<add> const newRecord = {
<add> status: 'resolved',
<add> value: text,
<add> };
<add> textCache.set(text, newRecord);
<add> } else if (record.status === 'pending') {
<add> const thenable = record.value;
<add> record.status = 'resolved';
<add> record.value = text;
<add> thenable.pings.forEach(t => t());
<add> }
<add> }
<add>
<add> function readText(text) {
<add> const record = textCache.get(text);
<add> if (record !== undefined) {
<add> switch (record.status) {
<add> case 'pending':
<add> throw record.value;
<add> case 'rejected':
<add> throw record.value;
<add> case 'resolved':
<add> return record.value;
<add> }
<add> } else {
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<add>
<add> const thenable = {
<add> pings: [],
<add> then(resolve) {
<add> if (newRecord.status === 'pending') {
<add> thenable.pings.push(resolve);
<add> } else {
<add> Promise.resolve().then(() => resolve(newRecord.value));
<add> }
<add> },
<add> };
<add>
<add> const newRecord = {
<add> status: 'pending',
<add> value: thenable,
<add> };
<add> textCache.set(text, newRecord);
<add>
<add> throw thenable;
<add> }
<add> }
<add>
<add> // function Text({text}) {
<add> // Scheduler.unstable_yieldValue(text);
<add> // return text;
<add> // }
<add>
<add> function AsyncText({text}) {
<add> readText(text);
<add> Scheduler.unstable_yieldValue(text);
<add> return text;
<add> }
<add>
<add> function resetTextCache() {
<add> textCache = new Map();
<add> }
<add>
<add> test('suspending in the shell during hydration', async () => {
<add> const div = React.createRef(null);
<add>
<add> function App() {
<add> return (
<add> <div ref={div}>
<add> <AsyncText text="Shell" />
<add> </div>
<add> );
<add> }
<add>
<add> // Server render
<add> await resolveText('Shell');
<add> await serverAct(async () => {
<add> const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
<add> pipe(writable);
<add> });
<add> expect(Scheduler).toHaveYielded(['Shell']);
<add> const dehydratedDiv = container.getElementsByTagName('div')[0];
<add>
<add> // Clear the cache and start rendering on the client
<add> resetTextCache();
<add>
<add> // Hydration suspends because the data for the shell hasn't loaded yet
<add> await clientAct(async () => {
<add> ReactDOM.hydrateRoot(container, <App />);
<add> });
<add> expect(Scheduler).toHaveYielded(['Suspend! [Shell]']);
<add> expect(div.current).toBe(null);
<add> expect(container.textContent).toBe('Shell');
<add>
<add> // The shell loads and hydration finishes
<add> await clientAct(async () => {
<add> await resolveText('Shell');
<add> });
<add> expect(Scheduler).toHaveYielded(['Shell']);
<add> expect(div.current).toBe(dehydratedDiv);
<add> expect(container.textContent).toBe('Shell');
<add> });
<add>
<add> test('suspending in the shell during a normal client render', async () => {
<add> // Same as previous test but during a normal client render, no hydration
<add> function App() {
<add> return <AsyncText text="Shell" />;
<add> }
<add>
<add> const root = ReactDOM.createRoot(container);
<add> await clientAct(async () => {
<add> root.render(<App />);
<add> });
<add> expect(Scheduler).toHaveYielded(['Suspend! [Shell]']);
<add>
<add> await clientAct(async () => {
<add> await resolveText('Shell');
<add> });
<add> expect(Scheduler).toHaveYielded(['Shell']);
<add> expect(container.textContent).toBe('Shell');
<add> });
<add>});
<ide><path>packages/react-reconciler/src/ReactFiberLane.new.js
<ide> export function getLanesToRetrySynchronouslyOnError(root: FiberRoot): Lanes {
<ide> return NoLanes;
<ide> }
<ide>
<add>export function includesSyncLane(lanes: Lanes) {
<add> return (lanes & SyncLane) !== NoLanes;
<add>}
<add>
<ide> export function includesNonIdleWork(lanes: Lanes) {
<ide> return (lanes & NonIdleLanes) !== NoLanes;
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberLane.old.js
<ide> export function getLanesToRetrySynchronouslyOnError(root: FiberRoot): Lanes {
<ide> return NoLanes;
<ide> }
<ide>
<add>export function includesSyncLane(lanes: Lanes) {
<add> return (lanes & SyncLane) !== NoLanes;
<add>}
<add>
<ide> export function includesNonIdleWork(lanes: Lanes) {
<ide> return (lanes & NonIdleLanes) !== NoLanes;
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberThrow.new.js
<ide> import {
<ide> includesSomeLane,
<ide> mergeLanes,
<ide> pickArbitraryLane,
<del> includesOnlyTransitions,
<add> includesSyncLane,
<ide> } from './ReactFiberLane.new';
<ide> import {
<ide> getIsHydrating,
<ide> function throwException(
<ide> attachRetryListener(suspenseBoundary, root, wakeable, rootRenderLanes);
<ide> return;
<ide> } else {
<del> // No boundary was found. If we're inside startTransition, this is OK.
<add> // No boundary was found. Unless this is a sync update, this is OK.
<ide> // We can suspend and wait for more data to arrive.
<ide>
<del> if (includesOnlyTransitions(rootRenderLanes)) {
<del> // This is a transition. Suspend. Since we're not activating a Suspense
<del> // boundary, this will unwind all the way to the root without performing
<del> // a second pass to render a fallback. (This is arguably how refresh
<del> // transitions should work, too, since we're not going to commit the
<del> // fallbacks anyway.)
<add> if (!includesSyncLane(rootRenderLanes)) {
<add> // This is not a sync update. Suspend. Since we're not activating a
<add> // Suspense boundary, this will unwind all the way to the root without
<add> // performing a second pass to render a fallback. (This is arguably how
<add> // refresh transitions should work, too, since we're not going to commit
<add> // the fallbacks anyway.)
<add> //
<add> // This case also applies to initial hydration.
<ide> attachPingListener(root, wakeable, rootRenderLanes);
<ide> renderDidSuspendDelayIfPossible();
<ide> return;
<ide> }
<ide>
<del> // We're not in a transition. We treat this case like an error because
<del> // discrete renders are expected to finish synchronously to maintain
<del> // consistency with external state.
<del> // TODO: This will error during non-transition concurrent renders, too.
<del> // But maybe it shouldn't?
<add> // This is a sync/discrete update. We treat this case like an error
<add> // because discrete renders are expected to produce a complete tree
<add> // synchronously to maintain consistency with external state.
<ide>
<ide> // TODO: We should never call getComponentNameFromFiber in production.
<ide> // Log a warning or something to prevent us from accidentally bundling it.
<ide><path>packages/react-reconciler/src/ReactFiberThrow.old.js
<ide> import {
<ide> includesSomeLane,
<ide> mergeLanes,
<ide> pickArbitraryLane,
<del> includesOnlyTransitions,
<add> includesSyncLane,
<ide> } from './ReactFiberLane.old';
<ide> import {
<ide> getIsHydrating,
<ide> function throwException(
<ide> attachRetryListener(suspenseBoundary, root, wakeable, rootRenderLanes);
<ide> return;
<ide> } else {
<del> // No boundary was found. If we're inside startTransition, this is OK.
<add> // No boundary was found. Unless this is a sync update, this is OK.
<ide> // We can suspend and wait for more data to arrive.
<ide>
<del> if (includesOnlyTransitions(rootRenderLanes)) {
<del> // This is a transition. Suspend. Since we're not activating a Suspense
<del> // boundary, this will unwind all the way to the root without performing
<del> // a second pass to render a fallback. (This is arguably how refresh
<del> // transitions should work, too, since we're not going to commit the
<del> // fallbacks anyway.)
<add> if (!includesSyncLane(rootRenderLanes)) {
<add> // This is not a sync update. Suspend. Since we're not activating a
<add> // Suspense boundary, this will unwind all the way to the root without
<add> // performing a second pass to render a fallback. (This is arguably how
<add> // refresh transitions should work, too, since we're not going to commit
<add> // the fallbacks anyway.)
<add> //
<add> // This case also applies to initial hydration.
<ide> attachPingListener(root, wakeable, rootRenderLanes);
<ide> renderDidSuspendDelayIfPossible();
<ide> return;
<ide> }
<ide>
<del> // We're not in a transition. We treat this case like an error because
<del> // discrete renders are expected to finish synchronously to maintain
<del> // consistency with external state.
<del> // TODO: This will error during non-transition concurrent renders, too.
<del> // But maybe it shouldn't?
<add> // This is a sync/discrete update. We treat this case like an error
<add> // because discrete renders are expected to produce a complete tree
<add> // synchronously to maintain consistency with external state.
<ide>
<ide> // TODO: We should never call getComponentNameFromFiber in production.
<ide> // Log a warning or something to prevent us from accidentally bundling it.
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspense-test.internal.js
<ide> describe('ReactSuspense', () => {
<ide> expect(root).toMatchRenderedOutput('Hi');
<ide> });
<ide>
<del> it('throws if tree suspends and none of the Suspense ancestors have a boundary', () => {
<del> ReactTestRenderer.create(<AsyncText text="Hi" ms={1000} />, {
<del> unstable_isConcurrent: true,
<del> });
<del>
<del> expect(Scheduler).toFlushAndThrow(
<del> 'AsyncText suspended while rendering, but no fallback UI was specified.',
<del> );
<del> expect(Scheduler).toHaveYielded(['Suspend! [Hi]', 'Suspend! [Hi]']);
<del> });
<del>
<ide> it('updates memoized child of suspense component when context updates (simple memo)', () => {
<ide> const {useContext, createContext, useState, memo} = React;
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.js
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> });
<ide>
<ide> // @gate enableCache
<del> it('throws a helpful error when an update is suspends without a placeholder', () => {
<del> ReactNoop.render(<AsyncText text="Async" />);
<del> expect(Scheduler).toFlushAndThrow(
<add> it('errors when an update suspends without a placeholder during a sync update', () => {
<add> // This is an error because sync/discrete updates are expected to produce
<add> // a complete tree immediately to maintain consistency with external state
<add> // — we can't delay the commit.
<add> expect(() => {
<add> ReactNoop.flushSync(() => {
<add> ReactNoop.render(<AsyncText text="Async" />);
<add> });
<add> }).toThrow(
<ide> 'AsyncText suspended while rendering, but no fallback UI was specified.',
<ide> );
<ide> }); | 7 |
Text | Text | add history entries for dep0162 on `fs.md` | c08a361f706e60db9a2718282ea12abc1b04b882 | <ide><path>doc/api/fs.md
<ide> the end of the file.
<ide> <!-- YAML
<ide> added: v0.11.5
<ide> changes:
<add> - version: v17.8.0
<add> pr-url: https://github.com/nodejs/node/pull/42149
<add> description: Passing to the `string` parameter an object with an own
<add> `toString` function is deprecated.
<ide> - version: v14.12.0
<ide> pr-url: https://github.com/nodejs/node/pull/34993
<ide> description: The `string` parameter will stringify an object with an
<ide> changes:
<ide> description: Passing an invalid callback to the `callback` argument
<ide> now throws `ERR_INVALID_ARG_TYPE` instead of
<ide> `ERR_INVALID_CALLBACK`.
<add> - version: v17.8.0
<add> pr-url: https://github.com/nodejs/node/pull/42149
<add> description: Passing to the `string` parameter an object with an own
<add> `toString` function is deprecated.
<ide> - version: v16.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/37460
<ide> description: The error returned may be an `AggregateError` if more than one
<ide> The `encoding` option is ignored if `data` is a buffer.
<ide> The `mode` option only affects the newly created file. See [`fs.open()`][]
<ide> for more details.
<ide>
<del>If `data` is a plain object, it must have an own (not inherited) `toString`
<del>function property.
<del>
<ide> ```mjs
<ide> import { writeFile } from 'fs';
<ide> import { Buffer } from 'buffer';
<ide> this API: [`fs.utimes()`][].
<ide> <!-- YAML
<ide> added: v0.1.29
<ide> changes:
<add> - version: v17.8.0
<add> pr-url: https://github.com/nodejs/node/pull/42149
<add> description: Passing to the `data` parameter an object with an own
<add> `toString` function is deprecated.
<ide> - version: v14.12.0
<ide> pr-url: https://github.com/nodejs/node/pull/34993
<ide> description: The `data` parameter will stringify an object with an
<ide> changes:
<ide>
<ide> Returns `undefined`.
<ide>
<del>If `data` is a plain object, it must have an own (not inherited) `toString`
<del>function property.
<del>
<ide> The `mode` option only affects the newly created file. See [`fs.open()`][]
<ide> for more details.
<ide> | 1 |
Go | Go | fix bug in followsymlinkinscope when link == root | 385c9b1a08aeaf7e08363007e5bb79bf30225b7e | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestModeHostname(t *testing.T) {
<ide> deleteAllContainers()
<ide>
<ide> logDone("run - hostname and several network modes")
<del>}
<add>}
<ide>\ No newline at end of file
<ide><path>pkg/symlink/fs.go
<ide> const maxLoopCounter = 100
<ide> // FollowSymlink will follow an existing link and scope it to the root
<ide> // path provided.
<ide> func FollowSymlinkInScope(link, root string) (string, error) {
<del> prev := "/"
<del>
<ide> root, err := filepath.Abs(root)
<ide> if err != nil {
<ide> return "", err
<ide> func FollowSymlinkInScope(link, root string) (string, error) {
<ide> return "", err
<ide> }
<ide>
<add> if link == root {
<add> return root, nil
<add> }
<add>
<add>
<ide> if !strings.HasPrefix(filepath.Dir(link), root) {
<ide> return "", fmt.Errorf("%s is not within %s", link, root)
<ide> }
<ide>
<add> prev := "/"
<add>
<ide> for _, p := range strings.Split(link, "/") {
<ide> prev = filepath.Join(prev, p)
<ide> prev = filepath.Clean(prev) | 2 |
Javascript | Javascript | replace prototypal on classical inheritance | cb54a5bf85d959bf5cfdf73f03fed8fac03024fa | <ide><path>packages/ember-routing/lib/system/dsl.js
<ide> import { assert, deprecate } from 'ember-metal';
<ide> @submodule ember-routing
<ide> */
<ide>
<del>function DSL(name, options) {
<del> this.parent = name;
<del> this.enableLoadingSubstates = options && options.enableLoadingSubstates;
<del> this.matches = [];
<del> this.explicitIndex = undefined;
<del> this.options = options;
<del>}
<add>let uuid = 0;
<ide>
<del>export default DSL;
<add>class DSL {
<add> constructor(name, options) {
<add> this.parent = name;
<add> this.enableLoadingSubstates = options && options.enableLoadingSubstates;
<add> this.matches = [];
<add> this.explicitIndex = undefined;
<add> this.options = options;
<add> }
<ide>
<del>DSL.prototype = {
<ide> route(name, options, callback) {
<ide> let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
<ide> if (arguments.length === 2 && typeof options === 'function') {
<ide> DSL.prototype = {
<ide>
<ide> assert(
<ide> `'${name}' cannot be used as a route name.`,
<del> (function() {
<add> ((() => {
<ide> if (options.overrideNameAssertion === true) { return true; }
<ide>
<ide> return ['array', 'basic', 'object', 'application'].indexOf(name) === -1;
<del> })()
<add> }))()
<ide> );
<ide>
<ide> if (this.enableLoadingSubstates) {
<ide> DSL.prototype = {
<ide> } else {
<ide> createRoute(this, name, options);
<ide> }
<del> },
<add> }
<ide>
<ide> push(url, name, callback, serialize) {
<ide> let parts = name.split('.');
<ide> DSL.prototype = {
<ide> if (url === '' || url === '/' || parts[parts.length - 1] === 'index') { this.explicitIndex = true; }
<ide>
<ide> this.matches.push([url, name, callback]);
<del> },
<add> }
<ide>
<ide> resource(name, options, callback) {
<ide> if (arguments.length === 2 && typeof options === 'function') {
<ide> DSL.prototype = {
<ide> options.resetNamespace = true;
<ide> deprecate('this.resource() is deprecated. Use this.route(\'name\', { resetNamespace: true }, function () {}) instead.', false, { id: 'ember-routing.router-resource', until: '3.0.0' });
<ide> this.route(name, options, callback);
<del> },
<add> }
<ide>
<ide> generate() {
<ide> let dslMatches = this.matches;
<ide> DSL.prototype = {
<ide> }
<ide> };
<ide> }
<del>};
<add>
<add> mount(_name, options = {}) {
<add> let engineRouteMap = this.options.resolveRouteMap(_name);
<add> let name = _name;
<add>
<add> if (options.as) {
<add> name = options.as;
<add> }
<add>
<add> let fullName = getFullName(this, name, options.resetNamespace);
<add>
<add> let engineInfo = {
<add> name: _name,
<add> instanceId: uuid++,
<add> mountPoint: fullName,
<add> fullName
<add> };
<add>
<add> let path = options.path;
<add>
<add> if (typeof path !== 'string') {
<add> path = `/${name}`;
<add> }
<add>
<add> let callback;
<add> let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
<add> if (engineRouteMap) {
<add> let shouldResetEngineInfo = false;
<add> let oldEngineInfo = this.options.engineInfo;
<add> if (oldEngineInfo) {
<add> shouldResetEngineInfo = true;
<add> this.options.engineInfo = engineInfo;
<add> }
<add>
<add> let optionsForChild = assign({ engineInfo }, this.options);
<add> let childDSL = new DSL(fullName, optionsForChild);
<add>
<add> createRoute(childDSL, 'loading');
<add> createRoute(childDSL, 'error', { path: dummyErrorRoute });
<add>
<add>
<add> engineRouteMap.class.call(childDSL);
<add>
<add> callback = childDSL.generate();
<add>
<add> if (shouldResetEngineInfo) {
<add> this.options.engineInfo = oldEngineInfo;
<add> }
<add> }
<add>
<add> let localFullName = 'application';
<add> let routeInfo = assign({ localFullName }, engineInfo);
<add>
<add> if (this.enableLoadingSubstates) {
<add> // These values are important to register the loading routes under their
<add> // proper names for the Router and within the Engine's registry.
<add> let substateName = `${name}_loading`;
<add> let localFullName = `application_loading`;
<add> let routeInfo = assign({ localFullName }, engineInfo);
<add> createRoute(this, substateName, { resetNamespace: options.resetNamespace });
<add> this.options.addRouteForEngine(substateName, routeInfo);
<add>
<add> substateName = `${name}_error`;
<add> localFullName = `application_error`;
<add> routeInfo = assign({ localFullName }, engineInfo);
<add> createRoute(this, substateName, { resetNamespace: options.resetNamespace, path: dummyErrorRoute });
<add> this.options.addRouteForEngine(substateName, routeInfo);
<add> }
<add>
<add> this.options.addRouteForEngine(fullName, routeInfo);
<add>
<add> this.push(path, fullName, callback);
<add> }
<add>}
<add>
<add>export default DSL;
<ide>
<ide> function canNest(dsl) {
<ide> return dsl.parent && dsl.parent !== 'application';
<ide> DSL.map = callback => {
<ide> callback.call(dsl);
<ide> return dsl;
<ide> };
<del>
<del>let uuid = 0;
<del>
<del>DSL.prototype.mount = function(_name, options = {}) {
<del> let engineRouteMap = this.options.resolveRouteMap(_name);
<del> let name = _name;
<del>
<del> if (options.as) {
<del> name = options.as;
<del> }
<del>
<del> let fullName = getFullName(this, name, options.resetNamespace);
<del>
<del> let engineInfo = {
<del> name: _name,
<del> instanceId: uuid++,
<del> mountPoint: fullName,
<del> fullName
<del> };
<del>
<del> let path = options.path;
<del>
<del> if (typeof path !== 'string') {
<del> path = `/${name}`;
<del> }
<del>
<del> let callback;
<del> let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
<del> if (engineRouteMap) {
<del> let shouldResetEngineInfo = false;
<del> let oldEngineInfo = this.options.engineInfo;
<del> if (oldEngineInfo) {
<del> shouldResetEngineInfo = true;
<del> this.options.engineInfo = engineInfo;
<del> }
<del>
<del> let optionsForChild = assign({ engineInfo }, this.options);
<del> let childDSL = new DSL(fullName, optionsForChild);
<del>
<del> createRoute(childDSL, 'loading');
<del> createRoute(childDSL, 'error', { path: dummyErrorRoute });
<del>
<del>
<del> engineRouteMap.class.call(childDSL);
<del>
<del> callback = childDSL.generate();
<del>
<del> if (shouldResetEngineInfo) {
<del> this.options.engineInfo = oldEngineInfo;
<del> }
<del> }
<del>
<del> let localFullName = 'application';
<del> let routeInfo = assign({ localFullName }, engineInfo);
<del>
<del> if (this.enableLoadingSubstates) {
<del> // These values are important to register the loading routes under their
<del> // proper names for the Router and within the Engine's registry.
<del> let substateName = `${name}_loading`;
<del> let localFullName = `application_loading`;
<del> let routeInfo = assign({ localFullName }, engineInfo);
<del> createRoute(this, substateName, { resetNamespace: options.resetNamespace });
<del> this.options.addRouteForEngine(substateName, routeInfo);
<del>
<del> substateName = `${name}_error`;
<del> localFullName = `application_error`;
<del> routeInfo = assign({ localFullName }, engineInfo);
<del> createRoute(this, substateName, { resetNamespace: options.resetNamespace, path: dummyErrorRoute });
<del> this.options.addRouteForEngine(substateName, routeInfo);
<del> }
<del>
<del> this.options.addRouteForEngine(fullName, routeInfo);
<del>
<del> this.push(path, fullName, callback);
<del>}; | 1 |
Text | Text | remove docs for `dockerd --no-new-privileges` | 0a1ace9d2f72f3e3c20e8ddad2407ba7145e3db5 | <ide><path>docs/reference/commandline/dockerd.md
<ide> Options:
<ide> --max-concurrent-uploads int Set the max concurrent uploads for each push (default 5)
<ide> --metrics-addr string Set address and port to serve the metrics api (default "")
<ide> --mtu int Set the containers network MTU
<del> --no-new-privileges Disable container processes from gaining new privileges
<ide> --oom-score-adjust int Set the oom_score_adj for the daemon (default -500)
<ide> -p, --pidfile string Path to use for daemon PID file (default "/var/run/docker.pid")
<ide> --raw-logs Full timestamps without ANSI coloring | 1 |
Java | Java | fix flowable#toobservable backpressure support | 3e4ae3856f184d5783d34ffc5c468d91e67d77d8 | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public final <K, V> Single<Map<K, Collection<V>>> toMultimap(
<ide> * @since 2.0
<ide> */
<ide> @CheckReturnValue
<del> @BackpressureSupport(BackpressureKind.NONE)
<add> @BackpressureSupport(BackpressureKind.UNBOUNDED_IN)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Observable<T> toObservable() {
<ide> return RxJavaPlugins.onAssembly(new ObservableFromPublisher<T>(this)); | 1 |
PHP | PHP | ignore an assert on windows | 5893031599b6ed631989a89ed5e07c249292cfb9 | <ide><path>tests/TestCase/Log/Engine/ConsoleLogTest.php
<ide> public function testConsoleOutputlogs()
<ide> {
<ide> $output = $this->getMockBuilder('Cake\Console\ConsoleOutput')->getMock();
<ide>
<del> $output->expects($this->at(0))
<del> ->method('setOutputAs')
<del> ->with($this->stringContains(ConsoleOutput::COLOR));
<del>
<add> if (DIRECTORY_SEPARATOR !== '\\') { //skip if test is on windows
<add> $output->expects($this->at(0))
<add> ->method('setOutputAs')
<add> ->with($this->stringContains(ConsoleOutput::COLOR));
<add> }
<ide> $message = ' Error: oh noes</error>';
<ide> $output->expects($this->at(1))
<ide> ->method('write') | 1 |
Ruby | Ruby | add check for ssl_cert_dir | 94bb92b4c1c27ad32be784975b03a337cd61695d | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_user_curlrc
<ide> end
<ide> end
<ide>
<add> def check_for_unsupported_curl_vars
<add> # Support for SSL_CERT_DIR seemed to be removed in the 10.10.5 update.
<add> if MacOS.version >= :yosemite && !ENV["SSL_CERT_DIR"].nil? then <<-EOS.undent
<add> SSL_CERT_DIR support was removed from Apple's curl.
<add> If fetching formulae fails you should:
<add> unset SSL_CERT_DIR
<add> and remove it from #{shell_profile} if present.
<add> EOS
<add> end
<add> end
<add>
<ide> def check_which_pkg_config
<ide> binary = which "pkg-config"
<ide> return if binary.nil? | 1 |
Text | Text | add redux-tcomb to the ecosystem | 99a0dc6a4ca0cea8106ed6c5a7b21f6693cfd1bd | <ide><path>docs/introduction/Ecosystem.md
<ide> On this page we will only feature a few of them that the Redux maintainers have
<ide> * [redux-transducers](https://github.com/acdlite/redux-transducers) — Transducer utilities for Redux
<ide> * [redux-immutablejs](https://github.com/indexiatech/redux-immutablejs) — Integration tools between Redux and [Immutable](https://github.com/facebook/immutable-js/)
<ide> * [redux-undo](https://github.com/omnidan/redux-undo) — Effortless undo/redo and action history for your reducers
<add>* [redux-tcomb](https://github.com/gcanti/redux-tcomb) — Immutable and type-checked state and actions for Redux
<ide>
<ide> ## Developer Tools
<ide> | 1 |
PHP | PHP | controller param behind. fixes | 74fd4849ba8e37ed7974a02bf7b9b40761ea7531 | <ide><path>cake/libs/router.php
<ide> function __mapRoute($route, $params = array()) {
<ide> if (isset($params[$key])) {
<ide> $string = $params[$key];
<ide> unset($params[$key]);
<del> } else {
<add> } elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
<ide> $key = $key . '/';
<ide> }
<ide> $out = str_replace(':' . $key, $string, $out);
<ide><path>cake/tests/cases/libs/router.test.php
<ide> function testAdminRouting() {
<ide> $result = Router::url(array('controller' => 'posts', 'action' => 'index', '0', '?' => 'var=test&var2=test2'));
<ide> $expected = '/beheer/posts/index/0?var=test&var2=test2';
<ide> $this->assertEqual($result, $expected);
<add>
<add> Configure::write('Routing.admin', 'admin');
<add> $paths = Configure::read('pluginPaths');
<add> Configure::write('pluginPaths', array(
<add> TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS
<add> ));
<add> Configure::write('__objects.plugin', array('test_plugin'));
<add>
<add> Router::reload();
<add> Router::setRequestInfo(array(
<add> array('admin' => true, 'controller' => 'controller', 'action' => 'action',
<add> 'form' => array(), 'url' => array(), 'plugin' => null),
<add> array('base' => '/', 'here' => '/', 'webroot' => '/base/', 'passedArgs' => array(),
<add> 'argSeparator' => ':', 'namedArgs' => array())
<add> ));
<add> Router::parse('/');
<add>
<add> $result = Router::url(array('plugin' => 'test_plugin', 'controller' => 'test_plugin', 'action' => 'index'));
<add> $expected = '/admin/test_plugin';
<add> $this->assertEqual($result, $expected);
<add>
<add> Configure::write('pluginPaths', $paths);
<ide> }
<ide> /**
<ide> * testExtensionParsingSetting method | 2 |
Python | Python | remove outdated comment | 37ebbc3a1cf1d284d9ef2afefb405884effb6928 | <ide><path>keras/backend/theano_backend.py
<ide> def random_uniform(shape, low=0.0, high=1.0, dtype=_FLOATX, seed=None):
<ide>
<ide> tensordot -> soon to be introduced in TF
<ide> batched_tensordot -> reimplement
<del>
<del>addbroadcast -> remove usage?
<del>unbroadcast -> remove usage?
<ide> ''' | 1 |
Python | Python | fix legacy printing mode check | 239783ffb705cdb8e0ed283f69fc05752e93e19b | <ide><path>numpy/core/arrayprint.py
<ide> def dtype_is_implied(dtype):
<ide> array([1, 2, 3], dtype=np.int8)
<ide> """
<ide> dtype = np.dtype(dtype)
<del> if _format_options['legacy'] and dtype.type == bool_:
<add> if _format_options['legacy'] == '1.13' and dtype.type == bool_:
<ide> return False
<ide> return dtype.type in _typelessdata
<ide> | 1 |
Text | Text | rephrase four hashes of the apocalypse [ci skip] | 97cac32841deed50a9caf6bb3b01039223f77071 | <ide><path>guides/source/testing.md
<ide> NOTE: Functional tests do not verify whether the specified request type is accep
<ide>
<ide> ### The Four Hashes of the Apocalypse
<ide>
<del>After a request has been made using one of the 6 methods (`get`, `post`, etc.) and processed, you will have 4 Hash objects ready for use:
<add>After a request has been made and processed, you will have 4 Hash objects ready for use:
<ide>
<ide> * `assigns` - Any objects that are stored as instance variables in actions for use in views.
<ide> * `cookies` - Any cookies that are set. | 1 |
Javascript | Javascript | return the native promise from play() | 091bdf9261549e49d453f4591cde9c6d555bfa00 | <ide><path>src/js/player.js
<ide> class Player extends Component {
<ide> /**
<ide> * start media playback
<ide> *
<del> * @return {Player}
<del> * A reference to the player object this function was called on
<add> * @return {Promise|undefined}
<add> * Returns a `Promise` if the browser returns one, for most browsers this will
<add> * return undefined.
<ide> */
<ide> play() {
<ide> // Only calls the tech's play if we already have a src loaded
<ide> if (this.src() || this.currentSrc()) {
<del> this.techCall_('play');
<del> } else {
<del> this.tech_.one('loadstart', function() {
<del> this.play();
<del> });
<add> return this.techGet_('play');
<ide> }
<ide>
<del> return this;
<add> this.ready(function() {
<add> this.tech_.one('loadstart', function() {
<add> const retval = this.play();
<add>
<add> // silence errors (unhandled promise from play)
<add> if (retval !== undefined && typeof retval.then === 'function') {
<add> retval.then(null, (e) => {});
<add> }
<add> });
<add> });
<ide> }
<ide>
<ide> /**
<ide><path>src/js/tech/html5.js
<ide> class Html5 extends Tech {
<ide> this.removeOldTracks_(techTracks, elTracks);
<ide> }
<ide>
<del> /**
<del> * Called by {@link Player#play} to play using the `Html5` `Tech`.
<del> */
<del> play() {
<del> const playPromise = this.el_.play();
<del>
<del> // Catch/silence error when a pause interrupts a play request
<del> // on browsers which return a promise
<del> if (playPromise !== undefined && typeof playPromise.then === 'function') {
<del> playPromise.then(null, (e) => {});
<del> }
<del> }
<del>
<ide> /**
<ide> * Set current time for the `HTML5` tech.
<ide> *
<ide> Html5.resetMediaElement = function(el) {
<ide> * @method Html5#load
<ide> * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
<ide> */
<del> 'load'
<add> 'load',
<add>
<add> /**
<add> * A wrapper around the media elements `play` function. This will call the `HTML5`s
<add> * media element `play` function.
<add> *
<add> * @method Html5#play
<add> * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
<add> */
<add> 'play'
<ide> ].forEach(function(prop) {
<ide> Html5.prototype[prop] = function() {
<ide> return this.el_[prop]();
<ide><path>test/unit/player.test.js
<ide> QUnit.test('should be scrubbing while seeking', function(assert) {
<ide> player.dispose();
<ide> });
<ide>
<add>if (window.Promise) {
<add> QUnit.test('play promise should resolve to native promise if returned', function(assert) {
<add> const player = TestHelpers.makePlayer({});
<add> const done = assert.async();
<add>
<add> player.tech_.play = () => window.Promise.resolve('foo');
<add> const p = player.play();
<add>
<add> assert.ok(p, 'play returns something');
<add> assert.equal(typeof p.then, 'function', 'play returns a promise');
<add> p.then(function(val) {
<add> assert.equal(val, 'foo', 'should resolve to native promise value');
<add>
<add> player.dispose();
<add> done();
<add> });
<add> });
<add>}
<add>
<add>QUnit.test('play promise should resolve to native value if returned', function(assert) {
<add> const player = TestHelpers.makePlayer({});
<add>
<add> player.tech_.play = () => 'foo';
<add> const p = player.play();
<add>
<add> assert.equal(p, 'foo', 'play returns foo');
<add>});
<add>
<ide> QUnit.test('should throw on startup no techs are specified', function(assert) {
<ide> const techOrder = videojs.options.techOrder;
<ide> | 3 |
Ruby | Ruby | fix stale cask detection | 6fe75fb1542995cdc641ca77f0529bfbb66f958e | <ide><path>Library/Homebrew/cleanup.rb
<ide> def stale_formula?(scrub)
<ide> def stale_cask?(scrub)
<ide> return false unless name = basename.to_s[/\A(.*?)\-\-/, 1]
<ide>
<add> return if dirname.basename.to_s != "Cask"
<add>
<ide> cask = begin
<ide> Cask::CaskLoader.load(name)
<ide> rescue Cask::CaskUnavailableError | 1 |
Ruby | Ruby | fetch approved reviews for a pull request | 90309e5f42a9c60c6040d9d4ee0401fa413d1c7e | <ide><path>Library/Homebrew/test/utils/github_spec.rb
<ide> end
<ide> end
<ide>
<add> describe "::approved_reviews", :needs_network do
<add> it "can get reviews for a pull request" do
<add> reviews = subject.approved_reviews("Homebrew", "homebrew-core", 1, commit: "deadbeef")
<add> expect(reviews).to eq([])
<add> end
<add> end
<add>
<ide> describe "::get_artifact_url", :needs_network do
<ide> it "fails to find a nonexistant workflow" do
<ide> expect {
<ide><path>Library/Homebrew/utils/github.rb
<ide> def search(entity, *queries, **qualifiers)
<ide> open_api(uri) { |json| json.fetch("items", []) }
<ide> end
<ide>
<add> def approved_reviews(user, repo, pr, commit: nil)
<add> url = "https://api.github.com/graphql"
<add> data = {
<add> query: <<~EOS,
<add> { repository(name: "#{repo}", owner: "#{user}") {
<add> pullRequest(number: #{pr}) {
<add> reviews(states: APPROVED, first: 100) {
<add> nodes {
<add> author {
<add> ... on User { email login name databaseId }
<add> ... on Organization { email login name databaseId }
<add> }
<add> authorAssociation
<add> commit { oid }
<add> }
<add> }
<add> }
<add> }
<add> }
<add> EOS
<add> }
<add> result = open_api(url, data: data, request_method: "POST")
<add> raise Error, result["errors"] if result["errors"].present?
<add>
<add> reviews = result["data"]["repository"]["pullRequest"]["reviews"]["nodes"]
<add>
<add> reviews.map do |r|
<add> next if commit.present? && commit != r["commit"]["oid"]
<add> next unless %w[MEMBER OWNER].include? r["authorAssociation"]
<add>
<add> email = if r["author"]["email"].empty?
<add> "#{r["author"]["databaseId"]}+#{r["author"]["login"]}@users.noreply.github.com"
<add> else
<add> r["author"]["email"]
<add> end
<add>
<add> name = r["author"]["name"] || r["author"]["login"]
<add>
<add> {
<add> "email" => email,
<add> "name" => name,
<add> "login" => r["author"]["login"],
<add> }
<add> end.compact
<add> end
<add>
<ide> def dispatch_event(user, repo, event, **payload)
<ide> url = "#{API_URL}/repos/#{user}/#{repo}/dispatches"
<ide> open_api(url, data: { event_type: event, client_payload: payload }, | 2 |
Javascript | Javascript | fix some missing semi-colons and spaces, typos | 4b4292edb86d34067a2babb9f572a3641dd1d2a7 | <ide><path>docs/src/gen-docs.js
<ide> writer.makeDir('build/docs/syntaxhighlighter').then(function() {
<ide> return Q.deep(fileFutures);
<ide> }).then(function generateManifestFile() {
<ide> return appCache('build/docs/').then(function(list) {
<del> writer.output('appcache-offline.manifest',list)
<add> writer.output('appcache-offline.manifest', list);
<ide> });
<ide> }).then(function printStats() {
<ide> console.log('DONE. Generated ' + docs.length + ' pages in ' + (now()-start) + 'ms.' );
<ide> function writeTheRest(writesFuture) {
<ide> var manifest = 'manifest="appcache.manifest"',
<ide> jq = '<script src="jquery.min.js"></script>',
<ide> ngMin = '<script src="../angular.min.js" ng:autobind></script>',
<del> ng = '<script src="../angular.js" ng:autobind></script>'
<add> ng = '<script src="../angular.js" ng:autobind></script>';
<ide>
<ide> writesFuture.push(writer.copy('docs/src/templates/index.html', 'build/docs/index.html',
<ide> writer.replace, {'doc:manifest': manifest,
<ide><path>docs/src/writer.js
<ide> var Q = require('qq');
<ide> var OUTPUT_DIR = "build/docs/";
<ide> var fs = require('fs');
<ide>
<del>exports.output = function(file, content){
<add>exports.output = function(file, content) {
<ide> console.log('writing ', file);
<ide> var fullPath = OUTPUT_DIR + file;
<ide> var dir = parent(fullPath);
<ide> return Q.when(exports.makeDir(dir), function(error) {
<ide> qfs.write(fullPath,exports.toString(content));
<ide> });
<del>}
<add>};
<ide>
<ide> //recursively create directory
<ide> exports.makeDir = function (path) {
<ide><path>src/service/route.js
<ide> angularServiceInject('$route', function($location, $routeParams) {
<ide> * @description
<ide> * Adds a new route definition to the `$route` service.
<ide> */
<del> when:function (path, route) {
<add> when: function (path, route) {
<ide> var routeDef = routes[path];
<ide> if (!routeDef) routeDef = routes[path] = {reloadOnSearch: true};
<del> if (route) extend(routeDef, route); //TODO(im): what the heck? merge two route definitions?
<add> if (route) extend(routeDef, route); // TODO(im): what the heck? merge two route definitions?
<ide> dirty++;
<ide> return routeDef;
<ide> },
<ide> angularServiceInject('$route', function($location, $routeParams) {
<ide> var regex = '^' + when.replace(/[\.\\\(\)\^\$]/g, "\$1") + '$',
<ide> params = [],
<ide> dst = {};
<del> forEach(when.split(/\W/), function(param){
<add> forEach(when.split(/\W/), function(param) {
<ide> if (param) {
<ide> var paramRegExp = new RegExp(":" + param + "([\\W])");
<ide> if (regex.match(paramRegExp)) {
<ide> angularServiceInject('$route', function($location, $routeParams) {
<ide> });
<ide> var match = on.match(new RegExp(regex));
<ide> if (match) {
<del> forEach(params, function(name, index){
<add> forEach(params, function(name, index) {
<ide> dst[name] = match[index + 1];
<ide> });
<ide> }
<ide> return match ? dst : null;
<ide> }
<ide>
<del> function updateRoute(){
<add> function updateRoute() {
<ide> var next = parseRoute(),
<ide> last = $route.current;
<ide>
<ide> angularServiceInject('$route', function($location, $routeParams) {
<ide> /**
<ide> * @returns the current active route, by matching it against the URL
<ide> */
<del> function parseRoute(){
<add> function parseRoute() {
<ide> // Match a route
<ide> var params, match;
<ide> forEach(routes, function(route, path) {
<ide><path>test/directivesSpec.js
<ide> 'use strict';
<ide>
<del>describe("directive", function(){
<add>describe("directive", function() {
<ide>
<ide> var compile, model, element;
<ide>
<ide> describe("directive", function(){
<ide> expect(scope.a).toEqual(123);
<ide> });
<ide>
<del> describe('ng:bind', function(){
<add> describe('ng:bind', function() {
<ide> it('should set text', function() {
<ide> var scope = compile('<div ng:bind="a"></div>');
<ide> expect(element.text()).toEqual('');
<ide> describe("directive", function(){
<ide> });
<ide>
<ide>
<del> it('should suppress rendering of falsy values', function(){
<add> it('should suppress rendering of falsy values', function() {
<ide> var scope = compile('<div>{{ null }}{{ undefined }}{{ "" }}-{{ 0 }}{{ false }}</div>');
<ide> scope.$digest();
<ide> expect(scope.$element.text()).toEqual('-0false');
<ide> });
<ide>
<ide> });
<ide>
<del> describe('ng:bind-template', function(){
<add> describe('ng:bind-template', function() {
<ide> it('should ng:bind-template', function() {
<ide> var scope = compile('<div ng:bind-template="Hello {{name}}!"></div>');
<ide> scope.name = 'Misko';
<ide> describe("directive", function(){
<ide> expect(element.text()).toEqual('Hello Misko!');
<ide> });
<ide>
<del> it('should have $element set to current bind element', function(){
<add> it('should have $element set to current bind element', function() {
<ide> var innerText;
<del> angularFilter.myFilter = function(text){
<add> angularFilter.myFilter = function(text) {
<ide> innerText = innerText || this.$element.text();
<ide> return text;
<ide> };
<ide> describe("directive", function(){
<ide>
<ide> });
<ide>
<del> describe('ng:bind-attr', function(){
<del> it('should bind attributes', function(){
<add> describe('ng:bind-attr', function() {
<add> it('should bind attributes', function() {
<ide> var scope = compile('<div ng:bind-attr="{src:\'http://localhost/mysrc\', alt:\'myalt\'}"/>');
<ide> scope.$digest();
<ide> expect(element.attr('src')).toEqual('http://localhost/mysrc');
<ide> expect(element.attr('alt')).toEqual('myalt');
<ide> });
<ide>
<del> it('should not pretty print JSON in attributes', function(){
<add> it('should not pretty print JSON in attributes', function() {
<ide> var scope = compile('<img alt="{{ {a:1} }}"/>');
<ide> scope.$digest();
<ide> expect(element.attr('alt')).toEqual('{"a":1}');
<ide> });
<ide> });
<ide>
<del> it('should remove special attributes on false', function(){
<add> it('should remove special attributes on false', function() {
<ide> var scope = compile('<input ng:bind-attr="{disabled:\'{{disabled}}\', readonly:\'{{readonly}}\', checked:\'{{checked}}\'}"/>');
<ide> var input = scope.$element[0];
<ide> expect(input.disabled).toEqual(false);
<ide> describe("directive", function(){
<ide> });
<ide>
<ide> describe('ng:click', function(){
<del> it('should get called on a click', function(){
<add> it('should get called on a click', function() {
<ide> var scope = compile('<div ng:click="clicked = true"></div>');
<ide> scope.$digest();
<ide> expect(scope.clicked).toBeFalsy();
<ide> describe("directive", function(){
<ide> });
<ide>
<ide>
<del> it('should ng:class odd/even', function(){
<add> it('should ng:class odd/even', function() {
<ide> var scope = compile('<ul><li ng:repeat="i in [0,1]" class="existing" ng:class-odd="\'odd\'" ng:class-even="\'even\'"></li><ul>');
<ide> scope.$digest();
<ide> var e1 = jqLite(element[0].childNodes[1]);
<ide> describe("directive", function(){
<ide> });
<ide>
<ide>
<del> describe('ng:style', function(){
<del> it('should set', function(){
<add> describe('ng:style', function() {
<add> it('should set', function() {
<ide> var scope = compile('<div ng:style="{height: \'40px\'}"></div>');
<ide> scope.$digest();
<ide> expect(element.css('height')).toEqual('40px');
<ide> describe("directive", function(){
<ide> expect(element.hasClass('ng-exception')).toBeFalsy();
<ide> });
<ide>
<del> it('should preserve and remove previous style', function(){
<add> it('should preserve and remove previous style', function() {
<ide> var scope = compile('<div style="height: 10px;" ng:style="myStyle"></div>');
<ide> scope.$digest();
<ide> expect(getStyle(element)).toEqual({height: '10px'});
<ide> describe("directive", function(){
<ide>
<ide>
<ide> describe('ng:show', function() {
<del> it('should show and hide an element', function(){
<add> it('should show and hide an element', function() {
<ide> var element = jqLite('<div ng:show="exp"></div>'),
<ide> scope = compile(element);
<ide>
<ide> describe("directive", function(){
<ide> });
<ide> });
<ide>
<del> describe('ng:controller', function(){
<add> describe('ng:controller', function() {
<ide>
<ide> var temp;
<ide>
<del> beforeEach(function(){
<add> beforeEach(function() {
<ide> temp = window.temp = {};
<del> temp.Greeter = function(){
<add> temp.Greeter = function() {
<ide> this.$root.greeter = this;
<ide> this.greeting = 'hello';
<ide> this.suffix = '!';
<ide> describe("directive", function(){
<ide> };
<ide> });
<ide>
<del> afterEach(function(){
<add> afterEach(function() {
<ide> window.temp = undefined;
<ide> });
<ide>
<del> it('should bind', function(){
<add> it('should bind', function() {
<ide> var scope = compile('<div ng:controller="temp.Greeter"></div>');
<ide> expect(scope.greeter.greeting).toEqual('hello');
<ide> expect(scope.greeter.greet('misko')).toEqual('hello misko!');
<ide> });
<ide>
<del> it('should support nested controllers', function(){
<del> temp.ChildGreeter = function(){
<add> it('should support nested controllers', function() {
<add> temp.ChildGreeter = function() {
<ide> this.greeting = 'hey';
<ide> this.$root.childGreeter = this;
<ide> };
<ide> describe("directive", function(){
<ide>
<ide> expect(element.attr('ng:cloak')).toBe('');
<ide>
<del> angular.compile(element)
<add> angular.compile(element);
<ide>
<ide> expect(element.attr('ng:cloak')).toBeUndefined();
<ide> });
<ide><path>test/markupSpec.js
<ide> describe("markups", function(){
<ide> expect(sortedHtml(element)).toEqual('<div ng:bind-attr="{"' + name +'":"some"}"></div>');
<ide> dealoc(element);
<ide> });
<del> })
<add> });
<ide>
<ide> it('should Parse Text With No Bindings', function(){
<ide> var parts = parseBindings("a");
<ide><path>test/service/localeSpec.js
<ide> describe('$locale', function() {
<ide> expect($locale.pluralCat(0)).toBe('other');
<ide> expect($locale.pluralCat(2)).toBe('other');
<ide> expect($locale.pluralCat(1)).toBe('one');
<del> })
<add> });
<ide> });
<del>
<ide><path>test/service/routeSpec.js
<ide> describe('$route', function() {
<ide> var scope, $route, $location;
<ide>
<del> beforeEach(function(){
<add> beforeEach(function() {
<ide> scope = angular.scope();
<ide> $location = scope.$service('$location');
<ide> $route = scope.$service('$route');
<ide> });
<ide>
<ide>
<del> it('should route and fire change event', function(){
<add> it('should route and fire change event', function() {
<ide> var log = '',
<ide> lastRoute,
<ide> nextRoute;
<ide> describe('$route', function() {
<ide> log += '<init>;';
<ide> }
<ide>
<del> $route.when('/Book/:book/Chapter/:chapter', {controller: BookChapter, template:'Chapter.html'});
<add> $route.when('/Book/:book/Chapter/:chapter', {controller: BookChapter, template: 'Chapter.html'});
<ide> $route.when('/Blank');
<del> scope.$on('$beforeRouteChange', function(event, next, current){
<add> scope.$on('$beforeRouteChange', function(event, next, current) {
<ide> log += 'before();';
<ide> expect(current).toBe($route.current);
<ide> lastRoute = current;
<ide> nextRoute = next;
<ide> });
<del> scope.$on('$afterRouteChange', function(event, current, last){
<add> scope.$on('$afterRouteChange', function(event, current, last) {
<ide> log += 'after();';
<ide> expect(current).toBe($route.current);
<ide> expect(lastRoute).toBe(last);
<ide> describe('$route', function() {
<ide> expect($route.current.template).toEqual('instant update');
<ide> });
<ide>
<add>
<ide> it('should change route even when only search param changes', function() {
<ide> var callback = jasmine.createSpy('onRouteChange');
<ide>
<ide> describe('$route', function() {
<ide> expect(onChangeSpy).toHaveBeenCalled();
<ide> });
<ide>
<del> it('should $destroy old routes', function(){
<del> $route.when('/foo', {template: 'foo.html', controller: function(){ this.name = 'FOO';}});
<del> $route.when('/bar', {template: 'bar.html', controller: function(){ this.name = 'BAR';}});
<add>
<add> it('should $destroy old routes', function() {
<add> $route.when('/foo', {template: 'foo.html', controller: function() {this.name = 'FOO';}});
<add> $route.when('/bar', {template: 'bar.html', controller: function() {this.name = 'BAR';}});
<ide> $route.when('/baz', {template: 'baz.html'});
<ide>
<ide> expect(scope.$childHead).toEqual(null);
<ide> describe('$route', function() {
<ide> }
<ide> });
<ide>
<add>
<ide> it('should replace the url when redirecting', function() {
<ide> $route.when('/bar/:id', {template: 'bar.html'});
<ide> $route.when('/foo/:id/:extra', {redirectTo: '/bar/:id'});
<ide> describe('$route', function() {
<ide>
<ide> describe('reloadOnSearch', function() {
<ide> it('should reload a route when reloadOnSearch is enabled and .search() changes', function() {
<del> var $rouetParams = scope.$service('$routeParams'),
<add> var $routeParams = scope.$service('$routeParams'),
<ide> reloaded = jasmine.createSpy('route reload');
<ide>
<ide> $route.when('/foo', {controller: FooCtrl});
<ide> describe('$route', function() {
<ide> $location.path('/foo');
<ide> scope.$digest();
<ide> expect(reloaded).toHaveBeenCalled();
<del> expect($rouetParams).toEqual({});
<add> expect($routeParams).toEqual({});
<ide> reloaded.reset();
<ide>
<ide> // trigger reload
<ide> $location.search({foo: 'bar'});
<ide> scope.$digest();
<ide> expect(reloaded).toHaveBeenCalled();
<del> expect($rouetParams).toEqual({foo:'bar'});
<add> expect($routeParams).toEqual({foo:'bar'});
<ide> });
<ide>
<ide>
<ide> describe('$route', function() {
<ide> });
<ide>
<ide>
<del> describe('reload', function(){
<add> describe('reload', function() {
<ide>
<del> it('should reload even if reloadOnSearch is false', function(){
<add> it('should reload even if reloadOnSearch is false', function() {
<ide> var $routeParams = scope.$service('$routeParams'),
<ide> count = 0;
<ide>
<ide> describe('$route', function() {
<ide> expect(count).toEqual(2);
<ide> });
<ide> });
<del>
<ide> });
<ide> }); | 7 |
Go | Go | add event types | 72f1881df102fce9ad31e98045b91c204dd44513 | <ide><path>api/client/events.go
<ide> package client
<ide>
<ide> import (
<add> "encoding/json"
<add> "fmt"
<add> "io"
<add> "strings"
<add> "time"
<add>
<ide> "github.com/docker/docker/api/types"
<add> eventtypes "github.com/docker/docker/api/types/events"
<ide> "github.com/docker/docker/api/types/filters"
<ide> Cli "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/opts"
<del> "github.com/docker/docker/pkg/jsonmessage"
<add> "github.com/docker/docker/pkg/jsonlog"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> )
<ide>
<ide> func (cli *DockerCli) CmdEvents(args ...string) error {
<ide> }
<ide> defer responseBody.Close()
<ide>
<del> return jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut)
<add> return streamEvents(responseBody, cli.out)
<add>}
<add>
<add>// streamEvents decodes prints the incoming events in the provided output.
<add>func streamEvents(input io.Reader, output io.Writer) error {
<add> dec := json.NewDecoder(input)
<add> for {
<add> var event eventtypes.Message
<add> if err := dec.Decode(&event); err != nil {
<add> if err == io.EOF {
<add> break
<add> }
<add> return err
<add> }
<add> printOutput(event, output)
<add> }
<add> return nil
<add>}
<add>
<add>// printOutput prints all types of event information.
<add>// Each output includes the event type, actor id, name and action.
<add>// Actor attributes are printed at the end if the actor has any.
<add>func printOutput(event eventtypes.Message, output io.Writer) {
<add> if event.TimeNano != 0 {
<add> fmt.Fprintf(output, "%s ", time.Unix(0, event.TimeNano).Format(jsonlog.RFC3339NanoFixed))
<add> } else if event.Time != 0 {
<add> fmt.Fprintf(output, "%s ", time.Unix(event.Time, 0).Format(jsonlog.RFC3339NanoFixed))
<add> }
<add>
<add> fmt.Fprintf(output, "%s %s %s", event.Type, event.Action, event.Actor.ID)
<add>
<add> if len(event.Actor.Attributes) > 0 {
<add> var attrs []string
<add> for k, v := range event.Actor.Attributes {
<add> attrs = append(attrs, fmt.Sprintf("%s=%s", k, v))
<add> }
<add> fmt.Fprintf(output, " (%s)", strings.Join(attrs, ", "))
<add> }
<add> fmt.Fprint(output, "\n")
<ide> }
<ide><path>api/server/router/system/backend.go
<ide> package system
<ide>
<ide> import (
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/api/types/events"
<ide> "github.com/docker/docker/api/types/filters"
<del> "github.com/docker/docker/pkg/jsonmessage"
<ide> )
<ide>
<ide> // Backend is the methods that need to be implemented to provide
<ide> // system specific functionality.
<ide> type Backend interface {
<ide> SystemInfo() (*types.Info, error)
<ide> SystemVersion() types.Version
<del> SubscribeToEvents(since, sinceNano int64, ef filters.Args) ([]*jsonmessage.JSONMessage, chan interface{})
<add> SubscribeToEvents(since, sinceNano int64, ef filters.Args) ([]events.Message, chan interface{})
<ide> UnsubscribeFromEvents(chan interface{})
<ide> AuthenticateToRegistry(authConfig *types.AuthConfig) (string, error)
<ide> }
<ide><path>api/server/router/system/system_routes.go
<ide> import (
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/server/httputils"
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/api/types/events"
<ide> "github.com/docker/docker/api/types/filters"
<ide> timetypes "github.com/docker/docker/api/types/time"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> "github.com/docker/docker/pkg/jsonmessage"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> func (s *systemRouter) getEvents(ctx context.Context, w http.ResponseWriter, r *
<ide> for {
<ide> select {
<ide> case ev := <-l:
<del> jev, ok := ev.(*jsonmessage.JSONMessage)
<add> jev, ok := ev.(events.Message)
<ide> if !ok {
<add> logrus.Warnf("unexpected event message: %q", ev)
<ide> continue
<ide> }
<ide> if err := enc.Encode(jev); err != nil {
<ide><path>api/types/events/events.go
<add>package events
<add>
<add>const (
<add> // ContainerEventType is the event type that containers generate
<add> ContainerEventType = "container"
<add> // ImageEventType is the event type that images generate
<add> ImageEventType = "image"
<add> // VolumeEventType is the event type that volumes generate
<add> VolumeEventType = "volume"
<add> // NetworkEventType is the event type that networks generate
<add> NetworkEventType = "network"
<add>)
<add>
<add>// Actor describes something that generates events,
<add>// like a container, or a network, or a volume.
<add>// It has a defined name and a set or attributes.
<add>// The container attributes are its labels, other actors
<add>// can generate these attributes from other properties.
<add>type Actor struct {
<add> ID string
<add> Attributes map[string]string
<add>}
<add>
<add>// Message represents the information an event contains
<add>type Message struct {
<add> // Deprecated information from JSONMessage.
<add> // With data only in container events.
<add> Status string `json:"status,omitempty"`
<add> ID string `json:"id,omitempty"`
<add> From string `json:"from,omitempty"`
<add>
<add> Type string
<add> Action string
<add> Actor Actor
<add>
<add> Time int64 `json:"time,omitempty"`
<add> TimeNano int64 `json:"timeNano,omitempty"`
<add>}
<ide><path>api/types/filters/parse.go
<ide> func (filters Args) ExactMatch(field, source string) bool {
<ide> return false
<ide> }
<ide>
<add>// FuzzyMatch returns true if the source matches exactly one of the filters,
<add>// or the source has one of the filters as a prefix.
<add>func (filters Args) FuzzyMatch(field, source string) bool {
<add> if filters.ExactMatch(field, source) {
<add> return true
<add> }
<add>
<add> fieldValues := filters.fields[field]
<add> for prefix := range fieldValues {
<add> if strings.HasPrefix(source, prefix) {
<add> return true
<add> }
<add> }
<add> return false
<add>}
<add>
<ide> // Include returns true if the name of the field to filter is in the filters.
<ide> func (filters Args) Include(field string) bool {
<ide> _, ok := filters.fields[field]
<ide><path>api/types/filters/parse_test.go
<ide> func TestWalkValues(t *testing.T) {
<ide> t.Fatalf("Expected to not iterate when the field doesn't exist, got %v", err)
<ide> }
<ide> }
<add>
<add>func TestFuzzyMatch(t *testing.T) {
<add> f := NewArgs()
<add> f.Add("container", "foo")
<add>
<add> cases := map[string]bool{
<add> "foo": true,
<add> "foobar": true,
<add> "barfoo": false,
<add> "bar": false,
<add> }
<add> for source, match := range cases {
<add> got := f.FuzzyMatch("container", source)
<add> if got != match {
<add> t.Fatalf("Expected %v, got %v: %s", match, got, source)
<add> }
<add> }
<add>}
<ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/types"
<ide> containertypes "github.com/docker/docker/api/types/container"
<add> eventtypes "github.com/docker/docker/api/types/events"
<ide> "github.com/docker/docker/api/types/filters"
<ide> registrytypes "github.com/docker/docker/api/types/registry"
<ide> "github.com/docker/docker/api/types/strslice"
<ide> import (
<ide> "github.com/docker/docker/pkg/fileutils"
<ide> "github.com/docker/docker/pkg/graphdb"
<ide> "github.com/docker/docker/pkg/idtools"
<del> "github.com/docker/docker/pkg/jsonmessage"
<ide> "github.com/docker/docker/pkg/mount"
<ide> "github.com/docker/docker/pkg/namesgenerator"
<ide> "github.com/docker/docker/pkg/progress"
<ide> func (daemon *Daemon) GetByName(name string) (*container.Container, error) {
<ide> return e, nil
<ide> }
<ide>
<del>// getEventFilter returns a filters.Filter for a set of filters
<del>func (daemon *Daemon) getEventFilter(filter filters.Args) *events.Filter {
<del> // incoming container filter can be name, id or partial id, convert to
<del> // a full container id
<del> for _, cn := range filter.Get("container") {
<del> c, err := daemon.GetContainer(cn)
<del> filter.Del("container", cn)
<del> if err == nil {
<del> filter.Add("container", c.ID)
<del> }
<del> }
<del> return events.NewFilter(filter, daemon.GetLabels)
<del>}
<del>
<ide> // SubscribeToEvents returns the currently record of events, a channel to stream new events from, and a function to cancel the stream of events.
<del>func (daemon *Daemon) SubscribeToEvents(since, sinceNano int64, filter filters.Args) ([]*jsonmessage.JSONMessage, chan interface{}) {
<del> ef := daemon.getEventFilter(filter)
<add>func (daemon *Daemon) SubscribeToEvents(since, sinceNano int64, filter filters.Args) ([]eventtypes.Message, chan interface{}) {
<add> ef := events.NewFilter(filter)
<ide> return daemon.EventsService.SubscribeTopic(since, sinceNano, ef)
<ide> }
<ide>
<ide> func (daemon *Daemon) UnsubscribeFromEvents(listener chan interface{}) {
<ide> daemon.EventsService.Evict(listener)
<ide> }
<ide>
<del>// GetLabels for a container or image id
<del>func (daemon *Daemon) GetLabels(id string) map[string]string {
<del> // TODO: TestCase
<del> container := daemon.containers.Get(id)
<del> if container != nil {
<del> return container.Config.Labels
<del> }
<del>
<del> img, err := daemon.GetImage(id)
<del> if err == nil {
<del> return img.ContainerConfig.Labels
<del> }
<del> return nil
<del>}
<del>
<ide> // children returns all child containers of the container with the
<ide> // given name. The containers are returned as a map from the container
<ide> // name to a pointer to Container.
<ide> func (daemon *Daemon) TagImage(newTag reference.Named, imageName string) error {
<ide> if err := daemon.referenceStore.AddTag(newTag, imageID, true); err != nil {
<ide> return err
<ide> }
<del> daemon.EventsService.Log("tag", newTag.String(), "")
<add>
<add> daemon.LogImageEvent(imageID.String(), newTag.String(), "tag")
<ide> return nil
<ide> }
<ide>
<ide> func (daemon *Daemon) PullImage(ref reference.Named, metaHeaders map[string][]st
<ide> }()
<ide>
<ide> imagePullConfig := &distribution.ImagePullConfig{
<del> MetaHeaders: metaHeaders,
<del> AuthConfig: authConfig,
<del> ProgressOutput: progress.ChanOutput(progressChan),
<del> RegistryService: daemon.RegistryService,
<del> EventsService: daemon.EventsService,
<del> MetadataStore: daemon.distributionMetadataStore,
<del> ImageStore: daemon.imageStore,
<del> ReferenceStore: daemon.referenceStore,
<del> DownloadManager: daemon.downloadManager,
<add> MetaHeaders: metaHeaders,
<add> AuthConfig: authConfig,
<add> ProgressOutput: progress.ChanOutput(progressChan),
<add> RegistryService: daemon.RegistryService,
<add> ImageEventLogger: daemon.LogImageEvent,
<add> MetadataStore: daemon.distributionMetadataStore,
<add> ImageStore: daemon.imageStore,
<add> ReferenceStore: daemon.referenceStore,
<add> DownloadManager: daemon.downloadManager,
<ide> }
<ide>
<ide> err := distribution.Pull(ctx, ref, imagePullConfig)
<ide> func (daemon *Daemon) PushImage(ref reference.Named, metaHeaders map[string][]st
<ide> }()
<ide>
<ide> imagePushConfig := &distribution.ImagePushConfig{
<del> MetaHeaders: metaHeaders,
<del> AuthConfig: authConfig,
<del> ProgressOutput: progress.ChanOutput(progressChan),
<del> RegistryService: daemon.RegistryService,
<del> EventsService: daemon.EventsService,
<del> MetadataStore: daemon.distributionMetadataStore,
<del> LayerStore: daemon.layerStore,
<del> ImageStore: daemon.imageStore,
<del> ReferenceStore: daemon.referenceStore,
<del> TrustKey: daemon.trustKey,
<del> UploadManager: daemon.uploadManager,
<add> MetaHeaders: metaHeaders,
<add> AuthConfig: authConfig,
<add> ProgressOutput: progress.ChanOutput(progressChan),
<add> RegistryService: daemon.RegistryService,
<add> ImageEventLogger: daemon.LogImageEvent,
<add> MetadataStore: daemon.distributionMetadataStore,
<add> LayerStore: daemon.layerStore,
<add> ImageStore: daemon.imageStore,
<add> ReferenceStore: daemon.referenceStore,
<add> TrustKey: daemon.trustKey,
<add> UploadManager: daemon.uploadManager,
<ide> }
<ide>
<ide> err := distribution.Push(ctx, ref, imagePushConfig)
<ide><path>daemon/events.go
<ide> package daemon
<ide>
<ide> import (
<add> "strings"
<add>
<add> "github.com/docker/docker/api/types/events"
<ide> "github.com/docker/docker/container"
<add> "github.com/docker/libnetwork"
<ide> )
<ide>
<ide> // LogContainerEvent generates an event related to a container.
<ide> func (daemon *Daemon) LogContainerEvent(container *container.Container, action string) {
<del> daemon.EventsService.Log(
<del> action,
<del> container.ID,
<del> container.Config.Image,
<del> )
<add> attributes := copyAttributes(container.Config.Labels)
<add> if container.Config.Image != "" {
<add> attributes["image"] = container.Config.Image
<add> }
<add> attributes["name"] = strings.TrimLeft(container.Name, "/")
<add>
<add> actor := events.Actor{
<add> ID: container.ID,
<add> Attributes: attributes,
<add> }
<add> daemon.EventsService.Log(action, events.ContainerEventType, actor)
<add>}
<add>
<add>// LogImageEvent generates an event related to a container.
<add>func (daemon *Daemon) LogImageEvent(imageID, refName, action string) {
<add> attributes := map[string]string{}
<add> img, err := daemon.GetImage(imageID)
<add> if err == nil && img.Config != nil {
<add> // image has not been removed yet.
<add> // it could be missing if the event is `delete`.
<add> attributes = copyAttributes(img.Config.Labels)
<add> }
<add> if refName != "" {
<add> attributes["name"] = refName
<add> }
<add> actor := events.Actor{
<add> ID: imageID,
<add> Attributes: attributes,
<add> }
<add>
<add> daemon.EventsService.Log(action, events.ImageEventType, actor)
<add>}
<add>
<add>// LogVolumeEvent generates an event related to a volume.
<add>func (daemon *Daemon) LogVolumeEvent(volumeID, action string, attributes map[string]string) {
<add> actor := events.Actor{
<add> ID: volumeID,
<add> Attributes: attributes,
<add> }
<add> daemon.EventsService.Log(action, events.VolumeEventType, actor)
<add>}
<add>
<add>// LogNetworkEvent generates an event related to a network with only the default attributes.
<add>func (daemon *Daemon) LogNetworkEvent(nw libnetwork.Network, action string) {
<add> daemon.LogNetworkEventWithAttributes(nw, action, map[string]string{})
<add>}
<add>
<add>// LogNetworkEventWithAttributes generates an event related to a network with specific given attributes.
<add>func (daemon *Daemon) LogNetworkEventWithAttributes(nw libnetwork.Network, action string, attributes map[string]string) {
<add> attributes["name"] = nw.Name()
<add> attributes["type"] = nw.Type()
<add>
<add> actor := events.Actor{
<add> ID: nw.ID(),
<add> Attributes: attributes,
<add> }
<add> daemon.EventsService.Log(action, events.NetworkEventType, actor)
<add>}
<add>
<add>// copyAttributes guarantees that labels are not mutated by event triggers.
<add>func copyAttributes(labels map[string]string) map[string]string {
<add> attributes := map[string]string{}
<add> if labels == nil {
<add> return attributes
<add> }
<add> for k, v := range labels {
<add> attributes[k] = v
<add> }
<add> return attributes
<ide> }
<ide><path>daemon/events/events.go
<ide> import (
<ide> "sync"
<ide> "time"
<ide>
<del> "github.com/docker/docker/pkg/jsonmessage"
<add> eventtypes "github.com/docker/docker/api/types/events"
<ide> "github.com/docker/docker/pkg/pubsub"
<ide> )
<ide>
<ide> const (
<ide> bufferSize = 1024
<ide> )
<ide>
<del>// Events is pubsub channel for *jsonmessage.JSONMessage
<add>// Events is pubsub channel for events generated by the engine.
<ide> type Events struct {
<ide> mu sync.Mutex
<del> events []*jsonmessage.JSONMessage
<add> events []eventtypes.Message
<ide> pub *pubsub.Publisher
<ide> }
<ide>
<ide> // New returns new *Events instance
<ide> func New() *Events {
<ide> return &Events{
<del> events: make([]*jsonmessage.JSONMessage, 0, eventsLimit),
<add> events: make([]eventtypes.Message, 0, eventsLimit),
<ide> pub: pubsub.NewPublisher(100*time.Millisecond, bufferSize),
<ide> }
<ide> }
<ide> func New() *Events {
<ide> // last events, a channel in which you can expect new events (in form
<ide> // of interface{}, so you need type assertion), and a function to call
<ide> // to stop the stream of events.
<del>func (e *Events) Subscribe() ([]*jsonmessage.JSONMessage, chan interface{}, func()) {
<add>func (e *Events) Subscribe() ([]eventtypes.Message, chan interface{}, func()) {
<ide> e.mu.Lock()
<del> current := make([]*jsonmessage.JSONMessage, len(e.events))
<add> current := make([]eventtypes.Message, len(e.events))
<ide> copy(current, e.events)
<ide> l := e.pub.Subscribe()
<ide> e.mu.Unlock()
<ide> func (e *Events) Subscribe() ([]*jsonmessage.JSONMessage, chan interface{}, func
<ide> // SubscribeTopic adds new listener to events, returns slice of 64 stored
<ide> // last events, a channel in which you can expect new events (in form
<ide> // of interface{}, so you need type assertion).
<del>func (e *Events) SubscribeTopic(since, sinceNano int64, ef *Filter) ([]*jsonmessage.JSONMessage, chan interface{}) {
<add>func (e *Events) SubscribeTopic(since, sinceNano int64, ef *Filter) ([]eventtypes.Message, chan interface{}) {
<ide> e.mu.Lock()
<ide> defer e.mu.Unlock()
<ide>
<del> var buffered []*jsonmessage.JSONMessage
<add> var buffered []eventtypes.Message
<ide> topic := func(m interface{}) bool {
<del> return ef.Include(m.(*jsonmessage.JSONMessage))
<add> return ef.Include(m.(eventtypes.Message))
<ide> }
<ide>
<ide> if since != -1 {
<ide> func (e *Events) SubscribeTopic(since, sinceNano int64, ef *Filter) ([]*jsonmess
<ide> break
<ide> }
<ide> if ef.filter.Len() == 0 || topic(ev) {
<del> buffered = append([]*jsonmessage.JSONMessage{ev}, buffered...)
<add> buffered = append([]eventtypes.Message{ev}, buffered...)
<ide> }
<ide> }
<ide> }
<ide> func (e *Events) Evict(l chan interface{}) {
<ide>
<ide> // Log broadcasts event to listeners. Each listener has 100 millisecond for
<ide> // receiving event or it will be skipped.
<del>func (e *Events) Log(action, id, from string) {
<add>func (e *Events) Log(action, eventType string, actor eventtypes.Actor) {
<ide> now := time.Now().UTC()
<del> jm := &jsonmessage.JSONMessage{Status: action, ID: id, From: from, Time: now.Unix(), TimeNano: now.UnixNano()}
<add> jm := eventtypes.Message{
<add> Action: action,
<add> Type: eventType,
<add> Actor: actor,
<add> Time: now.Unix(),
<add> TimeNano: now.UnixNano(),
<add> }
<add>
<add> // fill deprecated fields for container and images
<add> switch eventType {
<add> case eventtypes.ContainerEventType:
<add> jm.ID = actor.ID
<add> jm.Status = action
<add> jm.From = actor.Attributes["image"]
<add> case eventtypes.ImageEventType:
<add> jm.ID = actor.ID
<add> jm.Status = action
<add> }
<add>
<ide> e.mu.Lock()
<ide> if len(e.events) == cap(e.events) {
<ide> // discard oldest event
<ide><path>daemon/events/events_test.go
<ide> import (
<ide> "testing"
<ide> "time"
<ide>
<del> "github.com/docker/docker/pkg/jsonmessage"
<add> "github.com/docker/docker/api/types/events"
<ide> )
<ide>
<ide> func TestEventsLog(t *testing.T) {
<ide> func TestEventsLog(t *testing.T) {
<ide> if count != 2 {
<ide> t.Fatalf("Must be 2 subscribers, got %d", count)
<ide> }
<del> e.Log("test", "cont", "image")
<add> actor := events.Actor{
<add> ID: "cont",
<add> Attributes: map[string]string{"image": "image"},
<add> }
<add> e.Log("test", events.ContainerEventType, actor)
<ide> select {
<ide> case msg := <-l1:
<del> jmsg, ok := msg.(*jsonmessage.JSONMessage)
<add> jmsg, ok := msg.(events.Message)
<ide> if !ok {
<ide> t.Fatalf("Unexpected type %T", msg)
<ide> }
<ide> func TestEventsLog(t *testing.T) {
<ide> }
<ide> select {
<ide> case msg := <-l2:
<del> jmsg, ok := msg.(*jsonmessage.JSONMessage)
<add> jmsg, ok := msg.(events.Message)
<ide> if !ok {
<ide> t.Fatalf("Unexpected type %T", msg)
<ide> }
<ide> func TestEventsLogTimeout(t *testing.T) {
<ide>
<ide> c := make(chan struct{})
<ide> go func() {
<del> e.Log("test", "cont", "image")
<add> actor := events.Actor{
<add> ID: "image",
<add> }
<add> e.Log("test", events.ImageEventType, actor)
<ide> close(c)
<ide> }()
<ide>
<ide> func TestLogEvents(t *testing.T) {
<ide> action := fmt.Sprintf("action_%d", i)
<ide> id := fmt.Sprintf("cont_%d", i)
<ide> from := fmt.Sprintf("image_%d", i)
<del> e.Log(action, id, from)
<add>
<add> actor := events.Actor{
<add> ID: id,
<add> Attributes: map[string]string{"image": from},
<add> }
<add> e.Log(action, events.ContainerEventType, actor)
<ide> }
<ide> time.Sleep(50 * time.Millisecond)
<ide> current, l, _ := e.Subscribe()
<ide> func TestLogEvents(t *testing.T) {
<ide> action := fmt.Sprintf("action_%d", num)
<ide> id := fmt.Sprintf("cont_%d", num)
<ide> from := fmt.Sprintf("image_%d", num)
<del> e.Log(action, id, from)
<add>
<add> actor := events.Actor{
<add> ID: id,
<add> Attributes: map[string]string{"image": from},
<add> }
<add> e.Log(action, events.ContainerEventType, actor)
<ide> }
<ide> if len(e.events) != eventsLimit {
<ide> t.Fatalf("Must be %d events, got %d", eventsLimit, len(e.events))
<ide> }
<ide>
<del> var msgs []*jsonmessage.JSONMessage
<add> var msgs []events.Message
<ide> for len(msgs) < 10 {
<ide> m := <-l
<del> jm, ok := (m).(*jsonmessage.JSONMessage)
<add> jm, ok := (m).(events.Message)
<ide> if !ok {
<ide> t.Fatalf("Unexpected type %T", m)
<ide> }
<ide><path>daemon/events/filter.go
<ide> package events
<ide>
<ide> import (
<add> "github.com/docker/docker/api/types/events"
<ide> "github.com/docker/docker/api/types/filters"
<del> "github.com/docker/docker/pkg/jsonmessage"
<ide> "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> // Filter can filter out docker events from a stream
<ide> type Filter struct {
<del> filter filters.Args
<del> getLabels func(id string) map[string]string
<add> filter filters.Args
<ide> }
<ide>
<ide> // NewFilter creates a new Filter
<del>func NewFilter(filter filters.Args, getLabels func(id string) map[string]string) *Filter {
<del> return &Filter{filter: filter, getLabels: getLabels}
<add>func NewFilter(filter filters.Args) *Filter {
<add> return &Filter{filter: filter}
<ide> }
<ide>
<ide> // Include returns true when the event ev is included by the filters
<del>func (ef *Filter) Include(ev *jsonmessage.JSONMessage) bool {
<del> return ef.filter.ExactMatch("event", ev.Status) &&
<del> ef.filter.ExactMatch("container", ev.ID) &&
<del> ef.isImageIncluded(ev.ID, ev.From) &&
<del> ef.isLabelFieldIncluded(ev.ID)
<add>func (ef *Filter) Include(ev events.Message) bool {
<add> if ev.Type != events.ContainerEventType && ev.Type != events.ImageEventType {
<add> return false
<add> }
<add> return ef.filter.ExactMatch("event", ev.Action) &&
<add> ef.matchContainer(ev) &&
<add> ef.isImageIncluded(ev) &&
<add> ef.isLabelFieldIncluded(ev.Actor.Attributes)
<ide> }
<ide>
<del>func (ef *Filter) isLabelFieldIncluded(id string) bool {
<add>func (ef *Filter) isLabelFieldIncluded(attributes map[string]string) bool {
<ide> if !ef.filter.Include("label") {
<ide> return true
<ide> }
<del> return ef.filter.MatchKVList("label", ef.getLabels(id))
<add> return ef.filter.MatchKVList("label", attributes)
<add>}
<add>
<add>func (ef *Filter) matchContainer(ev events.Message) bool {
<add> return ef.filter.FuzzyMatch("container", ev.Actor.ID) ||
<add> ef.filter.FuzzyMatch("container", ev.Actor.Attributes["name"])
<ide> }
<ide>
<ide> // The image filter will be matched against both event.ID (for image events)
<ide> // and event.From (for container events), so that any container that was created
<ide> // from an image will be included in the image events. Also compare both
<ide> // against the stripped repo name without any tags.
<del>func (ef *Filter) isImageIncluded(eventID string, eventFrom string) bool {
<del> return ef.filter.ExactMatch("image", eventID) ||
<del> ef.filter.ExactMatch("image", eventFrom) ||
<del> ef.filter.ExactMatch("image", stripTag(eventID)) ||
<del> ef.filter.ExactMatch("image", stripTag(eventFrom))
<add>func (ef *Filter) isImageIncluded(ev events.Message) bool {
<add> id := ev.ID
<add> var imageName string
<add> if n, ok := ev.Actor.Attributes["image"]; ok {
<add> imageName = n
<add> }
<add> return ef.filter.ExactMatch("image", id) ||
<add> ef.filter.ExactMatch("image", imageName) ||
<add> ef.filter.ExactMatch("image", stripTag(id)) ||
<add> ef.filter.ExactMatch("image", stripTag(imageName))
<ide> }
<ide>
<ide> func stripTag(image string) string {
<ide><path>daemon/events_test.go
<add>package daemon
<add>
<add>import (
<add> "testing"
<add>
<add> containertypes "github.com/docker/docker/api/types/container"
<add> "github.com/docker/docker/container"
<add> "github.com/docker/docker/daemon/events"
<add>)
<add>
<add>func TestLogContainerCopyLabels(t *testing.T) {
<add> e := events.New()
<add> _, l, _ := e.Subscribe()
<add> defer e.Evict(l)
<add>
<add> container := &container.Container{
<add> CommonContainer: container.CommonContainer{
<add> ID: "container_id",
<add> Name: "container_name",
<add> Config: &containertypes.Config{
<add> Labels: map[string]string{
<add> "node": "1",
<add> "os": "alpine",
<add> },
<add> },
<add> },
<add> }
<add> daemon := &Daemon{
<add> EventsService: e,
<add> }
<add> daemon.LogContainerEvent(container, "create")
<add>
<add> if _, mutated := container.Config.Labels["image"]; mutated {
<add> t.Fatalf("Expected to not mutate the container labels, got %q", container.Config.Labels)
<add> }
<add>}
<ide><path>daemon/image_delete.go
<ide> func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.I
<ide>
<ide> untaggedRecord := types.ImageDelete{Untagged: parsedRef.String()}
<ide>
<del> daemon.EventsService.Log("untag", imgID.String(), "")
<add> daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
<ide> records = append(records, untaggedRecord)
<ide>
<ide> // If has remaining references then untag finishes the remove
<ide> func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.I
<ide>
<ide> untaggedRecord := types.ImageDelete{Untagged: parsedRef.String()}
<ide>
<del> daemon.EventsService.Log("untag", imgID.String(), "")
<add> daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
<ide> records = append(records, untaggedRecord)
<ide> }
<ide> }
<ide> func (daemon *Daemon) removeAllReferencesToImageID(imgID image.ID, records *[]ty
<ide>
<ide> untaggedRecord := types.ImageDelete{Untagged: parsedRef.String()}
<ide>
<del> daemon.EventsService.Log("untag", imgID.String(), "")
<add> daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
<ide> *records = append(*records, untaggedRecord)
<ide> }
<ide>
<ide> func (daemon *Daemon) imageDeleteHelper(imgID image.ID, records *[]types.ImageDe
<ide> return err
<ide> }
<ide>
<del> daemon.EventsService.Log("delete", imgID.String(), "")
<add> daemon.LogImageEvent(imgID.String(), imgID.String(), "delete")
<ide> *records = append(*records, types.ImageDelete{Deleted: imgID.String()})
<ide> for _, removedLayer := range removedLayers {
<ide> *records = append(*records, types.ImageDelete{Deleted: removedLayer.ChainID.String()})
<ide><path>daemon/import.go
<ide> func (daemon *Daemon) ImportImage(src string, newRef reference.Named, msg string
<ide> }
<ide> }
<ide>
<del> daemon.EventsService.Log("import", id.String(), "")
<add> daemon.LogImageEvent(id.String(), id.String(), "import")
<ide> outStream.Write(sf.FormatStatus("", id.String()))
<ide> return nil
<ide> }
<ide><path>daemon/update.go
<ide> func (daemon *Daemon) update(name string, hostConfig *container.HostConfig) erro
<ide> }
<ide> }
<ide>
<add> daemon.LogContainerEvent(container, "update")
<add>
<ide> return nil
<ide> }
<ide><path>distribution/pull.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/daemon/events"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/distribution/xfer"
<ide> "github.com/docker/docker/image"
<ide> type ImagePullConfig struct {
<ide> // RegistryService is the registry service to use for TLS configuration
<ide> // and endpoint lookup.
<ide> RegistryService *registry.Service
<del> // EventsService is the events service to use for logging.
<del> EventsService *events.Events
<add> // ImageEventLogger notifies events for a given image
<add> ImageEventLogger func(id, name, action string)
<ide> // MetadataStore is the storage backend for distribution-specific
<ide> // metadata.
<ide> MetadataStore metadata.Store
<ide> func Pull(ctx context.Context, ref reference.Named, imagePullConfig *ImagePullCo
<ide> }
<ide> }
<ide>
<del> imagePullConfig.EventsService.Log("pull", ref.String(), "")
<add> imagePullConfig.ImageEventLogger(ref.String(), repoInfo.Name(), "pull")
<ide> return nil
<ide> }
<ide>
<ide><path>distribution/push.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/digest"
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/daemon/events"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/distribution/xfer"
<ide> "github.com/docker/docker/image"
<ide> type ImagePushConfig struct {
<ide> // RegistryService is the registry service to use for TLS configuration
<ide> // and endpoint lookup.
<ide> RegistryService *registry.Service
<del> // EventsService is the events service to use for logging.
<del> EventsService *events.Events
<add> // ImageEventLogger notifies events for a given image
<add> ImageEventLogger func(id, name, action string)
<ide> // MetadataStore is the storage backend for distribution-specific
<ide> // metadata.
<ide> MetadataStore metadata.Store
<ide> func Push(ctx context.Context, ref reference.Named, imagePushConfig *ImagePushCo
<ide> return err
<ide> }
<ide>
<del> imagePushConfig.EventsService.Log("push", repoInfo.Name(), "")
<add> imagePushConfig.ImageEventLogger(ref.String(), repoInfo.Name(), "push")
<ide> return nil
<ide> }
<ide>
<ide><path>integration-cli/docker_api_events_test.go
<ide> package main
<ide>
<ide> import (
<add> "encoding/json"
<add> "io"
<ide> "net/http"
<add> "net/url"
<add> "strconv"
<add> "strings"
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/integration/checker"
<add> "github.com/docker/docker/pkg/jsonmessage"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestEventsApiEmptyOutput(c *check.C) {
<ide> c.Fatal("timeout waiting for events api to respond, should have responded immediately")
<ide> }
<ide> }
<add>
<add>func (s *DockerSuite) TestEventsApiBackwardsCompatible(c *check.C) {
<add> since := daemonTime(c).Unix()
<add> ts := strconv.FormatInt(since, 10)
<add>
<add> out, _ := dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
<add> containerID := strings.TrimSpace(out)
<add> c.Assert(waitRun(containerID), checker.IsNil)
<add>
<add> q := url.Values{}
<add> q.Set("since", ts)
<add>
<add> _, body, err := sockRequestRaw("GET", "/events?"+q.Encode(), nil, "")
<add> c.Assert(err, checker.IsNil)
<add> defer body.Close()
<add>
<add> dec := json.NewDecoder(body)
<add> var containerCreateEvent *jsonmessage.JSONMessage
<add> for {
<add> var event jsonmessage.JSONMessage
<add> if err := dec.Decode(&event); err != nil {
<add> if err == io.EOF {
<add> break
<add> }
<add> c.Fatal(err)
<add> }
<add> if event.Status == "create" && event.ID == containerID {
<add> containerCreateEvent = &event
<add> break
<add> }
<add> }
<add>
<add> c.Assert(containerCreateEvent, checker.Not(checker.IsNil))
<add> c.Assert(containerCreateEvent.Status, checker.Equals, "create")
<add> c.Assert(containerCreateEvent.ID, checker.Equals, containerID)
<add> c.Assert(containerCreateEvent.From, checker.Equals, "busybox")
<add>}
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildCancellationKillsSleep(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide> name := "testbuildcancellation"
<ide>
<add> observer, err := newEventObserver(c)
<add> c.Assert(err, checker.IsNil)
<add> err = observer.Start()
<add> c.Assert(err, checker.IsNil)
<add> defer observer.Stop()
<add>
<ide> // (Note: one year, will never finish)
<ide> ctx, err := fakeContext("FROM busybox\nRUN sleep 31536000", nil)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<ide> defer ctx.Close()
<ide>
<del> eventStart := make(chan struct{})
<del> eventDie := make(chan struct{})
<del>
<del> observer, err := newEventObserver(c)
<del> c.Assert(err, checker.IsNil)
<del> err = observer.Start()
<del> c.Assert(err, checker.IsNil)
<del> defer observer.Stop()
<del>
<ide> buildCmd := exec.Command(dockerBinary, "build", "-t", name, ".")
<ide> buildCmd.Dir = ctx.Dir
<ide>
<ide> func (s *DockerSuite) TestBuildCancellationKillsSleep(c *check.C) {
<ide> c.Fatalf("Unable to find build container id in build output:\n%s", outputBuffer.String())
<ide> }
<ide>
<del> matchStart := regexp.MustCompile(buildID + `.* start\z`)
<del> matchDie := regexp.MustCompile(buildID + `.* die\z`)
<del>
<del> matcher := func(text string) {
<del> switch {
<del> case matchStart.MatchString(text):
<del> close(eventStart)
<del> case matchDie.MatchString(text):
<del> close(eventDie)
<del> }
<add> testActions := map[string]chan bool{
<add> "start": make(chan bool),
<add> "die": make(chan bool),
<ide> }
<del> go observer.Match(matcher)
<add>
<add> go observer.Match(matchEventLine(buildID, "container", testActions))
<ide>
<ide> select {
<ide> case <-time.After(10 * time.Second):
<ide> c.Fatal(observer.TimeoutError(buildID, "start"))
<del> case <-eventStart:
<del> // Proceeds from here when we see the container fly past in the
<del> // output of "docker events".
<del> // Now we know the container is running.
<add> case <-testActions["start"]:
<add> // ignore, done
<ide> }
<ide>
<ide> // Send a kill to the `docker build` command.
<ide> func (s *DockerSuite) TestBuildCancellationKillsSleep(c *check.C) {
<ide>
<ide> select {
<ide> case <-time.After(10 * time.Second):
<del> // If we don't get here in a timely fashion, it wasn't killed.
<ide> c.Fatal(observer.TimeoutError(buildID, "die"))
<del> case <-eventDie:
<del> // We saw the container shut down in the `docker events` stream,
<del> // as expected.
<add> case <-testActions["die"]:
<add> // ignore, done
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildRm(c *check.C) {
<ide> func (s *DockerSuite) TestBuildNoNamedVolume(c *check.C) {
<ide> func (s *DockerSuite) TestBuildTagEvent(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide>
<del> observer, err := newEventObserver(c, "--filter", "event=tag")
<del> c.Assert(err, check.IsNil)
<del> err = observer.Start()
<del> c.Assert(err, check.IsNil)
<del> defer observer.Stop()
<add> since := daemonTime(c).Unix()
<ide>
<ide> dockerFile := `FROM busybox
<ide> RUN echo events
<ide> `
<del> _, err = buildImage("test", dockerFile, false)
<add> _, err := buildImage("test", dockerFile, false)
<ide> c.Assert(err, check.IsNil)
<ide>
<del> matchTag := regexp.MustCompile("test:latest")
<del> eventTag := make(chan bool)
<del> matcher := func(text string) {
<del> if matchTag.MatchString(text) {
<del> close(eventTag)
<add> out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "type=image")
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add> actions := eventActionsByIDAndType(c, events, "test:latest", "image")
<add> var foundTag bool
<add> for _, a := range actions {
<add> if a == "tag" {
<add> foundTag = true
<add> break
<ide> }
<ide> }
<del> go observer.Match(matcher)
<ide>
<del> select {
<del> case <-time.After(10 * time.Second):
<del> c.Fatal(observer.TimeoutError("test:latest", "tag"))
<del> case <-eventTag:
<del> // We saw the tag event as expected.
<del> }
<add> c.Assert(foundTag, checker.True, check.Commentf("No tag event found:\n%s", out))
<ide> }
<ide>
<ide> // #15780
<ide><path>integration-cli/docker_cli_events_test.go
<ide> import (
<ide> "net/http"
<ide> "os"
<ide> "os/exec"
<del> "regexp"
<ide> "strconv"
<ide> "strings"
<ide> "sync"
<ide> func (s *DockerSuite) TestEventsUntag(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsContainerFailStartDie(c *check.C) {
<del>
<ide> out, _ := dockerCmd(c, "images", "-q")
<ide> image := strings.Split(out, "\n")[0]
<ide> _, _, err := dockerCmdWithError("run", "--name", "testeventdie", image, "blerg")
<ide> c.Assert(err, checker.NotNil, check.Commentf("Container run with command blerg should have failed, but it did not, out=%s", out))
<ide>
<ide> out, _ = dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<ide> events := strings.Split(out, "\n")
<del> c.Assert(len(events), checker.GreaterThan, 1) //Missing expected event
<del>
<del> startEvent := strings.Fields(events[len(events)-3])
<del> dieEvent := strings.Fields(events[len(events)-2])
<ide>
<del> c.Assert(startEvent[len(startEvent)-1], checker.Equals, "start", check.Commentf("event should be start, not %#v", startEvent))
<del> c.Assert(dieEvent[len(dieEvent)-1], checker.Equals, "die", check.Commentf("event should be die, not %#v", dieEvent))
<add> nEvents := len(events)
<add> c.Assert(nEvents, checker.GreaterOrEqualThan, 1) //Missing expected event
<ide>
<add> c.Assert(parseEventAction(c, events[nEvents-3]), checker.Equals, "start")
<add> c.Assert(parseEventAction(c, events[nEvents-2]), checker.Equals, "die")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsLimit(c *check.C) {
<ide> func (s *DockerSuite) TestEventsLimit(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestEventsContainerEvents(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<del> dockerCmd(c, "run", "--rm", "busybox", "true")
<add> containerID, _ := dockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true")
<add> containerID = strings.TrimSpace(containerID)
<add>
<ide> out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<ide> events := strings.Split(out, "\n")
<ide> events = events[:len(events)-1]
<del> c.Assert(len(events), checker.GreaterOrEqualThan, 5) //Missing expected event
<del> createEvent := strings.Fields(events[len(events)-5])
<del> attachEvent := strings.Fields(events[len(events)-4])
<del> startEvent := strings.Fields(events[len(events)-3])
<del> dieEvent := strings.Fields(events[len(events)-2])
<del> destroyEvent := strings.Fields(events[len(events)-1])
<del> c.Assert(createEvent[len(createEvent)-1], checker.Equals, "create", check.Commentf("event should be create, not %#v", createEvent))
<del> c.Assert(attachEvent[len(attachEvent)-1], checker.Equals, "attach", check.Commentf("event should be attach, not %#v", attachEvent))
<del> c.Assert(startEvent[len(startEvent)-1], checker.Equals, "start", check.Commentf("event should be start, not %#v", startEvent))
<del> c.Assert(dieEvent[len(dieEvent)-1], checker.Equals, "die", check.Commentf("event should be die, not %#v", dieEvent))
<del> c.Assert(destroyEvent[len(destroyEvent)-1], checker.Equals, "destroy", check.Commentf("event should be destroy, not %#v", destroyEvent))
<ide>
<add> nEvents := len(events)
<add> c.Assert(nEvents, checker.GreaterOrEqualThan, 5) //Missing expected event
<add> containerEvents := eventActionsByIDAndType(c, events, "container-events-test", "container")
<add> c.Assert(containerEvents, checker.HasLen, 5, check.Commentf("events: %v", events))
<add>
<add> c.Assert(containerEvents[0], checker.Equals, "create", check.Commentf(out))
<add> c.Assert(containerEvents[1], checker.Equals, "attach", check.Commentf(out))
<add> c.Assert(containerEvents[2], checker.Equals, "start", check.Commentf(out))
<add> c.Assert(containerEvents[3], checker.Equals, "die", check.Commentf(out))
<add> c.Assert(containerEvents[4], checker.Equals, "destroy", check.Commentf(out))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<del> dockerCmd(c, "run", "--rm", "busybox", "true")
<add> dockerCmd(c, "run", "--rm", "--name", "since-epoch-test", "busybox", "true")
<ide> timeBeginning := time.Unix(0, 0).Format(time.RFC3339Nano)
<ide> timeBeginning = strings.Replace(timeBeginning, "Z", ".000000000Z", -1)
<del> out, _ := dockerCmd(c, "events", fmt.Sprintf("--since='%s'", timeBeginning),
<del> fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> out, _ := dockerCmd(c, "events", fmt.Sprintf("--since='%s'", timeBeginning), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<ide> events := strings.Split(out, "\n")
<ide> events = events[:len(events)-1]
<del> c.Assert(len(events), checker.GreaterOrEqualThan, 5) //Missing expected event
<del> createEvent := strings.Fields(events[len(events)-5])
<del> attachEvent := strings.Fields(events[len(events)-4])
<del> startEvent := strings.Fields(events[len(events)-3])
<del> dieEvent := strings.Fields(events[len(events)-2])
<del> destroyEvent := strings.Fields(events[len(events)-1])
<del> c.Assert(createEvent[len(createEvent)-1], checker.Equals, "create", check.Commentf("event should be create, not %#v", createEvent))
<del> c.Assert(attachEvent[len(attachEvent)-1], checker.Equals, "attach", check.Commentf("event should be attach, not %#v", attachEvent))
<del> c.Assert(startEvent[len(startEvent)-1], checker.Equals, "start", check.Commentf("event should be start, not %#v", startEvent))
<del> c.Assert(dieEvent[len(dieEvent)-1], checker.Equals, "die", check.Commentf("event should be die, not %#v", dieEvent))
<del> c.Assert(destroyEvent[len(destroyEvent)-1], checker.Equals, "destroy", check.Commentf("event should be destroy, not %#v", destroyEvent))
<ide>
<add> nEvents := len(events)
<add> c.Assert(nEvents, checker.GreaterOrEqualThan, 5) //Missing expected event
<add> containerEvents := eventActionsByIDAndType(c, events, "since-epoch-test", "container")
<add> c.Assert(containerEvents, checker.HasLen, 5, check.Commentf("events: %v", events))
<add>
<add> c.Assert(containerEvents[0], checker.Equals, "create", check.Commentf(out))
<add> c.Assert(containerEvents[1], checker.Equals, "attach", check.Commentf(out))
<add> c.Assert(containerEvents[2], checker.Equals, "start", check.Commentf(out))
<add> c.Assert(containerEvents[3], checker.Equals, "die", check.Commentf(out))
<add> c.Assert(containerEvents[4], checker.Equals, "destroy", check.Commentf(out))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsImageUntagDelete(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<add>
<add> observer, err := newEventObserver(c)
<add> c.Assert(err, checker.IsNil)
<add> err = observer.Start()
<add> c.Assert(err, checker.IsNil)
<add> defer observer.Stop()
<add>
<ide> name := "testimageevents"
<del> _, err := buildImage(name,
<add> imageID, err := buildImage(name,
<ide> `FROM scratch
<ide> MAINTAINER "docker"`,
<ide> true)
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(deleteImages(name), checker.IsNil)
<del> out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<del> events := strings.Split(out, "\n")
<ide>
<del> events = events[:len(events)-1]
<del> c.Assert(len(events), checker.GreaterOrEqualThan, 2) //Missing expected event
<del> untagEvent := strings.Fields(events[len(events)-2])
<del> deleteEvent := strings.Fields(events[len(events)-1])
<del> c.Assert(untagEvent[len(untagEvent)-1], checker.Equals, "untag", check.Commentf("untag should be untag, not %#v", untagEvent))
<del> c.Assert(deleteEvent[len(deleteEvent)-1], checker.Equals, "delete", check.Commentf("untag should be delete, not %#v", untagEvent))
<add> testActions := map[string]chan bool{
<add> "untag": make(chan bool),
<add> "delete": make(chan bool),
<add> }
<add>
<add> go observer.Match(matchEventLine(imageID, "image", testActions))
<add>
<add> select {
<add> case <-time.After(10 * time.Second):
<add> c.Fatal(observer.TimeoutError(imageID, "untag"))
<add> case <-testActions["untag"]:
<add> // ignore, done
<add> }
<add>
<add> select {
<add> case <-time.After(10 * time.Second):
<add> c.Fatal(observer.TimeoutError(imageID, "delete"))
<add> case <-testActions["delete"]:
<add> // ignore, done
<add> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsImageTag(c *check.C) {
<ide> func (s *DockerSuite) TestEventsImageTag(c *check.C) {
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(events, checker.HasLen, 1, check.Commentf("was expecting 1 event. out=%s", out))
<ide> event := strings.TrimSpace(events[0])
<del> expectedStr := image + ": tag"
<del>
<del> c.Assert(event, checker.HasSuffix, expectedStr, check.Commentf("wrong event format. expected='%s' got=%s", expectedStr, event))
<ide>
<add> matches := parseEventText(event)
<add> c.Assert(matches, checker.Not(checker.IsNil))
<add> c.Assert(matchEventID(matches, image), checker.True, check.Commentf("matches: %v\nout:\n%s", matches, out))
<add> c.Assert(matches["action"], checker.Equals, "tag")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsImagePull(c *check.C) {
<ide> func (s *DockerSuite) TestEventsImagePull(c *check.C) {
<ide>
<ide> events := strings.Split(strings.TrimSpace(out), "\n")
<ide> event := strings.TrimSpace(events[len(events)-1])
<del>
<del> c.Assert(event, checker.HasSuffix, "hello-world:latest: pull", check.Commentf("Missing pull event - got:%q", event))
<add> matches := parseEventText(event)
<add> c.Assert(matches, checker.Not(checker.IsNil))
<add> c.Assert(matches["id"], checker.Equals, "hello-world:latest")
<add> c.Assert(matches["action"], checker.Equals, "pull")
<ide>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsImageImport(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide>
<del> observer, err := newEventObserver(c)
<del> c.Assert(err, checker.IsNil)
<del>
<del> err = observer.Start()
<del> c.Assert(err, checker.IsNil)
<del> defer observer.Stop()
<del>
<ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide>
<del> out, _, err = runCommandPipelineWithOutput(
<add> since := daemonTime(c).Unix()
<add> out, _, err := runCommandPipelineWithOutput(
<ide> exec.Command(dockerBinary, "export", cleanedContainerID),
<ide> exec.Command(dockerBinary, "import", "-"),
<ide> )
<ide> c.Assert(err, checker.IsNil, check.Commentf("import failed with output: %q", out))
<ide> imageRef := strings.TrimSpace(out)
<ide>
<del> eventImport := make(chan bool)
<del> matchImport := regexp.MustCompile(imageRef + `: import\z`)
<del> matcher := func(text string) {
<del> if matchImport.MatchString(text) {
<del> close(eventImport)
<del> }
<del> }
<del> go observer.Match(matcher)
<del>
<del> select {
<del> case <-time.After(5 * time.Second):
<del> c.Fatal(observer.TimeoutError(imageRef, "import"))
<del> case <-eventImport:
<del> // ignore, done
<del> }
<add> out, _ = dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "event=import")
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add> c.Assert(events, checker.HasLen, 1)
<add> matches := parseEventText(events[0])
<add> c.Assert(matches["id"], checker.Equals, imageRef, check.Commentf("matches: %v\nout:\n%s\n", matches, out))
<add> c.Assert(matches["action"], checker.Equals, "import", check.Commentf("matches: %v\nout:\n%s\n", matches, out))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsFilters(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<del> parseEvents := func(out, match string) {
<del> events := strings.Split(out, "\n")
<del> events = events[:len(events)-1]
<del> for _, event := range events {
<del> eventFields := strings.Fields(event)
<del> eventName := eventFields[len(eventFields)-1]
<del> c.Assert(eventName, checker.Matches, match)
<del> }
<del> }
<ide>
<ide> since := daemonTime(c).Unix()
<ide> dockerCmd(c, "run", "--rm", "busybox", "true")
<ide> dockerCmd(c, "run", "--rm", "busybox", "true")
<ide> out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "event=die")
<del> parseEvents(out, "die")
<add> parseEvents(c, out, "die")
<ide>
<ide> out, _ = dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "event=die", "--filter", "event=start")
<del> parseEvents(out, "((die)|(start))")
<add> parseEvents(c, out, "die|start")
<ide>
<ide> // make sure we at least got 2 start events
<ide> count := strings.Count(out, "start")
<ide> func (s *DockerSuite) TestEventsFilterContainer(c *check.C) {
<ide> return fmt.Errorf("expected 4 events, got %v", events)
<ide> }
<ide> for _, event := range events {
<del> e := strings.Fields(event)
<del> if len(e) < 3 {
<del> return fmt.Errorf("got malformed event: %s", event)
<del> }
<del>
<del> // Check the id
<del> parsedID := strings.TrimSuffix(e[1], ":")
<del> if parsedID != id {
<del> return fmt.Errorf("expected event for container id %s: %s - parsed container id: %s", id, event, parsedID)
<add> matches := parseEventText(event)
<add> if !matchEventID(matches, id) {
<add> return fmt.Errorf("expected event for container id %s: %s - parsed container id: %s", id, event, matches["id"])
<ide> }
<ide> }
<ide> return nil
<ide> func (s *DockerSuite) TestEventsStreaming(c *check.C) {
<ide> select {
<ide> case <-time.After(5 * time.Second):
<ide> c.Fatal(observer.TimeoutError(containerID, "create"))
<del> case <-eventCreate:
<add> case <-testActions["create"]:
<ide> // ignore, done
<ide> }
<ide>
<ide> select {
<ide> case <-time.After(5 * time.Second):
<ide> c.Fatal(observer.TimeoutError(containerID, "start"))
<del> case <-eventStart:
<add> case <-testActions["start"]:
<ide> // ignore, done
<ide> }
<ide>
<ide> select {
<ide> case <-time.After(5 * time.Second):
<ide> c.Fatal(observer.TimeoutError(containerID, "die"))
<del> case <-eventDie:
<add> case <-testActions["die"]:
<ide> // ignore, done
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsCommit(c *check.C) {
<ide> dockerCmd(c, "stop", cID)
<ide>
<ide> out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since)))
<del> c.Assert(out, checker.Contains, " commit\n", check.Commentf("Missing 'commit' log event"))
<add> c.Assert(out, checker.Contains, "commit", check.Commentf("Missing 'commit' log event"))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsCopy(c *check.C) {
<ide> func (s *DockerSuite) TestEventsCopy(c *check.C) {
<ide> dockerCmd(c, "cp", "cptest:/tmp/file", tempFile.Name())
<ide>
<ide> out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+strconv.Itoa(int(since)))
<del> c.Assert(out, checker.Contains, " archive-path\n", check.Commentf("Missing 'archive-path' log event\n"))
<add> c.Assert(out, checker.Contains, "archive-path", check.Commentf("Missing 'archive-path' log event\n"))
<ide>
<ide> dockerCmd(c, "cp", tempFile.Name(), "cptest:/tmp/filecopy")
<ide>
<ide> out, _ = dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+strconv.Itoa(int(since)))
<del> c.Assert(out, checker.Contains, " extract-to-dir\n", check.Commentf("Missing 'extract-to-dir' log event"))
<add> c.Assert(out, checker.Contains, "extract-to-dir", check.Commentf("Missing 'extract-to-dir' log event"))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsResize(c *check.C) {
<ide> func (s *DockerSuite) TestEventsResize(c *check.C) {
<ide> dockerCmd(c, "stop", cID)
<ide>
<ide> out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since)))
<del> c.Assert(out, checker.Contains, " resize\n", check.Commentf("Missing 'resize' log event"))
<add> c.Assert(out, checker.Contains, "resize", check.Commentf("Missing 'resize' log event"))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsAttach(c *check.C) {
<ide> func (s *DockerSuite) TestEventsAttach(c *check.C) {
<ide> dockerCmd(c, "stop", cID)
<ide>
<ide> out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since)))
<del> c.Assert(out, checker.Contains, " attach\n", check.Commentf("Missing 'attach' log event"))
<add> c.Assert(out, checker.Contains, "attach", check.Commentf("Missing 'attach' log event"))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsRename(c *check.C) {
<ide> func (s *DockerSuite) TestEventsRename(c *check.C) {
<ide> dockerCmd(c, "rename", "oldName", "newName")
<ide>
<ide> out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=newName", "--until="+strconv.Itoa(int(since)))
<del> c.Assert(out, checker.Contains, " rename\n", check.Commentf("Missing 'rename' log event\n"))
<add> c.Assert(out, checker.Contains, "rename", check.Commentf("Missing 'rename' log event\n"))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsTop(c *check.C) {
<ide> func (s *DockerSuite) TestEventsTop(c *check.C) {
<ide> dockerCmd(c, "stop", cID)
<ide>
<ide> out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since)))
<del> c.Assert(out, checker.Contains, " top\n", check.Commentf("Missing 'top' log event"))
<add> c.Assert(out, checker.Contains, " top", check.Commentf("Missing 'top' log event"))
<ide> }
<ide>
<ide> // #13753
<ide> func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *check.C) {
<ide> dockerCmd(c, "push", repoName)
<ide>
<ide> out, _ = dockerCmd(c, "events", "--since=0", "-f", "image="+repoName, "-f", "event=push", "--until="+strconv.Itoa(int(since)))
<del> c.Assert(out, checker.Contains, repoName+": push\n", check.Commentf("Missing 'push' log event"))
<add> c.Assert(out, checker.Contains, repoName, check.Commentf("Missing 'push' log event for %s", repoName))
<ide> }
<ide><path>integration-cli/docker_cli_events_unix_test.go
<ide> func (s *DockerSuite) TestEventsOOMDisableFalse(c *check.C) {
<ide>
<ide> out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=oomFalse", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<ide> events := strings.Split(strings.TrimSuffix(out, "\n"), "\n")
<del> c.Assert(len(events), checker.GreaterOrEqualThan, 5) //Missing expected event
<del>
<del> createEvent := strings.Fields(events[len(events)-5])
<del> attachEvent := strings.Fields(events[len(events)-4])
<del> startEvent := strings.Fields(events[len(events)-3])
<del> oomEvent := strings.Fields(events[len(events)-2])
<del> dieEvent := strings.Fields(events[len(events)-1])
<del> c.Assert(createEvent[len(createEvent)-1], checker.Equals, "create", check.Commentf("event should be create, not %#v", createEvent))
<del> c.Assert(attachEvent[len(attachEvent)-1], checker.Equals, "attach", check.Commentf("event should be attach, not %#v", attachEvent))
<del> c.Assert(startEvent[len(startEvent)-1], checker.Equals, "start", check.Commentf("event should be start, not %#v", startEvent))
<del> c.Assert(oomEvent[len(oomEvent)-1], checker.Equals, "oom", check.Commentf("event should be oom, not %#v", oomEvent))
<del> c.Assert(dieEvent[len(dieEvent)-1], checker.Equals, "die", check.Commentf("event should be die, not %#v", dieEvent))
<add> nEvents := len(events)
<add>
<add> c.Assert(nEvents, checker.GreaterOrEqualThan, 5) //Missing expected event
<add> c.Assert(parseEventAction(c, events[nEvents-5]), checker.Equals, "create")
<add> c.Assert(parseEventAction(c, events[nEvents-4]), checker.Equals, "attach")
<add> c.Assert(parseEventAction(c, events[nEvents-3]), checker.Equals, "start")
<add> c.Assert(parseEventAction(c, events[nEvents-2]), checker.Equals, "oom")
<add> c.Assert(parseEventAction(c, events[nEvents-1]), checker.Equals, "die")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestEventsOOMDisableTrue(c *check.C) {
<ide> func (s *DockerSuite) TestEventsOOMDisableTrue(c *check.C) {
<ide>
<ide> out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=oomTrue", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<ide> events := strings.Split(strings.TrimSuffix(out, "\n"), "\n")
<del> c.Assert(len(events), checker.GreaterOrEqualThan, 4) //Missing expected event
<add> nEvents := len(events)
<add> c.Assert(nEvents, checker.GreaterOrEqualThan, 4) //Missing expected event
<ide>
<del> createEvent := strings.Fields(events[len(events)-4])
<del> attachEvent := strings.Fields(events[len(events)-3])
<del> startEvent := strings.Fields(events[len(events)-2])
<del> oomEvent := strings.Fields(events[len(events)-1])
<del>
<del> c.Assert(createEvent[len(createEvent)-1], checker.Equals, "create", check.Commentf("event should be create, not %#v", createEvent))
<del> c.Assert(attachEvent[len(attachEvent)-1], checker.Equals, "attach", check.Commentf("event should be attach, not %#v", attachEvent))
<del> c.Assert(startEvent[len(startEvent)-1], checker.Equals, "start", check.Commentf("event should be start, not %#v", startEvent))
<del> c.Assert(oomEvent[len(oomEvent)-1], checker.Equals, "oom", check.Commentf("event should be oom, not %#v", oomEvent))
<add> c.Assert(parseEventAction(c, events[nEvents-4]), checker.Equals, "create")
<add> c.Assert(parseEventAction(c, events[nEvents-3]), checker.Equals, "attach")
<add> c.Assert(parseEventAction(c, events[nEvents-2]), checker.Equals, "start")
<add> c.Assert(parseEventAction(c, events[nEvents-1]), checker.Equals, "oom")
<ide>
<ide> out, _ = dockerCmd(c, "inspect", "-f", "{{.State.Status}}", "oomTrue")
<ide> c.Assert(strings.TrimSpace(out), checker.Equals, "running", check.Commentf("container should be still running"))
<ide> }
<ide> }
<ide>
<ide> // #18453
<del>func (s *DockerSuite) TestEventsContainerFilter(c *check.C) {
<add>func (s *DockerSuite) TestEventsContainerFilterByName(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<del> out, _ := dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
<del> c1 := strings.TrimSpace(out)
<del> waitRun(c1)
<del> out, _ = dockerCmd(c, "run", "--name=bar", "-d", "busybox", "top")
<del> c2 := strings.TrimSpace(out)
<del> waitRun(c2)
<del> out, _ = dockerCmd(c, "events", "-f", "container=foo", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<del> c.Assert(out, checker.Contains, c1, check.Commentf("Missing event of container (foo)"))
<del> c.Assert(out, checker.Not(checker.Contains), c2, check.Commentf("Should not contain event of container (bar)"))
<add> cOut, _ := dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
<add> c1 := strings.TrimSpace(cOut)
<add> waitRun("foo")
<add> cOut, _ = dockerCmd(c, "run", "--name=bar", "-d", "busybox", "top")
<add> c2 := strings.TrimSpace(cOut)
<add> waitRun("bar")
<add> out, _ := dockerCmd(c, "events", "-f", "container=foo", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<add> c.Assert(out, checker.Contains, c1, check.Commentf(out))
<add> c.Assert(out, checker.Not(checker.Contains), c2, check.Commentf(out))
<ide> }
<ide>
<ide> // #18453
<ide><path>integration-cli/docker_cli_pause_test.go
<ide> func (s *DockerSuite) TestPause(c *check.C) {
<ide> dockerCmd(c, "unpause", name)
<ide>
<ide> out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<del> events := strings.Split(out, "\n")
<del> c.Assert(len(events) > 1, checker.Equals, true)
<del>
<del> pauseEvent := strings.Fields(events[len(events)-3])
<del> unpauseEvent := strings.Fields(events[len(events)-2])
<del>
<del> c.Assert(pauseEvent[len(pauseEvent)-1], checker.Equals, "pause")
<del> c.Assert(unpauseEvent[len(unpauseEvent)-1], checker.Equals, "unpause")
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add> actions := eventActionsByIDAndType(c, events, name, "container")
<ide>
<add> c.Assert(actions[len(actions)-2], checker.Equals, "pause")
<add> c.Assert(actions[len(actions)-1], checker.Equals, "unpause")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPauseMultipleContainers(c *check.C) {
<ide> func (s *DockerSuite) TestPauseMultipleContainers(c *check.C) {
<ide> dockerCmd(c, append([]string{"unpause"}, containers...)...)
<ide>
<ide> out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
<del> events := strings.Split(out, "\n")
<del> c.Assert(len(events) > len(containers)*3-2, checker.Equals, true)
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<ide>
<del> pauseEvents := make([][]string, len(containers))
<del> unpauseEvents := make([][]string, len(containers))
<del> for i := range containers {
<del> pauseEvents[i] = strings.Fields(events[len(events)-len(containers)*2-1+i])
<del> unpauseEvents[i] = strings.Fields(events[len(events)-len(containers)-1+i])
<del> }
<add> for _, name := range containers {
<add> actions := eventActionsByIDAndType(c, events, name, "container")
<ide>
<del> for _, pauseEvent := range pauseEvents {
<del> c.Assert(pauseEvent[len(pauseEvent)-1], checker.Equals, "pause")
<del> }
<del> for _, unpauseEvent := range unpauseEvents {
<del> c.Assert(unpauseEvent[len(unpauseEvent)-1], checker.Equals, "unpause")
<add> c.Assert(actions[len(actions)-2], checker.Equals, "pause")
<add> c.Assert(actions[len(actions)-1], checker.Equals, "unpause")
<ide> }
<del>
<ide> }
<ide><path>integration-cli/events_utils.go
<ide> import (
<ide> "io"
<ide> "os/exec"
<ide> "strconv"
<add> "strings"
<ide>
<add> "github.com/docker/docker/pkg/integration/checker"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<add>var (
<add> reTimestamp = `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{9}(:?(:?(:?-|\+)\d{2}:\d{2})|Z)`
<add> reEventType = `(?P<eventType>\w+)`
<add> reAction = `(?P<action>\w+)`
<add> reID = `(?P<id>[^\s]+)`
<add> reAttributes = `(\s\((?P<attributes>[^\)]+)\))?`
<add> reString = fmt.Sprintf(`\A%s\s%s\s%s\s%s%s\z`, reTimestamp, reEventType, reAction, reID, reAttributes)
<add>
<add> // eventCliRegexp is a regular expression that matches all possible event outputs in the cli
<add> eventCliRegexp = regexp.MustCompile(reString)
<add>)
<add>
<ide> // eventMatcher is a function that tries to match an event input.
<ide> type eventMatcher func(text string)
<ide>
<ide> type eventObserver struct {
<ide> // without running it. Users must call `eventObserver.Start` to start the command.
<ide> func newEventObserver(c *check.C, args ...string) (*eventObserver, error) {
<ide> since := daemonTime(c).Unix()
<add> return newEventObserverWithBacklog(c, since, args...)
<add>}
<ide>
<add>// newEventObserverWithBacklog creates a new observer changing the start time of the backlog to return.
<add>func newEventObserverWithBacklog(c *check.C, since int64, args ...string) (*eventObserver, error) {
<ide> cmdArgs := []string{"events", "--since", strconv.FormatInt(since, 10)}
<ide> if len(args) > 0 {
<ide> cmdArgs = append(cmdArgs, args...)
<ide> func (e *eventObserver) Start() error {
<ide> // Stop stops the events command.
<ide> func (e *eventObserver) Stop() {
<ide> e.command.Process.Kill()
<add> e.command.Process.Release()
<ide> }
<ide>
<ide> // Match tries to match the events output with a given matcher.
<ide> func (e *eventObserver) TimeoutError(id, event string) error {
<ide> func (e *eventObserver) output() string {
<ide> return e.buffer.String()
<ide> }
<add>
<add>// matchEventLine matches a text with the event regular expression.
<add>// It returns the action and true if the regular expression matches with the given id and event type.
<add>// It returns an empty string and false if there is no match.
<add>func matchEventLine(id, eventType string, actions map[string]chan bool) eventMatcher {
<add> return func(text string) {
<add> matches := parseEventText(text)
<add> if matches == nil {
<add> return
<add> }
<add>
<add> if matchIDAndEventType(matches, id, eventType) {
<add> if ch, ok := actions[matches["action"]]; ok {
<add> close(ch)
<add> }
<add> }
<add> }
<add>}
<add>
<add>// parseEventText parses a line of events coming from the cli and returns
<add>// the matchers in a map.
<add>func parseEventText(text string) map[string]string {
<add> matches := eventCliRegexp.FindAllStringSubmatch(text, -1)
<add> if len(matches) == 0 {
<add> return nil
<add> }
<add>
<add> names := eventCliRegexp.SubexpNames()
<add> md := map[string]string{}
<add> for i, n := range matches[0] {
<add> md[names[i]] = n
<add> }
<add> return md
<add>}
<add>
<add>// parseEventAction parses an event text and returns the action.
<add>// It fails if the text is not in the event format.
<add>func parseEventAction(c *check.C, text string) string {
<add> matches := parseEventText(text)
<add> c.Assert(matches, checker.Not(checker.IsNil))
<add> return matches["action"]
<add>}
<add>
<add>// eventActionsByIDAndType returns the actions for a given id and type.
<add>// It fails if the text is not in the event format.
<add>func eventActionsByIDAndType(c *check.C, events []string, id, eventType string) []string {
<add> var filtered []string
<add> for _, event := range events {
<add> matches := parseEventText(event)
<add> c.Assert(matches, checker.Not(checker.IsNil))
<add> if matchIDAndEventType(matches, id, eventType) {
<add> filtered = append(filtered, matches["action"])
<add> }
<add> }
<add> return filtered
<add>}
<add>
<add>// matchIDAndEventType returns true if an event matches a given id and type.
<add>// It also resolves names in the event attributes if the id doesn't match.
<add>func matchIDAndEventType(matches map[string]string, id, eventType string) bool {
<add> return matchEventID(matches, id) && matches["eventType"] == eventType
<add>}
<add>
<add>func matchEventID(matches map[string]string, id string) bool {
<add> matchID := matches["id"] == id || strings.HasPrefix(matches["id"], id)
<add> if !matchID && matches["attributes"] != "" {
<add> // try matching a name in the attributes
<add> attributes := map[string]string{}
<add> for _, a := range strings.Split(matches["attributes"], ", ") {
<add> kv := strings.Split(a, "=")
<add> attributes[kv[0]] = kv[1]
<add> }
<add> matchID = attributes["name"] == id
<add> }
<add> return matchID
<add>}
<add>
<add>func parseEvents(c *check.C, out, match string) {
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add> for _, event := range events {
<add> matches := parseEventText(event)
<add> c.Assert(matches, checker.Not(checker.IsNil))
<add> matched, err := regexp.MatchString(match, matches["action"])
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(matched, checker.True)
<add> }
<add>}
<add>
<add>func parseEventsWithID(c *check.C, out, match, id string) {
<add> events := strings.Split(strings.TrimSpace(out), "\n")
<add> for _, event := range events {
<add> matches := parseEventText(event)
<add> c.Assert(matches, checker.Not(checker.IsNil))
<add> c.Assert(matchEventID(matches, id), checker.True)
<add>
<add> matched, err := regexp.MatchString(match, matches["action"])
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(matched, checker.True)
<add> }
<add>} | 23 |
Javascript | Javascript | improve performance for incoming headers | da0dc51e396ea4a1f12f259a8149f4177ad674e8 | <ide><path>benchmark/_http-benchmarkers.js
<ide> class AutocannonBenchmarker {
<ide> '-c', options.connections,
<ide> '-j',
<ide> '-n',
<del> `http://127.0.0.1:${options.port}${options.path}`,
<ide> ];
<add> for (const field in options.headers) {
<add> args.push('-H', `${field}=${options.headers[field]}`);
<add> }
<add> args.push(`http://127.0.0.1:${options.port}${options.path}`);
<ide> const child = child_process.spawn(this.executable, args);
<ide> return child;
<ide> }
<ide><path>benchmark/http/incoming_headers.js
<add>'use strict';
<add>const common = require('../common.js');
<add>const http = require('http');
<add>
<add>const bench = common.createBenchmark(main, {
<add> // unicode confuses ab on os x.
<add> c: [50, 500],
<add> headerDuplicates: [0, 5, 20]
<add>});
<add>
<add>function main({ c, headerDuplicates }) {
<add> const server = http.createServer((req, res) => {
<add> res.end();
<add> });
<add>
<add> server.listen(common.PORT, () => {
<add> const headers = {
<add> 'Content-Type': 'text/plain',
<add> 'Accept': 'text/plain',
<add> 'User-Agent': 'nodejs-benchmark',
<add> 'Date': new Date().toString(),
<add> 'Cache-Control': 'no-cache'
<add> };
<add> for (let i = 0; i < headerDuplicates; i++) {
<add> headers[`foo${i}`] = `some header value ${i}`;
<add> }
<add> bench.http({
<add> path: '/',
<add> connections: c,
<add> headers
<add> }, () => {
<add> server.close();
<add> });
<add> });
<add>}
<ide><path>lib/_http_incoming.js
<ide> function _addHeaderLines(headers, n) {
<ide> // TODO: perhaps http_parser could be returning both raw and lowercased versions
<ide> // of known header names to avoid us having to call toLowerCase() for those
<ide> // headers.
<del>
<del>// 'array' header list is taken from:
<del>// https://mxr.mozilla.org/mozilla/source/netwerk/protocol/http/src/nsHttpHeaderArray.cpp
<del>function matchKnownFields(field) {
<del> var low = false;
<del> while (true) {
<del> switch (field) {
<del> case 'Content-Type':
<del> case 'content-type':
<del> return 'content-type';
<del> case 'Content-Length':
<del> case 'content-length':
<del> return 'content-length';
<del> case 'User-Agent':
<del> case 'user-agent':
<del> return 'user-agent';
<del> case 'Referer':
<del> case 'referer':
<del> return 'referer';
<del> case 'Host':
<del> case 'host':
<del> return 'host';
<del> case 'Authorization':
<del> case 'authorization':
<del> return 'authorization';
<del> case 'Proxy-Authorization':
<del> case 'proxy-authorization':
<del> return 'proxy-authorization';
<del> case 'If-Modified-Since':
<del> case 'if-modified-since':
<del> return 'if-modified-since';
<del> case 'If-Unmodified-Since':
<del> case 'if-unmodified-since':
<del> return 'if-unmodified-since';
<del> case 'From':
<del> case 'from':
<del> return 'from';
<del> case 'Location':
<del> case 'location':
<add>function matchKnownFields(field, lowercased) {
<add> switch (field.length) {
<add> case 3:
<add> if (field === 'Age' || field === 'age') return 'age';
<add> break;
<add> case 4:
<add> if (field === 'Host' || field === 'host') return 'host';
<add> if (field === 'From' || field === 'from') return 'from';
<add> if (field === 'ETag' || field === 'etag') return 'etag';
<add> if (field === 'Date' || field === 'date') return '\u0000date';
<add> if (field === 'Vary' || field === 'vary') return '\u0000vary';
<add> break;
<add> case 6:
<add> if (field === 'Server' || field === 'server') return 'server';
<add> if (field === 'Cookie' || field === 'cookie') return '\u0002cookie';
<add> if (field === 'Origin' || field === 'origin') return '\u0000origin';
<add> if (field === 'Expect' || field === 'expect') return '\u0000expect';
<add> if (field === 'Accept' || field === 'accept') return '\u0000accept';
<add> break;
<add> case 7:
<add> if (field === 'Referer' || field === 'referer') return 'referer';
<add> if (field === 'Expires' || field === 'expires') return 'expires';
<add> if (field === 'Upgrade' || field === 'upgrade') return '\u0000upgrade';
<add> break;
<add> case 8:
<add> if (field === 'Location' || field === 'location')
<ide> return 'location';
<del> case 'Max-Forwards':
<del> case 'max-forwards':
<del> return 'max-forwards';
<del> case 'Retry-After':
<del> case 'retry-after':
<del> return 'retry-after';
<del> case 'ETag':
<del> case 'etag':
<del> return 'etag';
<del> case 'Last-Modified':
<del> case 'last-modified':
<del> return 'last-modified';
<del> case 'Server':
<del> case 'server':
<del> return 'server';
<del> case 'Age':
<del> case 'age':
<del> return 'age';
<del> case 'Expires':
<del> case 'expires':
<del> return 'expires';
<del> case 'Set-Cookie':
<del> case 'set-cookie':
<add> if (field === 'If-Match' || field === 'if-match')
<add> return '\u0000if-match';
<add> break;
<add> case 10:
<add> if (field === 'User-Agent' || field === 'user-agent')
<add> return 'user-agent';
<add> if (field === 'Set-Cookie' || field === 'set-cookie')
<ide> return '\u0001';
<del> case 'Cookie':
<del> case 'cookie':
<del> return '\u0002cookie';
<del> // The fields below are not used in _addHeaderLine(), but they are common
<del> // headers where we can avoid toLowerCase() if the mixed or lower case
<del> // versions match the first time through.
<del> case 'Transfer-Encoding':
<del> case 'transfer-encoding':
<del> return '\u0000transfer-encoding';
<del> case 'Date':
<del> case 'date':
<del> return '\u0000date';
<del> case 'Connection':
<del> case 'connection':
<add> if (field === 'Connection' || field === 'connection')
<ide> return '\u0000connection';
<del> case 'Cache-Control':
<del> case 'cache-control':
<add> break;
<add> case 11:
<add> if (field === 'Retry-After' || field === 'retry-after')
<add> return 'retry-after';
<add> break;
<add> case 12:
<add> if (field === 'Content-Type' || field === 'content-type')
<add> return 'content-type';
<add> if (field === 'Max-Forwards' || field === 'max-forwards')
<add> return 'max-forwards';
<add> break;
<add> case 13:
<add> if (field === 'Authorization' || field === 'authorization')
<add> return 'authorization';
<add> if (field === 'Last-Modified' || field === 'last-modified')
<add> return 'last-modified';
<add> if (field === 'Cache-Control' || field === 'cache-control')
<ide> return '\u0000cache-control';
<del> case 'Vary':
<del> case 'vary':
<del> return '\u0000vary';
<del> case 'Content-Encoding':
<del> case 'content-encoding':
<del> return '\u0000content-encoding';
<del> case 'Origin':
<del> case 'origin':
<del> return '\u0000origin';
<del> case 'Upgrade':
<del> case 'upgrade':
<del> return '\u0000upgrade';
<del> case 'Expect':
<del> case 'expect':
<del> return '\u0000expect';
<del> case 'If-Match':
<del> case 'if-match':
<del> return '\u0000if-match';
<del> case 'If-None-Match':
<del> case 'if-none-match':
<add> if (field === 'If-None-Match' || field === 'if-none-match')
<ide> return '\u0000if-none-match';
<del> case 'Accept':
<del> case 'accept':
<del> return '\u0000accept';
<del> case 'Accept-Encoding':
<del> case 'accept-encoding':
<add> break;
<add> case 14:
<add> if (field === 'Content-Length' || field === 'content-length')
<add> return 'content-length';
<add> break;
<add> case 15:
<add> if (field === 'Accept-Encoding' || field === 'accept-encoding')
<ide> return '\u0000accept-encoding';
<del> case 'Accept-Language':
<del> case 'accept-language':
<add> if (field === 'Accept-Language' || field === 'accept-language')
<ide> return '\u0000accept-language';
<del> case 'X-Forwarded-For':
<del> case 'x-forwarded-for':
<add> if (field === 'X-Forwarded-For' || field === 'x-forwarded-for')
<ide> return '\u0000x-forwarded-for';
<del> case 'X-Forwarded-Host':
<del> case 'x-forwarded-host':
<add> break;
<add> case 16:
<add> if (field === 'Content-Encoding' || field === 'content-encoding')
<add> return '\u0000content-encoding';
<add> if (field === 'X-Forwarded-Host' || field === 'x-forwarded-host')
<ide> return '\u0000x-forwarded-host';
<del> case 'X-Forwarded-Proto':
<del> case 'x-forwarded-proto':
<add> break;
<add> case 17:
<add> if (field === 'If-Modified-Since' || field === 'if-modified-since')
<add> return 'if-modified-since';
<add> if (field === 'Transfer-Encoding' || field === 'transfer-encoding')
<add> return '\u0000transfer-encoding';
<add> if (field === 'X-Forwarded-Proto' || field === 'x-forwarded-proto')
<ide> return '\u0000x-forwarded-proto';
<del> default:
<del> if (low)
<del> return '\u0000' + field;
<del> field = field.toLowerCase();
<del> low = true;
<del> }
<add> break;
<add> case 19:
<add> if (field === 'Proxy-Authorization' || field === 'proxy-authorization')
<add> return 'proxy-authorization';
<add> if (field === 'If-Unmodified-Since' || field === 'if-unmodified-since')
<add> return 'if-unmodified-since';
<add> break;
<add> }
<add> if (lowercased) {
<add> return '\u0000' + field;
<add> } else {
<add> return matchKnownFields(field.toLowerCase(), true);
<ide> }
<ide> }
<ide> // Add the given (field, value) pair to the message | 3 |
Javascript | Javascript | fix bad logic and created additional test to cover | ea2274a82fb1f7fee8c1cbe5f724ac06358026e2 | <ide><path>bin/webpack.js
<ide> function processOptions(options) {
<ide> var statsPresetToOptions = require("../lib/Stats.js").presetToOptions;
<ide>
<ide> if(Array.isArray(options)) {
<del> options = options.forEach(function(singleOption) {
<del> singleOption.stats = statsPresetToOptions(singleOption.stats);
<add> options.forEach(function(option) {
<add> option.stats = statsPresetToOptions(option.stats);
<ide> });
<ide> } else {
<ide> options.stats = statsPresetToOptions(options.stats);
<ide><path>test/binCases/stats/multi-config/index2.js
<add>module.exports = "bar";
<ide><path>test/binCases/stats/multi-config/test.js
<ide>
<ide> module.exports = function testAssertions(code, stdout, stderr) {
<ide> code.should.be.oneOf(0, 1);
<del>
<del> console.log(stdout);
<del>
<ide> stdout.should.be.ok();
<del>
<ide> stderr.should.be.empty();
<ide> }
<ide><path>test/binCases/stats/multi-config/webpack.config.js
<ide> var path = require("path");
<ide> module.exports = [
<ide> {
<ide> entry: path.resolve(__dirname, "./index"),
<del> stats: "none"
<add> stats: "errors-only"
<ide> },
<ide> {
<ide> entry: path.resolve(__dirname, "./index2"),
<del> stats: "none"
<add> stats: "errors-only"
<ide> }
<ide> ]; | 4 |
Ruby | Ruby | add test for argv.include? | 2f94d5f499bca6bbab238bb6536f05195b358159 | <ide><path>Library/Homebrew/rubocops/lines_cop.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> problem "Use `depends_on :fortran` instead of `ENV.fortran`"
<ide> end
<ide>
<del> # find_instance_method_call(body_node, :ARGV, :include?) do |m|
<del> # param = parameters(m).first
<del> # next unless match = regex_match_group(param, %r{--(HEAD|devel)})
<del> # problem "Use \"if build.#{match[1].downcase}?\" instead"
<del> # end
<del> #
<add> find_instance_method_call(body_node, "ARGV", :include?) do |m|
<add> param = parameters(m).first
<add> next unless match = regex_match_group(param, %r{--(HEAD|devel)})
<add> problem "Use \"if build.#{match[1].downcase}?\" instead"
<add> end
<add>
<ide> # find_const(body_node, :MACOS_VERSION) do
<ide> # problem "Use MacOS.version instead of MACOS_VERSION"
<ide> # end
<ide><path>Library/Homebrew/test/rubocops/lines_cop_spec.rb
<ide> class Foo < Formula
<ide> end
<ide> end
<ide>
<add> it "with ARGV.include? (--HEAD)" do
<add> source = <<-EOS.undent
<add> class Foo < Formula
<add> desc "foo"
<add> url 'http://example.com/foo-1.0.tgz'
<add> test do
<add> head = ARGV.include? "--HEAD"
<add> end
<add> end
<add> EOS
<add>
<add> expected_offenses = [{ message: "Use \"if build.head?\" instead",
<add> severity: :convention,
<add> line: 5,
<add> column: 26,
<add> source: source }]
<add>
<add> inspect_source(cop, source)
<add>
<add> expected_offenses.zip(cop.offenses).each do |expected, actual|
<add> expect_offense(expected, actual)
<add> end
<add> end
<add>
<ide> end
<ide> def expect_offense(expected, actual)
<ide> expect(actual.message).to eq(expected[:message]) | 2 |
Python | Python | improve vision models | 09178705101b9803e7b9ea7f79a46b4c242dd4bf | <ide><path>src/transformers/models/beit/modeling_beit.py
<ide> class BeitModelOutputWithPooling(BaseModelOutputWithPooling):
<ide> """
<ide>
<ide>
<del># Inspired by
<del># https://github.com/rwightman/pytorch-image-models/blob/b9bd960a032c75ca6b808ddeed76bee5f3ed4972/timm/models/layers/helpers.py
<del># From PyTorch internals
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<del># Based on https://github.com/rwightman/pytorch-image-models/blob/a2727c1bf78ba0d7b5727f5f95e37fb7f8866b1f/timm/models/layers/drop.py
<del>def drop_path(x: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
<add>def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
<ide> """
<ide> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<ide>
<ide> def drop_path(x: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -
<ide> argument.
<ide> """
<ide> if drop_prob == 0.0 or not training:
<del> return x
<add> return input
<ide> keep_prob = 1 - drop_prob
<del> shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<del> random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
<add> shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<add> random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
<ide> random_tensor.floor_() # binarize
<del> output = x.div(keep_prob) * random_tensor
<add> output = input.div(keep_prob) * random_tensor
<ide> return output
<ide>
<ide>
<del>class DropPath(nn.Module):
<add>class BeitDropPath(nn.Module):
<ide> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
<ide>
<ide> def __init__(self, drop_prob: Optional[float] = None) -> None:
<ide> def __init__(self, config: BeitConfig) -> None:
<ide> self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
<ide> else:
<ide> self.mask_token = None
<del> self.patch_embeddings = PatchEmbeddings(
<del> image_size=config.image_size,
<del> patch_size=config.patch_size,
<del> num_channels=config.num_channels,
<del> embed_dim=config.hidden_size,
<del> )
<add> self.patch_embeddings = BeitPatchEmbeddings(config)
<ide> num_patches = self.patch_embeddings.num_patches
<ide> if config.use_absolute_position_embeddings:
<ide> self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
<ide> def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Bo
<ide> return embeddings
<ide>
<ide>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del>class PatchEmbeddings(nn.Module):
<add>class BeitPatchEmbeddings(nn.Module):
<ide> """
<del> Image to Patch Embedding.
<add> This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
<add> `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
<add> Transformer.
<ide> """
<ide>
<del> def __init__(
<del> self, image_size: int = 224, patch_size: int = 16, num_channels: int = 3, embed_dim: int = 768
<del> ) -> None:
<add> def __init__(self, config):
<ide> super().__init__()
<del> image_size = to_2tuple(image_size)
<del> patch_size = to_2tuple(patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.hidden_size
<add>
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> patch_shape = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<add> self.num_channels = num_channels
<ide> self.num_patches = num_patches
<ide> self.patch_shape = patch_shape
<ide>
<del> self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
<add> self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
<ide>
<ide> def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
<ide> batch_size, num_channels, height, width = pixel_values.shape
<del> # FIXME look at relaxing size constraints
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> if height != self.image_size[0] or width != self.image_size[1]:
<ide> raise ValueError(
<ide> f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
<ide> )
<del> x = self.projection(pixel_values).flatten(2).transpose(1, 2)
<add> embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
<ide>
<del> return x
<add> return embeddings
<ide>
<ide>
<ide> class BeitSelfAttention(nn.Module):
<ide> def __init__(self, config: BeitConfig, window_size: Optional[tuple] = None, drop
<ide> self.intermediate = BeitIntermediate(config)
<ide> self.output = BeitOutput(config)
<ide> self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
<del> self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
<add> self.drop_path = BeitDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
<ide> self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
<ide>
<ide> init_values = config.layer_scale_init_value
<ide><path>src/transformers/models/beit/modeling_flax_beit.py
<ide> class FlaxBeitPatchEmbeddings(nn.Module):
<ide> dtype: jnp.dtype = jnp.float32 # the dtype of the computation
<ide>
<ide> def setup(self):
<add> self.num_channels = self.config.num_channels
<ide> image_size = self.config.image_size
<ide> patch_size = self.config.patch_size
<ide> num_patches = (image_size // patch_size) * (image_size // patch_size)
<ide> def setup(self):
<ide> )
<ide>
<ide> def __call__(self, pixel_values):
<add> num_channels = pixel_values.shape[-1]
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> embeddings = self.projection(pixel_values)
<ide> batch_size, _, _, channels = embeddings.shape
<ide> return jnp.reshape(embeddings, (batch_size, -1, channels))
<ide> def __init__(
<ide> ):
<ide> module = self.module_class(config=config, dtype=dtype, **kwargs)
<ide> if input_shape is None:
<del> input_shape = (1, config.image_size, config.image_size, 3)
<add> input_shape = (1, config.image_size, config.image_size, config.num_channels)
<ide> super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
<ide>
<ide> def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
<ide><path>src/transformers/models/convnext/modeling_convnext.py
<ide> ]
<ide>
<ide>
<del># Stochastic depth implementation
<del># Taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py
<del>def drop_path(x, drop_prob: float = 0.0, training: bool = False):
<add># Copied from transformers.models.beit.modeling_beit.drop_path
<add>def drop_path(input, drop_prob: float = 0.0, training: bool = False):
<ide> """
<del> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the
<del> DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop
<del> Connect' is a different form of dropout in a separate paper... See discussion:
<del> https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and
<del> argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument.
<add> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<add>
<add> Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
<add> however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
<add> See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
<add> layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
<add> argument.
<ide> """
<ide> if drop_prob == 0.0 or not training:
<del> return x
<add> return input
<ide> keep_prob = 1 - drop_prob
<del> shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<del> random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
<add> shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<add> random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
<ide> random_tensor.floor_() # binarize
<del> output = x.div(keep_prob) * random_tensor
<add> output = input.div(keep_prob) * random_tensor
<ide> return output
<ide>
<ide>
<add># Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->ConvNext
<ide> class ConvNextDropPath(nn.Module):
<ide> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
<ide>
<del> def __init__(self, drop_prob=None):
<add> def __init__(self, drop_prob: Optional[float] = None) -> None:
<ide> super().__init__()
<ide> self.drop_prob = drop_prob
<ide>
<ide> def forward(self, x: torch.Tensor) -> torch.Tensor:
<ide> return drop_path(x, self.drop_prob, self.training)
<ide>
<add> def extra_repr(self) -> str:
<add> return "p={}".format(self.drop_prob)
<add>
<ide>
<ide> class ConvNextLayerNorm(nn.Module):
<ide> r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
<ide> def __init__(self, config):
<ide> config.num_channels, config.hidden_sizes[0], kernel_size=config.patch_size, stride=config.patch_size
<ide> )
<ide> self.layernorm = ConvNextLayerNorm(config.hidden_sizes[0], eps=1e-6, data_format="channels_first")
<add> self.num_channels = config.num_channels
<ide>
<ide> def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
<add> num_channels = pixel_values.shape[1]
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> embeddings = self.patch_embeddings(pixel_values)
<ide> embeddings = self.layernorm(embeddings)
<ide> return embeddings
<ide><path>src/transformers/models/convnext/modeling_tf_convnext.py
<ide> import numpy as np
<ide> import tensorflow as tf
<ide>
<add>from transformers import shape_list
<add>
<ide> from ...activations_tf import get_tf_activation
<ide> from ...modeling_tf_outputs import TFBaseModelOutput, TFBaseModelOutputWithPooling, TFSequenceClassifierOutput
<ide> from ...modeling_tf_utils import (
<ide> def __init__(self, config, **kwargs):
<ide> bias_initializer="zeros",
<ide> )
<ide> self.layernorm = tf.keras.layers.LayerNormalization(epsilon=1e-6, name="layernorm")
<add> self.num_channels = config.num_channels
<ide>
<ide> def call(self, pixel_values):
<ide> if isinstance(pixel_values, dict):
<ide> pixel_values = pixel_values["pixel_values"]
<ide>
<add> num_channels = shape_list(pixel_values)[1]
<add> if tf.executing_eagerly() and num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<add>
<ide> # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
<ide> # So change the input format from `NCHW` to `NHWC`.
<ide> # shape = (batch_size, in_height, in_width, in_channels=num_channels)
<ide><path>src/transformers/models/cvt/modeling_cvt.py
<ide> class BaseModelOutputWithCLSToken(ModelOutput):
<ide> hidden_states: Optional[Tuple[torch.FloatTensor]] = None
<ide>
<ide>
<del># Copied from transformers.models.convnext.modeling_convnext.drop_path
<del>def drop_path(x, drop_prob: float = 0.0, training: bool = False):
<add># Copied from transformers.models.beit.modeling_beit.drop_path
<add>def drop_path(input, drop_prob: float = 0.0, training: bool = False):
<ide> """
<del> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the
<del> DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop
<del> Connect' is a different form of dropout in a separate paper... See discussion:
<del> https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and
<del> argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument.
<add> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<add>
<add> Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
<add> however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
<add> See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
<add> layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
<add> argument.
<ide> """
<ide> if drop_prob == 0.0 or not training:
<del> return x
<add> return input
<ide> keep_prob = 1 - drop_prob
<del> shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<del> random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
<add> shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<add> random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
<ide> random_tensor.floor_() # binarize
<del> output = x.div(keep_prob) * random_tensor
<add> output = input.div(keep_prob) * random_tensor
<ide> return output
<ide>
<ide>
<del># Copied from transformers.models.convnext.modeling_convnext.ConvNextDropPath
<add># Copied from transformers.models.beit.modeling_beit.BeitDropPath
<ide> class CvtDropPath(nn.Module):
<ide> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
<ide>
<del> def __init__(self, drop_prob=None):
<add> def __init__(self, drop_prob: Optional[float] = None) -> None:
<ide> super().__init__()
<ide> self.drop_prob = drop_prob
<ide>
<ide> def forward(self, x: torch.Tensor) -> torch.Tensor:
<ide> return drop_path(x, self.drop_prob, self.training)
<ide>
<add> def extra_repr(self) -> str:
<add> return "p={}".format(self.drop_prob)
<add>
<ide>
<ide> class CvtEmbeddings(nn.Module):
<ide> """
<ide><path>src/transformers/models/data2vec/modeling_data2vec_vision.py
<ide> class Data2VecVisionModelOutputWithPooling(BaseModelOutputWithPooling):
<ide> """
<ide>
<ide>
<del># Inspired by
<del># https://github.com/rwightman/pytorch-image-models/blob/b9bd960a032c75ca6b808ddeed76bee5f3ed4972/timm/models/layers/helpers.py
<del># From PyTorch internals
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<del># Based on https://github.com/rwightman/pytorch-image-models/blob/a2727c1bf78ba0d7b5727f5f95e37fb7f8866b1f/timm/models/layers/drop.py
<ide> # Copied from transformers.models.beit.modeling_beit.drop_path
<del>def drop_path(x: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
<add>def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
<ide> """
<ide> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<ide>
<ide> def drop_path(x: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -
<ide> argument.
<ide> """
<ide> if drop_prob == 0.0 or not training:
<del> return x
<add> return input
<ide> keep_prob = 1 - drop_prob
<del> shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<del> random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
<add> shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<add> random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
<ide> random_tensor.floor_() # binarize
<del> output = x.div(keep_prob) * random_tensor
<add> output = input.div(keep_prob) * random_tensor
<ide> return output
<ide>
<ide>
<del># Copied from transformers.models.beit.modeling_beit.DropPath
<del>class DropPath(nn.Module):
<add># Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->Data2VecVision
<add>class Data2VecVisionDropPath(nn.Module):
<ide> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
<ide>
<ide> def __init__(self, drop_prob: Optional[float] = None) -> None:
<ide> def extra_repr(self) -> str:
<ide> return "p={}".format(self.drop_prob)
<ide>
<ide>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<ide> # Copied from transformers.models.beit.modeling_beit.BeitEmbeddings with Beit->Data2VecVision
<ide> class Data2VecVisionEmbeddings(nn.Module):
<ide> """
<ide> def __init__(self, config: Data2VecVisionConfig) -> None:
<ide> self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
<ide> else:
<ide> self.mask_token = None
<del> self.patch_embeddings = PatchEmbeddings(
<del> image_size=config.image_size,
<del> patch_size=config.patch_size,
<del> num_channels=config.num_channels,
<del> embed_dim=config.hidden_size,
<del> )
<add> self.patch_embeddings = Data2VecVisionPatchEmbeddings(config)
<ide> num_patches = self.patch_embeddings.num_patches
<ide> if config.use_absolute_position_embeddings:
<ide> self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
<ide> def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Bo
<ide> return embeddings
<ide>
<ide>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del># Copied from transformers.models.beit.modeling_beit.PatchEmbeddings
<del>class PatchEmbeddings(nn.Module):
<add># Copied from transformers.models.beit.modeling_beit.BeitPatchEmbeddings with Beit->Data2VecVision
<add>class Data2VecVisionPatchEmbeddings(nn.Module):
<ide> """
<del> Image to Patch Embedding.
<add> This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
<add> `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
<add> Transformer.
<ide> """
<ide>
<del> def __init__(
<del> self, image_size: int = 224, patch_size: int = 16, num_channels: int = 3, embed_dim: int = 768
<del> ) -> None:
<add> def __init__(self, config):
<ide> super().__init__()
<del> image_size = to_2tuple(image_size)
<del> patch_size = to_2tuple(patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.hidden_size
<add>
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> patch_shape = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<add> self.num_channels = num_channels
<ide> self.num_patches = num_patches
<ide> self.patch_shape = patch_shape
<ide>
<del> self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
<add> self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
<ide>
<ide> def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
<ide> batch_size, num_channels, height, width = pixel_values.shape
<del> # FIXME look at relaxing size constraints
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> if height != self.image_size[0] or width != self.image_size[1]:
<ide> raise ValueError(
<ide> f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
<ide> )
<del> x = self.projection(pixel_values).flatten(2).transpose(1, 2)
<add> embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
<ide>
<del> return x
<add> return embeddings
<ide>
<ide>
<ide> # Copied from transformers.models.beit.modeling_beit.BeitSelfAttention with Beit->Data2VecVision
<ide> def __init__(
<ide> self.intermediate = Data2VecVisionIntermediate(config)
<ide> self.output = Data2VecVisionOutput(config)
<ide> self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
<del> self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
<add> self.drop_path = Data2VecVisionDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
<ide> self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
<ide>
<ide> init_values = config.layer_scale_init_value
<ide><path>src/transformers/models/data2vec/modeling_tf_data2vec_vision.py
<ide> class TFData2VecVisionModelOutputWithPooling(TFBaseModelOutputWithPooling):
<ide> attentions: Optional[Tuple[tf.Tensor]] = None
<ide>
<ide>
<del>class TFDropPath(tf.keras.layers.Layer):
<add>class TFData2VecVisionDropPath(tf.keras.layers.Layer):
<ide> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<ide> References:
<ide> (1) github.com:rwightman/pytorch-image-models
<ide> def call(self, x, training=None):
<ide> return x
<ide>
<ide>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<ide> class TFData2VecVisionEmbeddings(tf.keras.layers.Layer):
<ide> """
<ide> Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
<ide> def __init__(self, config: Data2VecVisionConfig, **kwargs):
<ide> super().__init__(**kwargs)
<ide> self.config = config
<ide>
<del> self.patch_embeddings = TFPatchEmbeddings(
<del> config=config, image_size=config.image_size, patch_size=config.patch_size, name="patch_embeddings"
<del> )
<add> self.patch_embeddings = TFData2VecVisionPatchEmbeddings(config, name="patch_embeddings")
<ide> self.num_patches = self.patch_embeddings.num_patches
<ide> self.config = config
<ide>
<ide> def call(self, pixel_values: tf.Tensor, bool_masked_pos: Optional[tf.Tensor] = N
<ide> return embeddings
<ide>
<ide>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del>class TFPatchEmbeddings(tf.keras.layers.Layer):
<add>class TFData2VecVisionPatchEmbeddings(tf.keras.layers.Layer):
<ide> """
<ide> Image to Patch Embedding.
<ide> """
<ide>
<del> def __init__(self, config: Data2VecVisionConfig, image_size: int = 224, patch_size: int = 16, **kwargs):
<add> def __init__(self, config: Data2VecVisionConfig, **kwargs):
<ide> super().__init__(**kwargs)
<ide> self.config = config
<ide>
<del> image_size = (
<del> config.image_size
<del> if isinstance(config.image_size, collections.abc.Iterable)
<del> else (config.image_size, config.image_size)
<del> )
<del> patch_size = (
<del> config.patch_size
<del> if isinstance(config.patch_size, collections.abc.Iterable)
<del> else (config.patch_size, config.patch_size)
<del> )
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.hidden_size
<add>
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> patch_shape = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<ide> self.num_patches = num_patches
<ide> self.patch_shape = patch_shape
<del> self.num_channels = config.num_channels
<del> self.embed_dim = config.hidden_size
<add> self.num_channels = num_channels
<ide>
<ide> self.projection = tf.keras.layers.Conv2D(
<del> filters=self.embed_dim,
<del> kernel_size=self.patch_size,
<del> strides=self.patch_size,
<add> filters=hidden_size,
<add> kernel_size=patch_size,
<add> strides=patch_size,
<ide> padding="valid",
<ide> data_format="channels_last",
<ide> kernel_initializer="glorot_uniform", # following torch.nn.Linear
<ide> def __init__(self, config: Data2VecVisionConfig, image_size: int = 224, patch_si
<ide>
<ide> def call(self, pixel_values: tf.Tensor, training: bool = False) -> tf.Tensor:
<ide> batch_size, num_channels, height, width = shape_list(pixel_values)
<del> if getattr(height, "numpy", None) and getattr(width, "numpy", None):
<add> if tf.executing_eagerly():
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the"
<add> " configuration."
<add> )
<ide> if height != self.image_size[0] or width != self.image_size[1]:
<ide> raise ValueError(
<ide> f"Input image size ({height}*{width}) doesn't match model"
<ide> def __init__(
<ide> # Using `layers.Activation` instead of `tf.identity` to better control `training`
<ide> # behaviour.
<ide> self.drop_path = (
<del> TFDropPath(drop_path_rate, name="drop_path")
<add> TFData2VecVisionDropPath(drop_path_rate, name="drop_path")
<ide> if drop_path_rate > 0.0
<ide> else tf.keras.layers.Activation("linear", name="drop_path")
<ide> )
<ide><path>src/transformers/models/deit/modeling_deit.py
<ide> ]
<ide>
<ide>
<del># Copied from transformers.models.vit.modeling_vit.to_2tuple
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del>
<del>
<ide> class DeiTEmbeddings(nn.Module):
<ide> """
<ide> Construct the CLS token, distillation token, position and patch embeddings. Optionally, also the mask token.
<del>
<ide> """
<ide>
<ide> def __init__(self, config: DeiTConfig, use_mask_token: bool = False) -> None:
<ide> def __init__(self, config: DeiTConfig, use_mask_token: bool = False) -> None:
<ide> self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
<ide> self.distillation_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
<ide> self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
<del> self.patch_embeddings = PatchEmbeddings(
<del> image_size=config.image_size,
<del> patch_size=config.patch_size,
<del> num_channels=config.num_channels,
<del> embed_dim=config.hidden_size,
<del> )
<add> self.patch_embeddings = DeiTPatchEmbeddings(config)
<ide> num_patches = self.patch_embeddings.num_patches
<ide> self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 2, config.hidden_size))
<ide> self.dropout = nn.Dropout(config.hidden_dropout_prob)
<ide>
<ide> def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.BoolTensor] = None) -> torch.Tensor:
<ide> embeddings = self.patch_embeddings(pixel_values)
<del> batch_size, seq_len, _ = embeddings.size()
<add> batch_size, seq_length, _ = embeddings.size()
<ide>
<ide> if bool_masked_pos is not None:
<del> mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
<add> mask_tokens = self.mask_token.expand(batch_size, seq_length, -1)
<ide> # replace the masked visual tokens by mask_tokens
<ide> mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
<ide> embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
<ide> def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Bo
<ide> return embeddings
<ide>
<ide>
<del>class PatchEmbeddings(nn.Module):
<add>class DeiTPatchEmbeddings(nn.Module):
<ide> """
<del> Image to Patch Embedding.
<del>
<add> This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
<add> `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
<add> Transformer.
<ide> """
<ide>
<del> def __init__(
<del> self,
<del> image_size: int = 224,
<del> patch_size: Union[int, Tuple[int, int]] = 16,
<del> num_channels: int = 3,
<del> embed_dim: int = 768,
<del> ) -> None:
<add> def __init__(self, config):
<ide> super().__init__()
<del> image_size = to_2tuple(image_size)
<del> patch_size = to_2tuple(patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.hidden_size
<add>
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<add> self.num_channels = num_channels
<ide> self.num_patches = num_patches
<ide>
<del> self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
<add> self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
<ide>
<ide> def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
<ide> batch_size, num_channels, height, width = pixel_values.shape
<del> # FIXME look at relaxing size constraints
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> if height != self.image_size[0] or width != self.image_size[1]:
<ide> raise ValueError(
<ide> f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
<ide> def __init__(self, config: DeiTConfig, add_pooling_layer: bool = True, use_mask_
<ide> # Initialize weights and apply final processing
<ide> self.post_init()
<ide>
<del> def get_input_embeddings(self) -> PatchEmbeddings:
<add> def get_input_embeddings(self) -> DeiTPatchEmbeddings:
<ide> return self.embeddings.patch_embeddings
<ide>
<ide> def _prune_heads(self, heads_to_prune):
<ide> def forward(self, hidden_states):
<ide>
<ide>
<ide> @add_start_docstrings(
<del> "DeiT Model with a decoder on top for masked image modeling, as proposed in `SimMIM"
<del> " <https://arxiv.org/abs/2111.09886>`__.",
<add> "DeiT Model with a decoder on top for masked image modeling, as proposed in"
<add> " [SimMIM](https://arxiv.org/abs/2111.09886).",
<ide> DEIT_START_DOCSTRING,
<ide> )
<ide> class DeiTForMaskedImageModeling(DeiTPreTrainedModel):
<ide> def __init__(self, config: DeiTConfig) -> None:
<ide> self.deit = DeiTModel(config, add_pooling_layer=False, use_mask_token=True)
<ide>
<ide> self.decoder = nn.Sequential(
<del> nn.Conv2d(in_channels=config.hidden_size, out_channels=config.encoder_stride**2 * 3, kernel_size=1),
<add> nn.Conv2d(
<add> in_channels=config.hidden_size,
<add> out_channels=config.encoder_stride**2 * config.num_channels,
<add> kernel_size=1,
<add> ),
<ide> nn.PixelShuffle(config.encoder_stride),
<ide> )
<ide>
<ide><path>src/transformers/models/dpt/modeling_dpt.py
<ide> ]
<ide>
<ide>
<del># Copied from transformers.models.vit.modeling_vit.to_2tuple
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<ide> class DPTViTEmbeddings(nn.Module):
<ide> """
<ide> Construct the CLS token, position and patch embeddings.
<ide> def __init__(self, config):
<ide> super().__init__()
<ide>
<ide> self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
<del> self.patch_embeddings = DPTViTPatchEmbeddings(
<del> image_size=config.image_size,
<del> patch_size=config.patch_size,
<del> num_channels=config.num_channels,
<del> embed_dim=config.hidden_size,
<del> )
<add> self.patch_embeddings = DPTViTPatchEmbeddings(config)
<ide> num_patches = self.patch_embeddings.num_patches
<ide> self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
<ide> self.dropout = nn.Dropout(config.hidden_dropout_prob)
<ide> class DPTViTPatchEmbeddings(nn.Module):
<ide>
<ide> """
<ide>
<del> def __init__(self, image_size=224, patch_size=16, num_channels=3, embed_dim=768):
<add> def __init__(self, config):
<ide> super().__init__()
<del> image_size = to_2tuple(image_size)
<del> patch_size = to_2tuple(patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.hidden_size
<add>
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<add> self.num_channels = num_channels
<ide> self.num_patches = num_patches
<ide>
<del> self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
<add> self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
<ide>
<ide> def forward(self, pixel_values):
<ide> batch_size, num_channels, height, width = pixel_values.shape
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
<ide> return embeddings
<ide>
<ide><path>src/transformers/models/glpn/modeling_glpn.py
<ide>
<ide>
<ide> # Copied from transformers.models.segformer.modeling_segformer.drop_path
<del>def drop_path(x, drop_prob: float = 0.0, training: bool = False):
<add>def drop_path(input, drop_prob: float = 0.0, training: bool = False):
<ide> """
<del> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the
<del> DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop
<del> Connect' is a different form of dropout in a separate paper... See discussion:
<del> https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and
<del> argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument.
<add> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<add>
<add> Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
<add> however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
<add> See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
<add> layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
<add> argument.
<ide> """
<ide> if drop_prob == 0.0 or not training:
<del> return x
<add> return input
<ide> keep_prob = 1 - drop_prob
<del> shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<del> random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
<add> shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<add> random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
<ide> random_tensor.floor_() # binarize
<del> output = x.div(keep_prob) * random_tensor
<add> output = input.div(keep_prob) * random_tensor
<ide> return output
<ide>
<ide>
<ide> # Copied from transformers.models.segformer.modeling_segformer.SegformerDropPath
<ide> class GLPNDropPath(nn.Module):
<ide> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
<ide>
<del> def __init__(self, drop_prob=None):
<add> def __init__(self, drop_prob: Optional[float] = None) -> None:
<ide> super().__init__()
<ide> self.drop_prob = drop_prob
<ide>
<ide> def forward(self, x: torch.Tensor) -> torch.Tensor:
<ide> return drop_path(x, self.drop_prob, self.training)
<ide>
<add> def extra_repr(self) -> str:
<add> return "p={}".format(self.drop_prob)
<add>
<ide>
<ide> # Copied from transformers.models.segformer.modeling_segformer.SegformerOverlapPatchEmbeddings
<ide> class GLPNOverlapPatchEmbeddings(nn.Module):
<ide><path>src/transformers/models/levit/modeling_levit.py
<ide> def __init__(self, config):
<ide> self.embedding_layer_4 = LevitConvEmbeddings(
<ide> config.hidden_sizes[0] // 2, config.hidden_sizes[0], config.kernel_size, config.stride, config.padding
<ide> )
<add> self.num_channels = config.num_channels
<ide>
<ide> def forward(self, pixel_values):
<add> num_channels = pixel_values.shape[1]
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> embeddings = self.embedding_layer_1(pixel_values)
<ide> embeddings = self.activation_layer_1(embeddings)
<ide> embeddings = self.embedding_layer_2(embeddings)
<ide><path>src/transformers/models/maskformer/modeling_maskformer.py
<ide> def pair_wise_sigmoid_focal_loss(inputs: Tensor, labels: Tensor, alpha: float =
<ide> return loss / height_and_width
<ide>
<ide>
<del># Copied from transformers.models.vit.modeling_vit.to_2tuple
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<ide> # Copied from transformers.models.swin.modeling_swin.window_partition
<ide> def window_partition(input_feature, window_size):
<ide> """
<ide> def window_reverse(windows, window_size, height, width):
<ide> def drop_path(input, drop_prob=0.0, training=False, scale_by_keep=True):
<ide> """
<ide> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<add>
<add> Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
<add> however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
<add> See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
<add> layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
<add> argument.
<ide> """
<ide> if drop_prob == 0.0 or not training:
<ide> return input
<ide> keep_prob = 1 - drop_prob
<ide> shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<del> random_tensor = input.new_empty(shape).bernoulli_(keep_prob)
<del> if keep_prob > 0.0 and scale_by_keep:
<del> random_tensor.div_(keep_prob)
<del> return input * random_tensor
<add> random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
<add> random_tensor.floor_() # binarize
<add> output = input.div(keep_prob) * random_tensor
<add> return output
<ide>
<ide>
<ide> class MaskFormerSwinEmbeddings(nn.Module):
<ide> class MaskFormerSwinEmbeddings(nn.Module):
<ide> def __init__(self, config):
<ide> super().__init__()
<ide>
<del> self.patch_embeddings = MaskFormerSwinPatchEmbeddings(
<del> image_size=config.image_size,
<del> patch_size=config.patch_size,
<del> num_channels=config.num_channels,
<del> embed_dim=config.embed_dim,
<del> )
<add> self.patch_embeddings = MaskFormerSwinPatchEmbeddings(config)
<ide> num_patches = self.patch_embeddings.num_patches
<ide> self.patch_grid = self.patch_embeddings.grid_size
<ide>
<ide> class MaskFormerSwinPatchEmbeddings(nn.Module):
<ide> Image to Patch Embedding, including padding.
<ide> """
<ide>
<del> def __init__(self, image_size=224, patch_size=16, num_channels=3, embed_dim=768):
<add> def __init__(self, config):
<ide> super().__init__()
<del> image_size = to_2tuple(image_size)
<del> patch_size = to_2tuple(patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.embed_dim
<add>
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<add> self.num_channels = num_channels
<ide> self.num_patches = num_patches
<ide> self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
<ide>
<del> self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
<add> self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
<ide>
<ide> def maybe_pad(self, pixel_values, height, width):
<ide> if width % self.patch_size[1] != 0:
<ide> def maybe_pad(self, pixel_values, height, width):
<ide> return pixel_values
<ide>
<ide> def forward(self, pixel_values):
<del> _, _, height, width = pixel_values.shape
<add> _, num_channels, height, width = pixel_values.shape
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> # pad the input to be divisible by self.patch_size, if needed
<ide> pixel_values = self.maybe_pad(pixel_values, height, width)
<ide> embeddings = self.projection(pixel_values)
<ide> def forward(self, input_feature, input_dimensions):
<ide> class MaskFormerSwinDropPath(nn.Module):
<ide> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
<ide>
<del> def __init__(self, drop_prob=None, scale_by_keep=True):
<del> super(MaskFormerSwinDropPath, self).__init__()
<add> def __init__(self, drop_prob: Optional[float] = None) -> None:
<add> super().__init__()
<ide> self.drop_prob = drop_prob
<del> self.scale_by_keep = scale_by_keep
<ide>
<del> def forward(self, input):
<del> return drop_path(input, self.drop_prob, self.training, self.scale_by_keep)
<add> def forward(self, x: torch.Tensor) -> torch.Tensor:
<add> return drop_path(x, self.drop_prob, self.training)
<add>
<add> def extra_repr(self) -> str:
<add> return "p={}".format(self.drop_prob)
<ide>
<ide>
<ide> # Copied from transformers.models.swin.modeling_swin.SwinSelfAttention with Swin->MaskFormerSwin
<ide> def __init__(self, config, dim, num_heads):
<ide> self.num_attention_heads = num_heads
<ide> self.attention_head_size = int(dim / num_heads)
<ide> self.all_head_size = self.num_attention_heads * self.attention_head_size
<del> self.window_size = to_2tuple(config.window_size)
<add> window_size = config.window_size
<add> self.window_size = (
<add> window_size if isinstance(window_size, collections.abc.Iterable) else (window_size, window_size)
<add> )
<ide>
<ide> self.relative_position_bias_table = nn.Parameter(
<ide> torch.zeros((2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1), num_heads)
<ide><path>src/transformers/models/poolformer/modeling_poolformer.py
<ide> ]
<ide>
<ide>
<del># Copied from transformers.models.vit.modeling_vit.to_2tuple
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<del>def drop_path(x, drop_prob: float = 0.0, training: bool = False):
<del> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<del> This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is
<del> misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion:
<del> https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and
<del> argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument.
<add># Copied from transformers.models.beit.modeling_beit.drop_path
<add>def drop_path(input, drop_prob: float = 0.0, training: bool = False):
<add> """
<add> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<add>
<add> Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
<add> however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
<add> See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
<add> layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
<add> argument.
<ide> """
<ide> if drop_prob == 0.0 or not training:
<del> return x
<add> return input
<ide> keep_prob = 1 - drop_prob
<del> shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<del> random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
<add> shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<add> random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
<ide> random_tensor.floor_() # binarize
<del> output = x.div(keep_prob) * random_tensor
<add> output = input.div(keep_prob) * random_tensor
<ide> return output
<ide>
<ide>
<add># Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->PoolFormer
<ide> class PoolFormerDropPath(nn.Module):
<ide> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
<ide>
<del> def __init__(self, drop_prob=None):
<add> def __init__(self, drop_prob: Optional[float] = None) -> None:
<ide> super().__init__()
<ide> self.drop_prob = drop_prob
<ide>
<del> def forward(self, x):
<add> def forward(self, x: torch.Tensor) -> torch.Tensor:
<ide> return drop_path(x, self.drop_prob, self.training)
<ide>
<add> def extra_repr(self) -> str:
<add> return "p={}".format(self.drop_prob)
<add>
<ide>
<ide> class PoolFormerEmbeddings(nn.Module):
<ide> """
<ide> class PoolFormerEmbeddings(nn.Module):
<ide>
<ide> def __init__(self, hidden_size, num_channels, patch_size, stride, padding, norm_layer=None):
<ide> super().__init__()
<del> patch_size = to_2tuple(patch_size)
<del> stride = to_2tuple(stride)
<del> padding = to_2tuple(padding)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<add> stride = stride if isinstance(stride, collections.abc.Iterable) else (stride, stride)
<add> padding = padding if isinstance(padding, collections.abc.Iterable) else (padding, padding)
<ide>
<ide> self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=stride, padding=padding)
<ide> self.norm = norm_layer(hidden_size) if norm_layer else nn.Identity()
<ide>
<ide> def forward(self, pixel_values):
<del> x = self.projection(pixel_values)
<del> x = self.norm(x)
<del> return x
<add> embeddings = self.projection(pixel_values)
<add> embeddings = self.norm(embeddings)
<add> return embeddings
<ide>
<ide>
<ide> class PoolFormerGroupNorm(nn.GroupNorm):
<ide><path>src/transformers/models/regnet/modeling_regnet.py
<ide> def __init__(self, config: RegNetConfig):
<ide> self.embedder = RegNetConvLayer(
<ide> config.num_channels, config.embedding_size, kernel_size=3, stride=2, activation=config.hidden_act
<ide> )
<add> self.num_channels = config.num_channels
<ide>
<del> def forward(self, hidden_state):
<del> hidden_state = self.embedder(hidden_state)
<add> def forward(self, pixel_values):
<add> num_channels = pixel_values.shape[1]
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<add> hidden_state = self.embedder(pixel_values)
<ide> return hidden_state
<ide>
<ide>
<ide><path>src/transformers/models/resnet/modeling_resnet.py
<ide> def __init__(self, config: ResNetConfig):
<ide> config.num_channels, config.embedding_size, kernel_size=7, stride=2, activation=config.hidden_act
<ide> )
<ide> self.pooler = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
<add> self.num_channels = config.num_channels
<ide>
<del> def forward(self, input: Tensor) -> Tensor:
<del> embedding = self.embedder(input)
<add> def forward(self, pixel_values: Tensor) -> Tensor:
<add> num_channels = pixel_values.shape[1]
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<add> embedding = self.embedder(pixel_values)
<ide> embedding = self.pooler(embedding)
<ide> return embedding
<ide>
<ide> def forward(self, input: Tensor) -> Tensor:
<ide>
<ide> class ResNetBasicLayer(nn.Module):
<ide> """
<del> A classic ResNet's residual layer composed by a two `3x3` convolutions.
<add> A classic ResNet's residual layer composed by two `3x3` convolutions.
<ide> """
<ide>
<ide> def __init__(self, in_channels: int, out_channels: int, stride: int = 1, activation: str = "relu"):
<ide> def forward(self, hidden_state):
<ide>
<ide> class ResNetBottleNeckLayer(nn.Module):
<ide> """
<del> A classic ResNet's bottleneck layer composed by a three `3x3` convolutions.
<add> A classic ResNet's bottleneck layer composed by three `3x3` convolutions.
<ide>
<ide> The first `1x1` convolution reduces the input by a factor of `reduction` in order to make the second `3x3`
<del> convolution faster. The last `1x1` convolution remap the reduced features to `out_channels`.
<add> convolution faster. The last `1x1` convolution remaps the reduced features to `out_channels`.
<ide> """
<ide>
<ide> def __init__(
<ide><path>src/transformers/models/segformer/modeling_segformer.py
<ide> class SegFormerImageClassifierOutput(ImageClassifierOutput):
<ide>
<ide>
<ide> # Copied from transformers.models.convnext.modeling_convnext.drop_path
<del>def drop_path(x, drop_prob: float = 0.0, training: bool = False, scale_by_keep=True):
<add>def drop_path(input, drop_prob: float = 0.0, training: bool = False, scale_by_keep=True):
<ide> """
<del> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the
<del> DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop
<del> Connect' is a different form of dropout in a separate paper... See discussion:
<del> https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and
<del> argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument.
<add> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<add>
<add> Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
<add> however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
<add> See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
<add> layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
<add> argument.
<ide> """
<ide> if drop_prob == 0.0 or not training:
<del> return x
<add> return input
<ide> keep_prob = 1 - drop_prob
<del> shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<del> random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
<add> shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<add> random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
<ide> random_tensor.floor_() # binarize
<del> output = x.div(keep_prob) * random_tensor
<add> output = input.div(keep_prob) * random_tensor
<ide> return output
<ide>
<ide>
<ide> # Copied from transformers.models.convnext.modeling_convnext.ConvNextDropPath with ConvNext->Segformer
<ide> class SegformerDropPath(nn.Module):
<ide> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
<ide>
<del> def __init__(self, drop_prob=None):
<add> def __init__(self, drop_prob: Optional[float] = None) -> None:
<ide> super().__init__()
<ide> self.drop_prob = drop_prob
<ide>
<ide> def forward(self, x: torch.Tensor) -> torch.Tensor:
<ide> return drop_path(x, self.drop_prob, self.training)
<ide>
<add> def extra_repr(self) -> str:
<add> return "p={}".format(self.drop_prob)
<add>
<ide>
<ide> class SegformerOverlapPatchEmbeddings(nn.Module):
<ide> """Construct the overlapping patch embeddings."""
<ide><path>src/transformers/models/swin/modeling_swin.py
<ide> # See all Swin models at https://huggingface.co/models?filter=swin
<ide> ]
<ide>
<del># to_2tuple, drop_path, SwinPatchEmbeddings, SwinPatchMerging and SwinDropPath are from the timm library.
<add># drop_path, SwinPatchEmbeddings, SwinPatchMerging and SwinDropPath are from the timm library.
<ide>
<ide>
<ide> @dataclass
<ide> class SwinImageClassifierOutput(ModelOutput):
<ide> reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
<ide>
<ide>
<del># Copied from transformers.models.vit.modeling_vit.to_2tuple
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<ide> def window_partition(input_feature, window_size):
<ide> """
<ide> Partitions the given input into windows.
<ide> def window_reverse(windows, window_size, height, width):
<ide> return windows
<ide>
<ide>
<del>def drop_path(input, drop_prob=0.0, training=False, scale_by_keep=True):
<del> """
<del> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<del> """
<del> if drop_prob == 0.0 or not training:
<del> return input
<del> keep_prob = 1 - drop_prob
<del> shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<del> random_tensor = input.new_empty(shape).bernoulli_(keep_prob)
<del> if keep_prob > 0.0 and scale_by_keep:
<del> random_tensor.div_(keep_prob)
<del> return input * random_tensor
<del>
<del>
<ide> class SwinEmbeddings(nn.Module):
<ide> """
<ide> Construct the patch and position embeddings. Optionally, also the mask token.
<ide> class SwinEmbeddings(nn.Module):
<ide> def __init__(self, config, use_mask_token=False):
<ide> super().__init__()
<ide>
<del> self.patch_embeddings = SwinPatchEmbeddings(
<del> image_size=config.image_size,
<del> patch_size=config.patch_size,
<del> num_channels=config.num_channels,
<del> embed_dim=config.embed_dim,
<del> )
<add> self.patch_embeddings = SwinPatchEmbeddings(config)
<ide> num_patches = self.patch_embeddings.num_patches
<ide> self.patch_grid = self.patch_embeddings.grid_size
<ide> self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
<ide> def forward(
<ide>
<ide> class SwinPatchEmbeddings(nn.Module):
<ide> """
<del> Image to Patch Embedding.
<add> This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
<add> `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
<add> Transformer.
<ide> """
<ide>
<del> def __init__(self, image_size=224, patch_size=16, num_channels=3, embed_dim=768):
<add> def __init__(self, config):
<ide> super().__init__()
<del> image_size = to_2tuple(image_size)
<del> patch_size = to_2tuple(patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.embed_dim
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<add> self.num_channels = num_channels
<ide> self.num_patches = num_patches
<ide> self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
<ide>
<del> self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
<add> self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
<ide>
<ide> def maybe_pad(self, pixel_values, height, width):
<ide> if width % self.patch_size[1] != 0:
<ide> def maybe_pad(self, pixel_values, height, width):
<ide> return pixel_values
<ide>
<ide> def forward(self, pixel_values: Optional[torch.FloatTensor]) -> Tuple[torch.Tensor, Tuple[int]]:
<del> _, _, height, width = pixel_values.shape
<add> _, num_channels, height, width = pixel_values.shape
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> # pad the input to be divisible by self.patch_size, if needed
<ide> pixel_values = self.maybe_pad(pixel_values, height, width)
<ide> embeddings = self.projection(pixel_values)
<ide> def forward(self, input_feature: torch.Tensor, input_dimensions: Tuple[int, int]
<ide> return input_feature
<ide>
<ide>
<add># Copied from transformers.models.beit.modeling_beit.drop_path
<add>def drop_path(input, drop_prob=0.0, training=False, scale_by_keep=True):
<add> """
<add> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<add>
<add> Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
<add> however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
<add> See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
<add> layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
<add> argument.
<add> """
<add> if drop_prob == 0.0 or not training:
<add> return input
<add> keep_prob = 1 - drop_prob
<add> shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<add> random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
<add> random_tensor.floor_() # binarize
<add> output = input.div(keep_prob) * random_tensor
<add> return output
<add>
<add>
<add># Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->Swin
<ide> class SwinDropPath(nn.Module):
<ide> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
<ide>
<del> def __init__(self, drop_prob=None, scale_by_keep=True):
<del> super(SwinDropPath, self).__init__()
<add> def __init__(self, drop_prob: Optional[float] = None) -> None:
<add> super().__init__()
<ide> self.drop_prob = drop_prob
<del> self.scale_by_keep = scale_by_keep
<ide>
<del> def forward(self, input):
<del> return drop_path(input, self.drop_prob, self.training, self.scale_by_keep)
<add> def forward(self, x: torch.Tensor) -> torch.Tensor:
<add> return drop_path(x, self.drop_prob, self.training)
<add>
<add> def extra_repr(self) -> str:
<add> return "p={}".format(self.drop_prob)
<ide>
<ide>
<ide> class SwinSelfAttention(nn.Module):
<ide> def __init__(self, config, dim, num_heads):
<ide> self.num_attention_heads = num_heads
<ide> self.attention_head_size = int(dim / num_heads)
<ide> self.all_head_size = self.num_attention_heads * self.attention_head_size
<del> self.window_size = to_2tuple(config.window_size)
<add> window_size = config.window_size
<add> self.window_size = (
<add> window_size if isinstance(window_size, collections.abc.Iterable) else (window_size, window_size)
<add> )
<ide>
<ide> self.relative_position_bias_table = nn.Parameter(
<ide> torch.zeros((2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1), num_heads)
<ide> def forward(
<ide>
<ide>
<ide> @add_start_docstrings(
<del> "Swin Model with a decoder on top for masked image modeling, as proposed in `SimMIM"
<del> " <https://arxiv.org/abs/2111.09886>`__.",
<add> "Swin Model with a decoder on top for masked image modeling, as proposed in"
<add> " [SimMIM](https://arxiv.org/abs/2111.09886).",
<ide> SWIN_START_DOCSTRING,
<ide> )
<ide> class SwinForMaskedImageModeling(SwinPreTrainedModel):
<ide> def __init__(self, config):
<ide>
<ide> num_features = int(config.embed_dim * 2 ** (config.num_layers - 1))
<ide> self.decoder = nn.Sequential(
<del> nn.Conv2d(in_channels=num_features, out_channels=config.encoder_stride**2 * 3, kernel_size=1),
<add> nn.Conv2d(
<add> in_channels=num_features, out_channels=config.encoder_stride**2 * config.num_channels, kernel_size=1
<add> ),
<ide> nn.PixelShuffle(config.encoder_stride),
<ide> )
<ide>
<ide><path>src/transformers/models/swin/modeling_tf_swin.py
<ide> # See all Swin models at https://huggingface.co/models?filter=swin
<ide> ]
<ide>
<del># to_2tuple, drop_path, TFSwinPatchEmbeddings, TFSwinPatchMerging and TFSwinDropPath are tensorflow
<add># drop_path, TFSwinPatchEmbeddings, TFSwinPatchMerging and TFSwinDropPath are tensorflow
<ide> # implementations of PyTorch functionalities in the timm library.
<ide>
<ide>
<ide> class TFSwinImageClassifierOutput(ModelOutput):
<ide> reshaped_hidden_states: Optional[Tuple[tf.Tensor]] = None
<ide>
<ide>
<del># Copied from transformers.models.vit.modeling_tf_vit.to_2tuple
<del>def to_2tuple(x) -> Tuple[Any, Any]:
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<ide> def window_partition(input_feature: tf.Tensor, window_size: int) -> tf.Tensor:
<ide> """
<ide> Partitions the given input into windows.
<ide> class TFSwinEmbeddings(tf.keras.layers.Layer):
<ide>
<ide> def __init__(self, config: SwinConfig, use_mask_token: bool = False, **kwargs) -> None:
<ide> super().__init__(**kwargs)
<del> self.patch_embeddings = TFSwinPatchEmbeddings(
<del> image_size=config.image_size,
<del> patch_size=config.patch_size,
<del> num_channels=config.num_channels,
<del> embed_dim=config.embed_dim,
<del> name="patch_embeddings",
<del> )
<add> self.patch_embeddings = TFSwinPatchEmbeddings(config, name="patch_embeddings")
<ide> self.num_patches = self.patch_embeddings.num_patches
<ide> self.patch_grid = self.patch_embeddings.grid_size
<ide> self.embed_dim = config.embed_dim
<ide> class TFSwinPatchEmbeddings(tf.keras.layers.Layer):
<ide> Image to Patch Embedding.
<ide> """
<ide>
<del> def __init__(
<del> self, image_size: int = 224, patch_size: int = 16, num_channels: int = 3, embed_dim: int = 768, **kwargs
<del> ) -> None:
<add> def __init__(self, config, **kwargs):
<ide> super().__init__(**kwargs)
<del> image_size = to_2tuple(image_size)
<del> patch_size = to_2tuple(patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.embed_dim
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<add> self.num_channels = num_channels
<ide> self.num_patches = num_patches
<ide> self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
<ide>
<ide> self.projection = tf.keras.layers.Conv2D(
<del> filters=embed_dim, kernel_size=self.patch_size, strides=self.patch_size, padding="valid", name="projection"
<add> filters=hidden_size,
<add> kernel_size=self.patch_size,
<add> strides=self.patch_size,
<add> padding="valid",
<add> name="projection",
<ide> )
<ide>
<ide> def maybe_pad(self, pixel_values: tf.Tensor, height: int, width: int) -> tf.Tensor:
<ide> def maybe_pad(self, pixel_values: tf.Tensor, height: int, width: int) -> tf.Tens
<ide> return pixel_values
<ide>
<ide> def call(self, pixel_values: tf.Tensor, training: bool = False) -> Tuple[tf.Tensor, Tuple[int, int]]:
<del> _, _, height, width = shape_list(pixel_values)
<add> _, num_channels, height, width = shape_list(pixel_values)
<add> if tf.executing_eagerly() and num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> # pad the input to be divisible by self.patch_size, if needed
<ide> pixel_values = self.maybe_pad(pixel_values, height, width)
<ide>
<ide> def __init__(self, config: SwinConfig, dim: int, num_heads: int, **kwargs) -> No
<ide> self.num_attention_heads = num_heads
<ide> self.attention_head_size = int(dim / num_heads)
<ide> self.all_head_size = self.num_attention_heads * self.attention_head_size
<del> self.window_size = to_2tuple(config.window_size)
<add> window_size = config.window_size
<add> self.window_size = (
<add> window_size if isinstance(window_size, collections.abc.Iterable) else (window_size, window_size)
<add> )
<ide>
<ide> # get pair-wise relative position index for each token inside the window
<ide> coords_h = tf.range(self.window_size[0])
<ide> class TFSwinDecoder(tf.keras.layers.Layer):
<ide> def __init__(self, config: SwinConfig, **kwargs):
<ide> super().__init__(**kwargs)
<ide> self.conv2d = tf.keras.layers.Conv2D(
<del> filters=config.encoder_stride**2 * 3, kernel_size=1, strides=1, name="0"
<add> filters=config.encoder_stride**2 * config.num_channels, kernel_size=1, strides=1, name="0"
<ide> )
<ide> self._block_size = config.encoder_stride
<ide> self.pixel_shuffle = PixelShuffle(self._block_size, name="1")
<ide> def call(self, x: tf.Tensor) -> tf.Tensor:
<ide>
<ide>
<ide> @add_start_docstrings(
<del> "Swin Model with a decoder on top for masked image modeling, as proposed in `SimMIM"
<del> " <https://arxiv.org/abs/2111.09886>`__.",
<add> "Swin Model with a decoder on top for masked image modeling, as proposed in"
<add> " [SimMIM](https://arxiv.org/abs/2111.09886).",
<ide> SWIN_START_DOCSTRING,
<ide> )
<ide> class TFSwinForMaskedImageModeling(TFSwinPreTrainedModel):
<ide><path>src/transformers/models/van/modeling_van.py
<ide> ]
<ide>
<ide>
<del># Stochastic depth implementation
<del># Taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py
<del>def drop_path(x, drop_prob: float = 0.0, training: bool = False):
<add># Copied from transformers.models.convnext.modeling_convnext.drop_path
<add>def drop_path(input, drop_prob: float = 0.0, training: bool = False):
<ide> """
<del> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the
<del> DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop
<del> Connect' is a different form of dropout in a separate paper... See discussion:
<del> https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and
<del> argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument.
<add> Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
<add>
<add> Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
<add> however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
<add> See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
<add> layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
<add> argument.
<ide> """
<ide> if drop_prob == 0.0 or not training:
<del> return x
<add> return input
<ide> keep_prob = 1 - drop_prob
<del> shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<del> random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
<add> shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
<add> random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
<ide> random_tensor.floor_() # binarize
<del> output = x.div(keep_prob) * random_tensor
<add> output = input.div(keep_prob) * random_tensor
<ide> return output
<ide>
<ide>
<ide> # Copied from transformers.models.convnext.modeling_convnext.ConvNextDropPath with ConvNext->Van
<ide> class VanDropPath(nn.Module):
<ide> """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
<ide>
<del> def __init__(self, drop_prob=None):
<add> def __init__(self, drop_prob: Optional[float] = None) -> None:
<ide> super().__init__()
<ide> self.drop_prob = drop_prob
<ide>
<ide> def forward(self, x: torch.Tensor) -> torch.Tensor:
<ide> return drop_path(x, self.drop_prob, self.training)
<ide>
<add> def extra_repr(self) -> str:
<add> return "p={}".format(self.drop_prob)
<add>
<ide>
<ide> class VanOverlappingPatchEmbedder(nn.Module):
<ide> """
<ide><path>src/transformers/models/vilt/modeling_vilt.py
<ide> class ViltForImagesAndTextClassificationOutput(ModelOutput):
<ide> attentions: Optional[List[Tuple[torch.FloatTensor]]] = None
<ide>
<ide>
<del># Copied from transformers.models.vit.modeling_vit.to_2tuple
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<ide> class ViltEmbeddings(nn.Module):
<ide> """
<ide> Construct the text and patch embeddings.
<ide> def __init__(self, config):
<ide> self.text_embeddings = TextEmbeddings(config)
<ide> # patch embeddings
<ide> self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
<del> self.patch_embeddings = PatchEmbeddings(
<del> image_size=config.image_size,
<del> patch_size=config.patch_size,
<del> num_channels=config.num_channels,
<del> embed_dim=config.hidden_size,
<del> )
<add> self.patch_embeddings = ViltPatchEmbeddings(config)
<ide> num_patches = self.patch_embeddings.num_patches
<ide> self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
<ide> # modality type (text/patch) embeddings
<ide> def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs
<ide> return embeddings
<ide>
<ide>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del>class PatchEmbeddings(nn.Module):
<add>class ViltPatchEmbeddings(nn.Module):
<ide> """
<ide> Image to Patch Embedding.
<ide> """
<ide>
<del> def __init__(self, image_size=224, patch_size=16, num_channels=3, embed_dim=768):
<add> def __init__(self, config):
<ide> super().__init__()
<del> image_size = to_2tuple(image_size)
<del> patch_size = to_2tuple(patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.hidden_size
<add>
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<add> self.num_channels = num_channels
<ide> self.num_patches = num_patches
<ide>
<del> self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
<add> self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
<ide>
<ide> def forward(self, pixel_values):
<ide> batch_size, num_channels, height, width = pixel_values.shape
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> x = self.projection(pixel_values)
<ide> return x
<ide>
<ide><path>src/transformers/models/vit/modeling_flax_vit.py
<ide> """
<ide>
<ide>
<del>class FlaxPatchEmbeddings(nn.Module):
<add>class FlaxViTPatchEmbeddings(nn.Module):
<ide>
<ide> config: ViTConfig
<ide> dtype: jnp.dtype = jnp.float32 # the dtype of the computation
<ide> def setup(self):
<ide> patch_size = self.config.patch_size
<ide> num_patches = (image_size // patch_size) * (image_size // patch_size)
<ide> self.num_patches = num_patches
<add> self.num_channels = self.config.num_channels
<ide> self.projection = nn.Conv(
<ide> self.config.hidden_size,
<ide> kernel_size=(patch_size, patch_size),
<ide> def setup(self):
<ide> )
<ide>
<ide> def __call__(self, pixel_values):
<del> x = self.projection(pixel_values)
<del> batch_size, _, _, channels = x.shape
<del> return jnp.reshape(x, (batch_size, -1, channels))
<add> num_channels = pixel_values.shape[-1]
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<add> embeddings = self.projection(pixel_values)
<add> batch_size, _, _, channels = embeddings.shape
<add> return jnp.reshape(embeddings, (batch_size, -1, channels))
<ide>
<ide>
<ide> class FlaxViTEmbeddings(nn.Module):
<ide> class FlaxViTEmbeddings(nn.Module):
<ide>
<ide> def setup(self):
<ide> self.cls_token = self.param("cls_token", nn.initializers.zeros, (1, 1, self.config.hidden_size))
<del> self.patch_embeddings = FlaxPatchEmbeddings(self.config, dtype=self.dtype)
<add> self.patch_embeddings = FlaxViTPatchEmbeddings(self.config, dtype=self.dtype)
<ide> num_patches = self.patch_embeddings.num_patches
<ide> self.position_embeddings = self.param(
<ide> "position_embeddings", nn.initializers.zeros, (1, num_patches + 1, self.config.hidden_size)
<ide> def __init__(
<ide> ):
<ide> module = self.module_class(config=config, dtype=dtype, **kwargs)
<ide> if input_shape is None:
<del> input_shape = (1, config.image_size, config.image_size, 3)
<add> input_shape = (1, config.image_size, config.image_size, config.num_channels)
<ide> super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
<ide>
<ide> def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
<ide><path>src/transformers/models/vit/modeling_tf_vit.py
<ide> _IMAGE_CLASS_EXPECTED_OUTPUT = "Egyptian cat"
<ide>
<ide>
<del># Inspired by
<del># https://github.com/rwightman/pytorch-image-models/blob/b9bd960a032c75ca6b808ddeed76bee5f3ed4972/timm/models/layers/helpers.py
<del># From PyTorch internals
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del>
<del>
<ide> class TFViTEmbeddings(tf.keras.layers.Layer):
<ide> """
<ide> Construct the CLS token, position and patch embeddings.
<ide> class TFViTEmbeddings(tf.keras.layers.Layer):
<ide> def __init__(self, config: ViTConfig, **kwargs):
<ide> super().__init__(**kwargs)
<ide>
<del> self.patch_embeddings = TFPatchEmbeddings(config, name="patch_embeddings")
<add> self.patch_embeddings = TFViTPatchEmbeddings(config, name="patch_embeddings")
<ide> self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
<ide> self.config = config
<ide>
<ide> def interpolate_pos_encoding(self, embeddings, height, width) -> tf.Tensor:
<ide> """
<ide>
<ide> batch_size, seq_len, dim = shape_list(embeddings)
<del> npatch = seq_len - 1
<add> num_patches = seq_len - 1
<ide>
<del> _, N, _ = shape_list(self.position_embeddings)
<del> N -= 1
<add> _, num_positions, _ = shape_list(self.position_embeddings)
<add> num_positions -= 1
<ide>
<del> if npatch == N and height == width:
<add> if num_patches == num_positions and height == width:
<ide> return self.position_embeddings
<ide> class_pos_embed = self.position_embeddings[:, :1]
<ide> patch_pos_embed = self.position_embeddings[:, 1:]
<ide> h0 = height // self.config.patch_size
<ide> w0 = width // self.config.patch_size
<ide> patch_pos_embed = tf.image.resize(
<del> images=tf.reshape(patch_pos_embed, shape=(1, int(math.sqrt(N)), int(math.sqrt(N)), dim)),
<add> images=tf.reshape(
<add> patch_pos_embed, shape=(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
<add> ),
<ide> size=(h0, w0),
<ide> method="bicubic",
<ide> )
<ide> def call(
<ide>
<ide> # Based on timm implementation, which can be found here:
<ide> # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del>class TFPatchEmbeddings(tf.keras.layers.Layer):
<add>class TFViTPatchEmbeddings(tf.keras.layers.Layer):
<ide> """
<del> Image to Patch Embedding.
<add> This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
<add> `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
<add> Transformer.
<ide> """
<ide>
<ide> def __init__(self, config: ViTConfig, **kwargs):
<ide> super().__init__(**kwargs)
<del> image_size = to_2tuple(config.image_size)
<del> patch_size = to_2tuple(config.patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.hidden_size
<add>
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<ide> self.num_patches = num_patches
<del> self.num_channels = config.num_channels
<del> self.embed_dim = config.hidden_size
<add> self.num_channels = num_channels
<ide> self.config = config
<ide>
<ide> self.projection = tf.keras.layers.Conv2D(
<del> filters=self.embed_dim,
<add> filters=hidden_size,
<ide> kernel_size=patch_size,
<del> strides=self.patch_size,
<add> strides=patch_size,
<ide> padding="valid",
<ide> data_format="channels_last",
<ide> use_bias=True,
<ide> def call(
<ide> self, pixel_values: tf.Tensor, interpolate_pos_encoding: bool = False, training: bool = False
<ide> ) -> tf.Tensor:
<ide> batch_size, num_channels, height, width = shape_list(pixel_values)
<add> if tf.executing_eagerly() and num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> if not interpolate_pos_encoding:
<del> if getattr(height, "numpy", None) and getattr(width, "numpy", None):
<add> if tf.executing_eagerly():
<ide> if height != self.image_size[0] or width != self.image_size[1]:
<ide> raise ValueError(
<ide> f"Input image size ({height}*{width}) doesn't match model"
<ide> def call(
<ide> # Change the 2D spatial dimensions to a single temporal dimension.
<ide> # shape = (batch_size, num_patches, out_channels=embed_dim)
<ide> num_patches = (width // self.patch_size[1]) * (height // self.patch_size[0])
<del> x = tf.reshape(tensor=projection, shape=(batch_size, num_patches, -1))
<add> embeddings = tf.reshape(tensor=projection, shape=(batch_size, num_patches, -1))
<ide>
<del> return x
<add> return embeddings
<ide>
<ide>
<ide> class TFViTSelfAttention(tf.keras.layers.Layer):
<ide><path>src/transformers/models/vit/modeling_vit.py
<ide> ]
<ide>
<ide>
<del># Inspired by
<del># https://github.com/rwightman/pytorch-image-models/blob/b9bd960a032c75ca6b808ddeed76bee5f3ed4972/timm/models/layers/helpers.py
<del># From PyTorch internals
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del>
<del>
<ide> class ViTEmbeddings(nn.Module):
<ide> """
<ide> Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
<del>
<ide> """
<ide>
<ide> def __init__(self, config: ViTConfig, use_mask_token: bool = False) -> None:
<ide> super().__init__()
<ide>
<ide> self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
<ide> self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
<del> self.patch_embeddings = PatchEmbeddings(
<del> image_size=config.image_size,
<del> patch_size=config.patch_size,
<del> num_channels=config.num_channels,
<del> embed_dim=config.hidden_size,
<del> )
<add> self.patch_embeddings = ViTPatchEmbeddings(config)
<ide> num_patches = self.patch_embeddings.num_patches
<ide> self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
<ide> self.dropout = nn.Dropout(config.hidden_dropout_prob)
<ide> def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width:
<ide> https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
<ide> """
<ide>
<del> npatch = embeddings.shape[1] - 1
<del> N = self.position_embeddings.shape[1] - 1
<del> if npatch == N and height == width:
<add> num_patches = embeddings.shape[1] - 1
<add> num_positions = self.position_embeddings.shape[1] - 1
<add> if num_patches == num_positions and height == width:
<ide> return self.position_embeddings
<ide> class_pos_embed = self.position_embeddings[:, 0]
<ide> patch_pos_embed = self.position_embeddings[:, 1:]
<ide> def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width:
<ide> # we add a small number to avoid floating point error in the interpolation
<ide> # see discussion at https://github.com/facebookresearch/dino/issues/8
<ide> h0, w0 = h0 + 0.1, w0 + 0.1
<add> patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
<add> patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
<ide> patch_pos_embed = nn.functional.interpolate(
<del> patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),
<del> scale_factor=(h0 / math.sqrt(N), w0 / math.sqrt(N)),
<add> patch_pos_embed,
<add> scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)),
<ide> mode="bicubic",
<ide> align_corners=False,
<ide> )
<ide> def forward(
<ide> batch_size, num_channels, height, width = pixel_values.shape
<ide> embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
<ide>
<del> batch_size, seq_len, _ = embeddings.size()
<ide> if bool_masked_pos is not None:
<del> mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
<add> seq_length = embeddings.shape[1]
<add> mask_tokens = self.mask_token.expand(batch_size, seq_length, -1)
<ide> # replace the masked visual tokens by mask_tokens
<ide> mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
<ide> embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
<ide> def forward(
<ide> return embeddings
<ide>
<ide>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del>class PatchEmbeddings(nn.Module):
<add>class ViTPatchEmbeddings(nn.Module):
<ide> """
<del> Image to Patch Embedding.
<del>
<add> This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
<add> `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
<add> Transformer.
<ide> """
<ide>
<del> def __init__(
<del> self,
<del> image_size: int = 224,
<del> patch_size: Union[int, Tuple[int, int]] = 16,
<del> num_channels: int = 3,
<del> embed_dim: int = 768,
<del> ):
<add> def __init__(self, config):
<ide> super().__init__()
<del> image_size = to_2tuple(image_size)
<del> patch_size = to_2tuple(patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.hidden_size
<add>
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<add> self.num_channels = num_channels
<ide> self.num_patches = num_patches
<ide>
<del> self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
<add> self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
<ide>
<ide> def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
<ide> batch_size, num_channels, height, width = pixel_values.shape
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> if not interpolate_pos_encoding:
<ide> if height != self.image_size[0] or width != self.image_size[1]:
<ide> raise ValueError(
<ide> f"Input image size ({height}*{width}) doesn't match model"
<ide> f" ({self.image_size[0]}*{self.image_size[1]})."
<ide> )
<del> x = self.projection(pixel_values).flatten(2).transpose(1, 2)
<del> return x
<add> embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
<add> return embeddings
<ide>
<ide>
<ide> class ViTSelfAttention(nn.Module):
<ide> def __init__(self, config: ViTConfig, add_pooling_layer: bool = True, use_mask_t
<ide> # Initialize weights and apply final processing
<ide> self.post_init()
<ide>
<del> def get_input_embeddings(self) -> PatchEmbeddings:
<add> def get_input_embeddings(self) -> ViTPatchEmbeddings:
<ide> return self.embeddings.patch_embeddings
<ide>
<ide> def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
<ide> def forward(self, hidden_states):
<ide>
<ide>
<ide> @add_start_docstrings(
<del> "ViT Model with a decoder on top for masked image modeling, as proposed in `SimMIM"
<del> " <https://arxiv.org/abs/2111.09886>`__.",
<add> "ViT Model with a decoder on top for masked image modeling, as proposed in"
<add> " [SimMIM](https://arxiv.org/abs/2111.09886).",
<ide> VIT_START_DOCSTRING,
<ide> )
<ide> class ViTForMaskedImageModeling(ViTPreTrainedModel):
<ide> def __init__(self, config: ViTConfig) -> None:
<ide> self.vit = ViTModel(config, add_pooling_layer=False, use_mask_token=True)
<ide>
<ide> self.decoder = nn.Sequential(
<del> nn.Conv2d(in_channels=config.hidden_size, out_channels=config.encoder_stride**2 * 3, kernel_size=1),
<add> nn.Conv2d(
<add> in_channels=config.hidden_size,
<add> out_channels=config.encoder_stride**2 * config.num_channels,
<add> kernel_size=1,
<add> ),
<ide> nn.PixelShuffle(config.encoder_stride),
<ide> )
<ide>
<ide><path>src/transformers/models/vit_mae/modeling_tf_vit_mae.py
<ide> class TFViTMAEForPreTrainingOutput(ModelOutput):
<ide> attentions: Optional[Tuple[tf.Tensor]] = None
<ide>
<ide>
<del># copied from transformers.models.vit.modeling_tf_vit.to_2tuple
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<ide> def get_2d_sincos_pos_embed(embed_dim, grid_size, add_cls_token=False):
<ide> """
<ide> Create 2D sin/cos positional embeddings.
<ide> class TFViTMAEEmbeddings(tf.keras.layers.Layer):
<ide> def __init__(self, config: ViTMAEConfig, **kwargs):
<ide> super().__init__(**kwargs)
<ide>
<del> self.patch_embeddings = TFPatchEmbeddings(config, name="patch_embeddings")
<add> self.patch_embeddings = TFViTMAEPatchEmbeddings(config, name="patch_embeddings")
<ide> self.num_patches = self.patch_embeddings.num_patches
<ide>
<ide> self.config = config
<ide> def call(self, pixel_values: tf.Tensor, noise: tf.Tensor = None) -> tf.Tensor:
<ide> return embeddings, mask, ids_restore
<ide>
<ide>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del>class TFPatchEmbeddings(tf.keras.layers.Layer):
<add>class TFViTMAEPatchEmbeddings(tf.keras.layers.Layer):
<ide> """
<del> Image to Patch Embedding.
<del>
<add> This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
<add> `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
<add> Transformer.
<ide> """
<ide>
<ide> def __init__(self, config: ViTMAEConfig, **kwargs):
<ide> super().__init__(**kwargs)
<del> image_size = to_2tuple(config.image_size)
<del> patch_size = to_2tuple(config.patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.hidden_size
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<ide> self.num_patches = num_patches
<del> self.num_channels = config.num_channels
<del> self.embed_dim = config.hidden_size
<add> self.num_channels = num_channels
<ide> self.config = config
<ide>
<ide> self.projection = tf.keras.layers.Conv2D(
<del> filters=self.embed_dim,
<del> kernel_size=self.patch_size,
<del> strides=self.patch_size,
<add> filters=hidden_size,
<add> kernel_size=patch_size,
<add> strides=patch_size,
<ide> padding="valid",
<ide> data_format="channels_last",
<ide> kernel_initializer="glorot_uniform", # following torch.nn.Linear
<ide> def __init__(self, config: ViTMAEConfig, **kwargs):
<ide>
<ide> def call(self, pixel_values: tf.Tensor, training: bool = False) -> tf.Tensor:
<ide> batch_size, num_channels, height, width = shape_list(pixel_values)
<del> if getattr(height, "numpy", None) and getattr(width, "numpy", None):
<add> if tf.executing_eagerly():
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the"
<add> " configuration."
<add> )
<ide> if height != self.image_size[0] or width != self.image_size[1]:
<ide> raise ValueError(
<ide> f"Input image size ({height}*{width}) doesn't match model"
<ide><path>src/transformers/models/vit_mae/modeling_vit_mae.py
<ide> class ViTMAEForPreTrainingOutput(ModelOutput):
<ide> attentions: Optional[Tuple[torch.FloatTensor]] = None
<ide>
<ide>
<del># copied from transformers.models.vit.modeling_vit.to_2tuple ViT->ViTMAE
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<ide> def get_2d_sincos_pos_embed(embed_dim, grid_size, add_cls_token=False):
<ide> """
<ide> Create 2D sin/cos positional embeddings.
<ide> def __init__(self, config):
<ide> super().__init__()
<ide>
<ide> self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
<del> self.patch_embeddings = PatchEmbeddings(
<del> image_size=config.image_size,
<del> patch_size=config.patch_size,
<del> num_channels=config.num_channels,
<del> embed_dim=config.hidden_size,
<del> )
<add> self.patch_embeddings = ViTMAEPatchEmbeddings(config)
<ide> self.num_patches = self.patch_embeddings.num_patches
<ide> # fixed sin-cos embedding
<ide> self.position_embeddings = nn.Parameter(
<ide> def forward(self, pixel_values, noise=None):
<ide> return embeddings, mask, ids_restore
<ide>
<ide>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del>class PatchEmbeddings(nn.Module):
<add>class ViTMAEPatchEmbeddings(nn.Module):
<ide> """
<del> Image to Patch Embedding.
<del>
<add> This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
<add> `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
<add> Transformer.
<ide> """
<ide>
<del> def __init__(self, image_size=224, patch_size=16, num_channels=3, embed_dim=768):
<add> def __init__(self, config):
<ide> super().__init__()
<del> image_size = to_2tuple(image_size)
<del> patch_size = to_2tuple(patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.hidden_size
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<add> self.num_channels = num_channels
<ide> self.num_patches = num_patches
<ide>
<del> self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
<add> self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
<ide>
<ide> def forward(self, pixel_values):
<ide> batch_size, num_channels, height, width = pixel_values.shape
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<ide> if height != self.image_size[0] or width != self.image_size[1]:
<ide> raise ValueError(
<ide> f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
<ide><path>src/transformers/models/yolos/modeling_yolos.py
<ide> class YolosObjectDetectionOutput(ModelOutput):
<ide> attentions: Optional[Tuple[torch.FloatTensor]] = None
<ide>
<ide>
<del># Copied from transformers.models.vit.modeling_vit.to_2tuple
<del>def to_2tuple(x):
<del> if isinstance(x, collections.abc.Iterable):
<del> return x
<del> return (x, x)
<del>
<del>
<ide> class YolosEmbeddings(nn.Module):
<ide> """
<ide> Construct the CLS token, detection tokens, position and patch embeddings.
<ide> def __init__(self, config: YolosConfig) -> None:
<ide>
<ide> self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
<ide> self.detection_tokens = nn.Parameter(torch.zeros(1, config.num_detection_tokens, config.hidden_size))
<del> self.patch_embeddings = PatchEmbeddings(
<del> image_size=config.image_size,
<del> patch_size=config.patch_size,
<del> num_channels=config.num_channels,
<del> embed_dim=config.hidden_size,
<del> )
<add> self.patch_embeddings = YolosPatchEmbeddings(config)
<ide> num_patches = self.patch_embeddings.num_patches
<ide> self.position_embeddings = nn.Parameter(
<ide> torch.zeros(1, num_patches + config.num_detection_tokens + 1, config.hidden_size)
<ide> def forward(self, pos_embed, img_size=(800, 1344)) -> torch.Tensor:
<ide> return scale_pos_embed
<ide>
<ide>
<del># Based on timm implementation, which can be found here:
<del># https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
<del>class PatchEmbeddings(nn.Module):
<add>class YolosPatchEmbeddings(nn.Module):
<ide> """
<del> Image to Patch Embedding.
<del>
<add> This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
<add> `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
<add> Transformer.
<ide> """
<ide>
<del> def __init__(
<del> self,
<del> image_size: int = 224,
<del> patch_size: Union[int, Tuple[int, int]] = 16,
<del> num_channels: int = 3,
<del> embed_dim: int = 768,
<del> ):
<add> def __init__(self, config):
<ide> super().__init__()
<del> image_size = to_2tuple(image_size)
<del> patch_size = to_2tuple(patch_size)
<add> image_size, patch_size = config.image_size, config.patch_size
<add> num_channels, hidden_size = config.num_channels, config.hidden_size
<add>
<add> image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
<add> patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.image_size = image_size
<ide> self.patch_size = patch_size
<add> self.num_channels = num_channels
<ide> self.num_patches = num_patches
<ide>
<del> self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
<add> self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
<ide>
<ide> def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
<add> batch_size, num_channels, height, width = pixel_values.shape
<add> if num_channels != self.num_channels:
<add> raise ValueError(
<add> "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
<add> )
<add>
<ide> embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
<ide> return embeddings
<ide>
<ide> def __init__(self, config: YolosConfig, add_pooling_layer: bool = True):
<ide> # Initialize weights and apply final processing
<ide> self.post_init()
<ide>
<del> def get_input_embeddings(self) -> PatchEmbeddings:
<add> def get_input_embeddings(self) -> YolosPatchEmbeddings:
<ide> return self.embeddings.patch_embeddings
<ide>
<ide> def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
<ide><path>src/transformers/testing_utils.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide>
<add>import collections
<ide> import contextlib
<ide> import inspect
<ide> import logging
<ide> def check_json_file_has_correct_format(file_path):
<ide> left_indent = len(lines[1]) - len(lines[1].lstrip())
<ide> assert left_indent == 2
<ide> assert lines[-1].strip() == "}"
<add>
<add>
<add>def to_2tuple(x):
<add> if isinstance(x, collections.abc.Iterable):
<add> return x
<add> return (x, x)
<ide><path>tests/models/beit/test_modeling_beit.py
<ide> def create_and_check_for_image_classification(self, config, pixel_values, labels
<ide> result = model(pixel_values, labels=labels)
<ide> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<ide>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = BeitForImageClassification(config)
<add> model.to(torch_device)
<add> model.eval()
<add>
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values, labels=labels)
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<add>
<ide> def create_and_check_for_semantic_segmentation(self, config, pixel_values, labels, pixel_labels):
<ide> config.num_labels = self.num_labels
<ide> model = BeitForSemanticSegmentation(config)
<ide><path>tests/models/beit/test_modeling_flax_beit.py
<ide> def prepare_config_and_inputs(self):
<ide> return config, pixel_values, labels
<ide>
<ide> def create_and_check_model(self, config, pixel_values, labels):
<del>
<ide> model = FlaxBeitModel(config=config)
<ide> result = model(pixel_values)
<ide> self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
<ide> def create_and_check_for_image_classification(self, config, pixel_values, labels
<ide> result = model(pixel_values)
<ide> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<ide>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = FlaxBeitForImageClassification(config)
<add>
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values)
<add>
<ide> def prepare_config_and_inputs_for_common(self):
<ide> config_and_inputs = self.prepare_config_and_inputs()
<ide> (
<ide><path>tests/models/data2vec/test_modeling_data2vec_vision.py
<ide> Data2VecVisionForSemanticSegmentation,
<ide> Data2VecVisionModel,
<ide> )
<del> from transformers.models.data2vec.modeling_data2vec_vision import (
<del> DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST,
<del> to_2tuple,
<del> )
<add> from transformers.models.data2vec.modeling_data2vec_vision import DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST
<ide>
<ide>
<ide> if is_vision_available():
<ide> def __init__(
<ide> self.out_indices = out_indices
<ide> self.num_labels = num_labels
<ide>
<add> # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
<add> num_patches = (image_size // patch_size) ** 2
<add> self.seq_length = num_patches + 1
<add>
<ide> def prepare_config_and_inputs(self):
<ide> pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
<ide>
<ide> def create_and_check_model(self, config, pixel_values, labels, pixel_labels):
<ide> model.eval()
<ide> result = model(pixel_values)
<ide> # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
<del> image_size = to_2tuple(self.image_size)
<del> patch_size = to_2tuple(self.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<add> num_patches = (self.image_size // self.patch_size) ** 2
<ide> self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
<ide>
<ide> def create_and_check_for_image_classification(self, config, pixel_values, labels, pixel_labels):
<ide> def test_initialization(self):
<ide> msg=f"Parameter {name} of model {model_class} seems not properly initialized",
<ide> )
<ide>
<del> def test_attention_outputs(self):
<del> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del> config.return_dict = True
<del>
<del> # in Data2VecVision, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
<del> image_size = to_2tuple(self.model_tester.image_size)
<del> patch_size = to_2tuple(self.model_tester.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<del> seq_len = num_patches + 1
<del> encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len)
<del> encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
<del> chunk_length = getattr(self.model_tester, "chunk_length", None)
<del> if chunk_length is not None and hasattr(self.model_tester, "num_hashes"):
<del> encoder_seq_length = encoder_seq_length * self.model_tester.num_hashes
<del>
<del> for model_class in self.all_model_classes:
<del> inputs_dict["output_attentions"] = True
<del> inputs_dict["output_hidden_states"] = False
<del> config.return_dict = True
<del> model = model_class(config)
<del> model.to(torch_device)
<del> model.eval()
<del> with torch.no_grad():
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class))
<del> attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
<del> self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
<del>
<del> # check that output_attentions also work using config
<del> del inputs_dict["output_attentions"]
<del> config.output_attentions = True
<del> model = model_class(config)
<del> model.to(torch_device)
<del> model.eval()
<del> with torch.no_grad():
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class))
<del>
<del> attentions = outputs.attentions
<del> self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
<del>
<del> self.assertListEqual(
<del> list(attentions[0].shape[-3:]),
<del> [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
<del> )
<del> out_len = len(outputs)
<del>
<del> # Check attention is always last and order is fine
<del> inputs_dict["output_attentions"] = True
<del> inputs_dict["output_hidden_states"] = True
<del> model = model_class(config)
<del> model.to(torch_device)
<del> model.eval()
<del> with torch.no_grad():
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class))
<del>
<del> self.assertEqual(out_len + 1, len(outputs))
<del>
<del> self_attentions = outputs.attentions
<del>
<del> self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
<del> self.assertListEqual(
<del> list(self_attentions[0].shape[-3:]),
<del> [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
<del> )
<del>
<del> def test_hidden_states_output(self):
<del> def check_hidden_states_output(inputs_dict, config, model_class):
<del> model = model_class(config)
<del> model.to(torch_device)
<del> model.eval()
<del>
<del> with torch.no_grad():
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class))
<del>
<del> hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
<del>
<del> expected_num_layers = getattr(
<del> self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
<del> )
<del> self.assertEqual(len(hidden_states), expected_num_layers)
<del>
<del> # Data2VecVision has a different seq_length
<del> image_size = to_2tuple(self.model_tester.image_size)
<del> patch_size = to_2tuple(self.model_tester.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<del> seq_length = num_patches + 1
<del>
<del> self.assertListEqual(
<del> list(hidden_states[0].shape[-2:]),
<del> [seq_length, self.model_tester.hidden_size],
<del> )
<del>
<del> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del>
<del> for model_class in self.all_model_classes:
<del> inputs_dict["output_hidden_states"] = True
<del> check_hidden_states_output(inputs_dict, config, model_class)
<del>
<del> # check that output_hidden_states also work using config
<del> del inputs_dict["output_hidden_states"]
<del> config.output_hidden_states = True
<del>
<del> check_hidden_states_output(inputs_dict, config, model_class)
<del>
<ide> def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=2e-4, name="outputs", attributes=None):
<ide> # We override with a slightly higher tol value, as semseg models tend to diverge a bit more
<ide> super().check_pt_tf_outputs(tf_outputs, pt_outputs, model_class, tol, name, attributes)
<ide><path>tests/models/deit/test_modeling_deit.py
<ide> def create_and_check_model(self, config, pixel_values, labels):
<ide> result = model(pixel_values)
<ide> self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
<ide>
<add> def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels):
<add> model = DeiTForMaskedImageModeling(config=config)
<add> model.to(torch_device)
<add> model.eval()
<add> result = model(pixel_values)
<add> self.parent.assertEqual(
<add> result.logits.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size)
<add> )
<add>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = DeiTForMaskedImageModeling(config)
<add> model.to(torch_device)
<add> model.eval()
<add>
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values)
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, 1, self.image_size, self.image_size))
<add>
<ide> def create_and_check_for_image_classification(self, config, pixel_values, labels):
<ide> config.num_labels = self.type_sequence_label_size
<ide> model = DeiTForImageClassification(config)
<ide> def create_and_check_for_image_classification(self, config, pixel_values, labels
<ide> result = model(pixel_values, labels=labels)
<ide> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<ide>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = DeiTForImageClassification(config)
<add> model.to(torch_device)
<add> model.eval()
<add>
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values, labels=labels)
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<add>
<ide> def prepare_config_and_inputs_for_common(self):
<ide> config_and_inputs = self.prepare_config_and_inputs()
<ide> (
<ide> def test_model(self):
<ide> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<ide> self.model_tester.create_and_check_model(*config_and_inputs)
<ide>
<add> def test_for_masked_image_modeling(self):
<add> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<add> self.model_tester.create_and_check_for_masked_image_modeling(*config_and_inputs)
<add>
<ide> def test_for_image_classification(self):
<ide> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<ide> self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
<ide><path>tests/models/swin/test_modeling_swin.py
<ide> # limitations under the License.
<ide> """ Testing suite for the PyTorch Swin model. """
<ide>
<add>import collections
<ide> import inspect
<ide> import os
<ide> import pickle
<ide> from torch import nn
<ide>
<ide> from transformers import SwinForImageClassification, SwinForMaskedImageModeling, SwinModel
<del> from transformers.models.swin.modeling_swin import SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, to_2tuple
<add> from transformers.models.swin.modeling_swin import SWIN_PRETRAINED_MODEL_ARCHIVE_LIST
<ide>
<ide> if is_vision_available():
<ide> from PIL import Image
<ide> def create_and_check_model(self, config, pixel_values, labels):
<ide>
<ide> self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim))
<ide>
<add> def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels):
<add> model = SwinForMaskedImageModeling(config=config)
<add> model.to(torch_device)
<add> model.eval()
<add> result = model(pixel_values)
<add> self.parent.assertEqual(
<add> result.logits.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size)
<add> )
<add>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = SwinForMaskedImageModeling(config)
<add> model.to(torch_device)
<add> model.eval()
<add>
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values)
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, 1, self.image_size, self.image_size))
<add>
<ide> def create_and_check_for_image_classification(self, config, pixel_values, labels):
<ide> config.num_labels = self.type_sequence_label_size
<ide> model = SwinForImageClassification(config)
<ide> def create_and_check_for_image_classification(self, config, pixel_values, labels
<ide> result = model(pixel_values, labels=labels)
<ide> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<ide>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = SwinForImageClassification(config)
<add> model.to(torch_device)
<add> model.eval()
<add>
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values)
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<add>
<ide> def prepare_config_and_inputs_for_common(self):
<ide> config_and_inputs = self.prepare_config_and_inputs()
<ide> (
<ide> def test_model(self):
<ide> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<ide> self.model_tester.create_and_check_model(*config_and_inputs)
<ide>
<add> def test_for_masked_image_modeling(self):
<add> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<add> self.model_tester.create_and_check_for_masked_image_modeling(*config_and_inputs)
<add>
<add> def test_for_image_classification(self):
<add> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<add> self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
<add>
<ide> def test_inputs_embeds(self):
<ide> # Swin does not use inputs_embeds
<ide> pass
<ide> def check_hidden_states_output(self, inputs_dict, config, model_class, image_siz
<ide> self.assertEqual(len(hidden_states), expected_num_layers)
<ide>
<ide> # Swin has a different seq_length
<del> patch_size = to_2tuple(config.patch_size)
<add> patch_size = (
<add> config.patch_size
<add> if isinstance(config.patch_size, collections.abc.Iterable)
<add> else (config.patch_size, config.patch_size)
<add> )
<ide>
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide>
<ide> def check_hidden_states_output(self, inputs_dict, config, model_class, image_siz
<ide> def test_hidden_states_output(self):
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<ide>
<del> image_size = to_2tuple(self.model_tester.image_size)
<add> image_size = (
<add> self.model_tester.image_size
<add> if isinstance(self.model_tester.image_size, collections.abc.Iterable)
<add> else (self.model_tester.image_size, self.model_tester.image_size)
<add> )
<ide>
<ide> for model_class in self.all_model_classes:
<ide> inputs_dict["output_hidden_states"] = True
<ide> def test_hidden_states_output_with_padding(self):
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<ide> config.patch_size = 3
<ide>
<del> image_size = to_2tuple(self.model_tester.image_size)
<del> patch_size = to_2tuple(config.patch_size)
<add> image_size = (
<add> self.model_tester.image_size
<add> if isinstance(self.model_tester.image_size, collections.abc.Iterable)
<add> else (self.model_tester.image_size, self.model_tester.image_size)
<add> )
<add> patch_size = (
<add> config.patch_size
<add> if isinstance(config.patch_size, collections.abc.Iterable)
<add> else (config.patch_size, config.patch_size)
<add> )
<ide>
<ide> padded_height = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
<ide> padded_width = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
<ide> def test_hidden_states_output_with_padding(self):
<ide> config.output_hidden_states = True
<ide> self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width))
<ide>
<del> def test_for_image_classification(self):
<del> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<del> self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
<del>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<ide> for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
<ide><path>tests/models/swin/test_modeling_tf_swin.py
<ide> import numpy as np
<ide>
<ide> from transformers import SwinConfig
<del>from transformers.testing_utils import require_tf, require_vision, slow
<add>from transformers.testing_utils import require_tf, require_vision, slow, to_2tuple
<ide> from transformers.utils import cached_property, is_tf_available, is_vision_available
<ide>
<ide> from ...test_configuration_common import ConfigTester
<ide> TFSwinForImageClassification,
<ide> TFSwinForMaskedImageModeling,
<ide> TFSwinModel,
<del> to_2tuple,
<ide> )
<ide>
<ide>
<ide> def create_and_check_model(self, config, pixel_values, labels):
<ide>
<ide> self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim))
<ide>
<add> def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels):
<add> model = TFSwinForMaskedImageModeling(config=config)
<add> result = model(pixel_values)
<add> self.parent.assertEqual(
<add> result.logits.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size)
<add> )
<add>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = TFSwinForMaskedImageModeling(config)
<add>
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values)
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, 1, self.image_size, self.image_size))
<add>
<ide> def create_and_check_for_image_classification(self, config, pixel_values, labels):
<ide> config.num_labels = self.type_sequence_label_size
<ide> model = TFSwinForImageClassification(config)
<ide> result = model(pixel_values, labels=labels)
<ide> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<ide>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = TFSwinForImageClassification(config)
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values)
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<add>
<ide> def prepare_config_and_inputs_for_common(self):
<ide> config_and_inputs = self.prepare_config_and_inputs()
<ide> config, pixel_values, labels = config_and_inputs
<ide> def test_model(self):
<ide> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<ide> self.model_tester.create_and_check_model(*config_and_inputs)
<ide>
<add> def test_for_masked_image_modeling(self):
<add> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<add> self.model_tester.create_and_check_for_masked_image_modeling(*config_and_inputs)
<add>
<add> def test_for_image_classification(self):
<add> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<add> self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
<add>
<ide> @unittest.skip(reason="Swin does not use inputs_embeds")
<ide> def test_inputs_embeds(self):
<ide> pass
<ide> def test_inputs_requiring_padding(self):
<ide> config.output_hidden_states = True
<ide> self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width))
<ide>
<del> def test_for_image_classification(self):
<del> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<del> self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
<del>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<ide> for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
<ide><path>tests/models/vit/test_modeling_flax_vit.py
<ide> def prepare_config_and_inputs(self):
<ide>
<ide> return config, pixel_values
<ide>
<del> def create_and_check_model(self, config, pixel_values, labels):
<del>
<add> def create_and_check_model(self, config, pixel_values):
<ide> model = FlaxViTModel(config=config)
<ide> result = model(pixel_values)
<ide> # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
<ide> def create_and_check_model(self, config, pixel_values, labels):
<ide> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<ide> self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
<ide>
<add> def create_and_check_for_image_classification(self, config, pixel_values):
<add> config.num_labels = self.type_sequence_label_size
<add> model = FlaxViTForImageClassification(config=config)
<add> result = model(pixel_values)
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<add>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = FlaxViTForImageClassification(config)
<add>
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values)
<add>
<ide> def prepare_config_and_inputs_for_common(self):
<ide> config_and_inputs = self.prepare_config_and_inputs()
<ide> (
<ide> def setUp(self) -> None:
<ide> def test_config(self):
<ide> self.config_tester.run_common_tests()
<ide>
<del> # We neeed to override this test because ViT's forward signature is different than text models.
<add> def test_model(self):
<add> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<add> self.model_tester.create_and_check_model(*config_and_inputs)
<add>
<add> def test_for_image_classification(self):
<add> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<add> self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
<add>
<add> # We need to override this test because ViT's forward signature is different than text models.
<ide> def test_forward_signature(self):
<ide> config, _ = self.model_tester.prepare_config_and_inputs_for_common()
<ide>
<ide><path>tests/models/vit/test_modeling_tf_vit.py
<ide> def create_and_check_for_image_classification(self, config, pixel_values, labels
<ide> result = model(pixel_values, interpolate_pos_encoding=True, training=False)
<ide> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<ide>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = TFViTForImageClassification(config)
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values)
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<add>
<ide> def prepare_config_and_inputs_for_common(self):
<ide> config_and_inputs = self.prepare_config_and_inputs()
<ide> config, pixel_values, labels = config_and_inputs
<ide><path>tests/models/vit/test_modeling_vit.py
<ide> def create_and_check_model(self, config, pixel_values, labels):
<ide> result = model(pixel_values)
<ide> self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
<ide>
<add> def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels):
<add> model = ViTForMaskedImageModeling(config=config)
<add> model.to(torch_device)
<add> model.eval()
<add> result = model(pixel_values)
<add> self.parent.assertEqual(
<add> result.logits.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size)
<add> )
<add>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = ViTForMaskedImageModeling(config)
<add> model.to(torch_device)
<add> model.eval()
<add>
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values)
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, 1, self.image_size, self.image_size))
<add>
<ide> def create_and_check_for_image_classification(self, config, pixel_values, labels):
<ide> config.num_labels = self.type_sequence_label_size
<ide> model = ViTForImageClassification(config)
<ide> def create_and_check_for_image_classification(self, config, pixel_values, labels
<ide> result = model(pixel_values, labels=labels)
<ide> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<ide>
<add> # test greyscale images
<add> config.num_channels = 1
<add> model = ViTForImageClassification(config)
<add> model.to(torch_device)
<add> model.eval()
<add>
<add> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<add> result = model(pixel_values)
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
<add>
<ide> def prepare_config_and_inputs_for_common(self):
<ide> config_and_inputs = self.prepare_config_and_inputs()
<ide> (
<ide> def test_model(self):
<ide> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<ide> self.model_tester.create_and_check_model(*config_and_inputs)
<ide>
<add> def test_for_masked_image_modeling(self):
<add> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<add> self.model_tester.create_and_check_for_masked_image_modeling(*config_and_inputs)
<add>
<ide> def test_for_image_classification(self):
<ide> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<ide> self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
<ide> def test_inference_image_classification_head(self):
<ide> expected_slice = torch.tensor([-0.2744, 0.8215, -0.0836]).to(torch_device)
<ide>
<ide> self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
<add>
<add> @slow
<add> def test_inference_interpolate_pos_encoding(self):
<add> # ViT models have an `interpolate_pos_encoding` argument in their forward method,
<add> # allowing to interpolate the pre-trained position embeddings in order to use
<add> # the model on higher resolutions. The DINO model by Facebook AI leverages this
<add> # to visualize self-attention on higher resolution images.
<add> model = ViTModel.from_pretrained("facebook/dino-vits8").to(torch_device)
<add>
<add> feature_extractor = ViTFeatureExtractor.from_pretrained("facebook/dino-vits8", size=480)
<add> image = prepare_img()
<add> inputs = feature_extractor(images=image, return_tensors="pt")
<add> pixel_values = inputs.pixel_values.to(torch_device)
<add>
<add> # forward pass
<add> with torch.no_grad():
<add> outputs = model(pixel_values, interpolate_pos_encoding=True)
<add>
<add> # verify the logits
<add> expected_shape = torch.Size((1, 3601, 384))
<add> self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
<add>
<add> expected_slice = torch.tensor(
<add> [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]
<add> ).to(torch_device)
<add>
<add> self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))
<ide><path>tests/models/vit_mae/test_modeling_tf_vit_mae.py
<ide> import tensorflow as tf
<ide>
<ide> from transformers import TFViTMAEForPreTraining, TFViTMAEModel
<del> from transformers.models.vit_mae.modeling_tf_vit_mae import to_2tuple
<ide>
<ide>
<ide> if is_vision_available():
<ide> def __init__(
<ide> type_sequence_label_size=10,
<ide> initializer_range=0.02,
<ide> num_labels=3,
<add> mask_ratio=0.6,
<ide> scope=None,
<ide> ):
<ide> self.parent = parent
<ide> def __init__(
<ide> self.attention_probs_dropout_prob = attention_probs_dropout_prob
<ide> self.type_sequence_label_size = type_sequence_label_size
<ide> self.initializer_range = initializer_range
<add> self.mask_ratio = mask_ratio
<ide> self.scope = scope
<ide>
<add> # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
<add> # (we add 1 for the [CLS] token)
<add> num_patches = (image_size // patch_size) ** 2
<add> self.seq_length = int(math.ceil((1 - mask_ratio) * (num_patches + 1)))
<add>
<ide> def prepare_config_and_inputs(self):
<ide> pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
<ide>
<ide> def get_config(self):
<ide> attention_probs_dropout_prob=self.attention_probs_dropout_prob,
<ide> is_decoder=False,
<ide> initializer_range=self.initializer_range,
<add> mask_ratio=self.mask_ratio,
<ide> )
<ide>
<ide> def create_and_check_model(self, config, pixel_values, labels):
<ide> model = TFViTMAEModel(config=config)
<ide> result = model(pixel_values, training=False)
<del> # expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
<del> # (we add 1 for the [CLS] token)
<del> image_size = to_2tuple(self.image_size)
<del> patch_size = to_2tuple(self.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<del> expected_seq_len = int(math.ceil((1 - config.mask_ratio) * (num_patches + 1)))
<del> self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, self.hidden_size))
<add> self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
<ide>
<ide> def create_and_check_for_pretraining(self, config, pixel_values, labels):
<ide> model = TFViTMAEForPreTraining(config)
<ide> result = model(pixel_values, training=False)
<ide> # expected sequence length = num_patches
<del> image_size = to_2tuple(self.image_size)
<del> patch_size = to_2tuple(self.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<del> expected_seq_len = num_patches
<add> num_patches = (self.image_size // self.patch_size) ** 2
<ide> expected_num_channels = self.patch_size**2 * self.num_channels
<del> self.parent.assertEqual(result.logits.shape, (self.batch_size, expected_seq_len, expected_num_channels))
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, num_patches, expected_num_channels))
<ide>
<ide> # test greyscale images
<ide> config.num_channels = 1
<ide> def create_and_check_for_pretraining(self, config, pixel_values, labels):
<ide> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<ide> result = model(pixel_values, training=False)
<ide> expected_num_channels = self.patch_size**2
<del> self.parent.assertEqual(result.logits.shape, (self.batch_size, expected_seq_len, expected_num_channels))
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, num_patches, expected_num_channels))
<ide>
<ide> def prepare_config_and_inputs_for_common(self):
<ide> config_and_inputs = self.prepare_config_and_inputs()
<ide> def test_config(self):
<ide>
<ide> @unittest.skip(reason="ViTMAE does not use inputs_embeds")
<ide> def test_inputs_embeds(self):
<del> # ViTMAE does not use inputs_embeds
<ide> pass
<ide>
<ide> def test_model_common_attributes(self):
<ide> def prepare_numpy_arrays(inputs_dict):
<ide> output_for_kw_input = model(**inputs_np, noise=noise)
<ide> self.assert_outputs_same(output_for_dict_input, output_for_kw_input)
<ide>
<del> def test_attention_outputs(self):
<del> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del> config.return_dict = True
<del>
<del> # in ViTMAE, the seq_len equals (number of patches + 1) * (1 - mask_ratio), rounded above
<del> image_size = to_2tuple(self.model_tester.image_size)
<del> patch_size = to_2tuple(self.model_tester.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<del> seq_len = int(math.ceil((1 - config.mask_ratio) * (num_patches + 1)))
<del> encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len)
<del> encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
<del> chunk_length = getattr(self.model_tester, "chunk_length", None)
<del> if chunk_length is not None and hasattr(self.model_tester, "num_hashes"):
<del> encoder_seq_length = encoder_seq_length * self.model_tester.num_hashes
<del>
<del> for model_class in self.all_model_classes:
<del> inputs_dict["output_attentions"] = True
<del> inputs_dict["output_hidden_states"] = False
<del> config.return_dict = True
<del> model = model_class(config)
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class), training=False)
<del> attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
<del> self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
<del>
<del> # check that output_attentions also work using config
<del> del inputs_dict["output_attentions"]
<del> config.output_attentions = True
<del> model = model_class(config)
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class), training=False)
<del> attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
<del> self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
<del>
<del> if chunk_length is not None:
<del> self.assertListEqual(
<del> list(attentions[0].shape[-4:]),
<del> [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length],
<del> )
<del> else:
<del> self.assertListEqual(
<del> list(attentions[0].shape[-3:]),
<del> [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
<del> )
<del> out_len = len(outputs)
<del>
<del> # Check attention is always last and order is fine
<del> inputs_dict["output_attentions"] = True
<del> inputs_dict["output_hidden_states"] = True
<del> model = model_class(config)
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class), training=False)
<del>
<del> if hasattr(self.model_tester, "num_hidden_states_types"):
<del> added_hidden_states = self.model_tester.num_hidden_states_types
<del> elif self.is_encoder_decoder:
<del> added_hidden_states = 2
<del> else:
<del> added_hidden_states = 1
<del> self.assertEqual(out_len + added_hidden_states, len(outputs))
<del>
<del> self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
<del>
<del> self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
<del> if chunk_length is not None:
<del> self.assertListEqual(
<del> list(self_attentions[0].shape[-4:]),
<del> [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length],
<del> )
<del> else:
<del> self.assertListEqual(
<del> list(self_attentions[0].shape[-3:]),
<del> [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
<del> )
<del>
<del> def test_hidden_states_output(self):
<del> def check_hidden_states_output(inputs_dict, config, model_class):
<del> model = model_class(config)
<del>
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class))
<del>
<del> hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
<del>
<del> expected_num_layers = getattr(
<del> self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
<del> )
<del> self.assertEqual(len(hidden_states), expected_num_layers)
<del>
<del> # ViTMAE has a different seq_length
<del> image_size = to_2tuple(self.model_tester.image_size)
<del> patch_size = to_2tuple(self.model_tester.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<del> seq_length = int(math.ceil((1 - config.mask_ratio) * (num_patches + 1)))
<del>
<del> self.assertListEqual(
<del> list(hidden_states[0].shape[-2:]),
<del> [seq_length, self.model_tester.hidden_size],
<del> )
<del>
<del> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del>
<del> for model_class in self.all_model_classes:
<del> inputs_dict["output_hidden_states"] = True
<del> check_hidden_states_output(inputs_dict, config, model_class)
<del>
<del> # check that output_hidden_states also work using config
<del> del inputs_dict["output_hidden_states"]
<del> config.output_hidden_states = True
<del>
<del> check_hidden_states_output(inputs_dict, config, model_class)
<del>
<ide> # overwrite from common since TFViTMAEForPretraining has random masking, we need to fix the noise
<ide> # to generate masks during test
<ide> def check_pt_tf_models(self, tf_model, pt_model, tf_inputs_dict):
<ide><path>tests/models/vit_mae/test_modeling_vit_mae.py
<ide> from torch import nn
<ide>
<ide> from transformers import ViTMAEForPreTraining, ViTMAEModel
<del> from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST, to_2tuple
<add> from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST
<ide>
<ide>
<ide> if is_vision_available():
<ide> def __init__(
<ide> type_sequence_label_size=10,
<ide> initializer_range=0.02,
<ide> num_labels=3,
<add> mask_ratio=0.6,
<ide> scope=None,
<ide> ):
<ide> self.parent = parent
<ide> def __init__(
<ide> self.attention_probs_dropout_prob = attention_probs_dropout_prob
<ide> self.type_sequence_label_size = type_sequence_label_size
<ide> self.initializer_range = initializer_range
<add> self.mask_ratio = mask_ratio
<ide> self.scope = scope
<ide>
<add> # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
<add> # (we add 1 for the [CLS] token)
<add> num_patches = (image_size // patch_size) ** 2
<add> self.seq_length = int(math.ceil((1 - mask_ratio) * (num_patches + 1)))
<add>
<ide> def prepare_config_and_inputs(self):
<ide> pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
<ide>
<ide> def get_config(self):
<ide> attention_probs_dropout_prob=self.attention_probs_dropout_prob,
<ide> is_decoder=False,
<ide> initializer_range=self.initializer_range,
<add> mask_ratio=self.mask_ratio,
<ide> )
<ide>
<ide> def create_and_check_model(self, config, pixel_values, labels):
<ide> model = ViTMAEModel(config=config)
<ide> model.to(torch_device)
<ide> model.eval()
<ide> result = model(pixel_values)
<del> # expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
<del> # (we add 1 for the [CLS] token)
<del> image_size = to_2tuple(self.image_size)
<del> patch_size = to_2tuple(self.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<del> expected_seq_len = int(math.ceil((1 - config.mask_ratio) * (num_patches + 1)))
<del> self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, self.hidden_size))
<add> self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
<ide>
<ide> def create_and_check_for_pretraining(self, config, pixel_values, labels):
<ide> model = ViTMAEForPreTraining(config)
<ide> model.to(torch_device)
<ide> model.eval()
<ide> result = model(pixel_values)
<del> # expected sequence length = num_patches
<del> image_size = to_2tuple(self.image_size)
<del> patch_size = to_2tuple(self.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<del> expected_seq_len = num_patches
<add> num_patches = (self.image_size // self.patch_size) ** 2
<ide> expected_num_channels = self.patch_size**2 * self.num_channels
<del> self.parent.assertEqual(result.logits.shape, (self.batch_size, expected_seq_len, expected_num_channels))
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, num_patches, expected_num_channels))
<ide>
<ide> # test greyscale images
<ide> config.num_channels = 1
<ide> def create_and_check_for_pretraining(self, config, pixel_values, labels):
<ide> pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
<ide> result = model(pixel_values)
<ide> expected_num_channels = self.patch_size**2
<del> self.parent.assertEqual(result.logits.shape, (self.batch_size, expected_seq_len, expected_num_channels))
<add> self.parent.assertEqual(result.logits.shape, (self.batch_size, num_patches, expected_num_channels))
<ide>
<ide> def prepare_config_and_inputs_for_common(self):
<ide> config_and_inputs = self.prepare_config_and_inputs()
<ide> def setUp(self):
<ide> def test_config(self):
<ide> self.config_tester.run_common_tests()
<ide>
<add> @unittest.skip(reason="ViTMAE does not use inputs_embeds")
<ide> def test_inputs_embeds(self):
<del> # ViTMAE does not use inputs_embeds
<ide> pass
<ide>
<ide> def test_model_common_attributes(self):
<ide> def test_for_pretraining(self):
<ide> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<ide> self.model_tester.create_and_check_for_pretraining(*config_and_inputs)
<ide>
<del> def test_attention_outputs(self):
<del> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del> config.return_dict = True
<del>
<del> # in ViTMAE, the seq_len equals (number of patches + 1) * (1 - mask_ratio), rounded above
<del> image_size = to_2tuple(self.model_tester.image_size)
<del> patch_size = to_2tuple(self.model_tester.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<del> seq_len = int(math.ceil((1 - config.mask_ratio) * (num_patches + 1)))
<del> encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len)
<del> encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
<del> chunk_length = getattr(self.model_tester, "chunk_length", None)
<del> if chunk_length is not None and hasattr(self.model_tester, "num_hashes"):
<del> encoder_seq_length = encoder_seq_length * self.model_tester.num_hashes
<del>
<del> for model_class in self.all_model_classes:
<del> inputs_dict["output_attentions"] = True
<del> inputs_dict["output_hidden_states"] = False
<del> config.return_dict = True
<del> model = model_class(config)
<del> model.to(torch_device)
<del> model.eval()
<del> with torch.no_grad():
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class))
<del> attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
<del> self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
<del>
<del> # check that output_attentions also work using config
<del> del inputs_dict["output_attentions"]
<del> config.output_attentions = True
<del> model = model_class(config)
<del> model.to(torch_device)
<del> model.eval()
<del> with torch.no_grad():
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class))
<del> attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
<del> self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
<del>
<del> if chunk_length is not None:
<del> self.assertListEqual(
<del> list(attentions[0].shape[-4:]),
<del> [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length],
<del> )
<del> else:
<del> self.assertListEqual(
<del> list(attentions[0].shape[-3:]),
<del> [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
<del> )
<del> out_len = len(outputs)
<del>
<del> # Check attention is always last and order is fine
<del> inputs_dict["output_attentions"] = True
<del> inputs_dict["output_hidden_states"] = True
<del> model = model_class(config)
<del> model.to(torch_device)
<del> model.eval()
<del> with torch.no_grad():
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class))
<del>
<del> if hasattr(self.model_tester, "num_hidden_states_types"):
<del> added_hidden_states = self.model_tester.num_hidden_states_types
<del> elif self.is_encoder_decoder:
<del> added_hidden_states = 2
<del> else:
<del> added_hidden_states = 1
<del> self.assertEqual(out_len + added_hidden_states, len(outputs))
<del>
<del> self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
<del>
<del> self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
<del> if chunk_length is not None:
<del> self.assertListEqual(
<del> list(self_attentions[0].shape[-4:]),
<del> [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length],
<del> )
<del> else:
<del> self.assertListEqual(
<del> list(self_attentions[0].shape[-3:]),
<del> [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
<del> )
<del>
<del> def test_hidden_states_output(self):
<del> def check_hidden_states_output(inputs_dict, config, model_class):
<del> model = model_class(config)
<del> model.to(torch_device)
<del> model.eval()
<del>
<del> with torch.no_grad():
<del> outputs = model(**self._prepare_for_class(inputs_dict, model_class))
<del>
<del> hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
<del>
<del> expected_num_layers = getattr(
<del> self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
<del> )
<del> self.assertEqual(len(hidden_states), expected_num_layers)
<del>
<del> # ViTMAE has a different seq_length
<del> image_size = to_2tuple(self.model_tester.image_size)
<del> patch_size = to_2tuple(self.model_tester.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<del> seq_length = int(math.ceil((1 - config.mask_ratio) * (num_patches + 1)))
<del>
<del> self.assertListEqual(
<del> list(hidden_states[0].shape[-2:]),
<del> [seq_length, self.model_tester.hidden_size],
<del> )
<del>
<del> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del>
<del> for model_class in self.all_model_classes:
<del> inputs_dict["output_hidden_states"] = True
<del> check_hidden_states_output(inputs_dict, config, model_class)
<del>
<del> # check that output_hidden_states also work using config
<del> del inputs_dict["output_hidden_states"]
<del> config.output_hidden_states = True
<del>
<del> check_hidden_states_output(inputs_dict, config, model_class)
<del>
<ide> # overwrite from common since ViTMAEForPretraining has random masking, we need to fix the noise
<ide> # to generate masks during test
<ide> def check_pt_tf_models(self, tf_model, pt_model, pt_inputs_dict):
<ide><path>tests/models/yolos/test_modeling_yolos.py
<ide> from torch import nn
<ide>
<ide> from transformers import YolosForObjectDetection, YolosModel
<del> from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, to_2tuple
<add> from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST
<ide>
<ide>
<ide> if is_vision_available():
<ide> def __init__(
<ide> self.num_detection_tokens = num_detection_tokens
<ide> # we set the expected sequence length (which is used in several tests)
<ide> # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
<del> image_size = to_2tuple(self.image_size)
<del> patch_size = to_2tuple(self.patch_size)
<del> num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
<add> num_patches = (image_size[1] // patch_size) * (image_size[0] // patch_size)
<ide> self.expected_seq_len = num_patches + 1 + self.num_detection_tokens
<ide>
<ide> def prepare_config_and_inputs(self): | 39 |
Javascript | Javascript | fix names and default values | e45e20ad4b90ca0de7a1a738e7be90bd8abfb226 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide> * @pailhead
<ide> */
<ide>
<del> function SpecularGlossinessPbrMaterial( params ) {
<add> function MeshStandardSGMaterial( params ) {
<ide>
<ide> THREE.MeshStandardMaterial.call( this );
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide> ].join( '\n' );
<ide>
<ide> var uniforms = {
<del> specular: { value: new THREE.Color().setHex( 0x111111 ) },
<del> glossiness: { value: 0.5 },
<add> specular: { value: new THREE.Color().setHex( 0xffffff ) },
<add> glossiness: { value: 1 },
<ide> specularMap: { value: null },
<ide> glossinessMap: { value: null }
<ide> };
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> }
<ide>
<del> SpecularGlossinessPbrMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
<del> SpecularGlossinessPbrMaterial.prototype.constructor = SpecularGlossinessPbrMaterial;
<add> MeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
<add> MeshStandardSGMaterial.prototype.constructor = MeshStandardSGMaterial;
<ide>
<del> SpecularGlossinessPbrMaterial.prototype.copy = function ( source ) {
<add> MeshStandardSGMaterial.prototype.copy = function ( source ) {
<ide>
<ide> THREE.MeshStandardMaterial.prototype.copy.call( this, source );
<ide> this.specularMap = source.specularMap;
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> getMaterialType: function () {
<ide>
<del> return SpecularGlossinessPbrMaterial;
<add> return MeshStandardSGMaterial;
<ide>
<ide> },
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> createMaterial: function ( params ) {
<ide>
<del> var material = new SpecularGlossinessPbrMaterial( params );
<add> var material = new MeshStandardSGMaterial( params );
<ide> material.fog = true;
<ide>
<ide> material.color = params.color;
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> var material;
<ide>
<del> if ( materialType === SpecularGlossinessPbrMaterial ) {
<add> if ( materialType === MeshStandardSGMaterial ) {
<ide>
<ide> material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
<ide> | 1 |
Ruby | Ruby | add class to handle arguments | e9806b6b55afa5102b253c628c0d1c90297c5e23 | <ide><path>Library/Homebrew/cli/args.rb
<add>require "ostruct"
<add>
<add>module Homebrew
<add> module CLI
<add> class Args < OpenStruct
<add> # undefine tap to allow --tap argument
<add> undef tap
<add>
<add> def initialize(argv:)
<add> super
<add> @argv = argv
<add> end
<add> end
<add> end
<add>end | 1 |
Python | Python | fix mypy errors in `docs/exts` | 7e83e9cd1100b5c5e13a0285fb17abe6d60dfb88 | <ide><path>docs/exts/docs_build/lint_checks.py
<ide> def _check_missing_guide_references(operator_names, python_module_paths) -> List
<ide> continue
<ide>
<ide> docstring = ast.get_docstring(class_def)
<del> if "This class is deprecated." in docstring:
<del> continue
<add> if docstring:
<add> if "This class is deprecated." in docstring:
<add> continue
<ide>
<del> if f":ref:`howto/operator:{existing_operator}`" in ast.get_docstring(class_def):
<del> continue
<add> if f":ref:`howto/operator:{existing_operator}`" in docstring:
<add> continue
<ide>
<ide> build_errors.append(
<ide> _generate_missing_guide_error(py_module_path, class_def.lineno, existing_operator)
<ide><path>docs/exts/exampleinclude.py
<ide> from os import path
<ide>
<ide> from docutils import nodes
<del>from docutils.parsers.rst import directives
<add>
<add># No stub exists for docutils.parsers.rst.directives. See https://github.com/python/typeshed/issues/5755.
<add>from docutils.parsers.rst import directives # type: ignore[attr-defined]
<ide> from sphinx.directives.code import LiteralIncludeReader
<ide> from sphinx.ext.viewcode import viewcode_anchor
<ide> from sphinx.locale import _
<ide><path>docs/exts/operators_and_hooks_ref.py
<ide> import jinja2
<ide> from docutils import nodes
<ide> from docutils.nodes import Element
<del>from docutils.parsers.rst import Directive, directives
<add>
<add># No stub exists for docutils.parsers.rst.directives. See https://github.com/python/typeshed/issues/5755.
<add>from docutils.parsers.rst import Directive, directives # type: ignore[attr-defined]
<ide> from docutils.statemachine import StringList
<ide> from provider_yaml_utils import get_provider_yaml_paths, load_package_data
<ide> from sphinx.util import nested_parse_with_titles
<ide><path>docs/exts/substitution_extensions.py
<ide>
<ide> from docutils import nodes
<ide> from docutils.nodes import Node, system_message
<del>from docutils.parsers.rst import Directive, directives
<add>
<add># No stub exists for docutils.parsers.rst.directives. See https://github.com/python/typeshed/issues/5755.
<add>from docutils.parsers.rst import Directive, directives # type: ignore[attr-defined]
<ide> from docutils.parsers.rst.roles import code_role
<ide> from sphinx.application import Sphinx
<ide> from sphinx.transforms import SphinxTransform | 4 |
Ruby | Ruby | use path escaping for email addresses | 21ffef38a5dc5a6a21f7e841aecab5b51f4fd185 | <ide><path>actionview/lib/action_view/helpers/url_helper.rb
<ide> def mail_to(email_address, name = nil, html_options = {}, &block)
<ide> }.compact
<ide> extras = extras.empty? ? '' : '?' + extras.join('&')
<ide>
<del> encoded_email_address = ERB::Util.url_encode(email_address).gsub("%40", "@")
<add> encoded_email_address = Rack::Utils.escape_path(email_address)
<ide> html_options["href"] = "mailto:#{encoded_email_address}#{extras}"
<ide>
<ide> content_tag("a".freeze, name || email_address, html_options, &block)
<ide><path>actionview/test/template/url_helper_test.rb
<ide> def test_mail_to
<ide>
<ide> def test_mail_to_with_special_characters
<ide> assert_dom_equal(
<del> %{<a href="mailto:%23%21%24%25%26%27%2A%2B-%2F%3D%3F%5E_%60%7B%7D%7C%7E@example.org">#!$%&'*+-/=?^_`{}|~@example.org</a>},
<add> %(<a href="mailto:%23!$%25&'*+-/=?%5E_%60%7B%7D%7C~@example.org">#!$%&'*+-/=?^_`{}|~@example.org</a>),
<ide> mail_to("#!$%&'*+-/=?^_`{}|~@example.org")
<ide> )
<ide> end
<ide>
<ide> def test_mail_with_options
<ide> assert_dom_equal(
<del> %{<a href="mailto:me@example.com?cc=ccaddress%40example.com&bcc=bccaddress%40example.com&body=This%20is%20the%20body%20of%20the%20message.&subject=This%20is%20an%20example%20email&reply-to=foo%40bar.com">My email</a>},
<add> %{<a href="mailto:me@example.com?cc=ccaddress@example.com&bcc=bccaddress@example.com&body=This%20is%20the%20body%20of%20the%20message.&subject=This%20is%20an%20example%20email&reply-to=foo@bar.com">My email</a>},
<ide> mail_to("me@example.com", "My email", cc: "ccaddress@example.com", bcc: "bccaddress@example.com", subject: "This is an example email", body: "This is the body of the message.", reply_to: "foo@bar.com")
<ide> )
<ide>
<ide> def test_mail_to_with_block
<ide> end
<ide>
<ide> def test_mail_to_with_block_and_options
<del> assert_dom_equal %{<a class="special" href="mailto:me@example.com?cc=ccaddress%40example.com"><span>Email me</span></a>},
<add> assert_dom_equal %{<a class="special" href="mailto:me@example.com?cc=ccaddress@example.com"><span>Email me</span></a>},
<ide> mail_to('me@example.com', cc: "ccaddress@example.com", class: "special") { content_tag(:span, 'Email me') }
<ide> end
<ide> | 2 |
PHP | PHP | fix docblock in route | 7892af3b333a8668688d9505d8eedd7f94cdc6cc | <ide><path>src/Illuminate/Support/Facades/Route.php
<ide> * @method \Illuminate\Support\Facades\Route domain(string $value)
<ide> * @method \Illuminate\Support\Facades\Route name(string $value)
<ide> * @method \Illuminate\Support\Facades\Route namespace(string $value)
<del> * @method \Illuminate\Routing\Route group(string $value)
<add> * @method \Illuminate\Routing\Route group(array $value)
<ide> * @method \Illuminate\Support\Facades\Route redirect(string $uri, string $destination, int $status = 301)
<ide> * @method \Illuminate\Support\Facades\Route view(string $uri, string $view, array $data = [])
<ide> * | 1 |
Javascript | Javascript | fix lint error | 0be2dd32bc489043bfda568b114651e54705aa08 | <ide><path>stylelint.config.js
<ide> module.exports = {
<ide> "rule-empty-line-before": null, // TODO: enable?
<ide> "at-rule-empty-line-before": null, // TODO: enable?
<ide> "font-family-no-duplicate-names": null, // TODO: enable?
<add> "unit-no-unknown": [true, {"ignoreUnits": [ "x" ]}], // Needed for -webkit-image-set 1x/2x units
<ide> }
<ide> } | 1 |
Ruby | Ruby | use explicit checks instead of custom matcher | 31c51108ce43ae97f6b8c061be90ccc1a567010b | <ide><path>Library/Homebrew/cask/spec/cask/artifact/binary_spec.rb
<ide> shutup do
<ide> Hbc::Artifact::Binary.new(cask).install_phase
<ide> end
<del> expect(expected_path).to be_a_valid_symlink
<add> expect(expected_path).to be_a_symlink
<add> expect(expected_path.readlink).to exist
<ide> end
<ide>
<ide> it "avoids clobbering an existing binary by linking over it" do
<ide> Hbc::Artifact::Binary.new(cask).install_phase
<ide> end
<ide>
<del> expect(expected_path).to be_a_valid_symlink
<add> expect(expected_path).to be_a_symlink
<add> expect(expected_path.readlink).to exist
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cask/spec/spec_helper.rb
<ide> RSpec.configure do |config|
<ide> config.order = :random
<ide> config.include(Test::Helper::Shutup)
<del> config.include(FileMatchers)
<ide> end
<ide><path>Library/Homebrew/cask/spec/support/file_matchers.rb
<del>module FileMatchers
<del> extend RSpec::Matchers::DSL
<del>
<del> matcher :be_a_valid_symlink do
<del> match do |path|
<del> path.symlink? && path.readlink.exist?
<del> end
<del> end
<del>end | 3 |
Text | Text | remove extra readme | 95df0fd9b2639d660aec9f14f60a737ba2e3e3cf | <ide><path>official/vision/beta/projects/movinet/README.google.md
<del># Mobile Video Networks (MoViNets)
<del>
<del>Design doc: go/movinet
<del>
<del>## Getting Started
<del>
<del>```shell
<del>bash third_party/tensorflow_models/official/vision/beta/projects/movinet/google/run_train.sh
<del>```
<del>
<del>## Results
<del>
<del>Results are tracked at go/movinet-experiments. | 1 |
Ruby | Ruby | fix latest xcode on big sur | 51a57760715fb84e58187563943092351e86c171 | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> module Xcode
<ide> def latest_version(macos: MacOS.version)
<ide> latest_stable = "13.3"
<ide> case macos
<del> when "12", "11" then latest_stable
<add> when "12" then latest_stable
<add> when "11" then "13.2.1"
<ide> when "10.15" then "12.4"
<ide> when "10.14" then "11.3.1"
<ide> when "10.13" then "10.1"
<ide> def update_instructions
<ide> sig { returns(String) }
<ide> def latest_clang_version
<ide> case MacOS.version
<del> when "12", "11" then "1316.0.21.2"
<del> when "10.15" then "1200.0.32.29"
<del> when "10.14" then "1100.0.33.17"
<del> when "10.13" then "1000.10.44.2"
<del> when "10.12" then "900.0.39.2"
<del> when "10.11" then "800.0.42.1"
<del> when "10.10" then "700.1.81"
<del> else "600.0.57"
<add> when "12" then "1316.0.21.2"
<add> when "11" then "1300.0.29.30"
<add> when "10.15" then "1200.0.32.29"
<add> when "10.14" then "1100.0.33.17"
<add> when "10.13" then "1000.10.44.2"
<add> when "10.12" then "900.0.39.2"
<add> when "10.11" then "800.0.42.1"
<add> when "10.10" then "700.1.81"
<add> else "600.0.57"
<ide> end
<ide> end
<ide> | 1 |
Python | Python | add doc strings on deployment classes | dc9827e760bd642c7c8cb66f1c27fc678059e931 | <ide><path>libcloud/deployment.py
<ide> import os
<ide>
<ide> class Deployment(object):
<del> pass
<add> """
<add> Base class for deployment tasks.
<add> """
<add>
<add> def run(self, node, client):
<add> """
<add> Runs this deployment task on C{node} using the C{client} provided.
<add>
<add> @type node: L{Node}
<add> @keyword node: Node to operate one
<add>
<add> @type client: L{BaseSSHClient}
<add> @keyword client: Connected SSH client to use.
<add>
<add> @return: L{Node}
<add> """
<add> raise NotImplementedError, \
<add> 'run not implemented for this deployment'
<add>
<ide>
<ide> class SSHKeyDeployment(Deployment):
<add> """
<add> Installs a public SSH Key onto a host.
<add> """
<add>
<ide> def __init__(self, key):
<add> """
<add> @type key: C{str}
<add> @keyword key: Contents of the public key write
<add> """
<ide> self.key = key
<ide>
<ide> def run(self, node, client):
<add> """
<add> Installs SSH key into C{.ssh/authorized_keys}
<add>
<add> See also L{Deployment.run}
<add> """
<ide> client.put(".ssh/authorized_keys", contents=self.key)
<ide> return node
<ide>
<ide> class ScriptDeployment(Deployment):
<add> """
<add> Runs an arbitrary Shell Script task.
<add> """
<add>
<ide> def __init__(self, script, name=None, delete=False):
<add> """
<add> @type script: C{str}
<add> @keyword script: Contents of the script to run
<add>
<add> @type name: C{str}
<add> @keyword name: Name of the script to upload it as, if not specified, a random name will be choosen.
<add>
<add> @type delete: C{bool}
<add> @keyword delete: Weither to delete the script on completion.
<add> """
<ide> self.script = script
<ide> self.stdout = None
<ide> self.stderr = None
<ide> def __init__(self, script, name=None, delete=False):
<ide> self.name = "/root/deployment_%s.sh" % (os.urandom(4).encode('hex'))
<ide>
<ide> def run(self, node, client):
<add> """
<add> Uploads the shell script and then executes it.
<add>
<add> See also L{Deployment.run}
<add> """
<ide> client.put(path=self.name, chmod=755, contents=self.script)
<ide> self.stdout, self.stderr = client.run(self.name)
<ide> if self.delete:
<ide> client.delete(self.name)
<ide> return node
<ide>
<ide> class MultiStepDeployment(Deployment):
<add> """
<add> Runs a chain of Deployment steps.
<add> """
<ide> def __init__(self, add = None):
<add> """
<add> @type add: C{list}
<add> @keyword add: Deployment steps to add.
<add> """
<ide> self.steps = []
<ide> self.add(add)
<ide>
<ide> def add(self, add):
<add> """Add a deployment to this chain.
<add>
<add> @type add: Single L{Deployment} or a C{list} of L{Deployment}
<add> @keyword add: Adds this deployment to the others already in this object.
<add> """
<ide> if add is not None:
<ide> add = add if isinstance(add, (list, tuple)) else [add]
<ide> self.steps.extend(add)
<ide>
<ide> def run(self, node, client):
<add> """
<add> Run each deployment that has been added.
<add>
<add> See also L{Deployment.run}
<add> """
<ide> for s in self.steps:
<ide> node = s.run(node, client)
<ide> return node | 1 |
Python | Python | add platform info to the final optimization report | 3944f409884b50c3cb0cf101b54e622e6125a850 | <ide><path>numpy/distutils/ccompiler_opt.py
<ide> def generate_dispatch_header(self, header_path):
<ide>
<ide> def report(self, full=False):
<ide> report = []
<add> platform_rows = []
<ide> baseline_rows = []
<ide> dispatch_rows = []
<add> report.append(("Platform", platform_rows))
<add> report.append(("", ""))
<ide> report.append(("CPU baseline", baseline_rows))
<ide> report.append(("", ""))
<ide> report.append(("CPU dispatch", dispatch_rows))
<ide>
<add> ########## platform ##########
<add> platform_rows.append(("Architecture", (
<add> "unsupported" if self.cc_on_noarch else self.cc_march)
<add> ))
<add> platform_rows.append(("Compiler", (
<add> "unix-like" if self.cc_is_nocc else self.cc_name)
<add> ))
<ide> ########## baseline ##########
<ide> if self.cc_noopt:
<del> baseline_rows.append((
<del> "Requested", "optimization disabled %s" % (
<del> "(unsupported arch)" if self.cc_on_noarch else ""
<del> )
<del> ))
<add> baseline_rows.append(("Requested", "optimization disabled"))
<ide> else:
<ide> baseline_rows.append(("Requested", repr(self._requested_baseline)))
<ide>
<ide> def report(self, full=False):
<ide>
<ide> ########## dispatch ##########
<ide> if self.cc_noopt:
<del> dispatch_rows.append((
<del> "Requested", "optimization disabled %s" % (
<del> "(unsupported arch)" if self.cc_on_noarch else ""
<del> )
<del> ))
<add> baseline_rows.append(("Requested", "optimization disabled"))
<ide> else:
<ide> dispatch_rows.append(("Requested", repr(self._requested_dispatch)))
<ide> | 1 |
Text | Text | add 2.15.2 to changelog | c46c19dbc6cc2c6bf9bb033400a818fcbfcebe99 | <ide><path>CHANGELOG.md
<ide> - [#15528](https://github.com/emberjs/ember.js/pull/15528) [DEPRECATION] Deprecate `Controller#content` alias.
<ide> - [#15552](https://github.com/emberjs/ember.js/pull/15552) [FEATURE] Update blueprints and tests to RFC #176.
<ide>
<add>### 2.15.2 (October 4, 2017)
<add>
<add>- [#15604](https://github.com/emberjs/ember.js/pull/15604) [BUGFIX] Ember Inspector Data Adapter: Only trigger model type update if the record live array count actually changed.
<add>- [#15695](https://github.com/emberjs/ember.js/pull/15695) [BUGFIX] Avoid creating event dispatcher in FastBoot with Engines.
<add>
<ide> ### 2.15.1 (October 2, 2017)
<ide>
<ide> - [#15600](https://github.com/emberjs/ember.js/pull/15600) [BUGFIX] ensure “pause on exception” pauses in the right place. | 1 |
Text | Text | profile lookup. fixes and enhancements | 5e5c162303685ca0d8db1ad30cdf01c52b259454 | <ide><path>client/src/pages/guide/english/certifications/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup/index.md
<ide> ---
<ide> title: Profile Lookup
<ide> ---
<del> Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program  and write your own code 
<add>## Profile Lookup
<add> Remember to use `Read-Search-Ask` if you get stuck. Try to pair program  and write your own code 
<ide>
<ide> ###  Problem Explanation:
<ide>
<ide> If **prop** does not correspond to any valid properties then return `No such pro
<ide> * If **firstName** is found and no associated **prop** is found, you should return `No such property`.
<ide> * If **firstName** isn't found anywhere, you should return `No such contact`.
<ide>
<del>#### Relevant Links
<del>
<del>* <a href='http://www.freecodecamp.com/challenges/accessing-objects-properties-with-bracket-notation' target='_blank' rel='nofollow'>Challenge: Accessing Objects Properties with Bracket Notation</a>
<del>* <a href='http://www.freecodecamp.com/challenges/iterate-with-javascript-for-loops' target='_blank' rel='nofollow'>Challenge: Iterate with JavaScript For Loops</a>
<ide>
<ide> ##  Hint: 1
<ide>
<ide> Leave your `return "No such contact"` out of the `for` loop as a final catch-all
<ide>
<ide> ##  Basic Code Solution:
<ide>
<del> for (var x = 0; x < contacts.length; x++){
<del> if (contacts[x].firstName === name) {
<del> if (contacts[x].hasOwnProperty(prop)) {
<del> return contacts[x][prop];
<del> } else {
<del> return "No such property";
<del> }
<add>
<add>``` javascript
<add>for (var x = 0; x < contacts.length; x++){
<add> if (contacts[x].firstName === name) {
<add> if (contacts[x].hasOwnProperty(prop)) {
<add> return contacts[x][prop];
<add> } else {
<add> return "No such property";
<ide> }
<ide> }
<del> return "No such contact";
<add>}
<add>return "No such contact";
<add> ```
<ide>
<ide> ### Code Explanation:
<ide>
<ide> Leave your `return "No such contact"` out of the `for` loop as a final catch-all
<ide> * `"likes"` is found within the first object, so the second `if` statement returns true.
<ide> * The value of `"likes"` is returned - `"Pizza", "Coding", "Brownie Points"`.
<ide>
<del>##  NOTES FOR CONTRIBUTIONS:
<add>## Alternative code solution:
<add>
<add>```javascript
<add>for (var i = 0; i < contacts.length; i++){
<add> if (contacts[i].firstName === name){
<add> if (prop in contacts[i]){
<add> return contacts[i][prop];
<add> }
<add> else return "No such property";
<add> }
<add>}
<add>return "No such contact";
<add>}
<add>```
<add>· Run code at [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Profile-lookup).
<add>
<add>### Code explanation
<add>This works as the last example but uses the `in` operator to look for `prop` instead of the `hasOwnProperty()` method.
<add>
<ide>
<del>*  **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
<del>* Add an explanation of your solution.
<del>* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. 
<del>* Please add your username only if you have added any **relevant main contents**. ( **_DO NOT_** _remove any existing usernames_)
<add>### Resources
<ide>
<del>> See  <a>**`Wiki Challenge Solution Template`**</a> for reference.
<add>- ["Iterate with JavaScript For Loops" - *fCC's challenge*](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops/)
<add> - ["Object.prototype.hasOwnProperty()" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)
<add>- ["in operator" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in) | 1 |
Javascript | Javascript | remove duplicate `should` in test name | a4be780781bfe956c3f4c84d04fa189a752d8a29 | <ide><path>test/integration/prerender/test/index.test.js
<ide> const runTests = (dev = false, isEmulatedServerless = false) => {
<ide> })
<ide> } else {
<ide> if (!isEmulatedServerless) {
<del> it('should should use correct caching headers for a no-revalidate page', async () => {
<add> it('should use correct caching headers for a no-revalidate page', async () => {
<ide> const initialRes = await fetchViaHTTP(appPort, '/something')
<ide> expect(initialRes.headers.get('cache-control')).toBe(
<ide> 's-maxage=31536000, stale-while-revalidate' | 1 |
Python | Python | remove a pointless if | c2cbf13ac4df693cec70f6949efdc386c791d1f9 | <ide><path>numpy/lib/function_base.py
<ide> def _quantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
<ide> x1 = x1.squeeze(0)
<ide> x2 = x2.squeeze(0)
<ide>
<del> if out is not None:
<del> r = add(x1, x2, out=out)
<del> else:
<del> r = add(x1, x2)
<add> r = add(x1, x2, out=out)
<ide>
<ide> if np.any(n):
<ide> if zerod: | 1 |
Javascript | Javascript | move jest-dom into setup file | b9db30f7a1366ed26238b80032a93ec803a37bf7 | <ide><path>client/jest.config.js
<ide> module.exports = {
<ide> transform: {
<ide> '^.+\\.js$': '<rootDir>/jest.transform.js'
<ide> },
<del> transformIgnorePatterns: ['node_modules/(?!(gatsby)/)']
<add> transformIgnorePatterns: ['node_modules/(?!(gatsby)/)'],
<add> setupFilesAfterEnv: ['./jest.setup.js']
<ide> };
<ide><path>client/jest.setup.js
<add>import '@testing-library/jest-dom/extend-expect';
<ide><path>client/src/client-only-routes/ShowSettings.test.js
<ide> /* global jest, expect */
<ide> import React from 'react';
<del>import 'jest-dom/extend-expect';
<ide> import ShallowRenderer from 'react-test-renderer/shallow';
<ide> import { apiLocation } from '../../config/env.json';
<ide>
<ide><path>client/src/components/Footer/Footer.test.js
<ide> /* global expect */
<ide> import React from 'react';
<ide> import renderer from 'react-test-renderer';
<del>import 'jest-dom/extend-expect';
<ide>
<ide> import Footer from './';
<ide>
<ide><path>client/src/components/Intro/Intro.test.js
<ide> import renderer from 'react-test-renderer';
<ide> import { Provider } from 'react-redux';
<ide> import { createStore } from '../../redux/createStore';
<ide>
<del>import 'jest-dom/extend-expect';
<del>
<ide> import Intro from './';
<ide>
<ide> function rendererCreateWithRedux(ui) {
<ide><path>client/src/components/Map/Map.test.js
<ide> /* global expect jest */
<ide>
<del>import '@testing-library/jest-dom/extend-expect';
<ide> import React from 'react';
<ide> import { render } from '@testing-library/react';
<ide> import { Provider } from 'react-redux';
<ide><path>client/src/components/Map/components/Block.test.js
<ide> /* global jest, expect */
<ide>
<del>import '@testing-library/jest-dom/extend-expect';
<ide> import React from 'react';
<ide> import { render, fireEvent } from '@testing-library/react';
<ide>
<ide><path>client/src/components/Map/components/SuperBlock.test.js
<ide> /* global jest, expect */
<ide>
<del>import '@testing-library/jest-dom/extend-expect';
<ide> import React from 'react';
<ide> import { render, fireEvent } from '@testing-library/react';
<ide> import { Provider } from 'react-redux';
<ide><path>client/src/components/formHelpers/BlockSaveButton.test.js
<ide> /* global expect */
<ide>
<del>import '@testing-library/jest-dom/extend-expect';
<ide> import React from 'react';
<ide> import { render } from '@testing-library/react';
<ide>
<ide><path>client/src/components/formHelpers/Form.test.js
<ide> /* global jest, expect */
<del>import '@testing-library/jest-dom/extend-expect';
<ide>
<ide> import React from 'react';
<ide> import { render, fireEvent } from '@testing-library/react';
<ide><path>client/src/components/helpers/Link.test.js
<ide> /* global expect */
<ide> import React from 'react';
<ide> import renderer from 'react-test-renderer';
<del>import 'jest-dom/extend-expect';
<ide>
<ide> import Link from './Link';
<ide>
<ide><path>client/src/components/helpers/Loader.test.js
<ide> /* global expect */
<ide> import React from 'react';
<ide> import { render, cleanup } from '@testing-library/react';
<del>import 'jest-dom/extend-expect';
<ide>
<ide> import Loader from './Loader';
<ide>
<ide><path>client/src/components/profile/Profile.test.js
<ide> /* global expect */
<ide>
<del>import '@testing-library/jest-dom/extend-expect';
<ide> import React from 'react';
<ide> import { render } from '@testing-library/react';
<ide>
<ide><path>client/src/components/profile/components/HeatMap.test.js
<ide> /* global expect jest */
<ide>
<del>import '@testing-library/jest-dom/extend-expect';
<ide> import React from 'react';
<ide> import { render } from '@testing-library/react';
<ide>
<ide><path>client/src/components/search/searchBar/SearchBar.test.js
<ide> /* global jest, expect */
<ide> import React from 'react';
<del>import 'jest-dom/extend-expect';
<ide> import ShallowRenderer from 'react-test-renderer/shallow';
<ide>
<ide> import { SearchBar } from './SearchBar';
<ide><path>client/src/components/settings/Certification.test.js
<ide> /* global expect */
<ide>
<del>import '@testing-library/jest-dom/extend-expect';
<ide> import React from 'react';
<ide> import { render } from '@testing-library/react';
<ide> import { Provider } from 'react-redux';
<ide><path>client/src/templates/Challenges/components/CompletionModal.test.js
<ide> /* global expect */
<ide>
<del>import '@testing-library/jest-dom/extend-expect';
<del>
<ide> import { getCompletedPercent } from './CompletionModal';
<ide>
<ide> const completedChallengesIds = ['1', '3', '5'],
<ide><path>client/src/templates/Challenges/components/CompletionModalBody.test.js
<ide> /* global jest, expect */
<ide>
<del>import '@testing-library/jest-dom/extend-expect';
<ide> import React from 'react';
<ide> import { render, fireEvent } from '@testing-library/react';
<ide> | 18 |
PHP | PHP | fix multiple unused variables | 7464dce14d76071d6b9f6056f96d7983528bc6ee | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> protected function callScope(callable $scope, $parameters = [])
<ide> $this->addNewWheresWithinGroup($query, $originalWhereCount);
<ide> }
<ide>
<del> return $this;
<add> return $result;
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Queue/Console/WorkCommand.php
<ide> public function fire()
<ide> // connection being run for the queue operation currently being executed.
<ide> $queue = $this->getQueue($connection);
<ide>
<del> $response = $this->runWorker(
<add> $this->runWorker(
<ide> $connection, $queue
<ide> );
<ide> }
<ide><path>src/Illuminate/View/Concerns/ManagesComponents.php
<ide> public function slot($name)
<ide> */
<ide> public function endSlot()
<ide> {
<del> $current = last($this->componentStack);
<add> last($this->componentStack);
<ide>
<ide> $currentSlot = array_pop(
<ide> $this->slotStack[$this->currentComponent()]
<ide><path>src/Illuminate/View/Factory.php
<ide> public function make($view, $data = [], $mergeData = [])
<ide> */
<ide> public function renderEach($view, $data, $iterator, $empty = 'raw|')
<ide> {
<del> $result = '';
<del>
<ide> // If is actually data in the array, we will loop through the data and append
<ide> // an instance of the partial view to the final result HTML passing in the
<ide> // iterated value of this data array, allowing the views to access them.
<ide> if (count($data) > 0) {
<del> $result = $this->renderEachView($view, $data, $iterator);
<add> return $this->renderEachView($view, $data, $iterator);
<ide> }
<ide>
<ide> // If there is no data in the array, we will render the contents of the empty
<ide> // view. Alternatively, the "empty view" could be a raw string that begins
<ide> // with "raw|" for convenience and to let this know that it is a string.
<del> else {
<del> return $this->renderEmptyEach($empty);
<del> }
<del>
<del> return $result;
<add> return $this->renderEmptyEach($empty);
<ide> }
<ide>
<ide> /** | 4 |
Ruby | Ruby | switch secure token generation to base58 | 47316feee0f061f80e26c51fb0d41f537407ab9c | <ide><path>activerecord/lib/active_record/secure_token.rb
<ide> module ClassMethods
<ide> #
<ide> # user = User.new
<ide> # user.save
<del> # user.token # => "44539a6a59835a4ee9d7b112"
<del> # user.auth_token # => "e2426a93718d1817a43abbaa"
<add> # user.token # => "4kUgL2pdQMSCQtjE"
<add> # user.auth_token # => "77TMHrHJFvFDwodq8w7Ev2m7"
<ide> # user.regenerate_token # => true
<ide> # user.regenerate_auth_token # => true
<ide> #
<del> # SecureRandom is used to generate the 24-character unique token, so collisions are highly unlikely.
<del> # We'll check to see if the generated token has been used already using #exists?, and retry up to 10
<del> # times to find another unused token. After that a RuntimeError is raised if the problem persists.
<add> # SecureRandom::base58 is used to generate the 24-character unique token, so collisions are highly unlikely.
<ide> #
<ide> # Note that it's still possible to generate a race condition in the database in the same way that
<ide> # validates_presence_of can. You're encouraged to add a unique index in the database to deal with
<ide> # this even more unlikely scenario.
<ide> def has_secure_token(attribute = :token)
<ide> # Load securerandom only when has_secure_key is used.
<del> require 'securerandom'
<del> define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_secure_token(attribute) }
<del> before_create { self.send("#{attribute}=", self.class.generate_unique_secure_token(attribute)) }
<add> require 'active_support/core_ext/securerandom'
<add> define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_secure_token }
<add> before_create { self.send("#{attribute}=", self.class.generate_unique_secure_token) }
<ide> end
<ide>
<del> def generate_unique_secure_token(attribute)
<del> 10.times do |i|
<del> SecureRandom.hex(12).tap do |token|
<del> if exists?(attribute => token)
<del> raise "Couldn't generate a unique token in 10 attempts!" if i == 9
<del> else
<del> return token
<del> end
<del> end
<del> end
<add> def generate_unique_secure_token
<add> SecureRandom.base58(24)
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/secure_token_test.rb
<ide> def test_regenerating_the_secure_token
<ide> assert_not_equal @user.token, old_token
<ide> assert_not_equal @user.auth_token, old_auth_token
<ide> end
<del>
<del> def test_raise_after_ten_unsuccessful_attempts_to_generate_a_unique_token
<del> User.stubs(:exists?).returns(*Array.new(10, true))
<del> assert_raises(RuntimeError) do
<del> @user.save
<del> end
<del> end
<del>
<del> def test_return_unique_token_after_nine_unsuccessful_attempts
<del> User.stubs(:exists?).returns(*Array.new(10) { |i| i == 9 ? false : true })
<del> @user.save
<del> assert_not_nil @user.token
<del> assert_not_nil @user.auth_token
<del> end
<ide> end | 2 |
Ruby | Ruby | add satisfied test | 13dcdb3098d6c1089db937d5c122cf06a0631ac4 | <ide><path>Library/Homebrew/test/test_gpg2_requirement.rb
<add>require "testing_env"
<add>require "requirements/gpg2_requirement"
<add>require "fileutils"
<add>
<add>class GPG2RequirementTests < Homebrew::TestCase
<add> def setup
<add> @dir = Pathname.new(mktmpdir)
<add> (@dir/"bin/gpg").write <<-EOS.undent
<add> #!/bin/bash
<add> echo 2.0.30
<add> EOS
<add> FileUtils.chmod 0755, @dir/"bin/gpg"
<add> end
<add>
<add> def teardown
<add> FileUtils.rm_rf @dir
<add> end
<add>
<add> def test_satisfied
<add> with_environment("PATH" => @dir/"bin") do
<add> assert_predicate GPG2Requirement.new, :satisfied?
<add> end
<add> end
<add>end | 1 |
PHP | PHP | add @cannot blade directive | 9c41aa0d53412e3008285e89ff9764fa51b42469 | <ide><path>src/Illuminate/View/Compilers/BladeCompiler.php
<ide> protected function compileCan($expression)
<ide> return "<?php if (Gate::check{$expression}): ?>";
<ide> }
<ide>
<add> /**
<add> * Compile the cannot statements into valid PHP.
<add> *
<add> * @param string $expression
<add> * @return string
<add> */
<add> protected function compileCannot($expression)
<add> {
<add> return "<?php if (Gate::denies{$expression}): ?>";
<add> }
<add>
<ide> /**
<ide> * Compile the if statements into valid PHP.
<ide> *
<ide> protected function compileEndcan($expression)
<ide> return '<?php endif; ?>';
<ide> }
<ide>
<add> /**
<add> * Compile the end-cannot statements into valid PHP.
<add> *
<add> * @param string $expression
<add> * @return string
<add> */
<add> protected function compileEndcannot($expression)
<add> {
<add> return '<?php endif; ?>';
<add> }
<add>
<ide> /**
<ide> * Compile the end-if statements into valid PHP.
<ide> *
<ide><path>tests/View/ViewBladeCompilerTest.php
<ide> public function testCanStatementsAreCompiled()
<ide> $this->assertEquals($expected, $compiler->compileString($string));
<ide> }
<ide>
<add> public function testCannotStatementsAreCompiled()
<add> {
<add> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
<add> $string = '@cannot (\'update\', [$post])
<add>breeze
<add>@endcannot';
<add> $expected = '<?php if (Gate::denies(\'update\', [$post])): ?>
<add>breeze
<add><?php endif; ?>';
<add> $this->assertEquals($expected, $compiler->compileString($string));
<add> }
<add>
<ide> public function testElseStatementsAreCompiled()
<ide> {
<ide> $compiler = new BladeCompiler($this->getFiles(), __DIR__); | 2 |
Python | Python | allow sourcing disabled components | e43d43db32e66d7f03177b4214cd26dbacb9b4ed | <ide><path>spacy/language.py
<ide> def create_pipe_from_source(
<ide> # TODO: handle errors and mismatches (vectors etc.)
<ide> if not isinstance(source, self.__class__):
<ide> raise ValueError(Errors.E945.format(name=source_name, source=type(source)))
<del> if not source.has_pipe(source_name):
<add> if not source_name in source.component_names:
<ide> raise KeyError(
<ide> Errors.E944.format(
<ide> name=source_name,
<ide> model=f"{source.meta['lang']}_{source.meta['name']}",
<del> opts=", ".join(source.pipe_names),
<add> opts=", ".join(source.component_names),
<ide> )
<ide> )
<ide> pipe = source.get_pipe(source_name) | 1 |
Go | Go | avoid duplicate entries in /etc/hosts | 4850c5f1e68456dc360fd6837f67f7ea332f8335 | <ide><path>libnetwork/endpoint.go
<ide> func (ep *endpoint) sbJoin(sbox Sandbox, options ...EndpointOption) error {
<ide> if ip := ep.getFirstInterfaceAddress(); ip != nil {
<ide> address = ip.String()
<ide> }
<del> if err = sb.updateHostsFile(address, network.getSvcRecords()); err != nil {
<add> if err = sb.updateHostsFile(address, network.getSvcRecords(ep)); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (ep *endpoint) sbLeave(sbox Sandbox, options ...EndpointOption) error {
<ide> return err
<ide> }
<ide>
<del> // unwatch for service records
<del> n.getController().unWatchSvcRecord(ep)
<del>
<ide> if sb.needDefaultGW() {
<ide> ep := sb.getEPwithoutGateway()
<ide> if ep == nil {
<ide> func (ep *endpoint) Delete() error {
<ide> }
<ide> ep.Unlock()
<ide>
<del> if err = n.getEpCnt().DecEndpointCnt(); err != nil {
<add> if err = n.getController().deleteFromStore(ep); err != nil {
<ide> return err
<ide> }
<ide> defer func() {
<ide> if err != nil {
<del> if e := n.getEpCnt().IncEndpointCnt(); e != nil {
<del> log.Warnf("failed to update network %s : %v", n.name, e)
<add> ep.dbExists = false
<add> if e := n.getController().updateToStore(ep); e != nil {
<add> log.Warnf("failed to recreate endpoint in store %s : %v", name, e)
<ide> }
<ide> }
<ide> }()
<ide>
<del> if err = n.getController().deleteFromStore(ep); err != nil {
<add> if err = n.getEpCnt().DecEndpointCnt(); err != nil {
<ide> return err
<ide> }
<ide> defer func() {
<ide> if err != nil {
<del> ep.dbExists = false
<del> if e := n.getController().updateToStore(ep); e != nil {
<del> log.Warnf("failed to recreate endpoint in store %s : %v", name, e)
<add> if e := n.getEpCnt().IncEndpointCnt(); e != nil {
<add> log.Warnf("failed to update network %s : %v", n.name, e)
<ide> }
<ide> }
<ide> }()
<ide>
<add> // unwatch for service records
<add> n.getController().unWatchSvcRecord(ep)
<add>
<ide> if err = ep.deleteEndpoint(); err != nil {
<ide> return err
<ide> }
<ide><path>libnetwork/network.go
<ide> import (
<ide> "fmt"
<ide> "net"
<ide> "strconv"
<add> "strings"
<ide> "sync"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<ide> func (n *network) CreateEndpoint(name string, options ...EndpointOption) (Endpoi
<ide> }
<ide> }()
<ide>
<add> // Watch for service records
<add> n.getController().watchSvcRecord(ep)
<add> defer func() {
<add> if err != nil {
<add> n.getController().unWatchSvcRecord(ep)
<add> }
<add> }()
<add>
<ide> // Increment endpoint count to indicate completion of endpoint addition
<ide> if err = n.getEpCnt().IncEndpointCnt(); err != nil {
<ide> return nil, err
<ide> func (n *network) updateSvcRecord(ep *endpoint, localEps []*endpoint, isAdd bool
<ide> var recs []etchosts.Record
<ide> if iface := ep.Iface(); iface.Address() != nil {
<ide> if isAdd {
<add> // If we already have this endpoint in service db just return
<add> if _, ok := sr[ep.Name()]; ok {
<add> n.Unlock()
<add> return
<add> }
<add>
<ide> sr[ep.Name()] = iface.Address().IP
<ide> sr[ep.Name()+"."+n.name] = iface.Address().IP
<ide> } else {
<ide> func (n *network) updateSvcRecord(ep *endpoint, localEps []*endpoint, isAdd bool
<ide> }
<ide>
<ide> var sbList []*sandbox
<del> for _, ep := range localEps {
<del> if sb, hasSandbox := ep.getSandbox(); hasSandbox {
<add> for _, lEp := range localEps {
<add> if ep.ID() == lEp.ID() {
<add> continue
<add> }
<add>
<add> if sb, hasSandbox := lEp.getSandbox(); hasSandbox {
<ide> sbList = append(sbList, sb)
<ide> }
<ide> }
<ide> func (n *network) updateSvcRecord(ep *endpoint, localEps []*endpoint, isAdd bool
<ide> }
<ide> }
<ide>
<del>func (n *network) getSvcRecords() []etchosts.Record {
<add>func (n *network) getSvcRecords(ep *endpoint) []etchosts.Record {
<ide> n.Lock()
<ide> defer n.Unlock()
<ide>
<ide> var recs []etchosts.Record
<ide> sr, _ := n.ctrlr.svcDb[n.id]
<ide>
<ide> for h, ip := range sr {
<add> if ep != nil && strings.Split(h, ".")[0] == ep.Name() {
<add> continue
<add> }
<add>
<ide> recs = append(recs, etchosts.Record{
<ide> Hosts: h,
<ide> IP: ip.String(), | 2 |
Text | Text | fix typos in readme | e1131017022458ca20d56bf7ddc09243927e7d21 | <ide><path>README.md
<ide>
<ide> This repository contains an op-for-op PyTorch reimplementation of [Google's TensorFlow repository for the BERT model](https://github.com/google-research/bert) that was released together with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
<ide>
<del>This implementation is provided with [Google's pre-trained models](https://github.com/google-research/bert)) and a conversion script to load any pre-trained TensorFlow checkpoint for BERT is also provided.
<add>This implementation is provided with [Google's pre-trained models](https://github.com/google-research/bert), examples, notebooks and a command-line interface to load any pre-trained TensorFlow checkpoint for BERT is also provided.
<ide>
<ide> ## Content
<ide> | 1 |
PHP | PHP | make argument nullable | 8dc17abd82f009db1f6939de80fc6a7c20beb569 | <ide><path>src/Routing/Exception/DuplicateNamedRouteException.php
<ide> class DuplicateNamedRouteException extends Exception
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function __construct($message, int $code = 404, ?Throwable $previous = null)
<add> public function __construct($message, ?int $code = 404, ?Throwable $previous = null)
<ide> {
<ide> if (is_array($message) && isset($message['message'])) {
<ide> $this->_messageTemplate = $message['message'];
<ide><path>src/Routing/Exception/MissingControllerException.php
<ide> class MissingControllerException extends Exception
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function __construct($message, int $code = 404, ?Throwable $previous = null)
<add> public function __construct($message, ?int $code = 404, ?Throwable $previous = null)
<ide> {
<ide> parent::__construct($message, $code, $previous);
<ide> }
<ide><path>src/Routing/Exception/MissingRouteException.php
<ide> class MissingRouteException extends Exception
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function __construct($message, int $code = 404, ?Throwable $previous = null)
<add> public function __construct($message, ?int $code = 404, ?Throwable $previous = null)
<ide> {
<ide> if (is_array($message)) {
<ide> if (isset($message['message'])) { | 3 |
Text | Text | fix typo in http2.md | 0271b0f20309afae2b89a685e5002a25bfc94d37 | <ide><path>doc/api/http2.md
<ide> added: v8.4.0
<ide> -->
<ide>
<ide> Call [`http2stream.pushStream()`][] with the given headers, and wraps the
<del>given newly created [`Http2Stream`] on `Http2ServerRespose`.
<add>given newly created [`Http2Stream`] on `Http2ServerResponse`.
<ide>
<ide> The callback will be called with an error with code `ERR_HTTP2_STREAM_CLOSED`
<ide> if the stream is closed. | 1 |
Ruby | Ruby | exclude all located superenv paths | 161104cae70f3207b247331d182dc47c0b8c8a06 | <ide><path>Library/Homebrew/macos.rb
<ide> def locate tool
<ide> xcrun_path = unless Xcode.bad_xcode_select_path?
<ide> path = `/usr/bin/xcrun -find #{tool} 2>/dev/null`.chomp
<ide> # If xcrun finds a superenv tool then discard the result.
<del> path unless path.include?(HOMEBREW_REPOSITORY/"Library/ENV")
<add> path unless path.include?("Library/ENV")
<ide> end
<ide>
<ide> paths = %W[#{xcrun_path} | 1 |
PHP | PHP | fix alphanumeric validation | 14c81fe0521e4a1b0f32bf7f6b9936dcfcaf6998 | <ide><path>lib/Cake/Test/Case/Utility/ValidationTest.php
<ide> public function testAlphaNumeric() {
<ide>
<ide> $this->assertFalse(Validation::alphaNumeric('12 234'));
<ide> $this->assertFalse(Validation::alphaNumeric('dfd 234'));
<add> $this->assertFalse(Validation::alphaNumeric("0\n"));
<ide> $this->assertFalse(Validation::alphaNumeric("\n"));
<ide> $this->assertFalse(Validation::alphaNumeric("\t"));
<ide> $this->assertFalse(Validation::alphaNumeric("\r"));
<ide><path>lib/Cake/Utility/Validation.php
<ide> public static function alphaNumeric($check) {
<ide> if (empty($check) && $check != '0') {
<ide> return false;
<ide> }
<del> return self::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/mu');
<add> return self::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/Du');
<ide> }
<ide>
<ide> /** | 2 |
Go | Go | remove dead code registerdiffids | 02ed83aee95e506ace3a994bb2ebb7e94df5a438 | <ide><path>layer/layer_windows.go
<ide> package layer
<ide>
<ide> import (
<ide> "errors"
<del> "fmt"
<ide>
<del> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/daemon/graphdriver"
<del> "github.com/opencontainers/go-digest"
<ide> )
<ide>
<ide> // GetLayerPath returns the path to a layer
<ide> func GetLayerPath(s Store, layer ChainID) (string, error) {
<ide> return path, nil
<ide> }
<ide>
<del>func (ls *layerStore) RegisterDiffID(graphID string, size int64) (Layer, error) {
<del> var err error // this is used for cleanup in existingLayer case
<del> diffID := digest.FromBytes([]byte(graphID))
<del>
<del> // Create new roLayer
<del> layer := &roLayer{
<del> cacheID: graphID,
<del> diffID: DiffID(diffID),
<del> referenceCount: 1,
<del> layerStore: ls,
<del> references: map[Layer]struct{}{},
<del> size: size,
<del> }
<del>
<del> tx, err := ls.store.StartTransaction()
<del> if err != nil {
<del> return nil, err
<del> }
<del> defer func() {
<del> if err != nil {
<del> if err := tx.Cancel(); err != nil {
<del> logrus.Errorf("Error canceling metadata transaction %q: %s", tx.String(), err)
<del> }
<del> }
<del> }()
<del>
<del> layer.chainID = createChainIDFromParent("", layer.diffID)
<del>
<del> if !ls.driver.Exists(layer.cacheID) {
<del> return nil, fmt.Errorf("layer %q is unknown to driver", layer.cacheID)
<del> }
<del> if err = storeLayer(tx, layer); err != nil {
<del> return nil, err
<del> }
<del>
<del> ls.layerL.Lock()
<del> defer ls.layerL.Unlock()
<del>
<del> if existingLayer := ls.getWithoutLock(layer.chainID); existingLayer != nil {
<del> // Set error for cleanup, but do not return
<del> err = errors.New("layer already exists")
<del> return existingLayer.getReference(), nil
<del> }
<del>
<del> if err = tx.Commit(layer.chainID); err != nil {
<del> return nil, err
<del> }
<del>
<del> ls.layerMap[layer.chainID] = layer
<del>
<del> return layer.getReference(), nil
<del>}
<del>
<ide> func (ls *layerStore) mountID(name string) string {
<ide> // windows has issues if container ID doesn't match mount ID
<ide> return name | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.